[
  {
    "path": ".gitignore",
    "content": "*.*~\n*.iws\n*.iml\n*.ipr\ntarget/\ntest-output/\n \n## Eclipse stuff ##\n.project\n.classpath\n.settings\nbin\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contribution Guidelines\n\n### 1. Get the source code: \n\n[Download](https://github.com/impetus-opensource/Kundera/archive/trunk.zip) souce code as zip  \n\nor \nuse `git clone https://github.com/impetus-opensource/Kundera.git`\n\n### 2. Discuss with Kundera Team:\n\nShare your thoughts with us at Gitter [chat](https://gitter.im/impetus-opensource/Kundera?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) or mail us at kundera@impetus.co.in\n\nAfter discussion, Raise a new issue on [github](https://github.com/impetus-opensource/Kundera/issues).\n\n**Code Recommendations**\n\n- Add proper javadocs and comments.\n- Contributed code must pass existing test cases.\n- Write new test cases using junit.\n- For Eclipse: use Kundera [Formatter](https://github.com/devender-yadav/kundera-formatter/blob/master/cassandra_code_style.xml.zip?raw=true).\n- We recommend contributor to use Java 8.\n\n\n### 3. Code Submission and Review:\n\nThe contributor needs to open a pull request on the [trunk](https://github.com/impetus-opensource/Kundera/pulls) and get it reviewed by Kundera developers.\n\nThe contributor needs to incorporate code changes (_if any_).\n\n### 4. Wiki:\n\nThe contributor needs to write wiki page(s) talking about usage. Check [wiki](https://github.com/impetus-opensource/Kundera/wiki/Kundera-with-Kudu) for Kudu Client.\n\n\n_**At any point feel free to contact.**_\n\n\n\n# Contribution Ideas\n\n### Sample Projects\n\nCreate sample projects using Kundera. For example, you can create a sample web application using Spring. Check existing [examples](https://github.com/impetus-opensource/Kundera/tree/trunk/examples).\n\n### Fix open issues\n\n Check list of  [open issues](https://github.com/impetus-opensource/Kundera/issues).\n\n### Add support for new data source\n\nCheck Kundera supported [databases](https://github.com/impetus-opensource/Kundera/wiki/Datastores-Supported) and [Kundera's Client Extension Framework](https://github.com/impetus-opensource/Kundera/wiki/Kundera's-Client-Extension-Framework) for technical details on adding a new datasource. Check out our newly created Kudu [client](https://github.com/impetus-opensource/Kundera/tree/trunk/src/kundera-kudu) and it's [wiki](https://github.com/impetus-opensource/Kundera/wiki/Kundera-with-Kudu) to get an idea of the source code as Kudu client has fewer features so it's easier to understand. \n\n\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n\n"
  },
  {
    "path": "NOTICE.txt",
    "content": "Kundera\nCopyright 2010-2015 The Apache Software Foundation\n\nThis product includes software developed by The Apache Software\nFoundation (http://www.apache.org/). Additionally, \nit uses the following softwares included as its maven dependencies\n\nCassandra Libraries \ncassandra-all (https://github.com/apache/cassandra)\n\nLogging utilities\nslf4j (http://www.slf4j.org/)\nlog4j (http://logging.apache.org/log4j/)\ncommons-logging(http://commons.apache.org/proper/commons-logging/)\n\nPelops client utility\nhttps://github.com/s7/scale7-pelops\n\nCompression support provided by snappy-java (http://code.google.com/p/snappy-java/)\nWritten by Taro L. Saito.\norg.xerial(snappy)\n\nApache commoms library\ncommons-lang (http://commons.apache.org/proper/commons-lang/)\n\nPersistence Api :\njavaee-api (http://docs.oracle.com/javaee/7/api/)\n\nLucene utilities \nLucene core and helper jars (http://lucene.apache.org/)\n\nDirectory naming \ndirectory-naming\n\nEclipse link parser API\nEclipseLink(https://github.com/eclipse/eclipselink.runtime)\n\nByte code generation library \ncglib (https://github.com/cglib/cglib)\n\nCaching library\nEhcache (http://ehcache.org/)\n\nJava Bytecode manipulation libraray\njavassist(javassist(https://github.com/jboss-javassist/javassist)\n\nGoogle' core library \nGuava(https://code.google.com/p/guava-libraries/)\n\nHibernate libraries\nHibernate(http://hibernate.org/)\n\nTesting utils:\nEasymock (http://easymock.org/)\n\nHbase & Hadoop client APIs and utilities :\nhbase (http://hbase.apache.org/)\nhadoop (http://hadoop.apache.org/)\n\nMongoDB client APIs and utilities\nmongodb Driver (https://github.com/mongodb/mongo-java-driver)\n\nNeo4j database and driver\nNeo4j database driver (https://github.com/neo4j-contrib/neo4j-org)\n\nLibrary to serialize objects to XML and back again.\nthoughtworks xtream(http://xstream.codehaus.org/)\n\nJersey API for rest client \njersey(https://jersey.java.net/)\n\nRedis java driver \nJedis (https://github.com/xetorthio/jedis)\n\nContinuous test performing utility\norg.databene.contiperf(http://databene.org/contiperf)\n\nHSQL database andclient util\nHSQL DB (http://hsqldb.org/)\n\nOracle KV Store and Client Community edition\n(http://www.oracle.com/technetwork/database/database-technologies/nosqldb/downloads/)\nCopyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n\nJTS Topology Suite for 2D spatial predicates and functions\ncom.vividsolutions.jts(http://www.vividsolutions.com/)\n\nHttp client for rest calls :\nhttpcomponent (http://hc.apache.org/)\n\nJson library\nGson (https://code.google.com/p/google-gson/)\n\nJackson libraries for object to xml & json conversions\nfasterxml API(https://github.com/FasterXML/)\n\nApache Spark core APIs, spark-sql and spark-Hive library\nApache spark (https://github.com/apache/spark)\n\nJunit for wrriting unit tests\nJunit (http://junit.org/)\n\n"
  },
  {
    "path": "README.md",
    "content": "[![Join the chat at https://gitter.im/Impetus/Kundera](https://badges.gitter.im/Impetus/Kundera.svg)](https://gitter.im/Impetus/Kundera) [![Follow us on Twitter](http://i.imgur.com/wWzX9uB.png)](https://twitter.com/kundera_impetus)\n\nOverview\n=========\nKundera is a \"Polyglot Object Mapper\" with a JPA interface. The idea behind Kundera is to make working with NoSQL Databases drop-dead simple and fun. Kundera is being developed with following objectives:\n* To make working with NoSQL as simple as working with SQL\n* To serve as JPA Compliant mapping solution for NoSQL Datastores.\n*\tTo help developers, forget the complexity of NoSQL stores and focus on Domain Model.\n*\tTo make switching across data-stores as easy as changing a configuration.\n\nLatest \n======\n* **Ethereum** public data can be stored to any database of your choice. Check [Kundera with Ethereum](https://github.com/impetus-opensource/Kundera/wiki/Kundera-with-Ethereum-Blockchain) for more details.\n* Kundera now supports **RethinkDB**. Check [Kundera with RethinkDB](https://github.com/impetus-opensource/Kundera/wiki/Kundera-with-RethinkDB) for more details.\n* Kundera supports **Apache Kudu**. Check [Kundera with Kudu](https://github.com/impetus-opensource/Kundera/wiki/Kundera-with-Kudu) for more details.\n* Want to step out of JPA world and still take advantage of Kundera? Check [Kundera Data as Object](https://github.com/impetus-opensource/Kundera/wiki/Kundera-Data-As-Object).\n* Want to save your large files in MongoDB GridFS in the same JPA way. Check [GridFS support in Kundera](https://github.com/impetus-opensource/Kundera/wiki/GridFS-support-with-Kundera-MongoDB).\n* Perform SQL queries over big data using Kundera with **Apache Spark** as the query engine. Check [Kundera with Spark](https://github.com/impetus-opensource/Kundera/wiki/Kundera-with-Spark) for more details. \n* We are active on **stackoverflow.com**. Ask questions & check existing [Kundera Tagged Questions](http://stackoverflow.com/questions/tagged/kundera) on stackoverflow. \n\n\nSupported Datastores \n=====================\nKundera currently supports following data stores :\n*  Cassandra\n*  MongoDB\n*  HBase\n*  Redis\n*  OracleNoSQL\n*  Neo4j\n*  Couchdb\n*  RethinkDB\n*  Kudu\n*  Relational databases\n*  Apache Spark\n  \nYou can find the list of data stores(specific versions) supported by Kundera [here](https://github.com/impetus-opensource/Kundera/wiki/Datastores-Supported).\n\nGetting Started\n===============\nThe latest stable release of Kundera is <b>3.13</b>.\nIt is a maven based project . You can either download it directly from github and build using following command :\n\n<b>mvn clean install -Dfile src/pom.xml </b>\n\n<b>Or</b> it can be directly added as maven dependency in your project in the following manner :\n \n  * Add the following repository to pom.xml :\n   \n   ```\n    <repository>\n        <id>sonatype-nexus</id>\n        <name>Kundera Public Repository</name>\n        <url>https://oss.sonatype.org/content/repositories/releases</url>\n       <releases>\n           <enabled>true</enabled>\n       </releases>\n       <snapshots>\n           <enabled>false</enabled>\n       </snapshots>\n    </repository>\n   ```\n  \n  * Add the data store specific Kundera module as a dependency (e.g. Cassandra below) :\n  \n  ```\n    <dependency>\n          <groupId>com.impetus.kundera.client</groupId>\n          <artifactId>kundera-cassandra</artifactId>\n          <version>${kundera.version}</version>\n    </dependency>\n  ```\n\nBuild your project with the above changes to your pom.xml and start using Kundera !\n\n\n\nImportant Links\n===============\n* [Kundera in 5 minutes](https://github.com/impetus-opensource/Kundera/wiki/Getting-Started-in-5-minutes)\n* [Data Store specific Configurations](https://github.com/impetus-opensource/Kundera/wiki/Data-store-Specific-Configuration)\n* Features :\n   * [Polyglot Persistence](https://github.com/impetus-opensource/Kundera/wiki/Polyglot-Persistence)\n   * [JPQL](https://github.com/impetus-opensource/Kundera/wiki/JPQL) & [Native Query](https://github.com/impetus-opensource/Kundera/wiki/Native-queries) Support\n   * [Schema Generation](https://github.com/impetus-opensource/Kundera/wiki/Schema-Generation)\n   * [Transaction Management](https://github.com/impetus-opensource/Kundera/wiki/Transaction-Management)\n   * [Rest Based Access](https://github.com/impetus-opensource/Kundera/wiki/REST-Based-Access)\n   * [Aggregation over NoSQL](https://github.com/impetus-opensource/Kundera/wiki/How-to-perform-aggregation-over-data-stored-in-NoSQL%3F)\n* Tutorials :\n   * [Kundera with Openshift](https://github.com/impetus-opensource/Kundera/wiki/Deploying-Polyglot-(RDBMS---NoSQL)-Applications-on-Openshift)\n   * [Kundera with Play Framework](https://github.com/impetus-opensource/Kundera/wiki/Using-Kundera-with-Play!-Framework)\n   * [Kundera with GWT](https://github.com/impetus-opensource/Kundera/wiki/Using-Kundera-with-GWT)\n   * [Kundera with JBoss](https://github.com/impetus-opensource/Kundera/wiki/Using-Kundera-with-Jboss)\n   * [Kundera with Spring](https://github.com/impetus-opensource/Kundera/wiki/Building-Applications-with-Kundera-and-Spring)\n   * [Kundera with Spark](https://github.com/impetus-opensource/Kundera/wiki/Kundera-with-Spark)\n* [Kundera Tagged Questions on stackoverflow.com](http://stackoverflow.com/questions/tagged/kundera)\n* [Releases](https://github.com/impetus-opensource/Kundera/blob/trunk/src/README.md)\n\nTroubleshooting\n===============\n* [Common Issues and Troubleshooting](https://github.com/impetus-opensource/Kundera/wiki/Common-Issues-and-Troubleshooting)\n\nSample Projects\n===============\nPlease use latest version of Kundera in these sample projects.\n\n* [kundera-mongodb-kudu-example.zip (MongoDB - Kudu polyglot)](https://github.com/impetus-opensource/Kundera/blob/trunk/examples/basic-examples/downloadables/kundera-mongodb-kudu-example.zip?raw=true)\n* [kundera-cassandra-example.zip](https://github.com/impetus-opensource/Kundera/blob/trunk/examples/basic-examples/downloadables/kundera-cassandra-example.zip?raw=true)\n* [kundera-mongodb-example.zip](https://github.com/impetus-opensource/Kundera/blob/trunk/examples/basic-examples/downloadables/kundera-mongodb-example.zip?raw=true)\n* [kundera-hbase-example.zip](https://github.com/impetus-opensource/Kundera/blob/trunk/examples/basic-examples/downloadables/kundera-hbase-example.zip?raw=true)\n\n\nContribution\n============\n* [Contribution Ideas](https://github.com/impetus-opensource/Kundera/wiki/How-to-Contribute#contribution-ideas)\n* [Contribution Guidelines](https://github.com/impetus-opensource/Kundera/wiki/How-to-Contribute#contribution-guidelines)\n\nAbout Us\n========\nKundera 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.\n\nFollow us on [Twitter](https://twitter.com/kundera_impetus).\n"
  },
  {
    "path": "examples/basic-examples/kundera-cassandra-example/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.impetus.kundera</groupId>\n\t<artifactId>kundera-cassandra-example</artifactId>\n\t<packaging>jar</packaging>\n\t<version>1.0</version>\n\t<name>kundera-cassandra-example</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<kundera.version>3.13</kundera.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.12</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<version>3.5.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.8</source>\n\t\t\t\t\t<target>1.8</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n</project>\n"
  },
  {
    "path": "examples/basic-examples/kundera-cassandra-example/src/main/java/com/impetus/kundera/entities/Person.java",
    "content": "/*******************************************************************************\n * * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON\")\npublic class Person\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private int age;\n\n    /**\n     * Gets the person id.\n     *\n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     *\n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the person name.\n     *\n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     *\n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Gets the age.\n     *\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     *\n     * @param age\n     *            the new age\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "examples/basic-examples/kundera-cassandra-example/src/main/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\n        <persistence-unit name=\"cassandra_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n</persistence>\n"
  },
  {
    "path": "examples/basic-examples/kundera-cassandra-example/src/test/java/com/impetus/kundera/CRUDTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.entities.Person;\n\n/**\n * The Class CRUDTest.\n */\npublic class CRUDTest\n{\n\n    /** The Constant PU. */\n    private static final String PU = \"cassandra_pu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n    }\n\n    /**\n     * Sets the up.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test crud operations.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testCRUDOperations() throws Exception\n    {\n        testInsert();\n        testMerge();\n        testRemove();\n    }\n\n    /**\n     * Test insert.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    private void testInsert() throws Exception\n    {\n        Person p = new Person();\n        p.setPersonId(\"101\");\n        p.setPersonName(\"dev\");\n        p.setAge(24);\n        em.persist(p);\n\n        Person person = em.find(Person.class, \"101\");\n        Assert.assertNotNull(person);\n        Assert.assertEquals(\"101\", person.getPersonId());\n        Assert.assertEquals(\"dev\", person.getPersonName());\n\n    }\n\n    /**\n     * Test merge.\n     */\n    private void testMerge()\n    {\n        Person person = em.find(Person.class, \"101\");\n        person.setPersonName(\"devender\");\n        em.merge(person);\n\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertEquals(\"devender\", p1.getPersonName());\n    }\n\n    /**\n     * Test remove.\n     */\n    private void testRemove()\n    {\n        Person p = em.find(Person.class, \"101\");\n        em.remove(p);\n\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertNull(p1);\n    }\n\n    /**\n     * Tear down.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n            emf = null;\n        }\n    }\n}\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-example/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.impetus.kundera</groupId>\n\t<artifactId>kundera-ethereum-example</artifactId>\n\t<packaging>jar</packaging>\n\t<version>1.0</version>\n\t<name>kundera-ethereum-example</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<kundera.version>3.13</kundera.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-ethereum</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-mongo</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<version>3.0</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.8</source>\n\t\t\t\t\t<target>1.8</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n</project>\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-example/src/main/java/com/impetus/kundera/KunderaEthereumImporterTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera;\n\nimport java.math.BigInteger;\n\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.blockchain.entities.Block;\nimport com.impetus.kundera.blockchain.ethereum.BlockchainImporter;\n\n/**\n * The Class KunderaEthereumImporterTest.\n */\npublic class KunderaEthereumImporterTest\n{\n\n    /** The importer. */\n    private static BlockchainImporter importer;\n\n    /**\n     * Sets the up before class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        importer = BlockchainImporter.initialize();\n    }\n\n    /**\n     * Gets the block test.\n     *\n     * @return the block test\n     */\n    @Test\n    public void getBlockTest()\n    {\n        Block blk = importer.getBlock(BigInteger.valueOf(1000000));\n        Assert.assertNotNull(blk);\n        Assert.assertNull(blk.getTransactions());\n    }\n\n    /**\n     * Gets the block with transactions test.\n     *\n     * @return the block with transactions test\n     */\n    @Test\n    public void getBlockWithTransactionsTest()\n    {\n        Block blk = importer.getBlockWithTransactions(BigInteger.valueOf(1000000));\n        Assert.assertNotNull(blk);\n        Assert.assertNotNull(blk.getTransactions());\n    }\n\n    /**\n     * Gets the first block test.\n     *\n     * @return the first block test\n     */\n    @Test\n    public void getFirstBlockTest()\n    {\n        Block blk = importer.getFirstBlock();\n        Assert.assertNotNull(blk);\n        Assert.assertNull(blk.getTransactions());\n    }\n\n    /**\n     * Gets the first block with transactions test.\n     *\n     * @return the first block with transactions test\n     */\n    @Test\n    public void getFirstBlockWithTransactionsTest()\n    {\n        Block blk = importer.getFirstBlockWithTransactions();\n        Assert.assertNotNull(blk);\n        // No transactions in 1st block\n        Assert.assertNull(blk.getTransactions());\n    }\n\n    /**\n     * Gets the first block number test.\n     *\n     * @return the first block number test\n     */\n    @Test\n    public void getFirstBlockNumberTest()\n    {\n        BigInteger blkNum = importer.getFirstBlockNumber();\n        Assert.assertEquals(blkNum, new BigInteger(\"0\"));\n    }\n\n    /**\n     * Gets the latest block test.\n     *\n     * @return the latest block test\n     */\n    @Test\n    public void getLatestBlockTest()\n    {\n        Block blk = importer.getLatestBlock();\n        Assert.assertNotNull(blk);\n        Assert.assertNull(blk.getTransactions());\n    }\n\n    /**\n     * Gets the latest block with transactions test.\n     *\n     * @return the latest block with transactions test\n     */\n    @Test\n    public void getLatestBlockWithTransactionsTest()\n    {\n        Block blk = importer.getLatestBlockWithTransactions();\n        Assert.assertNotNull(blk);\n        Assert.assertNotNull(blk.getTransactions());\n    }\n\n    /**\n     * Gets the latest block number test.\n     *\n     * @return the latest block number test\n     */\n    @Test\n    public void getLatestBlockNumberTest()\n    {\n        BigInteger blkNum = importer.getLatestBlockNumber();\n        Assert.assertTrue(blkNum.compareTo(new BigInteger(\"4000000\")) > 0);\n    }\n\n    /**\n     * Import blocks test.\n     */\n    @Test\n    public void importBlocksTest()\n    {\n        importer.importBlocks(BigInteger.valueOf(1000000), BigInteger.valueOf(1000010));\n    }\n\n    /**\n     * Import blocks from starting test.\n     */\n    @Test\n    public void importBlocksFromStartingTest()\n    {\n        importer.importBlocksFromStarting(BigInteger.valueOf(10));\n    }\n\n    /**\n     * Tear down after class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n    \timporter.destroy();\n    }\n\n}\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-example/src/main/java/com/impetus/kundera/KunderaEthereumJPAQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera;\n\nimport java.math.BigInteger;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.blockchain.entities.Transaction;\nimport com.impetus.kundera.blockchain.ethereum.BlockchainImporter;\n\n/**\n * The Class KunderaEthereumJPAQueryTest.\n */\npublic class KunderaEthereumJPAQueryTest\n{\n\n    /** The importer. */\n    private static BlockchainImporter importer;\n\n    /**\n     * Sets the up before class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        importer = BlockchainImporter.initialize();\n        // init data\n        importer.importBlocks(BigInteger.valueOf(4545110), BigInteger.valueOf(4545112));\n\n    }\n\n    /**\n     * Gets the block test.\n     *\n     * @return the block test\n     */\n    @Test\n    public void testJPAQuery()\n    {\n        EntityManager em = BlockchainImporter.getKunderaWeb3jClient().getEntityManager();\n        Query query = (Query) em.createQuery(\"Select t.gas,t.gasPrice from Transaction t \"\n                + \"where t.blockNumber='0x455a56' and t.from='0xea674fdde714fd979de3edf0f56aa9716b898ec8'\");\n        List<Transaction> results = query.getResultList();\n        Assert.assertEquals(6, results.size());\n    }\n\n    /**\n     * Tear down after class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        importer.destroy();\n    }\n\n}\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-example/src/main/resources/kundera-ethereum.properties",
    "content": "database.type=mongodb\ndatabase.host=localhost\ndatabase.port=27017\ndatabase.name=EthereumDB\n\n## generate Block and Transaction tables \nschema.auto.generate=true\n\n## Drop existing tables\nschema.drop.existing=true\n\n## RPC HTTP end point or IPC socket file location or infura end point can be specified\nethereum.node.endpoint=http://localhost:8545/\n#ethereum.node.endpoint=/home/dev/ethereum/geth.ipc\n#ethereum.node.endpoint=https://mainnet.infura.io/<your-token>\n\n# Needed if IPC socket file located on windows OS\n#ethereum.node.os=windows\n\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-example/src/main/resources/logback.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration>\n\n\t<appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n\t\t<!-- By default, encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder -->\n\t\t<encoder>\n\t\t\t<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n</pattern>\n\t\t</encoder>\n\t</appender>\n\n\t<logger name=\"com.impetus.kundera.ethereum\" level=\"DEBUG\" additivity=\"false\">\n            <appender-ref ref=\"STDOUT\" />\n\t</logger>\n\n\t<root level=\"ERROR\">\n\t\t<appender-ref ref=\"STDOUT\" />\n\t</root>\n</configuration>"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-webapp/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<groupId>com.impetus.kundera.ethereum.webapp</groupId>\n\t<artifactId>kundera-ethereum-webapp</artifactId>\n\t<version>0.0.1-SNAPSHOT</version>\n\t<packaging>jar</packaging>\n\n\t<name>kundera-ethereum-webapp</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t</properties>\n\n\n\t<parent>\n\t\t<groupId>org.springframework.boot</groupId>\n\t\t<artifactId>spring-boot-starter-parent</artifactId>\n\t\t<version>1.5.8.RELEASE</version>\n\t</parent>\n\n\t<dependencies>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-web</artifactId>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework.boot</groupId>\n\t\t\t<artifactId>spring-boot-starter-tomcat</artifactId>\n\t\t\t<!--<scope>provided</scope> -->\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>javax.servlet</groupId>\n\t\t\t<artifactId>jstl</artifactId>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.tomcat.embed</groupId>\n\t\t\t<artifactId>tomcat-embed-jasper</artifactId>\n\t\t\t<!-- <version>9.0.1</version> -->\n\t\t\t<!--<scope>provided</scope> -->\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>3.12-SNAPSHOT</version>\n\t\t</dependency>\n\t\t\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-ethereum</artifactId>\n\t\t\t<version>3.13</version>\n\t\t</dependency>\n\n\t\t<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-orm</artifactId>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-web</artifactId>\n\t\t</dependency>\n\n\t\t<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->\n\t\t<dependency>\n\t\t\t<groupId>com.fasterxml.jackson.core</groupId>\n\t\t\t<artifactId>jackson-databind</artifactId>\n\t\t\t<version>2.9.2</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>com.fasterxml.jackson.core</groupId>\n\t\t\t\t\t<artifactId>jackson-core</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>com.fasterxml.jackson.core</groupId>\n\t\t\t\t\t<artifactId>jackson-annotations</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.fasterxml.jackson.core</groupId>\n\t\t\t<artifactId>jackson-core</artifactId>\n\t\t\t<version>2.9.2</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.fasterxml.jackson.core</groupId>\n\t\t\t<artifactId>jackson-annotations</artifactId>\n\t\t\t<version>2.9.2</version>\n\t\t</dependency>\n\n\t\t<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->\n<!-- \t\t<dependency> -->\n<!-- \t\t\t<groupId>org.springframework</groupId> -->\n<!-- \t\t\t<artifactId>spring-core</artifactId> -->\n<!-- \t\t\t<version>5.0.1.RELEASE</version> -->\n<!-- \t\t</dependency> -->\n\n\n\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>3.8.1</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n</project>\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/config/Application.java",
    "content": "package com.impetus.kundera.ethereum.webapp.config;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.EnableAutoConfiguration;\nimport org.springframework.boot.builder.SpringApplicationBuilder;\nimport org.springframework.boot.web.support.SpringBootServletInitializer;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Import;\n\n@Configuration\n@ComponentScan(basePackages = \"com.impetus.kundera.ethereum.webapp\")\n@Import({ BeanConfig.class, WebConfig.class })\n@EnableAutoConfiguration\npublic class Application extends SpringBootServletInitializer\n{\n    private static Class applicationClass = Application.class;\n\n    public static void main(String[] args)\n    {\n        SpringApplication.run(Application.class, args);\n    }\n\n    @Override\n    protected SpringApplicationBuilder configure(SpringApplicationBuilder application)\n    {\n        return application.sources(applicationClass);\n    }\n}\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/config/ApplicationInitializer.java",
    "content": "package com.impetus.kundera.ethereum.webapp.config;\n\nimport javax.servlet.ServletContext;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRegistration;\n\nimport org.springframework.web.WebApplicationInitializer;\nimport org.springframework.web.context.support.AnnotationConfigWebApplicationContext;\nimport org.springframework.web.servlet.DispatcherServlet;\n\npublic class ApplicationInitializer implements WebApplicationInitializer\n{\n\n    public void onStartup(ServletContext container) throws ServletException\n    {\n\n        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();\n        ctx.setServletContext(container);\n        ServletRegistration.Dynamic servlet = container.addServlet(\"dispatcher\", new DispatcherServlet(ctx));\n        servlet.setLoadOnStartup(1);\n        servlet.addMapping(\"/\");\n    }\n}\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/config/BeanConfig.java",
    "content": "package com.impetus.kundera.ethereum.webapp.config;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.servlet.view.InternalResourceViewResolver;\nimport org.springframework.web.servlet.view.JstlView;\n\n@Configuration\npublic class BeanConfig\n{\n\n    @Bean\n    public InternalResourceViewResolver setupViewResolver()\n    {\n        InternalResourceViewResolver resolver = new InternalResourceViewResolver();\n        resolver.setPrefix(\"/ui/jsp/\");\n        resolver.setSuffix(\".jsp\");\n        resolver.setViewClass(JstlView.class);\n        return resolver;\n    }\n\n}\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/config/WebConfig.java",
    "content": "package com.impetus.kundera.ethereum.webapp.config;\n\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;\n\n@Configuration\npublic class WebConfig extends WebMvcConfigurerAdapter\n{\n\n    @Override\n    public void addResourceHandlers(final ResourceHandlerRegistry registry)\n    {\n        registry.addResourceHandler(\"/*.js/**\").addResourceLocations(\"/ui/static/\");\n        registry.addResourceHandler(\"/*.css/**\").addResourceLocations(\"/ui/static/\");\n    }\n\n}\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/controller/EthereumController.java",
    "content": "package com.impetus.kundera.ethereum.webapp.controller;\n\nimport java.util.List;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.servlet.ModelAndView;\n\nimport com.impetus.kundera.ethereum.webapp.dao.EthereumDao;\n\n@Controller\npublic class EthereumController\n{\n    @Autowired\n    EthereumDao ethereumDao;\n\n    @RequestMapping(value = \"/\", method = RequestMethod.GET)\n    public ModelAndView root()\n    {\n        ModelAndView model = new ModelAndView();\n        model.setViewName(\"home\");\n        return model;\n    }\n\n    @RequestMapping(value = \"/home\", method = RequestMethod.GET)\n    public ModelAndView home()\n    {\n        ModelAndView model = new ModelAndView();\n        model.setViewName(\"home\");\n        return model;\n    }\n\n    @RequestMapping(value = \"/import\", method = RequestMethod.POST)\n    public ModelAndView importBlocks(@RequestParam(\"from_block\") String from, @RequestParam(\"to_block\") String to)\n    {\n        ModelAndView model = new ModelAndView();\n\n        ethereumDao.importBlocks(Long.parseLong(from), Long.parseLong(to));\n        model.addObject(\"importStatus\", \"Import of blocks from \" + from + \" to \" + to + \" is successful\");\n        model.setViewName(\"home\");\n        return model;\n    }\n\n    @RequestMapping(value = \"/queryresult\", method = RequestMethod.POST)\n    public ModelAndView queryBlocks(@RequestParam String query)\n    {\n        ModelAndView model = new ModelAndView();\n        List res = ethereumDao.runJPAQuery(query);\n        model.addObject(\"result\", res);\n        model.setViewName(\"queryresult\");\n        return model;\n    }\n\n}\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/dao/EthereumDao.java",
    "content": "package com.impetus.kundera.ethereum.webapp.dao;\n\nimport java.math.BigInteger;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport org.springframework.stereotype.Service;\n\nimport com.impetus.kundera.blockchain.ethereum.BlockchainImporter;\n\n@Service\npublic class EthereumDao\n{\n\n    private static BlockchainImporter importer = BlockchainImporter.initialize();\n\n    public void importBlocks(long from, long to)\n    {\n        importer.importBlocks(BigInteger.valueOf(from), BigInteger.valueOf(to));\n    }\n\n    public List runJPAQuery(String query)\n    {\n        EntityManager em = BlockchainImporter.getKunderaWeb3jClient().getEntityManager();\n        Query q = (Query) em.createQuery(query);\n        return q.getResultList();\n    }\n\n}\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-webapp/src/main/java/com/impetus/kundera/ethereum/webapp/dao/UserDao.java",
    "content": "//package com.impetus.kundera.ethereum.webapp.dao;\n//\n//import javax.persistence.EntityManager;\n//import javax.persistence.EntityManagerFactory;\n//import javax.persistence.PersistenceUnit;\n//\n//import org.springframework.stereotype.Service;\n//\n//import com.impetus.kundera.ethereum.webapp.model.User;\n//\n//@Service\n//public class UserDao\n//{\n//    @PersistenceUnit(unitName = \"cassandra_pu\")\n//    EntityManagerFactory entityManagerFactory;\n//\n//    public User addUser()\n//    {\n//        User user = new User();\n//        user.setEmail(\"johndoe123@gmail.com\");\n//        user.setName(\"John Doe\");\n//        user.setAddress(\"Bangalore, Karnataka\");\n//        EntityManager entityManager = entityManagerFactory.createEntityManager();\n//        entityManager.persist(user);\n//        entityManager.close();\n//        return user;\n//    }\n//\n//    public User getUserById(String Id)\n//    {\n//        EntityManager entityManager = entityManagerFactory.createEntityManager();\n//        User User = entityManager.find(User.class, Id);\n//        return User;\n//    }\n//\n//    public EntityManagerFactory getEntityManagerFactory()\n//    {\n//        return entityManagerFactory;\n//    }\n//\n//    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory)\n//    {\n//        this.entityManagerFactory = entityManagerFactory;\n//    }\n//}\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-webapp/src/main/resources/kundera-ethereum.properties",
    "content": "database.type=cassandra\ndatabase.host=localhost\ndatabase.port=9160\ndatabase.name=qwery\n\n## generate Block and Transaction tables \nschema.auto.generate=true\n\n## Drop existing tables\nschema.drop.existing=true\n\n## RPC HTTP end point or IPC socket file location or infura end point can be specified\n#ethereum.node.endpoint=http://localhost:8545/\n#ethereum.node.endpoint=/home/dev/ethereum/geth.ipc\nethereum.node.endpoint=https://mainnet.infura.io/1234\n\n# Needed if IPC socket file located on windows OS\n#ethereum.node.os=windows\n\n"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-webapp/src/main/webapp/ui/jsp/dashboard.jsp",
    "content": "<%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %>\n<html>\n<head>\n    <title> Spring Boot Example</title>\n<link href=\"/bootstrap.min.css\" rel=\"stylesheet\">\n    <script src=\"/jquery-2.2.1.min.js\"></script>\n    <script src=\"/bootstrap.min.js\"></script>\n</head>\n<body>\n<div>\n<div class=\"container\" style=\"margin:50px\">\n    <div class=\"row text-center\"><strong> User Details</strong></div>\n    <div class=\"row\" style=\"border:1px solid green;padding:10px\">\n        <div class=\"col-md-4 text-center\"><strong>Name</strong></div>\n        <div class=\"col-md-4 text-center\"><strong>Email</strong></div>\n        <div class=\"col-md-4 text-center\"><strong>Address</strong></div>\n    </div>\n        <c:forEach var=\"user\" items=\"${users}\">\n            <div class=\"row\" style=\"border:1px solid green;padding:10px\">\n            <div class=\"col-md-4 text-center\">${user.name}</div>\n            <div class=\"col-md-4 text-center\" >${user.email}</div>\n                <div class=\"col-md-4 text-center\">${user.address}</div>\n            </div>\n        </c:forEach>\n\n</div>\n</div>\n</body>\n</html>"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-webapp/src/main/webapp/ui/jsp/home.jsp",
    "content": "<html>\n   <body>\n   <div>\n         <form action = \"import\" method = \"POST\">\n         From Block: <input type = \"text\" name = \"from_block\" style=\"width: 120px;\">\n         To Block: <input type = \"text\" name = \"to_block\" style=\"width: 120px;\">\n         <input type = \"submit\" value = \"Import blocks\" />\n         ${importStatus}\n      </form>\n      </div>\n      \n      <div>\n      <form action = \"queryresult\" method = \"POST\">\n         JPA Query: <input type = \"text\" name = \"query\" style=\"width: 500px;\">\n         <input type = \"submit\" value = \"Run query\" />\n      </form>\n      </div>\n      \n   </body>\n</html>"
  },
  {
    "path": "examples/basic-examples/kundera-ethereum-webapp/src/main/webapp/ui/jsp/queryresult.jsp",
    "content": "<%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %>\n<html>\n<head>\n    <title> Spring Boot Example</title>\n<link href=\"/bootstrap.min.css\" rel=\"stylesheet\">\n    <script src=\"/jquery-2.2.1.min.js\"></script>\n    <script src=\"/bootstrap.min.js\"></script>\n</head>\n<body>\n<div>\n<div class=\"container\" style=\"margin:50px\">\n    <div class=\"row text-center\"><strong>Query Result</strong></div>\n    <div class=\"row\" style=\"border:1px solid green;padding:10px\">\n        <div class=\"col-md-4 text-center\"><strong>blockNumber</strong></div>\n        <div class=\"col-md-4 text-center\"><strong>from</strong></div>\n        <div class=\"col-md-4 text-center\"><strong>value</strong></div>\n    </div>\n        <c:forEach var=\"result\" items=\"${result}\">\n            <div class=\"row\" style=\"border:1px solid green;padding:10px\">\n            <div class=\"col-md-4 text-center\">${result.blockNumber}</div>\n            <div class=\"col-md-4 text-center\" >${result.from}</div>\n                <div class=\"col-md-4 text-center\">${result.value}</div>\n            </div>\n        </c:forEach>\n\n</div>\n</div>\n</body>\n</html>"
  },
  {
    "path": "examples/basic-examples/kundera-hbase-example/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.impetus.kundera</groupId>\n\t<artifactId>kundera-hbase-example</artifactId>\n\t<packaging>jar</packaging>\n\t<version>1.0</version>\n\t<name>kundera-hbase-example</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<kundera.version>3.13</kundera.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-hbase-v2</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.12</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<version>3.5.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n</project>\n"
  },
  {
    "path": "examples/basic-examples/kundera-hbase-example/src/main/java/com/impetus/kundera/entities/Person.java",
    "content": "/*******************************************************************************\n * * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON\")\npublic class Person\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private int age;\n\n    /**\n     * Gets the person id.\n     *\n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     *\n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the person name.\n     *\n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     *\n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Gets the age.\n     *\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     *\n     * @param age\n     *            the new age\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "examples/basic-examples/kundera-hbase-example/src/main/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\n\t<persistence-unit name=\"hbase_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n</persistence>\n"
  },
  {
    "path": "examples/basic-examples/kundera-hbase-example/src/test/java/com/impetus/kundera/CRUDTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.entities.Person;\n\n/**\n * The Class CRUDTest.\n */\npublic class CRUDTest\n{\n\n    /** The Constant PU. */\n    private static final String PU = \"hbase_pu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n    }\n\n    /**\n     * Sets the up.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test crud operations.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testCRUDOperations() throws Exception\n    {\n        testInsert();\n        testMerge();\n        testRemove();\n    }\n\n    /**\n     * Test insert.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    private void testInsert() throws Exception\n    {\n        Person p = new Person();\n        p.setPersonId(\"101\");\n        p.setPersonName(\"dev\");\n        p.setAge(24);\n        em.persist(p);\n\n        Person person = em.find(Person.class, \"101\");\n        Assert.assertNotNull(person);\n        Assert.assertEquals(\"101\", person.getPersonId());\n        Assert.assertEquals(\"dev\", person.getPersonName());\n\n    }\n\n    /**\n     * Test merge.\n     */\n    private void testMerge()\n    {\n        Person person = em.find(Person.class, \"101\");\n        person.setPersonName(\"devender\");\n        em.merge(person);\n\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertEquals(\"devender\", p1.getPersonName());\n    }\n\n    /**\n     * Test remove.\n     */\n    private void testRemove()\n    {\n        Person p = em.find(Person.class, \"101\");\n        em.remove(p);\n\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertNull(p1);\n    }\n\n    /**\n     * Tear down.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n            emf = null;\n        }\n    }\n}\n"
  },
  {
    "path": "examples/basic-examples/kundera-mongodb-example/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.impetus.kundera</groupId>\n\t<artifactId>kundera-mongodb-example</artifactId>\n\t<packaging>jar</packaging>\n\t<version>1.0</version>\n\t<name>kundera-mongodb-example</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<kundera.version>3.13</kundera.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-mongo</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.12</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<version>3.5.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n</project>\n"
  },
  {
    "path": "examples/basic-examples/kundera-mongodb-example/src/main/java/com/impetus/kundera/entities/Person.java",
    "content": "/*******************************************************************************\n * * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON\")\npublic class Person\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private int age;\n\n    /**\n     * Gets the person id.\n     *\n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     *\n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the person name.\n     *\n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     *\n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Gets the age.\n     *\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     *\n     * @param age\n     *            the new age\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "examples/basic-examples/kundera-mongodb-example/src/main/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\n\t<persistence-unit name=\"mongo_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n</persistence>\n"
  },
  {
    "path": "examples/basic-examples/kundera-mongodb-example/src/test/java/com/impetus/kundera/CRUDTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.entities.Person;\n\n/**\n * The Class CRUDTest.\n */\npublic class CRUDTest\n{\n\n    /** The Constant PU. */\n    private static final String PU = \"mongo_pu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n    }\n\n    /**\n     * Sets the up.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test crud operations.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testCRUDOperations() throws Exception\n    {\n        testInsert();\n        testMerge();\n        testRemove();\n    }\n\n    /**\n     * Test insert.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    private void testInsert() throws Exception\n    {\n        Person p = new Person();\n        p.setPersonId(\"101\");\n        p.setPersonName(\"dev\");\n        p.setAge(24);\n        em.persist(p);\n\n        Person person = em.find(Person.class, \"101\");\n        Assert.assertNotNull(person);\n        Assert.assertEquals(\"101\", person.getPersonId());\n        Assert.assertEquals(\"dev\", person.getPersonName());\n\n    }\n\n    /**\n     * Test merge.\n     */\n    private void testMerge()\n    {\n        Person person = em.find(Person.class, \"101\");\n        person.setPersonName(\"devender\");\n        em.merge(person);\n\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertEquals(\"devender\", p1.getPersonName());\n    }\n\n    /**\n     * Test remove.\n     */\n    private void testRemove()\n    {\n        Person p = em.find(Person.class, \"101\");\n        em.remove(p);\n\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertNull(p1);\n    }\n\n    /**\n     * Tear down.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n            emf = null;\n        }\n    }\n}\n"
  },
  {
    "path": "examples/basic-examples/polyglot/kundera-mongodb-kudu-example/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.impetus.kundera</groupId>\n\t<artifactId>kundera-mongodb-kudu-example</artifactId>\n\t<packaging>jar</packaging>\n\t<version>1.0</version>\n\t<name>kundera-mongodb-kudu-example</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<kundera.version>3.13</kundera.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-mongo</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-kudu</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.12</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<version>3.5.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n</project>\n"
  },
  {
    "path": "examples/basic-examples/polyglot/kundera-mongodb-kudu-example/src/main/java/com/impetus/kundera/entities/Address.java",
    "content": "/*******************************************************************************\n * * Copyright 2017 Impetus Infotech.\n * *\n * * Licensed under the Apache License, Version 2.0 (the \"License\");\n * * you may not use this file except in compliance with the License.\n * * You may obtain a copy of the License at\n * *\n * * http://www.apache.org/licenses/LICENSE-2.0\n * *\n * * Unless required by applicable law or agreed to in writing, software\n * * distributed under the License is distributed on an \"AS IS\" BASIS,\n * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * * See the License for the specific language governing permissions and\n * * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Address.\n */\n@Entity\n@Table(name = \"ADDRESS\", schema = \"kundera_mongo@mongo_pu\")\npublic class Address\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /** The city. */\n    @Column(name = \"CITY\")\n    private String city;\n\n    /** The country. */\n    @Column(name = \"COUNTRY\")\n    private String country;\n\n    /**\n     * Instantiates a new address.\n     */\n    public Address()\n    {\n\n    }\n\n    /**\n     * Instantiates a new address.\n     * \n     * @param addressId\n     *            the address id\n     * @param street\n     *            the street\n     * @param city\n     *            the city\n     * @param country\n     *            the country\n     */\n    public Address(String addressId, String street, String city, String country)\n    {\n        this.addressId = addressId;\n        this.street = street;\n        this.city = city;\n        this.country = country;\n    }\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    /**\n     * Gets the city.\n     * \n     * @return the city\n     */\n    public String getCity()\n    {\n        return city;\n    }\n\n    /**\n     * Sets the city.\n     * \n     * @param city\n     *            the new city\n     */\n    public void setCity(String city)\n    {\n        this.city = city;\n    }\n\n    /**\n     * Gets the country.\n     * \n     * @return the country\n     */\n    public String getCountry()\n    {\n        return country;\n    }\n\n    /**\n     * Sets the country.\n     * \n     * @param country\n     *            the new country\n     */\n    public void setCountry(String country)\n    {\n        this.country = country;\n    }\n\n}\n"
  },
  {
    "path": "examples/basic-examples/polyglot/kundera-mongodb-kudu-example/src/main/java/com/impetus/kundera/entities/Person.java",
    "content": "/*******************************************************************************\n * * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entities;\n\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON\", schema = \"kundera_kudu@kudu_pu\")\npublic class Person\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private int age;\n\n    /** The addresses. */\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private List<Address> addresses;\n\n    /**\n     * Gets the addresses.\n     * \n     * @return the addresses\n     */\n    public List<Address> getAddresses()\n    {\n        return addresses;\n    }\n\n    /**\n     * Sets the addresses.\n     * \n     * @param addresses\n     *            the new addresses\n     */\n    public void setAddresses(List<Address> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the new age\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "examples/basic-examples/polyglot/kundera-mongodb-kudu-example/src/main/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\n\t<persistence-unit name=\"mongo_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.entities.Address</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"kundera_mongo\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"kudu_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.entities.Person</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"quickstart.cloudera\" />\n\t\t\t<property name=\"kundera.port\" value=\"7051\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"kundera_kudu\" />\n\t\t\t<property name=\"kundera.client\" value=\"kudu\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.kudu.KuduDBClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n</persistence>\n"
  },
  {
    "path": "examples/basic-examples/polyglot/kundera-mongodb-kudu-example/src/test/java/com/impetus/kundera/CRUDTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.entities.Address;\nimport com.impetus.kundera.entities.Person;\n\n/**\n * The Class CRUDTest.\n */\npublic class CRUDTest\n{\n\n    /** The Constant PU. */\n    private static final String PU = \"mongo_pu,kudu_pu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test crud operations.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testCRUDOperations() throws Exception\n    {\n        testInsert();\n        testMerge();\n        testRemove();\n    }\n\n    /**\n     * Test insert.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    private void testInsert() throws Exception\n    {\n        Person p = new Person();\n        p.setPersonId(\"101\");\n        p.setPersonName(\"dev\");\n        p.setAge(24);\n\n        Address a1 = new Address(\"a1\", \"str1\", \"noida\", \"india\");\n        Address a2 = new Address(\"a2\", \"str2\", \"bglr\", \"india\");\n\n        List<Address> adds = new ArrayList<Address>();\n        adds.add(a1);\n        adds.add(a2);\n\n        p.setAddresses(adds);\n\n        em.persist(p);\n\n        Person person = em.find(Person.class, \"101\");\n        Assert.assertNotNull(person);\n        Assert.assertEquals(\"101\", person.getPersonId());\n        Assert.assertEquals(\"dev\", person.getPersonName());\n        Assert.assertEquals(\"india\", person.getAddresses().get(0).getCountry());\n\n    }\n\n    /**\n     * Test merge.\n     */\n    private void testMerge()\n    {\n        Person person = em.find(Person.class, \"101\");\n        person.setPersonName(\"devender\");\n        em.merge(person);\n\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertEquals(\"devender\", p1.getPersonName());\n    }\n\n    /**\n     * Test remove.\n     */\n    private void testRemove()\n    {\n        Person p = em.find(Person.class, \"101\");\n        em.remove(p);\n\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertNull(p1);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n            emf = null;\n        }\n    }\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t<groupId>com.impetus.kundera.examples</groupId>\n\t<artifactId>jboss</artifactId>\n\t<version>3.3-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.examples</groupId>\n\t<artifactId>jboss-data-keeper</artifactId>\n\t<packaging>war</packaging>\n\t<version>1.0-SNAPSHOT</version>\n\t<name>data-keeper</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t\t<spring.version>3.0.5.RELEASE</spring.version>\n\t\t<kundera.version>3.3-SNAPSHOT</kundera.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>${kundera.version}</version>\n                        <exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>io.netty</groupId>\n\t\t\t\t\t<artifactId>netty</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-mongo</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n                <dependency>\n\t\t\t<groupId>javax.servlet</groupId>\n\t\t\t<artifactId>javax.servlet-api</artifactId>\n\t\t\t<version>3.0.1</version>\n\t\t\t<scope>provided</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.sun.faces</groupId>\n\t\t\t<artifactId>jsf-api</artifactId>\n\t\t\t<version>2.1.10</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.sun.faces</groupId>\n\t\t\t<artifactId>jsf-impl</artifactId>\n\t\t\t<version>2.1.10</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>jstl</groupId>\n\t\t\t<artifactId>jstl</artifactId>\n\t\t\t<version>1.2</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.primefaces</groupId>\n\t\t\t<artifactId>primefaces</artifactId>\n\t\t\t<version>3.3.1</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>commons-fileupload</groupId>\n\t\t\t<artifactId>commons-fileupload</artifactId>\n\t\t\t<version>1.3</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>commons-io</groupId>\n\t\t\t<artifactId>commons-io</artifactId>\n\t\t\t<version>2.4</version>\n\t\t</dependency>\n\n\n\t\t<!-- Spring dependencies -->\n\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-core</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-web</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-beans</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-context</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-aop</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-context-support</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-tx</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-orm</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-jdbc</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-test</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t</dependencies>\n\t<build>\n\t\t<finalName>data-keeper</finalName>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t\t<addClasspath>true</addClasspath>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-ear-plugin</artifactId> \n\t\t\t\t<version>2.8</version> <configuration> <jboss> <version>4</version> <unauthenticated-principal>guest</unauthenticated-principal> \n\t\t\t\t<loader-repository>com.impetus.kundera.data-keeper:loader=data-keeper-application-1.0.ear</loader-repository> \n\t\t\t\t</jboss> </configuration> </plugin> -->\n\t\t</plugins>\n\t</build>\n\t\n    <repositories>\n        <repository>\n            <id>prime-repo</id>\n            <name>PrimeFaces Maven Repository</name>\n            <url>http://repository.primefaces.org</url>\n            <layout>default</layout>\n        </repository>\n    </repositories>\n</project>\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/DocumentDownloadBean.java",
    "content": "package com.impetus.kundera.datakeeper.beans;\n\nimport java.io.IOException;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\nimport javax.faces.context.FacesContext;\nimport javax.servlet.ServletOutputStream;\nimport javax.servlet.http.HttpServletResponse;\n\nimport com.impetus.kundera.datakeeper.entities.DocumentInfo;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\nimport com.impetus.kundera.datakeeper.utils.FacesUtils;\n\n@ManagedBean(name = \"documentDownloadBean\")\n@RequestScoped\npublic class DocumentDownloadBean\n{\n    private int documentId;\n\n    public int getDocumentId()\n    {\n        return documentId;\n    }\n\n    public void setDocumentId(int documentId)\n    {\n        this.documentId = documentId;\n    }\n\n    /**\n     * Download file used for downloading photo.\n     * \n     * @param photoPath\n     *            the photo path\n     */\n    public void download()\n    { \n        \n        \n        \n        DataKeeperService service = DataKeeperUtils.getService();\n\n        setDocumentId(Integer.parseInt(FacesUtils.getRequest().getParameter(\"documentId\")));\n        DocumentInfo document = service.findDocumentByDocumentId(getDocumentId());\n\n        final HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()\n                .getExternalContext().getResponse();\n\n        ServletOutputStream out = null;\n        try\n        {\n            out = response.getOutputStream();\n            out.write(document.getData(), 0, 4096);\n        }\n        catch (IOException e)\n        {\n\n        }\n        finally\n        {\n            if (out != null)\n            {\n                try\n                {\n                    out.flush();\n                    out.close();\n                }\n                catch (IOException e)\n                {\n\n                }\n            }\n        }\n        FacesContext.getCurrentInstance().responseComplete();\n    }\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/DocumentSearchBean.java",
    "content": "package com.impetus.kundera.datakeeper.beans;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\n\nimport com.impetus.kundera.datakeeper.entities.DocumentInfo;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\n\n@ManagedBean(name = \"documentSearchBean\")\n@RequestScoped\npublic class DocumentSearchBean\n{\n    private String searchText;\n\n    private int searchBy;\n\n    private List<DocumentInfo> documents;\n\n    public String getSearchText()\n    {\n        return searchText;\n    }\n\n    public void setSearchText(String searchText)\n    {\n        this.searchText = searchText;\n    }\n\n    public int getSearchBy()\n    {\n        return searchBy;\n    }\n\n    public void setSearchBy(int searchBy)\n    {\n        this.searchBy = searchBy;\n    }\n\n    public List<DocumentInfo> getDocuments()\n    {\n        return documents;\n    }\n\n    public void setDocuments(List<DocumentInfo> documents)\n    {\n        this.documents = documents;\n    }\n\n    public List<DocumentInfo> search()\n    {\n        documents = new ArrayList<DocumentInfo>();\n        DataKeeperService service = DataKeeperUtils.getService();\n\n        switch (SearchType.getSearchType(searchBy))\n        {\n        case ID:\n            documents = service.findDocumentByEmployeeId(getSearchText());\n            break;\n        case NAME:\n            documents = service.findDocumentByEmployeeName(getSearchText());\n            break;\n        }\n        return documents;\n    }\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/DocumentUploadBean.java",
    "content": "package com.impetus.kundera.datakeeper.beans;\n\nimport java.util.Date;\n\nimport javax.faces.application.FacesMessage;\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\nimport javax.faces.context.FacesContext;\nimport javax.servlet.http.HttpSession;\n\nimport org.primefaces.event.FileUploadEvent;\nimport org.primefaces.model.UploadedFile;\n\nimport com.impetus.kundera.datakeeper.entities.DocumentInfo;\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperConstants;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\nimport com.impetus.kundera.datakeeper.utils.FacesUtils;\n\n@ManagedBean(name = \"documentUploadBean\")\n@RequestScoped\npublic class DocumentUploadBean\n{\n    public DocumentUploadBean()\n    {\n    }\n\n    public String handleFileUpload(FileUploadEvent event)\n    {\n        HttpSession session = FacesUtils.getSession();\n        Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);\n\n        DataKeeperService service = DataKeeperUtils.getService();\n\n        UploadedFile file = event.getFile();\n\n        if (file != null)\n        {\n            DocumentInfo dataInfo = new DocumentInfo();\n            dataInfo.setData(file.getContents());\n            dataInfo.setDocumentName(file.getFileName());\n            dataInfo.setSize(file.getSize());\n            dataInfo.setOwnerName(employee.getEmployeeName());\n            dataInfo.setOwnerId(employee.getEmployeeId());\n            dataInfo.setUplodedDate(new Date());\n\n            service.insertData(dataInfo);\n\n            FacesMessage msg = new FacesMessage(\"Succesful\", file.getFileName() + \" is uploaded.\");\n            FacesContext.getCurrentInstance().addMessage(null, msg);\n\n            return \"successfully uploaded\";\n        }\n        return \"uploading fail\";\n    }\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/EmployeeSearchBean.java",
    "content": "package com.impetus.kundera.datakeeper.beans;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\nimport javax.servlet.http.HttpSession;\n\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperConstants;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\nimport com.impetus.kundera.datakeeper.utils.FacesUtils;\n\n@ManagedBean(name = \"subordinateSearchBean\")\n@RequestScoped\npublic class EmployeeSearchBean\n{\n    private List<Employee> subordinates = new ArrayList<Employee>();\n\n    private int managerId;\n\n    private int noOfYears;\n\n    private String searchText;\n\n    private int searchBy;\n\n    public String getSearchText()\n    {\n        return searchText;\n    }\n\n    public void setSearchText(String searchText)\n    {\n        this.searchText = searchText;\n    }\n\n    public int getSearchBy()\n    {\n        return searchBy;\n    }\n\n    public void setSearchBy(int searchBy)\n    {\n        this.searchBy = searchBy;\n    }\n\n    /**\n     * @return the managerName\n     */\n    public int getManagerId()\n    {\n        return managerId;\n    }\n\n    /**\n     * @param managerName\n     *            the managerName to set\n     */\n    public void setManagerId(int managerId)\n    {\n        this.managerId = managerId;\n    }\n\n    public int getNoOfYears()\n    {\n        return noOfYears;\n    }\n\n    public void setNoOfYears(int noOfYears)\n    {\n        this.noOfYears = noOfYears;\n    }\n\n    public List<Employee> getSubordinates()\n    {\n        return subordinates;\n    }\n\n    public void setSubordinates(List<Employee> subordinates)\n    {\n        this.subordinates = subordinates;\n    }\n\n    public String searchSubordinates()\n    {\n        DataKeeperService service = DataKeeperUtils.getService();\n        setManagerId(Integer.parseInt(FacesUtils.getRequest().getParameter(\"managerId\")));\n        List<Employee> subordinates = service.findSubOrdinates(getManagerId());\n        if (subordinates != null)\n        {\n            this.subordinates = subordinates;\n        }\n        return \"foundEmployess\";\n    }\n\n    public String searchEmployee()\n    {\n        DataKeeperService service = DataKeeperUtils.getService();\n        Employee employee = null;\n        switch (SearchType.getSearchType(searchBy))\n        {\n        case ID:\n            employee = service.findEmployee(Integer.parseInt(getSearchText()));\n            break;\n        case NAME:\n            employee = service.findEmployeeByName(getSearchText());\n            break;\n        }\n        if (employee != null)\n        {\n            List<Employee> employees = new ArrayList<Employee>();\n            employees.add(employee);\n            this.subordinates = employees;\n        }\n        return \"foundEmployess\";\n    }\n\n    public String searchEmployeeByYearOfComplition()\n    {\n        DataKeeperService service = DataKeeperUtils.getService();\n        HttpSession session = FacesUtils.getSession();\n        Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);\n        List<Employee> employees = service.findEmployeeByDateOfJoining(getNoOfYears(), employee.getCompany());\n        if (employees != null)\n        {\n            this.subordinates = employees;\n        }\n        return \"foundEmployess\";\n    }\n\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/IncrementCounterBean.java",
    "content": "package com.impetus.kundera.datakeeper.beans;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\nimport javax.servlet.http.HttpSession;\n\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.entities.SubordinatesCounter;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperConstants;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\nimport com.impetus.kundera.datakeeper.utils.FacesUtils;\n\n@ManagedBean(name = \"incrementCounterBean\")\n@RequestScoped\npublic class IncrementCounterBean\n{\n    private SubordinatesCounter counter = new SubordinatesCounter();\n\n    public IncrementCounterBean()\n    {\n\n    }\n\n    public SubordinatesCounter getCounter()\n    {\n        return counter;\n    }\n\n    public void setCounter(SubordinatesCounter counter)\n    {\n        this.counter = counter;\n    }\n\n    public String incrementCounter()\n    {\n        DataKeeperService service = DataKeeperUtils.getService();\n\n        HttpSession session = FacesUtils.getSession();\n        Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);\n        counter.setEmployeeId(employee.getEmployeeId());\n        \n        service.incrementCounter(counter);\n        \n        return \"success\";\n    }\n\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/LoginBean.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.datakeeper.beans;\n\nimport javax.faces.application.FacesMessage;\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\nimport javax.faces.context.FacesContext;\nimport javax.servlet.http.HttpSession;\n\nimport org.apache.commons.lang.StringUtils;\n\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperConstants;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\nimport com.impetus.kundera.datakeeper.utils.FacesUtils;\n\n/**\n * <Prove description of functionality provided by this Type>\n * \n * @author amresh.singh\n */\n\n@ManagedBean(name = \"loginBean\")\n@RequestScoped\npublic class LoginBean\n{\n    private Employee employee = new Employee();\n\n    public LoginBean()\n    {\n\n    }\n\n    public Employee getEmployee()\n    {\n        return employee;\n    }\n\n    public void setEmployee(Employee employee)\n    {\n        this.employee = employee;\n    }\n\n    public String logOff()\n    {\n        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);\n        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(\"You have successfully Logged off\"));\n        session.invalidate();\n        return DataKeeperConstants.OUTCOME_LOGOFF_SUCCESSFUL;\n    }\n\n    public String deleteAccount()\n    {\n        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);\n        DataKeeperService service = DataKeeperUtils.getService();\n        Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);\n\n        service.removeEmployee(employee);\n\n        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(\"Account successfully deleted\"));\n        session.invalidate();\n        return \"Account successfully deleted\";\n    }\n\n    public String authenticate()\n    {\n        String outcome = null;\n\n        // Validates Parameters\n        if (StringUtils.isBlank(employee.getEmployeeName()))\n        {\n            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(\"Please enter your user name\"));\n            outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;\n        }\n\n        if (StringUtils.isBlank(employee.getPassword()))\n        {\n            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(\"Please enter password\"));\n            outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;\n        }\n\n        if (StringUtils.isNotBlank(outcome))\n        {\n            return outcome;\n        }\n        else\n        {\n            DataKeeperService service = DataKeeperUtils.getService();\n            Employee foundEmployee = service.findEmployeeByName(employee.getEmployeeName());\n            boolean success = service.authenticateEmployee(foundEmployee, employee.getPassword());\n\n            if (!success)\n            {\n                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(\"Incorrect User Name/Password\"));\n                outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;\n            }\n            else\n            {\n                outcome = DataKeeperConstants.OUTCOME_LOGIN_SUCCESSFUL;\n                HttpSession session = FacesUtils.getSession();\n                session.setAttribute(DataKeeperConstants.EMPLOYEE, foundEmployee);\n            }\n            return outcome;\n        }\n    }\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/RegisterBean.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.datakeeper.beans;\n\nimport javax.faces.application.FacesMessage;\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\nimport javax.faces.context.FacesContext;\n\nimport org.primefaces.event.FlowEvent;\n\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\n\n/**\n * <Prove description of functionality provided by this Type>\n * \n * @author Kuldeep.Mishra\n */\n\n@ManagedBean(name = \"registerBean\")\n@RequestScoped\npublic class RegisterBean\n{\n    private Employee employee = new Employee();\n\n    private int managerId;\n\n    public RegisterBean()\n    {\n    }\n\n    public Employee getEmployee()\n    {\n        return employee;\n    }\n\n    public void setEmployee(Employee employee)\n    {\n        this.employee = employee;\n    }\n\n    public int getManagerId()\n    {\n        return managerId;\n    }\n\n    public void setManagerId(int managerId)\n    {\n        this.managerId = managerId;\n    }\n\n    public String onFlowProcess(FlowEvent event)\n    {\n        return event.getNewStep();\n    }\n\n    public String save()\n    {\n        DataKeeperService service = DataKeeperUtils.getService();\n\n        Employee manager = service.findEmployee(managerId);\n\n        employee.setManager(manager);\n        employee.setTimestamp(employee.getJoiningDate().getTime());\n\n        service.insertEmployee(employee);\n\n        FacesMessage msg = new FacesMessage(\"SignUp Successful! Welcome, \" + employee.getEmployeeName());\n\n        FacesContext.getCurrentInstance().addMessage(null, msg);\n\n        return \"signUpSuccessful\";\n    }\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/SearchType.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.datakeeper.beans;\n\n\n/**\n * @author Kuldeep.Mishra\n * \n */\nenum SearchType\n{\n    ID, NAME;\n\n    static SearchType getSearchType(int searchBy)\n    {\n        if (searchBy == 1)\n        {\n            return ID;\n        }\n        else if (searchBy == 0)\n        {\n            return NAME;\n        }\n        return null;\n    }\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/dao/DataKeeperDao.java",
    "content": "package com.impetus.kundera.datakeeper.dao;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic interface DataKeeperDao\n{\n    EntityManager getEntityManager();\n\n    void closeEntityManager();\n\n    void clearEntityManager();\n\n    void shutDown();\n\n    void insert(Object entity);\n\n    void merge(Object entity);\n\n    void remove(Object entity);\n\n    <T> T findById(Class<T> entityClazz, Object id);\n\n    List<?> findByQuery(String Query);\n\n    List<?> findByQuery(String queryString, String paramater, Object parameterValue);\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/dao/DataKeeperDaoImpl.java",
    "content": "package com.impetus.kundera.datakeeper.dao;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.PersistenceContext;\nimport javax.persistence.PersistenceContextType;\nimport javax.persistence.Query;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.transaction.annotation.Propagation;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport com.impetus.kundera.datakeeper.service.DataKeeperServiceImpl;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\n// @Transactional(propagation = Propagation.REQUIRED)\npublic class DataKeeperDaoImpl implements DataKeeperDao\n{\n    /**\n     * logger used for logging statement.\n     */\n    private static final Logger log = LoggerFactory.getLogger(DataKeeperServiceImpl.class);\n\n    @PersistenceContext(unitName = \"cassandra-pu,mongo-pu\", type = PersistenceContextType.EXTENDED)\n    private EntityManager em;\n\n    public DataKeeperDaoImpl()\n    {\n    }\n\n    @Override\n    public void insert(Object entity)\n    {\n        em.persist(entity);\n        em.clear();\n    }\n\n    @Override\n    public void merge(Object entity)\n    {\n        em.merge(entity);\n        em.clear();\n    }\n\n    @Override\n    public void remove(Object entity)\n    {\n        em.remove(entity);\n        em.clear();\n    }\n\n    @Override\n    public <T> T findById(Class<T> entityClazz, Object id)\n    {\n        T results = em.find(entityClazz, id);\n        return results;\n    }\n\n    @Override\n    public List<?> findByQuery(String queryString)\n    {\n        log.info(queryString);\n        Query query = em.createQuery(queryString);\n        List<?> resultList = query.getResultList();\n        return resultList;\n    }\n\n    @Override\n    public List<?> findByQuery(String queryString, String paramater, Object parameterValue)\n    {\n        Query query = em.createQuery(queryString);\n        query.setParameter(paramater, parameterValue);\n        log.info(queryString);\n        List<?> resultList = query.getResultList();\n        return resultList;\n    }\n\n    @Override\n    public EntityManager getEntityManager()\n    {\n        return em;\n    }\n\n    @Override\n    public void closeEntityManager()\n    {\n        if (em != null)\n        {\n            em.close();\n        }\n    }\n\n    @Override\n    public void clearEntityManager()\n    {\n        if (em != null)\n        {\n            em.clear();\n        }\n    }\n\n    @Override\n    public void shutDown()\n    {\n        if (em != null)\n        {\n            em.close();\n        }\n    }\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/entities/DocumentInfo.java",
    "content": "package com.impetus.kundera.datakeeper.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport org.primefaces.model.StreamedContent;\n\nimport com.impetus.kundera.datakeeper.utils.DataFormat;\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\n@Entity\n@Table(name = \"DOCUMENT\", schema = \"datakeeper@mongo-pu\")\n@IndexCollection(columns = { @Index(name = \"ownerName\"), @Index(name = \"ownerId\"), @Index(name = \"documentName\") })\npublic class DocumentInfo\n{\n    @Id\n    @Column(name = \"DOCUMENT_ID\")\n    @GeneratedValue()\n    private String dataId;\n\n    @Column(name = \"EMPLOYEE_NAME\")\n    private String ownerName;\n\n    @Column(name = \"EMPLOYEE_ID\")\n    private int ownerId;\n\n    @Column(name = \"UPLOADED_DATE\")\n    private Date uplodedDate;\n\n    @Column(name = \"DOCUMENT_FORMAT\")\n    private DataFormat dataFormat;\n\n    @Column(name = \"DOCUMENT_NAME\")\n    private String documentName;\n\n    @Column(name = \"DATA\")\n    private byte[] data;\n\n    private StreamedContent file;\n\n    @Column(name = \"SIZE\")\n    private long size;\n\n    /**\n     * @return the dataId\n     */\n    public String getDataId()\n    {\n        return dataId;\n    }\n\n    /**\n     * @param dataId\n     *            the dataId to set\n     */\n    public void setDataId(String dataId)\n    {\n        this.dataId = dataId;\n    }\n\n    /**\n     * @return the ownerName\n     */\n    public String getOwnerName()\n    {\n        return ownerName;\n    }\n\n    /**\n     * @param ownerName\n     *            the ownerName to set\n     */\n    public void setOwnerName(String ownerName)\n    {\n        this.ownerName = ownerName;\n    }\n\n    /**\n     * @return the ownerId\n     */\n    public int getOwnerId()\n    {\n        return ownerId;\n    }\n\n    /**\n     * @param ownerId\n     *            the ownerId to set\n     */\n    public void setOwnerId(int ownerId)\n    {\n        this.ownerId = ownerId;\n    }\n\n    /**\n     * @return the uplodedDate\n     */\n    public Date getUplodedDate()\n    {\n        return uplodedDate;\n    }\n\n    /**\n     * @param uplodedDate\n     *            the uplodedDate to set\n     */\n    public void setUplodedDate(Date uplodedDate)\n    {\n        this.uplodedDate = uplodedDate;\n    }\n\n    /**\n     * @return the dataFormat\n     */\n    public DataFormat getDataFormat()\n    {\n        return dataFormat;\n    }\n\n    /**\n     * @param dataFormat\n     *            the dataFormat to set\n     */\n    public void setDataFormat(DataFormat dataFormat)\n    {\n        this.dataFormat = dataFormat;\n    }\n\n    public byte[] getData()\n    {\n        return data;\n    }\n\n    public void setData(byte[] data)\n    {\n        this.data = data;\n    }\n\n    public String getDocumentName()\n    {\n        return documentName;\n    }\n\n    public void setDocumentName(String documentName)\n    {\n        this.documentName = documentName;\n    }\n\n    public long getSize()\n    {\n        return size;\n    }\n\n    public void setSize(long size)\n    {\n        this.size = size;\n    }\n\n    public StreamedContent getFile()\n    {\n        return file;\n    }\n\n    public void addFile(StreamedContent file)\n    {\n        this.file = file;\n    }\n\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/entities/Employee.java",
    "content": "package com.impetus.kundera.datakeeper.entities;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\n@Entity\n@Table(name = \"EMPLOYEE\", schema = \"datakeeper@cassandra-pu\")\n@IndexCollection(columns = { @Index(name = \"employeeName\"), @Index(name = \"designation\"), @Index(name = \"experience\"),\n        @Index(name = \"joiningDate\"), @Index(name = \"currentProject\"), @Index(name = \"timestamp\"),\n        @Index(name = \"company\") })\npublic class Employee\n{\n    @Id\n    @Column(name = \"EMPLOYEE_ID\")\n    @GeneratedValue(strategy = GenerationType.TABLE)\n    private int employeeId;\n\n    @Column(name = \"PASSWORD\")\n    private String password;\n\n    @Column(name = \"EMPLOYEE_NAME\")\n    private String employeeName;\n\n    @Column(name = \"EXPERIENCE\")\n    private int experience;\n\n    @Column(name = \"JOINING_DATE\")\n    private Date joiningDate;\n\n    @Column(name = \"DESIGNATION\")\n    private String designation;\n\n    @ManyToOne(fetch = FetchType.EAGER)\n    @JoinColumn(name = \"MANAGER_ID\")\n    private Employee manager;\n\n    @OneToMany(fetch = FetchType.EAGER, mappedBy = \"manager\")\n    private List<Employee> subordinates;\n\n    @Column(name = \"PROJECT\")\n    private String currentProject;\n\n    @Column(name = \"COMPANY\")\n    private String company;\n\n    @Column(name = \"JOINING_TIMESTAMP\")\n    private long timestamp;\n\n    public int getEmployeeId()\n    {\n        return employeeId;\n    }\n\n    public void setEmployeeId(int employeeId)\n    {\n        this.employeeId = employeeId;\n    }\n\n    public String getPassword()\n    {\n        return password;\n    }\n\n    public void setPassword(String password)\n    {\n        this.password = password;\n    }\n\n    public String getEmployeeName()\n    {\n        return employeeName;\n    }\n\n    public void setEmployeeName(String employeeName)\n    {\n        this.employeeName = employeeName;\n    }\n\n    public int getExperience()\n    {\n        return experience;\n    }\n\n    public void setExperience(int experience)\n    {\n        this.experience = experience;\n    }\n\n    public Date getJoiningDate()\n    {\n        return joiningDate;\n    }\n\n    public void setJoiningDate(Date joiningDate)\n    {\n        this.joiningDate = joiningDate;\n    }\n\n    public String getDesignation()\n    {\n        return designation;\n    }\n\n    public void setDesignation(String designation)\n    {\n        this.designation = designation;\n    }\n\n    public Employee getManager()\n    {\n        return manager;\n    }\n\n    public void setManager(Employee manager)\n    {\n        this.manager = manager;\n    }\n\n    public String getCurrentProject()\n    {\n        return currentProject;\n    }\n\n    public void setCurrentProject(String currentProject)\n    {\n        this.currentProject = currentProject;\n    }\n\n    public List<Employee> getSubordinates()\n    {\n        return subordinates;\n    }\n\n    public void setSubordinates(List<Employee> subordinates)\n    {\n        this.subordinates = subordinates;\n    }\n\n    public long getTimestamp()\n    {\n        return timestamp;\n    }\n\n    public void setTimestamp(long timestamp)\n    {\n        this.timestamp = timestamp;\n    }\n\n    public String getCompany()\n    {\n        return company;\n    }\n\n    public void setCompany(String company)\n    {\n        this.company = company;\n    }\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/entities/SubordinatesCounter.java",
    "content": "package com.impetus.kundera.datakeeper.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"SUBORDINATES_COUNTER\", schema = \"datakeeper@cassandra-pu\")\npublic class SubordinatesCounter\n{\n    @Id\n    @Column(name = \"EMPLOYEE_ID\")\n    private int employeeId;\n\n    @Column(name = \"SUBORDINATES_COUNTER\")\n    private int noOfSubordinates;\n\n    public int getEmployeeId()\n    {\n        return employeeId;\n    }\n\n    public void setEmployeeId(int employeeId)\n    {\n        this.employeeId = employeeId;\n    }\n\n    public int getNoOfSubordinates()\n    {\n        return noOfSubordinates;\n    }\n\n    public void setNoOfSubordinates(int noOfSubordinates)\n    {\n        this.noOfSubordinates = noOfSubordinates;\n    }\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/service/DataKeeperService.java",
    "content": "package com.impetus.kundera.datakeeper.service;\n\nimport java.util.List;\n\nimport com.impetus.kundera.datakeeper.entities.DocumentInfo;\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.entities.SubordinatesCounter;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic interface DataKeeperService\n{\n    void insertEmployee(Employee employee);\n\n    void insertData(DocumentInfo data);\n\n    Employee findEmployee(Object id);\n\n    Employee findEmployeeByName(String employeeName);\n\n    List<DocumentInfo> findDocumentByEmployeeId(String employeeId);\n\n    List<DocumentInfo> findDocumentByEmployeeName(String employeeName);\n\n    DocumentInfo findDocumentByDocumentId(int documentId);\n\n    void removeEmployee(Employee employee);\n\n    boolean authenticateEmployee(Employee employee, String password);\n\n    List<Employee> findSubOrdinates(int managerId);\n\n    List<Employee> findEmployeeByDateOfJoining(int noOfYears, String company);\n\n    void incrementCounter(SubordinatesCounter counter);\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/service/DataKeeperServiceImpl.java",
    "content": "package com.impetus.kundera.datakeeper.service;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.PersistenceException;\n\nimport org.primefaces.model.DefaultStreamedContent;\nimport org.primefaces.model.StreamedContent;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.datakeeper.dao.DataKeeperDao;\nimport com.impetus.kundera.datakeeper.entities.DocumentInfo;\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.entities.SubordinatesCounter;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic class DataKeeperServiceImpl implements DataKeeperService\n{\n    /**\n     * logger used for logging statement.\n     */\n    private static final Logger log = LoggerFactory.getLogger(DataKeeperServiceImpl.class);\n\n    private DataKeeperDao dao;\n\n    public DataKeeperServiceImpl()\n    {\n    }\n\n    public DataKeeperDao getDao()\n    {\n        return dao;\n    }\n\n    public void setDao(DataKeeperDao dao)\n    {\n        this.dao = dao;\n    }\n\n    @Override\n    public void insertEmployee(Employee employee)\n    {\n        employee.setPassword(encriptPassword(employee.getPassword()));\n        dao.insert(employee);\n        log.info(\"Employee {} information successfully inserted.\", employee.getEmployeeName());\n\n        if (employee.getManager() != null)\n        {\n            SubordinatesCounter counter = new SubordinatesCounter();\n            counter.setNoOfSubordinates(1);\n            counter.setEmployeeId(employee.getManager().getEmployeeId());\n            dao.insert(counter);\n            log.info(\"Incremented no of subordinates for manager {}, successfully.\", employee.getManager()\n                    .getEmployeeName());\n        }\n    }\n\n    @Override\n    public Employee findEmployeeByName(String employeeName)\n    {\n        Employee employee = null;\n        String query = \"Select e from \" + Employee.class.getSimpleName() + \" e where e.employeeName = \" + employeeName;\n        List<Employee> employees = (List<Employee>) dao.findByQuery(query);\n        if (!employees.isEmpty() && employees.get(0) != null)\n        {\n            employee = employees.get(0);\n        }\n        return employee;\n    }\n\n    @Override\n    public List<Employee> findSubOrdinates(int managerId)\n    {\n        Employee manager = dao.findById(Employee.class, managerId);\n        List<Employee> subOrdinates = manager != null ? manager.getSubordinates() : new ArrayList<Employee>();\n        return subOrdinates;\n    }\n\n    @Override\n    public void insertData(DocumentInfo data)\n    {\n        dao.insert(data);\n        log.info(\"Data uploaded by  employee {} successfully inserted.\", data.getOwnerName());\n    }\n\n    @Override\n    public Employee findEmployee(Object employeeId)\n    {\n        log.info(\"Finding employee by id {} .\", employeeId);\n        return dao.findById(Employee.class, employeeId);\n    }\n\n    @Override\n    public List<DocumentInfo> findDocumentByEmployeeId(String employeeId)\n    {\n        List<DocumentInfo> documents = new ArrayList<DocumentInfo>();\n        try\n        {\n            Integer.parseInt(employeeId);\n            documents = findDocumentByEmployeeId(Integer.parseInt(employeeId));\n        }\n        catch (NumberFormatException nfex)\n        {\n            log.warn(\"{} not a valid employee id.\", employeeId);\n        }\n        return documents;\n    }\n\n    public List<DocumentInfo> findDocumentByEmployeeId(int employeeId)\n    {\n        List<DocumentInfo> documents = new ArrayList<DocumentInfo>();\n        log.info(\"Finding document by employee id {} .\", employeeId);\n        String query = \"Select d from \" + DocumentInfo.class.getSimpleName() + \" d where d.ownerId =  \" + employeeId;\n        documents = (List<DocumentInfo>) dao.findByQuery(query);\n\n        for (DocumentInfo documentInfo : documents)\n        {\n            StreamedContent file = toStreamedContent(documentInfo.getData(), documentInfo.getDocumentName(),\n                    \"application/pdf\");\n            documentInfo.addFile(file);\n        }\n        return documents;\n    }\n\n    @Override\n    public List<DocumentInfo> findDocumentByEmployeeName(String employeeName)\n    {\n        List<DocumentInfo> documents = new ArrayList<DocumentInfo>();\n        log.info(\"Finding document by employee name {} .\", employeeName);\n        String query = \"Select d from \" + DocumentInfo.class.getSimpleName() + \" d where d.ownerName =  \"\n                + employeeName;\n        documents = (List<DocumentInfo>) dao.findByQuery(query);\n        for (DocumentInfo documentInfo : documents)\n        {\n            StreamedContent file = toStreamedContent(documentInfo.getData(), documentInfo.getDocumentName(),\n                    \"application/pdf\");\n            documentInfo.addFile(file);\n        }\n        return documents;\n    }\n\n    @Override\n    public void removeEmployee(Employee employee)\n    {\n        dao.remove(employee);\n        List<DocumentInfo> documents = findDocumentByEmployeeId(employee.getEmployeeId());\n        for (DocumentInfo document : documents)\n        {\n            if (document != null)\n            {\n                dao.remove(document);\n            }\n        }\n\n        log.info(\"Employee successfully removed\");\n    }\n\n    @Override\n    public boolean authenticateEmployee(Employee employee, String password)\n    {\n        boolean success = false;\n        if (employee != null && (employee.getPassword().equals(encriptPassword(password))))\n        {\n            log.info(\"Employee {} successfully authenticated.\", employee.getEmployeeName());\n            success = true;\n        }\n        else\n        {\n            log.info(\"Employee not authenticated, caused by either wrong userName or wrong password.\");\n        }\n        return success;\n    }\n\n    /**\n     * encriptPassword method used for encrypting password.\n     * \n     * @param password\n     *            the password\n     * @return the string\n     */\n    public String encriptPassword(String password)\n    {\n        String newpassword = null;\n        byte[] defaultBytes = password.getBytes();\n        try\n        {\n            MessageDigest algorithm = MessageDigest.getInstance(\"MD5\");\n            algorithm.reset();\n            algorithm.update(defaultBytes);\n            byte messageDigest[] = algorithm.digest();\n\n            StringBuffer hexString = new StringBuffer();\n            for (int i = 0; i < messageDigest.length; i++)\n            {\n                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));\n            }\n            newpassword = hexString.toString();\n        }\n        catch (NoSuchAlgorithmException e)\n        {\n            log.error(\"Error while encripting password {}, caused by : .\", password, e);\n            throw new PersistenceException(e);\n        }\n        return newpassword;\n    }\n\n    @Override\n    public DocumentInfo findDocumentByDocumentId(int documentId)\n    {\n        log.info(\"Finding document by id.\");\n        DocumentInfo document = dao.findById(DocumentInfo.class, documentId);\n        return document;\n    }\n\n    @Override\n    public List<Employee> findEmployeeByDateOfJoining(final int noOfYears, final String company)\n    {\n        long currentTimeStamp = System.currentTimeMillis();\n        long newTimeStamp = currentTimeStamp - (long) noOfYears * 365 * 24 * 60 * 60 * 1000;\n        String query = \"Select e from \" + Employee.class.getSimpleName() + \" e where e.company = \" + company\n                + \" and e.timestamp <= :timestamp\";\n        List<Employee> subOrdinates = (List<Employee>) dao.findByQuery(query, \"timestamp\", newTimeStamp);\n        return subOrdinates;\n    }\n\n    @Override\n    public void incrementCounter(SubordinatesCounter counter)\n    {\n        dao.insert(counter);\n    }\n\n    private StreamedContent toStreamedContent(byte[] bytes, String fileName, String contentType)\n    {\n        InputStream is = new ByteArrayInputStream(bytes);\n\n        StreamedContent file = new DefaultStreamedContent(is, contentType, fileName);\n\n        return file;\n    }\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/DataFormat.java",
    "content": "package com.impetus.kundera.datakeeper.utils;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic enum DataFormat\n{\n    XLS, XLSX, PDF, DOC, DOCX, AVI;\n\n    /**\n     * If provided protocol is within allowed protocol.\n     * \n     * @param protocol\n     *            protocol\n     * @return true, if it is in allowed protocol.\n     */\n    public static boolean isValidFormat(String format)\n    {\n        try\n        {\n            DataFormat.valueOf(format.toUpperCase());\n            return true;\n        }\n        catch (IllegalArgumentException iex)\n        {\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/DataKeeperConstants.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.datakeeper.utils;\n\n/**\n * <Prove description of functionality provided by this Type> \n * @author amresh.singh\n */\npublic class DataKeeperConstants\n{\n    public static final String OUTCOME_LOGIN_FAILED = \"loginFailed\";\n    public static final String OUTCOME_LOGIN_SUCCESSFUL = \"loginSuccessful\";\n    \n    public static final String OUTCOME_SIGNUP_SUCCESSFUL = \"signUpSuccessful\";\n    \n    public static final String OUTCOME_LOGOFF_SUCCESSFUL = \"logOfSuccessful\";\n    \n    public static final String OUTCOME_TIMELINE = \"timeline\";    \n    \n    public static final String PERSISTENCE_UNIT = \"twitample_cassandra\";\n    \n    public static final String EMPLOYEE_ID = \"employeeId\";\n\n    public static final String EMPLOYEE = \"employee\";\n    \n    public static final String EMPLOYEE_NAME = \"employeeName\";\n    \n    public static final String TWEET_DEVICE_WEB = \"Web\";\n    \n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/DataKeeperUtils.java",
    "content": "package com.impetus.kundera.datakeeper.utils;\n\nimport javax.faces.context.FacesContext;\nimport javax.servlet.http.HttpSession;\n\nimport org.springframework.beans.factory.BeanFactory;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\n\npublic class DataKeeperUtils\n{\n    public static DataKeeperService getService()\n    {\n        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);\n        DataKeeperService datakeeper = (DataKeeperService) session.getAttribute(\"datakeeper\");\n        if (datakeeper == null)\n        {\n            BeanFactory beanfactory = new ClassPathXmlApplicationContext(\"appContext.xml\");\n            datakeeper = (DataKeeperService) beanfactory.getBean(\"datakeeper\");\n            session.setAttribute(\"datakeeper\", datakeeper);\n        }\n        return datakeeper;\n    }\n}\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/FacesUtils.java",
    "content": "package com.impetus.kundera.datakeeper.utils;\r\n\r\nimport javax.faces.context.FacesContext;\r\nimport javax.servlet.http.HttpServletRequest;\r\nimport javax.servlet.http.HttpSession;\r\n\r\n/**\r\n * The Class FacesUtils has method for getting session variables and request\r\n * variables.\r\n */\r\npublic class FacesUtils\r\n{\r\n\r\n    /**\r\n     * getSession method used for getting session variable.\r\n     * \r\n     * @return the session\r\n     */\r\n    public static HttpSession getSession()\r\n    {\r\n        return (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);\r\n    }\r\n\r\n    /**\r\n     * getRequest method used for getting request variable.\r\n     * \r\n     * @return the request\r\n     */\r\n    public static HttpServletRequest getRequest()\r\n    {\r\n        return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();\r\n    }\r\n}\r\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"cassandra-pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.datakeeper.entities.DocumentInfo</class>\r\n\t\t<class>com.impetus.kundera.datakeeper.entities.Employee</class>\r\n\t\t<class>com.impetus.kundera.datakeeper.entities.SubordinatesCounter</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t<!-- \t<property name=\"jboss.as.jpa.managed\" value=\"false\" /> -->\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"datakeeper\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"thrift\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\r\n\t\t\t<property name=\"kundera.cache.provider.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\r\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\r\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaCounter.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"mongo-pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.datakeeper.entities.DocumentInfo</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<!-- <property name=\"jboss.as.jpa.managed\" value=\"false\" /> -->\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"datakeeper\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\r\n\t\t\t<property name=\"kundera.cache.provider.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\r\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"cassandra-pu,mongo-pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<!-- <property name=\"jboss.as.jpa.managed\" value=\"false\" /> -->\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\r\n</persistence>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/resources/appContext.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \"http://www.springframework.org/dtd/spring-beans.dtd\"> -->\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:context=\"http://www.springframework.org/schema/context\"\n\txmlns:tx=\"http://www.springframework.org/schema/tx\" xmlns:p=\"http://www.springframework.org/schema/p\"\n\txmlns:aop=\"http://www.springframework.org/schema/aop\"\n\txsi:schemaLocation=\"http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.0.xsd  http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd\">\n\n\t<bean id=\"datakeeper\" class=\"com.impetus.kundera.datakeeper.service.DataKeeperServiceImpl\"\n\t\tscope=\"singleton\">\n\t\t<property name=\"dao\" ref=\"dao\" />\n\t</bean>\n\t\n\t<bean id=\"dao\" class=\"com.impetus.kundera.datakeeper.dao.DataKeeperDaoImpl\"\n\t\tscope=\"singleton\">\n\t</bean>\n\t\n\t<!-- Enable @PersistenceContext initialization -->\n\t<!-- <bean\n\t\tclass=\"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor\" />\n\n\t<bean id=\"emf-p\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t\t<property name=\"persistenceUnitManager\" ref=\"persistence-unit\" />\n\t\t<property name=\"persistenceUnitName\" value=\"cassandra_pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean> -->\n\t\n\t<bean id=\"emf-p\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t\t<property name=\"persistenceUnitName\" value=\"cassandra-pu,mongo-pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean>\n\n\t<bean id=\"emf-p1\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t<property name=\"persistenceUnitName\" value=\"cassandra-pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean>\n\t<bean id=\"emf-p2\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t\t<property name=\"persistenceUnitName\" value=\"mongo-pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean>\n\n\t<!-- <bean id=\"persistence-unit\"\n\t\tclass=\"org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager\">\n\t\t<property name=\"persistenceXmlLocations\">\n\t\t\t<list>\n\t\t\t\t<value>META-INF/persistence.xml</value>\n\t\t\t</list>\n\t\t</property>\n\t</bean> -->\n<bean\n\t\tclass=\"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor\" >\n\t</bean>\n\n\t<bean id=\"pum\"\n\t\tclass=\"org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager\">\n\t\t<property name=\"persistenceXmlLocations\">\n\t\t\t<list>\n\t\t\t\t<value>META-INF/persistence.xml</value>\n\t\t\t</list>\n\t\t</property>\n\t</bean>\n\t\n\t<bean id=\"matchAllWithPropReq\"\n\t\tclass=\"org.springframework.transaction.interceptor.MatchAlwaysTransactionAttributeSource\">\n\t\t<property name=\"transactionAttribute\" value=\"PROPAGATION_REQUIRED\" />\n\t</bean>\n\n\t<bean id=\"jndiTemplate\" class=\"org.springframework.jndi.JndiTemplate\"\n\t\tlazy-init=\"true\">\n\t\t<property name=\"environment\">\n\t\t\t<props>\n\t\t\t\t<prop key=\"java.naming.factory.initial\">org.apache.naming.java.javaURLContextFactory</prop>\n\t\t\t\t<prop key=\"java.naming.factory.url.pkgs\">org.apache.naming</prop>\n\t\t\t</props>\n\t\t</property>\n\t</bean>\n</beans>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/resources/kunderaCounter.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>cassandra</name>\n\t\t\t<schemas>\n\t\t\t\t<schema>\n\t\t\t\t\t<name>datakeeper</name>\n\t\t\t\t\t<tables>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>SUBORDINATES_COUNTER</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"default.validation.class\" value=\"CounterColumnType\"></property>\n\t\t\t\t\t\t\t\t<property name=\"key.validation.class\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</tables>\n\t\t\t\t</schema>\n\t\t\t</schemas>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/resources/log4j.properties",
    "content": "log4j.rootLogger=INFO, DRFA, CONSOLE\r\n\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera-benchmark.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/WEB-INF/faces-config.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd\"\n\tversion=\"2.1\">\n\t<navigation-rule>\n\t\t<from-view-id>/xhtml/login/login.xhtml</from-view-id>\n\t\t<navigation-case>\n\t\t\t<from-outcome>loginSuccessful</from-outcome>\n\t\t\t<to-view-id>/xhtml/home/timeline.xhtml</to-view-id>\n\t\t</navigation-case>\n\t\t<navigation-case>\n\t\t\t<from-outcome>loginFailed</from-outcome>\n\t\t\t<to-view-id>/xhtml/login/login.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n\n\t<navigation-rule>\n\t\t<from-view-id>/xhtml/register/signUp.xhtml</from-view-id>\n\t\t<navigation-case>\n\t\t\t<from-outcome>signUpSuccessful</from-outcome>\n\t\t\t<to-view-id>/xhtml/login/login.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n\n\t<navigation-rule>\n\t\t<from-view-id>/xhtml/register/signUp.xhtml</from-view-id>\n\t\t<navigation-case>\n\t\t\t<from-outcome>timeline</from-outcome>\n\t\t\t<to-view-id>/xhtml/home/timeline.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n\t<navigation-rule>\n\t\t<from-view-id>/xhtml/home/timeline.xhtml</from-view-id>\n\t\t<navigation-case>\n\t\t\t<from-outcome>foundEmployess</from-outcome>\n\t\t\t<to-view-id>/xhtml/home/showSubordinatesInfo.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n\t<navigation-rule>\n\t\t<from-view-id>/xhtml/home/showSubordinatesInfo.xhtml</from-view-id>\n\t\t<navigation-case>\n\t\t\t<from-outcome>foundEmployess</from-outcome>\n\t\t\t<to-view-id>/xhtml/home/showSubordinatesInfo.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n\t<navigation-rule>\n\t\t<navigation-case>\n\t\t\t<from-outcome>logOfSuccessful</from-outcome>\n\t\t\t<to-view-id>/xhtml/login/login.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n\n\t<navigation-rule>\n\t\t<navigation-case>\n\t\t\t<from-outcome>Account successfully deleted</from-outcome>\n\t\t\t<to-view-id>/xhtml/login/login.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n</faces-config>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/WEB-INF/web.xml",
    "content": "<?xml version=\"1.0\"?>\n<web-app version=\"2.5\" xmlns=\"http://java.sun.com/xml/ns/javaee\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\">\n\t<display-name>DataKeeper application</display-name>\n\n\t<context-param>\n\t\t<param-name>javax.faces.STATE_SAVING_METHOD</param-name>\n\t\t<param-value>server</param-value>\n\t</context-param>\n\t<context-param>\n\t\t<param-name>javax.faces.CONFIG_FILES</param-name>\n\t\t<param-value>/WEB-INF/faces-config.xml</param-value>\n\t</context-param>\n\n\n\t<listener>\n\t\t<listener-class>com.sun.faces.config.ConfigureListener</listener-class>\n\t</listener>\n\n\t<!-- Faces Servlet -->\n\t<servlet>\n\t\t<servlet-name>Faces Servlet</servlet-name>\n\t\t<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n\t\t<load-on-startup>1</load-on-startup>\n\t</servlet>\n\n\t<servlet-mapping>\n\t\t<servlet-name>Faces Servlet</servlet-name>\n\t\t<url-pattern>*.jsf</url-pattern>\n\t</servlet-mapping>\n\n\t<welcome-file-list>\n\t\t<welcome-file>xhtml/login/login.jsf</welcome-file>\n\t</welcome-file-list>\n\n\t<filter>\n\t\t<filter-name>PrimeFaces FileUpload Filter</filter-name>\n\t\t<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>\n\t\t<init-param>\n\t\t\t<param-name>thresholdSize</param-name>\n\t\t\t<param-value>512000</param-value>\n\t\t</init-param>\n\t\t<init-param>\n\t\t\t<param-name>uploadDirectory</param-name>\n\t\t\t<param-value>C:\\etc</param-value>\n\t\t</init-param>\n\t</filter>\n\t<filter-mapping>\n\t\t<filter-name>PrimeFaces FileUpload Filter</filter-name>\n\t\t<servlet-name>Faces Servlet</servlet-name>\n\t</filter-mapping>\n\n</web-app>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/appContext.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \"http://www.springframework.org/dtd/spring-beans.dtd\"> -->\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:context=\"http://www.springframework.org/schema/context\"\n\txmlns:tx=\"http://www.springframework.org/schema/tx\" xmlns:p=\"http://www.springframework.org/schema/p\"\n\txmlns:aop=\"http://www.springframework.org/schema/aop\"\n\txsi:schemaLocation=\"http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.0.xsd  http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd\">\n\n\t<bean id=\"datakeeper\" class=\"com.impetus.kundera.datakeeper.service.DataKeeperServiceImpl\"\n\t\tscope=\"singleton\">\n\t\t<property name=\"dao\" ref=\"dao\" />\n\t</bean>\n\t\n\t<bean id=\"dao\" class=\"com.impetus.kundera.datakeeper.dao.DataKeeperDaoImpl\"\n\t\tscope=\"singleton\">\n\t</bean>\n\t\n\t<!-- Enable @PersistenceContext initialization -->\n\t<!-- <bean\n\t\tclass=\"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor\" />\n\n\t<bean id=\"emf-p\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t\t<property name=\"persistenceUnitManager\" ref=\"persistence-unit\" />\n\t\t<property name=\"persistenceUnitName\" value=\"cassandra_pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean> -->\n\t\n\t<bean id=\"emf-p\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t\t<property name=\"persistenceUnitName\" value=\"cassandra-pu,mongo-pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean>\n\n\t<bean id=\"emf-p1\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t<property name=\"persistenceUnitName\" value=\"cassandra-pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean>\n\t<bean id=\"emf-p2\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t\t<property name=\"persistenceUnitName\" value=\"mongo-pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean>\n\n\t<!-- <bean id=\"persistence-unit\"\n\t\tclass=\"org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager\">\n\t\t<property name=\"persistenceXmlLocations\">\n\t\t\t<list>\n\t\t\t\t<value>META-INF/persistence.xml</value>\n\t\t\t</list>\n\t\t</property>\n\t</bean> -->\n<bean\n\t\tclass=\"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor\" >\n\t</bean>\n\n\t<bean id=\"pum\"\n\t\tclass=\"org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager\">\n\t\t<property name=\"persistenceXmlLocations\">\n\t\t\t<list>\n\t\t\t\t<value>META-INF/persistence.xml</value>\n\t\t\t</list>\n\t\t</property>\n\t</bean>\n\t\n\t<bean id=\"matchAllWithPropReq\"\n\t\tclass=\"org.springframework.transaction.interceptor.MatchAlwaysTransactionAttributeSource\">\n\t\t<property name=\"transactionAttribute\" value=\"PROPAGATION_REQUIRED\" />\n\t</bean>\n\n\t<bean id=\"jndiTemplate\" class=\"org.springframework.jndi.JndiTemplate\"\n\t\tlazy-init=\"true\">\n\t\t<property name=\"environment\">\n\t\t\t<props>\n\t\t\t\t<prop key=\"java.naming.factory.initial\">org.apache.naming.java.javaURLContextFactory</prop>\n\t\t\t\t<prop key=\"java.naming.factory.url.pkgs\">org.apache.naming</prop>\n\t\t\t</props>\n\t\t</property>\n\t</bean>\n</beans>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/index.jsp",
    "content": "<html>\n<body>\n<h2>Hello World!</h2>\n</body>\n</html>\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/common/header.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:h=\"http://java.sun.com/jsf/html\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:ui=\"http://java.sun.com/jsf/facelets\"\n xmlns:p=\"http://primefaces.org/ui\">\n<h:panelGroup>\n    <table width=\"100%\">\n        <tbody>\n            <tr>\n        <td align=\"left\"><img src=\"../../images/impetus_logo.jpg\" height=\"50\" width=\"150\" /></td>\n                <td >\n                    <h2><h:outputText value=\"DataKeeper\" /></h2>\n                </td>\n                <td align=\"right\">\n                </td>\n        </tr>\n        </tbody>\n    </table>\n</h:panelGroup>\n</ui:composition>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/common/leftPane.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<p:panel header=\"Welcome, #{sessionScope.employee.employeeName}\">\n\n\t\t<table>\n\t\t\t<tr>\n\t\t\t\t<td><img src=\"../../images/BlankProfile.gif\" height=\"200\"\n\t\t\t\t\twidth=\"200\" /></td>\n\t\t\t</tr>\n\n\n\n\t\t\t<tr>\n\t\t\t\t<td><br /> <h:outputText value=\"Employee Detail\"\n\t\t\t\t\t\tstyle=\"font-weight:bold;\" /> <br /></td>\n\t\t\t</tr>\n\t\t\t<ui:repeat var=\"employee\" value=\"#{employee}\">\n\t\t\t\t<tr>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText value=\"Employee Id:-\" /></td>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"#{employee.employeeId}\" /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText value=\"Employee Name:-\"/></td>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"#{employee.employeeName}\" /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"Experience in year:-\" /></td>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"#{employee.experience}\" /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText value=\"Designation:-\" /></td>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"#{employee.designation}\" /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText value=\"Manager Name:-\" /></td>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"#{employee.manager.employeeName}\" /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText value=\"Project:-\" /></td>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"#{employee.currentProject}\" /></td>\n\t\t\t\t</tr>\n\n\t\t\t</ui:repeat>\n\n\t\t</table>\n\t</p:panel>\n</ui:composition>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/common/loggedInHeader.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<h:panelGroup>\n\t\t<table width=\"100%\">\n\t\t\t<tbody>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align=\"left\"><img src=\"../../images/impetus_logo.jpg\"\n\t\t\t\t\t\theight=\"50\" width=\"150\" /></td>\n\t\t\t\t\t<td>\n\t\t\t\t\t<h2><h:outputText value=\"DataKeeper\" /></h2>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td align=\"right\">\n\t\t\t\t\t\t<h:form>\n\t\t\t\t\t\t<h:commandLink value=\"Home\" action=\"/xhtml/home/timeline.xhtml\" />\t\t\t\n\t\t\t\t\t\t<h:outputText value=\" | \" />\n\t\t\t\t\t\t<h:commandLink value=\"Settings\" action=\"/xhtml/settings/settings.xhtml\" />\t\t\t\n\t\t\t\t\t\t<h:outputText value=\" | \" />\t\t\t\n\t\t\t\t\t\t<h:commandLink value=\"Logoff\" action=\"#{loginBean.logOff}\" />\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t</h:form>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</tbody>\n\t\t</table>\n\t</h:panelGroup>\n</ui:composition>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/home/showSubordinatesInfo.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\ttemplate=\"timelineTemplate.xhtml\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<ui:define name=\"title\">\n        DataKeeper :: Employees Information\n    </ui:define>\n\n\t<ui:define name=\"content\">\n\t\t<p:panel header=\"Employess\">\n\t\t\t<table width=\"100%\">\n\t\t\t\t<tr>\n\t\t\t\t\t<!-- <table width=\"100%\"> -->\n\t\t\t\t\t<!-- <tr> -->\n\t\t\t\t\t<td style=\"align: center;\"><h:form>\n\t\t\t\t\t\t\t<p:dataTable id=\"dataTable\" var=\"subordinate\"\n\t\t\t\t\t\t\t\tvalue=\"#{subordinateSearchBean.subordinates}\">\n\n\t\t\t\t\t\t\t\t<p:column id=\"idColumn\" headerText=\"Employee Id\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{subordinate.employeeId}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"nameColumn\" headerText=\"Employee Name\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:commandLink id=\"employeeNameColumn\"\n\t\t\t\t\t\t\t\t\t\tvalue=\"#{subordinate.employeeName}\"\n\t\t\t\t\t\t\t\t\t\taction=\"#{subordinateSearchBean.searchSubordinates}\">\n\t\t\t\t\t\t\t\t\t\t<f:param name=\"managerId\" value=\"#{subordinate.employeeId}\" />\n\t\t\t\t\t\t\t\t\t</h:commandLink>\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"managerColumn\" headerText=\"Manager Name\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{subordinate.manager.employeeName}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"designationColumn\" headerText=\"Designation\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{subordinate.designation}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"projectColumn\" headerText=\"Current Project\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{subordinate.currentProject}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t</p:dataTable>\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t\t<!-- </tr> -->\n\t\t\t\t\t<!-- </table> -->\n\t\t\t\t</tr>\n\n\t\t\t</table>\n\n\t\t</p:panel>\n\t</ui:define>\n</ui:composition>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/home/showSubordinatesInfoTemplate.xhtml",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.prime.com.tr/ui\">\n<f:view contentType=\"text/html\">\n\t<h:head>\n\t\t<title><ui:insert name=\"title\">Default title</ui:insert></title>\n\t</h:head>\n\t<h:body>\n\t\t<table width=\"100%\">\n\t\t\t<tr>\n\t\t\t\t<td><ui:include src=\"../common/loggedInHeader.xhtml\" /></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align=\"center\">\n\t\t\t\t<table>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><p:growl id=\"growl\" sticky=\"false\" showDetail=\"false\" /></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<br />\n\t\t\t\t<table width=\"100%\" style=\"vertical-align: top;\">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td width=\"20%\" style=\"vertical-align: top;\"><ui:include\n\t\t\t\t\t\t\tsrc=\"../common/leftPane.xhtml\" /></td>\n\t\t\t\t\t\t<td width=\"80%\" style=\"vertical-align: top;\"><ui:insert\n\t\t\t\t\t\t\tname=\"content\">Default content</ui:insert></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>\n\t</h:body>\n</f:view>\n</html>\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/home/timeline.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\ttemplate=\"timelineTemplate.xhtml\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<ui:define name=\"title\">\n        DataKeeper :: Home\n    </ui:define>\n\n\t<ui:define name=\"content\">\n\t\t<p:panel header=\"Your Timeline\">\n\t\t\t<table width=\"100%\">\n\t\t\t\t<tr>\n\t\t\t\t\t<td><h:form enctype=\"multipart/form-data\">\n\t\t\t\t\t\t\t<p:fileUpload\n\t\t\t\t\t\t\t\tfileUploadListener=\"#{documentUploadBean.handleFileUpload}\"\n\t\t\t\t\t\t\t\tmode=\"advanced\" update=\"messages\" sizeLimit=\"10000000\"\n\t\t\t\t\t\t\t\tallowTypes=\"/(\\.|\\/)(pdf|xls|xlsx|doc|docx|txt|text|avi)$/\" />\n\t\t\t\t\t\t\t<p:growl id=\"messages\" showDetail=\"true\" />\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><h:form>\n\t\t\t\t\t\t\t<strong><h:outputText value=\"SearchEmployee:-  \" /> </strong>\n\t\t\t\t\t\t\t<h:inputText value=\"#{subordinateSearchBean.noOfYears}\" />\n\t\t\t\t\t\t\t<h:commandButton value=\"Search\"\n\t\t\t\t\t\t\t\taction=\"#{subordinateSearchBean.searchEmployeeByYearOfComplition}\" />\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t\t<td><h:form>\n\t\t\t\t\t\t\t<h:commandButton value=\"Subordinates\"\n\t\t\t\t\t\t\t\taction=\"#{subordinateSearchBean.searchSubordinates}\">\n\t\t\t\t\t\t\t\t<f:param name=\"managerId\"\n\t\t\t\t\t\t\t\t\tvalue=\"#{sessionScope.employee.employeeId}\" />\n\t\t\t\t\t\t\t</h:commandButton>\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><h:form>\n\t\t\t\t\t\t\t<strong><h:outputText value=\"SearchEmployee:-  \" /> </strong>\n\t\t\t\t\t\t\t<h:selectOneMenu value=\"#{subordinateSearchBean.searchBy}\">\n\t\t\t\t\t\t\t\t<f:selectItem itemValue=\"0\" itemLabel=\"EmployeeName\" />\n\t\t\t\t\t\t\t\t<f:selectItem itemValue=\"1\" itemLabel=\"EmployeeId\" />\n\t\t\t\t\t\t\t</h:selectOneMenu>\n\t\t\t\t\t\t\t<h:inputText value=\"#{subordinateSearchBean.searchText}\" />\n\t\t\t\t\t\t\t<h:commandButton value=\"Search\"\n\t\t\t\t\t\t\t\taction=\"#{subordinateSearchBean.searchEmployee}\" />\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><h:form>\n\t\t\t\t\t\t\t<strong><h:outputText value=\"Search Document:-  \" /> </strong>\n\t\t\t\t\t\t\t<h:selectOneMenu value=\"#{documentSearchBean.searchBy}\">\n\t\t\t\t\t\t\t\t<f:selectItem itemValue=\"0\" itemLabel=\"EmployeeName\" />\n\t\t\t\t\t\t\t\t<f:selectItem itemValue=\"1\" itemLabel=\"EmployeeId\" />\n\t\t\t\t\t\t\t</h:selectOneMenu>\n\t\t\t\t\t\t\t<h:inputText value=\"#{documentSearchBean.searchText}\" />\n\t\t\t\t\t\t\t<h:commandButton value=\"Search\"\n\t\t\t\t\t\t\t\taction=\"#{documentSearchBean.search}\" />\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<!-- <table width=\"100%\"> -->\n\t\t\t\t\t<!-- <tr> -->\n\t\t\t\t\t<td style=\"align: center;\"><h:form>\n\t\t\t\t\t\t\t<p:dataTable id=\"dataTable\" var=\"documentInfo\"\n\t\t\t\t\t\t\t\tvalue=\"#{documentSearchBean.documents}\">\n\n\t\t\t\t\t\t\t\t<p:column id=\"nameColumn\" headerText=\"Document Name\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{documentInfo.documentName}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"ownerColumn\" headerText=\"Uploaded By\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{documentInfo.ownerName}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"dateColumn\" headerText=\"Uploaded Date\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{documentInfo.uplodedDate}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"sizeColumn\" headerText=\"Size\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{documentInfo.size}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"downloadColumn\" headerText=\"Download\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<p:commandButton id=\"downloadLink\" value=\"Download\"\n\t\t\t\t\t\t\t\t\t\tajax=\"false\" onclick=\"PrimeFaces.monitorDownload(start, stop)\"\n\t\t\t\t\t\t\t\t\t\ticon=\"ui-icon-arrowthichk-s\">\n\t\t\t\t\t\t\t\t\t\t<p:fileDownload value=\"#{documentInfo.file}\" />\n\t\t\t\t\t\t\t\t\t</p:commandButton>\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t</p:dataTable>\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t\t<!-- </tr> -->\n\t\t\t\t\t<!-- </table> -->\n\t\t\t\t</tr>\n\n\t\t\t</table>\n\n\t\t</p:panel>\n\t</ui:define>\n</ui:composition>\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/home/timelineTemplate.xhtml",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.prime.com.tr/ui\">\n<f:view contentType=\"text/html\">\n\t<h:head>\n\t\t<title><ui:insert name=\"title\">Default title</ui:insert></title>\n\t</h:head>\n\t<h:body>\n\t\t<table width=\"100%\">\n\t\t\t<tr>\n\t\t\t\t<td><ui:include src=\"../common/loggedInHeader.xhtml\" /></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align=\"center\">\n\t\t\t\t<table>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><p:growl id=\"growl\" sticky=\"false\" showDetail=\"false\" /></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<br />\n\t\t\t\t<table width=\"100%\" style=\"vertical-align: top;\">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td width=\"20%\" style=\"vertical-align: top;\"><ui:include\n\t\t\t\t\t\t\tsrc=\"../common/leftPane.xhtml\" /></td>\n\t\t\t\t\t\t<td width=\"80%\" style=\"vertical-align: top;\"><ui:insert\n\t\t\t\t\t\t\tname=\"content\">Default content</ui:insert></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>\n\t</h:body>\n</f:view>\n</html>\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/login/login.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\ttemplate=\"loginTemplate.xhtml\" xmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<ui:define name=\"title\">\n        Kwitter :: Login\n    </ui:define>\n\n\t<ui:define name=\"content\">\n\n\t\t<table>\n\t\t\t<tr>\n\t\t\t\t<td><p:growl id=\"growl\" sticky=\"false\" showDetail=\"false\"/> </td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<br />\n\t\t <p:panel header=\"Login to DataKeeper\">\n\t\t\t<h:form>\n\t\t\t\t<table>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><h:outputText value=\"User Name:\" /></td>\n\t\t\t\t\t\t<td><p:inputText size=\"20\" value=\"#{loginBean.employee.employeeName}\" /></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><h:outputText value=\"Password:\" /></td>\n\t\t\t\t\t\t<td><p:password size=\"20\"\n\t\t\t\t\t\t\tvalue=\"#{loginBean.employee.password}\" /></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t\n\t\t\t\t\t<tr>\t\t\t\t\t\t\n\t\t\t\t\t\t<td colspan=\"2\" align=\"right\"><h:commandButton value=\"Submit\"\n\t\t\t\t\t\t\taction=\"#{loginBean.authenticate}\" /></td>\n\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\t\t\t\t\t\t\n\t\t\t\t\t\t<td colspan=\"2\" align=\"right\">Not a member? <h:commandLink value=\"SignUp Now!\"\n\t\t\t\t\t\t\taction=\"/xhtml/register/signUp.xhtml\" /></td>\n\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</h:form>\n\t\t</p:panel>\n\t</ui:define>\n</ui:composition>\n\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/login/loginTemplate.xhtml",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.prime.com.tr/ui\">\n<f:view contentType=\"text/html\">\n<h:head>\n\t<title><ui:insert name=\"title\">Default title</ui:insert></title>\n</h:head>\n<h:body>\n\t<table width=\"100%\">\n\t\t<tr>\n\t\t\t<td><ui:include src=\"../common/header.xhtml\" /></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td align=\"center\"><ui:insert name=\"content\">Default content</ui:insert></td>\n\t\t</tr>\n\t</table>\n</h:body>\n</f:view>\n</html>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/register/signUp.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\ttemplate=\"signUpTemplate.xhtml\" xmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<ui:define name=\"title\">\n        Kwitter :: SignUp\n    </ui:define>\n\n\t<ui:define name=\"content\">\n\n\t\t<table>\n\t\t\t<tr>\n\t\t\t\t<td><p:growl id=\"growl\" sticky=\"false\" showDetail=\"false\" /></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<br />\n\t\t<p:panel header=\"SignUp to DataKeeper\">\n\t\t\t<h:form>\n\n\t\t\t\t<p:growl id=\"growl\" sticky=\"true\" showDetail=\"true\" />\n\n\t\t\t\t<p:panel header=\"Employee Details\">\n\n\t\t\t\t\t<h:messages errorClass=\"error\" />\n\n\t\t\t\t\t<h:panelGrid columns=\"2\" columnClasses=\"label, value\"\n\t\t\t\t\t\tstyleClass=\"grid\">\n\n\t\t\t\t\t\t<h:outputText value=\"Employee Name: *\" />\n\t\t\t\t\t\t<p:inputText required=\"true\" label=\"Employee Name\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.employee.employeeName}\" />\n\n\t\t\t\t\t\t<h:outputText value=\"Password: *\" />\n\t\t\t\t\t\t<p:password size=\"20\" required=\"true\" label=\"Password\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.employee.password}\" />\n\n\t\t\t\t\t\t<h:outputText value=\"Experience: *\" />\n\t\t\t\t\t\t<p:inputText required=\"true\" label=\"Experience\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.employee.experience}\" />\n\n\t\t\t\t\t\t<h:outputText value=\"Joining Date: *\" />\n\t\t\t\t\t\t<p:calendar value=\"#{registerBean.employee.joiningDate}\"\n\t\t\t\t\t\t\tid=\"popupCal\" />\n\n\t\t\t\t\t\t<h:outputText value=\"Company Name\" />\n\t\t\t\t\t\t<p:inputText required=\"true\" label=\"Company Name\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.employee.company}\" />\n\n\t\t\t\t\t\t<h:outputText value=\"Designation:*\" />\n\t\t\t\t\t\t<p:inputText required=\"true\" label=\"Designation\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.employee.designation}\" />\n\n\t\t\t\t\t\t<h:outputText value=\"ManagerId: *\" />\n\t\t\t\t\t\t<p:inputText required=\"true\" label=\"ManagerId\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.managerId}\" />\n\n\t\t\t\t\t\t<h:outputText value=\"Current Project *\" />\n\t\t\t\t\t\t<p:inputText required=\"true\" label=\"Current Project\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.employee.currentProject}\" />\n\t\t\t\t\t</h:panelGrid>\n\n\t\t\t\t</p:panel>\n\n\t\t\t\t<h:panelGrid>\n\t\t\t\t\t<p:commandButton value=\"Submit\" update=\"growl\"\n\t\t\t\t\t\taction=\"#{registerBean.save}\" />\n\t\t\t\t</h:panelGrid>\n\n\t\t\t</h:form>\n\n\t\t</p:panel>\n\t</ui:define>\n</ui:composition>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/register/signUpTemplate.xhtml",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.prime.com.tr/ui\">\n<f:view contentType=\"text/html\">\n<h:head>\n\t<title><ui:insert name=\"title\">Default title</ui:insert></title>\n</h:head>\n<h:body>\n\t<table width=\"100%\">\n\t\t<tr>\n\t\t\t<td><ui:include src=\"../common/header.xhtml\" /></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td align=\"center\"><ui:insert name=\"content\">Default content</ui:insert></td>\n\t\t</tr>\n\t</table>\n</h:body>\n</f:view>\n</html>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/settings/settings.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\ttemplate=\"settingsTemplate.xhtml\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<ui:define name=\"title\">\n        Kwitter :: Settings\n    </ui:define>\n\n\t<ui:define name=\"content\">\t\t\n\t\t<p:panel header=\"Your Settings\">\n\t\t\t<table width=\"100%\">\n\t\t\t\t<tr><td><h:outputText value=\"Click below to permanently delete your account\" /></td></tr>\n\t\t\t\t<tr><td><h:outputText value=\"Warning: This action can't be reverted back!\" style=\"color:red;\"/></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<h:form>\t\t\t\t\t\t\n\t\t\t\t\t\t<td><h:commandButton value=\"Delete My Account\"\n\t\t\t\t\t\t\taction=\"#{loginBean.deleteAccount}\" /></td>\n\t\t\t\t\t</h:form>\n\t\t\t\t</tr>\t\t\t\t\n\n\t\t\t</table>\n\n\t\t</p:panel>\n\t</ui:define>\n</ui:composition>\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/settings/settingsTemplate.xhtml",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.prime.com.tr/ui\">\n<f:view contentType=\"text/html\">\n\t<h:head>\n\t\t<title><ui:insert name=\"title\">Default title</ui:insert></title>\n\t</h:head>\n\t<h:body>\n\t\t<table width=\"100%\">\n\t\t\t<tr>\n\t\t\t\t<td><ui:include src=\"../common/loggedInHeader.xhtml\" /></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align=\"center\">\n\t\t\t\t<table>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><p:growl id=\"growl\" sticky=\"false\" showDetail=\"false\" /></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<br />\n\t\t\t\t<table width=\"100%\" style=\"vertical-align: top;\">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td width=\"20%\" style=\"vertical-align: top;\"><ui:include\n\t\t\t\t\t\t\tsrc=\"../common/leftPane.xhtml\" /></td>\n\t\t\t\t\t\t<td width=\"80%\" style=\"vertical-align: top;\"><ui:insert\n\t\t\t\t\t\t\tname=\"content\">Default content</ui:insert></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>\n\t</h:body>\n</f:view>\n</html>\n"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/upload/uploadDocument.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\ttemplate=\"uploadDocumentTemplate.xhtml\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<ui:define name=\"title\">\n        DataKeeper :: Upload\n    </ui:define>\n\t<ui:define name=\"content\">\n\t\t<h:form enctype=\"multipart/form-data\">\n\n\t\t\t<p:messages showDetail=\"true\" />\n\n\t\t\t<p:fileUpload value=\"#{documentUploadBean.file}\" mode=\"simple\"\n\t\t\t\tallowTypes=\"/(\\.|\\/)(pdf|xls?x|doc?x|avi)$/\" />\n\n\t\t\t<p:commandButton value=\"Submit\" ajax=\"false\"\n\t\t\t\tactionListener=\"#{documentUploadBean.handleFileUpload}\" />\n\n\t\t</h:form>\n\t\t<h:form enctype=\"multipart/form-data\">\n\t\t\t<p:fileUpload\n\t\t\t\tfileUploadListener=\"#{documentUploadBean.handleFileUpload}\"\n\t\t\t\tmode=\"advanced\" update=\"messages\" sizeLimit=\"100000000\"\n\t\t\t\tallowTypes=\"/(\\.|\\/)(pdf|xls?x|doc?x|avi)$/\" />\n\t\t\t<p:growl id=\"messages\" showDetail=\"true\" />\n\t\t</h:form>\n\n\t</ui:define>\n</ui:composition>"
  },
  {
    "path": "examples/container/jboss/data-keeper/src/main/webapp/xhtml/upload/uploadDocumentTemplate.xhtml",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.prime.com.tr/ui\">\n<f:view contentType=\"text/html\">\n<h:head>\n\t<title><ui:insert name=\"title\">Default title</ui:insert></title>\n</h:head>\n<h:body>\n\t<table width=\"100%\">\n\t\t<tr>\n\t\t\t<td><ui:include src=\"../common/header.xhtml\" /></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td align=\"center\"><ui:insert name=\"content\">Default content</ui:insert></td>\n\t\t</tr>\n\t</table>\n</h:body>\n</f:view>\n</html>"
  },
  {
    "path": "examples/container/jboss/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t<groupId>com.impetus.kundera.examples</groupId>\n\t<artifactId>container</artifactId>\n\t<version>3.3-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.examples</groupId>\n\t<artifactId>jboss</artifactId>\n\t<version>3.3-SNAPSHOT</version>\n\t<packaging>pom</packaging>\n\n\t<name>jboss-app</name>\n\t<url>https://github.com/impetus-opensource/Kundera</url>\n\n\t<!-- Build profiles -->\n\t<profiles>\n\n\t\t<profile>\n\t\t\t<id>all</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>true</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>data-keeper</module>\n\t\t\t</modules>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "examples/container/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t<groupId>com.impetus.kundera</groupId>\n\t<artifactId>examples</artifactId>\n\t<version>3.3-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.examples</groupId>\n\t<artifactId>container</artifactId>\n\t<version>3.3-SNAPSHOT</version>\n\t<packaging>pom</packaging>\n\n\t<name>container</name>\n\t<url>https://github.com/impetus-opensource/Kundera</url>\n\n\t<licenses>\n\t\t<license>\n\t\t\t<name>The Apache Software License, Version 2.0</name>\n\t\t\t<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>\n\t\t\t<distribution>repo</distribution>\n\t\t</license>\n\t</licenses>\n\n\t<scm>\n\t\t<connection>scm:git:git@github.com:impetus-opensource/Kundera.git</connection>\n\t\t<developerConnection>scm:git:git@github.com:impetus-opensource/Kundera.git</developerConnection>\n\t\t<url>git@github.com:impetus-opensource/Kundera.git</url>\n\t</scm>\n\n\t<developers>\n\t\t<developer>\n\t\t\t<id>vivek.mishra</id>\n\t\t\t<name>Vivek Mishra</name>\n\t\t\t<email>vivek.mishra@yahoo.com</email>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<id>amresh.singh</id>\n\t\t\t<name>Amresh Kumar Singh</name>\n\t\t\t<email>amresh1002@gmail.com</email>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<id>Kuldeep.mishra</id>\n\t\t\t<name>Kuldeep Kumar Mishra</name>\n\t\t\t<email>kuld.cs.mishra@gmail.com</email>\n\t\t</developer>\n\t</developers>\n\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t\t<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n\t\t<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>\n\t\t<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>\n\t\t<sonar.language>java</sonar.language>\n\t</properties>\n\n\n\t<repositories>\n\t\t<repository>\n\t\t\t<id>clover</id>\n\t\t\t<name>Clover maven repo</name>\n\t\t\t<url>http://mirrors.ibiblio.org/pub/mirrors/maven</url>\n\t\t\t<releases>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</releases>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>kundera-missing</id>\n\t\t\t<name>Kundera Public Missing Resources Repository</name>\n\t\t\t<url>http://kundera.googlecode.com/svn/maven2/maven-missing-resources</url>\n\t\t\t<releases>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</releases>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>riptano</id>\n\t\t\t<name>riptano</name>\n\t\t\t<url>http://mvn.riptano.com/content/repositories/public</url>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>maven.scale7.org</id>\n\t\t\t<name>Scale7 Maven Repo</name>\n\t\t\t<url>https://github.com/s7/mvnrepo/raw/master</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t</repositories>\n\t<!-- Build profiles -->\n\t<profiles>\n\n\t\t<profile>\n\t\t\t<id>all</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>true</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jboss</module>\n\t\t\t\t<module>tomcat-glassfish</module>\n\t\t\t</modules>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera.examples</groupId>\n\t\t<artifactId>tomcat-glassfish</artifactId>\n\t\t<version>3.3-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.examples</groupId>\n\t<artifactId>data-keeper</artifactId>\n\t<packaging>war</packaging>\n\t<version>1.0-SNAPSHOT</version>\n\t<name>data-keeper</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t\t<spring.version>3.0.5.RELEASE</spring.version>\n                <kundera.version>3.3-SNAPSHOT</kundera.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-mongo</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>javax.servlet</groupId>\n\t\t\t<artifactId>javax.servlet-api</artifactId>\n\t\t\t<version>3.0.1</version>\n\t\t\t<scope>provided</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.sun.faces</groupId>\n\t\t\t<artifactId>jsf-api</artifactId>\n\t\t\t<version>2.1.10</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.sun.faces</groupId>\n\t\t\t<artifactId>jsf-impl</artifactId>\n\t\t\t<version>2.1.10</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>jstl</groupId>\n\t\t\t<artifactId>jstl</artifactId>\n\t\t\t<version>1.2</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.primefaces</groupId>\n\t\t\t<artifactId>primefaces</artifactId>\n\t\t\t<version>3.3.1</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>commons-fileupload</groupId>\n\t\t\t<artifactId>commons-fileupload</artifactId>\n\t\t\t<version>1.3</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>commons-io</groupId>\n\t\t\t<artifactId>commons-io</artifactId>\n\t\t\t<version>2.4</version>\n\t\t</dependency>\n\n\n\t\t<!-- Spring dependencies -->\n\n\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-core</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-web</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-beans</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-context</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-aop</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-context-support</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-tx</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-orm</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-jdbc</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-test</artifactId>\n\t\t\t<version>${spring.version}</version>\n\t\t</dependency>\n\t</dependencies>\n\t<build>\n\t\t<finalName>data-keeper</finalName>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t\t<addClasspath>true</addClasspath>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-ear-plugin</artifactId> \n\t\t\t\t<version>2.8</version> <configuration> <jboss> <version>4</version> <unauthenticated-principal>guest</unauthenticated-principal> \n\t\t\t\t<loader-repository>com.impetus.kundera.data-keeper:loader=data-keeper-application-1.0.ear</loader-repository> \n\t\t\t\t</jboss> </configuration> </plugin> -->\n\t\t</plugins>\n\t</build>\n</project>\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/DocumentDownloadBean.java",
    "content": "package com.impetus.kundera.datakeeper.beans;\n\nimport java.io.IOException;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\nimport javax.faces.context.FacesContext;\nimport javax.servlet.ServletOutputStream;\nimport javax.servlet.http.HttpServletResponse;\n\nimport com.impetus.kundera.datakeeper.entities.DocumentInfo;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\nimport com.impetus.kundera.datakeeper.utils.FacesUtils;\n\n@ManagedBean(name = \"documentDownloadBean\")\n@RequestScoped\npublic class DocumentDownloadBean\n{\n    private int documentId;\n\n    public int getDocumentId()\n    {\n        return documentId;\n    }\n\n    public void setDocumentId(int documentId)\n    {\n        this.documentId = documentId;\n    }\n\n    /**\n     * Download file used for downloading photo.\n     * \n     * @param photoPath\n     *            the photo path\n     */\n    public void download()\n    { \n        \n        \n        \n        DataKeeperService service = DataKeeperUtils.getService();\n\n        setDocumentId(Integer.parseInt(FacesUtils.getRequest().getParameter(\"documentId\")));\n        DocumentInfo document = service.findDocumentByDocumentId(getDocumentId());\n\n        final HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance()\n                .getExternalContext().getResponse();\n\n        ServletOutputStream out = null;\n        try\n        {\n            out = response.getOutputStream();\n            out.write(document.getData(), 0, 4096);\n        }\n        catch (IOException e)\n        {\n\n        }\n        finally\n        {\n            if (out != null)\n            {\n                try\n                {\n                    out.flush();\n                    out.close();\n                }\n                catch (IOException e)\n                {\n\n                }\n            }\n        }\n        FacesContext.getCurrentInstance().responseComplete();\n    }\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/DocumentSearchBean.java",
    "content": "package com.impetus.kundera.datakeeper.beans;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\n\nimport com.impetus.kundera.datakeeper.entities.DocumentInfo;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\n\n@ManagedBean(name = \"documentSearchBean\")\n@RequestScoped\npublic class DocumentSearchBean\n{\n    private String searchText;\n\n    private int searchBy;\n\n    private List<DocumentInfo> documents;\n\n    public String getSearchText()\n    {\n        return searchText;\n    }\n\n    public void setSearchText(String searchText)\n    {\n        this.searchText = searchText;\n    }\n\n    public int getSearchBy()\n    {\n        return searchBy;\n    }\n\n    public void setSearchBy(int searchBy)\n    {\n        this.searchBy = searchBy;\n    }\n\n    public List<DocumentInfo> getDocuments()\n    {\n        return documents;\n    }\n\n    public void setDocuments(List<DocumentInfo> documents)\n    {\n        this.documents = documents;\n    }\n\n    public List<DocumentInfo> search()\n    {\n        documents = new ArrayList<DocumentInfo>();\n        DataKeeperService service = DataKeeperUtils.getService();\n\n        switch (SearchType.getSearchType(searchBy))\n        {\n        case ID:\n            documents = service.findDocumentByEmployeeId(getSearchText());\n            break;\n        case NAME:\n            documents = service.findDocumentByEmployeeName(getSearchText());\n            break;\n        }\n        return documents;\n    }\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/DocumentUploadBean.java",
    "content": "package com.impetus.kundera.datakeeper.beans;\n\nimport java.util.Date;\n\nimport javax.faces.application.FacesMessage;\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\nimport javax.faces.context.FacesContext;\nimport javax.servlet.http.HttpSession;\n\nimport org.primefaces.event.FileUploadEvent;\nimport org.primefaces.model.UploadedFile;\n\nimport com.impetus.kundera.datakeeper.entities.DocumentInfo;\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperConstants;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\nimport com.impetus.kundera.datakeeper.utils.FacesUtils;\n\n@ManagedBean(name = \"documentUploadBean\")\n@RequestScoped\npublic class DocumentUploadBean\n{\n    public DocumentUploadBean()\n    {\n    }\n\n    public String handleFileUpload(FileUploadEvent event)\n    {\n        HttpSession session = FacesUtils.getSession();\n        Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);\n\n        DataKeeperService service = DataKeeperUtils.getService();\n\n        UploadedFile file = event.getFile();\n\n        if (file != null)\n        {\n            DocumentInfo dataInfo = new DocumentInfo();\n            dataInfo.setData(file.getContents());\n            dataInfo.setDocumentName(file.getFileName());\n            dataInfo.setSize(file.getSize());\n            dataInfo.setOwnerName(employee.getEmployeeName());\n            dataInfo.setOwnerId(employee.getEmployeeId());\n            dataInfo.setUplodedDate(new Date());\n\n            service.insertData(dataInfo);\n\n            FacesMessage msg = new FacesMessage(\"Succesful\", file.getFileName() + \" is uploaded.\");\n            FacesContext.getCurrentInstance().addMessage(null, msg);\n\n            return \"successfully uploaded\";\n        }\n        return \"uploading fail\";\n    }\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/EmployeeSearchBean.java",
    "content": "package com.impetus.kundera.datakeeper.beans;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\nimport javax.servlet.http.HttpSession;\n\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperConstants;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\nimport com.impetus.kundera.datakeeper.utils.FacesUtils;\n\n@ManagedBean(name = \"subordinateSearchBean\")\n@RequestScoped\npublic class EmployeeSearchBean\n{\n    private List<Employee> subordinates = new ArrayList<Employee>();\n\n    private int managerId;\n\n    private int noOfYears;\n\n    private String searchText;\n\n    private int searchBy;\n\n    public String getSearchText()\n    {\n        return searchText;\n    }\n\n    public void setSearchText(String searchText)\n    {\n        this.searchText = searchText;\n    }\n\n    public int getSearchBy()\n    {\n        return searchBy;\n    }\n\n    public void setSearchBy(int searchBy)\n    {\n        this.searchBy = searchBy;\n    }\n\n    /**\n     * @return the managerName\n     */\n    public int getManagerId()\n    {\n        return managerId;\n    }\n\n    /**\n     * @param managerName\n     *            the managerName to set\n     */\n    public void setManagerId(int managerId)\n    {\n        this.managerId = managerId;\n    }\n\n    public int getNoOfYears()\n    {\n        return noOfYears;\n    }\n\n    public void setNoOfYears(int noOfYears)\n    {\n        this.noOfYears = noOfYears;\n    }\n\n    public List<Employee> getSubordinates()\n    {\n        return subordinates;\n    }\n\n    public void setSubordinates(List<Employee> subordinates)\n    {\n        this.subordinates = subordinates;\n    }\n\n    public String searchSubordinates()\n    {\n        DataKeeperService service = DataKeeperUtils.getService();\n        setManagerId(Integer.parseInt(FacesUtils.getRequest().getParameter(\"managerId\")));\n        List<Employee> subordinates = service.findSubOrdinates(getManagerId());\n        if (subordinates != null)\n        {\n            this.subordinates = subordinates;\n        }\n        return \"foundEmployess\";\n    }\n\n    public String searchEmployee()\n    {\n        DataKeeperService service = DataKeeperUtils.getService();\n        Employee employee = null;\n        switch (SearchType.getSearchType(searchBy))\n        {\n        case ID:\n            employee = service.findEmployee(Integer.parseInt(getSearchText()));\n            break;\n        case NAME:\n            employee = service.findEmployeeByName(getSearchText());\n            break;\n        }\n        if (employee != null)\n        {\n            List<Employee> employees = new ArrayList<Employee>();\n            employees.add(employee);\n            this.subordinates = employees;\n        }\n        return \"foundEmployess\";\n    }\n\n    public String searchEmployeeByYearOfComplition()\n    {\n        DataKeeperService service = DataKeeperUtils.getService();\n        HttpSession session = FacesUtils.getSession();\n        Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);\n        List<Employee> employees = service.findEmployeeByDateOfJoining(getNoOfYears(), employee.getCompany());\n        if (employees != null)\n        {\n            this.subordinates = employees;\n        }\n        return \"foundEmployess\";\n    }\n\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/IncrementCounterBean.java",
    "content": "package com.impetus.kundera.datakeeper.beans;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\nimport javax.servlet.http.HttpSession;\n\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.entities.SubordinatesCounter;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperConstants;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\nimport com.impetus.kundera.datakeeper.utils.FacesUtils;\n\n@ManagedBean(name = \"incrementCounterBean\")\n@RequestScoped\npublic class IncrementCounterBean\n{\n    private SubordinatesCounter counter = new SubordinatesCounter();\n\n    public IncrementCounterBean()\n    {\n\n    }\n\n    public SubordinatesCounter getCounter()\n    {\n        return counter;\n    }\n\n    public void setCounter(SubordinatesCounter counter)\n    {\n        this.counter = counter;\n    }\n\n    public String incrementCounter()\n    {\n        DataKeeperService service = DataKeeperUtils.getService();\n\n        HttpSession session = FacesUtils.getSession();\n        Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);\n        counter.setEmployeeId(employee.getEmployeeId());\n        \n        service.incrementCounter(counter);\n        \n        return \"success\";\n    }\n\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/LoginBean.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.datakeeper.beans;\n\nimport javax.faces.application.FacesMessage;\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\nimport javax.faces.context.FacesContext;\nimport javax.servlet.http.HttpSession;\n\nimport org.apache.commons.lang.StringUtils;\n\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperConstants;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\nimport com.impetus.kundera.datakeeper.utils.FacesUtils;\n\n/**\n * <Prove description of functionality provided by this Type>\n * \n * @author amresh.singh\n */\n\n@ManagedBean(name = \"loginBean\")\n@RequestScoped\npublic class LoginBean\n{\n    private Employee employee = new Employee();\n\n    public LoginBean()\n    {\n\n    }\n\n    public Employee getEmployee()\n    {\n        return employee;\n    }\n\n    public void setEmployee(Employee employee)\n    {\n        this.employee = employee;\n    }\n\n    public String logOff()\n    {\n        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);\n        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(\"You have successfully Logged off\"));\n        session.invalidate();\n        return DataKeeperConstants.OUTCOME_LOGOFF_SUCCESSFUL;\n    }\n\n    public String deleteAccount()\n    {\n        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);\n        DataKeeperService service = DataKeeperUtils.getService();\n        Employee employee = (Employee) session.getAttribute(DataKeeperConstants.EMPLOYEE);\n\n        service.removeEmployee(employee);\n\n        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(\"Account successfully deleted\"));\n        session.invalidate();\n        return \"Account successfully deleted\";\n    }\n\n    public String authenticate()\n    {\n        String outcome = null;\n\n        // Validates Parameters\n        if (StringUtils.isBlank(employee.getEmployeeName()))\n        {\n            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(\"Please enter your user name\"));\n            outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;\n        }\n\n        if (StringUtils.isBlank(employee.getPassword()))\n        {\n            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(\"Please enter password\"));\n            outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;\n        }\n\n        if (StringUtils.isNotBlank(outcome))\n        {\n            return outcome;\n        }\n        else\n        {\n            DataKeeperService service = DataKeeperUtils.getService();\n            Employee foundEmployee = service.findEmployeeByName(employee.getEmployeeName());\n            boolean success = service.authenticateEmployee(foundEmployee, employee.getPassword());\n\n            if (!success)\n            {\n                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(\"Incorrect User Name/Password\"));\n                outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;\n            }\n            else\n            {\n                outcome = DataKeeperConstants.OUTCOME_LOGIN_SUCCESSFUL;\n                HttpSession session = FacesUtils.getSession();\n                session.setAttribute(DataKeeperConstants.EMPLOYEE, foundEmployee);\n            }\n            return outcome;\n        }\n    }\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/RegisterBean.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.datakeeper.beans;\n\nimport javax.faces.application.FacesMessage;\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\nimport javax.faces.context.FacesContext;\n\nimport org.primefaces.event.FlowEvent;\n\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\nimport com.impetus.kundera.datakeeper.utils.DataKeeperUtils;\n\n/**\n * <Prove description of functionality provided by this Type>\n * \n * @author Kuldeep.Mishra\n */\n\n@ManagedBean(name = \"registerBean\")\n@RequestScoped\npublic class RegisterBean\n{\n    private Employee employee = new Employee();\n\n    private int managerId;\n\n    public RegisterBean()\n    {\n    }\n\n    public Employee getEmployee()\n    {\n        return employee;\n    }\n\n    public void setEmployee(Employee employee)\n    {\n        this.employee = employee;\n    }\n\n    public int getManagerId()\n    {\n        return managerId;\n    }\n\n    public void setManagerId(int managerId)\n    {\n        this.managerId = managerId;\n    }\n\n    public String onFlowProcess(FlowEvent event)\n    {\n        return event.getNewStep();\n    }\n\n    public String save()\n    {\n        DataKeeperService service = DataKeeperUtils.getService();\n\n        Employee manager = service.findEmployee(managerId);\n\n        employee.setManager(manager);\n        employee.setTimestamp(employee.getJoiningDate().getTime());\n\n        service.insertEmployee(employee);\n\n        FacesMessage msg = new FacesMessage(\"SignUp Successful! Welcome, \" + employee.getEmployeeName());\n\n        FacesContext.getCurrentInstance().addMessage(null, msg);\n\n        return \"signUpSuccessful\";\n    }\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/beans/SearchType.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.datakeeper.beans;\n\n\n/**\n * @author Kuldeep.Mishra\n * \n */\nenum SearchType\n{\n    ID, NAME;\n\n    static SearchType getSearchType(int searchBy)\n    {\n        if (searchBy == 1)\n        {\n            return ID;\n        }\n        else if (searchBy == 0)\n        {\n            return NAME;\n        }\n        return null;\n    }\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/dao/DataKeeperDao.java",
    "content": "package com.impetus.kundera.datakeeper.dao;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic interface DataKeeperDao\n{\n    EntityManager getEntityManager();\n\n    void closeEntityManager();\n\n    void clearEntityManager();\n\n    void shutDown();\n\n    void insert(Object entity);\n\n    void merge(Object entity);\n\n    void remove(Object entity);\n\n    <T> T findById(Class<T> entityClazz, Object id);\n\n    List<?> findByQuery(String Query);\n\n    List<?> findByQuery(String queryString, String paramater, Object parameterValue);\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/dao/DataKeeperDaoImpl.java",
    "content": "package com.impetus.kundera.datakeeper.dao;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.PersistenceContext;\nimport javax.persistence.PersistenceContextType;\nimport javax.persistence.Query;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.transaction.annotation.Propagation;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport com.impetus.kundera.datakeeper.service.DataKeeperServiceImpl;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\n// @Transactional(propagation = Propagation.REQUIRED)\npublic class DataKeeperDaoImpl implements DataKeeperDao\n{\n    /**\n     * logger used for logging statement.\n     */\n    private static final Logger log = LoggerFactory.getLogger(DataKeeperServiceImpl.class);\n\n    @PersistenceContext(unitName = \"cassandra-pu,mongo-pu\", type = PersistenceContextType.EXTENDED)\n    private EntityManager em;\n\n    public DataKeeperDaoImpl()\n    {\n    }\n\n    @Override\n    public void insert(Object entity)\n    {\n        em.persist(entity);\n        em.clear();\n    }\n\n    @Override\n    public void merge(Object entity)\n    {\n        em.merge(entity);\n        em.clear();\n    }\n\n    @Override\n    public void remove(Object entity)\n    {\n        em.remove(entity);\n        em.clear();\n    }\n\n    @Override\n    public <T> T findById(Class<T> entityClazz, Object id)\n    {\n        T results = em.find(entityClazz, id);\n        return results;\n    }\n\n    @Override\n    public List<?> findByQuery(String queryString)\n    {\n        log.info(queryString);\n        Query query = em.createQuery(queryString);\n        List<?> resultList = query.getResultList();\n        return resultList;\n    }\n\n    @Override\n    public List<?> findByQuery(String queryString, String paramater, Object parameterValue)\n    {\n        Query query = em.createQuery(queryString);\n        query.setParameter(paramater, parameterValue);\n        log.info(queryString);\n        List<?> resultList = query.getResultList();\n        return resultList;\n    }\n\n    @Override\n    public EntityManager getEntityManager()\n    {\n        return em;\n    }\n\n    @Override\n    public void closeEntityManager()\n    {\n        if (em != null)\n        {\n            em.close();\n        }\n    }\n\n    @Override\n    public void clearEntityManager()\n    {\n        if (em != null)\n        {\n            em.clear();\n        }\n    }\n\n    @Override\n    public void shutDown()\n    {\n        if (em != null)\n        {\n            em.close();\n        }\n    }\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/entities/DocumentInfo.java",
    "content": "package com.impetus.kundera.datakeeper.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport org.primefaces.model.StreamedContent;\n\nimport com.impetus.kundera.datakeeper.utils.DataFormat;\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\n@Entity\n@Table(name = \"DOCUMENT\", schema = \"datakeeper@mongo-pu\")\n@IndexCollection(columns = { @Index(name = \"ownerName\"), @Index(name = \"ownerId\"), @Index(name = \"documentName\") })\npublic class DocumentInfo\n{\n    @Id\n    @Column(name = \"DOCUMENT_ID\")\n    @GeneratedValue()\n    private String dataId;\n\n    @Column(name = \"EMPLOYEE_NAME\")\n    private String ownerName;\n\n    @Column(name = \"EMPLOYEE_ID\")\n    private int ownerId;\n\n    @Column(name = \"UPLOADED_DATE\")\n    private Date uplodedDate;\n\n    @Column(name = \"DOCUMENT_FORMAT\")\n    private DataFormat dataFormat;\n\n    @Column(name = \"DOCUMENT_NAME\")\n    private String documentName;\n\n    @Column(name = \"DATA\")\n    private byte[] data;\n\n    private StreamedContent file;\n\n    @Column(name = \"SIZE\")\n    private long size;\n\n    /**\n     * @return the dataId\n     */\n    public String getDataId()\n    {\n        return dataId;\n    }\n\n    /**\n     * @param dataId\n     *            the dataId to set\n     */\n    public void setDataId(String dataId)\n    {\n        this.dataId = dataId;\n    }\n\n    /**\n     * @return the ownerName\n     */\n    public String getOwnerName()\n    {\n        return ownerName;\n    }\n\n    /**\n     * @param ownerName\n     *            the ownerName to set\n     */\n    public void setOwnerName(String ownerName)\n    {\n        this.ownerName = ownerName;\n    }\n\n    /**\n     * @return the ownerId\n     */\n    public int getOwnerId()\n    {\n        return ownerId;\n    }\n\n    /**\n     * @param ownerId\n     *            the ownerId to set\n     */\n    public void setOwnerId(int ownerId)\n    {\n        this.ownerId = ownerId;\n    }\n\n    /**\n     * @return the uplodedDate\n     */\n    public Date getUplodedDate()\n    {\n        return uplodedDate;\n    }\n\n    /**\n     * @param uplodedDate\n     *            the uplodedDate to set\n     */\n    public void setUplodedDate(Date uplodedDate)\n    {\n        this.uplodedDate = uplodedDate;\n    }\n\n    /**\n     * @return the dataFormat\n     */\n    public DataFormat getDataFormat()\n    {\n        return dataFormat;\n    }\n\n    /**\n     * @param dataFormat\n     *            the dataFormat to set\n     */\n    public void setDataFormat(DataFormat dataFormat)\n    {\n        this.dataFormat = dataFormat;\n    }\n\n    public byte[] getData()\n    {\n        return data;\n    }\n\n    public void setData(byte[] data)\n    {\n        this.data = data;\n    }\n\n    public String getDocumentName()\n    {\n        return documentName;\n    }\n\n    public void setDocumentName(String documentName)\n    {\n        this.documentName = documentName;\n    }\n\n    public long getSize()\n    {\n        return size;\n    }\n\n    public void setSize(long size)\n    {\n        this.size = size;\n    }\n\n    public StreamedContent getFile()\n    {\n        return file;\n    }\n\n    public void addFile(StreamedContent file)\n    {\n        this.file = file;\n    }\n\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/entities/Employee.java",
    "content": "package com.impetus.kundera.datakeeper.entities;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\n@Entity\n@Table(name = \"EMPLOYEE\", schema = \"datakeeper@cassandra-pu\")\n@IndexCollection(columns = { @Index(name = \"employeeName\"), @Index(name = \"designation\"), @Index(name = \"experience\"),\n        @Index(name = \"joiningDate\"), @Index(name = \"currentProject\"), @Index(name = \"timestamp\"),\n        @Index(name = \"company\") })\npublic class Employee\n{\n    @Id\n    @Column(name = \"EMPLOYEE_ID\")\n    @GeneratedValue(strategy = GenerationType.TABLE)\n    private int employeeId;\n\n    @Column(name = \"PASSWORD\")\n    private String password;\n\n    @Column(name = \"EMPLOYEE_NAME\")\n    private String employeeName;\n\n    @Column(name = \"EXPERIENCE\")\n    private int experience;\n\n    @Column(name = \"JOINING_DATE\")\n    private Date joiningDate;\n\n    @Column(name = \"DESIGNATION\")\n    private String designation;\n\n    @ManyToOne(fetch = FetchType.EAGER)\n    @JoinColumn(name = \"MANAGER_ID\")\n    private Employee manager;\n\n    @OneToMany(fetch = FetchType.EAGER, mappedBy = \"manager\")\n    private List<Employee> subordinates;\n\n    @Column(name = \"PROJECT\")\n    private String currentProject;\n\n    @Column(name = \"COMPANY\")\n    private String company;\n\n    @Column(name = \"JOINING_TIMESTAMP\")\n    private long timestamp;\n\n    public int getEmployeeId()\n    {\n        return employeeId;\n    }\n\n    public void setEmployeeId(int employeeId)\n    {\n        this.employeeId = employeeId;\n    }\n\n    public String getPassword()\n    {\n        return password;\n    }\n\n    public void setPassword(String password)\n    {\n        this.password = password;\n    }\n\n    public String getEmployeeName()\n    {\n        return employeeName;\n    }\n\n    public void setEmployeeName(String employeeName)\n    {\n        this.employeeName = employeeName;\n    }\n\n    public int getExperience()\n    {\n        return experience;\n    }\n\n    public void setExperience(int experience)\n    {\n        this.experience = experience;\n    }\n\n    public Date getJoiningDate()\n    {\n        return joiningDate;\n    }\n\n    public void setJoiningDate(Date joiningDate)\n    {\n        this.joiningDate = joiningDate;\n    }\n\n    public String getDesignation()\n    {\n        return designation;\n    }\n\n    public void setDesignation(String designation)\n    {\n        this.designation = designation;\n    }\n\n    public Employee getManager()\n    {\n        return manager;\n    }\n\n    public void setManager(Employee manager)\n    {\n        this.manager = manager;\n    }\n\n    public String getCurrentProject()\n    {\n        return currentProject;\n    }\n\n    public void setCurrentProject(String currentProject)\n    {\n        this.currentProject = currentProject;\n    }\n\n    public List<Employee> getSubordinates()\n    {\n        return subordinates;\n    }\n\n    public void setSubordinates(List<Employee> subordinates)\n    {\n        this.subordinates = subordinates;\n    }\n\n    public long getTimestamp()\n    {\n        return timestamp;\n    }\n\n    public void setTimestamp(long timestamp)\n    {\n        this.timestamp = timestamp;\n    }\n\n    public String getCompany()\n    {\n        return company;\n    }\n\n    public void setCompany(String company)\n    {\n        this.company = company;\n    }\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/entities/SubordinatesCounter.java",
    "content": "package com.impetus.kundera.datakeeper.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"SUBORDINATES_COUNTER\", schema = \"datakeeper@cassandra-pu\")\npublic class SubordinatesCounter\n{\n    @Id\n    @Column(name = \"EMPLOYEE_ID\")\n    private int employeeId;\n\n    @Column(name = \"SUBORDINATES_COUNTER\")\n    private int noOfSubordinates;\n\n    public int getEmployeeId()\n    {\n        return employeeId;\n    }\n\n    public void setEmployeeId(int employeeId)\n    {\n        this.employeeId = employeeId;\n    }\n\n    public int getNoOfSubordinates()\n    {\n        return noOfSubordinates;\n    }\n\n    public void setNoOfSubordinates(int noOfSubordinates)\n    {\n        this.noOfSubordinates = noOfSubordinates;\n    }\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/service/DataKeeperService.java",
    "content": "package com.impetus.kundera.datakeeper.service;\n\nimport java.util.List;\n\nimport com.impetus.kundera.datakeeper.entities.DocumentInfo;\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.entities.SubordinatesCounter;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic interface DataKeeperService\n{\n    void insertEmployee(Employee employee);\n\n    void insertData(DocumentInfo data);\n\n    Employee findEmployee(Object id);\n\n    Employee findEmployeeByName(String employeeName);\n\n    List<DocumentInfo> findDocumentByEmployeeId(String employeeId);\n\n    List<DocumentInfo> findDocumentByEmployeeName(String employeeName);\n\n    DocumentInfo findDocumentByDocumentId(int documentId);\n\n    void removeEmployee(Employee employee);\n\n    boolean authenticateEmployee(Employee employee, String password);\n\n    List<Employee> findSubOrdinates(int managerId);\n\n    List<Employee> findEmployeeByDateOfJoining(int noOfYears, String company);\n\n    void incrementCounter(SubordinatesCounter counter);\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/service/DataKeeperServiceImpl.java",
    "content": "package com.impetus.kundera.datakeeper.service;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.PersistenceException;\n\nimport org.primefaces.model.DefaultStreamedContent;\nimport org.primefaces.model.StreamedContent;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.datakeeper.dao.DataKeeperDao;\nimport com.impetus.kundera.datakeeper.entities.DocumentInfo;\nimport com.impetus.kundera.datakeeper.entities.Employee;\nimport com.impetus.kundera.datakeeper.entities.SubordinatesCounter;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic class DataKeeperServiceImpl implements DataKeeperService\n{\n    /**\n     * logger used for logging statement.\n     */\n    private static final Logger log = LoggerFactory.getLogger(DataKeeperServiceImpl.class);\n\n    private DataKeeperDao dao;\n\n    public DataKeeperServiceImpl()\n    {\n    }\n\n    public DataKeeperDao getDao()\n    {\n        return dao;\n    }\n\n    public void setDao(DataKeeperDao dao)\n    {\n        this.dao = dao;\n    }\n\n    @Override\n    public void insertEmployee(Employee employee)\n    {\n        employee.setPassword(encriptPassword(employee.getPassword()));\n        dao.insert(employee);\n        log.info(\"Employee {} information successfully inserted.\", employee.getEmployeeName());\n\n        if (employee.getManager() != null)\n        {\n            SubordinatesCounter counter = new SubordinatesCounter();\n            counter.setNoOfSubordinates(1);\n            counter.setEmployeeId(employee.getManager().getEmployeeId());\n            dao.insert(counter);\n            log.info(\"Incremented no of subordinates for manager {}, successfully.\", employee.getManager()\n                    .getEmployeeName());\n        }\n    }\n\n    @Override\n    public Employee findEmployeeByName(String employeeName)\n    {\n        Employee employee = null;\n        String query = \"Select e from \" + Employee.class.getSimpleName() + \" e where e.employeeName = \" + employeeName;\n        List<Employee> employees = (List<Employee>) dao.findByQuery(query);\n        if (!employees.isEmpty() && employees.get(0) != null)\n        {\n            employee = employees.get(0);\n        }\n        return employee;\n    }\n\n    @Override\n    public List<Employee> findSubOrdinates(int managerId)\n    {\n        Employee manager = dao.findById(Employee.class, managerId);\n        List<Employee> subOrdinates = manager != null ? manager.getSubordinates() : new ArrayList<Employee>();\n        return subOrdinates;\n    }\n\n    @Override\n    public void insertData(DocumentInfo data)\n    {\n        dao.insert(data);\n        log.info(\"Data uploaded by  employee {} successfully inserted.\", data.getOwnerName());\n    }\n\n    @Override\n    public Employee findEmployee(Object employeeId)\n    {\n        log.info(\"Finding employee by id {} .\", employeeId);\n        return dao.findById(Employee.class, employeeId);\n    }\n\n    @Override\n    public List<DocumentInfo> findDocumentByEmployeeId(String employeeId)\n    {\n        List<DocumentInfo> documents = new ArrayList<DocumentInfo>();\n        try\n        {\n            Integer.parseInt(employeeId);\n            documents = findDocumentByEmployeeId(Integer.parseInt(employeeId));\n        }\n        catch (NumberFormatException nfex)\n        {\n            log.warn(\"{} not a valid employee id.\", employeeId);\n        }\n        return documents;\n    }\n\n    public List<DocumentInfo> findDocumentByEmployeeId(int employeeId)\n    {\n        List<DocumentInfo> documents = new ArrayList<DocumentInfo>();\n        log.info(\"Finding document by employee id {} .\", employeeId);\n        String query = \"Select d from \" + DocumentInfo.class.getSimpleName() + \" d where d.ownerId =  \" + employeeId;\n        documents = (List<DocumentInfo>) dao.findByQuery(query);\n\n        for (DocumentInfo documentInfo : documents)\n        {\n            StreamedContent file = toStreamedContent(documentInfo.getData(), documentInfo.getDocumentName(),\n                    \"application/pdf\");\n            documentInfo.addFile(file);\n        }\n        return documents;\n    }\n\n    @Override\n    public List<DocumentInfo> findDocumentByEmployeeName(String employeeName)\n    {\n        List<DocumentInfo> documents = new ArrayList<DocumentInfo>();\n        log.info(\"Finding document by employee name {} .\", employeeName);\n        String query = \"Select d from \" + DocumentInfo.class.getSimpleName() + \" d where d.ownerName =  \"\n                + employeeName;\n        documents = (List<DocumentInfo>) dao.findByQuery(query);\n        for (DocumentInfo documentInfo : documents)\n        {\n            StreamedContent file = toStreamedContent(documentInfo.getData(), documentInfo.getDocumentName(),\n                    \"application/pdf\");\n            documentInfo.addFile(file);\n        }\n        return documents;\n    }\n\n    @Override\n    public void removeEmployee(Employee employee)\n    {\n        dao.remove(employee);\n        List<DocumentInfo> documents = findDocumentByEmployeeId(employee.getEmployeeId());\n        for (DocumentInfo document : documents)\n        {\n            if (document != null)\n            {\n                dao.remove(document);\n            }\n        }\n\n        log.info(\"Employee successfully removed\");\n    }\n\n    @Override\n    public boolean authenticateEmployee(Employee employee, String password)\n    {\n        boolean success = false;\n        if (employee != null && (employee.getPassword().equals(encriptPassword(password))))\n        {\n            log.info(\"Employee {} successfully authenticated.\", employee.getEmployeeName());\n            success = true;\n        }\n        else\n        {\n            log.info(\"Employee not authenticated, caused by either wrong userName or wrong password.\");\n        }\n        return success;\n    }\n\n    /**\n     * encriptPassword method used for encrypting password.\n     * \n     * @param password\n     *            the password\n     * @return the string\n     */\n    public String encriptPassword(String password)\n    {\n        String newpassword = null;\n        byte[] defaultBytes = password.getBytes();\n        try\n        {\n            MessageDigest algorithm = MessageDigest.getInstance(\"MD5\");\n            algorithm.reset();\n            algorithm.update(defaultBytes);\n            byte messageDigest[] = algorithm.digest();\n\n            StringBuffer hexString = new StringBuffer();\n            for (int i = 0; i < messageDigest.length; i++)\n            {\n                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));\n            }\n            newpassword = hexString.toString();\n        }\n        catch (NoSuchAlgorithmException e)\n        {\n            log.error(\"Error while encripting password {}, caused by : .\", password, e);\n            throw new PersistenceException(e);\n        }\n        return newpassword;\n    }\n\n    @Override\n    public DocumentInfo findDocumentByDocumentId(int documentId)\n    {\n        log.info(\"Finding document by id.\");\n        DocumentInfo document = dao.findById(DocumentInfo.class, documentId);\n        return document;\n    }\n\n    @Override\n    public List<Employee> findEmployeeByDateOfJoining(final int noOfYears, final String company)\n    {\n        long currentTimeStamp = System.currentTimeMillis();\n        long newTimeStamp = currentTimeStamp - (long) noOfYears * 365 * 24 * 60 * 60 * 1000;\n        String query = \"Select e from \" + Employee.class.getSimpleName() + \" e where e.company = \" + company\n                + \" and e.timestamp <= :timestamp\";\n        List<Employee> subOrdinates = (List<Employee>) dao.findByQuery(query, \"timestamp\", newTimeStamp);\n        return subOrdinates;\n    }\n\n    @Override\n    public void incrementCounter(SubordinatesCounter counter)\n    {\n        dao.insert(counter);\n    }\n\n    private StreamedContent toStreamedContent(byte[] bytes, String fileName, String contentType)\n    {\n        InputStream is = new ByteArrayInputStream(bytes);\n\n        StreamedContent file = new DefaultStreamedContent(is, contentType, fileName);\n\n        return file;\n    }\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/DataFormat.java",
    "content": "package com.impetus.kundera.datakeeper.utils;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic enum DataFormat\n{\n    XLS, XLSX, PDF, DOC, DOCX, AVI;\n\n    /**\n     * If provided protocol is within allowed protocol.\n     * \n     * @param protocol\n     *            protocol\n     * @return true, if it is in allowed protocol.\n     */\n    public static boolean isValidFormat(String format)\n    {\n        try\n        {\n            DataFormat.valueOf(format.toUpperCase());\n            return true;\n        }\n        catch (IllegalArgumentException iex)\n        {\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/DataKeeperConstants.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.datakeeper.utils;\n\n/**\n * <Prove description of functionality provided by this Type> \n * @author amresh.singh\n */\npublic class DataKeeperConstants\n{\n    public static final String OUTCOME_LOGIN_FAILED = \"loginFailed\";\n    public static final String OUTCOME_LOGIN_SUCCESSFUL = \"loginSuccessful\";\n    \n    public static final String OUTCOME_SIGNUP_SUCCESSFUL = \"signUpSuccessful\";\n    \n    public static final String OUTCOME_LOGOFF_SUCCESSFUL = \"logOfSuccessful\";\n    \n    public static final String OUTCOME_TIMELINE = \"timeline\";    \n    \n    public static final String PERSISTENCE_UNIT = \"twitample_cassandra\";\n    \n    public static final String EMPLOYEE_ID = \"employeeId\";\n\n    public static final String EMPLOYEE = \"employee\";\n    \n    public static final String EMPLOYEE_NAME = \"employeeName\";\n    \n    public static final String TWEET_DEVICE_WEB = \"Web\";\n    \n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/DataKeeperUtils.java",
    "content": "package com.impetus.kundera.datakeeper.utils;\n\nimport javax.faces.context.FacesContext;\nimport javax.servlet.http.HttpSession;\n\nimport org.springframework.beans.factory.BeanFactory;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\nimport com.impetus.kundera.datakeeper.service.DataKeeperService;\n\npublic class DataKeeperUtils\n{\n    public static DataKeeperService getService()\n    {\n        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);\n        DataKeeperService datakeeper = (DataKeeperService) session.getAttribute(\"datakeeper\");\n        if (datakeeper == null)\n        {\n            BeanFactory beanfactory = new ClassPathXmlApplicationContext(\"appContext.xml\");\n            datakeeper = (DataKeeperService) beanfactory.getBean(\"datakeeper\");\n            session.setAttribute(\"datakeeper\", datakeeper);\n        }\n        return datakeeper;\n    }\n}\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/java/com/impetus/kundera/datakeeper/utils/FacesUtils.java",
    "content": "package com.impetus.kundera.datakeeper.utils;\r\n\r\nimport javax.faces.context.FacesContext;\r\nimport javax.servlet.http.HttpServletRequest;\r\nimport javax.servlet.http.HttpSession;\r\n\r\n/**\r\n * The Class FacesUtils has method for getting session variables and request\r\n * variables.\r\n */\r\npublic class FacesUtils\r\n{\r\n\r\n    /**\r\n     * getSession method used for getting session variable.\r\n     * \r\n     * @return the session\r\n     */\r\n    public static HttpSession getSession()\r\n    {\r\n        return (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);\r\n    }\r\n\r\n    /**\r\n     * getRequest method used for getting request variable.\r\n     * \r\n     * @return the request\r\n     */\r\n    public static HttpServletRequest getRequest()\r\n    {\r\n        return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();\r\n    }\r\n}\r\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"cassandra-pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.datakeeper.entities.DocumentInfo</class>\r\n\t\t<class>com.impetus.kundera.datakeeper.entities.Employee</class>\r\n\t\t<class>com.impetus.kundera.datakeeper.entities.SubordinatesCounter</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"datakeeper\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"thrift\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\r\n\t\t\t<property name=\"kundera.cache.provider.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\r\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\r\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaCounter.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"mongo-pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.datakeeper.entities.DocumentInfo</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"datakeeper\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\r\n\t\t\t<property name=\"kundera.cache.provider.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\r\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"cassandra-pu,mongo-pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"jboss.as.jpa.managed\" value=\"false\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\r\n</persistence>\r\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/resources/appContext.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \"http://www.springframework.org/dtd/spring-beans.dtd\"> -->\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:context=\"http://www.springframework.org/schema/context\"\n\txmlns:tx=\"http://www.springframework.org/schema/tx\" xmlns:p=\"http://www.springframework.org/schema/p\"\n\txmlns:aop=\"http://www.springframework.org/schema/aop\"\n\txsi:schemaLocation=\"http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.0.xsd  http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd\">\n\n\t<bean id=\"datakeeper\" class=\"com.impetus.kundera.datakeeper.service.DataKeeperServiceImpl\"\n\t\tscope=\"singleton\">\n\t\t<property name=\"dao\" ref=\"dao\" />\n\t</bean>\n\t\n\t<bean id=\"dao\" class=\"com.impetus.kundera.datakeeper.dao.DataKeeperDaoImpl\"\n\t\tscope=\"singleton\">\n\t</bean>\n\t\n\t<!-- Enable @PersistenceContext initialization -->\n\t<!-- <bean\n\t\tclass=\"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor\" />\n\n\t<bean id=\"emf-p\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t\t<property name=\"persistenceUnitManager\" ref=\"persistence-unit\" />\n\t\t<property name=\"persistenceUnitName\" value=\"cassandra_pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean> -->\n\t\n\t<bean id=\"emf-p\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t\t<property name=\"persistenceUnitName\" value=\"cassandra-pu,mongo-pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean>\n\n        <!-- emf-p1 and emf-p2 are required only in case of polyglot persistence\n        (i.e. using multiple cross data store persistence unit --> \n\t<bean id=\"emf-p1\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t<property name=\"persistenceUnitName\" value=\"cassandra-pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean>\n\t<bean id=\"emf-p2\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t\t<property name=\"persistenceUnitName\" value=\"mongo-pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean>\n\n\t<!-- <bean id=\"persistence-unit\"\n\t\tclass=\"org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager\">\n\t\t<property name=\"persistenceXmlLocations\">\n\t\t\t<list>\n\t\t\t\t<value>META-INF/persistence.xml</value>\n\t\t\t</list>\n\t\t</property>\n\t</bean> -->\n<bean\n\t\tclass=\"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor\" >\n\t</bean>\n\n\t<bean id=\"pum\"\n\t\tclass=\"org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager\">\n\t\t<property name=\"persistenceXmlLocations\">\n\t\t\t<list>\n\t\t\t\t<value>META-INF/persistence.xml</value>\n\t\t\t</list>\n\t\t</property>\n\t</bean>\n\t\n\t<bean id=\"matchAllWithPropReq\"\n\t\tclass=\"org.springframework.transaction.interceptor.MatchAlwaysTransactionAttributeSource\">\n\t\t<property name=\"transactionAttribute\" value=\"PROPAGATION_REQUIRED\" />\n\t</bean>\n\n\t<bean id=\"jndiTemplate\" class=\"org.springframework.jndi.JndiTemplate\"\n\t\tlazy-init=\"true\">\n\t\t<property name=\"environment\">\n\t\t\t<props>\n\t\t\t\t<prop key=\"java.naming.factory.initial\">org.apache.naming.java.javaURLContextFactory</prop>\n\t\t\t\t<prop key=\"java.naming.factory.url.pkgs\">org.apache.naming</prop>\n\t\t\t</props>\n\t\t</property>\n\t</bean>\n</beans>\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/resources/kunderaCounter.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>cassandra</name>\n\t\t\t<schemas>\n\t\t\t\t<schema>\n\t\t\t\t\t<name>datakeeper</name>\n\t\t\t\t\t<tables>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>SUBORDINATES_COUNTER</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"default.validation.class\" value=\"CounterColumnType\"></property>\n\t\t\t\t\t\t\t\t<property name=\"key.validation.class\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</tables>\n\t\t\t\t</schema>\n\t\t\t</schemas>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/resources/log4j.properties",
    "content": "log4j.rootLogger=INFO, DRFA, CONSOLE\r\n\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera-benchmark.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/WEB-INF/faces-config.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<faces-config xmlns=\"http://java.sun.com/xml/ns/javaee\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd\"\n\tversion=\"2.1\">\n\t<navigation-rule>\n\t\t<from-view-id>/xhtml/login/login.xhtml</from-view-id>\n\t\t<navigation-case>\n\t\t\t<from-outcome>loginSuccessful</from-outcome>\n\t\t\t<to-view-id>/xhtml/home/timeline.xhtml</to-view-id>\n\t\t</navigation-case>\n\t\t<navigation-case>\n\t\t\t<from-outcome>loginFailed</from-outcome>\n\t\t\t<to-view-id>/xhtml/login/login.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n\n\t<navigation-rule>\n\t\t<from-view-id>/xhtml/register/signUp.xhtml</from-view-id>\n\t\t<navigation-case>\n\t\t\t<from-outcome>signUpSuccessful</from-outcome>\n\t\t\t<to-view-id>/xhtml/login/login.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n\n\t<navigation-rule>\n\t\t<from-view-id>/xhtml/register/signUp.xhtml</from-view-id>\n\t\t<navigation-case>\n\t\t\t<from-outcome>timeline</from-outcome>\n\t\t\t<to-view-id>/xhtml/home/timeline.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n\t<navigation-rule>\n\t\t<from-view-id>/xhtml/home/timeline.xhtml</from-view-id>\n\t\t<navigation-case>\n\t\t\t<from-outcome>foundEmployess</from-outcome>\n\t\t\t<to-view-id>/xhtml/home/showSubordinatesInfo.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n\t<navigation-rule>\n\t\t<from-view-id>/xhtml/home/showSubordinatesInfo.xhtml</from-view-id>\n\t\t<navigation-case>\n\t\t\t<from-outcome>foundEmployess</from-outcome>\n\t\t\t<to-view-id>/xhtml/home/showSubordinatesInfo.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n\t<navigation-rule>\n\t\t<navigation-case>\n\t\t\t<from-outcome>logOfSuccessful</from-outcome>\n\t\t\t<to-view-id>/xhtml/login/login.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n\n\t<navigation-rule>\n\t\t<navigation-case>\n\t\t\t<from-outcome>Account successfully deleted</from-outcome>\n\t\t\t<to-view-id>/xhtml/login/login.xhtml</to-view-id>\n\t\t</navigation-case>\n\t</navigation-rule>\n</faces-config>"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/WEB-INF/web.xml",
    "content": "<?xml version=\"1.0\"?>\n<web-app version=\"2.5\" xmlns=\"http://java.sun.com/xml/ns/javaee\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\">\n\t<display-name>DataKeeper application</display-name>\n\n\t<context-param>\n\t\t<param-name>javax.faces.STATE_SAVING_METHOD</param-name>\n\t\t<param-value>server</param-value>\n\t</context-param>\n\t<context-param>\n\t\t<param-name>javax.faces.CONFIG_FILES</param-name>\n\t\t<param-value>/WEB-INF/faces-config.xml</param-value>\n\t</context-param>\n\n\n\t<listener>\n\t\t<listener-class>com.sun.faces.config.ConfigureListener</listener-class>\n\t</listener>\n\n\t<!-- Faces Servlet -->\n\t<servlet>\n\t\t<servlet-name>Faces Servlet</servlet-name>\n\t\t<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n\t\t<load-on-startup>1</load-on-startup>\n\t</servlet>\n\n\t<servlet-mapping>\n\t\t<servlet-name>Faces Servlet</servlet-name>\n\t\t<url-pattern>*.jsf</url-pattern>\n\t</servlet-mapping>\n\n\t<welcome-file-list>\n\t\t<welcome-file>xhtml/login/login.jsf</welcome-file>\n\t</welcome-file-list>\n\n\t<filter>\n\t\t<filter-name>PrimeFaces FileUpload Filter</filter-name>\n\t\t<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>\n\t\t<init-param>\n\t\t\t<param-name>thresholdSize</param-name>\n\t\t\t<param-value>512000</param-value>\n\t\t</init-param>\n\t\t<init-param>\n\t\t\t<param-name>uploadDirectory</param-name>\n\t\t\t<param-value>C:\\etc</param-value>\n\t\t</init-param>\n\t</filter>\n\t<filter-mapping>\n\t\t<filter-name>PrimeFaces FileUpload Filter</filter-name>\n\t\t<servlet-name>Faces Servlet</servlet-name>\n\t</filter-mapping>\n\n</web-app>"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/appContext.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \"http://www.springframework.org/dtd/spring-beans.dtd\"> -->\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:context=\"http://www.springframework.org/schema/context\"\n\txmlns:tx=\"http://www.springframework.org/schema/tx\" xmlns:p=\"http://www.springframework.org/schema/p\"\n\txmlns:aop=\"http://www.springframework.org/schema/aop\"\n\txsi:schemaLocation=\"http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.0.xsd  http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-3.0.xsd\">\n\n\t<bean id=\"datakeeper\" class=\"com.impetus.kundera.datakeeper.service.DataKeeperServiceImpl\"\n\t\tscope=\"singleton\">\n\t\t<property name=\"dao\" ref=\"dao\" />\n\t</bean>\n\t\n\t<bean id=\"dao\" class=\"com.impetus.kundera.datakeeper.dao.DataKeeperDaoImpl\"\n\t\tscope=\"singleton\">\n\t</bean>\n\t\n\t<!-- Enable @PersistenceContext initialization -->\n\t<!-- <bean\n\t\tclass=\"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor\" />\n\n\t<bean id=\"emf-p\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t\t<property name=\"persistenceUnitManager\" ref=\"persistence-unit\" />\n\t\t<property name=\"persistenceUnitName\" value=\"cassandra_pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean> -->\n\t\n\t<bean id=\"emf-p\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t\t<property name=\"persistenceUnitName\" value=\"cassandra-pu,mongo-pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean>\n\n\t<bean id=\"emf-p1\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t<property name=\"persistenceUnitName\" value=\"cassandra-pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean>\n\t<bean id=\"emf-p2\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t\t<property name=\"persistenceUnitName\" value=\"mongo-pu\" />\n\t\t<property name=\"loadTimeWeaver\">\n\t\t\t<bean\n\t\t\t\tclass=\"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver\" />\n\t\t</property>\n\t</bean>\n\n\t<!-- <bean id=\"persistence-unit\"\n\t\tclass=\"org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager\">\n\t\t<property name=\"persistenceXmlLocations\">\n\t\t\t<list>\n\t\t\t\t<value>META-INF/persistence.xml</value>\n\t\t\t</list>\n\t\t</property>\n\t</bean> -->\n<bean\n\t\tclass=\"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor\" >\n\t</bean>\n\n\t<bean id=\"pum\"\n\t\tclass=\"org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager\">\n\t\t<property name=\"persistenceXmlLocations\">\n\t\t\t<list>\n\t\t\t\t<value>META-INF/persistence.xml</value>\n\t\t\t</list>\n\t\t</property>\n\t</bean>\n\t\n\t<bean id=\"matchAllWithPropReq\"\n\t\tclass=\"org.springframework.transaction.interceptor.MatchAlwaysTransactionAttributeSource\">\n\t\t<property name=\"transactionAttribute\" value=\"PROPAGATION_REQUIRED\" />\n\t</bean>\n\n\t<bean id=\"jndiTemplate\" class=\"org.springframework.jndi.JndiTemplate\"\n\t\tlazy-init=\"true\">\n\t\t<property name=\"environment\">\n\t\t\t<props>\n\t\t\t\t<prop key=\"java.naming.factory.initial\">org.apache.naming.java.javaURLContextFactory</prop>\n\t\t\t\t<prop key=\"java.naming.factory.url.pkgs\">org.apache.naming</prop>\n\t\t\t</props>\n\t\t</property>\n\t</bean>\n</beans>"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/index.jsp",
    "content": "<html>\n<body>\n<h2>Hello World!</h2>\n</body>\n</html>\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/common/header.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n xmlns:h=\"http://java.sun.com/jsf/html\"\n xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:ui=\"http://java.sun.com/jsf/facelets\"\n xmlns:p=\"http://primefaces.org/ui\">\n<h:panelGroup>\n    <table width=\"100%\">\n        <tbody>\n            <tr>\n        <td align=\"left\"><img src=\"../../images/impetus_logo.jpg\" height=\"50\" width=\"150\" /></td>\n                <td >\n                    <h2><h:outputText value=\"DataKeeper\" /></h2>\n                </td>\n                <td align=\"right\">\n                </td>\n        </tr>\n        </tbody>\n    </table>\n</h:panelGroup>\n</ui:composition>"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/common/leftPane.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<p:panel header=\"Welcome, #{sessionScope.employee.employeeName}\">\n\n\t\t<table>\n\t\t\t<tr>\n\t\t\t\t<td><img src=\"../../images/BlankProfile.gif\" height=\"200\"\n\t\t\t\t\twidth=\"200\" /></td>\n\t\t\t</tr>\n\n\n\n\t\t\t<tr>\n\t\t\t\t<td><br /> <h:outputText value=\"Employee Detail\"\n\t\t\t\t\t\tstyle=\"font-weight:bold;\" /> <br /></td>\n\t\t\t</tr>\n\t\t\t<ui:repeat var=\"employee\" value=\"#{employee}\">\n\t\t\t\t<tr>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText value=\"Employee Id:-\" /></td>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"#{employee.employeeId}\" /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText value=\"Employee Name:-\"/></td>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"#{employee.employeeName}\" /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"Experience in year:-\" /></td>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"#{employee.experience}\" /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText value=\"Designation:-\" /></td>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"#{employee.designation}\" /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText value=\"Manager Name:-\" /></td>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"#{employee.manager.employeeName}\" /></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText value=\"Project:-\" /></td>\n\t\t\t\t\t<td style=\"align: center\"><h:outputText\n\t\t\t\t\t\t\tvalue=\"#{employee.currentProject}\" /></td>\n\t\t\t\t</tr>\n\n\t\t\t</ui:repeat>\n\n\t\t</table>\n\t</p:panel>\n</ui:composition>"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/common/loggedInHeader.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<h:panelGroup>\n\t\t<table width=\"100%\">\n\t\t\t<tbody>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align=\"left\"><img src=\"../../images/impetus_logo.jpg\"\n\t\t\t\t\t\theight=\"50\" width=\"150\" /></td>\n\t\t\t\t\t<td>\n\t\t\t\t\t<h2><h:outputText value=\"DataKeeper\" /></h2>\n\t\t\t\t\t</td>\n\t\t\t\t\t<td align=\"right\">\n\t\t\t\t\t\t<h:form>\n\t\t\t\t\t\t<h:commandLink value=\"Home\" action=\"/xhtml/home/timeline.xhtml\" />\t\t\t\n\t\t\t\t\t\t<h:outputText value=\" | \" />\n\t\t\t\t\t\t<h:commandLink value=\"Settings\" action=\"/xhtml/settings/settings.xhtml\" />\t\t\t\n\t\t\t\t\t\t<h:outputText value=\" | \" />\t\t\t\n\t\t\t\t\t\t<h:commandLink value=\"Logoff\" action=\"#{loginBean.logOff}\" />\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t</h:form>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</tbody>\n\t\t</table>\n\t</h:panelGroup>\n</ui:composition>"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/home/showSubordinatesInfo.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\ttemplate=\"timelineTemplate.xhtml\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<ui:define name=\"title\">\n        DataKeeper :: Employees Information\n    </ui:define>\n\n\t<ui:define name=\"content\">\n\t\t<p:panel header=\"Employess\">\n\t\t\t<table width=\"100%\">\n\t\t\t\t<tr>\n\t\t\t\t\t<!-- <table width=\"100%\"> -->\n\t\t\t\t\t<!-- <tr> -->\n\t\t\t\t\t<td style=\"align: center;\"><h:form>\n\t\t\t\t\t\t\t<p:dataTable id=\"dataTable\" var=\"subordinate\"\n\t\t\t\t\t\t\t\tvalue=\"#{subordinateSearchBean.subordinates}\">\n\n\t\t\t\t\t\t\t\t<p:column id=\"idColumn\" headerText=\"Employee Id\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{subordinate.employeeId}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"nameColumn\" headerText=\"Employee Name\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:commandLink id=\"employeeNameColumn\"\n\t\t\t\t\t\t\t\t\t\tvalue=\"#{subordinate.employeeName}\"\n\t\t\t\t\t\t\t\t\t\taction=\"#{subordinateSearchBean.searchSubordinates}\">\n\t\t\t\t\t\t\t\t\t\t<f:param name=\"managerId\" value=\"#{subordinate.employeeId}\" />\n\t\t\t\t\t\t\t\t\t</h:commandLink>\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"managerColumn\" headerText=\"Manager Name\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{subordinate.manager.employeeName}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"designationColumn\" headerText=\"Designation\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{subordinate.designation}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"projectColumn\" headerText=\"Current Project\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{subordinate.currentProject}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t</p:dataTable>\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t\t<!-- </tr> -->\n\t\t\t\t\t<!-- </table> -->\n\t\t\t\t</tr>\n\n\t\t\t</table>\n\n\t\t</p:panel>\n\t</ui:define>\n</ui:composition>"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/home/showSubordinatesInfoTemplate.xhtml",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.prime.com.tr/ui\">\n<f:view contentType=\"text/html\">\n\t<h:head>\n\t\t<title><ui:insert name=\"title\">Default title</ui:insert></title>\n\t</h:head>\n\t<h:body>\n\t\t<table width=\"100%\">\n\t\t\t<tr>\n\t\t\t\t<td><ui:include src=\"../common/loggedInHeader.xhtml\" /></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align=\"center\">\n\t\t\t\t<table>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><p:growl id=\"growl\" sticky=\"false\" showDetail=\"false\" /></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<br />\n\t\t\t\t<table width=\"100%\" style=\"vertical-align: top;\">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td width=\"20%\" style=\"vertical-align: top;\"><ui:include\n\t\t\t\t\t\t\tsrc=\"../common/leftPane.xhtml\" /></td>\n\t\t\t\t\t\t<td width=\"80%\" style=\"vertical-align: top;\"><ui:insert\n\t\t\t\t\t\t\tname=\"content\">Default content</ui:insert></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>\n\t</h:body>\n</f:view>\n</html>\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/home/timeline.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\ttemplate=\"timelineTemplate.xhtml\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<ui:define name=\"title\">\n        DataKeeper :: Home\n    </ui:define>\n\n\t<ui:define name=\"content\">\n\t\t<p:panel header=\"Your Timeline\">\n\t\t\t<table width=\"100%\">\n\t\t\t\t<tr>\n\t\t\t\t\t<td><h:form enctype=\"multipart/form-data\">\n\t\t\t\t\t\t\t<p:fileUpload\n\t\t\t\t\t\t\t\tfileUploadListener=\"#{documentUploadBean.handleFileUpload}\"\n\t\t\t\t\t\t\t\tmode=\"advanced\" update=\"messages\" sizeLimit=\"10000000\"\n\t\t\t\t\t\t\t\tallowTypes=\"/(\\.|\\/)(pdf|xls|xlsx|doc|docx|txt|text|avi)$/\" />\n\t\t\t\t\t\t\t<p:growl id=\"messages\" showDetail=\"true\" />\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><h:form>\n\t\t\t\t\t\t\t<strong><h:outputText value=\"SearchEmployee:-  \" /> </strong>\n\t\t\t\t\t\t\t<h:inputText value=\"#{subordinateSearchBean.noOfYears}\" />\n\t\t\t\t\t\t\t<h:commandButton value=\"Search\"\n\t\t\t\t\t\t\t\taction=\"#{subordinateSearchBean.searchEmployeeByYearOfComplition}\" />\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t\t<td><h:form>\n\t\t\t\t\t\t\t<h:commandButton value=\"Subordinates\"\n\t\t\t\t\t\t\t\taction=\"#{subordinateSearchBean.searchSubordinates}\">\n\t\t\t\t\t\t\t\t<f:param name=\"managerId\"\n\t\t\t\t\t\t\t\t\tvalue=\"#{sessionScope.employee.employeeId}\" />\n\t\t\t\t\t\t\t</h:commandButton>\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><h:form>\n\t\t\t\t\t\t\t<strong><h:outputText value=\"SearchEmployee:-  \" /> </strong>\n\t\t\t\t\t\t\t<h:selectOneMenu value=\"#{subordinateSearchBean.searchBy}\">\n\t\t\t\t\t\t\t\t<f:selectItem itemValue=\"0\" itemLabel=\"EmployeeName\" />\n\t\t\t\t\t\t\t\t<f:selectItem itemValue=\"1\" itemLabel=\"EmployeeId\" />\n\t\t\t\t\t\t\t</h:selectOneMenu>\n\t\t\t\t\t\t\t<h:inputText value=\"#{subordinateSearchBean.searchText}\" />\n\t\t\t\t\t\t\t<h:commandButton value=\"Search\"\n\t\t\t\t\t\t\t\taction=\"#{subordinateSearchBean.searchEmployee}\" />\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td><h:form>\n\t\t\t\t\t\t\t<strong><h:outputText value=\"Search Document:-  \" /> </strong>\n\t\t\t\t\t\t\t<h:selectOneMenu value=\"#{documentSearchBean.searchBy}\">\n\t\t\t\t\t\t\t\t<f:selectItem itemValue=\"0\" itemLabel=\"EmployeeName\" />\n\t\t\t\t\t\t\t\t<f:selectItem itemValue=\"1\" itemLabel=\"EmployeeId\" />\n\t\t\t\t\t\t\t</h:selectOneMenu>\n\t\t\t\t\t\t\t<h:inputText value=\"#{documentSearchBean.searchText}\" />\n\t\t\t\t\t\t\t<h:commandButton value=\"Search\"\n\t\t\t\t\t\t\t\taction=\"#{documentSearchBean.search}\" />\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<!-- <table width=\"100%\"> -->\n\t\t\t\t\t<!-- <tr> -->\n\t\t\t\t\t<td style=\"align: center;\"><h:form>\n\t\t\t\t\t\t\t<p:dataTable id=\"dataTable\" var=\"documentInfo\"\n\t\t\t\t\t\t\t\tvalue=\"#{documentSearchBean.documents}\">\n\n\t\t\t\t\t\t\t\t<p:column id=\"nameColumn\" headerText=\"Document Name\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{documentInfo.documentName}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"ownerColumn\" headerText=\"Uploaded By\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{documentInfo.ownerName}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"dateColumn\" headerText=\"Uploaded Date\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{documentInfo.uplodedDate}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"sizeColumn\" headerText=\"Size\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<h:outputText value=\"#{documentInfo.size}\" />\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t\t<p:column id=\"downloadColumn\" headerText=\"Download\"\n\t\t\t\t\t\t\t\t\tstyle=\"width:200px;align:center;\">\n\t\t\t\t\t\t\t\t\t<p:commandButton id=\"downloadLink\" value=\"Download\"\n\t\t\t\t\t\t\t\t\t\tajax=\"false\" onclick=\"PrimeFaces.monitorDownload(start, stop)\"\n\t\t\t\t\t\t\t\t\t\ticon=\"ui-icon-arrowthichk-s\">\n\t\t\t\t\t\t\t\t\t\t<p:fileDownload value=\"#{documentInfo.file}\" />\n\t\t\t\t\t\t\t\t\t</p:commandButton>\n\t\t\t\t\t\t\t\t</p:column>\n\n\t\t\t\t\t\t\t</p:dataTable>\n\t\t\t\t\t\t</h:form></td>\n\t\t\t\t\t<!-- </tr> -->\n\t\t\t\t\t<!-- </table> -->\n\t\t\t\t</tr>\n\n\t\t\t</table>\n\n\t\t</p:panel>\n\t</ui:define>\n</ui:composition>\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/home/timelineTemplate.xhtml",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.prime.com.tr/ui\">\n<f:view contentType=\"text/html\">\n\t<h:head>\n\t\t<title><ui:insert name=\"title\">Default title</ui:insert></title>\n\t</h:head>\n\t<h:body>\n\t\t<table width=\"100%\">\n\t\t\t<tr>\n\t\t\t\t<td><ui:include src=\"../common/loggedInHeader.xhtml\" /></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align=\"center\">\n\t\t\t\t<table>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><p:growl id=\"growl\" sticky=\"false\" showDetail=\"false\" /></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<br />\n\t\t\t\t<table width=\"100%\" style=\"vertical-align: top;\">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td width=\"20%\" style=\"vertical-align: top;\"><ui:include\n\t\t\t\t\t\t\tsrc=\"../common/leftPane.xhtml\" /></td>\n\t\t\t\t\t\t<td width=\"80%\" style=\"vertical-align: top;\"><ui:insert\n\t\t\t\t\t\t\tname=\"content\">Default content</ui:insert></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>\n\t</h:body>\n</f:view>\n</html>\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/login/login.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\ttemplate=\"loginTemplate.xhtml\" xmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<ui:define name=\"title\">\n        Kwitter :: Login\n    </ui:define>\n\n\t<ui:define name=\"content\">\n\n\t\t<table>\n\t\t\t<tr>\n\t\t\t\t<td><p:growl id=\"growl\" sticky=\"false\" showDetail=\"false\"/> </td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<br />\n\t\t <p:panel header=\"Login to DataKeeper\">\n\t\t\t<h:form>\n\t\t\t\t<table>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><h:outputText value=\"User Name:\" /></td>\n\t\t\t\t\t\t<td><p:inputText size=\"20\" value=\"#{loginBean.employee.employeeName}\" /></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><h:outputText value=\"Password:\" /></td>\n\t\t\t\t\t\t<td><p:password size=\"20\"\n\t\t\t\t\t\t\tvalue=\"#{loginBean.employee.password}\" /></td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t\n\t\t\t\t\t<tr>\t\t\t\t\t\t\n\t\t\t\t\t\t<td colspan=\"2\" align=\"right\"><h:commandButton value=\"Submit\"\n\t\t\t\t\t\t\taction=\"#{loginBean.authenticate}\" /></td>\n\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\t\t\t\t\t\t\n\t\t\t\t\t\t<td colspan=\"2\" align=\"right\">Not a member? <h:commandLink value=\"SignUp Now!\"\n\t\t\t\t\t\t\taction=\"/xhtml/register/signUp.xhtml\" /></td>\n\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t</h:form>\n\t\t</p:panel>\n\t</ui:define>\n</ui:composition>\n\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/login/loginTemplate.xhtml",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.prime.com.tr/ui\">\n<f:view contentType=\"text/html\">\n<h:head>\n\t<title><ui:insert name=\"title\">Default title</ui:insert></title>\n</h:head>\n<h:body>\n\t<table width=\"100%\">\n\t\t<tr>\n\t\t\t<td><ui:include src=\"../common/header.xhtml\" /></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td align=\"center\"><ui:insert name=\"content\">Default content</ui:insert></td>\n\t\t</tr>\n\t</table>\n</h:body>\n</f:view>\n</html>"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/register/signUp.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\ttemplate=\"signUpTemplate.xhtml\" xmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<ui:define name=\"title\">\n        Kwitter :: SignUp\n    </ui:define>\n\n\t<ui:define name=\"content\">\n\n\t\t<table>\n\t\t\t<tr>\n\t\t\t\t<td><p:growl id=\"growl\" sticky=\"false\" showDetail=\"false\" /></td>\n\t\t\t</tr>\n\t\t</table>\n\t\t<br />\n\t\t<p:panel header=\"SignUp to DataKeeper\">\n\t\t\t<h:form>\n\n\t\t\t\t<p:growl id=\"growl\" sticky=\"true\" showDetail=\"true\" />\n\n\t\t\t\t<p:panel header=\"Employee Details\">\n\n\t\t\t\t\t<h:messages errorClass=\"error\" />\n\n\t\t\t\t\t<h:panelGrid columns=\"2\" columnClasses=\"label, value\"\n\t\t\t\t\t\tstyleClass=\"grid\">\n\n\t\t\t\t\t\t<h:outputText value=\"Employee Name: *\" />\n\t\t\t\t\t\t<p:inputText required=\"true\" label=\"Employee Name\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.employee.employeeName}\" />\n\n\t\t\t\t\t\t<h:outputText value=\"Password: *\" />\n\t\t\t\t\t\t<p:password size=\"20\" required=\"true\" label=\"Password\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.employee.password}\" />\n\n\t\t\t\t\t\t<h:outputText value=\"Experience: *\" />\n\t\t\t\t\t\t<p:inputText required=\"true\" label=\"Experience\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.employee.experience}\" />\n\n\t\t\t\t\t\t<h:outputText value=\"Joining Date: *\" />\n\t\t\t\t\t\t<p:calendar value=\"#{registerBean.employee.joiningDate}\"\n\t\t\t\t\t\t\tid=\"popupCal\" />\n\n\t\t\t\t\t\t<h:outputText value=\"Company Name\" />\n\t\t\t\t\t\t<p:inputText required=\"true\" label=\"Company Name\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.employee.company}\" />\n\n\t\t\t\t\t\t<h:outputText value=\"Designation:*\" />\n\t\t\t\t\t\t<p:inputText required=\"true\" label=\"Designation\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.employee.designation}\" />\n\n\t\t\t\t\t\t<h:outputText value=\"ManagerId: *\" />\n\t\t\t\t\t\t<p:inputText required=\"true\" label=\"ManagerId\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.managerId}\" />\n\n\t\t\t\t\t\t<h:outputText value=\"Current Project *\" />\n\t\t\t\t\t\t<p:inputText required=\"true\" label=\"Current Project\"\n\t\t\t\t\t\t\tvalue=\"#{registerBean.employee.currentProject}\" />\n\t\t\t\t\t</h:panelGrid>\n\n\t\t\t\t</p:panel>\n\n\t\t\t\t<h:panelGrid>\n\t\t\t\t\t<p:commandButton value=\"Submit\" update=\"growl\"\n\t\t\t\t\t\taction=\"#{registerBean.save}\" />\n\t\t\t\t</h:panelGrid>\n\n\t\t\t</h:form>\n\n\t\t</p:panel>\n\t</ui:define>\n</ui:composition>"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/register/signUpTemplate.xhtml",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.prime.com.tr/ui\">\n<f:view contentType=\"text/html\">\n<h:head>\n\t<title><ui:insert name=\"title\">Default title</ui:insert></title>\n</h:head>\n<h:body>\n\t<table width=\"100%\">\n\t\t<tr>\n\t\t\t<td><ui:include src=\"../common/header.xhtml\" /></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td align=\"center\"><ui:insert name=\"content\">Default content</ui:insert></td>\n\t\t</tr>\n\t</table>\n</h:body>\n</f:view>\n</html>"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/settings/settings.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\ttemplate=\"settingsTemplate.xhtml\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<ui:define name=\"title\">\n        Kwitter :: Settings\n    </ui:define>\n\n\t<ui:define name=\"content\">\t\t\n\t\t<p:panel header=\"Your Settings\">\n\t\t\t<table width=\"100%\">\n\t\t\t\t<tr><td><h:outputText value=\"Click below to permanently delete your account\" /></td></tr>\n\t\t\t\t<tr><td><h:outputText value=\"Warning: This action can't be reverted back!\" style=\"color:red;\"/></td></tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<h:form>\t\t\t\t\t\t\n\t\t\t\t\t\t<td><h:commandButton value=\"Delete My Account\"\n\t\t\t\t\t\t\taction=\"#{loginBean.deleteAccount}\" /></td>\n\t\t\t\t\t</h:form>\n\t\t\t\t</tr>\t\t\t\t\n\n\t\t\t</table>\n\n\t\t</p:panel>\n\t</ui:define>\n</ui:composition>\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/settings/settingsTemplate.xhtml",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.prime.com.tr/ui\">\n<f:view contentType=\"text/html\">\n\t<h:head>\n\t\t<title><ui:insert name=\"title\">Default title</ui:insert></title>\n\t</h:head>\n\t<h:body>\n\t\t<table width=\"100%\">\n\t\t\t<tr>\n\t\t\t\t<td><ui:include src=\"../common/loggedInHeader.xhtml\" /></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td align=\"center\">\n\t\t\t\t<table>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td><p:growl id=\"growl\" sticky=\"false\" showDetail=\"false\" /></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t<br />\n\t\t\t\t<table width=\"100%\" style=\"vertical-align: top;\">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td width=\"20%\" style=\"vertical-align: top;\"><ui:include\n\t\t\t\t\t\t\tsrc=\"../common/leftPane.xhtml\" /></td>\n\t\t\t\t\t\t<td width=\"80%\" style=\"vertical-align: top;\"><ui:insert\n\t\t\t\t\t\t\tname=\"content\">Default content</ui:insert></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t</table>\n\t</h:body>\n</f:view>\n</html>\n"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/upload/uploadDocument.xhtml",
    "content": "<ui:composition xmlns=\"http://www.w3.org/1999/xhtml\"\n\ttemplate=\"uploadDocumentTemplate.xhtml\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.org/ui\">\n\t<ui:define name=\"title\">\n        DataKeeper :: Upload\n    </ui:define>\n\t<ui:define name=\"content\">\n\t\t<h:form enctype=\"multipart/form-data\">\n\n\t\t\t<p:messages showDetail=\"true\" />\n\n\t\t\t<p:fileUpload value=\"#{documentUploadBean.file}\" mode=\"simple\"\n\t\t\t\tallowTypes=\"/(\\.|\\/)(pdf|xls?x|doc?x|avi)$/\" />\n\n\t\t\t<p:commandButton value=\"Submit\" ajax=\"false\"\n\t\t\t\tactionListener=\"#{documentUploadBean.handleFileUpload}\" />\n\n\t\t</h:form>\n\t\t<h:form enctype=\"multipart/form-data\">\n\t\t\t<p:fileUpload\n\t\t\t\tfileUploadListener=\"#{documentUploadBean.handleFileUpload}\"\n\t\t\t\tmode=\"advanced\" update=\"messages\" sizeLimit=\"100000000\"\n\t\t\t\tallowTypes=\"/(\\.|\\/)(pdf|xls?x|doc?x|avi)$/\" />\n\t\t\t<p:growl id=\"messages\" showDetail=\"true\" />\n\t\t</h:form>\n\n\t</ui:define>\n</ui:composition>"
  },
  {
    "path": "examples/container/tomcat-glassfish/data-keeper/src/main/webapp/xhtml/upload/uploadDocumentTemplate.xhtml",
    "content": "<!DOCTYPE html>\n<html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"\n\txmlns:f=\"http://java.sun.com/jsf/core\"\n\txmlns:h=\"http://java.sun.com/jsf/html\"\n\txmlns:ui=\"http://java.sun.com/jsf/facelets\"\n\txmlns:p=\"http://primefaces.prime.com.tr/ui\">\n<f:view contentType=\"text/html\">\n<h:head>\n\t<title><ui:insert name=\"title\">Default title</ui:insert></title>\n</h:head>\n<h:body>\n\t<table width=\"100%\">\n\t\t<tr>\n\t\t\t<td><ui:include src=\"../common/header.xhtml\" /></td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td align=\"center\"><ui:insert name=\"content\">Default content</ui:insert></td>\n\t\t</tr>\n\t</table>\n</h:body>\n</f:view>\n</html>"
  },
  {
    "path": "examples/container/tomcat-glassfish/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t<groupId>com.impetus.kundera.examples</groupId>\n\t<artifactId>container</artifactId>\n\t<version>3.3-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.examples</groupId>\n\t<artifactId>tomcat-glassfish</artifactId>\n\t<version>3.3-SNAPSHOT</version>\n\t<packaging>pom</packaging>\n\n\t<name>tomcat-glassfish</name>\n\t<url>https://github.com/impetus-opensource/Kundera</url>\n\n\t<!-- Build profiles -->\n\t<profiles>\n\n\t\t<profile>\n\t\t\t<id>all</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>true</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>data-keeper</module>\n\t\t\t</modules>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "examples/data-as-object-example/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.impetus</groupId>\n\t<artifactId>data-as-object-example</artifactId>\n\t<packaging>jar</packaging>\n\t<version>1.0-SNAPSHOT</version>\n\t<name>data-as-object-example</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<kundera-version>3.4-SNAPSHOT</kundera-version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>data-as-object</artifactId>\n\t\t\t<version>${kundera-version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>${kundera-version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-mongo</artifactId>\n\t\t\t<version>${kundera-version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-rdbms</artifactId>\n\t\t\t<version>${kundera-version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-kudu</artifactId>\n\t\t\t<version>${kundera-version}</version>\n\t\t</dependency>\n\t\t<!-- <dependency> -->\n\t\t<!-- <groupId>com.impetus.kundera.client</groupId> -->\n\t\t<!-- <artifactId>kundera-elastic-search</artifactId> -->\n\t\t<!-- <version>${kundera-version}</version> -->\n\t\t<!-- </dependency> -->\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<version>3.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n</project>\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/crud/CassandraCRUDTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.dataasobject.crud;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.dataasobject.entities.Employee;\n\nimport junit.framework.Assert;\n\n/**\n * The Class CassandraCRUDTest.\n */\npublic class CassandraCRUDTest\n{\n\n    /**\n     * Sets the up before class.\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass()\n    {\n        Employee.bind(\"client-properties.json\", Employee.class);\n    }\n\n    /**\n     * Test crud.\n     */\n    @Test\n    public void testCRUD()\n    {\n        testInsert();\n        testUpdate();\n        testDelete();\n    }\n\n    /**\n     * Test insert.\n     */\n    private void testInsert()\n    {\n        Employee emp = new Employee();\n        emp.setEmplyoeeId(101l);\n        emp.setName(\"karthik\");\n        emp.setSalary(50000d);\n        emp.save();\n        Employee e = new Employee().find(101l);\n        Assert.assertEquals(Long.valueOf(101), e.getEmplyoeeId());\n        Assert.assertEquals(\"karthik\", e.getName());\n        Assert.assertEquals(50000d, e.getSalary());\n    }\n\n    /**\n     * Test update.\n     */\n    private void testUpdate()\n    {\n        Employee e = new Employee().find(101l);\n        e.setName(\"dev\");\n        e.update();\n\n        Employee e1 = new Employee().find(101l);\n        Assert.assertEquals(Long.valueOf(101), e1.getEmplyoeeId());\n        Assert.assertEquals(\"dev\", e1.getName());\n        Assert.assertEquals(50000d, e1.getSalary());\n    }\n\n    /**\n     * Test delete.\n     */\n    private void testDelete()\n    {\n        Employee e = new Employee().find(101l);\n        e.delete();\n\n        Employee e1 = new Employee().find(101l);\n        Assert.assertNull(e1);\n    }\n\n    /**\n     * Tear down after class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        Employee.unbind();\n    }\n}\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/crud/KuduCRUDTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.dataasobject.crud;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.dataasobject.entities.Customer;\n\nimport junit.framework.Assert;\n\n/**\n * The Class KuduCRUDTest.\n */\npublic class KuduCRUDTest\n{\n\n    /**\n     * Sets the up before class.\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass()\n    {\n        Customer.bind(\"client-properties.json\", Customer.class);\n    }\n\n    /**\n     * Test crud.\n     */\n    @Test\n    public void testCRUD()\n    {\n        testInsert();\n        testUpdate();\n        testDelete();\n    }\n\n    /**\n     * Test insert.\n     */\n    private void testInsert()\n    {\n        Customer customer = new Customer();\n        customer.setCustomerId(101);\n        customer.setName(\"dev\");\n        customer.setLocation(\"Noida\");\n        customer.save();\n\n        Customer c = new Customer().find(101);\n\n        Assert.assertEquals(101, c.getCustomerId());\n        Assert.assertEquals(\"dev\", c.getName());\n        Assert.assertEquals(\"Noida\", c.getLocation());\n    }\n\n    /**\n     * Test update.\n     */\n    private void testUpdate()\n    {\n        Customer c = new Customer().find(101);\n        c.setName(\"karthik\");\n        c.update();\n\n        Customer c1 = new Customer().find(101);\n        Assert.assertEquals(101, c1.getCustomerId());\n        Assert.assertEquals(\"karthik\", c1.getName());\n        Assert.assertEquals(\"Noida\", c1.getLocation());\n    }\n\n    /**\n     * Test delete.\n     */\n    private void testDelete()\n    {\n        Customer c = new Customer().find(101);\n        c.delete();\n\n        Customer c1 = new Customer().find(101);\n        Assert.assertNull(c1);\n    }\n\n    /**\n     * Tear down after class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        Customer.unbind();\n    }\n\n}\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/Book.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.dataasobject.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\nimport com.impetus.core.DefaultKunderaEntity;\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Book.\n * \n */\n@Entity\n@IndexCollection(columns = { @Index(name = \"title\"), @Index(name = \"author\"), @Index(name = \"year\"),\n        @Index(name = \"pages\") })\npublic class Book extends DefaultKunderaEntity<Book, Integer>\n{\n    /** The book_id. */\n    @Id\n    @Column(name = \"ID\")\n    private Integer bookId;\n\n    /** The title. */\n    @Column(name = \"TITLE\")\n    private String title;\n\n    /** The author. */\n    @Column(name = \"AUTHOR\")\n    private String author;\n\n    /** The year. */\n    @Column(name = \"YEAR\")\n    private int year;\n\n    /** The pages. */\n    @Column(name = \"PAGES\")\n    private int pages;\n\n    /**\n     * Gets the book id.\n     * \n     * @return the book id\n     */\n    public Integer getBookId()\n    {\n        return bookId;\n    }\n\n    /**\n     * Sets the book id.\n     * \n     * @param bookId\n     *            the new book id\n     */\n    public void setBookId(Integer bookId)\n    {\n        this.bookId = bookId;\n    }\n\n    /**\n     * Gets the title.\n     * \n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * Sets the title.\n     * \n     * @param title\n     *            the new title\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * Gets the author.\n     * \n     * @return the author\n     */\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    /**\n     * Sets the author.\n     * \n     * @param author\n     *            the new author\n     */\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    /**\n     * Gets the year.\n     * \n     * @return the year\n     */\n    public int getYear()\n    {\n        return year;\n    }\n\n    /**\n     * Sets the year.\n     * \n     * @param year\n     *            the new year\n     */\n    public void setYear(int year)\n    {\n        this.year = year;\n    }\n\n    /**\n     * Gets the pages.\n     * \n     * @return the pages\n     */\n    public int getPages()\n    {\n        return pages;\n    }\n\n    /**\n     * Sets the pages.\n     * \n     * @param pages\n     *            the new pages\n     */\n    public void setPages(int pages)\n    {\n        this.pages = pages;\n    }\n\n}\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/Customer.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.dataasobject.entities;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\nimport com.impetus.core.DefaultKunderaEntity;\n\n/**\n * The Class Customer.\n */\n@Entity\npublic class Customer extends DefaultKunderaEntity<Customer, Integer>\n{\n\n    /** The customer id. */\n    @Id\n    private int customerId;\n\n    /** The name. */\n    private String name;\n\n    /** The location. */\n    private String location;\n\n    /**\n     * Gets the customer id.\n     *\n     * @return the customer id\n     */\n    public int getCustomerId()\n    {\n        return customerId;\n    }\n\n    /**\n     * Sets the customer id.\n     *\n     * @param customerId\n     *            the new customer id\n     */\n    public void setCustomerId(int customerId)\n    {\n        this.customerId = customerId;\n    }\n\n    /**\n     * Gets the name.\n     *\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     *\n     * @param name\n     *            the new name\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * Gets the location.\n     *\n     * @return the location\n     */\n    public String getLocation()\n    {\n        return location;\n    }\n\n    /**\n     * Sets the location.\n     *\n     * @param location\n     *            the new location\n     */\n    public void setLocation(String location)\n    {\n        this.location = location;\n    }\n\n}\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/Department.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.dataasobject.entities;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\nimport com.impetus.core.DefaultKunderaEntity;\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Department.\n */\n@Entity\n@IndexCollection(columns = { @Index(name = \"employeeId\") })\npublic class Department extends DefaultKunderaEntity<Department, Long>\n{\n\n    /** The dept id. */\n    @Id\n    private Long deptId;\n\n    /** The employee id. */\n    private Long employeeId;\n\n    /** The department name. */\n    private String departmentName;\n\n    /**\n     * Gets the dept id.\n     *\n     * @return the dept id\n     */\n    public Long getDeptId()\n    {\n        return deptId;\n    }\n\n    /**\n     * Sets the dept id.\n     *\n     * @param deptId\n     *            the new dept id\n     */\n    public void setDeptId(Long deptId)\n    {\n        this.deptId = deptId;\n    }\n\n    /**\n     * Gets the employee id.\n     *\n     * @return the employee id\n     */\n    public Long getEmployeeId()\n    {\n        return employeeId;\n    }\n\n    /**\n     * Sets the employee id.\n     *\n     * @param employeeId\n     *            the new employee id\n     */\n    public void setEmployeeId(Long employeeId)\n    {\n        this.employeeId = employeeId;\n    }\n\n    /**\n     * Gets the department name.\n     *\n     * @return the department name\n     */\n    public String getDepartmentName()\n    {\n        return departmentName;\n    }\n\n    /**\n     * Sets the department name.\n     *\n     * @param departmentName\n     *            the new department name\n     */\n    public void setDepartmentName(String departmentName)\n    {\n        this.departmentName = departmentName;\n    }\n\n}\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/DepartmentKudu.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.dataasobject.entities;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\nimport com.impetus.core.DefaultKunderaEntity;\n\n/**\n * The Class DepartmentKudu.\n */\n@Entity\npublic class DepartmentKudu extends DefaultKunderaEntity<DepartmentKudu, Long>\n{\n\n    /** The dept id. */\n    @Id\n    private Long deptId;\n\n    /** The employee id. */\n    private Long employeeId;\n\n    /** The department name. */\n    private String departmentName;\n\n    /**\n     * Gets the dept id.\n     *\n     * @return the dept id\n     */\n    public Long getDeptId()\n    {\n        return deptId;\n    }\n\n    /**\n     * Sets the dept id.\n     *\n     * @param deptId\n     *            the new dept id\n     */\n    public void setDeptId(Long deptId)\n    {\n        this.deptId = deptId;\n    }\n\n    /**\n     * Gets the employee id.\n     *\n     * @return the employee id\n     */\n    public Long getEmployeeId()\n    {\n        return employeeId;\n    }\n\n    /**\n     * Sets the employee id.\n     *\n     * @param employeeId\n     *            the new employee id\n     */\n    public void setEmployeeId(Long employeeId)\n    {\n        this.employeeId = employeeId;\n    }\n\n    /**\n     * Gets the department name.\n     *\n     * @return the department name\n     */\n    public String getDepartmentName()\n    {\n        return departmentName;\n    }\n\n    /**\n     * Sets the department name.\n     *\n     * @param departmentName\n     *            the new department name\n     */\n    public void setDepartmentName(String departmentName)\n    {\n        this.departmentName = departmentName;\n    }\n\n}\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/Employee.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.dataasobject.entities;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\nimport com.impetus.core.DefaultKunderaEntity;\n\n/**\n * The Class Employee.\n */\n@Entity\npublic class Employee extends DefaultKunderaEntity<Employee, Long>\n{\n\n    /** The employee id. */\n    @Id\n    private Long employeeId;\n\n    /** The salary. */\n    private Double salary;\n\n    /** The name. */\n    private String name;\n\n    /**\n     * Gets the emplyoee id.\n     *\n     * @return the emplyoee id\n     */\n    public Long getEmplyoeeId()\n    {\n        return employeeId;\n    }\n\n    /**\n     * Sets the emplyoee id.\n     *\n     * @param emplyoeeId\n     *            the new emplyoee id\n     */\n    public void setEmplyoeeId(Long emplyoeeId)\n    {\n        this.employeeId = emplyoeeId;\n    }\n\n    /**\n     * Gets the salary.\n     *\n     * @return the salary\n     */\n    public Double getSalary()\n    {\n        return salary;\n    }\n\n    /**\n     * Sets the salary.\n     *\n     * @param salary\n     *            the new salary\n     */\n    public void setSalary(Double salary)\n    {\n        this.salary = salary;\n    }\n\n    /**\n     * Gets the name.\n     *\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     *\n     * @param name\n     *            the new name\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/Tweets.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.dataasobject.entities;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\nimport com.impetus.core.DefaultKunderaEntity;\n\n/**\n * The Class Tweets.\n *\n * @author impetus\n * \n *         Tweets entity\n */\n\n@Entity\npublic class Tweets extends DefaultKunderaEntity<Tweets, String>\n{\n\n    /** The tweet id. */\n    @Id\n    @Column(name = \"tweet_id\")\n    private String tweetId;\n\n    /** The body. */\n    @Column(name = \"body\")\n    private String body;\n\n    /** The tweet date. */\n    @Column(name = \"tweeted_at\")\n    @Temporal(TemporalType.DATE)\n    private Date tweetDate;\n\n    /** The videos. */\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"tweet_id\")\n    private Set<Video> videos;\n\n    /**\n     * Instantiates a new tweets.\n     */\n    public Tweets()\n    {\n        // Default constructor.\n    }\n\n    /**\n     * Gets the tweet id.\n     *\n     * @return the tweetId\n     */\n    public String getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * Sets the tweet id.\n     *\n     * @param tweetId\n     *            the tweetId to set\n     */\n    public void setTweetId(String tweetId)\n    {\n        this.tweetId = tweetId;\n    }\n\n    /**\n     * Gets the body.\n     *\n     * @return the body\n     */\n    public String getBody()\n    {\n        return body;\n    }\n\n    /**\n     * Sets the body.\n     *\n     * @param body\n     *            the body to set\n     */\n    public void setBody(String body)\n    {\n        this.body = body;\n    }\n\n    /**\n     * Gets the tweet date.\n     *\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * Sets the tweet date.\n     *\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n    /**\n     * Gets the videos.\n     *\n     * @return the videos\n     */\n    public Set<Video> getVideos()\n    {\n        return videos;\n    }\n\n    /**\n     * Sets the videos.\n     *\n     * @param videos\n     *            the new videos\n     */\n    public void setVideos(Set<Video> videos)\n    {\n        this.videos = videos;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.lang.Object#toString()\n     */\n    @Override\n    public String toString()\n    {\n        return \"Tweets [tweetId=\" + tweetId + \", body=\" + body + \", tweetDate=\" + tweetDate + \", videos=\" + videos\n                + \"]\";\n    }\n\n}\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/User.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.dataasobject.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\n\nimport com.impetus.core.DefaultKunderaEntity;\n\n/**\n * The Class User.\n *\n * @author impetus User entity.\n */\n@Entity\npublic class User extends DefaultKunderaEntity<User, String>\n{\n\n    /** The user id. */\n    @Id\n    @Column(name = \"user_id\")\n    private String userId;\n\n    /** The first name. */\n    @Column(name = \"first_name\")\n    private String firstName;\n\n    /** The last name. */\n    @Column(name = \"last_name\")\n    private String lastName;\n\n    /** The email id. */\n    @Column(name = \"emailId\")\n    private String emailId;\n\n    /** The tweets. */\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"user_id\")\n    private Set<Tweets> tweets;\n\n    /**\n     * Instantiates a new user.\n     */\n    public User()\n    {\n    }\n\n    /**\n     * Gets the user id.\n     *\n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * Sets the user id.\n     *\n     * @param userId\n     *            the userId to set\n     */\n    public void setUserId(String userId)\n    {\n        this.userId = userId;\n    }\n\n    /**\n     * Gets the first name.\n     *\n     * @return the firstName\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * Sets the first name.\n     *\n     * @param firstName\n     *            the firstName to set\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * Gets the last name.\n     *\n     * @return the lastName\n     */\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    /**\n     * Sets the last name.\n     *\n     * @param lastName\n     *            the lastName to set\n     */\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n    /**\n     * Gets the email id.\n     *\n     * @return the emailId\n     */\n    public String getEmailId()\n    {\n        return emailId;\n    }\n\n    /**\n     * Sets the email id.\n     *\n     * @param emailId\n     *            the emailId to set\n     */\n    public void setEmailId(String emailId)\n    {\n        this.emailId = emailId;\n    }\n\n    /**\n     * Gets the tweets.\n     *\n     * @return the tweets\n     */\n    public Set<Tweets> getTweets()\n    {\n        return tweets;\n    }\n\n    /**\n     * Sets the tweets.\n     *\n     * @param tweets\n     *            the tweets to set\n     */\n    public void setTweets(Set<Tweets> tweets)\n    {\n        this.tweets = tweets;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.lang.Object#toString()\n     */\n    @Override\n    public String toString()\n    {\n        return \"User [userId=\" + userId + \", firstName=\" + firstName + \", lastName=\" + lastName + \", emailId=\" + emailId\n                + \", tweets=\" + tweets + \"]\";\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.lang.Object#hashCode()\n     */\n    @Override\n    public int hashCode()\n    {\n        final int prime = 31;\n        int result = 1;\n        result = prime * result + ((userId == null) ? 0 : userId.hashCode());\n        return result;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.lang.Object#equals(java.lang.Object)\n     */\n    @Override\n    public boolean equals(Object obj)\n    {\n        if (this == obj)\n            return true;\n        if (obj == null)\n            return false;\n        if (getClass() != obj.getClass())\n            return false;\n        User other = (User) obj;\n        if (userId == null)\n        {\n            if (other.userId != null)\n                return false;\n        }\n        else if (!userId.equals(other.userId))\n            return false;\n        return true;\n    }\n\n}\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/entities/Video.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.dataasobject.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\nimport com.impetus.core.DefaultKunderaEntity;\n\n/**\n * The Class Video.\n *\n * @author impetus\n * \n *         Video entity\n */\n@Entity\npublic class Video extends DefaultKunderaEntity<Video, String>\n{\n\n    /** The video id. */\n    @Id\n    @Column(name = \"video_id\")\n    private String videoId;\n\n    /** The video name. */\n    @Column(name = \"video_name\")\n    private String videoName;\n\n    /** The video provider. */\n    @Column(name = \"video_provider\")\n    private String videoProvider;\n\n    /**\n     * Instantiates a new video.\n     */\n    public Video()\n    {\n        // Default constructor.\n    }\n\n    /**\n     * Gets the video id.\n     *\n     * @return the video id\n     */\n    public String getVideoId()\n    {\n        return videoId;\n    }\n\n    /**\n     * Sets the video id.\n     *\n     * @param videoId\n     *            the new video id\n     */\n    public void setVideoId(String videoId)\n    {\n        this.videoId = videoId;\n    }\n\n    /**\n     * Gets the video name.\n     *\n     * @return the video name\n     */\n    public String getVideoName()\n    {\n        return videoName;\n    }\n\n    /**\n     * Sets the video name.\n     *\n     * @param videoName\n     *            the new video name\n     */\n    public void setVideoName(String videoName)\n    {\n        this.videoName = videoName;\n    }\n\n    /**\n     * Gets the video provider.\n     *\n     * @return the video provider\n     */\n    public String getVideoProvider()\n    {\n        return videoProvider;\n    }\n\n    /**\n     * Sets the video provider.\n     *\n     * @param videoProvider\n     *            the new video provider\n     */\n    public void setVideoProvider(String videoProvider)\n    {\n        this.videoProvider = videoProvider;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.lang.Object#toString()\n     */\n    @Override\n    public String toString()\n    {\n        return \"Video [videoId=\" + videoId + \", videoName=\" + videoName + \", videoProvider=\" + videoProvider + \"]\";\n    }\n\n}\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/polyglot/PolyglotTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.dataasobject.polyglot;\n\nimport java.util.Date;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.dataasobject.entities.Tweets;\nimport com.impetus.kundera.dataasobject.entities.User;\nimport com.impetus.kundera.dataasobject.entities.Video;\n\nimport junit.framework.Assert;\n\n/**\n * The Class PolyglotTest.\n */\npublic class PolyglotTest\n{\n\n    /**\n     * Sets the up before class.\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass()\n    {\n        User.bind(\"client-polyglot-properties.json\", User.class);\n    }\n\n    /**\n     * Test polyglot.\n     */\n    @Test\n    public void testPolyglot()\n    {\n        testInsert();\n        testQuery();\n        testDelete();\n    }\n\n    /**\n     * Test insert.\n     */\n    private void testInsert()\n    {\n        User user = new User();\n        user.setFirstName(\"Devender\");\n        user.setLastName(\"Yadav\");\n        user.setUserId(\"u-101\");\n        user.setEmailId(\"devender.yadav@impetus.co.in\");\n\n        Set<Tweets> tweetSet = new HashSet<>();\n\n        Tweets tweet1 = new Tweets();\n        tweet1.setTweetId(\"t-101\");\n        tweet1.setBody(\"this is tweet 1\");\n        tweet1.setTweetDate(new Date());\n\n        Set<Video> videoSet = new HashSet<>();\n\n        Video video1 = new Video();\n        video1.setVideoId(\"v-101\");\n        video1.setVideoName(\"movie\");\n        video1.setVideoProvider(\"netflix\");\n\n        videoSet.add(video1);\n        tweet1.setVideos(videoSet);\n        tweetSet.add(tweet1);\n        user.setTweets(tweetSet);\n\n        user.save();\n\n        User u = new User().find(\"u-101\");\n        validateUser(u);\n    }\n\n    /**\n     * Test query.\n     */\n    private void testQuery()\n    {\n        List<User> users = new User().query(\"select u from User u\");\n        Assert.assertEquals(1, users.size());\n        User u = users.get(0);\n        validateUser(u);\n\n        users = null;\n\n        users = new User().query(\"select u from User u where u.emailId = 'devender.yadav@impetus.co.in'\");\n        validateUser(u);\n    }\n\n    /**\n     * Test delete.\n     */\n    private void testDelete()\n    {\n        User u = new User().find(\"u-101\");\n        u.delete();\n\n        User u1 = new User().find(\"u-101\");\n        Assert.assertNull(u1);\n    }\n\n    /**\n     * Tear down after class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        User.unbind();\n    }\n\n    /**\n     * Validate user.\n     *\n     * @param u\n     *            the u\n     */\n    private void validateUser(User u)\n    {\n        Assert.assertEquals(\"Devender\", u.getFirstName());\n        Assert.assertEquals(\"Yadav\", u.getLastName());\n        Assert.assertEquals(\"u-101\", u.getUserId());\n        Assert.assertEquals(\"devender.yadav@impetus.co.in\", u.getEmailId());\n\n        Set<Tweets> tweets = u.getTweets();\n        Assert.assertEquals(1, tweets.size());\n\n        Tweets t = tweets.iterator().next();\n        Assert.assertEquals(\"t-101\", t.getTweetId());\n        Assert.assertEquals(\"this is tweet 1\", t.getBody());\n\n        Set<Video> videos = t.getVideos();\n        Assert.assertEquals(1, videos.size());\n\n        Video v = videos.iterator().next();\n        Assert.assertEquals(\"v-101\", v.getVideoId());\n        Assert.assertEquals(\"movie\", v.getVideoName());\n        Assert.assertEquals(\"netflix\", v.getVideoProvider());\n    }\n}\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/query/BookBaseTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.dataasobject.query;\n\nimport java.util.List;\n\nimport com.impetus.kundera.dataasobject.entities.Book;\n\nimport junit.framework.Assert;\n\n/**\n * The Class BookBaseTest.\n * \n * @author Pragalbh Garg\n */\npublic abstract class BookBaseTest\n{\n\n    /** The t. */\n    protected boolean T = true;\n\n    /** The f. */\n    protected boolean F = false;\n\n    /**\n     * Validate book1.\n     * \n     * @param book\n     *            the book\n     */\n    protected void validateBook1(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(Integer.valueOf(1), book.getBookId());\n        Assert.assertEquals(\"book1\", book.getTitle());\n        Assert.assertEquals(\"author1\", book.getAuthor());\n        Assert.assertEquals(2000, book.getYear());\n        Assert.assertEquals(100, book.getPages());\n    }\n\n    /**\n     * Validate book2.\n     * \n     * @param book\n     *            the book\n     */\n    protected void validateBook2(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(Integer.valueOf(2), book.getBookId());\n        Assert.assertEquals(\"book2\", book.getTitle());\n        Assert.assertEquals(\"author2\", book.getAuthor());\n        Assert.assertEquals(2005, book.getYear());\n        Assert.assertEquals(200, book.getPages());\n    }\n\n    /**\n     * Validate book3.\n     * \n     * @param book\n     *            the book\n     */\n    protected void validateBook3(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(Integer.valueOf(3), book.getBookId());\n        Assert.assertEquals(\"book3\", book.getTitle());\n        Assert.assertEquals(\"author3\", book.getAuthor());\n        Assert.assertEquals(2010, book.getYear());\n        Assert.assertEquals(300, book.getPages());\n    }\n\n    /**\n     * Validate book4.\n     * \n     * @param book\n     *            the book\n     */\n    protected void validateBook4(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(Integer.valueOf(4), book.getBookId());\n        Assert.assertEquals(\"book4\", book.getTitle());\n        Assert.assertEquals(\"author1\", book.getAuthor());\n        Assert.assertEquals(2015, book.getYear());\n        Assert.assertEquals(400, book.getPages());\n    }\n\n    /**\n     * Assert results.\n     * \n     * @param results\n     *            the results\n     * @param foundBook1\n     *            the found book1\n     * @param foundBook2\n     *            the found book2\n     * @param foundBook3\n     *            the found book3\n     * @param foundBook4\n     *            the found book4\n     */\n    protected void assertResults(List<Book> results, boolean foundBook1, boolean foundBook2, boolean foundBook3,\n            boolean foundBook4)\n    {\n        for (Book book : (List<Book>) results)\n        {\n            switch (book.getBookId())\n            {\n            case 1:\n                if (foundBook1)\n                    validateBook1(book);\n                else\n                    Assert.fail();\n                break;\n            case 2:\n                if (foundBook2)\n                    validateBook2(book);\n                else\n                    Assert.fail();\n                break;\n            case 3:\n                if (foundBook3)\n                    validateBook3(book);\n                else\n                    Assert.fail();\n                break;\n            case 4:\n                if (foundBook4)\n                    validateBook4(book);\n                else\n                    Assert.fail();\n                break;\n            }\n        }\n    }\n\n    /**\n     * Assert deleted.\n     * \n     * @param foundBook1\n     *            the b1\n     * @param foundBook2\n     *            the b2\n     * @param foundBook3\n     *            the b3\n     * @param foundBook4\n     *            the b4\n     */\n    protected void assertDeleted(Boolean foundBook1, Boolean foundBook2, Boolean foundBook3, Boolean foundBook4)\n    {\n        Book book1 = new Book().find(1);\n        Book book2 = new Book().find(2);\n        Book book3 = new Book().find(3);\n        Book book4 = new Book().find(4);\n        if (foundBook1)\n        {\n            Assert.assertNull(book1);\n        }\n        else\n        {\n            Assert.assertNotNull(book1);\n        }\n        if (foundBook2)\n        {\n            Assert.assertNull(book2);\n        }\n        else\n        {\n            Assert.assertNotNull(book2);\n        }\n        if (foundBook3)\n        {\n            Assert.assertNull(book3);\n        }\n        else\n        {\n            Assert.assertNotNull(book3);\n        }\n        if (foundBook4)\n        {\n            Assert.assertNull(book4);\n        }\n        else\n        {\n            Assert.assertNotNull(book4);\n        }\n    }\n}\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/java/com/impetus/kundera/dataasobject/query/CassandraQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.dataasobject.query;\n\nimport java.util.List;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.core.QueryType;\nimport com.impetus.kundera.dataasobject.entities.Book;\n\nimport junit.framework.Assert;\n\n/**\n * The Class CassandraQueryTest.\n * \n * @author Devender Yadav\n */\npublic class CassandraQueryTest extends BookBaseTest\n{\n\n    /**\n     * Sets the up before class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        Book.bind(\"client-properties.json\", Book.class);\n    }\n\n    /**\n     * Sets the up.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        persistBooks();\n    }\n\n    /**\n     * Test select queries.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testSelectQueries() throws Exception\n    {\n        testSelectAll();\n        testSelectOnId();\n        testSelectWithWhereClause();\n        testSelectFields();\n    }\n\n    /**\n     * Test native queries.\n     */\n    @Test\n    public void testNativeQueries()\n    {\n        List results = new Book().query(\"select \\\"TITLE\\\" from \\\"Book\\\"\", QueryType.NATIVE);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n\n        results = new Book().query(\"select \\\"AUTHOR\\\" from \\\"Book\\\" where token(\\\"ID\\\") = token(1)\", QueryType.NATIVE);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"author1\", ((Book) results.get(0)).getAuthor());\n    }\n\n    /**\n     * Test select all.\n     */\n    private void testSelectAll()\n    {\n        List<Book> results = new Book().query(\"select b from Book b\");\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        Assert.assertTrue(Book.class.isAssignableFrom(results.get(0).getClass()));\n        assertResults(results, T, T, T, T);\n    }\n\n    /**\n     * Test select on id.\n     */\n    private void testSelectOnId()\n    {\n        List<Book> results = new Book().query(\"select b from Book b where b.bookId=1\");\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        validateBook1(results.get(0));\n\n        results = new Book().query(\"select b from Book b where b.bookId in (3,4,5,6)\");\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, F, F, T, T);\n\n    }\n\n    /**\n     * Test select with where clause.\n     */\n    private void testSelectWithWhereClause()\n    {\n        List<Book> results = new Book().query(\"select b from Book b where b.title = 'book1'\");\n        Assert.assertNotNull(results);\n        validateBook1(results.get(0));\n\n        results = new Book().query(\"select b from Book b where b.author = 'author2'\");\n        Assert.assertNotNull(results);\n        validateBook2(results.get(0));\n\n        results = new Book().query(\"select b from Book b where b.year = 2005\");\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        validateBook2(results.get(0));\n\n    }\n\n    /**\n     * Test select fields.\n     */\n    private void testSelectFields()\n    {\n        List results = new Book().query(\"select b.title from Book b\");\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n\n        results = new Book().query(\"select b.author from Book b where b.bookId=1\");\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"author1\", ((Book) results.get(0)).getAuthor());\n\n        results = new Book().query(\"select b.title from Book b where b.bookId in (3,4,5,6)\");\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n    }\n\n    /**\n     * Tear down.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        deleteBooks();\n    }\n\n    /**\n     * Tear down after class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        Book.unbind();\n    }\n\n    /**\n     * Persist books.\n     */\n    private void persistBooks()\n    {\n        Book book1 = prepareData(1, \"book1\", \"author1\", 2000, 100);\n        Book book2 = prepareData(2, \"book2\", \"author2\", 2005, 200);\n        Book book3 = prepareData(3, \"book3\", \"author3\", 2010, 300);\n        Book book4 = prepareData(4, \"book4\", \"author1\", 2015, 400);\n        book1.save();\n        book2.save();\n        book3.save();\n        book4.save();\n    }\n\n    /**\n     * Delete books.\n     */\n    private void deleteBooks()\n    {\n        Book b1 = new Book().find(1);\n        b1.delete();\n        Book b2 = new Book().find(2);\n        b2.delete();\n\n        Book b3 = new Book().find(3);\n        b3.delete();\n\n        Book b4 = new Book().find(4);\n        b4.delete();\n    }\n\n    /**\n     * Prepare data.\n     *\n     * @param bookId\n     *            the book id\n     * @param title\n     *            the title\n     * @param author\n     *            the author\n     * @param year\n     *            the year\n     * @param pages\n     *            the pages\n     * @return the book\n     */\n    private Book prepareData(int bookId, String title, String author, int year, int pages)\n    {\n        Book book = new Book();\n        book.setBookId(bookId);\n        book.setTitle(title);\n        book.setAuthor(author);\n        book.setYear(year);\n        book.setPages(pages);\n        return book;\n    }\n\n}\n"
  },
  {
    "path": "examples/data-as-object-example/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\n\t<!-- Persistence Units for user-tweets application -->\n\n\t<persistence-unit name=\"twirdbms\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.dataasobject.entities.User</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.rdbms.RDBMSClientFactory\" />\n\t\t\t<property name=\"hibernate.hbm2ddl.auto\" value=\"create\" />\n\t\t\t<property name=\"hibernate.show_sql\" value=\"false\" />\n\t\t\t<property name=\"hibernate.format_sql\" value=\"false\" />\n\t\t\t<property name=\"dialect\"\n\t\t\t\tvalue=\"org.openmeetings.app.hibernate.utils.MySQL5MyISAMDialect\" />\n\t\t\t<property name=\"hibernate.dialect\" value=\"org.hibernate.dialect.MySQL5Dialect\" />\n\t\t\t<property name=\"hibernate.connection.driver_class\" value=\"com.mysql.jdbc.Driver\" />\n\t\t\t<property name=\"hibernate.connection.url\" value=\"jdbc:mysql://localhost:3306/kvapps\" />\n\t\t\t<property name=\"hibernate.connection.username\" value=\"root\" />\n\t\t\t<property name=\"hibernate.connection.password\" value=\"root\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<!-- Persistence unit for mongo -->\n\t<persistence-unit name=\"twingo\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.dataasobject.entities.Tweets</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"kvapps\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<!-- Persistence unit for cassandra -->\n\t<persistence-unit name=\"twissandra\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.dataasobject.entities.Video</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"kvapps\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"cql.version\" value=\"3.0.0\"></property>\n\t\t</properties>\n\t</persistence-unit>\n</persistence>"
  },
  {
    "path": "examples/data-as-object-example/src/test/resources/client-polyglot-properties.json",
    "content": " {\n \"com.impetus.kundera.dataasobject.entities.User\": {\n\t \"kundera.pu\":\"twirdbms\"\n  },\n   \"com.impetus.kundera.dataasobject.entities.Tweets\": {\n\t \"kundera.pu\":\"twingo\"\n  },\n   \"com.impetus.kundera.dataasobject.entities.Video\": {\n\t \"kundera.pu\":\"twissandra\"\n  }\n  }"
  },
  {
    "path": "examples/data-as-object-example/src/test/resources/client-properties-all.json",
    "content": "{\n  \"all\": {\n    \"kundera.nodes\": \"localhost\",\n    \"kundera.port\": \"9160\",\n    \"kundera.client\": \"cassandra\",\n    \"kundera.keyspace\": \"DAOTest\",\n    \"kundera.ddl.auto.prepare\": \"update\",\n    \"cql.version\": \"3.0.0\",\n    \"kundera.client.lookup.class\": \"com.impetus.client.cassandra.thrift.ThriftClientFactory\"\n  }\n}"
  },
  {
    "path": "examples/data-as-object-example/src/test/resources/client-properties.json",
    "content": "{\n  \"com.impetus.kundera.dataasobject.entities.Employee,com.impetus.kundera.dataasobject.entities.Department\": {\n    \"kundera.nodes\": \"localhost\",\n    \"kundera.port\": \"9160\",\n    \"kundera.client\": \"cassandra\",\n    \"kundera.keyspace\": \"DAOTest\",\n    \"kundera.ddl.auto.prepare\": \"update\",\n    \"cql.version\": \"3.0.0\",\n    \"kundera.client.lookup.class\": \"com.impetus.client.cassandra.thrift.ThriftClientFactory\"\n  },\n  \"com.impetus.kundera.dataasobject.entities.Book\": {\n    \"kundera.nodes\": \"localhost\",\n    \"kundera.port\": \"9160\",\n    \"kundera.client\": \"cassandra\",\n    \"kundera.keyspace\": \"DAOTest\",\n    \"kundera.ddl.auto.prepare\": \"update\",\n    \"cql.version\": \"3.0.0\",\n    \"kundera.client.lookup.class\": \"com.impetus.client.cassandra.thrift.ThriftClientFactory\"\n  },\n  \"com.impetus.kundera.dataasobject.entities.Customer\": {\n    \"kundera.nodes\": \"quickstart.cloudera\",\n    \"kundera.port\": \"7051\",\n    \"kundera.client\": \"kudu\",\n    \"kundera.keyspace\": \"DAOTest\",\n    \"kundera.ddl.auto.prepare\": \"create\",\n    \"kundera.client.lookup.class\": \"com.impetus.client.kudu.KuduDBClientFactory\"\n  },\n  \"com.impetus.kundera.dataasobject.entities.DepartmentKudu\": {\n    \"kundera.nodes\": \"quickstart.cloudera\",\n    \"kundera.port\": \"7051\",\n    \"kundera.client\": \"kudu\",\n    \"kundera.keyspace\": \"DAOTest\",\n    \"kundera.ddl.auto.prepare\": \"create\",\n    \"kundera.client.lookup.class\": \"com.impetus.client.kudu.KuduDBClientFactory\"\n  }\n}"
  },
  {
    "path": "examples/polyglot/kvapps/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<groupId>com.impetus</groupId>\n\t<artifactId>kvapps</artifactId>\n\t<version>1.0</version>\n\t<packaging>jar</packaging>\n\n\t<name>kvapps</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t\t<kundera.version>3.3-SNAPSHOT</kundera.version>\n\t</properties>\n\t\n\t<repositories>\n\t\t<repository>\n\t\t\t<id>sonatype-nexus</id>\n\t\t\t<name>Kundera Public Repository</name>\n\t\t\t<url>https://oss.sonatype.org/content/repositories/releases</url>\n\t\t\t<releases>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</releases>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>false</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>kundera-missing</id>\n\t\t\t<name>Kundera Public Missing Resources Repository</name>\n\t\t\t<url>http://kundera.googlecode.com/svn/maven2/maven-missing-resources</url>\n\t\t\t<releases>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</releases>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t</repositories>\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-rdbms</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-mongo</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>mysql</groupId>\n\t\t\t<artifactId>mysql-connector-java</artifactId>\n\t\t\t<version>5.1.9</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.5</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.poi</groupId>\n\t\t\t<artifactId>poi</artifactId>\n\t\t\t<version>3.9</version>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<extensions>\n\t\t\t<extension>\n\t\t\t\t<groupId>org.apache.maven.wagon</groupId>\n\t\t\t\t<artifactId>wagon-webdav</artifactId>\n\t\t\t\t<version>1.0-beta-2</version>\n\t\t\t</extension>\n\t\t</extensions>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-clean-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<filesets>\n\t\t\t\t\t\t<fileset>\n\t\t\t\t\t\t\t<directory>${basedir}</directory>\n\t\t\t\t\t\t\t<includes>\n\t\t\t\t\t\t\t\t<include>cobertura.ser</include>\n\t\t\t\t\t\t\t</includes>\n\t\t\t\t\t\t</fileset>\n\t\t\t\t\t</filesets>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n\n</project>\n"
  },
  {
    "path": "examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/entities/PersonalDetail.java",
    "content": "/*\r\n * Copyright 2011 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kvapps.entities;\r\n\r\nimport java.io.Serializable;\r\nimport java.util.UUID;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\n/**\r\n * Entity class for user's personal details\r\n * \r\n * @author impetus\r\n */\r\n\r\n@Embeddable\r\npublic class PersonalDetail {\r\n\t@Column(name = \"personal_detail_id\")\r\n\tprivate String personalDetailId;\r\n\r\n\t@Column(name = \"name\")\r\n\tprivate String name;\r\n\r\n\t@Column(name = \"password\")\r\n\tprivate String password;\r\n\r\n\t@Column(name = \"rel_status\")\r\n\tprivate String relationshipStatus;\r\n\r\n\tpublic PersonalDetail() {\r\n\r\n\t}\r\n\r\n\tpublic PersonalDetail(String name, String password,\r\n\t\t\tString relationshipStatus) {\r\n\t\tsetPersonalDetailId(UUID.randomUUID().toString());\r\n\t\tsetName(name);\r\n\t\tsetPassword(password);\r\n\t\tsetRelationshipStatus(relationshipStatus);\r\n\t}\r\n\r\n\t/**\r\n\t * @return the personalDetailId\r\n\t */\r\n\tpublic String getPersonalDetailId() {\r\n\t\treturn personalDetailId;\r\n\t}\r\n\r\n\t/**\r\n\t * @param personalDetailId\r\n\t *            the personalDetailId to set\r\n\t */\r\n\tpublic void setPersonalDetailId(String personalDetailId) {\r\n\t\tthis.personalDetailId = personalDetailId;\r\n\t}\r\n\r\n\t/**\r\n\t * @return the name\r\n\t */\r\n\tpublic String getName() {\r\n\t\treturn name;\r\n\t}\r\n\r\n\t/**\r\n\t * @param name\r\n\t *            the name to set\r\n\t */\r\n\tpublic void setName(String name) {\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n\t/**\r\n\t * @return the password\r\n\t */\r\n\tpublic String getPassword() {\r\n\t\treturn password;\r\n\t}\r\n\r\n\t/**\r\n\t * @param password\r\n\t *            the password to set\r\n\t */\r\n\tpublic void setPassword(String password) {\r\n\t\tthis.password = password;\r\n\t}\r\n\r\n\t/**\r\n\t * @return the relationshipStatus\r\n\t */\r\n\tpublic String getRelationshipStatus() {\r\n\t\treturn relationshipStatus;\r\n\t}\r\n\r\n\t/**\r\n\t * @param relationshipStatus\r\n\t *            the relationshipStatus to set\r\n\t */\r\n\tpublic void setRelationshipStatus(String relationshipStatus) {\r\n\t\tthis.relationshipStatus = relationshipStatus;\r\n\t}\r\n\r\n\tpublic PersonalDetail(String personalDetailId, String name,\r\n\t\t\tString password, String relationshipStatus) {\r\n\t\tsuper();\r\n\t\tthis.personalDetailId = personalDetailId;\r\n\t\tthis.name = name;\r\n\t\tthis.password = password;\r\n\t\tthis.relationshipStatus = relationshipStatus;\r\n\t}\r\n\r\n}\r\n"
  },
  {
    "path": "examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/entities/Tweets.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kvapps.entities;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author impetus\n * \n *         Tweets entity\n */\n\n@Entity\n@Table(name = \"tweets\")\n@IndexCollection(columns = { @Index(name = \"body\"), @Index(name = \"tweeted_at\") })\npublic class Tweets\n{\n\n    @Id\n    @Column(name = \"tweet_id\")\n    private String tweetId;\n\n    @Column(name = \"body\")\n    private String body;\n\n    @Column(name = \"tweeted_at\")\n    @Temporal(TemporalType.DATE)\n    private Date tweetDate;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"tweet_id\")\n    private Set<Video> videos;\n\n    public Tweets()\n    {\n        // Default constructor.\n    }\n\n    /**\n     * @return the tweetId\n     */\n    public String getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * @param tweetId\n     *            the tweetId to set\n     */\n    public void setTweetId(String tweetId)\n    {\n        this.tweetId = tweetId;\n    }\n\n    /**\n     * @return the body\n     */\n    public String getBody()\n    {\n        return body;\n    }\n\n    /**\n     * @param body\n     *            the body to set\n     */\n    public void setBody(String body)\n    {\n        this.body = body;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n    public Set<Video> getVideos()\n    {\n        return videos;\n    }\n\n    public void setVideos(Set<Video> videos)\n    {\n        this.videos = videos;\n    }\n\n    @Override\n    public String toString()\n    {\n        return \"Tweets [tweetId=\" + tweetId + \", body=\" + body + \", tweetDate=\" + tweetDate + \", videos=\" + videos\n                + \"]\";\n    }\n\n}\n"
  },
  {
    "path": "examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/entities/User.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kvapps.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author impetus\n *  User entity.\n */\n@Entity\n@Table(name = \"User\")\n@IndexCollection(columns = { @Index(name = \"emailId\") })\npublic class User {\n\n\t@Id\n\t@Column(name = \"user_id\")\n\tprivate String userId;\n\n\t@Column(name = \"first_name\")\n\tprivate String firstName;\n\n\t@Column(name = \"last_name\")\n\tprivate String lastName;\n\n\t@Column(name = \"emailId\")\n\tprivate String emailId;\n\n\t@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n\t@JoinColumn(name = \"user_id\")\n\tprivate Set<Tweets> tweets;\n\n\t@Embedded\n\tprivate PersonalDetail personalDetail;\n\n\tpublic User() {\n\t\t// Default constructor.\n\t}\n\n\t/**\n\t * @return the userId\n\t */\n\tpublic String getUserId() {\n\t\treturn userId;\n\t}\n\n\t/**\n\t * @param userId\n\t *            the userId to set\n\t */\n\tpublic void setUserId(String userId) {\n\t\tthis.userId = userId;\n\t}\n\n\t/**\n\t * @return the firstName\n\t */\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\n\t/**\n\t * @param firstName\n\t *            the firstName to set\n\t */\n\tpublic void setFirstName(String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\n\t/**\n\t * @return the lastName\n\t */\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\n\t/**\n\t * @param lastName\n\t *            the lastName to set\n\t */\n\tpublic void setLastName(String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\n\t/**\n\t * @return the emailId\n\t */\n\tpublic String getEmailId() {\n\t\treturn emailId;\n\t}\n\n\t/**\n\t * @param emailId\n\t *            the emailId to set\n\t */\n\tpublic void setEmailId(String emailId) {\n\t\tthis.emailId = emailId;\n\t}\n\n\t/**\n\t * @return the tweets\n\t */\n\tpublic Set<Tweets> getTweets() {\n\t\treturn tweets;\n\t}\n\n\t/**\n\t * @param tweets\n\t *            the tweets to set\n\t */\n\tpublic void setTweets(Set<Tweets> tweets) {\n\t\tthis.tweets = tweets;\n\t}\n\n\tpublic PersonalDetail getPersonalDetail() {\n\t\treturn personalDetail;\n\t}\n\n\tpublic void setPersonalDetail(PersonalDetail personalDetail) {\n\t\tthis.personalDetail = personalDetail;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"User [userId=\" + userId + \", firstName=\" + firstName\n\t\t\t\t+ \", lastName=\" + lastName + \", emailId=\" + emailId\n\t\t\t\t+ \", tweets=\" + tweets + \", personalDetail=\" + personalDetail\n\t\t\t\t+ \"]\";\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((userId == null) ? 0 : userId.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tUser other = (User) obj;\n\t\tif (userId == null) {\n\t\t\tif (other.userId != null)\n\t\t\t\treturn false;\n\t\t} else if (!userId.equals(other.userId))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n}\n"
  },
  {
    "path": "examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/entities/Video.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kvapps.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author impetus\n * \n *  Video entity\n */\n@Entity\n@Table(name = \"video\")\npublic class Video {\n\n\t@Id\n\t@Column(name = \"video_id\")\n\tprivate String videoId;\n\n\t@Column(name = \"video_name\")\n\tprivate String videoName;\n\n\t@Column(name = \"video_provider\")\n\tprivate String videoProvider;\n\n\tpublic Video() {\n\t\t// Default constructor.\n\t}\n\n\tpublic String getVideoId() {\n\t\treturn videoId;\n\t}\n\n\tpublic void setVideoId(String videoId) {\n\t\tthis.videoId = videoId;\n\t}\n\n\tpublic String getVideoName() {\n\t\treturn videoName;\n\t}\n\n\tpublic void setVideoName(String videoName) {\n\t\tthis.videoName = videoName;\n\t}\n\n\tpublic String getVideoProvider() {\n\t\treturn videoProvider;\n\t}\n\n\tpublic void setVideoProvider(String videoProvider) {\n\t\tthis.videoProvider = videoProvider;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Video [videoId=\" + videoId + \", videoName=\" + videoName\n\t\t\t\t+ \", videoProvider=\" + videoProvider + \"]\";\n\t}\n\n}\n"
  },
  {
    "path": "examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/runner/AppRunner.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kvapps.runner;\n\n\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\n\nimport com.impetus.kvapps.entities.User;\n\n/**\n * @author impetus\n * \n * Sample Application runner. Application demonstrates:\n * <li> poly glot persistence, where user information {@link User} is getting persisted into mysql and corresponding tweets into Cassandra.</li>\n * <li> Fetch user(alongwith tweets) in polyglot way </li>\n * <li> Fetch tweets using native query support </li> \n * <li> Since {kundera.ddl.auto.prepare} is set to \"create\"(Please refer src/main/resources/persistence.xml). \n * hence schema will be automatically managed by Kundera itself.</li>\n * \n * Also, application takes path to excel data file as an input arguments.\n */\npublic class AppRunner\n{\n\n    /** the log used by this class. */\n    private static Log logger = LogFactory.getLog(AppRunner.class);\n\n    /**\n     * main runner method\n     * @param args takes excel data file as input argument args[0].\n     */\n    public static void main(String[] args)\n    {\n    \t\n    \t// Override CQL version while instantiating entity manager factory.\n\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"twissandra,twingo,twirdbms\");\n        EntityManager em = emf.createEntityManager();\n\n        try\n        {\n        \t\n        //populate user set from excel sheet.\n        Set<User> users = UserBroker.brokeUserList(args[0]);\n\n        for (Iterator<User> iterator = users.iterator(); iterator.hasNext();)\n        {\n            User user = (User) iterator.next();\n\n            // on Persist\n            ExecutorService.onPersist(em, user);\n            \n                 \n            // on find by id.\n            ExecutorService.findByKey(em,\"BigDataUser\");\n            \n            List<User> fetchedUsers = ExecutorService.onQueryByEmail(em, user);\n            \n            if (fetchedUsers != null && fetchedUsers.size() > 0)\n            {\n                logger.info(user.toString());\n            }\n\n            logger.info(\"\");\n            System.out.println(\"#######################Querying##########################################\");\n            logger.info(\"\");\n            logger.info(\"\");\n\n        }\n\n        // Execute wild search query.\n        String query = \"Select u from User u\";\n        logger.info(query);\n        ExecutorService.findByQuery(em, query);\n\n        // // Execute native CQL. Fetch tweets for given user.\n        logger.info(\"\");\n        System.out.println(\"#######################Querying##########################################\");\n        logger.info(\"\");\n        logger.info(\"\");\n\n        query = \"Select * from tweets where user_id='RDBMSUser'\";\n        logger.info(query);\n        ExecutorService.findByNativeQuery(em,query);\n    \t} finally\n    \t{\n    \t\tonDestroyDBResources(emf, em);\n    \t}\n    }\n\n\t/**\n\t * After successful processing close entity manager and it's factory instance.\n\t * \n\t * @param emf          entity manager factory instance.\n\t * @param em           entity manager instance\n\t */\n\tprivate static void onDestroyDBResources(EntityManagerFactory emf,EntityManager em) {\n\t\tif(emf != null)\n\t\t{\n\t\t\temf.close();\n\t\t}\n\t\t\n\t\tif(em != null)\n\t\t{\n\t\t\tem.close();\n\t\t}\n\t}\n\n\n}\n"
  },
  {
    "path": "examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/runner/ExecutorService.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2013 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kvapps.runner;\r\n\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.Query;\r\n\r\nimport org.apache.commons.logging.Log;\r\nimport org.apache.commons.logging.LogFactory;\r\n\r\nimport com.impetus.client.cassandra.common.CassandraConstants;\r\nimport com.impetus.client.cassandra.thrift.ThriftClient;\r\nimport com.impetus.kundera.client.Client;\r\nimport com.impetus.kvapps.entities.Tweets;\r\nimport com.impetus.kvapps.entities.User;\r\nimport com.impetus.kvapps.entities.Video;\r\n\r\n/**\r\n * @author impetus\r\n * \r\n * Executor service, responsible for performing various CRUD operation on {@link User} in polyglot way.\r\n *\r\n */\r\npublic final class ExecutorService {\r\n\r\n    /** the log used by this class. */\r\n    private static Log logger = LogFactory.getLog(ExecutorService.class);\r\n\r\n    \r\n    /**\r\n     * on query with user email id\r\n     * \r\n     * @param em         entity manager instance.\r\n     * @param user       user entity instance. \r\n     * @return           collection of user instance.\r\n     */\r\n    static List<User> onQueryByEmail(final EntityManager em, final User user) \r\n    {\r\n\t\t// Query by parameter (fetch user by email id)\r\n\t\tString query = \"Select u from User u where u.emailId =?1\";\r\n\r\n\t\tlogger.info(\"\");\r\n\t\tlogger.info(\"\");\r\n\t\tlogger.info(query);\r\n\t\tSystem.out.println(\"#######################Querying##########################################\");\r\n\r\n\t\t// find by named parameter(e.g. email)\r\n\t\tList<User> fetchedUsers = findByEmail(em, query, user.getEmailId());\r\n\t\treturn fetchedUsers;\r\n\t}\r\n\r\n\t/**\r\n\t *  On persist user.\r\n\t *  \r\n\t * @param em        entity manager instance.\r\n\t * @param user      user object. \r\n\t */\r\n\tstatic void onPersist(final EntityManager em, final User user) \r\n\t{\r\n\t\tlogger.info(\"\");\r\n\t\tlogger.info(\"\");\r\n\t\tlogger.info(\"#######################Persisting##########################################\");\r\n\t\tlogger.info(\"\");\r\n\t\tlogger.info(user.toString());\r\n\t\tpersist(user, em);\r\n\t\tlogger.info(\"\");\r\n\t\tSystem.out.println(\"#######################Persisting##########################################\");\r\n\t\tlogger.info(\"\");\r\n\t\tlogger.info(\"\");\r\n\t}\r\n\r\n    \r\n    /**\r\n     * On find by user id.\r\n     * \r\n     * @param em         entity manager instance.\r\n     * @param userId     user id.\r\n     */ \r\n    static User findByKey(final EntityManager em, final String userId)\r\n    {\r\n        User user = em.find(User.class, userId);\r\n        logger.info(\"[On Find by key]\");\r\n        System.out.println(\"#######################START##########################################\");\r\n        logger.info(\"\\n\");\r\n        logger.info(\"\\t\\t User's first name:\" + user.getFirstName());\r\n        logger.info(\"\\t\\t User's emailId:\" + user.getEmailId());\r\n        logger.info(\"\\t\\t User's Personal Details:\" + user.getPersonalDetail().getName());\r\n        logger.info(\"\\t\\t User's Personal Details:\" + user.getPersonalDetail().getPassword());\r\n        logger.info(\"\\t\\t User's total tweets:\" + user.getTweets().size());\r\n        logger.info(\"\\n\");\r\n        System.out.println(\"#######################END############################################\");\r\n        logger.info(\"\\n\");\r\n        return user;\r\n    }\r\n\r\n    /**\r\n     *  on find by wild search query.\r\n     *  \r\n     * @param em        entity manager instance.\r\n     * @param query     query. \r\n     */\r\n    @SuppressWarnings(\"unchecked\")\r\n\tstatic void findByQuery(final EntityManager em, final String query)\r\n    {\r\n        Query q = em.createNamedQuery(query);\r\n\r\n        logger.info(\"[On Find All by Query]\");\r\n        List<User> users = q.getResultList();\r\n\r\n        if (users == null || users.isEmpty())\r\n        {\r\n            logger.info(\"0 Users Returned\");\r\n            return;\r\n        }\r\n\r\n        System.out.println(\"#######################START##########################################\");\r\n        logger.info(\"\\t\\t Total number of users:\" + users.size());\r\n        logger.info(\"\\t\\t User's total tweets:\" + users.get(0).getTweets().size());\r\n        printTweets(users);\r\n        logger.info(\"\\n\");\r\n        // logger.info(\"First tweet:\" users.get(0).getTweets().);\r\n        System.out.println(\"#######################END############################################\");\r\n        logger.info(\"\\n\");\r\n    }\r\n\r\n    /**\r\n     * On find by native CQL3 query.\r\n     * \r\n     * @param em            entity manager instance.\r\n     * @param query         native cql3 query.\r\n     */\r\n    @SuppressWarnings(\"unchecked\")\r\n\tstatic void findByNativeQuery(final EntityManager em, final String query)\r\n    {\r\n\r\n        Query q = em.createNativeQuery(query, Tweets.class);\r\n\r\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\r\n        ThriftClient client = (ThriftClient) clients.get(\"twissandra\");\r\n        client.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\r\n\r\n        logger.info(\"[On Find Tweets by CQL3]\");\r\n        List<Tweets> tweets = q.getResultList();\r\n\r\n        System.out.println(\"#######################START##########################################\");\r\n        logger.info(\"\\t\\t User's total tweets:\" + tweets.size());\r\n        onPrintTweets(tweets);\r\n        logger.info(\"\\n\");\r\n        // logger.info(\"First tweet:\" users.get(0).getTweets().);\r\n        System.out.println(\"#######################END############################################\");\r\n        logger.info(\"\\n\");\r\n    }\r\n\r\n    /**\r\n     *  On print tweets event.\r\n     *  \r\n     * @param tweets\r\n     */\r\n    private static void onPrintTweets(final List<Tweets> tweets)\r\n    {\r\n        for (Iterator<Tweets> iterator = tweets.iterator(); iterator.hasNext();)\r\n        {\r\n\r\n            int counter = 1;\r\n            while (iterator.hasNext())\r\n            {\r\n                logger.info(\"\\n\");\r\n                logger.info(\"\\t\\t Tweet No:#\" + counter++);\r\n                Tweets rec = (Tweets) iterator.next();\r\n                logger.info(\"\\t\\t tweet is ->\" + rec.getBody());\r\n                logger.info(\"\\t\\t Tweeted at ->\" + rec.getTweetDate());\r\n\r\n                if (rec.getVideos() != null)\r\n                {\r\n                    logger.info(\"\\t\\t Tweeted Contains Video ->\" + rec.getVideos().size());\r\n\r\n                    for (Iterator<Video> iteratorVideo = rec.getVideos().iterator(); iteratorVideo.hasNext();)\r\n                    {\r\n                        Video video = (Video) iteratorVideo.next();\r\n                        logger.info(video);\r\n                    }\r\n                }\r\n\r\n            }\r\n        }\r\n\r\n    }\r\n\r\n\r\n    private static List<User> findByEmail(final EntityManager em, String query, String parameter)\r\n    {\r\n        Query q = em.createNamedQuery(query);\r\n        q.setParameter(1, parameter);\r\n\r\n        List<User> users = q.getResultList();\r\n\r\n        return users;\r\n    }\r\n\r\n    private static void printTweets(List<User> users)\r\n    {\r\n        for (Iterator<User> iterator = users.iterator(); iterator.hasNext();)\r\n        {\r\n            User user = (User) iterator.next();\r\n            Iterator<Tweets> tweets = users.get(0).getTweets().iterator();\r\n\r\n            int counter = 1;\r\n            while (tweets.hasNext())\r\n            {\r\n                logger.info(\"\\n\");\r\n                logger.info(\"\\t\\t Tweet No:#\" + counter++);\r\n                Tweets rec = tweets.next();\r\n                logger.info(\"\\t\\t tweet is ->\" + rec.getBody());\r\n                logger.info(\"\\t\\t Tweeted at ->\" + rec.getTweetDate());\r\n\r\n                if (rec.getVideos() != null)\r\n                {\r\n                    logger.info(\"\\t\\t Tweeted Contains Video ->\" + rec.getVideos().size());\r\n\r\n                    for (Iterator iteratorVideo = rec.getVideos().iterator(); iteratorVideo.hasNext();)\r\n                    {\r\n                        Video video = (Video) iteratorVideo.next();\r\n                        logger.info(video);\r\n                    }\r\n                }\r\n\r\n            }\r\n        }\r\n\r\n    }\r\n\r\n    /**\r\n     * @param user\r\n     */\r\n    private static void persist(User user, final EntityManager em)\r\n    {\r\n        em.persist(user);\r\n    }\r\n\r\n}"
  },
  {
    "path": "examples/polyglot/kvapps/src/main/java/com/impetus/kvapps/runner/UserBroker.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2013 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kvapps.runner;\r\n\r\nimport java.io.BufferedInputStream;\r\nimport java.io.File;\r\nimport java.io.FileInputStream;\r\nimport java.io.InputStream;\r\nimport java.text.SimpleDateFormat;\r\nimport java.util.Date;\r\nimport java.util.HashSet;\r\nimport java.util.Iterator;\r\nimport java.util.Set;\r\n\r\nimport org.apache.poi.hssf.usermodel.HSSFCell;\r\nimport org.apache.poi.hssf.usermodel.HSSFDateUtil;\r\nimport org.apache.poi.hssf.usermodel.HSSFWorkbook;\r\nimport org.apache.poi.poifs.filesystem.POIFSFileSystem;\r\nimport org.apache.poi.ss.usermodel.Cell;\r\nimport org.apache.poi.ss.usermodel.Row;\r\nimport org.apache.poi.ss.usermodel.Sheet;\r\nimport org.apache.poi.ss.usermodel.Workbook;\r\n\r\nimport com.impetus.kvapps.entities.PersonalDetail;\r\nimport com.impetus.kvapps.entities.Tweets;\r\nimport com.impetus.kvapps.entities.User;\r\nimport com.impetus.kvapps.entities.Video;\r\n\r\n/**\r\n * @author impetus\r\n *   \r\n */\r\npublic class UserBroker\r\n{\r\n\r\n    private Sheet m_sheet;\r\n\r\n    private int m_iNbRows;\r\n\r\n    private int m_iCurrentRow = 0;\r\n\r\n    private static final String JAVA_TOSTRING = \"EEE MMM dd HH:mm:ss zzz yyyy\";\r\n\r\n    public UserBroker(Sheet sheet)\r\n    {\r\n        m_sheet = sheet;\r\n        m_iNbRows = sheet.getPhysicalNumberOfRows();\r\n    }\r\n\r\n    /*\r\n     * Returns the contents of an Excel row in the form of a String array.\r\n     * \r\n     * @see com.ibm.ccd.common.parsing.Parser#splitLine()\r\n     */\r\n    public User addUser(Set<User> users) throws Exception\r\n    {\r\n\r\n        if (m_iCurrentRow == m_iNbRows)\r\n            return null;\r\n\r\n        Row row = m_sheet.getRow(m_iCurrentRow);\r\n        if (row == null)\r\n        {\r\n            return null;\r\n        }\r\n        else\r\n        {\r\n            // extract fields from excel sheet\r\n            String userName = extractCellData(row, 0);\r\n            String tweetBody = extractCellData(row, 1);\r\n            String videoId = extractCellData(row, 2);\r\n            String videoName = extractCellData(row, 3);\r\n\r\n            User user = null;\r\n            boolean present = false;\r\n            \r\n            //iterate over fields.\r\n            for (Iterator iterator = users.iterator(); iterator.hasNext();)\r\n            {\r\n                user = (User) iterator.next();\r\n                if (user.getFirstName().equals(userName))\r\n                {\r\n                    present = true;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            if (!present)\r\n            {\r\n                user = addUser(userName);\r\n            }\r\n\r\n            Tweets tweet = addTweets(user, tweetBody, new Date(), m_iCurrentRow + \"\");\r\n            assignVideosToTweet(tweet, videoId, videoName);\r\n\r\n            m_iCurrentRow++;\r\n\r\n            return user;\r\n        }\r\n\r\n    }\r\n\r\n    /*\r\n     *  Populates user instance for provided userName attribute.\r\n     */\r\n    private User addUser(String userName)\r\n    {\r\n        User user = new User();\r\n        PersonalDetail personalDetail = new PersonalDetail(userName, userName + \"Password\", \"Single\");\r\n        user.setUserId(userName);\r\n        user.setEmailId(userName + \"@\" + userName + \".com\");\r\n        user.setFirstName(userName);\r\n        user.setLastName(userName);\r\n        user.setTweets(new HashSet<Tweets>());\r\n        user.setPersonalDetail(personalDetail);\r\n        return user;\r\n    }\r\n\r\n    /*\r\n     *  Add user's tweets to provided user object. \r\n     */\r\n    private static Tweets addTweets(User user, String body, Date tweetDate, String tweetId)\r\n    {\r\n        Tweets tweet = new Tweets();\r\n        tweet.setTweetId(tweetId);\r\n        tweet.setBody(body);\r\n        tweet.setTweetDate(tweetDate);\r\n        user.getTweets().add(tweet);\r\n        return tweet;\r\n    }\r\n\r\n    /*\r\n     *   Upload a collection of videos for a specific tweet.  \r\n     */\r\n    private static void assignVideosToTweet(Tweets tweet, String videoId, String videoName)\r\n    {\r\n        Set<Video> videos = new HashSet<Video>();\r\n        Video video = new Video();\r\n        video.setVideoId(videoId);\r\n        video.setVideoName(videoName);\r\n        videos.add(video);\r\n        tweet.setVideos(videos);\r\n    }\r\n\r\n    /*\r\n     * Read a cell for specific column.\r\n     */\r\n    private String extractCellData(Row row, int iCurrent) throws Exception\r\n    {\r\n        Cell cell = (Cell) row.getCell(iCurrent);\r\n        if (cell == null)\r\n        {\r\n            return \"\";\r\n        }\r\n        else\r\n        {\r\n            switch (cell.getCellType())\r\n            {\r\n            case HSSFCell.CELL_TYPE_NUMERIC:\r\n                double value = cell.getNumericCellValue();\r\n                if (HSSFDateUtil.isCellDateFormatted(cell))\r\n\r\n                {\r\n                    if (HSSFDateUtil.isValidExcelDate(value))\r\n                    {\r\n                        Date date = HSSFDateUtil.getJavaDate(value);\r\n                        SimpleDateFormat dateFormat = new SimpleDateFormat(JAVA_TOSTRING);\r\n                        return dateFormat.format(date);\r\n                    }\r\n                    else\r\n                    {\r\n                        throw new Exception(\"Invalid Date value found at row number \" + row.getRowNum()\r\n                                + \" and column number \" + cell.getColumnIndex());\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    return value + \"\";\r\n                }\r\n            case HSSFCell.CELL_TYPE_STRING:\r\n                return cell.getStringCellValue();\r\n            case HSSFCell.CELL_TYPE_BLANK:\r\n                return null;\r\n            default:\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n\r\n    \r\n    /**\r\n     * Reads and populate a collection of {@link User} from excel file available at dataFilePath.\r\n     * \r\n     * @param dataFilePath\r\n     * @return  collection of users.\r\n     */\r\n    static Set<User> brokeUserList(final String dataFilePath)\r\n    {\r\n        Set<User> users = new HashSet<User>();\r\n        Workbook workBook = null;\r\n        File file = new File(dataFilePath);\r\n        InputStream excelDocumentStream = null;\r\n        try\r\n        {\r\n            excelDocumentStream = new FileInputStream(file);\r\n            POIFSFileSystem fsPOI = new POIFSFileSystem(new BufferedInputStream(excelDocumentStream));\r\n            workBook = new HSSFWorkbook(fsPOI);\r\n            UserBroker parser = new UserBroker(workBook.getSheetAt(0));\r\n            User user;\r\n            while ((user = parser.addUser(users)) != null)\r\n            {\r\n                users.add(user);\r\n            }\r\n            excelDocumentStream.close();\r\n\r\n        }\r\n        catch (Exception e)\r\n        {\r\n          throw new RuntimeException(\"Error while processing brokeUserList(), Caused by :\",e);\r\n        }\r\n        \r\n        return users;\r\n    }\r\n\r\n}"
  },
  {
    "path": "examples/polyglot/kvapps/src/main/resources/KunderaConnection.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<clientProperties>\r\n    <datastores>\r\n        <dataStore>\r\n        <name>cassandra</name>\r\n            <connection>\r\n            <properties>\r\n            <property name=\"cql.version\" value=\"3.0.0\"></property>                  \r\n        </properties>\r\n        </connection>\r\n\r\n    </dataStore>\r\n    </datastores>\r\n</clientProperties>"
  },
  {
    "path": "examples/polyglot/kvapps/src/main/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\t\n\t<!-- Persistence Units for user-tweets application -->\n\n\t<!-- Persistence unit for mysql -->\n\t<persistence-unit name=\"twirdbms\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kvapps.entities.User</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n    \t<properties>\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.rdbms.RDBMSClientFactory\" />\n\t\t\t<property name=\"hibernate.hbm2ddl.auto\" value=\"update\" />\n\t\t\t<property name=\"hibernate.show_sql\" value=\"false\" />\n\t\t\t<property name=\"hibernate.format_sql\" value=\"false\" />\n\t\t\t<property name=\"dialect\" value=\"org.openmeetings.app.hibernate.utils.MySQL5MyISAMDialect\"/>\n\t\t\t<property name=\"hibernate.dialect\" value=\"org.hibernate.dialect.MySQL5Dialect\" />\n\t\t\t<property name=\"hibernate.connection.driver_class\" value=\"com.mysql.jdbc.Driver\" />\n\t\t\t<property name=\"hibernate.connection.url\" value=\"jdbc:mysql://localhost:3306/kvapps\" />\n\t\t\t<property name=\"hibernate.connection.username\" value=\"root\" />\n\t\t\t<property name=\"hibernate.connection.password\" value=\"impetus\" />\n\t\t</properties>\n\t</persistence-unit>\n\n    <!-- Persistence unit for mongo -->\n\t<persistence-unit name=\"twingo\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kvapps.entities.Tweets</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t <property name=\"kundera.nodes\" value=\"localhost\" /> \n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"kvapps\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kundera-mongo.properties\"/>\n\t\t</properties>\n\t</persistence-unit>\n\t\n\t<!-- Persistence unit for cassandra -->\n\t<persistence-unit name=\"twissandra\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kvapps.entities.Video</class>\n    \t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"kvapps\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t   <property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t  </properties>\n\t</persistence-unit>\n</persistence>\n\n"
  },
  {
    "path": "examples/polyglot/kvapps/src/main/resources/log4j.properties",
    "content": "log4j.rootLogger=FATAL, DRFA, CONSOLE\r\n\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%m%n\r\nlog4j.category.com.impetus.kvapps=INFO\r\n"
  },
  {
    "path": "examples/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t<groupId>com.impetus</groupId>\n\t<artifactId>kundera-parent</artifactId>\n\t<version>3.3-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera</groupId>\n\t<artifactId>examples</artifactId>\n\t<version>3.3-SNAPSHOT</version>\n\t<packaging>pom</packaging>\n\n\t<name>examples</name>\n\t<url>https://github.com/impetus-opensource/Kundera</url>\n\n\t<licenses>\n\t\t<license>\n\t\t\t<name>The Apache Software License, Version 2.0</name>\n\t\t\t<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>\n\t\t\t<distribution>repo</distribution>\n\t\t</license>\n\t</licenses>\n\n\t<scm>\n\t\t<connection>scm:git:git@github.com:impetus-opensource/Kundera.git</connection>\n\t\t<developerConnection>scm:git:git@github.com:impetus-opensource/Kundera.git</developerConnection>\n\t\t<url>git@github.com:impetus-opensource/Kundera.git</url>\n\t</scm>\n\n\t<developers>\n\t\t<developer>\n\t\t\t<id>vivek.mishra</id>\n\t\t\t<name>Vivek Mishra</name>\n\t\t\t<email>vivek.mishra@yahoo.com</email>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<id>amresh.singh</id>\n\t\t\t<name>Amresh Kumar Singh</name>\n\t\t\t<email>amresh1002@gmail.com</email>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<id>Kuldeep.mishra</id>\n\t\t\t<name>Kuldeep Kumar Mishra</name>\n\t\t\t<email>kuld.cs.mishra@gmail.com</email>\n\t\t</developer>\n\t</developers>\n\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t\t<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n\t\t<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>\n\t\t<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>\n\t\t<sonar.language>java</sonar.language>\n\t</properties>\n\n\n\t<repositories>\n\t\t<repository>\n\t\t\t<id>clover</id>\n\t\t\t<name>Clover maven repo</name>\n\t\t\t<url>http://mirrors.ibiblio.org/pub/mirrors/maven</url>\n\t\t\t<releases>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</releases>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>kundera-missing</id>\n\t\t\t<name>Kundera Public Missing Resources Repository</name>\n\t\t\t<url>http://kundera.googlecode.com/svn/maven2/maven-missing-resources</url>\n\t\t\t<releases>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</releases>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>riptano</id>\n\t\t\t<name>riptano</name>\n\t\t\t<url>http://mvn.riptano.com/content/repositories/public</url>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>maven.scale7.org</id>\n\t\t\t<name>Scale7 Maven Repo</name>\n\t\t\t<url>https://github.com/s7/mvnrepo/raw/master</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t</repositories>\n\t<!-- Build profiles -->\n\t<profiles>\n\n\t\t<profile>\n\t\t\t<id>all</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>true</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>container</module>\n\t\t\t</modules>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>org.sonatype.oss</groupId>\n\t\t<artifactId>oss-parent</artifactId>\n\t\t<version>7</version>\n\t</parent>\n\n\t<groupId>com.impetus</groupId>\n\t<artifactId>kundera-parent</artifactId>\n\t<version>3.14-SNAPSHOT</version>\n\t<packaging>pom</packaging>\n\n\t<name>kundera</name>\n\t<url>https://github.com/Impetus/Kundera</url>\n\n\t<licenses>\n\t\t<license>\n\t\t\t<name>The Apache Software License, Version 2.0</name>\n\t\t\t<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>\n\t\t\t<distribution>repo</distribution>\n\t\t</license>\n\t</licenses>\n\n\t<scm>\n\t\t<connection>scm:git:git@github.com:Impetus/Kundera.git</connection>\n\t\t<developerConnection>scm:git:git@github.com:Impetus/Kundera.git</developerConnection>\n\t\t<url>git@github.com:Impetus/Kundera.git</url>\n\t  <tag>HEAD</tag>\n  </scm>\n\n\t<developers>\n\t\t<developer>\n\t\t\t<id>vivek.mishra</id>\n\t\t\t<name>Vivek Mishra</name>\n\t\t\t<email>vivek.mishra@impetus.co.in</email>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<id>devender-yadav</id>\n\t\t\t<name>Devender Yadav</name>\n\t\t\t<email>devender.yadav@impetus.co.in</email>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<id>karthikprasad13</id>\n\t\t\t<name>Karthik Prasad Manchala</name>\n\t\t\t<email>karthikp.manchala@impetus.co.in</email>\n\t\t</developer>\n\t</developers>\n\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t\t<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n\t\t<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>\n\t\t<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>\n\t\t<sonar.language>java</sonar.language>\n\t</properties>\n\n\t<!--\n\t<repositories>\n\t\t<repository>\n\t\t\t<id>clover</id>\n\t\t\t<name>Clover maven repo</name>\n\t\t\t<url>http://mirrors.ibiblio.org/pub/mirrors/maven</url>\n\t\t\t<releases>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</releases>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>kundera-missing</id>\n\t\t\t<name>Kundera Public Missing Resources Repository</name>\n\t\t\t<url>http://kundera.googlecode.com/svn/maven2/maven-missing-resources</url>\n\t\t\t<releases>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</releases>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>riptano</id>\n\t\t\t<name>riptano</name>\n\t\t\t<url>http://mvn.riptano.com/content/repositories/public</url>\n\t\t</repository>\n\t\t<repository>\n\t\t\t<id>maven.scale7.org</id>\n\t\t\t<name>Scale7 Maven Repo</name>\n\t\t\t<url>https://github.com/s7/mvnrepo/raw/master</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t</repositories> -->\n\n\t<!-- Build profiles -->\n\t<profiles>\n\n\t\t<profile>\n\t\t\t<id>all</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>true</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>src</module>\n\t\t\t</modules>\n\t\t</profile>\n\n\t\t<profile>\n\t\t\t<id>benchmark</id>\n\t\t\t<modules>\n\t\t\t\t<module>test</module>\n\t\t\t</modules>\n\t\t</profile>\n\n\t\t<profile>\n\t\t\t<id>examples</id>\n\t\t\t<modules>\n\t\t\t\t<module>examples</module>\n\t\t\t</modules>\n\t\t</profile>\n\n\t<!-- Profile to sign artifacts -->\n\n\t\t<profile>\n      \t\t\t<id>release-sign-artifacts</id>\n      \t\t\t<activation>\n\t\t\t\t<property>\n          \t\t\t\t<name>performRelease</name>\n         \t\t\t\t <value>true</value>\n       \t\t\t\t </property>\n      \t\t\t</activation>\n     \t\t\t <build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n         \t\t\t\t   <groupId>org.apache.maven.plugins</groupId>\n         \t\t\t\t   <artifactId>maven-gpg-plugin</artifactId>\n         \t\t\t\t   <executions>\n              \t\t\t\t\t<execution>\n               \t\t\t\t\t\t<id>sign-artifacts</id>\n\t\t\t\t\t\t\t<phase>verify</phase>\n           \t\t\t\t\t\t<goals>\n                  \t\t\t\t\t\t<goal>sign</goal>\n                \t\t\t\t\t</goals>\n              \t\t\t\t\t</execution>\n            \t\t\t\t   </executions>\n          \t\t\t\t</plugin>\n        \t\t\t</plugins>\n      \t\t\t</build>\n    \t\t</profile>\n\n\t</profiles>\n\n\t<build>\n\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-release-plugin</artifactId>\n\t\t\t\t<version>2.5.2</version>\n\t\t\t\t<configuration>\n\t\t\t\t        <arguments>-DskipTests</arguments>\n\t\t\t        </configuration>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<id>default</id>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>perform</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<pomFileName>src/pom.xml</pomFileName>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t\n\t\t</plugins>\n\t</build>\n\n</project>\n\n"
  },
  {
    "path": "src/README.md",
    "content": "Overview\n=========\nThe idea behind Kundera is to make working with NoSQL Databases drop-dead simple and fun. Kundera is being developed with following objectives:\n\n*  To make working with NoSQL as simple as working with SQL\n*  To serve as JPA Compliant mapping solution for NoSQL Datastores.\n*\tTo help developers, forget the complexity of NoSQL stores and focus on Domain Model.\n*\tTo make switching across data-stores as easy as changing a configuration.\n\n[Downloads](https://github.com/impetus-opensource/Kundera/wiki/Stable-Release)\n\n[Supported Databases](https://github.com/Impetus/Kundera/wiki/Datastores-Supported)\n\nNote\n====\nWith 2.9.1 release onwards artifact group id has been changed from\n\n\n\t<dependency>\n\t\t<groupId>com.impetus.client</groupId>\n\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t<version>2.9.1</version>\n\t</dependency>\n\t\nTO\n\n\t<dependency>\n\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t<version>2.9.1</version>\n\t</dependency>\n\nNote: 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.\n\nUp and running in 5 minutes\n============================\nIf 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\"):\n\n+ Set up Cassandra server.\n+ Download and include Kundera Jar\n+ Write persistence.xml file\n+ Write Entity class\n+ Moment of Truth!\n\nRecent Releases\n================================\n#### Please Note: trunk is current development branch. kundera-3.13 is released tag.\n\n#### 1-June-2018 - Kundera 3.13 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-313).\n\n#### 21-December-2017 - Kundera 3.12 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-312), additional improvements and the following new features : \n  * Added support for storing ethereum blockchain data in Kundera supported databases. Check [wiki](https://github.com/Impetus/Kundera/wiki/Kundera-with-Ethereum-Blockchain).\n\n#### 12-October-2017 - Kundera 3.11 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-311), additional improvements and the following new features : \n  * Added support for Couchbase. Check [wiki](https://github.com/Impetus/Kundera/wiki/Kundera-with-Couchbase).\n  * Upgraded Cassandra version to 3.11.0\n\n#### 22-August-2017 - Kundera 3.10.1 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-3101).\n\n#### 14-August-2017 - Kundera 3.10 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-310), additional improvements and the following new features : \n  * Added support for RethinkDB\n\n#### 3-July-2017 - Kundera 3.9.1 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-391).\n\n#### 31-May-2017 - Kundera 3.9 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-39), additional improvements and the following new features :\n  * MongoDB java driver updated to 3.4\n  * Parameterized and positional query support in Apache Kudu\n\n#### 6-March-2017 - Kundera 3.8 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-38), additional improvements and the following new features : \n  * Kundera-Kudu now supports Kudu 1.2\n  * IN Query support added in Kundera-Kudu\n  * Primary key auto generation added in Kundera-Kudu\n  * Support for nested embeddables in Kundera-Kudu\n  * Support for composite primary key in Kundera-Kudu\n  * Secondary indexer support for ES in Kundera-Kudu\n\n#### 6-December-2016 - Kundera 3.7 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-37), additional improvements and the following new features : \n  * Kundera-kudu now supports Kudu 1.x\n  * Support for fetch size in pagination in kundera-cassandra-ds-driver  \n  * Support for LIKE query on rowkey in kundera-hbase-v2 \n\n#### 21-September-2016 - Kundera 3.6 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-36), additional improvements and the following new features : \n  * Kundera-Cassandra now supports Cassandra 3.7\n  * Kundera-HBase-v2 has been upgraded for HBase 1.2+\n  * Primary key auto-generation is added for Kundera-Elasticsearch\n  * Support for pagination is added to Kundera-Elasticsearch\n\n#### 20-June-2016 - Kundera 3.5 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-35), additional improvements and the following new features : \n  * Kundera-Cassandra now supports Cassandra 3.5\n  * Kundera-Elasticsearch now supports Elasticsearch 2.3\n    \n#### 12-April-2016 - Kundera 3.4 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-34), additional improvements and the following new features : \n  * Support for Kudu. check [wiki](https://github.com/impetus-opensource/Kundera/wiki/Kundera-with-Kudu).\n  * Added new light weight layer- \"Data as Object\". Check [wiki](https://github.com/impetus-opensource/Kundera/wiki/Kundera-Data-As-Object).\n\n#### 16-January-2016 - Kundera 3.3 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-33), additional improvements and the following new features : \n   * Support for schema generation for relational entities and composite columns added with kundera-oracle-no-sql \n   * Support for like operator and regex enabled for kundera-hbase\n   * Redis 3.0 can now be used with kundera-redis\n\n#### 16-November-2015 - Kundera 3.2 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-32), additional improvements and the following new features : \n   * Support for Cassandra-2.2 enabled \n   * Support for Oracle NoSQL 3.2.5 enabled along with schema generation.\n\n#### 16-September-2015 - Kundera 3.1 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-31), additional improvements and the following new features : \n   * Querying via Apache Spark support enabled for Teradata and Hive \n   * 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.\n\n#### 25-July-2015 - Kundera 3.0 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-30), additional improvements and the following new features : \n   * Apache Spark support enabled with Kundera \n   * Spark support with Kundera currently works for Cassandra, MongoDB, HDFS and CSV. This support is enabled with Spark 1.4.0 version.\n\n#### 9-May-2015 - Kundera 2.17 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-217), additional improvements and the following new features : \n   * GridFS support added with MongoDB\n   * 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.\n\n#### 17-March-2015 - Kundera 2.16 released\nThis release includes [bug fixes](https://github.com/Impetus/Kundera/wiki/Bug-Fixes#release-216), additional improvements and the following new features :\n   * Hbase data remodeling with support for HBase-1.0 version.\n   ( Support for Hbase version 1.0 with the revised data model is available with Kundera's  \"kundera-hbase-v2\" dependency.)\n\n#### 2-March-2015 - Kundera 2.15.1 released\nThis 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:\n   * Support added for Cassandra-2.1.x version.\n   * Support for Cassandra User Defined Types as embeddables.\n   * Aggregation support available with elastic search is also enabled in Kundera \n  (Support for aggregate functions is also extended for other Kundera clients' by using Elastic search as indexing store.)\n\n#### 12-January-2015 - Kundera 2.15 released\nThis 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:\n\n * Support added for Redis-2.8.x version.\n * Support added for MongoDB-2.6.x version.\n * Support added for Elastic-search 1.4.2 version.\n\n#### 17-October-2014 - Kundera 2.14 released\nThis 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:\n\n * Or clause and in query support enabled for Hbase\n\n\n#### 4-July-2014 - Kundera 2.13 released\nThis 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:\n\n* Support added for Hbase-0.96\n* Support for composite keys over Lucene and  Hbase enabled\n\n#### 21-May-2014 - Kundera 2.12 released\nThis 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:\n\n* Support added for Oracle-KV 3.0.5\n* Support  for JPA-2.1 enabled\n\n\n#### 24-March-2014 - Kundera 2.11 released\nThis 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:\n\n* Support added for Cassandra datastax java driver\n* Support added for in clause with setParameter for collection object\n\n#### 31-January-2014 - Kundera 2.10 released\nThis 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:\n\n* Support added for bean validation.\n\n#### 13-December-2013 - Kundera 2.9 released\nThis 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:\n* Support for Secondary table.\n* Support Abstract entity.\n\n#### 21-October-2013 - Kundera 2.8 released\nThis 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:\n* Support for couchdb as a datastore.\n* Support for MappedSuperclass and JPA Inheritence strategy.\n\n#### 03-September-2013 - Kundera 2.7 released\nThis 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:\n\n* Support for pagination over Mongodb. \n* Added elastic search as datastore and fallback indexing mechanism. \n\n\n#### 06-July-2013 - Kundera 2.6 released\nThis 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:\n\n* Lazy fetching of relationships.\n* Multiple node support for Cassandra.\n* Pagination support for Cassandra and HBase\n\n\n#### 30-Apr-2013 - Kundera 2.5 released\nThis 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:\n\n* Support for OracleNoSQL\n   [Please use the Oracle NoSQL jars from the Oracle NoSQL distribution at:\n   http://download.oracle.com/otn-pub/otn_software/nosql-database/kv-ce-2.0.26.zip.\n   For the convenience of those who want to build Kundera from source we have additionally\n   placed the jars at http://kundera.googlecode.com/svn/maven2/maven-missing-resources/]\n \n* CQL 3.0 interoperability with thrift\n\n\n#### 08-Mar-2013 - Kundera 2.4 released\nThis 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:\n\n* Support for Neo4j graph database\n* Primary key auto-generation\n* Support for JoinByPrimaryKey relationship\n* Custom Secondary indexing hooks\n* Hadoop 0.94.3 migration\n\n\n#### 24-Jan-2013 - Kundera 2.3 released\nThis 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:\n\n* Redis Support\n* Cassandra 1.2 migration.\n* HBase schema handling changes\n* Stronger query support, like selective column/id search via JPQL.\n* Enabled support for @Transient for embedded columns and mapped super class.\n* Record limit setting on search for mongodb .\n\n\n#### 08-Nov-2012 - Kundera 2.2 released\nThis 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:\n\n* Geospatial Persistence and Queries for MongoDB\n* Composite keys support for Cassandra and MongoDB\n* Cassandra 1.1.6 migration\n* Support for enum data type\n* Named and Native queries support for REST based access\n\n#### 21-Sep-2012 - Kundera 2.1 released\nThis 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:\n\n* CQL Version configuration\n* Batch insert/update for Cassandra/MongoDB/HBase\n* JPA MetaModel and TypedQuery implementation\n* Raw thrift client support for Cassandra\n* Datastore specific XML configuration. (.properties file deprecated) \n* Stronger query support:\n   - JPQL support over all data types and associations\n   - JPQL support to query using primary key alongwith other columns\n* JPA compliance\n   - EntityManager methods implementation (contains, refresh, detach, setProperty)\n   - EntityManagerFactory methods (getPersistenceUnitUtil)\n   - Persistence methods (getProviderUtil)\n\n\n#### 25-July-2012 - Kundera 2.0.7 released\nThis release includes bug fixes, performance improvements and the following new features compared to version 2.0.6:\n\n\n* HBase 0.92.1 migration\n* Hadoop 1.0.2 migration\n* Cassandra 1.1.2 migration\n* MongoDB 2.0.4 migration\n* JPA EntityTransaction commit and rollback\n* JTA Transactions integration over web server\n* Kundera-REST API\n* Support for Counter column in cassandra\n* Inverted wide-row indexing support for Cassandra\n* Login Authentication support for Cassandra and MongoDB\n* Filters and filters list for HBase\n* Deprecated Lucene based indexing for HBase.\n* Datastore specific configuration files for specifying:\n   - Replication factor\n   - Placement strategy\n   - Consistency level per operation.\n   - Counter column family configuration\n   - Inverted indexing switch\n   - Zookeeper host and port\n   - Hbase column family configurations\n   - MongoDB servers list, read preference and socket timeout.\n ...etc.\n\n\n#### 20-Apr-2012 - Kundera 2.0.6 released\nThis release includes bug fixes and the following new features compared to version 2.0.5:\n\n* HBase 0.90.x migration.\n* Enhanced Persistence Context.\n* Named and Native queries support (including CQL support for cassandra)\n* UPDATE and DELETE queries support.\n* DDL auto-schema creation.\n* Performance improvements.\n\n#### 06-Feb-2012 - Kundera 2.0.5 released\nThis release includes bug fixes and the following new features compared to version 2.0.4:\n\n* Cassandra 1.x migration.\n* Support for Many-to-Many relationship (via Join table)\n* Transitive persistence.\n* Datastore native secondary index support in addition to Lucene based indexing. An optional switch provided to change between two.\n* Query support for >, < , >=,<=,!=, like, order by, like, logical operators and between.\n* Connection pooling settings provided for all datastores.\n* Support for all data types as required by JPA.\n* Range queries for cassandra (via between clause in JPA-QL)\n* Bug fixes related to self join. \n\n\n#### 09-Dec-2011 - Kundera 2.0.4 released\nThis release includes bug fixes, performance improvements and the following new features compared to version 2.0.3:\n\n* Cross-datastore persistence.\n* Support for relational databases.\n* Moved out solandra and replaced with lucene.\n\n#### 08-Aug-2011 - Kundera 2.0.3 released\nThis release includes bug fixes and the following new features compared to version 2.0.2:\n\n* Cassandra 0.8.x support added\n\n#### 31-July-2011 - Kundera 2.0.2 released\nThis release includes bug fixes and the following new features compared to version 2.0.1:\n\n* Kundera is now JPA 2.0 compliant. \n* Embedded objects/ collections support for HBase.\n\n#### 12-July-2011 - Kundera 2.0.1 released\nThis release includes bug fixes and the following new features compared to initial revision:\n\n* Cassandra 0.7.x support added\n* @Embedded annotation fields persisted co located with parent entity\n* Search within embedded objects.\n* Selective index.\n\n[Downloads](https://github.com/impetus-opensource/Kundera/wiki/Stable-Release \"Downloads\")\n\n\nAbout Us\n========\nKundera 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.\n"
  },
  {
    "path": "src/data-as-object/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<artifactId>kundera</artifactId>\n\t\t<groupId>com.impetus</groupId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>data-as-object</artifactId>\n\t<name>data-as-object</name>\n\t<url>http://maven.apache.org</url>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.codehaus.jackson</groupId>\n\t\t\t<artifactId>jackson-mapper-asl</artifactId>\n\t\t\t<version>1.9.13</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n\n\n\n"
  },
  {
    "path": "src/data-as-object/src/main/java/com/impetus/core/BindingException.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.core;\n\n/**\n * The Class BindingException.\n */\npublic class BindingException extends RuntimeException\n{\n\n    /** The Constant serialVersionUID. */\n    private static final long serialVersionUID = 1L;\n\n    /**\n     * Instantiates a new binding exception.\n     */\n    public BindingException()\n    {\n        super();\n    }\n\n    /**\n     * Instantiates a new binding exception.\n     *\n     * @param message\n     *            the message\n     */\n    public BindingException(String message)\n    {\n        super(message);\n\n    }\n\n    /**\n     * Instantiates a new binding exception.\n     *\n     * @param cause\n     *            the cause\n     */\n    public BindingException(Throwable cause)\n    {\n        super(cause);\n\n    }\n\n    /**\n     * Instantiates a new binding exception.\n     *\n     * @param message\n     *            the message\n     * @param cause\n     *            the cause\n     */\n    public BindingException(String message, Throwable cause)\n    {\n        super(message, cause);\n    }\n\n}\n"
  },
  {
    "path": "src/data-as-object/src/main/java/com/impetus/core/DefaultKunderaEntity.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.core;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Table;\n\nimport org.apache.commons.lang.StringUtils;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.configure.SchemaConfiguration;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.processor.IndexProcessor;\nimport com.impetus.kundera.metadata.processor.TableProcessor;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * The Class DefaultKunderaEntity.\n *\n * @param <T>\n *            the generic type\n * @param <K>\n *            the key type\n */\npublic class DefaultKunderaEntity<T, K> implements KunderaEntity<T, K>\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.core.KunderaEntity#find(java.lang.Object)\n     */\n    public final T find(K key)\n    {\n        return (T) em.find(this.getClass(), key);\n    }\n\n    /**\n     * On bind.\n     *\n     * @param clazz\n     *            the clazz\n     */\n    private static void onBind(Class clazz)\n    {\n\n        if (((MetamodelImpl) em.getMetamodel()).getEntityMetadataMap().isEmpty())\n        {\n\n            EntityMetadata metadata = new EntityMetadata(clazz);\n            metadata.setPersistenceUnit(getPersistenceUnit());\n\n            setSchemaAndPU(clazz, metadata);\n\n            new TableProcessor(em.getEntityManagerFactory().getProperties(),\n                    ((EntityManagerFactoryImpl) em.getEntityManagerFactory()).getKunderaMetadataInstance())\n                            .process(clazz, metadata);\n\n            KunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl) em.getEntityManagerFactory())\n                    .getKunderaMetadataInstance();\n\n            new IndexProcessor(kunderaMetadata).process(clazz, metadata);\n\n            ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\n\n            ((MetamodelImpl) em.getMetamodel()).addEntityMetadata(clazz, metadata);\n            ((MetamodelImpl) em.getMetamodel()).addEntityNameToClassMapping(clazz.getSimpleName(), clazz);\n            appMetadata.getMetamodelMap().put(getPersistenceUnit(), em.getMetamodel());\n\n            Map<String, List<String>> clazzToPuMap = new HashMap<String, List<String>>();\n            List<String> persistenceUnits = new ArrayList<String>();\n            persistenceUnits.add(getPersistenceUnit());\n            clazzToPuMap.put(clazz.getName(), persistenceUnits);\n            appMetadata.setClazzToPuMap(clazzToPuMap);\n            new SchemaConfiguration(em.getEntityManagerFactory().getProperties(), kunderaMetadata, getPersistenceUnit())\n                    .configure();\n\n        }\n\n    }\n\n    /**\n     * Sets the schema and pu.\n     *\n     * @param clazz\n     *            the clazz\n     * @param metadata\n     *            the metadata\n     */\n    private static void setSchemaAndPU(Class<?> clazz, EntityMetadata metadata)\n    {\n        Table table = clazz.getAnnotation(Table.class);\n        if (table != null)\n        {\n            metadata.setTableName(!StringUtils.isBlank(table.name()) ? table.name() : clazz.getSimpleName());\n            String schemaStr = table.schema();\n\n            MetadataUtils.setSchemaAndPersistenceUnit(metadata, schemaStr,\n                    em.getEntityManagerFactory().getProperties());\n        }\n        else\n        {\n            metadata.setTableName(clazz.getSimpleName());\n            metadata.setSchema((String) em.getEntityManagerFactory().getProperties().get(\"kundera.keyspace\"));\n        }\n\n        if (metadata.getPersistenceUnit() == null)\n        {\n            metadata.setPersistenceUnit(getPersistenceUnit());\n        }\n    }\n\n    /**\n     * Gets the persistence unit.\n     *\n     * @return the persistence unit\n     */\n    private static String getPersistenceUnit()\n    {\n        return (String) em.getEntityManagerFactory().getProperties().get(Constants.PERSISTENCE_UNIT_NAME);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.core.KunderaEntity#save()\n     */\n    public final void save()\n    {\n        em.persist(this);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.core.KunderaEntity#update()\n     */\n    public final void update()\n    {\n        em.merge(this);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.core.KunderaEntity#delete()\n     */\n    public final void delete()\n    {\n        em.remove(this);\n    }\n\n    /**\n     * Bind.\n     *\n     * @param propertiesPath\n     *            the properties path\n     * @param clazz\n     *            the clazz\n     * @throws BindingException\n     *             the binding exception\n     */\n    public static synchronized void bind(String propertiesPath, Class clazz) throws BindingException\n    {\n        if (em == null)\n        {\n            em = PersistenceService.getEM(emf, propertiesPath, clazz.getName());\n        }\n        onBind(clazz);\n    }\n\n    /**\n     * Unbind.\n     */\n    public static synchronized void unbind()\n    {\n        if (emf != null && emf.isOpen())\n        {\n            emf.close();\n            emf = null;\n\n        }\n        if (em != null && em.isOpen())\n        {\n            em.close();\n            em = null;\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.core.KunderaEntity#leftJoin(java.lang.Class,\n     * java.lang.String, java.lang.String[])\n     */\n    // public final List leftJoin(Class clazz, String joinColumn, String...\n    // columnTobeFetched)\n    // {\n    // List<T> finalResult = new ArrayList();\n    // List<T> leftTable = em.createQuery(\"Select p from \" +\n    // this.getClass().getSimpleName() + \" p\").getResultList();\n    // EntityType leftEntity = ((MetamodelImpl)\n    // em.getMetamodel()).entity(this.getClass());\n    // Attribute attribute = leftEntity.getAttribute(joinColumn);\n    // Field field = (Field) attribute.getJavaMember();\n    //\n    // for (T obj : leftTable)\n    // {\n    // List rightTable = em\n    // .createQuery(\n    // \"Select p from \" + clazz.getSimpleName() + \" p where p.\" + joinColumn + \"\n    // = :columnValue\")\n    // .setParameter(\"columnValue\", PropertyAccessorHelper.getObject(obj,\n    // field)).getResultList();\n    // if (!rightTable.isEmpty())\n    // {\n    // finalResult.add(obj);\n    // }\n    // }\n    // return finalResult;\n    // }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.core.KunderaEntity#query(java.lang.String)\n     */\n    public List<T> query(String query)\n    {\n        return em.createQuery(query).getResultList();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.core.KunderaEntity#query(java.lang.String,\n     * com.impetus.core.QueryType)\n     */\n    public List<T> query(String query, QueryType type)\n    {\n        switch (type)\n        {\n        case JPQL:\n            return query(query);\n\n        case NATIVE:\n            return nativeQuery(query);\n\n        default:\n            throw new KunderaException(\"invalid query type\");\n        }\n    }\n\n    /**\n     * Native query.\n     *\n     * @param query\n     *            the query\n     * @return the list\n     */\n    private List<T> nativeQuery(String query)\n    {\n        return em.createNativeQuery(query).getResultList();\n    }\n\n}\n"
  },
  {
    "path": "src/data-as-object/src/main/java/com/impetus/core/KunderaEntity.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.core;\n\nimport java.util.List;\n\n/**\n * The Interface KunderaEntity.\n *\n * @param <T>\n *            the generic type\n * @param <K>\n *            the key type\n */\npublic interface KunderaEntity<T, K>\n{\n\n    /**\n     * Find.\n     *\n     * @param key\n     *            the key\n     * @return the t\n     */\n    T find(K key);\n\n    /**\n     * Save.\n     */\n    void save();\n\n    /**\n     * Update.\n     */\n    void update();\n\n    /**\n     * Delete.\n     */\n    void delete();\n\n    /**\n     * Query.\n     *\n     * @param query\n     *            the query\n     * @return the list\n     */\n    List<T> query(String query);\n\n    /**\n     * Query.\n     *\n     * @param query\n     *            the query\n     * @param type\n     *            the type\n     * @return the list\n     */\n    List<T> query(String query, QueryType type);\n\n    /**\n     * Left join.\n     *\n     * @param clazz\n     *            the clazz\n     * @param joinColumn\n     *            the join column\n     * @param columnTobeFetched\n     *            the column tobe fetched\n     * @return the list\n     */\n    // List<T> leftJoin(Class clazz, String joinColumn, String...\n    // columnTobeFetched);\n\n}\n"
  },
  {
    "path": "src/data-as-object/src/main/java/com/impetus/core/PersistenceService.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.core;\n\nimport java.io.InputStream;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.StringTokenizer;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.dao.utils.JsonUtil;\nimport com.impetus.dao.utils.PropertyReader;\nimport com.impetus.kundera.KunderaException;\n\n/**\n * The Class PersistenceService.\n */\npublic class PersistenceService\n{\n\n    /** The logger. */\n    private static Logger LOGGER = LoggerFactory.getLogger(PersistenceService.class);\n\n    /**\n     * Gets the em.\n     *\n     * @param emf\n     *            the emf\n     * @param propertiesPath\n     *            the properties path\n     * @param clazzName\n     *            the clazz name\n     * @return the em\n     */\n    public static synchronized EntityManager getEM(EntityManagerFactory emf, final String propertiesPath,\n            final String clazzName)\n    {\n        /** The client properties. */\n        Map<?, Map<String, String>> clientProperties = new HashMap<>();\n\n        /** The entity configurations. */\n        Map<String, Map<String, String>> entityConfigurations = Collections\n                .synchronizedMap(new HashMap<String, Map<String, String>>());\n\n        loadClientProperties(propertiesPath, clazzName, clientProperties, entityConfigurations);\n\n        if (emf == null)\n        {\n\n            StringBuilder puNames = new StringBuilder();\n\n            for (Entry<String, Map<String, String>> entry : entityConfigurations.entrySet())\n            {\n                if (entry.getValue().get(\"kundera.pu\") != null)\n                {\n                    puNames.append(entry.getValue().get(\"kundera.pu\"));\n                    puNames.append(\",\");\n                }\n            }\n            if (puNames.length() > 0)\n            {\n                puNames.deleteCharAt(puNames.length() - 1);\n            }\n\n            try\n            {\n\n                if (puNames.toString().isEmpty())\n                {\n                    emf = Persistence.createEntityManagerFactory(\"testPU\", entityConfigurations.get(clazzName));\n                }\n\n                else\n                {\n                    emf = Persistence.createEntityManagerFactory(puNames.toString());\n                }\n\n            }\n            catch (Exception e)\n            {\n                LOGGER.error(\"Unable to create Entity Manager Factory. Caused By: \", e);\n                throw new KunderaException(\"Unable to create Entity Manager Factory. Caused By: \", e);\n            }\n        }\n\n        return emf.createEntityManager();\n    }\n\n    /**\n     * Load client properties.\n     *\n     * @param propertiesPath\n     *            the properties path\n     * @param clazzName\n     *            the clazz name\n     * @param clientProperties\n     *            the client properties\n     * @param entityConfigurations\n     *            the entity configurations\n     */\n    private static void loadClientProperties(String propertiesPath, String clazzName,\n            Map<?, Map<String, String>> clientProperties, Map<String, Map<String, String>> entityConfigurations)\n    {\n\n        InputStream inputStream = PropertyReader.class.getClassLoader().getResourceAsStream(propertiesPath);\n        clientProperties = JsonUtil.readJson(inputStream, Map.class);\n\n        if (clientProperties != null)\n        {\n            if (clientProperties.get(\"all\") != null)\n            {\n                entityConfigurations.put(clazzName, clientProperties.get(\"all\"));\n            }\n            else\n            {\n\n                Iterator iter = clientProperties.keySet().iterator();\n\n                while (iter.hasNext())\n                {\n                    Object key = iter.next();\n                    if (((String) key).indexOf(',') > 0)\n                    {\n                        StringTokenizer tokenizer = new StringTokenizer((String) key, \",\");\n                        while (tokenizer.hasMoreElements())\n                        {\n                            String token = tokenizer.nextToken();\n                            entityConfigurations.put(token, clientProperties.get(key));\n                        }\n                    }\n                    else\n                    {\n                        entityConfigurations.put((String) key, clientProperties.get(key));\n                    }\n                }\n            }\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/data-as-object/src/main/java/com/impetus/core/QueryType.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.core;\n\n/**\n * The Enum QueryType.\n */\npublic enum QueryType\n{\n\n    /** The jpql. */\n    JPQL,\n    /** The native. */\n    NATIVE;\n}"
  },
  {
    "path": "src/data-as-object/src/main/java/com/impetus/dao/utils/JsonUtil.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.dao.utils;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport org.codehaus.jackson.map.ObjectMapper;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * The Class JsonUtil.\n */\npublic class JsonUtil\n{\n\n    /** The logger. */\n    private static Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);\n\n    /**\n     * Read json.\n     *\n     * @param <T>\n     *            the generic type\n     * @param json\n     *            the json\n     * @param clazz\n     *            the clazz\n     * @return the t\n     */\n    public final static <T> T readJson(String json, Class<T> clazz)\n    {\n        ObjectMapper mapper = new ObjectMapper();\n        try\n        {\n            if (json != null && !json.isEmpty())\n            {\n                return mapper.readValue(json, clazz);\n            }\n            else\n            {\n                LOGGER.error(\"JSON is null or empty.\");\n                throw new KunderaException(\"JSON is null or empty.\");\n            }\n        }\n        catch (IOException e)\n        {\n            LOGGER.error(\"Error while converting in json{} presentation{}.\", json, e);\n            throw new KunderaException(\"Error while mapping JSON to Object. Caused By: \", e);\n        }\n\n    }\n\n    /**\n     * Read json.\n     *\n     * @param <T>\n     *            the generic type\n     * @param jsonStream\n     *            the json stream\n     * @param clazz\n     *            the clazz\n     * @return the t\n     */\n    public final static <T> T readJson(InputStream jsonStream, Class<T> clazz)\n    {\n        ObjectMapper mapper = new ObjectMapper();\n        try\n        {\n            if (jsonStream != null)\n            {\n                return mapper.readValue(jsonStream, clazz);\n            }\n            else\n            {\n                LOGGER.error(\"InputStream is null.\");\n                throw new KunderaException(\"InputStream is null.\");\n            }\n        }\n        catch (IOException e)\n        {\n            LOGGER.error(\"Error while mapping input stream to object. Caused By: \", e);\n            throw new KunderaException(\"Error while mapping input stream to object. Caused By: \", e);\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/data-as-object/src/main/java/com/impetus/dao/utils/PropertyReader.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.dao.utils;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Properties;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * The Class PropertyReader.\n */\npublic class PropertyReader\n{\n\n    /** The logger. */\n    private static Logger LOGGER = LoggerFactory.getLogger(PropertyReader.class);\n\n    /**\n     * Gets the props.\n     *\n     * @param fileName\n     *            the file name\n     * @return the props\n     * @throws Exception\n     *             the exception\n     */\n    public static Properties getProps(String fileName) throws Exception\n    {\n        Properties properties = new Properties();\n        InputStream inputStream = PropertyReader.class.getClassLoader().getResourceAsStream(fileName);\n\n        if (inputStream != null)\n        {\n            try\n            {\n                properties.load(inputStream);\n            }\n            catch (IOException e)\n            {\n                LOGGER.error(\"JSON is null or empty.\");\n                throw new KunderaException(\"JSON is null or empty.\");\n            }\n        }\n        else\n        {\n            throw new KunderaException(\"Property file: [\" + fileName + \"] not found in the classpath\");\n        }\n        return properties;\n    }\n\n}\n"
  },
  {
    "path": "src/data-as-object/src/main/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"testPU\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t</persistence-unit>\r\n\r\n</persistence>\r\n"
  },
  {
    "path": "src/jpa-engine/core/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t<artifactId>core-parent</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.core</groupId>\n\t<artifactId>kundera-core</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-core</name>\n\t<url>http://maven.apache.org</url>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>directory-naming</groupId>\n\t\t\t<artifactId>naming-java</artifactId>\n\t\t\t<version>0.8</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>commons-lang</groupId>\n\t\t\t<artifactId>commons-lang</artifactId>\n\t\t\t<version>2.4</version>\n\t\t</dependency>\n\t\t<!-- <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> \n\t\t\t<version>2.0</version> </dependency> -->\n\t\t<dependency>\n\t\t\t<groupId>javax</groupId>\n\t\t\t<artifactId>javaee-api</artifactId>\n\t\t\t<version>7.0</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.eclipse.persistence</groupId>\n\t\t\t<artifactId>org.eclipse.persistence.jpa.jpql</artifactId>\n\t\t\t<version>2.5.2</version>\n\t\t</dependency>\n\n\t\t<!-- <dependency> -->\n\t\t<!-- <groupId>javax.validation</groupId> -->\n\t\t<!-- <artifactId>validation-api</artifactId> -->\n\t\t<!-- <version>1.1.0.Final</version> -->\n\t\t<!-- </dependency> -->\n\t\t<dependency>\n\t\t\t<groupId>cglib</groupId>\n\t\t\t<artifactId>cglib</artifactId>\n\t\t\t<version>2.2.2</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>commons-logging</groupId>\n\t\t\t<artifactId>commons-logging</artifactId>\n\t\t\t<version>1.1.1</version>\n\t\t</dependency>\n\t\t<!-- <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> \n\t\t\t<version>2.5.2</version> </dependency> -->\n\t\t<dependency>\n\t\t\t<groupId>org.slf4j</groupId>\n\t\t\t<artifactId>slf4j-api</artifactId>\n\t\t\t<version>1.7.5</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.javassist</groupId>\n\t\t\t<artifactId>javassist</artifactId>\n\t\t\t<version>3.21.0-GA</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.google.guava</groupId>\n\t\t\t<artifactId>guava</artifactId>\n\t\t\t<version>18.0</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>javax.transaction</groupId>\n\t\t\t<artifactId>jta</artifactId>\n\t\t\t<version>1.1</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.thoughtworks.xstream</groupId>\n\t\t\t<artifactId>xstream</artifactId>\n\t\t\t<version>1.4.3</version>\n\t\t</dependency>\n\n\t\t<!-- apache commons -->\n\t\t<dependency>\n\t\t\t<groupId>commons-configuration</groupId>\n\t\t\t<artifactId>commons-configuration</artifactId>\n\t\t\t<version>1.9</version>\n\t\t</dependency>\n\n\n\t\t<!-- JTS Topology Suite -->\n\t\t<dependency>\n\t\t\t<groupId>com.vividsolutions</groupId>\n\t\t\t<artifactId>jts</artifactId>\n\t\t\t<version>1.11</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>xerces</groupId>\n\t\t\t\t\t<artifactId>xercesImpl</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\n\t</dependencies>\n\t<build>\n\t\t<!-- <resources> <resource> <directory>${project.basedir}/target/test-classes/com/impetus/kundera/index/</directory> \n\t\t\t<excludes> <exclude>LuceneIndexer.class</exclude> </excludes> </resource> \n\t\t\t</resources> -->\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> \n\t\t\t\t<executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> \n\t\t\t\t<goal>sign</goal> </goals> </execution> </executions> </plugin> -->\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t<version>2.8.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<show>private</show>\n\t\t\t\t\t<nohelp>true</nohelp>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<!-- <classifier>tests</classifier> -->\n\t\t\t\t\t\t\t<!-- <filesets> <fileset> <directory>${project.basedir}/target/test-classes/com/impetus/kundera/index/</directory> -->\n\t\t\t\t\t\t\t<excludes>\n\t\t\t\t\t\t\t\t<exclude>**/index/LuceneIndexer.class</exclude>\n\t\t\t\t\t\t\t\t<exclude>**/persistence/EntityReaderTest.class</exclude>\n\t\t\t\t\t\t\t</excludes>\n\t\t\t\t\t\t\t<!-- </fileset> </filesets> -->\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n\n</project>\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/Constants.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera;\r\n\r\n/**\r\n * Constants.\r\n * \r\n * @author animesh.kumar\r\n * @since 0.1\r\n */\r\npublic interface Constants\r\n{\r\n\r\n    /** The Constant ENCODING. */\r\n    public static final String ENCODING = \"utf-8\";\r\n\r\n    /** UTF-8 character set. */\r\n    public static final String CHARSET_UTF8 = \"UTF-8\";\r\n\r\n    /** The Constant SEPARATOR. */\r\n    public final static String FOREIGN_KEY_SEPARATOR = \"~\";\r\n\r\n    /** The Constant INVALID. */\r\n    public final static int INVALID = -1;\r\n\r\n    /** The Constant SUPER_COLUMN_NAME_DELIMITER. */\r\n    public final static String EMBEDDED_COLUMN_NAME_DELIMITER = \"#\";\r\n\r\n    /** The Constant TO_ONE_SUPER_COL_NAME. */\r\n    public static final String FOREIGN_KEY_EMBEDDED_COLUMN_NAME = \"FKey-TO\";\r\n\r\n    /** The Constant KUNDERA_SECONDARY_CACHE_NAME. */\r\n    public static final String KUNDERA_SECONDARY_CACHE_NAME = \"Kundera\";\r\n\r\n    /** The Constant PERSISTENCE_UNIT_NAME. */\r\n    public static final String PERSISTENCE_UNIT_NAME = \"persistenceUnitName\";\r\n\r\n    /** The Constant LUCENE_INDEX_DIRECTORY_NAME. */\r\n    public static final String LUCENE_INDEX_DIRECTORY_NAME = \"lucene\";\r\n\r\n    /**\r\n     * Separator used for providing persistence unit alongwith schema on entity\r\n     * class (applicable in case of cross-datastore persistence).\r\n     */\r\n    public static final String SCHEMA_PERSISTENCE_UNIT_SEPARATOR = \"@\";\r\n\r\n    /**\r\n     * Separator used for providing a list of persistence units while creating\r\n     * EMF.\r\n     */\r\n    public final static String PERSISTENCE_UNIT_SEPARATOR = \",\";\r\n\r\n    /**\r\n     * Name of column family(HBase) or super column(cassandra) which houses all\r\n     * join columns.\r\n     */\r\n    public final static String JOIN_COLUMNS_FAMILY_NAME = \"JoinColumns\";\r\n\r\n    /** The Constant JOIN_COLUMN_NAME_SEPARATOR. */\r\n    public final static String JOIN_COLUMN_NAME_SEPARATOR = \"_\";\r\n\r\n    /** The Constant NODE_ID_SEPARATOR. */\r\n    public final static String NODE_ID_SEPARATOR = \"$\";\r\n\r\n    /** The Constant RDBMS_CLIENT_FACTORY. */\r\n    public final static String RDBMS_CLIENT_FACTORY = \"com.impetus.client.rdbms.RDBMSClientFactory\";\r\n\r\n    /** The Constant NEO4J_CLIENT_FACTORY. */\r\n    public final static String NEO4J_CLIENT_FACTORY = \"com.impetus.client.neo4j.Neo4JClientFactory\";\r\n\r\n    /** The Constant REDIS_CLIENT_FACTORY. */\r\n    public final static String REDIS_CLIENT_FACTORY = \"com.impetus.client.redis.RedisClientFactory\";\r\n\r\n    /** The Constant DEFAULT_MAX_FETCH_DEPTH. */\r\n    public final static int DEFAULT_MAX_FETCH_DEPTH = 2;\r\n\r\n    /** The Constant INDEX_TABLE_SUFFIX. */\r\n    public final static String INDEX_TABLE_SUFFIX = \"_INVRTD_IDX\";\r\n\r\n    /** The Constant INDEX_TABLE_ROW_KEY_DELIMITER. */\r\n    public final static String INDEX_TABLE_ROW_KEY_DELIMITER = \".\";\r\n\r\n    /** The Constant INDEX_TABLE_EC_DELIMITER. */\r\n    public final static String INDEX_TABLE_EC_DELIMITER = \"@SuperColumn:\";\r\n\r\n    /** The Constant LOADBALANCING_POLICY. */\r\n    public final static String LOADBALANCING_POLICY = \"loadbalancing.policy\";\r\n\r\n    /** The Constant FAILOVER_POLICY. */\r\n    public final static String FAILOVER_POLICY = \"failover.policy\";\r\n\r\n    /** The Constant FAIL_FAST. */\r\n    public final static String FAIL_FAST = \"fail.fast\";\r\n\r\n    /** The Constant ON_FAIL_TRY_ONE_NEXT_AVAILABLE. */\r\n    public final static String ON_FAIL_TRY_ONE_NEXT_AVAILABLE = \"on.fail.try.one.next.available\";\r\n\r\n    /** The Constant ON_FAIL_TRY_ALL_AVAILABLE. */\r\n    public final static String ON_FAIL_TRY_ALL_AVAILABLE = \"on.fail.try.all.available\";\r\n\r\n    /** The Constant RETRY_DELAY. */\r\n    public final static String RETRY_DELAY = \"retry.delay\";\r\n\r\n    /** The Constant RETRY. */\r\n    public final static String RETRY = \"retry\";\r\n\r\n    /** The Constant PERSISTENCE_UNIT_LOCATIION. */\r\n    public final static String PERSISTENCE_UNIT_LOCATIION = \"persistenceunit.location\";\r\n\r\n    /** The Constant DEFAULT_PERSISTENCE_UNIT_LOCATIION. */\r\n    public final static String DEFAULT_PERSISTENCE_UNIT_LOCATIION = \"META-INF/persistence.xml\";\r\n\r\n    /** The Constant SPACE. */\r\n    public final static String SPACE = \" \";\r\n\r\n    /** The Constant DEFAULT_TIMESTAMP_GENERATOR. */\r\n    public final static String DEFAULT_TIMESTAMP_GENERATOR = \"default.timestamp.generator\";\r\n\r\n    /** The Constant AGGREGATIONS. */\r\n    public final static String AGGREGATIONS = \"aggregations\";\r\n\r\n    /** The Constant PRIMARY_KEYS. */\r\n    public final static String PRIMARY_KEYS = \"primaryKeys\";\r\n\r\n    /** The Constant SELECT_EXPRESSION_ORDER. */\r\n    public final static String SELECT_EXPRESSION_ORDER = \"selectExpressionOrder\";\r\n\r\n    /** The Constant COL_FAMILY. */\r\n    public static final String COL_FAMILY = \"colFamily\";\r\n\r\n    /** The Constant DB COL_NAME. */\r\n    public static final String DB_COL_NAME = \"dbColumn\";\r\n\r\n    /** The Constant COL_NAME. */\r\n    public static final String COL_NAME = \"colName\";\r\n\r\n    /** The Constant IGNORE_CASE. */\r\n    public static final String IGNORE_CASE = \"ignoreCase\";\r\n\r\n    /** The Constant COMPOSITE. */\r\n    public final static String COMPOSITE = \"composite\";\r\n\r\n    /** The Constant IS_EMBEDDABLE. */\r\n    public static final String IS_EMBEDDABLE = \"isEmbeddable\";\r\n\r\n    /** The Constant FIELD_CLAZZ. */\r\n    public static final String FIELD_CLAZZ = \"fieldClazz\";\r\n\r\n    /** The Constant FIELD_NAME. */\r\n    public static final String FIELD_NAME = \"fieldName\";\r\n\r\n    /** The Constant ESCAPE_QUOTE. */\r\n    public static final String ESCAPE_QUOTE = \"\\\"\";\r\n\r\n    /** The Constant OPEN_SQUARE_BRACKET. */\r\n    public static final String OPEN_SQUARE_BRACKET = \"[\";\r\n\r\n    /** The Constant CLOSE_SQUARE_BRACKET. */\r\n    public static final String CLOSE_SQUARE_BRACKET = \"]\";\r\n\r\n    /** The Constant OPEN_ROUND_BRACKET. */\r\n    public static final String OPEN_ROUND_BRACKET = \"(\";\r\n\r\n    /** The Constant CLOSE_ROUND_BRACKET. */\r\n    public static final String CLOSE_ROUND_BRACKET = \")\";\r\n\r\n    /** The Constant OPEN_CURLY_BRACKET. */\r\n    public static final String OPEN_CURLY_BRACKET = \"{\";\r\n\r\n    /** The Constant COMMA. */\r\n    public static final String COMMA = \",\";\r\n\r\n    /** The Constant CLOSE_CURLY_BRACKET. */\r\n    public static final String CLOSE_CURLY_BRACKET = \"}\";\r\n\r\n    /** The Constant COLON. */\r\n    public static final String COLON = \":\";\r\n\r\n    /** The Constant SEMI_COLON. */\r\n    public static final String SEMI_COLON = \";\";\r\n\r\n    /** The Constant STR_GT. */\r\n    public static final String STR_GT = \">\";\r\n\r\n    /** The Constant STR_LT. */\r\n    public static final String STR_LT = \"<\";\r\n\r\n    /** The Constant SPACE_COMMA. */\r\n    public static final String SPACE_COMMA = \" ,\";\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/DataWrapper.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera;\r\n\r\n/**\r\n * The Interface DataWrapper.\r\n * \r\n * @author vivek.mishra\r\n */\r\npublic interface DataWrapper\r\n{\r\n\r\n    /**\r\n     * Returns column family.\r\n     * \r\n     * @return column family.\r\n     */\r\n    String getColumnFamily();\r\n\r\n    /**\r\n     * Returns row key.\r\n     * \r\n     * @return rowKey.\r\n     */\r\n    byte[] getRowKey();\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/KunderaException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera;\n\n/**\n * Base Exception class for all type of exceptions thrown by Kundera.\n * \n * @author amresh.singh\n */\npublic class KunderaException extends RuntimeException\n{\n\n    private static final long serialVersionUID = 3855497974944993364L;\n\n    /**\n     * \n     */\n    public KunderaException()\n    {\n        super();\n    }\n\n    /**\n     * @param arg0\n     */\n    public KunderaException(String arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     */\n    public KunderaException(Throwable arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     * @param arg1\n     */\n    public KunderaException(String arg0, Throwable arg1)\n    {\n        super(arg0, arg1);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/KunderaPersistence.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera;\r\n\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.spi.PersistenceProvider;\r\nimport javax.persistence.spi.PersistenceUnitInfo;\r\nimport javax.persistence.spi.ProviderUtil;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.configure.PersistenceUnitConfigurationException;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\r\n\r\n/**\r\n * The Class KunderaPersistence.\r\n * \r\n * @author animesh.kumar\r\n */\r\n@SuppressWarnings(\"unchecked\")\r\npublic class KunderaPersistence implements PersistenceProvider\r\n{\r\n\r\n    /** The logger. */\r\n    private static Logger logger = LoggerFactory.getLogger(KunderaPersistence.class);\r\n\r\n    private final ProviderUtil providerUtil;\r\n\r\n    private final PersistenceUtilHelper.MetadataCache cache;\r\n\r\n    /**\r\n     * Instantiates a new kundera persistence.\r\n     */\r\n    public KunderaPersistence()\r\n    {\r\n        this.providerUtil = new KunderaPersistenceProviderUtil(this);\r\n        this.cache = new PersistenceUtilHelper.MetadataCache();\r\n    }\r\n\r\n    @Override\r\n    public final EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map)\r\n    {\r\n        synchronized (this)\r\n        {\r\n            try\r\n            {\r\n                EntityManagerFactory emf = new EntityManagerFactoryImpl(info, map);\r\n\r\n                return emf;\r\n            }\r\n            catch (PersistenceUnitConfigurationException pcex)\r\n            {\r\n                // Means it is not for kundera persistence!\r\n                logger.error(\"EntityManagerFactory not created, returning null.\");\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public synchronized final EntityManagerFactory createEntityManagerFactory(String persistenceUnit, Map map)\r\n    {\r\n        // TODO: This may be a comma separated PU list, synchronizing on this\r\n        // list may not be intended\r\n        synchronized (this)\r\n        {\r\n            try\r\n            {\r\n                EntityManagerFactory emf = new EntityManagerFactoryImpl(persistenceUnit, map);\r\n\r\n                return emf;\r\n            }\r\n            catch (PersistenceUnitConfigurationException pcex)\r\n            {\r\n                // Means it is not for kundera persistence!\r\n                logger.error(\"EntityManagerFactory not created, returning null.\");\r\n                return null;\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Returns Persistence Provider util\r\n     * \r\n     * @see javax.persistence.spi.PersistenceProvider#getProviderUtil()\r\n     */\r\n    @Override\r\n    public ProviderUtil getProviderUtil()\r\n    {\r\n        return this.providerUtil;\r\n    }\r\n\r\n    /**\r\n     * @return the cache\r\n     */\r\n    public PersistenceUtilHelper.MetadataCache getCache()\r\n    {\r\n        return cache;\r\n    }\r\n\r\n    @Override\r\n    public void generateSchema(PersistenceUnitInfo arg0, Map arg1)\r\n    {\r\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\r\n        // do nothing.\r\n    }\r\n\r\n    @Override\r\n    public boolean generateSchema(String arg0, Map arg1)\r\n    {\r\n        // returning default.\r\n        return false;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/KunderaPersistenceProviderUtil.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera;\n\nimport javax.persistence.spi.LoadState;\nimport javax.persistence.spi.ProviderUtil;\n\n/**\n * {@link ProviderUtil} for {@link KunderaPersistence}\n * \n * @author amresh.singh\n */\npublic class KunderaPersistenceProviderUtil implements ProviderUtil\n{\n    KunderaPersistence provider;\n\n    public KunderaPersistenceProviderUtil(KunderaPersistence provider)\n    {\n        this.provider = provider;\n    }\n\n    /**\n     * If the provider determines that the entity has been provided by itself\n     * and that the state of the specified attribute has been loaded, this\n     * method returns LoadState.LOADED. If the provider determines that the\n     * entity has been provided by itself and that either entity attributes with\n     * FetchType EAGER have not been loaded or that the state of the specified\n     * attribute has not been loaded, this methods returns LoadState.NOT_LOADED.\n     * If a provider cannot determine the load state, this method returns\n     * LoadState.UNKNOWN. The provider's implementation of this method must not\n     * obtain a reference to an attribute value, as this could trigger the\n     * loading of entity state if the entity has been provided by a different\n     * provider.\n     * \n     * @param entity\n     * @param attributeName\n     *            name of attribute whose load status is to be determined\n     * @return load status of the attribute\n     */\n    @Override\n    public LoadState isLoadedWithoutReference(Object paramObject, String paramString)\n    {\n        return PersistenceUtilHelper.isLoadedWithoutReference(paramObject, paramString, provider.getCache());\n    }\n\n    /**\n     * If the provider determines that the entity has been provided by itself\n     * and that the state of the specified attribute has been loaded, this\n     * method returns LoadState.LOADED. If a provider determines that the entity\n     * has been provided by itself and that either the entity attributes with\n     * FetchType EAGER have not been loaded or that the state of the specified\n     * attribute has not been loaded, this method returns LoadState.NOT_LOADED.\n     * If the provider cannot determine the load state, this method returns\n     * LoadState.UNKNOWN. The provider's implementation of this method is\n     * permitted to obtain a reference to the attribute value. (This access is\n     * safe because providers which might trigger the loading of the attribute\n     * state will have already been determined by isLoadedWithoutReference. )\n     * \n     * @param entity\n     * @param attributeName\n     *            name of attribute whose load status is to be determined\n     * @return load status of the attribute\n     */\n    @Override\n    public LoadState isLoadedWithReference(Object paramObject, String paramString)\n    {\n        return PersistenceUtilHelper.isLoadedWithReference(paramObject, paramString, provider.getCache());\n    }\n\n    /**\n     * If the provider determines that the entity has been provided by itself\n     * and that the state of all attributes for which FetchType EAGER has been\n     * specified have been loaded, this method returns LoadState.LOADED. If the\n     * provider determines that the entity has been provided by itself and that\n     * not all attributes with FetchType EAGER have been loaded, this method\n     * returns LoadState.NOT_LOADED. If the provider cannot determine if the\n     * entity has been provided by itself, this method returns\n     * LoadState.UNKNOWN. The provider's implementation of this method must not\n     * obtain a reference to any attribute value, as this could trigger the\n     * loading of entity state if the entity has been provided by a different\n     * provider.\n     * \n     * @param entity\n     *            whose loaded status is to be determined\n     * @return load status of the entity\n     */\n    @Override\n    public LoadState isLoaded(Object paramObject)\n    {\n        return PersistenceUtilHelper.isLoaded(paramObject);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/KunderaPersistenceUnitUtil.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera;\n\nimport javax.persistence.PersistenceUnitUtil;\nimport javax.persistence.spi.LoadState;\n\nimport com.impetus.kundera.property.PropertyAccessorHelper;\n\n/**\n * {@link PersistenceUnitUtil} for {@link KunderaPersistence}\n * \n * @author amresh.singh\n */\npublic class KunderaPersistenceUnitUtil implements PersistenceUnitUtil\n{\n    private transient PersistenceUtilHelper.MetadataCache cache;\n\n    public KunderaPersistenceUnitUtil(PersistenceUtilHelper.MetadataCache cache)\n    {\n        this.cache = cache;\n    }\n\n    @Override\n    public boolean isLoaded(Object entity, String attributeName)\n    {\n        LoadState state = PersistenceUtilHelper.isLoadedWithoutReference(entity, attributeName, this.cache);\n        if (state == LoadState.LOADED)\n        {\n            return true;\n        }\n        if (state == LoadState.NOT_LOADED)\n        {\n            return false;\n        }\n        return (PersistenceUtilHelper.isLoadedWithReference(entity, attributeName, this.cache) != LoadState.NOT_LOADED);\n    }\n\n    @Override\n    public boolean isLoaded(Object entity)\n    {\n        return (PersistenceUtilHelper.isLoaded(entity) != LoadState.NOT_LOADED);\n    }\n\n    @Override\n    public Object getIdentifier(Object entity)\n    {\n        Class<?> entityClass = entity.getClass();\n//        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n//\n//        if (entityMetadata == null)\n//        {\n//            throw new IllegalArgumentException(entityClass + \" is not an entity\");\n//        }\n        return PropertyAccessorHelper.getId(entity, /*entityMetadata*/null);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/PersistenceProperties.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera;\n\n/**\n * Contains all constants properties supported in persistence.xml\n * \n * @author amresh.singh\n * \n */\npublic interface PersistenceProperties\n{\n\n    /** The Constant KUNDERA_NODES. */\n    public static final String KUNDERA_NODES = \"kundera.nodes\";\n    \n    /** The Constant KUNDERA_PORT. */\n    public static final String KUNDERA_PORT = \"kundera.port\";\n\n    /** The Constant KUNDERA_KEYSPACE. */\n    public static final String KUNDERA_KEYSPACE = \"kundera.keyspace\";\n\n    /** The Constant KUNDERA_DIALECT. */\n    public static final String KUNDERA_DIALECT = \"kundera.dialect\";\n\n    /** The Constant Kundera Client factory */\n    public static final String KUNDERA_CLIENT_FACTORY = \"kundera.client.lookup.class\";\n\n    /** The Constant KUNDERA_CACHE_PROVIDER_CLASS. */\n    public static final String KUNDERA_CACHE_PROVIDER_CLASS = \"kundera.cache.provider.class\";\n\n    /** The Constant KUNDERA_CACHE_CONFIG_RESOURCE. */\n    public static final String KUNDERA_CACHE_CONFIG_RESOURCE = \"kundera.cache.config.resource\";\n\n    /** The Constant KUNDERA_FETCH_MAX_DEPTH. */\n    public static final String KUNDERA_FETCH_MAX_DEPTH = \"kundera.fetch.max.depth\";\n\n    /** Connection Pooling related constants. */\n\n    // Cap on the number of object instances managed by the pool per node.\n    public static final String KUNDERA_POOL_SIZE_MAX_ACTIVE = \"kundera.pool.size.max.active\";\n\n    // Cap on the number of \"idle\" instances in the pool.\n    /** The Constant KUNDERA_POOL_SIZE_MAX_IDLE. */\n    public static final String KUNDERA_POOL_SIZE_MAX_IDLE = \"kundera.pool.size.max.idle\";\n\n    // Minimum number of idle objects to maintain in each of the nodes.\n    /** The Constant KUNDERA_POOL_SIZE_MIN_IDLE. */\n    public static final String KUNDERA_POOL_SIZE_MIN_IDLE = \"kundera.pool.size.min.idle\";\n\n    // Cap on the total number of instances from all nodes combined.\n    /** The Constant KUNDERA_POOL_SIZE_MAX_TOTAL. */\n    public static final String KUNDERA_POOL_SIZE_MAX_TOTAL = \"kundera.pool.size.max.total\";\n\n    /**\n     * Home directory for alternative secondary indexing, Lucene to be specific.\n     */\n    public static final String KUNDERA_INDEX_HOME_DIR = \"index.home.dir\";\n\n    /** Option to create schema. */\n    public static final String KUNDERA_DDL_AUTO_PREPARE = \"kundera.ddl.auto.prepare\";\n\n    public static final String KUNDERA_SHOW_QUERY=\"kundera.show.query\";\n    \n    /** Option to give kundera-cassandra property information */\n    public static final String KUNDERA_CLIENT_PROPERTY = \"kundera.client.property\";\n\n    public static final String KUNDERA_USERNAME = \"kundera.username\";\n\n    public static final String KUNDERA_PASSWORD = \"kundera.password\";\n\n    public static final String KUNDERA_BATCH_SIZE = \"kundera.batch.size\";\n\n    public static final String KUNDERA_TRANSACTION_TIMEOUT = \"kundera.transaction.timeout\";\n\n    /** Location where datastore file is stored */\n    public static final String KUNDERA_DATASTORE_FILE_PATH = \"kundera.datastore.file.path\";\n\n    public static final String KUNDERA_TRANSACTION_RESOURCE = \"kundera.transaction.resource.class\";\n\n    public static final String KUNDERA_INDEXER_CLASS = \"kundera.indexer.class\";\n    \n    public static final String KUNDERA_AUTO_GENERATOR_CLASS = \"kundera.auto.generator.class\";\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/PersistenceUtilHelper.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera;\n\nimport java.io.Serializable;\nimport java.lang.reflect.AccessibleObject;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Member;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.WeakHashMap;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.PersistenceUtil;\nimport javax.persistence.spi.LoadState;\n\nimport com.impetus.kundera.proxy.KunderaProxy;\nimport com.impetus.kundera.proxy.LazyInitializer;\nimport com.impetus.kundera.proxy.ProxyHelper;\nimport com.impetus.kundera.proxy.collection.AbstractProxyCollection;\n\n/**\n * Helper for {@link PersistenceUtil}\n */\npublic class PersistenceUtilHelper\n{\n\n    public static LoadState isLoadedWithReference(Object proxy, String property, MetadataCache cache)\n    {\n        \n        return proxy == null? LoadState.NOT_LOADED:isLoaded(get(proxy, property, cache));\n    }\n\n    public static LoadState isLoadedWithoutReference(Object proxy, String property, MetadataCache cache)\n    {\n        if (proxy == null || property == null)\n        {\n            return LoadState.NOT_LOADED;\n        }\n\n        if (proxy instanceof KunderaProxy)\n        {\n            LazyInitializer li = ((KunderaProxy) proxy).getKunderaLazyInitializer();\n            if (li.isUninitialized())\n            {\n                return LoadState.NOT_LOADED;\n            }\n            return LoadState.LOADED;\n        }\n        else\n        {\n            return LoadState.LOADED;\n        }\n\n    }\n\n    private static Object get(Object proxy, String property, MetadataCache cache)\n    {\n        final Class<?> clazz = proxy.getClass();\n        try\n        {\n            Member member = cache.getMember(clazz, property);\n            if (member instanceof Field)\n            {\n                return ((Field) member).get(proxy);\n            }\n            else if (member instanceof Method)\n            {\n                return ((Method) member).invoke(proxy);\n            }\n            else\n            {\n                throw new PersistenceException(\"Member object neither Field nor Method: \" + member);\n            }\n        }\n        catch (IllegalAccessException e)\n        {\n            throw new PersistenceException(\"Unable to access field or method: \" + clazz + \"#\" + property, e);\n        }\n        catch (InvocationTargetException e)\n        {\n            throw new PersistenceException(\"Unable to access field or method: \" + clazz + \"#\" + property, e);\n        }\n\n    }\n\n    private static void setAccessibility(Member member)\n    {\n        ((AccessibleObject) member).setAccessible(true);\n    }\n\n    public static LoadState isLoaded(Object o)\n    {\n        if (o == null)\n        {\n            return LoadState.NOT_LOADED;\n        }             \n        else if (o instanceof KunderaProxy)\n        {\n            final boolean isInitialized = !((KunderaProxy) o).getKunderaLazyInitializer().isUninitialized();\n            return isInitialized ? LoadState.LOADED : LoadState.NOT_LOADED;\n        }\n        else if(ProxyHelper.isKunderaProxyCollection(o))\n        {\n        final boolean isInitialized = ((AbstractProxyCollection) o).getDataCollection() != null;\n            return isInitialized ? LoadState.LOADED : LoadState.NOT_LOADED;\n        }       \n        else\n        {\n            return LoadState.UNKNOWN;\n        }\n    }   \n\n\n\n    /**\n     * Returns the method with the specified name or <code>null</code> if it\n     * does not exist.\n     * \n     * @param clazz\n     *            The class to check.\n     * @param methodName\n     *            The method name.\n     * \n     * @return Returns the method with the specified name or <code>null</code>\n     *         if it does not exist.\n     */\n    private static Method getMethod(Class<?> clazz, String methodName)\n    {\n        try\n        {\n            char string[] = methodName.toCharArray();\n            string[0] = Character.toUpperCase(string[0]);\n            methodName = new String(string);\n            try\n            {\n                return clazz.getDeclaredMethod(\"get\" + methodName);\n            }\n            catch (NoSuchMethodException e)\n            {\n                return clazz.getDeclaredMethod(\"is\" + methodName);\n            }\n        }\n        catch (NoSuchMethodException e)\n        {\n            return null;\n        }\n    }\n\n    /**\n     * Cache hierarchy and member resolution in a weak hash map\n     */\n    public static class MetadataCache implements Serializable\n    {\n        private transient Map<Class<?>, ClassCache> classCache = new WeakHashMap<Class<?>, ClassCache>();\n\n        private void readObject(java.io.ObjectInputStream stream)\n        {\n            classCache = new WeakHashMap<Class<?>, ClassCache>();\n        }\n\n        Member getMember(Class<?> clazz, String property)\n        {\n            ClassCache cache = classCache.get(clazz);\n            if (cache == null)\n            {\n                cache = new ClassCache(clazz);\n                classCache.put(clazz, cache);\n            }\n            Member member = cache.members.get(property);\n            if (member == null)\n            {\n                member = findMember(clazz, property);\n                cache.members.put(property, member);\n            }\n            return member;\n        }\n\n        private Member findMember(Class<?> clazz, String property)\n        {\n            final List<Class<?>> classes = getClassHierarchy(clazz);\n\n            for (Class current : classes)\n            {\n                final Field field;\n                try\n                {\n                    field = current.getDeclaredField(property);\n                    setAccessibility(field);\n                    return field;\n                }\n                catch (NoSuchFieldException e)\n                {\n                    final Method method = getMethod(current, property);\n                    if (method != null)\n                    {\n                        setAccessibility(method);\n                        return method;\n                    }\n                }\n            }\n            // we could not find any match\n            throw new PersistenceException(\"Unable to find field or method: \" + clazz + \"#\" + property);\n        }\n\n        private List<Class<?>> getClassHierarchy(Class<?> clazz)\n        {\n            ClassCache cache = classCache.get(clazz);\n            if (cache == null)\n            {\n                cache = new ClassCache(clazz);\n                classCache.put(clazz, cache);\n            }\n            return cache.classHierarchy;\n        }\n\n        private static List<Class<?>> findClassHierarchy(Class<?> clazz)\n        {\n            List<Class<?>> classes = new ArrayList<Class<?>>();\n            Class<?> current = clazz;\n            do\n            {\n                classes.add(current);\n                current = current.getSuperclass();\n            }\n            while (current != null);\n            return classes;\n        }\n\n        private static class ClassCache\n        {\n            List<Class<?>> classHierarchy;\n\n            Map<String, Member> members = new HashMap<String, Member>();\n\n            public ClassCache(Class<?> clazz)\n            {\n                classHierarchy = findClassHierarchy(clazz);\n            }\n        }\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/Cache.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.cache;\r\n\r\n/**\r\n * Implementors define a caching algorithm. All implementors <b>must</b> be\r\n * threadsafe.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic interface Cache extends javax.persistence.Cache\r\n{\r\n\r\n    /**\r\n     * Size.\r\n     * \r\n     * @return the int\r\n     */\r\n    int size();\r\n\r\n    /**\r\n     * Get an item from the cache.\r\n     * \r\n     * @param key\r\n     *            the key\r\n     * @return the object\r\n     */\r\n    Object get(Object key);\r\n\r\n    /**\r\n     * Add an item to the cache.\r\n     * \r\n     * @param key\r\n     *            the key\r\n     * @param value\r\n     *            the value\r\n     */\r\n    void put(Object key, Object value);\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/CacheException.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.cache;\r\n\r\nimport com.impetus.kundera.KunderaException;\r\n\r\n/**\r\n * When something goes wrong in cache.\r\n * \r\n * @author animesh.kumar\r\n * \r\n */\r\npublic class CacheException extends KunderaException\r\n{\r\n\r\n    /** The Constant serialVersionUID. */\r\n    private static final long serialVersionUID = 1L;\r\n\r\n    /**\r\n     * Instantiates a new cache exception.\r\n     * \r\n     * @param s\r\n     *            the s\r\n     */\r\n    public CacheException(final String s)\r\n    {\r\n        super(s);\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new cache exception.\r\n     * \r\n     * @param s\r\n     *            the s\r\n     * @param e\r\n     *            the e\r\n     */\r\n    public CacheException(final String s, final Throwable e)\r\n    {\r\n        super(s, e);\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new cache exception.\r\n     * \r\n     * @param e\r\n     *            the e\r\n     */\r\n    public CacheException(final Throwable e)\r\n    {\r\n        super(e);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/CacheProvider.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.cache;\r\n\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.Cache;\r\n\r\n/**\r\n * CacheProvider.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic interface CacheProvider\r\n{\r\n\r\n    /**\r\n     * Called once to load up the CacheManager.\r\n     * \r\n     * @param properties\r\n     *            the properties\r\n     * @throws CacheException\r\n     *             the cache exception\r\n     */\r\n    void init(Map<?, ?> properties);\r\n\r\n    /**\r\n     * Inits the.\r\n     * \r\n     * @param cacheResourceName\r\n     *            the cache resource name\r\n     * @throws CacheException\r\n     *             the cache exception\r\n     */\r\n    void init(String cacheResourceName);\r\n\r\n    /**\r\n     * Creates cache for a given name.\r\n     * \r\n     * @param name\r\n     *            the name\r\n     * @return the cache\r\n     * @throws CacheException\r\n     *             the cache exception\r\n     */\r\n    Cache createCache(String name);\r\n\r\n    /**\r\n     * Returns cache for a given cache name.\r\n     * \r\n     * @param name\r\n     *            Cache Name\r\n     * @return the cache\r\n     * @throws CacheException\r\n     *             the cache exception\r\n     */\r\n    Cache getCache(String name);\r\n\r\n    /**\r\n     * Shutdown cache.\r\n     */\r\n    void shutdown();\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/ElementCollectionCacheManager.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.cache;\r\n\r\nimport java.util.Collection;\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.Constants;\r\nimport com.impetus.kundera.utils.DeepEquals;\r\n\r\n/**\r\n * Cache for holding element collection column names and corresponding objects\r\n * This is a singleton class TODO: Improve singleton implementation code, think\r\n * performance overhead due to synchronization TODO: Think of a better way to\r\n * handle element collection object handling. better remove this cache\r\n * altogether\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class ElementCollectionCacheManager\r\n{\r\n    /** log for this class. */\r\n    private static Logger log = LoggerFactory.getLogger(ElementCollectionCacheManager.class);\r\n\r\n    /* Single instance */\r\n    /** The instance. */\r\n    private static ElementCollectionCacheManager instance;\r\n\r\n    /**\r\n     * Instantiates a new element collection cache manager.\r\n     */\r\n    private ElementCollectionCacheManager()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * Gets the single instance of ElementCollectionCacheManager.\r\n     * \r\n     * @return single instance of ElementCollectionCacheManager\r\n     */\r\n    public static synchronized ElementCollectionCacheManager getInstance()\r\n    {\r\n        if (instance == null)\r\n        {\r\n            instance = new ElementCollectionCacheManager();\r\n        }\r\n        return instance;\r\n    }\r\n\r\n    /**\r\n     * Mapping between Row Key and (Map of element collection objects and\r\n     * element collection object name).\r\n     */\r\n    private static Map<Object, Map<Object, String>> elementCollectionCache;\r\n\r\n    /**\r\n     * Gets the element collection cache.\r\n     * \r\n     * @return the elementCollectionCache\r\n     */\r\n    public Map<Object, Map<Object, String>> getElementCollectionCache()\r\n    {\r\n        if (this.elementCollectionCache == null)\r\n        {\r\n            this.elementCollectionCache = new HashMap<Object, Map<Object, String>>();\r\n        }\r\n        return this.elementCollectionCache;\r\n    }\r\n\r\n    /**\r\n     * Checks if is cache empty.\r\n     * \r\n     * @return true, if is cache empty\r\n     */\r\n    public boolean isCacheEmpty()\r\n    {\r\n        return elementCollectionCache == null || elementCollectionCache.isEmpty();\r\n    }\r\n\r\n    /**\r\n     * Adds the element collection cache mapping.\r\n     * \r\n     * @param rowKey\r\n     *            the row key\r\n     * @param elementCollectionObject\r\n     *            the element collection object\r\n     * @param elementCollObjectName\r\n     *            the element coll object name\r\n     */\r\n    public void addElementCollectionCacheMapping(Object rowKey, Object elementCollectionObject,\r\n            String elementCollObjectName)\r\n    {\r\n        Map embeddedObjectMap = new HashMap<Object, String>();\r\n        if (getElementCollectionCache().get(rowKey) == null)\r\n        {\r\n            embeddedObjectMap.put(elementCollectionObject, elementCollObjectName);\r\n            getElementCollectionCache().put(rowKey, embeddedObjectMap);\r\n        }\r\n        else\r\n        {\r\n            getElementCollectionCache().get(rowKey).put(elementCollectionObject, elementCollObjectName);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Gets the element collection object name.\r\n     * \r\n     * @param rowKey\r\n     *            the row key\r\n     * @param elementCollectionObject\r\n     *            the element collection object\r\n     * @return the element collection object name\r\n     */\r\n    public String getElementCollectionObjectName(Object rowKey, Object elementCollectionObject)\r\n    {\r\n        if (getElementCollectionCache().isEmpty() || getElementCollectionCache().get(rowKey) == null)\r\n        {\r\n            log.debug(\"No element collection object map found in cache for Row key \" + rowKey);\r\n            return null;\r\n        }\r\n        else\r\n        {\r\n            Map<Object, String> elementCollectionObjectMap = getElementCollectionCache().get(rowKey);\r\n            String elementCollectionObjectName = elementCollectionObjectMap.get(elementCollectionObject);\r\n            if (elementCollectionObjectName == null)\r\n            {\r\n                for (Object obj : elementCollectionObjectMap.keySet())\r\n                {\r\n                    if (DeepEquals.deepEquals(elementCollectionObject, obj))\r\n                    {\r\n                        elementCollectionObjectName = elementCollectionObjectMap.get(obj);\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n\r\n            if (elementCollectionObjectName == null)\r\n            {\r\n                log.debug(\"No element collection object name found in cache for object:\" + elementCollectionObject);\r\n                return null;\r\n            }\r\n            else\r\n            {\r\n                return elementCollectionObjectName;\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Gets the last element collection object count.\r\n     * \r\n     * @param rowKey\r\n     *            the row key\r\n     * @return the last element collection object count\r\n     */\r\n    public int getLastElementCollectionObjectCount(Object rowKey)\r\n    {\r\n        if (getElementCollectionCache().get(rowKey) == null)\r\n        {\r\n            log.debug(\"No element collection object map found in cache for Row key \" + rowKey);\r\n            return -1;\r\n        }\r\n        else\r\n        {\r\n            Map<Object, String> elementCollectionMap = getElementCollectionCache().get(rowKey);\r\n            Collection<String> elementCollectionObjectNames = elementCollectionMap.values();\r\n            int max = 0;\r\n\r\n            for (String s : elementCollectionObjectNames)\r\n            {\r\n                String elementCollectionCountStr = s.substring(s.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) + 1);\r\n                int elementCollectionCount = 0;\r\n                try\r\n                {\r\n                    elementCollectionCount = Integer.parseInt(elementCollectionCountStr);\r\n                }\r\n                catch (NumberFormatException e)\r\n                {\r\n                    log.error(\"Invalid element collection Object name \" + s);\r\n                    throw new CacheException(\"Invalid element collection Object name \" + s,e);\r\n                }\r\n                if (elementCollectionCount > max)\r\n                {\r\n                    max = elementCollectionCount;\r\n                }\r\n            }\r\n            return max;\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Clear cache.\r\n     */\r\n    public void clearCache()\r\n    {\r\n        this.elementCollectionCache = null;\r\n        try\r\n        {\r\n            finalize();\r\n        }\r\n        catch (Throwable e)\r\n        {\r\n            log.warn(\"Unable to reclaim memory while clearing ElementCollection cache. Nothing to worry, will be taken care of by GC\");\r\n        }\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/NonOperationalCache.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.cache;\r\n\r\n/**\r\n * NonOperational Cache implementation.\r\n * \r\n * @author animesh.kumar\r\n * \r\n */\r\npublic class NonOperationalCache implements Cache, javax.persistence.Cache\r\n{\r\n\r\n    /* @see com.impetus.kundera.cache.Cache#size() */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.Cache#size()\r\n     */\r\n    @Override\r\n    public int size()\r\n    {\r\n        return 0;\r\n    }\r\n\r\n    /*\r\n     * @see com.impetus.kundera.cache.Cache#put(java.lang.Object,\r\n     * java.lang.Object)\r\n     */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.Cache#put(java.lang.Object,\r\n     * java.lang.Object)\r\n     */\r\n    @Override\r\n    public void put(final Object key, final Object value)\r\n    {\r\n    }\r\n\r\n    /* @see com.impetus.kundera.cache.Cache#get(java.lang.Object) */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.Cache#get(java.lang.Object)\r\n     */\r\n    @Override\r\n    public Object get(final Object key)\r\n    {\r\n        return null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.Cache#contains(java.lang.Class, java.lang.Object)\r\n     */\r\n    @Override\r\n    public boolean contains(Class paramClass, Object paramObject)\r\n    {\r\n        return false;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.Cache#evict(java.lang.Class, java.lang.Object)\r\n     */\r\n    @Override\r\n    public void evict(Class paramClass, Object paramObject)\r\n    {\r\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\r\n        // do nothing.\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.Cache#evict(java.lang.Class)\r\n     */\r\n    @Override\r\n    public void evict(Class paramClass)\r\n    {\r\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\r\n        // do nothing.\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.Cache#evictAll()\r\n     */\r\n    @Override\r\n    public void evictAll()\r\n    {\r\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\r\n        // do nothing.\r\n\r\n    }\r\n\r\n    @Override\r\n    public <T> T unwrap(Class<T> arg0)\r\n    {\r\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\r\n        // do nothing.\r\n        return null;\r\n    }\r\n\r\n    \r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/cache/NonOperationalCacheProvider.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.cache;\r\n\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.Cache;\r\n\r\n/**\r\n * NonOperational cache provider.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class NonOperationalCacheProvider implements CacheProvider\r\n{\r\n\r\n    /** The cache. */\r\n    private Cache cache = new NonOperationalCache();\r\n\r\n    /**\r\n     * Instantiates a new non operational cache provider.\r\n     */\r\n    public NonOperationalCacheProvider()\r\n    {\r\n    }\r\n\r\n    /* @see com.impetus.kundera.cache.CacheProvider#init(java.util.Map) */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.CacheProvider#init(java.util.Map)\r\n     */\r\n    @Override\r\n    public void init(Map<?, ?> properties)\r\n    {\r\n    }\r\n\r\n    /*\r\n     * @see\r\n     * com.impetus.kundera.cache.CacheProvider#createCache(java.lang.String)\r\n     */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.cache.CacheProvider#createCache(java.lang.String)\r\n     */\r\n    @Override\r\n    public Cache createCache(String name)\r\n    {\r\n        return cache;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.CacheProvider#getCache(java.lang.String)\r\n     */\r\n    @Override\r\n    public Cache getCache(String name) throws CacheException\r\n    {\r\n        return null;\r\n    }\r\n\r\n    /* @see com.impetus.kundera.cache.CacheProvider#shutdown() */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.CacheProvider#shutdown()\r\n     */\r\n    @Override\r\n    public void shutdown()\r\n    {\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.CacheProvider#init(java.lang.String)\r\n     */\r\n    @Override\r\n    public void init(String cacheResourceName) throws CacheException\r\n    {\r\n\r\n    }\r\n\r\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/AnnotationDiscoveryListener.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.classreading;\r\n\r\n/**\r\n * The Interface AnnotationDiscoveryListener.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic interface AnnotationDiscoveryListener\r\n{\r\n\r\n    /**\r\n     * Discovered.\r\n     * \r\n     * @param className\r\n     *            the class name\r\n     */\r\n    void discovered(String className);\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/ClassFileIterator.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.classreading;\r\n\r\nimport java.io.File;\r\nimport java.io.FileInputStream;\r\nimport java.io.FileNotFoundException;\r\nimport java.io.InputStream;\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\n/**\r\n * The Class ClassFileIterator.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class ClassFileIterator implements ResourceIterator\r\n{\r\n\r\n    /** The files. */\r\n    private List<File> files;\r\n\r\n    /** The index. */\r\n    private int index = 0;\r\n\r\n    /**\r\n     * Instantiates a new class file iterator.\r\n     * \r\n     * @param file\r\n     *            the file\r\n     * @param filter\r\n     *            the filter\r\n     */\r\n    public ClassFileIterator(File file, Filter filter)\r\n    {\r\n        files = new ArrayList<File>();\r\n\r\n        init(files, file, filter);\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new class file iterator.\r\n     * \r\n     * @param fileToAdd\r\n     *            the file to add\r\n     */\r\n    public ClassFileIterator(File fileToAdd)\r\n    {\r\n        files = new ArrayList<File>();\r\n        files.add(fileToAdd);\r\n    }\r\n\r\n    /**\r\n     * Creates the.\r\n     * \r\n     * @param list\r\n     *            the list\r\n     * @param dir\r\n     *            the dir\r\n     * @param filter\r\n     *            the filter\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    private static void init(List<File> list, File dir, Filter filter)\r\n    {\r\n        File[] files = dir.listFiles();\r\n        for (int i = 0; i < files.length; i++)\r\n        {\r\n            if (files[i].isDirectory())\r\n            {\r\n                init(list, files[i], filter);\r\n            }\r\n            else\r\n            {\r\n                if (filter == null || filter.accepts(files[i].getAbsolutePath()))\r\n                {\r\n                    list.add(files[i]);\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    public final InputStream next()\r\n    {\r\n        if (index >= files.size())\r\n            return null;\r\n        File fp = (File) files.get(index++);\r\n        try\r\n        {\r\n            return new FileInputStream(fp);\r\n        }\r\n        catch (FileNotFoundException e)\r\n        {\r\n            throw new ResourceReadingException(\"Couldn't read file \" + fp, e);\r\n        }\r\n    }\r\n\r\n    public void close()\r\n    {\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/ClasspathReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.classreading;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.net.URLClassLoader;\nimport java.net.URLDecoder;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.StringTokenizer;\nimport java.util.jar.JarEntry;\nimport java.util.jar.JarFile;\nimport java.util.jar.Manifest;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.loader.PersistenceXMLLoader.AllowedProtocol;\n\n/**\n * The Class ClasspathReader.\n * \n * @author animesh.kumar\n */\npublic class ClasspathReader extends Reader\n{\n    private static Logger logger = LoggerFactory.getLogger(ClasspathReader.class);\n\n    /**\n     * The filter.\n     */\n    private Filter filter;\n\n    /** The classes to scan. */\n    private List<String> classesToScan;\n\n    /**\n     * Instantiates a new classpath reader.\n     */\n    public ClasspathReader()\n    {\n        filter = new FilterImpl();\n    }\n\n    /**\n     * Instantiates a new classpath reader.\n     * \n     * @param classesToScan\n     *            the classes to scan\n     */\n    public ClasspathReader(List<String> classesToScan)\n    {\n        this();\n        this.classesToScan = classesToScan;\n    }\n\n    @Override\n    public final void read()\n    {\n        URL[] resources = findResources();\n        for (URL resource : resources)\n        {\n\n            try\n            {\n                ResourceIterator itr = getResourceIterator(resource, getFilter());\n\n                InputStream is = null;\n                while ((is = itr.next()) != null)\n                {\n                    scanClass(is);\n                }\n            }\n            catch (IOException e)\n            {\n                logger.error(\"Error during reading via classpath, Caused by:\" + e.getMessage());\n                throw new ResourceReadingException(e);\n            }\n        }\n    }\n\n    /**\n     * Uses the java.class.path system property to obtain a list of URLs that\n     * represent the CLASSPATH\n     * \n     * @return the URl[]\n     */\n    @SuppressWarnings(\"deprecation\")\n    @Override\n    public final URL[] findResourcesByClasspath()\n    {\n        List<URL> list = new ArrayList<URL>();\n        String classpath = System.getProperty(\"java.class.path\");\n        StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);\n\n        while (tokenizer.hasMoreTokens())\n        {\n            String path = tokenizer.nextToken();\n\n            File fp = new File(path);\n            if (!fp.exists())\n                throw new ResourceReadingException(\"File in java.class.path does not exist: \" + fp);\n            try\n            {\n                list.add(fp.toURL());\n            }\n            catch (MalformedURLException e)\n            {\n                throw new ResourceReadingException(e);\n            }\n        }\n        return list.toArray(new URL[list.size()]);\n    }\n\n    /**\n     * Scan class resource in the provided urls with the additional Class-Path\n     * of each jar checking\n     * \n     * @param classRelativePath\n     *            relative path to a class resource\n     * @param urls\n     *            urls to be checked\n     * @return list of class path included in the base package\n     */\n    private URL[] findResourcesInUrls(String classRelativePath, URL[] urls)\n    {\n        List<URL> list = new ArrayList<URL>();\n        for (URL url : urls)\n        {\n            if (AllowedProtocol.isValidProtocol(url.getProtocol().toUpperCase()) && url.getPath().endsWith(\".jar\"))\n            {\n                try\n                {\n                    JarFile jarFile = new JarFile(URLDecoder.decode(url.getFile(), Constants.CHARSET_UTF8));\n\n                    // Checking the dependencies of this jar file\n                    Manifest manifest = jarFile.getManifest();\n                    if (manifest != null)\n                    {\n                        String classPath = manifest.getMainAttributes().getValue(\"Class-Path\");\n                        // Scan all entries in the classpath if they are\n                        // specified in the jar\n                        if (!StringUtils.isEmpty(classPath))\n                        {\n                            List<URL> subList = new ArrayList<URL>();\n                            for (String cpEntry : classPath.split(\" \"))\n                            {\n                                try\n                                {\n                                    subList.add(new URL(cpEntry));\n                                }\n                                catch (MalformedURLException e)\n                                {\n                                    URL subResources = ClasspathReader.class.getClassLoader().getResource(cpEntry);\n                                    if (subResources != null)\n                                    {\n                                        subList.add(subResources);\n                                    }\n                                    // logger.warn(\"Incorrect URL in the classpath of a jar file [\"\n                                    // + url.toString()\n                                    // + \"]: \" + cpEntry);\n                                }\n                            }\n                            list.addAll(Arrays.asList(findResourcesInUrls(classRelativePath,\n                                    subList.toArray(new URL[subList.size()]))));\n                        }\n                    }\n                    JarEntry present = jarFile.getJarEntry(classRelativePath + \".class\");\n                    if (present != null)\n                    {\n                        list.add(url);\n                    }\n                }\n                catch (IOException e)\n                {\n                    logger.warn(\"Error during loading from context , Caused by:\" + e.getMessage());\n                }\n\n            }\n            else if (url.getPath().endsWith(\"/\"))\n            {\n                File file = new File(url.getPath() + classRelativePath + \".class\");\n                if (file.exists())\n                {\n                    try\n                    {\n                        list.add(file.toURL());\n                    }\n                    catch (MalformedURLException e)\n                    {\n                        throw new ResourceReadingException(e);\n                    }\n                }\n            }\n\n        }\n        return list.toArray(new URL[list.size()]);\n    }\n\n    /**\n     * Scan class resources into a basePackagetoScan path.\n     * \n     * @return list of class path included in the base package\n     */\n\n    private final URL[] findResourcesByContextLoader()\n    {\n        List<URL> list = new ArrayList<URL>();\n        ClassLoader classLoader = this.getClass().getClassLoader();\n        assert classLoader != null;        \n        URL[] urls = ((URLClassLoader) classLoader).getURLs();\n        \n        for (String fullyQualifiedClassName : classesToScan)\n        {\n            String classRelativePath = fullyQualifiedClassName.replace(\".\", \"/\");\n            list.addAll(Arrays.asList(findResourcesInUrls(classRelativePath, urls)));\n        }\n\n        return list.toArray(new URL[list.size()]);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.classreading.Reader#findResources()\n     */\n    @Override\n    public URL[] findResources()\n    {\n        URL[] result = null;\n\n        if (classesToScan != null && !classesToScan.isEmpty())\n        {\n            result = findResourcesByContextLoader();\n        }\n        // else\n        // {\n        // result = findResourcesByClasspath();\n        // }\n        return result;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.classreading.Reader#getFilter()\n     */\n\n    public final Filter getFilter()\n    {\n        return filter;\n    }\n\n    /**\n     * Sets the filter.\n     * \n     * @param filter\n     *            the new filter\n     */\n    public final void setFilter(Filter filter)\n    {\n        this.filter = filter;\n    }\n    \n    @Override\n    public InputStream[] findResourcesAsStream()\n    {\n        ClassLoader classLoader = this.getClass().getClassLoader();\n        assert classLoader != null;\n\n        InputStream[] iStreams = null;\n        int counter = 0;\n        if(classesToScan != null)\n        {\n            for (String fullyQualifiedClassName : classesToScan)\n            {\n                if (iStreams == null)\n                {\n                    iStreams = new InputStream[classesToScan.size()];\n                }\n\n                String classRelativePath = fullyQualifiedClassName.replace(\".\", \"/\");\n                InputStream is = this.getClass().getClassLoader().getResourceAsStream(classRelativePath + \".class\");\n                iStreams[counter++] = is;\n            }\n        }\n        return iStreams;\n\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/Filter.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.classreading;\r\n\r\n/**\r\n * Interface to filter out filenames.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic interface Filter\r\n{\r\n\r\n    /**\r\n     * Accepts.\r\n     * \r\n     * @param filename\r\n     *            the filename\r\n     * \r\n     * @return true, if successful\r\n     */\r\n    boolean accepts(String filename);\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/FilterImpl.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.classreading;\r\n\r\n/**\r\n * Basic implementation to skip well-known packages and allow only *.class files\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class FilterImpl implements Filter\r\n{\r\n\r\n    /** The ignored packages. */\r\n    private transient String[] ignoredPackages = { \"javax\", \"java\", \"sun\", \"com.sun\", \"javassist\" };\r\n\r\n    /* @see com.impetus.kundera.classreading.Filter#accepts(java.lang.String) */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.classreading.Filter#accepts(java.lang.String)\r\n     */\r\n    @Override\r\n    public final boolean accepts(String filename)\r\n    {\r\n        if (filename.endsWith(\".class\"))\r\n        {\r\n            if (filename.startsWith(\"/\"))\r\n            {\r\n                filename = filename.substring(1);\r\n            }\r\n            if (!ignoreScan(filename.replace('/', '.')))\r\n            {\r\n                return true;\r\n            }\r\n        }\r\n        return false;\r\n    }\r\n\r\n    /**\r\n     * Ignore scan.\r\n     * \r\n     * @param intf\r\n     *            the intf\r\n     * \r\n     * @return true, if successful\r\n     */\r\n    private boolean ignoreScan(String intf)\r\n    {\r\n        for (String ignored : ignoredPackages)\r\n        {\r\n            if (intf.startsWith(ignored + \".\"))\r\n            {\r\n                return true;\r\n            }\r\n        }\r\n        return false;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/JarFileIterator.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.classreading;\r\n\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.util.jar.JarEntry;\r\nimport java.util.jar.JarInputStream;\r\n\r\n/**\r\n * Iterates through a Jar file for each file resource.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic final class JarFileIterator implements ResourceIterator\r\n{\r\n\r\n    /** The jar. */\r\n    private JarInputStream jar;\r\n\r\n    /** The next. */\r\n    private JarEntry next;\r\n\r\n    /** The filter. */\r\n    private Filter filter;\r\n\r\n    /** The initial. */\r\n    private boolean initial = true;\r\n\r\n    /** The closed. */\r\n    private boolean closed = false;\r\n\r\n    /**\r\n     * Instantiates a new jar file iterator.\r\n     * \r\n     * @param file\r\n     *            the file\r\n     * @param filter\r\n     *            the filter\r\n     * \r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    /*\r\n     * public JarFileIterator(File file, Filter filter) throws\r\n     * FileNotFoundException { this(new FileInputStream(file), filter); }\r\n     */\r\n\r\n    /**\r\n     * Instantiates a new jar file iterator.\r\n     * \r\n     * @param is\r\n     *            the is\r\n     * @param filter\r\n     *            the filter\r\n     * \r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    public JarFileIterator(InputStream is, Filter filter)\r\n    {\r\n        this.filter = filter;\r\n        try\r\n        {\r\n            jar = new JarInputStream(is);\r\n        }\r\n        catch (IOException e)\r\n        {\r\n            throw new ResourceReadingException(e);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Sets the next.\r\n     */\r\n    private void setNext()\r\n    {\r\n        initial = true;\r\n        try\r\n        {\r\n            if (next != null)\r\n            {\r\n                jar.closeEntry();\r\n            }\r\n            next = null;\r\n\r\n            do\r\n            {\r\n                next = jar.getNextJarEntry();\r\n            }\r\n            while (next != null && (next.isDirectory() || (filter == null || !filter.accepts(next.getName()))));\r\n\r\n            if (next == null)\r\n            {\r\n                close();\r\n            }\r\n        }\r\n        catch (IOException e)\r\n        {\r\n            throw new ResourceReadingException(\"Failed to browse jar:\", e);\r\n        }\r\n    }\r\n\r\n    public InputStream next()\r\n    {\r\n        if (closed || (next == null && !initial))\r\n            return null;\r\n\r\n        setNext();\r\n\r\n        if (next == null)\r\n            return null;\r\n        return new InputStreamWrapper(jar);\r\n    }\r\n\r\n    public void close()\r\n    {\r\n        try\r\n        {\r\n            closed = true;\r\n            jar.close();\r\n        }\r\n        catch (IOException ignored)\r\n        {\r\n\r\n        }\r\n\r\n    }\r\n\r\n    /**\r\n     * The Class InputStreamWrapper.\r\n     */\r\n    class InputStreamWrapper extends InputStream\r\n    {\r\n\r\n        /** The delegate. */\r\n        private InputStream delegate;\r\n\r\n        /**\r\n         * Instantiates a new input stream wrapper.\r\n         * \r\n         * @param delegate\r\n         *            the delegate\r\n         */\r\n        public InputStreamWrapper(InputStream delegate)\r\n        {\r\n            this.delegate = delegate;\r\n        }\r\n\r\n        public int read() throws IOException\r\n        {\r\n            return delegate.read();\r\n        }\r\n\r\n        public int read(byte[] bytes) throws IOException\r\n        {\r\n            return delegate.read(bytes);\r\n        }\r\n\r\n        public int read(byte[] bytes, int i, int i1) throws IOException\r\n        {\r\n            return delegate.read(bytes, i, i1);\r\n        }\r\n\r\n        public long skip(long l) throws IOException\r\n        {\r\n            return delegate.skip(l);\r\n        }\r\n\r\n        public int available() throws IOException\r\n        {\r\n            return delegate.available();\r\n        }\r\n\r\n        public void close() throws IOException\r\n        {\r\n            // ignored\r\n        }\r\n\r\n        public void mark(int i)\r\n        {\r\n            delegate.mark(i);\r\n        }\r\n\r\n        public void reset() throws IOException\r\n        {\r\n            try\r\n            {\r\n                delegate.reset();\r\n            }\r\n            catch (IOException e)\r\n            {\r\n                throw e;\r\n            }\r\n        }\r\n\r\n        public boolean markSupported()\r\n        {\r\n            return delegate.markSupported();\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/Reader.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.classreading;\r\n\r\nimport java.io.BufferedInputStream;\r\nimport java.io.DataInputStream;\r\nimport java.io.File;\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.net.MalformedURLException;\r\nimport java.net.URL;\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport javassist.bytecode.AnnotationsAttribute;\r\nimport javassist.bytecode.ClassFile;\r\nimport javassist.bytecode.annotation.Annotation;\r\n\r\nimport com.impetus.kundera.loader.PersistenceXMLLoader.AllowedProtocol;\r\n\r\n/**\r\n * Base class-reader.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic abstract class Reader\r\n{\r\n\r\n    /** The valid annotations. */\r\n    private List<String> validAnnotations = new ArrayList<String>();\r\n\r\n    /** The annotation discovery listeners. */\r\n    private List<AnnotationDiscoveryListener> annotationDiscoveryListeners = new ArrayList<AnnotationDiscoveryListener>();\r\n\r\n    /**\r\n     * Instantiates a new reader.\r\n     */\r\n    public Reader()\r\n    {\r\n    }\r\n\r\n    /**\r\n     * Scan class.\r\n     * \r\n     * @param bits\r\n     *            the bits\r\n     * \r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    public void scanClass(InputStream bits) throws IOException\r\n    {\r\n        DataInputStream dstream = new DataInputStream(new BufferedInputStream(bits));\r\n        ClassFile cf = null;\r\n        try\r\n        {\r\n            cf = new ClassFile(dstream);\r\n\r\n            String className = cf.getName();\r\n            List<String> annotations = new ArrayList<String>();\r\n\r\n            accumulateAnnotations(annotations, (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.visibleTag));\r\n            accumulateAnnotations(annotations,\r\n                    (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.invisibleTag));\r\n\r\n            // iterate through all valid annotations\r\n            for (String validAnn : getValidAnnotations())\r\n            {\r\n                // check if the current class has one?\r\n                if (annotations.contains(validAnn))\r\n                {\r\n                    // fire all listeners\r\n                    for (AnnotationDiscoveryListener listener : getAnnotationDiscoveryListeners())\r\n                    {\r\n                        listener.discovered(className);\r\n                    }\r\n                }\r\n            }\r\n\r\n        }\r\n        finally\r\n        {\r\n            dstream.close();\r\n            bits.close();\r\n        }\r\n    }\r\n\r\n    // helper method to accumulate annotations.\r\n    /**\r\n     * Accumulate annotations.\r\n     * \r\n     * @param annotations\r\n     *            the annotations\r\n     * @param annatt\r\n     *            the annatt\r\n     */\r\n    public void accumulateAnnotations(List<String> annotations, AnnotationsAttribute annatt)\r\n    {\r\n        if (null == annatt)\r\n        {\r\n            return;\r\n        }\r\n        for (Annotation ann : annatt.getAnnotations())\r\n        {\r\n            annotations.add(ann.getTypeName());\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Gets the resource iterator.\r\n     * \r\n     * @param url\r\n     *            the url\r\n     * @param filter\r\n     *            the filter\r\n     * \r\n     * @return the resource iterator\r\n     * \r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    public ResourceIterator getResourceIterator(URL url, Filter filter)\r\n    {\r\n        String urlString = url.toString();\r\n        try\r\n        {\r\n            if (urlString.endsWith(\"!/\"))\r\n            {\r\n                urlString = urlString.substring(4);\r\n                urlString = urlString.substring(0, urlString.length() - 2);\r\n                url = new URL(urlString);\r\n            }\r\n\r\n            if (urlString.endsWith(\".class\"))\r\n            {\r\n                File f = new File(url.getPath());\r\n                return new ClassFileIterator(f);\r\n            }\r\n            else if (!urlString.endsWith(\"/\"))\r\n            {\r\n                return new JarFileIterator(url.openStream(), filter);\r\n            }\r\n            else\r\n            {\r\n                if (!url.getProtocol().equals(\"file\"))\r\n                {\r\n                    throw new ResourceReadingException(\"Unable to understand protocol: \" + url.getProtocol());\r\n                }\r\n\r\n                File f = new File(url.getPath());\r\n                if (f.isDirectory() || url.getProtocol().toUpperCase().equals(AllowedProtocol.VFS.name()))\r\n                {\r\n                    return new ClassFileIterator(f, filter);\r\n                }\r\n                else\r\n                {\r\n                    return new JarFileIterator(url.openStream(), filter);\r\n                }\r\n            }\r\n        }\r\n        catch (MalformedURLException e)\r\n        {\r\n            throw new ResourceReadingException(e);\r\n        }\r\n        catch (IOException e)\r\n        {\r\n            throw new ResourceReadingException(e);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Gets the valid annotations.\r\n     * \r\n     * @return the valid annotations\r\n     */\r\n    public List<String> getValidAnnotations()\r\n    {\r\n        return validAnnotations;\r\n    }\r\n\r\n    /**\r\n     * Adds the valid annotations.\r\n     * \r\n     * @param annotation\r\n     *            the annotation\r\n     */\r\n    public void addValidAnnotations(String annotation)\r\n    {\r\n        this.validAnnotations.add(annotation);\r\n    }\r\n\r\n    /**\r\n     * Gets the annotation discovery listeners.\r\n     * \r\n     * @return the annotation discovery listeners\r\n     */\r\n    public List<AnnotationDiscoveryListener> getAnnotationDiscoveryListeners()\r\n    {\r\n        return annotationDiscoveryListeners;\r\n    }\r\n\r\n    /**\r\n     * Adds the annotation discovery listeners.\r\n     * \r\n     * @param annotationDiscoveryListener\r\n     *            the annotation discovery listener\r\n     */\r\n    public void addAnnotationDiscoveryListeners(AnnotationDiscoveryListener annotationDiscoveryListener)\r\n    {\r\n        this.annotationDiscoveryListeners.add(annotationDiscoveryListener);\r\n    }\r\n\r\n    /**\r\n     * Read.\r\n     */\r\n    public abstract void read();\r\n\r\n    /**\r\n     * Gets the filter.\r\n     * \r\n     * @return the filter\r\n     */\r\n    public abstract Filter getFilter();\r\n\r\n    /**\r\n     * Find resources.\r\n     * \r\n     * @return the uR l[]\r\n     */\r\n    public abstract URL[] findResources();\r\n\r\n\r\n    /**\r\n     * Find resources.\r\n     * \r\n     * @return the uR l[]\r\n     */\r\n    public abstract InputStream[] findResourcesAsStream();\r\n\r\n\r\n    /**\r\n     * Find resources by classpath.\r\n     * \r\n     * @return the uR l[]\r\n     */\r\n    public abstract URL[] findResourcesByClasspath();\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/ResourceIterator.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.classreading;\r\n\r\nimport java.io.InputStream;\r\n\r\n/**\r\n * Interface for Resource Iterator, usually files.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic interface ResourceIterator\r\n{\r\n\r\n    /**\r\n     * Please close after use.\r\n     * \r\n     * @return null if no more streams left to iterate on\r\n     */\r\n    InputStream next();\r\n\r\n    /**\r\n     * Close.\r\n     */\r\n    void close();\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/classreading/ResourceReadingException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.classreading;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * Exception class for all exception scenarios involving resource reading.\n * \n * @author amresh.singh\n * \n */\npublic class ResourceReadingException extends KunderaException\n{\n\n    private static final long serialVersionUID = 2586557929464852258L;\n\n    /**\n     * \n     */\n    public ResourceReadingException()\n    {\n    }\n\n    /**\n     * @param arg0\n     */\n    public ResourceReadingException(String arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     */\n    public ResourceReadingException(Throwable arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     * @param arg1\n     */\n    public ResourceReadingException(String arg0, Throwable arg1)\n    {\n        super(arg0, arg1);\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/client/Client.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.client;\r\n\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.Query;\r\n\r\nimport com.impetus.kundera.generator.AutoGenerator;\r\nimport com.impetus.kundera.generator.Generator;\r\nimport com.impetus.kundera.graph.Node;\r\nimport com.impetus.kundera.index.IndexManager;\r\nimport com.impetus.kundera.loader.ClientFactory;\r\nimport com.impetus.kundera.persistence.EntityReader;\r\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\r\n\r\n/**\r\n * In Kundera, <b>Clients</b> act as a translator of JPA calls to\r\n * datastore-specific respective operations call. Clients are constructed via\r\n * {@link ClientFactory} that are configurable in persistence.xml. This makes it\r\n * possible for user to choose a {@link Client} implementation for a particular\r\n * persistence unit.\r\n * \r\n * Client API defines methods that are required to be implemented by various\r\n * clients implementations (Thrift, Mongo etc).\r\n * \r\n * Any new addition of datastore support must implement this API. This is\r\n * because kundera-core - after initialization, caching etc, calls clients\r\n * methods to read from/ write into datastores.\r\n * \r\n * @author vivek.mishra\r\n */\r\npublic interface Client<Q extends Query>\r\n{\r\n\r\n    /**\r\n     * Retrieves an entity from datastore\r\n     * \r\n     * @param entityClass\r\n     *            the entity class\r\n     * @param key\r\n     *            The key of the row\r\n     * @return Entity object\r\n     */\r\n    Object find(Class entityClass, Object key);\r\n\r\n    /**\r\n     * Retrieve <code>columnsToSelect</code> from multiple rows of a\r\n     * column-family.\r\n     * \r\n     * @param <E>\r\n     *            the element type\r\n     * @param entityClass\r\n     *            the entity class\r\n     * @param columnsToSelect\r\n     *            Array of column names that need to be populated into entity\r\n     * @param keys\r\n     *            Array of row keys\r\n     * @return List of entity objects\r\n     */\r\n    <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys);\r\n\r\n    /**\r\n     * Finds entities that match a given set of embedded column values provided\r\n     * in the Map\r\n     * \r\n     * @param <E>\r\n     *            the element type\r\n     * @param entityClass\r\n     *            the entity class\r\n     * @param embeddedColumnMap\r\n     *            Map of embedded column name and their values that are used as\r\n     *            a criteria for finding entities\r\n     * @return the list of entities\r\n     */\r\n    <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap);\r\n\r\n    /**\r\n     * Cleans up client\r\n     */\r\n    void close();\r\n\r\n    /**\r\n     * Removes an entity from datastore for a given primary key\r\n     * \r\n     * @param entity\r\n     *            the entity\r\n     * @param pKey\r\n     *            Primary key of entity to be deleted\r\n     */\r\n    void remove(Object entity, Object pKey);\r\n\r\n    /**\r\n     * Gets the persistence unit.\r\n     * \r\n     * @return the persistence unit\r\n     */\r\n    String getPersistenceUnit();\r\n\r\n    /**\r\n     * Gets the index manager.\r\n     * \r\n     * @return the index manager\r\n     */\r\n    IndexManager getIndexManager();\r\n\r\n    /**\r\n     * Data node to persist entity with specific client.\r\n     * \r\n     * @param node\r\n     *            data node.\r\n     */\r\n    void persist(Node node);\r\n\r\n    void persistJoinTable(JoinTableData joinTableData);\r\n\r\n    /**\r\n     * Returns List of column values for given primary key and column name.\r\n     * \r\n     * @param <E>\r\n     *            Type cast\r\n     * @param schemaName\r\n     *            Schema/Keyspace name.\r\n     * @param tableName\r\n     *            Table/column family name.\r\n     * @param pKeyColumnName\r\n     *            Primary key column name.\r\n     * @param columnName\r\n     *            Name of column to be fetched.\r\n     * @param pKeyColumnValue\r\n     *            primary key value.\r\n     * @return list of values fetched for <columnName>\r\n     */\r\n    <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,\r\n            Object pKeyColumnValue, Class columnJavaType);\r\n\r\n    /**\r\n     * Returns array of primary key for given column name and it's value.\r\n     * \r\n     * @param schemaName\r\n     *            Schema/Keyspace name.\r\n     * @param tableName\r\n     *            table/column family name.\r\n     * @param pKeyName\r\n     *            primary key column name.\r\n     * @param columnName\r\n     *            column name to be used for search.\r\n     * @param columnValue\r\n     *            value for parameterised <columnName>.\r\n     * @param entity\r\n     *            class entity class\r\n     * @return array containing fetched primary keys.\r\n     */\r\n\r\n    Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\r\n            Object columnValue, Class entityClazz);\r\n\r\n    /**\r\n     * Delete rows from given table for given column name and corresponding\r\n     * value..\r\n     * \r\n     * @param schemaName\r\n     *            Schema Name\r\n     * @param tableName\r\n     *            Name of the table\r\n     * @param columnName\r\n     *            Name of the column\r\n     * @param columnValue\r\n     *            Name of column value\r\n     */\r\n    void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue);\r\n\r\n    /**\r\n     * Find list of entities for given column name and column value, if index\r\n     * support is provided..\r\n     * \r\n     * @param colName\r\n     *            the column name\r\n     * @param colValue\r\n     *            the column value\r\n     * @param entityClass\r\n     *            the entity class\r\n     * @return the list list of entities.\r\n     */\r\n    List<Object> findByRelation(String colName, Object colValue, Class entityClazz);\r\n\r\n    /**\r\n     * Returns entity reader instance bind to specific client.\r\n     * \r\n     * @return reader entity reader.\r\n     */\r\n    EntityReader getReader();\r\n\r\n    /**\r\n     * Returns query implementor class, required for initializing client\r\n     * specific query interface.\r\n     * \r\n     * @return class instance of configured query interface.\r\n     */\r\n    Class<Q> getQueryImplementor();\r\n\r\n    /**\r\n     * Enables executing native script specific to a db client\r\n     * \r\n     * \r\n     * @param script\r\n     * @return\r\n     */\r\n    Object executeScript(String script);\r\n\r\n    /**\r\n     * Gets the id generator.\r\n     * \r\n     * @return the id generator\r\n     */\r\n    Generator getIdGenerator();\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/client/ClientBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.NodeLink;\nimport com.impetus.kundera.graph.NodeLink.LinkProperty;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.Relation.ForeignKey;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * Base class for all Client implementations providing common utility methods to\n * them all.\n * \n * @author amresh\n * \n */\npublic abstract class ClientBase\n{\n\n    /** The index manager. */\n    protected IndexManager indexManager;\n    \n \n    /**\n     * @return the autoGenerator\n     */\n    public String getAutoGenerator()\n    {\n       return this.getClientMetadata() != null ? this.getClientMetadata().getAutoGenImplementor() : null;\n    }\n\n    /** persistence unit */\n    protected String persistenceUnit;\n\n    protected boolean isUpdate;\n\n    protected ClientMetadata clientMetadata;\n\n    protected final KunderaMetadata kunderaMetadata;\n\n    protected final boolean showQuery;\n\n    protected Map<String, Object> externalProperties;\n\n    protected ClientBase(final KunderaMetadata kunderaMetadata, final Map<String, Object> properties,\n            final String persistenceUnit)\n    {\n        this.kunderaMetadata = kunderaMetadata;\n        this.externalProperties = properties;\n        this.persistenceUnit = persistenceUnit;\n        this.showQuery = KunderaCoreUtils.isShowQueryEnabled(properties, persistenceUnit, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIndexManager()\n     */\n    public final IndexManager getIndexManager()\n    {\n        return indexManager;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getPersistenceUnit()\n     */\n    public String getPersistenceUnit()\n    {\n        return persistenceUnit;\n    }\n\n    /**\n     * Method to handle\n     * \n     * @param node\n     */\n    public void persist(Node node)\n    {\n        Object entity = node.getData();\n        Object id = node.getEntityId();\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, node.getDataClass());\n        isUpdate = node.isUpdate();\n        List<RelationHolder> relationHolders = getRelationHolders(node);\n        onPersist(metadata, entity, id, relationHolders);\n        id = PropertyAccessorHelper.getId(entity, metadata);\n        node.setEntityId(id);\n        indexNode(node, metadata);\n    }\n\n    public void remove(Object entity, Object pKey){\n        delete(entity, pKey);\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        unIndexNode(metadata, entity,pKey);\n    }\n    protected void unIndexNode(EntityMetadata metadata, Object entity, Object pKey)\n    {\n        if(indexManager!=null)\n        {\n            indexManager.remove(metadata, entity, pKey);\n        }\n    }\n\n    /**\n     * @param node\n     * @return\n     */\n    protected List<RelationHolder> getRelationHolders(Node node)\n    {\n        List<RelationHolder> relationsHolder = new ArrayList<RelationHolder>();\n\n        // Add column value for all parent nodes linked to this node\n        Map<NodeLink, Node> parents = node.getParents();\n        Map<NodeLink, Node> children = node.getChildren();\n\n        if (parents != null && !parents.isEmpty())\n        {\n            for (NodeLink parentNodeLink : parents.keySet())\n            {\n                String linkName = (String) parentNodeLink.getLinkProperty(LinkProperty.LINK_NAME);\n                Object linkValue = parentNodeLink.getLinkProperty(LinkProperty.LINK_VALUE) != null ? parentNodeLink\n                        .getLinkProperty(LinkProperty.LINK_VALUE) : parents.get(parentNodeLink).getEntityId();\n                boolean isSharedByPrimaryKey = (Boolean) parentNodeLink\n                        .getLinkProperty(LinkProperty.IS_SHARED_BY_PRIMARY_KEY);\n                Relation.ForeignKey multiplicity = parentNodeLink.getMultiplicity();\n\n                if (linkName != null && linkValue != null && !isSharedByPrimaryKey\n                        && multiplicity.equals(ForeignKey.ONE_TO_MANY))\n                {\n                    RelationHolder relationHolder = new RelationHolder(linkName, linkValue);\n                    relationsHolder.add(relationHolder);\n                }\n            }\n        }\n\n        // Add column value for all child nodes linked to this node\n        if (children != null && !children.isEmpty())\n        {\n            for (NodeLink childNodeLink : children.keySet())\n            {\n                String linkName = (String) childNodeLink.getLinkProperty(LinkProperty.LINK_NAME);\n                Object linkValue = childNodeLink.getLinkProperty(LinkProperty.LINK_VALUE) != null ? childNodeLink\n                        .getLinkProperty(LinkProperty.LINK_VALUE) : children.get(childNodeLink).getEntityId();\n                boolean isSharedByPrimaryKey = (Boolean) childNodeLink\n                        .getLinkProperty(LinkProperty.IS_SHARED_BY_PRIMARY_KEY);\n                Relation.ForeignKey multiplicity = childNodeLink.getMultiplicity();\n\n                if (linkName != null && linkValue != null && !isSharedByPrimaryKey)\n                {\n                    if (multiplicity.equals(ForeignKey.ONE_TO_ONE) || multiplicity.equals(ForeignKey.MANY_TO_ONE))\n                    {\n                        RelationHolder relationHolder = new RelationHolder(linkName, linkValue);\n                        relationsHolder.add(relationHolder);\n                    }\n                    else if (multiplicity.equals(ForeignKey.MANY_TO_MANY)\n                            && ((Field) childNodeLink.getLinkProperty(LinkProperty.PROPERTY)).getType()\n                                    .isAssignableFrom(Map.class))\n                    {\n                        Object relationTo = ((Node) children.get(childNodeLink)).getData();\n                        RelationHolder relationHolder = new RelationHolder(linkName, relationTo, linkValue);\n                        relationsHolder.add(relationHolder);\n                    }\n                }\n            }\n        }\n        return relationsHolder;\n    }\n\n    /**\n     * @param node\n     * @param entityMetadata\n     */\n    protected void indexNode(Node node, EntityMetadata entityMetadata)\n    {\n        if (indexManager != null)\n        {\n            if (!MetadataUtils.useSecondryIndex(getClientMetadata()))\n            {\n                Map<NodeLink, Node> parents = node.getParents();\n                if (parents != null)\n                {\n                    for (NodeLink parentNodeLink : parents.keySet())\n                    {\n                        indexManager.update(entityMetadata, node.getData(), parentNodeLink\n                                .getLinkProperty(LinkProperty.LINK_VALUE), parents.get(parentNodeLink).getDataClass());\n                    }\n                }\n                else if (node.getChildren() != null)\n                {\n                    Map<NodeLink, Node> children = node.getChildren();\n                    for (NodeLink childNodeLink : children.keySet())\n                    {\n                        if (childNodeLink.getMultiplicity().equals(ForeignKey.MANY_TO_ONE))\n                        {\n                            indexManager.update(entityMetadata, node.getData(), children.get(childNodeLink).getEntityId(),children.get(childNodeLink)\n                                    .getDataClass());\n                        }\n                        else\n                        {\n                            indexManager\n                                    .update(entityMetadata, node.getData(), node.getEntityId(), node.getDataClass());\n                        }\n                    }\n                }\n                else\n                {\n                    indexManager.update(entityMetadata, node.getData(), node.getEntityId(), node.getDataClass());\n                }\n            }\n        }\n    }\n\n    /**\n     * Method to be implemented by inherited classes. On receiving persist event\n     * specific client need to implement this method.\n     * \n     * @param entityMetadata\n     *            entity metadata.\n     * @param entity\n     *            entity object.\n     * @param id\n     *            entity id.\n     * @param rlHolders\n     *            relation holders. This field is only required in case Entity\n     *            is holding up any associations with other entities.\n     */\n    protected abstract void onPersist(EntityMetadata entityMetadata, Object entity, Object id,\n            List<RelationHolder> rlHolders);\n    protected abstract void delete(Object entity, Object pKey);\n\n    public ClientMetadata getClientMetadata()\n    {\n        return this.clientMetadata;\n    }\n\n    public boolean useSecondryIndex()\n    {\n        return clientMetadata != null ? clientMetadata.isUseSecondryIndex() : false;\n    }\n    \n    /**\n     * Method to execute mongo jscripts.\n     * \n     * @param script\n     *            jscript in string format\n     * \n     * @return result object.\n     */\n    public Object executeScript(String script)\n    {\n        throw new UnsupportedOperationException(\"Execute script is not supported by this client\");\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/client/ClientPropertiesSetter.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client;\n\nimport java.util.Map;\n\n/**\n * Defines methods for setting client properties\n * \n * @author amresh.singh\n */\npublic interface ClientPropertiesSetter\n{\n\n    /**\n     * \n     * @param client\n     * @param properties\n     */\n    void populateClientProperties(Client client, Map<String, Object> properties);\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/client/ClientResolver.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.client;\r\n\r\nimport java.lang.reflect.InvocationTargetException;\r\nimport java.lang.reflect.Method;\r\nimport java.util.Map;\r\nimport java.util.concurrent.ConcurrentHashMap;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.PersistenceProperties;\r\nimport com.impetus.kundera.loader.ClientFactory;\r\nimport com.impetus.kundera.loader.GenericClientFactory;\r\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\n\r\n/**\r\n * Resolver class for client. It instantiates client factory and discover\r\n * specific client.\r\n * \r\n * @author vivek.mishra\r\n */\r\npublic final class ClientResolver\r\n{\r\n\r\n    // /** The client factories. */\r\n    static Map<String, ClientFactory> clientFactories = new ConcurrentHashMap<String, ClientFactory>();\r\n\r\n    /** logger instance. */\r\n    private static final Logger logger = LoggerFactory.getLogger(ClientResolver.class);\r\n\r\n    /**\r\n     * Gets the client factory.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the persistence unit\r\n     * @return the client factory\r\n     */\r\n    public static ClientFactory getClientFactory(String persistenceUnit, Map<String, Object> puProperties,final KunderaMetadata kunderaMetadata)\r\n    {\r\n        ClientFactory clientFactory = instantiateClientFactory(persistenceUnit, puProperties, kunderaMetadata);\r\n        clientFactories.put(persistenceUnit, clientFactory);\r\n        return clientFactory;\r\n    }\r\n\r\n    /**\r\n     * Creates new instance of client factory for given persistence unit.\r\n     * \r\n     * @param persistenceUnit\r\n     * @param puProperties\r\n     * @param clientFactory\r\n     * @return new instance of clientFactory\r\n     */\r\n    private static ClientFactory instantiateClientFactory(String persistenceUnit, Map<String, Object> puProperties,\r\n            final KunderaMetadata kunderaMetadata)\r\n    {\r\n        ClientFactory clientFactory = null;\r\n        logger.info(\"Initializing client factory for: \" + persistenceUnit);\r\n        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()\r\n                .getPersistenceUnitMetadata(persistenceUnit);\r\n        String kunderaClientFactory = puProperties != null ? (String) puProperties\r\n                .get(PersistenceProperties.KUNDERA_CLIENT_FACTORY) : null;\r\n        if (kunderaClientFactory == null)\r\n        {\r\n            kunderaClientFactory = persistenceUnitMetadata.getProperties().getProperty(\r\n                    PersistenceProperties.KUNDERA_CLIENT_FACTORY);\r\n        }\r\n\r\n        if (kunderaClientFactory == null)\r\n        {\r\n            throw new ClientResolverException(\r\n                    \"<kundera.client.lookup.class> is missing from persistence.xml, please provide specific client factory. e.g., <property name=\\\"kundera.client.lookup.class\\\" value=\\\"com.impetus.client.cassandra.pelops.PelopsClientFactory\\\" />\");\r\n        }\r\n        try\r\n        {\r\n            clientFactory = (ClientFactory) Class.forName(kunderaClientFactory).newInstance();\r\n\r\n            Method m = GenericClientFactory.class.getDeclaredMethod(\"setPersistenceUnit\", String.class);\r\n            if (!m.isAccessible())\r\n            {\r\n                m.setAccessible(true);\r\n            }\r\n\r\n            m.invoke(clientFactory, persistenceUnit);\r\n\r\n            m = GenericClientFactory.class.getDeclaredMethod(\"setExternalProperties\", Map.class);\r\n            if (!m.isAccessible())\r\n            {\r\n                m.setAccessible(true);\r\n            }\r\n\r\n            m.invoke(clientFactory, puProperties);\r\n            \r\n            m = GenericClientFactory.class.getDeclaredMethod(\"setKunderaMetadata\", KunderaMetadata.class);\r\n            if (!m.isAccessible())\r\n            {\r\n                m.setAccessible(true);\r\n            }\r\n\r\n            m.invoke(clientFactory, kunderaMetadata);\r\n            \r\n        }\r\n        catch (InstantiationException e)\r\n        {\r\n            onError(e);\r\n        }\r\n        catch (IllegalAccessException e)\r\n        {\r\n            onError(e);\r\n        }\r\n        catch (ClassNotFoundException e)\r\n        {\r\n            onError(e);\r\n        }\r\n        catch (SecurityException e)\r\n        {\r\n            onError(e);\r\n        }\r\n        catch (NoSuchMethodException e)\r\n        {\r\n            onError(e);\r\n        }\r\n        catch (IllegalArgumentException e)\r\n        {\r\n            onError(e);\r\n        }\r\n        catch (InvocationTargetException e)\r\n        {\r\n            onError(e);\r\n        }\r\n\r\n        if (clientFactory == null)\r\n        {\r\n            logger.error(\"Client Factory Not Configured For Specified Client Type : \");\r\n            throw new ClientResolverException(\"Client Factory Not Configured For Specified Client Type.\");\r\n        }\r\n        logger.info(\"Finishing factory initialization\");\r\n        return clientFactory;\r\n    }\r\n\r\n    public static ClientFactory getClientFactory(String pu)\r\n    {\r\n        ClientFactory clientFactory = clientFactories.get(pu);\r\n        if (clientFactory != null)\r\n        {\r\n            return clientFactory;\r\n        }\r\n        logger.error(\"Client Factory Not Configured For Specified Client Type : \");\r\n        throw new ClientResolverException(\"Client Factory Not Configured For Specified Client Type.\");\r\n    }\r\n\r\n    /**\r\n     * @param e\r\n     */\r\n    private static void onError(Exception e)\r\n    {\r\n        logger.error(\"Error while initializing client factory, Caused by: .\", e.getMessage());\r\n        throw new ClientResolverException(e);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/client/ClientResolverException.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.client;\r\n\r\nimport com.impetus.kundera.KunderaException;\r\n\r\n/**\r\n * Exception class for error scenarios involving resolution of clients. The\r\n * Class ClientResolverException.\r\n * \r\n * @author impetus\r\n */\r\npublic class ClientResolverException extends KunderaException\r\n{\r\n\r\n    /** The Constant serialVersionUID. */\r\n    private static final long serialVersionUID = 1L;\r\n\r\n    /**\r\n     * \r\n     */\r\n    public ClientResolverException()\r\n    {\r\n        super();\r\n    }\r\n\r\n    /**\r\n     * @param arg0\r\n     * @param arg1\r\n     */\r\n    public ClientResolverException(String arg0, Throwable arg1)\r\n    {\r\n        super(arg0, arg1);\r\n\r\n    }\r\n\r\n    /**\r\n     * @param arg0\r\n     */\r\n    public ClientResolverException(String arg0)\r\n    {\r\n        super(arg0);\r\n\r\n    }\r\n\r\n    /**\r\n     * @param arg0\r\n     */\r\n    public ClientResolverException(Throwable arg0)\r\n    {\r\n        super(arg0);\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/client/EnhanceEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client;\n\nimport java.util.Collections;\nimport java.util.Map;\n\n/**\n * The Class EnhanceEntity.\n * \n * @author vivek.mishra\n */\npublic class EnhanceEntity\n{\n\n    /** The entity. */\n    private Object entity;\n\n    /** The entity id. */\n    private Object entityId;\n\n    /** The relations. */\n    private Map<String, Object> relations;\n\n    public EnhanceEntity()\n    {\n\n    }\n\n    /**\n     * Instantiates a new enhance entity.\n     * \n     * @param entity\n     *            the entity\n     * @param entityId\n     *            the entity id\n     * @param relations\n     *            the relations\n     */\n    public EnhanceEntity(Object entity, Object entityId, Map<String, Object> relations)\n    {\n        super();\n        this.entity = entity;\n        this.entityId = entityId;\n        this.relations = relations;\n    }\n\n    /**\n     * Gets the entity.\n     * \n     * @return the entity\n     */\n    public Object getEntity()\n    {\n        return entity;\n    }\n\n    /**\n     * Gets the entity id.\n     * \n     * @return the entityId\n     */\n    public Object getEntityId()\n    {\n        return entityId;\n    }\n\n    /**\n     * Gets the relations.\n     * \n     * @return the relations\n     */\n    public Map<String, Object> getRelations()\n    {\n        return relations != null ? Collections.unmodifiableMap(relations) : null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/AbstractPropertyReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.InputStream;\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.thoughtworks.xstream.XStream;\n\n/**\n * Abstract property reader parse xml or properties on the basis of\n * {@code PropertyType}\n * \n * @author Kuldeep Mishra\n * \n */\npublic abstract class AbstractPropertyReader\n{\n    /** The log instance. */\n    private static final Logger log = LoggerFactory.getLogger(AbstractPropertyReader.class);\n\n    /** The xStream instance */\n    private XStream xStream;\n\n    protected PersistenceUnitMetadata puMetadata;\n\n    protected Map externalProperties;\n\n    public AbstractPropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        this.externalProperties = externalProperties;\n        this.puMetadata = puMetadata;\n    }\n\n    /**\n     * Reads property file which is given in persistence unit\n     * \n     * @param pu\n     */\n    public void read(String pu)\n    {\n\n        String propertyFileName = null;\n        if (puMetadata.getProperties() != null\n                && puMetadata.getProperties().containsKey(PersistenceProperties.KUNDERA_CLIENT_PROPERTY))\n        {\n            propertyFileName = (String) puMetadata.getProperties().get(PersistenceProperties.KUNDERA_CLIENT_PROPERTY);\n        }\n        if (externalProperties != null && externalProperties.containsKey(PersistenceProperties.KUNDERA_CLIENT_PROPERTY))\n        {\n            propertyFileName = (String) externalProperties.get(PersistenceProperties.KUNDERA_CLIENT_PROPERTY);\n        }\n        \n        if (propertyFileName == null)\n        {\n            propertyFileName = puMetadata != null ? puMetadata\n                    .getProperty(PersistenceProperties.KUNDERA_CLIENT_PROPERTY) : null;\n        }\n        if (propertyFileName != null && PropertyType.value(propertyFileName) != null\n                && PropertyType.value(propertyFileName).equals(PropertyType.xml))\n        {\n            onXml(onParseXML(propertyFileName, puMetadata));\n        }\n    }\n\n    /**\n     * If property file is xml.\n     * \n     * @param propertyFileName\n     * @param puMetadata\n     * @return\n     */\n    private ClientProperties onParseXML(String propertyFileName, PersistenceUnitMetadata puMetadata)\n    {\n        InputStream inStream = puMetadata.getClassLoader().getResourceAsStream(propertyFileName);\n        if (inStream == null)\n        {\n            propertyFileName = KunderaCoreUtils.resolvePath(propertyFileName);\n            try\n            {\n                inStream = new FileInputStream(new File(propertyFileName));\n            }\n            catch (FileNotFoundException e)\n            {\n                log.warn(\"File {} not found, Caused by \", propertyFileName);\n                return null;\n            }\n\n        }\n\n        if (inStream != null)\n        {\n            xStream = getXStreamObject();\n            Object o = xStream.fromXML(inStream);\n            return (ClientProperties) o;\n        }\n\n        return null;\n    }\n\n    /**\n     * get XStream Object.\n     * \n     * @return XStream object.\n     */\n    private XStream getXStreamObject()\n    {\n        if (xStream == null)\n        {\n            XStream stream = new XStream();\n            stream.alias(\"clientProperties\", ClientProperties.class);\n            stream.alias(\"dataStore\", ClientProperties.DataStore.class);\n            stream.alias(\"schema\", ClientProperties.DataStore.Schema.class);\n            stream.alias(\"table\", ClientProperties.DataStore.Schema.Table.class);\n            stream.alias(\"dataCenter\", ClientProperties.DataStore.Schema.DataCenter.class);\n            stream.alias(\"connection\", ClientProperties.DataStore.Connection.class);\n            stream.alias(\"server\", ClientProperties.DataStore.Connection.Server.class);\n            return stream;\n        }\n        else\n        {\n            return xStream;\n        }\n    }\n\n    /**\n     * property type emun.\n     * \n     * @author Kuldeep Mishra\n     * \n     */\n    protected enum PropertyType\n    {\n        xml, properties;\n\n        private static final String DELIMETER = \".\";\n\n        /**\n         * Check for allowed property format.\n         * \n         * @param propertyFileName\n         * @return\n         */\n        public static PropertyType value(String propertyFileName)\n        {\n            PropertyType type = null;\n            if (isValid(propertyFileName, PropertyType.xml))\n            {\n                type = xml;\n            }\n            else if (isValid(propertyFileName, PropertyType.properties))\n            {\n                if (log.isWarnEnabled())\n                {\n                    log.warn(\"Support for .properties have been deprecated and no longer supported by Kundera\");\n                }\n                type = properties;\n            }\n            else\n            {\n                log.warn(\"Invalid file format {} provided, returning null\", propertyFileName);\n            }\n\n            return type;\n        }\n\n        /**\n         * Check for property is xml.\n         * \n         * @param propertyFileName\n         * @return\n         */\n        private static boolean isValid(String propertyFileName, PropertyType type)\n        {\n            return propertyFileName.endsWith(DELIMETER + type);\n        }\n    }\n\n    /**\n     * If property is xml.\n     * \n     * @param cp\n     */\n    protected abstract void onXml(ClientProperties cp);\n\n    protected class AbstractSchemaMetadata\n    {\n        private ClientProperties clientProperties;\n\n        /**\n         * @param parseXML\n         */\n        public void setClientProperties(ClientProperties clientProperties)\n        {\n            this.clientProperties = clientProperties;\n        }\n\n        /**\n         * @return the clientProperties\n         */\n        public ClientProperties getClientProperties()\n        {\n            return clientProperties;\n        }\n\n        protected DataStore getDataStore(final String dataStoreName)\n        {\n            if (getClientProperties() != null)\n            {\n                if (getClientProperties().getDatastores() != null)\n                {\n                    for (DataStore dataStore : getClientProperties().getDatastores())\n                    {\n                        if (dataStore.getName() != null && dataStore.getName().trim().equalsIgnoreCase(dataStoreName))\n                        {\n                            return dataStore;\n                        }\n                    }\n                }\n\n                if (log.isWarnEnabled())\n                {\n                    log.warn(\"No data store configuration found, returning null.\");\n                }\n            }\n            return null;\n        }\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/AbstractSchemaConfiguration.java",
    "content": "package com.impetus.kundera.configure;\n\nimport java.util.Map;\n\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\npublic abstract class AbstractSchemaConfiguration\n{\n\n    /** Holding instance for persistence units. */\n    protected String[] persistenceUnits;\n\n    /** Holding persistenceUnit properties */\n    protected Map externalPropertyMap;\n\n    protected KunderaMetadata kunderaMetadata;\n\n    public AbstractSchemaConfiguration(final String[] persistenceUnits, final Map externalPropertyMap,\n            final KunderaMetadata kunderaMetadata)\n    {\n        this.persistenceUnits = persistenceUnits;\n        this.externalPropertyMap = externalPropertyMap;\n        this.kunderaMetadata = kunderaMetadata;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/ClientFactoryConfiguraton.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure;\n\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.ClientResolver;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class ClientFactoryConfiguration load client metadata.\n * \n * @author kuldeep.mishra\n * \n */\npublic class ClientFactoryConfiguraton extends AbstractSchemaConfiguration implements Configuration\n{\n    /** The log instance. */\n    private static Logger log = LoggerFactory.getLogger(ClientFactoryConfiguraton.class);\n\n    /**\n     * Constructor parameterised with persistence units.\n     * \n     * @param persistenceUnits\n     *            persistence units.\n     */\n    public ClientFactoryConfiguraton(Map externalProperties, final KunderaMetadata kunderaMetadata,\n            String... persistenceUnits)\n    {\n        super(persistenceUnits, externalProperties, kunderaMetadata);\n    }\n\n    @Override\n    public void configure()\n    {\n        // Invoke Client Loaders\n\n        for (String pu : persistenceUnits)\n        {\n            log.info(\"Loading Client(s) For Persistence Unit(s) \" + pu);\n\n            Map<String, Object> puProperty = KunderaCoreUtils.getExternalProperties(pu, externalPropertyMap,\n                    persistenceUnits);\n\n            ClientResolver.getClientFactory(pu, puProperty, kunderaMetadata).load(pu, puProperty);\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/ClientMetadataBuilder.java",
    "content": "package com.impetus.kundera.configure;\n\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.ClientResolver;\nimport com.impetus.kundera.loader.ClientFactory;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\npublic class ClientMetadataBuilder\n{\n    /** The log instance. */\n    private static Logger log = LoggerFactory.getLogger(ClientMetadataBuilder.class);\n\n    private String[] persistenceUnits;\n\n    private Map mapExternalProperties;\n\n    private SchemaConfiguration schemaConfiguration;\n\n    public ClientMetadataBuilder(Map mapOfPuProperties, final KunderaMetadata kunderaMetadata,\n            String... persistenceUnits)\n    {\n        this.persistenceUnits = persistenceUnits;\n        this.mapExternalProperties = mapOfPuProperties;\n        this.schemaConfiguration = new SchemaConfiguration(mapOfPuProperties, kunderaMetadata, persistenceUnits);\n    }\n\n    public void buildClientFactoryMetadata(Map<String, ClientFactory> clientFactories,\n            final KunderaMetadata kunderaMetadata)\n    {\n        for (String pu : persistenceUnits)\n        {\n            log.info(\"Loading client factory for persistence unit \" + pu);\n\n            Map<String, Object> puProperty = KunderaCoreUtils.getExternalProperties(pu, mapExternalProperties,\n                    persistenceUnits);\n\n            ClientFactory clientFactory = ClientResolver.getClientFactory(pu, puProperty, kunderaMetadata);\n            clientFactories.put(pu, clientFactory);\n        }\n\n        // configuring schema before loading client factories because during\n        // initilazation schema nedds to be created.\n        schemaConfiguration.configure();\n\n        // load all client factories.\n        for (String pu : persistenceUnits)\n        {\n            Map<String, Object> puProperty = KunderaCoreUtils.getExternalProperties(pu, mapExternalProperties,\n                    persistenceUnits);\n            clientFactories.get(pu).load(pu, puProperty);\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/ClientProperties.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure;\n\nimport java.io.Serializable;\nimport java.util.List;\nimport java.util.Properties;\n\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * \n * @author Kuldeep Mishra\n * \n */\n@XmlRootElement\npublic class ClientProperties implements Serializable\n{\n    private static final long serialVersionUID = 1L;\n\n    private List<DataStore> datastores;\n\n    /**\n     * @return the datastores\n     */\n    @XmlElement\n    public List<DataStore> getDatastores()\n    {\n        return datastores;\n    }\n\n    /**\n     * @param datastores\n     *            the datastores to set\n     */\n    public void setDatastores(List<DataStore> datastores)\n    {\n        this.datastores = datastores;\n    }\n\n    @XmlRootElement\n    public static class DataStore\n    {\n        private Connection connection;\n\n        private List<Schema> schemas;\n\n        private String name;\n\n        private Properties properties;\n\n        /**\n         * @return the connection\n         */\n        @XmlElement\n        public Connection getConnection()\n        {\n            return connection;\n        }\n\n        /**\n         * @param connection\n         *            the connection to set\n         */\n        public void setConnection(Connection connection)\n        {\n            this.connection = connection;\n        }\n\n        /**\n         * @return the schemas\n         */\n        @XmlElement\n        public List<Schema> getSchemas()\n        {\n            return schemas;\n        }\n\n        /**\n         * @return the name\n         */\n        public String getName()\n        {\n            return name;\n        }\n\n        /**\n         * @param name\n         *            the name to set\n         */\n        public void setName(String name)\n        {\n            this.name = name;\n        }\n\n        /**\n         * @return the properties\n         */\n        public Properties getProperties()\n        {\n            return properties;\n        }\n\n        /**\n         * @param properties\n         *            the properties to set\n         */\n        public void setProperties(Properties properties)\n        {\n            this.properties = properties;\n        }\n\n        /**\n         * @param schemas\n         *            the schemas to set\n         */\n        public void setSchemas(List<Schema> schemas)\n        {\n            this.schemas = schemas;\n        }\n\n        @XmlRootElement\n        public static class Schema\n        {\n            private List<Table> tables;\n\n            // private List<Properties> schemaProperties;\n            private Properties properties;\n\n            private List<DataCenter> dataCenters;\n\n            private String name;\n\n            /**\n             * @return the name\n             */\n            public String getName()\n            {\n                return name;\n            }\n\n            /**\n             * @param name\n             *            the name to set\n             */\n            public void setName(String name)\n            {\n                this.name = name;\n            }\n\n            /**\n             * @return the tables\n             */\n            public List<Table> getTables()\n            {\n                return tables;\n            }\n\n            /**\n             * @param tables\n             *            the tables to set\n             */\n            public void setTables(List<Table> tables)\n            {\n                this.tables = tables;\n            }\n\n            /**\n             * @return the schemaProperties\n             */\n            public Properties getSchemaProperties()\n            {\n                return properties;\n            }\n\n            /**\n             * @param schemaProperties\n             *            the schemaProperties to set\n             */\n            public void setProperties(Properties props)\n            {\n                this.properties = props;\n            }\n\n            /**\n             * @return the dataCenters\n             */\n            public List<DataCenter> getDataCenters()\n            {\n                return dataCenters;\n            }\n\n            /**\n             * @param dataCenters\n             *            the dataCenters to set\n             */\n            public void setDataCenters(List<DataCenter> dataCenters)\n            {\n                this.dataCenters = dataCenters;\n            }\n\n            public static class Table\n            {\n                private Properties properties;\n\n                private String name;\n\n                /**\n                 * @return the name\n                 */\n                public String getName()\n                {\n                    return name;\n                }\n\n                /**\n                 * @param name\n                 *            the name to set\n                 */\n                public void setName(String name)\n                {\n                    this.name = name;\n                }\n\n                /**\n                 * @return the properties\n                 */\n                public Properties getProperties()\n                {\n                    return properties;\n                }\n\n                /**\n                 * @param properties\n                 *            the properties to set\n                 */\n                public void setProperties(Properties properties)\n                {\n                    this.properties = properties;\n                }\n\n            }\n\n            public static class DataCenter\n            {\n                private String name;\n\n                private String value;\n\n                /**\n                 * @return the name\n                 */\n                public String getName()\n                {\n                    return name;\n                }\n\n                /**\n                 * @param name\n                 *            the name to set\n                 */\n                public void setName(String name)\n                {\n                    this.name = name;\n                }\n\n                /**\n                 * @return the value\n                 */\n                public String getValue()\n                {\n                    return value;\n                }\n\n                /**\n                 * @param value\n                 *            the value to set\n                 */\n                public void setValue(String value)\n                {\n                    this.value = value;\n                }\n            }\n        }\n\n        public static class Connection\n        {\n            private Properties properties;\n\n            private List<Server> servers;\n\n            /**\n             * @return the properties\n             */\n            public Properties getProperties()\n            {\n                return properties;\n            }\n\n            /**\n             * @param properties\n             *            the properties to set\n             */\n            public void setProperties(Properties properties)\n            {\n                this.properties = properties;\n            }\n\n            /**\n             * @return the servers\n             */\n            public List<Server> getServers()\n            {\n                return servers;\n            }\n\n            /**\n             * @param servers\n             *            the servers to set\n             */\n            public void setServers(List<Server> servers)\n            {\n                this.servers = servers;\n            }\n\n            public static class Server\n            {\n                private String host;\n\n                private String port;\n\n                private Properties properties;\n\n                /**\n                 * @return the host\n                 */\n                public String getHost()\n                {\n                    return host;\n                }\n\n                /**\n                 * @param host\n                 *            the host to set\n                 */\n                public void setHost(String host)\n                {\n                    this.host = host;\n                }\n\n                /**\n                 * @return the port\n                 */\n                public String getPort()\n                {\n                    return port;\n                }\n\n                /**\n                 * @param port\n                 *            the port to set\n                 */\n                public void setPort(String port)\n                {\n                    this.port = port;\n                }\n\n                /**\n                 * \n                 * @return\n                 */\n                public Properties getProperties()\n                {\n                    if (this.properties == null)\n                    {\n                        this.properties = new Properties();\n                    }\n                    return this.properties;\n                }\n\n                /**\n                 * @param properties\n                 *            the properties to set\n                 */\n                public void setProperties(Properties properties)\n                {\n                    this.properties = properties;\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/Configuration.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure;\n\n/**\n * Interface to be implemented by different configuration implementations:\n *  <b>{@link MetamodelConfiguration} </b>\n *  <b>{@link PersistenceUnitConfiguration}</b>\n *  <b>{@link SchemaConfiguration}</b>\n *  <b>{@link ClientFactoryConfiguraton}</b>\n * \n * @author vivek.mishra\n * \n */\ninterface Configuration\n{\n\n    /**\n     * Configures and load meta-information for parameterized persistence units.\n     */\n    void configure();\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/MetamodelConfiguration.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.configure;\r\n\r\nimport java.io.BufferedInputStream;\r\nimport java.io.DataInputStream;\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.lang.reflect.Field;\r\nimport java.net.URL;\r\nimport java.net.URLClassLoader;\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javassist.bytecode.AnnotationsAttribute;\r\nimport javassist.bytecode.ClassFile;\r\n\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.GeneratedValue;\r\nimport javax.persistence.Table;\r\nimport javax.persistence.metamodel.Metamodel;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.PersistenceProperties;\r\nimport com.impetus.kundera.classreading.ClasspathReader;\r\nimport com.impetus.kundera.classreading.Reader;\r\nimport com.impetus.kundera.classreading.ResourceIterator;\r\nimport com.impetus.kundera.loader.MetamodelLoaderException;\r\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\r\nimport com.impetus.kundera.metadata.MetadataBuilder;\r\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.metadata.model.IdDiscriptor;\r\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\r\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\r\nimport com.impetus.kundera.metadata.processor.GeneratedValueProcessor;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\nimport com.impetus.kundera.utils.KunderaCoreUtils;\r\nimport com.impetus.kundera.validation.ValidationFactory;\r\nimport com.impetus.kundera.validation.ValidationFactoryGenerator;\r\nimport com.impetus.kundera.validation.ValidationFactoryGenerator.ValidationFactoryType;\r\nimport com.impetus.kundera.validation.rules.RuleValidationException;\r\n\r\n/**\r\n * The Metamodel configurer: a) Configure application meta data b) loads entity\r\n * metadata and maps metadata.\r\n * \r\n * @author vivek.mishra\r\n */\r\npublic class MetamodelConfiguration extends AbstractSchemaConfiguration implements Configuration\r\n{\r\n\r\n    /** The log. */\r\n    private static Logger log = LoggerFactory.getLogger(MetamodelConfiguration.class);\r\n\r\n    private ValidationFactory factory;\r\n\r\n    /**\r\n     * Constructor using persistence units as parameter.\r\n     * \r\n     * @param persistenceUnits\r\n     *            persistence units.\r\n     */\r\n    public MetamodelConfiguration(Map properties, final KunderaMetadata metadata, String... persistenceUnits)\r\n    {\r\n        super(persistenceUnits, properties, metadata);\r\n        ValidationFactoryGenerator generator = new ValidationFactoryGenerator();\r\n        this.factory = generator.getFactory(ValidationFactoryType.BOOT_STRAP_VALIDATION);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.configure.Configuration#configure()\r\n     */\r\n    @Override\r\n    public void configure()\r\n    {\r\n        log.debug(\"Loading Entity Metadata...\");\r\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\r\n\r\n        for (String persistenceUnit : persistenceUnits)\r\n        {\r\n            if (appMetadata.getMetamodelMap().get(persistenceUnit.trim()) != null)\r\n            {\r\n                if (log.isDebugEnabled())\r\n                {\r\n                    log.debug(\"Metadata already exists for the Persistence Unit \" + persistenceUnit + \". Nothing to do\");\r\n                }\r\n            }\r\n            else\r\n            {\r\n                loadEntityMetadata(persistenceUnit);\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Load entity metadata.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the persistence unit\r\n     */\r\n    private void loadEntityMetadata(String persistenceUnit)\r\n    {\r\n        if (persistenceUnit == null)\r\n        {\r\n            throw new IllegalArgumentException(\r\n                    \"Must have a persistenceUnitName in order to load entity metadata, you provided :\"\r\n                            + persistenceUnit);\r\n        }\r\n\r\n        Map<String, PersistenceUnitMetadata> persistentUnitMetadataMap = kunderaMetadata.getApplicationMetadata()\r\n                .getPersistenceUnitMetadataMap();\r\n\r\n        /** Classes to scan */\r\n        List<String> classesToScan;\r\n        URL[] resources = null;\r\n        String client = null;\r\n        List<URL> managedURLs = null;\r\n        if (persistentUnitMetadataMap == null || persistentUnitMetadataMap.isEmpty())\r\n        {\r\n            log.error(\"It is necessary to load Persistence Unit metadata  for persistence unit \" + persistenceUnit\r\n                    + \" first before loading entity metadata.\");\r\n            throw new MetamodelLoaderException(\"load Persistence Unit metadata  for persistence unit \"\r\n                    + persistenceUnit + \" first before loading entity metadata.\");\r\n        }\r\n        else\r\n        {\r\n            PersistenceUnitMetadata puMetadata = persistentUnitMetadataMap.get(persistenceUnit);\r\n            classesToScan = puMetadata.getManagedClassNames();\r\n            managedURLs = puMetadata.getManagedURLs();\r\n            client = getClientFactoryName(persistenceUnit);\r\n        }\r\n\r\n        /*\r\n         * Check whether Classes to scan was provided into persistence.xml If\r\n         * yes, load them. Otherwise load them from classpath/ context path\r\n         */\r\n        Reader reader;\r\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\r\n        if (classesToScan == null || classesToScan.isEmpty())\r\n        {\r\n            log.info(\"No class to scan for persistence unit \" + persistenceUnit\r\n                    + \". Entities will be loaded from classpath/ context-path\");\r\n            // Entity metadata is not related to any PU, and hence will be\r\n            // stored at common place\r\n            // persistenceUnit = Constants.COMMON_ENTITY_METADATAS;\r\n\r\n            // Check whether all common entity metadata have already been loaded\r\n            if (appMetadata.getMetamodelMap().get(persistenceUnit) != null)\r\n            {\r\n                log.info(\"All common entitity metadata already loaded, nothing need to be done\");\r\n                return;\r\n            }\r\n\r\n            reader = new ClasspathReader();\r\n            // resources = reader.findResourcesByClasspath();\r\n        }\r\n        else\r\n        {\r\n            reader = new ClasspathReader(classesToScan);\r\n            // resources = reader.findResourcesByContextLoader();\r\n        }\r\n\r\n        InputStream[] iStreams = null;\r\n        PersistenceUnitMetadata puMetadata = persistentUnitMetadataMap.get(persistenceUnit);\r\n        if (this.getClass().getClassLoader() instanceof URLClassLoader && !puMetadata.getExcludeUnlistedClasses())\r\n        {\r\n            URL[] managedClasses = reader.findResources();\r\n            if (managedClasses != null)\r\n            {\r\n                List<URL> managedResources = Arrays.asList(managedClasses);\r\n                managedURLs.addAll(managedResources);\r\n            }\r\n        }\r\n        else\r\n        {\r\n            iStreams = reader.findResourcesAsStream();\r\n        }\r\n\r\n        if (managedURLs != null)\r\n        {\r\n            resources = managedURLs.toArray(new URL[] {});\r\n        }\r\n\r\n        // All entities to load should be annotated with @Entity\r\n        reader.addValidAnnotations(Entity.class.getName());\r\n\r\n        Metamodel metamodel = appMetadata.getMetamodel(persistenceUnit);\r\n        if (metamodel == null)\r\n        {\r\n            metamodel = new MetamodelImpl();\r\n        }\r\n\r\n        Map<String, EntityMetadata> entityMetadataMap = ((MetamodelImpl) metamodel).getEntityMetadataMap();\r\n        Map<String, Class<?>> entityNameToClassMap = ((MetamodelImpl) metamodel).getEntityNameToClassMap();\r\n        Map<String, List<String>> puToClazzMap = new HashMap<String, List<String>>();\r\n        Map<String, IdDiscriptor> entityNameToKeyDiscriptorMap = new HashMap<String, IdDiscriptor>();\r\n        List<Class<?>> classes = new ArrayList<Class<?>>();\r\n        if (resources != null && resources.length > 0)\r\n        {\r\n            for (URL resource : resources)\r\n            {\r\n                try\r\n                {\r\n                    ResourceIterator itr = reader.getResourceIterator(resource, reader.getFilter());\r\n\r\n                    InputStream is = null;\r\n                    while ((is = itr.next()) != null)\r\n                    {\r\n                        classes.addAll(scanClassAndPutMetadata(is, reader, entityMetadataMap, entityNameToClassMap,\r\n                                persistenceUnit, client, puToClazzMap, entityNameToKeyDiscriptorMap));\r\n                    }\r\n                }\r\n                catch (IOException e)\r\n                {\r\n                    log.error(\"Error while retrieving and storing entity metadata. Details:\", e);\r\n                    throw new MetamodelLoaderException(\"Error while retrieving and storing entity metadata\");\r\n\r\n                }\r\n            }\r\n        }\r\n        else if (iStreams != null)\r\n        {\r\n            try\r\n            {\r\n                for (InputStream is : iStreams)\r\n                {\r\n                    try\r\n                    {\r\n                        classes.addAll(scanClassAndPutMetadata(is, reader, entityMetadataMap, entityNameToClassMap,\r\n                                persistenceUnit, client, puToClazzMap, entityNameToKeyDiscriptorMap));\r\n                    }\r\n                    finally\r\n                    {\r\n                        if (is != null)\r\n                        {\r\n                            is.close();\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n            catch (IOException e)\r\n            {\r\n                log.error(\"Error while retrieving and storing entity metadata. Details:\", e);\r\n                throw new MetamodelLoaderException(\"Error while retrieving and storing entity metadata, Caused by : .\",\r\n                        e);\r\n\r\n            }\r\n        }\r\n        ((MetamodelImpl) metamodel).setEntityMetadataMap(entityMetadataMap);\r\n        appMetadata.getMetamodelMap().put(persistenceUnit, metamodel);\r\n        appMetadata.setClazzToPuMap(puToClazzMap);\r\n        ((MetamodelImpl) metamodel).addKeyValues(entityNameToKeyDiscriptorMap);\r\n        // assign JPA metamodel.\r\n        ((MetamodelImpl) metamodel).assignEmbeddables(kunderaMetadata.getApplicationMetadata()\r\n                .getMetaModelBuilder(persistenceUnit).getEmbeddables());\r\n        ((MetamodelImpl) metamodel).assignManagedTypes(kunderaMetadata.getApplicationMetadata()\r\n                .getMetaModelBuilder(persistenceUnit).getManagedTypes());\r\n        ((MetamodelImpl) metamodel).assignMappedSuperClass(kunderaMetadata.getApplicationMetadata()\r\n                .getMetaModelBuilder(persistenceUnit).getMappedSuperClassTypes());\r\n    }\r\n\r\n    /**\r\n     * Scan class and put metadata.\r\n     * \r\n     * @param bits\r\n     *            the bits\r\n     * @param reader\r\n     *            the reader\r\n     * @param entityMetadataMap\r\n     *            the entity metadata map\r\n     * @param entityNameToClassMap\r\n     *            the entity name to class map\r\n     * @param keyDiscriptor\r\n     * @param persistence\r\n     *            unit the persistence unit.\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     * @throws RuleValidationException\r\n     */\r\n    private List<Class<?>> scanClassAndPutMetadata(InputStream bits, Reader reader,\r\n            Map<String, EntityMetadata> entityMetadataMap, Map<String, Class<?>> entityNameToClassMap,\r\n            String persistenceUnit, String client, Map<String, List<String>> clazzToPuMap,\r\n            Map<String, IdDiscriptor> entityNameToKeyDiscriptorMap) throws IOException\r\n    {\r\n        DataInputStream dstream = new DataInputStream(new BufferedInputStream(bits));\r\n        ClassFile cf = null;\r\n        String className = null;\r\n\r\n        List<Class<?>> classes = new ArrayList<Class<?>>();\r\n\r\n        try\r\n        {\r\n            cf = new ClassFile(dstream);\r\n\r\n            className = cf.getName();\r\n\r\n            List<String> annotations = new ArrayList<String>();\r\n\r\n            reader.accumulateAnnotations(annotations,\r\n                    (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.visibleTag));\r\n            reader.accumulateAnnotations(annotations,\r\n                    (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.invisibleTag));\r\n            \r\n\r\n            // iterate through all valid annotations\r\n            for (String validAnn : reader.getValidAnnotations())\r\n            {\r\n            \t\r\n\r\n                // check if the current class has one?\r\n                if (annotations.contains(validAnn))\r\n                {\r\n                \t\r\n                \tClass<?> clazz = this.getClass().getClassLoader().loadClass(className);\r\n                    this.factory.validate(clazz);\r\n\r\n                    // get the name of entity to be used for entity to class map\r\n                    // if or not annotated with name\r\n                    String entityName = getEntityName(clazz);\r\n\r\n                    if ((entityNameToClassMap.containsKey(entityName) && !entityNameToClassMap.get(entityName)\r\n                            .getName().equals(clazz.getName())))\r\n                    {\r\n                        throw new MetamodelLoaderException(\"Name conflict between classes \"\r\n                                + entityNameToClassMap.get(entityName).getName() + \" and \" + clazz.getName()\r\n                                + \". Make sure no two entity classes with the same name \"\r\n                                + \" are specified for persistence unit \" + persistenceUnit);\r\n                    }\r\n                    entityNameToClassMap.put(entityName, clazz);\r\n\r\n                    EntityMetadata metadata = entityMetadataMap.get(clazz);\r\n                    if (null == metadata)\r\n                    {\r\n                        log.debug(\"Metadata not found in cache for \" + clazz.getName());\r\n                        // double check locking.\r\n                        synchronized (clazz)\r\n                        {\r\n                            if (null == metadata)\r\n                            {\r\n                                MetadataBuilder metadataBuilder = new MetadataBuilder(persistenceUnit, client,\r\n                                        KunderaCoreUtils.getExternalProperties(persistenceUnit, externalPropertyMap,\r\n                                                persistenceUnits), kunderaMetadata);\r\n                                metadata = metadataBuilder.buildEntityMetadata(clazz);\r\n\r\n                                // in case entity's pu does not belong to parse\r\n                                // persistence unit, it will be null.\r\n                                if (metadata != null)\r\n                                {\r\n                                    entityMetadataMap.put(clazz.getName(), metadata);\r\n                                    mapClazztoPu(clazz, persistenceUnit, clazzToPuMap);\r\n                                    processGeneratedValueAnnotation(clazz, persistenceUnit, metadata,\r\n                                            entityNameToKeyDiscriptorMap);\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    // TODO :\r\n                    onValidateClientProperties(classes, clazz, persistenceUnit);\r\n                }\r\n            }\r\n        }\r\n        catch (ClassNotFoundException e)\r\n        {\r\n            log.error(\"Class \" + className + \" not found, it won't be loaded as entity\");\r\n        }\r\n\r\n        finally\r\n        {\r\n            if (dstream != null)\r\n            {\r\n                dstream.close();\r\n            }\r\n            if (bits != null)\r\n            {\r\n                bits.close();\r\n            }\r\n        }\r\n\r\n        return classes;\r\n    }\r\n\r\n    /**\r\n     * @param clazz\r\n     */\r\n    private String getEntityName(Class<?> clazz)\r\n    {\r\n        return !StringUtils.isBlank(clazz.getAnnotation(Entity.class).name()) ? clazz.getAnnotation(Entity.class)\r\n                .name() : clazz.getSimpleName();\r\n    }\r\n\r\n    /**\r\n     * @param clazz\r\n     */\r\n    private List<Class<?>> onValidateClientProperties(List<Class<?>> classes, Class<?> clazz,\r\n            final String persistenceUnit)\r\n    {\r\n        if (clazz.isAnnotationPresent(Entity.class) && clazz.isAnnotationPresent(Table.class))\r\n        {\r\n            classes.add(clazz);\r\n        }\r\n        return classes;\r\n    }\r\n\r\n    /**\r\n     * Method to prepare class simple name to list of pu's mapping. 1 class can\r\n     * be mapped to multiple persistence units, in case of RDBMS, in other cases\r\n     * it will only be 1!\r\n     * \r\n     * @param clazz\r\n     *            entity class to be mapped.\r\n     * @param pu\r\n     *            current persistence unit name\r\n     * @param clazzToPuMap\r\n     *            collection holding mapping.\r\n     * @return map holding mapping.\r\n     */\r\n    private Map<String, List<String>> mapClazztoPu(Class<?> clazz, String pu, Map<String, List<String>> clazzToPuMap)\r\n    {\r\n        List<String> puCol = new ArrayList<String>(1);\r\n        if (clazzToPuMap == null)\r\n        {\r\n            clazzToPuMap = new HashMap<String, List<String>>();\r\n        }\r\n        else\r\n        {\r\n            if (clazzToPuMap.containsKey(clazz.getName()))\r\n            {\r\n                puCol = clazzToPuMap.get(clazz.getName());\r\n            }\r\n        }\r\n\r\n        if (!puCol.contains(pu))\r\n        {\r\n            puCol.add(pu);\r\n            clazzToPuMap.put(clazz.getName(), puCol);\r\n            String annotateEntityName = clazz.getAnnotation(Entity.class).name();\r\n            if (!StringUtils.isBlank(annotateEntityName))\r\n            {\r\n                clazzToPuMap.put(annotateEntityName, puCol);\r\n            }\r\n        }\r\n\r\n        return clazzToPuMap;\r\n    }\r\n    \r\n    private void processGeneratedValueAnnotation(Class<?> clazz, String persistenceUnit, EntityMetadata m,\r\n            Map<String, IdDiscriptor> entityNameToKeyDiscriptorMap)\r\n    {\r\n        GeneratedValueProcessor processer = new GeneratedValueProcessor();\r\n        String pu = m.getPersistenceUnit();\r\n\r\n        String clientFactoryName = getClientFactoryName(persistenceUnit);\r\n\r\n        if (pu != null && pu.equals(persistenceUnit)\r\n                || clientFactoryName.equalsIgnoreCase(\"com.impetus.client.rdbms.RDBMSClientFactory\"))\r\n        {\r\n            Field f = (Field) m.getIdAttribute().getJavaMember();\r\n\r\n            if (f.isAnnotationPresent(GeneratedValue.class))\r\n            {\r\n                processer.process(clazz, f, m, entityNameToKeyDiscriptorMap);\r\n            }\r\n        }\r\n    }\r\n\r\n    private String getClientFactoryName(String persistenceUnit)\r\n    {\r\n        Map<String, Object> externalProperties = KunderaCoreUtils.getExternalProperties(persistenceUnit,\r\n                externalPropertyMap, persistenceUnits);\r\n\r\n        String clientFactoryName  = externalProperties != null ? (String) externalProperties\r\n                .get(PersistenceProperties.KUNDERA_CLIENT_FACTORY) : null;\r\n\r\n        if (clientFactoryName == null)\r\n        {\r\n            clientFactoryName = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\r\n                    persistenceUnit).getClient();\r\n        }\r\n        return clientFactoryName;\r\n    }\r\n \r\n/*\r\n    private void processGeneratedValueAnnotation(Class<?> clazz, String persistenceUnit, EntityMetadata m,\r\n            Map<String, IdDiscriptor> entityNameToKeyDiscriptorMap)\r\n    {\r\n        GeneratedValueProcessor processer = new GeneratedValueProcessor();\r\n        String pu = m.getPersistenceUnit() getPersistenceUnitOfEntity(clazz) ;\r\n        \r\n        Map<String, Object> externalProperties = KunderaCoreUtils.getExternalProperties(persistenceUnit,\r\n                externalPropertyMap, persistenceUnits);\r\n\r\n        String clientFactoryName  = externalProperties != null ? (String) externalProperties\r\n                .get(PersistenceProperties.KUNDERA_CLIENT_FACTORY) : null;\r\n\r\n        if (clientFactoryName == null)\r\n        {\r\n            clientFactoryName = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\r\n                    m.getPersistenceUnit()).getClient();\r\n        }\r\n        \r\n        if (pu != null && pu.equals(persistenceUnit)\r\n                || clientFactoryName.equalsIgnoreCase(\"com.impetus.client.rdbms.RDBMSClientFactory\"))\r\n        {\r\n            Field f = (Field) m.getIdAttribute().getJavaMember();\r\n\r\n            if (f.isAnnotationPresent(GeneratedValue.class))\r\n            {\r\n                processer.process(clazz, f, m, entityNameToKeyDiscriptorMap);\r\n            }\r\n        }\r\n    }*/\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/PersistenceUnitConfiguration.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.configure;\r\n\r\nimport java.io.IOException;\r\nimport java.net.URL;\r\nimport java.util.Enumeration;\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.spi.PersistenceUnitInfo;\r\nimport javax.persistence.spi.PersistenceUnitTransactionType;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.Constants;\r\nimport com.impetus.kundera.KunderaPersistence;\r\nimport com.impetus.kundera.loader.PersistenceLoaderException;\r\nimport com.impetus.kundera.loader.PersistenceXMLLoader;\r\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\r\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\nimport com.impetus.kundera.utils.InvalidConfigurationException;\r\n\r\n/**\r\n * The Class PersistenceUnitConfiguration: 1) Find and load/configure\r\n * persistence unit metadata. Earlier it was PersistenceUnitLoader.\r\n * \r\n * @author vivek.mishra\r\n */\r\n\r\npublic class PersistenceUnitConfiguration extends AbstractSchemaConfiguration implements Configuration\r\n{\r\n\r\n    /** The log instance. */\r\n    private static Logger log = LoggerFactory.getLogger(PersistenceUnitConfiguration.class);\r\n\r\n    /** The Constant PROVIDER_IMPLEMENTATION_NAME. */\r\n    private static final String PROVIDER_IMPLEMENTATION_NAME = KunderaPersistence.class.getName();\r\n\r\n    /**\r\n     * Constructor parameterised with persistence units.\r\n     * \r\n     * @param persistenceUnits\r\n     *            persistence units.\r\n     */\r\n    public PersistenceUnitConfiguration(Map properties, final KunderaMetadata metadata, String... persistenceUnits)\r\n    {\r\n        super(persistenceUnits, properties, metadata);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.configure.Configuration#configure()\r\n     */\r\n    @Override\r\n    public void configure()\r\n    {\r\n        log.info(\"Loading Metadata from persistence.xml ...\");\r\n\r\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\r\n\r\n        try\r\n        {\r\n            Map<String, PersistenceUnitMetadata> metadatas = findPersistenceMetadatas();\r\n            for (String persistenceUnit : persistenceUnits)\r\n            {\r\n                if (!metadatas.containsKey(persistenceUnit))\r\n                {\r\n                    log.error(\"Unconfigured persistence unit: \" + persistenceUnit\r\n                            + \" please validate with persistence.xml\");\r\n                    throw new PersistenceUnitConfigurationException(\"Invalid persistence unit: \" + persistenceUnit\r\n                            + \" provided\");\r\n                }\r\n            }\r\n            log.info(\"Finishing persistence unit metadata configuration ...\");\r\n            appMetadata.addPersistenceUnitMetadata(metadatas);\r\n        }\r\n        catch (InvalidConfigurationException icex)\r\n        {\r\n            log.error(\"Error occurred during persistence unit configuration, Caused by: .\", icex);\r\n            throw new PersistenceLoaderException(icex);\r\n        }\r\n    }\r\n\r\n    public void configure(PersistenceUnitInfo puInfo)\r\n    {\r\n        log.info(\"Loading Metadata from persistence.xml ...\");\r\n\r\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\r\n        Map<String, PersistenceUnitMetadata> metadatas = new HashMap<String, PersistenceUnitMetadata>();\r\n\r\n        this.configure();\r\n\r\n        for (String persistenceUnit : persistenceUnits)\r\n        {\r\n            mergeProperties(puInfo, appMetadata, persistenceUnit);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Find persistence meta data. Loads configured persistence.xml and load all\r\n     * provided configurations within persistence meta data as per @see JPA 2.0\r\n     * specifications.\r\n     * \r\n     * @return the list configure persistence unit meta data.\r\n     */\r\n    private Map<String, PersistenceUnitMetadata> findPersistenceMetadatas() throws InvalidConfigurationException\r\n    {\r\n        String puLocation = (String) (externalPropertyMap != null\r\n                && externalPropertyMap.get(Constants.PERSISTENCE_UNIT_LOCATIION) != null ? externalPropertyMap\r\n                .get(Constants.PERSISTENCE_UNIT_LOCATIION) : Constants.DEFAULT_PERSISTENCE_UNIT_LOCATIION);\r\n\r\n        Enumeration<URL> xmls = null;\r\n        try\r\n        {\r\n            xmls = this.getClass().getClassLoader().getResources(puLocation);\r\n        }\r\n        catch (IOException ioex)\r\n        {\r\n            log.warn(\"Error while loading persistence.xml, Caused by: {}.\", ioex);\r\n        }\r\n\r\n        if (xmls == null || !xmls.hasMoreElements())\r\n        {\r\n            log.error(\"Could not find any META-INF/persistence.xml file in the classpath\");\r\n            throw new InvalidConfigurationException(\"Could not find any META-INF/persistence.xml file in the classpath\");\r\n        }\r\n\r\n        Set<String> persistenceUnitNames = new HashSet<String>();\r\n        Map<String, PersistenceUnitMetadata> persistenceUnitMap = new HashMap<String, PersistenceUnitMetadata>();\r\n        while (xmls.hasMoreElements())\r\n        {\r\n            URL url = xmls.nextElement();\r\n\r\n            log.trace(\"Analysing persistence.xml: \" + url);\r\n            List<PersistenceUnitMetadata> metadataFiles = PersistenceXMLLoader.findPersistenceUnits(url, persistenceUnits, \r\n                    PersistenceUnitTransactionType.RESOURCE_LOCAL);\r\n\r\n            // Pick only those that have Kundera Provider\r\n            for (PersistenceUnitMetadata metadata : metadataFiles)\r\n            {\r\n                // check for unique names\r\n                if (persistenceUnitNames.contains(metadata.getPersistenceUnitName()))\r\n                {\r\n                    if (log.isWarnEnabled())\r\n                    {\r\n                        log.warn(\"Duplicate persistence-units for name: \" + metadata.getPersistenceUnitName()\r\n                                + \". verify your persistence.xml file\");\r\n                    }\r\n                }\r\n\r\n                // check for provider\r\n                if (metadata.getPersistenceProviderClassName() == null\r\n                        || PROVIDER_IMPLEMENTATION_NAME.equalsIgnoreCase(metadata.getPersistenceProviderClassName()))\r\n                {\r\n                    persistenceUnitMap.put(metadata.getPersistenceUnitName(), metadata);\r\n                }\r\n\r\n                // add to check for duplicate persistence unit.\r\n                persistenceUnitNames.add(metadata.getPersistenceUnitName());\r\n            }\r\n        }\r\n        return persistenceUnitMap;\r\n    }\r\n\r\n    /**\r\n     * \r\n     * @param puInfo\r\n     * @param appMetadata\r\n     * @param metadatas\r\n     * @param persistenceUnit\r\n     */\r\n    private void mergeProperties(PersistenceUnitInfo puInfo, ApplicationMetadata appMetadata, String persistenceUnit)\r\n    {\r\n        PersistenceUnitMetadata metadata = appMetadata.getPersistenceUnitMetadata(persistenceUnit);\r\n\r\n        metadata.setTransactionType(puInfo.getTransactionType());\r\n\r\n        metadata.getClasses().addAll(puInfo.getManagedClassNames());\r\n\r\n        metadata.setExcludeUnlistedClasses(puInfo.excludeUnlistedClasses());\r\n\r\n        metadata.getProperties().putAll(puInfo.getProperties());\r\n\r\n        if (puInfo.getPersistenceProviderClassName() == null\r\n                || PROVIDER_IMPLEMENTATION_NAME.equalsIgnoreCase(puInfo.getPersistenceProviderClassName()))\r\n        {\r\n            metadata.setProvider(puInfo.getPersistenceProviderClassName());\r\n        }\r\n        else\r\n        {\r\n            throw new PersistenceUnitConfigurationException(\"Invalid persistence provider : \"\r\n                    + puInfo.getPersistenceProviderClassName() + \", persistence provider must be \"\r\n                    + PROVIDER_IMPLEMENTATION_NAME + \".\");\r\n        }\r\n\r\n        metadata.getPackages().addAll(puInfo.getMappingFileNames());\r\n\r\n        for (URL url : puInfo.getJarFileUrls())\r\n        {\r\n            metadata.addJarFile(url.getPath());\r\n        }\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/PersistenceUnitConfigurationException.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.configure;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class PersistenceUnitConfigurationException extends KunderaException\n{\n\n    /** Default Serial Version UID. */\n    private static final long serialVersionUID = 1L;\n\n    /**\n     * \n     */\n    public PersistenceUnitConfigurationException()\n    {\n        super();\n    }\n\n    /**\n     * @param paramString\n     * @param paramThrowable\n     */\n    public PersistenceUnitConfigurationException(String paramString, Throwable paramThrowable)\n    {\n        super(paramString, paramThrowable);\n    }\n\n    /**\n     * @param paramString\n     */\n    public PersistenceUnitConfigurationException(String paramString)\n    {\n        super(paramString);\n    }\n\n    /**\n     * @param paramThrowable\n     */\n    public PersistenceUnitConfigurationException(Throwable paramThrowable)\n    {\n        super(paramThrowable);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/PropertyReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure;\n\n/**\n * Property reader to read client specific property.\n * \n * @author kuldeep.mishra\n * \n */\npublic interface PropertyReader\n{\n    /**\n     * reads all properties from property.\n     * \n     * @param string\n     */\n    void read(String string);\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/SchemaConfiguration.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\nimport javax.persistence.DiscriminatorColumn;\nimport javax.persistence.Lob;\nimport javax.persistence.OrderBy;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.Metamodel;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.ClientResolver;\nimport com.impetus.kundera.configure.schema.CollectionColumnInfo;\nimport com.impetus.kundera.configure.schema.ColumnInfo;\nimport com.impetus.kundera.configure.schema.EmbeddedColumnInfo;\nimport com.impetus.kundera.configure.schema.IndexInfo;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.configure.schema.TableInfo;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.loader.ClientFactory;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata.Type;\nimport com.impetus.kundera.metadata.model.IdDiscriptor;\nimport com.impetus.kundera.metadata.model.JoinTableMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.model.PropertyIndex;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.Relation.ForeignKey;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.metadata.processor.IndexProcessor;\nimport com.impetus.kundera.metadata.validator.EntityValidator;\nimport com.impetus.kundera.metadata.validator.EntityValidatorImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * Schema configuration implementation to support ddl_schema_creation\n * functionality. e.g. kundera_ddl_auto_prepare\n * (create,create-drop,validate,update)\n * \n * @author Kuldeep.Kumar\n * \n */\npublic class SchemaConfiguration extends AbstractSchemaConfiguration implements Configuration\n{\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(SchemaConfiguration.class);\n\n    /**\n     * pu to schema metadata map .\n     */\n    private Map<String, List<TableInfo>> puToSchemaMetadata = new HashMap<String, List<TableInfo>>();\n\n    /**\n     * Constructor using persistence units as parameter.\n     * \n     * @param persistenceUnits\n     *            persistence units.\n     */\n    public SchemaConfiguration(Map externalProperties, final KunderaMetadata metadata, String... persistenceUnits)\n    {\n        super(persistenceUnits, externalProperties, metadata);\n    }\n\n    @Override\n    /**\n     * configure method responsible for creating pu to schema metadata map for\n     * each entity in class path.\n     * \n     */\n    public void configure()\n    {\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\n\n        // TODO, FIXME: Refactoring is required.\n        for (String persistenceUnit : persistenceUnits)\n        {\n            EntityValidator validator = new EntityValidatorImpl(\n                    KunderaCoreUtils.getExternalProperties(persistenceUnit, externalPropertyMap, persistenceUnits));\n\n            log.info(\"Configuring schema export for : \" + persistenceUnit);\n            List<TableInfo> tableInfos = getSchemaInfo(persistenceUnit);\n\n            Map<String, EntityMetadata> entityMetadataMap = getEntityMetadataCol(appMetadata, persistenceUnit);\n\n            PersistenceUnitMetadata puMetadata = appMetadata.getPersistenceUnitMetadata(persistenceUnit);\n\n            // Iterate each entity metadata.\n            for (EntityMetadata entityMetadata : entityMetadataMap.values())\n            {\n                // get entity metadata(table info as well as columns)\n                // if table info exists, get it from map.\n                boolean found = false;\n\n                Type type = entityMetadata.getType();\n                Class idClassName = entityMetadata.getIdAttribute() != null\n                        ? entityMetadata.getIdAttribute().getJavaType() : null;\n\n                String idName = entityMetadata.getIdAttribute() != null\n                        ? ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName() : null;\n\n                TableInfo tableInfo = new TableInfo(entityMetadata.getTableName(), type.name(), idClassName, idName);\n\n                // check for tableInfos not empty and contains the present\n                // tableInfo.\n                if (!tableInfos.isEmpty() && tableInfos.contains(tableInfo))\n                {\n                    found = true;\n                    int idx = tableInfos.indexOf(tableInfo);\n                    tableInfo = tableInfos.get(idx);\n                    addColumnToTableInfo(entityMetadata, type, tableInfo);\n                }\n                else\n                {\n                    addColumnToTableInfo(entityMetadata, type, tableInfo);\n                }\n\n                List<Relation> relations = entityMetadata.getRelations();\n\n                parseRelations(persistenceUnit, tableInfos, entityMetadata, tableInfo, relations);\n\n                if (!found)\n                {\n                    tableInfos.add(tableInfo);\n                }\n                // Add table for GeneratedValue if opted TableStrategy\n                addTableGenerator(appMetadata, persistenceUnit, tableInfos, entityMetadata);\n\n                // Validating entity against counter column family.\n                validator.validateEntity(entityMetadata.getEntityClazz(), kunderaMetadata);\n            }\n\n            puToSchemaMetadata.put(persistenceUnit, tableInfos);\n\n        }\n\n        // Need to iterate, as in case of non unary relations\n        for (String persistenceUnit : persistenceUnits)\n        {\n            PersistenceUnitMetadata puMetadata = appMetadata.getPersistenceUnitMetadata(persistenceUnit);\n\n            Map externalPuMap = externalPropertyMap;\n\n            // in case of polyglot.\n            if (persistenceUnits.length > 1 && externalPropertyMap != null)\n            {\n                externalPuMap = (Map) externalPropertyMap.get(persistenceUnit);\n            }\n            if (externalPuMap != null && externalPuMap.get(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE) != null\n                    || puMetadata.getProperty(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE) != null)\n            {\n                SchemaManager schemaManager = getSchemaManagerForPu(persistenceUnit);\n\n                if (schemaManager != null)\n                {\n                    schemaManager.exportSchema(persistenceUnit, puToSchemaMetadata.get(persistenceUnit));\n                }\n            }\n        }\n    }\n\n    /**\n     * Return schema manager for pu.\n     * \n     * @param persistenceUnit\n     * @return\n     */\n    private SchemaManager getSchemaManagerForPu(final String persistenceUnit)\n    {\n        SchemaManager schemaManager = null;\n        Map<String, Object> externalProperties = KunderaCoreUtils.getExternalProperties(persistenceUnit,\n                externalPropertyMap, persistenceUnits);\n        if (getSchemaProperty(persistenceUnit, externalProperties) != null\n                && !getSchemaProperty(persistenceUnit, externalProperties).isEmpty())\n        {\n            ClientFactory clientFactory = ClientResolver.getClientFactory(persistenceUnit);\n            schemaManager = clientFactory != null ? clientFactory.getSchemaManager(externalProperties) : null;\n        }\n        return schemaManager;\n    }\n\n    /**\n     * Add tableGenerator to table info.\n     * \n     * @param appMetadata\n     * @param persistenceUnit\n     * @param tableInfos\n     * @param entityMetadata\n     * @param isCompositeId\n     */\n    private void addTableGenerator(ApplicationMetadata appMetadata, String persistenceUnit, List<TableInfo> tableInfos,\n            EntityMetadata entityMetadata)\n    {\n        Metamodel metamodel = appMetadata.getMetamodel(persistenceUnit);\n        IdDiscriptor keyValue = ((MetamodelImpl) metamodel).getKeyValue(entityMetadata.getEntityClazz().getName());\n        if (keyValue != null && keyValue.getTableDiscriptor() != null)\n        {\n            TableInfo tableGeneratorDiscriptor = new TableInfo(keyValue.getTableDiscriptor().getTable(),\n                    \"CounterColumnType\", String.class, keyValue.getTableDiscriptor().getPkColumnName());\n            if (!tableInfos.contains(tableGeneratorDiscriptor))\n            {\n                tableGeneratorDiscriptor.addColumnInfo(getJoinColumn(tableGeneratorDiscriptor,\n                        keyValue.getTableDiscriptor().getValueColumnName(), Long.class));\n                tableInfos.add(tableGeneratorDiscriptor);\n            }\n        }\n    }\n\n    /**\n     * parse the relations of entites .\n     * \n     * @param persistenceUnit\n     * @param tableInfos\n     * @param entityMetadata\n     * @param tableInfo\n     * @param relations\n     */\n    private void parseRelations(String persistenceUnit, List<TableInfo> tableInfos, EntityMetadata entityMetadata,\n            TableInfo tableInfo, List<Relation> relations)\n    {\n        for (Relation relation : relations)\n        {\n            if (relation != null)\n            {\n                Class entityClass = relation.getTargetEntity();\n                EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                        entityClass);\n                if (targetEntityMetadata == null)\n                {\n                    log.error(\"Persistence unit for class : \" + entityClass + \" is not loaded\");\n                    throw new SchemaGenerationException(\n                            \"Persistence unit for class : \" + entityClass + \" is not loaded\");\n                }\n                ForeignKey relationType = relation.getType();\n\n                // if relation type is one to many or join by primary key\n                if (targetEntityMetadata != null && relationType.equals(ForeignKey.ONE_TO_MANY)\n                        && relation.getJoinColumnName(kunderaMetadata) != null)\n                {\n                    // if self association\n                    if (targetEntityMetadata.equals(entityMetadata))\n                    {\n                        tableInfo.addColumnInfo(getJoinColumn(tableInfo, relation.getJoinColumnName(kunderaMetadata),\n                                entityMetadata.getIdAttribute().getJavaType()));\n                    }\n                    else\n                    {\n                        String pu = targetEntityMetadata.getPersistenceUnit();\n                        Type targetEntityType = targetEntityMetadata.getType();\n                        Class idClass = targetEntityMetadata.getIdAttribute().getJavaType();\n                        String idName = ((AbstractAttribute) targetEntityMetadata.getIdAttribute()).getJPAColumnName();\n                        TableInfo targetTableInfo = new TableInfo(targetEntityMetadata.getTableName(),\n                                targetEntityType.name(), idClass, idName);\n\n                        // In case of different persistence unit. case for poly\n                        // glot\n                        // persistence.\n                        if (!pu.equals(persistenceUnit))\n                        {\n                            List<TableInfo> targetTableInfos = getSchemaInfo(pu);\n\n                            addJoinColumnToInfo(relation.getJoinColumnName(kunderaMetadata), targetTableInfo,\n                                    targetTableInfos, entityMetadata);\n\n                            // add for newly discovered persistence unit.\n                            puToSchemaMetadata.put(pu, targetTableInfos);\n                        }\n                        else\n                        {\n                            addJoinColumnToInfo(relation.getJoinColumnName(kunderaMetadata), targetTableInfo,\n                                    tableInfos, entityMetadata);\n                        }\n                    }\n                }\n                // if relation type is one to one or many to one.\n                else if (relation.isUnary() && relation.getJoinColumnName(kunderaMetadata) != null)\n                {\n                    if (!relation.isJoinedByPrimaryKey())\n                    {\n                        tableInfo.addColumnInfo(getJoinColumn(tableInfo, relation.getJoinColumnName(kunderaMetadata),\n                                targetEntityMetadata.getIdAttribute().getJavaType()));\n                    }\n                }\n                // if relation type is many to many and relation via join table.\n                else if ((relationType.equals(ForeignKey.MANY_TO_MANY)) && (entityMetadata.isRelationViaJoinTable()))\n                {\n                    JoinTableMetadata joinTableMetadata = relation.getJoinTableMetadata();\n                    String joinTableName = joinTableMetadata != null ? joinTableMetadata.getJoinTableName() : null;\n                    String joinColumnName = joinTableMetadata != null\n                            ? (String) joinTableMetadata.getJoinColumns().toArray()[0] : null;\n                    String inverseJoinColumnName = joinTableMetadata != null\n                            ? (String) joinTableMetadata.getInverseJoinColumns().toArray()[0] : null;\n                    if (joinTableName != null)\n                    {\n                        TableInfo joinTableInfo = new TableInfo(joinTableName, Type.COLUMN_FAMILY.name(), String.class,\n                                \"key\");\n                        if (!tableInfos.isEmpty() && !tableInfos.contains(joinTableInfo) || tableInfos.isEmpty())\n                        {\n                            joinTableInfo.addColumnInfo(getJoinColumn(joinTableInfo, joinColumnName,\n                                    entityMetadata.getIdAttribute().getJavaType()));\n                            joinTableInfo.addColumnInfo(getJoinColumn(joinTableInfo, inverseJoinColumnName,\n                                    targetEntityMetadata.getIdAttribute().getJavaType()));\n\n                            // // Do not delete above lines. Currently join\n                            // table\n                            // columns are of type string only.\n                            // // It needs to be fixed later.\n                            // joinTableInfo.addColumnInfo(getJoinColumn(joinTableInfo,\n                            // joinColumnName, String.class));\n                            // joinTableInfo.addColumnInfo(getJoinColumn(joinTableInfo,\n                            // inverseJoinColumnName, String.class));\n\n                            tableInfos.add(joinTableInfo);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * adds join column name to the table Info of entity.\n     * \n     * @param joinColumn\n     * @param targetTableInfo\n     * @param targetTableInfos\n     */\n    private void addJoinColumnToInfo(String joinColumn, TableInfo targetTableInfo, List<TableInfo> targetTableInfos,\n            EntityMetadata m)\n    {\n        if (!joinColumn.equals(targetTableInfo.getIdColumnName()))\n        {\n\n            if (!targetTableInfos.isEmpty() && targetTableInfos.contains(targetTableInfo))\n            {\n                int idx = targetTableInfos.indexOf(targetTableInfo);\n                targetTableInfo = targetTableInfos.get(idx);\n                ColumnInfo columnInfoOfJoinColumn = getJoinColumn(targetTableInfo, joinColumn,\n                        m.getIdAttribute().getBindableJavaType());\n                if (!targetTableInfo.getColumnMetadatas().contains(columnInfoOfJoinColumn))\n                {\n                    targetTableInfo.addColumnInfo(columnInfoOfJoinColumn);\n                }\n            }\n            else\n            {\n                ColumnInfo columnInfoOfJoinColumn = getJoinColumn(targetTableInfo, joinColumn,\n                        m.getIdAttribute().getBindableJavaType());\n                if (!targetTableInfo.getColumnMetadatas().contains(columnInfoOfJoinColumn))\n                {\n                    targetTableInfo.addColumnInfo(columnInfoOfJoinColumn);\n                }\n                targetTableInfos.add(targetTableInfo);\n            }\n        }\n    }\n\n    /**\n     * Adds column to table info of entity.\n     * \n     * @param entityMetadata\n     * @param type\n     * @param tableInfo\n     */\n    private void addColumnToTableInfo(EntityMetadata entityMetadata, Type type, TableInfo tableInfo)\n    {\n        // Add columns to table info.\n\n        Metamodel metaModel = kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(entityMetadata.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n        Map<String, PropertyIndex> columns = entityMetadata.getIndexProperties();\n\n        // populate columnsToBeIndexed with composite indexes\n        for (Entry<String, PropertyIndex> c : columns.entrySet())\n        {\n            PropertyIndex indexedColumn = c.getValue();\n            if (indexedColumn.getIndexType() != null\n                    && indexedColumn.getIndexType().toLowerCase().equals(Constants.COMPOSITE))\n            {\n                IndexInfo indexInfo = new IndexInfo(c.getKey(), indexedColumn.getMax(), indexedColumn.getMin(),\n                        indexedColumn.getIndexType(), indexedColumn.getName());\n                tableInfo.addToIndexedColumnList(indexInfo);\n            }\n        }\n\n        Set attributes = entityType.getAttributes();\n\n        Iterator<Attribute> iter = attributes.iterator();\n        while (iter.hasNext())\n        {\n            Attribute attr = iter.next();\n\n            if (!attr.isAssociation())\n            {\n                if (((MetamodelImpl) metaModel).isEmbeddable(attr.getJavaType()))\n                {\n\n                    EmbeddableType embeddable = metaModel.embeddable(attr.getJavaType());\n\n                    EmbeddedColumnInfo embeddedColumnInfo = getEmbeddedColumn(tableInfo, embeddable, attr.getName(),\n                            attr.getJavaType(), ((Field) ((Field) attr.getJavaMember())));\n\n                    if (!tableInfo.getEmbeddedColumnMetadatas().contains(embeddedColumnInfo))\n                    {\n                        tableInfo.addEmbeddedColumnInfo(embeddedColumnInfo);\n                    }\n                }\n                else if (!attr.isCollection() && !((SingularAttribute) attr).isId())\n                {\n\n                    if (((Field) attr.getJavaMember()).getAnnotation(Lob.class) != null)\n                    {\n                        tableInfo.addLobColumnInfo(((AbstractAttribute) attr).getJPAColumnName());\n                    }\n\n                    ColumnInfo columnInfo = getColumn(tableInfo, attr,\n                            columns != null ? columns.get(((AbstractAttribute) attr).getJPAColumnName()) : null, null);\n                    if (!tableInfo.getColumnMetadatas().contains(columnInfo))\n                    {\n                        tableInfo.addColumnInfo(columnInfo);\n                    }\n                }\n                else if (attr.isCollection()\n                        && MetadataUtils.isBasicElementCollectionField((Field) attr.getJavaMember()))\n                {\n                    CollectionColumnInfo cci = new CollectionColumnInfo();\n                    cci.setCollectionColumnName(((AbstractAttribute) attr).getJPAColumnName());\n                    cci.setType(attr.getJavaType());\n                    cci.setGenericClasses(PropertyAccessorHelper.getGenericClasses((Field) attr.getJavaMember()));\n\n                    tableInfo.addCollectionColumnMetadata(cci);\n                    // add if collection column is indexed\n                    String jpaName = ((AbstractAttribute) attr).getJPAColumnName();\n                    PropertyIndex indexedColumn = columns.get(jpaName);\n                    if (indexedColumn != null && indexedColumn.getName() != null)\n                    {\n                        IndexInfo indexInfo = new IndexInfo(jpaName, indexedColumn.getMax(), indexedColumn.getMin(),\n                                indexedColumn.getIndexType(), indexedColumn.getName());\n                        tableInfo.addToIndexedColumnList(indexInfo);\n                        // Add more if required\n                    }\n                }\n                else if (attr.isCollection()\n                        && !MetadataUtils.isBasicElementCollectionField((Field) attr.getJavaMember()))\n                {\n                    CollectionColumnInfo eci = new CollectionColumnInfo();\n                    eci.setCollectionColumnName(((AbstractAttribute) attr).getJPAColumnName());\n                    eci.setType(attr.getJavaType());\n                    eci.setGenericClasses(PropertyAccessorHelper.getGenericClasses((Field) attr.getJavaMember()));\n\n                    tableInfo.addElementCollectionMetadata(eci);\n                    // add if collection column is indexed\n                    String jpaName = ((AbstractAttribute) attr).getJPAColumnName();\n                    PropertyIndex indexedColumn = columns.get(jpaName);\n                    if (indexedColumn != null && indexedColumn.getName() != null)\n                    {\n                        IndexInfo indexInfo = new IndexInfo(jpaName, indexedColumn.getMax(), indexedColumn.getMin(),\n                                indexedColumn.getIndexType(), indexedColumn.getName());\n                        tableInfo.addToIndexedColumnList(indexInfo);\n                        // Add more if required\n                    }\n                }\n\n            }\n        }\n\n        onInheritedProperty(tableInfo, entityType);\n    }\n\n    /**\n     * Add {@link DiscriminatorColumn} for schema generation.\n     * \n     * @param tableInfo\n     *            table info.\n     * @param entityType\n     *            entity type.\n     */\n    private void onInheritedProperty(TableInfo tableInfo, EntityType entityType)\n    {\n        String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n\n        if (discrColumn != null)\n        {\n            ColumnInfo columnInfo = new ColumnInfo();\n            columnInfo.setColumnName(discrColumn);\n            columnInfo.setType(String.class);\n            columnInfo.setIndexable(true);\n\n            IndexInfo idxInfo = new IndexInfo(discrColumn);\n            tableInfo.addColumnInfo(columnInfo);\n            tableInfo.addToIndexedColumnList(idxInfo);\n        }\n    }\n\n    /**\n     * Returns list of configured table/column families.\n     * \n     * @param persistenceUnit\n     *            persistence unit, for which schema needs to be fetched.\n     * \n     * @return list of {@link TableInfo}\n     */\n    private List<TableInfo> getSchemaInfo(String persistenceUnit)\n    {\n        List<TableInfo> tableInfos = puToSchemaMetadata.get(persistenceUnit);\n        // if no TableInfos for given persistence unit.\n        if (tableInfos == null)\n        {\n            tableInfos = new ArrayList<TableInfo>();\n        }\n        return tableInfos;\n    }\n\n    /**\n     * Returns map of entity metdata {@link EntityMetadata}.\n     * \n     * @param appMetadata\n     *            application metadata\n     * @param persistenceUnit\n     *            persistence unit\n     * @return map of entity metadata.\n     */\n    private Map<String, EntityMetadata> getEntityMetadataCol(ApplicationMetadata appMetadata, String persistenceUnit)\n    {\n        Metamodel metaModel = appMetadata.getMetamodel(persistenceUnit);\n        Map<String, EntityMetadata> entityMetadataMap = ((MetamodelImpl) metaModel).getEntityMetadataMap();\n        return entityMetadataMap;\n    }\n\n    /**\n     * Get Embedded column info.\n     * \n     * @param embeddableType\n     * @param embeddableColName\n     * @param embeddedEntityClass\n     * @param field\n     * @return\n     */\n    private EmbeddedColumnInfo getEmbeddedColumn(TableInfo tableInfo, EmbeddableType embeddableType,\n            String embeddableColName, Class embeddedEntityClass, Field field)\n    {\n\n        String[] orderByColumns = null;\n        if (field.isAnnotationPresent(OrderBy.class))\n        {\n            OrderBy order = (OrderBy) field.getAnnotation(OrderBy.class);\n            orderByColumns = order.value().split(\"\\\\s*,\\\\s*\");\n        }\n        EmbeddedColumnInfo embeddedColumnInfo = new EmbeddedColumnInfo(embeddableType);\n        embeddedColumnInfo.setEmbeddedColumnName(embeddableColName);\n        Map<String, PropertyIndex> indexedColumns = IndexProcessor.getIndexesOnEmbeddable(embeddedEntityClass);\n        List<ColumnInfo> columns = new ArrayList<ColumnInfo>();\n\n        Set attributes = embeddableType.getAttributes();\n        Iterator<Attribute> iter = attributes.iterator();\n\n        while (iter.hasNext())\n        {\n            Attribute attr = iter.next();\n            columns.add(getColumn(tableInfo, attr, indexedColumns.get(attr.getName()), orderByColumns));\n        }\n        embeddedColumnInfo.setColumns(columns);\n        return embeddedColumnInfo;\n    }\n\n    /**\n     * getColumn method return ColumnInfo for the given column\n     * \n     * @param Object\n     *            of Column.\n     * @return Object of ColumnInfo.\n     */\n    private ColumnInfo getColumn(TableInfo tableInfo, Attribute column, PropertyIndex indexedColumn,\n            String[] orderByColumns)\n    {\n        ColumnInfo columnInfo = new ColumnInfo();\n\n        if (column.getJavaType().isAnnotationPresent(OrderBy.class))\n        {\n            OrderBy order = (OrderBy) column.getJavaType().getAnnotation(OrderBy.class);\n            orderByColumns = order.value().split(\"\\\\s*,\\\\s*\");\n\n        }\n        columnInfo.setOrderBy(getOrderByColumn(orderByColumns, column));\n\n        if (column.getJavaType().isEnum())\n        {\n            columnInfo.setType(String.class);\n        }\n        else\n        {\n            columnInfo.setType(column.getJavaType());\n        }\n        columnInfo.setColumnName(((AbstractAttribute) column).getJPAColumnName());\n        if (indexedColumn != null && indexedColumn.getName() != null)\n        {\n            columnInfo.setIndexable(true);\n            IndexInfo indexInfo = new IndexInfo(((AbstractAttribute) column).getJPAColumnName(), indexedColumn.getMax(),\n                    indexedColumn.getMin(), indexedColumn.getIndexType(), indexedColumn.getName());\n            tableInfo.addToIndexedColumnList(indexInfo);\n            // Add more if required\n        }\n\n        return columnInfo;\n    }\n\n    /**\n     * getOrderByColumn method return order by value of the column\n     * \n     * @param String\n     *            [] orderByColumns\n     * \n     * @param Attribute\n     *            column\n     * \n     * @return orderColumnValue.\n     */\n    private String getOrderByColumn(String[] orderByColumns, Attribute column)\n    {\n\n        if (orderByColumns != null)\n        {\n            for (String orderColumn : orderByColumns)\n            {\n                String[] orderValue = orderColumn.split(\"\\\\s\");\n                String orderColumnName = orderValue[0].substring(orderValue[0].lastIndexOf('.') + 1);\n                String orderColumnValue = orderValue[1];\n\n                if (orderColumnName.equals(((AbstractAttribute) column).getName())\n                        || orderColumnName.equals(((AbstractAttribute) column).getJPAColumnName()))\n                {\n                    return orderColumnValue;\n                }\n            }\n        }\n        return null;\n\n    }\n\n    /**\n     * getJoinColumn method return ColumnInfo for the join column\n     * \n     * @param columnType\n     * \n     * @param String\n     *            joinColumnName.\n     * @return ColumnInfo object columnInfo.\n     */\n    private ColumnInfo getJoinColumn(TableInfo tableInfo, String joinColumnName, Class columnType)\n    {\n        ColumnInfo columnInfo = new ColumnInfo();\n        columnInfo.setColumnName(joinColumnName);\n        columnInfo.setIndexable(true);\n\n        IndexInfo indexInfo = new IndexInfo(joinColumnName);\n        tableInfo.addToIndexedColumnList(indexInfo);\n\n        columnInfo.setType(columnType);\n        return columnInfo;\n    }\n\n    /**\n     * getKunderaProperty method return auto schema generation property for give\n     * persistence unit.\n     * \n     * @param externalProperties\n     * \n     * @param String\n     *            persistenceUnit.\n     * @return value of kundera auto ddl in form of String.\n     */\n    private String getSchemaProperty(String persistenceUnit, Map<String, Object> externalProperties)\n    {\n        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(persistenceUnit);\n        String autoDdlOption = externalProperties != null\n                ? (String) externalProperties.get(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE) : null;\n        if (autoDdlOption == null)\n        {\n            autoDdlOption = persistenceUnitMetadata != null\n                    ? persistenceUnitMetadata.getProperty(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE) : null;\n        }\n        return autoDdlOption;\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/schema/CollectionColumnInfo.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure.schema;\n\nimport java.util.List;\n\n\n/**\n * @author amresh.singh\n *\n */\npublic class CollectionColumnInfo \n{\n    /** The collection column name variable .*/\n    private String collectionColumnName;  \n    \n    /**\n     * Type of collection column among:\n     * 1. java.util.List\n     * 2. java.util.Set\n     * 3. java.util.Map \n     */\n    private Class<?> type;\n    \n    /**\n     * Generic classes of data held in collection\n     * would hold one element for Set and List, two for Map\n     */\n    private List<Class<?>> genericClasses;\n\n    /**\n     * @return the collectionColumnName\n     */\n    public String getCollectionColumnName()\n    {\n        return collectionColumnName;\n    }\n\n    /**\n     * @param collectionColumnName the collectionColumnName to set\n     */\n    public void setCollectionColumnName(String collectionColumnName)\n    {\n        this.collectionColumnName = collectionColumnName;\n    }\n\n    /**\n     * @return the type\n     */\n    public Class<?> getType()\n    {\n        return type;\n    }\n\n    /**\n     * @param type the type to set\n     */\n    public void setType(Class<?> type)\n    {\n        this.type = type;\n    }\n\n    /**\n     * @return the genericClasses\n     */\n    public List<Class<?>> getGenericClasses()\n    {\n        return genericClasses;\n    }\n\n    /**\n     * @param genericClasses the genericClasses to set\n     */\n    public void setGenericClasses(List<Class<?>> genericClasses)\n    {\n        this.genericClasses = genericClasses;\n    }   \n    \n    /* (non-Javadoc)\n     * @see java.lang.Object#equals(java.lang.Object)\n     */\n    @Override\n    public boolean equals(Object obj){\n    \t\n    \t//if object's class and column name matches then return true;\n        return obj != null && obj instanceof CollectionColumnInfo && ((CollectionColumnInfo) obj).collectionColumnName != null ? this.collectionColumnName != null\n                && this.collectionColumnName.equals(((CollectionColumnInfo) obj).collectionColumnName)\n                : false;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/schema/ColumnInfo.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.configure.schema;\n\nimport org.apache.commons.lang.builder.HashCodeBuilder;\n\n/**\n * The Class ColumnInfo holds column related information.\n * \n * @author Kuldeep.Kumar\n */\npublic class ColumnInfo\n{\n\n    /** The is indexable variable for indexing the column. */\n    private boolean isIndexable = false;\n\n    /** The column name variable . */\n    private String columnName;\n    \n    /** The column order by variable . */\n    private String order;\n\n    /** The type variable. */\n    private Class type;\n\n    /**\n     * Instantiates a new column info.\n     */\n    public ColumnInfo()\n    {\n\n    }\n\n    /**\n     * Equals method compare two object of columnInfo on the basis of their\n     * name.\n     * \n     * @param Object\n     *            instance.\n     * \n     * @return boolean value.\n     */\n    @Override\n    public boolean equals(Object obj)\n    {\n\n        // / if object's class and column name matches then return true;\n\n        return obj != null && obj instanceof ColumnInfo && ((ColumnInfo) obj).columnName != null ? this.columnName != null\n                && this.columnName.equals(((ColumnInfo) obj).columnName)\n                : false;\n\n    }\n\n    @Override\n    /**\n     * returns the hash code for object. \n     * \n     */\n    public int hashCode()\n    {\n        return HashCodeBuilder.reflectionHashCode(this);\n    }\n\n    @Override\n    /**\n     * returns the string representation of object .\n     * \n     */\n    public String toString()\n    {\n        StringBuilder strBuilder = new StringBuilder(\"type:==> \");\n        strBuilder.append(type);\n        strBuilder.append(\" | columnName: ==>\");\n        strBuilder.append(columnName);\n        strBuilder.append(\" | isIndexable: ==>\");\n        strBuilder.append(isIndexable);\n        strBuilder.append(\" | orderby: ==>\");\n        strBuilder.append(order);\n        return strBuilder.toString();\n    }\n\n    /**\n     * Gets the column name.\n     * \n     * @return the columnName\n     */\n    public String getColumnName()\n    {\n        return columnName;\n    }\n\n    /**\n     * Sets the column name.\n     * \n     * @param columnName\n     *            the columnName to set\n     */\n    public void setColumnName(String columnName)\n    {\n        this.columnName = columnName;\n    }\n\n    /**\n     * Checks if is indexable.\n     * \n     * @return the isIndexable\n     */\n    public boolean isIndexable()\n    {\n        return isIndexable;\n    }\n\n    /**\n     * Sets the indexable.\n     * \n     * @param isIndexable\n     *            the isIndexable to set\n     */\n    public void setIndexable(boolean isIndexable)\n    {\n        this.isIndexable = isIndexable;\n    }\n\n    /**\n     * @return the type\n     */\n    public Class getType()\n    {\n        return type;\n    }\n\n    /**\n     * @param type\n     *            the type to set\n     */\n    public void setType(Class type)\n    {\n        this.type = type;\n    }\n\n    public void setOrderBy(String order)\n    {\n        this.order = order;\n    }\n\n    public String getOrderBy()\n    {\n        return order;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/schema/EmbeddedColumnInfo.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.configure.schema;\n\nimport java.util.List;\n\nimport javax.persistence.metamodel.EmbeddableType;\n\nimport org.apache.commons.lang.builder.HashCodeBuilder;\n\n/**\n * The Class ColumnInfo holds the information of Embedded Columns.\n * \n * @author Kuldeep.Kumar\n * \n */\npublic class EmbeddedColumnInfo\n{\n    /** The embedded column name variable . */\n    private String embeddedColumnName;\n\n    /** The list of columns variable is columns . */\n    private List<ColumnInfo> columns;\n\n    private EmbeddableType embeddable;\n\n    /**\n     * @param metaModel\n     */\n    public EmbeddedColumnInfo(EmbeddableType metaModel)\n    {\n        this.embeddable = metaModel;\n    }\n\n    /**\n     * @return the embeddable\n     */\n    public EmbeddableType getEmbeddable()\n    {\n        return embeddable;\n    }\n\n    /**\n     * @return the embeddedColumnName\n     */\n    public String getEmbeddedColumnName()\n    {\n        return embeddedColumnName;\n    }\n\n    /**\n     * @param embeddedColumnName\n     *            the embeddedColumnName to set\n     */\n    public void setEmbeddedColumnName(String embeddedColumnName)\n    {\n        this.embeddedColumnName = embeddedColumnName;\n    }\n\n    /**\n     * @return the columns\n     */\n    public List<ColumnInfo> getColumns()\n    {\n        return columns;\n    }\n\n    /**\n     * @param columns\n     *            the columns to set\n     */\n    public void setColumns(List<ColumnInfo> columns)\n    {\n        this.columns = columns;\n    }\n\n    /**\n     * Equals method compare two object of EmbeddedColumnInfo on the basis of\n     * their name.\n     * \n     * @param Object\n     *            instance.\n     * \n     * @return boolean value.\n     */\n    @Override\n    public boolean equals(Object obj)\n    {\n        return obj != null && obj instanceof EmbeddedColumnInfo\n                && ((EmbeddedColumnInfo) obj).embeddedColumnName != null ? this.embeddedColumnName != null\n                && this.embeddedColumnName.equals(((EmbeddedColumnInfo) obj).embeddedColumnName) : false;\n    }\n\n    @Override\n    /**\n     * returns the hash code for object.\n     * \n     */\n    public int hashCode()\n    {\n        return HashCodeBuilder.reflectionHashCode(this);\n    }\n\n    @Override\n    /**\n     * returns the string representation of object .\n     * \n     */\n    public String toString()\n    {\n        StringBuilder strBuilder = new StringBuilder(\"embeddedColumnName:==> \");\n        strBuilder.append(embeddedColumnName);\n        return strBuilder.toString();\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/schema/IndexInfo.java",
    "content": "package com.impetus.kundera.configure.schema;\n\n/**\n * Class IndexInfo holds the information about index for a column.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class IndexInfo\n{\n    /** The column name variable . */\n    private String columnName;\n\n    /** Maximum allowed value for this column */\n    private Integer maxValue;\n\n    /** Minimum allowed value for this column */\n    private Integer minValue;\n\n    /** The index type. */\n    private String indexType;\n\n    /** Index name value */\n    private String indexName;\n\n    public IndexInfo(String columnName, Integer maxValue, Integer minValue, String indexType, String indexName)\n    {\n        this.columnName = columnName;\n        this.maxValue = maxValue;\n        this.minValue = minValue;\n        this.indexType = indexType;\n        this.indexName = indexName;\n    }\n\n    public IndexInfo(String columnName)\n    {\n        this(columnName, null, null, null, columnName);\n    }\n\n    public String getColumnName()\n    {\n        return columnName;\n    }\n\n    public void setColumnName(String columnName)\n    {\n        this.columnName = columnName;\n    }\n\n    public Integer getMaxValue()\n    {\n        return maxValue;\n    }\n\n    public void setMaxValue(Integer maxValue)\n    {\n        this.maxValue = maxValue;\n    }\n\n    public Integer getMinValue()\n    {\n        return minValue;\n    }\n\n    public void setMinValue(Integer minValue)\n    {\n        this.minValue = minValue;\n    }\n\n    public String getIndexType()\n    {\n        return indexType;\n    }\n\n    public void setIndexType(String indexType)\n    {\n        this.indexType = indexType;\n    }\n\n    /**\n     * Equals method compare two object of columnInfo on the basis of their\n     * name.\n     * \n     * @param Object\n     *            instance.\n     * \n     * @return boolean value.\n     */\n    @Override\n    public boolean equals(Object columnName)\n    {\n        // if column name matches then return true;\n        return columnName != null ? this.columnName.equals(columnName.toString()) : false;\n    }\n\n    @Override\n    /**\n     * returns the string representation of object .\n     * \n     */\n    public String toString()\n    {\n        return columnName;\n    }\n\n    /**\n     * \n     * @return index name\n     */\n    public String getIndexName()\n    {\n        return indexName;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/schema/SchemaGenerationException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.configure.schema;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * Exception class for all type of exceptions thrown by SchemaManager during\n * generating schema.\n * \n * @author Kuldeep.Kumar\n */\npublic class SchemaGenerationException extends KunderaException\n{\n\n    /** The Constant serialVersionUID. */\n    private static final long serialVersionUID = 3855497974944993364L;\n\n    /** The data store name. */\n    private String dataStoreName;\n\n    /** The schema name. */\n    private String schemaName;\n\n    /** The table name. */\n    private String tableName;\n\n    /**\n     * Instantiates a new schemaGeneration exception.\n     * \n     * @param dataStore\n     *            the data store\n     * @param schema\n     *            the schema\n     */\n    public SchemaGenerationException(String arg0, String dataStore, String schema)\n    {\n        super(arg0);\n        this.dataStoreName = dataStore;\n        this.schemaName = schema;\n    }\n\n    /**\n     * Instantiates a new schemaGeneration exception.\n     * \n     * @param arg0\n     *            the arg0\n     * @param dataStore\n     *            the data store\n     * @param schema\n     *            the schema\n     * @param table\n     *            the table\n     */\n    public SchemaGenerationException(String arg0, String dataStore, String schema, String table)\n    {\n        super(arg0);\n        this.dataStoreName = dataStore;\n        this.schemaName = schema;\n        this.tableName = table;\n    }\n\n    /**\n     * Instantiates a new schemaGeneration exception.\n     * \n     * @param arg0\n     *            the arg0\n     */\n    public SchemaGenerationException(Throwable arg0)\n    {\n        super(arg0);\n    }\n\n    /**\n     * Instantiates a new schemaGeneration exception.\n     * \n     * @param arg0\n     *            the arg0\n     * @param dataStore\n     *            the data store\n     */\n    public SchemaGenerationException(Throwable arg0, String dataStore)\n    {\n        super(arg0);\n        this.dataStoreName = dataStore;\n    }\n\n    /**\n     * Instantiates a new schemaGeneration exception.\n     * \n     * @param arg0\n     *            the arg0\n     * @param dataStore\n     *            the data store\n     * @param schema\n     *            the schema\n     */\n    public SchemaGenerationException(Throwable arg0, String dataStore, String schema)\n    {\n        super(arg0);\n        this.dataStoreName = dataStore;\n        this.schemaName = schema;\n    }\n\n    /**\n     * Instantiates a new schemaGeneration exception.\n     * \n     * @param arg0\n     *            the arg0\n     * @param arg1\n     *            the arg1\n     * @param dataStore\n     *            the data store\n     */\n    public SchemaGenerationException(String arg0, Throwable arg1, String dataStore)\n    {\n        super(arg0, arg1);\n        this.dataStoreName = dataStore;\n    }\n\n    public SchemaGenerationException(String arg0, Throwable arg1, String dataStoreName, String databaseName)\n    {\n        super(arg0, arg1);\n        this.dataStoreName = dataStoreName;\n        this.schemaName = databaseName;\n    }\n\n    public SchemaGenerationException(String arg0)\n    {\n        super(arg0);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/schema/TableInfo.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure.schema;\n\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport org.apache.commons.lang.builder.HashCodeBuilder;\n\n/**\n * TableInfo class holds table creation related information.\n * \n * @author Kuldeep.Kumar\n * \n */\npublic class TableInfo\n{\n    /** The table name. */\n    private String tableName;\n\n    /** The column metadatas. */\n    private List<ColumnInfo> columnMetadatas;\n\n    /** The table id class. */\n    private Class<?> idClazz;\n\n    /** The table id name. */\n    private String idColumnName;\n\n    /** The type. */\n    private String type;\n\n    /** The embedded column metadatas. */\n    private List<EmbeddedColumnInfo> embeddedColumnMetadatas;\n\n    /** The collection column metadatas. */\n    private List<CollectionColumnInfo> collectionColumnMetadatas;\n\n    /** The element collection metadatas. */\n    private List<CollectionColumnInfo> elementCollectionMetadatas;\n\n    private Set<String> lobColumnInfos;\n\n    public Set<String> getLobColumnInfo()\n    {\n        return lobColumnInfos == null ? new HashSet<String>() : lobColumnInfos;\n    }\n\n    public void addLobColumnInfo(String lobColumnInfo)\n    {\n        if (this.lobColumnInfos == null)\n        {\n            this.lobColumnInfos = new HashSet<String>();\n        }\n        lobColumnInfos.add(lobColumnInfo);\n    }\n\n    /**\n     * Gets the element collection metadatas.\n     * \n     * @return the element collection metadatas\n     */\n    public List<CollectionColumnInfo> getElementCollectionMetadatas()\n    {\n        if (this.elementCollectionMetadatas == null)\n        {\n            this.elementCollectionMetadatas = new ArrayList<CollectionColumnInfo>();\n        }\n        return elementCollectionMetadatas;\n    }\n\n    /**\n     * Adds the element collection metadata.\n     * \n     * @param elementCollectionMetadata\n     *            the element collection metadata\n     */\n    public void addElementCollectionMetadata(CollectionColumnInfo elementCollectionMetadata)\n    {\n        if (this.elementCollectionMetadatas == null)\n        {\n            this.elementCollectionMetadatas = new ArrayList<CollectionColumnInfo>();\n        }\n\n        if (!elementCollectionMetadatas.contains(elementCollectionMetadata))\n        {\n            elementCollectionMetadatas.add(elementCollectionMetadata);\n        }\n    }\n\n    /** The column to be indexed. */\n    private List<IndexInfo> columnToBeIndexed = new ArrayList<IndexInfo>();\n\n    /**\n     * Instantiates a new table info.\n     * \n     * @param tableName\n     *            the table name\n     * @param tableSchemaType\n     *            the table schema type\n     * @param idClassType\n     *            the id class type\n     * @param idColumnName\n     *            the id column name\n     */\n    public TableInfo(String tableName, String tableSchemaType, Class<?> idClassType, String idColumnName)\n    {\n        this.tableName = tableName;\n        this.type = tableSchemaType;\n        this.idClazz = idClassType;\n        this.idColumnName = idColumnName;\n    }\n\n    /**\n     * Equals method compare two object of TableInfo on the basis of their name\n     * .\n     * \n     * @param obj\n     *            the obj\n     * @return boolean value.\n     */\n    @Override\n    public boolean equals(Object obj)\n    {\n\n        return obj != null && obj instanceof TableInfo && ((TableInfo) obj).tableName != null ? this.tableName != null\n                && this.tableName.equals(((TableInfo) obj).tableName) : false;\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.lang.Object#hashCode()\n     */\n    @Override\n    /**\n     * returns the hash code for object. \n     * \n     */\n    public int hashCode()\n    {\n        return HashCodeBuilder.reflectionHashCode(this);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.lang.Object#toString()\n     */\n    @Override\n    /**\n     * returns the string representation of object .\n     * \n     */\n    public String toString()\n    {\n        StringBuilder strBuilder = new StringBuilder(\"tableIdType:==> \");\n        strBuilder.append(idClazz);\n        strBuilder.append(\" | tableName: ==>\");\n        strBuilder.append(tableName);\n        strBuilder.append(\" | type: ==>\");\n        strBuilder.append(type);\n        return strBuilder.toString();\n    }\n\n    /**\n     * Gets the table name.\n     * \n     * @return the tableName\n     */\n    public String getTableName()\n    {\n        return tableName;\n    }\n\n    /**\n     * Sets the table name.\n     * \n     * @param tableName\n     *            the tableName to set\n     */\n    public void setTableName(String tableName)\n    {\n        this.tableName = tableName;\n    }\n\n    /**\n     * Gets the table id type.\n     * \n     * @return the tableIdType\n     */\n    public Class<?> getTableIdType()\n    {\n        return idClazz;\n    }\n\n    /**\n     * Sets the table id type.\n     * \n     * @param tableIdType\n     *            the tableIdType to set\n     */\n    public void setTableIdType(Class<?> tableIdType)\n    {\n        this.idClazz = tableIdType;\n    }\n\n    /**\n     * Gets the column metadatas.\n     * \n     * @return the columnMetadatas\n     */\n    public List<ColumnInfo> getColumnMetadatas()\n    {\n\n        if (this.columnMetadatas == null)\n        {\n            this.columnMetadatas = new ArrayList<ColumnInfo>();\n        }\n\n        return columnMetadatas;\n    }\n\n    /**\n     * Adds the column info.\n     * \n     * @param columnInfo\n     *            the column info\n     */\n    public void addColumnInfo(ColumnInfo columnInfo)\n    {\n        if (this.columnMetadatas == null)\n        {\n            this.columnMetadatas = new ArrayList<ColumnInfo>();\n        }\n        if (!columnMetadatas.contains(columnInfo) && !this.getIdColumnName().equals(columnInfo.getColumnName()))\n        {\n            columnMetadatas.add(columnInfo);\n        }\n    }\n\n    /**\n     * Adds the embedded column info.\n     * \n     * @param embdColumnInfo\n     *            the embd column info\n     */\n    public void addEmbeddedColumnInfo(EmbeddedColumnInfo embdColumnInfo)\n    {\n        if (this.embeddedColumnMetadatas == null)\n        {\n            this.embeddedColumnMetadatas = new ArrayList<EmbeddedColumnInfo>();\n        }\n        if (!embeddedColumnMetadatas.contains(embdColumnInfo))\n        {\n            embeddedColumnMetadatas.add(embdColumnInfo);\n        }\n    }\n\n    /**\n     * Gets the embedded column metadatas.\n     * \n     * @return the embeddedColumnMetadatas\n     */\n    public List<EmbeddedColumnInfo> getEmbeddedColumnMetadatas()\n    {\n        if (this.embeddedColumnMetadatas == null)\n        {\n            this.embeddedColumnMetadatas = new ArrayList<EmbeddedColumnInfo>();\n        }\n        return embeddedColumnMetadatas;\n    }\n\n    /**\n     * Gets the collection column metadatas.\n     * \n     * @return the collectionColumnMetadatas\n     */\n    public List<CollectionColumnInfo> getCollectionColumnMetadatas()\n    {\n        if (this.collectionColumnMetadatas == null)\n        {\n            this.collectionColumnMetadatas = new ArrayList<CollectionColumnInfo>();\n        }\n        return collectionColumnMetadatas;\n    }\n\n    /**\n     * Adds the collection column metadata.\n     * \n     * @param collectionColumnMetadata\n     *            the collection column metadata\n     */\n    public void addCollectionColumnMetadata(CollectionColumnInfo collectionColumnMetadata)\n    {\n        if (this.collectionColumnMetadatas == null)\n        {\n            this.collectionColumnMetadatas = new ArrayList<CollectionColumnInfo>();\n        }\n\n        if (!collectionColumnMetadatas.contains(collectionColumnMetadata))\n        {\n            collectionColumnMetadatas.add(collectionColumnMetadata);\n        }\n    }\n\n    /**\n     * Gets the type.\n     * \n     * @return the type\n     */\n    public String getType()\n    {\n        return type;\n    }\n\n    /**\n     * Returns name of id attribute.\n     * \n     * @return id attribute name.\n     */\n    public String getIdColumnName()\n    {\n        return idColumnName;\n    }\n\n    /**\n     * Returns list of index information object.\n     * \n     * @return the columns to be indexed\n     */\n    public List<IndexInfo> getColumnsToBeIndexed()\n    {\n        return this.columnToBeIndexed;\n    }\n\n    /**\n     * Gets the column to be indexed.\n     * \n     * @param columnName\n     *            the column name\n     * @return the column to be indexed\n     */\n    public IndexInfo getColumnToBeIndexed(String columnName)\n    {\n        IndexInfo idxInfo = new IndexInfo(columnName);\n        if (columnToBeIndexed.contains(idxInfo))\n        {\n            int index = columnToBeIndexed.indexOf(idxInfo);\n            return getColumnsToBeIndexed().get(index);\n        }\n        return idxInfo;\n    }\n\n    /**\n     * Adds the to indexed column list.\n     * \n     * @param indexInfo\n     *            the index info\n     */\n    public void addToIndexedColumnList(IndexInfo indexInfo)\n    {\n        ColumnInfo columnInfo = new ColumnInfo();\n        columnInfo.setColumnName(indexInfo.getColumnName());\n        if (getEmbeddedColumnMetadatas().isEmpty()\n                || !getEmbeddedColumnMetadatas().get(0).getColumns().contains(columnInfo))\n        {\n            if (!columnToBeIndexed.contains(indexInfo))\n            {\n                columnToBeIndexed.add(indexInfo);\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/schema/api/AbstractSchemaManager.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure.schema.api;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Schema;\nimport com.impetus.kundera.configure.schema.TableInfo;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * Abstract Schema Manager has abstract method to handle\n * {@code SchemaOperationType}.\n * \n * @author Kuldeep.Kumar\n * \n */\npublic abstract class AbstractSchemaManager\n{\n\n    /** The pu metadata variable. */\n    protected PersistenceUnitMetadata puMetadata;\n\n    /** The port variable. */\n    protected String port;\n\n    /** The host variable . */\n    protected String[] hosts;\n\n    /** The kundera_client variable. */\n    protected String clientFactory;\n\n    /** The database name variable. */\n    protected String databaseName;\n\n    /** The table infos variable . */\n    protected List<TableInfo> tableInfos;\n\n    /** The operation variable. */\n    protected String operation;\n\n    /** for kundera.show property */\n    protected boolean showQuery;\n\n    protected List<Schema> schemas = null;\n\n    protected Connection conn = null;\n\n    protected DataStore dataStore = null;\n\n    protected Map<String, Object> externalProperties;\n\n    protected String userName = null;\n\n    protected String password = null;\n\n    protected final KunderaMetadata kunderaMetadata;\n\n    /**\n     * Initialise with configured client factory.\n     * \n     * @param clientFactory\n     *            specific client factory.\n     * @param externalProperties\n     */\n    protected AbstractSchemaManager(String clientFactory, Map<String, Object> externalProperties,\n            final KunderaMetadata kunderaMetadata)\n    {\n        this.clientFactory = clientFactory;\n        this.externalProperties = externalProperties;\n        this.kunderaMetadata = kunderaMetadata;\n    }\n\n    /**\n     * Export schema handles the handleOperation method.\n     * \n     * @param hbase\n     */\n    protected void exportSchema(final String persistenceUnit, List<TableInfo> tables)\n    {\n        // Get persistence unit metadata\n        this.puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit);\n        String paramString = externalProperties != null ? (String) externalProperties\n                .get(PersistenceProperties.KUNDERA_CLIENT_FACTORY) : null;\n        if (clientFactory != null\n                && ((clientFactory.equalsIgnoreCase(puMetadata.getProperties().getProperty(\n                        PersistenceProperties.KUNDERA_CLIENT_FACTORY))) || (paramString != null && clientFactory\n                        .equalsIgnoreCase(paramString))))\n        {\n            readConfigProperties(puMetadata);\n\n            // invoke handle operation.\n            if (operation != null && initiateClient())\n            {\n                tableInfos = tables;\n                handleOperations(tables);\n            }\n        }\n    }\n\n    /**\n     * @param pu\n     */\n    private void readConfigProperties(final PersistenceUnitMetadata puMetadata)\n    {\n        String hostName = null;\n        String portName = null;\n        String operationType = null;\n        String schemaName = null;\n        if (externalProperties != null)\n        {\n            portName = (String) externalProperties.get(PersistenceProperties.KUNDERA_PORT);\n            hostName = (String) externalProperties.get(PersistenceProperties.KUNDERA_NODES);\n            userName = (String) externalProperties.get(PersistenceProperties.KUNDERA_USERNAME);\n            password = (String) externalProperties.get(PersistenceProperties.KUNDERA_PASSWORD);\n            schemaName = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);\n            // get type of schema of operation.\n            operationType = (String) externalProperties.get(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE);\n            showQuery = KunderaCoreUtils.isShowQueryEnabled(externalProperties, puMetadata.getPersistenceUnitName(), kunderaMetadata);\n        }\n        if (portName == null)\n            portName = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_PORT);\n        if (hostName == null)\n            hostName = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_NODES);\n        if (schemaName == null)\n            schemaName = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_KEYSPACE);\n        // get type of schema of operation.\n        if (operationType == null)\n            operationType = puMetadata.getProperty(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE);\n       /* if (!showQuery)\n            showQuery = Boolean.parseBoolean(puMetadata.getProperties().getProperty(\n                    PersistenceProperties.KUNDERA_SHOW_QUERY));\n*/\n        if (userName == null)\n        {\n            userName = puMetadata.getProperty(PersistenceProperties.KUNDERA_USERNAME);\n            password = puMetadata.getProperty(PersistenceProperties.KUNDERA_PASSWORD);\n        }\n        String[] hostArray = hostName.split(\",\");\n        hosts = new String[hostArray.length];\n        for (int i = 0; i < hostArray.length; i++)\n        {\n            hosts[i] = hostArray[i].trim();\n        }\n        this.port = portName;\n        this.databaseName = schemaName;\n        this.operation = operationType;\n    }\n\n    /**\n     * Initiate client to initialize with client specific schema.\n     * \n     * @return true, if successful\n     */\n    protected abstract boolean initiateClient();\n\n    /**\n     * Validates the schema.\n     * \n     * @param tableInfos\n     *            the table infos\n     */\n    protected abstract void validate(List<TableInfo> tableInfos);\n\n    /**\n     * Update.\n     * \n     * @param tableInfos\n     *            the table infos\n     */\n    protected abstract void update(List<TableInfo> tableInfos);\n\n    /**\n     * Creates the.\n     * \n     * @param tableInfos\n     *            the table infos\n     */\n    protected abstract void create(List<TableInfo> tableInfos);\n\n    /**\n     * Create_drop.\n     * \n     * @param tableInfos\n     *            the table infos\n     */\n    protected abstract void create_drop(List<TableInfo> tableInfos);\n\n    /**\n     * handleOperations method handles the all operation on the basis of\n     * operationType\n     */\n\n    /**\n     * enum class for operation type\n     */\n    /**\n     * The Enum ScheamOperationType.\n     */\n    public enum SchemaOperationType\n    {\n\n        /** The createdrop. */\n        createdrop,\n        /** The create. */\n        create,\n        /** The validate. */\n        validate,\n        /** The update. */\n        update;\n\n        /**\n         * Gets the single instance of ScheamOperationType.\n         * \n         * @param operation\n         *            the operation\n         * @return single instance of ScheamOperationType\n         */\n        public static SchemaOperationType getInstance(String operation)\n        {\n            if (operation.equalsIgnoreCase(\"create-drop\"))\n            {\n                return SchemaOperationType.createdrop;\n            }\n            return SchemaOperationType.valueOf(SchemaOperationType.class, operation);\n        }\n    }\n\n    /**\n     * Handle operations.\n     * \n     * @param tableInfos\n     *            the table infos\n     */\n    private void handleOperations(List<TableInfo> tableInfos)\n    {\n        SchemaOperationType operationType = SchemaOperationType.getInstance(operation);\n\n        switch (operationType)\n        {\n        case createdrop:\n            create_drop(tableInfos);\n            break;\n        case create:\n            create(tableInfos);\n            break;\n        case update:\n            update(tableInfos);\n            break;\n        case validate:\n            validate(tableInfos);\n            break;\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/configure/schema/api/SchemaManager.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure.schema.api;\n\nimport java.util.List;\n\nimport com.impetus.kundera.configure.schema.TableInfo;\n\n/**\n * Interface to define methods to be implemented by different schema managers.\n * \n * @author kuldeep.kumar\n * \n */\npublic interface SchemaManager\n{\n    /**\n     * Exports schema according to configured schema operation e.g.\n     * {create,create-drop,update,validate}\n     */\n    void exportSchema(String persistenceUnit, List<TableInfo> puToSchemaCol);\n\n    /**\n     * Method required to drop auto create schema,in case of schema operation as\n     * {create-drop},\n     */\n    void dropSchema();\n\n    /**\n     * validates the entity against the Client specific properties.\n     * \n     * @return\n     * \n     */\n    boolean validateEntity(Class clazz);\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/db/DataRow.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.db;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\n/**\r\n * Utility class that represents a row in Column family based datastores like\r\n * cassandra and HBase.\r\n * \r\n * @param <TF>\r\n *            the generic type\r\n * @author amresh.singh\r\n */\r\npublic class DataRow<TF>\r\n{\r\n    /** Id of the row. */\r\n    private String id;\r\n\r\n    /** name of the family. */\r\n    private String columnFamilyName;\r\n\r\n    /** list of thrift columns from the row. */\r\n    private List<TF> columns;\r\n\r\n    /**\r\n     * default constructor.\r\n     */\r\n    public DataRow()\r\n    {\r\n        columns = new ArrayList<TF>();\r\n    }\r\n\r\n    /**\r\n     * The Constructor.\r\n     * \r\n     * @param id\r\n     *            the id\r\n     * @param columnFamilyName\r\n     *            the column family name\r\n     * @param columns\r\n     *            the columns\r\n     */\r\n    public DataRow(String id, String columnFamilyName, List<TF> columns)\r\n    {\r\n        this.id = id;\r\n        this.columnFamilyName = columnFamilyName;\r\n        this.columns = columns;\r\n    }\r\n\r\n    /**\r\n     * Gets the id.\r\n     * \r\n     * @return the id\r\n     */\r\n    public String getId()\r\n    {\r\n        return id;\r\n    }\r\n\r\n    /**\r\n     * Gets the column family name.\r\n     * \r\n     * @return the columnFamilyName\r\n     */\r\n    public String getColumnFamilyName()\r\n    {\r\n        return columnFamilyName;\r\n    }\r\n\r\n    /**\r\n     * Gets the columns.\r\n     * \r\n     * @return the columns\r\n     */\r\n    public List<TF> getColumns()\r\n    {\r\n        return columns;\r\n    }\r\n\r\n    /**\r\n     * Adds the column.;\r\n     * \r\n     * @param column\r\n     *            the column\r\n     */\r\n    public void addColumn(TF column)\r\n    {\r\n        columns.add(column);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/db/RelationHolder.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.db;\n\n/**\n * The Class RelationHolder.\n * \n * @author vivek.mishra\n */\npublic class RelationHolder\n{\n\n    /** The relation name. */\n    private String relationName;\n\n    /** The relation value. */\n    private Object relationValue;\n\n    /** Holds object through which this relation is maintained */\n    private Object relationVia;\n\n    /**\n     * Instantiates a new relation holder.\n     * \n     * @param relationName\n     *            the relation name\n     * @param relationValue\n     *            the relation value\n     */\n    public RelationHolder(String relationName, Object relationValue)\n    {\n        this.relationName = relationName;\n        this.relationValue = relationValue;\n    }\n\n    public RelationHolder(String relationName, Object relationValue, Object relationVia)\n    {\n        this.relationName = relationName;\n        this.relationValue = relationValue;\n        this.relationVia = relationVia;\n    }\n\n    /**\n     * Gets the relation name.\n     * \n     * @return the relationName\n     */\n    public String getRelationName()\n    {\n        return relationName;\n    }\n\n    /**\n     * Gets the relation value.\n     * \n     * @return the relationValue\n     */\n    public Object getRelationValue()\n    {\n        return relationValue;\n    }\n\n    /**\n     * @return the relationVia\n     */\n    public Object getRelationVia()\n    {\n        return relationVia;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/db/SearchResult.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.db;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Holds High level search result info from database records\n * \n * @author amresh\n * \n */\npublic class SearchResult\n{\n    private Object primaryKey;\n\n    private String embeddedColumnName;\n\n    private List<String> embeddedColumnValues;\n\n    /**\n     * @return the primaryKey\n     */\n    public Object getPrimaryKey()\n    {\n        return primaryKey;\n    }\n\n    /**\n     * @param primaryKey\n     *            the primaryKey to set\n     */\n    public void setPrimaryKey(Object primaryKey)\n    {\n        this.primaryKey = primaryKey;\n    }\n\n    /**\n     * @return the embeddedColumnName\n     */\n    public String getEmbeddedColumnName()\n    {\n        return embeddedColumnName;\n    }\n\n    /**\n     * @param embeddedColumnName\n     *            the embeddedColumnName to set\n     */\n    public void setEmbeddedColumnName(String embeddedColumnName)\n    {\n        this.embeddedColumnName = embeddedColumnName;\n    }\n\n    /**\n     * @return the embeddedColumnValues\n     */\n    public List<String> getEmbeddedColumnValues()\n    {\n        return embeddedColumnValues;\n    }\n\n    /**\n     * @param embeddedColumnValues\n     *            the embeddedColumnValues to set\n     */\n    public void addEmbeddedColumnValue(String embeddedColumnValue)\n    {\n        if (embeddedColumnValues == null)\n        {\n            embeddedColumnValues = new ArrayList<String>();\n        }\n        embeddedColumnValues.add(embeddedColumnValue);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/generator/AutoGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.generator;\n\nimport com.impetus.kundera.client.Client;\n\n/**\n * {@link AutoGenerator} interface , all client should implement this interface\n * in order to support auto generation strategy.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic interface AutoGenerator extends Generator\n{\n\n    /**\n     * Generate.\n     * \n     * @param client\n     *            the client\n     * @param dataType\n     *            the data type\n     * @return the object\n     */\n    public Object generate(Client<?> client, String dataType);\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/generator/Generator.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.generator;\n\n/**\n * Generator Interface implemented by all generator.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic interface Generator\n{\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/generator/IdentityGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.generator;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.metadata.model.SequenceGeneratorDiscriptor;\n\n/**\n * {@link IdentityGenerator} interface , all client should implement this\n * interface in order to support identity generation strategy.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic interface IdentityGenerator extends Generator\n{\n\n    /**\n     * Generate.\n     * \n     * @param discriptor\n     *            the discriptor\n     * @param client\n     *            the client\n     * @param dataType\n     *            the data type\n     * @return the object\n     */\n    public Object generate(SequenceGeneratorDiscriptor discriptor, Client<?> client, String dataType);\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/generator/SequenceGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.generator;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.metadata.model.SequenceGeneratorDiscriptor;\n\n/**\n * {@link SequenceGenerator} interface , all client should implement this\n * interface in order to support sequence generation strategy.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic interface SequenceGenerator extends Generator\n{\n\n    /**\n     * Generate.\n     * \n     * @param discriptor\n     *            the discriptor\n     * @param client\n     *            the client\n     * @param dataType\n     *            the data type\n     * @return the object\n     */\n    public Object generate(SequenceGeneratorDiscriptor discriptor, Client<?> client, String dataType);\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/generator/TableGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.generator;\n\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.metadata.model.TableGeneratorDiscriptor;\n\n/**\n * {@link TableGenerator} interface , all client should implement this interface\n * in order to support table generation strategy.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic interface TableGenerator extends Generator\n{\n\n    /**\n     * Generate.\n     * \n     * @param discriptor\n     *            the discriptor\n     * @param client\n     *            the client\n     * @param dataType\n     *            the data type\n     * @return the object\n     */\n    public Object generate(TableGeneratorDiscriptor discriptor, ClientBase client, String dataType);\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/gis/SurfaceType.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.gis;\n\n/**\n * @author amresh\n * \n */\npublic enum SurfaceType\n{\n    FLAT, SPHERICAL;\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/gis/geometry/Circle.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.gis.geometry;\n\nimport com.impetus.kundera.gis.SurfaceType;\n\n/**\n * Geometric class representing circle shape\n * \n * @author amresh.singh\n */\npublic class Circle\n{\n    private Coordinate centre;\n\n    private double radius;\n\n    /** Surface type on which this circle is based */\n    private SurfaceType surfaceType = SurfaceType.FLAT;\n\n    public Circle(double x, double y, double r)\n    {\n        setCentre(new Coordinate(x, y));\n        setRadius(r);\n    }\n\n    public Circle(Coordinate centre, double radius)\n    {\n        this.centre = centre;\n        this.radius = radius;\n    }\n\n    /**\n     * @return the centre\n     */\n    public Coordinate getCentre()\n    {\n        return centre;\n    }\n\n    /**\n     * @param centre\n     *            the centre to set\n     */\n    public void setCentre(Coordinate centre)\n    {\n        this.centre = centre;\n    }\n\n    /**\n     * @return the radius\n     */\n    public double getRadius()\n    {\n        return radius;\n    }\n\n    /**\n     * @param radius\n     *            the radius to set\n     */\n    public void setRadius(double radius)\n    {\n        this.radius = radius;\n    }\n\n    /**\n     * @return the surfaceType\n     */\n    public SurfaceType getSurfaceType()\n    {\n        return surfaceType;\n    }\n\n    /**\n     * @param surfaceType\n     *            the surfaceType to set\n     */\n    public void setSurfaceType(SurfaceType surfaceType)\n    {\n        this.surfaceType = surfaceType;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/gis/geometry/Coordinate.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.gis.geometry;\n\n/**\n * Geometric Coordinate implementation\n * \n * @author amresh.singh\n */\npublic class Coordinate extends com.vividsolutions.jts.geom.Coordinate\n{\n    /**\n     * \n     */\n    public Coordinate()\n    {\n        super();\n\n    }\n\n    /**\n     * @param c\n     */\n    public Coordinate(com.vividsolutions.jts.geom.Coordinate c)\n    {\n        super(c);\n\n    }\n\n    /**\n     * @param x\n     * @param y\n     * @param z\n     */\n    public Coordinate(double x, double y, double z)\n    {\n        super(x, y, z);\n\n    }\n\n    /**\n     * @param x\n     * @param y\n     */\n    public Coordinate(double x, double y)\n    {\n        super(x, y);\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/gis/geometry/Envelope.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.gis.geometry;\n\nimport com.vividsolutions.jts.geom.Coordinate;\n\n/**\n * Geometric Envelope (Box) implementation\n * \n * @author amresh.singh\n */\npublic class Envelope extends com.vividsolutions.jts.geom.Envelope\n{\n\n    /**\n     * \n     */\n    public Envelope()\n    {\n    }\n\n    /**\n     * @param p\n     */\n    public Envelope(Coordinate p)\n    {\n        super(p);\n\n    }\n\n    /**\n     * @param env\n     */\n    public Envelope(com.vividsolutions.jts.geom.Envelope env)\n    {\n        super(env);\n\n    }\n\n    /**\n     * @param p1\n     * @param p2\n     */\n    public Envelope(Coordinate p1, Coordinate p2)\n    {\n        super(p1, p2);\n\n    }\n\n    /**\n     * @param x1\n     * @param x2\n     * @param y1\n     * @param y2\n     */\n    public Envelope(double x1, double x2, double y1, double y2)\n    {\n        super(x1, x2, y1, y2);\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/gis/geometry/Point.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.gis.geometry;\n\nimport com.impetus.kundera.gis.SurfaceType;\nimport com.vividsolutions.jts.geom.Coordinate;\nimport com.vividsolutions.jts.geom.CoordinateSequence;\nimport com.vividsolutions.jts.geom.GeometryFactory;\nimport com.vividsolutions.jts.geom.PrecisionModel;\n\n/**\n * Geometric Point implementation\n * \n * @author amresh.singh\n */\npublic class Point extends com.vividsolutions.jts.geom.Point\n{\n    /** Surface type on which this point is based */\n    private SurfaceType surfaceType = SurfaceType.FLAT;\n\n    public Point(com.vividsolutions.jts.geom.Point point)\n    {\n        super(point.getCoordinate(), point.getPrecisionModel(), point.getSRID());\n    }\n\n    public Point(double x, double y)\n    {\n        super(new Coordinate(x, y), new PrecisionModel(), 0);\n    }\n\n    /**\n     * @param coordinates\n     * @param factory\n     */\n    public Point(CoordinateSequence coordinates, GeometryFactory factory)\n    {\n        super(coordinates, factory);\n    }\n\n    /**\n     * @param coordinate\n     * @param precisionModel\n     * @param SRID\n     * @deprecated\n     */\n    public Point(Coordinate coordinate, PrecisionModel precisionModel, int SRID)\n    {\n        super(coordinate, precisionModel, SRID);\n\n    }\n\n    /**\n     * @return the surfaceType\n     */\n    public SurfaceType getSurfaceType()\n    {\n        return surfaceType;\n    }\n\n    /**\n     * @param surfaceType\n     *            the surfaceType to set\n     */\n    public void setSurfaceType(SurfaceType surfaceType)\n    {\n        this.surfaceType = surfaceType;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/gis/geometry/Polygon.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.gis.geometry;\n\nimport com.vividsolutions.jts.geom.GeometryFactory;\nimport com.vividsolutions.jts.geom.LinearRing;\n\n/**\n * Geometric Polygon implementation\n * \n * @author amresh.singh\n */\npublic class Polygon extends com.vividsolutions.jts.geom.Polygon\n{\n\n    /**\n     * @param shell\n     * @param holes\n     * @param factory\n     */\n    public Polygon(LinearRing shell, LinearRing[] holes, GeometryFactory factory)\n    {\n        super(shell, holes, factory);\n    }\n\n    @Override\n    public Coordinate[] getCoordinates()\n    {\n        com.vividsolutions.jts.geom.Coordinate[] coordinates = super.getCoordinates();\n\n        Coordinate[] cs = new Coordinate[coordinates.length];\n\n        int count = 0;\n        for (com.vividsolutions.jts.geom.Coordinate c : coordinates)\n        {\n            cs[count++] = new Coordinate(c);\n        }\n\n        return cs;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/gis/geometry/Triangle.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.gis.geometry;\n\n/**\n * Geometric Triangle implementation\n * \n * @author amresh.singh\n */\npublic class Triangle extends com.vividsolutions.jts.geom.Triangle\n{\n\n    public Triangle(double x1, double y1, double x2, double y2, double x3, double y3)\n    {\n        super(new Coordinate(x1, y1), new Coordinate(x2, y2), new Coordinate(x3, y3));\n    }\n\n    /**\n     * @param p0\n     * @param p1\n     * @param p2\n     */\n    public Triangle(Coordinate p0, Coordinate p1, Coordinate p2)\n    {\n        super(p0, p1, p2);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/gis/query/GeospatialQuery.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.gis.query;\n\n/**\n * Provides methods related to Geospatial Queries\n * \n * @author amresh.singh\n */\npublic interface GeospatialQuery\n{\n    Object createGeospatialQuery(String geolocationColumnName, Object shape, Object query);\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/graph/GraphBuilder.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.graph;\n\nimport java.lang.reflect.Field;\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.MapKeyJoinColumn;\n\nimport org.apache.commons.lang.StringUtils;\n\nimport com.impetus.kundera.graph.NodeLink.LinkProperty;\nimport com.impetus.kundera.lifecycle.states.ManagedState;\nimport com.impetus.kundera.lifecycle.states.NodeState;\nimport com.impetus.kundera.lifecycle.states.TransientState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\nimport com.impetus.kundera.proxy.ProxyHelper;\nimport com.impetus.kundera.utils.DeepEquals;\n\n/**\n * Assign head node set relational node: 1. check for proxy 2. graph status of\n * node.\n * \n * @author vivek.mishra\n * \n */\npublic class GraphBuilder\n{\n    private ObjectGraph graph;\n\n    private GraphGenerator generator;\n\n    public GraphBuilder()\n    {\n        this.graph = new ObjectGraph();\n    }\n\n    /**\n     * Assign generator reference.\n     * \n     * @param generator\n     *            graph generator.\n     */\n    public void assign(GraphGenerator generator)\n    {\n        this.generator = generator;\n    }\n\n    /**\n     * On build node.\n     * \n     * @param entity\n     *            entity\n     * @param pc\n     *            persistence cache\n     * @param entityId\n     *            entity id\n     * @return added node.\n     */\n    public final Node buildNode(Object entity, PersistenceDelegator pd, Object entityId, NodeState nodeState)\n    {\n        String nodeId = ObjectGraphUtils.getNodeId(entityId, entity.getClass());\n\n        Node node = this.graph.getNode(nodeId);\n\n        // If this node is already there in graph (may happen for bidirectional\n        // relationship, do nothing and return null)\n        // return node in case has already been traversed.\n\n        if (node != null)\n        {\n            if (this.generator.traversedNodes.contains(node))\n            {\n                return node;\n            }\n\n            return null;\n        }\n\n        node = new NodeBuilder().assignState(nodeState).buildNode(entity, pd, entityId, nodeId).node;\n        this.graph.addNode(node.getNodeId(), node);\n        return node;\n\n    }\n\n    /**\n     * Assign head node to graph\n     * \n     * @param headNode\n     * @return graph builder instance.\n     */\n    public GraphBuilder assignHeadNode(final Node headNode)\n    {\n        this.graph.setHeadNode(headNode);\n        return this;\n    }\n\n    /**\n     * Returns relation builder instance.\n     * \n     * @param target\n     *            relational entity\n     * @param relation\n     *            relation\n     * @param source\n     *            relation originator entity\n     * @return relation builder instance.\n     */\n    RelationBuilder getRelationBuilder(Object target, Relation relation, Node source)\n    {\n        RelationBuilder relationBuilder = new RelationBuilder(target, relation, source);\n        relationBuilder.assignGraphGenerator(this.generator);\n        return relationBuilder;\n    }\n\n    /**\n     * Returns completed graph.\n     * \n     * @return object graph.\n     */\n    ObjectGraph getGraph()\n    {\n        return this.graph;\n    }\n\n    /**\n     * Inner class {Relation builder}\n     * \n     * @author vivek.mishra\n     * \n     */\n    class RelationBuilder\n    {\n        private GraphGenerator generator;\n\n        private Object target;\n\n        private Node source;\n\n        private EntityMetadata metadata;\n\n        private PersistenceDelegator pd;\n\n        private PersistenceCache pc;\n\n        private Relation relation;\n\n        private RelationBuilder(Object target, Relation relation, Node source)\n        {\n            this.target = target;\n            this.relation = relation;\n            this.source = source;\n        }\n\n        /**\n         * Assign graph generator\n         * \n         * @param generator\n         *            graph generator\n         * \n         * @return\n         */\n        private RelationBuilder assignGraphGenerator(GraphGenerator generator)\n        {\n            this.generator = generator;\n            return this;\n        }\n\n        /**\n         * Assign relation builder resources\n         * \n         * @param pd\n         *            persistence delegator\n         * @param pc\n         *            persistence cache\n         * @param metadata\n         *            entity meta data\n         * @return relation builder\n         */\n        RelationBuilder assignResources(final PersistenceDelegator pd, final PersistenceCache pc,\n                final EntityMetadata metadata)\n        {\n            this.pc = pc;\n            this.pd = pd;\n            this.metadata = metadata;\n            return this;\n        }\n\n        /**\n         * Build relation\n         * \n         * @return relation builder\n         */\n        RelationBuilder build()\n        {\n            if (!onNonUnaryRelation())\n            {\n                this.generator.onBuildChildNode(target, metadata, this.pd, pc, source, relation);\n            }\n\n            return this;\n        }\n\n        /**\n         * parse and process non unary relations {e.g. 1-M and M-M}\n         * \n         * @return true, if is a non unary relation and processed.\n         */\n        private boolean onNonUnaryRelation()\n        {\n            if (!relation.isUnary())\n            {\n                if (Collection.class.isAssignableFrom(target.getClass()))\n                {\n                    Collection childrenObjects = (Collection) target;\n\n                    for (Object childObj : childrenObjects)\n                    {\n                        if (childObj != null)\n                        {\n                            this.generator.onBuildChildNode(childObj, metadata, this.pd, pc, source, relation);\n                        }\n                    }\n\n                }\n                else if (Map.class.isAssignableFrom(target.getClass()))\n                {\n                    Map childrenObjects = (Map) target;\n                    if (childrenObjects != null && !ProxyHelper.isProxyCollection(childrenObjects))\n                    {\n                        for (Map.Entry entry : (Set<Map.Entry>) childrenObjects.entrySet())\n                        {\n                            Object relObject = entry.getKey();\n                            Object entityObject = entry.getValue();\n                            if (entityObject != null)\n                            {\n                                Node childNode = this.generator.generate(entityObject, pd, pc, null);\n                                // in case node is already in cache.\n                                if (childNode != null)\n                                {\n                                    if (StringUtils.isEmpty(relation.getMappedBy())\n                                            && relation.getProperty().getAnnotation(MapKeyJoinColumn.class) != null)\n                                    {\n                                        NodeLink nodeLink = new NodeLink(source.getNodeId(), childNode.getNodeId());\n                                        this.generator.setLink(source, relation, childNode, nodeLink);\n                                        nodeLink.addLinkProperty(LinkProperty.LINK_VALUE, relObject);\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n\n                return true;\n            }\n\n            return false;\n\n        }\n\n        /**\n         * Returns built node.\n         * \n         * @return node\n         */\n        Node getNode()\n        {\n            return this.source;\n        }\n    }\n\n    /**\n     * Inner class { Node builder }\n     * \n     * @author vivek.mishra\n     * \n     */\n    private class NodeBuilder\n    {\n        private Node node;\n\n        private NodeState state;\n\n        private NodeBuilder assignState(NodeState state)\n        {\n            this.state = state;\n            return this;\n        }\n\n        /**\n         * Build node. Check for: 1. Node state, whether in pc or not 2. Node\n         * dirty check\n         * \n         * @param entity\n         *            originating entity\n         * @param pc\n         *            persistence cache.\n         * @param entityId\n         *            entity id\n         * @param nodeId\n         *            node id.\n         * @return node builder instance.\n         */\n        private NodeBuilder buildNode(Object entity, PersistenceDelegator pd, Object entityId, String nodeId)\n        {\n\n            Node nodeInPersistenceCache = pd.getPersistenceCache().getMainCache().getNodeFromCache(nodeId, pd);\n\n            EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(pd.getKunderaMetadata(),\n                    entity.getClass());\n\n            // TODO: in case of composite key. it is a bit hack and should be\n            // handled better.\n            if (nodeInPersistenceCache == null)\n            {\n                this.state = state != null ? this.state : new TransientState();\n\n                node = new Node(\n                        nodeId,\n                        entity,\n                        ((Field) entityMetadata.getIdAttribute().getJavaMember()).isAnnotationPresent(EmbeddedId.class) ? new ManagedState()\n                                : this.state, pd.getPersistenceCache(), entityId, pd);\n            }\n            else\n            {\n                node = nodeInPersistenceCache;\n                node.setPersistenceCache(pd.getPersistenceCache());\n                node.setTraversed(false);\n            }\n\n            // Determine whether this node is dirty based on comparison between\n            // Node data and entity data\n            // If dirty, set the entity data into node and mark it as dirty\n            onDirtyCheck(entity, node);\n            node.setData(entity);\n\n            return this;\n        }\n\n        /**\n         * Check for dirty.\n         * \n         * @param entity\n         *            entity\n         * @param node\n         *            node.\n         */\n        private void onDirtyCheck(Object entity, Node node)\n        {\n            if (!node.isInState(TransientState.class))\n            {\n                if (!DeepEquals.deepEquals(node.getData(), entity))\n                {\n                    node.setDirty(true);\n                }\n                else if (node.isProcessed())\n                {\n                    node.setDirty(false);\n                }\n            }\n        }\n\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/graph/GraphGenerator.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.graph;\n\nimport java.lang.reflect.Field;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.GeneratedValue;\n\nimport com.impetus.kundera.graph.NodeLink.LinkProperty;\nimport com.impetus.kundera.lifecycle.states.NodeState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.IdGenerator;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.persistence.PersistenceValidator;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.proxy.ProxyHelper;\nimport com.impetus.kundera.validation.rules.NullOrInvalidEntityRule;\nimport com.impetus.kundera.validation.rules.PrimaryKeyNullCheck;\n\n/**\n * @author vivek.mishra\n * \n *         Responsible for:\n * \n *         1. Do pre-checks a) validation entity b) set id c) check for shared\n *         via primary key { on parse relation } d) dirty check { on associated\n *         and self entity }\n * \n *         2. Parse through relations and relational objects.\n * \n *         3. Recursively process transitive relations\n */\npublic final class GraphGenerator\n{\n\n    private GraphBuilder builder = new GraphBuilder();\n\n    Set<Node> traversedNodes = new HashSet<Node>();\n\n    private PersistenceValidator validator = new PersistenceValidator();\n\n    /**\n     * Generate entity graph and returns after assigning headnode. n\n     * \n     * @param entity\n     *            entity.\n     * @param delegator\n     *            delegator\n     * @param pc\n     *            persistence cache\n     * @return object graph.\n     */\n    public <E> ObjectGraph generateGraph(E entity, PersistenceDelegator delegator)\n    {\n        this.builder.assign(this);\n        Node node = generate(entity, delegator, delegator.getPersistenceCache(), null);\n        this.builder.assignHeadNode(node);\n        return this.builder.getGraph();\n    }\n\n    // TODO: Till the time issue populating all objects via cache is not yet\n    // solved.\n    // keep this method alive!\n\n    /**\n     * Generate entity graph and returns after assigning headnode. n\n     * \n     * @param entity\n     *            entity.\n     * @param delegator\n     *            delegator\n     * @param pc\n     *            persistence cache\n     * @return object graph.\n     */\n    public <E> ObjectGraph generateGraph(E entity, PersistenceDelegator delegator, NodeState state)\n    {\n\n        this.builder.assign(this);\n        Node node = generate(entity, delegator, delegator.getPersistenceCache(), state);\n        this.builder.assignHeadNode(node);\n        return this.builder.getGraph();\n    }\n\n    /**\n     * Generate graph for head node. <li>traverse through it's relational\n     * entities recursively\n     * \n     * @param entity\n     *            entity object\n     * @param delegator\n     *            delegator object\n     * @param pc\n     *            persistence cache\n     * @return head node\n     */\n    <E> Node generate(E entity, PersistenceDelegator delegator, PersistenceCache pc, NodeState state)\n    {\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),\n                entity.getClass());\n\n        if (!new NullOrInvalidEntityRule<E>(entityMetadata).validate(entity))\n        {\n            Object entityId = onPreChecks(entity, delegator);\n\n            // TODO::check for composite key.\n            Node node = builder.buildNode(entity, delegator, entityId, state);\n\n            node = traverseNode(entity, delegator, pc, entityId, node);\n\n            return node;\n        }\n\n        return null;\n    }\n\n    private <E> Node traverseNode(E entity, PersistenceDelegator delegator, PersistenceCache pc, Object entityId,\n            Node node)\n    {\n        if (node != null && !traversedNodes.contains(node))\n        {\n            EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),\n                    entity.getClass());\n\n            // parse relations\n\n            for (Relation relation : entityMetadata.getRelations())\n            {\n                if (relation != null)\n                {\n                    Object childObject = PropertyAccessorHelper.getObject(entity, relation.getProperty());\n\n                    // if child object is valid and not a proxy\n                    if (childObject != null && !ProxyHelper.isProxyOrCollection(childObject))\n                    {\n                        // check for join by primary key, collection and map\n                        EntityMetadata childMetadata = KunderaMetadataManager.getEntityMetadata(\n                                delegator.getKunderaMetadata(),\n                                PropertyAccessorHelper.getGenericClass(relation.getProperty()));\n\n                        // set id,in case joined by primary key.\n                        childObject = onIfSharedByPK(relation, childObject, childMetadata, entityId);\n\n                        node = builder.getRelationBuilder(childObject, relation, node)\n                                .assignResources(delegator, pc, childMetadata).build().getNode();\n                    }\n                }\n            }\n\n            // node.setGraphCompleted(true);\n            traversedNodes.add(node);\n        }\n        return node;\n    }\n\n    /**\n     * Check and set if relation is set via primary key.\n     * \n     * @param relation\n     *            relation\n     * @param childObject\n     *            target entity\n     * @param childMetadata\n     *            target entity metadata\n     * @param entityId\n     *            entity id\n     * @return target entity.\n     */\n    private Object onIfSharedByPK(Relation relation, Object childObject, EntityMetadata childMetadata, Object entityId)\n    {\n        if (relation.isJoinedByPrimaryKey())\n        {\n            PropertyAccessorHelper.setId(childObject, childMetadata, entityId);\n        }\n\n        return childObject;\n    }\n\n    /**\n     * On pre checks before generating graph. performed checks: <li>Check if\n     * entity is valid.</li> <li>generated and set id in case\n     * {@link GeneratedValue} is present and not set.</li> <li>Check if primary\n     * key is not null.</li>\n     * \n     * \n     * @param entity\n     *            entity\n     * @param client\n     *            client\n     * @return entity id\n     */\n    private <E> Object onPreChecks(E entity, PersistenceDelegator delegator)\n    {\n        // pre validation.\n        // check if entity is Null or with Invalid meta data!\n        Object id = null;\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),\n                entity.getClass());\n        id = PropertyAccessorHelper.getId(entity, entityMetadata);\n\n        // set id, in case of auto generation and still not set.\n\n        if (ObjectGraphUtils.onAutoGenerateId((Field) entityMetadata.getIdAttribute().getJavaMember(), id))\n        {\n            id = new IdGenerator().generateAndSetId(entity, entityMetadata, delegator, delegator.getKunderaMetadata());\n        }\n\n        // check if id is set or not.\n        new PrimaryKeyNullCheck<Object>().validate(id);\n\n        validator.validate(entity, delegator.getKunderaMetadata());\n\n        // }\n\n        return id;\n    }\n\n    /**\n     * On building child node\n     * \n     * @param childObject\n     *            child object\n     * @param childMetadata\n     *            child metadata\n     * @param delegator\n     *            persistence delegator\n     * @param pc\n     *            persistence cache\n     * @param node\n     *            node\n     * @param relation\n     *            entity relation\n     */\n    void onBuildChildNode(Object childObject, EntityMetadata childMetadata, PersistenceDelegator delegator,\n            PersistenceCache pc, Node node, Relation relation)\n    {\n        Node childNode = generate(childObject, delegator, pc, null);\n        if (childNode != null)\n        {\n            assignNodeLinkProperty(node, relation, childNode);\n        }\n    }\n\n    /**\n     * On assigning node link properties\n     * \n     * @param node\n     *            node\n     * @param relation\n     *            relation\n     * @param childNode\n     *            child node\n     */\n    private void assignNodeLinkProperty(Node node, Relation relation, Node childNode)\n    {\n        // Construct Node Link for this relationship\n        NodeLink nodeLink = new NodeLink(node.getNodeId(), childNode.getNodeId());\n        setLink(node, relation, childNode, nodeLink);\n    }\n\n    /**\n     * Set link property\n     * \n     * @param node\n     *            node\n     * @param relation\n     *            relation\n     * @param childNode\n     *            target node\n     * @param nodeLink\n     *            node link(bridge)\n     */\n    void setLink(Node node, Relation relation, Node childNode, NodeLink nodeLink)\n    {\n        nodeLink.setMultiplicity(relation.getType());\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(node.getPersistenceDelegator()\n                .getKunderaMetadata(), node.getDataClass());\n        nodeLink.setLinkProperties(getLinkProperties(metadata, relation, node.getPersistenceDelegator()\n                .getKunderaMetadata()));\n\n        // Add Parent node to this child\n        childNode.addParentNode(nodeLink, node);\n\n        // Add child node to this node\n        node.addChildNode(nodeLink, childNode);\n    }\n\n    /**\n     * \n     * @param metadata\n     *            Entity metadata of the parent node\n     * @param relation\n     * @return\n     */\n    private Map<LinkProperty, Object> getLinkProperties(EntityMetadata metadata, Relation relation,\n            final KunderaMetadata kunderaMetadata)\n    {\n        Map<LinkProperty, Object> linkProperties = new HashMap<NodeLink.LinkProperty, Object>();\n\n        linkProperties.put(LinkProperty.LINK_NAME, MetadataUtils.getMappedName(metadata, relation, kunderaMetadata));\n        linkProperties.put(LinkProperty.IS_SHARED_BY_PRIMARY_KEY, relation.isJoinedByPrimaryKey());\n        linkProperties.put(LinkProperty.IS_BIDIRECTIONAL, !relation.isUnary());\n        linkProperties.put(LinkProperty.IS_RELATED_VIA_JOIN_TABLE, relation.isRelatedViaJoinTable());\n        linkProperties.put(LinkProperty.PROPERTY, relation.getProperty());\n        linkProperties.put(LinkProperty.CASCADE, relation.getCascades());\n\n        if (relation.isRelatedViaJoinTable())\n        {\n            linkProperties.put(LinkProperty.JOIN_TABLE_METADATA, relation.getJoinTableMetadata());\n        }\n        return linkProperties;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/graph/Node.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.graph;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.PostLoad;\nimport javax.persistence.PostPersist;\nimport javax.persistence.PostRemove;\nimport javax.persistence.PostUpdate;\nimport javax.persistence.PrePersist;\nimport javax.persistence.PreRemove;\nimport javax.persistence.PreUpdate;\n\nimport org.apache.commons.lang.builder.HashCodeBuilder;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.graph.NodeLink.LinkProperty;\nimport com.impetus.kundera.lifecycle.NodeStateContext;\nimport com.impetus.kundera.lifecycle.states.NodeState;\nimport com.impetus.kundera.lifecycle.states.RemovedState;\nimport com.impetus.kundera.lifecycle.states.TransientState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.Relation.ForeignKey;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\nimport com.impetus.kundera.persistence.event.EntityEventDispatcher;\nimport com.impetus.kundera.utils.ObjectUtils;\n\n/**\n * Represents a node in object graph\n * \n * @author amresh.singh\n */\npublic class Node implements NodeStateContext\n{\n\n    // ID of a node into object graph\n    private String nodeId;\n\n    // Primary key of entity data contained in this node\n    private Object entityId;\n\n    // Actual node data\n    private Object data;\n\n    // Current node state as defined in state machine\n    private NodeState currentNodeState;\n\n    // Class of actual node data\n    private Class<?> dataClass;\n\n    // All parents of this node, Key is Node Link info and value is node itself\n    private Map<NodeLink, Node> parents;\n\n    // All children of this node, Key is Node Link info and value is node itself\n    private Map<NodeLink, Node> children;\n\n    // Whether this node has been traversed\n    private boolean traversed;\n\n    // Whether this node is dirty\n    private boolean dirty;\n\n    // Whether this node for update.\n    private boolean isUpdate;\n\n    /** Client for this node */\n    private Client client;\n\n    // Reference to Persistence cache where this node is stored\n    private PersistenceCache persistenceCache;\n\n    // Whether graph is completely traversed or not.\n    private boolean isGraphCompleted;\n\n    private PersistenceDelegator pd;\n\n    private Node originalNode;\n\n    private boolean isProcessed;\n\n    private EntityEventDispatcher eventDispatcher = new EntityEventDispatcher();\n\n    private Node(String nodeId, Object data, PersistenceCache pc, Object primaryKey, PersistenceDelegator pd)\n    {\n        initializeNode(nodeId, data, primaryKey, pd);\n        setPersistenceCache(pc);\n\n        // Initialize current node state to transient state\n        this.currentNodeState = new TransientState();\n    }\n\n    Node(String nodeId, Object data, NodeState initialNodeState, PersistenceCache pc, Object primaryKey, PersistenceDelegator pd)\n    {\n        initializeNode(nodeId, data, primaryKey, pd);\n        setPersistenceCache(pc);\n\n        // Initialize current node state\n        if (initialNodeState == null)\n        {\n            this.currentNodeState = new TransientState();\n        }\n        else\n        {\n            this.currentNodeState = initialNodeState;\n        }\n    }\n\n    public Node(String nodeId, Class<?> nodeDataClass, NodeState initialNodeState, PersistenceCache pc,\n            Object primaryKey, PersistenceDelegator pd)\n    {\n        this.nodeId = nodeId;\n        this.dataClass = nodeDataClass;\n        this.entityId = primaryKey;\n        this.pd = pd;\n        setPersistenceCache(pc);\n\n        // Initialize current node state\n        if (initialNodeState == null)\n        {\n            this.currentNodeState = new TransientState();\n        }\n        else\n        {\n            this.currentNodeState = initialNodeState;\n        }\n    }\n\n    private void initializeNode(String nodeId, Object data, Object primaryKey, PersistenceDelegator pd)\n    {\n        this.pd = pd;\n        this.nodeId = nodeId;\n        this.data = data;\n        this.dataClass = data != null ? data.getClass() : null;\n        this.dirty = true;\n        this.entityId = primaryKey;\n    }\n\n    /**\n     * @return the nodeId\n     */\n    @Override\n    public String getNodeId()\n    {\n        return nodeId;\n    }\n\n    /**\n     * @param nodeId\n     *            the nodeId to set\n     */\n    @Override\n    public void setNodeId(String nodeId)\n    {\n        this.nodeId = nodeId;\n    }\n\n    /**\n     * @return the data\n     */\n    @Override\n    public Object getData()\n    {\n        return data;\n    }\n\n    /**\n     * @param data\n     *            the data to set\n     */\n    @Override\n    public void setData(Object data)\n    {\n        this.data = data;\n    }\n\n    /**\n     * @return the dataClass\n     */\n    @Override\n    public Class getDataClass()\n    {\n        return dataClass;\n    }\n\n    /**\n     * @param dataClass\n     *            the dataClass to set\n     */\n    @Override\n    public void setDataClass(Class dataClass)\n    {\n        this.dataClass = dataClass;\n    }\n\n    /**\n     * @return the currentNodeState\n     */\n    @Override\n    public NodeState getCurrentNodeState()\n    {\n        return currentNodeState;\n    }\n\n    /**\n     * @param currentNodeState\n     *            the currentNodeState to set\n     */\n    @Override\n    public void setCurrentNodeState(NodeState currentNodeState)\n    {\n        this.currentNodeState = currentNodeState;\n    }\n\n    /**\n     * @return the parents\n     */\n    @Override\n    public Map<NodeLink, Node> getParents()\n    {\n        return parents;\n    }\n\n    /**\n     * @param parents\n     *            the parents to set\n     */\n    @Override\n    public void setParents(Map<NodeLink, Node> parents)\n    {\n        this.parents = parents;\n    }\n\n    /**\n     * @return the children\n     */\n    @Override\n    public Map<NodeLink, Node> getChildren()\n    {\n        return children;\n    }\n\n    /**\n     * @param children\n     *            the children to set\n     */\n    @Override\n    public void setChildren(Map<NodeLink, Node> children)\n    {\n        this.children = children;\n    }\n\n    /**\n     * @return the isHeadNode\n     */\n    public boolean isHeadNode()\n    {\n        return this != null && this.parents == null ? true : false;\n    }\n\n    /**\n     * Retrieves parent node of this node for a given parent node ID\n     */\n    @Override\n    public Node getParentNode(String parentNodeId)\n    {\n        NodeLink link = new NodeLink(parentNodeId, getNodeId());\n\n        if (this.parents == null)\n        {\n            return null;\n        }\n        else\n        {\n            return this.parents.get(link);\n        }\n    }\n\n    /**\n     * Retrieves child node of this node for a given child node ID\n     */\n\n    @Override\n    public Node getChildNode(String childNodeId)\n    {\n        NodeLink link = new NodeLink(getNodeId(), childNodeId);\n\n        if (this.children == null)\n        {\n            return null;\n        }\n        else\n        {\n            return this.children.get(link);\n        }\n    }\n\n    @Override\n    public void addParentNode(NodeLink nodeLink, Node node)\n    {\n        if (parents == null || parents.isEmpty())\n        {\n            parents = new HashMap<NodeLink, Node>();\n        }\n        parents.put(nodeLink, node);\n    }\n\n    @Override\n    public void addChildNode(NodeLink nodeLink, Node node)\n    {\n        if (children == null || children.isEmpty())\n        {\n            children = new HashMap<NodeLink, Node>();\n        }\n        children.put(nodeLink, node);\n    }\n\n    /**\n     * @return the traversed\n     */\n    @Override\n    public boolean isTraversed()\n    {\n        return traversed;\n    }\n\n    /**\n     * @param traversed\n     *            the traversed to set\n     */\n    @Override\n    public void setTraversed(boolean traversed)\n    {\n        this.traversed = traversed;\n    }\n\n    /**\n     * @return the dirty\n     */\n    @Override\n    public boolean isDirty()\n    {\n        return dirty;\n    }\n\n    /**\n     * @param dirty\n     *            the dirty to set\n     */\n    @Override\n    public void setDirty(boolean dirty)\n    {\n        this.dirty = dirty;\n    }\n\n    /**\n     * @return the client\n     */\n    @Override\n    public Client getClient()\n    {\n        return client;\n    }\n\n    /**\n     * @param client\n     *            the client to set\n     */\n\n    @Override\n    public void setClient(Client client)\n    {\n        this.client = client;\n    }\n\n    @Override\n    public PersistenceDelegator getPersistenceDelegator()\n    {\n        return pd;\n    }\n\n    @Override\n    public void setPersistenceDelegator(PersistenceDelegator pd)\n    {\n        this.pd = pd;\n        setPersistenceCache(pd.getPersistenceCache());\n    }\n\n    @Override\n    public String toString()\n    {\n        return \"[\" + nodeId + \"]\" + nodeId;\n    }\n\n    @Override\n    public boolean equals(Object otherNode)\n    {\n        if (otherNode == null)\n        {\n            return false;\n        }\n\n        if (!(otherNode instanceof Node))\n        {\n            return false;\n        }\n\n        return this.nodeId.equals(((Node) otherNode).getNodeId());\n    }\n\n    @Override\n    public int hashCode()\n    {\n        return HashCodeBuilder.reflectionHashCode(this.nodeId);\n    }\n\n    // ////////////////////////////////////////\n    /* CRUD related operations on this node */\n    // ////////////////////////////////////////\n\n    @Override\n    public void persist()\n    {\n        getCurrentNodeState().handlePersist(this);\n    }\n\n    @Override\n    public void remove()\n    {\n        getCurrentNodeState().handleRemove(this);\n    }\n\n    @Override\n    public void refresh()\n    {\n        getCurrentNodeState().handleRefresh(this);\n\n        // Fix for handling PostLoad event on refresh.\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(pd.getKunderaMetadata(), this.getDataClass());\n        onPostEvent(metadata, EntityEvent.FIND);\n\n    }\n\n    @Override\n    public void merge()\n    {\n        getCurrentNodeState().handleMerge(this);\n    }\n\n    @Override\n    public void detach()\n    {\n        getCurrentNodeState().handleDetach(this);\n    }\n\n    @Override\n    public void close()\n    {\n        getCurrentNodeState().handleClose(this);\n    }\n\n    @Override\n    public void lock()\n    {\n        getCurrentNodeState().handleLock(this);\n    }\n\n    @Override\n    public void commit()\n    {\n        getCurrentNodeState().handleCommit(this);\n    }\n\n    @Override\n    public void rollback()\n    {\n        getCurrentNodeState().handleRollback(this);\n    }\n\n    @Override\n    public void find()\n    {\n        getCurrentNodeState().handleFind(this);\n\n        // Fix for handling PostLoad event on find.\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(pd.getKunderaMetadata(), this.getDataClass());\n        onPostEvent(metadata, EntityEvent.FIND);\n    }\n\n    @Override\n    public void getReference()\n    {\n        getCurrentNodeState().handleGetReference(this);\n    }\n\n    @Override\n    public void contains()\n    {\n        getCurrentNodeState().handleContains(this);\n    }\n\n    @Override\n    public void clear()\n    {\n        getCurrentNodeState().handleClear(this);\n    }\n\n    @Override\n    public void flush()\n    {\n        if (isDirty())\n        {\n            handlePreEvent();\n            getCurrentNodeState().handleFlush(this);\n            handlePostEvent();\n            this.isProcessed = true;\n        }\n\n        // Update Link value for all nodes attached to this one\n        Map<NodeLink, Node> parents = this.getParents();\n        Map<NodeLink, Node> children = this.getChildren();\n\n        // update links.\n        if (parents != null && !parents.isEmpty())\n        {\n            for (NodeLink parentNodeLink : parents.keySet())\n            {\n                if (!parentNodeLink.getMultiplicity().equals(ForeignKey.MANY_TO_MANY))\n                    parentNodeLink.addLinkProperty(LinkProperty.LINK_VALUE, this.getEntityId());   \n            }\n        }\n\n        if (children != null && !children.isEmpty())\n        {\n            for (NodeLink childNodeLink : children.keySet())\n            {\n                if (!childNodeLink.getMultiplicity().equals(ForeignKey.MANY_TO_MANY))\n                    childNodeLink.addLinkProperty(LinkProperty.LINK_VALUE, this.getEntityId());\n            }\n        }\n    }\n\n    // Overridden methods from\n\n    @Override\n    public boolean isInState(Class<?> stateClass)\n    {\n        return getCurrentNodeState().getClass().equals(stateClass);\n    }\n\n    @Override\n    public PersistenceCache getPersistenceCache()\n    {\n        return this.persistenceCache;\n    }\n\n    @Override\n    public void setPersistenceCache(PersistenceCache persistenceCache)\n    {\n        this.persistenceCache = persistenceCache;\n    }\n\n    /**\n     * @return the isGraphCompleted\n     */\n    boolean isGraphCompleted()\n    {\n        return isGraphCompleted;\n    }\n\n    /**\n     * @param isGraphCompleted\n     *            the isGraphCompleted to set\n     */\n    void setGraphCompleted(boolean isGraphCompleted)\n    {\n        this.isGraphCompleted = isGraphCompleted;\n    }\n\n    /**\n     * @return the originalNode\n     */\n    public Node getOriginalNode()\n    {\n        return originalNode;\n    }\n\n    /**\n     * @param originalNode\n     *            the originalNode to set\n     */\n    public void setOriginalNode(Node originalNode)\n    {\n        this.originalNode = originalNode;\n    }\n\n    /**\n     * @return the isProcessed\n     */\n    public boolean isProcessed()\n    {\n        return isProcessed;\n    }\n\n    /**\n     * @return the isUpdate\n     */\n    public boolean isUpdate()\n    {\n        return isUpdate;\n    }\n\n    /**\n     * @param isUpdate\n     *            the isUpdate to set\n     */\n    public void setUpdate(boolean isUpdate)\n    {\n        this.isUpdate = isUpdate;\n    }\n\n    @Override\n    public Node clone()\n    {\n        Node cloneCopy = new Node(this.nodeId, ObjectUtils.deepCopy(this.getData(), pd.getKunderaMetadata()), this.persistenceCache,\n                this.entityId, this.pd);\n        cloneCopy.setChildren(this.children);\n        cloneCopy.setParents(this.parents);\n        cloneCopy.setDataClass(this.dataClass);\n        cloneCopy.setTraversed(this.traversed);\n\n        return cloneCopy;\n    }\n\n    @Override\n    public Object getEntityId()\n    {\n        return this.entityId;\n    }\n\n    public void setEntityId(Object id)\n    {\n        this.entityId = id;\n    }\n\n    public void handlePreEvent()\n    {\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(pd.getKunderaMetadata(), this.getDataClass());\n\n        if (isUpdate)\n        {\n            onPreEvent(metadata, EntityEvent.UPDATE);\n        }\n        else if (this.isInState(RemovedState.class))\n        {\n            onPreEvent(metadata, EntityEvent.REMOVE);\n        }\n        else\n        {\n            onPreEvent(metadata, EntityEvent.PERSIST);\n        }\n    }\n\n    public void handlePostEvent()\n    {\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(pd.getKunderaMetadata(), this.getDataClass());\n\n        if (isUpdate)\n        {\n            onPostEvent(metadata, EntityEvent.UPDATE);\n        }\n        else if (this.isInState(RemovedState.class))\n        {\n            onPostEvent(metadata, EntityEvent.REMOVE);\n        }\n        else\n        {\n            onPostEvent(metadata, EntityEvent.PERSIST);\n        }\n    }\n\n    private void onPreEvent(EntityMetadata metadata, EntityEvent event)\n    {\n        try\n        {\n            this.eventDispatcher.fireEventListeners(metadata, this.data, EntityEvent.getPreEvent(event));\n        }\n        catch (Exception es)\n        {\n            throw new KunderaException(es);\n        }\n    }\n\n    private void onPostEvent(EntityMetadata metadata, EntityEvent event)\n    {\n        try\n        {\n            this.eventDispatcher.fireEventListeners(metadata, this.data, EntityEvent.getPostEvent(event));\n        }\n        catch (Exception es)\n        {\n            throw new KunderaException(es);\n        }\n    }\n\n    private enum EntityEvent\n    {\n        UPDATE, PERSIST, REMOVE,FIND;\n\n        private final static Class getPreEvent(EntityEvent event)\n        {\n            Class clazz = null;\n            switch (event)\n            {\n            case PERSIST:\n                clazz = PrePersist.class;\n                break;\n\n            case UPDATE:\n                clazz = PreUpdate.class;\n                break;\n\n            case REMOVE:\n                clazz = PreRemove.class;\n                break;\n\n            default:\n                // TODO: Throw an error.\n            }\n            return clazz;\n        }\n\n        private final static Class getPostEvent(EntityEvent event)\n        {\n            Class clazz = null;\n            switch (event)\n            {\n            case PERSIST:\n                clazz = PostPersist.class;\n                break;\n\n            case UPDATE:\n                clazz = PostUpdate.class;\n                break;\n\n            case REMOVE:\n                clazz = PostRemove.class;\n                break;\n\n            case FIND:\n                clazz = PostLoad.class;\n                break;\n                \n            default:\n                // TODO: Throw an error.\n            }\n            return clazz;\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/graph/NodeLink.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.graph;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.commons.lang.builder.EqualsBuilder;\n\nimport com.impetus.kundera.metadata.model.Relation;\n\n/**\n * Holds link meta data for a unidirectional directed link from source node to\n * target node.\n * \n * @author amresh.singh\n */\npublic class NodeLink\n{\n    // All possible node link properties\n    public enum LinkProperty\n    {\n        LINK_NAME, LINK_VALUE, IS_SHARED_BY_PRIMARY_KEY, IS_BIDIRECTIONAL, IS_RELATED_VIA_JOIN_TABLE, PROPERTY, BIDIRECTIONAL_PROPERTY, CASCADE, JOIN_TABLE_METADATA\n        // Add more if required\n    };\n\n    private String sourceNodeId;\n\n    private String targetNodeId;\n\n    // Multiplicity of relationship\n    private Relation.ForeignKey multiplicity;\n\n    // Contains all properties for this link\n    private Map<LinkProperty, Object> linkProperties;\n\n    public NodeLink()\n    {\n\n    }\n\n    public NodeLink(String sourceNodeId, String targetNodeId)\n    {\n        this.sourceNodeId = sourceNodeId;\n        this.targetNodeId = targetNodeId;\n    }\n\n    /**\n     * @return the sourceNodeId\n     */\n    public String getSourceNodeId()\n    {\n        return sourceNodeId;\n    }\n\n    /**\n     * @param sourceNodeId\n     *            the sourceNodeId to set\n     */\n    public void setSourceNodeId(String sourceNodeId)\n    {\n        this.sourceNodeId = sourceNodeId;\n    }\n\n    /**\n     * @return the targetNodeId\n     */\n    public String getTargetNodeId()\n    {\n        return targetNodeId;\n    }\n\n    /**\n     * @param targetNodeId\n     *            the targetNodeId to set\n     */\n    public void setTargetNodeId(String targetNodeId)\n    {\n        this.targetNodeId = targetNodeId;\n    }\n\n    /**\n     * @return the multiplicity\n     */\n    public Relation.ForeignKey getMultiplicity()\n    {\n        return multiplicity;\n    }\n\n    /**\n     * @param multiplicity\n     *            the multiplicity to set\n     */\n    public void setMultiplicity(Relation.ForeignKey multiplicity)\n    {\n        this.multiplicity = multiplicity;\n    }\n\n    /**\n     * @return the linkProperties\n     */\n    public Map<LinkProperty, Object> getLinkProperties()\n    {\n        return linkProperties;\n    }\n\n    /**\n     * @param linkProperties\n     *            the linkProperties to set\n     */\n    public void setLinkProperties(Map<LinkProperty, Object> linkProperties)\n    {\n        this.linkProperties = linkProperties;\n    }\n\n    /**\n     * @return the linkProperties\n     */\n    public Object getLinkProperty(LinkProperty name)\n    {\n        if (linkProperties == null || linkProperties.isEmpty())\n        {\n            throw new IllegalStateException(\"Link properties not initialized\");\n        }\n\n        return linkProperties.get(name);\n    }\n\n    public void addLinkProperty(LinkProperty name, Object propertyValue)\n    {\n        if (linkProperties == null)\n        {\n            linkProperties = new HashMap<NodeLink.LinkProperty, Object>();\n        }\n\n        linkProperties.put(name, propertyValue);\n    }\n\n    @Override\n    public int hashCode()\n    {\n        int n = getSourceNodeId().hashCode() * getTargetNodeId().hashCode();\n        return n;\n\n        // return new\n        // HashCodeBuilder().append(getSourceNodeId()).append(getTargetNodeId()).hashCode();\n    }\n\n    @Override\n    public boolean equals(Object obj)\n    {\n        if (this == obj)\n        {\n            return true;\n        }\n\n        if (!(obj instanceof NodeLink))\n        {\n            return false;\n        }\n\n        NodeLink targetNodeLink = (NodeLink) obj;\n\n        return new EqualsBuilder().append(getSourceNodeId(), targetNodeLink.getSourceNodeId())\n                .append(getTargetNodeId(), targetNodeLink.getTargetNodeId()).isEquals();\n        // return getSourceNodeId().equals(targetNodeLink.getSourceNodeId())\n        // && getTargetNodeId().equals(targetNodeLink.getTargetNodeId());\n    }\n\n    @Override\n    public String toString()\n    {\n        return sourceNodeId + \"---(\" + multiplicity + \")--->\" + targetNodeId;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/graph/ObjectGraph.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.graph;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Holds graph of an object\n * \n * @author amresh.singh\n */\npublic class ObjectGraph\n{\n    // Head node in this object graph\n    private Node headNode;\n\n    // Mapping between Node ID and Node itself\n    // Each node contains link to parent/ child nodes it is related to\n    private Map<String, Node> nodeMapping;\n\n    ObjectGraph()\n    {\n        clear();\n        nodeMapping = new HashMap<String, Node>();\n    }\n\n    /**\n     * Adds a {@link Node} with a give nodeId to object graph.\n     * \n     * @param nodeId\n     * @param node\n     */\n    public void addNode(String nodeId, Node node)\n    {\n        nodeMapping.put(nodeId, node);\n    }\n\n    /**\n     * Returns Node for a given node ID\n     * \n     * @param nodeId\n     * @return\n     */\n    Node getNode(String nodeId)\n    {\n        return nodeMapping.get(nodeId);\n    }\n\n    /**\n     * @return the headNode\n     */\n    public Node getHeadNode()\n    {\n        return headNode;\n    }\n\n    /**\n     * @param headNode\n     *            the headNode to set\n     */\n    void setHeadNode(Node headNode)\n    {\n        this.headNode = headNode;\n    }\n\n    /**\n     * @return the nodeMapping\n     */\n    public Map<String, Node> getNodeMapping()\n    {\n        return nodeMapping;\n    }\n\n    public void clear()\n    {\n        if (nodeMapping != null)\n        {\n            nodeMapping.clear();\n            nodeMapping = null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/graph/ObjectGraphBuilder.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.graph;\n\nimport java.lang.reflect.Field;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.MapKeyJoinColumn;\n\nimport org.apache.commons.lang.StringUtils;\n\nimport com.impetus.kundera.graph.NodeLink.LinkProperty;\nimport com.impetus.kundera.lifecycle.states.NodeState;\nimport com.impetus.kundera.lifecycle.states.TransientState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.persistence.IdGenerator;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.persistence.PersistenceValidator;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.proxy.KunderaProxy;\nimport com.impetus.kundera.proxy.ProxyHelper;\nimport com.impetus.kundera.proxy.collection.ProxyCollection;\nimport com.impetus.kundera.utils.DeepEquals;\n\n/**\n * Responsible for generating {@link ObjectGraph} of nodes from a given entity\n * \n * @author amresh.singh\n */\npublic class ObjectGraphBuilder\n{\n    private PersistenceCache persistenceCache;\n\n    private PersistenceDelegator pd;\n\n    private IdGenerator idGenerator;\n\n    private PersistenceValidator validator;\n\n    public ObjectGraphBuilder(PersistenceCache pcCache, PersistenceDelegator pd)\n    {\n        this.persistenceCache = pcCache;\n        this.pd = pd;\n        this.idGenerator = new IdGenerator();\n        this.validator = new PersistenceValidator();\n    }\n\n    public ObjectGraph getObjectGraph(Object entity, NodeState initialNodeState)\n    {\n        // Initialize object graph\n        ObjectGraph objectGraph = new ObjectGraph();\n\n        // Recursively build object graph and get head node.\n        Node headNode = getNode(entity, objectGraph, initialNodeState);\n\n        // Set head node into object graph\n        if (headNode != null)\n        {\n            objectGraph.setHeadNode(headNode);\n        }\n        return objectGraph;\n    }\n\n    /**\n     * Constructs and returns {@link Node} representation for a given entity\n     * object. Output is fully constructed graph with relationships embedded.\n     * Each node is put into <code>graph</code> once it is constructed.\n     * \n     * @param entity\n     * @return\n     */\n    private Node getNode(Object entity, ObjectGraph graph, NodeState initialNodeState)\n    {\n        if (entity == null)\n        {\n            return null;\n        }\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(pd.getKunderaMetadata(),\n                entity.getClass());\n\n        // entity metadata could be null.\n        if (entityMetadata == null)\n        {\n            throw new IllegalArgumentException(\n                    \"Entity object is invalid, operation failed. Please check previous log message for details\");\n        }\n\n        Object id = PropertyAccessorHelper.getId(entity, entityMetadata);\n        // Generate and set Id if @GeneratedValue present.\n        if (((Field) entityMetadata.getIdAttribute().getJavaMember()).isAnnotationPresent(GeneratedValue.class))\n        {\n            if (!isIdSet(id))\n            {\n                id = idGenerator.generateAndSetId(entity, entityMetadata, pd, pd.getKunderaMetadata());\n            }\n        }\n\n        if (!validator.isValidEntityObject(entity, entityMetadata))\n        {\n            throw new IllegalArgumentException(\n                    \"Entity object is invalid, operation failed. Please check previous log message for details\");\n        }\n\n        // id = PropertyAccessorHelper.getId(entity, entityMetadata);\n\n        String nodeId = ObjectGraphUtils.getNodeId(id, entity.getClass());\n        Node node = graph.getNode(nodeId);\n\n        // If this node is already there in graph (may happen for bidirectional\n        // relationship, do nothing and return null)\n        if (node != null)\n        {\n            if (node.isGraphCompleted())\n            {\n                return node;\n            }\n            return null;\n        }\n\n        // Construct this Node first, if one not already there in Persistence\n        // Cache\n        Node nodeInPersistenceCache = persistenceCache.getMainCache().getNodeFromCache(nodeId, pd);\n\n        // Make a deep copy of entity data\n\n        if (nodeInPersistenceCache == null)\n        {\n            node = new Node(nodeId, entity, initialNodeState, persistenceCache, id, pd);\n        }\n        else\n        {\n            node = nodeInPersistenceCache;\n            node.setPersistenceCache(persistenceCache);\n\n            // Determine whether this node is dirty based on comparison between\n            // Node data and entity data\n            // If dirty, set the entity data into node and mark it as dirty\n            if (!DeepEquals.deepEquals(node.getData(), entity))\n            {\n                node.setDirty(true);\n            }\n            else if (node.isProcessed())\n            {\n                node.setDirty(false);\n            }\n\n            node.setData(entity);\n\n            // If node is NOT in managed state, its data needs to be\n            // replaced with the one provided in entity object\n        }\n\n        // Put this node into object graph\n        graph.addNode(nodeId, node);\n\n        // Iterate over relations and construct children nodes\n        for (Relation relation : entityMetadata.getRelations())\n        {\n            if (relation != null)\n            {\n                // Child Object set in this entity\n                Object childObject = PropertyAccessorHelper.getObject(entity, relation.getProperty());\n\n                if (childObject != null && !ProxyHelper.isProxy(childObject))\n                {\n                    EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(pd.getKunderaMetadata(),\n                            PropertyAccessorHelper.getGenericClass(relation.getProperty()));\n\n                    if (metadata != null && relation.isJoinedByPrimaryKey())\n                    {\n                        PropertyAccessorHelper.setId(childObject, metadata,\n                                PropertyAccessorHelper.getId(entity, entityMetadata));\n                    }\n                    // This child object could be either an entity(1-1 or M-1)\n                    // or a\n                    // collection/ Map of entities(1-M or M-M)\n                    if (Collection.class.isAssignableFrom(childObject.getClass()))\n                    {\n                        // For each entity in the collection, construct a child\n                        // node and add to graph\n                        Collection childrenObjects = (Collection) childObject;\n\n                        if (childrenObjects != null && !ProxyHelper.isProxyCollection(childrenObjects))\n\n                            for (Object childObj : childrenObjects)\n                            {\n                                if (childObj != null)\n                                {\n                                    addChildNodesToGraph(graph, node, relation, childObj,\n                                            metadata != null ? getChildNodeState(metadata, childObj) : initialNodeState);\n                                }\n                            }\n                    }\n                    else if (Map.class.isAssignableFrom(childObject.getClass()))\n                    {\n                        Map childrenObjects = (Map) childObject;\n                        if (childrenObjects != null && !ProxyHelper.isProxyCollection(childrenObjects))\n                        {\n                            for (Map.Entry entry : (Set<Map.Entry>) childrenObjects.entrySet())\n                            {\n                                addChildNodesToGraph(graph, node, relation, entry,\n                                        metadata != null ? getChildNodeState(metadata, entry) : initialNodeState);\n                            }\n                        }\n                    }\n                    else\n                    {\n                        // Construct child node and add to graph\n                        addChildNodesToGraph(graph, node, relation, childObject,\n                                metadata != null ? getChildNodeState(metadata, childObject) : initialNodeState);\n                    }\n                }\n            }\n        }\n\n        // Means compelte graph is build.\n        node.setGraphCompleted(true);\n        return node;\n    }\n\n    private NodeState getChildNodeState(EntityMetadata metadata, Object childObj)\n    {\n        Object childId = PropertyAccessorHelper.getId(childObj, metadata);\n        String childNodeId = ObjectGraphUtils.getNodeId(childId, childObj.getClass());\n\n        Node childNodeInCache = persistenceCache.getMainCache().getNodeFromCache(childNodeId, pd);\n\n        return childNodeInCache != null ? childNodeInCache.getCurrentNodeState() : new TransientState();\n    }\n\n    /**\n     * @param graph\n     * @param node\n     * @param relation\n     * @param childObject\n     */\n    private void addChildNodesToGraph(ObjectGraph graph, Node node, Relation relation, Object childObject,\n            NodeState initialNodeState)\n    {\n        if (childObject instanceof KunderaProxy || childObject instanceof ProxyCollection)\n        {\n            return;\n        }\n\n        else if (childObject instanceof Map.Entry)\n        {\n            Map.Entry entry = (Map.Entry) childObject;\n            Object relObject = entry.getKey();\n            Object entityObject = entry.getValue();\n\n            Node childNode = getNode(entityObject, graph, initialNodeState);\n\n            if (childNode != null)\n            {\n                if (!StringUtils.isEmpty(relation.getMappedBy())\n                        && relation.getProperty().getAnnotation(MapKeyJoinColumn.class) == null)\n                {\n                    return;\n                }\n\n                NodeLink nodeLink = new NodeLink(node.getNodeId(), childNode.getNodeId());\n                nodeLink.setMultiplicity(relation.getType());\n\n                EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(pd.getKunderaMetadata(),\n                        node.getDataClass());\n                nodeLink.setLinkProperties(getLinkProperties(metadata, relation));\n\n                nodeLink.addLinkProperty(LinkProperty.LINK_VALUE, relObject);\n\n                // Add Parent node to this child\n                childNode.addParentNode(nodeLink, node);\n\n                // Add child node to this node\n                node.addChildNode(nodeLink, childNode);\n            }\n        }\n        else\n        {\n            // Construct child node for this child object via recursive call\n            Node childNode = getNode(childObject, graph, initialNodeState);\n\n            if (childNode != null)\n            {\n                // Construct Node Link for this relationship\n                NodeLink nodeLink = new NodeLink(node.getNodeId(), childNode.getNodeId());\n                nodeLink.setMultiplicity(relation.getType());\n\n                EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(pd.getKunderaMetadata(),\n                        node.getDataClass());\n                nodeLink.setLinkProperties(getLinkProperties(metadata, relation));\n\n                // Add Parent node to this child\n                childNode.addParentNode(nodeLink, node);\n\n                // Add child node to this node\n                node.addChildNode(nodeLink, childNode);\n            }\n        }\n    }\n\n    /**\n     * \n     * @param metadata\n     *            Entity metadata of the parent node\n     * @param relation\n     * @return\n     */\n    private Map<LinkProperty, Object> getLinkProperties(EntityMetadata metadata, Relation relation)\n    {\n        Map<LinkProperty, Object> linkProperties = new HashMap<NodeLink.LinkProperty, Object>();\n\n        linkProperties.put(LinkProperty.LINK_NAME,\n                MetadataUtils.getMappedName(metadata, relation, pd.getKunderaMetadata()));\n        linkProperties.put(LinkProperty.IS_SHARED_BY_PRIMARY_KEY, relation.isJoinedByPrimaryKey());\n        linkProperties.put(LinkProperty.IS_BIDIRECTIONAL, !relation.isUnary());\n        linkProperties.put(LinkProperty.IS_RELATED_VIA_JOIN_TABLE, relation.isRelatedViaJoinTable());\n        linkProperties.put(LinkProperty.PROPERTY, relation.getProperty());\n        linkProperties.put(LinkProperty.CASCADE, relation.getCascades());\n\n        if (relation.isRelatedViaJoinTable())\n        {\n            linkProperties.put(LinkProperty.JOIN_TABLE_METADATA, relation.getJoinTableMetadata());\n        }\n\n        // TODO: Add more link properties as required\n        return linkProperties;\n    }\n\n    private boolean isIdSet(Object id)\n    {\n        if (id == null)\n        {\n            return false;\n        }\n        else if (id.getClass().isPrimitive() || id instanceof Number)\n        {\n            // Check for default value of integer/short/long/byte,float/double\n            // and char.\n            if (id.toString().equals(\"0\") || id.toString().equals(\"0.0\") || id.toString().equals(\"\"))\n            {\n                return false;\n            }\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/graph/ObjectGraphUtils.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.graph;\n\nimport java.lang.reflect.Field;\n\nimport javax.persistence.GeneratedValue;\n\nimport org.apache.commons.lang.StringUtils;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.utils.NumericUtils;\n\n/**\n * Provides utility methods for object graph\n * \n * @author amresh.singh\n */\npublic class ObjectGraphUtils\n{\n\n    /**\n     * \n     * @param pk\n     * @param objectClass\n     * @return\n     */\n    public static String getNodeId(Object pk, Class<?> objectClass)\n    {\n        StringBuffer strBuffer = new StringBuffer(objectClass.getName());\n        strBuffer.append(Constants.NODE_ID_SEPARATOR);\n        strBuffer.append(pk);\n        return strBuffer.toString();\n    }\n\n    /**\n     * \n     * @param nodeId\n     * @return\n     */\n    public static Object getEntityId(String nodeId)\n    {\n        return nodeId.substring(nodeId.indexOf(Constants.NODE_ID_SEPARATOR) + 1, nodeId.length());\n    }\n\n    /**\n     * Validates and set id, in case not set and intended for auto generation.\n     * \n     * @param idField\n     *            id field\n     * @param idValue\n     *            value of id attribute.\n     * @return returns true if id is not set and @GeneratedValue annotation is\n     *         present. Else false.\n     */\n    public static boolean onAutoGenerateId(Field idField, Object idValue)\n    {\n        if (idField.isAnnotationPresent(GeneratedValue.class))\n        {\n            return !isIdSet(idValue, idField);\n        }\n\n        return false;\n    }\n\n    /**\n     * \n     * @param id\n     * @param idField\n     * @return\n     */\n    private static boolean isIdSet(Object id, Field idField)\n    {\n        // return true, if it is non blank and not zero in case of numeric\n        // value.\n\n        if (id != null)\n        {\n            return !(NumericUtils.checkIfZero(id.toString(), idField.getType()) || (StringUtils\n                    .isNumeric(id.toString()) && StringUtils.isBlank(id.toString())));\n        }\n        return false;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/index/Index.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.index;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * Annotation interface for column\n * \n * @author Kuldeep Mishra\n * \n */\n@Target({ ElementType.TYPE, ElementType.FIELD })\n@Retention(RetentionPolicy.RUNTIME)\n@Documented\npublic @interface Index\n{\n\n    /**\n     * Column to index.\n     * \n     * @return the string\n     */\n    public abstract String name();\n\n    /**\n     * Type of index.\n     * \n     * @return the string\n     */\n    public abstract String type() default \"\";\n\n    /**\n     * Max value of index column.\n     * \n     * @return\n     */\n    public abstract int max() default Integer.MAX_VALUE;\n\n    /**\n     * Min value of index column.\n     * \n     * @return\n     */\n    public abstract int min() default Integer.MIN_VALUE;\n\n    /**\n     * Name of index, if it is different that column name.\n     * \n     * @return index name.\n     */\n    public abstract String indexName() default \"\";\n\n    /**\n     * Type of index.\n     * \n     * @author Kuldeep.Mishra\n     * \n     */\n    public enum IndexType\n    {\n        normal, composite, unique\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/index/IndexCollection.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.index;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * Annotation interface for collection of {@link Index}\n * \n * @author Kuldeep Mishra\n * \n */\n@Target({ ElementType.TYPE, ElementType.FIELD })\n@Retention(RetentionPolicy.RUNTIME)\n@Documented\npublic @interface IndexCollection\n{\n    /**\n     * Array of index columns to index.\n     * \n     * @return the string[]\n     */\n    public abstract Index[] columns();\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/index/IndexManager.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.index;\n\nimport java.lang.reflect.Field;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PropertyIndex;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * Manager responsible to co-ordinate with an Indexer. It is bound with\n * EntityManager.\n * \n * @author animesh.kumar\n */\npublic class IndexManager\n{\n\n    /** The indexer. */\n    private final Indexer indexer;\n\n    private final KunderaMetadata kunderaMetadata;\n\n    /**\n     * The Constructor.\n     * \n     * @param indexer\n     *            the indexer\n     */\n    @SuppressWarnings(\"deprecation\")\n    public IndexManager(Indexer indexer, final KunderaMetadata kunderaMetadata)\n    {\n        this.indexer = indexer;\n        this.kunderaMetadata = kunderaMetadata;\n    }\n\n    /**\n     * @return the indexer\n     */\n    public Indexer getIndexer()\n    {\n        return indexer;\n    }\n\n    /**\n     * Removes an object from Index.\n     * \n     * @param metadata\n     *            the metadata\n     * @param entity\n     *            the entity\n     * @param key\n     *            the key\n     */\n    public final void remove(EntityMetadata metadata, Object entity, Object key)\n    {\n        if (indexer != null)\n        {\n            if (indexer.getClass().getName().equals(IndexingConstants.LUCENE_INDEXER))\n            {\n                ((com.impetus.kundera.index.lucene.Indexer) indexer).unindex(metadata, key, kunderaMetadata, null);\n            }\n            else\n            {\n                indexer.unIndex(metadata.getEntityClazz(), entity, metadata, (MetamodelImpl) kunderaMetadata\n                        .getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit()));\n            }\n        }\n    }\n\n    /**\n     * Updates the index for an object.\n     * \n     * @param metadata\n     *            the metadata\n     * @param entity\n     *            the entity\n     */\n    public final void update(EntityMetadata metadata, Object entity, Object parentId, Class<?> clazz)\n    {\n        try\n        {\n            if (indexer != null)\n            {\n                if (indexer.getClass().getName().equals(IndexingConstants.LUCENE_INDEXER))\n                {\n                    MetamodelImpl metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                            metadata.getPersistenceUnit());\n                    Object id = PropertyAccessorHelper.getId(entity, metadata);\n                    boolean isEmbeddedId = metamodel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType());\n\n                    boolean documentExistsInIndex = ((com.impetus.kundera.index.lucene.Indexer) indexer)\n                            .documentExistsInIndex(metadata, id, kunderaMetadata, isEmbeddedId, clazz);\n\n                    if (documentExistsInIndex)\n                    {\n                        ((com.impetus.kundera.index.lucene.Indexer) indexer).update(metadata, metamodel, entity, id,\n                                parentId != null ? parentId.toString() : null);\n                    }\n                    else\n                    {\n\n                        boolean documentExists = ((com.impetus.kundera.index.lucene.Indexer) indexer)\n                                .entityExistsInIndex(entity.getClass(), kunderaMetadata, metadata);\n                        if (documentExists)\n                        {\n                            ((com.impetus.kundera.index.lucene.Indexer) indexer).unindex(metadata, id, kunderaMetadata,\n                                    clazz);\n                            ((com.impetus.kundera.index.lucene.Indexer) indexer).flush();\n                        }\n                        ((com.impetus.kundera.index.lucene.Indexer) indexer).index(metadata, metamodel, entity,\n                                parentId != null ? parentId.toString() : null, clazz);\n                    }\n                }\n                else\n                {\n                    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                            metadata.getPersistenceUnit());\n\n                    Map<String, PropertyIndex> indexProperties = metadata.getIndexProperties();\n                    Map<String, Object> indexCollection = new HashMap<String, Object>();\n                    Object id = PropertyAccessorHelper.getId(entity, metadata);\n                    for (String columnName : indexProperties.keySet())\n                    {\n                        PropertyIndex index = indexProperties.get(columnName);\n                        Field property = index.getProperty();\n                        // String propertyName = index.getName();\n                        Object obj = PropertyAccessorHelper.getObject(entity, property);\n                        indexCollection.put(columnName, obj);\n                    }\n\n                    indexCollection.put(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName(), id);\n\n                    EntityMetadata parentMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n                    if (parentId != null)\n                        indexCollection.put(((AbstractAttribute) parentMetadata.getIdAttribute()).getJPAColumnName(),\n                                parentId);\n\n                    onEmbeddable(entity, metadata.getEntityClazz(), metaModel, indexCollection);\n                    indexer.index(metadata.getEntityClazz(), metadata, indexCollection, parentId, clazz);\n                }\n            }\n        }\n        catch (PropertyAccessException e)\n        {\n            throw new IndexingException(\"Can't access ID from entity class \" + metadata.getEntityClazz(), e);\n        }\n    }\n\n    /**\n     * @param entity\n     * @param clazz\n     * @param metaModel\n     * @param indexCollection\n     */\n    private void onEmbeddable(Object entity, Class<?> clazz, MetamodelImpl metaModel,\n            Map<String, Object> indexCollection)\n    {\n        Map<String, EmbeddableType> embeddables = metaModel.getEmbeddables(clazz);\n        EntityType entityType = metaModel.entity(clazz);\n\n        for (String embeddedFieldName : embeddables.keySet())\n        {\n            EmbeddableType embeddedColumn = embeddables.get(embeddedFieldName);\n\n            // Index embeddable only when specified by user\n            Field embeddedField = (Field) entityType.getAttribute(embeddedFieldName).getJavaMember();\n            if (!MetadataUtils.isEmbeddedAtributeIndexable(embeddedField))\n            {\n                continue;\n            }\n\n            Object embeddedObject = PropertyAccessorHelper.getObject(entity,\n                    (Field) entityType.getAttribute(embeddedFieldName).getJavaMember());\n            if (embeddedObject != null && !(embeddedObject instanceof Collection))\n            {\n                for (Object column : embeddedColumn.getAttributes())\n                {\n                    Attribute columnAttribute = (Attribute) column;\n                    String columnName = columnAttribute.getName();\n                    Class<?> columnClass = ((AbstractAttribute) columnAttribute).getBindableJavaType();\n                    if (MetadataUtils.isColumnInEmbeddableIndexable(embeddedField, columnName))\n                    {\n                        indexCollection.put(\n                                embeddedField.getName() + \".\" + columnName,\n                                PropertyAccessorHelper.getObject(embeddedObject,\n                                        (Field) columnAttribute.getJavaMember()));\n                    }\n                }\n            }\n\n        }\n    }\n\n    /**\n     * Indexes an object.\n     * \n     * @param metadata\n     *            the metadata\n     * @param entity\n     *            the entity\n     */\n    public final void write(EntityMetadata metadata, Object entity)\n    {\n        if (indexer != null)\n        {\n            MetamodelImpl metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    metadata.getPersistenceUnit());\n            ((com.impetus.kundera.index.lucene.Indexer) indexer).index(metadata, metamodel, entity);\n        }\n    }\n\n    /**\n     * Indexes an object.\n     * \n     * @param metadata\n     *            the metadata\n     * @param entity\n     *            the entity\n     * @param parentId\n     *            parent Id.\n     * @param clazz\n     *            class name\n     */\n    public final void write(EntityMetadata metadata, Object entity, String parentId, Class<?> clazz)\n    {\n        if (indexer != null)\n        {\n            MetamodelImpl metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    metadata.getPersistenceUnit());\n            ((com.impetus.kundera.index.lucene.Indexer) indexer).index(metadata, metamodel, entity, parentId, clazz);\n        }\n    }\n\n    /**\n     * Searches on the index. Note: Query must be in Indexer's understandable\n     * format\n     * \n     * @param query\n     *            the query\n     * @return the list\n     */\n    @Deprecated\n    // TODO: All lucene specific code (methods that accept lucene query as\n    // parameter) from this class should go away\n    // and should be moved to LuceneIndexer instead\n    public final Map<String, Object> search(Class<?> clazz, String query)\n    {\n\n        return search(clazz, query, Constants.INVALID, Constants.INVALID, false);\n    }\n\n    public final Map<String, Object> search(Class<?> parentClass, Class<?> childClass, Object entityId)\n    {\n        if (indexer == null)\n            return null;\n\n        // Ideally it should be interface driven and should be handled by\n        // fallback-impl.\n\n        if (indexer != null && indexer.getClass().getName().equals(IndexingConstants.LUCENE_INDEXER))\n        {\n\n            // Search into Lucene index using lucene query, where entity class\n            // is child class, parent class is\n            // entity's class and parent Id is entity ID! that's it!\n            String query = LuceneQueryUtils.getQuery(IndexingConstants.PARENT_ID_CLASS, parentClass.getCanonicalName()\n                    .toLowerCase(), IndexingConstants.PARENT_ID_FIELD, entityId, childClass.getCanonicalName()\n                    .toLowerCase());\n            return ((com.impetus.kundera.index.lucene.Indexer) indexer).search(query, Constants.INVALID,\n                    Constants.INVALID, false, kunderaMetadata,\n                    KunderaMetadataManager.getEntityMetadata(kunderaMetadata, parentClass));\n        }\n        else\n        {\n            String query = LuceneQueryUtils.getQuery(IndexingConstants.PARENT_ID_CLASS, parentClass.getCanonicalName()\n                    .toLowerCase(), IndexingConstants.PARENT_ID_FIELD, entityId, childClass.getCanonicalName()\n                    .toLowerCase());\n            // If an alternate indexer implementation class is provided by user,\n            // search into that\n            return indexer.search(query, parentClass,\n                    KunderaMetadataManager.getEntityMetadata(kunderaMetadata, parentClass), childClass,\n                    KunderaMetadataManager.getEntityMetadata(kunderaMetadata, childClass), entityId, Constants.INVALID,\n                    Constants.INVALID);\n        }\n\n    }\n\n    /**\n     * Searches on the index. Note: Query must be in Indexer's understandable\n     * format\n     * \n     * @param query\n     *            the query\n     * @return the list\n     */\n    public final Map<String, Object> fetchRelation(Class<?> clazz, String query)\n    {\n        // TODO: need to return list.\n        return search(clazz, query, Constants.INVALID, Constants.INVALID, true);\n    }\n\n    /**\n     * Search.\n     * \n     * @param query\n     *            the query\n     * @param count\n     *            the count\n     * @return the list\n     */\n    public final Map<String, Object> search(Class<?> clazz, String query, int count)\n    {\n        return search(clazz, query, Constants.INVALID, count, false);\n    }\n\n    /**\n     * Search.\n     *\n     * @param clazz\n     *            the clazz\n     * @param query\n     *            the query\n     * @param start\n     *            the start\n     * @param count\n     *            the count\n     * @return the list\n     */\n    public final Map<String, Object> search(Class<?> clazz, String query, int start, int count)\n    {\n        if (indexer != null)\n        {\n            if (indexer != null && indexer.getClass().getName().equals(IndexingConstants.LUCENE_INDEXER))\n            {\n                return indexer != null ? ((com.impetus.kundera.index.lucene.Indexer) indexer)\n                        .search(query, start, count, false, kunderaMetadata,\n                                KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz)) : null;\n            }\n            else\n            {\n                return indexer.search(clazz, KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz), query,\n                        start, count);\n            }\n        }\n        return new HashMap<String, Object>();\n    }\n\n    public final Map<String, Object> search(KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery,\n            PersistenceDelegator persistenceDelegator, EntityMetadata m,int firstResult, int maxResults)\n    {\n        return indexer.search(kunderaMetadata, kunderaQuery, persistenceDelegator, m, firstResult, maxResults);\n    }\n\n    /**\n     * Search.\n     * \n     * @param query\n     *            the query\n     * @param start\n     *            the start\n     * @param count\n     *            the count\n     * @param fetchRelation\n     *            the fetch relation\n     * @return the list\n     */\n    public final Map<String, Object> search(Class<?> clazz, String query, int start, int count, boolean fetchRelation)\n    {\n        if (indexer != null)\n        {\n            if (indexer.getClass().getName().equals(IndexingConstants.LUCENE_INDEXER))\n            {\n                return indexer != null ? ((com.impetus.kundera.index.lucene.Indexer) indexer).search(query, start,\n                        count, fetchRelation, kunderaMetadata,\n                        KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz)) : null;\n            }\n            else\n            {\n                return indexer.search(clazz, KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz), query,\n                        start, count);\n            }\n        }\n        return new HashMap<String, Object>();\n    }\n\n    /**\n     * Flushes out the indexes, keeping RAM directory open.\n     */\n    public void flush() throws IndexingException\n    {\n        if (indexer != null)\n        {\n            // ((Indexer) indexer).close();\n        }\n    }\n\n    /**\n     * Closes the transaction along with RAM directory.\n     */\n    public void close() throws IndexingException\n    {\n        if (indexer != null)\n        {\n            indexer.close();\n        }\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/index/Indexer.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.index;\n\nimport java.util.Map;\n\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * Indexer interface. Any custom implementation for this interface can be\n * plugged-in by configuring kundera.indexer.class property in persistence.xml.\n * Once this is enabled in persistence provider, Kundera will automatically\n * delegate index related requests to configure indexer interface implementation\n * but will keep functioning for any database specific requests. For example,\n * developer may rely upon custom index implementation for inverted\n * indexes(e.g. @Id attributes) but entity data population will be handled by\n * Kundera.\n * \n * @author vivek.mishra\n * \n */\npublic interface Indexer\n{\n    /**\n     * Index a document for given entity class and collection of values.\n     * \n     * @param entityClazz\n     *            entity class\n     * \n     * @param values\n     *            map of values containing field name as key and it's value.\n     */\n    void index(final Class entityClazz, EntityMetadata entityMetadata, Map<String, Object> values,\n            final Object parentId, final Class parentClazz);\n\n    /**\n     * Executes lucene query and returns inverted indices as output. TODO:\n     * Indexer interface shouldn't make any assumption about its implementation,\n     * this method signature accepts lucene query, and hence should go away\n     * \n     * @param queryString\n     *            lucene query.\n     * @param start\n     *            start counter\n     * @param end\n     *            end counter\n     * @return collection containing stored index value.\n     */\n    @Deprecated\n    Map<String, Object> search(Class<?> clazz, EntityMetadata m, String luceneQuery, int start, int count);\n\n    /**\n     * Searches into a secondary index\n     * \n     * @return\n     */\n    Map<String, Object> search(String query, Class<?> parentClass, EntityMetadata parentMetadata, Class<?> childClass,\n            EntityMetadata childMetadata, Object entityId, int start, int count);\n\n    Map<String, Object> search(KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery,\n            PersistenceDelegator persistenceDelegator, EntityMetadata m, int firstResult, int maxResults);\n\n    /**\n     * Deletes index for given entity class.\n     * \n     * @param entityClazz\n     *            entity class\n     * \n     * @param entity\n     *            Entity object\n     */\n    void unIndex(final Class entityClazz, final Object entity, EntityMetadata entityMetadata, MetamodelImpl metamodel);\n\n    /**\n     * Close indexer instance.\n     */\n    void close();\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/index/IndexerProperties.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.index;\n\nimport java.util.List;\nimport java.util.Properties;\n\nimport javax.xml.bind.annotation.XmlElement;\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\n@XmlRootElement\npublic class IndexerProperties\n{\n\n    private List<Node> nodes;\n\n    @XmlRootElement\n    public static class Node\n    {\n        private Properties properties;\n\n        public Properties getProperties()\n        {\n            return properties;\n        }\n\n        public void setProperties(Properties properties)\n        {\n            this.properties = properties;\n        }\n    }\n\n    @XmlElement\n    public List<Node> getNodes()\n    {\n        return nodes;\n    }\n\n    public void setNodes(List<Node> nodes)\n    {\n        this.nodes = nodes;\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/index/IndexingConstants.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.index;\r\n\r\n\r\n/**\r\n * The Class IndexingConstants.\r\n * \r\n * @author vivek.mishra\r\n */\r\npublic final class IndexingConstants\r\n{\r\n\r\n    // persistent-unit-name\r\n\r\n    /** The Constant UUID. */\r\n    private static final long UUID = 6077004083174677888L;\r\n\r\n    /** The Constant DELIMETER. */\r\n    public static final String DELIMETER = \"~\";\r\n\r\n    /** The Constant ENTITY_ID_FIELD. */\r\n    public static final String ENTITY_ID_FIELD = UUID + \".entity.id\";\r\n\r\n    /** The Constant KUNDERA_ID_FIELD. */\r\n    public static final String KUNDERA_ID_FIELD = UUID + \".kundera.id\";\r\n\r\n    /** The Constant ENTITY_INDEXNAME_FIELD. */\r\n    public static final String ENTITY_INDEXNAME_FIELD = UUID + \".entity.indexname\";\r\n\r\n    /** The Constant ENTITY_CLASS_FIELD. */\r\n    public static final String ENTITY_CLASS_FIELD = /* UUID + */\"entity.class\";\r\n\r\n    /** The Constant PARENT_ID_FIELD. */\r\n    public static final String PARENT_ID_FIELD = UUID + \".parent.id\";\r\n\r\n    /** The Constant PARENT_ID_CLASS. */\r\n    public static final String PARENT_ID_CLASS = UUID + \".parent.class\";\r\n\r\n    \r\n    public static final String LUCENE_INDEXER = \"com.impetus.kundera.index.LuceneIndexer\";\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/index/IndexingException.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.index;\r\n\r\nimport com.impetus.kundera.KunderaException;\r\n\r\n/**\r\n * Captures any indexing related exceptions.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class IndexingException extends KunderaException\r\n{\r\n\r\n    /** The Constant serialVersionUID. */\r\n    private static final long serialVersionUID = 7917821486831927353L;\r\n\r\n    /**\r\n     * \r\n     */\r\n    public IndexingException()\r\n    {\r\n        super();\r\n\r\n    }\r\n\r\n    /**\r\n     * @param arg0\r\n     * @param arg1\r\n     */\r\n    public IndexingException(String arg0, Throwable arg1)\r\n    {\r\n        super(arg0, arg1);\r\n\r\n    }\r\n\r\n    /**\r\n     * @param arg0\r\n     */\r\n    public IndexingException(String arg0)\r\n    {\r\n        super(arg0);\r\n\r\n    }\r\n\r\n    /**\r\n     * @param arg0\r\n     */\r\n    public IndexingException(Throwable arg0)\r\n    {\r\n        super(arg0);\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/index/LuceneIndexingException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.index;\n\n/**\n * @author amresh.singh\n * \n */\npublic class LuceneIndexingException extends IndexingException\n{\n    /**\n     * \n     */\n    private static final long serialVersionUID = -9021996457355536038L;\n\n    /**\n     * \n     */\n    public LuceneIndexingException()\n    {\n    }\n\n    /**\n     * @param arg0\n     * @param arg1\n     */\n    public LuceneIndexingException(String arg0, Throwable arg1)\n    {\n        super(arg0, arg1);\n\n    }\n\n    /**\n     * @param arg0\n     */\n    public LuceneIndexingException(String arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     */\n    public LuceneIndexingException(Throwable arg0)\n    {\n        super(arg0);\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/index/LuceneQueryUtils.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.index;\n\n/**\n * Provides utility methods for Lucene Query related functionality\n * \n * @author amresh.singh\n */\npublic class LuceneQueryUtils\n{\n    /**\n     * Returns lucene based query.\n     * \n     * @param clazzFieldName\n     *            lucene field name for class\n     * @param clazzName\n     *            class name\n     * @param idFieldName\n     *            lucene id field name\n     * @param idFieldValue\n     *            lucene id field value\n     * @return query lucene query.\n     */\n    public static String getQuery(String clazzFieldName, String clazzName, String idFieldName, String idFieldValue)\n    {\n        StringBuffer sb = new StringBuffer(\"+\");\n        sb.append(clazzFieldName);\n        sb.append(\":\");\n        sb.append(clazzName);\n        sb.append(\" AND \");\n        sb.append(\"+\");\n        sb.append(idFieldName);\n        sb.append(\":\");\n        sb.append(idFieldValue);\n        return sb.toString();\n    }\n\n    /**\n     * Returns lucene based query.\n     * \n     * @param clazzFieldName\n     *            lucene field name for class\n     * @param clazzName\n     *            class name\n     * @param idFieldName\n     *            lucene id field name\n     * @param idFieldValue\n     *            lucene id field value\n     * @param entityClazz\n     *            the entity clazz\n     * @return query lucene query.\n     */\n    public static String getQuery(String clazzFieldName, String clazzName, String idFieldName, Object idFieldValue,\n            String entityClazz)\n    {\n        StringBuffer sb = new StringBuffer(\"+\");\n        sb.append(clazzFieldName);\n        sb.append(\":\");\n        sb.append(clazzName);\n        sb.append(\" AND \");\n        sb.append(\"+\");\n        sb.append(idFieldName);\n        sb.append(\":\");\n        sb.append(idFieldValue);\n        if (entityClazz != null)\n        {\n            sb.append(\" AND \");\n            sb.append(\"+\");\n            sb.append(IndexingConstants.ENTITY_CLASS_FIELD);\n            sb.append(\":\");\n            sb.append(entityClazz);\n        }\n        return sb.toString();\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/index/lucene/Indexer.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.index.lucene;\n\nimport java.util.Map;\n\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * Interface to define the behavior of an Indexer.\n * \n * @author animesh.kumar\n */\npublic interface Indexer extends com.impetus.kundera.index.Indexer\n{\n\n    /**\n     * Unindexed an entity with key:id.\n     * \n     * @param metadata\n     *            the metadata\n     * @param id\n     *            the id\n     */\n\n    void unindex(EntityMetadata metadata, Object id,KunderaMetadata kunderaMetadata, Class<?> parentClazz);\n\n    /**\n     * Indexes and object.\n     * \n     * @param metadata\n     *            the metadata\n     * @param object\n     *            the object\n     */\n    void index(EntityMetadata metadata, final MetamodelImpl metaModel, Object object);\n\n    /**\n     * Indexes and object.\n     * \n     * @param metadata\n     *            the meta data.\n     * @param object\n     *            the object.\n     * @param parentId\n     *            parent Id.\n     * @param clazz\n     *            parent class.\n     */\n    void index(EntityMetadata metadata, final MetamodelImpl metaModel, Object object, String parentId, Class<?> clazz);\n\n    /**\n     * Searches for an object. Note that the \"query\" must be in Indexer\n     * specified form.\n     * \n     * @param luceneQuery\n     *            the lucene query\n     * @param start\n     *            the start\n     * @param count\n     *            the count\n     * @param fetchRelation\n     *            the fetch relation\n     * @return the list\n     */\n\n    Map<String, Object> search(String luceneQuery, int start, int count, boolean fetchRelation,\n            KunderaMetadata kunderaMetadata, EntityMetadata metadata);\n\n    \n\n    /**\n     * Close on index writer/reader.\n     */\n    void close();\n\n    /**\n     * Flushes out indexes.\n     */\n    void flush();\n\n    /**\n     * Validates, if document exists in index.\n     * \n     * @param metadata entity metadata\n     * @param id   entity id\n     * @return true, if exists else false.\n     */\n    \n\n    \n    /**\n     * Updates the existing document.\n     * \n     * @param metadata   entity metadata.\n     * @param entity     entity object. \n     * @param id         entity id\n     * @param parentId   parent entity id\n     * @param parentClazz  parent class\n     */\n    void update(EntityMetadata metadata, final MetamodelImpl metaModel, Object entity, Object id, String parentId);\n\n    /**\n     * @param entityClass\n     * @param kunderaMetadata\n     * @param metadata\n     * @return\n     */\n    boolean entityExistsInIndex(Class<?> entityClass, KunderaMetadata kunderaMetadata, EntityMetadata metadata);\n\n    /**\n     * @param metadata\n     * @param id\n     * @param kunderaMetadata\n     * @param isEmbeddedId\n     * @param parentClazz\n     * @return\n     */\n    boolean documentExistsInIndex(EntityMetadata metadata, Object id, KunderaMetadata kunderaMetadata,\n            boolean isEmbeddedId, Class<?> parentClazz);\n\n    \n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/lifecycle/NodeStateContext.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.lifecycle;\n\nimport java.util.Map;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.NodeLink;\nimport com.impetus.kundera.lifecycle.states.NodeState;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\n\n/**\n * State context of a given entity\n * \n * @author amresh\n * \n */\npublic interface NodeStateContext\n{\n    // State methods\n    NodeState getCurrentNodeState();\n\n    void setCurrentNodeState(NodeState nodeState);\n\n    String getNodeId();\n\n    void setNodeId(String nodeId);\n\n    Object getData();\n\n    void setData(Object data);\n\n    Class getDataClass();\n\n    void setDataClass(Class dataClass);\n\n    Map<NodeLink, Node> getParents();\n\n    void setParents(Map<NodeLink, Node> parents);\n\n    Map<NodeLink, Node> getChildren();\n\n    void setChildren(Map<NodeLink, Node> children);\n\n    Node getParentNode(String parentNodeId);\n\n    Node getChildNode(String childNodeId);\n\n    void addParentNode(NodeLink nodeLink, Node node);\n\n    void addChildNode(NodeLink nodeLink, Node node);\n\n    boolean isTraversed();\n\n    void setTraversed(boolean traversed);\n\n    boolean isDirty();\n\n    void setDirty(boolean dirty);\n\n    boolean isHeadNode();\n\n    Client getClient();\n\n    void setClient(Client client);\n\n    PersistenceDelegator getPersistenceDelegator();\n\n    void setPersistenceDelegator(PersistenceDelegator pd);\n\n    // Life cycle Management\n    void persist();\n\n    void remove();\n\n    void refresh();\n\n    void merge();\n\n    void detach();\n\n    void close();\n\n    void lock();\n\n    void commit();\n\n    void rollback();\n\n    // Identity Management\n    void find();\n\n    void getReference();\n\n    void contains();\n\n    // Cache Management\n    void clear();\n\n    void flush();\n\n    public boolean isInState(Class<?> stateClass);\n\n    public PersistenceCache getPersistenceCache();\n\n    public void setPersistenceCache(PersistenceCache persistenceCache);\n\n    public Object getEntityId();\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/lifecycle/states/DetachedState.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.lifecycle.states;\n\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.lifecycle.NodeStateContext;\n\n/**\n * @author amresh\n * \n */\npublic class DetachedState extends NodeState\n{\n\n    @Override\n    public void initialize(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handlePersist(NodeStateContext nodeStateContext)\n    {\n        throw new IllegalArgumentException(\"Persist operation not allowed in Detached state\");\n    }\n\n    @Override\n    public void handleRemove(NodeStateContext nodeStateContext)\n    {\n        throw new IllegalArgumentException(\n                \"Remove operation not allowed in Detached state.\"\n                        + \" Possible reason: You may have closed entity manager before calling remove. A solution is to call merge before remove.\");\n    }\n\n    @Override\n    public void handleRefresh(NodeStateContext nodeStateContext)\n    {\n        throw new IllegalArgumentException(\"Refresh operation not allowed in Detached state\");\n    }\n\n    @Override\n    public void handleMerge(NodeStateContext nodeStateContext)\n    {\n        // Detached ---> Managed\n        moveNodeToNextState(nodeStateContext, new ManagedState());\n\n        ((Node) nodeStateContext).setUpdate(true);\n\n        // Copy detached entity's current state to existing managed instance of\n        // the\n        // same entity identity (if one exists), or create a new managed copy\n\n        // Cascade manage operation for all related entities for whom\n        // cascade=ALL or MERGE\n//        recursivelyPerformOperation(nodeStateContext, OPERATION.MERGE);\n    }\n\n    @Override\n    public void handleFind(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleClose(NodeStateContext nodeStateContext)\n    {\n        // Nothing to do, already in Detached State\n    }\n\n    @Override\n    public void handleClear(NodeStateContext nodeStateContext)\n    {\n        // Nothing to do, already in Detached State\n    }\n\n    @Override\n    public void handleFlush(NodeStateContext nodeStateContext)\n    {\n        // Nothing to do, Entities are flushed from Managed/ Removed state only\n    }\n\n    @Override\n    public void handleLock(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleDetach(NodeStateContext nodeStateContext)\n    {\n        // Nothing to do, already in Detached State\n    }\n\n    @Override\n    public void handleCommit(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleRollback(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleGetReference(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleContains(NodeStateContext nodeStateContext)\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/lifecycle/states/ManagedState.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.lifecycle.states;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.PersistenceContextType;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.lifecycle.NodeStateContext;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\n\n/**\n * @author amresh\n * \n */\npublic class ManagedState extends NodeState\n{\n\n    @Override\n    public void initialize(NodeStateContext nodeStateContext)\n    {\n\n    }\n\n    @Override\n    public void handlePersist(NodeStateContext nodeStateContext)\n    {\n        // Ignored, entity remains in the same state\n\n        // Cascade persist operation for related entities for whom cascade=ALL\n        // or PERSIST\n//        if (((Node) nodeStateContext).isDirty())\n//        {\n//            recursivelyPerformOperation(nodeStateContext, OPERATION.PERSIST);\n//        }\n    }\n\n    @Override\n    public void handleRemove(NodeStateContext nodeStateContext)\n    {\n        // Managed ---> Removed\n        moveNodeToNextState(nodeStateContext, new RemovedState());\n\n        // Mark entity for removal in persistence context\n        nodeStateContext.setDirty(true);\n\n        // Recurse remove operation for all related entities for whom\n        // cascade=ALL or REMOVE\n//        recursivelyPerformOperation(nodeStateContext, OPERATION.REMOVE);\n    }\n\n    @Override\n    public void handleRefresh(NodeStateContext nodeStateContext)\n    {\n        // Refresh entity state from the database\n        // Fetch Node data from Client\n        Client client = nodeStateContext.getClient();\n        Class<?> nodeDataClass = nodeStateContext.getDataClass();\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(nodeStateContext.getPersistenceDelegator().getKunderaMetadata(), nodeDataClass);\n        Object entityId = nodeStateContext.getEntityId();\n\n        EntityReader reader = client.getReader();\n        EnhanceEntity ee = reader.findById(entityId, entityMetadata, client);\n\n        if (ee != null && ee.getEntity() != null)\n        {\n            Object nodeData = ee.getEntity();\n            nodeStateContext.setData(nodeData);\n        }\n\n        // Cascade refresh operation for all related entities for whom\n        // cascade=ALL or REFRESH\n        recursivelyPerformOperation(nodeStateContext, OPERATION.REFRESH);\n    }\n\n    @Override\n    public void handleMerge(NodeStateContext nodeStateContext)\n    {\n        // Ignored, entity remains in the same state\n\n        // Mark this entity for saving in database depending upon whether it's\n        // deep equals to the\n        // one in persistence cache\n        // nodeStateContext.setDirty(true);\n\n//        if (((Node) nodeStateContext).isDirty() || ((Node) nodeStateContext).isInState(DetachedState.class))\n//        {\n            ((Node) nodeStateContext).setUpdate(true);\n            // Add this node into persistence cache\n            nodeStateContext.getPersistenceCache().getMainCache().addNodeToCache((Node) nodeStateContext);\n\n            // Cascade merge operation for all related entities for whom\n            // cascade=ALL\n            // or MERGE\n//            recursivelyPerformOperation(nodeStateContext, OPERATION.MERGE);\n\n//        }\n    }\n\n    @Override\n    public void handleFind(NodeStateContext nodeStateContext)\n    {\n        // Fetch Node data from Client\n        Client client = nodeStateContext.getClient();\n        Class<?> nodeDataClass = nodeStateContext.getDataClass();\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(nodeStateContext.getPersistenceDelegator().getKunderaMetadata(), nodeDataClass);\n        Object entityId = nodeStateContext.getEntityId();\n\n        Object nodeData = null; // Node data\n\n        EntityReader reader = client.getReader();\n        if (reader == null)\n        {\n            return;\n        }\n\n        EnhanceEntity ee = reader.findById(entityId, entityMetadata, client);\n        // Recursively retrieve relationship entities (if there are any)\n        if (ee != null && ee.getEntity() != null)\n        {\n            Object entity = ee.getEntity();\n\n            if ((entityMetadata.getRelationNames() == null || entityMetadata.getRelationNames().isEmpty())\n                    && !entityMetadata.isRelationViaJoinTable())\n            {\n                // There is no relation (not even via Join Table), Construct\n                // Node out of this enhance entity,\n                nodeData = entity;\n            }\n\n            else\n            {\n                // This entity has associated entities, find them recursively.\n                Map<Object, Object> relationStack = new HashMap<Object, Object>();\n                relationStack.put(nodeDataClass.getCanonicalName()+\"#\"+PropertyAccessorHelper.getId(entity, entityMetadata), entity);\n                nodeData = reader.recursivelyFindEntities(ee.getEntity(), ee.getRelations(), entityMetadata,\n                        nodeStateContext.getPersistenceDelegator(), false,relationStack);\n            }\n        }\n\n        // Construct Node out of this entity and put into Persistence Cache\n        if (nodeData != null)\n        {\n\n            nodeStateContext.setData(nodeData);\n            nodeStateContext.getPersistenceCache().getMainCache().processNodeMapping((Node) nodeStateContext);\n\n            // This node is fresh and hence NOT dirty\n            nodeStateContext.setDirty(false);\n            // One time set as required for rollback.\n            Object original = ((Node) nodeStateContext).clone();\n            ((Node) nodeStateContext).setOriginalNode((Node) original);\n        }\n\n        // No state change, Node to remain in Managed state\n    }\n\n    @Override\n    public void handleClose(NodeStateContext nodeStateContext)\n    {\n        handleDetach(nodeStateContext);\n    }\n\n    @Override\n    public void handleClear(NodeStateContext nodeStateContext)\n    {\n        handleDetach(nodeStateContext);\n    }\n\n    @Override\n    public void handleFlush(NodeStateContext nodeStateContext)\n    {\n        // Entity state to remain as Managed\n\n        // Flush this node to database\n        Client client = nodeStateContext.getClient();\n        client.persist((Node) nodeStateContext);\n\n        // logNodeEvent(\"FLUSHED\", this, nodeStateContext.getNodeId());\n\n        // Since node is flushed, mark it as NOT dirty\n        nodeStateContext.setDirty(false);\n\n    }\n\n    @Override\n    public void handleLock(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleDetach(NodeStateContext nodeStateContext)\n    {\n        // Managed ---> Detached\n        moveNodeToNextState(nodeStateContext, new DetachedState());\n\n        // Cascade detach operation to all referenced entities for whom\n        // cascade=ALL or DETACH\n        recursivelyPerformOperation(nodeStateContext, OPERATION.DETACH);\n    }\n\n    @Override\n    public void handleCommit(NodeStateContext nodeStateContext)\n    {\n        nodeStateContext.setCurrentNodeState(new DetachedState());\n    }\n\n    @Override\n    public void handleRollback(NodeStateContext nodeStateContext)\n    {\n        // If persistence context is EXTENDED, Next state should be Transient\n        // If persistence context is TRANSACTIONAL, Next state should be\n        // detached\n\n        if (PersistenceContextType.EXTENDED.equals(nodeStateContext.getPersistenceCache().getPersistenceContextType()))\n        {\n            moveNodeToNextState(nodeStateContext, new TransientState());\n\n        }\n        else if (PersistenceContextType.TRANSACTION.equals(nodeStateContext.getPersistenceCache()\n                .getPersistenceContextType()))\n        {\n            moveNodeToNextState(nodeStateContext, new DetachedState());\n        }\n    }\n\n    @Override\n    public void handleGetReference(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleContains(NodeStateContext nodeStateContext)\n    {\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/lifecycle/states/NodeState.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.lifecycle.states;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.CascadeType;\n\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.NodeLink;\nimport com.impetus.kundera.graph.NodeLink.LinkProperty;\nimport com.impetus.kundera.lifecycle.NodeStateContext;\n\n/**\n * State machine class for Node state\n * \n * @author amresh\n * \n */\npublic abstract class NodeState\n{\n    public enum OPERATION\n    {\n        PERSIST, MERGE, REMOVE, REFRESH, DETACH\n    }\n\n    public abstract void initialize(NodeStateContext nodeStateContext);\n\n    // Life cycle Management\n    public abstract void handlePersist(NodeStateContext nodeStateContext);\n\n    public abstract void handleRemove(NodeStateContext nodeStateContext);\n\n    public abstract void handleRefresh(NodeStateContext nodeStateContext);\n\n    public abstract void handleMerge(NodeStateContext nodeStateContext);\n\n    public abstract void handleDetach(NodeStateContext nodeStateContext);\n\n    public abstract void handleClose(NodeStateContext nodeStateContext);\n\n    public abstract void handleLock(NodeStateContext nodeStateContext);\n\n    public abstract void handleCommit(NodeStateContext nodeStateContext);\n\n    public abstract void handleRollback(NodeStateContext nodeStateContext);\n\n    // Identity Management\n    public abstract void handleFind(NodeStateContext nodeStateContext);\n\n    public abstract void handleGetReference(NodeStateContext nodeStateContext);\n\n    public abstract void handleContains(NodeStateContext nodeStateContext);\n\n    // Cache Management\n    public abstract void handleClear(NodeStateContext nodeStateContext);\n\n    public abstract void handleFlush(NodeStateContext nodeStateContext);\n\n    /**\n     * @param nodeStateContext\n     */\n    void moveNodeToNextState(NodeStateContext nodeStateContext, NodeState nextState)\n    {\n        nodeStateContext.setCurrentNodeState(nextState);\n    }\n\n    /**\n     * @param nodeStateContext\n     */\n    void recursivelyPerformOperation(NodeStateContext nodeStateContext, OPERATION operation)\n    {\n        Map<NodeLink, Node> children = nodeStateContext.getChildren();\n        if (children != null)\n        {\n            for (NodeLink nodeLink : children.keySet())\n            {\n                List<CascadeType> cascadeTypes = (List<CascadeType>) nodeLink.getLinkProperty(LinkProperty.CASCADE);\n\n                switch (operation)\n                {\n                /*case PERSIST:\n                    if (cascadeTypes.contains(CascadeType.PERSIST) || cascadeTypes.contains(CascadeType.ALL))\n                    {\n                        Node childNode = children.get(nodeLink);\n                        childNode.persist();\n                    }\n                    break;\n                case MERGE:\n                    if (cascadeTypes.contains(CascadeType.MERGE) || cascadeTypes.contains(CascadeType.ALL))\n                    {\n                        Node childNode = children.get(nodeLink);\n                        if (childNode.isInState(TransientState.class))\n                        {\n                            childNode.persist();\n                        }\n                        else\n                        {\n                            childNode.merge();\n                        }\n                    }\n                    break;\n\n                case REMOVE:\n                    if (cascadeTypes.contains(CascadeType.REMOVE) || cascadeTypes.contains(CascadeType.ALL))\n                    {\n                        Node childNode = children.get(nodeLink);\n                        childNode.remove();\n                    }\n                    break;*/\n\n                case REFRESH:\n                    if (cascadeTypes.contains(CascadeType.REFRESH) || cascadeTypes.contains(CascadeType.ALL))\n                    {\n                        Node childNode = children.get(nodeLink);\n                        childNode.refresh();\n                    }\n                    break;\n                case DETACH:\n                    if (cascadeTypes.contains(CascadeType.DETACH) || cascadeTypes.contains(CascadeType.ALL))\n                    {\n                        Node childNode = children.get(nodeLink);\n                        childNode.detach();\n                    }\n                    break;\n                }\n\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/lifecycle/states/RemovedState.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.lifecycle.states;\n\nimport javax.persistence.PersistenceContextType;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.lifecycle.NodeStateContext;\n\n/**\n * @author amresh\n * \n */\npublic class RemovedState extends NodeState\n{\n    @Override\n    public void initialize(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handlePersist(NodeStateContext nodeStateContext)\n    {\n        // Removed ---> Managed State\n        moveNodeToNextState(nodeStateContext, new ManagedState());\n\n        // Recurse persist operation on all related entities for whom\n        // cascade=ALL or PERSIST\n//        recursivelyPerformOperation(nodeStateContext, OPERATION.PERSIST);\n    }\n\n    @Override\n    public void handleRemove(NodeStateContext nodeStateContext)\n    {\n        // Ignored, entity will remain in removed state\n\n        // Recurse remove operation for all related entities for whom\n        // cascade=ALL or REMOVE\n//        recursivelyPerformOperation(nodeStateContext, OPERATION.REMOVE);\n    }\n\n    @Override\n    public void handleRefresh(NodeStateContext nodeStateContext)\n    {\n        throw new IllegalArgumentException(\"Refresh operation not allowed in Removed state\");\n    }\n\n    @Override\n    public void handleMerge(NodeStateContext nodeStateContext)\n    {\n        throw new IllegalArgumentException(\"Merge operation not allowed in Removed state\");\n    }\n\n    @Override\n    public void handleFind(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleClose(NodeStateContext nodeStateContext)\n    {\n        // Nothing to do, only entities in Managed state move to detached state\n    }\n\n    @Override\n    public void handleClear(NodeStateContext nodeStateContext)\n    {\n        // Nothing to do, only entities in Managed state move to detached state\n    }\n\n    @Override\n    public void handleFlush(NodeStateContext nodeStateContext)\n    {\n        // Entity state to remain as Removed\n\n        // Flush this node to database\n        Client client = nodeStateContext.getClient();\n\n        Node node = (Node) nodeStateContext;\n\n        Object entityId = node.getEntityId();\n\n        client.remove(node.getData(), entityId);\n\n        // Since node is flushed, mark it as NOT dirty\n        nodeStateContext.setDirty(false);\n\n        // Remove this node from Persistence Cache\n        nodeStateContext.getPersistenceCache().getMainCache().removeNodeFromCache(node);\n    }\n\n    @Override\n    public void handleLock(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleDetach(NodeStateContext nodeStateContext)\n    {\n        // Removed ---> Detached\n        moveNodeToNextState(nodeStateContext, new DetachedState());\n\n        // Cascade detach operation to all referenced entities for whom\n        // cascade=ALL or DETACH\n        recursivelyPerformOperation(nodeStateContext, OPERATION.DETACH);\n    }\n\n    @Override\n    public void handleCommit(NodeStateContext nodeStateContext)\n    {\n        nodeStateContext.setCurrentNodeState(new TransientState());\n    }\n\n    @Override\n    public void handleRollback(NodeStateContext nodeStateContext)\n    {\n        // If persistence context is EXTENDED, Next state should be Managed\n        // If persistence context is TRANSACTIONAL, Node should be detached\n\n        if (PersistenceContextType.EXTENDED.equals(nodeStateContext.getPersistenceCache().getPersistenceContextType()))\n        {\n            moveNodeToNextState(nodeStateContext, new ManagedState());\n\n        }\n        else if (PersistenceContextType.TRANSACTION.equals(nodeStateContext.getPersistenceCache()\n                .getPersistenceContextType()))\n        {\n            nodeStateContext.detach();\n        }\n\n    }\n\n    @Override\n    public void handleGetReference(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleContains(NodeStateContext nodeStateContext)\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/lifecycle/states/TransientState.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.lifecycle.states;\n\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.lifecycle.NodeStateContext;\nimport com.impetus.kundera.utils.ObjectUtils;\n\n/**\n * @author amresh\n * \n */\npublic class TransientState extends NodeState\n{\n    @Override\n    public void initialize(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handlePersist(NodeStateContext nodeStateContext)\n    {\n\n        // Transient ---> Managed\n        moveNodeToNextState(nodeStateContext, new ManagedState());\n\n        // Mark this entity for saving in database\n        nodeStateContext.setDirty(true);\n\n        // Add this node into persistence cache\n        nodeStateContext.getPersistenceCache().getMainCache().addNodeToCache((Node) nodeStateContext);\n        // Recurse persist operation on all managed entities for whom\n        // cascade=ALL or PERSIST\n        // recursivelyPerformOperation(nodeStateContext, OPERATION.PERSIST);\n    }\n\n    @Override\n    public void handleRemove(NodeStateContext nodeStateContext)\n    {\n        // Ignored, Entity will remain in the Transient state\n\n        // Recurse remove operation for all related entities for whom\n        // cascade=ALL or REMOVE\n        // recursivelyPerformOperation(nodeStateContext, OPERATION.REMOVE);\n    }\n\n    @Override\n    public void handleRefresh(NodeStateContext nodeStateContext)\n    {\n        throw new IllegalArgumentException(\"Refresh operation not allowed in Transient state\");\n    }\n\n    @Override\n    public void handleMerge(NodeStateContext nodeStateContext)\n    {\n        // create a new managed entity and copy state of original entity into\n        // this one.\n        Object copiedNodeData = ObjectUtils.deepCopy(nodeStateContext.getData(), nodeStateContext.getPersistenceDelegator().getKunderaMetadata());\n        nodeStateContext.setData(copiedNodeData);\n        moveNodeToNextState(nodeStateContext, new ManagedState());\n\n        nodeStateContext.getPersistenceCache().getMainCache().addNodeToCache((Node) nodeStateContext);\n    }\n\n    @Override\n    public void handleFind(NodeStateContext nodeStateContext)\n    {\n        // Nothing to do, Entity once found, jusmps directly to managed state\n    }\n\n    @Override\n    public void handleClose(NodeStateContext nodeStateContext)\n    {\n        // Nothing to do, only entities in Managed/ Removed state move to\n        // detached state\n    }\n\n    @Override\n    public void handleClear(NodeStateContext nodeStateContext)\n    {\n        // Nothing to do, only entities in Managed/ Removed state move to\n        // detached state\n    }\n\n    @Override\n    public void handleFlush(NodeStateContext nodeStateContext)\n    {\n        // Nothing to do, Entities are flushed from Managed/ Removed state only\n    }\n\n    @Override\n    public void handleLock(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleDetach(NodeStateContext nodeStateContext)\n    {\n        // Nothing to do, only entities in Managed/ Removed state move to\n        // detached state\n    }\n\n    @Override\n    public void handleCommit(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleRollback(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleGetReference(NodeStateContext nodeStateContext)\n    {\n    }\n\n    @Override\n    public void handleContains(NodeStateContext nodeStateContext)\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/loader/ClientFactory.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.loader;\n\nimport java.util.Map;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\n\n/**\n * Interface for client factory.\n * \n * @author vivek.mishra\n * \n */\npublic interface ClientFactory\n{\n\n    /**\n     * Load.\n     * \n     * @param persistenceUnit\n     *            the persistence units\n     */\n    void load(String persistenceUnit, Map<String, Object> puProperties);\n\n    /**\n     * Instantiate and returns client instance\n     * \n     * @return client instance.\n     */\n    Client getClientInstance();\n\n    /**\n     * return the instance of schema manager\n     * \n     * @return schemaManager interface.\n     */\n    SchemaManager getSchemaManager(Map<String, Object> puProperties);\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/loader/ClientLifeCycleManager.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.loader;\r\n\r\nimport java.util.Map;\r\n\r\n/**\r\n * Interface to define for client life cycle manager.\r\n * \r\n * @author vivek.mishra\r\n * \r\n */\r\npublic interface ClientLifeCycleManager\r\n{\r\n\r\n    /**\r\n     * Initialize configured client.\r\n     */\r\n    void initialize(Map<String, Object> puProperties);\r\n\r\n    /**\r\n     * Returns true if client is thread safe, else false.\r\n     * \r\n     * @return true if client is thread safe.\r\n     */\r\n    boolean isThreadSafe();\r\n\r\n    /**\r\n     * Unloads/destroy configured client instance.\r\n     */\r\n    void destroy();\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/loader/ClientLoaderException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.loader;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * @author amresh.singh\n * \n */\npublic class ClientLoaderException extends KunderaException\n{\n\n    /**\n     * \n     */\n    private static final long serialVersionUID = -2780499169457052865L;\n\n    /**\n     * \n     */\n    public ClientLoaderException()\n    {\n    }\n\n    /**\n     * @param arg0\n     */\n    public ClientLoaderException(String arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     */\n    public ClientLoaderException(Throwable arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     * @param arg1\n     */\n    public ClientLoaderException(String arg0, Throwable arg1)\n    {\n        super(arg0, arg1);\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/loader/CoreLoader.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.loader;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.metadata.model.CoreMetadata;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\nimport com.impetus.kundera.proxy.cglib.CglibLazyInitializerFactory;\r\n\r\n/**\r\n * The Class CoreLoader.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class CoreLoader\r\n{\r\n\r\n    /** The log. */\r\n    private static Logger log = LoggerFactory.getLogger(CoreLoader.class);\r\n\r\n    /**\r\n     * Load.\r\n     */\r\n    public void load(final KunderaMetadata kunderaMetadata)\r\n    {\r\n        log.info(\"Loading Kundera Core Metdata ... \");\r\n\r\n        CoreMetadata coreMetadata = new CoreMetadata();\r\n        coreMetadata.setLazyInitializerFactory(new CglibLazyInitializerFactory());\r\n        kunderaMetadata.setCoreMetadata(coreMetadata);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/loader/GenericClientFactory.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.loader;\r\n\r\nimport java.lang.reflect.Method;\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\nimport java.util.concurrent.ConcurrentHashMap;\r\nimport java.util.concurrent.ConcurrentMap;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.KunderaException;\r\nimport com.impetus.kundera.PersistenceProperties;\r\nimport com.impetus.kundera.client.Client;\r\nimport com.impetus.kundera.configure.PropertyReader;\r\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\r\nimport com.impetus.kundera.index.IndexManager;\r\nimport com.impetus.kundera.index.Indexer;\r\nimport com.impetus.kundera.index.IndexingConstants;\r\nimport com.impetus.kundera.metadata.model.ClientMetadata;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\nimport com.impetus.kundera.persistence.EntityReader;\r\nimport com.impetus.kundera.service.Host;\r\nimport com.impetus.kundera.service.policy.LoadBalancingPolicy;\r\nimport com.impetus.kundera.service.policy.RetryService;\r\nimport com.impetus.kundera.service.policy.RoundRobinBalancingPolicy;\r\nimport com.impetus.kundera.utils.InvalidConfigurationException;\r\n\r\n/**\r\n * Abstract class to hold generic definitions for client factory\r\n * implementations.\r\n * \r\n * @author vivek.mishra\r\n */\r\npublic abstract class GenericClientFactory implements ClientFactory, ClientLifeCycleManager\r\n{\r\n\r\n    /** The logger. */\r\n    private static Logger logger = LoggerFactory.getLogger(GenericClientFactory.class);\r\n\r\n    /** The client. */\r\n    private Client client;\r\n\r\n    /** The persistence unit. */\r\n    private String persistenceUnit;\r\n\r\n    /** The connection pool or connection. */\r\n    private Object connectionPoolOrConnection;\r\n\r\n    /** The reader. */\r\n    protected EntityReader reader;\r\n\r\n    /** Configure schema manager. */\r\n    protected SchemaManager schemaManager;\r\n\r\n    /** property reader instance */\r\n    protected PropertyReader propertyReader;\r\n\r\n    /** Holds persistence unit related property */\r\n    protected Map<String, Object> externalProperties = new HashMap<String, Object>();\r\n\r\n    /** Holds LoadBalancer instance **/\r\n    protected LoadBalancingPolicy loadBalancingPolicy = new RoundRobinBalancingPolicy();\r\n\r\n    /** Holds Instance of retry service */\r\n    protected RetryService hostRetryService;\r\n\r\n    /** Holds one pool instance per host */\r\n    protected ConcurrentMap<Host, Object> hostPools = new ConcurrentHashMap<Host, Object>();\r\n\r\n    /**\r\n     * Holds reference to client metadata.\r\n     */\r\n    protected ClientMetadata clientMetadata;\r\n\r\n    /** kundera metadata */\r\n    protected KunderaMetadata kunderaMetadata;\r\n\r\n    /** The index manager. */\r\n    protected IndexManager indexManager = new IndexManager(null, kunderaMetadata);\r\n\r\n    /**\r\n     * Load.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the persistence unit\r\n     */\r\n    @Override\r\n    public void load(String persistenceUnit, Map<String, Object> puProperties)\r\n    {\r\n        setPersistenceUnit(persistenceUnit);\r\n\r\n        // Load Client Specific Stuff\r\n        logger.info(\"Loading client metadata for persistence unit : \" + persistenceUnit);\r\n        loadClientMetadata(puProperties);\r\n\r\n        // initialize the client\r\n        logger.info(\"Initializing client for persistence unit : \" + persistenceUnit);\r\n        initialize(puProperties);\r\n\r\n        // Construct Pool\r\n        logger.info(\"Constructing pool for persistence unit : \" + persistenceUnit);\r\n        connectionPoolOrConnection = createPoolOrConnection();\r\n    }\r\n\r\n    /**\r\n     * Load client metadata.\r\n     * \r\n     * @param puProperties\r\n     */\r\n    protected void loadClientMetadata(Map<String, Object> puProperties)\r\n    {\r\n        clientMetadata = new ClientMetadata();\r\n        String luceneDirectoryPath = puProperties != null ? (String) puProperties\r\n                .get(PersistenceProperties.KUNDERA_INDEX_HOME_DIR) : null;\r\n\r\n        String indexerClass = puProperties != null ? (String) puProperties\r\n                .get(PersistenceProperties.KUNDERA_INDEXER_CLASS) : null;\r\n                \r\n        String autoGenClass = puProperties != null ? (String) puProperties\r\n                        .get(PersistenceProperties.KUNDERA_AUTO_GENERATOR_CLASS) : null;\r\n\r\n\r\n        if (indexerClass == null)\r\n        {\r\n            indexerClass = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit)\r\n                    .getProperties().getProperty(PersistenceProperties.KUNDERA_INDEXER_CLASS);\r\n        }\r\n        if (autoGenClass == null)\r\n        {\r\n            autoGenClass = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit)\r\n                    .getProperties().getProperty(PersistenceProperties.KUNDERA_AUTO_GENERATOR_CLASS);\r\n        }\r\n\r\n        if (luceneDirectoryPath == null)\r\n        {\r\n            luceneDirectoryPath = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit)\r\n                    .getProperty(PersistenceProperties.KUNDERA_INDEX_HOME_DIR);\r\n        }\r\n        \r\n        if (autoGenClass != null) \r\n        {\r\n            clientMetadata.setAutoGenImplementor(autoGenClass);    \r\n        }\r\n\r\n        // in case set empty via external property, means want to avoid lucene\r\n        // directory set up.\r\n        if (luceneDirectoryPath != null && !StringUtils.isEmpty(luceneDirectoryPath))\r\n        {\r\n            // Add client metadata\r\n            clientMetadata.setLuceneIndexDir(luceneDirectoryPath);\r\n\r\n            // Set Index Manager\r\n\r\n            try\r\n            {\r\n                Method method = Class.forName(IndexingConstants.LUCENE_INDEXER).getDeclaredMethod(\"getInstance\",\r\n                        String.class);\r\n\r\n                Indexer indexer = (Indexer) method.invoke(null, luceneDirectoryPath);\r\n                indexManager = new IndexManager(indexer, kunderaMetadata);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                logger.error(\r\n                        \"Missing lucene from classpath. Please make sure those are available to load lucene directory {}!\",\r\n                        luceneDirectoryPath);\r\n                throw new InvalidConfigurationException(e);\r\n            }\r\n\r\n            // indexManager = new IndexManager(LuceneIndexer.getInstance(new\r\n            // StandardAnalyzer(Version.LUCENE_CURRENT),\r\n            // luceneDirectoryPath));\r\n        }\r\n        else if (indexerClass != null)\r\n        {\r\n            try\r\n            {\r\n                Class<?> indexerClazz = Class.forName(indexerClass);\r\n                Indexer indexer = (Indexer) indexerClazz.newInstance();\r\n                indexManager = new IndexManager(indexer, kunderaMetadata);\r\n                clientMetadata.setIndexImplementor(indexerClass);\r\n            }\r\n            catch (Exception cnfex)\r\n            {\r\n                logger.error(\"Error while initialzing indexer:\" + indexerClass, cnfex);\r\n                throw new KunderaException(cnfex);\r\n            }\r\n        }\r\n        else\r\n        {\r\n            indexManager = new IndexManager(null, kunderaMetadata);\r\n        }\r\n        // if\r\n        // (kunderaMetadata.getClientMetadata(persistenceUnit)\r\n        // ==\r\n        // null)\r\n        // {\r\n        // kunderaMetadata.addClientMetadata(persistenceUnit,\r\n        // clientMetadata);\r\n        // }\r\n    }\r\n\r\n    /**\r\n     * Initialize client.\r\n     * \r\n     * @param puProperties\r\n     */\r\n    public abstract void initialize(Map<String, Object> puProperties);\r\n\r\n    /**\r\n     * Creates a new GenericClient object.\r\n     * \r\n     * @param externalProperties\r\n     * \r\n     * @return the object\r\n     */\r\n    protected abstract Object createPoolOrConnection();\r\n\r\n    /**\r\n     * Gets the client instance.\r\n     * \r\n     * @return the client instance\r\n     */\r\n    @Override\r\n    public Client getClientInstance()\r\n    {\r\n        // if threadsafe recycle the same single instance; if not create a new\r\n        // instance\r\n\r\n        if (isThreadSafe())\r\n        {\r\n            logger.info(\"Returning threadsafe used client instance for persistence unit : \" + persistenceUnit);\r\n            if (client == null)\r\n            {\r\n                client = instantiateClient(persistenceUnit);\r\n            }\r\n        }\r\n        else\r\n        {\r\n            logger.debug(\"Returning fresh client instance for persistence unit : \" + persistenceUnit);\r\n            // no need to hold a client reference.\r\n            return instantiateClient(persistenceUnit);\r\n        }\r\n\r\n        return client;\r\n    }\r\n\r\n    /**\r\n     * Instantiate client.\r\n     * \r\n     * @return the client\r\n     */\r\n    protected abstract Client instantiateClient(String persistenceUnit);\r\n\r\n    /**\r\n     * Checks if is client thread safe.\r\n     * \r\n     * @return true, if is client thread safe\r\n     */\r\n    public abstract boolean isThreadSafe();\r\n\r\n    /**\r\n     * Gets the persistence unit.\r\n     * \r\n     * @return the persistence unit\r\n     */\r\n    protected String getPersistenceUnit()\r\n    {\r\n        return persistenceUnit;\r\n    }\r\n\r\n    /**\r\n     * Gets the connection pool or connection.\r\n     * \r\n     * @return the connection pool or connection\r\n     */\r\n    protected Object getConnectionPoolOrConnection()\r\n    {\r\n        return connectionPoolOrConnection;\r\n    }\r\n\r\n    /**\r\n     * Sets the connection pool or connection.\r\n     */\r\n    protected void setConnectionPoolOrConnection(Object connectionPoolOrConnection)\r\n    {\r\n        this.connectionPoolOrConnection = connectionPoolOrConnection;\r\n    }\r\n\r\n    /**\r\n     * Sets the persistence unit.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the new persistence unit\r\n     */\r\n    private void setPersistenceUnit(String persistenceUnit)\r\n    {\r\n        this.persistenceUnit = persistenceUnit;\r\n    }\r\n\r\n    /**\r\n     * Sets the persistence unit.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the new persistence unit\r\n     */\r\n    protected void setKunderaMetadata(KunderaMetadata kunderaMetadata)\r\n    {\r\n        this.kunderaMetadata = kunderaMetadata;\r\n    }\r\n\r\n    /**\r\n     * @param puProperties\r\n     */\r\n    protected void setExternalProperties(Map<String, Object> puProperties)\r\n    {\r\n        if (puProperties != null)\r\n        {\r\n            this.externalProperties = puProperties;\r\n        }\r\n    }\r\n\r\n    protected void onValidation(final String host, final String port)\r\n    {\r\n        if (host == null || !StringUtils.isNumeric(port) || port.isEmpty())\r\n        {\r\n            logger.error(\"Host or port should not be null / port should be numeric\");\r\n            throw new IllegalArgumentException(\"Host or port should not be null / port should be numeric\");\r\n        }\r\n    }\r\n\r\n    protected void unload()\r\n    {\r\n        if (client != null)\r\n        {\r\n            client.close();\r\n            client = null;\r\n        }\r\n        externalProperties = null;\r\n        hostPools.clear();\r\n    }\r\n\r\n    protected abstract void initializeLoadBalancer(String loadBalancingPolicyName);\r\n\r\n    public ClientMetadata getClientMetadata()\r\n    {\r\n        return this.clientMetadata;\r\n    }\r\n\r\n    protected enum LoadBalancer\r\n    {\r\n        ROUNDROBIN, LEASTACTIVE;\r\n\r\n        public static LoadBalancer getValue(String loadBalancename)\r\n        {\r\n            if (loadBalancename != null && loadBalancename.equalsIgnoreCase(ROUNDROBIN.name()))\r\n            {\r\n                return ROUNDROBIN;\r\n            }\r\n            else if (loadBalancename != null && loadBalancename.equalsIgnoreCase(LEASTACTIVE.name()))\r\n            {\r\n                return LEASTACTIVE;\r\n            }\r\n            else\r\n            {\r\n                logger.info(\"Using default load balancer {} . \" + ROUNDROBIN.name());\r\n                return ROUNDROBIN;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/loader/KunderaAuthenticationException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.loader;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class KunderaAuthenticationException extends KunderaException\n{\n\n    /**\n     * \n     */\n    private static final long serialVersionUID = -708462011401566049L;\n\n    /**\n     * \n     */\n    public KunderaAuthenticationException()\n    {\n    }\n\n    /**\n     * @param arg0\n     */\n    public KunderaAuthenticationException(String arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     */\n    public KunderaAuthenticationException(Throwable arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     * @param arg1\n     */\n    public KunderaAuthenticationException(String arg0, Throwable arg1)\n    {\n        super(arg0, arg1);\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/loader/MetamodelLoaderException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.loader;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * @author amresh.singh\n * \n */\npublic class MetamodelLoaderException extends KunderaException\n{\n\n    /**\n     * \n     */\n    public MetamodelLoaderException()\n    {\n    }\n\n    /**\n     * @param arg0\n     */\n    public MetamodelLoaderException(String arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     */\n    public MetamodelLoaderException(Throwable arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     * @param arg1\n     */\n    public MetamodelLoaderException(String arg0, Throwable arg1)\n    {\n        super(arg0, arg1);\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/loader/PersistenceLoaderException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.loader;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PersistenceLoaderException extends KunderaException\n{\n\n    /**\n     * \n     */\n    private static final long serialVersionUID = -8108190222765147635L;\n\n    /**\n     * \n     */\n    public PersistenceLoaderException()\n    {\n    }\n\n    /**\n     * @param arg0\n     */\n    public PersistenceLoaderException(String arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     */\n    public PersistenceLoaderException(Throwable arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     * @param arg1\n     */\n    public PersistenceLoaderException(String arg0, Throwable arg1)\n    {\n        super(arg0, arg1);\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/loader/PersistenceXMLLoader.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.loader;\r\n\r\nimport java.io.File;\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.net.MalformedURLException;\r\nimport java.net.URL;\r\nimport java.net.URLConnection;\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.List;\r\n\r\nimport javax.persistence.PersistenceException;\r\nimport javax.persistence.spi.PersistenceUnitTransactionType;\r\nimport javax.xml.XMLConstants;\r\nimport javax.xml.parsers.DocumentBuilder;\r\nimport javax.xml.parsers.DocumentBuilderFactory;\r\nimport javax.xml.parsers.ParserConfigurationException;\r\nimport javax.xml.transform.dom.DOMSource;\r\nimport javax.xml.transform.stream.StreamSource;\r\nimport javax.xml.validation.Schema;\r\nimport javax.xml.validation.SchemaFactory;\r\nimport javax.xml.validation.Validator;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\nimport org.w3c.dom.Document;\r\nimport org.w3c.dom.Element;\r\nimport org.w3c.dom.Node;\r\nimport org.w3c.dom.NodeList;\r\nimport org.xml.sax.ErrorHandler;\r\nimport org.xml.sax.InputSource;\r\nimport org.xml.sax.SAXException;\r\nimport org.xml.sax.SAXParseException;\r\n\r\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\r\nimport com.impetus.kundera.utils.InvalidConfigurationException;\r\n\r\n/**\r\n * The Class PersistenceXMLLoader.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class PersistenceXMLLoader\r\n{\r\n    /** The log. */\r\n    private static Logger log = LoggerFactory.getLogger(PersistenceXMLLoader.class);\r\n\r\n    /**\r\n     * Instantiates a new persistence xml loader.\r\n     */\r\n    private PersistenceXMLLoader()\r\n    {\r\n    }\r\n\r\n    /**\r\n     * Reads the persistence xml content into an object graph and validates it\r\n     * against the related xsd schema.\r\n     * \r\n     * @param pathToPersistenceXml\r\n     *            path to the persistence.xml file\r\n     * @return parsed persistence xml as object graph\r\n     * @throws InvalidConfigurationException\r\n     *             if the file could not be parsed or is not valid against the\r\n     *             schema\r\n     */\r\n    private static Document getDocument(URL pathToPersistenceXml) throws InvalidConfigurationException\r\n    {\r\n        InputStream is = null;\r\n        Document xmlRootNode = null;\r\n\r\n        try\r\n        {\r\n            if (pathToPersistenceXml != null)\r\n            {\r\n                URLConnection conn = pathToPersistenceXml.openConnection();\r\n                conn.setUseCaches(false); // avoid JAR locking on Windows and\r\n                                          // Tomcat.\r\n                is = conn.getInputStream();\r\n            }\r\n\r\n            if (is == null)\r\n            {\r\n                throw new IOException(\"Failed to obtain InputStream from url: \" + pathToPersistenceXml);\r\n            }\r\n\r\n            xmlRootNode = parseDocument(is);\r\n            validateDocumentAgainstSchema(xmlRootNode);\r\n        }\r\n        catch (IOException e)\r\n        {\r\n            throw new InvalidConfigurationException(e);\r\n        }\r\n        finally\r\n        {\r\n            if (is != null)\r\n            {\r\n                try\r\n                {\r\n                    is.close();\r\n                }\r\n                catch (IOException ex)\r\n                {\r\n                    log.warn(\"Input stream could not be closed after parsing persistence.xml, caused by: {}\", ex);\r\n                }\r\n            }\r\n        }\r\n\r\n        return xmlRootNode;\r\n    }\r\n\r\n    /**\r\n     * Reads the content of the persistence.xml file into an object model, with\r\n     * the root node of type {@link Document}.\r\n     * \r\n     * @param is\r\n     *            {@link InputStream} of the persistence.xml content\r\n     * @return root node of the parsed xml content\r\n     * @throws InvalidConfigurationException\r\n     *             if the content could not be read due to an I/O error or could\r\n     *             not be parsedÏ\r\n     */\r\n    private static Document parseDocument(final InputStream is) throws InvalidConfigurationException\r\n    {\r\n        Document persistenceXmlDoc;\r\n        final List parsingErrors = new ArrayList();\r\n        final InputSource source = new InputSource(is);\r\n        final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();\r\n        docBuilderFactory.setNamespaceAware(true);\r\n\r\n        try\r\n        {\r\n            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();\r\n            docBuilder.setErrorHandler(new ErrorLogger(\"XML InputStream\", parsingErrors));\r\n            persistenceXmlDoc = docBuilder.parse(source);\r\n        }\r\n        catch (ParserConfigurationException e)\r\n        {\r\n            log.error(\"Error during parsing, Caused by: {}.\", e);\r\n            throw new PersistenceLoaderException(\"Error during parsing persistence.xml, caused by: \", e);\r\n        }\r\n        catch (IOException e)\r\n        {\r\n            throw new InvalidConfigurationException(\"Error reading persistence.xml, caused by: \", e);\r\n        }\r\n        catch (SAXException e)\r\n        {\r\n            throw new InvalidConfigurationException(\"Error parsing persistence.xml, caused by: \", e);\r\n        }\r\n\r\n        if (!parsingErrors.isEmpty())\r\n        {\r\n            throw new InvalidConfigurationException(\"Invalid persistence.xml\", (Throwable) parsingErrors.get(0));\r\n        }\r\n\r\n        return persistenceXmlDoc;\r\n    }\r\n\r\n    /**\r\n     * Validates an xml object graph against its schema. Therefore it reads the\r\n     * version from the root tag and tries to load the related xsd file from the\r\n     * classpath.\r\n     * \r\n     * @param xmlRootNode\r\n     *            root xml node of the document to validate\r\n     * @throws InvalidConfigurationException\r\n     *             if the validation could not be performed or the xml graph is\r\n     *             invalid against the schema\r\n     */\r\n    private static void validateDocumentAgainstSchema(final Document xmlRootNode) throws InvalidConfigurationException\r\n    {\r\n        final Element rootElement = xmlRootNode.getDocumentElement();\r\n        final String version = rootElement.getAttribute(\"version\");\r\n        String schemaFileName = \"persistence_\" + version.replace(\".\", \"_\") + \".xsd\";\r\n\r\n        try\r\n        {\r\n            final List validationErrors = new ArrayList();\r\n            final String schemaLanguage = XMLConstants.W3C_XML_SCHEMA_NS_URI;\r\n            final StreamSource streamSource = new StreamSource(getStreamFromClasspath(schemaFileName));\r\n            final Schema schemaDefinition = SchemaFactory.newInstance(schemaLanguage).newSchema(streamSource);\r\n\r\n            final Validator schemaValidator = schemaDefinition.newValidator();\r\n            schemaValidator.setErrorHandler(new ErrorLogger(\"XML InputStream\", validationErrors));\r\n            schemaValidator.validate(new DOMSource(xmlRootNode));\r\n\r\n            if (!validationErrors.isEmpty())\r\n            {\r\n                final String exceptionText = \"persistence.xml is not conform against the supported schema definitions.\";\r\n                throw new InvalidConfigurationException(exceptionText);\r\n            }\r\n        }\r\n        catch (SAXException e)\r\n        {\r\n            final String exceptionText = \"Error validating persistence.xml against schema defintion, caused by: \";\r\n            throw new InvalidConfigurationException(exceptionText, e);\r\n        }\r\n        catch (IOException e)\r\n        {\r\n            final String exceptionText = \"Error opening xsd schema file. The given persistence.xml descriptor version \"\r\n                    + version + \" might not be supported yet.\";\r\n            throw new InvalidConfigurationException(exceptionText, e);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Get stream from classpath.\r\n     * \r\n     * @param fileName\r\n     *            the file name\r\n     * @return the stream\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    private static InputStream getStreamFromClasspath(String fileName)\r\n    {\r\n        String path = fileName;\r\n        InputStream dtdStream = PersistenceXMLLoader.class.getClassLoader().getResourceAsStream(path);\r\n        return dtdStream;\r\n    }\r\n\r\n    /**\r\n     * Find persistence units.\r\n     * \r\n     * @param url\r\n     *            the url\r\n     * @return the list\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    public static List<PersistenceUnitMetadata> findPersistenceUnits(URL url, final String[] persistenceUnits)\r\n            throws Exception\r\n    {\r\n        return findPersistenceUnits(url, persistenceUnits, PersistenceUnitTransactionType.JTA);\r\n    }\r\n\r\n    /**\r\n     * Find persistence units.\r\n     * \r\n     * @param url\r\n     *            the url\r\n     * @param defaultTransactionType\r\n     *            the default transaction type\r\n     * @return the list\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    public static List<PersistenceUnitMetadata> findPersistenceUnits(final URL url, final String[] persistenceUnits,\r\n            PersistenceUnitTransactionType defaultTransactionType) throws InvalidConfigurationException\r\n    {\r\n        Document doc;\r\n        try\r\n        {\r\n            doc = getDocument(url);\r\n        }\r\n        catch (InvalidConfigurationException e)\r\n        {\r\n            throw e;\r\n        }\r\n        doc.getXmlVersion();\r\n        Element top = doc.getDocumentElement();\r\n\r\n        String versionName = top.getAttribute(\"version\");\r\n\r\n        NodeList children = top.getChildNodes();\r\n        ArrayList<PersistenceUnitMetadata> units = new ArrayList<PersistenceUnitMetadata>();\r\n\r\n        // parse for persistenceUnitRootInfoURL.\r\n        for (int i = 0; i < children.getLength(); i++)\r\n        {\r\n            if (children.item(i).getNodeType() == Node.ELEMENT_NODE)\r\n            {\r\n                Element element = (Element) children.item(i);\r\n                String tag = element.getTagName();\r\n                // look for \"persistence-unit\" element\r\n                if (tag.equals(\"persistence-unit\"))\r\n                {\r\n                    PersistenceUnitMetadata metadata = parsePersistenceUnit(url, persistenceUnits, element, versionName);\r\n                    if (metadata != null)\r\n                    {\r\n                        units.add(metadata);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        return units;\r\n    }\r\n\r\n    /**\r\n     * Parses the persistence unit.\r\n     * \r\n     * @param top\r\n     *            the top\r\n     * @return the persistence metadata\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    private static PersistenceUnitMetadata parsePersistenceUnit(final URL url, final String[] persistenceUnits,\r\n            Element top, final String versionName)\r\n    {\r\n        PersistenceUnitMetadata metadata = new PersistenceUnitMetadata(versionName, getPersistenceRootUrl(url), url);\r\n\r\n        String puName = top.getAttribute(\"name\");\r\n\r\n        if (!Arrays.asList(persistenceUnits).contains(puName))\r\n        {\r\n            // Returning null because this persistence unit is not intended for\r\n            // creating entity manager factory.\r\n            return null;\r\n        }\r\n\r\n        if (!isEmpty(puName))\r\n        {\r\n            log.trace(\"Persistent Unit name from persistence.xml: \" + puName);\r\n            metadata.setPersistenceUnitName(puName);\r\n            String transactionType = top.getAttribute(\"transaction-type\");\r\n            if (StringUtils.isEmpty(transactionType)\r\n                    || PersistenceUnitTransactionType.RESOURCE_LOCAL.name().equals(transactionType))\r\n            {\r\n                metadata.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);\r\n            }\r\n            else if (PersistenceUnitTransactionType.JTA.name().equals(transactionType))\r\n            {\r\n                metadata.setTransactionType(PersistenceUnitTransactionType.JTA);\r\n            }\r\n        }\r\n\r\n        NodeList children = top.getChildNodes();\r\n        for (int i = 0; i < children.getLength(); i++)\r\n        {\r\n            if (children.item(i).getNodeType() == Node.ELEMENT_NODE)\r\n            {\r\n                Element element = (Element) children.item(i);\r\n                String tag = element.getTagName();\r\n\r\n                if (tag.equals(\"provider\"))\r\n                {\r\n                    metadata.setProvider(getElementContent(element));\r\n                }\r\n                else if (tag.equals(\"properties\"))\r\n                {\r\n                    NodeList props = element.getChildNodes();\r\n                    for (int j = 0; j < props.getLength(); j++)\r\n                    {\r\n                        if (props.item(j).getNodeType() == Node.ELEMENT_NODE)\r\n                        {\r\n                            Element propElement = (Element) props.item(j);\r\n                            // if element is not \"property\" then skip\r\n                            if (!\"property\".equals(propElement.getTagName()))\r\n                            {\r\n                                continue;\r\n                            }\r\n\r\n                            String propName = propElement.getAttribute(\"name\").trim();\r\n                            String propValue = propElement.getAttribute(\"value\").trim();\r\n                            if (isEmpty(propValue))\r\n                            {\r\n                                propValue = getElementContent(propElement, \"\");\r\n                            }\r\n                            metadata.getProperties().put(propName, propValue);\r\n                        }\r\n                    }\r\n                }\r\n                else if (tag.equals(\"class\"))\r\n                {\r\n                    metadata.getClasses().add(getElementContent(element));\r\n                }\r\n                else if (tag.equals(\"jar-file\"))\r\n                {\r\n                    metadata.addJarFile(getElementContent(element));\r\n                }\r\n                else if (tag.equals(\"exclude-unlisted-classes\"))\r\n                {\r\n                    String excludeUnlisted = getElementContent(element);\r\n                    metadata.setExcludeUnlistedClasses(Boolean.parseBoolean(excludeUnlisted));\r\n                }\r\n            }\r\n        }\r\n        PersistenceUnitTransactionType transactionType = getTransactionType(top.getAttribute(\"transaction-type\"));\r\n        if (transactionType != null)\r\n        {\r\n            metadata.setTransactionType(transactionType);\r\n        }\r\n\r\n        return metadata;\r\n    }\r\n\r\n    /**\r\n     * Gets the transaction type.\r\n     * \r\n     * @param elementContent\r\n     *            the element content\r\n     * @return the transaction type\r\n     */\r\n    public static PersistenceUnitTransactionType getTransactionType(String elementContent)\r\n    {\r\n\r\n        if (elementContent == null || elementContent.isEmpty())\r\n        {\r\n            return null;\r\n        }\r\n        else if (elementContent.equalsIgnoreCase(\"JTA\"))\r\n        {\r\n            return PersistenceUnitTransactionType.JTA;\r\n        }\r\n        else if (elementContent.equalsIgnoreCase(\"RESOURCE_LOCAL\"))\r\n        {\r\n            return PersistenceUnitTransactionType.RESOURCE_LOCAL;\r\n        }\r\n        else\r\n        {\r\n            throw new PersistenceException(\"Unknown TransactionType: \" + elementContent);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * The Class ErrorLogger.\r\n     */\r\n    public static class ErrorLogger implements ErrorHandler\r\n    {\r\n\r\n        /** The file. */\r\n        private String file;\r\n\r\n        /** The errors. */\r\n        private List errors;\r\n\r\n        /**\r\n         * Instantiates a new error logger.\r\n         * \r\n         * @param file\r\n         *            the file\r\n         * @param errors\r\n         *            the errors\r\n         */\r\n        ErrorLogger(String file, List errors)\r\n        {\r\n            this.file = file;\r\n            this.errors = errors;\r\n        }\r\n\r\n        /* @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) */\r\n        /*\r\n         * (non-Javadoc)\r\n         * \r\n         * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)\r\n         */\r\n        public void error(SAXParseException error)\r\n        {\r\n            log.error(\"Error parsing XML: \" + file + '(' + error.getLineNumber() + \") \" + error.getMessage());\r\n            errors.add(error);\r\n        }\r\n\r\n        /*\r\n         * @see\r\n         * org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)\r\n         */\r\n        /*\r\n         * (non-Javadoc)\r\n         * \r\n         * @see\r\n         * org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)\r\n         */\r\n        public void fatalError(SAXParseException error)\r\n        {\r\n            log.error(\"Error parsing XML: \" + file + '(' + error.getLineNumber() + \") \" + error.getMessage());\r\n            errors.add(error);\r\n        }\r\n\r\n        /* @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) */\r\n        /*\r\n         * (non-Javadoc)\r\n         * \r\n         * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)\r\n         */\r\n        public void warning(SAXParseException warn)\r\n        {\r\n            log.warn(\"Warning parsing XML: \" + file + '(' + warn.getLineNumber() + \") \" + warn.getMessage());\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Checks if is empty.\r\n     * \r\n     * @param str\r\n     *            the str\r\n     * @return true, if is empty\r\n     */\r\n    private static boolean isEmpty(String str)\r\n    {\r\n        return null == str || str.isEmpty();\r\n    }\r\n\r\n    /**\r\n     * Gets the element content.\r\n     * \r\n     * @param element\r\n     *            the element\r\n     * @return the element content\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    public static String getElementContent(final Element element)\r\n    {\r\n        return getElementContent(element, null);\r\n    }\r\n\r\n    /**\r\n     * Get the content of the given element.\r\n     * \r\n     * @param element\r\n     *            The element to get the content for.\r\n     * @param defaultStr\r\n     *            The default to return when there is no content.\r\n     * @return The content of the element or the default.\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    private static String getElementContent(Element element, String defaultStr)\r\n    {\r\n        if (element == null)\r\n        {\r\n            return defaultStr;\r\n        }\r\n\r\n        NodeList children = element.getChildNodes();\r\n        StringBuilder result = new StringBuilder(\"\");\r\n        for (int i = 0; i < children.getLength(); i++)\r\n        {\r\n            if (children.item(i).getNodeType() == Node.TEXT_NODE\r\n                    || children.item(i).getNodeType() == Node.CDATA_SECTION_NODE)\r\n            {\r\n                result.append(children.item(i).getNodeValue());\r\n            }\r\n        }\r\n        return result.toString().trim();\r\n    }\r\n\r\n    /**\r\n     * Returns persistence unit root url\r\n     * \r\n     * @param url\r\n     *            raw url\r\n     * @return rootUrl rootUrl\r\n     */\r\n    private static URL getPersistenceRootUrl(URL url)\r\n    {\r\n        String f = url.getFile();\r\n        f = parseFilePath(f);\r\n\r\n        URL jarUrl = url;\r\n        try\r\n        {\r\n            if (AllowedProtocol.isJarProtocol(url.getProtocol()))\r\n            {\r\n                jarUrl = new URL(f);\r\n                if (jarUrl.getProtocol() != null\r\n                        && AllowedProtocol.FILE.name().equals(jarUrl.getProtocol().toUpperCase())\r\n                        && StringUtils.contains(f, \" \"))\r\n                {\r\n                    jarUrl = new File(f).toURI().toURL();\r\n                }\r\n            }\r\n            else if (AllowedProtocol.isValidProtocol(url.getProtocol()))\r\n            {\r\n                if (StringUtils.contains(f, \" \"))\r\n                {\r\n                    jarUrl = new File(f).toURI().toURL();\r\n                }\r\n                else\r\n                {\r\n                    jarUrl = new File(f).toURL();\r\n                }\r\n            }\r\n        }\r\n        catch (MalformedURLException mex)\r\n        {\r\n            log.error(\"Error during getPersistenceRootUrl(), Caused by: {}.\", mex);\r\n            throw new IllegalArgumentException(\"Invalid jar URL[] provided!\" + url);\r\n        }\r\n\r\n        return jarUrl;\r\n    }\r\n\r\n    /**\r\n     * Parse and exclude path till META-INF\r\n     * \r\n     * @param file\r\n     *            raw file path.\r\n     * @return extracted/parsed file path.\r\n     */\r\n    private static String parseFilePath(String file)\r\n    {\r\n        final String excludePattern = \"/META-INF/persistence.xml\";\r\n        file = file.substring(0, file.length() - excludePattern.length());\r\n\r\n        // in case protocol is \"file\".\r\n        file = file.endsWith(\"!\") ? file.substring(0, file.length() - 1) : file;\r\n\r\n        return file;\r\n    }\r\n\r\n    /**\r\n     * Allowed protocols\r\n     */\r\n    public enum AllowedProtocol\r\n    {\r\n        WSJAR, JAR, ZIP, FILE, VFSZIP, VFS;\r\n\r\n        /**\r\n         * In case it is jar protocol\r\n         * \r\n         * @param protocol\r\n         * @return\r\n         */\r\n        public static boolean isJarProtocol(String protocol)\r\n        {\r\n            return protocol != null\r\n                    && (protocol.toUpperCase().equals(JAR.name()) || protocol.toUpperCase().equals(WSJAR.name()));\r\n        }\r\n\r\n        /**\r\n         * If provided protocol is within allowed protocol.\r\n         * \r\n         * @param protocol\r\n         *            protocol\r\n         * @return true, if it is in allowed protocol.\r\n         */\r\n        public static boolean isValidProtocol(String protocol)\r\n        {\r\n            try\r\n            {\r\n                AllowedProtocol.valueOf(protocol.toUpperCase());\r\n                return true;\r\n            }\r\n            catch (IllegalArgumentException iex)\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/KunderaMetadataManager.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata;\r\n\r\nimport java.util.List;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.KunderaException;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\r\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\n\r\n/**\r\n * The Class KunderaMetadataManager.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class KunderaMetadataManager\r\n{\r\n\r\n    /** The log. */\r\n    private static Logger log = LoggerFactory.getLogger(KunderaMetadataManager.class);\r\n\r\n    /**\r\n     * Gets the persistence unit metadata.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the persistence unit\r\n     * @return the persistence unit metadata\r\n     */\r\n    public static PersistenceUnitMetadata getPersistenceUnitMetadata(final KunderaMetadata kunderaMetadata,\r\n            String persistenceUnit)\r\n    {\r\n        if (persistenceUnit != null && kunderaMetadata != null)\r\n        {\r\n            return kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit);\r\n        }\r\n        return null;\r\n    }\r\n\r\n    /**\r\n     * Gets the metamodel.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the persistence unit\r\n     * @return the metamodel\r\n     */\r\n    public static MetamodelImpl getMetamodel(final KunderaMetadata kunderaMetadata, String persistenceUnit)\r\n    {\r\n        MetamodelImpl metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\r\n                .getMetamodel(persistenceUnit);\r\n\r\n        return metamodel;\r\n    }\r\n\r\n    /**\r\n     * Gets the metamodel.\r\n     * \r\n     * @param persistenceUnits\r\n     *            the persistence units\r\n     * @return the metamodel\r\n     */\r\n    public static MetamodelImpl getMetamodel(final KunderaMetadata kunderaMetadata, String... persistenceUnits)\r\n    {\r\n        MetamodelImpl metamodel = null;\r\n        for (String pu : persistenceUnits)\r\n        {\r\n            metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(pu);\r\n\r\n            if (metamodel != null)\r\n            {\r\n                return metamodel;\r\n            }\r\n        }\r\n\r\n        // FIXME: I need to verify this why we need common entity metadata now!\r\n        // if (metamodel == null)\r\n        // {\r\n        // metamodel = (MetamodelImpl)\r\n        // kunderaMetadata.getApplicationMetadata().getMetamodel(\r\n        // Constants.COMMON_ENTITY_METADATAS);\r\n        // }\r\n        return metamodel;\r\n    }\r\n\r\n    /**\r\n     * Gets the entity metadata.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the persistence unit\r\n     * @param entityClass\r\n     *            the entity class\r\n     * @return the entity metadata\r\n     */\r\n    public static EntityMetadata getEntityMetadata(final KunderaMetadata kunderaMetadata, String persistenceUnit,\r\n            Class entityClass)\r\n    {\r\n        return getMetamodel(kunderaMetadata, persistenceUnit).getEntityMetadata(entityClass);\r\n    }\r\n\r\n    /**\r\n     * Finds ands returns Entity metadata for a given array of PUs.\r\n     * \r\n     * @param entityClass\r\n     *            the entity class\r\n     * @param persistenceUnits\r\n     *            the persistence units\r\n     * @return the entity metadata\r\n     */\r\n    public static EntityMetadata getEntityMetadata(final KunderaMetadata kunderaMetadata, Class entityClass)\r\n    {\r\n        if (entityClass == null)\r\n        {\r\n            throw new KunderaException(\"Invalid class provided \" + entityClass);\r\n        }\r\n        List<String> persistenceUnits = kunderaMetadata.getApplicationMetadata().getMappedPersistenceUnit(entityClass);\r\n\r\n        // persistence units will only have more than 1 persistence unit in case\r\n        // of RDBMS.\r\n        if (persistenceUnits != null)\r\n        {\r\n            for (String pu : persistenceUnits)\r\n            {\r\n                MetamodelImpl metamodel = getMetamodel(kunderaMetadata, pu);\r\n                EntityMetadata metadata = metamodel.getEntityMetadata(entityClass);\r\n                if (metadata != null && metadata.getPersistenceUnit().equals(pu))\r\n                {\r\n                    return metadata;\r\n                }\r\n            }\r\n        }\r\n        if (log.isDebugEnabled())\r\n            log.warn(\"No Entity metadata found for the class \" + entityClass\r\n                    + \". Any CRUD operation on this entity will fail.\"\r\n                    + \"If your entity is for RDBMS, make sure you put fully qualified entity class\"\r\n                    + \" name under <class></class> tag in persistence.xml for RDBMS \"\r\n                    + \"persistence unit. Returning null value.\");\r\n\r\n        return null;\r\n        // throw new KunderaException(\"Unable to load entity metadata for :\" +\r\n        // entityClass);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/MetadataBuilder.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.NamedNativeQueries;\r\nimport javax.persistence.NamedNativeQuery;\r\nimport javax.persistence.NamedQueries;\r\nimport javax.persistence.NamedQuery;\r\nimport javax.persistence.PersistenceException;\r\nimport javax.persistence.Table;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.PersistenceProperties;\r\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\r\nimport com.impetus.kundera.metadata.processor.CacheableAnnotationProcessor;\r\nimport com.impetus.kundera.metadata.processor.EntityListenersProcessor;\r\nimport com.impetus.kundera.metadata.processor.IndexProcessor;\r\nimport com.impetus.kundera.metadata.processor.TableProcessor;\r\nimport com.impetus.kundera.metadata.validator.EntityValidator;\r\nimport com.impetus.kundera.metadata.validator.EntityValidatorImpl;\r\nimport com.impetus.kundera.metadata.validator.InvalidEntityDefinitionException;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\n\r\n/**\r\n * Concrete implementation of IMetadataManager.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class MetadataBuilder\r\n{\r\n\r\n    /** the log used by this class. */\r\n    private static Logger log = LoggerFactory.getLogger(MetadataBuilder.class);\r\n\r\n    /** The metadata processors. */\r\n    private List<MetadataProcessor> metadataProcessors;\r\n\r\n    /** The Validator. */\r\n    private EntityValidator validator;\r\n\r\n    /** persistence unit */\r\n    private String persistenceUnit;\r\n\r\n    /** kundera client */\r\n    private String client;\r\n\r\n    private Map puProperties;\r\n\r\n    private KunderaMetadata kunderaMetadata;\r\n    /**\r\n     * Instantiates a new metadata manager.\r\n     * \r\n     */\r\n\r\n    public MetadataBuilder(String puName, String client, Map puProperties, KunderaMetadata kunderaMetadata)\r\n    {\r\n        this.persistenceUnit = puName;\r\n        this.client = client;\r\n        this.puProperties = puProperties;\r\n        this.validator = new EntityValidatorImpl(puProperties);\r\n        this.metadataProcessors = new ArrayList<MetadataProcessor>();\r\n        this.kunderaMetadata = kunderaMetadata;\r\n\r\n        // add processors to chain.\r\n        this.metadataProcessors.add(new TableProcessor(puProperties,kunderaMetadata));\r\n        this.metadataProcessors.add(new CacheableAnnotationProcessor());\r\n        this.metadataProcessors.add(new IndexProcessor(kunderaMetadata));\r\n        this.metadataProcessors.add(new EntityListenersProcessor());\r\n        \r\n    }\r\n\r\n    /**\r\n     * Validate.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     * \r\n     * @throws PersistenceException\r\n     *             the persistence exception\r\n     */\r\n    public final void validate(Class<?> clazz) throws PersistenceException\r\n    {\r\n        validator.validate(clazz);\r\n    }\r\n\r\n    /**\r\n     * Process.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     * @param externalProperties\r\n     * @return the entity metadata\r\n     */\r\n    public EntityMetadata buildEntityMetadata(Class<?> clazz)\r\n    {\r\n\r\n        EntityMetadata metadata = new EntityMetadata(clazz);\r\n      //  validate(clazz);\r\n\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"Processing @Entity >> \" + clazz);\r\n\r\n        for (MetadataProcessor processor : metadataProcessors)\r\n        {\r\n            // // in case it is not intend for current persistence unit.\r\n            // checkForRDBMS(metadata);\r\n            // checkForNeo4J(metadata);\r\n\r\n            setSchemaAndPU(clazz, metadata);\r\n\r\n            processor.process(clazz, metadata);\r\n            metadata = belongsToPersistenceUnit(metadata);\r\n            if (metadata == null)\r\n            {\r\n                break;\r\n            }\r\n\r\n            // Check for schema attribute of Table annotation.\r\n            if (MetadataUtils.isSchemaAttributeRequired(metadata.getPersistenceUnit(), kunderaMetadata)\r\n                    && StringUtils.isBlank(metadata.getSchema()))\r\n            {\r\n                if (log.isErrorEnabled())\r\n                {\r\n                    log.error(\"It is mandatory to specify Schema alongwith Table name:\" + metadata.getTableName()\r\n                            + \". This entity won't be persisted\");\r\n                }\r\n                throw new InvalidEntityDefinitionException(\"It is mandatory to specify Schema alongwith Table name:\"\r\n                        + metadata.getTableName() + \". This entity won't be persisted\");\r\n            }\r\n        }\r\n\r\n        return metadata;\r\n    }\r\n\r\n    /**\r\n     * If parameterised metadata is not for intended persistence unit, assign it\r\n     * to null.\r\n     * \r\n     * @param metadata\r\n     *            entity metadata\r\n     * @return metadata.\r\n     */\r\n    private EntityMetadata belongsToPersistenceUnit(EntityMetadata metadata)\r\n    {\r\n\r\n        // if pu is null and client is not rdbms OR metadata pu does not match\r\n        // with configured one. don't process for anything.\r\n\r\n        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata()\r\n                .getPersistenceUnitMetadata(persistenceUnit);\r\n        String keyspace = puProperties != null ? (String) puProperties.get(PersistenceProperties.KUNDERA_KEYSPACE):null;\r\n        \r\n        keyspace = keyspace == null ? puMetadata.getProperty(PersistenceProperties.KUNDERA_KEYSPACE):keyspace;\r\n\r\n        if (metadata.getPersistenceUnit() != null && !metadata.getPersistenceUnit().equals(persistenceUnit)\r\n                || (keyspace != null && metadata.getSchema() != null && !metadata.getSchema().equals(keyspace)))\r\n        {\r\n            metadata = null;\r\n        }\r\n        else\r\n        {\r\n            applyMetadataChanges(metadata);\r\n        }\r\n\r\n        /*\r\n         * if ((metadata.getPersistenceUnit() == null &&\r\n         * !(Constants.RDBMS_CLIENT_FACTORY.equalsIgnoreCase(client) ||\r\n         * Constants.NEO4J_CLIENT_FACTORY .equalsIgnoreCase(client))) ||\r\n         * metadata.getPersistenceUnit() != null &&\r\n         * !metadata.getPersistenceUnit().equals(persistenceUnit)) { metadata =\r\n         * null; }\r\n         */\r\n\r\n        return metadata;\r\n    }\r\n\r\n    private void applyMetadataChanges(EntityMetadata metadata)\r\n    {\r\n//        log.debug(\"In apply changes class is \" + metadata.getEntityClazz().getName());\r\n//        log.debug(\"In apply changes pu is \" + persistenceUnit);\r\n        metadata.setPersistenceUnit(persistenceUnit);\r\n        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata()\r\n                .getPersistenceUnitMetadata(persistenceUnit);\r\n        \r\n        String keyspace = puProperties != null ? (String) puProperties.get(PersistenceProperties.KUNDERA_KEYSPACE):null;\r\n        \r\n        keyspace = keyspace == null ? puMetadata.getProperty(PersistenceProperties.KUNDERA_KEYSPACE):keyspace;\r\n\r\n        // precedence to @Table annotation.\r\n        if (metadata.getSchema() == null)\r\n        {\r\n            metadata.setSchema(keyspace);\r\n        }\r\n        if (metadata.getTableName() == null)\r\n        {\r\n            metadata.setTableName(metadata.getEntityClazz().getSimpleName());\r\n        }\r\n    }\r\n\r\n    private void setSchemaAndPU(Class<?> clazz, EntityMetadata metadata)\r\n    {\r\n        Table table = clazz.getAnnotation(Table.class);\r\n        if (table != null)\r\n        {\r\n//            log.debug(\"In set schema and pu, class is \" + clazz.getName());\r\n            // Set Name of persistence object\r\n            metadata.setTableName(!StringUtils.isBlank(table.name()) ? \r\n                     table.name() : clazz.getSimpleName());\r\n            // Add named/native query related application metadata.\r\n            addNamedNativeQueryMetadata(clazz);\r\n            // set schema name and persistence unit name (if provided)\r\n            String schemaStr = table.schema();\r\n\r\n            MetadataUtils.setSchemaAndPersistenceUnit(metadata, schemaStr, puProperties);\r\n        }\r\n        if (metadata.getPersistenceUnit() == null)\r\n        {\r\n//            log.debug(\"In set schema and pu, pu is \" + persistenceUnit);\r\n            metadata.setPersistenceUnit(persistenceUnit);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Add named/native query annotated fields to application meta data.\r\n     * \r\n     * @param clazz\r\n     *            entity class.\r\n     */\r\n    private void addNamedNativeQueryMetadata(Class clazz)\r\n    {\r\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\r\n        String name, query = null;\r\n        if (clazz.isAnnotationPresent(NamedQuery.class))\r\n        {\r\n            NamedQuery ann = (NamedQuery) clazz.getAnnotation(NamedQuery.class);\r\n            appMetadata.addQueryToCollection(ann.name(), ann.query(), false, clazz);\r\n        }\r\n\r\n        if (clazz.isAnnotationPresent(NamedQueries.class))\r\n        {\r\n            NamedQueries ann = (NamedQueries) clazz.getAnnotation(NamedQueries.class);\r\n\r\n            NamedQuery[] anns = ann.value();\r\n            for (NamedQuery a : anns)\r\n            {\r\n                appMetadata.addQueryToCollection(a.name(), a.query(), false, clazz);\r\n            }\r\n        }\r\n\r\n        if (clazz.isAnnotationPresent(NamedNativeQuery.class))\r\n        {\r\n            NamedNativeQuery ann = (NamedNativeQuery) clazz.getAnnotation(NamedNativeQuery.class);\r\n            appMetadata.addQueryToCollection(ann.name(), ann.query(), true, clazz);\r\n        }\r\n\r\n        if (clazz.isAnnotationPresent(NamedNativeQueries.class))\r\n        {\r\n            NamedNativeQueries ann = (NamedNativeQueries) clazz.getAnnotation(NamedNativeQueries.class);\r\n\r\n            NamedNativeQuery[] anns = ann.value();\r\n            for (NamedNativeQuery a : anns)\r\n            {\r\n                appMetadata.addQueryToCollection(a.name(), a.query(), true, clazz);\r\n            }\r\n        }\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/MetadataProcessor.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata;\r\n\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\n\r\n/**\r\n * The Interface IMetadataProcessor.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic interface MetadataProcessor\r\n{\r\n\r\n    /**\r\n     * Process.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     * @param metadata\r\n     *            the metadata\r\n     * @param puProperties\r\n     */\r\n    void process(Class<?> clazz, EntityMetadata metadata);\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/MetadataUtils.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata;\r\n\r\nimport java.lang.reflect.Field;\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.Collection;\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\nimport java.util.StringTokenizer;\r\n\r\nimport javax.persistence.Embeddable;\r\nimport javax.persistence.Embedded;\r\nimport javax.persistence.PersistenceException;\r\nimport javax.persistence.metamodel.Attribute;\r\nimport javax.persistence.metamodel.EmbeddableType;\r\nimport javax.persistence.metamodel.EntityType;\r\nimport javax.persistence.metamodel.Metamodel;\r\nimport javax.validation.constraints.AssertFalse;\r\nimport javax.validation.constraints.AssertTrue;\r\nimport javax.validation.constraints.DecimalMax;\r\nimport javax.validation.constraints.DecimalMin;\r\nimport javax.validation.constraints.Digits;\r\nimport javax.validation.constraints.Future;\r\nimport javax.validation.constraints.Max;\r\nimport javax.validation.constraints.Min;\r\nimport javax.validation.constraints.NotNull;\r\nimport javax.validation.constraints.Null;\r\nimport javax.validation.constraints.Past;\r\nimport javax.validation.constraints.Pattern;\r\nimport javax.validation.constraints.Size;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\n\r\nimport com.impetus.kundera.Constants;\r\nimport com.impetus.kundera.PersistenceProperties;\r\nimport com.impetus.kundera.index.IndexCollection;\r\nimport com.impetus.kundera.metadata.model.ClientMetadata;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\r\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\r\nimport com.impetus.kundera.metadata.model.Relation;\r\nimport com.impetus.kundera.metadata.model.Relation.ForeignKey;\r\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\r\nimport com.impetus.kundera.metadata.validator.InvalidEntityDefinitionException;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\nimport com.impetus.kundera.property.PropertyAccessorHelper;\r\n\r\n/**\r\n * Utility class for entity metadata related funcntionality.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class MetadataUtils\r\n{\r\n\r\n    /**\r\n     * Populate column and super column maps.\r\n     * \r\n     * @param m\r\n     *            the m\r\n     * @param columnNameToFieldMap\r\n     *            the column name to field map\r\n     * @param superColumnNameToFieldMap\r\n     *            the super column name to field map\r\n     */\r\n    public static void populateColumnAndSuperColumnMaps(EntityMetadata m, Map<String, Field> columnNameToFieldMap,\r\n            Map<String, Field> superColumnNameToFieldMap, final KunderaMetadata kunderaMetadata)\r\n    {\r\n\r\n        getEmbeddableType(m, columnNameToFieldMap, superColumnNameToFieldMap, kunderaMetadata);\r\n    }\r\n\r\n    /**\r\n     * Creates the columns field map.\r\n     * \r\n     * @param m\r\n     *            the m\r\n     * @param superColumn\r\n     *            the super column\r\n     * @return the map\r\n     */\r\n    public static Map<String, Field> createColumnsFieldMap(EntityMetadata m, EmbeddableType superColumn)\r\n    {\r\n        Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();\r\n\r\n        Set<Attribute> attributes = superColumn.getAttributes();\r\n        for (Attribute column : attributes)\r\n        {\r\n            columnNameToFieldMap.put(((AbstractAttribute) column).getJPAColumnName(), (Field) column.getJavaMember());\r\n        }\r\n        return columnNameToFieldMap;\r\n    }\r\n\r\n    /**\r\n     * Creates the super columns field map.\r\n     * \r\n     * @param m\r\n     *            the m\r\n     * @return the map\r\n     */\r\n    public static Map<String, Field> createSuperColumnsFieldMap(final EntityMetadata m,\r\n            final KunderaMetadata kunderaMetadata)\r\n    {\r\n        Map<String, Field> superColumnNameToFieldMap = new HashMap<String, Field>();\r\n        getEmbeddableType(m, null, superColumnNameToFieldMap, kunderaMetadata);\r\n        return superColumnNameToFieldMap;\r\n    }\r\n\r\n    /**\r\n     * Gets the embedded collection instance.\r\n     * \r\n     * @param embeddedCollectionField\r\n     *            the embedded collection field\r\n     * @return the embedded collection instance\r\n     */\r\n    public static Collection getEmbeddedCollectionInstance(Field embeddedCollectionField)\r\n    {\r\n        Collection embeddedCollection = null;\r\n        Class embeddedCollectionFieldClass = embeddedCollectionField.getType();\r\n\r\n        if (embeddedCollection == null || embeddedCollection.isEmpty())\r\n        {\r\n            if (embeddedCollectionFieldClass.equals(List.class))\r\n            {\r\n                embeddedCollection = new ArrayList<Object>();\r\n            }\r\n            else if (embeddedCollectionFieldClass.equals(Set.class))\r\n            {\r\n                embeddedCollection = new HashSet<Object>();\r\n            }\r\n            else\r\n            {\r\n                throw new InvalidEntityDefinitionException(\"Field \" + embeddedCollectionField.getName()\r\n                        + \" must be either instance of List or Set\");\r\n            }\r\n        }\r\n        return embeddedCollection;\r\n    }\r\n\r\n    /**\r\n     * Gets the embedded generic object instance.\r\n     * \r\n     * @param embeddedCollectionField\r\n     *            the embedded collection field\r\n     * @return the embedded generic object instance\r\n     */\r\n    public static Object getEmbeddedGenericObjectInstance(Field embeddedCollectionField)\r\n    {\r\n        Class<?> embeddedClass = PropertyAccessorHelper.getGenericClass(embeddedCollectionField);\r\n        Object embeddedObject = null;\r\n        // must have a default no-argument constructor\r\n        try\r\n        {\r\n            embeddedClass.getConstructor();\r\n            embeddedObject = embeddedClass.newInstance();\r\n        }\r\n        catch (NoSuchMethodException nsme)\r\n        {\r\n            throw new PersistenceException(embeddedClass.getName()\r\n                    + \" is @Embeddable and must have a default no-argument constructor.\");\r\n        }\r\n        catch (InstantiationException e)\r\n        {\r\n            throw new PersistenceException(embeddedClass.getName() + \" could not be instantiated\");\r\n        }\r\n\r\n        catch (IllegalAccessException e)\r\n        {\r\n            throw new PersistenceException(embeddedClass.getName() + \" could not be accessed\");\r\n        }\r\n        return embeddedObject;\r\n    }\r\n\r\n    /**\r\n     * Gets the embedded collection prefix.\r\n     * \r\n     * @param embeddedCollectionName\r\n     *            the embedded collection name\r\n     * @return the embedded collection prefix\r\n     */\r\n    public static String getEmbeddedCollectionPrefix(String embeddedCollectionName)\r\n    {\r\n        return embeddedCollectionName.substring(0,\r\n                embeddedCollectionName.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER));\r\n    }\r\n\r\n    /**\r\n     * Gets the embedded collection postfix.\r\n     * \r\n     * @param embeddedCollectionName\r\n     *            the embedded collection name\r\n     * @return the embedded collection postfix\r\n     */\r\n    public static String getEmbeddedCollectionPostfix(String embeddedCollectionName)\r\n    {\r\n        return embeddedCollectionName.substring(\r\n                embeddedCollectionName.lastIndexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) + 1,\r\n                embeddedCollectionName.length());\r\n    }\r\n\r\n    /**\r\n     * Creates a string representation of a set of foreign keys by combining\r\n     * them together separated by \"~\" character.\r\n     * \r\n     * Note: Assumption is that @Id will never contain \"~\" character. Checks for\r\n     * this are not added yet.\r\n     * \r\n     * @param foreignKeys\r\n     *            the foreign keys\r\n     * @return the string\r\n     */\r\n    public static String serializeKeys(Set<String> foreignKeys)\r\n    {\r\n        if (null == foreignKeys || foreignKeys.isEmpty())\r\n        {\r\n            return null;\r\n        }\r\n\r\n        StringBuilder sb = new StringBuilder();\r\n        for (String key : foreignKeys)\r\n        {\r\n            if (sb.length() > 0)\r\n            {\r\n                sb.append(Constants.FOREIGN_KEY_SEPARATOR);\r\n            }\r\n            sb.append(key);\r\n        }\r\n        return sb.toString();\r\n    }\r\n\r\n    /**\r\n     * Splits foreign keys into Set.\r\n     * \r\n     * @param foreignKeys\r\n     *            the foreign keys\r\n     * @return the set\r\n     */\r\n    public static Set<String> deserializeKeys(String foreignKeys)\r\n    {\r\n        Set<String> keys = new HashSet<String>();\r\n\r\n        if (null == foreignKeys || foreignKeys.isEmpty())\r\n        {\r\n            return keys;\r\n        }\r\n\r\n        String array[] = foreignKeys.split(Constants.FOREIGN_KEY_SEPARATOR);\r\n        for (String element : array)\r\n        {\r\n            keys.add(element);\r\n        }\r\n        return keys;\r\n    }\r\n\r\n    /**\r\n     * Sets the schema and persistence unit.\r\n     * \r\n     * @param m\r\n     *            the m\r\n     * @param schemaStr\r\n     *            the schema str\r\n     * @param puProperties\r\n     */\r\n    public static void setSchemaAndPersistenceUnit(EntityMetadata m, String schemaStr, Map puProperties)\r\n    {\r\n\r\n        if (schemaStr.indexOf(Constants.SCHEMA_PERSISTENCE_UNIT_SEPARATOR) > 0)\r\n        {\r\n            String schemaName = null;\r\n            if (puProperties != null)\r\n            {\r\n                schemaName = (String) puProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);\r\n            }\r\n            if (schemaName == null)\r\n            {\r\n                schemaName = schemaStr.substring(0, schemaStr.indexOf(Constants.SCHEMA_PERSISTENCE_UNIT_SEPARATOR));\r\n            }\r\n            m.setSchema(schemaName);\r\n            m.setPersistenceUnit(schemaStr.substring(\r\n                    schemaStr.indexOf(Constants.SCHEMA_PERSISTENCE_UNIT_SEPARATOR) + 1, schemaStr.length()));\r\n        }\r\n        else\r\n        {\r\n            m.setSchema(StringUtils.isBlank(schemaStr) ? null : schemaStr);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Returns true, if use of secondry index is available, else false.\r\n     * \r\n     * @param persistenceUnit\r\n     *            persistence unit name\r\n     * @return true, if usage is true in pu. else false.\r\n     */\r\n    public static boolean useSecondryIndex(ClientMetadata clientMetadata)\r\n    {\r\n        return clientMetadata != null ? clientMetadata.isUseSecondryIndex() : false;\r\n    }\r\n\r\n    /* *//**\r\n     * Returns lucene indexing directory.\r\n     * \r\n     * @param persistenceUnit\r\n     *            persistence unit name\r\n     * @return lucene directory\r\n     */\r\n    /*\r\n     * public static String getLuceneDirectory(String persistenceUnit) { if\r\n     * (!useSecondryIndex(persistenceUnit)) { ClientMetadata clientMetadata =\r\n     * kunderaMetadata.getClientMetadata(persistenceUnit); return\r\n     * clientMetadata.getLuceneIndexDir(); }\r\n     * \r\n     * return null; }\r\n     */\r\n\r\n    /**\r\n     * Returns mapped relational name, in case of bi directional mapping, it\r\n     * will return back pKey name of associated entity.\r\n     * \r\n     * @param relation\r\n     *            holding relation.\r\n     * @return mapped/join column name.\r\n     */\r\n    public static String getMappedName(EntityMetadata parentMetadata, Relation relation,\r\n            final KunderaMetadata kunderaMetadata)\r\n    {\r\n        if (relation != null)\r\n        {\r\n            String joinColumn = relation.getJoinColumnName(kunderaMetadata);\r\n            if (joinColumn == null)\r\n            {\r\n                Class clazz = relation.getTargetEntity();\r\n                EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\r\n\r\n                joinColumn = relation.getType().equals(ForeignKey.ONE_TO_MANY) ? ((AbstractAttribute) parentMetadata\r\n                        .getIdAttribute()).getJPAColumnName() : ((AbstractAttribute) metadata.getIdAttribute())\r\n                        .getJPAColumnName();\r\n            }\r\n            return joinColumn;\r\n        }\r\n        return null;\r\n    }\r\n\r\n    /**\r\n     * Gets the enclosing document name.\r\n     * \r\n     * @param m\r\n     *            the m\r\n     * @param criteria\r\n     *            Input criteria\r\n     * @param viaColumnName\r\n     *            true if <code>criteria</code> is column Name, false if\r\n     *            <code>criteria</code> is column field name\r\n     * @return the enclosing document name\r\n     */\r\n    public static String getEnclosingEmbeddedFieldName(EntityMetadata m, String criteria, boolean viaColumnName,\r\n            final KunderaMetadata kunderaMetadata)\r\n    {\r\n        String enclosingEmbeddedFieldName = null;\r\n\r\n        StringTokenizer strToken = new StringTokenizer(criteria, \".\");\r\n        String embeddableAttributeName = null;\r\n        String embeddedFieldName = null;\r\n        String nestedEmbeddedFieldName = null;\r\n\r\n        if (strToken.countTokens() > 0)\r\n        {\r\n            embeddableAttributeName = strToken.nextToken();\r\n        }\r\n        if (strToken.countTokens() > 0)\r\n        {\r\n            embeddedFieldName = strToken.nextToken();\r\n        }\r\n        if (strToken.countTokens() > 0)\r\n        {\r\n            nestedEmbeddedFieldName = strToken.nextToken();\r\n        }\r\n\r\n        Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());\r\n        EntityType entity = metaModel.entity(m.getEntityClazz());\r\n\r\n        try\r\n        {\r\n            Attribute attribute = entity.getAttribute(embeddableAttributeName);\r\n\r\n            if (((MetamodelImpl) metaModel).isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType()))\r\n            {\r\n                EmbeddableType embeddable = metaModel.embeddable(((AbstractAttribute) attribute).getBindableJavaType());\r\n                Iterator<Attribute> attributeIter = embeddable.getAttributes().iterator();\r\n                while (attributeIter.hasNext())\r\n                {\r\n                    AbstractAttribute attrib = (AbstractAttribute) attributeIter.next();\r\n\r\n                    if (viaColumnName && attrib.getName().equals(embeddedFieldName))\r\n                    {\r\n                        if (nestedEmbeddedFieldName != null\r\n                                && ((MetamodelImpl) metaModel).isEmbeddable(((AbstractAttribute) attrib)\r\n                                        .getBindableJavaType()))\r\n                        {\r\n                            EmbeddableType nestedEmbeddable = metaModel.embeddable(((AbstractAttribute) attrib)\r\n                                    .getBindableJavaType());\r\n                            Iterator<Attribute> iter = embeddable.getAttributes().iterator();\r\n                            while (iter.hasNext())\r\n                            {\r\n                                AbstractAttribute nestedAttribute = (AbstractAttribute) iter.next();\r\n\r\n                                if (viaColumnName && nestedAttribute.getName().equals(embeddedFieldName))\r\n                                {\r\n                                    return nestedAttribute.getName();\r\n                                }\r\n\r\n                                if (!viaColumnName && nestedAttribute.getJPAColumnName().equals(embeddedFieldName))\r\n                                {\r\n                                    return nestedAttribute.getName();\r\n                                }\r\n                            }\r\n                        }\r\n                        else if (nestedEmbeddedFieldName != null\r\n                                && !((MetamodelImpl) metaModel).isEmbeddable(((AbstractAttribute) attrib)\r\n                                        .getBindableJavaType()))\r\n                        {\r\n                            return null;\r\n                        }\r\n                        else\r\n                        {\r\n                            return attribute.getName();\r\n                        }\r\n                    }\r\n\r\n                    if (!viaColumnName && attrib.getJPAColumnName().equals(embeddedFieldName))\r\n                    {\r\n                        return attribute.getName();\r\n                    }\r\n                }\r\n            }\r\n\r\n        }\r\n        catch (IllegalArgumentException iax)\r\n        {\r\n            return null;\r\n        }\r\n        return enclosingEmbeddedFieldName;\r\n    }\r\n\r\n    private static void getEmbeddableType(EntityMetadata m, Map<String, Field> columnNameToFieldMap,\r\n            Map<String, Field> superColumnNameToFieldMap, final KunderaMetadata kunderaMetadata)\r\n    {\r\n        Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());\r\n\r\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\r\n\r\n        Set attributes = entityType.getAttributes();\r\n        Iterator<Attribute> iter = attributes.iterator();\r\n        while (iter.hasNext())\r\n        {\r\n            Attribute attribute = iter.next();\r\n            if (((MetamodelImpl) metaModel).isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType()))\r\n            {\r\n                superColumnNameToFieldMap.put(((AbstractAttribute) attribute).getJPAColumnName(),\r\n                        (Field) attribute.getJavaMember());\r\n                if (columnNameToFieldMap != null)\r\n                {\r\n                    getAttributeOfEmbedddable(columnNameToFieldMap, metaModel, attribute);\r\n                }\r\n\r\n            }\r\n            else\r\n            {\r\n                if (columnNameToFieldMap != null)\r\n                {\r\n                    columnNameToFieldMap.put(((AbstractAttribute) attribute).getJPAColumnName(),\r\n                            (Field) attribute.getJavaMember());\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    private static void getAttributeOfEmbedddable(Map<String, Field> columnNameToFieldMap, Metamodel metaModel,\r\n            Attribute attribute)\r\n    {\r\n        EmbeddableType embeddable = metaModel.embeddable(((AbstractAttribute) attribute).getBindableJavaType());\r\n\r\n        Iterator<Attribute> embeddableIter = embeddable.getAttributes().iterator();\r\n        while (embeddableIter.hasNext())\r\n        {\r\n            Attribute embedAttrib = embeddableIter.next();\r\n\r\n            // Reason is to avoid in case embeddable attribute within\r\n            // embeddable.\r\n            if (!((MetamodelImpl) metaModel).isEmbeddable(embedAttrib.getJavaType()))\r\n            {\r\n                columnNameToFieldMap.put(((AbstractAttribute) embedAttrib).getJPAColumnName(),\r\n                        (Field) embedAttrib.getJavaMember());\r\n            }\r\n            else\r\n            {\r\n                getAttributeOfEmbedddable(columnNameToFieldMap, metaModel, embedAttrib);\r\n            }\r\n        }\r\n    }\r\n\r\n    public static boolean isEmbeddedAtributeIndexable(Field embeddedField)\r\n    {\r\n        Class<?> embeddableClass = PropertyAccessorHelper.getGenericClass(embeddedField);\r\n    \r\n        IndexCollection indexCollection = embeddableClass.getAnnotation(IndexCollection.class);\r\n        if (indexCollection != null && indexCollection.columns() != null)\r\n        {\r\n            return true;\r\n        }\r\n      \r\n        return false;\r\n    }\r\n\r\n    public static boolean isColumnInEmbeddableIndexable(Field embeddedField, String columnFieldName)\r\n    {\r\n        Class<?> embeddableClass = PropertyAccessorHelper.getGenericClass(embeddedField);\r\n       \r\n        IndexCollection indexCollection = embeddableClass.getAnnotation(IndexCollection.class);\r\n        if (indexCollection != null && indexCollection.columns() != null)\r\n        {\r\n            for (com.impetus.kundera.index.Index column : indexCollection.columns())\r\n            {\r\n                if (columnFieldName != null && column != null && column.name() != null\r\n                        && column.name().equals(columnFieldName))\r\n                {\r\n                    return true;\r\n                }\r\n            }\r\n        }\r\n     \r\n        return false;\r\n    }\r\n\r\n    /**\r\n     * If client specific to parameterized persistence unit does not support\r\n     * transaction, return true else will return false.\r\n     * \r\n     * @param persistenceUnit\r\n     * @return\r\n     */\r\n    public static boolean defaultTransactionSupported(final String persistenceUnit,\r\n            final KunderaMetadata kunderaMetadata)\r\n    {\r\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\r\n                persistenceUnit);\r\n\r\n        String txResource = puMetadata.getProperty(PersistenceProperties.KUNDERA_TRANSACTION_RESOURCE);\r\n\r\n        if (txResource == null)\r\n        {\r\n            return true;\r\n        }\r\n        else if (txResource.isEmpty())\r\n        {\r\n            throw new IllegalArgumentException(\"Property \" + PersistenceProperties.KUNDERA_TRANSACTION_RESOURCE\r\n                    + \" is blank\");\r\n        }\r\n        else\r\n        {\r\n            return false;\r\n        }\r\n    }\r\n\r\n    public static boolean isSchemaAttributeRequired(final String persistenceUnit, final KunderaMetadata kunderaMetadata)\r\n    {\r\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\r\n                persistenceUnit);\r\n        String clientFactoryName = puMetadata != null ? puMetadata\r\n                .getProperty(PersistenceProperties.KUNDERA_CLIENT_FACTORY) : null;\r\n        return !(Constants.NEO4J_CLIENT_FACTORY.equalsIgnoreCase(clientFactoryName) || Constants.RDBMS_CLIENT_FACTORY\r\n                .equalsIgnoreCase(clientFactoryName));\r\n    }\r\n\r\n    /**\r\n     * Index based search has to be optional, ideally need to register a\r\n     * callback in case index persistence/search etc is optional.\r\n     * \r\n     * @param persistenceUnit\r\n     *            persistence unit\r\n     * \r\n     * @return true, if index based search is enabled.\r\n     */\r\n    public static boolean indexSearchEnabled(final String persistenceUnit, final KunderaMetadata kunderaMetadata)\r\n    {\r\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\r\n                persistenceUnit);\r\n        String clientFactoryName = puMetadata != null ? puMetadata\r\n                .getProperty(PersistenceProperties.KUNDERA_CLIENT_FACTORY) : null;\r\n        return !(Constants.REDIS_CLIENT_FACTORY.equalsIgnoreCase(clientFactoryName));\r\n\r\n    }\r\n\r\n    /**\r\n     * Checks whether a given field is Element collection field of BASIC type\r\n     * \r\n     * @param collectionField\r\n     * @return\r\n     */\r\n    public static boolean isBasicElementCollectionField(Field collectionField)\r\n    {\r\n        if (!Collection.class.isAssignableFrom(collectionField.getType())\r\n                && !Map.class.isAssignableFrom(collectionField.getType()))\r\n        {\r\n            return false;\r\n        }\r\n\r\n        List<Class<?>> genericClasses = PropertyAccessorHelper.getGenericClasses(collectionField);\r\n        for (Class genericClass : genericClasses)\r\n        {\r\n            if (genericClass.getAnnotation(Embeddable.class) != null)\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n        return true;\r\n    }\r\n\r\n    /**\r\n     * Checks whether an entity with given metadata contains a collection field\r\n     * \r\n     * @param m\r\n     * @return\r\n     */\r\n    public static boolean containsBasicElementCollectionField(final EntityMetadata m,\r\n            final KunderaMetadata kunderaMetadata)\r\n    {\r\n        Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());\r\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\r\n        Iterator<Attribute> iter = entityType.getAttributes().iterator();\r\n        while (iter.hasNext())\r\n        {\r\n            Attribute attr = iter.next();\r\n\r\n            if (attr.isCollection() && !attr.isAssociation()\r\n                    && isBasicElementCollectionField((Field) attr.getJavaMember()))\r\n            {\r\n                return true;\r\n            }\r\n        }\r\n        return false;\r\n    }\r\n\r\n    public static void onJPAColumnMapping(final EntityType entityType, EntityMetadata entityMetadata)\r\n    {\r\n        Set<Attribute> attributes = entityType.getAttributes();\r\n\r\n        Iterator<Attribute> iter = attributes.iterator();\r\n\r\n        while (iter.hasNext())\r\n        {\r\n            Attribute attribute = iter.next();\r\n\r\n            // jpa column mapping is for non id columns only.\r\n            if (!entityMetadata.getIdAttribute().equals(attribute))\r\n            {\r\n                entityMetadata.addJPAColumnMapping(((AbstractAttribute) attribute).getJPAColumnName(),\r\n                        attribute.getName());\r\n            }\r\n        }\r\n\r\n        entityMetadata.setEntityType(entityType);\r\n    }\r\n\r\n    /**\r\n     * Returns true if an entity contains attributes with validation constraints\r\n     * enabled\r\n     * \r\n     * @param attribute\r\n     * @return\r\n     */\r\n    public static boolean onCheckValidationConstraints(Field attribute)\r\n    {\r\n        // / Checks if attribute contains any validation constraint enabled\r\n        return attribute.isAnnotationPresent(AssertFalse.class) || attribute.isAnnotationPresent(AssertTrue.class)\r\n                || attribute.isAnnotationPresent(DecimalMax.class) || attribute.isAnnotationPresent(DecimalMin.class)\r\n                || attribute.isAnnotationPresent(Digits.class) || attribute.isAnnotationPresent(Future.class)\r\n                || attribute.isAnnotationPresent(Max.class) || attribute.isAnnotationPresent(Min.class)\r\n                || attribute.isAnnotationPresent(NotNull.class) || attribute.isAnnotationPresent(Null.class)\r\n                || attribute.isAnnotationPresent(Past.class) || attribute.isAnnotationPresent(Pattern.class)\r\n                || attribute.isAnnotationPresent(Size.class);\r\n\r\n    }\r\n    \r\n    /**\r\n     * Returns true if an entity contains embedded attribute\r\n     * enabled\r\n     * \r\n     * @param attribute\r\n     * @return\r\n     */\r\n    public static boolean onCheckEmbeddableAttribute(Field attribute)\r\n    {\r\n        // / Checks if attribute is embeddable\r\n        return attribute.isAnnotationPresent(Embedded.class) ;\r\n\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/ApplicationLoaderException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model;\n\n/**\n * Runtime exception handler class ApplicationLoader.\n * \n * @author vivek.mishra\n * \n */\npublic class ApplicationLoaderException extends RuntimeException\n{\n\n    /**\n     * Generated Serial version UID.\n     */\n    private static final long serialVersionUID = 2139307646040466455L;\n\n    /**\n     * Default constructor using fields.\n     * \n     * @param errMsg\n     *            error message.\n     */\n    public ApplicationLoaderException(String errMsg)\n    {\n        super(errMsg);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/ApplicationMetadata.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.model;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Properties;\r\nimport java.util.Set;\r\nimport java.util.concurrent.ConcurrentHashMap;\r\n\r\nimport javax.persistence.metamodel.Metamodel;\r\nimport javax.persistence.spi.PersistenceUnitTransactionType;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.metadata.processor.MetaModelBuilder;\r\n\r\n/**\r\n * Application metadata refers to metdata specific to application(e.g. metamodel\r\n * collection, persistence unit metdatas) Any reference which is out of\r\n * persistence unit metadata and entity specific metadata is held by this class.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class ApplicationMetadata\r\n{\r\n    /** Map of Entity Metadata. */\r\n    private Map<String, Metamodel> metamodelMap = new ConcurrentHashMap<String, Metamodel>();\r\n\r\n    /** Map of Persistence Unit Metadata. */\r\n    private Map<String, PersistenceUnitMetadata> persistenceUnitMetadataMap = new ConcurrentHashMap<String, PersistenceUnitMetadata>();\r\n\r\n    /** The Constant log. */\r\n    private static Logger logger = LoggerFactory.getLogger(ApplicationMetadata.class);\r\n\r\n    // private MetaModelBuilder metaModelBuilder = new MetaModelBuilder();\r\n\r\n    private Map<String, MetaModelBuilder> metaModelBuilder = new ConcurrentHashMap<String, MetaModelBuilder>();\r\n\r\n    /**\r\n     * Collection instance to hold clazz's full name to persistence unit\r\n     * mapping. Valid Assumption: 1 class can belong to 1 pu only. Reason is @table\r\n     * needs to give pu name!\r\n     */\r\n    private Map<String, List<String>> clazzToPuMap;\r\n\r\n    private Map<String, QueryWrapper> namedNativeQueries;\r\n\r\n    /**\r\n     * Adds the entity metadata.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the persistence unit\r\n     * @param clazz\r\n     *            the clazz\r\n     * @param entityMetadata\r\n     *            the entity metadata\r\n     */\r\n    public void addEntityMetadata(String persistenceUnit, Class<?> clazz, EntityMetadata entityMetadata)\r\n    {\r\n        Metamodel metamodel = getMetamodelMap().get(persistenceUnit);\r\n        Map<String, EntityMetadata> entityClassToMetadataMap = ((MetamodelImpl) metamodel).getEntityMetadataMap();\r\n        if (entityClassToMetadataMap == null || entityClassToMetadataMap.isEmpty())\r\n        {\r\n            entityClassToMetadataMap.put(clazz.getName(), entityMetadata);\r\n        }\r\n        else\r\n        {\r\n            if (logger.isDebugEnabled())\r\n                logger.debug(\"Entity meta model already exists for persistence unit \" + persistenceUnit + \" and class \"\r\n                        + clazz + \". Noting needs to be done\");\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Adds the persistence unit metadata.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the persistence unit\r\n     * @param persistenceUnitMetadata\r\n     *            the persistence unit metadata\r\n     */\r\n    public void addPersistenceUnitMetadata(Map<String, PersistenceUnitMetadata> metadata)\r\n    {\r\n        getPersistenceUnitMetadataMap().putAll(metadata);\r\n    }\r\n\r\n    /**\r\n     * Gets the metamodel map.\r\n     * \r\n     * @return the entityMetadataMap\r\n     */\r\n    public Map<String, Metamodel> getMetamodelMap()\r\n    {\r\n        if (metamodelMap == null)\r\n        {\r\n            metamodelMap = new HashMap<String, Metamodel>();\r\n        }\r\n        return metamodelMap;\r\n    }\r\n\r\n    /**\r\n     * Gets the persistence unit metadata.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the persistence unit\r\n     * @return the persistence unit metadata\r\n     */\r\n    public PersistenceUnitMetadata getPersistenceUnitMetadata(String persistenceUnit)\r\n    {\r\n        return getPersistenceUnitMetadataMap().get(persistenceUnit);\r\n    }\r\n\r\n    /**\r\n     * Gets the metamodel.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the persistence unit\r\n     * @return the metamodel\r\n     */\r\n    public Metamodel getMetamodel(String persistenceUnit)\r\n    {\r\n        Map<String, Metamodel> model = getMetamodelMap();\r\n        return persistenceUnit != null && model.containsKey(persistenceUnit) ? model.get(persistenceUnit) : null;\r\n    }\r\n\r\n    /**\r\n     * Gets the persistence unit metadata map.\r\n     * \r\n     * @return the persistenceUnitMetadataMap\r\n     */\r\n    public Map<String, PersistenceUnitMetadata> getPersistenceUnitMetadataMap()\r\n    {\r\n        return persistenceUnitMetadataMap;\r\n    }\r\n\r\n    /**\r\n     * Sets the clazz to pu map.\r\n     * \r\n     * @param map\r\n     *            the map\r\n     */\r\n    public void setClazzToPuMap(Map<String, List<String>> map)\r\n    {\r\n        if (clazzToPuMap == null)\r\n        {\r\n            this.clazzToPuMap = map;\r\n        }\r\n        else\r\n        {\r\n            clazzToPuMap.putAll(map);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Gets the mapped persistence unit.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     * \r\n     * @return the mapped persistence unit\r\n     */\r\n    public List<String> getMappedPersistenceUnit(Class<?> clazz)\r\n    {\r\n        return this.clazzToPuMap != null ? this.clazzToPuMap.get(clazz.getName()) : null;\r\n    }\r\n\r\n    /**\r\n     * returns mapped persistence unit.\r\n     * \r\n     * @param clazzName\r\n     *            clazz name.\r\n     * \r\n     * @return mapped persistence unit.\r\n     */\r\n    public String getMappedPersistenceUnit(String clazzName)\r\n    {\r\n\r\n        List<String> pus = clazzToPuMap.get(clazzName);\r\n\r\n        final int _first = 0;\r\n        String pu = null;\r\n\r\n        if (pus != null && !pus.isEmpty())\r\n        {\r\n            if (pus.size() == 2)\r\n            {\r\n                onError(clazzName);\r\n            }\r\n            return pus.get(_first);\r\n        }\r\n        else\r\n        {\r\n            Set<String> mappedClasses = this.clazzToPuMap.keySet();\r\n            boolean found = false;\r\n            for (String clazz : mappedClasses)\r\n            {\r\n                if (found && clazz.endsWith(\".\" + clazzName))\r\n                {\r\n                    onError(clazzName);\r\n                }\r\n                else if (clazz.endsWith(\".\" + clazzName) || clazz.endsWith(\"$\" + clazzName))\r\n                {\r\n                    pu = clazzToPuMap.get(clazz).get(_first);\r\n                    found = true;\r\n                }\r\n            }\r\n        }\r\n\r\n        return pu;\r\n    }\r\n\r\n    /**\r\n     * Adds parameterised query with given name into collection. Throws\r\n     * exception if duplicate name is provided.\r\n     * \r\n     * @param queryName\r\n     *            query name.\r\n     * @param query\r\n     *            named/native query.\r\n     * @param isNativeQuery\r\n     *            true, if it is a namednativequery.\r\n     * \r\n     */\r\n    public void addQueryToCollection(String queryName, String query, boolean isNativeQuery, Class clazz)\r\n    {\r\n        if (namedNativeQueries == null)\r\n        {\r\n            namedNativeQueries = new ConcurrentHashMap<String, QueryWrapper>();\r\n        }\r\n        if (!namedNativeQueries.containsKey(queryName))\r\n        {\r\n            namedNativeQueries.put(queryName, new QueryWrapper(queryName, query, isNativeQuery, clazz));\r\n        }\r\n        // No null check made as it will never hold null value\r\n        else if (queryName != null && !getQuery(queryName).equals(query))\r\n        {\r\n            logger.error(\"Duplicate named/native query with name:\" + queryName\r\n                    + \"found! Already there is a query with same name:\" + namedNativeQueries.get(queryName));\r\n            throw new ApplicationLoaderException(\"Duplicate named/native query with name:\" + queryName\r\n                    + \"found! Already there is a query with same name:\" + namedNativeQueries.get(queryName));\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Returns query interface.\r\n     * \r\n     * @param name\r\n     *            query name.\r\n     * @return query.\r\n     */\r\n    public String getQuery(String name)\r\n    {\r\n        QueryWrapper wrapper = namedNativeQueries != null && name != null ? namedNativeQueries.get(name) : null;\r\n        return wrapper != null ? wrapper.getQuery() : null;\r\n    }\r\n\r\n    /**\r\n     * Returns true, if query is named native or native, else false\r\n     * \r\n     * @param name\r\n     *            mapped name.\r\n     * @return boolean value\r\n     */\r\n    public boolean isNative(String name)\r\n    {\r\n        QueryWrapper wrapper = namedNativeQueries != null && name != null ? namedNativeQueries.get(name) : null;\r\n        return wrapper != null ? wrapper.isNativeQuery() : false;\r\n    }\r\n\r\n    public Class getMappedClass(String name)\r\n    {\r\n        QueryWrapper wrapper = namedNativeQueries != null && name != null ? namedNativeQueries.get(name) : null;\r\n        return wrapper != null ? wrapper.getMappedClazz() : null;\r\n    }\r\n\r\n    /**\r\n     * Handler error and log statements.\r\n     * \r\n     * @param clazzName\r\n     *            class name.\r\n     */\r\n    private void onError(String clazzName)\r\n    {\r\n        logger.error(\"Duplicate name:\" + clazzName + \"Please provide entity with complete package name.\");\r\n        throw new ApplicationLoaderException(\"Duplicate name:\" + clazzName\r\n                + \"Please provide entity with complete package name\");\r\n    }\r\n\r\n    private class QueryWrapper\r\n    {\r\n        private String queryName;\r\n\r\n        private String query;\r\n\r\n        private boolean isNativeQuery;\r\n\r\n        private Class entityClazz;\r\n\r\n        /**\r\n         * @param queryName\r\n         * @param query\r\n         * @param isNativeQuery\r\n         */\r\n        public QueryWrapper(String queryName, String query, boolean isNativeQuery, Class clazz)\r\n        {\r\n            this.queryName = queryName;\r\n            this.query = query;\r\n            this.isNativeQuery = isNativeQuery;\r\n            this.entityClazz = clazz;\r\n        }\r\n\r\n        /**\r\n         * @return the query\r\n         */\r\n        String getQuery()\r\n        {\r\n            return query;\r\n        }\r\n\r\n        /**\r\n         * @return the isNativeQuery\r\n         */\r\n        boolean isNativeQuery()\r\n        {\r\n            return isNativeQuery;\r\n        }\r\n\r\n        Class getMappedClazz()\r\n        {\r\n            return entityClazz;\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @return the metaModelBuilder\r\n     */\r\n    public MetaModelBuilder getMetaModelBuilder(String persistenceUnit)\r\n    {\r\n        if (metaModelBuilder.containsKey(persistenceUnit))\r\n        {\r\n            return metaModelBuilder.get(persistenceUnit);\r\n        }\r\n        else\r\n        {\r\n            MetaModelBuilder builder = new MetaModelBuilder();\r\n            metaModelBuilder.put(persistenceUnit, builder);\r\n            return builder;\r\n        }\r\n    }\r\n\r\n    /**\r\n     * \r\n     */\r\n    void unloadApplicationMatadata(final String pu)\r\n    {\r\n        Metamodel metamodel = getMetamodel(pu);\r\n        if (metamodel != null)\r\n        {\r\n            this.metamodelMap.remove(pu);\r\n            ((MetamodelImpl) metamodel).setEntityMetadataMap(null);\r\n            ((MetamodelImpl) metamodel).setEntityNameToClassMap(null);\r\n            ((MetamodelImpl) metamodel).addKeyValues(new HashMap<String, IdDiscriptor>());\r\n        }\r\n        MetaModelBuilder builder = getMetaModelBuilder(pu);\r\n        if (builder != null)\r\n        {\r\n            this.metaModelBuilder.remove(pu);\r\n            builder = null;\r\n        }\r\n\r\n        // for (String className : clazzToPuMap.keySet())\r\n        // {\r\n        // List<String> pus = clazzToPuMap.get(className);\r\n        // }\r\n        // this.clazzToPuMap = null;\r\n\r\n        PersistenceUnitMetadata puMetadata = getPersistenceUnitMetadata(pu);\r\n        if (puMetadata != null)\r\n        {\r\n            this.persistenceUnitMetadataMap.remove(pu);\r\n            puMetadata.setClasses(new ArrayList<String>());\r\n            puMetadata.setExcludeUnlistedClasses(false);\r\n            puMetadata.setPackages(new ArrayList<String>());\r\n            puMetadata.setPersistenceUnitName(null);\r\n            puMetadata.setProperties(new Properties());\r\n            puMetadata.setTransactionType(PersistenceUnitTransactionType.RESOURCE_LOCAL);\r\n            puMetadata.setProvider(null);\r\n            puMetadata = null;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/ClientMetadata.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.model;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\n\r\n/**\r\n * The Class ClientMetadata.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class ClientMetadata\r\n{\r\n\r\n    /** The client implementor. */\r\n    private String clientImplementor;\r\n\r\n    /** The index implementor. */\r\n    private String indexImplementor;\r\n\r\n    /** The autogen implementor. */\r\n    private String autoGenImplementor;\r\n\r\n    /**\r\n     * @return the autoGenImplementor\r\n     */\r\n    public String getAutoGenImplementor()\r\n    {\r\n        return autoGenImplementor;\r\n    }\r\n\r\n    /**\r\n     * @param autoGenImplementor the autoGenImplementor to set\r\n     */\r\n    public void setAutoGenImplementor(String autoGenImplementor)\r\n    {\r\n        this.autoGenImplementor = autoGenImplementor;\r\n    }\r\n\r\n    /** The Lucene index dir. */\r\n    private String LuceneIndexDir;\r\n\r\n    /**\r\n     * Gets the client implementor.\r\n     * \r\n     * @return the clientImplementor\r\n     */\r\n    public String getClientImplementor()\r\n    {\r\n        return clientImplementor;\r\n    }\r\n\r\n    /**\r\n     * Sets the client implementor.\r\n     * \r\n     * @param clientImplementor\r\n     *            the clientImplementor to set\r\n     */\r\n    public void setClientImplementor(String clientImplementor)\r\n    {\r\n        this.clientImplementor = clientImplementor;\r\n    }\r\n\r\n    /**\r\n     * Gets the index implementor.\r\n     * \r\n     * @return the indexImplementor\r\n     */\r\n    public String getIndexImplementor()\r\n    {\r\n        return indexImplementor;\r\n    }\r\n\r\n    /**\r\n     * Sets the index implementor.\r\n     * \r\n     * @param indexImplementor\r\n     *            the indexImplementor to set\r\n     */\r\n    public void setIndexImplementor(String indexImplementor)\r\n    {\r\n        this.indexImplementor = indexImplementor;\r\n    }\r\n\r\n    /**\r\n     * Checks if is use secondry index.\r\n     * \r\n     * @return the useSecondryIndex\r\n     */\r\n    public boolean isUseSecondryIndex()\r\n    {\r\n        // if lucene directory and indexer class both not present then return\r\n        // true.\r\n\r\n        return StringUtils.isEmpty(LuceneIndexDir) && StringUtils.isBlank(LuceneIndexDir)\r\n                && StringUtils.isEmpty(indexImplementor) && StringUtils.isBlank(indexImplementor);\r\n    }\r\n\r\n    /**\r\n     * Gets the lucene index dir.\r\n     * \r\n     * @return the luceneIndexDir\r\n     */\r\n    public String getLuceneIndexDir()\r\n    {\r\n        return LuceneIndexDir;\r\n    }\r\n\r\n    /**\r\n     * Sets the lucene index dir.\r\n     * \r\n     * @param luceneIndexDir\r\n     *            the luceneIndexDir to set\r\n     */\r\n    public void setLuceneIndexDir(String luceneIndexDir)\r\n    {\r\n        LuceneIndexDir = luceneIndexDir;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/Column.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.model;\r\n\r\nimport java.lang.reflect.Field;\r\n\r\n/**\r\n * Holds metadata for entity column.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic final class Column\r\n{\r\n\r\n    /** name of the column. */\r\n    private String name;\r\n\r\n    /** column field. */\r\n    private Field field;\r\n\r\n    /** whether indexable. */\r\n    private boolean isIndexable; // default is NOT indexable\r\n\r\n    /**\r\n     * Instantiates a new column.\r\n     * \r\n     * @param name\r\n     *            the name\r\n     * @param field\r\n     *            the field\r\n     */\r\n    public Column(String name, Field field)\r\n    {\r\n        this.name = name;\r\n        this.field = field;\r\n    }\r\n\r\n    public Column(String name, Field field, boolean isIndexable)\r\n    {\r\n        this.name = name;\r\n        this.field = field;\r\n        this.isIndexable = isIndexable;\r\n    }\r\n\r\n    /**\r\n     * Gets the name.\r\n     * \r\n     * @return the name\r\n     */\r\n    public String getName()\r\n    {\r\n        return name;\r\n    }\r\n\r\n    /**\r\n     * Gets the field.\r\n     * \r\n     * @return the field\r\n     */\r\n    public Field getField()\r\n    {\r\n        return field;\r\n    }\r\n\r\n    /**\r\n     * Checks if is indexable.\r\n     * \r\n     * @return the isIndexable\r\n     */\r\n    public boolean isIndexable()\r\n    {\r\n        return isIndexable;\r\n    }\r\n\r\n    /**\r\n     * Sets the indexable.\r\n     * \r\n     * @param isIndexable\r\n     *            the isIndexable to set\r\n     */\r\n    public void setIndexable(boolean isIndexable)\r\n    {\r\n        this.isIndexable = isIndexable;\r\n    }\r\n\r\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/CoreMetadata.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.model;\r\n\r\nimport com.impetus.kundera.proxy.LazyInitializerFactory;\r\n\r\n/**\r\n * The Class CoreMetadata.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class CoreMetadata\r\n{\r\n\r\n    /** The lazy initializer factory. */\r\n    private LazyInitializerFactory lazyInitializerFactory;\r\n\r\n    /**\r\n     * Gets the lazy initializer factory.\r\n     * \r\n     * @return the lazy initializer factory\r\n     */\r\n    public LazyInitializerFactory getLazyInitializerFactory()\r\n    {\r\n        return lazyInitializerFactory;\r\n    }\r\n\r\n    /**\r\n     * Sets the lazy initializer factory.\r\n     * \r\n     * @param lazyInitializerFactory\r\n     *            the new lazy initializer factory\r\n     */\r\n    public void setLazyInitializerFactory(LazyInitializerFactory lazyInitializerFactory)\r\n    {\r\n        this.lazyInitializerFactory = lazyInitializerFactory;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/EntityMetadata.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.model;\r\n\r\nimport java.lang.reflect.Field;\r\nimport java.lang.reflect.Method;\r\nimport java.util.ArrayList;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.PrimaryKeyJoinColumn;\r\nimport javax.persistence.metamodel.EntityType;\r\nimport javax.persistence.metamodel.SingularAttribute;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\n\r\nimport com.impetus.kundera.metadata.MetadataUtils;\r\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\r\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\r\nimport com.impetus.kundera.persistence.event.CallbackMethod;\r\n\r\n/**\r\n * Holds metadata for entities.\r\n * \r\n * @author animesh.kumar\r\n */\r\n\r\npublic final class EntityMetadata\r\n{\r\n\r\n    /*\r\n     * Entity related metadata properties\r\n     */\r\n\r\n    /** class corresponding to this meta. */\r\n    private Class<?> entityClazz;\r\n\r\n    /** Name of Persistence Object. */\r\n    private String tableName;\r\n\r\n    /** database name. */\r\n    private String schema;\r\n\r\n    /** Persistence unit of database this entity is to be persisted. */\r\n    private String persistenceUnit;\r\n\r\n    /** The index name. */\r\n    private String indexName;\r\n\r\n    /** The is indexable. */\r\n    private boolean isIndexable = true; // default is indexable\r\n\r\n    /** Cacheable?. */\r\n    private boolean cacheable = false; // default is to not set second-level\r\n\r\n    private boolean isCounterColumnType = false;\r\n\r\n    private SingularAttribute idAttribute;\r\n\r\n    private Map<String, String> jpaColumnMapping = new HashMap<String, String>();\r\n\r\n    /** The read identifier method. */\r\n    private Method readIdentifierMethod;\r\n\r\n    /** The write identifier method. */\r\n    private Method writeIdentifierMethod;\r\n\r\n    /** The index prperties. */\r\n    private Map<String, PropertyIndex> indexPrperties = new HashMap<String, PropertyIndex>();\r\n\r\n    /** The callback methods map. */\r\n    private Map<Class<?>, List<? extends CallbackMethod>> callbackMethodsMap = new HashMap<Class<?>, List<? extends CallbackMethod>>();\r\n\r\n    /** Relationship map, key=>property name, value=>relation. */\r\n    private Map<String, Relation> relationsMap = new HashMap<String, Relation>();\r\n\r\n    /** type. */\r\n    private Type type;\r\n\r\n    /** The is relation via join table. */\r\n    private boolean isRelationViaJoinTable;\r\n\r\n    private List<String> relationNames;\r\n\r\n    // Whether it contains One-To-Many relationship\r\n    private boolean isParent;\r\n\r\n    private EntityType entityType;\r\n\r\n    /**\r\n     * The Enum Type.\r\n     */\r\n    public static enum Type\r\n    {\r\n\r\n        /** Denotes that the Entity is related to a ColumnFamily. */\r\n        COLUMN_FAMILY\r\n        {\r\n\r\n            public boolean isColumnFamilyMetadata()\r\n            {\r\n                return true;\r\n            }\r\n\r\n            public boolean isSuperColumnFamilyMetadata()\r\n            {\r\n                return false;\r\n            }\r\n\r\n            public boolean isDocumentMetadata()\r\n            {\r\n                return false;\r\n            }\r\n\r\n        },\r\n\r\n        /** Denotes that the Entity is related to a SuperColumnFamily. */\r\n        SUPER_COLUMN_FAMILY\r\n        {\r\n\r\n            public boolean isColumnFamilyMetadata()\r\n            {\r\n                return false;\r\n            }\r\n\r\n            public boolean isSuperColumnFamilyMetadata()\r\n            {\r\n                return true;\r\n            }\r\n\r\n            public boolean isDocumentMetadata()\r\n            {\r\n                return false;\r\n            }\r\n\r\n        };\r\n\r\n        /**\r\n         * Checks if is column family metadata.\r\n         * \r\n         * @return true, if is column family metadata\r\n         */\r\n        public abstract boolean isColumnFamilyMetadata();\r\n\r\n        /**\r\n         * Checks if is super column family metadata.\r\n         * \r\n         * @return true, if is super column family metadata\r\n         */\r\n        public abstract boolean isSuperColumnFamilyMetadata();\r\n\r\n        /**\r\n         * Checks if is Document metadata.\r\n         * \r\n         * @return true, if is Document metadata\r\n         */\r\n        public abstract boolean isDocumentMetadata();\r\n    }\r\n\r\n    /**\r\n     * Gets the type.\r\n     * \r\n     * @return the type\r\n     */\r\n    public Type getType()\r\n    {\r\n        return type;\r\n    }\r\n\r\n    /**\r\n     * Sets the type.\r\n     * \r\n     * @param type\r\n     *            the new type\r\n     */\r\n    public void setType(Type type)\r\n    {\r\n        this.type = type;\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new metadata.\r\n     * \r\n     * @param entityClazz\r\n     *            the entity clazz\r\n     */\r\n    public EntityMetadata(Class<?> entityClazz)\r\n    {\r\n        this.entityClazz = entityClazz;\r\n\r\n    }\r\n\r\n    /**\r\n     * Gets the entity clazz.\r\n     * \r\n     * @return the entity clazz\r\n     */\r\n    public Class<?> getEntityClazz()\r\n    {\r\n        return entityClazz;\r\n    }\r\n\r\n    /**\r\n     * Gets the table name.\r\n     * \r\n     * @return the tableName\r\n     */\r\n    public String getTableName()\r\n    {\r\n        getEntityType();\r\n\r\n        return this.entityType != null && !StringUtils.isBlank(((AbstractManagedType) this.entityType).getTableName()) ? ((AbstractManagedType) this.entityType)\r\n                .getTableName() : tableName;\r\n    }\r\n\r\n    private EntityType getEntityType()\r\n    {\r\n        /*\r\n         * if (this.entityType == null) { MetamodelImpl metaModel =\r\n         * (MetamodelImpl)\r\n         * kunderaMetadata.getApplicationMetadata().getMetamodel(\r\n         * getPersistenceUnit()); if (metaModel != null) { this.entityType =\r\n         * metaModel.entity(this.entityClazz); } }\r\n         */\r\n        return this.entityType;\r\n    }\r\n\r\n    /**\r\n     * Sets the table name.\r\n     * \r\n     * @param tableName\r\n     *            the tableName to set\r\n     */\r\n    public void setTableName(String tableName)\r\n    {\r\n        this.tableName = tableName;\r\n    }\r\n\r\n    /**\r\n     * Gets the schema.\r\n     * \r\n     * @return the schema\r\n     */\r\n    public String getSchema()\r\n    {\r\n        getEntityType();\r\n\r\n        return this.entityType != null && !StringUtils.isBlank(((AbstractManagedType) this.entityType).getSchemaName()) ? ((AbstractManagedType) this.entityType)\r\n                .getSchemaName() : schema;\r\n    }\r\n\r\n    /**\r\n     * Sets the schema.\r\n     * \r\n     * @param schema\r\n     *            the schema to set\r\n     */\r\n    public void setSchema(String schema)\r\n    {\r\n        this.schema = schema;\r\n    }\r\n\r\n    /**\r\n     * Gets the persistence unit.\r\n     * \r\n     * @return the persistenceUnit\r\n     */\r\n    public String getPersistenceUnit()\r\n    {\r\n        return persistenceUnit;\r\n    }\r\n\r\n    /**\r\n     * Sets the persistence unit.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the persistenceUnit to set\r\n     */\r\n    public void setPersistenceUnit(String persistenceUnit)\r\n    {\r\n        this.persistenceUnit = persistenceUnit;\r\n    }\r\n\r\n    /**\r\n     * Gets the read identifier method.\r\n     * \r\n     * @return the readIdentifierMethod\r\n     */\r\n    public Method getReadIdentifierMethod()\r\n    {\r\n        return readIdentifierMethod;\r\n    }\r\n\r\n    /**\r\n     * Sets the read identifier method.\r\n     * \r\n     * @param readIdentifierMethod\r\n     *            the readIdentifierMethod to set\r\n     */\r\n    public void setReadIdentifierMethod(Method readIdentifierMethod)\r\n    {\r\n        this.readIdentifierMethod = readIdentifierMethod;\r\n    }\r\n\r\n    /**\r\n     * Gets the write identifier method.\r\n     * \r\n     * @return the writeIdentifierMethod\r\n     */\r\n    public Method getWriteIdentifierMethod()\r\n    {\r\n        return writeIdentifierMethod;\r\n    }\r\n\r\n    /**\r\n     * Sets the write identifier method.\r\n     * \r\n     * @param writeIdentifierMethod\r\n     *            the writeIdentifierMethod to set\r\n     */\r\n    public void setWriteIdentifierMethod(Method writeIdentifierMethod)\r\n    {\r\n        this.writeIdentifierMethod = writeIdentifierMethod;\r\n    }\r\n\r\n    /**\r\n     * Adds the index property.\r\n     * \r\n     * @param index\r\n     *            the index\r\n     */\r\n    public void addIndexProperty(String columnName, PropertyIndex index)\r\n    {\r\n        indexPrperties.put(columnName, index);\r\n\r\n    }\r\n\r\n    /**\r\n     * Adds the relation.\r\n     * \r\n     * @param property\r\n     *            the property\r\n     * @param relation\r\n     *            the relation\r\n     */\r\n    public void addRelation(String property, Relation relation)\r\n    {\r\n        relationsMap.put(property, relation);\r\n        addRelationName(relation);\r\n    }\r\n\r\n    /**\r\n     * Gets the relation.\r\n     * \r\n     * @param property\r\n     *            the property\r\n     * @return the relation\r\n     */\r\n    public Relation getRelation(String property)\r\n    {\r\n        return relationsMap.get(property);\r\n    }\r\n\r\n    /**\r\n     * Gets the relations.\r\n     * \r\n     * @return the relations\r\n     */\r\n    public List<Relation> getRelations()\r\n    {\r\n        return new ArrayList<Relation>(relationsMap.values());\r\n    }\r\n\r\n    /**\r\n     * Gets the index properties.\r\n     * \r\n     * @return the index properties\r\n     */\r\n    public Map<String, PropertyIndex> getIndexProperties()\r\n    {\r\n        return indexPrperties;\r\n    }\r\n\r\n    /**\r\n     * Gets the index name.\r\n     * \r\n     * @return the index name\r\n     */\r\n    public String getIndexName()\r\n    {\r\n        return indexName;\r\n    }\r\n\r\n    /**\r\n     * Sets the index name.\r\n     * \r\n     * @param indexName\r\n     *            the new index name\r\n     */\r\n    public void setIndexName(String indexName)\r\n    {\r\n        this.indexName = indexName;\r\n    }\r\n\r\n    /**\r\n     * Checks if is indexable.\r\n     * \r\n     * @return true, if is indexable\r\n     */\r\n    public boolean isIndexable()\r\n    {\r\n        return isIndexable;\r\n    }\r\n\r\n    /**\r\n     * Sets the indexable.\r\n     * \r\n     * @param isIndexable\r\n     *            the new indexable\r\n     */\r\n    public void setIndexable(boolean isIndexable)\r\n    {\r\n        this.isIndexable = isIndexable;\r\n    }\r\n\r\n    /**\r\n     * Sets the callback methods map.\r\n     * \r\n     * @param callbackMethodsMap\r\n     *            the callback methods map\r\n     */\r\n    public void setCallbackMethodsMap(Map<Class<?>, List<? extends CallbackMethod>> callbackMethodsMap)\r\n    {\r\n        this.callbackMethodsMap = callbackMethodsMap;\r\n    }\r\n\r\n    /**\r\n     * Gets the callback methods map.\r\n     * \r\n     * @return the callback methods map\r\n     */\r\n    public Map<Class<?>, List<? extends CallbackMethod>> getCallbackMethodsMap()\r\n    {\r\n        return callbackMethodsMap;\r\n    }\r\n\r\n    /**\r\n     * Gets the callback methods.\r\n     * \r\n     * @param event\r\n     *            the event\r\n     * \r\n     * @return the callback methods\r\n     */\r\n    public List<? extends CallbackMethod> getCallbackMethods(Class<?> event)\r\n    {\r\n        return this.callbackMethodsMap.get(event);\r\n    }\r\n\r\n    /**\r\n     * Checks if is cacheable.\r\n     * \r\n     * @return the cacheable\r\n     */\r\n    public boolean isCacheable()\r\n    {\r\n        return cacheable;\r\n    }\r\n\r\n    /**\r\n     * Sets the cacheable.\r\n     * \r\n     * @param cacheable\r\n     *            the cacheable to set\r\n     */\r\n    public void setCacheable(boolean cacheable)\r\n    {\r\n        this.cacheable = cacheable;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see java.lang.Object#toString()\r\n     */\r\n    @Override\r\n    public String toString()\r\n    {\r\n        int start = 0;\r\n        StringBuilder builder = new StringBuilder();\r\n        builder.append(entityClazz.getName() + \" (\\n\");\r\n        builder.append(\"\\tTable: \" + tableName + \", \\n\");\r\n        builder.append(\"\\tKeyspace: \" + schema + \",\\n\");\r\n        builder.append(\"\\tPersistence Unit: \" + persistenceUnit + \",\\n\");\r\n        builder.append(\"\\tId: \" + idAttribute.getName() + \",\\n\");\r\n        builder.append(\"\\tCacheable: \" + cacheable + \",\\n\");\r\n\r\n        if (!indexPrperties.isEmpty())\r\n        {\r\n\r\n            builder.append(\"\\tIndexes (\");\r\n            start = 0;\r\n            for (String indexColumnName : indexPrperties.keySet())\r\n            {\r\n                if (start++ != 0)\r\n                {\r\n                    builder.append(\", \");\r\n                }\r\n                builder.append(indexPrperties.get(indexColumnName));\r\n            }\r\n            builder.append(\"),\\n\");\r\n        }\r\n\r\n        if (!callbackMethodsMap.isEmpty())\r\n        {\r\n            builder.append(\"\\tListeners (\\n\");\r\n            for (Map.Entry<Class<?>, List<? extends CallbackMethod>> entry : callbackMethodsMap.entrySet())\r\n            {\r\n                String key = entry.getKey().getSimpleName();\r\n                for (CallbackMethod cbm : entry.getValue())\r\n                {\r\n                    builder.append(\"\\t\\t\" + key + \": \" + cbm + \"\\n\");\r\n                }\r\n            }\r\n            builder.append(\"\\t)\\n\");\r\n        }\r\n\r\n        if (!relationsMap.isEmpty())\r\n        {\r\n            builder.append(\"\\tRelation (\\n\");\r\n            for (Relation rel : relationsMap.values())\r\n            {\r\n                if (rel.getMapKeyJoinClass() != null)\r\n                    builder.append(\" --- via \").append(rel.getMapKeyJoinClass().getSimpleName()).append(\" ---\\n\");\r\n                builder.append(\"\\t\\t\" + rel.getTargetEntity().getName() + \"#\" + rel.getProperty().getName());\r\n                builder.append(\" (\" + rel.getCascades());\r\n                builder.append(\", \" + rel.getType());\r\n                builder.append(\", \" + rel.getFetchType());\r\n                builder.append(\")\\n\");\r\n            }\r\n            builder.append(\"\\t)\\n\");\r\n        }\r\n\r\n        builder.append(\")\");\r\n        return builder.toString();\r\n    }\r\n\r\n    /**\r\n     * Getter method for isRelatedViaJoinTable.\r\n     * \r\n     * @return true, if holds join table relation, else false.\r\n     */\r\n    public boolean isRelationViaJoinTable()\r\n    {\r\n        return isRelationViaJoinTable;\r\n    }\r\n\r\n    /**\r\n     * @return the isParent\r\n     */\r\n    public boolean isParent()\r\n    {\r\n        return isParent;\r\n    }\r\n\r\n    /**\r\n     * @param isParent\r\n     *            the isParent to set\r\n     */\r\n    public void setParent(boolean isParent)\r\n    {\r\n        this.isParent = isParent;\r\n    }\r\n\r\n    /**\r\n     * Setter method for isRelatedViaJoinTable.\r\n     * \r\n     * @param isRelationViaJoinTable\r\n     *            the new relation via join table\r\n     */\r\n    public void setRelationViaJoinTable(boolean isRelationViaJoinTable)\r\n    {\r\n        this.isRelationViaJoinTable = isRelationViaJoinTable;\r\n    }\r\n\r\n    public List<String> getRelationNames()\r\n    {\r\n        return relationNames;\r\n    }\r\n\r\n    /**\r\n     * Method to add specific relation name for given relational field.\r\n     * \r\n     * @param rField\r\n     *            relation object.\r\n     */\r\n    private void addRelationName(Relation rField)\r\n    {\r\n        if (rField != null && !rField.isRelatedViaJoinTable())\r\n        {\r\n            String relationName = getJoinColumnName(rField.getProperty());\r\n            if (rField.getProperty().isAnnotationPresent(PrimaryKeyJoinColumn.class))\r\n            {\r\n                relationName = this.getIdAttribute().getName();\r\n            }\r\n\r\n            addToRelationNameCollection(relationName);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Adds relation name to relation name collection.\r\n     * \r\n     * @param relationName\r\n     *            relational name\r\n     */\r\n    private void addToRelationNameCollection(String relationName)\r\n    {\r\n        if (relationNames == null)\r\n        {\r\n            relationNames = new ArrayList<String>();\r\n        }\r\n        if (relationName != null)\r\n        {\r\n            relationNames.add(relationName);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Gets the relation field name.\r\n     * \r\n     * @param relation\r\n     *            the relation\r\n     * @return the relation field name\r\n     */\r\n    private String getJoinColumnName(Field relation)\r\n    {\r\n        String columnName = null;\r\n        JoinColumn ann = relation.getAnnotation(JoinColumn.class);\r\n        if (ann != null)\r\n        {\r\n            columnName = ann.name();\r\n\r\n        }\r\n        return StringUtils.isBlank(columnName) ? relation.getName() : columnName;\r\n    }\r\n\r\n    /**\r\n     * @return the isCounterColumnType\r\n     */\r\n    public boolean isCounterColumnType()\r\n    {\r\n        return isCounterColumnType;\r\n    }\r\n\r\n    /**\r\n     * @param isCounterColumnType\r\n     *            the isCounterColumnType to set\r\n     */\r\n    public void setCounterColumnType(boolean isCounterColumnType)\r\n    {\r\n        this.isCounterColumnType = isCounterColumnType;\r\n    }\r\n\r\n    /**\r\n     * @return the idAttribute\r\n     */\r\n    public SingularAttribute getIdAttribute()\r\n    {\r\n        return idAttribute;\r\n    }\r\n\r\n    /**\r\n     * @param idAttribute\r\n     *            the idAttribute to set\r\n     */\r\n    public void setIdAttribute(SingularAttribute idAttribute)\r\n    {\r\n        this.idAttribute = idAttribute;\r\n    }\r\n\r\n    public void addJPAColumnMapping(String jpaColumnName, String fieldName)\r\n    {\r\n        jpaColumnMapping.put(jpaColumnName, fieldName);\r\n    }\r\n\r\n    public String getFieldName(String jpaColumnName)\r\n    {\r\n        // if(jpaColumnName.equals(((AbstractAttribute)this.getIdAttribute()).getJPAColumnName()))\r\n        // {\r\n        // return this.getIdAttribute().getName();\r\n        // }\r\n\r\n        String fieldName = jpaColumnMapping.get(jpaColumnName);\r\n\r\n        if (fieldName == null)\r\n        {\r\n            getEntityType();\r\n            MetadataUtils.onJPAColumnMapping(this.entityType, this); // rebase.\r\n                                                                     // require\r\n                                                                     // in case\r\n                                                                     // of\r\n                                                                     // concrete\r\n                                                                     // super\r\n                                                                     // entity\r\n                                                                     // class.\r\n            fieldName = jpaColumnMapping.get(jpaColumnName);\r\n        }\r\n\r\n        if (fieldName == null && jpaColumnName.equals(((AbstractAttribute) this.getIdAttribute()).getJPAColumnName()))\r\n        {\r\n            return this.getIdAttribute().getName();\r\n        }\r\n\r\n        return fieldName;\r\n    }\r\n\r\n    public void setEntityType(EntityType entityType)\r\n    {\r\n        if (entityType != null)\r\n        {\r\n            this.entityType = entityType;\r\n        }\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/IdDiscriptor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model;\n\nimport javax.persistence.GenerationType;\n\n/**\n * Class IdDiscriptor holds all information about generating id.\n * \n * @author Kuldeep.kumar\n * \n */\npublic class IdDiscriptor\n{\n    private GenerationType strategy;\n\n    private TableGeneratorDiscriptor tableDiscriptor;\n\n    private SequenceGeneratorDiscriptor sequenceDiscriptor;\n\n    /**\n     * @return the strategy\n     */\n    public GenerationType getStrategy()\n    {\n        return strategy;\n    }\n\n    /**\n     * @param strategy\n     *            the strategy to set\n     */\n    public void setStrategy(GenerationType strategy)\n    {\n        this.strategy = strategy;\n    }\n\n    /**\n     * @return the tableDiscriptor\n     */\n    public TableGeneratorDiscriptor getTableDiscriptor()\n    {\n        return tableDiscriptor;\n    }\n\n    /**\n     * @param tableDiscriptor\n     *            the tableDiscriptor to set\n     */\n    public void setTableDiscriptor(TableGeneratorDiscriptor tableDiscriptor)\n    {\n        this.tableDiscriptor = tableDiscriptor;\n    }\n\n    /**\n     * @return the sequenceDiscriptor\n     */\n    public SequenceGeneratorDiscriptor getSequenceDiscriptor()\n    {\n        return sequenceDiscriptor;\n    }\n\n    /**\n     * @param sequenceDiscriptor\n     *            the sequenceDiscriptor to set\n     */\n    public void setSequenceDiscriptor(SequenceGeneratorDiscriptor sequenceDiscriptor)\n    {\n        this.sequenceDiscriptor = sequenceDiscriptor;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/JoinTableMetadata.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model;\n\nimport java.lang.reflect.Field;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\n\n/**\n * The Class JoinTableMetadata.\n * \n * @author Amresh Singh\n */\npublic class JoinTableMetadata\n{\n\n    /** The join table name. */\n    private String joinTableName;\n\n    /** The join table schema. */\n    private String joinTableSchema;\n\n    /** The join columns. */\n    private Set<String> joinColumns;\n\n    /** The inverse join columns. */\n    private Set<String> inverseJoinColumns;\n\n    /**\n     * Instantiates a new join table metadata.\n     * \n     * @param relationField\n     *            the relation field\n     */\n    public JoinTableMetadata(Field relationField)\n    {\n        JoinTable jtAnn = relationField.getAnnotation(JoinTable.class);\n\n        setJoinTableName(jtAnn.name());\n        setJoinTableSchema(jtAnn.schema());\n\n        for (JoinColumn joinColumn : jtAnn.joinColumns())\n        {\n            addJoinColumns(joinColumn.name());\n        }\n\n        for (JoinColumn inverseJoinColumn : jtAnn.inverseJoinColumns())\n        {\n            addInverseJoinColumns(inverseJoinColumn.name());\n        }\n    }\n\n    /**\n     * Gets the join table name.\n     * \n     * @return the joinTableName\n     */\n    public String getJoinTableName()\n    {\n        return joinTableName;\n    }\n\n    /**\n     * Sets the join table name.\n     * \n     * @param joinTableName\n     *            the joinTableName to set\n     */\n    public void setJoinTableName(String joinTableName)\n    {\n        this.joinTableName = joinTableName;\n    }\n\n    /**\n     * Gets the join table schema.\n     * \n     * @return the joinTableSchema\n     */\n    public String getJoinTableSchema()\n    {\n        return joinTableSchema;\n    }\n\n    /**\n     * Sets the join table schema.\n     * \n     * @param joinTableSchema\n     *            the joinTableSchema to set\n     */\n    public void setJoinTableSchema(String joinTableSchema)\n    {\n        this.joinTableSchema = joinTableSchema;\n    }\n\n    /**\n     * Gets the join columns.\n     * \n     * @return the joinColumns\n     */\n    public Set<String> getJoinColumns()\n    {\n        return joinColumns;\n    }\n\n    /**\n     * Adds the join columns.\n     * \n     * @param joinColumn\n     *            the joinColumns to add\n     */\n    public void addJoinColumns(String joinColumn)\n    {\n        if (joinColumns == null || joinColumns.isEmpty())\n        {\n            joinColumns = new HashSet<String>();\n        }\n        joinColumns.add(joinColumn);\n    }\n\n    /**\n     * Gets the inverse join columns.\n     * \n     * @return the inverseJoinColumns\n     */\n    public Set<String> getInverseJoinColumns()\n    {\n        return inverseJoinColumns;\n    }\n\n    /**\n     * Adds the inverse join columns.\n     * \n     * @param inverseJoinColumn\n     *            the inverseJoinColumns to add\n     */\n    public void addInverseJoinColumns(String inverseJoinColumn)\n    {\n        if (inverseJoinColumns == null || inverseJoinColumns.isEmpty())\n        {\n            inverseJoinColumns = new HashSet<String>();\n        }\n\n        inverseJoinColumns.add(inverseJoinColumn);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/MetamodelImpl.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.model;\r\n\r\nimport java.util.Collection;\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.metamodel.Attribute;\r\nimport javax.persistence.metamodel.EmbeddableType;\r\nimport javax.persistence.metamodel.EntityType;\r\nimport javax.persistence.metamodel.ManagedType;\r\nimport javax.persistence.metamodel.Metamodel;\r\nimport javax.persistence.metamodel.StaticMetamodel;\r\nimport javax.persistence.metamodel.Type.PersistenceType;\r\n\r\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\r\n\r\n/**\r\n * The Class MetamodelImpl implements <code> MetaModel</code> interface.\r\n * Responsible for holding reference to complete metamodel and relative\r\n * information, in the form of: a) EntityTypes b) Embeddables\r\n * c)MappedSuperClassTypes\r\n * \r\n * @author vivek.mishra\r\n */\r\n@StaticMetamodel(value = MetamodelImpl.class)\r\npublic class MetamodelImpl implements Metamodel\r\n{\r\n    /** The entity metadata map. */\r\n    Map<String, EntityMetadata> entityMetadataMap;\r\n\r\n    /** The entity name to class map. */\r\n    Map<String, Class<?>> entityNameToClassMap;\r\n\r\n    /** The managed types. */\r\n    private Map<Class<?>, EntityType<?>> entityTypes;\r\n\r\n    /** The embeddables. */\r\n    private Map<Class<?>, ManagedType<?>> embeddables;\r\n\r\n    /** The mapped super class types. */\r\n    private Map<Class<?>, ManagedType<?>> mappedSuperClassTypes;\r\n\r\n    /** Entity name to id discriptor. */\r\n    private Map<String, IdDiscriptor> keyValues;\r\n\r\n    /** Entity name to List of Secondary tables */\r\n    private Map<Class<?>, List<String>> classToTables;\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.metamodel.Metamodel#entity(java.lang.Class)\r\n     */\r\n    @Override\r\n    public <X> EntityType<X> entity(Class<X> paramClass)\r\n    {\r\n        EntityType entityType = entityTypes.get(paramClass);\r\n        if (entityType == null)\r\n        {\r\n            throw new IllegalArgumentException(\"Not an entity, {class:\" + paramClass + \"}\");\r\n        }\r\n        return entityType;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.metamodel.Metamodel#managedType(java.lang.Class)\r\n     */\r\n    @Override\r\n    public <X> ManagedType<X> managedType(Class<X> paramClass)\r\n    {\r\n        ManagedType managedType = entityTypes.get(paramClass);\r\n        if (managedType == null)\r\n        {\r\n            managedType = embeddables.get(paramClass);\r\n            if (managedType == null)\r\n            {\r\n                managedType = mappedSuperClassTypes.get(paramClass);\r\n            }\r\n        }\r\n\r\n        if (managedType == null)\r\n        {\r\n            throw new IllegalArgumentException(\"Not a managed type, {class: \" + paramClass + \"}\");\r\n        }\r\n        return managedType;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.metamodel.Metamodel#embeddable(java.lang.Class)\r\n     */\r\n    @Override\r\n    public <X> EmbeddableType<X> embeddable(Class<X> paramClass)\r\n    {\r\n        EmbeddableType embeddableType = (EmbeddableType) embeddables.get(paramClass);\r\n        if (embeddableType == null)\r\n        {\r\n            throw new IllegalArgumentException(\"Not a embeddable type, {class: \" + paramClass + \"}\");\r\n        }\r\n\r\n        return embeddableType;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.metamodel.Metamodel#getManagedTypes()\r\n     */\r\n    @Override\r\n    public Set<ManagedType<?>> getManagedTypes()\r\n    {\r\n        Set<ManagedType<?>> managedTypeCollection = new HashSet<ManagedType<?>>();\r\n        if (entityTypes != null)\r\n        {\r\n            managedTypeCollection.addAll(entityTypes.values());\r\n        }\r\n        if (embeddables != null)\r\n        {\r\n            managedTypeCollection.addAll((Collection<? extends ManagedType<?>>) embeddables.values());\r\n        }\r\n        if (mappedSuperClassTypes != null)\r\n        {\r\n            managedTypeCollection.addAll((Collection<? extends ManagedType<?>>) mappedSuperClassTypes.values());\r\n        }\r\n        return managedTypeCollection;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.metamodel.Metamodel#getEntities()\r\n     */\r\n    @Override\r\n    public Set<EntityType<?>> getEntities()\r\n    {\r\n        Set<EntityType<?>> entities = null;\r\n        if (entityTypes != null)\r\n        {\r\n            entities = new HashSet<EntityType<?>>(entityTypes.values());\r\n        }\r\n        return entities;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.metamodel.Metamodel#getEmbeddables()\r\n     */\r\n    @Override\r\n    public Set<EmbeddableType<?>> getEmbeddables()\r\n    {\r\n        Set embeddableEntities = null;\r\n        if (embeddables != null)\r\n        {\r\n            embeddableEntities = new HashSet(embeddables.values());\r\n        }\r\n        return embeddableEntities;\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new metamodel impl.\r\n     */\r\n    public MetamodelImpl()\r\n    {\r\n        super();\r\n        setEntityMetadataMap(new HashMap<String, EntityMetadata>());\r\n    }\r\n\r\n    /**\r\n     * Gets the entity metadata map.\r\n     * \r\n     * @return the entityMetadataMap\r\n     */\r\n    public Map<String, EntityMetadata> getEntityMetadataMap()\r\n    {\r\n        if (entityMetadataMap == null)\r\n        {\r\n            entityMetadataMap = new HashMap<String, EntityMetadata>();\r\n        }\r\n        return entityMetadataMap;\r\n    }\r\n\r\n    /**\r\n     * Sets the entity metadata map.\r\n     * \r\n     * @param entityMetadataMap\r\n     *            the entityMetadataMap to set\r\n     */\r\n    public void setEntityMetadataMap(Map<String, EntityMetadata> entityMetadataMap)\r\n    {\r\n        this.entityMetadataMap = entityMetadataMap;\r\n    }\r\n\r\n    /**\r\n     * Adds the entity metadata.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     * @param entityMetadata\r\n     *            the entity metadata\r\n     */\r\n    public void addEntityMetadata(Class<?> clazz, EntityMetadata entityMetadata)\r\n    {\r\n        getEntityMetadataMap().put(clazz.getName(), entityMetadata);\r\n    }\r\n\r\n    /**\r\n     * Gets the entity metadata.\r\n     * \r\n     * @param entityClass\r\n     *            the entity class\r\n     * @return the entity metadata\r\n     */\r\n    public EntityMetadata getEntityMetadata(Class<?> entityClass)\r\n    {\r\n        return getEntityMetadataMap().get(entityClass.getName());\r\n    }\r\n\r\n    /**\r\n     * Gets the entity name to class map.\r\n     * \r\n     * @return the entityNameToClassMap\r\n     */\r\n    public Map<String, Class<?>> getEntityNameToClassMap()\r\n    {\r\n        if (entityNameToClassMap == null)\r\n        {\r\n            entityNameToClassMap = new HashMap<String, Class<?>>();\r\n        }\r\n        return entityNameToClassMap;\r\n    }\r\n\r\n    /**\r\n     * Sets the entity name to class map.\r\n     * \r\n     * @param entityNameToClassMap\r\n     *            the entityNameToClassMap to set\r\n     */\r\n    public void setEntityNameToClassMap(Map<String, Class<?>> entityNameToClassMap)\r\n    {\r\n        this.entityNameToClassMap = entityNameToClassMap;\r\n    }\r\n\r\n    /**\r\n     * Adds the entity name to class mapping.\r\n     * \r\n     * @param className\r\n     *            the class name\r\n     * @param entityClass\r\n     *            the entity class\r\n     */\r\n    public void addEntityNameToClassMapping(String className, Class<?> entityClass)\r\n    {\r\n        getEntityNameToClassMap().put(className, entityClass);\r\n    }\r\n\r\n    /**\r\n     * Gets the entity class.\r\n     * \r\n     * @param className\r\n     *            the class name\r\n     * @return the entity class\r\n     */\r\n    public Class<?> getEntityClass(String className)\r\n    {\r\n        return getEntityNameToClassMap().get(className);\r\n    }\r\n\r\n    /**\r\n     * Assign to managedTypes.\r\n     * \r\n     * @param managedTypes\r\n     *            the managedTypes to set\r\n     */\r\n    public void assignManagedTypes(Map<Class<?>, EntityType<?>> managedTypes)\r\n    {\r\n        if (this.entityTypes == null)\r\n        {\r\n            this.entityTypes = managedTypes;\r\n        }\r\n        else\r\n        {\r\n            this.entityTypes.putAll(managedTypes);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Assign embeddables to embeddables collection.\r\n     * \r\n     * @param embeddables\r\n     *            the embeddables to set\r\n     */\r\n    public void assignEmbeddables(Map<Class<?>, ManagedType<?>> embeddables)\r\n    {\r\n        if (this.embeddables == null)\r\n        {\r\n            this.embeddables = embeddables;\r\n        }\r\n        else\r\n        {\r\n            this.embeddables.putAll(embeddables);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Adds mapped super class to mapped super class collection.\r\n     * \r\n     * @param mappedSuperClass\r\n     *            the mappedSuperClassTypes to set\r\n     */\r\n    public void assignMappedSuperClass(Map<Class<?>, ManagedType<?>> mappedSuperClass)\r\n    {\r\n        if (this.mappedSuperClassTypes == null)\r\n        {\r\n            this.mappedSuperClassTypes = mappedSuperClass;\r\n        }\r\n        else\r\n        {\r\n            this.mappedSuperClassTypes.putAll(mappedSuperClassTypes);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Returns true, if attribute is embeddable.\r\n     * \r\n     * @param embeddableClazz\r\n     *            class for embeddable type attribute.\r\n     * @return try, if paramterized class is of embeddable java type.\r\n     */\r\n    public boolean isEmbeddable(Class embeddableClazz)\r\n    {\r\n        return embeddables != null ? embeddables.containsKey(embeddableClazz)\r\n                && embeddables.get(embeddableClazz).getPersistenceType().equals(PersistenceType.EMBEDDABLE) : false;\r\n    }\r\n\r\n    /**\r\n     * Returns entity attribute for given managed entity class.\r\n     * \r\n     * @param clazz\r\n     *            Entity class\r\n     * @param fieldName\r\n     *            field name\r\n     * @return entity attribute\r\n     */\r\n    public Attribute getEntityAttribute(Class clazz, String fieldName)\r\n    {\r\n        if (entityTypes != null && entityTypes.containsKey(clazz))\r\n        {\r\n            EntityType entityType = entityTypes.get(clazz);\r\n            return entityType.getAttribute(fieldName);\r\n        }\r\n        throw new IllegalArgumentException(\"No entity found: \" + clazz);\r\n    }\r\n\r\n    /**\r\n     * Custom implementation to offer map of embeddables available for given\r\n     * entityType.\r\n     * \r\n     * @param clazz\r\n     *            entity class\r\n     * @return map of holding {@link EmbeddableType} as value and attribute name\r\n     *         as key.\r\n     */\r\n    public Map<String, EmbeddableType> getEmbeddables(Class clazz)\r\n    {\r\n        Map<String, EmbeddableType> embeddableAttibutes = new HashMap<String, EmbeddableType>();\r\n\r\n        if (entityTypes != null)\r\n        {\r\n            EntityType entity = entityTypes.get(clazz);\r\n            Iterator<Attribute> iter = entity.getAttributes().iterator();\r\n            while (iter.hasNext())\r\n            {\r\n                Attribute attribute = iter.next();\r\n                if (isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType()))\r\n                {\r\n                    embeddableAttibutes.put(attribute.getName(),\r\n                            embeddable(((AbstractAttribute) attribute).getBindableJavaType()));\r\n                }\r\n            }\r\n        }\r\n        return embeddableAttibutes;\r\n    }\r\n\r\n    /**\r\n     * @return the keyValues\r\n     */\r\n    public IdDiscriptor getKeyValue(String entityName)\r\n    {\r\n        if (keyValues != null)\r\n        {\r\n            return this.keyValues.get(entityName);\r\n        }\r\n        return null;\r\n    }\r\n\r\n    /**\r\n     * @param keyValues\r\n     *            the keyValues to set\r\n     */\r\n    public void addKeyValues(Map<String, IdDiscriptor> keyDiscriptors)\r\n    {\r\n        if (keyValues == null)\r\n        {\r\n            keyValues = new HashMap<String, IdDiscriptor>();\r\n        }\r\n        this.keyValues.putAll(keyDiscriptors);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/PersistenceUnitMetadata.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.model;\r\n\r\nimport java.io.File;\r\nimport java.net.MalformedURLException;\r\nimport java.net.URL;\r\nimport java.util.ArrayList;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Properties;\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.SharedCacheMode;\r\nimport javax.persistence.ValidationMode;\r\nimport javax.persistence.spi.ClassTransformer;\r\nimport javax.persistence.spi.PersistenceUnitInfo;\r\nimport javax.persistence.spi.PersistenceUnitTransactionType;\r\nimport javax.sql.DataSource;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.PersistenceProperties;\r\nimport com.impetus.kundera.loader.PersistenceLoaderException;\r\n\r\n/**\r\n * The Class PersistenceUnitMetadata.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class PersistenceUnitMetadata implements PersistenceUnitInfo\r\n{\r\n    /** logger instance. */\r\n    private static Logger log = LoggerFactory.getLogger(PersistenceUnitMetadata.class);\r\n\r\n    /** Persistence Unit name. */\r\n    private String persistenceUnitName;\r\n\r\n    /** The provider. */\r\n    private String provider;\r\n\r\n    /** The transaction type. */\r\n    private PersistenceUnitTransactionType transactionType;\r\n\r\n    /** The classes. */\r\n    private List<String> classes = new ArrayList<String>();\r\n\r\n    /** The packages. */\r\n    private List<String> packages = new ArrayList<String>();\r\n\r\n    /** The jar files. */\r\n    private Set<String> jarFiles;\r\n\r\n    private Set<URL> jarUrls;\r\n\r\n    /** The properties. */\r\n    private Properties properties = new Properties();\r\n\r\n    /** The exclude unlisted classes. */\r\n    private boolean excludeUnlistedClasses = false;\r\n\r\n    private URL rootUrl;\r\n\r\n    private String schemaVersion;\r\n\r\n    private URL mappedUrl;\r\n\r\n    public PersistenceUnitMetadata()\r\n    {\r\n\r\n    }\r\n\r\n    public PersistenceUnitMetadata(String xmlSchemaVersion, URL rootUrl, URL mappingFileUrl)\r\n    {\r\n        this.schemaVersion = xmlSchemaVersion;\r\n        this.rootUrl = rootUrl;\r\n        this.mappedUrl = mappingFileUrl;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.spi.PersistenceUnitInfo#getPersistenceUnitName()\r\n     */\r\n    @Override\r\n    public String getPersistenceUnitName()\r\n    {\r\n        return persistenceUnitName;\r\n    }\r\n\r\n    /**\r\n     * Sets the persistence unit name.\r\n     * \r\n     * @param persistenceUnitName\r\n     *            the persistenceUnitName to set\r\n     */\r\n    public void setPersistenceUnitName(String persistenceUnitName)\r\n    {\r\n        this.persistenceUnitName = persistenceUnitName;\r\n    }\r\n\r\n    /**\r\n     * Sets the transaction type.\r\n     * \r\n     * @param transactionType\r\n     *            the new transaction type\r\n     */\r\n    public void setTransactionType(PersistenceUnitTransactionType transactionType)\r\n    {\r\n        this.transactionType = transactionType;\r\n    }\r\n\r\n    /**\r\n     * Sets the provider.\r\n     * \r\n     * @param provider\r\n     *            the new provider\r\n     */\r\n    public void setProvider(String provider)\r\n    {\r\n        if (provider != null && provider.endsWith(\".class\"))\r\n        {\r\n            this.provider = provider.substring(0, provider.length() - 6);\r\n        }\r\n        this.provider = provider;\r\n    }\r\n\r\n    /**\r\n     * Gets the classes.\r\n     * \r\n     * @return the classes\r\n     */\r\n    public List<String> getClasses()\r\n    {\r\n        return classes;\r\n    }\r\n\r\n    /**\r\n     * Sets the classes.\r\n     * \r\n     * @param classes\r\n     *            the new classes\r\n     */\r\n    public void setClasses(List<String> classes)\r\n    {\r\n        this.classes = classes;\r\n    }\r\n\r\n    /**\r\n     * Gets the packages.\r\n     * \r\n     * @return the packages\r\n     */\r\n    public List<String> getPackages()\r\n    {\r\n        return packages;\r\n    }\r\n\r\n    /**\r\n     * Sets the packages.\r\n     * \r\n     * @param packages\r\n     *            the new packages\r\n     */\r\n    public void setPackages(List<String> packages)\r\n    {\r\n        this.packages = packages;\r\n    }\r\n\r\n    /**\r\n     * Gets the jar files.\r\n     * \r\n     * @return the jar files\r\n     */\r\n    public Set<String> getJarFiles()\r\n    {\r\n        return jarFiles;\r\n    }\r\n\r\n    /**\r\n     * Sets the jar files.\r\n     * \r\n     * @param jarFiles\r\n     *            the new jar files\r\n     */\r\n    public void addJarFile(String jarFile)\r\n    {\r\n        if (jarFiles == null)\r\n        {\r\n            jarFiles = new HashSet<String>();\r\n        }\r\n        this.jarFiles.add(jarFile);\r\n        addJarFileUrl(jarFile);\r\n\r\n    }\r\n\r\n    /**\r\n     * Gets the exclude unlisted classes.\r\n     * \r\n     * @return the exclude unlisted classes\r\n     */\r\n    public boolean getExcludeUnlistedClasses()\r\n    {\r\n        return excludeUnlistedClasses;\r\n    }\r\n\r\n    /**\r\n     * Sets the exclude unlisted classes.\r\n     * \r\n     * @param excludeUnlistedClasses\r\n     *            the new exclude unlisted classes\r\n     */\r\n    public void setExcludeUnlistedClasses(boolean excludeUnlistedClasses)\r\n    {\r\n        this.excludeUnlistedClasses = excludeUnlistedClasses;\r\n    }\r\n\r\n    /* @see java.lang.Object#toString() */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see java.lang.Object#toString()\r\n     */\r\n    @Override\r\n    public String toString()\r\n    {\r\n        StringBuilder builder = new StringBuilder();\r\n        builder.append(\"PersistenceMetadata [name=\");\r\n        builder.append(persistenceUnitName);\r\n        builder.append(\", provider=\");\r\n        builder.append(provider);\r\n        builder.append(\", transactionType=\");\r\n        builder.append(transactionType);\r\n        builder.append(\", classes=\");\r\n        builder.append(classes);\r\n        builder.append(\", excludeUnlistedClasses=\");\r\n        builder.append(excludeUnlistedClasses);\r\n        builder.append(\", jarFiles=\");\r\n        builder.append(jarFiles);\r\n        builder.append(\", packages=\");\r\n        builder.append(packages);\r\n        builder.append(\", props=\");\r\n        builder.append(properties);\r\n        builder.append(\"]\");\r\n        return builder.toString();\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * javax.persistence.spi.PersistenceUnitInfo#getPersistenceProviderClassName\r\n     * ()\r\n     */\r\n    @Override\r\n    public String getPersistenceProviderClassName()\r\n    {\r\n        return provider;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.spi.PersistenceUnitInfo#getTransactionType()\r\n     */\r\n    @Override\r\n    public PersistenceUnitTransactionType getTransactionType()\r\n    {\r\n        return transactionType;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.spi.PersistenceUnitInfo#getJtaDataSource()\r\n     */\r\n    @Override\r\n    public DataSource getJtaDataSource()\r\n    {\r\n        return null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.spi.PersistenceUnitInfo#getNonJtaDataSource()\r\n     */\r\n    @Override\r\n    public DataSource getNonJtaDataSource()\r\n    {\r\n        return null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.spi.PersistenceUnitInfo#getMappingFileNames()\r\n     */\r\n    @Override\r\n    public List<String> getMappingFileNames()\r\n    {\r\n        return null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.spi.PersistenceUnitInfo#getJarFileUrls()\r\n     */\r\n    @Override\r\n    public List<URL> getJarFileUrls()\r\n    {\r\n        return jarUrls != null ? new ArrayList<URL>(jarUrls) : null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * javax.persistence.spi.PersistenceUnitInfo#getPersistenceUnitRootUrl()\r\n     */\r\n    @Override\r\n    public URL getPersistenceUnitRootUrl()\r\n    {\r\n        return rootUrl;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.spi.PersistenceUnitInfo#getManagedClassNames()\r\n     */\r\n    @Override\r\n    public List<String> getManagedClassNames()\r\n    {\r\n        return classes;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.spi.PersistenceUnitInfo#excludeUnlistedClasses()\r\n     */\r\n    @Override\r\n    public boolean excludeUnlistedClasses()\r\n    {\r\n        return excludeUnlistedClasses;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.spi.PersistenceUnitInfo#getSharedCacheMode()\r\n     */\r\n    @Override\r\n    public SharedCacheMode getSharedCacheMode()\r\n    {\r\n        return null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.spi.PersistenceUnitInfo#getValidationMode()\r\n     */\r\n    @Override\r\n    public ValidationMode getValidationMode()\r\n    {\r\n        return null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.spi.PersistenceUnitInfo#getProperties()\r\n     */\r\n    @Override\r\n    public Properties getProperties()\r\n    {\r\n        if (this.properties == null)\r\n        {\r\n            throw new PersistenceLoaderException(\" Error while loading metadata as perssitenceUnitMetadata is null\");\r\n        }\r\n        return this.properties;\r\n    }\r\n\r\n    /**\r\n     * Sets the properties.\r\n     * \r\n     * @param properties\r\n     *            the properties to set\r\n     */\r\n    public void setProperties(Properties properties)\r\n    {\r\n        this.properties = properties;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * javax.persistence.spi.PersistenceUnitInfo#getPersistenceXMLSchemaVersion\r\n     * ()\r\n     */\r\n    @Override\r\n    public String getPersistenceXMLSchemaVersion()\r\n    {\r\n        return schemaVersion;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.spi.PersistenceUnitInfo#getClassLoader()\r\n     */\r\n    @Override\r\n    public ClassLoader getClassLoader()\r\n    {\r\n        return this.getClass().getClassLoader();\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * javax.persistence.spi.PersistenceUnitInfo#addTransformer(javax.persistence\r\n     * .spi.ClassTransformer)\r\n     */\r\n    @Override\r\n    public void addTransformer(ClassTransformer paramClassTransformer)\r\n    {\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.spi.PersistenceUnitInfo#getNewTempClassLoader()\r\n     */\r\n    @Override\r\n    public ClassLoader getNewTempClassLoader()\r\n    {\r\n        return null;\r\n    }\r\n\r\n    /**\r\n     * Gets the property.\r\n     * \r\n     * @param prop\r\n     *            the prop\r\n     * @return the property\r\n     */\r\n    public String getProperty(String prop)\r\n    {\r\n        // assuming Properties are initialized with this call\r\n        return prop != null ? getProperties().getProperty(prop) : null;\r\n    }\r\n\r\n    /**\r\n     * Returns list of managed urls.\r\n     * \r\n     * @return\r\n     */\r\n    public List<URL> getManagedURLs()\r\n    {\r\n        // should we cache it?\r\n        List<URL> managedURL = getJarFileUrls();\r\n        if (managedURL == null)\r\n        {\r\n            managedURL = new ArrayList<URL>(1);\r\n        }\r\n\r\n        if (!getExcludeUnlistedClasses())\r\n        {\r\n            managedURL.add(getPersistenceUnitRootUrl());\r\n        }\r\n        return managedURL;\r\n    }\r\n\r\n    /**\r\n     * Adds jar file URL.\r\n     * \r\n     * @param jarFile\r\n     *            jar file path\r\n     */\r\n    private void addJarFileUrl(String jarFile)\r\n    {\r\n        if (jarUrls == null)\r\n        {\r\n            jarUrls = new HashSet<URL>();\r\n        }\r\n        try\r\n        {\r\n            jarUrls.add(new File(jarFile).toURI().toURL());\r\n        }\r\n        catch (MalformedURLException e)\r\n        {\r\n            log.error(\"Error while mapping jar-file url\" + jarFile + \"caused by:\" + e.getMessage());\r\n            throw new IllegalArgumentException(\"Invalid jar-file URL:\" + jarFile + \"Caused by: \" + e);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Gets the client. In case client is not configure, it throws\r\n     * IllegalArgumentException.\r\n     * \r\n     * @return the client\r\n     */\r\n    public String getClient()\r\n    {\r\n        String client = null;\r\n        if (this.properties != null)\r\n        {\r\n            client = (String) this.properties.get(PersistenceProperties.KUNDERA_CLIENT_FACTORY);\r\n        }\r\n\r\n        if (client == null)\r\n        {\r\n            log.error(\"kundera.client property is missing for persistence unit:\" + persistenceUnitName);\r\n            throw new IllegalArgumentException(\"kundera.client property is missing for persistence unit:\"\r\n                    + persistenceUnitName);\r\n        }\r\n\r\n        return client;\r\n    }\r\n\r\n    /**\r\n     * Returns true, if pu is specified with batch size.\r\n     * \r\n     * @return true, if pu consists batch.size property.\r\n     */\r\n    private boolean isBatch()\r\n    {\r\n        return getProperty(PersistenceProperties.KUNDERA_BATCH_SIZE) != null;\r\n    }\r\n\r\n    /**\r\n     * Return batch.size value.\r\n     * \r\n     * @return integer value for batch size.\r\n     */\r\n    public int getBatchSize()\r\n    {\r\n        if (isBatch())\r\n        {\r\n            String batchSize = getProperty(PersistenceProperties.KUNDERA_BATCH_SIZE);\r\n            int batch_Size = Integer.valueOf(batchSize);\r\n            if (batch_Size == 0)\r\n            {\r\n                throw new IllegalArgumentException(\"kundera.batch.size property must be numeric and > 0\");\r\n            }\r\n            return batch_Size;\r\n        }\r\n\r\n        return 0;\r\n    }\r\n\r\n    /**\r\n     * @return the mappedUrl\r\n     */\r\n    public URL getMappedUrl()\r\n    {\r\n        return mappedUrl;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/PropertyIndex.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.model;\r\n\r\nimport java.lang.reflect.Field;\r\n\r\n/**\r\n * Contains Index information of a field.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic final class PropertyIndex\r\n{\r\n\r\n    /** The name. */\r\n    private String name;\r\n\r\n    /** The property. */\r\n    private Field property;\r\n\r\n    private String indexType;\r\n\r\n    /** The boost. */\r\n    private float boost = 1.0f;\r\n\r\n    private Integer max;\r\n\r\n    private Integer min;\r\n\r\n    /**\r\n     * Instantiates a new property index.\r\n     * \r\n     * @param property\r\n     *            the property\r\n     * @param name\r\n     *            the name\r\n     */\r\n    public PropertyIndex(Field property, String name, String indexType)\r\n    {\r\n        this.property = property;\r\n        this.name = name;\r\n        this.indexType = indexType;\r\n    }\r\n\r\n    /**\r\n     * Gets the name.\r\n     * \r\n     * @return the name\r\n     */\r\n    public String getName()\r\n    {\r\n        return name;\r\n    }\r\n\r\n    /**\r\n     * Gets the property.\r\n     * \r\n     * @return the property\r\n     */\r\n    public Field getProperty()\r\n    {\r\n        return property;\r\n    }\r\n\r\n    /**\r\n     * Gets the boost.\r\n     * \r\n     * @return the boost\r\n     */\r\n    public float getBoost()\r\n    {\r\n        return boost;\r\n    }\r\n\r\n    /**\r\n     * Sets the boost.\r\n     * \r\n     * @param boost\r\n     *            the new boost\r\n     */\r\n    public void setBoost(float boost)\r\n    {\r\n        this.boost = boost;\r\n    }\r\n\r\n    /**\r\n     * @return the indexType\r\n     */\r\n    public String getIndexType()\r\n    {\r\n        return indexType;\r\n    }\r\n\r\n    /**\r\n     * @return the max\r\n     */\r\n    public Integer getMax()\r\n    {\r\n        return max;\r\n    }\r\n\r\n    /**\r\n     * @param max\r\n     *            the max to set\r\n     */\r\n    public void setMax(Integer max)\r\n    {\r\n        this.max = max;\r\n    }\r\n\r\n    /**\r\n     * @return the min\r\n     */\r\n    public Integer getMin()\r\n    {\r\n        return min;\r\n    }\r\n\r\n    /**\r\n     * @param min\r\n     *            the min to set\r\n     */\r\n    public void setMin(Integer min)\r\n    {\r\n        this.min = min;\r\n    }\r\n\r\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/Relation.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.model;\r\n\r\nimport java.lang.reflect.Field;\r\nimport java.lang.reflect.ParameterizedType;\r\nimport java.lang.reflect.Type;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.JoinColumn;\r\n\r\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\r\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\nimport com.impetus.kundera.property.PropertyAccessorHelper;\r\nimport com.impetus.kundera.utils.ReflectUtils;\r\n\r\n/**\r\n * The Class Relation.\r\n */\r\npublic final class Relation\r\n{\r\n\r\n    /** The property. */\r\n    private Field property;\r\n\r\n    /** The target entity. */\r\n    private Class<?> targetEntity;\r\n\r\n    /** If relation is through a Map, Map Key Join Class */\r\n    private Class<?> mapKeyJoinClass;\r\n\r\n    /** The property type. */\r\n    private Class<?> propertyType;\r\n\r\n    /** The fetch type. */\r\n    private FetchType fetchType;\r\n\r\n    /** The cascades. */\r\n    private List<CascadeType> cascades;\r\n\r\n    /** The optional. */\r\n    private boolean optional;\r\n\r\n    /** The mapped by. */\r\n    private String mappedBy;\r\n\r\n    /** The type. */\r\n    private Relation.ForeignKey type;\r\n\r\n    /** Join column name for this relationship. */\r\n    private String joinColumnName;\r\n\r\n    /** Whether this relationship is through a Join Table. */\r\n    private boolean isRelatedViaJoinTable;\r\n\r\n    /** Metadata for JoinTable, applicable only if isRelatedViaJoinTable==true. */\r\n    private JoinTableMetadata joinTableMetadata;\r\n\r\n    /** Target entity metadata. */\r\n    private EntityMetadata targetEntityMetadata;\r\n    /**\r\n     * Whether this relationship is joined by primary key, only applicable for\r\n     * OneToOne.\r\n     */\r\n    private boolean isJoinedByPrimaryKey;\r\n\r\n    private Field biDirectionalField; \r\n    /**\r\n     * \r\n     * The Enum ForeignKey.\r\n     */\r\n    public static enum ForeignKey\r\n    {\r\n        /** The ON e_ t o_ one. */\r\n        ONE_TO_ONE,\r\n        /** The ON e_ t o_ many. */\r\n        ONE_TO_MANY,\r\n        /** The MAN y_ t o_ one. */\r\n        MANY_TO_ONE,\r\n        /** The MAN y_ t o_ many. */\r\n        MANY_TO_MANY\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new relation.\r\n     * \r\n     * @param property\r\n     *            the property\r\n     * @param targetEntity\r\n     *            the target entity\r\n     * @param propertyType\r\n     *            the property type\r\n     * @param fetchType\r\n     *            the fetch type\r\n     * @param cascades\r\n     *            the cascades\r\n     * @param optional\r\n     *            the optional\r\n     * @param mappedBy\r\n     *            the mapped by\r\n     * @param type\r\n     *            the type\r\n     */\r\n\r\n    /**\r\n     * Specifies the type of the metadata.\r\n     */\r\n\r\n    public Relation(Field property, Class<?> targetEntity, Class<?> propertyType, FetchType fetchType,\r\n            List<CascadeType> cascades, boolean optional, String mappedBy, Relation.ForeignKey type)\r\n    {\r\n        super();\r\n        this.property = property;\r\n        this.targetEntity = targetEntity;\r\n        this.propertyType = propertyType;\r\n        this.fetchType = fetchType;\r\n        this.cascades = cascades;\r\n        this.optional = optional;\r\n        this.mappedBy = mappedBy;\r\n        this.type = type;\r\n    }\r\n\r\n    /**\r\n     * Gets the property.\r\n     * \r\n     * @return the property\r\n     */\r\n    public Field getProperty()\r\n    {\r\n        return property;\r\n    }\r\n\r\n    /**\r\n     * Gets the target entity.\r\n     * \r\n     * @return the targetEntity\r\n     */\r\n    public Class<?> getTargetEntity()\r\n    {\r\n        return targetEntity;\r\n    }\r\n\r\n    /**\r\n     * @return the mapKeyJoinClass\r\n     */\r\n    public Class<?> getMapKeyJoinClass()\r\n    {\r\n        return mapKeyJoinClass;\r\n    }\r\n\r\n    /**\r\n     * @param mapKeyJoinClass\r\n     *            the mapKeyJoinClass to set\r\n     */\r\n    public void setMapKeyJoinClass(Class<?> mapKeyJoinClass)\r\n    {\r\n        this.mapKeyJoinClass = mapKeyJoinClass;\r\n    }\r\n\r\n    /**\r\n     * Gets the property type.\r\n     * \r\n     * @return the propertyType\r\n     */\r\n    public Class<?> getPropertyType()\r\n    {\r\n        return propertyType;\r\n    }\r\n\r\n    /**\r\n     * Gets the fetch type.\r\n     * \r\n     * @return the fetchType\r\n     */\r\n    public FetchType getFetchType()\r\n    {\r\n        return fetchType;\r\n    }\r\n\r\n    /**\r\n     * Gets the cascades.\r\n     * \r\n     * @return the cascades\r\n     */\r\n    public List<CascadeType> getCascades()\r\n    {\r\n        return cascades;\r\n    }\r\n\r\n    /**\r\n     * Checks if is optional.\r\n     * \r\n     * @return the optional\r\n     */\r\n    public boolean isOptional()\r\n    {\r\n        return optional;\r\n    }\r\n\r\n    /**\r\n     * Gets the mapped by.\r\n     * \r\n     * @return the mappedBy\r\n     */\r\n    public String getMappedBy()\r\n    {\r\n        return mappedBy;\r\n    }\r\n\r\n    /**\r\n     * Gets the type.\r\n     * \r\n     * @return the type\r\n     */\r\n    public Relation.ForeignKey getType()\r\n    {\r\n        return type;\r\n    }\r\n\r\n    /**\r\n     * Gets the join column name.\r\n     * \r\n     * @return the joinColumnName\r\n     */\r\n    public String getJoinColumnName(final KunderaMetadata kunderaMetadata)\r\n    {\r\n                \r\n        if(joinColumnName == null && isJoinedByPrimaryKey)\r\n        {\r\n            EntityMetadata joinClassMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, targetEntity);\r\n            joinColumnName  = ((AbstractAttribute)joinClassMetadata.getIdAttribute()).getJPAColumnName();\r\n        }\r\n        \r\n        if(joinTableMetadata != null)\r\n        {\r\n            joinColumnName = joinTableMetadata.getJoinColumns() != null? joinTableMetadata.getJoinColumns().iterator().next():null;\r\n        }\r\n        \r\n        if(isBiDirectional())\r\n        {\r\n            // Give precedence to join column name!\r\n            if(biDirectionalField.isAnnotationPresent(JoinColumn.class))\r\n            {\r\n                joinColumnName = biDirectionalField.getAnnotation(JoinColumn.class).name();\r\n            }\r\n        }\r\n        \r\n        return joinColumnName !=null? joinColumnName:property.getName();\r\n    }\r\n\r\n    /**\r\n     * Sets the join column name.\r\n     * \r\n     * @param joinColumnName\r\n     *            the joinColumnName to set\r\n     */\r\n    public void setJoinColumnName(String joinColumnName)\r\n    {\r\n        this.joinColumnName = joinColumnName;\r\n    }\r\n\r\n    /**\r\n     * Checks if is related via join table.\r\n     * \r\n     * @return the isRelatedViaJoinTable\r\n     */\r\n    public boolean isRelatedViaJoinTable()\r\n    {\r\n        return isRelatedViaJoinTable;\r\n    }\r\n\r\n    /**\r\n     * Sets the related via join table.\r\n     * \r\n     * @param isRelatedViaJoinTable\r\n     *            the isRelatedViaJoinTable to set\r\n     */\r\n    public void setRelatedViaJoinTable(boolean isRelatedViaJoinTable)\r\n    {\r\n        this.isRelatedViaJoinTable = isRelatedViaJoinTable;\r\n    }\r\n\r\n    /**\r\n     * Gets the join table metadata.\r\n     * \r\n     * @return the joinTableMetadata\r\n     */\r\n    public JoinTableMetadata getJoinTableMetadata()\r\n    {\r\n        return joinTableMetadata;\r\n    }\r\n\r\n    /**\r\n     * Sets the join table metadata.\r\n     * \r\n     * @param joinTableMetadata\r\n     *            the joinTableMetadata to set\r\n     */\r\n    public void setJoinTableMetadata(JoinTableMetadata joinTableMetadata)\r\n    {\r\n        this.joinTableMetadata = joinTableMetadata;\r\n    }\r\n\r\n    /**\r\n     * Checks if is joined by primary key.\r\n     * \r\n     * @return the isJoinedByPrimaryKey\r\n     */\r\n    public boolean isJoinedByPrimaryKey()\r\n    {\r\n        return isJoinedByPrimaryKey;\r\n    }\r\n\r\n    /**\r\n     * Sets the joined by primary key.\r\n     * \r\n     * @param isJoinedByPrimaryKey\r\n     *            the isJoinedByPrimaryKey to set\r\n     */\r\n    public void setJoinedByPrimaryKey(boolean isJoinedByPrimaryKey)\r\n    {\r\n        this.isJoinedByPrimaryKey = isJoinedByPrimaryKey;\r\n    }\r\n\r\n    /**\r\n     * Checks if is unary.\r\n     * \r\n     * @return true, if is unary\r\n     */\r\n    public boolean isUnary()\r\n    {\r\n        return type.equals(Relation.ForeignKey.ONE_TO_ONE) || type.equals(Relation.ForeignKey.MANY_TO_ONE);\r\n    }\r\n\r\n    /**\r\n     * Checks if is collection.\r\n     * \r\n     * @return true, if is collection\r\n     */\r\n    public boolean isCollection()\r\n    {\r\n        return type.equals(Relation.ForeignKey.ONE_TO_MANY) || type.equals(Relation.ForeignKey.MANY_TO_MANY);\r\n    }\r\n\r\n\r\n    public boolean isBiDirectional()\r\n    {\r\n        return biDirectionalField != null;       \r\n    }\r\n    \r\n    public Field getBiDirectionalField()\r\n    {\r\n        return biDirectionalField;\r\n    }\r\n    \r\n    public void setBiDirectionalField(Class referencedClass)\r\n    {\r\n        Field[] fields = this.getTargetEntity().getDeclaredFields();\r\n        Class<?> clazzz = null;\r\n        for (Field field : fields)\r\n        {\r\n            if (!ReflectUtils.isTransientOrStatic(field))\r\n            {\r\n                clazzz = field.getType();\r\n                if (PropertyAccessorHelper.isCollection(clazzz))\r\n                {\r\n                    ParameterizedType type = (ParameterizedType) field.getGenericType();\r\n                    Type[] types = type.getActualTypeArguments();\r\n                    clazzz = (Class<?>) types[0];\r\n                }\r\n                else if (Map.class.isAssignableFrom(clazzz))\r\n                {\r\n                    ParameterizedType type = (ParameterizedType) field.getGenericType();\r\n                    Type[] types = type.getActualTypeArguments();\r\n                    clazzz = (Class<?>) types[1];\r\n                }\r\n                if (clazzz.equals(referencedClass))\r\n                {\r\n                    biDirectionalField = field;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n \r\n    }\r\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/SequenceGeneratorDiscriptor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model;\n\nimport javax.persistence.SequenceGenerator;\n\n/**\n * SequenceGeneratorDiscriptor class holds the information about sequence\n * generator.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class SequenceGeneratorDiscriptor\n{\n    private static final int default_initial_value = 1;\n\n    private static final String default_sequence_name = \"sequence_name\";\n\n    private static final int default_allocation_size = 50;\n\n    private int initialValue;\n\n    private int allocationSize;\n\n    private String sequenceName;\n\n    private String schemaName;\n\n    private String catalog;\n\n    public SequenceGeneratorDiscriptor(SequenceGenerator sequenceGenerator, String defaultSchemaName)\n    {\n        this.initialValue = sequenceGenerator.initialValue();\n        this.allocationSize = sequenceGenerator.allocationSize();\n        this.sequenceName = sequenceGenerator.sequenceName().isEmpty() ? default_sequence_name : sequenceGenerator\n                .sequenceName();\n        this.schemaName = sequenceGenerator.schema().isEmpty() ? defaultSchemaName : sequenceGenerator.schema();\n    }\n\n    public SequenceGeneratorDiscriptor(String defaultSchemaName)\n    {\n        this.initialValue = default_initial_value;\n        this.allocationSize = default_allocation_size;\n        this.sequenceName = default_sequence_name;\n        this.schemaName = defaultSchemaName;\n    }\n\n    /**\n     * @return the initialValue\n     */\n    public int getInitialValue()\n    {\n        return initialValue;\n    }\n\n    /**\n     * @return the allocationSize\n     */\n    public int getAllocationSize()\n    {\n        return allocationSize;\n    }\n\n    /**\n     * @return the sequenceName\n     */\n    public String getSequenceName()\n    {\n        return sequenceName;\n    }\n\n    /**\n     * @return the schemaName\n     */\n    public String getSchemaName()\n    {\n        return schemaName;\n    }\n\n    /**\n     * @return the catalog\n     */\n    public String getCatalog()\n    {\n        return catalog;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/TableGeneratorDiscriptor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model;\n\nimport javax.persistence.TableGenerator;\nimport javax.persistence.UniqueConstraint;\n\n/**\n * TableGeneratorDiscriptor class holds the information about table generator.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class TableGeneratorDiscriptor\n{\n    private static final String default_table_name = \"kundera_sequences\";\n\n    private static final String default_pkColumn_name = \"sequence_name\";\n\n    private static final String default_valueColumn_name = \"sequence_value\";\n\n    private static final int default_allocation_size = 50;\n\n    private static final int default_initial_value = 1;\n\n    private String table;\n\n    private String catalog;\n\n    private String schema;\n\n    private String pkColumnName;\n\n    private String valueColumnName;\n\n    private String pkColumnValue;\n\n    private int initialValue;\n\n    private int allocationSize;\n\n    private UniqueConstraint[] uniqueConstraints;\n\n    public TableGeneratorDiscriptor(TableGenerator tableGenerator, String defaultSchemaName, String defaultPkColumnValue)\n    {\n        this.table = tableGenerator.table().isEmpty() ? default_table_name : tableGenerator.table();\n        this.schema = tableGenerator.schema().isEmpty() ? defaultSchemaName : tableGenerator.schema();\n        this.pkColumnName = tableGenerator.pkColumnName().isEmpty() ? default_pkColumn_name : tableGenerator\n                .pkColumnName();\n        this.valueColumnName = tableGenerator.valueColumnName().isEmpty() ? default_valueColumn_name : tableGenerator\n                .valueColumnName();\n        this.pkColumnValue = tableGenerator.pkColumnValue().isEmpty() ? defaultPkColumnValue : tableGenerator\n                .pkColumnValue();\n        this.initialValue = tableGenerator.initialValue() != 0 ? tableGenerator.initialValue() : default_initial_value;\n        this.allocationSize = tableGenerator.allocationSize();\n    }\n\n    public TableGeneratorDiscriptor(String defaultSchemaName, String defaultPkColumnValue)\n    {\n        this.table = default_table_name;\n        this.schema = defaultSchemaName;\n        this.pkColumnName = default_pkColumn_name;\n        this.valueColumnName = default_valueColumn_name;\n        this.pkColumnValue = defaultPkColumnValue;\n        this.initialValue = default_initial_value;\n        this.allocationSize = default_allocation_size;\n    }\n\n    /**\n     * @return the table\n     */\n    public String getTable()\n    {\n        return table;\n    }\n\n    /**\n     * @return the catalog\n     */\n    public String getCatalog()\n    {\n        return catalog;\n    }\n\n    /**\n     * @return the schema\n     */\n    public String getSchema()\n    {\n        return schema;\n    }\n\n    /**\n     * @return the pkColumnName\n     */\n    public String getPkColumnName()\n    {\n        return pkColumnName;\n    }\n\n    /**\n     * @return the valueColumnName\n     */\n    public String getValueColumnName()\n    {\n        return valueColumnName;\n    }\n\n    /**\n     * @return the pkColumnValue\n     */\n    public String getPkColumnValue()\n    {\n        return pkColumnValue;\n    }\n\n    /**\n     * @return the initialValue\n     */\n    public int getInitialValue()\n    {\n        return initialValue;\n    }\n\n    /**\n     * @return the allocationSize\n     */\n    public int getAllocationSize()\n    {\n        return allocationSize;\n    }\n\n    /**\n     * @return the uniqueConstraints\n     */\n    public UniqueConstraint[] getUniqueConstraints()\n    {\n        return uniqueConstraints;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/annotation/DefaultEntityAnnotationProcessor.java",
    "content": "package com.impetus.kundera.metadata.model.annotation;\n\nimport java.lang.annotation.Annotation;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.SecondaryTable;\nimport javax.persistence.SecondaryTables;\n\npublic class DefaultEntityAnnotationProcessor implements EntityAnnotationProcessor\n{\n    private Map<String, Annotation> entityAnnotations;\n\n    public DefaultEntityAnnotationProcessor(Class clazz)\n    {\n        entityAnnotations = new HashMap<String, Annotation>();\n        processEntityAnnotations(clazz);\n    }\n\n    @Override\n    public Map<String, Annotation> getAnnotations()\n    {\n        return entityAnnotations;\n    }\n\n    @Override\n    public Annotation getAnnotation(String annotationName)\n    {\n        return entityAnnotations.get(annotationName);\n    }\n\n    @Override\n    public void validateClassAnnotation(Annotation annotation, Class clazz)\n    {\n\n    }\n\n    private void processEntityAnnotations(Class clazz)\n    {\n        if (clazz != null)\n        {\n            Annotation[] annotations = clazz.getAnnotations();\n            for (Annotation annotation : annotations)\n            {\n                entityAnnotations.put(annotation.annotationType().getName(), annotation);\n            }\n        }\n    }\n\n    public List<String> getSecondaryTablesName()\n    {\n        List<String> tables = new ArrayList<String>();\n\n        SecondaryTables secondaryTablesAnnotation = (SecondaryTables) getAnnotation(SecondaryTables.class.getName());\n\n        SecondaryTable secondaryTableAnnotation = (SecondaryTable) getAnnotation(SecondaryTable.class.getName());\n\n        if (secondaryTablesAnnotation != null)\n        {\n            SecondaryTable[] secondaryTables = secondaryTablesAnnotation.value();\n\n            for (SecondaryTable secondaryTable : secondaryTables)\n            {\n                tables.add(secondaryTable.name());\n            }\n        }\n        else if (secondaryTableAnnotation != null)\n        {\n            tables.add(secondaryTableAnnotation.name());\n        }\n        return tables;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/annotation/DefaultFieldAnnotationProcessor.java",
    "content": "package com.impetus.kundera.metadata.model.annotation;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.Column;\nimport javax.persistence.Table;\nimport javax.persistence.metamodel.ManagedType;\n\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.metadata.validator.InvalidEntityDefinitionException;\n\npublic class DefaultFieldAnnotationProcessor implements FieldAnnotationProcessor\n{\n    private Map<String, Annotation> fieldAnnotations;\n\n    public DefaultFieldAnnotationProcessor(Field field)\n    {\n        fieldAnnotations = new HashMap<String, Annotation>();\n        processFieldAnnotations(field);\n    }\n\n    @Override\n    public Map<String, Annotation> getAnnotations()\n    {\n        return fieldAnnotations;\n    }\n\n    @Override\n    public Annotation getAnnotation(String annotationName)\n    {\n        return fieldAnnotations.get(annotationName);\n    }\n\n    @Override\n    public void validateFieldAnnotation(Annotation annotation, Field field, ManagedType managedType)\n    {\n\n        List<String> tables = ((DefaultEntityAnnotationProcessor) ((AbstractManagedType) managedType)\n                .getEntityAnnotation()).getSecondaryTablesName();\n\n        Annotation primaryTableannotation = ((AbstractManagedType) managedType).getEntityAnnotation().getAnnotation(\n                Table.class.getName());\n\n        String primaryTableName = \"\";\n        if (primaryTableannotation != null)\n        {\n            primaryTableName = ((Table) primaryTableannotation).name();\n        }\n\n        String tableNameOfColumn = getTableNameOfColumn();\n        if (tableNameOfColumn != null && !tables.contains(tableNameOfColumn) && !primaryTableName.isEmpty()\n                && !primaryTableName.equals(tableNameOfColumn))\n        {\n            throw new InvalidEntityDefinitionException(\"Inavalid table \" + tableNameOfColumn + \" for field \" + field);\n        }\n    }\n\n    private void processFieldAnnotations(Field field)\n    {\n        if (field != null)\n        {\n            Annotation[] annotations = field.getAnnotations();\n            for (Annotation annotation : annotations)\n            {\n                fieldAnnotations.put(annotation.annotationType().getName(), annotation);\n            }\n        }\n    }\n\n    public String getTableNameOfColumn()\n    {\n        Column column = (Column) getAnnotation(Column.class.getName());\n\n        String tableName = null;\n        if (column != null)\n        {\n            tableName = column.table();\n        }\n\n        if (tableName == null || tableName.isEmpty())\n        {\n            return null;\n        }\n        return tableName;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/annotation/EntityAnnotationProcessor.java",
    "content": "package com.impetus.kundera.metadata.model.annotation;\n\nimport java.lang.annotation.Annotation;\n\npublic interface EntityAnnotationProcessor extends JPAAnnotationProcessor\n{\n    void validateClassAnnotation(Annotation annotation, Class clazz);\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/annotation/FieldAnnotationProcessor.java",
    "content": "package com.impetus.kundera.metadata.model.annotation;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\n\nimport javax.persistence.metamodel.ManagedType;\n\npublic interface FieldAnnotationProcessor extends JPAAnnotationProcessor\n{\n    void validateFieldAnnotation(Annotation annotation, Field field, ManagedType managedType); \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/annotation/JPAAnnotationProcessor.java",
    "content": "package com.impetus.kundera.metadata.model.annotation;\n\nimport java.lang.annotation.Annotation;\nimport java.util.Map;\n\npublic interface JPAAnnotationProcessor\n{\n    public Map<String, Annotation> getAnnotations();\n\n    public Annotation getAnnotation(String annotationName);\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/attributes/AbstractAttribute.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.attributes;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Member;\nimport java.util.Date;\n\nimport javax.persistence.CollectionTable;\nimport javax.persistence.Column;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.Temporal;\nimport javax.persistence.metamodel.Attribute.PersistentAttributeType;\nimport javax.persistence.metamodel.ManagedType;\nimport javax.persistence.metamodel.Type;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.metadata.model.annotation.DefaultFieldAnnotationProcessor;\nimport com.impetus.kundera.metadata.model.annotation.FieldAnnotationProcessor;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\n\n/**\n * Abstract class for to provide generalisation, abstraction to\n * <code>Type</code> hierarchy.\n * \n * @param <X>\n *            the generic mananged entitytype\n * @param <T>\n *            the generic attribute type\n * @author vivek.mishra\n */\npublic abstract class AbstractAttribute<X, T>\n{\n\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(AbstractAttribute.class);\n\n    /** The attrib type. */\n    protected Type<T> attribType;\n\n    /** The attrib name. */\n    private String attribName;\n\n    /** The persistence attrib type. */\n    private PersistentAttributeType persistenceAttribType;\n\n    /** The managed type. */\n    private ManagedType<X> managedType;\n\n    /** The member. */\n    protected Field member;\n\n    /** Column name */\n    private String columnName;\n\n    /** Name of Table, to which this attribute belongs to */\n    private String tableName;\n\n    private FieldAnnotationProcessor fieldAnnotationProcessor;\n\n    /**\n     * Instantiates a new abstract attribute.\n     * \n     * @param attribType\n     *            the attrib type\n     * @param attribName\n     *            the attrib name\n     * @param persistenceAttribType\n     *            the persistence attrib type\n     * @param managedType\n     *            the managed type\n     * @param member\n     *            the member\n     */\n    AbstractAttribute(Type<T> attribType, String attribName,\n            javax.persistence.metamodel.Attribute.PersistentAttributeType persistenceAttribType,\n            ManagedType<X> managedType, Field member)\n    {\n\n        this.attribType = attribType;\n        this.attribName = attribName;\n        this.persistenceAttribType = persistenceAttribType;\n        this.managedType = managedType;\n        this.member = member;\n        this.columnName = getValidJPAColumnName();\n        this.fieldAnnotationProcessor = new DefaultFieldAnnotationProcessor(member);\n        this.fieldAnnotationProcessor.validateFieldAnnotation(\n                fieldAnnotationProcessor.getAnnotation(Column.class.getName()), (Field) member, this.managedType);\n        this.tableName = getTableName();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Bindable#getBindableType()\n     */\n    public abstract javax.persistence.metamodel.Bindable.BindableType getBindableType();\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Attribute#isCollection()\n     */\n    public abstract boolean isCollection();\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Bindable#getBindableJavaType()\n     */\n    public Class<T> getBindableJavaType()\n    {\n        return attribType.getJavaType();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Attribute#getName()\n     */\n    public String getName()\n    {\n        return attribName;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Attribute#getPersistentAttributeType()\n     */\n\n    public javax.persistence.metamodel.Attribute.PersistentAttributeType getPersistentAttributeType()\n    {\n        return persistenceAttribType;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Attribute#getDeclaringType()\n     */\n    public ManagedType<X> getDeclaringType()\n    {\n        return managedType;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Attribute#getJavaMember()\n     */\n    public Member getJavaMember()\n    {\n        return member;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Attribute#isAssociation()\n     */\n    public boolean isAssociation()\n    {\n        return persistenceAttribType.equals(PersistentAttributeType.MANY_TO_MANY)\n                || persistenceAttribType.equals(PersistentAttributeType.MANY_TO_ONE)\n                || persistenceAttribType.equals(PersistentAttributeType.ONE_TO_MANY)\n                || persistenceAttribType.equals(PersistentAttributeType.ONE_TO_ONE);\n    }\n\n    /**\n     * Returns assigned jpa column name.\n     * \n     * @return column name jpa column name.\n     */\n    public String getJPAColumnName()\n    {\n        // In case of Attribute override.\n        Column column = ((AbstractManagedType) this.managedType).getAttributeBinding(member);\n        if (column != null)\n        {\n            columnName = column.name();\n        }\n\n        return columnName;\n    }\n\n    /**\n     * Returns assigned table name.\n     * \n     * @return table name.\n     */\n    public String getTableName()\n    {\n        return ((DefaultFieldAnnotationProcessor) fieldAnnotationProcessor).getTableNameOfColumn();\n    }\n\n    /**\n     * Gets the valid jpa column name.\n     * \n     * @param entity\n     *            the entity\n     * @param f\n     *            the f\n     * @return the valid jpa column name\n     */\n    private final String getValidJPAColumnName()\n    {\n\n        String name = null;\n        if (member.isAnnotationPresent(Column.class))\n        {\n            Column c = member.getAnnotation(Column.class);\n            if (!c.name().isEmpty())\n            {\n                name = c.name();\n            }\n\n        }\n        if (member.isAnnotationPresent(Temporal.class))\n        {\n            if (!member.getType().equals(Date.class))\n            {\n                log.error(\"@Temporal must map to java.util.Date for @Entity(\" + managedType.getJavaType() + \".\"\n                        + member.getName() + \")\");\n                return name;\n            }\n        }\n        else if (member.isAnnotationPresent(JoinColumn.class))\n        {\n            JoinColumn c = member.getAnnotation(JoinColumn.class);\n            if (!c.name().isEmpty())\n            {\n                name = c.name();\n            }\n        }\n        else if (member.isAnnotationPresent(CollectionTable.class))\n        {\n            CollectionTable c = member.getAnnotation(CollectionTable.class);\n            if (!c.name().isEmpty())\n            {\n                name = c.name();\n            }\n        }\n\n        return name == null ? getName() : name;\n    }\n\n    public FieldAnnotationProcessor getFieldAnnotation()\n    {\n        return fieldAnnotationProcessor;\n    }\n    \n    public void setColumnName(final String columnName)\n    {\n        this.columnName = columnName;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/attributes/AbstractPluralAttribute.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.attributes;\n\nimport java.lang.reflect.Field;\n\nimport javax.persistence.metamodel.Bindable.BindableType;\nimport javax.persistence.metamodel.ManagedType;\nimport javax.persistence.metamodel.PluralAttribute;\nimport javax.persistence.metamodel.PluralAttribute.CollectionType;\nimport javax.persistence.metamodel.Type;\n\n/**\n * Abstract class to provide generalisation to\n * <code> {@link PluralAttribute} </code> interface.\n * \n * @author vivek.mishra\n * \n * @param <X>\n *            managed entity java type.\n * @param <E>\n *            attribute's java type.\n * @param <T>\n *            Collection type of plural attributes.\n */\npublic abstract class AbstractPluralAttribute<X, E, T> extends AbstractAttribute<X, E>\n{\n\n    private Class<T> collectionClazz;\n\n    /**\n     * Constructor with fields.\n     * \n     * @param attribType\n     *            attribute type\n     * @param attribName\n     *            attribute field's name\n     * @param persistenceAttribType\n     *            persistent attribute type\n     * @param managedType\n     *            type of managed entity.\n     * @param member\n     *            java member.\n     */\n    AbstractPluralAttribute(Type<E> attribType, String attribName,\n            javax.persistence.metamodel.Attribute.PersistentAttributeType persistenceAttribType,\n            ManagedType<X> managedType, Field member, Class<T> clazz)\n    {\n        super(attribType, attribName, persistenceAttribType, managedType, member);\n        this.collectionClazz = clazz;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.metadata.model.attributes.AbstractAttribute#\n     * getBindableType()\n     */\n    @Override\n    public javax.persistence.metamodel.Bindable.BindableType getBindableType()\n    {\n        return BindableType.PLURAL_ATTRIBUTE;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.metadata.model.attributes.AbstractAttribute#isCollection\n     * ()\n     */\n    @Override\n    public boolean isCollection()\n    {\n        return true;\n    }\n\n    /**\n     * Return the collection type.\n     * \n     * @return collection type\n     */\n    public abstract CollectionType getCollectionType();\n\n    /**\n     * Returns get java type.\n     * \n     * @return java type.\n     */\n    protected Class<T> getBoundJavaType()\n    {\n        return collectionClazz;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/attributes/AttributeType.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.attributes;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.impetus.kundera.gis.geometry.Point;\n\n/**\n * Attribute type.\n * \n * @author Kuldeep.Mishra\n *\n */\npublic enum AttributeType\n{\n    ENUM, LIST, SET, MAP, POINT, PRIMITIVE;\n\n    public static AttributeType getType(Class javaType)\n    {\n        AttributeType type = null;\n        if (javaType.isAssignableFrom(List.class))\n        {\n            type = LIST;\n        }\n        else if (javaType.isAssignableFrom(Map.class))\n        {\n            type = MAP;\n        }\n        else if (javaType.isAssignableFrom(Set.class))\n        {\n            type = SET;\n        }\n        else if (javaType.isEnum())\n        {\n            type = ENUM;\n        }\n        else if (javaType.isAssignableFrom(Point.class))\n        {\n            type = POINT;\n        }\n        else\n        {\n            type = PRIMITIVE;\n        }\n        return type;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/attributes/DefaultCollectionAttribute.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.metadata.model.attributes;\n\nimport java.lang.reflect.Field;\nimport java.util.Collection;\n\nimport javax.persistence.metamodel.CollectionAttribute;\nimport javax.persistence.metamodel.ManagedType;\nimport javax.persistence.metamodel.Type;\n\n/**\n * Implementation class for <code> {@link CollectionAttribute} </code>\n * interface. Offers metadata information implementation for collection\n * attribute as per jpa.\n * \n * @author vivek.mishra\n * \n * @param <X>\n *            Managed type\n * @param <E>\n *            collection's attribute type\n */\npublic class DefaultCollectionAttribute<X, E> extends AbstractPluralAttribute<X, E, Collection<E>> implements\n        CollectionAttribute<X, E>\n{\n\n    /**\n     * /** Constructor using fields.\n     * \n     * @param attribType\n     *            attribute type\n     * @param attribName\n     *            attribute name\n     * @param persistenceAttribType\n     *            persistent attribute type.\n     * @param managedType\n     *            managed type\n     * @param member\n     *            attribute's java member.\n     */\n    public DefaultCollectionAttribute(Type<E> attribType, String attribName,\n            javax.persistence.metamodel.Attribute.PersistentAttributeType persistenceAttribType,\n            ManagedType<X> managedType, Field member, Class<Collection<E>> clazz)\n    {\n        super(attribType, attribName, persistenceAttribType, managedType, member, clazz);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.metadata.model.attributes.AbstractPluralAttribute\n     * #getCollectionType()\n     */\n    @Override\n    public javax.persistence.metamodel.PluralAttribute.CollectionType getCollectionType()\n    {\n        return CollectionType.COLLECTION;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.metadata.model.attributes.AbstractPluralAttribute\n     * #getElementType()\n     */\n    @Override\n    public Type<E> getElementType()\n    {\n        return attribType;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Attribute#getJavaType()\n     */\n    @Override\n    public Class<Collection<E>> getJavaType()\n    {\n        return super.getBoundJavaType();\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/attributes/DefaultListAttribute.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.attributes;\n\nimport java.lang.reflect.Field;\nimport java.util.List;\n\nimport javax.persistence.metamodel.ListAttribute;\nimport javax.persistence.metamodel.ManagedType;\nimport javax.persistence.metamodel.Type;\n\n/**\n * Implementation class for <code> {@link ListAttribute} </code> interface.\n * Offers metadata information implementation for collection attribute as per\n * jpa.\n * \n * @author vivek.mishra\n * \n * @param <X>\n *            managed type\n * @param <E>\n *            attribute type of list attribute.\n */\npublic class DefaultListAttribute<X, E> extends AbstractPluralAttribute<X, E, List<E>> implements ListAttribute<X, E>\n{\n\n    /**\n     * Constructor using fields.\n     * \n     * @param attribType\n     *            attribute type\n     * @param attribName\n     *            attribute name\n     * @param persistenceAttribType\n     *            persistent attribute type.\n     * @param managedType\n     *            managed type\n     * @param member\n     *            attribute's java member.\n     */\n    public DefaultListAttribute(Type<E> attribType, String attribName,\n            javax.persistence.metamodel.Attribute.PersistentAttributeType persistenceAttribType,\n            ManagedType<X> managedType, Field member, Class<List<E>> clazz)\n    {\n        super(attribType, attribName, persistenceAttribType, managedType, member, clazz);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.metadata.model.attributes.AbstractPluralAttribute\n     * #getCollectionType()\n     */\n    @Override\n    public javax.persistence.metamodel.PluralAttribute.CollectionType getCollectionType()\n    {\n        return CollectionType.LIST;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.metadata.model.attributes.AbstractPluralAttribute\n     * #getElementType()\n     */\n    @Override\n    public Type<E> getElementType()\n    {\n        return attribType;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Attribute#getJavaType()\n     */\n    @Override\n    public Class<List<E>> getJavaType()\n    {\n        return super.getBoundJavaType();\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/attributes/DefaultMapAttribute.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.attributes;\n\nimport java.lang.reflect.Field;\nimport java.util.Map;\n\nimport javax.persistence.metamodel.ManagedType;\nimport javax.persistence.metamodel.MapAttribute;\nimport javax.persistence.metamodel.Type;\n\n/**\n * Implementation class for <code> {@link MapAttribute} </code> interface.\n * Offers metadata information implementation for collection attribute as per\n * jpa.\n * \n * @author vivek.mishra\n * \n * @param <X>\n *            managed type\n * @param <E>\n *            attribute type present in map.\n */\npublic class DefaultMapAttribute<X, K, V> extends AbstractPluralAttribute<X, V, Map<K, V>> implements\n        MapAttribute<X, K, V>\n{\n\n    private Type<K> keyType;\n\n    /**\n     * Constructor using fields.\n     * \n     * @param attribType\n     *            attribute type\n     * @param attribName\n     *            attribute name\n     * @param persistenceAttribType\n     *            persistent attribute type.\n     * @param managedType\n     *            managed type\n     * @param member\n     *            attribute's java member.\n     * @param key\n     *            type attribute of key type.\n     */\n    public DefaultMapAttribute(Type<V> attribType, String attribName,\n            javax.persistence.metamodel.Attribute.PersistentAttributeType persistenceAttribType,\n            ManagedType<X> managedType, Field member, Class<Map<K, V>> clazz, Type<K> keyType)\n    {\n        super(attribType, attribName, persistenceAttribType, managedType, member, clazz);\n        this.keyType = keyType;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.MapAttribute#getKeyJavaType()\n     */\n    @Override\n    public Class<K> getKeyJavaType()\n    {\n        return this.keyType.getJavaType();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.MapAttribute#getKeyType()\n     */\n    @Override\n    public Type<K> getKeyType()\n    {\n        return this.keyType;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.metadata.model.attributes.AbstractPluralAttribute\n     * #getCollectionType()\n     */\n    @Override\n    public javax.persistence.metamodel.PluralAttribute.CollectionType getCollectionType()\n    {\n        return CollectionType.MAP;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.metadata.model.attributes.AbstractPluralAttribute\n     * #getElementType()\n     */\n    @Override\n    public Type<V> getElementType()\n    {\n        return attribType;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.metadata.model.attributes.AbstractAttribute#isCollection\n     * ()\n     */\n    @Override\n    public boolean isCollection()\n    {\n        return true;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Attribute#getJavaType()\n     */\n    @Override\n    public Class<Map<K, V>> getJavaType()\n    {\n        return super.getBoundJavaType();\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/attributes/DefaultSetAttribute.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.attributes;\n\nimport java.lang.reflect.Field;\nimport java.util.Set;\n\nimport javax.persistence.metamodel.ManagedType;\nimport javax.persistence.metamodel.SetAttribute;\nimport javax.persistence.metamodel.Type;\n\n/**\n * Implementation class for <code> {@link SetAttribute} </code> interface.\n * Offers metadata information implementation for collection attribute as per\n * jpa.\n * \n * @author vivek.mishra\n * \n * @param <X>\n *            managed type\n * @param <E>\n *            attribute type in set\n */\npublic class DefaultSetAttribute<X, E> extends AbstractPluralAttribute<X, E, Set<E>> implements SetAttribute<X, E>\n{\n\n    /**\n     * Constructor using fields.\n     * \n     * @param attribType\n     *            attribute type\n     * @param attribName\n     *            attribute name\n     * @param persistenceAttribType\n     *            persistent attribute type.\n     * @param managedType\n     *            managed type\n     * @param member\n     *            attribute's java member.\n     */\n    public DefaultSetAttribute(Type<E> attribType, String attribName,\n            javax.persistence.metamodel.Attribute.PersistentAttributeType persistenceAttribType,\n            ManagedType<X> managedType, Field member, Class<Set<E>> clazz)\n    {\n        super(attribType, attribName, persistenceAttribType, managedType, member, clazz);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.metadata.model.attributes.AbstractPluralAttribute\n     * #getCollectionType()\n     */\n    @Override\n    public javax.persistence.metamodel.PluralAttribute.CollectionType getCollectionType()\n    {\n        return CollectionType.SET;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.PluralAttribute#getElementType()\n     */\n    @Override\n    public Type<E> getElementType()\n    {\n        return this.attribType;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Attribute#getJavaType()\n     */\n    @Override\n    public Class<Set<E>> getJavaType()\n    {\n        return super.getBoundJavaType();\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/attributes/DefaultSingularAttribute.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.attributes;\n\nimport java.lang.reflect.Field;\n\nimport javax.persistence.Column;\nimport javax.persistence.metamodel.ManagedType;\nimport javax.persistence.metamodel.SetAttribute;\nimport javax.persistence.metamodel.SingularAttribute;\nimport javax.persistence.metamodel.Type;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Implementation class for <code> {@link SetAttribute} </code> interface.\n * Offers metadata information implementation for collection attribute as per\n * jpa.\n * \n * @author vivek.mishra\n * \n * @param <X>\n *            managed type.\n * @param <T>\n *            attribute type.\n */\n\npublic class DefaultSingularAttribute<X, T> extends AbstractAttribute<X, T> implements SingularAttribute<X, T>\n{\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(DefaultSingularAttribute.class);\n\n    /** Attribute is an id? */\n    private boolean isId;\n\n    /**\n     * @param attribName\n     *            attribute name.\n     * @param persistenceAttribType\n     *            persistent attribute type.\n     * @param member\n     *            attribute's java member..\n     * @param attribType\n     *            attribute type.\n     * @param managedType\n     *            managed type.\n     */\n    public DefaultSingularAttribute(String attribName,\n            javax.persistence.metamodel.Attribute.PersistentAttributeType persistenceAttribType, Field member,\n            Type<T> attribType, ManagedType<X> managedType, boolean isId)\n    {\n        super(attribType, attribName, persistenceAttribType, managedType, member);\n        this.isId = isId;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Attribute#isCollection()\n     */\n    @Override\n    public boolean isCollection()\n    {\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Bindable#getBindableType()\n     */\n    @Override\n    public javax.persistence.metamodel.Bindable.BindableType getBindableType()\n    {\n        return BindableType.SINGULAR_ATTRIBUTE;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.SingularAttribute#isId()\n     */\n    @Override\n    public boolean isId()\n    {\n        return isId;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.SingularAttribute#isVersion()\n     */\n    @Override\n    public boolean isVersion()\n    {\n        log.info(\"Currently versioning is not supported in kundera, returning false as default\");\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.SingularAttribute#isOptional()\n     */\n    @Override\n    public boolean isOptional()\n    {\n        boolean isNullable = true;\n        if (!isId())\n        {\n            Column anno = member.getAnnotation(Column.class);\n            if (anno != null)\n            {\n                isNullable = anno.nullable();\n            }\n        }\n        else\n        {\n            isNullable = false;\n        }\n        return isNullable;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.SingularAttribute#getType()\n     */\n    @Override\n    public Type<T> getType()\n    {\n        return attribType;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.metadata.model.attributes.AbstractAttribute#getJavaType\n     * ()\n     */\n    @Override\n    public Class<T> getJavaType()\n    {\n        return attribType.getJavaType();\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/type/AbstractIdentifiableType.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.type;\n\nimport java.lang.reflect.Field;\nimport java.util.Set;\n\nimport javax.persistence.metamodel.IdentifiableType;\nimport javax.persistence.metamodel.SingularAttribute;\nimport javax.persistence.metamodel.Type;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.metadata.MetadataUtils;\n\n/**\n * Abstract implementation for <code>IdentifiableType</code>.\n * \n * @param <X>\n *            the generic type\n * @author vivek.mishra\n */\npublic abstract class AbstractIdentifiableType<X> extends AbstractManagedType<X> implements IdentifiableType<X>\n{\n\n    /** The id attribute. */\n    private SingularAttribute<? super X, ?> idAttribute;\n\n    /** The is id class. */\n    private boolean isIdClass;\n\n    /** The id class attributes. */\n    private Set<SingularAttribute<? super X, ?>> idClassAttributes;\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(AbstractIdentifiableType.class);\n\n    /**\n     * Instantiates a new abstract identifiable type.\n     * \n     * @param clazz\n     *            the clazz\n     * @param persistenceType\n     *            the persistence type\n     * @param superClazzType\n     *            the super clazz type\n     */\n    AbstractIdentifiableType(Class<X> clazz, javax.persistence.metamodel.Type.PersistenceType persistenceType,\n            AbstractIdentifiableType<? super X> superClazzType)\n    {\n        super(clazz, persistenceType, superClazzType);\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.IdentifiableType#getId(java.lang.Class)\n     */\n    @Override\n    public <Y> SingularAttribute<? super X, Y> getId(Class<Y> paramClass)\n    {\n        if (idAttribute != null)\n        {\n            if (idAttribute.getJavaType().equals(paramClass) && !isIdClass)\n            {\n                return (SingularAttribute<? super X, Y>) idAttribute;\n            }\n            else\n            {\n                onError();\n            }\n        }\n        else\n        {\n\n            AbstractIdentifiableType<? super X> superType = (AbstractIdentifiableType<? super X>) getSupertype();\n            if (superType != null)\n            {\n                return superType.getId(paramClass);\n            }\n        }\n\n        onError();\n\n        return null;\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.IdentifiableType#getDeclaredId(java.lang.\n     * Class)\n     */\n    @Override\n    public <Y> SingularAttribute<X, Y> getDeclaredId(Class<Y> paramClass)\n    {\n        if (idAttribute != null)\n        {\n            if (idAttribute.getJavaType().equals(paramClass) && !isIdClass)\n            {\n                return (SingularAttribute<X, Y>) idAttribute;\n            }\n        }\n\n        onError();\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.IdentifiableType#getVersion(java.lang.Class)\n     */\n    @Override\n    public <Y> SingularAttribute<? super X, Y> getVersion(Class<Y> paramClass)\n    {\n        // TODO: Versioning not yet supported.\n        throw new UnsupportedOperationException(\"Method not supported\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.IdentifiableType#getDeclaredVersion(java.\n     * lang.Class)\n     */\n    @Override\n    public <Y> SingularAttribute<X, Y> getDeclaredVersion(Class<Y> paramClass)\n    {\n        // TODO: Versioning not yet supported.\n        throw new UnsupportedOperationException(\"Method not supported\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.IdentifiableType#getSupertype()\n     */\n    @Override\n    public IdentifiableType<? super X> getSupertype()\n    {\n        return (AbstractIdentifiableType<? super X>) super.getSuperClazzType();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.IdentifiableType#hasSingleIdAttribute()\n     */\n    @Override\n    public boolean hasSingleIdAttribute()\n    {\n        return !isIdClass && getIdAttribute() != null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.IdentifiableType#hasVersionAttribute()\n     */\n    @Override\n    public boolean hasVersionAttribute()\n    {\n        log.warn(\"Versioning not yet supported. returning false, By default\");\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.IdentifiableType#getIdClassAttributes()\n     */\n    @Override\n    public Set<SingularAttribute<? super X, ?>> getIdClassAttributes()\n    {\n        if (isIdClass)\n        {\n            return idClassAttributes;\n        }\n        else if (getSuperClazzType() != null\n        /*\n         * && getSuperClazzType().getJavaType().isAssignableFrom(\n         * AbstractIdentifiableType.class)\n         */)\n        {\n            idClassAttributes = ((AbstractIdentifiableType) getSuperClazzType()).getIdClassAttributes();\n        }\n\n        throw new IllegalArgumentException(\"The identifiable type does not have an id class\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.IdentifiableType#getIdType()\n     */\n    @Override\n    public Type<?> getIdType()\n    {\n        if (idAttribute != null && !isIdClass)\n        {\n            return idAttribute.getType();\n        }\n\n        return getSupertype().getIdType();\n    }\n\n    /**\n     * Adds the id attribute.\n     * \n     * @param idAttribute\n     *            the id attribute\n     * @param isIdClass\n     *            the is id class\n     * @param idClassAttributes\n     *            the id class attributes\n     */\n    public void addIdAttribute(SingularAttribute<? super X, ?> idAttribute, boolean isIdClass,\n            Set<SingularAttribute<? super X, ?>> idClassAttributes)\n    {\n\n        this.idAttribute = idAttribute;\n        this.isIdClass = isIdClass;\n        this.idClassAttributes = idClassAttributes;\n        if (MetadataUtils.onCheckValidationConstraints((Field) idAttribute.getJavaMember()))\n        {\n            this.hasValidationConstraints = true;\n        }\n    }\n\n    public SingularAttribute<? super X, ?> getIdAttribute()\n    {\n        idAttribute = idAttribute == null ? getSuperClazzType() != null\n        /*\n         * && getSuperClazzType().getJavaType().isAssignableFrom(\n         * AbstractIdentifiableType.class)\n         */? ((AbstractIdentifiableType) getSuperClazzType()).getIdAttribute() : null : idAttribute;\n        return idAttribute;\n    }\n\n    /**\n     * On error.\n     */\n    private void onError()\n    {\n        throw new IllegalArgumentException(\n                \"id attribute of the given type is not declared in the identifiable type or if the identifiable type has an id class(e.g. @IdClass is in use)\");\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/type/AbstractManagedType.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.type;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorColumn;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.Table;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.Bindable;\nimport javax.persistence.metamodel.CollectionAttribute;\nimport javax.persistence.metamodel.ListAttribute;\nimport javax.persistence.metamodel.ManagedType;\nimport javax.persistence.metamodel.MapAttribute;\nimport javax.persistence.metamodel.PluralAttribute;\nimport javax.persistence.metamodel.PluralAttribute.CollectionType;\nimport javax.persistence.metamodel.SetAttribute;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.annotation.DefaultEntityAnnotationProcessor;\nimport com.impetus.kundera.metadata.model.annotation.EntityAnnotationProcessor;\n\n/**\n * Implementation for <code>ManagedType</code> interface.\n * \n * @author vivek.mishra\n * @param <X>\n *            the generic entity type.\n */\npublic abstract class AbstractManagedType<X> extends AbstractType<X> implements ManagedType<X>\n{\n\n    /** The super clazz type. */\n    private ManagedType<? super X> superClazzType;\n\n    /** The declared singluar attribs. */\n    private Map<String, SingularAttribute<X, ?>> declaredSingluarAttribs;\n\n    /** The declared plural attributes. */\n    private Map<String, PluralAttribute<X, ?, ?>> declaredPluralAttributes;\n\n    /** The Constant validJPAAnnotations. */\n    private static final List<Class<? extends Annotation>> validJPAAnnotations = Arrays.asList(\n            AttributeOverrides.class, AttributeOverride.class);\n\n    /** The column bindings. */\n    private Map<String, Column> columnBindings = new ConcurrentHashMap<String, Column>();\n\n    /** The model. */\n    private InheritanceModel model;\n\n    /** The entity annotation processor. */\n    private EntityAnnotationProcessor entityAnnotationProcessor;\n\n    /** The sub managed types. */\n    private List<ManagedType<X>> subManagedTypes = new ArrayList<ManagedType<X>>();\n\n    /** The has lob attribute. */\n    private boolean hasLobAttribute;\n\n    /**\n     * Checks for lob attribute.\n     * \n     * @return true, if successful\n     */\n    public boolean hasLobAttribute()\n    {\n        return hasLobAttribute;\n    }\n\n    /**\n     * Sets the checks for lob attribute.\n     * \n     * @param hasLobAttribute\n     *            the new checks for lob attribute\n     */\n    public void setHasLobAttribute(boolean hasLobAttribute)\n    {\n        this.hasLobAttribute = hasLobAttribute;\n    }\n\n    /** Whether a managed type has validation constraints. */\n    protected boolean hasValidationConstraints = false;\n\n    /** Whether a managed type has embeddable attribute. */\n    private boolean hasEmbeddableAttribute;\n\n    /**\n     * Super constructor with arguments.\n     * \n     * @param clazz\n     *            parameterised class.\n     * @param persistenceType\n     *            persistenceType.\n     * @param superClazzType\n     *            the super clazz type\n     */\n    AbstractManagedType(Class<X> clazz, javax.persistence.metamodel.Type.PersistenceType persistenceType,\n            ManagedType<? super X> superClazzType)\n    {\n        super(clazz, persistenceType);\n        this.superClazzType = superClazzType;\n        bindTypeAnnotations();\n        if (this.superClazzType != null)\n        {\n            ((AbstractManagedType<? super X>) this.superClazzType).addSubManagedType(this);\n        }\n        this.model = buildInheritenceModel();\n        entityAnnotationProcessor = new DefaultEntityAnnotationProcessor(clazz);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.ManagedType#getAttributes()\n     */\n    @Override\n    public Set<Attribute<? super X, ?>> getAttributes()\n    {\n        Set<Attribute<? super X, ?>> attributes = new HashSet<Attribute<? super X, ?>>();\n\n        Set<Attribute<X, ?>> declaredAttribs = getDeclaredAttributes();\n        if (declaredAttribs != null)\n        {\n            attributes.addAll(declaredAttribs);\n        }\n        if (superClazzType != null)\n        {\n            attributes.addAll(superClazzType.getAttributes());\n        }\n\n        return attributes;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.ManagedType#getDeclaredAttributes()\n     */\n    @Override\n    public Set<Attribute<X, ?>> getDeclaredAttributes()\n    {\n        Set<Attribute<X, ?>> attributes = new HashSet<Attribute<X, ?>>();\n\n        if (declaredSingluarAttribs != null)\n        {\n            attributes.addAll(declaredSingluarAttribs.values());\n        }\n        if (declaredPluralAttributes != null)\n        {\n            attributes.addAll(declaredPluralAttributes.values());\n        }\n\n        return attributes;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getSingularAttribute(java.lang\n     * .String, java.lang.Class)\n     */\n    @Override\n    public <Y> SingularAttribute<? super X, Y> getSingularAttribute(String paramString, Class<Y> paramClass)\n    {\n        SingularAttribute<? super X, Y> attribute = getDeclaredSingularAttribute(paramString, paramClass, false);\n        if (superClazzType != null && attribute == null)\n        {\n            return superClazzType.getSingularAttribute(paramString, paramClass);\n        }\n        checkForValid(paramString, attribute);\n        return attribute;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getDeclaredSingularAttribute(\n     * java.lang.String, java.lang.Class)\n     */\n    @Override\n    public <Y> SingularAttribute<X, Y> getDeclaredSingularAttribute(String paramString, Class<Y> paramClass)\n    {\n        return getDeclaredSingularAttribute(paramString, paramClass, true);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.ManagedType#getSingularAttributes()\n     */\n    @SuppressWarnings(\"unchecked\")\n    @Override\n    public Set<SingularAttribute<? super X, ?>> getSingularAttributes()\n    {\n        Set<SingularAttribute<? super X, ?>> singularAttrib = new HashSet<SingularAttribute<? super X, ?>>();\n\n        if (superClazzType != null)\n        {\n            Set parentAttrib = superClazzType.getSingularAttributes();\n\n            if (parentAttrib != null)\n            {\n                singularAttrib.addAll(parentAttrib);\n            }\n        }\n\n        Set<SingularAttribute<X, ?>> declaredAttribSet = getDeclaredSingularAttributes();\n\n        if (declaredAttribSet != null)\n        {\n            singularAttrib.addAll(declaredAttribSet);\n        }\n\n        return singularAttrib;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getDeclaredSingularAttributes()\n     */\n    @Override\n    public Set<SingularAttribute<X, ?>> getDeclaredSingularAttributes()\n    {\n        Set<SingularAttribute<X, ?>> declaredAttribSet = null;\n        if (declaredSingluarAttribs != null)\n        {\n            declaredAttribSet = new HashSet<SingularAttribute<X, ?>>();\n            declaredAttribSet.addAll(declaredSingluarAttribs.values());\n        }\n        return declaredAttribSet;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getCollection(java.lang.String,\n     * java.lang.Class)\n     */\n    @SuppressWarnings(\"unchecked\")\n    @Override\n    public <E> CollectionAttribute<? super X, E> getCollection(String paramName, Class<E> paramClass)\n    {\n        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (onCheckCollectionAttribute(declaredAttrib, paramClass))\n        {\n            return (CollectionAttribute<X, E>) declaredAttrib;\n        }\n\n        PluralAttribute<? super X, ?, ?> superAttrib = getPluralAttriute(paramName);\n\n        if (onCheckCollectionAttribute(superAttrib, paramClass))\n        {\n            return (CollectionAttribute<? super X, E>) superAttrib;\n\n        }\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramName\n                        + \" , type:\" + paramClass);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getDeclaredCollection(java.lang\n     * .String, java.lang.Class)\n     */\n    @Override\n    public <E> CollectionAttribute<X, E> getDeclaredCollection(String paramString, Class<E> paramClass)\n    {\n        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramString);\n\n        if (onCheckCollectionAttribute(declaredAttrib, paramClass))\n        {\n            return (CollectionAttribute<X, E>) declaredAttrib;\n        }\n\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramString\n                        + \" , type:\" + paramClass);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.ManagedType#getSet(java.lang.String,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> SetAttribute<? super X, E> getSet(String paramName, Class<E> paramClass)\n    {\n        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (onCheckSetAttribute(declaredAttrib, paramClass))\n        {\n            return (SetAttribute<X, E>) declaredAttrib;\n        }\n\n        PluralAttribute<? super X, ?, ?> superAttrib = getPluralAttriute(paramName);\n\n        if (onCheckSetAttribute(superAttrib, paramClass))\n        {\n            return (SetAttribute<? super X, E>) superAttrib;\n\n        }\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramName\n                        + \" , type:\" + paramClass);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getDeclaredSet(java.lang.String,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> SetAttribute<X, E> getDeclaredSet(String paramName, Class<E> paramClass)\n    {\n        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (onCheckSetAttribute(declaredAttrib, paramClass))\n        {\n            return (SetAttribute<X, E>) declaredAttrib;\n        }\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramName\n                        + \" , type:\" + paramClass);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.ManagedType#getList(java.lang.String,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> ListAttribute<? super X, E> getList(String paramName, Class<E> paramClass)\n    {\n        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (onCheckListAttribute(declaredAttrib, paramClass))\n        {\n            return (ListAttribute<X, E>) declaredAttrib;\n        }\n\n        PluralAttribute<? super X, ?, ?> superAttrib = getPluralAttriute(paramName);\n\n        if (onCheckListAttribute(superAttrib, paramClass))\n        {\n            return (ListAttribute<? super X, E>) superAttrib;\n\n        }\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramName\n                        + \" , type:\" + paramClass);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getDeclaredList(java.lang.String,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> ListAttribute<X, E> getDeclaredList(String paramName, Class<E> paramClass)\n    {\n        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (onCheckListAttribute(declaredAttrib, paramClass))\n        {\n            return (ListAttribute<X, E>) declaredAttrib;\n        }\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramName\n                        + \" , type:\" + paramClass);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.ManagedType#getMap(java.lang.String,\n     * java.lang.Class, java.lang.Class)\n     */\n    @Override\n    public <K, V> MapAttribute<? super X, K, V> getMap(String paramName, Class<K> keyClazz, Class<V> valueClazz)\n    {\n        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (onCheckMapAttribute(declaredAttrib, valueClazz))\n        {\n            if (valueClazz != null && valueClazz.equals(((MapAttribute<X, K, V>) declaredAttrib).getKeyJavaType()))\n            {\n                return (MapAttribute<X, K, V>) declaredAttrib;\n\n            }\n        }\n\n        PluralAttribute<? super X, ?, ?> superAttrib = getPluralAttriute(paramName);\n\n        if (onCheckMapAttribute(superAttrib, valueClazz))\n        {\n            if (valueClazz != null && valueClazz.equals(((MapAttribute<? super X, K, V>) superAttrib).getKeyJavaType()))\n            {\n                return (MapAttribute<? super X, K, V>) superAttrib;\n\n            }\n        }\n\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed MapAttribute type, for name:\"\n                        + paramName + \" , value type:\" + valueClazz + \"key tpye:\" + keyClazz);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getDeclaredMap(java.lang.String,\n     * java.lang.Class, java.lang.Class)\n     */\n    @Override\n    public <K, V> MapAttribute<X, K, V> getDeclaredMap(String paramName, Class<K> keyClazz, Class<V> valueClazz)\n    {\n        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (onCheckMapAttribute(declaredAttrib, valueClazz))\n        {\n            if (valueClazz != null && valueClazz.equals(((MapAttribute<X, K, V>) declaredAttrib).getKeyJavaType()))\n            {\n                return (MapAttribute<X, K, V>) declaredAttrib;\n\n            }\n        }\n\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed MapAttribute type, for name:\"\n                        + paramName + \" , value type:\" + valueClazz + \"key tpye:\" + keyClazz);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.ManagedType#getPluralAttributes()\n     */\n    @Override\n    public Set<PluralAttribute<? super X, ?, ?>> getPluralAttributes()\n    {\n        Set<PluralAttribute<? super X, ?, ?>> pluralAttributes = new HashSet<PluralAttribute<? super X, ?, ?>>();\n        Set<PluralAttribute<X, ?, ?>> declaredAttribSet = getDeclaredPluralAttributes();\n        if (declaredAttribSet != null)\n        {\n            pluralAttributes.addAll(declaredAttribSet);\n        }\n\n        if (superClazzType != null)\n        {\n            pluralAttributes.addAll(superClazzType.getPluralAttributes());\n        }\n\n        return pluralAttributes;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getDeclaredPluralAttributes()\n     */\n    @Override\n    public Set<PluralAttribute<X, ?, ?>> getDeclaredPluralAttributes()\n    {\n        Set<PluralAttribute<X, ?, ?>> declaredAttribSet = null;\n\n        if (declaredPluralAttributes != null)\n        {\n            declaredAttribSet = new HashSet<PluralAttribute<X, ?, ?>>();\n            declaredAttribSet.addAll(declaredPluralAttributes.values());\n        }\n        return declaredAttribSet;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getAttribute(java.lang.String)\n     */\n    @Override\n    public Attribute<? super X, ?> getAttribute(String paramName)\n    {\n        Attribute<? super X, ?> attribute = getDeclaredAttribute(paramName, false);\n        if (attribute == null && superClazzType != null)\n        {\n            attribute = superClazzType.getAttribute(paramName);\n        }\n\n        checkForValid(paramName, attribute);\n        return attribute;\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getDeclaredAttribute(java.lang\n     * .String)\n     */\n    @Override\n    public Attribute<X, ?> getDeclaredAttribute(String paramName)\n    {\n        Attribute<X, ?> attribute = getDeclaredAttribute(paramName, true);\n        return attribute;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getSingularAttribute(java.lang\n     * .String)\n     */\n    @Override\n    public SingularAttribute<? super X, ?> getSingularAttribute(String paramString)\n    {\n        SingularAttribute<? super X, ?> attribute = getSingularAttribute(paramString, true);\n        return attribute;\n    }\n\n    /**\n     * Gets the singular attribute.\n     * \n     * @param paramString\n     *            the param string\n     * @param checkValidity\n     *            the check validity\n     * @return the singular attribute\n     */\n    private SingularAttribute<? super X, ?> getSingularAttribute(String paramString, boolean checkValidity)\n    {\n        SingularAttribute<? super X, ?> attribute = getDeclaredSingularAttribute(paramString, false);\n\n        try\n        {\n            if (attribute == null && superClazzType != null)\n            {\n                attribute = superClazzType.getSingularAttribute(paramString);\n            }\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            attribute = null;\n            onValidity(paramString, checkValidity, attribute);\n        }\n        onValidity(paramString, checkValidity, attribute);\n        return attribute;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getDeclaredSingularAttribute(\n     * java.lang.String)\n     */\n    @Override\n    public SingularAttribute<X, ?> getDeclaredSingularAttribute(String paramString)\n    {\n        SingularAttribute<X, ?> attribute = getDeclaredSingularAttribute(paramString, true);\n\n        return attribute;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getCollection(java.lang.String)\n     */\n    @Override\n    public CollectionAttribute<? super X, ?> getCollection(String paramName)\n    {\n        PluralAttribute<? super X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (isCollectionAttribute(declaredAttrib))\n        {\n            return (CollectionAttribute<X, ?>) declaredAttrib;\n        }\n\n        declaredAttrib = getPluralAttriute(paramName);\n\n        if (isCollectionAttribute(declaredAttrib))\n        {\n            return (CollectionAttribute<? super X, ?>) declaredAttrib;\n\n        }\n\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramName);\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getDeclaredCollection(java.lang\n     * .String)\n     */\n    @Override\n    public CollectionAttribute<X, ?> getDeclaredCollection(String paramName)\n    {\n        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (isCollectionAttribute(declaredAttrib))\n        {\n            return (CollectionAttribute<X, ?>) declaredAttrib;\n        }\n\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.ManagedType#getSet(java.lang.String)\n     */\n    @Override\n    public SetAttribute<? super X, ?> getSet(String paramName)\n    {\n        PluralAttribute<? super X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (isSetAttribute(declaredAttrib))\n        {\n            return (SetAttribute<X, ?>) declaredAttrib;\n        }\n\n        declaredAttrib = getPluralAttriute(paramName);\n\n        if (isSetAttribute(declaredAttrib))\n        {\n            return (SetAttribute<X, ?>) declaredAttrib;\n        }\n\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getDeclaredSet(java.lang.String)\n     */\n    @Override\n    public SetAttribute<X, ?> getDeclaredSet(String paramName)\n    {\n        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (isSetAttribute(declaredAttrib))\n        {\n            return (SetAttribute<X, ?>) declaredAttrib;\n        }\n\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.ManagedType#getList(java.lang.String)\n     */\n    @Override\n    public ListAttribute<? super X, ?> getList(String paramName)\n    {\n        PluralAttribute<? super X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (isListAttribute(declaredAttrib))\n        {\n            return (ListAttribute<X, ?>) declaredAttrib;\n        }\n\n        declaredAttrib = getPluralAttriute(paramName);\n\n        if (isListAttribute(declaredAttrib))\n        {\n            return (ListAttribute<X, ?>) declaredAttrib;\n        }\n\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getDeclaredList(java.lang.String)\n     */\n    @Override\n    public ListAttribute<X, ?> getDeclaredList(String paramName)\n    {\n        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (isListAttribute(declaredAttrib))\n        {\n            return (ListAttribute<X, ?>) declaredAttrib;\n        }\n\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.ManagedType#getMap(java.lang.String)\n     */\n    @Override\n    public MapAttribute<? super X, ?, ?> getMap(String paramName)\n    {\n        PluralAttribute<? super X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (isMapAttribute(declaredAttrib))\n        {\n            return (MapAttribute<X, ?, ?>) declaredAttrib;\n        }\n\n        declaredAttrib = getPluralAttriute(paramName);\n\n        if (isMapAttribute(declaredAttrib))\n        {\n            return (MapAttribute<X, ?, ?>) declaredAttrib;\n        }\n\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.metamodel.ManagedType#getDeclaredMap(java.lang.String)\n     */\n    @Override\n    public MapAttribute<X, ?, ?> getDeclaredMap(String paramName)\n    {\n        PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName);\n\n        if (isMapAttribute(declaredAttrib))\n        {\n            return (MapAttribute<X, ?, ?>) declaredAttrib;\n        }\n\n        throw new IllegalArgumentException(\n                \"attribute of the given name and type is not present in the managed type, for name:\" + paramName);\n    }\n\n    /**\n     * Gets the super clazz type.\n     * \n     * @return the super clazz type\n     */\n    ManagedType<? super X> getSuperClazzType()\n    {\n        return superClazzType;\n    }\n\n    /**\n     * Adds the singular attribute.\n     * \n     * @param attributeName\n     *            the attribute name\n     * @param attribute\n     *            the attribute\n     */\n    public void addSingularAttribute(String attributeName, SingularAttribute<X, ?> attribute)\n    {\n        if (declaredSingluarAttribs == null)\n        {\n            declaredSingluarAttribs = new HashMap<String, SingularAttribute<X, ?>>();\n        }\n\n        declaredSingluarAttribs.put(attributeName, attribute);\n\n        onValidateAttributeConstraints((Field) attribute.getJavaMember());\n        onEmbeddableAttribute((Field) attribute.getJavaMember());\n    }\n\n    /**\n     * Adds the plural attribute.\n     * \n     * @param attributeName\n     *            the attribute name\n     * @param attribute\n     *            the attribute\n     */\n    public void addPluralAttribute(String attributeName, PluralAttribute<X, ?, ?> attribute)\n    {\n        if (declaredPluralAttributes == null)\n        {\n            declaredPluralAttributes = new HashMap<String, PluralAttribute<X, ?, ?>>();\n        }\n\n        declaredPluralAttributes.put(attributeName, attribute);\n\n        onValidateAttributeConstraints((Field) attribute.getJavaMember());\n        onEmbeddableAttribute((Field) attribute.getJavaMember());\n\n    }\n\n    /**\n     * Gets the attribute binding.\n     * \n     * @param attribute\n     *            the attribute\n     * @return the attribute binding\n     */\n    public Column getAttributeBinding(Field attribute)\n    {\n        return columnBindings.get(attribute.getName());\n    }\n\n    /**\n     * Adds the sub managed type.\n     * \n     * @param inheritedType\n     *            the inherited type\n     */\n    private void addSubManagedType(ManagedType inheritedType)\n    {\n\n        if (Modifier.isAbstract(this.getJavaType().getModifiers()))\n        {\n            subManagedTypes.add(inheritedType);\n        }\n    }\n\n    /**\n     * Gets the sub managed type.\n     * \n     * @return the sub managed type\n     */\n    public List<ManagedType<X>> getSubManagedType()\n    {\n        return subManagedTypes;\n    }\n\n    /**\n     * Gets the declared plural attribute.\n     * \n     * @param paramName\n     *            the param name\n     * @return the declared plural attribute\n     */\n    private PluralAttribute<X, ?, ?> getDeclaredPluralAttribute(String paramName)\n    {\n        return declaredPluralAttributes != null ? declaredPluralAttributes.get(paramName) : null;\n    }\n\n    /**\n     * Gets the plural attriute.\n     * \n     * @param paramName\n     *            the param name\n     * @return the plural attriute\n     */\n    private PluralAttribute<? super X, ?, ?> getPluralAttriute(String paramName)\n    {\n        if (superClazzType != null)\n        {\n            return ((AbstractManagedType<? super X>) superClazzType).getDeclaredPluralAttribute(paramName);\n        }\n        return null;\n    }\n\n    /**\n     * On check collection attribute.\n     * \n     * @param <E>\n     *            the element type\n     * @param pluralAttribute\n     *            the plural attribute\n     * @param paramClass\n     *            the param class\n     * @return true, if successful\n     */\n    private <E> boolean onCheckCollectionAttribute(PluralAttribute<? super X, ?, ?> pluralAttribute, Class<E> paramClass)\n    {\n        if (pluralAttribute != null)\n        {\n            if (isCollectionAttribute(pluralAttribute) && isBindable(pluralAttribute, paramClass))\n            {\n                return true;\n            }\n\n        }\n\n        return false;\n    }\n\n    /**\n     * On check set attribute.\n     * \n     * @param <E>\n     *            the element type\n     * @param pluralAttribute\n     *            the plural attribute\n     * @param paramClass\n     *            the param class\n     * @return true, if successful\n     */\n    private <E> boolean onCheckSetAttribute(PluralAttribute<? super X, ?, ?> pluralAttribute, Class<E> paramClass)\n    {\n        if (pluralAttribute != null)\n        {\n            if (isSetAttribute(pluralAttribute) && isBindable(pluralAttribute, paramClass))\n            {\n                return true;\n            }\n\n        }\n\n        return false;\n    }\n\n    /**\n     * On check list attribute.\n     * \n     * @param <E>\n     *            the element type\n     * @param pluralAttribute\n     *            the plural attribute\n     * @param paramClass\n     *            the param class\n     * @return true, if successful\n     */\n    private <E> boolean onCheckListAttribute(PluralAttribute<? super X, ?, ?> pluralAttribute, Class<E> paramClass)\n    {\n        if (pluralAttribute != null)\n        {\n            if (isListAttribute(pluralAttribute) && isBindable(pluralAttribute, paramClass))\n            {\n                return true;\n            }\n\n        }\n\n        return false;\n    }\n\n    /**\n     * On check map attribute.\n     * \n     * @param <V>\n     *            the value type\n     * @param pluralAttribute\n     *            the plural attribute\n     * @param valueClazz\n     *            the value clazz\n     * @return true, if successful\n     */\n    private <V> boolean onCheckMapAttribute(PluralAttribute<? super X, ?, ?> pluralAttribute, Class<V> valueClazz)\n    {\n        if (pluralAttribute != null)\n        {\n            if (isMapAttribute(pluralAttribute) && isBindable(pluralAttribute, valueClazz))\n            {\n                return true;\n            }\n\n        }\n\n        return false;\n    }\n\n    /**\n     * Checks if is collection attribute.\n     * \n     * @param attribute\n     *            the attribute\n     * @return true, if is collection attribute\n     */\n    private boolean isCollectionAttribute(PluralAttribute<? super X, ?, ?> attribute)\n    {\n        return attribute != null && attribute.getCollectionType().equals(CollectionType.COLLECTION);\n    }\n\n    /**\n     * Checks if is list attribute.\n     * \n     * @param attribute\n     *            the attribute\n     * @return true, if is list attribute\n     */\n    private boolean isListAttribute(PluralAttribute<? super X, ?, ?> attribute)\n    {\n        return attribute != null && attribute.getCollectionType().equals(CollectionType.LIST);\n    }\n\n    /**\n     * Checks if is sets the attribute.\n     * \n     * @param attribute\n     *            the attribute\n     * @return true, if is sets the attribute\n     */\n    private boolean isSetAttribute(PluralAttribute<? super X, ?, ?> attribute)\n    {\n        return attribute != null && attribute.getCollectionType().equals(CollectionType.SET);\n    }\n\n    /**\n     * Checks if is map attribute.\n     * \n     * @param attribute\n     *            the attribute\n     * @return true, if is map attribute\n     */\n    private boolean isMapAttribute(PluralAttribute<? super X, ?, ?> attribute)\n    {\n        return attribute != null && attribute.getCollectionType().equals(CollectionType.MAP);\n    }\n\n    /**\n     * Checks if is bindable.\n     * \n     * @param <E>\n     *            the element type\n     * @param attribute\n     *            the attribute\n     * @param elementType\n     *            the element type\n     * @return true, if is bindable\n     */\n    private <E> boolean isBindable(Bindable<?> attribute, Class<E> elementType)\n    {\n        return attribute != null && attribute.getBindableJavaType().equals(elementType);\n    }\n\n    /**\n     * Check for valid.\n     * \n     * @param paramName\n     *            the param name\n     * @param attribute\n     *            the attribute\n     */\n    private void checkForValid(String paramName, Attribute<? super X, ?> attribute)\n    {\n        if (attribute == null)\n        {\n            throw new IllegalArgumentException(\n                    \"attribute of the given name and type is not present in the managed type, for name:\" + paramName);\n\n        }\n    }\n\n    /**\n     * Gets the declared attribute.\n     * \n     * @param paramName\n     *            the param name\n     * @param checkValidity\n     *            the check validity\n     * @return the declared attribute\n     */\n    private Attribute<X, ?> getDeclaredAttribute(String paramName, boolean checkValidity)\n    {\n        Attribute<X, ?> attribute = (Attribute<X, ?>) getSingularAttribute(paramName, false);\n\n        if (attribute == null)\n        {\n            attribute = (Attribute<X, ?>) getDeclaredPluralAttribute(paramName);\n        }\n\n        if (checkValidity)\n        {\n            checkForValid(paramName, attribute);\n        }\n        return attribute;\n    }\n\n    /**\n     * Returns declared singular attribute.\n     * \n     * @param <Y>\n     *            the generic type\n     * @param paramString\n     *            the param string\n     * @param paramClass\n     *            the param class\n     * @param checkValidity\n     *            the check validity\n     * @return the declared singular attribute\n     */\n    private <Y> SingularAttribute<X, Y> getDeclaredSingularAttribute(String paramString, Class<Y> paramClass,\n            boolean checkValidity)\n    {\n        SingularAttribute<X, ?> declaredAttrib = declaredSingluarAttribs.get(paramString);\n\n        if (declaredAttrib != null && declaredAttrib.getBindableJavaType().equals(paramClass))\n        {\n            return (SingularAttribute<X, Y>) declaredAttrib;\n        }\n\n        if (checkValidity)\n        {\n            throw new IllegalArgumentException(\n                    \"attribute of the given name and type is not present in the managed type, for name:\" + paramString\n                            + \" , type:\" + paramClass);\n        }\n        return null;\n    }\n\n    /**\n     * Returns declared singular attribute.\n     * \n     * @param paramString\n     *            the param string\n     * @param checkValidity\n     *            the check validity\n     * @return the declared singular attribute\n     */\n    private SingularAttribute<X, ?> getDeclaredSingularAttribute(String paramString, boolean checkValidity)\n    {\n        SingularAttribute<X, ?> attribute = null;\n        if (declaredSingluarAttribs != null)\n        {\n            attribute = declaredSingluarAttribs.get(paramString);\n        }\n\n        if (checkValidity)\n        {\n            checkForValid(paramString, attribute);\n        }\n        return attribute;\n    }\n\n    /**\n     * On validity check.\n     * \n     * @param paramString\n     *            the param string\n     * @param checkValidity\n     *            the check validity\n     * @param attribute\n     *            the attribute\n     */\n    private void onValidity(String paramString, boolean checkValidity, SingularAttribute<? super X, ?> attribute)\n    {\n        if (checkValidity)\n        {\n            checkForValid(paramString, attribute);\n\n        }\n    }\n\n    /**\n     * Bind type annotations.\n     */\n    private void bindTypeAnnotations()\n    {\n        // TODO:: need to check @Embeddable attributes as well!\n\n        // TODO:: need to Handle association override in\n        // RelationMetadataProcessor.\n\n        for (Class<? extends Annotation> ann : validJPAAnnotations)\n        {\n            if (getJavaType().isAnnotationPresent(ann))\n            {\n                checkForValid();\n\n                Annotation annotation = getJavaType().getAnnotation(ann);\n\n                if (ann.isAssignableFrom(AttributeOverride.class))\n                {\n                    bindAttribute(annotation);\n                }\n                else if (ann.isAssignableFrom(AttributeOverrides.class))\n                {\n\n                    AttributeOverride[] attribAnns = ((AttributeOverrides) annotation).value();\n\n                    for (AttributeOverride attribOverann : attribAnns)\n                    {\n                        bindAttribute(attribOverann);\n                    }\n\n                }\n\n            }\n        }\n    }\n\n    /**\n     * Bind attribute.\n     * \n     * @param annotation\n     *            the annotation\n     */\n    private void bindAttribute(Annotation annotation)\n    {\n        String fieldname = ((AttributeOverride) annotation).name();\n        Column column = ((AttributeOverride) annotation).column();\n        ((AbstractManagedType) this.superClazzType).columnBindings.put(fieldname, column);\n    }\n\n    /**\n     * Check for valid.\n     */\n    private void checkForValid()\n    {\n        if (this.superClazzType == null)\n        {\n            throw new IllegalArgumentException(\n                    \"@AttributeOverride and @AttributeOverrides are only applicable if super class is @MappedSuperClass\");\n        }\n    }\n\n    /**\n     * Build inheritance model.\n     * \n     * @return inheritance model instance.\n     */\n    private InheritanceModel buildInheritenceModel()\n    {\n        InheritanceModel model = null;\n\n        if (superClazzType != null)\n        {\n            // means there is a super class\n            // scan for inheritence model.\n\n            if (superClazzType.getPersistenceType().equals(PersistenceType.ENTITY)\n                    && superClazzType.getJavaType().isAnnotationPresent(Inheritance.class))\n            {\n                Inheritance inheritenceAnn = superClazzType.getJavaType().getAnnotation(Inheritance.class);\n\n                InheritanceType strategyType = inheritenceAnn.strategy();\n\n                String descriminator = null;\n                String descriminatorValue = null;\n                String tableName = null;\n                String schemaName = null;\n                tableName = superClazzType.getJavaType().getSimpleName();\n\n                if (superClazzType.getJavaType().isAnnotationPresent(Table.class))\n                {\n                    tableName = superClazzType.getJavaType().getAnnotation(Table.class).name();\n                    schemaName = superClazzType.getJavaType().getAnnotation(Table.class).schema();\n                }\n\n                model = onStrategyType(model, strategyType, descriminator, descriminatorValue, tableName, schemaName);\n\n            }\n\n        }\n\n        return model;\n    }\n\n    /**\n     * On strategy type.\n     * \n     * @param model\n     *            the model\n     * @param strategyType\n     *            the strategy type\n     * @param descriminator\n     *            the descriminator\n     * @param descriminatorValue\n     *            the descriminator value\n     * @param tableName\n     *            the table name\n     * @param schemaName\n     *            the schema name\n     * @return the inheritance model\n     */\n    private InheritanceModel onStrategyType(InheritanceModel model, InheritanceType strategyType, String descriminator,\n            String descriminatorValue, String tableName, String schemaName)\n    {\n        switch (strategyType)\n        {\n        case SINGLE_TABLE:\n\n            // if single table\n\n            if (superClazzType.getJavaType().isAnnotationPresent(DiscriminatorColumn.class))\n            {\n                descriminator = superClazzType.getJavaType().getAnnotation(DiscriminatorColumn.class).name();\n                descriminatorValue = getJavaType().getAnnotation(DiscriminatorValue.class).value();\n            }\n\n            model = new InheritanceModel(InheritanceType.SINGLE_TABLE, descriminator, descriminatorValue, tableName,\n                    schemaName);\n\n            break;\n\n        case JOINED:\n\n            // if join table\n            // TODOO: PRIMARY KEY JOIN COLUMN\n            model = new InheritanceModel(InheritanceType.JOINED, tableName, schemaName);\n\n            break;\n\n        case TABLE_PER_CLASS:\n\n            // don't override, use original ones.\n            model = new InheritanceModel(InheritanceType.TABLE_PER_CLASS, null, null);\n\n            break;\n\n        default:\n            // do nothing.\n            break;\n        }\n        return model;\n    }\n\n    /**\n     * Checks if is inherited.\n     * \n     * @return true, if is inherited\n     */\n    public boolean isInherited()\n    {\n        return this.model != null;\n    }\n\n    /**\n     * Gets the inheritence type.\n     * \n     * @return the inheritence type\n     */\n    public InheritanceType getInheritenceType()\n    {\n\n        return isInherited() ? this.model.inheritenceType : null;\n    }\n\n    /**\n     * Gets the discriminator column.\n     * \n     * @return the discriminator column\n     */\n    public String getDiscriminatorColumn()\n    {\n        return isInherited() ? this.model.discriminatorColumn : null;\n    }\n\n    /**\n     * Gets the discriminator value.\n     * \n     * @return the discriminator value\n     */\n    public String getDiscriminatorValue()\n    {\n        return isInherited() ? this.model.discriminatorValue : null;\n    }\n\n    /**\n     * Gets the table name.\n     * \n     * @return the table name\n     */\n    public String getTableName()\n    {\n        return isInherited() ? this.model.tableName : null;\n    }\n\n    /**\n     * Gets the schema name.\n     * \n     * @return the schema name\n     */\n    public String getSchemaName()\n    {\n        return isInherited() ? this.model.schemaName : null;\n    }\n\n    /**\n     * The Class InheritanceModel.\n     */\n    private static class InheritanceModel\n    {\n\n        /** The inheritence type. */\n        private InheritanceType inheritenceType;\n\n        /** The discriminator column. */\n        private String discriminatorColumn;\n\n        /** The discriminator value. */\n        private String discriminatorValue;\n\n        /** The table name. */\n        private String tableName;\n\n        /** The schema name. */\n        private String schemaName;\n\n        /**\n         * Instantiates a new inheritance model.\n         * \n         * @param type\n         *            the type\n         * @param discriminatorCol\n         *            the discriminator col\n         * @param discriminatorValue\n         *            the discriminator value\n         * @param tableName\n         *            the table name\n         * @param schemaName\n         *            the schema name\n         */\n        InheritanceModel(final InheritanceType type, final String discriminatorCol, final String discriminatorValue,\n                final String tableName, final String schemaName)\n        {\n            this.inheritenceType = type;\n            this.discriminatorColumn = discriminatorCol;\n            this.discriminatorValue = discriminatorValue;\n            this.tableName = tableName;\n            this.schemaName = schemaName;\n        }\n\n        /**\n         * Instantiates a new inheritance model.\n         * \n         * @param type\n         *            the type\n         * @param tableName\n         *            the table name\n         * @param schemaName\n         *            the schema name\n         */\n        InheritanceModel(final InheritanceType type, final String tableName, final String schemaName)\n        {\n            this.inheritenceType = type;\n            this.tableName = tableName;\n            this.schemaName = schemaName;\n        }\n    }\n\n    /**\n     * Gets the entity annotation.\n     * \n     * @return the entity annotation\n     */\n    public EntityAnnotationProcessor getEntityAnnotation()\n    {\n        return entityAnnotationProcessor;\n    }\n\n    /**\n     * Checks for validation constraints.\n     * \n     * @return the hasValidationConstraints\n     */\n    public boolean hasValidationConstraints()\n    {\n        if (this.hasValidationConstraints)\n        {\n            return this.hasValidationConstraints;\n        }\n        if (this.superClazzType != null)\n        {\n            return ((AbstractManagedType) superClazzType).hasValidationConstraints();\n        }\n        return false;\n    }\n\n    /**\n     * Sets the validation constraint present field if an attribute has a\n     * constraint present.\n     * \n     * @param field\n     *            the field\n     */\n    private void onValidateAttributeConstraints(Field field)\n    {\n\n        if (!this.hasValidationConstraints && MetadataUtils.onCheckValidationConstraints(field))\n        {\n\n            this.hasValidationConstraints = true;\n\n        }\n\n    }\n\n    /**\n     * Sets if a managed type consists of an embeddable attribute.\n     * \n     * @param field\n     *            the field\n     */\n    private void onEmbeddableAttribute(Field field)\n    {\n\n        if (!this.hasEmbeddableAttribute && MetadataUtils.onCheckEmbeddableAttribute(field))\n        {\n\n            this.hasEmbeddableAttribute = true;\n\n        }\n\n    }\n\n    /**\n     * Checks for embeddable attribute.\n     * \n     * @return the hasEmbeddableAttribute\n     */\n    public boolean hasEmbeddableAttribute()\n    {\n        if (this.hasEmbeddableAttribute)\n        {\n            return this.hasEmbeddableAttribute;\n        }\n        if (this.superClazzType != null)\n        {\n            return ((AbstractManagedType) superClazzType).hasEmbeddableAttribute();\n        }\n        return false;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/type/AbstractType.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.type;\n\nimport javax.persistence.metamodel.Type;\n\n/**\n * Implements <code> Type</code> interface of MetaModel API.\n * \n * @param <X>\n *            the generic type\n * \n * @author vivek.mishra\n */\npublic abstract class AbstractType<X> implements Type<X>\n{\n\n    /** The clazz type. */\n    private Class<X> clazzType;\n\n    /** The persistence type. */\n    private PersistenceType persistenceType;\n\n    /**\n     * Instantiates a new default type.\n     * \n     * @param clazz\n     *            the clazz\n     * @param persistenceType\n     *            the persistence type\n     */\n    AbstractType(Class<X> clazz, PersistenceType persistenceType)\n    {\n        this.clazzType = clazz;\n        this.persistenceType = persistenceType;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Type#getPersistenceType()\n     */\n    @Override\n    public javax.persistence.metamodel.Type.PersistenceType getPersistenceType()\n    {\n        return this.persistenceType;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Type#getJavaType()\n     */\n    @Override\n    public Class<X> getJavaType()\n    {\n        return this.clazzType;\n    }\n\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/type/DefaultBasicType.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.type;\n\nimport javax.persistence.metamodel.BasicType;\nimport javax.persistence.metamodel.Type;\n\n/**\n * Default implementation of {@link BasicType}\n * \n * <code> DefaultBasicType</code> implements <code>BasicType</code> interface,\n * invokes constructor with PersistenceType.BASIC. Default implementation of\n * {@link Type} interface is provided by {@link AbstractType}\n * \n * @author vivek.mishra\n * \n */\npublic class DefaultBasicType<X> extends AbstractType<X> implements BasicType<X>\n{\n\n    /**\n     * Constructor with arguments.\n     * \n     * @param clazz\n     *            typed class.\n     */\n    public DefaultBasicType(Class<X> clazz)\n    {\n        super(clazz, PersistenceType.BASIC);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/type/DefaultEmbeddableType.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.type;\n\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.ManagedType;\nimport javax.persistence.metamodel.Type;\n\n/**\n * Default implementation of {@link EmbeddableType}\n * \n * <code> DefaultEmbeddableType</code> implements <code>EmbeddableType</code>\n * interface, invokes constructor with PersistenceType.EMBEDDABLE. Default\n * implementation of {@link Type} interface is provided by {@link AbstractType}\n * \n * @author vivek.mishra\n * @param <X>\n *            Embeddable generic java type.\n */\npublic class DefaultEmbeddableType<X> extends AbstractManagedType<X> implements EmbeddableType<X>\n{\n\n    /**\n     * Default constructor using fields.\n     */\n    public DefaultEmbeddableType(Class<X> clazz, javax.persistence.metamodel.Type.PersistenceType persistenceType,\n            ManagedType<? super X> superClazzType)\n    {\n        super(clazz, persistenceType, superClazzType);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/type/DefaultEntityType.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.type;\n\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.Type;\n\n/**\n * Default implementation of {@link EntityType}\n * \n * <code> DefaultEmbeddableType</code> implements <code>EntityType</code>\n * interface, invokes constructor with PersistenceType.ENTITY. Default\n * implementation of {@link Type} interface is provided by {@link AbstractType}\n * \n * @author vivek.mishra\n * @param <X>\n *            Entity generic java type.\n */\n\npublic class DefaultEntityType<X> extends AbstractIdentifiableType<X> implements EntityType<X>\n{\n\n    /**\n     * Default constructor using fields.\n     */\n    public DefaultEntityType(Class<X> clazz, javax.persistence.metamodel.Type.PersistenceType persistenceType,\n            AbstractIdentifiableType<? super X> superClazzType)\n    {\n        super(clazz, persistenceType, superClazzType);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Bindable#getBindableType()\n     */\n    @Override\n    public javax.persistence.metamodel.Bindable.BindableType getBindableType()\n    {\n        return BindableType.ENTITY_TYPE;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.Bindable#getBindableJavaType()\n     */\n    @Override\n    public Class<X> getBindableJavaType()\n    {\n        return super.getJavaType();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.metamodel.EntityType#getName()\n     */\n    @Override\n    public String getName()\n    {\n        return getBindableJavaType().getSimpleName();\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/model/type/DefaultMappedSuperClass.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model.type;\n\nimport javax.persistence.metamodel.MappedSuperclassType;\nimport javax.persistence.metamodel.Type;\n\n/**\n * Default implementation of {@link MappedSuperclassType}\n * \n * <code> DefaultMappedSuperClass</code> implements\n * <code>MappedSuperclassType</code> interface, invokes constructor with\n * PersistenceType.MAPPED_SUPERCLASS. Default implementation of {@link Type}\n * interface is provided by {@link AbstractType}\n * \n * @author vivek.mishra\n * @param <X>\n *            Embeddable generic java type.\n */\npublic class DefaultMappedSuperClass<X> extends AbstractIdentifiableType<X> implements MappedSuperclassType<X>\n{\n\n    /**\n     * Default constructor using fields.\n     */\n    public DefaultMappedSuperClass(Class<X> clazz, javax.persistence.metamodel.Type.PersistenceType persistenceType,\n            AbstractIdentifiableType<? super X> superClazzType)\n    {\n        super(clazz, persistenceType, superClazzType);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/AbstractEntityFieldProcessor.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.processor;\r\n\r\nimport java.beans.BeanInfo;\r\nimport java.beans.IntrospectionException;\r\nimport java.beans.Introspector;\r\nimport java.beans.PropertyDescriptor;\r\nimport java.lang.reflect.Field;\r\nimport java.util.Date;\r\n\r\nimport javax.persistence.Basic;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.PersistenceException;\r\nimport javax.persistence.Temporal;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.metadata.MetadataProcessor;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.metadata.validator.EntityValidator;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\n\r\n/**\r\n * The Class AbstractEntityFieldProcessor.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic abstract class AbstractEntityFieldProcessor implements MetadataProcessor\r\n{\r\n\r\n    /** The Constant log. */\r\n    private static final Logger log = LoggerFactory.getLogger(AbstractEntityFieldProcessor.class);\r\n\r\n    /** The Validator. */\r\n    protected EntityValidator validator;\r\n\r\n    protected KunderaMetadata kunderaMetadata;\r\n\r\n    public AbstractEntityFieldProcessor(KunderaMetadata kunderaMetadata)\r\n    {\r\n        this.kunderaMetadata = kunderaMetadata;\r\n    }\r\n\r\n    /**\r\n     * Gets the valid jpa column.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     * @return the valid jpa column\r\n     * @throws PersistenceException\r\n     *             the persistence exception\r\n     */\r\n\r\n    /**\r\n     * Validate.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     * \r\n     * @throws PersistenceException\r\n     *             the persistence exception\r\n     */\r\n    public final void validate(Class<?> clazz) throws PersistenceException\r\n    {\r\n        validator.validate(clazz);\r\n    }\r\n\r\n    /**\r\n     * Gets the valid jpa column name.\r\n     * \r\n     * @param entity\r\n     *            the entity\r\n     * @param f\r\n     *            the f\r\n     * @return the valid jpa column name\r\n     */\r\n    protected final String getValidJPAColumnName(Class<?> entity, Field f)\r\n    {\r\n\r\n        String name = null;\r\n\r\n        if (f.isAnnotationPresent(Column.class))\r\n        {\r\n            Column c = f.getAnnotation(Column.class);\r\n            if (!c.name().isEmpty())\r\n            {\r\n                name = c.name();\r\n            }\r\n            else\r\n            {\r\n                name = f.getName();\r\n            }\r\n        }\r\n        else if (f.isAnnotationPresent(Basic.class))\r\n        {\r\n            name = f.getName();\r\n        }\r\n\r\n        if (f.isAnnotationPresent(Temporal.class))\r\n        {\r\n            if (!f.getType().equals(Date.class))\r\n            {\r\n                log.error(\"@Temporal must map to java.util.Date for @Entity(\" + entity.getName() + \".\" + f.getName()\r\n                        + \")\");\r\n                return name;\r\n            }\r\n            if (null == name)\r\n            {\r\n                name = f.getName();\r\n            }\r\n        }\r\n        return name;\r\n    }\r\n\r\n    /**\r\n     * Populates @Id accesser methods like, getId and setId of clazz to\r\n     * metadata.\r\n     * \r\n     * @param metadata\r\n     *            the metadata\r\n     * @param clazz\r\n     *            the clazz\r\n     * @param f\r\n     *            the f\r\n     */\r\n    protected final void populateIdAccessorMethods(EntityMetadata metadata, Class<?> clazz, Field f)\r\n    {\r\n        try\r\n        {\r\n            BeanInfo info = Introspector.getBeanInfo(clazz);\r\n\r\n            for (PropertyDescriptor descriptor : info.getPropertyDescriptors())\r\n            {\r\n                if (descriptor.getName().equals(f.getName()))\r\n                {\r\n                    metadata.setReadIdentifierMethod(descriptor.getReadMethod());\r\n                    metadata.setWriteIdentifierMethod(descriptor.getWriteMethod());\r\n                    return;\r\n                }\r\n            }\r\n        }\r\n        catch (IntrospectionException e)\r\n        {\r\n            throw new RuntimeException(e);\r\n        }\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/CacheableAnnotationProcessor.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.processor;\r\n\r\nimport javax.persistence.Cacheable;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.metadata.MetadataProcessor;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\n\r\n/**\r\n * The MetadataProcessor implementation to scan for EntityListener class/method\r\n * JPA Specifications: 1. EntityListeners classes must have a no-argument\r\n * constructor. 2. Callback methods can have any visibility. 3. Callback methods\r\n * must return void. 4. Callback methods must NOT throw any checked exception.\r\n * 5. ExternalCallback methods must accept only entity object. 6.\r\n * InternalCallback methods must NOT accept any parameter. 7. EntityListeners\r\n * are state-less. 8. EnternalCallbackMethods must be fired before\r\n * InternalCallbackMethods.\r\n * \r\n * @author animesh.kumar\r\n */\r\n\r\npublic class CacheableAnnotationProcessor implements MetadataProcessor\r\n{\r\n\r\n    /** the log used by this class. */\r\n    private static Logger log = LoggerFactory.getLogger(CacheableAnnotationProcessor.class);\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.metadata.MetadataProcessor#process(java.lang.Class,\r\n     * com.impetus.kundera.metadata.model.EntityMetadata)\r\n     */\r\n    @Override\r\n    public final void process(final Class<?> entityClass, EntityMetadata metadata)\r\n    {\r\n\r\n        Cacheable cacheable = (Cacheable) entityClass.getAnnotation(Cacheable.class);\r\n\r\n        if (null != cacheable)\r\n        {\r\n            metadata.setCacheable(cacheable.value());\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/EntityListenersProcessor.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.processor;\r\n\r\nimport java.lang.annotation.Annotation;\r\nimport java.lang.reflect.Method;\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.EntityListeners;\r\nimport javax.persistence.PostLoad;\r\nimport javax.persistence.PostPersist;\r\nimport javax.persistence.PostRemove;\r\nimport javax.persistence.PostUpdate;\r\nimport javax.persistence.PrePersist;\r\nimport javax.persistence.PreRemove;\r\nimport javax.persistence.PreUpdate;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.loader.MetamodelLoaderException;\r\nimport com.impetus.kundera.metadata.MetadataProcessor;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.persistence.event.CallbackMethod;\r\nimport com.impetus.kundera.persistence.event.ExternalCallbackMethod;\r\nimport com.impetus.kundera.persistence.event.InternalCallbackMethod;\r\nimport com.impetus.kundera.utils.ReflectUtils;\r\n\r\n/**\r\n * The MetadataProcessor implementation to scan for EntityListener class/method\r\n * JPA Specifications: 1. EntityListeners classes must have a no-argument\r\n * constructor. 2. Callback methods can have any visibility. 3. Callback methods\r\n * must return void. 4. Callback methods must NOT throw any checked exception.\r\n * 5. ExternalCallback methods must accept only entity object. 6.\r\n * InternalCallback methods must NOT accept any parameter. 7. EntityListeners\r\n * are state-less. 8. EnternalCallbackMethods must be fired before\r\n * InternalCallbackMethods.\r\n * \r\n * @author animesh.kumar\r\n */\r\n\r\npublic class EntityListenersProcessor implements MetadataProcessor\r\n{\r\n\r\n    /** the log used by this class. */\r\n    private static Logger log = LoggerFactory.getLogger(EntityListenersProcessor.class);\r\n\r\n    // list of all valid JPA Entity Listeners\r\n    /** The Constant JPAListenersAnnotations. */\r\n    @SuppressWarnings(\"unchecked\")\r\n    private static final List<Class<? extends Annotation>> JPAListenersAnnotations = Arrays.asList(PrePersist.class,\r\n            PostPersist.class, PreUpdate.class, PostUpdate.class, PreRemove.class, PostRemove.class, PostLoad.class);\r\n\r\n    @Override\r\n    public final void process(final Class<?> entityClass, EntityMetadata metadata)\r\n    {\r\n\r\n        // list all external listeners first.\r\n        EntityListeners entityListeners = (EntityListeners) entityClass.getAnnotation(EntityListeners.class);\r\n\r\n        if (entityListeners == null && entityClass.getSuperclass() != null)\r\n        {\r\n            entityListeners = entityClass.getSuperclass().getAnnotation(EntityListeners.class);\r\n        }\r\n        \r\n        if (entityListeners != null)\r\n        {\r\n            Class<?>[] entityListenerClasses = entityListeners.value();\r\n            if (entityListenerClasses != null)\r\n            {\r\n                // iterate through all EntityListeners\r\n                for (Class<?> entityListener : entityListenerClasses)\r\n                {\r\n\r\n                    // entityListener class must have a no-argument constructor\r\n                    try\r\n                    {\r\n                        entityListener.getConstructor();\r\n                    }\r\n                    catch (NoSuchMethodException nsme)\r\n                    {\r\n                        throw new MetamodelLoaderException(\"Skipped method(\" + entityListener.getName()\r\n                                + \") must have a default no-argument constructor.\");\r\n                    }\r\n\r\n                    // iterate through all public methods\r\n                    for (Method method : entityListener.getDeclaredMethods())\r\n                    {\r\n\r\n                        // find valid jpa annotations for this method\r\n                        List<Class<?>> jpaAnnotations = getValidJPAAnnotationsFromMethod(entityListener, method, 1,\r\n                                entityClass);\r\n\r\n                        // add them all to metadata\r\n                        for (Class<?> jpaAnnotation : jpaAnnotations)\r\n                        {\r\n                            CallbackMethod callBackMethod = new ExternalCallbackMethod(entityListener, method);\r\n                            addCallBackMethod(metadata, jpaAnnotation, callBackMethod);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n\r\n        // list all internal listeners now.\r\n        // iterate through all public methods of entityClass\r\n        // since this is already an @Entity class, it will sure have a default\r\n        // no-arg constructor\r\n        for (Method method : entityClass.getMethods())\r\n        {\r\n            // find valid jpa annotations for this method\r\n            List<Class<?>> jpaAnnotations = getValidJPAAnnotationsFromMethod(entityClass, method, 0, entityClass);\r\n            // add them all to metadata\r\n            for (Class<?> jpaAnnotation : jpaAnnotations)\r\n            {\r\n                CallbackMethod callbackMethod = new InternalCallbackMethod(metadata, method);\r\n                addCallBackMethod(metadata, jpaAnnotation, callbackMethod);\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Adds the call back method.\r\n     * \r\n     * @param metadata\r\n     *            the metadata\r\n     * @param jpaAnnotation\r\n     *            the jpa annotation\r\n     * @param callbackMethod\r\n     *            the callback method\r\n     */\r\n    @SuppressWarnings(\"unchecked\")\r\n    private void addCallBackMethod(EntityMetadata metadata, Class<?> jpaAnnotation, CallbackMethod callbackMethod)\r\n    {\r\n        Map<Class<?>, List<? extends CallbackMethod>> callBackMethodsMap = metadata.getCallbackMethodsMap();\r\n        List<CallbackMethod> list = (List<CallbackMethod>) callBackMethodsMap.get(jpaAnnotation);\r\n        if (null == list)\r\n        {\r\n            list = new ArrayList<CallbackMethod>();\r\n            callBackMethodsMap.put(jpaAnnotation, list);\r\n        }\r\n        list.add(callbackMethod);\r\n    }\r\n\r\n    /**\r\n     * Gets the valid jpa annotations from method.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     * @param method\r\n     *            the method\r\n     * @param numberOfParams\r\n     *            the number of params\r\n     * \r\n     * @return the valid jpa annotations from method\r\n     */\r\n    private List<Class<?>> getValidJPAAnnotationsFromMethod(Class<?> clazz, Method method, int numberOfParams,\r\n            Class<?> entityClazz)\r\n    {\r\n        List<Class<?>> annotations = new ArrayList<Class<?>>();\r\n\r\n        for (Annotation methodAnnotation : method.getAnnotations())\r\n        {\r\n            Class<?> methodAnnotationType = methodAnnotation.annotationType();\r\n\r\n            if (isValidJPAEntityListenerAnnotation(methodAnnotationType))\r\n            {\r\n\r\n                // verify method signature\r\n\r\n                // verify exceptions\r\n                boolean hasUncheckedExceptions = false;\r\n                for (Class<?> exception : method.getExceptionTypes())\r\n                {\r\n                    if (!ReflectUtils.hasSuperClass(RuntimeException.class, exception))\r\n                    {\r\n                        hasUncheckedExceptions = true;\r\n                        break;\r\n                    }\r\n                }\r\n\r\n                if (hasUncheckedExceptions)\r\n                {\r\n                    log.info(\"Skipped method(\" + clazz.getName() + \".\" + method.getName()\r\n                            + \") Must not throw unchecked exceptions.\");\r\n                    continue;\r\n                }\r\n\r\n                // return type must be \"void\"\r\n                if (!method.getReturnType().getSimpleName().equals(\"void\"))\r\n                {\r\n                    log.info(\"Skipped method(\" + clazz.getName() + \".\" + method.getName()\r\n                            + \") Must have \\\"void\\\" return type.\");\r\n                    continue;\r\n                }\r\n                // argument must be an Entity or Object\r\n                Class<?>[] paramTypes = method.getParameterTypes();\r\n                if (paramTypes.length != numberOfParams)\r\n                {\r\n                    log.info(\"Skipped method(\" + clazz.getName() + \".\" + method.getName() + \") Must have \"\r\n                            + numberOfParams + \" parameter.\");\r\n                    continue;\r\n                }\r\n\r\n                if (numberOfParams == 1)\r\n                {\r\n                    Class<?> parameter = paramTypes[0];\r\n                    if (!(parameter != null && parameter.isAssignableFrom(entityClazz)))\r\n                    {\r\n                        log.info(\"Skipped method(\" + clazz.getName() + \".\" + method.getName()\r\n                                + \") Must have only 1 \\\"Object\\\" type parameter.\");\r\n                        continue;\r\n                    }\r\n                }\r\n\r\n                annotations.add(methodAnnotationType);\r\n            }\r\n        }\r\n        return annotations;\r\n    }\r\n\r\n    /**\r\n     * Checks if is valid jpa entity listener annotation.\r\n     * \r\n     * @param annotation\r\n     *            the annotation\r\n     * \r\n     * @return true, if is valid jpa entity listener annotation\r\n     */\r\n    private boolean isValidJPAEntityListenerAnnotation(Class<?> annotation)\r\n    {\r\n        return JPAListenersAnnotations.contains(annotation);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/GeneratedValueProcessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor;\n\nimport java.lang.reflect.Field;\nimport java.util.Map;\n\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.TableGenerator;\n\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.IdDiscriptor;\nimport com.impetus.kundera.metadata.model.SequenceGeneratorDiscriptor;\nimport com.impetus.kundera.metadata.model.TableGeneratorDiscriptor;\n\npublic class GeneratedValueProcessor\n{\n    public void process(Class<?> clazz, Field idField, EntityMetadata m,\n            Map<String, IdDiscriptor> entityNameToKeyDiscriptorMap)\n    {\n        IdDiscriptor keyValue = new IdDiscriptor();\n\n        GeneratedValue value = idField.getAnnotation(GeneratedValue.class);\n        String generatorName = value.generator();\n        GenerationType generationType = value.strategy();\n\n        switch (generationType)\n        {\n        case TABLE:\n            TableGeneratorDiscriptor tgd = processTableGenerator(clazz, idField, m, generatorName);\n            keyValue.setTableDiscriptor(tgd);\n            keyValue.setStrategy(GenerationType.TABLE);\n            break;\n        case SEQUENCE:\n            SequenceGeneratorDiscriptor sgd = processSequenceGenerator(clazz, idField, m, generatorName);\n            keyValue.setSequenceDiscriptor(sgd);\n            keyValue.setStrategy(GenerationType.SEQUENCE);\n            break;\n        case IDENTITY:\n            keyValue.setStrategy(GenerationType.IDENTITY);\n            break;\n        case AUTO:\n            // No need of Any Generator\n            keyValue.setStrategy(GenerationType.AUTO);\n            break;\n        }\n        entityNameToKeyDiscriptorMap.put(clazz.getName(), keyValue);\n    }\n\n    private SequenceGeneratorDiscriptor processSequenceGenerator(Class<?> clazz, Field idField, EntityMetadata m,\n            String generatorName)\n    {\n        SequenceGeneratorDiscriptor sgd = null;\n        if (!generatorName.isEmpty())\n        {\n            SequenceGenerator sequenceGenerator = idField.getAnnotation(SequenceGenerator.class);\n            if (sequenceGenerator == null || !sequenceGenerator.name().equals(generatorName))\n            {\n                sequenceGenerator = clazz.getAnnotation(SequenceGenerator.class);\n            }\n            sgd = new SequenceGeneratorDiscriptor(sequenceGenerator, m.getSchema());\n        }\n        else\n        {\n            sgd = new SequenceGeneratorDiscriptor(m.getSchema());\n        }\n        return sgd;\n    }\n\n    private TableGeneratorDiscriptor processTableGenerator(Class<?> clazz, Field idField, EntityMetadata m,\n            String generatorName)\n    {\n        TableGeneratorDiscriptor tgd = null;\n        if (!generatorName.isEmpty())\n        {\n            TableGenerator tableGenerator = idField.getAnnotation(TableGenerator.class);\n            if (tableGenerator == null || !tableGenerator.name().equals(generatorName))\n            {\n                tableGenerator = clazz.getAnnotation(TableGenerator.class);\n            }\n            tgd = new TableGeneratorDiscriptor(tableGenerator, m.getSchema(), m.getTableName());\n        }\n        else\n        {\n            tgd = new TableGeneratorDiscriptor(m.getSchema(), m.getTableName());\n        }\n        return tgd;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/IndexProcessor.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.processor;\r\n\r\nimport java.lang.reflect.Field;\r\nimport java.util.ArrayList;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\nimport java.util.StringTokenizer;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.metamodel.Attribute;\r\nimport javax.persistence.metamodel.EmbeddableType;\r\nimport javax.persistence.metamodel.EntityType;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.index.IndexCollection;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.metadata.model.PropertyIndex;\r\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\n\r\n/**\r\n * The Class BaseMetadataProcessor.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class IndexProcessor extends AbstractEntityFieldProcessor\r\n{\r\n\r\n    /** the log used by this class. */\r\n    private static Logger log = LoggerFactory.getLogger(IndexProcessor.class);\r\n\r\n    public IndexProcessor(KunderaMetadata kunderaMetadata)\r\n    {\r\n        super(kunderaMetadata);\r\n    }\r\n\r\n    public final void process(final Class<?> clazz, EntityMetadata metadata)\r\n    {\r\n        if (clazz != null)\r\n        {\r\n            metadata.setIndexName(clazz.getSimpleName());\r\n        }\r\n        \r\n\r\n        IndexCollection indexes = clazz.getAnnotation(IndexCollection.class);\r\n\r\n        EntityType entityType = (EntityType) kunderaMetadata.getApplicationMetadata()\r\n                .getMetaModelBuilder(metadata.getPersistenceUnit()).getManagedTypes().get(clazz);\r\n\r\n        List<String> columnsNameToBeIndexed = new ArrayList<String>();\r\n\r\n        Map<String, com.impetus.kundera.index.Index> indexedColumnsMap = new HashMap<String, com.impetus.kundera.index.Index>();\r\n\r\n        if (null != indexes)\r\n        {\r\n            if (indexes.columns() != null && indexes.columns().length != 0)\r\n            {\r\n                metadata.setIndexable(true);\r\n                for (com.impetus.kundera.index.Index indexedColumn : indexes.columns())\r\n                {\r\n                    if (indexedColumn.type().equals(\"composite\"))\r\n                    {\r\n                        // means comma seperated list of columns\r\n                        metadata.addIndexProperty(\r\n                                prepareCompositeIndexName(indexedColumn.name(), entityType, metadata),\r\n                                populatePropertyIndex(indexedColumn.indexName(), indexedColumn.type(), null, null, null));\r\n\r\n                    }\r\n                    else\r\n                    {\r\n                        indexedColumnsMap.put(indexedColumn.name(), indexedColumn);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        else\r\n        {\r\n            log.debug(\"@Entity \" + clazz.getName() + \" will not be indexed for \"\r\n                    + (indexedColumnsMap.isEmpty() ? \"all columns\" : indexedColumnsMap));\r\n            return;\r\n        }\r\n\r\n        log.debug(\"Processing @Entity \" + clazz.getName() + \" for Indexes.\");\r\n\r\n        // scan for fields\r\n        Set<Attribute> attributes = entityType.getAttributes();\r\n        for (Attribute attrib : attributes)\r\n        {\r\n            if (!attrib.isAssociation())\r\n            {\r\n                String colName = attrib.getName();\r\n                String columnName = ((AbstractAttribute) attrib).getJPAColumnName();\r\n                if (indexedColumnsMap != null && !indexedColumnsMap.isEmpty() && indexedColumnsMap.containsKey(colName))\r\n                {\r\n                    com.impetus.kundera.index.Index indexedColumn = indexedColumnsMap.get(colName);\r\n                    String indexName = StringUtils.isBlank(indexedColumn.indexName()) ? columnName : indexedColumn\r\n                            .indexName();\r\n                    metadata.addIndexProperty(\r\n                            columnName,\r\n                            populatePropertyIndex(indexName, indexedColumn.type(), indexedColumn.max(),\r\n                                    indexedColumn.min(), (Field) attrib.getJavaMember()));\r\n\r\n                }\r\n                else if (columnsNameToBeIndexed != null && !columnsNameToBeIndexed.isEmpty()\r\n                        && columnsNameToBeIndexed.contains(colName))\r\n                {\r\n                    metadata.addIndexProperty(columnName,\r\n                            populatePropertyIndex(columnName, null, null, null, (Field) attrib.getJavaMember()));\r\n                }\r\n            }\r\n\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @param indexedColumn\r\n     * @param f\r\n     * @return TODO: Make this method accept n number of parameters elegantly\r\n     */\r\n    private static PropertyIndex populatePropertyIndex(String indexName, String indexType, Integer max, Integer min,\r\n            Field f)\r\n    {\r\n        PropertyIndex pi = new PropertyIndex(f, indexName, indexType);\r\n\r\n        pi.setMax(max);\r\n        pi.setMin(min);\r\n\r\n        return pi;\r\n    }\r\n\r\n    /**\r\n     * Returns list of indexed columns on {@code @Embeddable} entity\r\n     * \r\n     * @param entityMetadata\r\n     *            entity metadata\r\n     * @return list of indexed columns\r\n     */\r\n    public static Map<String, PropertyIndex> getIndexesOnEmbeddable(Class<?> entityClazz)\r\n    {\r\n        Map<String, PropertyIndex> pis = new HashMap<String, PropertyIndex>();\r\n       \r\n        IndexCollection indexes = entityClazz.getAnnotation(IndexCollection.class);\r\n        List<String> columnsNameToBeIndexed = null;\r\n        Map<String, com.impetus.kundera.index.Index> columnsToBeIndexed = null;\r\n        if (null != indexes)\r\n        {\r\n            columnsToBeIndexed = new HashMap<String, com.impetus.kundera.index.Index>();\r\n            if (indexes.columns() != null && indexes.columns().length != 0)\r\n            {\r\n                for (com.impetus.kundera.index.Index indexedColumn : indexes.columns())\r\n                {\r\n                    columnsToBeIndexed.put(indexedColumn.name(), indexedColumn);\r\n                }\r\n            }\r\n        }\r\n       \r\n        getPropertyIndexes(entityClazz, pis, columnsNameToBeIndexed, columnsToBeIndexed);\r\n        return pis;\r\n    }\r\n\r\n    /**\r\n     * @param entityClazz\r\n     * @param pis\r\n     * @param columnsNameToBeIndexed\r\n     * @param columnsToBeIndexed\r\n     */\r\n    private static void getPropertyIndexes(Class<?> entityClazz, Map<String, PropertyIndex> pis,\r\n            List<String> columnsNameToBeIndexed, Map<String, com.impetus.kundera.index.Index> columnsToBeIndexed)\r\n    {\r\n        for (Field f : entityClazz.getDeclaredFields())\r\n        {\r\n            if (f.isAnnotationPresent(Column.class))\r\n            {\r\n                String fieldName = f.getName();\r\n                if (columnsToBeIndexed != null && !columnsToBeIndexed.isEmpty()\r\n                        && columnsToBeIndexed.containsKey(fieldName))\r\n                {\r\n                    com.impetus.kundera.index.Index indexedColumn = columnsToBeIndexed.get(fieldName);\r\n                    pis.put(indexedColumn.name(),\r\n                            populatePropertyIndex(indexedColumn.name(), indexedColumn.type(), indexedColumn.max(),\r\n                                    indexedColumn.min(), f));\r\n                }\r\n                else if (columnsNameToBeIndexed != null && !columnsNameToBeIndexed.isEmpty()\r\n                        && columnsNameToBeIndexed.contains(fieldName))\r\n                {\r\n                    pis.put(fieldName, populatePropertyIndex(fieldName, null, null, null, f));\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * prepare composite index.\r\n     * \r\n     * @param indexedColumns\r\n     * @param entityType\r\n     * @return\r\n     */\r\n    private String prepareCompositeIndexName(String indexedColumns, final EntityType entityType, EntityMetadata metadata)\r\n    {\r\n        StringTokenizer tokenizer = new StringTokenizer(indexedColumns, \",\");\r\n        StringBuilder builder = new StringBuilder();\r\n        while (tokenizer.hasMoreTokens())\r\n        {\r\n            String fieldName = (String) tokenizer.nextElement();\r\n\r\n            StringTokenizer stringTokenizer = new StringTokenizer(fieldName, \".\");\r\n            // if need to select embedded columns\r\n            if (stringTokenizer.countTokens() > 1)\r\n            {\r\n                fieldName = stringTokenizer.nextToken();\r\n                String embeddedFieldName = stringTokenizer.nextToken();\r\n                Attribute embeddable = entityType.getAttribute(fieldName);\r\n\r\n                EmbeddableType embeddedEntity = (EmbeddableType) kunderaMetadata.getApplicationMetadata()\r\n                        .getMetaModelBuilder(metadata.getPersistenceUnit()).getEmbeddables()\r\n                        .get(((AbstractAttribute) embeddable).getBindableJavaType());\r\n\r\n                Attribute embeddedAttribute = embeddedEntity.getAttribute(embeddedFieldName);\r\n\r\n                builder.append(((AbstractAttribute) embeddedAttribute).getJPAColumnName());\r\n            }\r\n            else\r\n            {\r\n                builder.append(((AbstractAttribute) entityType.getAttribute(fieldName)).getJPAColumnName());\r\n            }\r\n            builder.append(\",\");\r\n\r\n        }\r\n\r\n        // scan embeddable as well for\r\n\r\n        builder.deleteCharAt(builder.length() - 1);\r\n\r\n        return builder.toString();\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/MetaModelBuilder.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.TypeVariable;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javassist.Modifier;\n\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Embedded;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.IdClass;\nimport javax.persistence.Lob;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.MappedSuperclass;\nimport javax.persistence.OneToMany;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Transient;\nimport javax.persistence.metamodel.Attribute.PersistentAttributeType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.ManagedType;\nimport javax.persistence.metamodel.MappedSuperclassType;\nimport javax.persistence.metamodel.PluralAttribute;\nimport javax.persistence.metamodel.SingularAttribute;\nimport javax.persistence.metamodel.Type;\nimport javax.persistence.metamodel.Type.PersistenceType;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.loader.MetamodelLoaderException;\nimport com.impetus.kundera.metadata.model.attributes.DefaultCollectionAttribute;\nimport com.impetus.kundera.metadata.model.attributes.DefaultListAttribute;\nimport com.impetus.kundera.metadata.model.attributes.DefaultMapAttribute;\nimport com.impetus.kundera.metadata.model.attributes.DefaultSetAttribute;\nimport com.impetus.kundera.metadata.model.attributes.DefaultSingularAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractIdentifiableType;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.metadata.model.type.DefaultBasicType;\nimport com.impetus.kundera.metadata.model.type.DefaultEmbeddableType;\nimport com.impetus.kundera.metadata.model.type.DefaultEntityType;\nimport com.impetus.kundera.metadata.model.type.DefaultMappedSuperClass;\n\n/**\n * The Class MetaModelBuilder.\n * \n * @param <X>\n *            the generic managed type\n * @param <T>\n *            the generic attribute type\n * \n *            TODO : Handle of {@link MappedSuperclass}, {@link IdClass}\n * \n * @author vivek.mishra\n */\npublic final class MetaModelBuilder<X, T>\n{\n    /** The Constant log. */\n    private static final Logger LOG = LoggerFactory.getLogger(MetaModelBuilder.class);\n\n    /** The managed type. */\n    private AbstractManagedType<X> managedType;\n\n    /** The managed types. */\n    private Map<Class<?>, EntityType<?>> managedTypes = new HashMap<Class<?>, EntityType<?>>();\n\n    /** The mapped super class types. */\n    private Map<Class<?>, ManagedType<?>> mappedSuperClassTypes = new HashMap<Class<?>, ManagedType<?>>();\n\n    /** The embeddables. */\n    private Map<Class<?>, AbstractManagedType<?>> embeddables = new HashMap<Class<?>, AbstractManagedType<?>>();\n\n    /**\n     * Process.\n     * \n     * @param clazz\n     *            the clazz\n     */\n    public void process(Class<X> clazz)\n    {\n        this.managedType = processInternal(clazz, false);\n\n        // TODO: this.managedType has to be removed.\n        // Need a validation that TypeBuilder class must be same as\n        // MetaModelBuilder class.\n\n        // TODO::: To handle association cases, need to check from managedType\n        // only and populate the same.\n\n    }\n\n    /**\n     * Adds the embeddables.\n     * \n     * @param clazz\n     *            the clazz\n     * @param embeddable\n     *            the embeddable\n     */\n    void addEmbeddables(Class<?> clazz, AbstractManagedType<?> embeddable)\n    {\n        embeddables.put(clazz, embeddable);\n    }\n\n    /**\n     * Construct.\n     * \n     * @param clazz\n     *            the clazz\n     * @param attribute\n     *            the attribute\n     */\n    void construct(Class<X> clazz, Field attribute)\n    {\n        TypeBuilder<X> typeBuilder = new TypeBuilder<X>(attribute);\n        typeBuilder.build((AbstractManagedType) managedTypes.get(clazz), attribute.getType());\n    }\n\n    /**\n     * The Class TypeBuilder.\n     * \n     * @param <X>\n     *            the generic type\n     */\n    private class TypeBuilder<X>\n    {\n\n        /** The attribute. */\n        private Field attribute;\n\n        /** The persistent attribute type. */\n        private PersistentAttributeType persistentAttribType;\n\n        /**\n         * Instantiates a new type builder.\n         * \n         * @param attribute\n         *            the attribute\n         */\n        TypeBuilder(Field attribute)\n        {\n            this.attribute = attribute;\n        }\n\n        /**\n         * Instantiates a new type builder.\n         * \n         * @param attribute\n         *            the attribute\n         * @param persistentAttribType\n         *            the persistent attrib type\n         */\n        TypeBuilder(Field attribute, PersistentAttributeType persistentAttribType)\n        {\n            this.attribute = attribute;\n            this.persistentAttribType = persistentAttribType;\n        }\n\n        /**\n         * Builds the type.\n         * \n         * @param <T>\n         *            the generic type\n         * @param attribType\n         *            the attrib type\n         * @return the type\n         */\n        <T> Type<T> buildType(Class<T> attribType)\n        {\n            // Only in case of Map attribute attribute will be null;\n            PersistentAttributeType attributeType = attribute != null ? MetaModelBuilder\n                    .getPersistentAttributeType(attribute) : persistentAttribType;\n            switch (attributeType)\n            {\n            case BASIC:\n                return new DefaultBasicType<T>(attribType);\n            case EMBEDDED:\n                return processOnEmbeddables(attribType);\n\n            case ELEMENT_COLLECTION:\n                if (attribute != null && Collection.class.isAssignableFrom(attribType))\n                {\n                    java.lang.reflect.Type[] argument = ((ParameterizedType) attribute.getGenericType())\n                            .getActualTypeArguments();\n\n                    return processOnEmbeddables(getTypedClass(argument[0]));\n                }\n                else if (attribute != null && Map.class.isAssignableFrom(attribType))\n                {\n                    java.lang.reflect.Type[] argument = ((ParameterizedType) attribute.getGenericType())\n                            .getActualTypeArguments();\n                    processOnEmbeddables(getTypedClass(argument[0]));\n                    return processOnEmbeddables(getTypedClass(argument[1]));\n                }\n                else\n                {\n                    LOG.warn(\"Cannot process for : \" + attribute\n                            + \" as it is not a collection but annotated with @ElementCollection\");\n                }\n            default:\n                if (!(managedTypes.get(attribType) != null))\n                {\n                    // get Generic type from attribute and then pass it.\n                    if (attribute != null && isPluralAttribute(attribute))\n                    {\n                        java.lang.reflect.Type[] arguments = ((ParameterizedType) attribute.getGenericType())\n                                .getActualTypeArguments();\n                        if (arguments != null && arguments.length == 1)\n                        {\n                            attribType = (Class<T>) getTypedClass(arguments[0]);\n                        }\n                        else if (arguments != null && arguments.length > 1)\n                        {\n                            attribType = (Class<T>) getTypedClass(arguments[1]);\n                        }\n                    }\n\n                    // If generic typed class is managed entity.\n                    if (managedTypes.get(attribType) == null)\n                    {\n\n                        if (attribType.isAnnotationPresent(Entity.class))\n                        {\n                            EntityType<T> entityType = new DefaultEntityType<T>((Class<T>) attribType,\n                                    PersistenceType.ENTITY, (AbstractIdentifiableType) getType(\n                                            attribType.getSuperclass(), false));\n                            managedTypes.put(attribType, entityType);\n                        }\n                        else\n                        {\n                            return new DefaultBasicType<T>(attribType);\n                        }\n                    }\n                }\n                return (Type<T>) managedTypes.get(attribType);\n            }\n        }\n\n        /**\n         * Process on embeddables.\n         * \n         * @param <T>\n         *            the generic type\n         * @param attribType\n         *            the attrib type\n         * @return the abstract managed type\n         */\n        private AbstractManagedType processOnEmbeddables(Class attribType)\n        {\n            // Check if this embeddable type is already present in\n            // collection of MetaModelBuider.\n            AbstractManagedType<T> embeddableType = null;\n\n            PersistenceType persistenceType = PersistenceType.BASIC;\n            Annotation embeddableAnnotation = attribType.getAnnotation(Embeddable.class);\n            if (embeddableAnnotation != null)\n            {\n                persistenceType = PersistenceType.EMBEDDABLE;\n            }\n\n            if (!embeddables.containsKey(attribType))\n            {\n                embeddableType = new DefaultEmbeddableType<T>(attribType, persistenceType, null);\n\n                if (attribute != null)\n                {\n                    Field[] embeddedFields = attribType.getDeclaredFields();\n                    for (Field f : embeddedFields)\n                    {\n                        if (isNonTransient(f))\n                        {\n                            new TypeBuilder<T>(f).build(embeddableType, f.getType());\n                        }\n                    }\n                }\n                addEmbeddables(attribType, embeddableType);\n            }\n            else\n            {\n                embeddableType = (AbstractManagedType<T>) embeddables.get(attribType);\n            }\n\n            onPostProcess(embeddableType);\n\n            return embeddableType;\n        }\n\n        /**\n         * Checks for constraint on embeddabletype and accordingly set it on\n         * managedType\n         * \n         * @param embeddableType\n         */\n        private void onPostProcess(AbstractManagedType<T> embeddableType)\n        {\n            try\n            {\n                if (managedType != null)\n                {\n                    \n                    Field managedTypeField = managedType.getClass().getSuperclass().getSuperclass()\n                            .getDeclaredField(\"hasValidationConstraints\");\n\n                    if (!managedTypeField.isAccessible())\n                    {\n                        managedTypeField.setAccessible(true);\n                    }\n\n                    if (embeddableType.hasValidationConstraints())\n                    {\n                        managedTypeField.set(managedType, true);\n\n                    }\n\n                }\n            }\n            catch (Exception e)\n            {\n                LOG.error(\"Error setting Contstraint for managed type, Caused by: {}\", e);\n                throw new MetamodelLoaderException(\"Error setting Contstraint for managed type\" + e.getMessage());\n            }\n\n        }\n\n        /**\n         * Builds the.\n         * \n         * @param managedType\n         *            the managed type\n         * @param attributeType\n         *            the attribute type\n         */\n        void build(AbstractManagedType managedType, Class attributeType)\n        {\n            new AttributeBuilder(attribute, managedType, buildType(attributeType)).build();\n        }\n\n        /**\n         * The Class AttributeBuilder.\n         * \n         * @param <X>\n         *            the generic type\n         * @param <T>\n         *            the generic type\n         */\n        private class AttributeBuilder<X, T>\n        {\n\n            /** The attribute. */\n            private Field attribute;\n\n            /** The attribute type. */\n            private Type<T> attributeType;\n\n            /** The managed type. */\n            private AbstractManagedType<X> managedType;\n\n            /**\n             * Instantiates a new attribute builder.\n             * \n             * @param attribute\n             *            the attribute\n             * @param managedType\n             *            the managed type\n             * @param attributeType\n             *            the attribute type\n             */\n            public AttributeBuilder(Field attribute, AbstractManagedType<X> managedType, Type<T> attributeType)\n            {\n                this.attribute = attribute;\n                this.managedType = managedType;\n                this.attributeType = attributeType;\n            }\n\n            /**\n             * Builds the.\n             * \n             * @param <K>\n             *            the key type\n             * @param <V>\n             *            the value type\n             */\n            public <K, V> void build()\n            {\n                if (isNonTransient(attribute))\n                {\n                    if (!managedType.hasLobAttribute() && attribute.getAnnotation(Lob.class) != null)\n                        managedType.setHasLobAttribute(true);\n\n                    if (isPluralAttribute(attribute))\n                    {\n                        PluralAttribute<X, ?, ?> pluralAttribute = null;\n                        if (attribute.getType().equals(java.util.Collection.class))\n                        {\n                            pluralAttribute = new DefaultCollectionAttribute<X, T>(attributeType, attribute.getName(),\n                                    getAttributeType(), managedType, attribute,\n                                    (Class<java.util.Collection<T>>) attribute.getType());\n                        }\n                        else if (attribute.getType().equals(java.util.List.class))\n                        {\n                            pluralAttribute = new DefaultListAttribute<X, T>(attributeType, attribute.getName(),\n                                    getAttributeType(), managedType, attribute, (Class<List<T>>) attribute.getType());\n                        }\n                        else if (attribute.getType().equals(java.util.Set.class))\n                        {\n                            pluralAttribute = new DefaultSetAttribute<X, T>(attributeType, attribute.getName(),\n                                    getAttributeType(), managedType, attribute, (Class<Set<T>>) attribute.getType());\n                        }\n                        else if (attribute.getType().equals(java.util.Map.class))\n                        {\n                            java.lang.reflect.Type[] arguments = ((ParameterizedType) attribute.getGenericType())\n                                    .getActualTypeArguments();\n\n                            Type keyType = new TypeBuilder<X>(null, getPersistentAttributeType(attribute))\n                                    .buildType(getTypedClass(arguments[0]));\n                            pluralAttribute = new DefaultMapAttribute(attributeType, attribute.getName(),\n                                    getAttributeType(), managedType, attribute, (Class<Map<T, ?>>) attribute.getType(),\n                                    keyType);\n                        }\n                        ((AbstractManagedType<X>) managedType).addPluralAttribute(attribute.getName(), pluralAttribute);\n                    }\n                    else\n                    {\n                        SingularAttribute<X, T> singularAttribute = new DefaultSingularAttribute(attribute.getName(),\n                                getAttributeType(), attribute, attributeType, managedType, checkId(attribute));\n                        ((AbstractManagedType<X>) managedType).addSingularAttribute(attribute.getName(),\n                                singularAttribute);\n\n                        if (checkSimpleId(attribute) && checkIdClass(managedType.getJavaType()))\n\n                        {\n                            IdClass anno = managedType.getJavaType().getAnnotation(IdClass.class);\n                            AbstractManagedType superType = onSuperType(anno.value(), true);\n                            onDeclaredFields(anno.value(), superType);\n                            ((AbstractIdentifiableType<X>) managedType).addIdAttribute(singularAttribute, true,\n                                    superType.getDeclaredSingularAttributes());\n                        }\n                        else if (checkEmbeddedId(attribute))\n                        {\n                            AbstractManagedType superType = onSuperType(attribute.getType(), false);\n                            checkEmbeddable(superType.getJavaType(), attribute.getName());\n                            ((AbstractIdentifiableType<X>) managedType).addIdAttribute(singularAttribute, true,\n                                    superType.getDeclaredSingularAttributes());\n\n                        }\n                        else if (checkSimpleId(attribute))\n                        {\n                            ((AbstractIdentifiableType<X>) managedType).addIdAttribute(singularAttribute, false, null);\n                        }\n                    }\n                }\n            }\n\n            /**\n             * Validates that super type must be embeddable.\n             * \n             * @param superType\n             * @throws MetamodelLoaderException\n             *             exception.\n             */\n            private void checkEmbeddable(Class superType, String fieldname)\n            {\n                // check validity.\n                if (superType != null && !superType.isAnnotationPresent(Embeddable.class))\n                {\n                    throw new MetamodelLoaderException(\"Field: \" + fieldname\n                            + \" is annotated with @EmbeddedId but corresponding class:\" + superType\n                            + \" is not an @Embeddable entity\");\n                }\n            }\n\n            private AbstractManagedType onSuperType(Class clazz, boolean isIdClass)\n            {\n                AbstractManagedType superType = getType(clazz, isIdClass);\n\n                isValidId(superType);\n\n                return superType;\n            }\n\n            /**\n             * Check id.\n             * \n             * @param member\n             *            the member\n             * @return true, if successful\n             */\n            boolean checkId(Field member)\n            {\n                return checkSimpleId(member) || checkEmbeddedId(member);\n            }\n\n            /**\n             * Check simple id.\n             * \n             * @param member\n             *            the member\n             * @return true, if successful\n             */\n            boolean checkSimpleId(Field member)\n            {\n                return member.isAnnotationPresent(Id.class);\n            }\n\n            /**\n             * Check id class.\n             * \n             * @param member\n             *            the member\n             * @return true, if successful\n             */\n            boolean checkIdClass(Class member)\n            {\n                return member.isAnnotationPresent(IdClass.class);\n            }\n\n            /**\n             * Check embedded id.\n             * \n             * @param member\n             *            the member\n             * @return true, if successful\n             */\n            boolean checkEmbeddedId(Field member)\n            {\n                return member.isAnnotationPresent(EmbeddedId.class);\n            }\n\n            /**\n             * Gets the attribute type.\n             * \n             * @return the attribute type\n             */\n            PersistentAttributeType getAttributeType()\n            {\n                return MetaModelBuilder.getPersistentAttributeType(attribute);\n            }\n        }\n\n        private void isValidId(AbstractManagedType superType)\n        {\n            if (superType == null)\n            {\n                throw new MetamodelLoaderException(\"field : \" + attribute.getName()\n                        + \" is either annotated with @EmbeddedId or class:\" + managedType.getJavaType()\n                        + \" is annotated with @Idclass, but enclosed class is not having any member\");\n            }\n        }\n\n    }\n\n    /**\n     * Gets the managed types.\n     * \n     * @return the managedTypes\n     */\n    public Map<Class<?>, EntityType<?>> getManagedTypes()\n    {\n        return managedTypes;\n    }\n\n    /**\n     * Gets the embeddables.\n     * \n     * @return the embeddables\n     */\n    public Map<Class<?>, AbstractManagedType<?>> getEmbeddables()\n    {\n        return embeddables;\n    }\n\n    /**\n     * @return the mappedSuperClassTypes\n     */\n    public Map<Class<?>, ManagedType<?>> getMappedSuperClassTypes()\n    {\n        return mappedSuperClassTypes;\n    }\n\n    /**\n     * Returns true, if attribute belongs plural hierarchy.\n     * \n     * @param attribute\n     *            the attribute\n     * @return true, if attribute belongs plural hierarchy. else false.\n     */\n    private boolean isPluralAttribute(Field attribute)\n    {\n        return attribute.getType().equals(Collection.class) || attribute.getType().equals(Set.class)\n                || attribute.getType().equals(List.class) || attribute.getType().equals(Map.class);\n    }\n\n    /**\n     * Gets the typed class.\n     * \n     * @param type\n     *            the type\n     * @return the typed class\n     */\n    private Class<?> getTypedClass(java.lang.reflect.Type type)\n    {\n        if (type instanceof Class)\n        {\n            return ((Class) type);\n        }\n        else if (type instanceof ParameterizedType)\n        {\n            java.lang.reflect.Type rawParamterizedType = ((ParameterizedType) type).getRawType();\n            return getTypedClass(rawParamterizedType);\n        }\n        else if (type instanceof TypeVariable)\n        {\n            java.lang.reflect.Type upperBound = ((TypeVariable) type).getBounds()[0];\n            return getTypedClass(upperBound);\n        }\n\n        throw new IllegalArgumentException(\"Error while finding generic class for :\" + type);\n    }\n\n    /**\n     * Gets the persistent attribute type.\n     * \n     * @param member\n     *            the member\n     * @return the persistent attribute type\n     */\n    static PersistentAttributeType getPersistentAttributeType(Field member)\n    {\n        PersistentAttributeType attributeType = PersistentAttributeType.BASIC;\n        if (member.isAnnotationPresent(ElementCollection.class))\n        {\n            attributeType = PersistentAttributeType.ELEMENT_COLLECTION;\n        }\n        else if (member.isAnnotationPresent(OneToMany.class))\n        {\n            attributeType = PersistentAttributeType.ONE_TO_MANY;\n        }\n        else if (member.isAnnotationPresent(ManyToMany.class))\n        {\n            attributeType = PersistentAttributeType.MANY_TO_MANY;\n        }\n        else if (member.isAnnotationPresent(ManyToOne.class))\n        {\n            attributeType = PersistentAttributeType.MANY_TO_ONE;\n        }\n        else if (member.isAnnotationPresent(OneToOne.class))\n        {\n            attributeType = PersistentAttributeType.ONE_TO_ONE;\n        }\n        else if (member.isAnnotationPresent(Embedded.class))\n        {\n            attributeType = PersistentAttributeType.EMBEDDED;\n        }\n\n        return attributeType;\n\n    }\n\n    /**\n     * Builds the managed type.\n     * \n     * @param <X>\n     *            the generic type\n     * @param clazz\n     *            the clazz\n     * @return the abstract managed type\n     */\n    private <X> AbstractManagedType<X> buildManagedType(Class<X> clazz, boolean isIdClass)\n    {\n        AbstractManagedType<X> managedType = null;\n        if (clazz.isAnnotationPresent(Embeddable.class))\n        {\n\n            validate(clazz, true);\n            if (!embeddables.containsKey(clazz))\n            {\n                managedType = new DefaultEmbeddableType<X>(clazz, PersistenceType.EMBEDDABLE, getType(\n                        clazz.getSuperclass(), isIdClass));\n                onDeclaredFields(clazz, managedType);\n                embeddables.put(clazz, managedType);\n            }\n            else\n            {\n                managedType = (AbstractManagedType<X>) embeddables.get(clazz);\n            }\n\n        }\n        else if (clazz.isAnnotationPresent(MappedSuperclass.class))\n        {\n\n            validate(clazz, false);\n            // if (!mappedSuperClassTypes.containsKey(clazz))\n            // {\n            managedType = new DefaultMappedSuperClass<X>(clazz, PersistenceType.MAPPED_SUPERCLASS,\n                    (AbstractIdentifiableType) getType(clazz.getSuperclass(), isIdClass));\n            onDeclaredFields(clazz, managedType);\n            mappedSuperClassTypes.put(clazz, (MappedSuperclassType<?>) managedType);\n            // }\n            // else\n            // {\n            // managedType = (AbstractManagedType<X>)\n            // mappedSuperClassTypes.get(clazz);\n            // }\n        }\n        else if (clazz.isAnnotationPresent(Entity.class) || isIdClass)\n        {\n            if (!managedTypes.containsKey(clazz))\n            {\n                managedType = new DefaultEntityType<X>(clazz, PersistenceType.ENTITY,\n                        (AbstractIdentifiableType) getType(clazz.getSuperclass(), isIdClass));\n                // in case of @IdClass, it is a temporary managed type.\n                if (!isIdClass)\n                {\n                    managedTypes.put(clazz, (EntityType<?>) managedType);\n                }\n            }\n            else\n            {\n                managedType = (AbstractManagedType<X>) managedTypes.get(clazz);\n            }\n        }\n\n        return managedType;\n    }\n\n    /**\n     * Gets the super type.\n     * \n     * @param clazz\n     *            the clazz\n     * @return the super type\n     */\n    private AbstractManagedType getType(Class clazz, boolean isIdClass)\n    {\n        if (clazz != null && !clazz.equals(Object.class))\n        {\n            return processInternal(clazz, isIdClass);\n        }\n        return null;\n    }\n\n    /**\n     * Validate.\n     * \n     * @param <X>\n     *            the generic type\n     * @param clazz\n     *            the clazz\n     * @param isEmbeddable\n     *            the is embeddable\n     */\n    private <X> void validate(Class<X> clazz, boolean isEmbeddable)\n    {\n        final String mappedSuperClazzErrMsg = \"Class:\" + clazz\n                + \"is annotated with @MappedSuperClass and @Entity not allowed\";\n        final String embeddableClazzErrMsg = \"Class:\" + clazz + \"is annotated with @Embeddable and @Entity not allowed\";\n        if (clazz.isAnnotationPresent(Entity.class))\n        {\n            throw new MetamodelLoaderException(isEmbeddable ? embeddableClazzErrMsg : mappedSuperClazzErrMsg);\n        }\n    }\n\n    /**\n     * On declared fields.\n     * \n     * @param <X>\n     *            the generic type\n     * @param clazz\n     *            the clazz\n     * @param managedType\n     *            the managed type\n     */\n    private <X> void onDeclaredFields(Class<X> clazz, AbstractManagedType<X> managedType)\n    {\n        Field[] embeddedFields = clazz.getDeclaredFields();\n        for (Field f : embeddedFields)\n        {\n            if (isNonTransient(f))\n            {\n                new TypeBuilder<T>(f).build(managedType, f.getType());\n            }\n        }\n    }\n\n    /**\n     * Process.\n     * \n     * @param clazz\n     *            the clazz\n     * @return the abstract managed type\n     */\n    private AbstractManagedType<X> processInternal(Class<X> clazz, boolean isIdClass)\n    {\n        if (managedTypes.get(clazz) == null)\n        {\n            return buildManagedType(clazz, isIdClass);\n        }\n        else\n        {\n            return (AbstractManagedType<X>) managedTypes.get(clazz);\n        }\n    }\n\n    /**\n     * @return\n     */\n    private boolean isNonTransient(Field attribute)\n    {\n        return attribute != null && !Modifier.isStatic(attribute.getModifiers())\n                && !Modifier.isTransient(attribute.getModifiers()) && !attribute.isAnnotationPresent(Transient.class);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/TableProcessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor;\n\nimport java.lang.reflect.Field;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javassist.Modifier;\n\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Embedded;\nimport javax.persistence.NamedNativeQueries;\nimport javax.persistence.NamedNativeQuery;\nimport javax.persistence.NamedQueries;\nimport javax.persistence.NamedQuery;\nimport javax.persistence.PersistenceException;\nimport javax.persistence.Transient;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.loader.MetamodelLoaderException;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata.Type;\nimport com.impetus.kundera.metadata.model.type.AbstractIdentifiableType;\nimport com.impetus.kundera.metadata.processor.relation.RelationMetadataProcessor;\nimport com.impetus.kundera.metadata.processor.relation.RelationMetadataProcessorFactory;\nimport com.impetus.kundera.metadata.validator.EntityValidatorImpl;\nimport com.impetus.kundera.metadata.validator.InvalidEntityDefinitionException;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.validation.ValidationFactory;\nimport com.impetus.kundera.validation.ValidationFactoryGenerator;\nimport com.impetus.kundera.validation.ValidationFactoryGenerator.ValidationFactoryType;\nimport com.impetus.kundera.validation.rules.RelationAttributeRule;\nimport com.impetus.kundera.validation.rules.RuleValidationException;\n\n/**\n * Metadata processor class for persistent entities.\n * \n * @author amresh.singh\n */\npublic class TableProcessor extends AbstractEntityFieldProcessor\n{\n\n    /** The Constant log. */\n    private static final Logger LOG = LoggerFactory.getLogger(TableProcessor.class);\n\n    /** holds pu prperties */\n    private Map puProperties;\n\n    private ValidationFactory factory;\n\n    /**\n     * Instantiates a new table processor.\n     */\n    public TableProcessor(Map puProperty, KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n        validator = new EntityValidatorImpl(puProperty);\n        // validator = new EntityValidatorImpl(puProperty);\n        ValidationFactoryGenerator generator = new ValidationFactoryGenerator();\n        this.factory = generator.getFactory(ValidationFactoryType.BOOT_STRAP_VALIDATION);\n        this.puProperties = puProperty;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.metadata.MetadataProcessor#process(java.lang.Class,\n     * com.impetus.kundera.metadata.model.EntityMetadata)\n     */\n    @Override\n    public void process(Class clazz, EntityMetadata metadata)\n    {\n\n        if (LOG.isDebugEnabled())\n            LOG.debug(\"Processing @Entity(\" + clazz.getName() + \") for Persistence Object.\");\n        populateMetadata(metadata, clazz, puProperties);\n    }\n\n    /**\n     * Populate metadata.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     * @param metadata\n     *            the metadata\n     * @param clazz\n     *            the clazz\n     */\n    private <X extends Class, T extends Object> void populateMetadata(EntityMetadata metadata, Class<X> clazz,\n            Map puProperties)\n    {\n        // process for metamodelImpl\n\n        if (metadata.getPersistenceUnit() != null)\n        {\n            MetaModelBuilder<X, T> metaModelBuilder = kunderaMetadata.getApplicationMetadata().getMetaModelBuilder(\n                    metadata.getPersistenceUnit());\n\n            onBuildMetaModelSuperClass(clazz.getSuperclass(), metaModelBuilder);\n\n            metaModelBuilder.process(clazz);\n\n            for (Field f : clazz.getDeclaredFields())\n            {\n                if (f != null && !Modifier.isStatic(f.getModifiers()) && !Modifier.isTransient(f.getModifiers())\n                        && !f.isAnnotationPresent(Transient.class))\n                {\n                    // construct metamodel.\n                    metaModelBuilder.construct(clazz, f);\n\n                    // on id attribute.\n                    onIdAttribute(metaModelBuilder, metadata, clazz, f);\n\n                    // determine if it is a column family or super column\n                    // family.\n                    onFamilyType(metadata, clazz, f);\n                }\n            }\n\n            EntityType entityType = (EntityType) metaModelBuilder.getManagedTypes().get(metadata.getEntityClazz());\n\n            validateAndSetId(metadata, clazz, metaModelBuilder);\n            validateandSetEntityType(metadata, clazz, metaModelBuilder);\n            MetadataUtils.onJPAColumnMapping(entityType, metadata);\n\n            /* Scan for Relationship field */\n            populateRelationMetaData(entityType, clazz, metadata);\n        }\n    }\n\n    /**\n     * Populate metadata.\n     * \n     * @param entityType\n     *            the EntityType\n     * @param <X>\n     *            the generic type\n     * @param metadata\n     *            the metadata\n     * @throws RuleValidationException\n     */\n    private <X> void populateRelationMetaData(EntityType entityType, Class<X> clazz, EntityMetadata metadata)\n    {\n        Set<Attribute> attributes = entityType.getAttributes();\n\n        for (Attribute attribute : attributes)\n        {\n            if (attribute.isAssociation())\n            {\n\n                addRelationIntoMetadata(clazz, (Field) attribute.getJavaMember(), metadata);\n            }\n        }\n\n    }\n\n    /**\n     * Populate metadata.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     * @param metaModelBuilder\n     *            the metaModelBuilder\n     */\n    private <X, T> void onBuildMetaModelSuperClass(Class<? super X> clazz, MetaModelBuilder<X, T> metaModelBuilder)\n    {\n        if (clazz != null && clazz.isAnnotationPresent(javax.persistence.Entity.class))\n        {\n            while (clazz != null && clazz.isAnnotationPresent(javax.persistence.Entity.class))\n            {\n                metaModelBuilder.process((Class<X>) clazz);\n\n                for (Field f : clazz.getDeclaredFields())\n                {\n                    if (f != null && !Modifier.isStatic(f.getModifiers()) && !Modifier.isTransient(f.getModifiers())\n                            && !f.isAnnotationPresent(Transient.class))\n                    {\n                        metaModelBuilder.construct((Class<X>) clazz, f);\n                    }\n\n                }\n                clazz = clazz.getSuperclass();\n            }\n        }\n    }\n\n    /**\n     * Adds relationship info into metadata for a given field\n     * <code>relationField</code>.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param relationField\n     *            the relation field\n     * @param metadata\n     *            the metadata\n     */\n    private void addRelationIntoMetadata(Class<?> entityClass, Field relationField, EntityMetadata metadata)\n    {\n        RelationMetadataProcessor relProcessor = null;\n        try\n        {\n            relProcessor = RelationMetadataProcessorFactory\n                    .getRelationMetadataProcessor(relationField, kunderaMetadata);\n\n            this.factory.validate(relationField, new RelationAttributeRule());\n\n            relProcessor = RelationMetadataProcessorFactory\n                    .getRelationMetadataProcessor(relationField, kunderaMetadata);\n\n            if (relProcessor != null)\n            {\n                relProcessor.addRelationIntoMetadata(relationField, metadata);\n            }\n\n        }\n        catch (PersistenceException pe)\n        {\n            throw new MetamodelLoaderException(\"Error with relationship in @Entity(\" + entityClass + \".\"\n                    + relationField.getName() + \"), reason: \" + pe);\n        }\n\n    }\n\n    /**\n     * Add named/native query annotated fields to application meta data.\n     * \n     * @param clazz\n     *            entity class.\n     */\n    private void addNamedNativeQueryMetadata(Class clazz)\n    {\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\n        String name, query = null;\n        if (clazz.isAnnotationPresent(NamedQuery.class))\n        {\n            NamedQuery ann = (NamedQuery) clazz.getAnnotation(NamedQuery.class);\n            appMetadata.addQueryToCollection(ann.name(), ann.query(), false, clazz);\n        }\n\n        if (clazz.isAnnotationPresent(NamedQueries.class))\n        {\n            NamedQueries ann = (NamedQueries) clazz.getAnnotation(NamedQueries.class);\n\n            NamedQuery[] anns = ann.value();\n            for (NamedQuery a : anns)\n            {\n                appMetadata.addQueryToCollection(a.name(), a.query(), false, clazz);\n            }\n        }\n\n        if (clazz.isAnnotationPresent(NamedNativeQuery.class))\n        {\n            NamedNativeQuery ann = (NamedNativeQuery) clazz.getAnnotation(NamedNativeQuery.class);\n            appMetadata.addQueryToCollection(ann.name(), ann.query(), true, clazz);\n        }\n\n        if (clazz.isAnnotationPresent(NamedNativeQueries.class))\n        {\n            NamedNativeQueries ann = (NamedNativeQueries) clazz.getAnnotation(NamedNativeQueries.class);\n\n            NamedNativeQuery[] anns = ann.value();\n            for (NamedNativeQuery a : anns)\n            {\n                appMetadata.addQueryToCollection(a.name(), a.query(), true, clazz);\n            }\n        }\n    }\n\n    /**\n     * On id attribute.\n     * \n     * @param builder\n     *            the builder\n     * @param entityMetadata\n     *            the entity metadata\n     * @param clazz\n     *            the clazz\n     * @param f\n     *            the f\n     */\n    private void onIdAttribute(final MetaModelBuilder builder, EntityMetadata entityMetadata, final Class clazz, Field f)\n    {\n        EntityType entity = (EntityType) builder.getManagedTypes().get(clazz);\n\n        Attribute attrib = entity.getAttribute(f.getName());\n        if (!attrib.isCollection() && ((SingularAttribute) attrib).isId())\n        {\n            entityMetadata.setIdAttribute((SingularAttribute) attrib);\n            populateIdAccessorMethods(entityMetadata, clazz, f);\n        }\n    }\n\n    /**\n     * On family type.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param clazz\n     *            the clazz\n     * @param f\n     *            the f\n     */\n    private void onFamilyType(EntityMetadata entityMetadata, final Class clazz, Field f)\n    {\n        if (entityMetadata.getType() == null || !entityMetadata.getType().equals(Type.SUPER_COLUMN_FAMILY))\n        {\n            if ((f.isAnnotationPresent(Embedded.class) && f.getType().getAnnotation(Embeddable.class) != null))\n            {\n                entityMetadata.setType(Type.SUPER_COLUMN_FAMILY);\n            }\n            else if (f.isAnnotationPresent(ElementCollection.class) && !MetadataUtils.isBasicElementCollectionField(f))\n            {\n                entityMetadata.setType(Type.SUPER_COLUMN_FAMILY);\n            }\n            else\n            {\n                entityMetadata.setType(Type.COLUMN_FAMILY);\n            }\n        }\n    }\n\n    /**\n     * \n     * @param metadata\n     * @param clazz\n     * @param metaModelBuilder\n     */\n    private <X, T> void validateAndSetId(EntityMetadata metadata, Class<X> clazz,\n            MetaModelBuilder<X, T> metaModelBuilder)\n    {\n        if (metadata.getIdAttribute() == null)\n        {\n            EntityType entityType = (EntityType) metaModelBuilder.getManagedTypes().get(clazz);\n\n            if (entityType.getSupertype() != null)\n            {\n                Attribute idAttribute = ((AbstractIdentifiableType) entityType.getSupertype()).getIdAttribute();\n\n                metadata.setIdAttribute((SingularAttribute) idAttribute);\n                populateIdAccessorMethods(metadata, clazz, (Field) idAttribute.getJavaMember());\n            }\n        }\n\n        validateIdAttribute(metadata.getIdAttribute(), clazz);\n    }\n    \n    /**\n     * \n     * @param metadata\n     * @param clazz\n     * @param metaModelBuilder\n     */\n    private <X, T> void validateandSetEntityType(EntityMetadata metadata, Class<X> clazz,\n            MetaModelBuilder<X, T> metaModelBuilder)\n    {\n        if (metadata.getType() == null && clazz != null && !clazz.equals(Object.class) \n                            && clazz.isAnnotationPresent(javax.persistence.Entity.class))\n        {\n            EntityType entityType = (EntityType) metaModelBuilder.getManagedTypes().get(clazz);\n\n            if (entityType.getSupertype() != null)\n            {\n                Set<Attribute> attributes = ((AbstractIdentifiableType) entityType.getSupertype()).getAttributes();\n                Iterator<Attribute> iter = attributes.iterator();\n\n                while (iter.hasNext())\n                {\n                    Attribute attribute = iter.next();\n                   \n                    Field f = (Field) ((Field) attribute.getJavaMember());\n                    \n                    onFamilyType(metadata, clazz, f);\n                }\n                \n\n            }\n            validateandSetEntityType(metadata, (Class<X>) clazz.getSuperclass(), metaModelBuilder);\n        }\n\n    }\n\n    /**\n     * \n     * @param idAttribute\n     * @param clazz\n     */\n    private void validateIdAttribute(SingularAttribute idAttribute, Class clazz)\n    {\n        // Means if id attribute not found neither on entity or mappedsuper\n        // class.\n\n        if (idAttribute == null)\n        {\n            throw new InvalidEntityDefinitionException(clazz.getName() + \" must have an @Id field.\");\n        }\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/relation/ManyToManyRelationMetadataProcessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor.relation;\n\nimport java.lang.reflect.Field;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.MapKeyClass;\nimport javax.persistence.MapKeyJoinColumn;\n\nimport com.impetus.kundera.loader.MetamodelLoaderException;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.JoinTableMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.processor.AbstractEntityFieldProcessor;\nimport com.impetus.kundera.metadata.validator.EntityValidatorImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\n\n/**\n * The Class ManyToManyRelationMetadataProcessor.\n * \n * @author Amresh Singh\n */\npublic class ManyToManyRelationMetadataProcessor extends AbstractEntityFieldProcessor implements\n        RelationMetadataProcessor\n{\n\n    /**\n     * Instantiates a new many to many relation metadata processor.\n     */\n    public ManyToManyRelationMetadataProcessor(KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n        validator = new EntityValidatorImpl();\n    }\n\n    @Override\n    public void addRelationIntoMetadata(Field relationField, EntityMetadata metadata)\n    {\n        ManyToMany m2mAnnotation = relationField.getAnnotation(ManyToMany.class);\n\n//        boolean isJoinedByFK = relationField.isAnnotationPresent(JoinColumn.class);\n        boolean isJoinedByTable = relationField.isAnnotationPresent(JoinTable.class);\n        boolean isJoinedByMap = false;\n        if (m2mAnnotation != null && relationField.getType().isAssignableFrom(Map.class))\n        {\n            isJoinedByMap = true;\n        }\n\n        Class<?> targetEntity = null;\n        Class<?> mapKeyClass = null;\n\n        if (!isJoinedByMap)\n        {\n\n            targetEntity = PropertyAccessorHelper.getGenericClass(relationField);\n        }\n        else\n        {\n            List<Class<?>> genericClasses = PropertyAccessorHelper.getGenericClasses(relationField);\n\n            if (!genericClasses.isEmpty() && genericClasses.size() == 2)\n            {\n                mapKeyClass = genericClasses.get(0);\n                targetEntity = genericClasses.get(1);\n            }\n\n            MapKeyClass mapKeyClassAnn = relationField.getAnnotation(MapKeyClass.class);\n\n            // Check for Map key class specified at annotation\n            if (mapKeyClass == null && mapKeyClassAnn != null && mapKeyClassAnn.value() != null\n                    && !mapKeyClassAnn.value().getSimpleName().equals(\"void\"))\n            {\n                mapKeyClass = mapKeyClassAnn.value();\n            }\n\n\n        }\n\n        // Check for target class specified at annotation\n        if (targetEntity == null && null != m2mAnnotation.targetEntity()\n                && !m2mAnnotation.targetEntity().getSimpleName().equals(\"void\"))\n        {\n            targetEntity = m2mAnnotation.targetEntity();\n        }\n        Relation relation = new Relation(relationField, targetEntity, relationField.getType(), m2mAnnotation.fetch(),\n                Arrays.asList(m2mAnnotation.cascade()), Boolean.TRUE, m2mAnnotation.mappedBy(),\n                Relation.ForeignKey.MANY_TO_MANY);\n\n\n\n        if (isJoinedByTable)\n        {\n            JoinTableMetadata jtMetadata = new JoinTableMetadata(relationField);\n\n            relation.setRelatedViaJoinTable(true);\n            relation.setJoinTableMetadata(jtMetadata);\n        }\n\n        if (isJoinedByMap)\n        {\n            relation.setMapKeyJoinClass(mapKeyClass);\n\n            MapKeyJoinColumn mapKeyJoinColumnAnn = relationField.getAnnotation(MapKeyJoinColumn.class);\n            if (mapKeyJoinColumnAnn != null)\n            {\n                String mapKeyJoinColumnName = mapKeyJoinColumnAnn.name();\n\n                    relation.setJoinColumnName(mapKeyJoinColumnName);\n\n            }\n\n        }\n\n\n        relation.setBiDirectionalField(metadata.getEntityClazz());\n        metadata.addRelation(relationField.getName(), relation);\n\n        // Set whether this entity has at least one Join table relation, if not\n        // already set\n        if (!metadata.isRelationViaJoinTable())\n        {\n            metadata.setRelationViaJoinTable(relation.isRelatedViaJoinTable());\n        }\n\n    }\n\n    @Override\n    public void process(Class<?> clazz, EntityMetadata metadata)\n    {\n        throw new MetamodelLoaderException(\"Method call not applicable for Relation processors\");\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/relation/ManyToOneRelationMetadataProcessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor.relation;\n\nimport java.lang.reflect.Field;\nimport java.util.Arrays;\n\nimport javax.persistence.AssociationOverride;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\n\nimport org.apache.commons.lang.StringUtils;\n\nimport com.impetus.kundera.loader.MetamodelLoaderException;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.processor.AbstractEntityFieldProcessor;\nimport com.impetus.kundera.metadata.validator.EntityValidatorImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * The Class ManyToOneRelationMetadataProcessor.\n * \n * @author Amresh Singh\n */\npublic class ManyToOneRelationMetadataProcessor extends AbstractEntityFieldProcessor implements\n        RelationMetadataProcessor\n{\n\n    /**\n     * Instantiates a new many to one relation metadata processor.\n     */\n    public ManyToOneRelationMetadataProcessor(KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n        validator = new EntityValidatorImpl();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.metadata.processor.relation.RelationMetadataProcessor\n     * #addRelationIntoMetadata(java.lang.reflect.Field,\n     * com.impetus.kundera.metadata.model.EntityMetadata)\n     */\n    @Override\n    public void addRelationIntoMetadata(Field relationField, EntityMetadata metadata)\n    {\n        // taking field's type as foreign entity, ignoring \"targetEntity\"\n        Class<?> targetEntity = relationField.getType();\n\n        ManyToOne ann = relationField.getAnnotation(ManyToOne.class);\n        Relation relation = new Relation(relationField, targetEntity, null, ann.fetch(), Arrays.asList(ann.cascade()),\n                ann.optional(), null, // mappedBy is null\n                Relation.ForeignKey.MANY_TO_ONE);\n\n        boolean isJoinedByFK = relationField.isAnnotationPresent(JoinColumn.class);\n\n        if (relationField.isAnnotationPresent(AssociationOverride.class))\n        {\n            AssociationOverride annotation = relationField.getAnnotation(AssociationOverride.class);\n            JoinColumn[] joinColumns = annotation.joinColumns();\n\n            relation.setJoinColumnName(joinColumns[0].name());\n\n        }\n        else if (isJoinedByFK)\n        {\n            JoinColumn joinColumnAnn = relationField.getAnnotation(JoinColumn.class);\n            relation.setJoinColumnName(StringUtils.isBlank(joinColumnAnn.name()) ? relationField.getName()\n                    : joinColumnAnn.name());\n        }\n        else\n        {\n            relation.setJoinColumnName(relationField.getName());\n        }\n\n        relation.setBiDirectionalField(metadata.getEntityClazz());\n        metadata.addRelation(relationField.getName(), relation);\n\n    }\n\n    @Override\n    public void process(Class<?> clazz, EntityMetadata metadata)\n    {\n        throw new MetamodelLoaderException(\"Method call not applicable for Relation processors\");\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/relation/OneToManyRelationMetadataProcessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor.relation;\n\nimport java.lang.reflect.Field;\nimport java.util.Arrays;\n\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\n\nimport org.apache.commons.lang.StringUtils;\n\nimport com.impetus.kundera.loader.MetamodelLoaderException;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.processor.AbstractEntityFieldProcessor;\nimport com.impetus.kundera.metadata.validator.EntityValidatorImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\n\n/**\n * The Class OneToManyRelationMetadataProcessor.\n * \n * @author Amresh Singh\n */\npublic class OneToManyRelationMetadataProcessor extends AbstractEntityFieldProcessor implements\n        RelationMetadataProcessor\n{\n\n    /**\n     * Instantiates a new one to many relation metadata processor.\n     */\n    public OneToManyRelationMetadataProcessor(KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n        validator = new EntityValidatorImpl();\n    }\n\n    @Override\n    public void process(Class<?> clazz, EntityMetadata metadata)\n    {\n        throw new MetamodelLoaderException(\"Method call not applicable for Relation processors\");\n    }\n\n    @Override\n    public void addRelationIntoMetadata(Field relationField, EntityMetadata metadata)\n    {\n        \n        OneToMany ann = relationField.getAnnotation(OneToMany.class);\n        Class<?> targetEntity = PropertyAccessorHelper.getGenericClass(relationField);\n\n        // now, check annotations\n        if (null != ann.targetEntity() && !ann.targetEntity().getSimpleName().equals(\"void\"))\n        {\n            targetEntity = ann.targetEntity();\n        }\n\n \n\n        Relation relation = new Relation(relationField, targetEntity, relationField.getType(), ann.fetch(),\n                Arrays.asList(ann.cascade()), Boolean.TRUE, ann.mappedBy(), Relation.ForeignKey.ONE_TO_MANY);\n\n        boolean isJoinedByFK = relationField.isAnnotationPresent(JoinColumn.class);\n     \n\n        if (isJoinedByFK)\n        {\n            JoinColumn joinColumnAnn = relationField.getAnnotation(JoinColumn.class);\n            relation.setJoinColumnName(StringUtils.isBlank(joinColumnAnn.name()) ? relationField.getName() : joinColumnAnn.name());\n        }\n\n        else\n        {        \n            String joinColumnName = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();\n            if (relation.getMappedBy() != null)\n            {\n                try\n                {\n                    Field mappedField = metadata.getEntityClazz().getDeclaredField(relation.getMappedBy());\n                    if (mappedField != null && mappedField.isAnnotationPresent(JoinColumn.class))\n                    {\n                        joinColumnName = mappedField.getAnnotation(JoinColumn.class).name();\n                    }\n                }\n                catch (NoSuchFieldException e)\n                {\n                    // do nothing, it means not a case of self association\n                }\n                catch (SecurityException e)\n                {\n                    // do nothing, it means not a case of self association\n                }\n            }\n            relation.setJoinColumnName(joinColumnName);\n        }\n        \n        relation.setBiDirectionalField(metadata.getEntityClazz());\n        metadata.addRelation(relationField.getName(), relation);\n        metadata.setParent(true);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/relation/OneToOneRelationMetadataProcessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor.relation;\n\nimport java.lang.reflect.Field;\nimport java.util.Arrays;\n\nimport javax.persistence.AssociationOverride;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\n\nimport com.impetus.kundera.loader.MetamodelLoaderException;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.processor.AbstractEntityFieldProcessor;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * The Class OneToOneRelationMetadataProcessor.\n * \n * @author Amresh Singh\n */\npublic class OneToOneRelationMetadataProcessor extends AbstractEntityFieldProcessor implements\n        RelationMetadataProcessor\n{\n\n    /**\n     * Instantiates a new one to one relation metadata processor.\n     */\n    public OneToOneRelationMetadataProcessor(KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    @Override\n    public void addRelationIntoMetadata(Field relationField, EntityMetadata metadata)\n    {\n        // taking field's type as foreign entity, ignoring \"targetEntity\"\n        Class<?> targetEntity = relationField.getType();\n\n        // TODO: Add code to check whether this entity has already been\n        // validated, at all places below\n\n        OneToOne oneToOneAnn = relationField.getAnnotation(OneToOne.class);\n\n        boolean isJoinedByPK = relationField.isAnnotationPresent(PrimaryKeyJoinColumn.class);\n        boolean isJoinedByFK = relationField.isAnnotationPresent(JoinColumn.class);\n\n        Relation relation = new Relation(relationField, targetEntity, null, oneToOneAnn.fetch(),\n                Arrays.asList(oneToOneAnn.cascade()), oneToOneAnn.optional(), oneToOneAnn.mappedBy(),\n                Relation.ForeignKey.ONE_TO_ONE);\n\n        if (relationField.isAnnotationPresent(AssociationOverride.class))\n        {\n            AssociationOverride annotation = relationField.getAnnotation(AssociationOverride.class);\n            JoinColumn[] joinColumns = annotation.joinColumns();\n            relation.setJoinColumnName(joinColumns[0].name());\n\n            JoinTable joinTable = annotation.joinTable();\n            onJoinTable(joinTable);\n        }\n        else if (isJoinedByPK)\n        {\n\n            relation.setJoinedByPrimaryKey(true);\n            EntityMetadata joinClassMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                    targetEntity.getClass());\n            relation.setJoinColumnName(joinClassMetadata != null ? ((AbstractAttribute) joinClassMetadata\n                    .getIdAttribute()).getJPAColumnName() : null);\n        }\n        else if (isJoinedByFK)\n        {\n            JoinColumn joinColumnAnn = relationField.getAnnotation(JoinColumn.class);\n            relation.setJoinColumnName(joinColumnAnn.name());\n        }\n\n        relation.setBiDirectionalField(metadata.getEntityClazz());\n        metadata.addRelation(relationField.getName(), relation);\n    }\n\n    private void onJoinTable(JoinTable joinTable)\n    {\n        if (joinTable != null)\n        {\n            throw new UnsupportedOperationException(\"@JoinTable not supported for many to one association\");\n        }\n    }\n\n    @Override\n    public void process(Class<?> clazz, EntityMetadata metadata)\n    {\n        throw new MetamodelLoaderException(\"Method call not applicable for Relation processors\");\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/relation/RelationMetadataProcessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor.relation;\n\nimport java.lang.reflect.Field;\n\nimport com.impetus.kundera.metadata.model.EntityMetadata;\n\n/**\n * The Interface RelationMetadataProcessor.\n * \n * @author Amresh Singh\n */\npublic interface RelationMetadataProcessor\n{\n\n    /**\n     * Adds the relation into metadata.\n     * \n     * @param relationField\n     *            the relation field\n     * @param metadata\n     *            the metadata\n     */\n    void addRelationIntoMetadata(Field relationField, EntityMetadata metadata);\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/processor/relation/RelationMetadataProcessorFactory.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor.relation;\n\nimport java.lang.reflect.Field;\n\nimport javax.persistence.ManyToMany;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.OneToMany;\nimport javax.persistence.OneToOne;\n\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * A factory for creating RelationMetadataProcessor objects.\n * \n * @author Amresh Singh\n */\npublic class RelationMetadataProcessorFactory\n{\n\n    /**\n     * Gets the relation metadata processor.\n     * \n     * @param relationField\n     *            the relation field\n     * @return the relation metadata processor\n     */\n    public static RelationMetadataProcessor getRelationMetadataProcessor(Field relationField, KunderaMetadata kunderaMetadata)\n    {\n        RelationMetadataProcessor relProcessor = null;\n\n        // OneToOne\n        if (relationField.isAnnotationPresent(OneToOne.class))\n        {\n            relProcessor = new OneToOneRelationMetadataProcessor(kunderaMetadata);\n        }\n\n        // OneToMany\n        else if (relationField.isAnnotationPresent(OneToMany.class))\n        {\n            relProcessor = new OneToManyRelationMetadataProcessor(kunderaMetadata);\n\n        }\n\n        // ManyToOne\n        else if (relationField.isAnnotationPresent(ManyToOne.class))\n        {\n            relProcessor = new ManyToOneRelationMetadataProcessor(kunderaMetadata);\n\n        }\n\n        // ManyToMany\n        else if (relationField.isAnnotationPresent(ManyToMany.class))\n        {\n            relProcessor = new ManyToManyRelationMetadataProcessor(kunderaMetadata);\n\n        }\n\n        return relProcessor;\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/validator/EntityValidator.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.validator;\r\n\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\n\r\n/**\r\n * Interface to validate an entity.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic interface EntityValidator\r\n{\r\n\r\n    /**\r\n     * Validate.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     */\r\n    void validate(Class<?> clazz);\r\n\r\n    /**\r\n     * Validate entity.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     * @param puProperties\r\n     */\r\n    void validateEntity(Class<?> clazz, final KunderaMetadata kunderaMetadata);\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/validator/EntityValidatorImpl.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.validator;\r\n\r\nimport java.lang.reflect.Field;\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.EmbeddedId;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.GeneratedValue;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.SequenceGenerator;\r\nimport javax.persistence.Table;\r\nimport javax.persistence.TableGenerator;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.client.ClientResolver;\r\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\r\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\n\r\n/**\r\n * Validates entity for JPA rules.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class EntityValidatorImpl implements EntityValidator\r\n{\r\n\r\n    /** The Constant log. */\r\n    private static final Logger log = LoggerFactory.getLogger(EntityValidatorImpl.class);\r\n\r\n    /** cache for validated classes. */\r\n    private List<Class<?>> classes = new ArrayList<Class<?>>();\r\n\r\n    private Map<String, Object> puProperties;\r\n\r\n    /**\r\n     * @param puPropertyMap\r\n     */\r\n    public EntityValidatorImpl(Map puPropertyMap)\r\n    {\r\n        this.puProperties = puPropertyMap;\r\n    }\r\n\r\n    /**\r\n     * @param externalPropertyMap\r\n     */\r\n    public EntityValidatorImpl()\r\n    {\r\n        this(null);\r\n    }\r\n\r\n    /**\r\n     * Checks the validity of a class for Cassandra entity.\r\n     * \r\n     * @param clazz\r\n     *            validates this class\r\n     * \r\n     * @return returns 'true' if valid\r\n     */\r\n    @Override\r\n    // TODO: reduce Cyclomatic complexity\r\n    public final void validate(final Class<?> clazz)\r\n    {\r\n\r\n        if (classes.contains(clazz))\r\n        {\r\n            return;\r\n        }\r\n\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"Validating \" + clazz.getName());\r\n\r\n        // Is Entity?\r\n//        if (clazz.isAnnotationPresent(MappedSuperclass.class))\r\n//        {\r\n//            throw new InvalidEntityDefinitionException(\"JPA operation over MappedSuperclass are not allowed\" + clazz);\r\n//        }\r\n        \r\n        \r\n        // Is Entity?\r\n        if (!clazz.isAnnotationPresent(Entity.class))\r\n        {\r\n            throw new InvalidEntityDefinitionException(clazz.getName() + \" is not annotated with @Entity.\");\r\n        }\r\n\r\n        \r\n        // TODO:: add validation for MappedSuperClass.\r\n        \r\n//        // Must be annotated with @Table\r\n//        if (!clazz.isAnnotationPresent(Table.class))\r\n//        {\r\n//            throw new InvalidEntityDefinitionException(clazz.getName() + \" must be annotated with @Table.\");\r\n//        }\r\n\r\n        // must have a default no-argument constructor\r\n        try\r\n        {\r\n            clazz.getConstructor();\r\n        }\r\n        catch (NoSuchMethodException nsme)\r\n        {\r\n            throw new InvalidEntityDefinitionException(clazz.getName()\r\n                    + \" must have a default no-argument constructor.\");\r\n        }\r\n\r\n        // Check for @Key and ensure that there is just 1 @Key field of String\r\n        // type.\r\n        List<Field> keys = new ArrayList<Field>();\r\n        for (Field field : clazz.getDeclaredFields())\r\n        {\r\n            if (field.isAnnotationPresent(Id.class) && field.isAnnotationPresent(EmbeddedId.class))\r\n            {\r\n                throw new InvalidEntityDefinitionException(clazz.getName()\r\n                        + \" must have either @Id field or @EmbeddedId field\");\r\n            }\r\n\r\n            if (field.isAnnotationPresent(Id.class))\r\n            {\r\n                keys.add(field);\r\n                // validate @GeneratedValue annotation if given\r\n                if (field.isAnnotationPresent(GeneratedValue.class))\r\n                {\r\n                    validateGeneratedValueAnnotation(clazz, field);\r\n                }\r\n            }\r\n            else if (field.isAnnotationPresent(EmbeddedId.class))\r\n            {\r\n                keys.add(field);\r\n            }\r\n        }\r\n\r\n        if (keys.size() < 0)\r\n        {\r\n            throw new InvalidEntityDefinitionException(clazz.getName() + \" must have an @Id field.\");\r\n        }\r\n        else if (keys.size() > 1)\r\n        {\r\n            throw new InvalidEntityDefinitionException(clazz.getName() + \" can only have 1 @Id field.\");\r\n        }\r\n\r\n        // save in cache\r\n\r\n        classes.add(clazz);\r\n    }\r\n\r\n    /**\r\n     * validate generated value annotation if given.\r\n     * \r\n     * @param clazz\r\n     * @param field\r\n     */\r\n    private void validateGeneratedValueAnnotation(final Class<?> clazz, Field field)\r\n    {\r\n        Table table = clazz.getAnnotation(Table.class);\r\n        // Still we need to validate for this after post metadata population.\r\n        if (table != null)\r\n        {\r\n            String schemaName = table.schema();\r\n            if (schemaName != null && schemaName.indexOf('@') > 0)\r\n            {\r\n                schemaName = schemaName.substring(0, schemaName.indexOf('@'));\r\n                GeneratedValue generatedValue = field.getAnnotation(GeneratedValue.class);\r\n                if (generatedValue != null && generatedValue.generator() != null\r\n                        && !generatedValue.generator().isEmpty())\r\n                {\r\n                    if (!(field.isAnnotationPresent(TableGenerator.class)\r\n                            || field.isAnnotationPresent(SequenceGenerator.class)\r\n                            || clazz.isAnnotationPresent(TableGenerator.class) || clazz\r\n                                .isAnnotationPresent(SequenceGenerator.class)))\r\n                    {\r\n                        log.error(\"Unknown Id.generator{}: for class{}\", generatedValue.generator(), clazz);\r\n                        throw new IllegalArgumentException(\"Unknown Id.generator: \" + generatedValue.generator());\r\n                    }\r\n                    else\r\n                    {\r\n                        checkForGenerator(clazz, field, generatedValue, schemaName);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Validate for generator.\r\n     * \r\n     * @param clazz\r\n     * @param field\r\n     * @param generatedValue\r\n     * @param schemaName\r\n     */\r\n    private void checkForGenerator(final Class<?> clazz, Field field, GeneratedValue generatedValue, String schemaName)\r\n    {\r\n        TableGenerator tableGenerator = field.getAnnotation(TableGenerator.class);\r\n        SequenceGenerator sequenceGenerator = field.getAnnotation(SequenceGenerator.class);\r\n        if (tableGenerator == null || !tableGenerator.name().equals(generatedValue.generator()))\r\n        {\r\n            tableGenerator = clazz.getAnnotation(TableGenerator.class);\r\n        }\r\n        if (sequenceGenerator == null || !sequenceGenerator.name().equals(generatedValue.generator()))\r\n        {\r\n            sequenceGenerator = clazz.getAnnotation(SequenceGenerator.class);\r\n        }\r\n\r\n        if ((tableGenerator == null && sequenceGenerator == null)\r\n                || (tableGenerator != null && !tableGenerator.name().equals(generatedValue.generator()))\r\n                || (sequenceGenerator != null && !sequenceGenerator.name().equals(generatedValue.generator())))\r\n        {\r\n            throw new IllegalArgumentException(\"Unknown Id.generator: \" + generatedValue.generator());\r\n        }\r\n        else if ((tableGenerator != null && !tableGenerator.schema().isEmpty() && !tableGenerator.schema().equals(\r\n                schemaName))\r\n                || (sequenceGenerator != null && !sequenceGenerator.schema().isEmpty() && !sequenceGenerator.schema()\r\n                        .equals(schemaName)))\r\n        {\r\n            throw new InvalidEntityDefinitionException(\"Generator \" + generatedValue.generator() + \" in entity : \"\r\n                    + clazz.getName() + \" has different schema name ,it should be same as entity have\");\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void validateEntity(Class<?> clazz, final KunderaMetadata kunderaMetadata)\r\n    {\r\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\r\n        if (metadata != null)\r\n        {\r\n            SchemaManager schemaManager = ClientResolver.getClientFactory(metadata.getPersistenceUnit())\r\n                    .getSchemaManager(puProperties);\r\n            if (schemaManager != null && !schemaManager.validateEntity(clazz))\r\n            {\r\n                log.warn(\"Validation for : \" + clazz + \" failed , any operation on this class will result in fail.\");\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/validator/InvalidEntityDefinitionException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.validator;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * @author amresh\n * \n */\npublic class InvalidEntityDefinitionException extends KunderaException\n{\n\n    /**\n     * \n     */\n    private static final long serialVersionUID = 944429642343486327L;\n\n    /**\n     * \n     */\n    public InvalidEntityDefinitionException()\n    {\n\n    }\n\n    /**\n     * @param paramString\n     */\n    public InvalidEntityDefinitionException(String paramString)\n    {\n        super(paramString);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/AbstractEntityReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.FetchType;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.Relation.ForeignKey;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.context.PersistenceCacheManager;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.proxy.ProxyHelper;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class AbstractEntityReader.\n * \n * @author vivek.mishra\n */\npublic class AbstractEntityReader\n{\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(AbstractEntityReader.class);\n\n    private AssociationBuilder associationBuilder;\n\n    protected KunderaQuery kunderaQuery;\n\n    protected KunderaMetadata kunderaMetadata;\n\n    public AbstractEntityReader(final KunderaMetadata kunderaMetadata)\n    {\n        this.kunderaMetadata = kunderaMetadata;\n    }\n\n    /**\n     * Retrieves an entity from ID\n     * \n     * @param primaryKey\n     * @param m\n     * @param client\n     * @return\n     */\n    protected EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        try\n        {\n            Object o = client.find(m.getEntityClazz(), primaryKey);\n\n            if (o == null)\n            {\n                // No entity found\n                return null;\n            }\n            else\n            {\n                return o instanceof EnhanceEntity ? (EnhanceEntity) o : new EnhanceEntity(o, getId(o, m), null);\n            }\n        }\n        catch (Exception e)\n        {\n            throw new EntityReaderException(e);\n        }\n    }\n\n    /**\n     * Recursively fetches associated entities for a given <code>entity</code>\n     * \n     * @param entity\n     * @param relationsMap\n     * @param client\n     * @param m\n     * @param pd\n     * @param relationStack\n     * @return\n     */\n    private Object handleAssociation(final Object entity, final Map<String, Object> relationsMap,\n            final EntityMetadata m, final PersistenceDelegator pd, boolean lazilyloaded,\n            Map<Object, Object> relationStack)\n    {\n\n        for (Relation relation : m.getRelations())\n        {\n            if (relation != null)\n            {\n                ForeignKey relationType = relation.getType();\n\n                Object relationalObject = PropertyAccessorHelper.getObject(entity, relation.getProperty());\n\n                if (KunderaCoreUtils.isEmptyOrNull(relationalObject)\n                        || ProxyHelper.isProxyOrCollection(relationalObject))\n                {\n                    onRelation(entity, relationsMap, m, pd, relation, relationType, lazilyloaded, relationStack);\n                } // a bit of hack for neo4j only\n                else if (!ProxyHelper.isProxyOrCollection(relationalObject)\n                        && Map.class.isAssignableFrom(relationalObject.getClass()))\n                {\n                    Map relationalMap = (Map) relationalObject;\n                    for (Map.Entry entry : (Set<Map.Entry>) relationalMap.entrySet())\n                    {\n                        Object entityObject = entry.getValue();\n                        if (entityObject != null)\n                        {\n                            EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                                    entityObject.getClass());\n                            PersistenceCacheManager.addEntityToPersistenceCache(entityObject, pd,\n                                    PropertyAccessorHelper.getId(entityObject, metadata));\n                        }\n                    }\n                }\n            }\n        }\n        return entity;\n    }\n\n    /**\n     * Parse over each relation of fetched entity.\n     * \n     * @param entity\n     * @param relationsMap\n     * @param m\n     * @param pd\n     * @param relation\n     * @param relationType\n     * @param lazilyloaded\n     * @param relationStack\n     */\n    private void onRelation(final Object entity, final Map<String, Object> relationsMap, final EntityMetadata m,\n            final PersistenceDelegator pd, Relation relation, ForeignKey relationType, boolean lazilyloaded,\n            Map<Object, Object> relationStack)\n    {\n\n        FetchType fetchType = relation.getFetchType();\n\n        if (!lazilyloaded && fetchType.equals(FetchType.LAZY))\n        {\n            final Object entityId = PropertyAccessorHelper.getId(entity, m);\n            getAssociationBuilder().setProxyRelationObject(entity, relationsMap, m, pd, entityId, relation);\n        }\n        else\n        {\n            if (relation.getType().equals(ForeignKey.MANY_TO_MANY))\n            {\n                // First, Save this entity to persistence cache\n                Field f = relation.getProperty();\n                Object object = PropertyAccessorHelper.getObject(entity, f);\n                final Object entityId = PropertyAccessorHelper.getId(entity, m);\n                PersistenceCacheManager.addEntityToPersistenceCache(entity, pd, entityId);\n                getAssociationBuilder().populateRelationForM2M(entity, m, pd, relation, object, relationsMap);\n            }\n            else\n            {\n                onRelation(entity, relationsMap, relation, m, pd, lazilyloaded, relationStack);\n            }\n        }\n    }\n\n    /**\n     * Method to handle one to one association relation events.\n     * \n     * @param entity\n     *            relation owning entity.\n     * @param entityId\n     *            entity id of relation owning entity.\n     * @param relationsMap\n     *            contains relation name and it's value.\n     * @param relationStack\n     * @param m\n     *            entity metadata.\n     */\n    private void onRelation(Object entity, Map<String, Object> relationsMap, final Relation relation,\n            final EntityMetadata metadata, final PersistenceDelegator pd, boolean lazilyloaded,\n            Map<Object, Object> relationStack)\n    {\n        final Object entityId = PropertyAccessorHelper.getId(entity, metadata);\n\n        // if relation map contains value, then invoke target entity with find\n        // by id.\n        // else invoke target entity for find by relation, pass it's entityId as\n        // a column value and relation.getJoinColumnName as column name.\n\n        Object relationValue = relationsMap != null ? relationsMap.get(relation.getJoinColumnName(kunderaMetadata))\n                : null;\n        EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                relation.getTargetEntity());\n\n        List relationalEntities = fetchRelations(relation, metadata, pd, entityId, relationValue, targetEntityMetadata);\n\n        if (relationalEntities != null)\n        {\n\n            for (Object relationEntity : relationalEntities)\n            {\n                if (relationEntity != null)\n                {\n                    addToRelationStack(relationStack, relationEntity, targetEntityMetadata);\n                }\n            }\n            for (Object relationEntity : relationalEntities)\n            {\n                if (relationEntity != null)\n                {\n                    onParseRelation(entity, pd, targetEntityMetadata, relationEntity, relation, lazilyloaded,\n                            relationStack);\n                    PersistenceCacheManager.addEntityToPersistenceCache(getEntity(relationEntity), pd,\n                            PropertyAccessorHelper.getId(relationEntity, targetEntityMetadata));\n                }\n            }\n        }\n\n    }\n\n    /**\n     * Invokes parseRelations for relation entity and set relational entity\n     * within entity\n     * \n     * @param entity\n     * @param pd\n     * @param targetEntityMetadata\n     * @param relationEntity\n     * @param relation\n     * @param lazilyloaded\n     * @param relationStack\n     */\n    private void onParseRelation(Object entity, final PersistenceDelegator pd, EntityMetadata targetEntityMetadata,\n            Object relationEntity, Relation relation, boolean lazilyloaded, Map<Object, Object> relationStack)\n    {\n        parseRelations(entity, getEntity(relationEntity), getPersistedRelations(relationEntity), pd,\n                targetEntityMetadata, lazilyloaded, relationStack);\n\n        // if relation ship is unary, no problem else we need to add\n        setRelationToEntity(entity, relationEntity, relation);\n    }\n\n    /**\n     * After successfully parsing set relational entity object within entity\n     * object.\n     * \n     * @param entity\n     * @param relationEntity\n     * @param relation\n     */\n    private void setRelationToEntity(Object entity, Object relationEntity, Relation relation)\n    {\n        if (relation.getTargetEntity().isAssignableFrom(getEntity(relationEntity).getClass()))\n        {\n\n            if (relation.isUnary())\n            {\n                PropertyAccessorHelper.set(entity, relation.getProperty(), getEntity(relationEntity));\n            }\n            else\n            {\n                Object associationObject = PropertyAccessorHelper.getObject(entity, relation.getProperty());\n                if (associationObject == null || ProxyHelper.isProxyOrCollection(associationObject))\n                {\n                    associationObject = PropertyAccessorHelper.getCollectionInstance(relation.getProperty());\n                    PropertyAccessorHelper.set(entity, relation.getProperty(), associationObject);\n                }\n\n                ((Collection) associationObject).add(getEntity(relationEntity));\n            }\n        }\n    }\n\n    /**\n     * Parse relations of provided relationEntity.\n     * \n     * @param originalEntity\n     * @param relationEntity\n     * @param relationsMap\n     * @param pd\n     * @param metadata\n     * @param lazilyloaded\n     * @param relationStack\n     */\n    private void parseRelations(final Object originalEntity, final Object relationEntity,\n            final Map<String, Object> relationsMap, final PersistenceDelegator pd, final EntityMetadata metadata,\n            boolean lazilyloaded, Map<Object, Object> relationStack)\n    {\n\n        for (Relation relation : metadata.getRelations())\n        {\n            if (relation != null)\n            {\n                FetchType fetchType = relation.getFetchType();\n\n                if (!lazilyloaded && fetchType.equals(FetchType.LAZY))\n                {\n                    final Object entityId = PropertyAccessorHelper.getId(relationEntity, metadata);\n                    getAssociationBuilder().setProxyRelationObject(relationEntity, relationsMap, metadata, pd,\n                            entityId, relation);\n                }\n                else\n                {\n\n                    if (relation.isUnary() && relation.getTargetEntity().isAssignableFrom(originalEntity.getClass()))\n                    {\n                        Object associationObject = PropertyAccessorHelper.getObject(relationEntity,\n                                relation.getProperty());\n                        if (relation.getType().equals(ForeignKey.ONE_TO_ONE))\n                        {\n                            if ((associationObject == null || ProxyHelper.isProxyOrCollection(associationObject)))\n                            {\n                                PropertyAccessorHelper.set(relationEntity, relation.getProperty(), originalEntity);\n                            }\n                        }\n                        else if (relationsMap != null\n                                && relationsMap.containsKey(relation.getJoinColumnName(kunderaMetadata)))\n                        {\n                            PropertyAccessorHelper.set(relationEntity, relation.getProperty(), originalEntity);\n                        }\n                    }\n                    else\n                    {\n                        // Here\n                        // onRelation(relationEntity, relationsMap, metadata,\n                        // pd,\n                        // relation, relationType);\n                        final Object entityId = PropertyAccessorHelper.getId(relationEntity, metadata);\n                        Object relationValue = relationsMap != null ? relationsMap.get(relation\n                                .getJoinColumnName(kunderaMetadata)) : null;\n                        final EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(\n                                kunderaMetadata, relation.getTargetEntity());\n                        List immediateRelations = fetchRelations(relation, metadata, pd, entityId, relationValue,\n                                targetEntityMetadata);\n                        // Here in case of one-to-many/many-to-one we should\n                        // skip\n                        // this\n                        // relation as it\n                        if (immediateRelations != null && !immediateRelations.isEmpty())\n                        {\n                            for (Object immediateRelation : immediateRelations)\n                            {\n                                if (immediateRelation != null )\n                                {\n                                    if (existsInRelationStack(relationStack, immediateRelation, targetEntityMetadata))\n                                    {\n                                        setRelationToEntity(\n                                                relationEntity,\n                                                fetchFromRelationStack(relationStack, immediateRelation,\n                                                        targetEntityMetadata), relation);\n\n                                    }\n                                    else\n                                    {\n                                        addToRelationStack(relationStack, immediateRelation, targetEntityMetadata);\n                                        onParseRelation(relationEntity, pd, targetEntityMetadata, immediateRelation,\n                                                relation, lazilyloaded, relationStack);\n                                      \n\n                                    }\n                                    PersistenceCacheManager.addEntityToPersistenceCache(getEntity(relationEntity), pd,\n                                            PropertyAccessorHelper.getId(relationEntity, metadata));\n                                }\n                            }\n\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    // Adds an object to the stack for referring\n    /**\n     * @param relationStack\n     * @param entity\n     * @param m\n     */\n    private void addToRelationStack(Map<Object, Object> relationStack, Object entity, EntityMetadata m)\n    {\n        Object obj = entity;\n        if (entity instanceof EnhanceEntity)\n        {\n            obj = ((EnhanceEntity) entity).getEntity();\n        }\n        relationStack.put(obj.getClass().getCanonicalName() + \"#\" + PropertyAccessorHelper.getId(obj, m), obj);\n\n    }\n\n    // Checks whether the object already exists in stack\n    /**\n     * @param relationStack\n     * @param entity\n     * @param m\n     * @return\n     */\n    private Boolean existsInRelationStack(Map<Object, Object> relationStack, Object entity, EntityMetadata m)\n    {\n        Object obj = entity;\n        if (entity instanceof EnhanceEntity)\n        {\n            obj = ((EnhanceEntity) entity).getEntity();\n        }\n        return relationStack\n                .containsKey(obj.getClass().getCanonicalName() + \"#\" + PropertyAccessorHelper.getId(obj, m));\n    }\n\n    // Fetches the object from stack\n    /**\n     * @param relationStack\n     * @param entity\n     * @param m\n     * @return\n     */\n    private Object fetchFromRelationStack(Map<Object, Object> relationStack, Object entity, EntityMetadata m)\n    {\n        Object obj = entity;\n        if (entity instanceof EnhanceEntity)\n        {\n            obj = ((EnhanceEntity) entity).getEntity();\n        }\n        return relationStack.get(obj.getClass().getCanonicalName() + \"#\" + PropertyAccessorHelper.getId(obj, m));\n    }\n\n    /**\n     * \n     * Based on relation type, method invokes database to fetch relation\n     * entities.\n     * \n     * @param relation\n     *            relation\n     * @param metadata\n     *            entity metadata\n     * @param pd\n     *            persistence delegator\n     * @param entityId\n     *            entity id\n     * @param relationValue\n     *            relational value\n     * @param targetEntityMetadata\n     *            relational entity's metadata.\n     * \n     * @return list of fetched relations.\n     */\n    private List fetchRelations(final Relation relation, final EntityMetadata metadata, final PersistenceDelegator pd,\n            final Object entityId, Object relationValue, EntityMetadata targetEntityMetadata)\n    {\n        List relationalEntities = new ArrayList();\n\n        if ((relationValue != null && relation.isUnary()) || (relation.isJoinedByPrimaryKey()))\n        {\n            // Call it\n            Object relationEntity = pd.getClient(targetEntityMetadata).find(relation.getTargetEntity(),\n                    relationValue != null ? relationValue : entityId);\n            if (relationEntity != null)\n            {\n                relationalEntities.add(relationEntity);\n            }\n        }\n        else if (!relation.isUnary())\n        {\n            // Now these entities may be enhance entities and may not be as\n            // well.\n            Client associatedClient = pd.getClient(targetEntityMetadata);\n\n            if (!MetadataUtils.useSecondryIndex(((ClientBase) associatedClient).getClientMetadata())\n                    && MetadataUtils.indexSearchEnabled(targetEntityMetadata.getPersistenceUnit(), kunderaMetadata))\n            {\n\n                relationalEntities = getAssociationBuilder().getAssociatedEntitiesFromIndex(\n                        relation.getProperty().getDeclaringClass(), entityId, targetEntityMetadata.getEntityClazz(),\n                        associatedClient);\n            }\n            else\n            {\n                relationalEntities = associatedClient.findByRelation(relation.getJoinColumnName(kunderaMetadata),\n                        entityId, relation.getTargetEntity());\n            }\n        }\n        return relationalEntities;\n    }\n\n    /**\n     * Recursively fetches associated entities for a given <code>entity</code>\n     * \n     * @param entity\n     * @param relationsMap\n     * @param client\n     * @param m\n     * @param pd\n     * @return\n     */\n    public Object recursivelyFindEntities(Object entity, Map<String, Object> relationsMap, EntityMetadata m,\n            PersistenceDelegator pd, boolean lazilyLoaded, Map<Object, Object> relationStack)\n    {\n        return handleAssociation(entity, relationsMap, m, pd, lazilyLoaded, relationStack);\n\n    }\n\n    /**\n     * Returns wrapped relations.\n     * \n     * @param relationEntity\n     * @return\n     */\n    private Map<String, Object> getPersistedRelations(Object relationEntity)\n    {\n        return relationEntity != null && relationEntity.getClass().isAssignableFrom(EnhanceEntity.class) ? ((EnhanceEntity) relationEntity)\n                .getRelations() : null;\n    }\n\n    /**\n     * Returns wrapped entity.\n     * \n     * @param relationEntity\n     * @return\n     */\n    private Object getEntity(Object relationEntity)\n    {\n        return relationEntity != null && relationEntity.getClass().isAssignableFrom(EnhanceEntity.class) ? ((EnhanceEntity) relationEntity)\n                .getEntity() : relationEntity;\n    }\n\n    /**\n     * On association using lucene.\n     * \n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @param ls\n     *            the ls\n     * @return the list\n     */\n    protected List<EnhanceEntity> onAssociationUsingLucene(EntityMetadata m, Client client, List<EnhanceEntity> ls)\n    {\n        Set<String> rSet = fetchDataFromLucene(m.getEntityClazz(), client);\n        List resultList = client.findAll(m.getEntityClazz(), null, rSet.toArray(new String[] {}));\n        return m.getRelationNames() != null && !m.getRelationNames().isEmpty() ? resultList : transform(m, ls,\n                resultList);\n    }\n\n    /**\n     * Transform.\n     * \n     * @param m\n     *            the m\n     * @param ls\n     *            the ls\n     * @param resultList\n     *            the result list\n     * @return the list\n     */\n    protected List<EnhanceEntity> transform(EntityMetadata m, List<EnhanceEntity> ls, List resultList)\n    {\n        if ((ls == null || ls.isEmpty()) && resultList != null && !resultList.isEmpty())\n        {\n            ls = new ArrayList<EnhanceEntity>(resultList.size());\n        }\n        for (Object r : resultList)\n        {\n            if (r != null && !r.getClass().isAssignableFrom(EnhanceEntity.class))\n            {\n                EnhanceEntity e = new EnhanceEntity(r, getId(r, m), null);\n                ls.add(e);\n            }\n        }\n        return ls;\n    }\n\n    /**\n     * Fetch data from lucene.\n     * \n     * @param client\n     *            the client\n     * @return the sets the\n     */\n    protected Set<String> fetchDataFromLucene(Class<?> clazz, Client client)\n    {\n        // use lucene to query and get Pk's only.\n        // go to client and get relation with values.!\n        // populate EnhanceEntity\n\n        /** The lucene query from jpa query. */\n        String luceneQueryFromJPAQuery = KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata);\n\n        Map<String, Object> results = client.getIndexManager().search(clazz, luceneQueryFromJPAQuery);\n        Set rSet = new HashSet(results.values());\n        return rSet;\n    }\n\n    /**\n     * Gets the id.\n     * \n     * @param entity\n     *            the entity\n     * @param metadata\n     *            the metadata\n     * @return the id\n     */\n    protected Object getId(Object entity, EntityMetadata metadata)\n    {\n        try\n        {\n            return PropertyAccessorHelper.getId(entity, metadata);\n        }\n        catch (PropertyAccessException e)\n        {\n            log.error(\"Error while Getting ID for entity {}, Caused by: {}.\", entity, e);\n            throw new EntityReaderException(\"Error while Getting ID for entity \" + entity, e);\n        }\n\n    }\n\n    /**\n     * Compares original with relational entity.\n     * \n     * @param relationalEntity\n     * @param originalEntity\n     * @return\n     */\n    private boolean compareTo(Object relationalEntity, Object originalEntity)\n    {\n        if (relationalEntity != null && originalEntity != null\n                && relationalEntity.getClass().isAssignableFrom(originalEntity.getClass()))\n        {\n            EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                    originalEntity.getClass());\n\n            Object relationalEntityId = PropertyAccessorHelper.getId(relationalEntity, metadata);\n            Object originalEntityId = PropertyAccessorHelper.getId(originalEntity, metadata);\n\n            return relationalEntityId.equals(originalEntityId);\n        }\n\n        return false;\n    }\n\n    /**\n     * Returns association builder instance.\n     * \n     * @return association builder\n     */\n    private AssociationBuilder getAssociationBuilder()\n    {\n        if (this.associationBuilder == null)\n        {\n            this.associationBuilder = new AssociationBuilder();\n        }\n\n        return this.associationBuilder;\n\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/AbstractExpression.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.util.Collection;\nimport java.util.List;\n\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Predicate;\nimport javax.persistence.criteria.Selection;\n\n/**\n * The Class AbstractExpression.\n * \n * @param <T>\n *            the generic type\n * @author: karthikp.manchala\n */\npublic class AbstractExpression<T> implements Expression<T>\n{\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.Selection#alias(java.lang.String)\n     */\n    @Override\n    public Selection<T> alias(String name)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.Selection#isCompoundSelection()\n     */\n    @Override\n    public boolean isCompoundSelection()\n    {\n        // TODO Auto-generated method stub\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.Selection#getCompoundSelectionItems()\n     */\n    @Override\n    public List<Selection<?>> getCompoundSelectionItems()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TupleElement#getJavaType()\n     */\n    @Override\n    public Class<? extends T> getJavaType()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TupleElement#getAlias()\n     */\n    @Override\n    public String getAlias()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.Expression#isNull()\n     */\n    @Override\n    public Predicate isNull()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.Expression#isNotNull()\n     */\n    @Override\n    public Predicate isNotNull()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.Expression#in(java.lang.Object[])\n     */\n    @Override\n    public Predicate in(Object... values)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.Expression#in(javax.persistence.criteria.\n     * Expression[])\n     */\n    @Override\n    public Predicate in(Expression<?>... values)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.Expression#in(java.util.Collection)\n     */\n    @Override\n    public Predicate in(Collection<?> values)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.Expression#in(javax.persistence.criteria.\n     * Expression)\n     */\n    @Override\n    public Predicate in(Expression<Collection<?>> values)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.Expression#as(java.lang.Class)\n     */\n    @Override\n    public <X> Expression<X> as(Class<X> type)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/AbstractPredicate.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.List;\n\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Predicate;\nimport javax.persistence.criteria.Selection;\n\n/**\n * Abstract super class for {@link Predicate}\n *  \n * @author vivek.mishra\n *\n */\nabstract class AbstractPredicate implements Predicate\n{\n\n\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Predicate#getOperator()\n     */\n    @Override\n    public BooleanOperator getOperator()\n    {\n        return BooleanOperator.AND;\n    }\n\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Expression#isNull()\n     */\n    @Override\n    public Predicate isNull()\n    {\n        throw new UnsupportedOperationException(\"Method isNull() not yet supported\");\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Expression#isNotNull()\n     */\n    @Override\n    public Predicate isNotNull()\n    {\n        throw new UnsupportedOperationException(\"Method isNotNull() not yet supported\");\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Expression#in(java.lang.Object[])\n     */\n    @Override\n    public Predicate in(Object... paramArrayOfObject)\n    {\n        throw new UnsupportedOperationException(\"Method in(Object... paramArrayOfObject) not yet supported\");\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Expression#in(javax.persistence.criteria.Expression<?>[])\n     */\n    @Override\n    public Predicate in(Expression<?>... paramArrayOfExpression)\n    {\n        // TODO Auto-generated method stub\n        throw new UnsupportedOperationException(\"Method in(Expression<?>... paramArrayOfExpression) not yet supported\");\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Expression#in(java.util.Collection)\n     */\n    @Override\n    public Predicate in(Collection<?> paramCollection)\n    {\n        throw new UnsupportedOperationException(\"Method in(Collection<?> paramCollection) not yet supported\");\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Expression#in(javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate in(Expression<Collection<?>> paramExpression)\n    {\n        throw new UnsupportedOperationException(\"Method in(Expression<Collection<?>> paramExpression) not yet supported\");\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Expression#as(java.lang.Class)\n     */\n    @Override\n    public <X> Expression<X> as(Class<X> paramClass)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Selection#alias(java.lang.String)\n     */\n    @Override\n    public Selection<Boolean> alias(String paramString)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Selection#isCompoundSelection()\n     */\n    @Override\n    public boolean isCompoundSelection()\n    {\n        return false;\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Selection#getCompoundSelectionItems()\n     */\n    @Override\n    public List<Selection<?>> getCompoundSelectionItems()\n    {\n        return Collections.emptyList();\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.TupleElement#getJavaType()\n     */\n    @Override\n    public Class<? extends Boolean> getJavaType()\n    {\n        return null;\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.TupleElement#getAlias()\n     */\n    @Override\n    public String getAlias()\n    {\n        return null;\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Predicate#isNegated()\n     */\n    @Override\n    public boolean isNegated()\n    {\n        throw new UnsupportedOperationException(\"Method isNegated() not yet supported\");\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Predicate#not()\n     */\n    @Override\n    public Predicate not()\n    {\n        throw new UnsupportedOperationException(\"Method not() not yet supported\");\n    }\n\n    \n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Predicate#getExpressions()\n     */\n    @Override\n    public List<Expression<Boolean>> getExpressions()\n    {\n        return java.util.Collections.emptyList();\n    }\n\n\n    public static enum ConditionalOperator\n    {\n        EQ, NEQ, LT, LTE, GT, GTE, BTW;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/AggregateExpression.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport javax.persistence.criteria.Expression;\n\n/**\n * The Class AggregateExpression.\n * \n * @author: karthikp.manchala\n */\npublic class AggregateExpression extends AbstractExpression<Long>\n{\n\n    /** The expression. */\n    private Expression<?> expression;\n\n    /** The aggregation. */\n    private String aggregation;\n\n    /**\n     * Instantiates a new aggregate expression.\n     * \n     * @param expression\n     *            the expression\n     * @param aggregation\n     *            the aggregation\n     */\n    public AggregateExpression(Expression<?> expression, String aggregation)\n    {\n        this.expression = expression;\n        this.aggregation = aggregation;\n    }\n\n    /**\n     * Gets the expression.\n     * \n     * @return the expression\n     */\n    public Expression<?> getExpression()\n    {\n        return expression;\n    }\n\n    /**\n     * Sets the expression.\n     * \n     * @param expression\n     *            the new expression\n     */\n    public void setExpression(Expression<?> expression)\n    {\n        this.expression = expression;\n    }\n\n    /**\n     * Gets the aggregation.\n     * \n     * @return the aggregation\n     */\n    public String getAggregation()\n    {\n        return aggregation;\n    }\n\n    /**\n     * Sets the aggregation.\n     * \n     * @param aggregation\n     *            the new aggregation\n     */\n    public void setAggregation(String aggregation)\n    {\n        this.aggregation = aggregation;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/AssociationBuilder.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.JoinTableMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.Relation.ForeignKey;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.context.PersistenceCacheManager;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.proxy.KunderaProxy;\nimport com.impetus.kundera.proxy.ProxyHelper;\nimport com.impetus.kundera.proxy.collection.ProxyCollection;\nimport com.impetus.kundera.proxy.collection.ProxyList;\nimport com.impetus.kundera.proxy.collection.ProxyMap;\nimport com.impetus.kundera.proxy.collection.ProxySet;\nimport com.impetus.kundera.utils.ObjectUtils;\n\n/**\n * This class is responsible for building association for given entities.\n * \n * @author vivek.mishra\n */\npublic final class AssociationBuilder\n{\n\n    private static Logger log = LoggerFactory.getLogger(AssociationBuilder.class);\n\n    /**\n     * Retrieves associated entities from secondary index. There are two\n     * alternatives here:\n     * \n     * 1. Via running Lucene query into Lucene powered secondary index. 2.\n     * Searching into a secondary index by custom secondary index class provided\n     * by user.\n     * \n     * @see PersistenceProperties#KUNDERA_INDEX_HOME_DIR\n     * @see PersistenceProperties#KUNDERA_INDEXER_CLASS\n     * \n     *      TODO: Which secondary index to use should be transparent. All we\n     *      should bother about is indexer.index(), indexer.search() etc.\n     */\n    List getAssociatedEntitiesFromIndex(Class owningClazz, Object entityId, Class<?> childClass, Client childClient)\n    {\n        List associatedEntities;\n        IndexManager indexManager = childClient.getIndexManager();\n\n        Map<String, Object> results = indexManager != null ? indexManager.search(owningClazz, childClass, entityId)\n                : new HashMap<String, Object>();\n        Set rsSet = results != null ? new HashSet(results.values()) : new HashSet();\n\n        if (childClass.equals(owningClazz))\n        {\n            associatedEntities = (List<Object>) childClient.findAll(childClass, null, rsSet.toArray(new Object[] {}));\n        }\n        else\n        {\n            associatedEntities = (List<Object>) childClient.findAll(childClass, null, rsSet.toArray(new Object[] {}));\n        }\n        return associatedEntities;\n    }\n\n    /**\n     * Populates entities related via join table for <code>entity</code>\n     * \n     * @param entity\n     * @param entityMetadata\n     * @param delegator\n     * @param relation\n     */\n    void populateRelationForM2M(Object entity, EntityMetadata entityMetadata, PersistenceDelegator delegator,\n            Relation relation, Object relObject, Map<String, Object> relationsMap)\n    {\n        // For M-M relationship of Collection type, relationship entities are\n        // always fetched from Join Table.\n        if (relation.getPropertyType().isAssignableFrom(List.class)\n                || relation.getPropertyType().isAssignableFrom(Set.class))\n        {\n            if (relation.isRelatedViaJoinTable() && (relObject == null || ProxyHelper.isProxyOrCollection(relObject)))\n            {\n                populateCollectionFromJoinTable(entity, entityMetadata, delegator, relation);\n            }\n\n        }\n        else if (relation.getPropertyType().isAssignableFrom(Map.class))\n        {\n            if (relation.isRelatedViaJoinTable())\n            {\n                // TODO: Implement Map relationships via Join Table (not\n                // supported as of now)\n            }\n            else\n            {\n                populateCollectionFromMap(entity, delegator, relation, relObject, relationsMap);\n            }\n        }\n    }\n\n    /**\n     * Populates a relationship of type {@link Collection} (i.e. those of type\n     * {@link Set} or {@link List})\n     */\n    private void populateCollectionFromJoinTable(Object entity, EntityMetadata entityMetadata,\n            PersistenceDelegator delegator, Relation relation)\n    {\n        JoinTableMetadata jtMetadata = relation.getJoinTableMetadata();\n        Client pClient = delegator.getClient(entityMetadata);\n\n        String schema = entityMetadata.getSchema();\n\n        EntityMetadata owningEntityMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),\n                relation.getTargetEntity());\n        Class columnJavaType = owningEntityMetadata.getIdAttribute().getJavaType();\n        if (jtMetadata == null)\n        {\n            columnJavaType = entityMetadata.getIdAttribute().getJavaType();\n            Relation owningEntityMetadataRelation = owningEntityMetadata.getRelation(relation.getMappedBy());\n            jtMetadata = owningEntityMetadataRelation.getJoinTableMetadata();\n            pClient = delegator.getClient(owningEntityMetadata);\n            schema = owningEntityMetadata.getSchema();\n        }\n\n        String joinTableName = jtMetadata.getJoinTableName();\n\n        Set<String> joinColumns = jtMetadata.getJoinColumns();\n        Set<String> inverseJoinColumns = jtMetadata.getInverseJoinColumns();\n\n        String joinColumnName = (String) joinColumns.toArray()[0];\n        String inverseJoinColumnName = (String) inverseJoinColumns.toArray()[0];\n\n        Object entityId = PropertyAccessorHelper.getId(entity, entityMetadata);\n        List<?> foreignKeys = pClient.getColumnsById(schema, joinTableName, joinColumnName, inverseJoinColumnName,\n                entityId, columnJavaType);\n\n        List childrenEntities = new ArrayList();\n\n        if (foreignKeys != null)\n        {\n            for (Object foreignKey : foreignKeys)\n            {\n                EntityMetadata childMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),\n                        relation.getTargetEntity());\n\n                Object child = delegator.find(relation.getTargetEntity(), foreignKey);\n                Object obj = child instanceof EnhanceEntity && child != null ? ((EnhanceEntity) child).getEntity()\n                        : child;\n\n                // If child has any bidirectional relationship, process them\n                // here\n                Field biDirectionalField = relation.getBiDirectionalField();\n                boolean isBidirectionalRelation = (biDirectionalField != null);\n\n                if (isBidirectionalRelation && obj != null)\n                {\n                    Object columnValue = PropertyAccessorHelper.getId(obj, childMetadata);\n                    Object[] pKeys = pClient.findIdsByColumn(entityMetadata.getSchema(), joinTableName, joinColumnName,\n                            inverseJoinColumnName, columnValue, entityMetadata.getEntityClazz());\n                    List parents = delegator.find(entity.getClass(), pKeys);\n                    PropertyAccessorHelper.set(obj, biDirectionalField,\n                            ObjectUtils.getFieldInstance(parents, biDirectionalField));\n                    PersistenceCacheManager.addEntityToPersistenceCache(obj, delegator, columnValue);\n                }\n\n                childrenEntities.add(obj);\n            }\n        }\n        Field childField = relation.getProperty();\n\n        try\n        {\n            PropertyAccessorHelper.set(\n                    entity,\n                    childField,\n                    PropertyAccessorHelper.isCollection(childField.getType()) ? ObjectUtils.getFieldInstance(\n                            childrenEntities, childField) : childrenEntities.get(0));\n            PersistenceCacheManager.addEntityToPersistenceCache(entity, delegator, entityId);\n        }\n        catch (PropertyAccessException ex)\n        {\n            throw new EntityReaderException(ex);\n        }\n    }\n\n    /**\n     * Populates a a relationship collection which is of type {@link Map} from\n     * relationsMap into entity\n     * \n     * @param entity\n     * @param delegator\n     * @param relation\n     * @param relObject\n     * @param relationsMap\n     */\n    private void populateCollectionFromMap(Object entity, PersistenceDelegator delegator, Relation relation,\n            Object relObject, Map<String, Object> relationsMap)\n    {\n        EntityMetadata childMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),\n                relation.getTargetEntity());\n        // Map collection to be set into entity\n        Map<Object, Object> relationshipEntityMap = new HashMap<Object, Object>();\n\n        if ((relObject == null || ProxyHelper.isProxyCollection(relObject)) && relationsMap != null\n                && !relationsMap.isEmpty())\n        {\n            for (String relationName : relationsMap.keySet())\n            {\n                Object relationValue = relationsMap.get(relationName);\n                if (relationValue instanceof Map)\n                {\n                    Map<Object, Object> relationValueMap = (Map<Object, Object>) relationValue;\n\n                    // Client for target entity\n                    Client targetEntityClient = delegator.getClient(childMetadata);\n\n                    for (Object targetEntityKey : relationValueMap.keySet())\n                    {\n                        // Find target entity from database\n                        Object targetEntity = targetEntityClient.find(childMetadata.getEntityClazz(), targetEntityKey);\n                        if (targetEntity != null && targetEntity instanceof EnhanceEntity)\n                        {\n                            targetEntity = ((EnhanceEntity) targetEntity).getEntity();\n                        }\n\n                        // Set source and target entities into Map key entity\n                        Object mapKeyEntity = relationValueMap.get(targetEntityKey);\n                        Class<?> relationshipClass = relation.getMapKeyJoinClass();\n                        for (Field f : relationshipClass.getDeclaredFields())\n                        {\n                            if (f.getType().equals(entity.getClass()))\n                            {\n                                PropertyAccessorHelper.set(mapKeyEntity, f, entity);\n                            }\n                            else if (f.getType().equals(childMetadata.getEntityClazz()))\n                            {\n                                PropertyAccessorHelper.set(mapKeyEntity, f, targetEntity);\n                            }\n                        }\n\n                        // Finally, put map key and value into collection\n                        relationshipEntityMap.put(mapKeyEntity, targetEntity);\n                    }\n                }\n            }\n            relObject = relationshipEntityMap;\n        }\n\n        // Set relationship collection into original entity\n        PropertyAccessorHelper.set(entity, relation.getProperty(), relObject);\n\n        // Add target entities into persistence cache\n        if (relObject != null && !ProxyHelper.isProxyCollection(relObject))\n        {\n            for (Object child : ((Map) relObject).values())\n            {\n                if (child != null)\n                {\n                    Object childId = PropertyAccessorHelper.getId(child, childMetadata);\n                    PersistenceCacheManager.addEntityToPersistenceCache(child, delegator, childId);\n                }\n            }\n        }\n    }\n\n    /**\n     * @param entity\n     * @param relationsMap\n     * @param m\n     * @param pd\n     * @param entityId\n     * @param relation\n     */\n    public void setProxyRelationObject(Object entity, Map<String, Object> relationsMap, EntityMetadata m,\n            PersistenceDelegator pd, Object entityId, Relation relation)\n    {\n        KunderaMetadata kunderaMetadata = pd.getKunderaMetadata();\n        String relationName = MetadataUtils.getMappedName(m, relation, kunderaMetadata);\n        Object relationValue = relationsMap != null ? relationsMap.get(relationName) : null;\n\n        if ((relation.getType().equals(ForeignKey.ONE_TO_ONE) || relation.getType().equals(ForeignKey.MANY_TO_ONE)))\n        { // One-To-One or Many-To-One relationship\n\n            Field biDirectionalField = relation.getBiDirectionalField();\n            boolean isBidirectionalRelation = (biDirectionalField != null);\n            if (isBidirectionalRelation && (relationValue == null && !relation.isJoinedByPrimaryKey()))\n            {\n                EntityMetadata parentEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                        relation.getTargetEntity());\n                Object owner = null;\n\n                String entityName = m.getEntityClazz().getName() + \"_\" + entityId + \"#\"\n                        + relation.getProperty().getName();\n\n                KunderaProxy kp = kunderaMetadata.getCoreMetadata().getLazyInitializerFactory().getProxy(entityName);\n\n                if (kp != null)\n                {\n                    owner = kp.getKunderaLazyInitializer().getOwner();\n                    if (owner != null && owner.getClass().equals(parentEntityMetadata.getEntityClazz()))\n                    {\n\n                        relationValue = PropertyAccessorHelper.getId(owner, parentEntityMetadata);\n                    }\n\n                    if (relationValue != null)\n                    {\n                        if (log.isDebugEnabled())\n                        {\n                            log.debug(\"Creating proxy for >> \" + parentEntityMetadata.getEntityClazz().getName() + \"#\"\n                                    + relation.getProperty().getName() + \"_\" + relationValue);\n                        }\n\n                        Object proxy = getLazyEntity(entityName, relation.getTargetEntity(),\n                                parentEntityMetadata.getReadIdentifierMethod(),\n                                parentEntityMetadata.getWriteIdentifierMethod(), relationValue, pd);\n                        PropertyAccessorHelper.set(entity, relation.getProperty(), proxy);\n                    }\n                }\n\n            }\n\n            else if (relationValue != null)\n            {\n                if (log.isDebugEnabled())\n                {\n                    log.debug(\"Creating proxy for >> \" + m.getEntityClazz().getName() + \"#\"\n                            + relation.getProperty().getName() + \"_\" + relationValue);\n                }\n\n                String entityName = m.getEntityClazz().getName() + \"_\" + entityId + \"#\"\n                        + relation.getProperty().getName();\n\n                Object proxy = getLazyEntity(entityName, relation.getTargetEntity(), m.getReadIdentifierMethod(),\n                        m.getWriteIdentifierMethod(), relationValue, pd);\n                PropertyAccessorHelper.set(entity, relation.getProperty(), proxy);\n\n            }\n            else if (relation.isJoinedByPrimaryKey())\n            {\n                if (log.isDebugEnabled())\n                {\n                    log.debug(\"Creating proxy for >> \" + m.getEntityClazz().getName() + \"#\"\n                            + relation.getProperty().getName() + \"_\" + relationValue);\n                }\n\n                String entityName = m.getEntityClazz().getName() + \"_\" + entityId + \"#\"\n                        + relation.getProperty().getName();\n\n                Object proxy = getLazyEntity(entityName, relation.getTargetEntity(), m.getReadIdentifierMethod(),\n                        m.getWriteIdentifierMethod(), entityId, pd);\n                PropertyAccessorHelper.set(entity, relation.getProperty(), proxy);\n            }\n\n        }\n        else if (relation.getType().equals(ForeignKey.ONE_TO_MANY)\n                || relation.getType().equals(ForeignKey.MANY_TO_MANY))\n        {\n            ProxyCollection proxyCollection = null;\n\n            if (relation.getPropertyType().isAssignableFrom(Set.class))\n            {\n                proxyCollection = new ProxySet(pd, relation);\n\n            }\n            else if (relation.getPropertyType().isAssignableFrom(List.class))\n            {\n                proxyCollection = new ProxyList(pd, relation);\n            }\n\n            else if (relation.getPropertyType().isAssignableFrom(Map.class))\n            {\n                proxyCollection = new ProxyMap(pd, relation);\n            }\n\n            proxyCollection.setOwner(entity);\n            proxyCollection.setRelationsMap(relationsMap);\n\n            PropertyAccessorHelper.set(entity, relation.getProperty(), proxyCollection);\n        }\n    }\n\n    private KunderaProxy getLazyEntity(String entityName, Class<?> persistentClass, Method getIdentifierMethod,\n            Method setIdentifierMethod, Object id, PersistenceDelegator pd)\n    {\n        return pd.getKunderaMetadata().getCoreMetadata().getLazyInitializerFactory()\n                .getProxy(entityName, persistentClass, getIdentifierMethod, setIdentifierMethod, id, pd);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/BetweenPredicate.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Predicate;\n\n/**\n * Implementation class for between clause {@link Predicate}\n * \n * @author vivek.mishra\n * \n */\npublic final class BetweenPredicate extends AbstractPredicate\n{\n    private Expression<?> expression;\n\n    private Object lower;\n\n    private Object upper;\n\n    private ConditionalOperator condition = ConditionalOperator.BTW;\n\n    BetweenPredicate(Expression expr, Object lower, Object upper)\n    {\n        this.expression = expr;\n        this.lower = lower;\n        this.upper = upper;\n    }\n\n    ConditionalOperator getCondition()\n    {\n        return this.condition;\n    }\n\n    Object getUpper()\n    {\n        return this.upper;\n    }\n\n    Object getLower()\n    {\n        return this.lower;\n    }\n\n    Expression getExpression()\n    {\n        return this.expression;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/ComparisonPredicate.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Predicate;\n\n/**\n * Predicate implementation for \"=\",\"<\",\">\",\"<=\",\">=\" {@link Predicate}\n *  \n * @author vivek.mishra\n *\n */\npublic final class ComparisonPredicate extends AbstractPredicate\n{\n\n    private Expression<?> lhs;\n    private Object rhs;\n    private ConditionalOperator condition;\n    \n    public ComparisonPredicate(Expression<?> lhs,Object rhs, ConditionalOperator operator)\n    {\n        this.lhs = lhs;\n        this.rhs = rhs;\n        this.condition = operator;\n    }\n    \n    public Expression<?> getLhs()\n    {\n        return lhs;\n    }\n\n    public Object getRhs()\n    {\n        return rhs;\n    }\n\n\n\n    public ConditionalOperator getCondition()\n    {\n        return this.condition;\n    }\n    \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/ConjuctionPredicate.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Predicate;\n\n/**\n * Implementation class for AND {@link Predicate}\n * @author vivek.mishra\n *\n */\npublic class ConjuctionPredicate extends AbstractPredicate \n{\n\n    private List<Expression<Boolean>> expressions = new ArrayList<Expression<Boolean>>();\n    \n    ConjuctionPredicate()\n    {\n        \n    }\n    \n    ConjuctionPredicate(Expression<Boolean>...paramArrayOfExpression)\n    {\n        this.expressions = Arrays.asList(paramArrayOfExpression);\n    }\n    \n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Predicate#getOperator()\n     */\n    @Override\n    public BooleanOperator getOperator()\n    {\n        return BooleanOperator.AND;\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Predicate#getExpressions()\n     */\n    @Override\n    public List<Expression<Boolean>> getExpressions()\n    {\n        return this.expressions;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/Coordinator.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.persistence;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport com.impetus.kundera.persistence.KunderaEntityTransaction.TxAction;\nimport com.impetus.kundera.persistence.TransactionResource.Response;\n\n/**\n * @author vivek\n * \n */\nclass Coordinator\n{\n\n    // private List<TransactionResource> txResources = new\n    // ArrayList<TransactionResource>();\n\n    private Map<String, TransactionResource> txResources = new HashMap<String, TransactionResource>();\n\n    public Coordinator()\n    {\n\n    }\n\n    void addResource(TransactionResource resource, final String pu)\n    {\n        txResources.put(pu, resource);\n    }\n\n    TransactionResource getResource(final String pu)\n    {\n        return txResources.get(pu);\n    }\n\n    Response coordinate(TxAction action)\n    {\n        Response response = Response.YES;\n        switch (action)\n        {\n        case BEGIN:\n            for (TransactionResource res : txResources.values())\n            {\n                res.onBegin();\n            }\n            break;\n\n        case PREPARE:\n\n            // TODO:: need to handle case of two phase commit, in case of\n            // polyglot persistence.\n\n            for (TransactionResource res : txResources.values())\n            {\n                res.prepare();\n            }\n            break;\n\n        case COMMIT:\n\n            for (TransactionResource res : txResources.values())\n            {\n                res.onCommit();\n            }\n            break;\n\n        case ROLLBACK:\n            for (TransactionResource res : txResources.values())\n            {\n                res.onRollback();\n            }\n\n            break;\n\n        default:\n            throw new IllegalArgumentException(\"Invalid transaction action : \" + action);\n        }\n\n        return response;\n    }\n\n    boolean isTransactionActive()\n    {\n        for (TransactionResource res : txResources.values())\n        {\n            if (res.isActive())\n            {\n                return true;\n            }\n\n        }\n        return false;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/CriteriaQueryTranslator.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.criteria.CompoundSelection;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Order;\nimport javax.persistence.criteria.Predicate;\nimport javax.persistence.criteria.Root;\nimport javax.persistence.criteria.Selection;\nimport javax.persistence.metamodel.Attribute;\n\nimport org.apache.commons.lang.StringUtils;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.AbstractPredicate.ConditionalOperator;\nimport com.impetus.kundera.query.KunderaQuery.SortOrder;\n\n/**\n * Translator class to transform {@link CriteriaQuery} to JPQL.\n * \n * @author vivek.mishra\n */\nfinal class CriteriaQueryTranslator\n{\n\n    static Map<ConditionalOperator, String> conditions = new HashMap<AbstractPredicate.ConditionalOperator, String>();\n\n    static\n    {\n        conditions.put(ConditionalOperator.EQ, \"=\");\n        conditions.put(ConditionalOperator.LT, \"<\");\n        conditions.put(ConditionalOperator.LTE, \"<=\");\n        conditions.put(ConditionalOperator.GT, \">\");\n        conditions.put(ConditionalOperator.GTE, \">=\");\n        conditions.put(ConditionalOperator.BTW, \"BETWEEN\");\n    }\n\n    /**\n     * Method to translate criteriaQuery into JPQL.\n     * \n     * @param criteriaQuery\n     *            criteria query.\n     * \n     * @return JPQL string.\n     */\n    static <S> String translate(CriteriaQuery criteriaQuery)\n    {\n        QueryBuilder builder = new CriteriaQueryTranslator.QueryBuilder();\n\n        // validate if criteria query is valid\n\n        /**\n         * select, from clause is mandatory\n         * \n         * multiple from clause not support where clause is optional\n         * \n         */\n\n        Selection<S> select = criteriaQuery.getSelection();\n\n        if (select != null)\n        {\n            builder.appendSelectClause();\n\n        }\n\n        if (select.getClass().isAssignableFrom(DefaultCompoundSelection.class)\n                && ((CompoundSelection) select).isCompoundSelection())\n        {\n            List<Selection<?>> selections = ((CompoundSelection) select).getCompoundSelectionItems();\n            builder.appendMultiSelect(selections);\n        }\n        else if (select instanceof AggregateExpression)\n        {\n            builder.appendAggregate(((AggregateExpression) select).getAggregation());\n        }\n        else\n        {\n            String alias = select.getAlias();\n\n            if (!StringUtils.isEmpty(alias))\n            {\n                builder.appendAlias(alias);\n            }\n\n            Attribute attribute = ((DefaultPath) select).getAttribute();\n\n            if (attribute != null)\n            {\n                builder.appendAttribute(attribute);\n            }\n        }\n        Class<? extends S> clazzType = select.getJavaType();\n\n        Set<Root<?>> roots = criteriaQuery.getRoots();\n\n        Root<?> from = roots.iterator().next();\n\n        Class entityClazz = from.getJavaType();\n\n        builder.appendFromClause();\n\n        // select.alias(paramString)\n        builder.appendFrom(entityClazz);\n        builder.appendAlias(from.getAlias() != null ? from.getAlias() : select.getAlias());\n        Predicate where = criteriaQuery.getRestriction(); // this could be null.\n        if (where != null)\n        {\n            builder.appendWhereClause();\n            List<Expression<Boolean>> expressions = where.getExpressions();\n            for (Expression expr : expressions)\n            {\n                builder.appendWhere(expr, from.getAlias());\n            }\n\n        }\n\n        List<Order> orderings = criteriaQuery.getOrderList();\n\n        if (orderings != null && !orderings.isEmpty())\n        {\n            builder.appendOrderClause(where == null);\n            String alias = from.getAlias() != null ? from.getAlias() : select.getAlias();\n            builder.appendMultiOrdering(orderings, alias);\n        }\n        return builder.getQuery();\n\n        // check that roots has to be one. multiple clause not yet supported\n\n    }\n\n    /**\n     * @author vivek.mishra QueryBuilder class\n     */\n    static class QueryBuilder\n    {\n\n        private StringBuilder builder = new StringBuilder();\n\n        QueryBuilder()\n        {\n\n        }\n\n        QueryBuilder appendAggregate(String aggregation)\n        {\n            this.builder.append(aggregation);\n            return this;\n\n        }\n\n        public String getQuery()\n        {\n            return this.builder.toString();\n        }\n\n        QueryBuilder appendSelectClause()\n        {\n            this.builder.append(\"Select\");\n            this.builder.append(Constants.SPACE);\n            return this;\n        }\n\n        QueryBuilder appendAlias(final String alias)\n        {\n            this.builder.append(alias);\n            return this;\n        }\n\n        QueryBuilder appendOrderClause(boolean prefixSpace)\n        {\n            if (prefixSpace)\n            {\n                this.builder.append(Constants.SPACE);\n            }\n            this.builder.append(\"ORDER BY\");\n            this.builder.append(Constants.SPACE);\n            return this;\n\n        }\n        \n        QueryBuilder appendMultiOrdering(List<Order> orderings, String alias)\n        {\n            for (Order order : orderings)\n            {\n                this.appendAlias(alias);\n                this.appendOrdering(order);\n                this.builder.append(Constants.COMMA);\n            }\n\n            // remove last comma\n            this.builder.deleteCharAt(this.builder.length() - 1);\n            return this;\n        }\n\n        QueryBuilder appendOrdering(Order orderAttribute)\n        {\n            DefaultPath expression = (DefaultPath) orderAttribute.getExpression();\n            Attribute attrib = expression.getAttribute();\n            Attribute embedAttribute = expression.getEmbeddedAttribute();\n            String fieldName = null;\n\n            this.builder.append(\".\");\n            if (embedAttribute != null)\n            {\n                fieldName = embedAttribute.getName();\n                this.builder.append(fieldName);\n                this.builder.append(\".\");\n            }\n\n            this.builder.append(attrib.getName());\n\n            SortOrder order = ((QueryOrder) orderAttribute).getOrder();\n\n            this.builder.append(Constants.SPACE);\n            this.builder.append(order.name());\n            return this;\n        }\n\n        private QueryBuilder appendMultiSelectSuffix()\n        {\n            this.builder.append(\",\");\n            return this;\n        }\n\n        QueryBuilder appendMultiSelect(List<Selection<?>> selections)\n        {\n            for (Selection s : selections)\n            {\n                Attribute attribute = ((DefaultPath) s).getAttribute();\n\n                if (attribute != null)\n                {\n                    this.builder.append(s.getAlias());\n                    this.appendAttribute(attribute);\n                    this.appendMultiSelectSuffix();\n                }\n\n            }\n            this.builder.delete(this.builder.toString().lastIndexOf(\",\"), this.builder.length());\n            return this;\n        }\n\n        QueryBuilder appendFromClause()\n        {\n            this.builder.append(Constants.SPACE);\n            this.builder.append(\"from\");\n            this.builder.append(Constants.SPACE);\n            return this;\n        }\n\n        QueryBuilder appendFrom(final Class entityClazz)\n        {\n            this.builder.append(entityClazz.getSimpleName());\n            this.builder.append(Constants.SPACE);\n            return this;\n        }\n\n        /**\n         * @return\n         */\n        QueryBuilder appendWhereClause()\n        {\n            this.builder.append(Constants.SPACE);\n            this.builder.append(\"where\");\n            this.builder.append(Constants.SPACE);\n            return this;\n        }\n\n        /**\n         * @param attrib\n         * @return\n         */\n        QueryBuilder appendAttribute(Attribute attrib)\n        {\n            this.builder.append(\".\");\n            this.builder.append(attrib.getName());\n            return this;\n        }\n\n        /**\n         * @param expr\n         * @param alias\n         * @return\n         */\n        QueryBuilder appendWhere(final Expression<Boolean> expr, final String alias)\n        {\n\n            if (expr.getClass().isAssignableFrom(ComparisonPredicate.class))\n            {\n                appendValueClause(alias, expr);\n            }\n            else\n            {\n                List<Expression<Boolean>> exprs = new ArrayList<Expression<Boolean>>();\n                if (expr.getClass().isAssignableFrom(ConjuctionPredicate.class))\n                {\n                    exprs = ((ConjuctionPredicate) expr).getExpressions();\n                    for (Expression<Boolean> e : exprs)\n                    {\n                        appendWhere(e, alias);\n                        this.builder.append(\"AND\");\n                        this.builder.append(Constants.SPACE);\n                    }\n\n                    this.builder.delete(this.builder.toString().lastIndexOf(\"AND\"), this.builder.length());\n                }\n                else if (expr.getClass().isAssignableFrom(DisjunctionPredicate.class))\n                {\n                    exprs = ((DisjunctionPredicate) expr).getExpressions();\n                    for (Expression<Boolean> e : exprs)\n                    {\n                        appendWhere(e, alias);\n                        this.builder.append(\"OR\");\n                        this.builder.append(Constants.SPACE);\n                    }\n                    this.builder.delete(this.builder.toString().lastIndexOf(\"OR\"), this.builder.length());\n                }\n                else if (expr.getClass().isAssignableFrom(BetweenPredicate.class))\n                {\n                    Expression btExpression = ((BetweenPredicate) expr).getExpression();\n                    appendBTValueClause(alias, btExpression, (BetweenPredicate) expr);\n                }\n\n            }\n\n            return this;\n        }\n\n        /**\n         * @param alias\n         * @param expr\n         */\n        private void appendValueClause(final String alias, Expression expr)\n        {\n            ConditionalOperator condition = ((ComparisonPredicate) expr).getCondition();\n            DefaultPath path = (DefaultPath) ((ComparisonPredicate) expr).getLhs();\n            Object value = ((ComparisonPredicate) expr).getRhs();\n            this.builder.append(alias);\n            this.builder.append(\".\");\n            if (path.getEmbeddedAttribute() != null)\n            {\n                this.builder.append(path.getEmbeddedAttribute().getName());\n                this.builder.append(\".\");\n            }\n            this.builder.append(path.getAttribute().getName());\n            this.builder.append(Constants.SPACE);\n            this.builder.append(conditions.get(condition));\n            this.builder.append(Constants.SPACE);\n            appendValue(value, isStringLiteral(((AbstractAttribute) path.getAttribute()).getBindableJavaType(), value));\n            this.builder.append(Constants.SPACE);\n        }\n\n        /**\n         * @param alias\n         * @param expr\n         * @param btw\n         */\n        private void appendBTValueClause(final String alias, Expression expr, BetweenPredicate btw)\n        {\n            DefaultPath path = (DefaultPath) expr;\n            this.builder.append(alias);\n            this.builder.append(\".\");\n            this.builder.append(path.getAttribute().getName());\n            this.builder.append(Constants.SPACE);\n            this.builder.append(conditions.get(btw.getCondition()));\n            this.builder.append(Constants.SPACE);\n            appendValue(btw.getLower(),\n                    isStringLiteral(((AbstractAttribute) path.getAttribute()).getBindableJavaType(), btw.getLower()));\n            this.builder.append(Constants.SPACE);\n            this.builder.append(\"AND\");\n            this.builder.append(Constants.SPACE);\n            appendValue(btw.getUpper(),\n                    isStringLiteral(((AbstractAttribute) path.getAttribute()).getBindableJavaType(), btw.getUpper()));\n        }\n\n        /**\n         * @param value\n         * @param isString\n         */\n        private void appendValue(Object value, boolean isString)\n        {\n            if (isString)\n            {\n                this.builder.append(\"\\\"\").append(value).append(\"\\\"\");\n            }\n            else\n            {\n                this.builder.append(value);\n            }\n\n        }\n\n        /**\n         * @param fieldClazz\n         * @param value\n         * @return\n         */\n        private boolean isStringLiteral(Class fieldClazz, Object value)\n        {\n            return !isNumericValue(fieldClazz) && !isNumericValue(value.getClass());\n        }\n\n        /**\n         * @param clazz\n         * @return\n         */\n        private boolean isNumericValue(Class clazz)\n        {\n\n            if (!clazz.isPrimitive())\n            {\n                return Number.class.isAssignableFrom(clazz.getSuperclass());\n            }\n            else\n            {\n                return int.class.isAssignableFrom(clazz) || float.class.isAssignableFrom(clazz)\n                        || double.class.isAssignableFrom(clazz) || long.class.isAssignableFrom(clazz)\n                        || byte.class.isAssignableFrom(clazz) || short.class.isAssignableFrom(clazz);\n            }\n\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/DefaultCompoundSelection.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.util.List;\n\nimport javax.persistence.criteria.CompoundSelection;\nimport javax.persistence.criteria.Selection;\n\n/**\n * Implementation class for multi column selection {@link CompoundSelection}\n * @author vivek.mishra\n *\n */\npublic class DefaultCompoundSelection<X> implements CompoundSelection<X>\n{\n\n    private List<Selection<?>> selections;\n    private Class<? extends X> resultType;\n    private String alias;\n\n    DefaultCompoundSelection(List<Selection<?>> selections, Class resultClazz)\n    {\n        this.selections = selections;\n        this.resultType = resultClazz;\n        if(isCompoundSelection())\n        {\n            this.alias = selections.get(0).getAlias();\n        }\n    }\n    \n    @Override\n    public Selection<X> alias(String paramString)\n    {\n        this.alias = paramString;\n        return this;\n    }\n\n    @Override\n    public boolean isCompoundSelection()\n    {\n        return this.selections != null && !this.selections.isEmpty() && this.selections.size() > 1;\n    }\n\n    @Override\n    public List<Selection<?>> getCompoundSelectionItems()\n    {\n        return this.selections;\n    }\n\n    @Override\n    public Class<? extends X> getJavaType()\n    {\n        return this.resultType;\n    }\n\n    @Override\n    public String getAlias()\n    {\n        return this.alias;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/DefaultFrom.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.util.Set;\n\nimport javax.persistence.criteria.CollectionJoin;\nimport javax.persistence.criteria.Fetch;\nimport javax.persistence.criteria.From;\nimport javax.persistence.criteria.Join;\nimport javax.persistence.criteria.JoinType;\nimport javax.persistence.criteria.ListJoin;\nimport javax.persistence.criteria.MapJoin;\nimport javax.persistence.criteria.SetJoin;\nimport javax.persistence.metamodel.CollectionAttribute;\nimport javax.persistence.metamodel.ListAttribute;\nimport javax.persistence.metamodel.MapAttribute;\nimport javax.persistence.metamodel.PluralAttribute;\nimport javax.persistence.metamodel.SetAttribute;\nimport javax.persistence.metamodel.SingularAttribute;\n\n/**\n * Default implementation class for {@link From}\n * \n * @author vivek.mishra\n *\n */\npublic class DefaultFrom<Z,X> extends DefaultPath<X> implements From<Z, X>\n{\n\n    public DefaultFrom()\n    {\n     super();\n    }\n    @Override\n    public Set<Fetch<X, ?>> getFetches()\n    {\n        throw new UnsupportedOperationException(\"Method getFetches() is not yet supported\");\n    }\n\n    @Override\n    public <Y> Fetch<X, Y> fetch(SingularAttribute<? super X, Y> paramSingularAttribute)\n    {\n        throw new UnsupportedOperationException(\"Method fetch(SingularAttribute<? super X, Y> paramSingularAttribute) is not yet supported\");\n    }\n\n    @Override\n    public <Y> Fetch<X, Y> fetch(SingularAttribute<? super X, Y> paramSingularAttribute, JoinType paramJoinType)\n    {\n        throw new UnsupportedOperationException(\"Method fetch(SingularAttribute<? super X, Y> paramSingularAttribute, JoinType paramJoinType) is not yet supported\");\n    }\n\n    @Override\n    public <Y> Fetch<X, Y> fetch(PluralAttribute<? super X, ?, Y> paramPluralAttribute)\n    {\n        throw new UnsupportedOperationException(\"Method fetch(PluralAttribute<? super X, ?, Y> paramPluralAttribute) is not yet supported\");\n    }\n\n    @Override\n    public <Y> Fetch<X, Y> fetch(PluralAttribute<? super X, ?, Y> paramPluralAttribute, JoinType paramJoinType)\n    {\n        throw new UnsupportedOperationException(\"Method fetch(PluralAttribute<? super X, ?, Y> paramPluralAttribute, JoinType paramJoinType) is not yet supported\");\n    }\n\n    @Override\n    public <X, Y> Fetch<X, Y> fetch(String paramString)\n    {\n        throw new UnsupportedOperationException(\"Method fetch(String paramString) is not yet supported\");\n    }\n\n    @Override\n    public <X, Y> Fetch<X, Y> fetch(String paramString, JoinType paramJoinType)\n    {\n        throw new UnsupportedOperationException(\"Method fetch(String paramString, JoinType paramJoinType) is not yet supported\");\n    }\n\n    @Override\n    public Set<Join<X, ?>> getJoins()\n    {\n        throw new UnsupportedOperationException(\"Method getJoins() is not yet supported\");\n    }\n\n    @Override\n    public boolean isCorrelated()\n    {\n        throw new UnsupportedOperationException(\"Method isCorrelated() is not yet supported\");\n    }\n\n    @Override\n    public From<Z, X> getCorrelationParent()\n    {\n        throw new UnsupportedOperationException(\"Method getCorrelationParent() is not yet supported\");\n    }\n\n    @Override\n    public <Y> Join<X, Y> join(SingularAttribute<? super X, Y> paramSingularAttribute)\n    {\n        throw new UnsupportedOperationException(\"Method join(SingularAttribute<? super X, Y> paramSingularAttribute) is not yet supported\");\n    }\n\n    @Override\n    public <Y> Join<X, Y> join(SingularAttribute<? super X, Y> paramSingularAttribute, JoinType paramJoinType)\n    {\n        throw new UnsupportedOperationException(\"Method join(SingularAttribute<? super X, Y> paramSingularAttribute, JoinType paramJoinType) is not yet supported\");\n    }\n\n    @Override\n    public <Y> CollectionJoin<X, Y> join(CollectionAttribute<? super X, Y> paramCollectionAttribute)\n    {\n        throw new UnsupportedOperationException(\"Method join(CollectionAttribute<? super X, Y> paramCollectionAttribute) is not yet supported\");\n    }\n\n    @Override\n    public <Y> SetJoin<X, Y> join(SetAttribute<? super X, Y> paramSetAttribute)\n    {\n        throw new UnsupportedOperationException(\"Method join(SetAttribute<? super X, Y> paramSetAttribute) is not yet supported\");\n    }\n\n    @Override\n    public <Y> ListJoin<X, Y> join(ListAttribute<? super X, Y> paramListAttribute)\n    {\n        throw new UnsupportedOperationException(\"Method join(ListAttribute<? super X, Y> paramListAttribute) is not yet supported\");\n    }\n\n    @Override\n    public <K, V> MapJoin<X, K, V> join(MapAttribute<? super X, K, V> paramMapAttribute)\n    {\n        throw new UnsupportedOperationException(\"Method join(MapAttribute<? super X, K, V> paramMapAttribute) is not yet supported\");\n    }\n\n    @Override\n    public <Y> CollectionJoin<X, Y> join(CollectionAttribute<? super X, Y> paramCollectionAttribute,\n            JoinType paramJoinType)\n    {\n        throw new UnsupportedOperationException(\"Method join(CollectionAttribute<? super X, Y> paramCollectionAttribute,JoinType paramJoinType) is not yet supported\");\n    }\n\n    @Override\n    public <Y> SetJoin<X, Y> join(SetAttribute<? super X, Y> paramSetAttribute, JoinType paramJoinType)\n    {\n        throw new UnsupportedOperationException(\"Method join(SetAttribute<? super X, Y> paramSetAttribute, JoinType paramJoinType) is not yet supported\");\n    }\n\n    @Override\n    public <Y> ListJoin<X, Y> join(ListAttribute<? super X, Y> paramListAttribute, JoinType paramJoinType)\n    {\n        throw new UnsupportedOperationException(\"Method join(ListAttribute<? super X, Y> paramListAttribute, JoinType paramJoinType) is not yet supported\");\n    }\n\n    @Override\n    public <K, V> MapJoin<X, K, V> join(MapAttribute<? super X, K, V> paramMapAttribute, JoinType paramJoinType)\n    {\n        throw new UnsupportedOperationException(\"Method join(MapAttribute<? super X, K, V> paramMapAttribute, JoinType paramJoinType) is not yet supported\");\n    }\n\n    @Override\n    public <X, Y> Join<X, Y> join(String paramString)\n    {\n        throw new UnsupportedOperationException(\"Method join(String paramString) is not yet supported\");\n    }\n\n    @Override\n    public <X, Y> CollectionJoin<X, Y> joinCollection(String paramString)\n    {\n        throw new UnsupportedOperationException(\"Method joinCollection(String paramString) is not yet supported\");\n    }\n\n    @Override\n    public <X, Y> SetJoin<X, Y> joinSet(String paramString)\n    {\n        throw new UnsupportedOperationException(\"Method joinSet(String paramString) is not yet supported\");\n    }\n\n    @Override\n    public <X, Y> ListJoin<X, Y> joinList(String paramString)\n    {\n        throw new UnsupportedOperationException(\"Method joinList(String paramString) is not yet supported\");\n    }\n\n    @Override\n    public <X, K, V> MapJoin<X, K, V> joinMap(String paramString)\n    {\n        throw new UnsupportedOperationException(\"Method joinMap(String paramString) is not yet supported\");\n    }\n\n    @Override\n    public <X, Y> Join<X, Y> join(String paramString, JoinType paramJoinType)\n    {\n        throw new UnsupportedOperationException(\"Method join(String paramString, JoinType paramJoinType) is not yet supported\");\n    }\n\n    @Override\n    public <X, Y> CollectionJoin<X, Y> joinCollection(String paramString, JoinType paramJoinType)\n    {\n        throw new UnsupportedOperationException(\"Method joinCollection(String paramString, JoinType paramJoinType) is not yet supported\");\n    }\n\n    @Override\n    public <X, Y> SetJoin<X, Y> joinSet(String paramString, JoinType paramJoinType)\n    {\n        throw new UnsupportedOperationException(\"Method joinSet(String paramString, JoinType paramJoinType) is not yet supported\");\n    }\n\n    @Override\n    public <X, Y> ListJoin<X, Y> joinList(String paramString, JoinType paramJoinType)\n    {\n        throw new UnsupportedOperationException(\"Method joinList(String paramString, JoinType paramJoinType) is not yet supported\");\n    }\n\n    @Override\n    public <X, K, V> MapJoin<X, K, V> joinMap(String paramString, JoinType paramJoinType)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/DefaultPath.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Path;\nimport javax.persistence.criteria.Predicate;\nimport javax.persistence.criteria.Selection;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.Attribute.PersistentAttributeType;\nimport javax.persistence.metamodel.Bindable;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.ManagedType;\nimport javax.persistence.metamodel.MapAttribute;\nimport javax.persistence.metamodel.PluralAttribute;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport com.impetus.kundera.metadata.model.attributes.DefaultSingularAttribute;\nimport com.impetus.kundera.metadata.model.type.DefaultEmbeddableType;\n\n/**\n * Default implementation for {@link Path}\n * \n * @author vivek.mishra\n * \n */\npublic class DefaultPath<X> implements Path<X>\n{\n\n    private PathType pathType;\n\n    protected ManagedType<X> managedType;\n\n    private Attribute<X, ?> attribute;\n    \n    private Attribute embeddedAttribute;\n    \n    protected EntityType<X> entityType;\n\n    private String alias;\n\n    // protected EntityType<X> entityType;\n\n    private PathCache cache = new PathCache();\n\n    DefaultPath()\n    {\n\n    }\n\n    private DefaultPath(PathType pathType, ManagedType<X> managedType, Attribute<X, ?> attribute, EntityType<X> entityType,Attribute embeddedAttribute)\n    {\n        this.pathType = pathType;\n        this.managedType = managedType;\n        this.attribute = attribute;\n        this.entityType = entityType;\n        if(embeddedAttribute != null && embeddedAttribute.getPersistentAttributeType().equals(PersistentAttributeType.EMBEDDED))\n        {\n            this.embeddedAttribute =embeddedAttribute;\n        }\n    }\n\n    @Override\n    public <Y> Path<Y> get(SingularAttribute<? super X, Y> paramSingularAttribute)\n    {\n\n        return cache.get(paramSingularAttribute,this.entityType, this.attribute);\n    }\n\n    @Override\n    public <E, C extends Collection<E>> Expression<C> get(PluralAttribute<X, C, E> paramPluralAttribute)\n    {\n        // return cache.get(paramPluralAttribute);\n        throw new UnsupportedOperationException(\"Support for plural attribute is not yet available\");\n    }\n\n    @Override\n    public <K, V, M extends Map<K, V>> Expression<M> get(MapAttribute<X, K, V> paramMapAttribute)\n    {\n        throw new UnsupportedOperationException(\"Support for map attribute is not yet available\");\n    }\n\n    @Override\n    public Expression<Class<? extends X>> type()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.Path#get(java.lang.String)\n     */\n    @Override\n    public <Y> Path<Y> get(String paramString)\n    {\n        Attribute attribute = null;\n        if (this.attribute != null\n                && this.attribute.getPersistentAttributeType().equals(PersistentAttributeType.EMBEDDED))\n        {\n            try\n            {\n                DefaultEmbeddableType embeddableType = (DefaultEmbeddableType) ((DefaultSingularAttribute) this.attribute)\n                        .getType();\n                attribute = embeddableType.getAttribute(paramString);\n            }\n            catch (IllegalArgumentException iaex)\n            {\n                // do nothing. ignore\n            }\n        }\n\n        attribute = attribute == null ? this.managedType.getAttribute(paramString) : attribute;\n\n        // TODO:: need to check for illegalStateException.\n\n        return cache.get(attribute, this.entityType, this.attribute);\n    }\n\n    @Override\n    public Predicate isNull()\n    {\n        throw new UnsupportedOperationException(\"Method isNull() not yet supported\");\n    }\n\n    @Override\n    public Predicate isNotNull()\n    {\n        throw new UnsupportedOperationException(\"Method isNotNull() not yet supported\");\n    }\n\n    @Override\n    public Predicate in(Object... paramArrayOfObject)\n    {\n        throw new UnsupportedOperationException(\"Method in(Object... paramArrayOfObject) not yet supported\");\n    }\n\n    @Override\n    public Predicate in(Expression<?>... paramArrayOfExpression)\n    {\n        throw new UnsupportedOperationException(\"Method in(Expression<?>... paramArrayOfExpression) not yet supported\");\n    }\n\n    @Override\n    public Predicate in(Collection<?> paramCollection)\n    {\n        throw new UnsupportedOperationException(\"Method in(Collection<?> paramCollection) not yet supported\");\n    }\n\n    @Override\n    public Predicate in(Expression<Collection<?>> paramExpression)\n    {\n        throw new UnsupportedOperationException(\"Method in(Expression<Collection<?>> paramExpression) not yet supported\");\n    }\n\n    @Override\n    public <X> Expression<X> as(Class<X> paramClass)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public Selection<X> alias(String alias)\n    {\n        this.alias = alias;\n        return this;\n    }\n\n    @Override\n    public boolean isCompoundSelection()\n    {\n        // TODO Auto-generated method stub\n        return false;\n    }\n\n    @Override\n    public List<Selection<?>> getCompoundSelectionItems()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public Class<? extends X> getJavaType()\n    {\n        return this.managedType.getJavaType();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TupleElement#getAlias()\n     */\n    @Override\n    public String getAlias()\n    {\n        return this.alias;\n    }\n\n    public EntityType<X> getEntityType()\n    {\n        return this.entityType;\n    }\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.DefaultPath#getModel()\n     * \n     * @Override public EntityType<X> getModel() { return this.managedType; }\n     */\n    enum PathType\n    {\n        SINGULAR, PLURAL;\n    }\n\n    Attribute getAttribute()\n    {\n        return this.attribute;\n    }\n\n    ManagedType<X> getManagedType()\n    {\n        return managedType;\n    }\n    \n    Attribute getEmbeddedAttribute()\n    {\n        return embeddedAttribute;\n    }\n    \n    private <Y> Path<Y> getPath(Attribute attribute,EntityType<Y> entityType,Attribute embeddedAttribute)\n    {\n        Path<Y> path = null;\n        if (attribute.isCollection())\n        {\n            path = new DefaultPath<Y>(PathType.PLURAL, attribute.getDeclaringType(), attribute, entityType,embeddedAttribute);\n        }\n        else\n        {\n            path = new DefaultPath<Y>(PathType.SINGULAR, attribute.getDeclaringType(), attribute,entityType,embeddedAttribute);\n        }\n\n        return path;\n    }\n\n    @Override\n    public Bindable<X> getModel()\n    {\n        return (Bindable<X>) this.attribute;\n    }\n\n    @Override\n    public Path<?> getParentPath()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    class PathCache\n    {\n        private Map<String, Path> cacheAttributes = new ConcurrentHashMap<String, Path>();\n\n        synchronized Path get(Attribute attribute, EntityType<X> entityType, Attribute embeddedAttribute)\n        {\n            if (!cacheAttributes.containsKey(attribute.getName()))\n            {\n                cacheAttributes.put(attribute.getName(), getPath(attribute,entityType,embeddedAttribute));\n            }\n            return cacheAttributes.get(attribute.getName());\n        }\n\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/DefaultRoot.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.util.Set;\n\nimport javax.persistence.criteria.Fetch;\nimport javax.persistence.criteria.JoinType;\nimport javax.persistence.criteria.Root;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.PluralAttribute;\nimport javax.persistence.metamodel.SingularAttribute;\n\n/**\n * Default implementation for {@link Root}\n * @author vivek.mishra\n * \n */\npublic class DefaultRoot<X> extends DefaultFrom<X, X> implements Root<X>\n{\n\n\n    DefaultRoot(EntityType<X> entityType)\n    {\n        this.entityType = entityType;\n        this.managedType = entityType;\n    }\n\n\n    @Override\n    public Set<Fetch<X, ?>> getFetches()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public <Y> Fetch<X, Y> fetch(SingularAttribute<? super X, Y> paramSingularAttribute)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public <Y> Fetch<X, Y> fetch(SingularAttribute<? super X, Y> paramSingularAttribute, JoinType paramJoinType)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public <Y> Fetch<X, Y> fetch(PluralAttribute<? super X, ?, Y> paramPluralAttribute)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public <Y> Fetch<X, Y> fetch(PluralAttribute<? super X, ?, Y> paramPluralAttribute, JoinType paramJoinType)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public <X, Y> Fetch<X, Y> fetch(String paramString)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public <X, Y> Fetch<X, Y> fetch(String paramString, JoinType paramJoinType)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.persistence.DefaultPath#getModel()\n     */\n    @Override\n    public EntityType<X> getModel()\n    {\n        return this.entityType;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/DefaultTransactionResource.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.persistence;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.persistence.api.Batcher;\n\n/**\n * Default transaction implementation for databases who does not support\n * transactions. This can only ensure ATOMICITY out of ACID properties.\n * \n * @author vivek.mishra\n */\npublic class DefaultTransactionResource implements TransactionResource\n{\n\n    private boolean isActive;\n\n    private Client client;\n\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(DefaultTransactionResource.class);\n\n    private List<Node> nodes = new ArrayList<Node>();\n\n    public DefaultTransactionResource(Client client)\n    {\n        this.client = client;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.TransactionResource#onBegin()\n     */\n    @Override\n    public void onBegin()\n    {\n        isActive = true;\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.TransactionResource#onCommit()\n     */\n    @Override\n    public void onCommit()\n    {\n        onFlush();\n        nodes.clear();\n        nodes = null;\n        nodes = new ArrayList<Node>();\n        isActive = false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.TransactionResource#onFlush()\n     */\n    public void onFlush()\n    {\n        for (Node node : nodes)\n        {\n            node.flush();\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.TransactionResource#onRollback()\n     */\n    @Override\n    public void onRollback()\n    {\n        onBatchRollBack();\n\n        nodes.clear();\n        nodes = null;\n        nodes = new ArrayList<Node>();\n        isActive = false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.TransactionResource#prepare()\n     */\n    @Override\n    public Response prepare()\n    {\n        return Response.YES;\n    }\n\n    /**\n     * \n     * @param node\n     * @param events\n     */\n    void syncNode(Node node)\n    {\n        nodes.add(node);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.TransactionResource#isActive()\n     */\n    @Override\n    public boolean isActive()\n    {\n        return isActive;\n    }\n\n    /**\n     * In case of rollback, clear added batch, if any.\n     */\n    private void onBatchRollBack()\n    {\n        if (client instanceof Batcher)\n        {\n            ((Batcher) client).clear();\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/DisjunctionPredicate.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Predicate;\n\n/**\n * Implementation of OR {@link Predicate}\n * \n * @author vivek.mishra\n *\n */\npublic class DisjunctionPredicate extends AbstractPredicate \n{\n    private List<Expression<Boolean>> expressions = new ArrayList<Expression<Boolean>>();\n\n    DisjunctionPredicate()\n    {\n    \n    }\n    \n    DisjunctionPredicate(Expression<Boolean>...paramArrayOfExpression)\n    {\n        this.expressions = Arrays.asList(paramArrayOfExpression);\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Predicate#getOperator()\n     */\n    @Override\n    public BooleanOperator getOperator()\n    {\n        return BooleanOperator.OR;\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Predicate#getExpressions()\n     */\n    @Override\n    public List<Expression<Boolean>> getExpressions()\n    {\n        return this.expressions;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/EntityManagerFactoryImpl.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.persistence;\r\n\r\n\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\nimport java.util.concurrent.ConcurrentHashMap;\r\n\r\nimport javax.persistence.Cache;\r\nimport javax.persistence.EntityGraph;\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.PersistenceContextType;\r\nimport javax.persistence.PersistenceUnitUtil;\r\nimport javax.persistence.Query;\r\nimport javax.persistence.SynchronizationType;\r\nimport javax.persistence.criteria.CriteriaBuilder;\r\nimport javax.persistence.metamodel.Metamodel;\r\nimport javax.persistence.spi.LoadState;\r\nimport javax.persistence.spi.PersistenceUnitInfo;\r\nimport javax.persistence.spi.PersistenceUnitTransactionType;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.Constants;\r\nimport com.impetus.kundera.KunderaException;\r\nimport com.impetus.kundera.KunderaPersistence;\r\nimport com.impetus.kundera.PersistenceProperties;\r\nimport com.impetus.kundera.PersistenceUtilHelper;\r\nimport com.impetus.kundera.cache.CacheException;\r\nimport com.impetus.kundera.cache.CacheProvider;\r\nimport com.impetus.kundera.cache.NonOperationalCacheProvider;\r\nimport com.impetus.kundera.client.ClientResolverException;\r\nimport com.impetus.kundera.configure.ClientMetadataBuilder;\r\nimport com.impetus.kundera.configure.MetamodelConfiguration;\r\nimport com.impetus.kundera.configure.PersistenceUnitConfiguration;\r\nimport com.impetus.kundera.loader.ClientFactory;\r\nimport com.impetus.kundera.loader.ClientLifeCycleManager;\r\nimport com.impetus.kundera.loader.CoreLoader;\r\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\r\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\r\nimport com.impetus.kundera.metadata.model.CoreMetadata;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\r\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\r\nimport com.impetus.kundera.property.PropertyAccessorHelper;\r\n\r\n/**\r\n * Implementation class for {@link EntityManagerFactory}\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class EntityManagerFactoryImpl implements EntityManagerFactory\r\n{\r\n\r\n    /** the log used by this class. */\r\n    private static Logger logger = LoggerFactory.getLogger(EntityManagerFactoryImpl.class);\r\n\r\n    /** Whether or not the factory has been closed. */\r\n    private boolean closed;\r\n\r\n    /**\r\n     * Persistence Unit Properties Overriden by user provided factory\r\n     * properties.\r\n     */\r\n    private Map<String, Object> properties;\r\n\r\n    // TODO: Move it to Application Metadata\r\n    /** The cache provider. */\r\n    private CacheProvider cacheProvider;\r\n\r\n    /**\r\n     * Array of persistence units. (Contains only one string usually except when\r\n     * persisting in multiple data-stores)\r\n     */\r\n    private String[] persistenceUnits;\r\n\r\n    // Transaction type\r\n    private PersistenceUnitTransactionType transactionType;\r\n\r\n    private final KunderaPersistenceUnitUtil util;\r\n\r\n    private final PersistenceUtilHelper.MetadataCache cache = new PersistenceUtilHelper.MetadataCache();\r\n\r\n    /** ClientFactory map holds one clientfactory for one persistence unit */\r\n    private Map<String, ClientFactory> clientFactories = new ConcurrentHashMap<String, ClientFactory>();\r\n\r\n    /** The Constant INSTANCE holds all application and core metadata. */\r\n    private final KunderaMetadata kunderaMetadata = new KunderaMetadata();\r\n\r\n    public EntityManagerFactoryImpl(PersistenceUnitInfo puInfo, Map<String, Object> properties)\r\n    {\r\n        // Load Core\r\n        logger.info(\"Loading Core\");\r\n        new CoreLoader().load(kunderaMetadata);\r\n\r\n        this.configurePersistenceUnit(puInfo, properties);\r\n        this.util = new KunderaPersistenceUnitUtil(cache);\r\n        this.configure(puInfo.getPersistenceUnitName(), properties);\r\n    }\r\n\r\n    /**\r\n     * Use this if you want to construct this directly.\r\n     * \r\n     * @param persistenceUnit\r\n     *            used to prefix the Cassandra domains\r\n     * @param properties\r\n     *            the properties\r\n     */\r\n    public EntityManagerFactoryImpl(String persistenceUnit, Map<String, Object> properties)\r\n    {\r\n        // Load Core\r\n        logger.info(\"Loading Core\");\r\n        new CoreLoader().load(kunderaMetadata);\r\n\r\n        this.configurePersistenceUnit(persistenceUnit, properties);\r\n        this.util = new KunderaPersistenceUnitUtil(cache);\r\n        this.configure(persistenceUnit, properties);\r\n    }\r\n\r\n    /**\r\n     * \r\n     * @param persistenceUnit\r\n     * @param properties\r\n     */\r\n    private void configure(String persistenceUnit, Map<String, Object> properties)\r\n    {\r\n        Map<String, Object> propsMap = new HashMap<String, Object>();\r\n\r\n        if (properties != null)\r\n        {\r\n            propsMap.putAll(properties);\r\n        }\r\n\r\n        // TODO Devise some better (JPA) way\r\n        propsMap.put(Constants.PERSISTENCE_UNIT_NAME, persistenceUnit);\r\n        this.properties = propsMap;\r\n        this.persistenceUnits = persistenceUnit.split(Constants.PERSISTENCE_UNIT_SEPARATOR);\r\n\r\n        // Configure metamodel.\r\n        new MetamodelConfiguration(properties, kunderaMetadata, persistenceUnits).configure();\r\n\r\n        // configure client factories\r\n        configureClientFactories();\r\n\r\n        // Initialize L2 cache\r\n        // Invoke Client Loaders\r\n\r\n        Set<PersistenceUnitTransactionType> txTypes = new HashSet<PersistenceUnitTransactionType>();\r\n\r\n        for (String pu : persistenceUnits)\r\n        {\r\n            PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,  pu);\r\n            PersistenceUnitTransactionType txType = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata, pu).getTransactionType();\r\n            txTypes.add(txType);\r\n            if (cacheProvider == null)\r\n            {\r\n                this.cacheProvider = initSecondLevelCache(puMetadata);\r\n                this.cacheProvider.createCache(Constants.KUNDERA_SECONDARY_CACHE_NAME);\r\n            }\r\n        }\r\n\r\n        if (txTypes.size() != 1)\r\n        {\r\n            throw new IllegalArgumentException(\r\n                    \"For polyglot persistence, it is mandatory for all persistence units to have same Transction type.\");\r\n        }\r\n        else\r\n        {\r\n            this.transactionType = txTypes.iterator().next();\r\n        }\r\n\r\n        if (logger.isInfoEnabled())\r\n        {\r\n            logger.info(\"EntityManagerFactory created for persistence unit : \" + persistenceUnit);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Close the factory, releasing any resources that it holds. After a factory\r\n     * instance has been closed, all methods invoked on it will throw the\r\n     * IllegalStateException, except for isOpen, which will return false. Once\r\n     * an EntityManagerFactory has been closed, all its entity managers are\r\n     * considered to be in the closed state.\r\n     * \r\n     * @throws IllegalStateException\r\n     *             if the entity manager factory has been closed\r\n     * @see javax.persistence.EntityManagerFactory#close()\r\n     */\r\n    @Override\r\n    public final void close()\r\n    {\r\n        if (isOpen())\r\n        {\r\n            closed = true;\r\n\r\n            // Shut cache provider down\r\n            if (cacheProvider != null)\r\n            {\r\n                cacheProvider.shutdown();\r\n            }\r\n\r\n            for (String pu : persistenceUnits)\r\n            {\r\n                ((ClientLifeCycleManager) clientFactories.get(pu)).destroy();\r\n            }\r\n            this.persistenceUnits = null;\r\n            this.properties = null;\r\n            clientFactories.clear();\r\n            clientFactories = new ConcurrentHashMap<String, ClientFactory>();\r\n        }\r\n        else\r\n        {\r\n            throw new IllegalStateException(\"Entity manager factory has been closed\");\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Create a new application-managed EntityManager. This method returns a new\r\n     * EntityManager instance each time it is invoked. The isOpen method will\r\n     * return true on the returned instance.\r\n     * \r\n     * @return entity manager instance\r\n     * @throws IllegalStateException\r\n     *             if the entity manager factory has been closed\r\n     */\r\n    @Override\r\n    public final EntityManager createEntityManager()\r\n    {\r\n        // For Application managed persistence context, type is always EXTENDED\r\n        if (isOpen())\r\n        {\r\n            return new EntityManagerImpl(this, transactionType, PersistenceContextType.EXTENDED);\r\n        }\r\n        throw new IllegalStateException(\"Entity manager factory has been closed.\");\r\n    }\r\n\r\n    /**\r\n     * Create a new application-managed EntityManager with the specified Map of\r\n     * properties. This method returns a new EntityManager instance each time it\r\n     * is invoked. The isOpen method will return true on the returned instance.\r\n     * \r\n     * @param map\r\n     *            properties for entity manager\r\n     * @return entity manager instance\r\n     * @throws IllegalStateException\r\n     *             if the entity manager factory has been closed\r\n     */\r\n    @Override\r\n    public final EntityManager createEntityManager(Map map)\r\n    {\r\n        // For Application managed persistence context, type is always EXTENDED\r\n        if (isOpen())\r\n        {\r\n            return new EntityManagerImpl(this, map, transactionType, PersistenceContextType.EXTENDED);\r\n        }\r\n        throw new IllegalStateException(\"Entity manager factory has been closed.\");\r\n    }\r\n\r\n    /**\r\n     * Indicates whether the factory is open. Returns true until the factory has\r\n     * been closed.\r\n     * \r\n     * @return boolean indicating whether the factory is open\r\n     * @see javax.persistence.EntityManagerFactory#isOpen()\r\n     */\r\n    @Override\r\n    public final boolean isOpen()\r\n    {\r\n        return !closed;\r\n    }\r\n\r\n    /**\r\n     * Return an instance of CriteriaBuilder for the creation of CriteriaQuery\r\n     * objects.\r\n     * \r\n     * @return CriteriaBuilder instance\r\n     * @throws IllegalStateException\r\n     *             if the entity manager factory has been closed\r\n     * @see javax.persistence.EntityManagerFactory#getCriteriaBuilder()\r\n     */\r\n    @Override\r\n    public CriteriaBuilder getCriteriaBuilder()\r\n    {\r\n        if (isOpen())\r\n        {\r\n            return new KunderaCriteriaBuilder(this);\r\n        }\r\n        throw new IllegalStateException(\"Entity manager factory has been closed.\");\r\n    }\r\n\r\n    /**\r\n     * Return an instance of Metamodel interface for access to the metamodel of\r\n     * the persistence unit.\r\n     * \r\n     * @return Metamodel instance\r\n     * @throws IllegalStateException\r\n     *             if the entity manager factory has been closed\r\n     * @see javax.persistence.EntityManagerFactory#getMetamodel()\r\n     */\r\n    @Override\r\n    public Metamodel getMetamodel()\r\n    {\r\n        if (isOpen())\r\n        {\r\n            MetamodelImpl metamodel = null;\r\n            for (String pu : persistenceUnits)\r\n            {\r\n                metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(pu);\r\n\r\n                if (metamodel != null)\r\n                {\r\n                    return metamodel;\r\n                }\r\n            }\r\n            // return\r\n            // KunderaMetadataManager.getMetamodel(getPersistenceUnits());\r\n        }\r\n        throw new IllegalStateException(\"Entity manager factory has been closed.\");\r\n    }\r\n\r\n    /**\r\n     * Get the properties and associated values that are in effect for the\r\n     * entity manager factory. Changing the contents of the map does not change\r\n     * the configuration in effect.\r\n     * \r\n     * @return properties\r\n     * @throws IllegalStateException\r\n     *             if the entity manager factory has been closed\r\n     * @see javax.persistence.EntityManagerFactory#getProperties()\r\n     */\r\n    @Override\r\n    public Map<String, Object> getProperties()\r\n    {\r\n        if (isOpen())\r\n        {\r\n            return properties;\r\n        }\r\n        throw new IllegalStateException(\"Entity manager factory has been closed.\");\r\n    }\r\n\r\n    /**\r\n     * Access the cache that is associated with the entity manager factory (the\r\n     * \"second level cache\").\r\n     * \r\n     * @return instance of the Cache interface\r\n     * @throws IllegalStateException\r\n     *             if the entity manager factory has been closed\r\n     * @see javax.persistence.EntityManagerFactory#getCache()\r\n     */\r\n    @Override\r\n    public Cache getCache()\r\n    {\r\n        if (isOpen())\r\n        {\r\n            return cacheProvider.getCache(Constants.KUNDERA_SECONDARY_CACHE_NAME);\r\n        }\r\n        throw new IllegalStateException(\"Entity manager factory has been closed.\");\r\n    }\r\n\r\n    /**\r\n     * Return interface providing access to utility methods for the persistence\r\n     * unit.\r\n     * \r\n     * @return PersistenceUnitUtil interface\r\n     * @throws IllegalStateException\r\n     *             if the entity manager factory has been closed\r\n     * @see javax.persistence.EntityManagerFactory#getPersistenceUnitUtil()\r\n     */\r\n    @Override\r\n    public PersistenceUnitUtil getPersistenceUnitUtil()\r\n    {\r\n        if (!isOpen())\r\n        {\r\n            throw new IllegalStateException(\"Entity manager factory has been closed.\");\r\n        }\r\n        return this.util;\r\n    }\r\n\r\n    /**\r\n     * Initialize and load clientFactory for all persistenceUnit with external\r\n     * properties.\r\n     * \r\n     * @param persistenceUnit\r\n     * @param externalProperties\r\n     */\r\n    private void configureClientFactories()\r\n    {\r\n        ClientMetadataBuilder builder = new ClientMetadataBuilder(getProperties(), kunderaMetadata,\r\n                getPersistenceUnits());\r\n        builder.buildClientFactoryMetadata(clientFactories, kunderaMetadata);\r\n    }\r\n\r\n    /**\r\n     * Inits the second level cache.\r\n     * \r\n     * @return the cache provider\r\n     */\r\n    private CacheProvider initSecondLevelCache(final PersistenceUnitMetadata puMetadata)\r\n    {\r\n\r\n        String classResourceName = (String) getProperties().get(PersistenceProperties.KUNDERA_CACHE_CONFIG_RESOURCE);\r\n\r\n        classResourceName = classResourceName != null ? classResourceName : puMetadata\r\n                .getProperty(PersistenceProperties.KUNDERA_CACHE_CONFIG_RESOURCE);\r\n\r\n        String cacheProviderClassName = (String) getProperties()\r\n                .get(PersistenceProperties.KUNDERA_CACHE_PROVIDER_CLASS);\r\n\r\n        cacheProviderClassName = cacheProviderClassName != null ? cacheProviderClassName : puMetadata\r\n                .getProperty(PersistenceProperties.KUNDERA_CACHE_PROVIDER_CLASS);\r\n\r\n        CacheProvider cacheProvider = null;\r\n        if (cacheProviderClassName != null)\r\n        {\r\n            try\r\n            {\r\n                Class<CacheProvider> cacheProviderClass = (Class<CacheProvider>) Class.forName(cacheProviderClassName);\r\n                cacheProvider = cacheProviderClass.newInstance();\r\n                cacheProvider.init(classResourceName);\r\n            }\r\n            catch (ClassNotFoundException e)\r\n            {\r\n                throw new CacheException(\"Could not find class \" + cacheProviderClassName\r\n                        + \". Check whether you spelled it correctly in persistence.xml\", e);\r\n            }\r\n            catch (InstantiationException e)\r\n            {\r\n                throw new CacheException(\"Could not instantiate \" + cacheProviderClassName, e);\r\n            }\r\n            catch (IllegalAccessException e)\r\n            {\r\n                throw new CacheException(e);\r\n            }\r\n        }\r\n        if (cacheProvider == null)\r\n        {\r\n            cacheProvider = new NonOperationalCacheProvider();\r\n        }\r\n        return cacheProvider;\r\n    }\r\n\r\n    /**\r\n     * Gets the persistence units.\r\n     * \r\n     * @return the persistence units\r\n     */\r\n    String[] getPersistenceUnits()\r\n    {\r\n        return persistenceUnits;\r\n    }\r\n\r\n    /**\r\n     * \r\n     * @param pu\r\n     * @return\r\n     */\r\n    ClientFactory getClientFactory(final String pu)\r\n    {\r\n        ClientFactory clientFactory = clientFactories.get(pu);\r\n        if (clientFactory != null)\r\n        {\r\n            return clientFactory;\r\n        }\r\n        logger.error(\"Client Factory Not Configured For Specified Client Type : \");\r\n        throw new ClientResolverException(\"Client Factory Not Configured For Specified Client Type.\");\r\n    }\r\n\r\n    /**\r\n     * \r\n     * @return Kundera metadata instance.\r\n     */\r\n    public KunderaMetadata getKunderaMetadataInstance()\r\n    {\r\n        return kunderaMetadata;\r\n    }\r\n\r\n    /**\r\n     * The Class KunderaMetadata.\r\n     * \r\n     * @author amresh.singh\r\n     */\r\n    public static class KunderaMetadata\r\n    {\r\n        /* Metadata for Kundera core */\r\n        /** The core metadata. */\r\n        private CoreMetadata coreMetadata;\r\n\r\n        /* User application specific metadata */\r\n        /** The application metadata. */\r\n        private ApplicationMetadata applicationMetadata;\r\n\r\n        /**\r\n         * Instantiates a new kundera metadata.\r\n         */\r\n        private KunderaMetadata()\r\n        {\r\n\r\n        }\r\n\r\n        /**\r\n         * Gets the application metadata.\r\n         * \r\n         * @return the applicationMetadata\r\n         */\r\n        public ApplicationMetadata getApplicationMetadata()\r\n        {\r\n            if (applicationMetadata == null)\r\n            {\r\n                applicationMetadata = new ApplicationMetadata();\r\n            }\r\n            return applicationMetadata;\r\n        }\r\n\r\n        /**\r\n         * Gets the core metadata.\r\n         * \r\n         * @return the coreMetadata\r\n         */\r\n        public CoreMetadata getCoreMetadata()\r\n        {\r\n            return coreMetadata;\r\n        }\r\n\r\n        /**\r\n         * Sets the application metadata.\r\n         * \r\n         * @param applicationMetadata\r\n         *            the applicationMetadata to set\r\n         */\r\n        public void setApplicationMetadata(ApplicationMetadata applicationMetadata)\r\n        {\r\n            this.applicationMetadata = applicationMetadata;\r\n        }\r\n\r\n        /**\r\n         * Sets the core metadata.\r\n         * \r\n         * @param coreMetadata\r\n         *            the coreMetadata to set\r\n         */\r\n        public void setCoreMetadata(CoreMetadata coreMetadata)\r\n        {\r\n            this.coreMetadata = coreMetadata;\r\n        }\r\n    }\r\n\r\n    /**\r\n     * {@link PersistenceUnitUtil} for {@link KunderaPersistence}\r\n     * \r\n     * @author amresh.singh\r\n     */\r\n    private class KunderaPersistenceUnitUtil implements PersistenceUnitUtil\r\n    {\r\n        private transient PersistenceUtilHelper.MetadataCache cache;\r\n\r\n        public KunderaPersistenceUnitUtil(PersistenceUtilHelper.MetadataCache cache)\r\n        {\r\n            this.cache = cache;\r\n        }\r\n\r\n        @Override\r\n        public boolean isLoaded(Object entity, String attributeName)\r\n        {\r\n            LoadState state = PersistenceUtilHelper.isLoadedWithoutReference(entity, attributeName, this.cache);\r\n            if (state == LoadState.LOADED)\r\n            {\r\n                return true;\r\n            }\r\n            if (state == LoadState.NOT_LOADED)\r\n            {\r\n                return false;\r\n            }\r\n            return (PersistenceUtilHelper.isLoadedWithReference(entity, attributeName, this.cache) != LoadState.NOT_LOADED);\r\n        }\r\n\r\n        @Override\r\n        public boolean isLoaded(Object entity)\r\n        {\r\n            return (PersistenceUtilHelper.isLoaded(entity) != LoadState.NOT_LOADED);\r\n        }\r\n\r\n        @Override\r\n        public Object getIdentifier(Object entity)\r\n        {\r\n            Class<?> entityClass = entity.getClass();\r\n            EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,  entityClass);\r\n\r\n            if (entityMetadata == null)\r\n            {\r\n                throw new IllegalArgumentException(entityClass + \" is not an entity\");\r\n            }\r\n            return PropertyAccessorHelper.getId(entity, entityMetadata);\r\n        }\r\n\r\n    }\r\n\r\n\r\n    @Override\r\n    public void addNamedQuery(String paramString, Query paramQuery)\r\n    {\r\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\r\n        // Do nothing. Not yet implemented.\r\n    }\r\n\r\n    @Override\r\n    public <T> T unwrap(Class<T> paramClass)\r\n    {\r\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\r\n        // Do nothing. Not yet implemented.\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    public <T> void addNamedEntityGraph(String paramString, EntityGraph<T> paramEntityGraph)\r\n    {\r\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\r\n        // Do nothing. Not yet implemented.\r\n        \r\n    }\r\n    \r\n    /**\r\n     * One time initialization for persistence unit metadata.\r\n     * \r\n     * @param persistenceUnit\r\n     *            Persistence Unit/ Comma separated persistence units\r\n     */\r\n    private void configurePersistenceUnit(String persistenceUnit, Map props)\r\n    {\r\n        // Invoke Persistence unit MetaData\r\n        if (persistenceUnit == null)\r\n        {\r\n            throw new KunderaException(\"Persistence unit name should not be null\");\r\n        }\r\n        if (logger.isInfoEnabled())\r\n        {\r\n            logger.info(\"Loading Persistence Unit MetaData For Persistence Unit(s) {}.\", persistenceUnit);\r\n        }\r\n\r\n        String[] persistenceUnits = persistenceUnit.split(Constants.PERSISTENCE_UNIT_SEPARATOR);\r\n\r\n        new PersistenceUnitConfiguration(props, kunderaMetadata, persistenceUnits).configure();\r\n    }\r\n\r\n    /**\r\n     * One time initialization for persistence unit metadata.\r\n     * \r\n     * @param persistenceUnit\r\n     *            Persistence Unit/ Comma separated persistence units\r\n     */\r\n    private void configurePersistenceUnit(PersistenceUnitInfo puInfo, Map props)\r\n    {\r\n        // Invoke Persistence unit MetaData\r\n        if (puInfo.getPersistenceUnitName() == null)\r\n        {\r\n            throw new KunderaException(\"Persistence unit name should not be null\");\r\n        }\r\n        if (logger.isInfoEnabled())\r\n        {\r\n            logger.info(\"Loading Persistence Unit MetaData For Persistence Unit(s) {}.\",\r\n                    puInfo.getPersistenceUnitName());\r\n        }\r\n\r\n        String[] persistenceUnits = puInfo.getPersistenceUnitName().split(Constants.PERSISTENCE_UNIT_SEPARATOR);\r\n\r\n        new PersistenceUnitConfiguration(props, kunderaMetadata, persistenceUnits).configure(puInfo);\r\n    }\r\n\r\n    @Override\r\n    public EntityManager createEntityManager(SynchronizationType paramSynchronizationType)\r\n    {\r\n        return createEntityManager();\r\n    }\r\n\r\n    @Override\r\n    public EntityManager createEntityManager(SynchronizationType paramSynchronizationType, Map paramMap)\r\n    {\r\n        return createEntityManager(paramMap);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/EntityManagerImpl.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.persistence;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.naming.Context;\r\nimport javax.naming.InitialContext;\r\nimport javax.naming.NamingException;\r\nimport javax.persistence.EntityExistsException;\r\nimport javax.persistence.EntityGraph;\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.EntityNotFoundException;\r\nimport javax.persistence.EntityTransaction;\r\nimport javax.persistence.FlushModeType;\r\nimport javax.persistence.LockModeType;\r\nimport javax.persistence.PersistenceContextType;\r\nimport javax.persistence.Query;\r\nimport javax.persistence.StoredProcedureQuery;\r\nimport javax.persistence.TransactionRequiredException;\r\nimport javax.persistence.TypedQuery;\r\nimport javax.persistence.criteria.CriteriaBuilder;\r\nimport javax.persistence.criteria.CriteriaDelete;\r\nimport javax.persistence.criteria.CriteriaQuery;\r\nimport javax.persistence.criteria.CriteriaUpdate;\r\nimport javax.persistence.metamodel.Metamodel;\r\nimport javax.persistence.spi.PersistenceUnitTransactionType;\r\nimport javax.transaction.UserTransaction;\r\n\r\nimport org.apache.commons.lang.NotImplementedException;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.Constants;\r\nimport com.impetus.kundera.KunderaException;\r\nimport com.impetus.kundera.cache.Cache;\r\nimport com.impetus.kundera.client.Client;\r\nimport com.impetus.kundera.client.ClientResolverException;\r\nimport com.impetus.kundera.loader.ClientFactory;\r\nimport com.impetus.kundera.persistence.context.PersistenceCache;\r\nimport com.impetus.kundera.persistence.jta.KunderaJTAUserTransaction;\r\nimport com.impetus.kundera.query.KunderaTypedQuery;\r\nimport com.impetus.kundera.query.QueryImpl;\r\n\r\n/**\r\n * The Class EntityManagerImpl.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class EntityManagerImpl implements EntityManager, ResourceManager\r\n{\r\n\r\n    /** The Constant log. */\r\n    private static Logger logger = LoggerFactory.getLogger(EntityManagerImpl.class);\r\n\r\n    /** The factory. */\r\n    private final EntityManagerFactory factory;\r\n\r\n    /** The closed. */\r\n    private boolean closed;\r\n\r\n    /** Flush mode for this EM, default is AUTO. */\r\n    private FlushModeType flushMode = FlushModeType.AUTO;\r\n\r\n    /** Properties provided by user at the time of EntityManager Creation. */\r\n    private Map<String, Object> properties;\r\n\r\n    /** Properties provided by user at the time of EntityManager Creation. */\r\n    private final PersistenceDelegator persistenceDelegator;\r\n\r\n    /** Persistence Context Type (Transaction/ Extended) */\r\n    private final PersistenceContextType persistenceContextType;\r\n\r\n    /** Transaction Type (JTA/ RESOURCE_LOCAL) */\r\n    private final PersistenceUnitTransactionType transactionType;\r\n\r\n    private final PersistenceCache persistenceCache;\r\n\r\n    private UserTransaction utx;\r\n\r\n    private EntityTransaction entityTransaction;\r\n\r\n    /**\r\n     * Instantiates a new entity manager impl.\r\n     * \r\n     * @param factory\r\n     *            the factory\r\n     * @param properties\r\n     *            the properties\r\n     */\r\n    EntityManagerImpl(final EntityManagerFactory factory, final Map properties, PersistenceUnitTransactionType transactionType,\r\n            final PersistenceContextType persistenceContextType)\r\n    {\r\n        this(factory, transactionType, persistenceContextType);\r\n        this.properties = properties;\r\n\r\n        getPersistenceDelegator().populateClientProperties(this.properties);\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new entity manager impl.\r\n     * \r\n     * @param factory\r\n     *            the factory\r\n     */\r\n    EntityManagerImpl(final EntityManagerFactory factory, final PersistenceUnitTransactionType transactionType,\r\n            final PersistenceContextType persistenceContextType)\r\n    {\r\n        this.factory = factory;\r\n\r\n        if (logger.isDebugEnabled())\r\n        {\r\n            logger.debug(\"Creating EntityManager for persistence unit : \" + getPersistenceUnit());\r\n        }\r\n        this.persistenceContextType = persistenceContextType;\r\n\r\n        this.persistenceCache = new PersistenceCache((Cache) factory.getCache());\r\n        this.persistenceCache.setPersistenceContextType(this.persistenceContextType);\r\n\r\n        this.transactionType = transactionType;\r\n        this.persistenceDelegator = new PersistenceDelegator(\r\n                ((EntityManagerFactoryImpl) this.factory).getKunderaMetadataInstance(), this.persistenceCache);\r\n\r\n        for (String pu : ((EntityManagerFactoryImpl) this.factory).getPersistenceUnits())\r\n        {\r\n            this.persistenceDelegator.loadClient(pu, discoverClient(pu));\r\n        }\r\n\r\n        if (logger.isDebugEnabled())\r\n        {\r\n            logger.debug(\"Created EntityManager for persistence unit : \" + getPersistenceUnit());\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Make an instance managed and persistent.\r\n     * \r\n     * @param entity\r\n     * @throws EntityExistsException\r\n     *             if the entity already exists. (If the entity already exists,\r\n     *             the EntityExistsException may be thrown when the persist\r\n     *             operation is invoked, or the EntityExistsException or another\r\n     *             PersistenceException may be thrown at flush or commit time.)\r\n     * @throws IllegalArgumentException\r\n     *             if the instance is not an entity\r\n     * @throws TransactionRequiredException\r\n     *             if invoked on a container-managed entity manager of type\r\n     *             PersistenceContextType.TRANSACTION and there is no\r\n     *             transaction\r\n     */\r\n    @Override\r\n    public final void persist(Object e)\r\n    {\r\n        checkClosed();\r\n        checkTransactionNeeded();\r\n        try\r\n        {\r\n            getPersistenceDelegator().persist(e);\r\n        }\r\n        catch (Exception ex)\r\n        {\r\n            // onRollBack.\r\n            doRollback();\r\n            throw new KunderaException(ex);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Merge the state of the given entity into the current persistence context.\r\n     * \r\n     * @param entity\r\n     * @return the managed instance that the state was merged to\r\n     * @throws IllegalArgumentException\r\n     *             if instance is not an entity or is a removed entity\r\n     * @throws TransactionRequiredException\r\n     *             if invoked on a container-managed entity manager of type\r\n     *             PersistenceContextType.TRANSACTION and there is no\r\n     *             transaction\r\n     * @see javax.persistence.EntityManager#merge(java.lang.Object)\r\n     */\r\n    @Override\r\n    public final <E> E merge(E e)\r\n    {\r\n        checkClosed();\r\n        checkTransactionNeeded();\r\n        try\r\n        {\r\n            return getPersistenceDelegator().merge(e);\r\n        }\r\n        catch (Exception ex)\r\n        {\r\n            // on Rollback\r\n            doRollback();\r\n            throw new KunderaException(ex);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Remove the entity instance.\r\n     * \r\n     * @param entity\r\n     * @throws IllegalArgumentException\r\n     *             if the instance is not an entity or is a detached entity\r\n     * @throws TransactionRequiredException\r\n     *             if invoked on a container-managed entity manager of type\r\n     *             PersistenceContextType.TRANSACTION and there is no\r\n     *             transaction\r\n     */\r\n    @Override\r\n    public final void remove(Object e)\r\n    {\r\n        checkClosed();\r\n        checkTransactionNeeded();\r\n        try\r\n        {\r\n            getPersistenceDelegator().remove(e);\r\n        }\r\n        catch (Exception ex)\r\n        {\r\n            // on rollback.\r\n            doRollback();\r\n            throw new KunderaException(ex);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Find by primary key. Search for an entity of the specified class and\r\n     * primary key. If the entity instance is contained in the persistence\r\n     * context it is returned from there.\r\n     * \r\n     * @param entityClass\r\n     * @param primaryKey\r\n     * @return the found entity instance or null if the entity does not exist\r\n     * @throws IllegalArgumentException\r\n     *             if the first argument does not denote an entity type or the\r\n     *             second argument is is not a valid type for that entity’s\r\n     *             primary key or is null\r\n     * @see javax.persistence.EntityManager#find(java.lang.Class,\r\n     *      java.lang.Object)\r\n     */\r\n\r\n    @Override\r\n    public final <E> E find(Class<E> entityClass, Object primaryKey)\r\n    {\r\n        checkClosed();\r\n        checkTransactionNeeded();\r\n        return getPersistenceDelegator().findById(entityClass, primaryKey);\r\n    }\r\n\r\n    /**\r\n     * Find by primary key, using the specified properties. Search for an entity\r\n     * of the specified class and primary key. If the entity instance is\r\n     * contained in the persistence context it is returned from there. If a\r\n     * vendor-specific property or hint is not recognized, it is silently\r\n     * ignored.\r\n     * \r\n     * @param entityClass\r\n     * @param primaryKey\r\n     * @param properties\r\n     *            standard and vendor-specific properties and hints\r\n     * @return the found entity instance or null if the entity does not exist\r\n     * @throws IllegalArgumentException\r\n     *             if the first argument does not denote an entity type or the\r\n     *             second argument is is not a valid type for that entity’s\r\n     *             primary key or is null\r\n     * @see javax.persistence.EntityManager#find(java.lang.Class,\r\n     *      java.lang.Object, java.util.Map)\r\n     */\r\n    @Override\r\n    public <T> T find(Class<T> entityClass, Object primaryKey, Map<String, Object> properties)\r\n    {\r\n        checkClosed();\r\n        checkTransactionNeeded();\r\n\r\n        // Store current properties in a variable for post-find reset\r\n        Map<String, Object> currentProperties = getProperties();\r\n\r\n        // Populate properties in client\r\n        getPersistenceDelegator().populateClientProperties(properties);\r\n        T result = find(entityClass, primaryKey);\r\n\r\n        // Reset Client properties\r\n        getPersistenceDelegator().populateClientProperties(currentProperties);\r\n        return result;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#find(java.lang.Class,\r\n     * java.lang.Object, javax.persistence.LockModeType)\r\n     */\r\n    @Override\r\n    public <T> T find(Class<T> paramClass, Object paramObject, LockModeType paramLockModeType)\r\n    {\r\n        checkClosed();\r\n        throw new NotImplementedException(\"Lock mode type currently not supported by Kundera\");\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#find(java.lang.Class,\r\n     * java.lang.Object, javax.persistence.LockModeType, java.util.Map)\r\n     */\r\n    @Override\r\n    public <T> T find(Class<T> arg0, Object arg1, LockModeType arg2, Map<String, Object> arg3)\r\n    {\r\n        checkClosed();\r\n        throw new NotImplementedException(\"Lock mode type currently not supported by Kundera\");\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#clear()\r\n     */\r\n    @Override\r\n    public final void clear()\r\n    {\r\n        checkClosed();\r\n\r\n        // TODO Do we need a client and persistenceDelegator close here?\r\n        if (!PersistenceUnitTransactionType.JTA.equals(this.transactionType))\r\n        {\r\n            getPersistenceDelegator().clear();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public final void close()\r\n    {\r\n        clear();\r\n\r\n        getPersistenceDelegator().close();\r\n\r\n        this.closed = true;\r\n    }\r\n\r\n    /**\r\n     * Check if the instance is a managed entity instance belonging to the\r\n     * current persistence context.\r\n     * \r\n     * @param entity\r\n     * @return boolean indicating if entity is in persistence context\r\n     * @throws IllegalArgumentException\r\n     *             if not an entity\r\n     * @see javax.persistence.EntityManager#contains(java.lang.Object)\r\n     */\r\n    @Override\r\n    public final boolean contains(Object entity)\r\n    {\r\n        checkClosed();\r\n\r\n        return getPersistenceDelegator().contains(entity);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#createQuery(java.lang.String)\r\n     */\r\n    @Override\r\n    public final Query createQuery(String query)\r\n    {\r\n        checkClosed();\r\n        checkTransactionNeeded();\r\n        return getPersistenceDelegator().createQuery(query);\r\n    }\r\n\r\n    @Override\r\n    public final void flush()\r\n    {\r\n        checkClosed();\r\n        getPersistenceDelegator().doFlush();\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#getDelegate()\r\n     */\r\n    @Override\r\n    public final Object getDelegate()\r\n    {\r\n        checkClosed();\r\n        return getPersistenceDelegator().getDelegate();\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#createNamedQuery(java.lang.String)\r\n     */\r\n    @Override\r\n    public final Query createNamedQuery(String name)\r\n    {\r\n        checkClosed();\r\n        checkTransactionNeeded();\r\n        return getPersistenceDelegator().createQuery(name);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#createNativeQuery(java.lang.String)\r\n     */\r\n    @Override\r\n    public final Query createNativeQuery(String sqlString)\r\n    {\r\n        checkClosed();\r\n        return getPersistenceDelegator().createQuery(sqlString, getPersistenceUnit());\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#createNativeQuery(java.lang.String,\r\n     * java.lang.Class)\r\n     */\r\n    @Override\r\n    public final Query createNativeQuery(String sqlString, Class resultClass)\r\n    {\r\n        checkClosed();\r\n        checkTransactionNeeded();\r\n\r\n        return getPersistenceDelegator().createNativeQuery(sqlString, resultClass);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#createNativeQuery(java.lang.String,\r\n     * java.lang.String)\r\n     */\r\n    @Override\r\n    public final Query createNativeQuery(String sqlString, String resultSetMapping)\r\n    {\r\n        checkClosed();\r\n        throw new NotImplementedException(\"ResultSetMapping currently not supported by Kundera. \"\r\n                + \"Please use createNativeQuery(String sqlString, Class resultClass) instead.\");\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#getReference(java.lang.Class,\r\n     * java.lang.Object)\r\n     */\r\n    @Override\r\n    public final <T> T getReference(Class<T> entityClass, Object primaryKey)\r\n    {\r\n        checkClosed();\r\n        throw new NotImplementedException(\"getReference currently not supported by Kundera\");\r\n    }\r\n\r\n    @Override\r\n    public final FlushModeType getFlushMode()\r\n    {\r\n        checkClosed();\r\n        return this.flushMode;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#getTransaction()\r\n     */\r\n    @Override\r\n    public final EntityTransaction getTransaction()\r\n    {\r\n        checkClosed();\r\n        if (this.transactionType == PersistenceUnitTransactionType.JTA)\r\n        {\r\n            throw new IllegalStateException(\"A JTA EntityManager cannot use getTransaction()\");\r\n        }\r\n\r\n        if (this.entityTransaction == null)\r\n        {\r\n            this.entityTransaction = new KunderaEntityTransaction(this);\r\n        }\r\n        return this.entityTransaction;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#joinTransaction()\r\n     */\r\n    @Override\r\n    public final void joinTransaction()\r\n    {\r\n        checkClosed();\r\n        if (this.utx != null)\r\n        {\r\n            return;\r\n        }\r\n        else\r\n        {\r\n            throw new TransactionRequiredException(\"No transaction in progress\");\r\n        }\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#lock(java.lang.Object,\r\n     * javax.persistence.LockModeType)\r\n     */\r\n    @Override\r\n    public final void lock(Object entity, LockModeType lockMode)\r\n    {\r\n        checkClosed();\r\n        throw new NotImplementedException(\"lock currently not supported by Kundera\");\r\n    }\r\n\r\n    /**\r\n     * Refresh the state of the instance from the database, overwriting changes\r\n     * made to the entity, if any.\r\n     * \r\n     * @param entity\r\n     * @throws IllegalArgumentException\r\n     *             if the instance is not an entity or the entity is not managed\r\n     * @throws TransactionRequiredException\r\n     *             if invoked on a container-managed entity manager of type\r\n     *             PersistenceContextType.TRANSACTION and there is no\r\n     *             transaction\r\n     * @throws EntityNotFoundException\r\n     *             if the entity no longer exists in the database\r\n     * @see javax.persistence.EntityManager#refresh(java.lang.Object)\r\n     */\r\n    @Override\r\n    public final void refresh(Object entity)\r\n    {\r\n        checkClosed();\r\n\r\n        checkTransactionNeeded();\r\n\r\n        getPersistenceDelegator().refresh(entity);\r\n    }\r\n\r\n    /**\r\n     * Refresh the state of the instance from the database, using the specified\r\n     * properties, and overwriting changes made to the entity, if any. If a\r\n     * vendor-specific property or hint is not recognized, it is silently\r\n     * ignored.\r\n     * \r\n     * @param entity\r\n     * @param properties\r\n     *            standard and vendor-specific properties and hints\r\n     * @throws IllegalArgumentException\r\n     *             if the instance is not an entity or the entity is not managed\r\n     * @throws TransactionRequiredException\r\n     *             if invoked on a container-managed entity manager of type\r\n     *             PersistenceContextType.TRANSACTION and there is no\r\n     *             transaction\r\n     * @throws EntityNotFoundException\r\n     *             if the entity no longer exists in the database\r\n     * @see javax.persistence.EntityManager#refresh(java.lang.Object,\r\n     *      java.util.Map)\r\n     */\r\n    @Override\r\n    public void refresh(Object entity, Map<String, Object> properties)\r\n    {\r\n        checkClosed();\r\n\r\n        // Store current properties in a variable for post-find reset\r\n        Map<String, Object> currentProperties = getProperties();\r\n\r\n        // Populate properties in client\r\n        getPersistenceDelegator().populateClientProperties(properties);\r\n\r\n        // Refresh state of entity\r\n        refresh(entity);\r\n\r\n        // Reset Client properties\r\n        getPersistenceDelegator().populateClientProperties(currentProperties);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#lock(java.lang.Object,\r\n     * javax.persistence.LockModeType, java.util.Map)\r\n     */\r\n    @Override\r\n    public void lock(Object paramObject, LockModeType paramLockModeType, Map<String, Object> paramMap)\r\n    {\r\n        checkClosed();\r\n        throw new NotImplementedException(\"Lock currently not supported by Kundera.\");\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#refresh(java.lang.Object,\r\n     * javax.persistence.LockModeType)\r\n     */\r\n    @Override\r\n    public void refresh(Object paramObject, LockModeType paramLockModeType)\r\n    {\r\n        checkClosed();\r\n        throw new NotImplementedException(\"Lock mode type currently not supported by Kundera.\");\r\n\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#refresh(java.lang.Object,\r\n     * javax.persistence.LockModeType, java.util.Map)\r\n     */\r\n    @Override\r\n    public void refresh(Object paramObject, LockModeType paramLockModeType, Map<String, Object> paramMap)\r\n    {\r\n        checkClosed();\r\n        throw new NotImplementedException(\"LockModeType currently not supported by Kundera.\");\r\n    }\r\n\r\n    /**\r\n     * Remove the given entity from the persistence context, causing a managed\r\n     * entity to become detached. Unflushed changes made to the entity if any\r\n     * (including removal of the entity), will not be synchronized to the\r\n     * database. Entities which previously referenced the detached entity will\r\n     * continue to reference it.\r\n     * \r\n     * @param entity\r\n     * @throws IllegalArgumentException\r\n     *             if the instance is not an entity\r\n     * @see javax.persistence.EntityManager#detach(java.lang.Object)\r\n     */\r\n    @Override\r\n    public void detach(Object entity)\r\n    {\r\n        checkClosed();\r\n\r\n        if (entity == null)\r\n        {\r\n            throw new IllegalArgumentException(\"Entity is null, can't detach it.\");\r\n        }\r\n        getPersistenceDelegator().detach(entity);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#getLockMode(java.lang.Object)\r\n     */\r\n    @Override\r\n    public LockModeType getLockMode(Object paramObject)\r\n    {\r\n        checkClosed();\r\n        throw new NotImplementedException(\"Lock mode type currently not supported by Kundera.\");\r\n    }\r\n\r\n    /**\r\n     * Set an entity manager property or hint. If a vendor-specific property or\r\n     * hint is not recognized, it is silently ignored.\r\n     * \r\n     * @param propertyName\r\n     *            name of property or hint\r\n     * @param value\r\n     * @throws IllegalArgumentException\r\n     *             if the second argument is not valid for the implementation\r\n     * @see javax.persistence.EntityManager#setProperty(java.lang.String,\r\n     *      java.lang.Object)\r\n     */\r\n    @Override\r\n    public void setProperty(String paramString, Object paramObject)\r\n    {\r\n        checkClosed();\r\n        if (getProperties() == null)\r\n        {\r\n            this.properties = new HashMap<String, Object>();\r\n        }\r\n\r\n        this.properties.put(paramString, paramObject);\r\n        getPersistenceDelegator().populateClientProperties(this.properties);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * javax.persistence.EntityManager#createQuery(javax.persistence.criteria\r\n     * .CriteriaQuery)\r\n     */\r\n    @Override\r\n    public <T> TypedQuery<T> createQuery(CriteriaQuery<T> paramCriteriaQuery)\r\n    {\r\n        checkClosed();\r\n\r\n        return this.createQuery(CriteriaQueryTranslator.translate(paramCriteriaQuery),\r\n                paramCriteriaQuery.getResultType());\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#createQuery(java.lang.String,\r\n     * java.lang.Class)\r\n     */\r\n    @Override\r\n    public <T> TypedQuery<T> createQuery(String paramString, Class<T> paramClass)\r\n    {\r\n        Query q = createQuery(paramString);\r\n        return onTypedQuery(paramClass, q);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#createNamedQuery(java.lang.String,\r\n     * java.lang.Class)\r\n     */\r\n    @Override\r\n    public <T> TypedQuery<T> createNamedQuery(String paramString, Class<T> paramClass)\r\n    {\r\n        Query q = createNamedQuery(paramString);\r\n        return onTypedQuery(paramClass, q);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#unwrap(java.lang.Class)\r\n     */\r\n    @Override\r\n    public <T> T unwrap(Class<T> paramClass)\r\n    {\r\n        checkClosed();\r\n        throw new NotImplementedException(\"Unwrap currently not supported by Kundera\");\r\n    }\r\n\r\n    @Override\r\n    public final void setFlushMode(FlushModeType flushMode)\r\n    {\r\n        checkClosed();\r\n        this.flushMode = flushMode;\r\n        getPersistenceDelegator().setFlushMode(flushMode);\r\n    }\r\n\r\n    /**\r\n     * Get the properties and hints and associated values that are in effect for\r\n     * the entity manager. Changing the contents of the map does not change the\r\n     * configuration in effect.\r\n     * \r\n     * @return map of properties and hints in effect\r\n     */\r\n    @Override\r\n    public Map<String, Object> getProperties()\r\n    {\r\n        checkClosed();\r\n        return this.properties;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#getEntityManagerFactory()\r\n     */\r\n    @Override\r\n    public EntityManagerFactory getEntityManagerFactory()\r\n    {\r\n        checkClosed();\r\n        return this.factory;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#getCriteriaBuilder()\r\n     */\r\n    @Override\r\n    public CriteriaBuilder getCriteriaBuilder()\r\n    {\r\n        checkClosed();\r\n        return getEntityManagerFactory().getCriteriaBuilder();\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#getMetamodel()\r\n     */\r\n    @Override\r\n    public Metamodel getMetamodel()\r\n    {\r\n        checkClosed();\r\n        return getEntityManagerFactory().getMetamodel();\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.EntityManager#isOpen()\r\n     */\r\n    @Override\r\n    public final boolean isOpen()\r\n    {\r\n        return !closed;\r\n    }\r\n\r\n    /**\r\n     * Check closed.\r\n     */\r\n    private void checkClosed()\r\n    {\r\n        if (!isOpen())\r\n        {\r\n            throw new IllegalStateException(\"EntityManager has already been closed.\");\r\n        }\r\n    }\r\n\r\n    private void checkTransactionNeeded()\r\n    {\r\n        onLookUp(transactionType);\r\n\r\n        if ((getPersistenceContextType() != PersistenceContextType.TRANSACTION)\r\n                || (getPersistenceDelegator().isTransactionInProgress()))\r\n        {\r\n            return;\r\n        }\r\n        throw new TransactionRequiredException(\r\n                \"no transaction is in progress for a TRANSACTION type persistence context\");\r\n    }\r\n\r\n    private void onLookUp(PersistenceUnitTransactionType transactionType)\r\n    {\r\n        // TODO transaction should not be null;\r\n        if (transactionType != null && transactionType.equals(PersistenceUnitTransactionType.JTA))\r\n        {\r\n            if (this.entityTransaction == null)\r\n            {\r\n                this.entityTransaction = new KunderaEntityTransaction(this);\r\n            }\r\n            Context ctx;\r\n            try\r\n            {\r\n                ctx = new InitialContext();\r\n\r\n                this.utx = (UserTransaction) ctx.lookup(\"java:comp/UserTransaction\");\r\n\r\n                if (this.utx == null)\r\n                {\r\n                    throw new KunderaException(\r\n                            \"Lookup for UserTransaction returning null for :{java:comp/UserTransaction}\");\r\n                }\r\n                // TODO what is need to check?\r\n                if (!(this.utx instanceof KunderaJTAUserTransaction))\r\n                {\r\n                    throw new KunderaException(\"Please bind [\" + KunderaJTAUserTransaction.class.getName()\r\n                            + \"] for :{java:comp/UserTransaction} lookup\" + this.utx.getClass());\r\n                }\r\n\r\n                if (!this.entityTransaction.isActive())\r\n                {\r\n                    this.entityTransaction.begin();\r\n                    this.setFlushMode(FlushModeType.COMMIT);\r\n                    ((KunderaJTAUserTransaction) this.utx).setImplementor(this);\r\n                }\r\n\r\n            }\r\n            catch (NamingException e)\r\n            {\r\n                logger.error(\"Error during initialization of entity manager, Caused by:\", e);\r\n                throw new KunderaException(e);\r\n            }\r\n\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Returns Persistence unit (or comma separated units) associated with EMF.\r\n     * \r\n     * @return the persistence unit\r\n     */\r\n    private String getPersistenceUnit()\r\n    {\r\n        return (String) getEntityManagerFactory().getProperties().get(Constants.PERSISTENCE_UNIT_NAME);\r\n    }\r\n\r\n    /**\r\n     * Gets the persistence delegator.\r\n     * \r\n     * @return the persistence delegator\r\n     */\r\n    PersistenceDelegator getPersistenceDelegator()\r\n    {\r\n        checkClosed();\r\n        return this.persistenceDelegator;\r\n    }\r\n\r\n    /**\r\n     * @return the persistenceContextType\r\n     */\r\n    private PersistenceContextType getPersistenceContextType()\r\n    {\r\n        return this.persistenceContextType;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.persistence.EntityImplementor#doCommit()\r\n     */\r\n    @Override\r\n    public void doCommit()\r\n    {\r\n        checkClosed();\r\n        this.entityTransaction.commit();\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.persistence.EntityImplementor#doRollback()\r\n     */\r\n    @Override\r\n    public void doRollback()\r\n    {\r\n        checkClosed();\r\n        if (this.entityTransaction != null)\r\n        {\r\n            this.entityTransaction.rollback();\r\n        }\r\n        else\r\n        {\r\n            getPersistenceDelegator().rollback();\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Validates if expected result class is matching with supplied one, else\r\n     * throws {@link IllegalArgumentException}\r\n     * \r\n     * @param <T>\r\n     *            object type\r\n     * @param paramClass\r\n     *            expected result class\r\n     * @param q\r\n     *            query\r\n     * @return typed query instance.\r\n     */\r\n    private <T> TypedQuery<T> onTypedQuery(Class<T> paramClass, Query q)\r\n    {\r\n        if (paramClass.equals(((QueryImpl) q).getKunderaQuery().getEntityClass()) || paramClass.equals(Object.class))\r\n        {\r\n            return new KunderaTypedQuery<T>(q);\r\n        }\r\n\r\n        throw new IllegalArgumentException(\"Mismatch in expected return type. Expected:\" + paramClass\r\n                + \" But actual class is:\" + ((QueryImpl) q).getKunderaQuery().getEntityClass());\r\n    }\r\n\r\n    /**\r\n     * Gets the client.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the persistence unit\r\n     * @return the client\r\n     */\r\n    private Client discoverClient(String persistenceUnit)\r\n    {\r\n        if (logger.isInfoEnabled())\r\n        {\r\n            logger.info(\"Returning client instance for persistence unit {}.\", persistenceUnit);\r\n        }\r\n\r\n        ClientFactory clientFactory = ((EntityManagerFactoryImpl) getEntityManagerFactory())\r\n                .getClientFactory(persistenceUnit);\r\n        if (clientFactory != null)\r\n        {\r\n            return clientFactory.getClientInstance();\r\n        }\r\n        throw new ClientResolverException(\"No client configured for persistence unit \" + persistenceUnit + \".\");\r\n    }\r\n\r\n\r\n    @Override\r\n    public <T> EntityGraph<T> createEntityGraph(Class<T> arg0)\r\n    {\r\n        // TODO Auto-generated method stub\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    public EntityGraph<?> createEntityGraph(String arg0)\r\n    {\r\n        // TODO Auto-generated method stub\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    public StoredProcedureQuery createNamedStoredProcedureQuery(String arg0)\r\n    {\r\n        // TODO Auto-generated method stub\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    public Query createQuery(CriteriaUpdate arg0)\r\n    {\r\n        // TODO Auto-generated method stub\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    public Query createQuery(CriteriaDelete arg0)\r\n    {\r\n        // TODO Auto-generated method stub\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    public StoredProcedureQuery createStoredProcedureQuery(String arg0)\r\n    {\r\n        // TODO Auto-generated method stub\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    public StoredProcedureQuery createStoredProcedureQuery(String arg0, Class... arg1)\r\n    {\r\n        // TODO Auto-generated method stub\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    public StoredProcedureQuery createStoredProcedureQuery(String arg0, String... arg1)\r\n    {\r\n        // TODO Auto-generated method stub\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    public EntityGraph<?> getEntityGraph(String arg0)\r\n    {\r\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\r\n        // Do nothing. Not yet implemented.\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> arg0)\r\n    {\r\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\r\n        // Do nothing. Not yet implemented.\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    public boolean isJoinedToTransaction()\r\n    {\r\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\r\n        // Do nothing. Not yet implemented.\r\n        return false;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/EntityManagerSession.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.persistence;\r\n\r\nimport java.util.Map;\r\nimport java.util.concurrent.ConcurrentHashMap;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.cache.Cache;\r\n\r\n/**\r\n * The Class EntityManagerSession.\r\n */\r\npublic class EntityManagerSession\r\n{\r\n\r\n    /** The Constant log. */\r\n    private static final Logger LOG = LoggerFactory.getLogger(EntityManagerSession.class);\r\n\r\n    /** cache is used to store objects retrieved in this EntityManager session. */\r\n    private Map<Object, Object> sessionCache;\r\n\r\n    /** The l2 cache. */\r\n    private Cache l2Cache; // L2 Cache\r\n\r\n    /**\r\n     * Instantiates a new entity manager cache.\r\n     * \r\n     * @param cache\r\n     *            the cache\r\n     */\r\n    public EntityManagerSession(Cache cache)\r\n    {\r\n        this.sessionCache = new ConcurrentHashMap<Object, Object>();\r\n        setL2Cache(cache);\r\n    }\r\n\r\n    /**\r\n     * Find in cache.\r\n     * \r\n     * @param <T>\r\n     *            the generic type\r\n     * @param entityClass\r\n     *            the entity class\r\n     * @param id\r\n     *            the id\r\n     * @return the t\r\n     */\r\n    @SuppressWarnings(\"unchecked\")\r\n    protected <T> T lookup(Class<T> entityClass, Object id)\r\n    {\r\n        String key = cacheKey(entityClass, id);\r\n        LOG.debug(\"Reading from L1 >> \" + key);\r\n        T o = (T) sessionCache.get(key);\r\n\r\n        // go to second-level cache\r\n        if (o == null)\r\n        {\r\n            LOG.debug(\"Reading from L2 >> \" + key);\r\n            Cache c = (Cache) getL2Cache();\r\n            if (c != null)\r\n            {\r\n                o = (T) c.get(key);\r\n                if (o != null)\r\n                {\r\n                    LOG.debug(\"Found item in second level cache!\");\r\n                }\r\n            }\r\n        }\r\n        return o;\r\n    }\r\n\r\n    /**\r\n     * Store in L1 only.\r\n     * \r\n     * @param id\r\n     *            the id\r\n     * @param entity\r\n     *            the entity\r\n     */\r\n    protected void store(Object id, Object entity)\r\n    {\r\n        store(id, entity, Boolean.TRUE);\r\n    }\r\n\r\n    /**\r\n     * Save to cache.\r\n     * \r\n     * @param id\r\n     *            the id\r\n     * @param entity\r\n     *            the entity\r\n     * @param spillOverToL2\r\n     *            the spill over to l2\r\n     */\r\n    protected void store(Object id, Object entity, boolean spillOverToL2)\r\n    {\r\n        String key = cacheKey(entity.getClass(), id);\r\n        LOG.debug(\"Writing to L1 >> \" + key);\r\n        sessionCache.put(key, entity);\r\n\r\n        if (spillOverToL2)\r\n        {\r\n            LOG.debug(\"Writing to L2 >>\" + key);\r\n            // save to second level cache\r\n            Cache c = (Cache) getL2Cache();\r\n            if (c != null)\r\n            {\r\n                c.put(key, entity);\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Removes the.\r\n     * \r\n     * @param <T>\r\n     *            the generic type\r\n     * @param entityClass\r\n     *            the entity class\r\n     * @param id\r\n     *            the id\r\n     */\r\n    protected <T> void remove(Class<T> entityClass, Object id)\r\n    {\r\n        remove(entityClass, id, Boolean.TRUE);\r\n    }\r\n\r\n    /**\r\n     * Removes the from cache.\r\n     * \r\n     * @param <T>\r\n     *            the generic type\r\n     * @param entityClass\r\n     *            the entity class\r\n     * @param id\r\n     *            the id\r\n     * @param spillOverToL2\r\n     *            the spill over to l2\r\n     */\r\n    protected <T> void remove(Class<T> entityClass, Object id, boolean spillOverToL2)\r\n    {\r\n        String key = cacheKey(entityClass, id);\r\n        LOG.debug(\"Removing from L1 >> \" + key);\r\n        Object o = sessionCache.remove(key);\r\n\r\n        if (spillOverToL2)\r\n        {\r\n            LOG.debug(\"Removing from L2 >> \" + key);\r\n            Cache c = (Cache) getL2Cache();\r\n            if (c != null)\r\n            {\r\n                c.evict(entityClass, key);\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Cache key.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     * @param id\r\n     *            the id\r\n     * \r\n     * @return the string\r\n     */\r\n    private String cacheKey(Class<?> clazz, Object id)\r\n    {\r\n        return clazz.getName() + \"_\" + id;\r\n    }\r\n\r\n    /**\r\n     * Clear.\r\n     */\r\n    public final void clear()\r\n    {\r\n        sessionCache = new ConcurrentHashMap<Object, Object>();\r\n\r\n        // Clear L2 Cahce\r\n        if (getL2Cache() != null)\r\n        {\r\n            getL2Cache().evictAll();\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Gets the l2 cache.\r\n     * \r\n     * @return the l2Cache\r\n     */\r\n    public Cache getL2Cache()\r\n    {\r\n        return l2Cache;\r\n    }\r\n\r\n    /**\r\n     * Sets the l2 cache.\r\n     * \r\n     * @param l2Cache\r\n     *            the l2Cache to set\r\n     */\r\n    public void setL2Cache(Cache l2Cache)\r\n    {\r\n        this.l2Cache = l2Cache;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/EntityReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\n\n/**\n * The Interface EntityReader.\n * \n * @author vivek.mishra\n * \n *         Interface to provide declarations for methods responsible for entity\n *         read operations.(Except queries).\n */\npublic interface EntityReader\n{\n\n    /**\n     * Method responsible for reading back entity and relations using secondary\n     * indexes(if it holds any relation), else retrieve row keys using lucene.\n     * \n     * @param m\n     *            entity meta data\n     * @param relationNames\n     *            relation names\n     * @param isParent\n     *            if entity is not holding any relation.\n     * @param client\n     *            client instance\n     * @return list of wrapped enhance entities.\n     */\n    List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults);\n\n    /**\n     * Returns populated entity along with all relational value.\n     * \n     * @param e\n     *            enhance entity\n     * @param graphs\n     *            entity graph\n     * @param collectionHolder\n     *            collection holder.\n     * @param client\n     *            client\n     * @param m\n     *            entity meta data\n     * @param relationStack \n     * @param persistenceDelegeator\n     *            persistence delegator.\n     * @param lazily loaded. true if invoked over lazily fetched object.           \n     * @return populate entity.\n     * @throws Exception\n     *             the exception\n     */\n\n    Object recursivelyFindEntities(Object entity, Map<String, Object> relationsMap, EntityMetadata m,\n            PersistenceDelegator pd, boolean lazilyLoaded, Map<Object, Object> relationStack);\n\n    /**\n     * Find by id.\n     * \n     * @param primaryKey\n     *            the primary key\n     * @param m\n     *            the m\n     * @param relationNames\n     *            the relation names\n     * @param client\n     *            the client\n     * @return the enhance entity\n     */\n    EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client);\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/EntityReaderException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * @author amresh\n * \n */\npublic class EntityReaderException extends KunderaException\n{\n\n    /**\n     * \n     */\n    public EntityReaderException()\n    {\n        super();\n    }\n\n    /**\n     * @param arg0\n     */\n    public EntityReaderException(String arg0)\n    {\n        super(arg0);\n    }\n\n    /**\n     * @param arg0\n     */\n    public EntityReaderException(Throwable arg0)\n    {\n        super(arg0);\n    }\n\n    /**\n     * @param arg0\n     * @param arg1\n     */\n    public EntityReaderException(String arg0, Throwable arg1)\n    {\n        super(arg0, arg1);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/IdGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport javax.persistence.GenerationType;\nimport javax.persistence.metamodel.Metamodel;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.generator.AutoGenerator;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.generator.SequenceGenerator;\nimport com.impetus.kundera.generator.TableGenerator;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.IdDiscriptor;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * Generate id for entity when {@GeneratedValue} annotation\n * given.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class IdGenerator\n{\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(IdGenerator.class);\n\n    public Object generateAndSetId(Object e, EntityMetadata m, PersistenceDelegator pd,\n            final KunderaMetadata kunderaMetadata)\n    {\n        Metamodel metamodel = KunderaMetadataManager.getMetamodel(kunderaMetadata, m.getPersistenceUnit());\n        Client<?> client = pd.getClient(m);\n        return generateId(e, m, client, kunderaMetadata);\n    }\n\n    private Object generateId(Object e, EntityMetadata m, Client<?> client, final KunderaMetadata kunderaMetadata)\n    {\n        Metamodel metamodel = KunderaMetadataManager.getMetamodel(kunderaMetadata, m.getPersistenceUnit());\n        IdDiscriptor keyValue = ((MetamodelImpl) metamodel).getKeyValue(e.getClass().getName());\n\n        if (keyValue != null)\n        {\n\n            if (!client.getQueryImplementor().getSimpleName().equalsIgnoreCase(\"RDBMSQuery\"))\n            {\n                if (client != null)\n                {\n                    GenerationType type = keyValue.getStrategy();\n                    switch (type)\n                    {\n                    case TABLE:\n                        return onTableGenerator(m, client, keyValue, e);\n                    case SEQUENCE:\n                        return onSequenceGenerator(m, client, keyValue, e);\n                    case AUTO:\n                        return onAutoGenerator(m, client, e);\n                    case IDENTITY:\n                        throw new UnsupportedOperationException(GenerationType.class.getSimpleName() + \".\" + type\n                                + \" Strategy not supported by this client :\" + client.getClass().getName());\n                    }\n                }\n            }\n            else\n            {\n                int hashCode = e.hashCode();\n                Object generatedId = PropertyAccessorHelper.fromSourceToTargetClass(m.getIdAttribute().getJavaType(),\n                        Integer.class, new Integer(hashCode));\n                PropertyAccessorHelper.setId(e, m, generatedId);\n                return generatedId;\n            }\n        }\n\n        return null;\n    }\n\n    /**\n     * Generate Id when given auto generation strategy.\n     * \n     * @param m\n     * @param client\n     * @param e\n     * @param kunderaMetadata\n     */\n    private Object onAutoGenerator(EntityMetadata m, Client<?> client, Object e)\n    {\n        Object autogenerator = getAutoGenClazz(client);\n        \n        if (autogenerator instanceof AutoGenerator)\n        {\n            \n            Object generatedId = ((AutoGenerator)autogenerator).generate(client, m.getIdAttribute().getJavaType().getSimpleName());\n            try\n            {\n                generatedId = PropertyAccessorHelper.fromSourceToTargetClass(m.getIdAttribute().getJavaType(),\n                        generatedId.getClass(), generatedId);\n                PropertyAccessorHelper.setId(e, m, generatedId);\n                return generatedId;\n            }\n            catch (IllegalArgumentException iae)\n            {\n                log.error(\"Unknown data type for ids : \" + m.getIdAttribute().getJavaType());\n                throw new KunderaException(\"Unknown data type for ids : \" + m.getIdAttribute().getJavaType(), iae);\n            }\n        }\n        throw new IllegalArgumentException(GenerationType.class.getSimpleName() + \".\" + GenerationType.AUTO\n                + \" Strategy not supported by this client :\" + client.getClass().getName());\n    }\n\n    private Generator getAutoGenClazz(Client<?> client)\n    {\n        Generator autoGenerator = null;\n        String autoGen = ((ClientBase)client).getAutoGenerator();\n        if (null != autoGen)\n        {\n            Class autogenClazz;\n            try\n            {\n                autogenClazz = Class.forName(autoGen);\n                autoGenerator = (Generator) (KunderaCoreUtils.createNewInstance(autogenClazz));\n            }\n            catch (ClassNotFoundException cnfe)\n            {\n                log.error(\"The autogen custom class is invalid\");\n                throw new KunderaException(\"The autogen custom class should implement AutoGenerator class\", cnfe);\n            }\n\n        }\n        else\n        {\n\n            autoGenerator = ((Generator) client.getIdGenerator());\n\n        }\n        return autoGenerator;\n    }\n\n    /**\n     * Generate Id when given sequence generation strategy.\n     * \n     * @param m\n     * @param client\n     * @param keyValue\n     * @param e\n     */\n    private Object onSequenceGenerator(EntityMetadata m, Client<?> client, IdDiscriptor keyValue, Object e)\n    {\n        Object seqgenerator = getAutoGenClazz(client);\n        if (seqgenerator instanceof SequenceGenerator)\n        {\n            Object generatedId = ((SequenceGenerator) seqgenerator).generate(\n                    keyValue.getSequenceDiscriptor(), client, m.getIdAttribute().getJavaType().getSimpleName());\n            try\n            {\n                generatedId = PropertyAccessorHelper.fromSourceToTargetClass(m.getIdAttribute().getJavaType(),\n                        generatedId.getClass(), generatedId);\n                PropertyAccessorHelper.setId(e, m, generatedId);\n                return generatedId;\n            }\n            catch (IllegalArgumentException iae)\n            {\n                log.error(\"Unknown integral data type for ids : \" + m.getIdAttribute().getJavaType());\n                throw new KunderaException(\"Unknown integral data type for ids : \" + m.getIdAttribute().getJavaType(),\n                        iae);\n            }\n        }\n        throw new IllegalArgumentException(GenerationType.class.getSimpleName() + \".\" + GenerationType.SEQUENCE\n                + \" Strategy not supported by this client :\" + client.getClass().getName());\n    }\n\n    /**\n     * Generate Id when given table generation strategy.\n     * \n     * @param m\n     * @param client\n     * @param keyValue\n     * @param e\n     */\n    private Object onTableGenerator(EntityMetadata m, Client<?> client, IdDiscriptor keyValue, Object e)\n    {\n        Object tablegenerator = getAutoGenClazz(client);   \n        if (tablegenerator instanceof TableGenerator)\n        {\n            Object generatedId = ((TableGenerator) tablegenerator).generate(keyValue.getTableDiscriptor(),\n                    (ClientBase) client, m.getIdAttribute().getJavaType().getSimpleName());\n            try\n            {\n                generatedId = PropertyAccessorHelper.fromSourceToTargetClass(m.getIdAttribute().getJavaType(),\n                        generatedId.getClass(), generatedId);\n                PropertyAccessorHelper.setId(e, m, generatedId);\n                return generatedId;\n            }\n            catch (IllegalArgumentException iae)\n            {\n                log.error(\"Unknown integral data type for ids : \" + m.getIdAttribute().getJavaType());\n                throw new KunderaException(\"Unknown integral data type for ids : \" + m.getIdAttribute().getJavaType(),\n                        iae);\n            }\n        }\n        throw new IllegalArgumentException(GenerationType.class.getSimpleName() + \".\" + GenerationType.TABLE\n                + \" Strategy not supported by this client :\" + client.getClass().getName());\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/KunderaCriteriaBuilder.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.sql.Date;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Tuple;\nimport javax.persistence.criteria.CollectionJoin;\nimport javax.persistence.criteria.CompoundSelection;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaDelete;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.CriteriaUpdate;\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Join;\nimport javax.persistence.criteria.ListJoin;\nimport javax.persistence.criteria.MapJoin;\nimport javax.persistence.criteria.Order;\nimport javax.persistence.criteria.ParameterExpression;\nimport javax.persistence.criteria.Path;\nimport javax.persistence.criteria.Predicate;\nimport javax.persistence.criteria.Root;\nimport javax.persistence.criteria.Selection;\nimport javax.persistence.criteria.SetJoin;\nimport javax.persistence.criteria.Subquery;\nimport javax.persistence.metamodel.Metamodel;\n\nimport com.impetus.kundera.persistence.AbstractPredicate.ConditionalOperator;\nimport com.impetus.kundera.query.KunderaQuery.SortOrder;\n\n/**\n * Implements criteria builder {@link CriteriaBuilder}.\n * \n * @author vivek.mishra\n * \n */\npublic class KunderaCriteriaBuilder implements CriteriaBuilder\n{\n\n    private EntityManagerFactory entityManagerFactory;\n\n    KunderaCriteriaBuilder(EntityManagerFactory entityManagerFactory)\n    {\n        this.entityManagerFactory = entityManagerFactory;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#abs(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public <N extends Number> Expression<N> abs(Expression<N> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#all(javax.persistence.criteria\n     * .Subquery)\n     */\n    @Override\n    public <Y> Expression<Y> all(Subquery<Y> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#and(javax.persistence.criteria\n     * .Predicate[])\n     */\n    @Override\n    public Predicate and(Predicate... predicates)\n    {\n        return new ConjuctionPredicate(predicates);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#and(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate and(Expression<Boolean> arg0, Expression<Boolean> arg1)\n    {\n        if (arg0 != null && arg1 != null)\n        {\n           return new ConjuctionPredicate((Predicate)arg0, (Predicate)arg1);\n        }\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#any(javax.persistence.criteria\n     * .Subquery)\n     */\n    @Override\n    public <Y> Expression<Y> any(Subquery<Y> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    \n    CompoundSelection array( Class resultClazz, Selection<?>... arg0)\n    {\n        return new DefaultCompoundSelection(Arrays.asList(arg0), resultClazz);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#array(javax.persistence.criteria\n     * .Selection<?>[])\n     */\n    @Override\n    public CompoundSelection<Object[]> array(Selection<?>... arg0)\n    {\n        return new DefaultCompoundSelection<Object[]>(Arrays.asList(arg0), Object.class);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#asc(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public Order asc(Expression<?> arg0)\n    {\n        return new QueryOrder(arg0, SortOrder.ASC);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#avg(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public <N extends Number> Expression<Double> avg(Expression<N> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#between(javax.persistence.\n     * criteria.Expression, javax.persistence.criteria.Expression,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <Y extends Comparable<? super Y>> Predicate between(Expression<? extends Y> arg0,\n            Expression<? extends Y> arg1, Expression<? extends Y> arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#between(javax.persistence.\n     * criteria.Expression, java.lang.Comparable, java.lang.Comparable)\n     */\n    @Override\n    public <Y extends Comparable<? super Y>> Predicate between(Expression<? extends Y> arg0, Y arg1, Y arg2)\n    {\n        return new BetweenPredicate(arg0,arg1,arg2);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#coalesce()\n     */\n    @Override\n    public <T> Coalesce<T> coalesce()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#coalesce(javax.persistence\n     * .criteria.Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <Y> Expression<Y> coalesce(Expression<? extends Y> arg0, Expression<? extends Y> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#coalesce(javax.persistence\n     * .criteria.Expression, java.lang.Object)\n     */\n    @Override\n    public <Y> Expression<Y> coalesce(Expression<? extends Y> arg0, Y arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#concat(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<String> concat(Expression<String> arg0, Expression<String> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#concat(javax.persistence.criteria\n     * .Expression, java.lang.String)\n     */\n    @Override\n    public Expression<String> concat(Expression<String> arg0, String arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#concat(java.lang.String,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<String> concat(String arg0, Expression<String> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#conjunction()\n     */\n    @Override\n    public Predicate conjunction()\n    {\n        return new ConjuctionPredicate();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#construct(java.lang.Class,\n     * javax.persistence.criteria.Selection<?>[])\n     */\n    @Override\n    public <Y> CompoundSelection<Y> construct(Class<Y> arg0, Selection<?>... arg1)\n    {\n        return new DefaultCompoundSelection<Y>(Arrays.asList(arg1), arg0);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#count(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public Expression<Long> count(Expression<?> arg0)\n    {\n        // TODO Auto-generated method stub\n        String arg1 = \"Count(\"+arg0.getAlias()+\")\";\n        return new AggregateExpression(arg0, arg1);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#countDistinct(javax.persistence\n     * .criteria.Expression)\n     */\n    @Override\n    public Expression<Long> countDistinct(Expression<?> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#createQuery()\n     */\n    @Override\n    public CriteriaQuery<Object> createQuery()\n    {\n        return new KunderaCritieriaQuery<Object>(this);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#createQuery(java.lang.Class)\n     */\n    @Override\n    public <T> CriteriaQuery<T> createQuery(Class<T> returnClazz)\n    {\n        return new KunderaCritieriaQuery<T>(this, returnClazz);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#createTupleQuery()\n     */\n    @Override\n    public CriteriaQuery<Tuple> createTupleQuery()\n    {\n        return new KunderaCritieriaQuery<Tuple>(this, Tuple.class);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#currentDate()\n     */\n    @Override\n    public Expression<Date> currentDate()\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#currentTime()\n     */\n    @Override\n    public Expression<Time> currentTime()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#currentTimestamp()\n     */\n    @Override\n    public Expression<Timestamp> currentTimestamp()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#desc(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public Order desc(Expression<?> arg0)\n    {\n        return new QueryOrder(arg0, SortOrder.DESC);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#diff(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <N extends Number> Expression<N> diff(Expression<? extends N> arg0, Expression<? extends N> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#diff(javax.persistence.criteria\n     * .Expression, java.lang.Number)\n     */\n    @Override\n    public <N extends Number> Expression<N> diff(Expression<? extends N> arg0, N arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#diff(java.lang.Number,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <N extends Number> Expression<N> diff(N arg0, Expression<? extends N> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#disjunction()\n     */\n    @Override\n    public Predicate disjunction()\n    {\n        return new DisjunctionPredicate();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#equal(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate equal(Expression<?> lhs, Expression<?> rhs)\n    {\n        return new ComparisonPredicate(lhs, rhs, ConditionalOperator.EQ);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#equal(javax.persistence.criteria\n     * .Expression, java.lang.Object)\n     */\n    @Override\n    public Predicate equal(Expression<?> lhs, Object rhs)\n    {\n        return new ComparisonPredicate(lhs, rhs, ConditionalOperator.EQ);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#exists(javax.persistence.criteria\n     * .Subquery)\n     */\n    @Override\n    public Predicate exists(Subquery<?> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#function(java.lang.String,\n     * java.lang.Class, javax.persistence.criteria.Expression<?>[])\n     */\n    @Override\n    public <T> Expression<T> function(String arg0, Class<T> arg1, Expression<?>... arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#ge(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate ge(Expression<? extends Number> arg0, Expression<? extends Number> arg1)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#ge(javax.persistence.criteria\n     * .Expression, java.lang.Number)\n     */\n    @Override\n    public Predicate ge(Expression<? extends Number> arg0, Number arg1)\n    {\n        // TODO Auto-generated method stub\n        return new ComparisonPredicate(arg0, arg1, ConditionalOperator.GTE);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#greaterThan(javax.persistence\n     * .criteria.Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <Y extends Comparable<? super Y>> Predicate greaterThan(Expression<? extends Y> lhs,\n            Expression<? extends Y> rhs)\n    {\n\n        return new ComparisonPredicate(lhs, rhs, ConditionalOperator.GT);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#greaterThan(javax.persistence\n     * .criteria.Expression, java.lang.Comparable)\n     */\n    @Override\n    public <Y extends Comparable<? super Y>> Predicate greaterThan(Expression<? extends Y> lhs, Y rhs)\n    {\n        return new ComparisonPredicate(lhs, rhs, ConditionalOperator.GT);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#greaterThanOrEqualTo(javax\n     * .persistence.criteria.Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <Y extends Comparable<? super Y>> Predicate greaterThanOrEqualTo(Expression<? extends Y> lhs,\n            Expression<? extends Y> rhs)\n    {\n        return new ComparisonPredicate(lhs, rhs, ConditionalOperator.GTE);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#greaterThanOrEqualTo(javax\n     * .persistence.criteria.Expression, java.lang.Comparable)\n     */\n    @Override\n    public <Y extends Comparable<? super Y>> Predicate greaterThanOrEqualTo(Expression<? extends Y> lhs, Y rhs)\n    {\n        return new ComparisonPredicate(lhs, rhs, ConditionalOperator.GTE);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#greatest(javax.persistence\n     * .criteria.Expression)\n     */\n    @Override\n    public <X extends Comparable<? super X>> Expression<X> greatest(Expression<X> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#gt(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate gt(Expression<? extends Number> arg0, Expression<? extends Number> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#gt(javax.persistence.criteria\n     * .Expression, java.lang.Number)\n     */\n    @Override\n    public Predicate gt(Expression<? extends Number> lhs, Number rhs)\n    {\n        return new ComparisonPredicate(lhs, rhs, ConditionalOperator.GT);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#in(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public <T> In<T> in(Expression<? extends T> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#isEmpty(javax.persistence.\n     * criteria.Expression)\n     */\n    @Override\n    public <C extends Collection<?>> Predicate isEmpty(Expression<C> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#isFalse(javax.persistence.\n     * criteria.Expression)\n     */\n    @Override\n    public Predicate isFalse(Expression<Boolean> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#isMember(javax.persistence\n     * .criteria.Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <E, C extends Collection<E>> Predicate isMember(Expression<E> arg0, Expression<C> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#isMember(java.lang.Object,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <E, C extends Collection<E>> Predicate isMember(E arg0, Expression<C> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#isNotEmpty(javax.persistence\n     * .criteria.Expression)\n     */\n    @Override\n    public <C extends Collection<?>> Predicate isNotEmpty(Expression<C> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#isNotMember(javax.persistence\n     * .criteria.Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <E, C extends Collection<E>> Predicate isNotMember(Expression<E> arg0, Expression<C> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#isNotMember(java.lang.Object,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <E, C extends Collection<E>> Predicate isNotMember(E arg0, Expression<C> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#isNotNull(javax.persistence\n     * .criteria.Expression)\n     */\n    @Override\n    public Predicate isNotNull(Expression<?> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#isNull(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public Predicate isNull(Expression<?> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#isTrue(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public Predicate isTrue(Expression<Boolean> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#keys(java.util.Map)\n     */\n    @Override\n    public <K, M extends Map<K, ?>> Expression<Set<K>> keys(M arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#le(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate le(Expression<? extends Number> arg0, Expression<? extends Number> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#le(javax.persistence.criteria\n     * .Expression, java.lang.Number)\n     */\n    @Override\n    public Predicate le(Expression<? extends Number> arg0, Number arg1)\n    {\n        // TODO Auto-generated method stub\n        return new ComparisonPredicate(arg0, arg1, ConditionalOperator.LTE);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#least(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public <X extends Comparable<? super X>> Expression<X> least(Expression<X> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#length(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public Expression<Integer> length(Expression<String> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#lessThan(javax.persistence\n     * .criteria.Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <Y extends Comparable<? super Y>> Predicate lessThan(Expression<? extends Y> arg0,\n            Expression<? extends Y> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#lessThan(javax.persistence\n     * .criteria.Expression, java.lang.Comparable)\n     */\n    @Override\n    public <Y extends Comparable<? super Y>> Predicate lessThan(Expression<? extends Y> arg0, Y arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#lessThanOrEqualTo(javax.\n     * persistence.criteria.Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <Y extends Comparable<? super Y>> Predicate lessThanOrEqualTo(Expression<? extends Y> arg0,\n            Expression<? extends Y> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#lessThanOrEqualTo(javax.\n     * persistence.criteria.Expression, java.lang.Comparable)\n     */\n    @Override\n    public <Y extends Comparable<? super Y>> Predicate lessThanOrEqualTo(Expression<? extends Y> arg0, Y arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#like(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate like(Expression<String> arg0, Expression<String> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#like(javax.persistence.criteria\n     * .Expression, java.lang.String)\n     */\n    @Override\n    public Predicate like(Expression<String> arg0, String arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#like(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate like(Expression<String> arg0, Expression<String> arg1, Expression<Character> arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#like(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression, char)\n     */\n    @Override\n    public Predicate like(Expression<String> arg0, Expression<String> arg1, char arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#like(javax.persistence.criteria\n     * .Expression, java.lang.String, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate like(Expression<String> arg0, String arg1, Expression<Character> arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#like(javax.persistence.criteria\n     * .Expression, java.lang.String, char)\n     */\n    @Override\n    public Predicate like(Expression<String> arg0, String arg1, char arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#literal(java.lang.Object)\n     */\n    @Override\n    public <T> Expression<T> literal(T arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#locate(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<Integer> locate(Expression<String> arg0, Expression<String> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#locate(javax.persistence.criteria\n     * .Expression, java.lang.String)\n     */\n    @Override\n    public Expression<Integer> locate(Expression<String> arg0, String arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#locate(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<Integer> locate(Expression<String> arg0, Expression<String> arg1, Expression<Integer> arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#locate(javax.persistence.criteria\n     * .Expression, java.lang.String, int)\n     */\n    @Override\n    public Expression<Integer> locate(Expression<String> arg0, String arg1, int arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#lower(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public Expression<String> lower(Expression<String> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#lt(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate lt(Expression<? extends Number> arg0, Expression<? extends Number> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#lt(javax.persistence.criteria\n     * .Expression, java.lang.Number)\n     */\n    @Override\n    public Predicate lt(Expression<? extends Number> arg0, Number arg1)\n    {\n        return new ComparisonPredicate(arg0, arg1, ConditionalOperator.LT);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#max(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public <N extends Number> Expression<N> max(Expression<N> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#min(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public <N extends Number> Expression<N> min(Expression<N> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#mod(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<Integer> mod(Expression<Integer> arg0, Expression<Integer> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#mod(javax.persistence.criteria\n     * .Expression, java.lang.Integer)\n     */\n    @Override\n    public Expression<Integer> mod(Expression<Integer> arg0, Integer arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#mod(java.lang.Integer,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<Integer> mod(Integer arg0, Expression<Integer> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#neg(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public <N extends Number> Expression<N> neg(Expression<N> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#not(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public Predicate not(Expression<Boolean> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#notEqual(javax.persistence\n     * .criteria.Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate notEqual(Expression<?> arg0, Expression<?> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#notEqual(javax.persistence\n     * .criteria.Expression, java.lang.Object)\n     */\n    @Override\n    public Predicate notEqual(Expression<?> arg0, Object arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#notLike(javax.persistence.\n     * criteria.Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate notLike(Expression<String> arg0, Expression<String> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#notLike(javax.persistence.\n     * criteria.Expression, java.lang.String)\n     */\n    @Override\n    public Predicate notLike(Expression<String> arg0, String arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#notLike(javax.persistence.\n     * criteria.Expression, javax.persistence.criteria.Expression,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate notLike(Expression<String> arg0, Expression<String> arg1, Expression<Character> arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#notLike(javax.persistence.\n     * criteria.Expression, javax.persistence.criteria.Expression, char)\n     */\n    @Override\n    public Predicate notLike(Expression<String> arg0, Expression<String> arg1, char arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#notLike(javax.persistence.\n     * criteria.Expression, java.lang.String,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate notLike(Expression<String> arg0, String arg1, Expression<Character> arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#notLike(javax.persistence.\n     * criteria.Expression, java.lang.String, char)\n     */\n    @Override\n    public Predicate notLike(Expression<String> arg0, String arg1, char arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#nullLiteral(java.lang.Class)\n     */\n    @Override\n    public <T> Expression<T> nullLiteral(Class<T> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#nullif(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <Y> Expression<Y> nullif(Expression<Y> arg0, Expression<?> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#nullif(javax.persistence.criteria\n     * .Expression, java.lang.Object)\n     */\n    @Override\n    public <Y> Expression<Y> nullif(Expression<Y> arg0, Y arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#or(javax.persistence.criteria\n     * .Predicate[])\n     */\n    @Override\n    public Predicate or(Predicate... predicates)\n    {\n        return new DisjunctionPredicate(predicates);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#or(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Predicate or(Expression<Boolean> arg0, Expression<Boolean> arg1)\n    {\n        // TODO Auto-generated method stub\n        if (arg0 != null && arg1 != null)\n        {\n            if (arg0.getClass().isAssignableFrom(ComparisonPredicate.class) && arg1.getClass().isAssignableFrom(ComparisonPredicate.class))\n            {\n                return new DisjunctionPredicate((Predicate)arg0, (Predicate)arg1);\n            }\n        }\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#parameter(java.lang.Class)\n     */\n    @Override\n    public <T> ParameterExpression<T> parameter(Class<T> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#parameter(java.lang.Class,\n     * java.lang.String)\n     */\n    @Override\n    public <T> ParameterExpression<T> parameter(Class<T> arg0, String arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#prod(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <N extends Number> Expression<N> prod(Expression<? extends N> arg0, Expression<? extends N> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#prod(javax.persistence.criteria\n     * .Expression, java.lang.Number)\n     */\n    @Override\n    public <N extends Number> Expression<N> prod(Expression<? extends N> arg0, N arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#prod(java.lang.Number,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <N extends Number> Expression<N> prod(N arg0, Expression<? extends N> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#quot(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<Number> quot(Expression<? extends Number> arg0, Expression<? extends Number> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#quot(javax.persistence.criteria\n     * .Expression, java.lang.Number)\n     */\n    @Override\n    public Expression<Number> quot(Expression<? extends Number> arg0, Number arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#quot(java.lang.Number,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<Number> quot(Number arg0, Expression<? extends Number> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#selectCase()\n     */\n    @Override\n    public <R> Case<R> selectCase()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#selectCase(javax.persistence\n     * .criteria.Expression)\n     */\n    @Override\n    public <C, R> SimpleCase<C, R> selectCase(Expression<? extends C> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#size(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public <C extends Collection<?>> Expression<Integer> size(Expression<C> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#size(java.util.Collection)\n     */\n    @Override\n    public <C extends Collection<?>> Expression<Integer> size(C arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#some(javax.persistence.criteria\n     * .Subquery)\n     */\n    @Override\n    public <Y> Expression<Y> some(Subquery<Y> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#sqrt(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public Expression<Double> sqrt(Expression<? extends Number> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#substring(javax.persistence\n     * .criteria.Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<String> substring(Expression<String> arg0, Expression<Integer> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#substring(javax.persistence\n     * .criteria.Expression, int)\n     */\n    @Override\n    public Expression<String> substring(Expression<String> arg0, int arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#substring(javax.persistence\n     * .criteria.Expression, javax.persistence.criteria.Expression,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<String> substring(Expression<String> arg0, Expression<Integer> arg1, Expression<Integer> arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#substring(javax.persistence\n     * .criteria.Expression, int, int)\n     */\n    @Override\n    public Expression<String> substring(Expression<String> arg0, int arg1, int arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#sum(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public <N extends Number> Expression<N> sum(Expression<N> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#sum(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <N extends Number> Expression<N> sum(Expression<? extends N> arg0, Expression<? extends N> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#sum(javax.persistence.criteria\n     * .Expression, java.lang.Number)\n     */\n    @Override\n    public <N extends Number> Expression<N> sum(Expression<? extends N> arg0, N arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#sum(java.lang.Number,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public <N extends Number> Expression<N> sum(N arg0, Expression<? extends N> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#sumAsDouble(javax.persistence\n     * .criteria.Expression)\n     */\n    @Override\n    public Expression<Double> sumAsDouble(Expression<Float> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#sumAsLong(javax.persistence\n     * .criteria.Expression)\n     */\n    @Override\n    public Expression<Long> sumAsLong(Expression<Integer> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#toBigDecimal(javax.persistence\n     * .criteria.Expression)\n     */\n    @Override\n    public Expression<BigDecimal> toBigDecimal(Expression<? extends Number> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#toBigInteger(javax.persistence\n     * .criteria.Expression)\n     */\n    @Override\n    public Expression<BigInteger> toBigInteger(Expression<? extends Number> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#toDouble(javax.persistence\n     * .criteria.Expression)\n     */\n    @Override\n    public Expression<Double> toDouble(Expression<? extends Number> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#toFloat(javax.persistence.\n     * criteria.Expression)\n     */\n    @Override\n    public Expression<Float> toFloat(Expression<? extends Number> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#toInteger(javax.persistence\n     * .criteria.Expression)\n     */\n    @Override\n    public Expression<Integer> toInteger(Expression<? extends Number> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#toLong(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public Expression<Long> toLong(Expression<? extends Number> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#toString(javax.persistence\n     * .criteria.Expression)\n     */\n    @Override\n    public Expression<String> toString(Expression<Character> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#trim(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public Expression<String> trim(Expression<String> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#trim(javax.persistence.criteria\n     * .CriteriaBuilder.Trimspec, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<String> trim(Trimspec arg0, Expression<String> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#trim(javax.persistence.criteria\n     * .Expression, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<String> trim(Expression<Character> arg0, Expression<String> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#trim(char,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<String> trim(char arg0, Expression<String> arg1)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#trim(javax.persistence.criteria\n     * .CriteriaBuilder.Trimspec, javax.persistence.criteria.Expression,\n     * javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<String> trim(Trimspec arg0, Expression<Character> arg1, Expression<String> arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#trim(javax.persistence.criteria\n     * .CriteriaBuilder.Trimspec, char, javax.persistence.criteria.Expression)\n     */\n    @Override\n    public Expression<String> trim(Trimspec arg0, char arg1, Expression<String> arg2)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#tuple(javax.persistence.criteria\n     * .Selection<?>[])\n     */\n    @Override\n    public CompoundSelection<Tuple> tuple(Selection<?>... arg0)\n    {\n        return new DefaultCompoundSelection<Tuple>(Arrays.asList(arg0), Tuple.class);\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.criteria.CriteriaBuilder#upper(javax.persistence.criteria\n     * .Expression)\n     */\n    @Override\n    public Expression<String> upper(Expression<String> arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.criteria.CriteriaBuilder#values(java.util.Map)\n     */\n    @Override\n    public <V, M extends Map<?, V>> Expression<Collection<V>> values(M arg0)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    Metamodel getMetaModel()\n    {\n        return this.entityManagerFactory.getMetamodel();\n    }\n\n    @Override\n    public <T> CriteriaUpdate<T> createCriteriaUpdate(Class<T> paramClass)\n    {\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\n        // Do nothing. Not yet implemented.\n        return null;\n    }\n\n    @Override\n    public <T> CriteriaDelete<T> createCriteriaDelete(Class<T> paramClass)\n    {\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\n        // Do nothing. Not yet implemented.\n        return null;\n    }\n\n    @Override\n    public <X, T, V extends T> Join<X, V> treat(Join<X, T> paramJoin, Class<V> paramClass)\n    {\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\n        // Do nothing. Not yet implemented.\n        return null;\n    }\n\n    @Override\n    public <X, T, E extends T> CollectionJoin<X, E> treat(CollectionJoin<X, T> paramCollectionJoin, Class<E> paramClass)\n    {\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\n        // Do nothing. Not yet implemented.\n        return null;\n    }\n\n    @Override\n    public <X, T, E extends T> SetJoin<X, E> treat(SetJoin<X, T> paramSetJoin, Class<E> paramClass)\n    {\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\n        // Do nothing. Not yet implemented.\n        return null;\n    }\n\n    @Override\n    public <X, T, E extends T> ListJoin<X, E> treat(ListJoin<X, T> paramListJoin, Class<E> paramClass)\n    {\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\n        // Do nothing. Not yet implemented.\n        return null;\n    }\n\n    @Override\n    public <X, K, T, V extends T> MapJoin<X, K, V> treat(MapJoin<X, K, T> paramMapJoin, Class<V> paramClass)\n    {\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\n        // Do nothing. Not yet implemented.\n        return null;\n    }\n\n    @Override\n    public <X, T extends X> Path<T> treat(Path<X> paramPath, Class<T> paramClass)\n    {\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\n        // Do nothing. Not yet implemented.\n        return null;\n    }\n\n    @Override\n    public <X, T extends X> Root<T> treat(Root<X> paramRoot, Class<T> paramClass)\n    {\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\n        // Do nothing. Not yet implemented.\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/KunderaCritieriaQuery.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.persistence;\n\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.Tuple;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Order;\nimport javax.persistence.criteria.ParameterExpression;\nimport javax.persistence.criteria.Predicate;\nimport javax.persistence.criteria.Root;\nimport javax.persistence.criteria.Selection;\nimport javax.persistence.criteria.Subquery;\nimport javax.persistence.metamodel.EntityType;\n\n\n/**\n * @author vivek.mishra\n *\n */\npublic class KunderaCritieriaQuery<T> implements CriteriaQuery<T>\n{\n\n    private KunderaCriteriaBuilder criteriaBuilder;\n    private Class<T> returnType;\n    private QueryPlan queryPlan = new QueryPlan();\n    \n    KunderaCritieriaQuery(KunderaCriteriaBuilder kunderaCriteriaBuilder)\n    {\n        this.criteriaBuilder = kunderaCriteriaBuilder;\n        this.returnType = (Class<T>) Object.class;\n    }\n\n    KunderaCritieriaQuery(KunderaCriteriaBuilder kunderaCriteriaBuilder, Class<T> returnClazz)\n    {\n        this.criteriaBuilder = kunderaCriteriaBuilder;\n        this.returnType = returnClazz;\n    }\n\n    @Override\n    public <X> Root<X> from(Class<X> paramClass)\n    {\n        EntityType<X> entityType = this.criteriaBuilder.getMetaModel().entity(paramClass);\n        return fromEntityType(entityType);\n    }\n\n    \n    @Override\n    public <X> Root<X> from(EntityType<X> paramEntityType)\n    {\n        \n        if(!this.criteriaBuilder.getMetaModel().getEntities().contains(paramEntityType))\n        {\n            throw new IllegalArgumentException(\"Invalid entity type, {class:\" + paramEntityType.getName() + \"}\");   \n        }\n        \n        return fromEntityType(paramEntityType);\n    }\n\n    @Override\n    public <U> Subquery<U> subquery(Class<U> paramClass)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public Set<Root<?>> getRoots()\n    {\n        return this.queryPlan.from;\n    }\n\n    @Override\n    public Selection<T> getSelection()\n    {\n        return (Selection<T>) this.queryPlan.select;\n    }\n\n    @Override\n    public Predicate getRestriction()\n    {\n        return this.queryPlan.where;\n    }\n\n    @Override\n    public List<Expression<?>> getGroupList()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public Predicate getGroupRestriction()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public boolean isDistinct()\n    {\n        // TODO Auto-generated method stub\n        return false;\n    }\n\n    @Override\n    public Class<T> getResultType()\n    {\n        return this.returnType;\n    }\n\n    @Override\n    public CriteriaQuery<T> select(Selection<? extends T> paramSelection)\n    {\n        this.queryPlan.setSelection(paramSelection);\n        return this;\n    }\n\n    @Override\n    public CriteriaQuery<T> multiselect(Selection<?>... paramArrayOfSelection)\n    {\n        SelectionType type = SelectionType.getSelectionType(getResultType());\n        switch (type)\n        {\n        case TUPLE:\n                this.queryPlan.setSelection(this.criteriaBuilder.tuple(paramArrayOfSelection));\n            break;\n\n        case ARRAY:\n            this.queryPlan.setSelection(this.criteriaBuilder.array(this.getResultType(),paramArrayOfSelection));\n            break;\n\n        case OBJECT:\n            this.queryPlan.setSelection(this.criteriaBuilder.construct(getResultType(), paramArrayOfSelection));\n            break;\n\n        }\n\n        return this;\n    }\n\n    @Override\n    public CriteriaQuery<T> multiselect(List<Selection<?>> paramList)\n    {\n//        this.queryPlan\n        return multiselect((Selection<?>[]) paramList.toArray());\n    }\n\n    @Override\n    public CriteriaQuery<T> where(Expression<Boolean> paramExpression)\n    {\n        if (Predicate.class.isAssignableFrom(paramExpression.getClass()))\n        {\n            this.queryPlan.setWhere(this.criteriaBuilder.and((Predicate)paramExpression));\n        }\n        \n        return this;\n    }\n\n    @Override\n    public CriteriaQuery<T> where(Predicate... paramArrayOfPredicate)\n    {\n        this.queryPlan.setWhere(this.criteriaBuilder.and(paramArrayOfPredicate));\n        return this;\n    }\n\n    @Override\n    public CriteriaQuery<T> groupBy(Expression<?>... paramArrayOfExpression)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public CriteriaQuery<T> groupBy(List<Expression<?>> paramList)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public CriteriaQuery<T> having(Expression<Boolean> paramExpression)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public CriteriaQuery<T> having(Predicate... paramArrayOfPredicate)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public CriteriaQuery<T> orderBy(Order... paramArrayOfOrder)\n    {\n        return orderBy(Arrays.asList(paramArrayOfOrder));\n    }\n\n    @Override\n    public CriteriaQuery<T> orderBy(List<Order> paramList)\n    {\n        // TODO Auto-generated method stub\n        this.queryPlan.setOrderBy(paramList);\n        return this;\n    }\n\n    @Override\n    public CriteriaQuery<T> distinct(boolean paramBoolean)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    public List<Order> getOrderList()\n    {\n        return this.queryPlan.orderBy;\n    }\n\n    @Override\n    public Set<ParameterExpression<?>> getParameters()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    private <X> Root<X> fromEntityType(EntityType<X> paramEntityType)\n    {\n        Root<X> root =  new DefaultRoot<X>(paramEntityType);\n        this.queryPlan.add(root);\n        return root;\n    }\n\n    enum SelectionType\n    {\n        TUPLE, ARRAY, OBJECT;\n        \n        static SelectionType getSelectionType(Class clazz)\n        {\n            if(clazz.isAssignableFrom(Tuple.class))\n            {\n                return TUPLE;\n            }else if(clazz.isArray())\n            {\n                return ARRAY;\n            }else\n            {\n                return OBJECT;\n            }\n        }\n    }\n    \n    class QueryPlan\n    {\n        private Selection<?> select;\n        private Set<Root<?>> from = new HashSet<Root<?>>();\n        private Predicate where;\n        private List<Order> orderBy;\n     \n        void add(Root root)\n        {\n            from.add(root);\n        }\n        \n        void setWhere(Predicate predicate)\n        {\n            this.where = predicate;\n        }\n        \n        void setSelection(Selection selection)\n        {\n            this.select = selection;\n        }\n        \n        \n        void setOrderBy(List<Order> orderBy)\n        {\n            this.orderBy = orderBy;\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/KunderaEntityTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.persistence;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityTransaction;\n\n/**\n * Class implements <code>EntityTransaction </code> interface. It implements\n * begin/commit/roll back and other methods.\n * \n * @author vivek.mishra\n * \n */\npublic class KunderaEntityTransaction implements EntityTransaction\n{\n    private EntityManager entityManager;\n\n    private Coordinator coordinator;\n\n    private Boolean rollbackOnly;\n\n    enum TxAction\n    {\n        BEGIN, COMMIT, ROLLBACK, PREPARE;\n    }\n\n    KunderaEntityTransaction(EntityManager entityManager)\n    {\n        this.entityManager = entityManager;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.EntityTransaction#begin()\n     */\n    @Override\n    public void begin()\n    {\n        if (isActive())\n        {\n            throw new IllegalStateException(\"Transaction is already active\");\n        }\n        else\n        {\n            this.coordinator = ((EntityManagerImpl) entityManager).getPersistenceDelegator().getCoordinator();\n            ((EntityManagerImpl) entityManager).getPersistenceDelegator().begin(); // transaction\n                                                                                   // de-marcation.\n            this.coordinator.coordinate(TxAction.BEGIN);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.EntityTransaction#commit()\n     */\n    @Override\n    public void commit()\n    {\n        if (!getRollbackOnly())\n        {\n            onTransaction(TxAction.COMMIT);\n            ((EntityManagerImpl) entityManager).getPersistenceDelegator().commit();\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.EntityTransaction#getRollbackOnly()\n     */\n    @Override\n    public boolean getRollbackOnly()\n    {\n        if (isActive())\n        {\n            return rollbackOnly != null ? rollbackOnly : false;\n        }\n        else\n        {\n            throw new IllegalStateException(\"No transaction in progress\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.EntityTransaction#isActive()\n     */\n    @Override\n    public boolean isActive()\n    {\n        return (coordinator != null && coordinator.isTransactionActive());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.EntityTransaction#rollback()\n     */\n    @Override\n    public void rollback()\n    {\n        onTransaction(TxAction.ROLLBACK);\n        ((EntityManagerImpl) entityManager).getPersistenceDelegator().rollback();\n    }\n\n    private void onTransaction(TxAction action)\n    {\n        if (isActive())\n        {\n            coordinator.coordinate(action);\n        }\n        else\n        {\n            throw new IllegalStateException(\"No transaction in progress\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.EntityTransaction#setRollbackOnly()\n     */\n    @Override\n    public void setRollbackOnly()\n    {\n        this.rollbackOnly = true;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/KunderaTransactionException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * @author amresh\n * \n */\npublic class KunderaTransactionException extends KunderaException\n{\n\n    /**\n     * \n     */\n    private static final long serialVersionUID = -7672192031279208722L;\n\n    /**\n     * \n     */\n    public KunderaTransactionException()\n    {\n    }\n\n    /**\n     * @param arg0\n     */\n    public KunderaTransactionException(String arg0)\n    {\n        super(arg0);\n    }\n\n    /**\n     * @param arg0\n     */\n    public KunderaTransactionException(Throwable arg0)\n    {\n        super(arg0);\n    }\n\n    /**\n     * @param arg0\n     * @param arg1\n     */\n    public KunderaTransactionException(String arg0, Throwable arg1)\n    {\n        super(arg0, arg1);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/PersistenceDelegator.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.persistence;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Deque;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.locks.ReentrantReadWriteLock;\n\nimport javax.persistence.FlushModeType;\nimport javax.persistence.Query;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.impetus.kundera.client.ClientResolverException;\nimport com.impetus.kundera.graph.GraphGenerator;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.ObjectGraph;\nimport com.impetus.kundera.graph.ObjectGraphUtils;\nimport com.impetus.kundera.lifecycle.states.ManagedState;\nimport com.impetus.kundera.lifecycle.states.RemovedState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.EventLog.EventType;\nimport com.impetus.kundera.persistence.context.FlushManager;\nimport com.impetus.kundera.persistence.context.MainCache;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData.OPERATION;\nimport com.impetus.kundera.persistence.event.EntityEventDispatcher;\nimport com.impetus.kundera.proxy.LazyInitializerFactory;\nimport com.impetus.kundera.query.QueryResolver;\nimport com.impetus.kundera.utils.ObjectUtils;\n\n/**\n * The Class PersistenceDelegator.\n */\npublic final class PersistenceDelegator\n{\n\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(PersistenceDelegator.class);\n\n    /** The closed. */\n    private boolean closed;\n\n    /** The client map. */\n    private final Map<String, Client> clientMap = new HashMap<String, Client>();\n\n    /** The event dispatcher. */\n    private final EntityEventDispatcher eventDispatcher = new EntityEventDispatcher();\n\n    private FlushModeType flushMode = FlushModeType.AUTO;\n\n    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();\n\n    // Whether a transaction is in progress\n    private boolean isTransactionInProgress;\n\n    private final PersistenceCache persistenceCache;\n\n    private final FlushManager flushManager = new FlushManager();\n\n    private boolean enableFlush;\n\n    private Coordinator coordinator;\n\n    private final KunderaMetadata kunderaMetadata;\n\n    /**\n     * Instantiates a new persistence delegator.\n     * \n     * @param session\n     *            the session\n     * @param persistenceUnits\n     *            the persistence units\n     */\n    PersistenceDelegator(final KunderaMetadata kunderaMetadata, final PersistenceCache pc)\n    {\n        this.persistenceCache = pc;\n        this.kunderaMetadata = kunderaMetadata;\n    }\n\n    /***********************************************************************/\n    /***************** CRUD Methods ****************************************/\n    /***********************************************************************/\n\n    /**\n     * Writes an entity into Persistence cache. (Actual database write is done\n     * while flushing)\n     */\n    public void persist(Object e)\n    {\n        if (e == null)\n        {\n            throw new IllegalArgumentException(\n                    \"Entity object is invalid, operation failed. Please check previous log message for details\");\n        }\n\n        // Create an object graph of the entity object.\n        ObjectGraph graph = new GraphGenerator().generateGraph(e, this);\n        // Call persist on each node in object graph.\n        Node node = graph.getHeadNode();\n        try\n        {\n            // Get write lock before writing object required for transaction.\n            lock.writeLock().lock();\n\n            node.setPersistenceDelegator(this);\n            node.persist();\n\n            // build flush stack.\n            flushManager.buildFlushStack(node, com.impetus.kundera.persistence.context.EventLog.EventType.INSERT);\n\n            // Flushing data.\n            flush();\n\n            // Add node to persistence context after successful flush.\n            getPersistenceCache().getMainCache().addHeadNode(node);\n        }\n        finally\n        {\n            lock.writeLock().unlock();\n        }\n\n        // Unlocking object.\n        graph.clear();\n        graph = null;\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"Data persisted successfully for entity {}.\", e.getClass());\n        }\n    }\n\n    /**\n     * Find object based on primary key either form persistence cache or from\n     * database\n     * \n     * @param entityClass\n     * @param primaryKey\n     * @return\n     */\n    public <E> E findById(final Class<E> entityClass, final Object primaryKey)\n    {\n        E e = find(entityClass, primaryKey);\n        if (e == null)\n        {\n            return null;\n        }\n\n        // Return a copy of this entity\n        return (E) (e);\n    }\n\n    /**\n     * Finds an entity from persistence cache, if not there, fetches from\n     * database. Nodes are added into persistence cache (if not already there)\n     * as and when they are found from DB. While adding nodes to persistence\n     * cache, a deep copy is added, so that found object doesn't refer to\n     * managed entity in persistence cache.\n     * \n     * @param entityClass\n     *            Entity Class\n     * @param primaryKey\n     *            Primary Key\n     * @return Entity Object for the given primary key\n     * \n     */\n    <E> E find(final Class<E> entityClass, final Object primaryKey)\n    {\n        if (primaryKey == null)\n        {\n            throw new IllegalArgumentException(\"PrimaryKey value must not be null for object you want to find.\");\n        }\n        // Locking as it might read from persistence context.\n\n        EntityMetadata entityMetadata = getMetadata(entityClass);\n\n        String nodeId = ObjectGraphUtils.getNodeId(primaryKey, entityClass);\n\n        // TODO all the scrap should go from here.\n        MainCache mainCache = (MainCache) getPersistenceCache().getMainCache();\n        Node node = mainCache.getNodeFromCache(nodeId, this);\n\n        // if node is not in persistence cache or is dirty, fetch from database\n        if (node == null || node.isDirty())\n        {\n            node = new Node(nodeId, entityClass, new ManagedState(), getPersistenceCache(), primaryKey, this);\n            node.setClient(getClient(entityMetadata));\n            // TODO ManagedState.java require serious attention.\n            node.setPersistenceDelegator(this);\n\n            try\n            {\n                lock.readLock().lock();\n                node.find();\n            }\n            finally\n            {\n                lock.readLock().unlock();\n            }\n        }\n        else\n        {\n            node.setPersistenceDelegator(this);\n        }\n        Object nodeData = node.getData();\n        if (nodeData == null)\n        {\n            return null;\n        }\n        else\n        {\n            E e = (E) ObjectUtils.deepCopy(nodeData, getKunderaMetadata());\n            onSetProxyOwners(entityMetadata, e);\n            return e;\n        }\n    }\n\n    /**\n     * Retrieves a {@link List} of Entities for given Primary Keys\n     * \n     * @param entityClass\n     *            Entity Class\n     * @param primaryKeys\n     *            Array of Primary Keys\n     * @see {@link PersistenceDelegator#find(Class, Object)}\n     * @return List of found entities\n     */\n    // TODO Is it possible to pass all primary keys directly to database client.\n    public <E> List<E> find(Class<E> entityClass, Object... primaryKeys)\n    {\n        List<E> entities = new ArrayList<E>();\n        if (primaryKeys == null)\n        {\n            return entities;\n        }\n        Set<Object> pKeys = new HashSet<Object>(Arrays.asList(primaryKeys));\n        for (Object primaryKey : pKeys)\n        {\n            E e = find(entityClass, primaryKey);\n            if (e != null)\n            {\n                entities.add(e);\n            }\n        }\n        return entities;\n    }\n\n    /**\n     * Retrieves {@link List} of entities for a given {@link Map} of embedded\n     * column values. Purpose of this method is to provide functionality of\n     * search based on columns inside embedded objects.\n     * \n     * @param entityClass\n     *            Entity Class\n     * @param embeddedColumnMap\n     *            Embedded column map values\n     * @return List of found entities.\n     */\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n        EntityMetadata entityMetadata = getMetadata(entityClass);\n\n        // TODO Why returning entities are not added into cache we should not\n        // iterate here but client should i think.\n        List<E> entities = new ArrayList<E>();\n        entities = getClient(entityMetadata).find(entityClass, embeddedColumnMap);\n\n        return entities;\n    }\n\n    /**\n     * Removes an entity object from persistence cache.\n     * \n     */\n    public void remove(Object e)\n    {\n        // Invoke Pre Remove Events\n\n        // TODO Check for validity also as per JPA\n        if (e == null)\n        {\n            throw new IllegalArgumentException(\"Entity to be removed must not be null.\");\n        }\n\n        EntityMetadata metadata = getMetadata(e.getClass());\n\n        // Create an object graph of the entity object\n        ObjectGraph graph = new GraphGenerator().generateGraph(e, this, new ManagedState());\n\n        Node node = graph.getHeadNode();\n\n        try\n        {\n            lock.writeLock().lock();\n\n            // TODO : push into action queue, get original end-point from\n            // persistenceContext first!\n\n            // Action/ExecutionQueue/ActivityQueue :-> id, name, EndPoint,\n            // changed\n            // state\n\n            // Change state of node, after successful flush processing.\n            node.setPersistenceDelegator(this);\n            node.remove();\n\n            // build flush stack.\n\n            flushManager.buildFlushStack(node, EventType.DELETE);\n\n            // Flush node.\n            flush();\n        }\n        finally\n        {\n            lock.writeLock().unlock();\n        }\n        // clear out graph\n        graph.clear();\n        graph = null;\n\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"Data removed successfully for entity : \" + e.getClass());\n        }\n    }\n\n    /**\n     * Flushes Dirty objects in {@link PersistenceCache} to databases.\n     * \n     */\n    private void flush()\n    {\n        // Get flush stack from Flush Manager\n        Deque<Node> fs = flushManager.getFlushStack();\n\n        // Flush each node in flush stack from top to bottom unit it's empty\n\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"Flushing following flush stack to database(s) (showing stack objects from top to bottom):\\n\"\n                    + fs);\n        }\n        if (fs != null)\n        {\n            boolean isBatch = false;\n            while (!fs.isEmpty())\n            {\n                Node node = fs.pop();\n\n                // Only nodes in Managed and Removed state are flushed, rest\n                // are ignored\n                if (node.isInState(ManagedState.class) || node.isInState(RemovedState.class))\n                {\n                    EntityMetadata metadata = getMetadata(node.getDataClass());\n                    node.setClient(getClient(metadata));\n\n                    // if batch size is defined.\n                    if ((node.getClient() instanceof Batcher) && ((Batcher) (node.getClient())).getBatchSize() > 0)\n                    {\n                        isBatch = true;\n                        ((Batcher) (node.getClient())).addBatch(node);\n                    }\n                    else if (isTransactionInProgress\n                            && MetadataUtils\n                                    .defaultTransactionSupported(metadata.getPersistenceUnit(), kunderaMetadata))\n                    {\n                        onSynchronization(node, metadata);\n                    }\n                    else\n                    {\n                        node.flush();\n                    }\n                }\n\n            }\n\n            if (!isBatch)\n            {\n                // TODO : This needs to be look for different\n                // permutation/combination\n                // Flush Join Table data into database\n                flushJoinTableData();\n                // performed,\n            }\n        }\n    }\n\n    public <E> E merge(E e)\n    {\n        if (log.isDebugEnabled())\n            log.debug(\"Merging Entity : \" + e);\n\n        if (e == null)\n        {\n            throw new IllegalArgumentException(\"Entity to be merged must not be null.\");\n        }\n\n        EntityMetadata m = getMetadata(e.getClass());\n\n        // Create an object graph of the entity object to be merged\n        ObjectGraph graph = new GraphGenerator().generateGraph(e, this);\n\n        // Call merge on each node in object graph\n        Node node = graph.getHeadNode();\n\n        try\n        {\n            lock.writeLock().lock();\n            // Change node's state after successful flush.\n            node.setPersistenceDelegator(this);\n            node.merge();\n\n            // build flush stack.\n            flushManager.buildFlushStack(node, EventType.UPDATE);\n\n            flush();\n        }\n        finally\n        {\n            lock.writeLock().unlock();\n        }\n        graph.clear();\n        graph = null;\n\n        return (E) node.getData();\n    }\n\n    /**\n     * Remove the given entity from the persistence context, causing a managed\n     * entity to become detached.\n     */\n    public void detach(Object entity)\n    {\n        Node node = getPersistenceCache().getMainCache().getNodeFromCache(entity, getMetadata(entity.getClass()), this);\n        if (node != null)\n        {\n            node.detach();\n        }\n    }\n\n    /**\n     * Gets the client.\n     * \n     * @param m\n     *            the m\n     * @return the client\n     */\n    public Client getClient(EntityMetadata m)\n    {\n        // // Persistence Unit used to retrieve client\n        if (m == null)\n        {\n            throw new KunderaException(\"Entitymatadata should not be null\");\n        }\n        String persistenceUnit = m.getPersistenceUnit();\n\n        return getClient(persistenceUnit);\n    }\n\n    public Client getClient(final String persistenceUnit)\n    {\n        Client client = clientMap.get(persistenceUnit);\n        if (client == null)\n        {\n            throw new ClientResolverException(\"No client configured for persistenceUnit \" + persistenceUnit);\n        }\n        return client;\n    }\n\n    /**\n     * Gets the event dispatcher.\n     * \n     * @return the event dispatcher\n     */\n    public EntityEventDispatcher getEventDispatcher()\n    {\n        return eventDispatcher;\n    }\n\n    /**\n     * Creates the query.\n     * \n     * @param jpaQuery\n     *            the jpa query\n     * @return the query\n     */\n    Query createQuery(String jpaQuery)\n    {\n        return getQueryInstance(jpaQuery, false, null);\n    }\n\n    /**\n     * Creates the query.\n     * \n     * @param jpaQuery\n     *            the jpa query\n     * @return the query\n     */\n    Query createQuery(String jpaQuery, final String persistenceUnit)\n    {\n        Client client = getClient(persistenceUnit);\n        EntityMetadata metadata = null;\n        try\n        {\n            metadata = KunderaMetadataManager.getMetamodel(kunderaMetadata, client.getPersistenceUnit())\n                    .getEntityMetadataMap().values().iterator().next();\n        }\n        catch (Exception e)\n        {\n            log.info(\"Entity metadata is null. Proceeding as Scalar Query.\");\n        }\n\n        Query query = new QueryResolver().getQueryImplementation(jpaQuery, getClient(persistenceUnit)\n                .getQueryImplementor(), this, metadata, persistenceUnit);\n        return query;\n    }\n\n    /*\n     * \n     */\n    Query createNativeQuery(String jpaQuery, Class resultClass)\n    {\n        return getQueryInstance(jpaQuery, true, resultClass);\n    }\n\n    private Query getQueryInstance(String jpaQuery, boolean isNative, Class mappedClass)\n    {\n        Query query = new QueryResolver()\n                .getQueryImplementation(jpaQuery, this, mappedClass, isNative, kunderaMetadata);\n        return query;\n    }\n\n    /**\n     * Checks if is open.\n     * \n     * @return true, if is open\n     */\n    public boolean isOpen()\n    {\n        return !closed;\n    }\n\n    /**\n     * Close.\n     */\n    void close()\n    {\n        doFlush();\n\n        // Close all clients created in this session\n        if (!clientMap.isEmpty())\n        {\n            for (Client client : clientMap.values())\n            {\n                client.close();\n            }\n            clientMap.clear();\n        }\n\n        onClearProxy();\n\n        // TODO: Move all nodes tied to this EM into detached state, need to\n        // discuss with Amresh.\n\n        closed = true;\n    }\n\n    private void onClearProxy()\n    {\n        if (kunderaMetadata.getCoreMetadata() != null)\n        {\n            LazyInitializerFactory lazyInitializerrFactory = kunderaMetadata.getCoreMetadata()\n                    .getLazyInitializerFactory();\n\n            if (lazyInitializerrFactory != null)\n            {\n                lazyInitializerrFactory.clearProxies();\n            }\n        }\n    }\n\n    private void onSetProxyOwners(final EntityMetadata m, Object e)\n    {\n        if (kunderaMetadata.getCoreMetadata() != null)\n        {\n            LazyInitializerFactory lazyInitializerrFactory = kunderaMetadata.getCoreMetadata()\n                    .getLazyInitializerFactory();\n\n            if (lazyInitializerrFactory != null)\n            {\n                lazyInitializerrFactory.setProxyOwners(m, e);\n            }\n        }\n    }\n\n    void clear()\n    {\n        // Move all nodes tied to this EM into detached state\n        flushManager.clearFlushStack();\n        getPersistenceCache().clean();\n        onClearProxy();\n    }\n\n    /**\n     * Check if the instance is a managed entity instance belonging to the\n     * current persistence context.\n     */\n    boolean contains(Object entity)\n    {\n        Node node = getPersistenceCache().getMainCache().getNodeFromCache(entity, getMetadata(entity.getClass()), this);\n        return node != null && node.isInState(ManagedState.class);\n    }\n\n    /**\n     * Refresh the state of the instance from the database, overwriting changes\n     * made to the entity, if any.\n     */\n    public void refresh(Object entity)\n    {\n        if (contains(entity))\n        {\n            MainCache mainCache = (MainCache) getPersistenceCache().getMainCache();\n            Node node = mainCache.getNodeFromCache(entity, getMetadata(entity.getClass()), this);\n            // Locking as it might read from persistence context.\n\n            try\n            {\n                lock.readLock().lock();\n                node.setPersistenceDelegator(this);\n                node.refresh();\n            }\n            finally\n            {\n                lock.readLock().unlock();\n            }\n        }\n        else\n        {\n            throw new IllegalArgumentException(\"This is not a valid or managed entity, can't be refreshed\");\n        }\n    }\n\n    /**\n     * Gets the metadata.\n     * \n     * @param clazz\n     *            the clazz\n     * @return the metadata\n     */\n    private EntityMetadata getMetadata(Class<?> clazz)\n    {\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n        if (metadata == null)\n        {\n            log.error(\"Entity metadata not found for {}, possible reasons may be: \"\n                    + \"1) not annotated with @Entity. 2) is annotated with @MappedSuperclass.\"\n                    + \"3) does not properly with mapped persistence unit for persistence unit and keyspace. Please verify with @Table annotation or persistence.xml \"\n                    + clazz);\n            throw new KunderaException(\"Entity metadata not found for \" + clazz.getName());\n        }\n        return metadata;\n    }\n\n    /**\n     * @param flushMode\n     *            the flushMode to set\n     */\n    void setFlushMode(FlushModeType flushMode)\n    {\n        // TODO keeping it open for future releases current not using any where.\n        this.flushMode = flushMode;\n    }\n\n    /**\n     * @return the isTransactionInProgress\n     */\n    public boolean isTransactionInProgress()\n    {\n        return isTransactionInProgress;\n    }\n\n    /**\n     * @return the persistenceCache\n     */\n    public PersistenceCache getPersistenceCache()\n    {\n        return persistenceCache;\n    }\n\n    /******************************* Transaction related methods ***********************************************/\n\n    void begin()\n    {\n        isTransactionInProgress = true;\n    }\n\n    void commit()\n    {\n        enableFlush = true;\n        execute();\n        flushManager.commit();\n        flushManager.clearFlushStack();\n        isTransactionInProgress = false;\n        enableFlush = false;\n    }\n\n    /**\n     * On explicit call from em.flush().\n     */\n    void doFlush()\n    {\n        enableFlush = true;\n        flush();\n        execute();\n        enableFlush = false;\n        flushManager.commit();\n        flushManager.clearFlushStack();\n    }\n\n    void rollback()\n    {\n        flushManager.rollback(this);\n        flushManager.clearFlushStack();\n        getPersistenceCache().clean();\n        isTransactionInProgress = false;\n    }\n\n    /**\n     * Populates client specific properties.\n     * \n     * @param properties\n     *            map of properties.\n     */\n    void populateClientProperties(Map properties)\n    {\n        if (properties != null && !properties.isEmpty())\n        {\n            Map<String, Client> clientMap = getDelegate();\n            if (!clientMap.isEmpty())\n            {\n                // TODO If we have two pu for same client then? Need to discuss\n                // with Amresh.\n                for (Client client : clientMap.values())\n                {\n                    if (client instanceof ClientPropertiesSetter)\n                    {\n                        ClientPropertiesSetter cps = (ClientPropertiesSetter) client;\n                        cps.populateClientProperties(client, properties);\n                    }\n                }\n            }\n        }\n        else\n        {\n            if (log.isDebugEnabled())\n            {\n                log.debug(\"Can't set Client properties as None/ Null was supplied\");\n            }\n        }\n    }\n\n    /**\n     * Pre load client specific to persistence unit.\n     * \n     * @param persistenceUnit\n     *            persistence unit.\n     * @param client\n     */\n\n    void loadClient(String persistenceUnit, Client client)\n    {\n        if (!clientMap.containsKey(persistenceUnit) && client != null)\n        {\n            clientMap.put(persistenceUnit, client);\n        }\n    }\n\n    /**\n     * Returns map of client as delegate to entity manager.\n     * \n     * @return clientMap client map\n     */\n    Map<String, Client> getDelegate()\n    {\n        return clientMap;\n    }\n\n    /**\n     * Executes batch.\n     */\n    private void execute()\n    {\n        for (Client client : clientMap.values())\n        {\n            if (client != null && client instanceof Batcher)\n            {\n                // if no batch operation performed{may be running in\n                // transaction?}\n                if (((Batcher) client).getBatchSize() == 0 || ((Batcher) client).executeBatch() > 0)\n                {\n                    flushJoinTableData();\n                }\n            }\n        }\n    }\n\n    /**\n     * On flushing join table data\n     */\n    private void flushJoinTableData()\n    {\n        if (applyFlush())\n        {\n            for (JoinTableData jtData : flushManager.getJoinTableData())\n            {\n                if (!jtData.isProcessed())\n                {\n                    EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                            jtData.getEntityClass());\n                    Client client = getClient(m);\n                    if (OPERATION.INSERT.equals(jtData.getOperation()))\n                    {\n                        client.persistJoinTable(jtData);\n                        jtData.setProcessed(true);\n                    }\n                    else if (OPERATION.DELETE.equals(jtData.getOperation()))\n                    {\n                        for (Object pk : jtData.getJoinTableRecords().keySet())\n                        {\n                            client.deleteByColumn(m.getSchema(), jtData.getJoinTableName(),\n                                    jtData.getJoinColumnName(), pk);\n                        }\n                        jtData.setProcessed(true);\n                    }\n                }\n\n            }\n        }\n    }\n\n    /**\n     * Returns true, if flush mode is AUTO and not running within transaction ||\n     * running within transaction and commit is invoked.\n     * \n     * @return boolean value.\n     */\n    private boolean applyFlush()\n    {\n        return (!isTransactionInProgress && flushMode.equals(FlushModeType.AUTO)) || enableFlush;\n    }\n\n    /**\n     * Returns transaction coordinator.\n     * \n     * @return\n     */\n    Coordinator getCoordinator()\n    {\n        coordinator = new Coordinator();\n        try\n        {\n            for (String pu : clientMap.keySet())\n            {\n                PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\n                        pu);\n\n                String txResource = puMetadata.getProperty(PersistenceProperties.KUNDERA_TRANSACTION_RESOURCE);\n\n                if (txResource != null)\n                {\n                    TransactionResource resource = (TransactionResource) Class.forName(txResource).newInstance();\n                    coordinator.addResource(resource, pu);\n                    Client client = clientMap.get(pu);\n\n                    if (!(client instanceof TransactionBinder))\n                    {\n                        throw new KunderaTransactionException(\n                                \"Client : \"\n                                        + client.getClass()\n                                        + \" must implement TransactionBinder interface, if {kundera.transaction.resource.class} property provided!\");\n                    }\n                    else\n                    {\n                        ((TransactionBinder) client).bind(resource);\n                    }\n                }\n                else\n                {\n                    coordinator.addResource(new DefaultTransactionResource(clientMap.get(pu)), pu);\n                }\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while initializing Transaction Resource:\", e);\n            throw new KunderaTransactionException(e);\n\n        }\n\n        return coordinator;\n    }\n\n    /**\n     * If transaction is in progress and user explicitly invokes em.flush()!\n     * \n     * @param node\n     *            data node\n     * @param metadata\n     *            entity metadata.\n     */\n    private void onSynchronization(Node node, EntityMetadata metadata)\n    {\n        DefaultTransactionResource resource = (DefaultTransactionResource) coordinator.getResource(metadata\n                .getPersistenceUnit());\n        if (enableFlush)\n        {\n            resource.onFlush();\n        }\n        else\n        {\n            resource.syncNode(node);\n        }\n    }\n\n    public KunderaMetadata getKunderaMetadata()\n    {\n        return this.kunderaMetadata;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/PersistenceValidator.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence;\n\nimport java.lang.reflect.Field;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.Set;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.metadata.processor.MetaModelBuilder;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.validation.ValidationFactory;\nimport com.impetus.kundera.validation.ValidationFactoryGenerator;\nimport com.impetus.kundera.validation.ValidationFactoryGenerator.ValidationFactoryType;\nimport com.impetus.kundera.validation.rules.AttributeConstraintRule;\n\n/**\n * Responsible for validating entity persistence\n * \n * @author amresh.singh\n */\npublic class PersistenceValidator\n{\n    private static final Logger log = LoggerFactory.getLogger(PersistenceValidator.class);\n\n    private ValidationFactoryGenerator generator;\n\n    private ValidationFactory factory;\n    \n    \n    public PersistenceValidator(){\n        \n        this.generator = new ValidationFactoryGenerator();\n        this.factory = generator.getFactory(ValidationFactoryType.OPERATIONAL_VALIDATION);\n        \n    }\n    /**\n     * Validates an entity object for CRUD operations\n     * \n     * @param entity\n     *            Instance of entity object\n     * @return True if entity object is valid, false otherwise\n     */\n    public boolean isValidEntityObject(Object entity, EntityMetadata metadata)\n    {\n        if (entity == null)\n        {\n            log.error(\"Entity to be persisted must not be null, operation failed\");\n            return false;\n        }\n\n        Object id = PropertyAccessorHelper.getId(entity, metadata);\n        if (id == null)\n        {\n            log.error(\"Entity to be persisted can't have Primary key set to null.\");\n            throw new IllegalArgumentException(\"Entity to be persisted can't have Primary key set to null.\");\n            // return false;\n        }\n        return true;\n    }\n\n    /**\n     * Validates an entity object for CRUD operations\n     * \n     * @param entity\n     *            Instance of entity object\n     */\n    public void validate(Object entity, KunderaMetadata kunderaMetadata)\n    {\n        validateEntityAttributes(entity, kunderaMetadata);\n    }\n\n    /**\n     * Validates an entity object for CRUD operations\n     * \n     * @param entity\n     *            Instance of entity object\n     */\n    private <X extends Class, T extends Object> void validateEntityAttributes(Object entity,\n            KunderaMetadata kunderaMetadata)\n    {\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(entityMetadata.getEntityClazz());\n\n        MetaModelBuilder<X, T> metaModelBuilder = kunderaMetadata.getApplicationMetadata().getMetaModelBuilder(\n                entityMetadata.getPersistenceUnit());\n        EntityType entityType = (EntityType) metaModelBuilder.getManagedTypes().get(entityMetadata.getEntityClazz());\n\n        \n\n\n\n        // if managed type has any validation constraint present then validate\n        // the attributes\n       \n        if (managedType.hasValidationConstraints())\n        {\n          \n            Set<Attribute> attributes = entityType.getAttributes();\n            Iterator<Attribute> iter = attributes.iterator();\n\n            while (iter.hasNext())\n            {\n                Attribute attribute = iter.next();\n               \n                Field f = (Field) ((Field) attribute.getJavaMember());\n                \n                //check if an embeddable field has a constraint\n                if (metaModel.isEmbeddable(attribute.getJavaType()))\n                {\n                   \n                    EmbeddableType embeddedColumn = (EmbeddableType) metaModelBuilder.getEmbeddables().get(attribute.getJavaType());\n                    Object embeddedObject = PropertyAccessorHelper.getObject(entity,\n                            (Field) entityType.getAttribute(attribute.getName()).getJavaMember());\n                    \n                    onValidateEmbeddable(embeddedObject, embeddedColumn);\n                }\n                this.factory.validate(f, entity, new AttributeConstraintRule());\n\n            }\n\n        }\n\n    }\n\n   \n    /**\n     * Checks constraints present on embeddable attributes\n     * \n     * @param embeddedObject\n     * @param embeddedColumn\n     * @param embeddedFieldName\n     */\n    private void onValidateEmbeddable(Object embeddedObject, EmbeddableType embeddedColumn)\n    {\n        if (embeddedObject instanceof Collection)\n        {\n           \n            for (Object obj : (Collection) embeddedObject)\n            {\n                for (Object column : embeddedColumn.getAttributes())\n                {\n\n                    Attribute columnAttribute = (Attribute) column;\n                    Field f = (Field) columnAttribute.getJavaMember();\n                    this.factory.validate(f, embeddedObject, new AttributeConstraintRule());\n                }\n            }\n        }\n        else\n        {\n            for (Object column : embeddedColumn.getAttributes())\n            {\n\n                Attribute columnAttribute = (Attribute) column;\n                Field f = (Field) ((Field) columnAttribute.getJavaMember());\n                this.factory.validate(f, embeddedObject, new AttributeConstraintRule());\n\n            }\n        }\n\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/QueryOrder.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.persistence;\n\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Order;\n\nimport com.impetus.kundera.query.KunderaQuery.SortOrder;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class QueryOrder implements Order\n{\n\n    private Expression<?> expression;\n    private SortOrder ordering;\n    \n    QueryOrder(final Expression<?> expression, SortOrder sortOrdering)\n    {\n        this.expression = expression;\n        this.ordering = sortOrdering;\n    }\n    \n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Order#reverse()\n     */\n    @Override\n    public Order reverse()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Order#isAscending()\n     */\n    @Override\n    public boolean isAscending()\n    {\n        // TODO Auto-generated method stub\n        return this.ordering.equals(SortOrder.ASC);\n    }\n\n    SortOrder getOrder()\n    {\n        return this.ordering;\n    }\n    \n    /* (non-Javadoc)\n     * @see javax.persistence.criteria.Order#getExpression()\n     */\n    @Override\n    public Expression<?> getExpression()\n    {\n        return this.expression;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/ResourceManager.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\n/**\n * The Interface ResourceManager.\n * \n * @author vivek.mishra\n */\npublic interface ResourceManager\n{\n\n    /**\n     * Do commit.\n     */\n    void doCommit();\n\n    /**\n     * Do rollback.\n     */\n    void doRollback();\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/TransactionBinder.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.persistence;\n\n/**\n * TransactionBinder interface. If underlying database provides in-built\n * transaction support, client has to implement this interface and bind\n * transaction resource with client.\n * \n * @author vivek.mishra\n * \n */\npublic interface TransactionBinder\n{\n\n    /**\n     * Binds a transaction resource with client instance. Any subsequent CRUD\n     * calls will use this transaction resource to mark bind within already\n     * running transaction boundary. TransactionResource is responsible to bind\n     * and provide connection instance with for subsequent commit/rollback.\n     * \n     * @param resource\n     *            transactional resource\n     */\n    void bind(TransactionResource resource);\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/TransactionResource.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\n/**\n * TransactionResource interface will delegate begin/commit/rollback to client\n * and each client will implement this interface provided transaction support is\n * required for corresponding database. If underlying database supports\n * transaction then it will\n * \n * @author vivek.mishra\n * \n */\npublic interface TransactionResource\n{\n\n    /**\n     * On begin transactions.\n     */\n    void onBegin();\n\n    /**\n     * On commit transactions.\n     */\n    void onCommit();\n\n    /**\n     * On rollback transactions.\n     */\n    void onRollback();\n\n    /**\n     * On intermediate flush, when explicitly flush is invoked by em.flush()!\n     */\n    void onFlush();\n\n    /**\n     * On prepare for two phase commit.\n     * \n     * @return response, returns YES if it is ready for commit\n     */\n    Response prepare();\n\n    /**\n     * Returns true if transaction is active else false.\n     * \n     * @return boolean true.\n     */\n    boolean isActive();\n\n    /**\n     * \n     * Response enum\n     * \n     */\n    enum Response\n    {\n        YES, NO;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/api/Batcher.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.api;\n\nimport com.impetus.kundera.graph.Node;\n\n/**\n * API to handler batch operations.\n * \n * @author vivek.mishra\n * \n */\npublic interface Batcher\n{\n\n    /**\n     * Adds node to batch collection.\n     * \n     * @param node\n     *            data node.\n     */\n    void addBatch(Node node);\n\n    /**\n     * executes batch.\n     * \n     * @return returns number of records persisted/update via batch.\n     */\n    int executeBatch();\n\n    /**\n     * Returns batch size\n     * \n     * @return batch size as integer\n     */\n    int getBatchSize();\n\n    /**\n     * In case user asked for\n     */\n    void clear();\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/context/CacheBase.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence.context;\n\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.NodeLink;\nimport com.impetus.kundera.graph.ObjectGraph;\nimport com.impetus.kundera.graph.ObjectGraphUtils;\nimport com.impetus.kundera.lifecycle.states.ManagedState;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.ObjectUtils;\n\n/**\n * Base class for all cache required in persistence context\n * \n * @author amresh.singh\n */\npublic class CacheBase\n{\n    private static Logger log = LoggerFactory.getLogger(CacheBase.class);\n\n    private Map<String, Node> nodeMappings;\n\n    private Set<Node> headNodes;\n\n    private com.impetus.kundera.cache.Cache l2Cache;\n\n    private PersistenceCache persistenceCache;\n\n    public CacheBase(com.impetus.kundera.cache.Cache l2Cache, PersistenceCache pc)\n    {\n        this.headNodes = new HashSet<Node>();\n        this.nodeMappings = new ConcurrentHashMap<String, Node>();\n        this.l2Cache = l2Cache;\n        this.persistenceCache = pc;\n    }\n\n    public Node getNodeFromCache(String nodeId, PersistenceDelegator pd)\n    {\n        Node node = nodeMappings.get(nodeId);\n        // if not present in first level cache, check from second level cache.\n        return node != null ? node : lookupL2Cache(nodeId, pd);\n    }\n\n    public Node getNodeFromCache(Object entity, EntityMetadata entityMetadata, PersistenceDelegator pd)\n    {\n        if (entity == null)\n        {\n            throw new IllegalArgumentException(\"Entity is null, can't check whether it's in persistence context\");\n        }\n        Object primaryKey = PropertyAccessorHelper.getId(entity, entityMetadata);\n\n        if (primaryKey == null)\n        {\n            throw new IllegalArgumentException(\"Primary key not set into entity\");\n        }\n        String nodeId = ObjectGraphUtils.getNodeId(primaryKey, entity.getClass());\n        return getNodeFromCache(nodeId, pd);\n    }\n\n    public synchronized void addNodeToCache(Node node)\n    {\n        // Make a deep copy of Node data and and set into node\n        // Original data object is now detached from Node and is possibly\n        // referred by user code\n        Object nodeDataCopy = ObjectUtils.deepCopy(node.getData(), node.getPersistenceDelegator().getKunderaMetadata());\n        node.setData(nodeDataCopy);\n\n        /*\n         * check if this node already exists in cache node mappings If yes,\n         * update parents and children links Otherwise, just simply add the node\n         * to cache node mappings\n         */\n\n        processNodeMapping(node);\n\n        if (l2Cache != null)\n        {\n            l2Cache.put(node.getNodeId(), node.getData());\n        }\n    }\n\n    public void processNodeMapping(Node node)\n    {\n        if (nodeMappings.containsKey(node.getNodeId()))\n        {\n            Node existingNode = nodeMappings.get(node.getNodeId());\n\n            if (existingNode.getParents() != null)\n            {\n                if (node.getParents() == null)\n                {\n                    node.setParents(new HashMap<NodeLink, Node>());\n                }\n                node.getParents().putAll(existingNode.getParents());\n            }\n\n            if (existingNode.getChildren() != null)\n            {\n                if (node.getChildren() == null)\n                {\n                    node.setChildren(new HashMap<NodeLink, Node>());\n                }\n                node.getChildren().putAll(existingNode.getChildren());\n            }\n\n            nodeMappings.put(node.getNodeId(), node);\n            logCacheEvent(\"ADDED TO \", node.getNodeId());\n        }\n        else\n        {\n            logCacheEvent(\"ADDED TO \", node.getNodeId());\n            nodeMappings.put(node.getNodeId(), node);\n        }\n\n        // If it's a head node, add this to the list of head nodes in\n        // Persistence Cache\n        if (node.isHeadNode())\n        {\n            node.getPersistenceCache().getMainCache().addHeadNode(node);\n        }\n    }\n\n    public synchronized void removeNodeFromCache(Node node)\n    {\n        if (getHeadNodes().contains(node))\n        {\n            getHeadNodes().remove(node);\n        }\n\n        if (nodeMappings.get(node.getNodeId()) != null)\n        {\n            nodeMappings.remove(node.getNodeId());\n        }\n\n        evictFroml2Cache(node);\n        logCacheEvent(\"REMOVED FROM \", node.getNodeId());\n        node = null; // Eligible for GC\n    }\n\n    public void addGraphToCache(ObjectGraph graph, PersistenceCache persistenceCache)\n    {\n        // Add each node in the graph to cache\n        for (String key : graph.getNodeMapping().keySet())\n        {\n            Node thisNode = graph.getNodeMapping().get(key);\n            addNodeToCache(thisNode);\n\n            // Remove all those head nodes in persistence cache, that are there\n            // in Graph as a non-head node\n            if (!thisNode.isHeadNode() && persistenceCache.getMainCache().getHeadNodes().contains(thisNode))\n            {\n                persistenceCache.getMainCache().getHeadNodes().remove(thisNode);\n            }\n        }\n        // Add head Node to list of head nodes\n        addHeadNode(graph.getHeadNode());\n    }\n\n    private void logCacheEvent(String eventType, String nodeId)\n    {\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"Node: \" + nodeId + \":: \" + eventType + \" Persistence Context\");\n        }\n    }\n\n    /**\n     * @param nodeMappings\n     *            the nodeMappings to set\n     */\n    public void setNodeMappings(Map<String, Node> nodeMappings)\n    {\n        this.nodeMappings = nodeMappings;\n    }\n\n    public synchronized void addHeadNode(Node headNode)\n    {\n        headNodes.add(headNode);\n    }\n\n    public int size()\n    {\n        return nodeMappings.size();\n    }\n\n    public Collection<Node> getAllNodes()\n    {\n        return nodeMappings.values();\n    }\n\n    /**\n     * \n     */\n    public void clear()\n    {\n        if (this.nodeMappings != null)\n        {\n            this.nodeMappings.clear();\n        }\n\n        if (this.headNodes != null)\n        {\n            this.headNodes.clear();\n        }\n\n        if (this.l2Cache != null)\n        {\n            l2Cache.evictAll();\n        }\n    }\n\n    /**\n     * @return the headNodes\n     */\n    public Set<Node> getHeadNodes()\n    {\n        return Collections.synchronizedSet(headNodes);\n    }\n\n    private Node lookupL2Cache(String nodeId, PersistenceDelegator pd)\n    {\n        Node node = null;\n        if (l2Cache != null)\n        {\n            Object entity = l2Cache.get(nodeId);\n            if (entity != null)\n            {\n                node = new Node(nodeId, entity.getClass(), new ManagedState(), this.persistenceCache,\n                        nodeId.substring(nodeId.indexOf(\"$\") + 1), pd);\n                node.setData(entity);\n            }\n        }\n\n        return node;\n    }\n\n    private void evictFroml2Cache(Node node)\n    {\n        if (l2Cache != null)\n        {\n            this.l2Cache.evict(node.getDataClass(), node.getNodeId());\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/context/ElementCollectionCache.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence.context;\n\n\n/**\n * <Prove description of functionality provided by this Type>\n * \n * @author amresh.singh\n */\npublic class ElementCollectionCache extends CacheBase\n{\n\n    public ElementCollectionCache(com.impetus.kundera.cache.Cache l2Cache, PersistenceCache pc)\n    {\n        super(l2Cache, pc);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/context/EmbeddedCache.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence.context;\n\n\n/**\n * <Prove description of functionality provided by this Type>\n * \n * @author amresh.singh\n */\npublic class EmbeddedCache extends CacheBase\n{\n\n    public EmbeddedCache(com.impetus.kundera.cache.Cache l2Cache, PersistenceCache pc)\n    {\n        super(l2Cache, pc);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/context/EventLog.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.context;\n\nimport com.impetus.kundera.graph.Node;\n\n/**\n * Logs CRUD events,\n * \n * @author vivek.mishra\n * \n */\npublic class EventLog\n{\n\n    private EventType eventType;\n\n    private long timeinMillies;\n\n    private Node node;\n\n    EventLog(EventType eventType, Node transactional)\n    {\n        this.node = transactional;\n        this.eventType = eventType;\n        this.timeinMillies = System.currentTimeMillis();\n    }\n\n    Node getSavePointData()\n    {\n        return node.getOriginalNode();\n    }\n\n    /**\n     * @return the entityId\n     */\n    Object getEntityId()\n    {\n        return node.getNodeId();\n    }\n\n    /**\n     * @return the eventType\n     */\n    EventType getEventType()\n    {\n        return eventType;\n    }\n\n    /**\n     * @return the timeinMillies\n     */\n    long getTimeinMillies()\n    {\n        return timeinMillies;\n    }\n\n    /**\n     * @return the node\n     */\n    Node getNode()\n    {\n        return node;\n    }\n\n    public enum EventType\n    {\n        INSERT, UPDATE, DELETE;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/context/EventLogQueue.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.context;\n\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.persistence.context.EventLog.EventType;\n\n/**\n * The Class EventLogQueue.\n * \n * @author vivek.mishra\n */\nclass EventLogQueue\n{\n\n    /** The insert events. */\n    private Map<Object, EventLog> insertEvents;\n\n    /** The update events. */\n    private Map<Object, EventLog> updateEvents;\n\n    /** The delete events. */\n    private Map<Object, EventLog> deleteEvents;\n\n    /**\n     * On event.\n     * \n     * @param log\n     *            the log\n     * @param eventType\n     *            the event type\n     */\n    void onEvent(EventLog log, EventType eventType)\n    {\n\n        switch (eventType)\n        {\n        case INSERT:\n\n            onInsert(log);\n            break;\n\n        case UPDATE:\n            onUpdate(log);\n            break;\n\n        case DELETE:\n            onDelete(log);\n            break;\n\n        default:\n\n            throw new KunderaException(\"Invalid event type:\" + eventType);\n        }\n\n    }\n\n    /**\n     * On delete.\n     * \n     * @param log\n     *            the log\n     */\n    private void onDelete(EventLog log)\n    {\n        if (deleteEvents == null)\n        {\n            deleteEvents = new ConcurrentHashMap<Object, EventLog>();\n        }\n\n        deleteEvents.put(log.getEntityId(), log);\n\n    }\n\n    /**\n     * On update.\n     * \n     * @param log\n     *            the log\n     */\n    private void onUpdate(EventLog log)\n    {\n        if (updateEvents == null)\n        {\n            updateEvents = new ConcurrentHashMap<Object, EventLog>();\n\n        }\n\n        updateEvents.put(log.getEntityId(), log);\n    }\n\n    /**\n     * On insert.\n     * \n     * @param log\n     *            the log\n     */\n    private void onInsert(EventLog log)\n    {\n        if (insertEvents == null)\n        {\n            insertEvents = new ConcurrentHashMap<Object, EventLog>();\n        }\n\n        insertEvents.put(log.getEntityId(), log);\n\n    }\n\n    /**\n     * Clear.\n     */\n    void clear()\n    {\n        if (this.insertEvents != null)\n        {\n            insertEvents.clear();\n            insertEvents = null;\n\n        }\n        if (this.updateEvents != null)\n        {\n            updateEvents.clear();\n            updateEvents = null;\n\n        }\n        if (this.deleteEvents != null)\n        {\n            deleteEvents.clear();\n            deleteEvents = null;\n\n        }\n    }\n\n    /**\n     * Gets the insert events.\n     * \n     * @return the insert events\n     */\n    Map<Object, EventLog> getInsertEvents()\n    {\n        return insertEvents;\n    }\n\n    /**\n     * Gets the update events.\n     * \n     * @return the update events\n     */\n    Map<Object, EventLog> getUpdateEvents()\n    {\n        return updateEvents;\n    }\n\n    /**\n     * Gets the delete events.\n     * \n     * @return the delete events\n     */\n    Map<Object, EventLog> getDeleteEvents()\n    {\n        return deleteEvents;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/context/FlushManager.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence.context;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Deque;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.LinkedBlockingDeque;\n\nimport javax.persistence.CascadeType;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.NodeLink;\nimport com.impetus.kundera.graph.NodeLink.LinkProperty;\nimport com.impetus.kundera.lifecycle.states.ManagedState;\nimport com.impetus.kundera.lifecycle.states.RemovedState;\nimport com.impetus.kundera.lifecycle.states.TransientState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.JoinTableMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.persistence.context.EventLog.EventType;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData.OPERATION;\n\n/**\n * Provides utility methods for managing Flush Stack.\n * \n * @author amresh.singh\n */\npublic class FlushManager\n{\n\n    /**\n     * Deque containing Nodes to be flushed Entities are always flushed from the\n     * start, there way to end until deque is empty.\n     */\n    private Deque<Node> stackQueue;\n\n    /**\n     * Map containing data required for inserting records for each join table.\n     * Key -> Name of Join Table Value -> records to be persisted in the join\n     * table\n     */\n    private List<JoinTableData> joinTableDataCollection = new ArrayList<JoinTableData>();\n\n    /** The event log queue. */\n    private EventLogQueue eventLogQueue = new EventLogQueue();\n\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(FlushManager.class);\n\n    private static Map<EventType, List<CascadeType>> cascadePermission = new HashMap<EventType, List<CascadeType>>();\n\n    static\n    {\n        List<CascadeType> cascades = new ArrayList<CascadeType>();\n        cascades.add(CascadeType.ALL);\n        cascades.add(CascadeType.PERSIST);\n\n        cascadePermission.put(EventType.INSERT, cascades);\n        \n        cascades = new ArrayList<CascadeType>();\n        cascades.add(CascadeType.ALL);\n        cascades.add(CascadeType.MERGE);\n        cascadePermission.put(EventType.UPDATE, cascades);\n        \n        cascades = new ArrayList<CascadeType>();\n        cascades.add(CascadeType.ALL);\n        cascades.add(CascadeType.REMOVE);\n        cascadePermission.put(EventType.DELETE, cascades);\n\n        // cascades.remove(CascadeType.REMOVE);\n        // cascades.add(CascadeType.REFRESH);\n        // cascadePermission.put(com.impetus.kundera.lifecycle.states.NodeState.OPERATION.REFRESH,\n        // cascades);\n\n        // cascades.remove(CascadeType.REFRESH);\n        // cascades.add(CascadeType.DETACH);\n        // cascadePermission.put(com.impetus.kundera.lifecycle.states.NodeState.OPERATION.DETACH,\n        // cascades);\n    }\n\n    /**\n     * Instantiates a new flush manager.\n     */\n    public FlushManager()\n    {\n        stackQueue = new LinkedBlockingDeque<Node>();\n    }\n\n    /**\n     * Builds the flush stack.\n     * \n     * @param headNode\n     *            the head node\n     * @param eventType\n     *            the event type\n     */\n    public void buildFlushStack(Node headNode, EventType eventType)\n    {\n        if (headNode != null)\n        {\n            headNode.setTraversed(false);\n            addNodesToFlushStack(headNode, eventType);\n        }\n    }\n\n    /**\n     * Adds the nodes to flush stack.\n     * \n     * @param node\n     *            the node\n     * @param eventType\n     *            the event type\n     */\n    private void addNodesToFlushStack(Node node, EventType eventType)\n    {\n\n        Map<NodeLink, Node> children = node.getChildren();\n\n        performOperation(node, eventType);\n\n        // If this is a leaf node (not having any child, no need to go any\n        // deeper\n        if (children != null)\n        {\n            Map<NodeLink, Node> oneToOneChildren = new HashMap<NodeLink, Node>();\n            Map<NodeLink, Node> oneToManyChildren = new HashMap<NodeLink, Node>();\n            Map<NodeLink, Node> manyToOneChildren = new HashMap<NodeLink, Node>();\n            Map<NodeLink, Node> manyToManyChildren = new HashMap<NodeLink, Node>();\n\n            for (NodeLink nodeLink : children.keySet())\n            {\n                List<CascadeType> cascadeTypes = (List<CascadeType>) nodeLink.getLinkProperty(LinkProperty.CASCADE);\n\n                if (cascadeTypes.contains(cascadePermission.get(eventType).get(0))\n                        || cascadeTypes.contains(cascadePermission.get(eventType).get(1)))\n                {\n                    Relation.ForeignKey multiplicity = nodeLink.getMultiplicity();\n\n                    Node childNode = children.get(nodeLink);\n\n                    switch (multiplicity)\n                    {\n                    case ONE_TO_ONE:\n                        oneToOneChildren.put(nodeLink, childNode);\n                        break;\n                    case ONE_TO_MANY:\n                        oneToManyChildren.put(nodeLink, childNode);\n                        break;\n                    case MANY_TO_ONE:\n                        manyToOneChildren.put(nodeLink, childNode);\n                        break;\n                    case MANY_TO_MANY:\n                        manyToManyChildren.put(nodeLink, childNode);\n                        break;\n                    }\n                }\n            }\n\n            // Process One-To-Many children\n            for (NodeLink nodeLink : oneToManyChildren.keySet())\n            {\n                // Process child node Graph recursively first\n                Node childNode = children.get(nodeLink);\n\n                if (childNode != null && !childNode.isTraversed())\n                {\n                    addNodesToFlushStack(childNode, eventType);\n                }\n            }\n\n            // Process Many-To-Many children\n            for (NodeLink nodeLink : manyToManyChildren.keySet())\n            {\n                if (!node.isTraversed() && !(Boolean) nodeLink.getLinkProperty(LinkProperty.IS_RELATED_VIA_JOIN_TABLE))\n                {\n                    // Push this node to stack\n                    node.setTraversed(true);\n                    stackQueue.push(node);\n                    logEvent(node, eventType);\n                }\n\n                Node childNode = children.get(nodeLink);\n\n                if (childNode != null)\n                {\n                    // Extract information required to be persisted into\n                    // Join\n                    // Table\n                    if (node.isDirty() && !node.isTraversed())\n                    {\n                        // M-2-M relation fields that are Set or List are joined\n                        // by join table.\n                        // M-2-M relation fields that are Map aren't joined by\n                        // Join table\n\n                        JoinTableMetadata jtmd = (JoinTableMetadata) nodeLink\n                                .getLinkProperty(LinkProperty.JOIN_TABLE_METADATA);\n                        if (jtmd != null)\n                        {\n                            String joinColumnName = (String) jtmd.getJoinColumns().toArray()[0];\n                            String inverseJoinColumnName = (String) jtmd.getInverseJoinColumns().toArray()[0];\n                            Object entityId = node.getEntityId();\n                            Object childId = childNode.getEntityId();\n                            Set<Object> childValues = new HashSet<Object>();\n                            childValues.add(childId);\n\n                            OPERATION operation = null;\n                            if (node.getCurrentNodeState().getClass().equals(ManagedState.class))\n                            {\n                                operation = OPERATION.INSERT;\n                            }\n                            else if (node.getCurrentNodeState().getClass().equals(RemovedState.class))\n                            {\n                                operation = OPERATION.DELETE;\n                            }\n\n                            addJoinTableData(operation, jtmd.getJoinTableSchema(), jtmd.getJoinTableName(),\n                                    joinColumnName, inverseJoinColumnName, node.getDataClass(), entityId, childValues);\n                        }\n                    }\n\n                    // Process child node Graph recursively first\n                    if (!childNode.isTraversed())\n                    {\n                        addNodesToFlushStack(childNode, eventType);\n                    }\n                }\n            }\n            // Process One-To-One children\n            for (NodeLink nodeLink : oneToOneChildren.keySet())\n            {\n                if (!node.isTraversed())\n                {\n                    // Push this node to stack\n                    node.setTraversed(true);\n                    stackQueue.push(node);\n                    logEvent(node, eventType);\n                }\n\n                // Process child node Graph recursively\n                Node childNode = children.get(nodeLink);\n\n                addNodesToFlushStack(childNode, eventType);\n            }\n\n            // Process Many-To-One children\n            for (NodeLink nodeLink : manyToOneChildren.keySet())\n            {\n                if (!node.isTraversed())\n                {\n                    // Push this node to stack\n                    node.setTraversed(true);\n                    stackQueue.push(node);\n                    logEvent(node, eventType);\n                }\n\n                // Child node of this node\n                Node childNode = children.get(nodeLink);\n\n                // Process all parents of child node with Many-To-One\n                // relationship first\n                Map<NodeLink, Node> parents = childNode.getParents();\n                for (NodeLink parentLink : parents.keySet())\n                {\n                    List<CascadeType> cascadeTypes = (List<CascadeType>) nodeLink.getLinkProperty(LinkProperty.CASCADE);\n\n                    if (cascadeTypes.contains(cascadePermission.get(eventType).get(0))\n                            || cascadeTypes.contains(cascadePermission.get(eventType).get(1)))\n                    {\n                        Relation.ForeignKey multiplicity = parentLink.getMultiplicity();\n\n                        Node parentNode = parents.get(parentLink);\n\n//                        performOperation(parentNode, eventType);\n\n                        if (multiplicity.equals(Relation.ForeignKey.MANY_TO_ONE))\n                        {\n                            if (!parentNode.isTraversed() && parentNode.isDirty())\n                            {\n                                addNodesToFlushStack(parentNode, eventType);\n                            }\n                        }\n                    }\n                }\n\n                // Finally process this child node\n                if (!childNode.isTraversed() && childNode.isDirty())\n                {\n                    addNodesToFlushStack(childNode, eventType);\n                }\n                else if (!childNode.isDirty())\n                {\n                    childNode.setTraversed(true);\n                    stackQueue.push(childNode);\n                    logEvent(childNode, eventType);\n                }\n            }\n        }\n\n        // Finally, if this node itself is not traversed yet, (as may happen\n        // in\n        // 1-1 and M-1\n        // cases), push it to stack\n        if (!node.isTraversed() && node.isDirty())\n        {\n            node.setTraversed(true);\n            stackQueue.push(node);\n            logEvent(node, eventType);\n        }\n    }\n\n    /*    *//**\n     * Gets the flush stack.\n     * \n     * @return the flushStack\n     */\n    public Deque<Node> getFlushStack()\n    {\n        return stackQueue;\n    }\n\n    /**\n     * Gets the join table data map.\n     * \n     * @return the joinTableDataMap\n     */\n    public List<JoinTableData> getJoinTableData()\n    {\n        return joinTableDataCollection;\n    }\n\n    /**\n     * Empties Flush stack present in a PersistenceCache.\n     * \n     */\n    public void clearFlushStack()\n    {\n        if (stackQueue != null && !stackQueue.isEmpty())\n        {\n            stackQueue.clear();\n        }\n        if (joinTableDataCollection != null && !joinTableDataCollection.isEmpty())\n        {\n            joinTableDataCollection.clear();\n        }\n\n        if (eventLogQueue != null)\n        {\n            eventLogQueue.clear();\n        }\n    }\n\n    /**\n     * Rollback.\n     * \n     * @param delegator\n     *            the delegator\n     */\n    public void rollback(PersistenceDelegator delegator)\n    {\n        if (eventLogQueue != null)\n        {\n            onRollBack(delegator, eventLogQueue.getInsertEvents());\n            onRollBack(delegator, eventLogQueue.getUpdateEvents());\n            onRollBack(delegator, eventLogQueue.getDeleteEvents());\n\n            rollbackJoinTableData(delegator);\n        }\n    }\n\n    /**\n     * Rollback.\n     * \n     * @param delegator\n     *            the delegator\n     */\n    public void commit()\n    {\n        onCommit(eventLogQueue.getInsertEvents());\n        onCommit(eventLogQueue.getUpdateEvents());\n        onCommit(eventLogQueue.getDeleteEvents());\n    }\n\n    /**\n     * @param deleteEvents\n     */\n    private void onCommit(Map<Object, EventLog> eventCol)\n    {\n        if (eventCol != null && !eventCol.isEmpty())\n        {\n            Collection<EventLog> events = eventCol.values();\n            Iterator<EventLog> iter = events.iterator();\n\n            while (iter.hasNext())\n            {\n                try\n                {\n                    EventLog event = iter.next();\n                    Node node = event.getNode();\n                    if (node.isProcessed())\n                    {\n                        // One time set as required for rollback.\n                        Node original = node.clone();\n                        node.setOriginalNode(original);\n                    }\n\n                    // mark it null for garbage collection.\n                    event = null;\n                }\n                catch (Exception ex)\n                {\n                    log.warn(\"Caught exception during rollback, Caused by:\", ex);\n                    // bypass to next event\n                }\n\n            }\n        }\n    }\n\n    /**\n     * On roll back.\n     * \n     * @param delegator\n     *            the delegator\n     * @param eventCol\n     *            the event col\n     */\n    private void onRollBack(PersistenceDelegator delegator, Map<Object, EventLog> eventCol)\n    {\n        if (eventCol != null && !eventCol.isEmpty())\n        {\n            Collection<EventLog> events = eventCol.values();\n            Iterator<EventLog> iter = events.iterator();\n\n            while (iter.hasNext())\n            {\n                try\n                {\n                    EventLog event = iter.next();\n                    Node node = event.getNode();\n                    Class clazz = node.getDataClass();\n                    EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(), clazz);\n                    Client client = delegator.getClient(metadata);\n\n                    // do manual rollback, if data is processed, and running\n                    // without transaction or with kundera's default transaction\n                    // support!\n                    if (node.isProcessed()\n                            && (!delegator.isTransactionInProgress() || MetadataUtils\n                                    .defaultTransactionSupported(metadata.getPersistenceUnit(), delegator.getKunderaMetadata())))\n                    {\n                        if (node.getOriginalNode() == null)\n                        {\n                            Object entityId = node.getEntityId();\n                            client.remove(node.getData(), entityId);\n                        }\n                        else\n                        {\n                            client.persist(node.getOriginalNode());\n                        }\n                    }\n                    // mark it null for garbage collection.\n                    event = null;\n                }\n                catch (Exception ex)\n                {\n                    log.warn(\"Caught exception during rollback, Caused by:\", ex);\n                    // bypass to next event\n                }\n            }\n        }\n        // mark it null for garbage collection.\n        eventCol = null;\n    }\n\n    /**\n     * Adds the join table data into map.\n     * \n     * @param operation\n     *            the operation\n     * @param joinTableName\n     *            the join table name\n     * @param joinColumnName\n     *            the join column name\n     * @param invJoinColumnName\n     *            the inv join column name\n     * @param entityClass\n     *            the entity class\n     * @param joinColumnValue\n     *            the join column value\n     * @param invJoinColumnValues\n     *            the inv join column values\n     */\n    private void addJoinTableData(OPERATION operation, String schemaName, String joinTableName, String joinColumnName,\n            String invJoinColumnName, Class<?> entityClass, Object joinColumnValue, Set<Object> invJoinColumnValues)\n    {\n        JoinTableData joinTableData = new JoinTableData(operation, schemaName, joinTableName, joinColumnName,\n                invJoinColumnName, entityClass);\n        joinTableData.addJoinTableRecord(joinColumnValue, invJoinColumnValues);\n        joinTableDataCollection.add(joinTableData);\n    }\n\n    /**\n     * Log event.\n     * \n     * @param node\n     *            the node\n     * @param eventType\n     *            the event type\n     */\n    private void logEvent(Node node, EventType eventType)\n    {\n        // Node contains original as well as transactional copy.\n        EventLog log = new EventLog(eventType, node);\n        eventLogQueue.onEvent(log, eventType);\n    }\n\n    private void rollbackJoinTableData(PersistenceDelegator delegator)\n    {\n        // on deleting join table data.\n        for (JoinTableData jtData : joinTableDataCollection)\n        {\n            if (jtData.isProcessed())\n            {\n                EntityMetadata m = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(), jtData.getEntityClass());\n                Client client = delegator.getClient(m);\n\n                if (OPERATION.INSERT.equals(jtData.getOperation()))\n                {\n                    for (Object pk : jtData.getJoinTableRecords().keySet())\n                    {\n                        client.deleteByColumn(jtData.getSchemaName(), jtData.getJoinTableName(), m.getIdAttribute()\n                                .getName(), pk);\n                    }\n                }\n                else if (OPERATION.DELETE.equals(jtData.getOperation()))\n                {\n                    client.persistJoinTable(jtData);\n                }\n            }\n        }\n        joinTableDataCollection.clear();\n        joinTableDataCollection = null;\n        joinTableDataCollection = new ArrayList<JoinTableData>();\n    }\n\n    /**\n     * @param nodeStateContext\n     */\n    private void performOperation(Node node, EventType eventType)\n    {\n        switch (eventType)\n        {\n        case INSERT:\n            node.persist();\n            break;\n\n        case UPDATE:\n            if (node.isInState(TransientState.class))\n            {\n                node.persist();\n            }\n            else\n            {\n                node.merge();\n            }\n            break;\n\n        case DELETE:\n            node.remove();\n            break;\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/context/MainCache.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence.context;\n\n\n/**\n * Main cache for the persistence context\n * \n * @author amresh.singh\n */\npublic class MainCache extends CacheBase\n{\n\n    public MainCache(com.impetus.kundera.cache.Cache l2Cache, PersistenceCache pc)\n    {\n        super(l2Cache,pc);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/context/PersistenceCache.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence.context;\n\nimport javax.persistence.PersistenceContextType;\n\n/**\n * Implementation of Persistence Context as defined in JPA. Acts as a cache of\n * entities.\n * \n * @author amresh.singh\n */\npublic class PersistenceCache\n{\n    /* Main Cache of entity objects */\n    private CacheBase mainCache;\n\n/*     Cache of embedded objects \n    private CacheBase embeddedCache;\n\n     Cache of objects within element collection \n    private CacheBase elementCollectionCache;\n\n     Cache of transactional objects \n    private CacheBase transactionalCache;\n*/\n    // FlushManager flushManager;\n\n    private PersistenceContextType persistenceContextType;\n\n    /**\n     * Stack containing Nodes to be flushed Entities are always flushed from the\n     * top, there way to bottom until stack is empty\n     */\n    // private FlushStack flushStack;\n\n    /**\n     * Map containing data required for inserting records for each join table.\n     * Key -> Name of Join Table Value -> records to be persisted in the join\n     * table\n     */\n    // private Map<String, JoinTableData> joinTableDataMap;\n\n    public PersistenceCache()\n    {\n        initialize(null,this);\n    }\n    \n    public PersistenceCache(com.impetus.kundera.cache.Cache l2Cache)\n    {\n        initialize(l2Cache,this);\n    }\n\n    private void initialize(com.impetus.kundera.cache.Cache l2Cache, PersistenceCache pc)\n    {\n        mainCache = new MainCache(l2Cache,this);\n//        embeddedCache = new EmbeddedCache(l2Cache);\n//        elementCollectionCache = new ElementCollectionCache(l2Cache);\n//        transactionalCache = new TransactionalCache(l2Cache);\n\n        // flushStack = new FlushStack();\n        // joinTableDataMap = new HashMap<String, JoinTableData>();\n        //\n        // flushManager = new FlushManager();\n    }\n\n    /**\n     * Cleaned out the data.\n     * \n     */\n    public void clean()\n    {\n        // Clear main cache.\n        if (mainCache != null)\n        {\n            mainCache.clear();\n        }\n\n/*        if (embeddedCache != null)\n        {\n            embeddedCache.clear();\n        }\n        if (elementCollectionCache != null)\n        {\n            elementCollectionCache.clear();\n        }\n        if (transactionalCache != null)\n        {\n            transactionalCache.clear();\n        }\n*/    }\n\n    /**\n     * @return the mainCache\n     */\n    public CacheBase getMainCache()\n    {\n        return mainCache;\n    }\n\n/*    *//**\n     * @param mainCache\n     *            the mainCache to set\n     *//*\n    public void setMainCache(CacheBase mainCache)\n    {\n        this.mainCache = mainCache;\n    }\n*/\n/*    *//**\n     * @return the embeddedCache\n     *//*\n    public CacheBase getEmbeddedCache()\n    {\n        return embeddedCache;\n    }\n\n    *//**\n     * @param embeddedCache\n     *            the embeddedCache to set\n     *//*\n    public void setEmbeddedCache(CacheBase embeddedCache)\n    {\n        this.embeddedCache = embeddedCache;\n    }\n\n    *//**\n     * @return the elementCollectionCache\n     *//*\n    public CacheBase getElementCollectionCache()\n    {\n        return elementCollectionCache;\n    }\n\n    *//**\n     * @param elementCollectionCache\n     *            the elementCollectionCache to set\n     *//*\n    public void setElementCollectionCache(CacheBase elementCollectionCache)\n    {\n        this.elementCollectionCache = elementCollectionCache;\n    }\n\n    *//**\n     * @return the transactionalCache\n     *//*\n    public CacheBase getTransactionalCache()\n    {\n        return transactionalCache;\n    }\n\n    *//**\n     * @param transactionalCache\n     *            the transactionalCache to set\n     *//*\n    public void setTransactionalCache(CacheBase transactionalCache)\n    {\n        this.transactionalCache = transactionalCache;\n    }\n*/\n    /**\n     * @return the persistenceContextType\n     */\n    public PersistenceContextType getPersistenceContextType()\n    {\n        return persistenceContextType;\n    }\n\n    /**\n     * @param persistenceContextType\n     *            the persistenceContextType to set\n     */\n    public void setPersistenceContextType(PersistenceContextType persistenceContextType)\n    {\n        this.persistenceContextType = persistenceContextType;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/context/PersistenceCacheManager.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.context;\n\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.ObjectGraphUtils;\nimport com.impetus.kundera.lifecycle.states.ManagedState;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\n\n/**\n * @author amresh\n * \n */\npublic class PersistenceCacheManager\n{\n    private PersistenceCache persistenceCache;\n\n    public PersistenceCacheManager(PersistenceCache pc)\n    {\n        this.persistenceCache = pc;\n    }\n\n    public void clearPersistenceCache()\n    {\n        persistenceCache.clean();\n\n    } // cleanIndividualCache(pc.getMainCache());\n      // cleanIndividualCache(pc.getEmbeddedCache());\n      // cleanIndividualCache(pc.getElementCollectionCache());\n      // cleanIndividualCache(pc.getTransactionalCache());\n\n    private void cleanIndividualCache(CacheBase cache)\n    {\n        for (Node node : cache.getAllNodes())\n        {\n            node.clear();\n        }\n    }\n\n    public void markAllNodesNotTraversed()\n    {\n        for (Node node : persistenceCache.getMainCache().getAllNodes())\n        {\n            node.setTraversed(false);\n        }\n\n/*        for (Node node : persistenceCache.getEmbeddedCache().getAllNodes())\n        {\n            node.setTraversed(false);\n        }\n\n        for (Node node : persistenceCache.getElementCollectionCache().getAllNodes())\n        {\n            node.setTraversed(false);\n        }\n\n        for (Node node : persistenceCache.getTransactionalCache().getAllNodes())\n        {\n            node.setTraversed(false);\n        }*/\n    }\n\n    /**\n     * @param entity\n     * @param pd\n     * @param entityId\n     */\n    public static void addEntityToPersistenceCache(Object entity, PersistenceDelegator pd, Object entityId)\n    {\n        MainCache mainCache = (MainCache) pd.getPersistenceCache().getMainCache();\n        String nodeId = ObjectGraphUtils.getNodeId(entityId, entity.getClass());\n        Node node = new Node(nodeId, entity.getClass(), new ManagedState(), pd.getPersistenceCache(), entityId, pd);\n        node.setData(entity);\n        node.setPersistenceDelegator(pd);\n        mainCache.addNodeToCache(node);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/context/TransactionalCache.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence.context;\n\n\n/**\n * <Prove description of functionality provided by this Type>\n * \n * @author amresh.singh\n */\npublic class TransactionalCache extends CacheBase\n{\n\n    public TransactionalCache(com.impetus.kundera.cache.Cache l2Cache, PersistenceCache pc)\n    {\n        super(l2Cache, pc);\n    }\n\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/context/jointable/JoinTableData.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence.context.jointable;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\n/**\n * Holds data required prior to persisting records in Join Table\n * \n * @author amresh.singh\n */\npublic class JoinTableData\n{\n    private String joinTableName;\n\n    private String schemaName;\n\n    private Class<?> entityClass;\n\n    private String joinColumnName;\n\n    private String inverseJoinColumnName;\n\n    private boolean isProcessed;\n\n    public static enum OPERATION\n    {\n        INSERT, UPDATE, DELETE\n    }\n\n    /**\n     * Operation to be performed on this Join Table data\n     * \n     * @See {@link OPERATION}\n     */\n    private OPERATION operation;\n\n    /**\n     * Key -> Primary key of entity at the Join column side Value -> Set of\n     * primary keys of entities at the inverse join column side\n     */\n    Map<Object, Set<Object>> joinTableRecords;\n\n    public JoinTableData(OPERATION operation, String schemaName, String joinTableName, String joinColumnName,\n            String inverseJoinColumnName, Class<?> entityClass)\n    {\n        this.operation = operation;\n        this.schemaName = schemaName;\n        this.joinTableName = joinTableName;\n        this.joinColumnName = joinColumnName;\n        this.inverseJoinColumnName = inverseJoinColumnName;\n        this.entityClass = entityClass;\n\n        joinTableRecords = new HashMap<Object, Set<Object>>();\n    }\n\n    /**\n     * @return the joinTableName\n     */\n    public String getJoinTableName()\n    {\n        return joinTableName;\n    }\n\n    /**\n     * @param joinTableName\n     *            the joinTableName to set\n     */\n    public void setJoinTableName(String joinTableName)\n    {\n        this.joinTableName = joinTableName;\n    }\n\n    /**\n     * @return the joinColumnName\n     */\n    public String getJoinColumnName()\n    {\n        return joinColumnName;\n    }\n\n    /**\n     * @param joinColumnName\n     *            the joinColumnName to set\n     */\n    public void setJoinColumnName(String joinColumnName)\n    {\n        this.joinColumnName = joinColumnName;\n    }\n\n    /**\n     * @return the inverseJoinColumnName\n     */\n    public String getInverseJoinColumnName()\n    {\n        return inverseJoinColumnName;\n    }\n\n    /**\n     * @param inverseJoinColumnName\n     *            the inverseJoinColumnName to set\n     */\n    public void setInverseJoinColumnName(String inverseJoinColumnName)\n    {\n        this.inverseJoinColumnName = inverseJoinColumnName;\n    }\n\n    /**\n     * @return the joinTableRecords\n     */\n    public Map<Object, Set<Object>> getJoinTableRecords()\n    {\n        return joinTableRecords;\n    }\n\n    /**\n     * @return the entityClass\n     */\n    public Class<?> getEntityClass()\n    {\n        return entityClass;\n    }\n\n    /**\n     * @param entityClass\n     *            the entityClass to set\n     */\n    public void setEntityClass(Class<?> entityClass)\n    {\n        this.entityClass = entityClass;\n    }\n\n    /**\n     * @return the operation\n     */\n    public OPERATION getOperation()\n    {\n        return operation;\n    }\n\n    /**\n     * @param operation\n     *            the operation to set\n     */\n    public void setOperation(OPERATION operation)\n    {\n        this.operation = operation;\n    }\n\n    /**\n     * @param joinTableRecords\n     *            the joinTableRecords to set\n     */\n    public void addJoinTableRecord(Object key, Set<Object> values)\n    {\n        Set<Object> existingValues = joinTableRecords.get(key);\n        if (existingValues == null)\n        {\n            existingValues = new HashSet<Object>();\n            existingValues.addAll(values);\n            joinTableRecords.put(key, existingValues);\n        }\n        else\n        {\n            existingValues.addAll(values);\n        }\n    }\n\n    /**\n     * @return the isProcessed\n     */\n    public boolean isProcessed()\n    {\n        return isProcessed;\n    }\n\n    /**\n     * @param isProcessed\n     *            the isProcessed to set\n     */\n    public void setProcessed(boolean isProcessed)\n    {\n        this.isProcessed = isProcessed;\n    }\n\n    /**\n     * @return the schemaName\n     */\n    public String getSchemaName()\n    {\n        return schemaName;\n    }\n\n    /**\n     * @param schemaName\n     *            the schemaName to set\n     */\n    public void setSchemaName(String schemaName)\n    {\n        this.schemaName = schemaName;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/event/CallbackMethod.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.persistence.event;\r\n\r\nimport java.lang.reflect.InvocationTargetException;\r\n\r\n/**\r\n * Interface that defines how JPA Entity Listeners can be called.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic interface CallbackMethod\r\n{\r\n\r\n    /**\r\n     * Invokes the method with entity object.\r\n     * \r\n     * @param entity\r\n     *            the entity\r\n     * \r\n     * @throws IllegalArgumentException\r\n     *             the illegal argument exception\r\n     * @throws IllegalAccessException\r\n     *             the illegal access exception\r\n     * @throws InvocationTargetException\r\n     *             the invocation target exception\r\n     * @throws InstantiationException\r\n     *             the instantiation exception\r\n     */\r\n    public void invoke(Object entity) throws EventListenerException;\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/event/EntityEventDispatcher.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.persistence.event;\r\n\r\nimport java.util.List;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.PersistenceException;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\n\r\n/**\r\n * The Class EntityEventDispatcher.\r\n */\r\npublic class EntityEventDispatcher\r\n{\r\n\r\n    /** The Constant log. */\r\n    private static final Logger log = LoggerFactory.getLogger(EntityManager.class);\r\n\r\n    /**\r\n     * Fire event listeners.\r\n     * \r\n     * @param metadata\r\n     *            the metadata\r\n     * @param entity\r\n     *            the entity\r\n     * @param event\r\n     *            the event\r\n     * @throws PersistenceException\r\n     *             the persistence exception\r\n     */\r\n    public void fireEventListeners(EntityMetadata metadata, Object entity, Class<?> event)\r\n    {\r\n\r\n        // handle external listeners first\r\n        List<? extends CallbackMethod> callBackMethods = metadata.getCallbackMethods(event);\r\n\r\n        if (null != callBackMethods && !callBackMethods.isEmpty() && null != entity)\r\n        {\r\n            log.debug(\"Callback >> \" + event.getSimpleName() + \" on \" + metadata.getEntityClazz().getName());\r\n            for (CallbackMethod callback : callBackMethods)\r\n            {\r\n                log.debug(\"Firing >> \" + callback);\r\n\r\n                callback.invoke(entity);\r\n\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/event/EventListenerException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.event;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * @author amresh\n * \n */\npublic class EventListenerException extends KunderaException\n{\n\n    /**\n     * \n     */\n    public EventListenerException()\n    {\n\n    }\n\n    /**\n     * @param arg0\n     */\n    public EventListenerException(String arg0)\n    {\n        super(arg0);\n    }\n\n    /**\n     * @param arg0\n     */\n    public EventListenerException(Throwable arg0)\n    {\n        super(arg0);\n    }\n\n    /**\n     * @param arg0\n     * @param arg1\n     */\n    public EventListenerException(String arg0, Throwable arg1)\n    {\n        super(arg0, arg1);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/event/ExternalCallbackMethod.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.persistence.event;\r\n\r\nimport java.lang.reflect.InvocationTargetException;\r\nimport java.lang.reflect.Method;\r\n\r\n/**\r\n * Class to hold class-method instances for EntityListeners.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic final class ExternalCallbackMethod implements CallbackMethod\r\n{\r\n\r\n    /** The clazz. */\r\n    private Class<?> clazz;\r\n\r\n    /** The method. */\r\n    private Method method;\r\n\r\n    /**\r\n     * Instantiates a new external callback method.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     * @param method\r\n     *            the method\r\n     */\r\n    public ExternalCallbackMethod(Class<?> clazz, Method method)\r\n    {\r\n        this.clazz = clazz;\r\n        this.method = method;\r\n    }\r\n\r\n    public void invoke(Object entity) throws EventListenerException\r\n    {\r\n        if (!method.isAccessible())\r\n            method.setAccessible(true);\r\n        try\r\n        {\r\n            method.invoke(clazz.newInstance(), new Object[] { entity });\r\n        }\r\n        catch (IllegalArgumentException e)\r\n        {\r\n            throw new EventListenerException(e);\r\n        }\r\n        catch (IllegalAccessException e)\r\n        {\r\n            throw new EventListenerException(e);\r\n        }\r\n        catch (InvocationTargetException e)\r\n        {\r\n            throw new EventListenerException(e);\r\n        }\r\n        catch (InstantiationException e)\r\n        {\r\n            throw new EventListenerException(e);\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public String toString()\r\n    {\r\n        StringBuilder builder = new StringBuilder();\r\n        builder.append(clazz.getName() + \".\" + method.getName());\r\n        return builder.toString();\r\n    }\r\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/event/InternalCallbackMethod.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.persistence.event;\r\n\r\nimport java.lang.reflect.InvocationTargetException;\r\nimport java.lang.reflect.Method;\r\n\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\n\r\n/**\r\n * The Class InternalCallbackMethod.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic final class InternalCallbackMethod implements CallbackMethod\r\n{\r\n\r\n    /** The entity metadata. */\r\n    private final EntityMetadata entityMetadata;\r\n\r\n    /** The method. */\r\n    private Method method;\r\n\r\n    /**\r\n     * Instantiates a new internal callback method.\r\n     * \r\n     * @param entityMetadata\r\n     *            TODO\r\n     * @param method\r\n     *            the method\r\n     */\r\n    public InternalCallbackMethod(EntityMetadata entityMetadata, Method method)\r\n    {\r\n        this.entityMetadata = entityMetadata;\r\n        this.method = method;\r\n    }\r\n\r\n    /*\r\n     * @see\r\n     * com.impetus.kundera.ejb.event.CallbackMethod#invoke(java.lang.Object)\r\n     */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.ejb.event.CallbackMethod#invoke(java.lang.Object)\r\n     */\r\n    public void invoke(Object entity) throws EventListenerException\r\n    {\r\n        if (!method.isAccessible())\r\n            method.setAccessible(true);\r\n        try\r\n        {\r\n            method.invoke(entity, new Object[] {});\r\n        }\r\n        catch (IllegalArgumentException e)\r\n        {\r\n            throw new EventListenerException(e);\r\n        }\r\n        catch (IllegalAccessException e)\r\n        {\r\n            throw new EventListenerException(e);\r\n        }\r\n        catch (InvocationTargetException e)\r\n        {\r\n            throw new EventListenerException(e);\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public String toString()\r\n    {\r\n        StringBuilder builder = new StringBuilder();\r\n        builder.append(this.entityMetadata.getEntityClazz().getName() + \".\" + method.getName());\r\n        return builder.toString();\r\n    }\r\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/jta/KunderaJTAUserTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.jta;\n\nimport java.io.Serializable;\n\nimport javax.naming.NamingException;\nimport javax.naming.Reference;\nimport javax.naming.Referenceable;\nimport javax.transaction.HeuristicMixedException;\nimport javax.transaction.HeuristicRollbackException;\nimport javax.transaction.NotSupportedException;\nimport javax.transaction.RollbackException;\nimport javax.transaction.Status;\nimport javax.transaction.SystemException;\nimport javax.transaction.Transaction;\nimport javax.transaction.UserTransaction;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.persistence.ResourceManager;\n\n/**\n * Kundera implementation for JTA <code> UserTransaction</code>\n * \n * This needs to hooked up with initial context for use of Kundera's\n * commit/rollback handling.\n * \n * @author vivek.mishra@impetus.co.in\n * \n */\n\npublic class KunderaJTAUserTransaction implements UserTransaction, Referenceable, Serializable\n{\n\n    /** The thread local. */\n    private static transient ThreadLocal<KunderaTransaction> threadLocal = new ThreadLocal<KunderaTransaction>();\n\n    /** The timer thead. */\n    private static transient ThreadLocal<Integer> timerThead = new ThreadLocal<Integer>();\n\n    /** The Constant DEFAULT_TIME_OUT. */\n    private static final Integer DEFAULT_TIME_OUT = 60;\n\n    /** The current tx. */\n    private static transient KunderaJTAUserTransaction currentTx;\n\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(KunderaJTAUserTransaction.class);\n\n    /**\n     * Instantiates a new kundera jta user transaction.\n     */\n    public KunderaJTAUserTransaction()\n    {\n        currentTx = this;\n    }\n\n    /**\n     * Gets the current tx.\n     * \n     * @return the current tx\n     */\n    public static KunderaJTAUserTransaction getCurrentTx()\n    {\n        return currentTx;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.transaction.UserTransaction#begin()\n     */\n    @Override\n    public void begin() throws NotSupportedException, SystemException\n    {\n        if (log.isDebugEnabled())\n            log.info(\"beginning JTA transaction\");\n\n        Transaction tx = threadLocal.get();\n        if (tx != null)\n        {\n            if ((tx.getStatus() == Status.STATUS_MARKED_ROLLBACK))\n            {\n                throw new NotSupportedException(\"Nested Transaction not supported!\");\n            }\n        }\n\n        Integer timer = timerThead.get();\n        threadLocal.set(new KunderaTransaction(timer != null ? timer : DEFAULT_TIME_OUT));\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.transaction.UserTransaction#commit()\n     */\n    @Override\n    public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException,\n            SecurityException, IllegalStateException, SystemException\n    {\n        Transaction tx = threadLocal.get();\n\n        try\n        {\n            if (tx != null)\n            {\n                if (log.isDebugEnabled())\n                    log.info(\"Commiting transaction:\" + tx);\n                tx.commit();\n            }\n            else\n            {\n                log.debug(\"Cannot locate a transaction to commit.\");\n\n            }\n        }\n        finally\n        {\n            if (log.isDebugEnabled())\n                log.info(\"Resetting after commit.\");\n            threadLocal.set(null);\n            timerThead.set(null);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.transaction.UserTransaction#getStatus()\n     */\n    @Override\n    public int getStatus() throws SystemException\n    {\n        Transaction tx = threadLocal.get();\n        if (tx == null)\n        {\n            return Status.STATUS_NO_TRANSACTION;\n        }\n        return tx.getStatus();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.transaction.UserTransaction#rollback()\n     */\n    @Override\n    public void rollback() throws IllegalStateException, SecurityException, SystemException\n    {\n\n        try\n        {\n            Transaction tx = threadLocal.get();\n            if (tx == null)\n            {\n                throw new IllegalStateException(\"Cannot locate a Transaction for rollback.\");\n            }\n\n            if (log.isDebugEnabled())\n                log.info(\"Rollback transaction:\" + tx);\n\n            tx.rollback();\n\n        }\n        finally\n        {\n            if (log.isDebugEnabled())\n                log.info(\"Resetting after rollback.\");\n            threadLocal.set(null);\n            timerThead.set(null);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.transaction.UserTransaction#setRollbackOnly()\n     */\n    @Override\n    public void setRollbackOnly() throws IllegalStateException, SystemException\n    {\n        Transaction tx = threadLocal.get();\n        if (tx == null)\n        {\n            throw new IllegalStateException(\"Cannot get Transaction for setRollbackOnly\");\n        }\n        tx.setRollbackOnly();\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.transaction.UserTransaction#setTransactionTimeout(int)\n     */\n    @Override\n    public void setTransactionTimeout(int timeout) throws SystemException\n    {\n        Transaction tx = threadLocal.get();\n        if (tx == null)\n        {\n            timerThead.set(timeout);\n        }\n        else\n        {\n            if (log.isDebugEnabled())\n                log.debug(\"Cannot reset running transaction:\" + tx);\n        }\n\n    }\n\n    /**\n     * Returns transaction time out. If no timeout is associate with current\n     * thread, returns default timeout(e.g. 60).\n     * \n     * @return the transactionTimeout transaction timeout.\n     */\n    public int getTransactionTimeout()\n    {\n        Integer timeOut = timerThead.get();\n        if (timeOut == null)\n        {\n            return DEFAULT_TIME_OUT;\n        }\n        return timeOut;\n    }\n\n    /**\n     * Links referenced resource to current transaction thread.\n     * \n     * @param implementor\n     *            resource implementor.\n     */\n    public void setImplementor(ResourceManager implementor)\n    {\n        KunderaTransaction tx = threadLocal.get();\n        if (tx == null)\n        {\n            throw new IllegalStateException(\"Cannot get Transaction to start\");\n        }\n        tx.setImplementor(implementor);\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.naming.Referenceable#getReference()\n     */\n    @Override\n    public Reference getReference() throws NamingException\n    {\n        return UserTransactionFactory.getReference(this);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/jta/KunderaTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.jta;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.transaction.HeuristicMixedException;\nimport javax.transaction.HeuristicRollbackException;\nimport javax.transaction.RollbackException;\nimport javax.transaction.Status;\nimport javax.transaction.Synchronization;\nimport javax.transaction.SystemException;\nimport javax.transaction.Transaction;\nimport javax.transaction.xa.XAResource;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.persistence.ResourceManager;\n\n/**\n * Implementation for <code> javax.transaction.Transaction </code>\n * \n * @author vivek.mishra\n * \n */\npublic class KunderaTransaction implements Transaction\n{\n\n    private Set<ResourceManager> implementors = new HashSet<ResourceManager>();\n\n    private boolean setRollBackOnly;\n\n    private int status = Status.STATUS_ACTIVE;\n\n    /** The time out in millis. */\n    private int timeOutInMillis;\n\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(KunderaTransaction.class);\n\n    /**\n     * Default constructor with timeout parameter.\n     */\n    KunderaTransaction(int timeOutInMillis)\n    {\n        this.timeOutInMillis = timeOutInMillis;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.transaction.Transaction#commit()\n     */\n    @Override\n    public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException,\n            SecurityException, IllegalStateException, SystemException\n    {\n        if (!setRollBackOnly)\n        {\n            for (ResourceManager implementor : implementors)\n            {\n                if (implementor != null)\n                {\n                    implementor.doCommit();\n                }\n            }\n            status = Status.STATUS_COMMITTED;\n        }\n        else\n        {\n            if (log.isDebugEnabled())\n                log.debug(\"Transaction is set for rollback only, processing rollback.\");\n\n            for (ResourceManager implementor : implementors)\n            {\n                if (implementor != null)\n                {\n                    implementor.doRollback();\n                    status = Status.STATUS_ROLLEDBACK;\n                }\n            }\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.transaction.Transaction#delistResource(javax.transaction.xa.XAResource\n     * , int)\n     */\n    @Override\n    public boolean delistResource(XAResource paramXAResource, int paramInt) throws IllegalStateException,\n            SystemException\n    {\n        // TODD: need to look into.\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.transaction.Transaction#enlistResource(javax.transaction.xa.XAResource\n     * )\n     */\n    @Override\n    public boolean enlistResource(XAResource paramXAResource) throws RollbackException, IllegalStateException,\n            SystemException\n    {\n        // TODD: need to look into.\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.transaction.Transaction#getStatus()\n     */\n    @Override\n    public int getStatus() throws SystemException\n    {\n        return status;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.transaction.Transaction#registerSynchronization(javax.transaction\n     * .Synchronization)\n     */\n    @Override\n    public void registerSynchronization(Synchronization paramSynchronization) throws RollbackException,\n            IllegalStateException, SystemException\n    {\n        throw new UnsupportedOperationException(\"Currently it is not supported.\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.transaction.Transaction#rollback()\n     */\n    @Override\n    public void rollback() throws IllegalStateException, SystemException\n    {\n        for (ResourceManager implementor : implementors)\n        {\n            if (implementor != null)\n            {\n                implementor.doRollback();\n                status = Status.STATUS_ROLLEDBACK;\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.transaction.Transaction#setRollbackOnly()\n     */\n    @Override\n    public void setRollbackOnly() throws IllegalStateException, SystemException\n    {\n        setRollBackOnly = true;\n        status = Status.STATUS_MARKED_ROLLBACK;\n    }\n\n    void setImplementor(ResourceManager implementor)\n    {\n        implementors.add(implementor);\n    }\n\n    /**\n     * @return the transactionTimeout\n     */\n    public int getTransactionTimeout()\n    {\n        return timeOutInMillis;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/persistence/jta/UserTransactionFactory.java",
    "content": "/*******************************************************************************\n\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.persistence.jta;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nimport java.util.Hashtable;\n\nimport javax.naming.BinaryRefAddr;\nimport javax.naming.Context;\nimport javax.naming.Name;\nimport javax.naming.NamingException;\nimport javax.naming.Reference;\nimport javax.naming.spi.ObjectFactory;\n\n/**\n * The factory for JNDI lookup of <code> KunderaJTAUserTransaction</code>\n * objects.\n * \n * @author vivek.mishra@impetus.co.in\n */\n\npublic class UserTransactionFactory implements ObjectFactory\n{\n    /**\n     * Default constructor.\n     */\n    public UserTransactionFactory()\n    {\n    }\n\n    /**\n     * Returns reference to userTransaction object.\n     * \n     * @see javax.naming.spi.ObjectFactory\n     */\n    @Override\n    public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception\n    {\n        Reference ref = (Reference) obj;\n        Object ret = null;\n\n        if (ref.getClassName().equals(\"javax.transaction.UserTransaction\")\n                || ref.getClassName().equals(\"com.impetus.kundera.persistence.jta.KunderaJTAUserTransaction\"))\n        {\n            ret = KunderaJTAUserTransaction.getCurrentTx();\n        }\n\n        if (ret == null)\n        {\n            ret = new KunderaJTAUserTransaction();\n        }\n        return ret;\n\n    }\n\n    /**\n     * Method to return reference for serialized object.(i.e.\n     * KunderJTAUserTransaction)\n     * \n     * @param object\n     *            serilized object.\n     * @return reference to that object.\n     * @throws NamingException\n     *             naming exception.\n     */\n    public static Reference getReference(Serializable object) throws NamingException\n    {\n        ByteArrayOutputStream outStream;\n        try\n        {\n            outStream = new ByteArrayOutputStream();\n            ObjectOutputStream out = new ObjectOutputStream(outStream);\n            out.writeObject(object);\n            out.close();\n        }\n        catch (IOException e)\n        {\n            throw new NamingException(e.getMessage());\n        }\n\n        BinaryRefAddr handle = new BinaryRefAddr(\"com.impetus.kundera.persistence.jta\", outStream.toByteArray());\n        Reference ret = new Reference(object.getClass().getName(), handle, UserTransactionFactory.class.getName(), null);\n        return ret;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/PropertyAccessException.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.property;\r\n\r\nimport com.impetus.kundera.KunderaException;\r\n\r\n/**\r\n * The Class PropertyAccessException.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class PropertyAccessException extends KunderaException\r\n{\r\n\r\n    /** The Constant serialVersionUID. */\r\n    private static final long serialVersionUID = 2920598132353417557L;\r\n\r\n    /**\r\n     * Instantiates a new property access exception.\r\n     */\r\n    public PropertyAccessException()\r\n    {\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new property access exception.\r\n     * \r\n     * @param message\r\n     *            the message\r\n     */\r\n    public PropertyAccessException(String message)\r\n    {\r\n        super(message);\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new property access exception.\r\n     * \r\n     * @param cause\r\n     *            the cause\r\n     */\r\n    public PropertyAccessException(Throwable cause)\r\n    {\r\n        super(cause);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/PropertyAccessor.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.property;\r\n\r\nimport java.lang.reflect.Field;\r\n\r\n/**\r\n * Interface to access {@link Field} property of a java class.\r\n * \r\n * @param <T>\r\n *            the generic type\r\n * @author animesh.kumar\r\n */\r\npublic interface PropertyAccessor<T>\r\n{\r\n\r\n    /**\r\n     * From bytes.\r\n     * \r\n     * @param b\r\n     *            the b\r\n     * \r\n     * @return the T\r\n     * \r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    T fromBytes(Class targetClass, byte[] b);\r\n\r\n    /**\r\n     * To bytes.\r\n     * \r\n     * @param object\r\n     *            the object\r\n     * \r\n     * @return the byte[]\r\n     * \r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    byte[] toBytes(Object object);\r\n\r\n    /**\r\n     * Converts Object to String. Normally, this will be object.toString() But\r\n     * in some cases, this might be different.\r\n     * \r\n     * @param object\r\n     *            the object\r\n     * \r\n     * @return the string\r\n     */\r\n    String toString(Object object);\r\n\r\n    /**\r\n     * Converts string representation to the data object whose type is T.\r\n     * \r\n     * @param s\r\n     *            the s\r\n     * @return the t\r\n     * @throws PropertyAccessException\r\n     *             When string can't be converted to specified type, usually as\r\n     *             a result of NumberFormatException\r\n     */\r\n    T fromString(Class targetClass, String s);\r\n\r\n    /**\r\n     * Gets copy of object\r\n     * \r\n     * @param object\r\n     * @return\r\n     */\r\n    T getCopy(Object object);\r\n\r\n    /**\r\n     * @param clazz\r\n     * \r\n     */\r\n    Object getInstance(Class<?> clazz);\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/PropertyAccessorFactory.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.property;\r\n\r\nimport java.lang.reflect.Field;\r\nimport java.math.BigDecimal;\r\nimport java.math.BigInteger;\r\nimport java.sql.Time;\r\nimport java.sql.Timestamp;\r\nimport java.util.Calendar;\r\nimport java.util.Date;\r\nimport java.util.GregorianCalendar;\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\nimport java.util.UUID;\r\n\r\nimport com.impetus.kundera.gis.geometry.Point;\r\nimport com.impetus.kundera.property.accessor.BigDecimalAccessor;\r\nimport com.impetus.kundera.property.accessor.BigIntegerAccessor;\r\nimport com.impetus.kundera.property.accessor.BooleanAccessor;\r\nimport com.impetus.kundera.property.accessor.ByteAccessor;\r\nimport com.impetus.kundera.property.accessor.CalendarAccessor;\r\nimport com.impetus.kundera.property.accessor.CharAccessor;\r\nimport com.impetus.kundera.property.accessor.DateAccessor;\r\nimport com.impetus.kundera.property.accessor.DoubleAccessor;\r\nimport com.impetus.kundera.property.accessor.EnumAccessor;\r\nimport com.impetus.kundera.property.accessor.FloatAccessor;\r\nimport com.impetus.kundera.property.accessor.IntegerAccessor;\r\nimport com.impetus.kundera.property.accessor.LongAccessor;\r\nimport com.impetus.kundera.property.accessor.ObjectAccessor;\r\nimport com.impetus.kundera.property.accessor.PointAccessor;\r\nimport com.impetus.kundera.property.accessor.SQLDateAccessor;\r\nimport com.impetus.kundera.property.accessor.SQLTimeAccessor;\r\nimport com.impetus.kundera.property.accessor.SQLTimestampAccessor;\r\nimport com.impetus.kundera.property.accessor.ShortAccessor;\r\nimport com.impetus.kundera.property.accessor.StringAccessor;\r\nimport com.impetus.kundera.property.accessor.UUIDAccessor;\r\n\r\n/**\r\n * The Class PropertyAccessorFactory.\r\n * \r\n * @author animesh.kumar\r\n */\r\n\r\npublic class PropertyAccessorFactory\r\n{\r\n\r\n    /** The map. */\r\n    public static Map<Class<?>, PropertyAccessor<?>> map = new HashMap<Class<?>, PropertyAccessor<?>>();\r\n\r\n    static\r\n    {\r\n        // Premitive Type accessors\r\n        map.put(boolean.class, new BooleanAccessor());\r\n        map.put(byte.class, new ByteAccessor());\r\n        map.put(short.class, new ShortAccessor());\r\n        map.put(char.class, new CharAccessor());\r\n        map.put(int.class, new IntegerAccessor());\r\n        map.put(long.class, new LongAccessor());\r\n        map.put(float.class, new FloatAccessor());\r\n        map.put(double.class, new DoubleAccessor());\r\n\r\n        // Wrapper Object accessors\r\n        map.put(Boolean.class, new BooleanAccessor());\r\n        map.put(Byte.class, new ByteAccessor());\r\n        map.put(Short.class, new ShortAccessor());\r\n        map.put(Character.class, new CharAccessor());\r\n        map.put(Integer.class, new IntegerAccessor());\r\n        map.put(Long.class, new LongAccessor());\r\n        map.put(Float.class, new FloatAccessor());\r\n        map.put(Double.class, new DoubleAccessor());\r\n\r\n        // Date/ Time type accessors\r\n        map.put(Date.class, new DateAccessor());\r\n        map.put(java.sql.Date.class, new SQLDateAccessor());\r\n        map.put(Time.class, new SQLTimeAccessor());\r\n        map.put(Timestamp.class, new SQLTimestampAccessor());\r\n        map.put(Calendar.class, new CalendarAccessor());\r\n        map.put(GregorianCalendar.class, new CalendarAccessor());\r\n\r\n        // Accessors for Math classes\r\n        map.put(BigInteger.class, new BigIntegerAccessor());\r\n        map.put(BigDecimal.class, new BigDecimalAccessor());\r\n\r\n        // String class Accessor\r\n        map.put(String.class, new StringAccessor());\r\n\r\n        // Accessor for the generic object\r\n        map.put(Object.class, new ObjectAccessor());\r\n\r\n        // Accessor for Enum types\r\n        map.put(Enum.class, new EnumAccessor());\r\n\r\n        map.put(UUID.class, new UUIDAccessor());\r\n\r\n        // Accessor for Geolocation classes\r\n        map.put(Point.class, new PointAccessor());\r\n    }\r\n\r\n    /** Making String Accessor easy to access. */\r\n    public static final PropertyAccessor<String> STRING = new StringAccessor();\r\n\r\n    /**\r\n     * Instantiates a new property accessor factory.\r\n     */\r\n    private PropertyAccessorFactory()\r\n    {\r\n    }\r\n\r\n    /**\r\n     * Gets the property accessor.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     * \r\n     * @return the property accessor\r\n     */\r\n    @SuppressWarnings(\"unchecked\")\r\n    public static PropertyAccessor getPropertyAccessor(Class<?> clazz)\r\n    {\r\n        PropertyAccessor<?> accessor;\r\n        if (clazz.isEnum())\r\n        {\r\n            accessor = new EnumAccessor();\r\n        }\r\n        else\r\n        {\r\n            accessor = map.get(clazz);\r\n        }\r\n\r\n        // allow fall-back to Object streamer.\r\n        if (null == accessor)\r\n        {\r\n            if (Enum.class.isAssignableFrom(clazz))\r\n            {\r\n                accessor = map.get(Enum.class);\r\n            }\r\n            else\r\n            {\r\n                accessor = map.get(Object.class);\r\n            }\r\n\r\n        }\r\n        return accessor;\r\n    }\r\n\r\n    /**\r\n     * Gets the property accessor.\r\n     * \r\n     * @param property\r\n     *            the property\r\n     * \r\n     * @return the property accessor\r\n     */\r\n    public static PropertyAccessor<?> getPropertyAccessor(Field property)\r\n    {\r\n        return getPropertyAccessor(property.getType());\r\n    }\r\n\r\n    /**\r\n     * Adds the.\r\n     * \r\n     * @param key\r\n     *            the key\r\n     * @param value\r\n     *            the value\r\n     */\r\n    public static void add(Class<?> key, PropertyAccessor<?> value)\r\n    {\r\n        map.put(key, value);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/PropertyAccessorHelper.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.property;\r\n\r\nimport java.lang.reflect.Array;\r\nimport java.lang.reflect.Field;\r\nimport java.lang.reflect.GenericArrayType;\r\nimport java.lang.reflect.ParameterizedType;\r\nimport java.lang.reflect.Type;\r\nimport java.lang.reflect.TypeVariable;\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\n\r\nimport com.impetus.kundera.client.EnhanceEntity;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.utils.ReflectUtils;\r\n\r\n/**\r\n * Helper class to access fields.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class PropertyAccessorHelper\r\n{\r\n\r\n    /**\r\n     * Sets a byte-array onto a field.\r\n     * \r\n     * @param target\r\n     *            the target\r\n     * @param field\r\n     *            the field\r\n     * @param bytes\r\n     *            the bytes\r\n     * \r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    public static void set(Object target, Field field, byte[] bytes)\r\n    {\r\n        PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor(field);\r\n        Object value = accessor.fromBytes(field.getType(), bytes);\r\n        set(target, field, value);\r\n    }\r\n\r\n    /**\r\n     * Sets a byte-array onto a field.\r\n     * \r\n     * @param target\r\n     *            the target\r\n     * @param field\r\n     *            the field\r\n     * @param fieldVal\r\n     *            the field value\r\n     * \r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    public static void set(Object target, Field field, String fieldVal)\r\n    {\r\n        PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor(field);\r\n        Object value = accessor.fromString(target.getClass(), fieldVal);\r\n        set(target, field, value);\r\n    }\r\n\r\n    /**\r\n     * Sets an object onto a field.\r\n     * \r\n     * @param target\r\n     *            the target\r\n     * @param field\r\n     *            the field\r\n     * @param value\r\n     *            the value\r\n     * \r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    public static void set(Object target, Field field, Object value)\r\n    {\r\n        if (target != null)\r\n        {\r\n            if (!field.isAccessible())\r\n            {\r\n                field.setAccessible(true);\r\n            }\r\n            try\r\n            {\r\n                field.set(target, value);\r\n            }\r\n            catch (IllegalArgumentException iarg)\r\n            {\r\n                throw new PropertyAccessException(iarg);\r\n            }\r\n            catch (IllegalAccessException iacc)\r\n            {\r\n                throw new PropertyAccessException(iacc);\r\n            }\r\n        } // ignore if object is null;\r\n    }\r\n\r\n    /**\r\n     * Gets object from field.\r\n     * \r\n     * @param from\r\n     *            the from\r\n     * @param field\r\n     *            the field\r\n     * \r\n     * @return the object\r\n     * \r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    public static Object getObject(Object from, Field field)\r\n    {\r\n        if (!field.isAccessible())\r\n        {\r\n            field.setAccessible(true);\r\n        }\r\n        try\r\n        {\r\n            return field.get(from);\r\n        }\r\n        catch (IllegalArgumentException iarg)\r\n        {\r\n            throw new PropertyAccessException(iarg);\r\n        }\r\n        catch (IllegalAccessException iacc)\r\n        {\r\n            throw new PropertyAccessException(iacc);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Retutrns copy of object\r\n     * \r\n     * @param from\r\n     * @param field\r\n     * @return\r\n     */\r\n    public static Object getObjectCopy(Object from, Field field)\r\n    {\r\n        if (!field.isAccessible())\r\n        {\r\n            field.setAccessible(true);\r\n        }\r\n        try\r\n        {\r\n            PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor(field);\r\n            return accessor.getCopy(field.get(from));\r\n        }\r\n        catch (IllegalArgumentException iarg)\r\n        {\r\n            throw new PropertyAccessException(iarg);\r\n        }\r\n        catch (IllegalAccessException iacc)\r\n        {\r\n            throw new PropertyAccessException(iacc);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Gets the string.\r\n     * \r\n     * @param from\r\n     *            the from\r\n     * @param field\r\n     *            the field\r\n     * \r\n     * @return the string\r\n     * \r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    public static String getString(Object from, Field field)\r\n    {\r\n        PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor(field);\r\n        Object object = getObject(from, field);\r\n        return object != null ? accessor.toString(object) : null;\r\n    }\r\n\r\n    /**\r\n     * Gets field value as byte-array.\r\n     * \r\n     * @param from\r\n     *            the from\r\n     * @param field\r\n     *            the field\r\n     * \r\n     * @return the byte[]\r\n     * \r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    public static byte[] get(Object from, Field field)\r\n    {\r\n        PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor(field);\r\n        return accessor.toBytes(getObject(from, field));\r\n    }\r\n\r\n    /**\r\n     * Get identifier of an entity object by invoking getXXX() method.\r\n     * \r\n     * \r\n     * @param entity\r\n     *            the entity\r\n     * @param metadata\r\n     *            the metadata\r\n     * \r\n     * @return the id\r\n     * \r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    public static Object getId(Object entity, EntityMetadata metadata)\r\n    {\r\n        // If an Entity has been wrapped in a Proxy, we can call the Proxy\r\n        // classes' getId() method\r\n        if (entity instanceof EnhanceEntity)\r\n        {\r\n            return ((EnhanceEntity) entity).getEntityId();\r\n        }\r\n\r\n        // Otherwise, as Kundera currently supports only field access, access\r\n        // the underlying Entity's id field\r\n\r\n        return getObject(entity, (Field) metadata.getIdAttribute().getJavaMember());\r\n    }\r\n\r\n    /**\r\n     * Sets Primary Key (Row key) into entity field that was annotated with @Id.\r\n     * \r\n     * @param entity\r\n     *            the entity\r\n     * @param metadata\r\n     *            the metadata\r\n     * @param rowKey\r\n     *            the row key\r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    public static void setId(Object entity, EntityMetadata metadata, Object rowKey)\r\n    {\r\n        try\r\n        {\r\n            Field idField = (Field) metadata.getIdAttribute().getJavaMember();\r\n            set(entity, idField, rowKey);\r\n        }\r\n        catch (IllegalArgumentException iarg)\r\n        {\r\n            throw new PropertyAccessException(iarg);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Sets Primary Key (Row key) into entity field that was annotated with @Id.\r\n     * \r\n     * @param entity\r\n     *            the entity\r\n     * @param metadata\r\n     *            the metadata\r\n     * @param rowKey\r\n     *            the row key\r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    public static void setId(Object entity, EntityMetadata metadata, byte[] rowKey)\r\n    {\r\n        try\r\n        {\r\n            Field idField = (Field) metadata.getIdAttribute().getJavaMember();\r\n            set(entity, idField, rowKey);\r\n        }\r\n        catch (IllegalArgumentException iarg)\r\n        {\r\n            throw new PropertyAccessException(iarg);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Gets the embedded object.\r\n     * \r\n     * @param obj\r\n     *            the obj\r\n     * @param fieldName\r\n     *            the field name\r\n     * @return the embedded object\r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    @SuppressWarnings(\"null\")\r\n    // TODO: Too much code, improve this, possibly by breaking it\r\n    public static final Object getObject(Object obj, String fieldName)\r\n    {\r\n        Field embeddedField;\r\n        try\r\n        {\r\n            embeddedField = obj.getClass().getDeclaredField(fieldName);\r\n            if (embeddedField != null)\r\n            {\r\n                if (!embeddedField.isAccessible())\r\n                {\r\n                    embeddedField.setAccessible(true);\r\n                }\r\n                Object embededObject = embeddedField.get(obj);\r\n                if (embededObject == null)\r\n                {\r\n                    Class embeddedObjectClass = embeddedField.getType();\r\n                    if (Collection.class.isAssignableFrom(embeddedObjectClass))\r\n                    {\r\n                        if (embeddedObjectClass.equals(List.class))\r\n                        {\r\n                            return new ArrayList();\r\n                        }\r\n                        else if (embeddedObjectClass.equals(Set.class))\r\n                        {\r\n                            return new HashSet();\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        embededObject = embeddedField.getType().newInstance();\r\n                        embeddedField.set(obj, embededObject);\r\n                    }\r\n\r\n                }\r\n                return embededObject;\r\n            }\r\n            else\r\n            {\r\n                throw new PropertyAccessException(\"Embedded object not found: \" + fieldName);\r\n            }\r\n\r\n        }\r\n        catch (Exception e)\r\n        {\r\n            throw new PropertyAccessException(e);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Retrieves Generic class from a collection field that has only one\r\n     * argument.\r\n     * \r\n     * @param collectionField\r\n     *            the collection field\r\n     * @return the generic class\r\n     */\r\n    public static Class<?> getGenericClass(Field collectionField)\r\n    {\r\n        Class<?> genericClass = null;\r\n        if (collectionField == null)\r\n        {\r\n            return genericClass;\r\n        }\r\n        if (isCollection(collectionField.getType()))\r\n        {\r\n            Type[] parameters = ReflectUtils.getTypeArguments(collectionField);\r\n            if (parameters != null)\r\n            {\r\n                if (parameters.length == 1)\r\n                {\r\n                    genericClass = toClass(parameters[0]);\r\n                }\r\n                else\r\n                {\r\n                    throw new PropertyAccessException(\r\n                            \"Can't determine generic class from a field that has more than one parameters.\");\r\n                }\r\n            }\r\n        }\r\n        if (collectionField.getType().isAssignableFrom(Map.class))\r\n        {\r\n            java.lang.reflect.Type[] arguments = ((ParameterizedType) collectionField.getGenericType())\r\n                    .getActualTypeArguments();\r\n            if (arguments != null && arguments.length > 1)\r\n            {\r\n                genericClass = getTypedClass(arguments[1]);\r\n            }\r\n        }\r\n        return genericClass != null ? genericClass : collectionField.getType();\r\n    }\r\n\r\n    /**\r\n     * Retrieves Generic class from a collection field that has only one\r\n     * argument.\r\n     * \r\n     * @param collectionField\r\n     *            the collection field\r\n     * @return the generic class\r\n     */\r\n    public static List<Class<?>> getGenericClasses(Field collectionField)\r\n    {\r\n        List<Class<?>> genericClasses = new ArrayList<Class<?>>();\r\n        if (collectionField == null)\r\n        {\r\n            return genericClasses;\r\n        }\r\n        Type[] parameters = ReflectUtils.getTypeArguments(collectionField);\r\n        if (parameters != null)\r\n        {\r\n\r\n            for (Type parameter : parameters)\r\n            {\r\n                // workaround for jdk1.6 issue.\r\n                genericClasses.add(toClass(parameter));\r\n            }\r\n        }\r\n        return genericClasses;\r\n    }\r\n\r\n    /**\r\n     * Gets the declared fields.\r\n     * \r\n     * @param relationalField\r\n     *            the relational field\r\n     * @return the declared fields\r\n     */\r\n    public static Field[] getDeclaredFields(Field relationalField)\r\n    {\r\n        Field[] fields;\r\n        if (isCollection(relationalField.getType()))\r\n        {\r\n            fields = PropertyAccessorHelper.getGenericClass(relationalField).getDeclaredFields();\r\n        }\r\n        else\r\n        {\r\n            fields = relationalField.getType().getDeclaredFields();\r\n        }\r\n        return fields;\r\n    }\r\n\r\n    /**\r\n     * Checks if is collection.\r\n     * \r\n     * @param clazz\r\n     *            the clazz\r\n     * @return true, if is collection\r\n     */\r\n    public static final boolean isCollection(Class<?> clazz)\r\n    {\r\n        return Collection.class.isAssignableFrom(clazz);\r\n\r\n    }\r\n\r\n    public static final Object getObject(Class<?> clazz)\r\n    {\r\n        PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(clazz);\r\n        return accessor.getInstance(clazz);\r\n    }\r\n\r\n    public static final byte[] toBytes(Object o, Field f)\r\n    {\r\n        PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(f);\r\n        return accessor.toBytes(o);\r\n    }\r\n\r\n    public static final byte[] toBytes(Object o, Class c)\r\n    {\r\n        PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(c);\r\n        return accessor.toBytes(o);\r\n    }\r\n\r\n    public static Object fromSourceToTargetClass(Class<?> targetClass, Class<?> sourceClass, Object o)\r\n    {\r\n        if (!targetClass.equals(sourceClass))\r\n        {\r\n            PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor(sourceClass);\r\n            String s = accessor.toString(o);\r\n            accessor = PropertyAccessorFactory.getPropertyAccessor(targetClass);\r\n            return accessor.fromString(targetClass, s);\r\n        }\r\n        return o;\r\n    }\r\n\r\n    public static Object fromDate(Class<?> targetClass, Class<?> sourceClass, Object o)\r\n    {\r\n        if (!targetClass.equals(sourceClass))\r\n        {\r\n            PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor(sourceClass);\r\n            byte[] b = accessor.toBytes(o);\r\n            accessor = PropertyAccessorFactory.getPropertyAccessor(targetClass);\r\n            return accessor.fromBytes(targetClass, b);\r\n        }\r\n        return o;\r\n    }\r\n\r\n    public static byte[] getBytes(Object o)\r\n    {\r\n        return PropertyAccessorFactory.getPropertyAccessor(o.getClass()).toBytes(o);\r\n    }\r\n\r\n    public static String getString(Object o)\r\n    {\r\n        return o != null ? PropertyAccessorFactory.getPropertyAccessor(o.getClass()).toString(o) : null;\r\n    }\r\n\r\n    public static Object getObject(Class clazz, byte[] b)\r\n    {\r\n        return PropertyAccessorFactory.getPropertyAccessor(clazz).fromBytes(clazz, b);\r\n    }\r\n\r\n    public static final Collection getCollectionInstance(Field collectionField)\r\n    {\r\n        if (collectionField != null)\r\n        {\r\n            if (collectionField.getType().isAssignableFrom(List.class))\r\n            {\r\n                return new ArrayList();\r\n            }\r\n            else if (collectionField.getType().isAssignableFrom(Set.class))\r\n            {\r\n                return new HashSet();\r\n            }\r\n        }\r\n        return null;\r\n    }\r\n\r\n    /**\r\n     * Borrowed from java.lang.class\r\n     * \r\n     * @param o\r\n     * @return\r\n     */\r\n\r\n    private static Class<?> toClass(Type o)\r\n    {\r\n        if (o instanceof GenericArrayType)\r\n        {\r\n            Class clazz = Array.newInstance(toClass(((GenericArrayType) o).getGenericComponentType()), 0).getClass();\r\n            return clazz;\r\n        }\r\n        return (Class<?>) o;\r\n    }\r\n\r\n    /**\r\n     * Gets the typed class.\r\n     * \r\n     * @param type\r\n     *            the type\r\n     * @return the typed class\r\n     */\r\n    private static Class<?> getTypedClass(java.lang.reflect.Type type)\r\n    {\r\n        if (type instanceof Class)\r\n        {\r\n            return ((Class) type);\r\n        }\r\n        else if (type instanceof ParameterizedType)\r\n        {\r\n            java.lang.reflect.Type rawParamterizedType = ((ParameterizedType) type).getRawType();\r\n            return getTypedClass(rawParamterizedType);\r\n        }\r\n        else if (type instanceof TypeVariable)\r\n        {\r\n            java.lang.reflect.Type upperBound = ((TypeVariable) type).getBounds()[0];\r\n            return getTypedClass(upperBound);\r\n        }\r\n\r\n        throw new IllegalArgumentException(\"Error while finding generic class for :\" + type);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/BigDecimalAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Arrays;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * The Class BigDecimalAccessor.\n * \n * @author amresh.singh\n */\npublic class BigDecimalAccessor implements PropertyAccessor<BigDecimal>\n{\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\n     */\n    @Override\n    public BigDecimal fromBytes(Class targetClass, byte[] bytes)\n    {\n        if (bytes == null)\n        {\n            return null;\n        }\n        int scale = (((bytes[0]) << 24) | ((bytes[1] & 0xff) << 16) | ((bytes[2] & 0xff) << 8) | ((bytes[3] & 0xff)));\n\n        byte[] bibytes = Arrays.copyOfRange(bytes, 4, bytes.length);\n\n        BigInteger bi = new BigInteger(bibytes);\n\n        return new BigDecimal(bi, scale);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\n     */\n    @Override\n    public byte[] toBytes(Object object)\n    {\n        if (object == null)\n        {\n            return null;\n        }\n\n        BigDecimal b = (BigDecimal) object;\n        final int scale = b.scale();\n        final BigInteger unscaled = b.unscaledValue();\n        final byte[] value = unscaled.toByteArray();\n        final byte[] bytes = new byte[value.length + 4];\n        bytes[0] = (byte) (scale >>> 24);\n        bytes[1] = (byte) (scale >>> 16);\n        bytes[2] = (byte) (scale >>> 8);\n        bytes[3] = (byte) (scale >>> 0);\n        System.arraycopy(value, 0, bytes, 4, value.length);\n        return bytes;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\n     */\n    @Override\n    public String toString(Object object)\n    {\n        if (object == null)\n        {\n            return null;\n        }\n        return object.toString();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\n     * )\n     */\n    @Override\n    public BigDecimal fromString(Class targetClass, String s)\n    {\n\n        return s != null ? new BigDecimal(s) : null;\n    }\n\n    @Override\n    public BigDecimal getCopy(Object object)\n    {\n        BigDecimal b = (BigDecimal) object;\n        return object != null ? b : null;\n    }\n\n    public BigDecimal getInstance(Class<?> clazz)\n    {\n        return BigDecimal.TEN;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/BigIntegerAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.math.BigInteger;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * The Class BigIntegerAccessor.\n * \n * @author amresh.singh\n */\npublic class BigIntegerAccessor implements PropertyAccessor<BigInteger>\n{\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\n     */\n    @Override\n    public BigInteger fromBytes(Class targetClass, byte[] b)\n    {\n        return b != null ? new BigInteger(b) : null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\n     */\n    @Override\n    public byte[] toBytes(Object object)\n    {\n        if (object == null)\n        {\n            return null;\n        }\n        BigInteger b = (BigInteger) object;\n        return b.toByteArray();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\n     */\n    @Override\n    public String toString(Object object)\n    {\n        if (object == null)\n        {\n            return null;\n        }\n        return object.toString();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\n     * )\n     */\n    @Override\n    public BigInteger fromString(Class targetClass, String s)\n    {\n        return s != null ? new BigInteger(s) : null;\n    }\n\n    @Override\n    public BigInteger getCopy(Object object)\n    {\n        BigInteger i = (BigInteger) object;\n        return object != null ? new BigInteger(i.toByteArray()) : null;\n    }\n\n    public BigInteger getInstance(Class<?> clazz)\n    {\n        return BigInteger.TEN;\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/BooleanAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * The Class BooleanAccessor.\n * \n * @author Amresh Singh\n */\npublic class BooleanAccessor implements PropertyAccessor<Boolean>\n{\n\n    private final static Logger log = LoggerFactory.getLogger(BooleanAccessor.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\n     */\n    @Override\n    public Boolean fromBytes(Class targetClass, byte[] data)\n    {\n        return (data == null || data.length == 0) ? false : data[0] != 0x00;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\n     */\n    @Override\n    public byte[] toBytes(Object object)\n    {\n        if (object != null)\n        {\n            Boolean b = (Boolean) object;\n\n            return new byte[] { (byte) (b ? 0x01 : 0x00) }; // bool -> {1 byte}\n        }\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\n     */\n    @Override\n    public String toString(Object object)\n    {\n        return object != null ? object.toString() : null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\n     * )\n     */\n    @Override\n    public Boolean fromString(Class targetClass, String s)\n    {\n        try\n        {\n            if (s == null)\n            {\n                return null;\n            }\n\n            Boolean b = new Boolean(s);\n            return b;\n        }\n        catch (NumberFormatException e)\n        {\n            log.error(\"Number format exception, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    @Override\n    public Boolean getCopy(Object object)\n    {\n        return object != null ? new Boolean((Boolean) object) : null;\n    }\n\n    public Boolean getInstance(Class<?> clazz)\n    {\n        return Boolean.TRUE;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/ByteAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.nio.ByteBuffer;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * The Class ByteAccessor.\n * \n * @author Amresh Singh\n */\npublic class ByteAccessor implements PropertyAccessor<Byte>\n{\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(ByteAccessor.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\n     */\n    @Override\n    public Byte fromBytes(Class targetClass, byte[] b)\n    {\n        try\n        {\n            if (b == null)\n            {\n                return null;\n            }\n            // return new Byte(new String(b, Constants.ENCODING));\n            return (ByteBuffer.wrap(b).get());\n        }\n        catch (NumberFormatException e)\n        {\n            log.warn(\"Number format exception caught!,returning null!\");\n            return null;\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\n     */\n    @Override\n    public byte[] toBytes(Object object)\n    {\n        if (object == null)\n        {\n            return null;\n        }\n        Byte b = (Byte) object;\n        ByteBuffer buffer = ByteBuffer.allocate(8);\n        buffer.put(b);\n        return buffer.array();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\n     */\n    @Override\n    public String toString(Object object)\n    {\n        return object != null ? object.toString() : null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\n     * )\n     */\n    @Override\n    public Byte fromString(Class targetClass, String s)\n    {\n        try\n        {\n            if (s == null)\n            {\n                return null;\n            }\n            Byte b = new Byte(s);\n            return b;\n        }\n        catch (NumberFormatException e)\n        {\n            log.error(\"Number fromat exception, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    @Override\n    public Byte getCopy(Object object)\n    {\n        return object != null ? new Byte((Byte) object) : null;\n    }\n\n    public Byte getInstance(Class<?> clazz)\n    {\n        return Byte.MAX_VALUE;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/CalendarAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.Locale;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * The Class CalendarAccessor.\n * \n * @author amresh.singh\n */\npublic class CalendarAccessor implements PropertyAccessor<Calendar>\n{\n\n    /** The Constant DATE_FORMATTER. */\n    private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat(\"dd-MM-yyyy HH:mm:ss\", Locale.ENGLISH);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\n     */\n    @Override\n    public Calendar fromBytes(Class targetClass, byte[] b)\n    {\n        Calendar cal = Calendar.getInstance();\n        Date d = new Date();\n        if (b == null)\n        {\n            return null;\n        }\n        LongAccessor longAccessor = new LongAccessor();\n        d.setTime(longAccessor.fromBytes(targetClass, b));\n        cal.setTime(d);\n        return cal;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\n     */\n    @Override\n    public byte[] toBytes(Object object)\n    {\n        if (object == null)\n        {\n            return null;\n        }\n        Calendar cal = (Calendar) object;\n        // return\n        // DateAccessor.getFormattedObect(cal.getTime().toString()).getBytes();\n        LongAccessor longAccessor = new LongAccessor();\n        return longAccessor.toBytes(cal.getTime().getTime());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\n     */\n    @Override\n    public String toString(Object object)\n    {\n        Calendar calendar = (Calendar) object;\n\n        if (calendar == null)\n        {\n            return null;\n        }\n        return String.valueOf(calendar.getTime().getTime());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\n     * )\n     */\n    @Override\n    public Calendar fromString(Class targetClass, String s)\n    {\n        if (s == null)\n        {\n            return null;\n        }\n        Calendar cal = Calendar.getInstance();\n        Date d;\n        // d = (Date)DATE_FORMATTER.parse(s);\n        d = DateAccessor.getDateByPattern(s);\n        cal.setTime(d);\n        return cal;\n    }\n\n    @Override\n    public Calendar getCopy(Object object)\n    {\n        if (object == null)\n            return null;\n        Calendar c = (Calendar) object;\n        Calendar copy = Calendar.getInstance();\n        copy.setTimeInMillis(c.getTimeInMillis());\n        return copy;\n    }\n\n    public Calendar getInstance(Class<?> clazz)\n    {\n        return Calendar.getInstance();\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/CharAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * The Class CharAccessor.\n * \n * @author Amresh Singh\n */\npublic class CharAccessor implements PropertyAccessor<Character>\n{\n\n    private final static Logger log = LoggerFactory.getLogger(CharAccessor.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\n     */\n    @Override\n    public Character fromBytes(Class targetClass, byte[] data)\n    {\n        if (data == null || data.length != 2)\n        {\n            if (log.isWarnEnabled())\n            {\n                log.warn(\"Data length is not matching\");\n            }\n            return 0x0;\n        }\n        return (char) ((0xff & data[0]) << 8 | (0xff & data[1]) << 0);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\n     */\n    @Override\n    public byte[] toBytes(Object object)\n    {\n        if (object == null)\n        {\n            return null;\n        }\n        Character data = null;\n        if (object.getClass().isAssignableFrom(String.class))\n        {\n            data = ((String) object).charAt(0);\n        }\n        else\n        {\n            data = (Character) object;\n        }\n\n        return new byte[] { (byte) ((data >> 8) & 0xff), (byte) ((data >> 0) & 0xff), };\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\n     */\n    @Override\n    public String toString(Object object)\n    {\n        if (object == null)\n        {\n            return null;\n        }\n\n        return object.toString();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\n     * )\n     */\n    @Override\n    public Character fromString(Class targetClass, String s)\n    {\n        try\n        {\n            if (s == null)\n            {\n                log.error(\"Can't convert String \" + s + \" to character\");\n                throw new PropertyAccessException(\"Can't convert String \" + s + \" to character\");\n            }\n\n            Character c = null;\n            if (s.length() == 1)\n            {\n                c = s.charAt(0);\n            }\n            else\n            {\n                c = Character.MIN_VALUE;\n            }\n\n            return c;\n        }\n        catch (NumberFormatException e)\n        {\n            log.error(\"Number format exception caught,Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    @Override\n    public Character getCopy(Object object)\n    {\n        return object != null ? new Character((Character) object) : null;\n    }\n\n    public Character getInstance(Class<?> clazz)\n    {\n        return Character.MAX_VALUE;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/DateAccessor.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.property.accessor;\r\n\r\nimport java.text.DateFormat;\r\nimport java.text.ParseException;\r\nimport java.text.SimpleDateFormat;\r\nimport java.util.ArrayList;\r\nimport java.util.Date;\r\nimport java.util.List;\r\nimport java.util.Locale;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.Constants;\r\nimport com.impetus.kundera.property.PropertyAccessException;\r\nimport com.impetus.kundera.property.PropertyAccessor;\r\n\r\n/**\r\n * The Class DateAccessor.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class DateAccessor implements PropertyAccessor<Date>\r\n{\r\n\r\n    /** The log. */\r\n    private static Logger log = LoggerFactory.getLogger(DateAccessor.class);\r\n\r\n    /** The Constant DATE_FORMATTER. */\r\n    private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat(\"dd MMM yyyy HH:mm:ss:S Z\",\r\n            Locale.ENGLISH);\r\n\r\n    /** The patterns. */\r\n    private static List<String> patterns = new ArrayList<String>(15);\r\n\r\n    static\r\n    {\r\n        patterns.add(\"E MMM dd HH:mm:ss z yyyy\");\r\n        patterns.add(\"dd MMM yyyy HH:mm:ss:SSS\");\r\n        patterns.add(\"dd MMM yyyy H:mm:ss:SSS\");\r\n        patterns.add(\"MM-dd-yyyy HH:mm:ss:SSS\");\r\n        patterns.add(\"MM/dd/yyyy HH:mm:ss:SSS\");\r\n        patterns.add(\"dd/MM/yyyy HH:mm:ss:SSS\");\r\n        patterns.add(\"dd-MM-yyyy HH:mm:ss:SSS\");\r\n        patterns.add(\"MMM/dd/yyyy HH:mm:ss:SSS\");\r\n        patterns.add(\"MMM-dd-yyyy HH:mm:ss:SSS\");\r\n        patterns.add(\"dd-MMM-yyyy HH:mm:ss:SSS\");\r\n        patterns.add(\"MM-dd-yyyy H:mm:ss:SSS\");\r\n        patterns.add(\"MM/dd/yyyy H:mm:ss:SSS\");\r\n        patterns.add(\"dd/MM/yyyy H:mm:ss:SSS\");\r\n        patterns.add(\"dd-MM-yyyy H:mm:ss:SSS\");\r\n        patterns.add(\"MMM/dd/yyyy H:mm:ss:SSS\");\r\n        patterns.add(\"MMM-dd-yyyy H:mm:ss:SSS\");\r\n        patterns.add(\"dd-MMM-yyyy H:mm:ss:SSS\");\r\n        patterns.add(\"MM-dd-yyyy HH:mm:ss\");\r\n        patterns.add(\"MM/dd/yyyy HH:mm:ss\");\r\n        patterns.add(\"dd/MM/yyyy HH:mm:ss\");\r\n        patterns.add(\"dd-MM-yyyy HH:mm:ss\");\r\n        patterns.add(\"MMM/dd/yyyy HH:mm:ss\");\r\n        patterns.add(\"MMM-dd-yyyy HH:mm:ss\");\r\n        patterns.add(\"dd-MMM-yyyy HH:mm:ss\");\r\n        patterns.add(\"MM-dd-yyyy H:mm:ss\");\r\n        patterns.add(\"MM/dd/yyyy H:mm:ss\");\r\n        patterns.add(\"dd/MM/yyyy H:mm:ss\");\r\n        patterns.add(\"dd-MM-yyyy H:mm:ss\");\r\n        patterns.add(\"MMM/dd/yyyy H:mm:ss\");\r\n        patterns.add(\"MMM-dd-yyyy H:mm:ss\");\r\n        patterns.add(\"dd-MMM-yyyy H:mm:ss\");\r\n\r\n        patterns.add(\"MM-dd-yyyy\");\r\n        patterns.add(\"MM/dd/yyyy\");\r\n        patterns.add(\"dd/MM/yyyy\");\r\n        patterns.add(\"dd-MM-yyyy\");\r\n        patterns.add(\"MMM/dd/yyyy\");\r\n        patterns.add(\"MMM-dd-yyyy\");\r\n        patterns.add(\"dd-MMM-yyyy\");\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\r\n     */\r\n    @Override\r\n    public/* final */Date fromBytes(Class targetClass, byte[] bytes)\r\n    {\r\n        try\r\n        {\r\n            if (bytes == null)\r\n            {\r\n                return null;\r\n            }\r\n\r\n            try\r\n            {\r\n                // In case date.getTime() is stored in DB.\r\n                LongAccessor longAccessor = new LongAccessor();\r\n\r\n                return new Date(longAccessor.fromBytes(targetClass, bytes));\r\n            }\r\n            catch (NumberFormatException nfex)\r\n            {\r\n                return getDateByPattern(new String(bytes, Constants.ENCODING));\r\n\r\n            }\r\n        }\r\n        catch (Exception e)\r\n        {\r\n            log.error(\"Caused by {}.\", e);\r\n            throw new PropertyAccessException(e);\r\n        }\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\r\n     */\r\n    @Override\r\n    public/* final */byte[] toBytes(Object date)\r\n    {\r\n        try\r\n        {\r\n            if (date == null)\r\n            {\r\n                return null;\r\n            }\r\n            LongAccessor longAccessor = new LongAccessor();\r\n            return longAccessor.toBytes(((Date) date).getTime());\r\n            // return DATE_FORMATTER.format(((Date)\r\n            // date)).getBytes(Constants.ENCODING);\r\n        }\r\n        catch (Exception e)\r\n        {\r\n            log.error(\"Caused by {}.\", e);\r\n            throw new PropertyAccessException(e);\r\n        }\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\r\n     */\r\n    @Override\r\n    public/* final */String toString(Object object)\r\n    {\r\n        Date date = (Date) object;\r\n\r\n        if (date == null)\r\n        {\r\n            return null;\r\n        }\r\n\r\n        return String.valueOf(date.getTime());\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\r\n     * )\r\n     */\r\n    @Override\r\n    public Date fromString(Class targetClass, String s)\r\n    {\r\n        try\r\n        {\r\n            if (s == null)\r\n            {\r\n                return null;\r\n            }\r\n            Date d = getDateByPattern(s);\r\n            return d;\r\n        }\r\n        catch (NumberFormatException e)\r\n        {\r\n            log.error(\"Number format exception, Caused by {}.\", e);\r\n            throw new PropertyAccessException(e);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Get Date from given below formats.\r\n     * \r\n     * @param date\r\n     *            Date pattern\r\n     * @return date instance\r\n     * @throws PropertyAccessException\r\n     *             throws only if invalid format is supplied.\r\n     */\r\n    public static Date getDateByPattern(String date)\r\n    {\r\n        if (StringUtils.isNumeric(date))\r\n        {\r\n            return new Date(Long.parseLong(date));\r\n        }\r\n\r\n        for (String p : patterns)\r\n        {\r\n            try\r\n            {\r\n                DateFormat formatter = new SimpleDateFormat(p);\r\n                Date dt = formatter.parse(date);\r\n                return dt;\r\n            }\r\n            catch (IllegalArgumentException iae)\r\n            {\r\n                // Do nothing.\r\n                // move to next pattern.\r\n            }\r\n            catch (ParseException e)\r\n            {\r\n                // Do nothing.\r\n                // move to next pattern.\r\n            }\r\n\r\n        }\r\n        log.error(\"Required Date format is not supported!\" + date);\r\n        throw new PropertyAccessException(\"Required Date format is not supported!\" + date);\r\n    }\r\n\r\n    @Override\r\n    public Date getCopy(Object object)\r\n    {\r\n        Date d = (Date) object;\r\n        return d != null ? new Date(d.getTime()) : null;\r\n    }\r\n\r\n    /**\r\n     * Just to verify with supported types of date pattern. Get Date from given\r\n     * below formats\r\n     * \r\n     * @param date\r\n     *            Date pattern\r\n     * @return date instance\r\n     * @throws PropertyAccessException\r\n     *             throws only if invalid format is supplied.\r\n     */\r\n    public static String getFormattedObect(String date)\r\n    {\r\n        return date != null ? getDateByPattern(date).toString() : null;\r\n    }\r\n\r\n    public Date getInstance(Class<?> clazz)\r\n    {\r\n        return new Date();\r\n    }\r\n\r\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/DoubleAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * The Class DoubleAccessor.\n * \n * @author Amresh Singh\n */\npublic class DoubleAccessor implements PropertyAccessor<Double>\n{\n\n    private final static Logger log = LoggerFactory.getLogger(DoubleAccessor.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\n     */\n    @Override\n    public Double fromBytes(Class targetClass, byte[] data)\n    {\n        if (data == null || data.length != 8)\n            return (double) 0x0;\n\n        return Double.longBitsToDouble(toLong(data));\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\n     */\n    @Override\n    public byte[] toBytes(Object object) throws PropertyAccessException\n    {\n        return object != null ? fromLong(Double.doubleToRawLongBits((Double) object)) : null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\n     */\n    @Override\n    public String toString(Object object)\n    {\n        return object != null ? object.toString() : null;\n    }\n\n    /**\n     * To long.\n     * \n     * @param data\n     *            the data\n     * @return the long\n     */\n    private long toLong(byte[] data)\n    {\n        if (data == null || data.length != 8)\n            return 0x0;\n        // ----------\n        return (long) (\n        // (Below) convert to longs before shift because digits\n        // are lost with ints beyond the 32-bit limit\n        (long) (0xff & data[0]) << 56 | (long) (0xff & data[1]) << 48 | (long) (0xff & data[2]) << 40\n                | (long) (0xff & data[3]) << 32 | (long) (0xff & data[4]) << 24 | (long) (0xff & data[5]) << 16\n                | (long) (0xff & data[6]) << 8 | (long) (0xff & data[7]) << 0);\n    }\n\n    /**\n     * From long.\n     * \n     * @param data\n     *            the data\n     * @return the byte[]\n     */\n    private byte[] fromLong(long data)\n    {\n        return new byte[] { (byte) ((data >> 56) & 0xff), (byte) ((data >> 48) & 0xff), (byte) ((data >> 40) & 0xff),\n                (byte) ((data >> 32) & 0xff), (byte) ((data >> 24) & 0xff), (byte) ((data >> 16) & 0xff),\n                (byte) ((data >> 8) & 0xff), (byte) ((data >> 0) & 0xff), };\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\n     * )\n     */\n    @Override\n    public Double fromString(Class targetClass, String s)\n    {\n        try\n        {\n            if (s == null)\n            {\n                return null;\n            }\n            Double d = new Double(s);\n            return d;\n        }\n        catch (NumberFormatException e)\n        {\n            log.error(\"Number format exception, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    @Override\n    public Double getCopy(Object object)\n    {\n        return object != null ? new Double((Double) object) : null;\n    }\n\n    public Double getInstance(Class<?> clazz)\n    {\n        return Double.MAX_VALUE;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/EnumAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.io.UnsupportedEncodingException;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n * \n */\n@SuppressWarnings(\"rawtypes\")\npublic class EnumAccessor implements PropertyAccessor<Enum>\n{\n\n    private final static Logger log = LoggerFactory.getLogger(EnumAccessor.class);\n\n    @Override\n    public Enum fromBytes(Class targetClass, byte[] b)\n    {\n        String s = null;\n        try\n        {\n            if (b == null)\n            {\n                return null;\n            }\n            s = new String(b, Constants.ENCODING);\n        }\n        catch (UnsupportedEncodingException e)\n        {\n            log.error(\"Unsupported encoding exception, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n        return fromString(targetClass, s);\n    }\n\n    @Override\n    public byte[] toBytes(Object object)\n    {\n        if (object == null)\n        {\n            return null;\n        }\n        String s = toString(object);\n        try\n        {\n            return s.getBytes(Constants.ENCODING);\n        }\n        catch (UnsupportedEncodingException e)\n        {\n            log.error(\"Unsupported encoding exception, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    @Override\n    public String toString(Object object)\n    {\n        if (object == null)\n        {\n            return null;\n        }\n        Enum en = (Enum) object;\n        return en.name();\n    }\n\n    @Override\n    public Enum fromString(Class targetClass, String string)\n    {\n        if (targetClass != null && string != null)\n        {\n            try\n            {\n                return Enum.valueOf(targetClass, string.trim());\n            }\n            catch (IllegalArgumentException ex)\n            {\n                log.error(\"Illegal argument exception, Caused by {}.\", ex);\n                throw new PropertyAccessException(ex);\n            }\n        }\n\n        return null;\n    }\n\n    @Override\n    public Enum getCopy(Object object)\n    {\n        if (object != null)\n        {\n            return fromString(object.getClass(), toString(object));\n        }\n        return null;\n    }\n\n    public Enum getInstance(Class<?> clazz)\n    {\n        return null;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/FloatAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * The Class FloatAccessor.\n * \n * @author Amresh Singh\n */\npublic class FloatAccessor implements PropertyAccessor<Float>\n{\n    private final static Logger log = LoggerFactory.getLogger(FloatAccessor.class);\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\n     */\n    @Override\n    public Float fromBytes(Class targetClass, byte[] data)\n    {\n        if (data == null || data.length != 4)\n            return (float) 0x0;\n\n        return Float.intBitsToFloat(toInt(data));\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\n     */\n    @Override\n    public byte[] toBytes(Object object)\n    {\n        return object != null ? fromInt(Float.floatToRawIntBits((Float) object)) : null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\n     */\n    @Override\n    public String toString(Object object)\n    {\n        return object != null ? object.toString() : null;\n    }\n\n    /**\n     * From int.\n     * \n     * @param data\n     *            the data\n     * @return the byte[]\n     */\n    private byte[] fromInt(int data)\n    {\n        return new byte[] { (byte) ((data >> 24) & 0xff), (byte) ((data >> 16) & 0xff), (byte) ((data >> 8) & 0xff),\n                (byte) ((data >> 0) & 0xff), };\n    }\n\n    /**\n     * To int.\n     * \n     * @param data\n     *            the data\n     * @return the int\n     */\n    private int toInt(byte[] data)\n    {\n        if (data == null || data.length != 4)\n            return 0x0;\n\n        return (int) ( // NOTE: type cast not necessary for int\n        (0xff & data[0]) << 24 | (0xff & data[1]) << 16 | (0xff & data[2]) << 8 | (0xff & data[3]) << 0);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\n     * )\n     */\n    @Override\n    public Float fromString(Class targetClass, String s)\n    {\n        try\n        {\n            if (s == null)\n            {\n                return null;\n            }\n            Float f = new Float(s);\n            return f;\n        }\n        catch (NumberFormatException e)\n        {\n            log.error(\"Number format exception, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    @Override\n    public Float getCopy(Object object)\n    {\n        return object != null ? (Float) object : null;\n    }\n\n    public Float getInstance(Class<?> clazz)\n    {\n        return Float.MAX_VALUE;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/IntegerAccessor.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.property.accessor;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.property.PropertyAccessException;\r\nimport com.impetus.kundera.property.PropertyAccessor;\r\n\r\n/**\r\n * The Class IntegerAccessor.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class IntegerAccessor implements PropertyAccessor<Integer>\r\n{\r\n\r\n    private final static Logger log = LoggerFactory.getLogger(IntegerAccessor.class);\r\n\r\n    /* @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[]) */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\r\n     */\r\n    @Override\r\n    public final Integer fromBytes(Class targetClass, byte[] b)\r\n    {\r\n        if (b == null)\r\n        {\r\n            return null;\r\n        }\r\n        return ((b[0] << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8) + (b[3] & 0xFF));\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\r\n     */\r\n    @Override\r\n    public final byte[] toBytes(Object val)\r\n    {\r\n        if (val != null)\r\n        {\r\n            Integer value = (Integer) (val);\r\n            return new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8),\r\n                    (byte) value.intValue() };\r\n        }\r\n        return null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\r\n     */\r\n    @Override\r\n    public String toString(Object object)\r\n    {\r\n        return object != null ? object.toString() : null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\r\n     * )\r\n     */\r\n    @Override\r\n    public Integer fromString(Class targetClass, String s)\r\n    {\r\n        try\r\n        {\r\n            if (s == null)\r\n            {\r\n                return null;\r\n            }\r\n            Integer i = new Integer(s);\r\n            return i;\r\n        }\r\n        catch (NumberFormatException e)\r\n        {\r\n            log .error(\"Number format exception, Caused by {}.\", e);\r\n            throw new PropertyAccessException(e);\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public Integer getCopy(Object object)\r\n    {\r\n        return object != null ? (Integer) object : null;\r\n    }\r\n\r\n    public Integer getInstance(Class<?> clazz)\r\n    {\r\n        return Integer.MAX_VALUE;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/LongAccessor.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.property.accessor;\r\n\r\nimport java.nio.ByteBuffer;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.property.PropertyAccessException;\r\nimport com.impetus.kundera.property.PropertyAccessor;\r\n\r\n/**\r\n * The Class LongAccessor.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class LongAccessor implements PropertyAccessor<Long>\r\n{\r\n\r\n    private final static Logger log = LoggerFactory.getLogger(LongAccessor.class);\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\r\n     */\r\n    @Override\r\n    public final Long fromBytes(Class targetClass, byte[] bytes)\r\n    {\r\n        if (bytes == null || bytes.length != 8)\r\n        {\r\n            if (log.isWarnEnabled())\r\n            {\r\n                log.warn(\"Bytes length not equal to 8\");\r\n            }\r\n            return null;\r\n        }\r\n        return (ByteBuffer.wrap(bytes).getLong());\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\r\n     */\r\n    @Override\r\n    public final byte[] toBytes(Object object)\r\n    {\r\n        if (object != null)\r\n        {\r\n            Long l = (Long) object;\r\n            ByteBuffer buffer = ByteBuffer.allocate(8);\r\n            buffer.putLong(l);\r\n            return buffer.array();\r\n        }\r\n        if (log.isWarnEnabled())\r\n        {\r\n            log.warn(\"Object is null.\");\r\n        }\r\n        return null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\r\n     */\r\n    @Override\r\n    public final String toString(Object object)\r\n    {\r\n        return object != null ? object.toString() : null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\r\n     * )\r\n     */\r\n    @Override\r\n    public Long fromString(Class targetClass, String s)\r\n    {\r\n        try\r\n        {\r\n            if (s == null)\r\n            {\r\n                if (log.isWarnEnabled())\r\n                {\r\n                    log.warn(\"String s is null.\");\r\n                }\r\n                return null;\r\n            }\r\n            Long l = new Long(s);\r\n            return l;\r\n        }\r\n        catch (NumberFormatException e)\r\n        {\r\n            log.error(\"Number format exception, Caused by {}.\", e);\r\n            throw new PropertyAccessException(e);\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public Long getCopy(Object object)\r\n    {\r\n        return object != null ? (Long) object : null;\r\n    }\r\n\r\n    public Long getInstance(Class<?> clazz)\r\n    {\r\n        return Long.MAX_VALUE;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/ObjectAccessor.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.property.accessor;\r\n\r\nimport java.io.ByteArrayInputStream;\r\nimport java.io.ByteArrayOutputStream;\r\nimport java.io.IOException;\r\nimport java.io.ObjectInputStream;\r\nimport java.io.ObjectOutputStream;\r\nimport java.lang.reflect.InvocationTargetException;\r\nimport java.lang.reflect.Method;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.property.PropertyAccessException;\r\nimport com.impetus.kundera.property.PropertyAccessor;\r\n\r\n/**\r\n * The Class ObjectAccessor.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class ObjectAccessor implements PropertyAccessor<Object>\r\n{\r\n\r\n    public static Logger log = LoggerFactory.getLogger(ObjectAccessor.class);\r\n\r\n    /* @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[]) */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\r\n     */\r\n    @Override\r\n    public final Object fromBytes(Class targetClass, byte[] bytes)\r\n    {\r\n        try\r\n        {\r\n            if (bytes == null)\r\n            {\r\n                return null;\r\n            }\r\n            if (targetClass != null && targetClass.equals(byte[].class))\r\n            {\r\n                return bytes;\r\n            }\r\n            ObjectInputStream ois;\r\n            ois = new ObjectInputStream(new ByteArrayInputStream(bytes));\r\n            Object o = ois.readObject();\r\n            ois.close();\r\n            return o;\r\n        }\r\n        catch (IOException e)\r\n        {\r\n            log.error(\"IO exception, Caused by {}.\", e);\r\n            throw new PropertyAccessException(e);\r\n        }\r\n        catch (ClassNotFoundException e)\r\n        {\r\n            log.error(\"Class not found exception, Caused by {}.\", e);\r\n            throw new PropertyAccessException(e);\r\n        }\r\n\r\n    }\r\n\r\n    /*\r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\r\n     */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\r\n     */\r\n    @Override\r\n    public final byte[] toBytes(Object o)\r\n    {\r\n\r\n        try\r\n        {\r\n            if (o != null)\r\n            {\r\n                if (o instanceof byte[])\r\n                {\r\n                    return (byte[]) o;\r\n                }\r\n\r\n                ByteArrayOutputStream baos = new ByteArrayOutputStream();\r\n                ObjectOutputStream oos = new ObjectOutputStream(baos);\r\n                oos.writeObject(o);\r\n                oos.close();\r\n                return baos.toByteArray();\r\n            }\r\n        }\r\n        catch (IOException e)\r\n        {\r\n            log.error(\"IO exception, Caused by {}.\", e);\r\n            throw new PropertyAccessException(e);\r\n        }\r\n        return null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\r\n     */\r\n    @Override\r\n    public final String toString(Object object)\r\n    {\r\n        return object != null ? object.toString() : null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\r\n     * )\r\n     */\r\n    @Override\r\n    public Object fromString(Class targetClass, String s)\r\n    {\r\n        try\r\n        {\r\n            if (s == null)\r\n            {\r\n                return null;\r\n            }\r\n            Object o = (Object) s;\r\n            return o;\r\n        }\r\n        catch (NumberFormatException e)\r\n        {\r\n            log.error(\"Number format exception, Caused by {}.\", e);\r\n            throw new PropertyAccessException(e);\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public Object getCopy(Object object)\r\n    {\r\n        if (object == null)\r\n            return null;\r\n\r\n        if (object instanceof byte[])\r\n        {\r\n            byte[] byteArr = (byte[]) object;\r\n            return byteArr.clone();\r\n        }\r\n        else if (object instanceof Cloneable)\r\n        {\r\n            Class<?> clazz = object.getClass();\r\n\r\n            Object o = null;\r\n            try\r\n            {\r\n                Method m = clazz.getMethod(\"clone\");\r\n                o = m.invoke(object);\r\n            }\r\n            catch (SecurityException e)\r\n            {\r\n                log.warn(\"Object of class \" + object.getClass() + \" can't be cloned, due to exception:\"\r\n                        + e.getMessage());\r\n                return object;\r\n            }\r\n            catch (IllegalArgumentException e)\r\n            {\r\n                log.warn(\"Object of class \" + object.getClass() + \" can't be cloned, due to exception:\"\r\n                        + e.getMessage());\r\n                return object;\r\n            }\r\n            catch (NoSuchMethodException e)\r\n            {\r\n                log.warn(\"Object of class \" + object.getClass() + \" can't be cloned, due to exception:\"\r\n                        + e.getMessage());\r\n                return object;\r\n            }\r\n            catch (IllegalAccessException e)\r\n            {\r\n                log.warn(\"Object of class \" + object.getClass() + \" can't be cloned, due to exception:\"\r\n                        + e.getMessage());\r\n                return object;\r\n            }\r\n            catch (InvocationTargetException e)\r\n            {\r\n                log.warn(\"Object of class \" + object.getClass() + \" can't be cloned, due to exception:\"\r\n                        + e.getMessage());\r\n                return object;\r\n            }\r\n            return o;\r\n        }\r\n        else\r\n        {\r\n            return object;\r\n        }\r\n    }\r\n\r\n    public Object getInstance(Class<?> clazz)\r\n    {\r\n        Object o = null;\r\n        try\r\n        {\r\n            o = clazz.newInstance();\r\n            return o;\r\n        }\r\n        catch (InstantiationException ie)\r\n        {\r\n            log.warn(\"Instantiation exception,caused by :\" + ie.getMessage());\r\n            return null;\r\n        }\r\n        catch (IllegalAccessException iae)\r\n        {\r\n            log.warn(\"Illegal access exception,caused by :\" + iae.getMessage());\r\n            return null;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/PointAccessor.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.property.accessor;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.gis.geometry.Point;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\nimport com.vividsolutions.jts.io.ParseException;\nimport com.vividsolutions.jts.io.WKTReader;\n\n/**\n * Property Accessor for {@link Point}\n * \n * @author amresh.singh\n */\npublic class PointAccessor implements PropertyAccessor<Point>\n{\n    public static Logger log = LoggerFactory.getLogger(PointAccessor.class);\n    \n    @Override\n    public Point fromBytes(Class targetClass, byte[] b)\n    {\n        ObjectInputStream ois;\n        Point o;\n        try\n        {\n            ois = new ObjectInputStream(new ByteArrayInputStream(b));\n            o = (Point) ois.readObject();\n            ois.close();\n        }\n        catch (IOException e)\n        {\n            log.error(\"IO exception, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n        catch (ClassNotFoundException e)\n        {\n            log.error(\"Class not found exception, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n        return o;\n    }\n\n    @Override\n    public byte[] toBytes(Object object)\n    {\n        ByteArrayOutputStream baos;\n        try\n        {\n            baos = new ByteArrayOutputStream();\n            ObjectOutputStream oos = new ObjectOutputStream(baos);\n            oos.writeObject(object);\n            oos.close();\n            return baos.toByteArray();\n        }\n        catch (IOException e)\n        {\n            log.error(\"IO exception, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    @Override\n    public String toString(Object object)\n    {\n        return object != null ? object.toString() : null;\n    }\n\n    @Override\n    public Point fromString(Class targetClass, String s)\n    {\n        if (s == null)\n            return null;\n\n        WKTReader reader = new WKTReader();\n        try\n        {\n            return new Point((com.vividsolutions.jts.geom.Point) reader.read(s));\n        }\n        catch (ParseException e)\n        {\n            log.error(\"Parse exception, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    @Override\n    public Point getCopy(Object object)\n    {\n        if (object == null)\n            return null;\n\n        Point p = (Point) object;\n        return new Point(p.getX(), p.getY());\n    }\n\n    @Override\n    public Object getInstance(Class<?> clazz)\n    {\n        return new Point(0.0, 0.0);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/SQLDateAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.sql.Date;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * The Class SQLDateAccessor.\n * \n * @author amresh.singh\n */\npublic class SQLDateAccessor implements PropertyAccessor<Date>\n\n{\n    public static Logger log = LoggerFactory.getLogger(SQLDateAccessor.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\n     */\n    @Override\n    public Date fromBytes(Class targetClass, byte[] b)\n    {\n        try\n        {\n            if (b == null)\n            {\n                return null;\n            }\n\n            // In case date.getTime() is stored in DB.\n            LongAccessor longAccessor = new LongAccessor();\n\n            return new Date(longAccessor.fromBytes(targetClass, b));\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error occured, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\n     */\n    @Override\n    public byte[] toBytes(Object object)\n    {\n\n        try\n        {\n            if (object == null)\n            {\n                return null;\n            }\n            LongAccessor longAccessor = new LongAccessor();\n            return longAccessor.toBytes(((Date) object).getTime());\n            // return DATE_FORMATTER.format(((Date)\n            // date)).getBytes(Constants.ENCODING);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error occured, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\n     */\n    @Override\n    public String toString(Object object)\n    {\n        Date date = (Date) object;\n\n        if (date == null)\n        {\n            return null;\n        }\n\n        return String.valueOf(date.getTime())/*date.toString()*/;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\n     * )\n     */\n    @Override\n    public Date fromString(Class targetClass, String s)\n    {\n\n        if (s == null)\n        {\n            return null;\n        }\n        if (StringUtils.isNumeric(s))\n        {\n            return new Date(Long.parseLong(s));\n        }\n        Date d = Date.valueOf(s);\n        return d;\n    }\n\n    @Override\n    public Date getCopy(Object object)\n    {\n        Date d = (Date) object;\n        return d != null ? new Date(d.getTime()) : null;\n    }\n\n    public Date getInstance(Class<?> clazz)\n    {\n        return new Date(Integer.MAX_VALUE);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/SQLTimeAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.sql.Time;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * The Class SQLTimeAccessor.\n * \n * @author amresh.singh\n */\npublic class SQLTimeAccessor implements PropertyAccessor<Time>\n{\n    public static Logger log = LoggerFactory.getLogger(SQLTimeAccessor.class);\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\n     */\n    @Override\n    public Time fromBytes(Class targetClass, byte[] b)\n    {\n        // String s;\n        // try\n        // {\n        //\n        // if (b == null)\n        // {\n        // return null;\n        // }\n        // s = new String(b, Constants.ENCODING);\n        // }\n        // catch (UnsupportedEncodingException e)\n        // {\n        // throw new PropertyAccessException(e);\n        // }\n        // return fromString(targetClass, s);\n        try\n        {\n            if (b == null)\n            {\n                return null;\n            }\n\n            // In case date.getTime() is stored in DB.\n            LongAccessor longAccessor = new LongAccessor();\n\n            return new Time(longAccessor.fromBytes(targetClass, b));\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error occured, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\n     */\n    @Override\n    public byte[] toBytes(Object object)\n    {\n\n        // if (object == null)\n        // {\n        // return null;\n        // }\n        // Time t = (Time) object;\n        // return t.toString().getBytes();\n\n        try\n        {\n            if (object == null)\n            {\n                return null;\n            }\n            LongAccessor longAccessor = new LongAccessor();\n            return longAccessor.toBytes(((Time) object).getTime());\n            // return DATE_FORMATTER.format(((Date)\n            // date)).getBytes(Constants.ENCODING);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error occured, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\n     */\n    @Override\n    public String toString(Object object)\n    {\n        Time time = (Time) object;\n\n        if (time == null)\n        {\n            return null;\n        }\n\n        return String.valueOf(time.getTime());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\n     * )\n     */\n    @Override\n    public Time fromString(Class targetClass, String s)\n    {\n        if (s == null)\n        {\n            return null;\n        }\n\n        if (StringUtils.isNumeric(s))\n        {\n            return new Time(Long.parseLong(s));\n        }\n        Time t = Time.valueOf(s);\n        return t;\n    }\n\n    @Override\n    public Time getCopy(Object object)\n    {\n        Time t = (Time) object;\n        return t != null ? new Time(t.getTime()) : null;\n    }\n\n    public Time getInstance(Class<?> clazz)\n    {\n        return new Time(Integer.MAX_VALUE);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/SQLTimestampAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.sql.Timestamp;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * The Class SQLTimestampAccessor.\n * \n * @author amresh.singh\n */\npublic class SQLTimestampAccessor implements PropertyAccessor<Timestamp>\n{\n    public static Logger log = LoggerFactory.getLogger(SQLTimestampAccessor.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\n     */\n    @Override\n    public Timestamp fromBytes(Class targetClass, byte[] b)\n    {\n\n        // String s;\n        // try\n        // {\n        // if(b == null)\n        // {\n        // return null;\n        // }\n        // s = new String(b, Constants.ENCODING);\n        // }\n        // catch (UnsupportedEncodingException e)\n        // {\n        // throw new PropertyAccessException(e);\n        // }\n        // return fromString(targetClass, s);\n        try\n        {\n            if (b == null)\n            {\n                return null;\n            }\n\n            // In case date.getTime() is stored in DB.\n            LongAccessor longAccessor = new LongAccessor();\n\n            return new Timestamp(longAccessor.fromBytes(targetClass, b));\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error occured, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\n     */\n    @Override\n    public byte[] toBytes(Object object)\n    {\n        // if(object == null)\n        // {\n        // return null;\n        // }\n        // Timestamp t = (Timestamp) object;\n        // return t.toString().getBytes();\n        try\n        {\n            if (object == null)\n            {\n                return null;\n            }\n            LongAccessor longAccessor = new LongAccessor();\n            return longAccessor.toBytes(((Timestamp) object).getTime());\n            // return DATE_FORMATTER.format(((Date)\n            // date)).getBytes(Constants.ENCODING);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error occured, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\n     */\n    @Override\n    public String toString(Object object)\n    {\n        Timestamp timeStamp = (Timestamp) object;\n\n        if (timeStamp == null)\n        {\n            return null;\n        }\n\n        return String.valueOf(timeStamp.getTime());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\n     * )\n     */\n    @Override\n    public Timestamp fromString(Class targetClass, String s)\n    {\n        if (s == null)\n        {\n            return null;\n        }\n        if (StringUtils.isNumeric(s))\n        {\n            return new Timestamp(Long.parseLong(s));\n        }\n        Timestamp t = Timestamp.valueOf(s);\n        return t;\n    }\n\n    @Override\n    public Timestamp getCopy(Object object)\n    {\n        Timestamp ts = (Timestamp) object;\n        return ts != null ? new Timestamp(ts.getTime()) : null;\n    }\n\n    public Timestamp getInstance(Class<?> clazz)\n    {\n        return new Timestamp(Integer.MAX_VALUE);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/ShortAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * The Class ShortAccessor.\n * \n * @author Amresh Singh\n */\npublic class ShortAccessor implements PropertyAccessor<Short>\n{\n    public static Logger log = LoggerFactory.getLogger(ShortAccessor.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\n     */\n    @Override\n    public Short fromBytes(Class targetClass, byte[] data)\n    {\n        if (data == null || data.length != 2)\n        {\n            if (log.isWarnEnabled())\n            {\n                log.warn(\"Bytes length not equal to 2\");\n            }\n            return 0x0;\n        }\n        return (short) ((0xff & data[0]) << 8 | (0xff & data[1]) << 0);\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\n     */\n    @Override\n    public byte[] toBytes(Object object)\n    {\n        Short s = null;\n        if (object != null)\n        {\n\n            if (object.getClass().isAssignableFrom(String.class))\n            {\n                s = Short.valueOf(object.toString());\n            }\n            else\n            {\n                s = (Short) object;\n            }\n            return new byte[] { (byte) ((s >> 8) & 0xff), (byte) ((s >> 0) & 0xff), };\n        }\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\n     */\n    @Override\n    public String toString(Object object)\n    {\n        return object != null ? object.toString() : null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\n     * )\n     */\n    @Override\n    public Short fromString(Class targetClass, String s)\n    {\n        try\n        {\n\n            if (s == null)\n            {\n                return null;\n            }\n            Short sh = new Short(s);\n            return sh;\n        }\n        catch (NumberFormatException e)\n        {\n            log.error(\"Number format exception, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    @Override\n    public Short getCopy(Object object)\n    {\n        return object != null ? (Short) object : null;\n    }\n\n    public Short getInstance(Class<?> clazz)\n    {\n        return Short.MAX_VALUE;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/StringAccessor.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.property.accessor;\r\n\r\nimport java.io.UnsupportedEncodingException;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.Constants;\r\nimport com.impetus.kundera.property.PropertyAccessException;\r\nimport com.impetus.kundera.property.PropertyAccessor;\r\n\r\n/**\r\n * The Class StringAccessor.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class StringAccessor implements PropertyAccessor<String>\r\n{\r\n    public static Logger log = LoggerFactory.getLogger(StringAccessor.class);\r\n\r\n    /* @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[]) */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.property.PropertyAccessor#fromBytes(byte[])\r\n     */\r\n    @Override\r\n    public final String fromBytes(Class targetClass, byte[] bytes)\r\n    {\r\n\r\n        try\r\n        {\r\n            return bytes != null ? new String(bytes, Constants.CHARSET_UTF8) : null;\r\n        }\r\n        catch (UnsupportedEncodingException e)\r\n        {\r\n            log.error(\"Unsupported encoding exception, Caused by {}.\", e);\r\n            throw new PropertyAccessException(e);\r\n        }\r\n\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\r\n     */\r\n    @Override\r\n    public final byte[] toBytes(Object s) throws PropertyAccessException\r\n    {\r\n\r\n        try\r\n        {\r\n            return s != null ? ((String) s).getBytes(Constants.CHARSET_UTF8) : null;\r\n        }\r\n        catch (UnsupportedEncodingException e)\r\n        {\r\n            log.error(\"Unsupported encoding exception, Caused by {}.\", e);\r\n            throw new PropertyAccessException(e);\r\n        }\r\n\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\r\n     */\r\n    @Override\r\n    public final String toString(Object object)\r\n    {\r\n        if (object != null && object.getClass().isAssignableFrom(String.class))\r\n        {\r\n            return (String) object;\r\n        }\r\n        return null;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.String\r\n     * )\r\n     */\r\n    @Override\r\n    public String fromString(Class targetClass, String s)\r\n    {\r\n        return s;\r\n    }\r\n\r\n    @Override\r\n    public String getCopy(Object object)\r\n    {\r\n        return object != null ? new String((String) object) : null;\r\n    }\r\n\r\n    public String getInstance(Class<?> clazz)\r\n    {\r\n        return new String();\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/property/accessor/UUIDAccessor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.util.UUID;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * The Class UUIDAccessor.\n * \n * @author kcarlson\n */\npublic class UUIDAccessor implements PropertyAccessor<UUID>\n{\n\n    public static Logger log = LoggerFactory.getLogger(UUIDAccessor.class);\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromBytes(java.lang.Class,\n     * byte[])\n     */\n    @Override\n    public UUID fromBytes(Class targetClass, byte[] bytes) throws PropertyAccessException\n    {\n        // try\n        // {\n        // if(bytes == null)\n        // {\n        // return null;\n        // }\n        // return UUID.nameUUIDFromBytes(bytes);\n        // }\n        // catch (Exception e)\n        // {\n        // throw new PropertyAccessException(e);\n        // }\n\n        // * Deserializes a TimeUUID from a byte array\n        // * @param uuid The bytes of the time UUID\n        // * @return The deserialized time UUID object\n        // */\n        // public static java.util.UUID timeUuidFromBytes( byte[] uuid )\n        // {\n        // long msb = 0;\n        // long lsb = 0;\n        // assert bytes.length == 16;\n        // for (int i = 0; i < 8; i++)\n        // msb = (msb << 8) | (bytes[i] & 0xff);\n        // for (int i = 8; i < 16; i++)\n        // lsb = (lsb << 8) | (bytes[i] & 0xff);\n        //\n        // com.eaio.uuid.UUID u = new com.eaio.uuid.UUID(msb, lsb);\n        //\n        // return java.util.UUID.fromString(u.toString());\n\n        try\n        {\n            if (bytes == null)\n            {\n                return null;\n            }\n            long msb = 0;\n            long lsb = 0;\n            for (int i = 0; i < 8; i++)\n                msb = (msb << 8) | (bytes[i] & 0xff);\n            for (int i = 8; i < 16; i++)\n                lsb = (lsb << 8) | (bytes[i] & 0xff);\n            return new UUID(msb, lsb);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error occured, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toBytes(java.lang.Object)\n     */\n    @Override\n    public byte[] toBytes(Object object) throws PropertyAccessException\n    {\n        try\n        {\n            if (object == null)\n            {\n                return null;\n            }\n            UUID uuid = (UUID) object;\n            return asByteArray(uuid);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error occured, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#toString(java.lang.Object)\n     */\n    @Override\n    public String toString(Object object)\n    {\n        if (object == null)\n        {\n            return null;\n        }\n        return ((UUID) object).toString();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.property.PropertyAccessor#fromString(java.lang.Class,\n     * java.lang.String)\n     */\n    @Override\n    public UUID fromString(Class targetClass, String s) throws PropertyAccessException\n    {\n        try\n        {\n            if (s == null)\n            {\n                return null;\n            }\n            return UUID.fromString(s);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error occured, Caused by {}.\", e);\n            throw new PropertyAccessException(e);\n        }\n    }\n\n    /**\n     * Returns as byte array.\n     * \n     * @param uuid\n     *            UUID\n     * @return byte[] array.\n     */\n    private static byte[] asByteArray(UUID uuid)\n    {\n        if (uuid == null)\n        {\n            return null;\n        }\n        long msb = uuid.getMostSignificantBits();\n        long lsb = uuid.getLeastSignificantBits();\n        byte[] buffer = new byte[16];\n\n        for (int i = 0; i < 8; i++)\n        {\n            buffer[i] = (byte) (msb >>> 8 * (7 - i));\n        }\n        for (int i = 8; i < 16; i++)\n        {\n            buffer[i] = (byte) (lsb >>> 8 * (7 - i));\n        }\n\n        return buffer;\n    }\n\n    @Override\n    public UUID getCopy(Object object)\n    {\n        UUID uuid = (UUID) object;\n\n        return uuid != null ? UUID.fromString(uuid.toString()) : null;\n    }\n\n    public UUID getInstance(Class<?> clazz)\n    {\n        return UUID.randomUUID();\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/KunderaProxy.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.proxy;\r\n\r\n/**\r\n * Interface for proxies.*\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic interface KunderaProxy\r\n{\r\n    public abstract Object writeReplace();\r\n\r\n    public abstract LazyInitializer getKunderaLazyInitializer();\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/LazyInitializationException.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.proxy;\r\n\r\nimport com.impetus.kundera.KunderaException;\r\n\r\n/**\r\n * The Class LazyInitializationException.\r\n */\r\npublic class LazyInitializationException extends KunderaException\r\n{\r\n\r\n    /** The Constant serialVersionUID. */\r\n    private static final long serialVersionUID = 1L;\r\n\r\n    /**\r\n     * @param arg0\r\n     */\r\n    public LazyInitializationException(String arg0)\r\n    {\r\n        super(arg0);\r\n    }\r\n\r\n    /**\r\n     * @param arg0\r\n     */\r\n    public LazyInitializationException(Throwable arg0)\r\n    {\r\n        super(arg0);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/LazyInitializer.java",
    "content": "/*******************************************************************************\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.proxy;\r\n\r\nimport javax.persistence.PersistenceException;\r\n\r\nimport com.impetus.kundera.persistence.PersistenceDelegator;\r\n\r\n/**\r\n * Handles fetching of the underlying entity for a proxy.\r\n * \r\n * @author Gavin King\r\n * @author Steve Ebersole\r\n */\r\npublic interface LazyInitializer\r\n{\r\n\r\n    /**\r\n     * Initialize the proxy, fetching the target entity if necessary.\r\n     * \r\n     * @throws PersistenceException\r\n     *             the persistence exception\r\n     */\r\n    public void initialize() throws PersistenceException;\r\n\r\n    /**\r\n     * Retrieve the identifier value for the enity our owning proxy represents.\r\n     * \r\n     * @return The identifier value.\r\n     */\r\n    public Object getIdentifier();\r\n\r\n    /**\r\n     * Set the identifier value for the enity our owning proxy represents.\r\n     * \r\n     * @param id\r\n     *            The identifier value.\r\n     */\r\n    public void setIdentifier(Object id);\r\n\r\n    /**\r\n     * The entity-name of the entity our owning proxy represents.\r\n     * \r\n     * @return The entity-name.\r\n     */\r\n    public String getEntityName();\r\n\r\n    /**\r\n     * Get the actual class of the entity. Generally, {@link #getEntityName()}\r\n     * should be used instead.\r\n     * \r\n     * @return The actual entity class.\r\n     */\r\n    public Class<?> getPersistentClass();\r\n\r\n    /**\r\n     * Is the proxy uninitialzed?.\r\n     * \r\n     * @return True if uninitialized; false otherwise.\r\n     */\r\n    public boolean isUninitialized();\r\n\r\n    /**\r\n     * Get the session to which this proxy is associated, or null if it is not\r\n     * attached.\r\n     * \r\n     * @return The associated session.\r\n     */\r\n    public PersistenceDelegator getPersistenceDelegator();\r\n\r\n    /**\r\n     * Unset this initializer's reference to session. It is assumed that the\r\n     * caller is also taking care or cleaning up the owning proxy's reference in\r\n     * the persistence context.\r\n     */\r\n    public void unsetPersistenceDelegator();\r\n\r\n    /**\r\n     * Sets the unwrap.\r\n     * \r\n     * @param unwrap\r\n     *            the new unwrap\r\n     */\r\n    public void setUnwrap(boolean unwrap);\r\n\r\n    /**\r\n     * Checks if is unwrap.\r\n     * \r\n     * @return true, if is unwrap\r\n     */\r\n    public boolean isUnwrap();\r\n\r\n    public abstract Object getImplementation();\r\n\r\n    public abstract void setImplementation(Object paramObject);\r\n\r\n    public void setOwner(Object owner) throws PersistenceException;\r\n\r\n    public Object getOwner() throws PersistenceException;\r\n\r\n    public void setInitialized(boolean initialized);\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/LazyInitializerFactory.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.proxy;\r\n\r\nimport java.lang.reflect.Method;\r\n\r\nimport javax.persistence.PersistenceException;\r\n\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.persistence.PersistenceDelegator;\r\n\r\n/**\r\n * Interface LazyInitializerFactory\r\n * \r\n * Creates Lazily loadable proxies for @Entity classes.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic interface LazyInitializerFactory\r\n{\r\n\r\n    /**\r\n     * Get Lazily loadable @Entity proxy.\r\n     * \r\n     * @param entityName\r\n     *            the entity name\r\n     * @param persistentClass\r\n     *            the persistent class\r\n     * @param getIdentifierMethod\r\n     *            the get identifier method\r\n     * @param setIdentifierMethod\r\n     *            the set identifier method\r\n     * @param id\r\n     *            the id\r\n     * @param persistenceDelegator\r\n     *            the persistence delegator\r\n     * @return the proxy\r\n     * @throws PersistenceException\r\n     *             the persistence exception\r\n     */\r\n    KunderaProxy getProxy(final String entityName, final Class<?> persistentClass, final Method getIdentifierMethod,\r\n            final Method setIdentifierMethod, final Object id, final PersistenceDelegator pd);\r\n\r\n    /**\r\n     * Returns proxy instance for a given entity name, null if none exists\r\n     * \r\n     * @param entityName\r\n     * @return\r\n     */\r\n    KunderaProxy getProxy(String entityName);\r\n\r\n    /**\r\n     * Clears all proxy objects stored in this factory\r\n     */\r\n    void clearProxies();\r\n    \r\n    /**\r\n     * Sets the entity e as \"owner\" into proxy it holds.\r\n     */\r\n    <E> void setProxyOwners(EntityMetadata entityMetadata, E e);\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/ProxyHelper.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.proxy;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javassist.util.proxy.ProxyFactory;\n\nimport com.impetus.kundera.proxy.collection.ProxyCollection;\n\n/**\n * Utility class for proxy objects\n * \n * @author amresh.singh\n */\npublic class ProxyHelper\n{\n\n    static List<String> proxyTypes = new ArrayList<String>();\n\n    static List<String> persistentCollectionTypes = new ArrayList<String>();\n\n    static\n    {\n        proxyTypes.add(\"org.hibernate.proxy.HibernateProxy\");\n        proxyTypes.add(\"org.hibernate.proxy.map.MapProxy\");\n        proxyTypes.add(\"org.hibernate.proxy.dom4j.Dom4jProxy\");\n\n        persistentCollectionTypes.add(\"org.hibernate.collection.spi.PersistentCollection\");\n        persistentCollectionTypes.add(\"org.hibernate.collection.internal.AbstractPersistentCollection\");\n        persistentCollectionTypes.add(\"org.hibernate.collection.internal.PersistentBag\");\n        persistentCollectionTypes.add(\"org.hibernate.collection.internal.PersistentList\");\n        persistentCollectionTypes.add(\"org.hibernate.collection.internal.PersistentSet\");\n        persistentCollectionTypes.add(\"org.hibernate.collection.internal.PersistentSortedSet\");\n        persistentCollectionTypes.add(\"org.hibernate.collection.internal.PersistentMap\");\n        persistentCollectionTypes.add(\"org.hibernate.collection.internal.PersistentSortedMap\");\n    }\n\n    public static boolean isKunderaProxy(Object o)\n    {\n        return o == null ? false : o instanceof KunderaProxy;\n    }\n\n    public static boolean isHibernateProxy(Object o)\n    {\n        return o == null ? false : proxyTypes.contains(o.getClass().getName());\n    }\n\n    public static boolean isKunderaProxyCollection(Object collection)\n    {\n        return collection == null ? false : collection instanceof ProxyCollection;\n    }\n\n    public static boolean isPersistentCollection(Object collection)\n    {\n        return collection == null ? false : persistentCollectionTypes.contains(collection.getClass().getName());\n    }\n\n    public static boolean isProxy(Object o)\n    {\n        return isKunderaProxy(o) || isHibernateProxy(o) || ProxyFactory.isProxyClass(o.getClass());\n    }\n\n    public static boolean isProxyCollection(Object o)\n    {\n        return isKunderaProxyCollection(o) || isPersistentCollection(o);\n    }\n\n    public static boolean isProxyOrCollection(Object o)\n    {\n        return isProxy(o) || isProxyCollection(o);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/cglib/CglibLazyInitializer.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.proxy.cglib;\r\n\r\nimport java.lang.reflect.InvocationTargetException;\r\nimport java.lang.reflect.Method;\r\n\r\nimport javax.persistence.PersistenceException;\r\n\r\nimport net.sf.cglib.proxy.Callback;\r\nimport net.sf.cglib.proxy.CallbackFilter;\r\nimport net.sf.cglib.proxy.Enhancer;\r\nimport net.sf.cglib.proxy.InvocationHandler;\r\nimport net.sf.cglib.proxy.NoOp;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.metadata.model.Relation;\r\nimport com.impetus.kundera.persistence.PersistenceDelegator;\r\nimport com.impetus.kundera.property.PropertyAccessorHelper;\r\nimport com.impetus.kundera.proxy.KunderaProxy;\r\nimport com.impetus.kundera.proxy.LazyInitializationException;\r\nimport com.impetus.kundera.proxy.LazyInitializer;\r\n\r\n/**\r\n * A <tt>LazyInitializer</tt> implemented using the CGLIB bytecode generation\r\n * library.\r\n */\r\npublic final class CglibLazyInitializer implements LazyInitializer, InvocationHandler\r\n{\r\n\r\n    /** The Constant log. */\r\n    private static final Logger log = LoggerFactory.getLogger(CglibLazyInitializer.class);\r\n\r\n    /** The entity name. */\r\n    private String entityName;\r\n\r\n    /** The id. */\r\n    private Object id;\r\n\r\n    /** The target. */\r\n    private Object owner;\r\n\r\n    /** The target. */\r\n    private Object target;\r\n\r\n    /** The initialized. */\r\n    private boolean initialized;\r\n\r\n    /** The unwrap. */\r\n    private boolean unwrap;\r\n\r\n    /** The persistent class. */\r\n    protected Class<?> persistentClass;\r\n\r\n    /** The get identifier method. */\r\n    protected Method getIdentifierMethod;\r\n\r\n    /** The set identifier method. */\r\n    protected Method setIdentifierMethod;\r\n\r\n    /** The interfaces. */\r\n    private Class<?>[] interfaces;\r\n\r\n    /** The constructed. */\r\n    private boolean constructed = false;\r\n\r\n    /** The persistenceDelegator. */\r\n    private transient PersistenceDelegator persistenceDelegator;\r\n\r\n    /** The Constant FINALIZE_FILTER. */\r\n    private static final CallbackFilter FINALIZE_FILTER = new CallbackFilter()\r\n    {\r\n        public int accept(Method method)\r\n        {\r\n            if (method.getParameterTypes().length == 0 && method.getName().equals(\"finalize\"))\r\n            {\r\n                return 1;\r\n            }\r\n            else\r\n            {\r\n                return 0;\r\n            }\r\n        }\r\n    };\r\n\r\n    /**\r\n     * Gets the proxy.\r\n     * \r\n     * @param entityName\r\n     *            the entity name\r\n     * @param persistentClass\r\n     *            the persistent class\r\n     * @param interfaces\r\n     *            the interfaces\r\n     * @param getIdentifierMethod\r\n     *            the get identifier method\r\n     * @param setIdentifierMethod\r\n     *            the set identifier method\r\n     * @param id\r\n     *            the id\r\n     * @param persistenceDelegator\r\n     *            the persistence delegator\r\n     * @return the proxy\r\n     * @throws PersistenceException\r\n     *             the persistence exception\r\n     */\r\n    public static KunderaProxy getProxy(final String entityName, final Class<?> persistentClass,\r\n            final Class<?>[] interfaces, final Method getIdentifierMethod, final Method setIdentifierMethod,\r\n            final Object id, final PersistenceDelegator pd) throws PersistenceException\r\n    {\r\n\r\n        final CglibLazyInitializer instance = new CglibLazyInitializer(entityName, persistentClass, interfaces, id,\r\n                getIdentifierMethod, setIdentifierMethod, pd);\r\n\r\n        final KunderaProxy proxy;\r\n        Class factory = getProxyFactory(persistentClass, interfaces);\r\n\r\n        proxy = getProxyInstance(factory, instance);\r\n\r\n        instance.constructed = true;\r\n        return proxy;\r\n\r\n    }\r\n\r\n    /**\r\n     * Gets the proxy instance.\r\n     * \r\n     * @param factory\r\n     *            the factory\r\n     * @param instance\r\n     *            the instance\r\n     * @return the proxy instance\r\n     * @throws InstantiationException\r\n     *             the instantiation exception\r\n     * @throws IllegalAccessException\r\n     *             the illegal access exception\r\n     */\r\n    private static KunderaProxy getProxyInstance(Class factory, CglibLazyInitializer instance)\r\n    {\r\n        KunderaProxy proxy;\r\n        try\r\n        {\r\n            Enhancer.registerCallbacks(factory, new Callback[] { instance, null });\r\n            proxy = (KunderaProxy) factory.newInstance();\r\n        }\r\n        catch (IllegalAccessException e)\r\n        {\r\n            throw new LazyInitializationException(e);\r\n        }\r\n        catch (InstantiationException e)\r\n        {\r\n            throw new LazyInitializationException(e);\r\n        }\r\n        finally\r\n        {\r\n            Enhancer.registerCallbacks(factory, null);\r\n        }\r\n        return proxy;\r\n    }\r\n\r\n    /**\r\n     * Gets the proxy factory.\r\n     * \r\n     * @param persistentClass\r\n     *            the persistent class\r\n     * @param interfaces\r\n     *            the interfaces\r\n     * @return the proxy factory\r\n     * @throws PersistenceException\r\n     *             the persistence exception\r\n     */\r\n    public static Class getProxyFactory(Class persistentClass, Class[] interfaces) throws PersistenceException\r\n    {\r\n        Enhancer e = new Enhancer();\r\n        e.setSuperclass(interfaces.length == 1 ? persistentClass : null);\r\n        e.setInterfaces(interfaces);\r\n        e.setCallbackTypes(new Class[] { InvocationHandler.class, NoOp.class, });\r\n        e.setCallbackFilter(FINALIZE_FILTER);\r\n        e.setUseFactory(false);\r\n        e.setInterceptDuringConstruction(false);\r\n        return e.createClass();\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new cglib lazy initializer.\r\n     * \r\n     * @param entityName\r\n     *            the entity name\r\n     * @param persistentClass\r\n     *            the persistent class\r\n     * @param interfaces\r\n     *            the interfaces\r\n     * @param id\r\n     *            the id\r\n     * @param getIdentifierMethod\r\n     *            the get identifier method\r\n     * @param setIdentifierMethod\r\n     *            the set identifier method\r\n     * @param persistenceDelegator\r\n     *            the persistence delegator\r\n     */\r\n    private CglibLazyInitializer(final String entityName, final Class<?> persistentClass, final Class<?>[] interfaces,\r\n            final Object id, final Method getIdentifierMethod, final Method setIdentifierMethod,\r\n            final PersistenceDelegator pd)\r\n    {\r\n\r\n        this.entityName = entityName;\r\n        this.id = id;\r\n        this.persistenceDelegator = pd;\r\n        this.persistentClass = persistentClass;\r\n        this.getIdentifierMethod = getIdentifierMethod;\r\n        this.setIdentifierMethod = setIdentifierMethod;\r\n        this.interfaces = interfaces;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see net.sf.cglib.proxy.InvocationHandler#invoke(java.lang.Object,\r\n     * java.lang.reflect.Method, java.lang.Object[])\r\n     */\r\n    @Override\r\n    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable\r\n    {\r\n        if (constructed)\r\n        {\r\n\r\n            String methodName = method.getName();\r\n            int params = args.length;\r\n\r\n            if (params == 0)\r\n            {\r\n                if (isUninitialized() && method.equals(getIdentifierMethod))\r\n                {\r\n                    return getIdentifier();\r\n                }\r\n\r\n                else if (\"getKunderaLazyInitializer\".equals(methodName))\r\n                {\r\n                    return this;\r\n                }\r\n            }\r\n\r\n            Object target = getImplementation();\r\n\r\n            String[] strArr = entityName.split(\"#\");\r\n            String fieldName = strArr[1];\r\n\r\n            if (owner != null)\r\n            {\r\n                EntityMetadata m = KunderaMetadataManager.getEntityMetadata(persistenceDelegator.getKunderaMetadata(),\r\n                        owner.getClass());\r\n                Relation r = m.getRelation(fieldName);\r\n                if (r != null)\r\n                {\r\n                    PropertyAccessorHelper.set(owner, r.getProperty(), target);\r\n                }\r\n                if (r.getBiDirectionalField() != null && method.getReturnType().equals(m.getEntityClazz()))\r\n                {\r\n                    PropertyAccessorHelper.set(target, r.getBiDirectionalField(), owner);\r\n                }\r\n\r\n            }\r\n\r\n            try\r\n            {\r\n                final Object returnValue;\r\n                if (method.isAccessible())\r\n                {\r\n                    if (!method.getDeclaringClass().isInstance(target))\r\n                    {\r\n                        throw new ClassCastException(target.getClass().getName());\r\n                    }\r\n                    returnValue = method.invoke(target, args);\r\n                }\r\n                else\r\n                {\r\n                    if (!method.isAccessible())\r\n                    {\r\n                        method.setAccessible(true);\r\n                    }\r\n                    returnValue = method.invoke(target, args);\r\n                }\r\n                return ((returnValue == target) ? proxy : returnValue);\r\n            }\r\n            catch (InvocationTargetException ite)\r\n            {\r\n                throw new LazyInitializationException(ite);\r\n            }\r\n        }\r\n        else\r\n        {\r\n            // while constructor is running\r\n            throw new LazyInitializationException(\"unexpected case hit, method=\" + method.getName());\r\n        }\r\n\r\n    }\r\n\r\n    /* @see com.impetus.kundera.proxy.LazyInitializer#getPersistentClass() */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.proxy.LazyInitializer#getPersistentClass()\r\n     */\r\n    public final Class<?> getPersistentClass()\r\n    {\r\n        return persistentClass;\r\n    }\r\n\r\n    /**\r\n     * Gets the entity name.\r\n     * \r\n     * @return the entity name {@inheritDoc}\r\n     */\r\n    public final String getEntityName()\r\n    {\r\n        return entityName;\r\n    }\r\n\r\n    /**\r\n     * @return the id\r\n     */\r\n    @Override\r\n    public Object getIdentifier()\r\n    {\r\n        return id;\r\n    }\r\n\r\n    /**\r\n     * @param id\r\n     *            the id to set\r\n     */\r\n    @Override\r\n    public void setIdentifier(Object id)\r\n    {\r\n        this.id = id;\r\n    }\r\n\r\n    /**\r\n     * Checks if is uninitialized.\r\n     * \r\n     * @return true, if is uninitialized {@inheritDoc}\r\n     */\r\n    public final boolean isUninitialized()\r\n    {\r\n        return !initialized;\r\n    }\r\n\r\n    /**\r\n     * @param initialized\r\n     *            the initialized to set\r\n     */\r\n    public void setInitialized(boolean initialized)\r\n    {\r\n        this.initialized = initialized;\r\n    }\r\n\r\n    /**\r\n     * Initialize.\r\n     * \r\n     * @throws PersistenceException\r\n     *             the persistence exception {@inheritDoc}\r\n     */\r\n    public final void initialize() throws PersistenceException\r\n    {\r\n        if (!initialized)\r\n        {\r\n            if (persistenceDelegator == null)\r\n            {\r\n                throw new LazyInitializationException(\"could not initialize proxy \" + persistentClass.getName() + \"_\"\r\n                        + id + \" - no EntityManager\");\r\n            }\r\n            else if (!persistenceDelegator.isOpen())\r\n            {\r\n                throw new LazyInitializationException(\"could not initialize proxy \" + persistentClass.getName() + \"_\"\r\n                        + id + \" - the owning Session was closed\");\r\n            }\r\n            else\r\n            {\r\n                if (log.isDebugEnabled())\r\n                    log.debug(\"Proxy >> Initialization >> \" + persistentClass.getName() + \"_\" + id);\r\n\r\n                // TODO: consider not calling em.find from here. Not sure 'why',\r\n                // but something\r\n                // doesn't feel right.\r\n                target = persistenceDelegator.findById(persistentClass, id);\r\n                initialized = true;\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Return the underlying persistent object, initializing if necessary.\r\n     * \r\n     * @return the implementation\r\n     */\r\n    @Override\r\n    public final Object getImplementation()\r\n    {\r\n        initialize();\r\n        return target;\r\n    }\r\n\r\n    /**\r\n     * Getter for property 'target'.\r\n     * <p/>\r\n     * Same as {@link #getImplementation()} except that this method will not\r\n     * force initialization.\r\n     * \r\n     * @return Value for property 'target'.\r\n     */\r\n    protected final Object getTarget()\r\n    {\r\n        return target;\r\n    }\r\n\r\n    /**\r\n     * Checks if is unwrap.\r\n     * \r\n     * @return true, if is unwrap {@inheritDoc}\r\n     */\r\n    public boolean isUnwrap()\r\n    {\r\n        return unwrap;\r\n    }\r\n\r\n    /**\r\n     * Sets the unwrap.\r\n     * \r\n     * @param unwrap\r\n     *            the new unwrap {@inheritDoc}\r\n     */\r\n    public void setUnwrap(boolean unwrap)\r\n    {\r\n        this.unwrap = unwrap;\r\n    }\r\n\r\n    @Override\r\n    public void setImplementation(Object paramObject)\r\n    {\r\n        this.target = paramObject;\r\n        this.initialized = true;\r\n    }\r\n\r\n    /**\r\n     * @return the persistenceDelegator\r\n     */\r\n    public PersistenceDelegator getPersistenceDelegator()\r\n    {\r\n        return persistenceDelegator;\r\n    }\r\n\r\n    /**\r\n     * @param persistenceDelegator\r\n     *            the persistenceDelegator to set\r\n     */\r\n    public void setPersistenceDelegator(PersistenceDelegator persistenceDelegator)\r\n    {\r\n        this.persistenceDelegator = persistenceDelegator;\r\n    }\r\n\r\n    @Override\r\n    public void unsetPersistenceDelegator()\r\n    {\r\n        this.persistenceDelegator = null;\r\n    }\r\n\r\n    @Override\r\n    public void setOwner(Object owner) throws PersistenceException\r\n    {\r\n        if (owner != null && !owner.getClass().equals(persistentClass))\r\n            this.owner = owner;\r\n    }\r\n\r\n    @Override\r\n    public Object getOwner() throws PersistenceException\r\n    {\r\n        return owner;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/cglib/CglibLazyInitializerFactory.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\n/*\r\n * Copyright 2010 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.proxy.cglib;\r\n\r\nimport java.lang.reflect.Method;\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.Entity;\r\n\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.metadata.model.Relation;\r\nimport com.impetus.kundera.persistence.PersistenceDelegator;\r\nimport com.impetus.kundera.property.PropertyAccessorHelper;\r\nimport com.impetus.kundera.proxy.KunderaProxy;\r\nimport com.impetus.kundera.proxy.LazyInitializerFactory;\r\n\r\n/**\r\n * Implementation of LazyInitializerFactory using cglib library.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class CglibLazyInitializerFactory implements LazyInitializerFactory\r\n{\r\n\r\n    Map<String, KunderaProxy> proxies = new HashMap<String, KunderaProxy>();\r\n\r\n    @Override\r\n    public KunderaProxy getProxy(String entityName, Class<?> persistentClass, Method getIdentifierMethod,\r\n            Method setIdentifierMethod, Object id, PersistenceDelegator pd)\r\n    {\r\n        KunderaProxy kunderaProxy = (KunderaProxy) CglibLazyInitializer.getProxy(entityName, persistentClass,\r\n                new Class[] { KunderaProxy.class }, getIdentifierMethod, setIdentifierMethod, id, pd);\r\n        proxies.put(entityName, kunderaProxy);\r\n\r\n        return kunderaProxy;\r\n    }\r\n\r\n    @Override\r\n    public KunderaProxy getProxy(String entityName)\r\n    {\r\n        return proxies.get(entityName);\r\n    }\r\n\r\n    @Override\r\n    public void clearProxies()\r\n    {\r\n        for (KunderaProxy proxy : proxies.values())\r\n        {\r\n            proxy.getKunderaLazyInitializer().setOwner(null);\r\n            proxy.getKunderaLazyInitializer().setInitialized(false);\r\n        }\r\n        proxies.clear();\r\n    }\r\n\r\n    @Override\r\n    public <E> void setProxyOwners(EntityMetadata entityMetadata, E e)\r\n    {\r\n        if (e != null && e.getClass().getAnnotation(Entity.class) != null && entityMetadata != null)\r\n        {\r\n            for (Relation r : entityMetadata.getRelations())\r\n            {\r\n                if (r != null)\r\n                {\r\n                    Object entityId = PropertyAccessorHelper.getId(e, entityMetadata);\r\n                    if (r.isUnary())\r\n                    {\r\n                        String entityName = entityMetadata.getEntityClazz().getName() + \"_\" + entityId + \"#\"\r\n                                + r.getProperty().getName();\r\n\r\n                        KunderaProxy kunderaProxy = getProxy(entityName);\r\n                        if (kunderaProxy != null)\r\n                        {\r\n                            kunderaProxy.getKunderaLazyInitializer().setOwner(e);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/collection/AbstractProxyBase.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.proxy.collection;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\n\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.proxy.LazyInitializationException;\n\n/**\n * Abstract class containing common methods for all interfaces extending\n * {@link Collection} interface and {@link Map} interface\n * \n * @author amresh.singh\n */\npublic abstract class AbstractProxyBase implements ProxyCollection\n{\n\n    private PersistenceDelegator delegator;\n\n    private Object owner;\n\n    private Map<String, Object> relationsMap;\n\n    private Relation relation;\n\n    protected Object dataCollection;\n\n    public AbstractProxyBase()\n    {\n    }\n\n    /**\n     * @param delegator\n     */\n    public AbstractProxyBase(PersistenceDelegator delegator, Relation relation)\n    {\n        this.delegator = delegator;\n        this.relation = relation;\n    }\n\n    @Override\n    public Object getOwner()\n    {\n        return owner;\n    }\n\n    @Override\n    public void setOwner(Object owner)\n    {\n        this.owner = owner;\n    }\n\n    @Override\n    public PersistenceDelegator getPersistenceDelegator()\n    {\n        return delegator;\n    }\n\n    @Override\n    public Map<String, Object> getRelationsMap()\n    {\n        return relationsMap;\n    }\n\n    @Override\n    public void setRelationsMap(Map<String, Object> relationsMap)\n    {\n        this.relationsMap = relationsMap;\n    }\n\n    @Override\n    public Relation getRelation()\n    {\n        return relation;\n    }\n\n    /**\n * \n */\n    protected void eagerlyLoadDataCollection()\n    {\n        if (getDataCollection() == null || getDataCollection() instanceof ProxyCollection)\n        {\n            EntityMetadata m = KunderaMetadataManager.getEntityMetadata(getPersistenceDelegator().getKunderaMetadata(),\n                    getOwner().getClass());\n\n            if (!getPersistenceDelegator().isOpen())\n            {\n                throw new LazyInitializationException(\n                        \"Unable to load Proxy Collection.\"\n                                + \" This happens when you access a lazily loaded proxy collection in an entity after entity manager has been closed.\");\n            }\n            \n            Map<Object, Object> relationStack = new HashMap<Object, Object>();\n            getPersistenceDelegator().getClient(m).getReader()\n                    .recursivelyFindEntities(getOwner(), relationsMap, m, getPersistenceDelegator(), true,relationStack);\n\n            if (getRelation().getProperty().getType().isAssignableFrom(Map.class))\n            {\n                dataCollection = (Map) PropertyAccessorHelper.getObject(getOwner(), getRelation().getProperty());\n            }\n            else\n            {\n                dataCollection = (Collection) PropertyAccessorHelper.getObject(getOwner(), getRelation().getProperty());\n            }\n\n            if (dataCollection instanceof ProxyCollection)\n            {\n                if (getRelation().getProperty().getType().isAssignableFrom(java.util.Set.class))\n                {\n                    dataCollection = new HashSet();\n                }\n                else if (getRelation().getProperty().getType().isAssignableFrom(java.util.List.class))\n                {\n                    dataCollection = new ArrayList();\n                }\n                else\n                {\n                    dataCollection = null;\n                }\n            }\n            PropertyAccessorHelper.set(getOwner(), getRelation().getProperty(), dataCollection);\n        }\n    }\n\n    // ///////////////////Common collection\n    // implementation////////////////////////////\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/collection/AbstractProxyCollection.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.proxy.collection;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\n\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\n\n/**\n * Abstract class containing common methods for all interfaces extending\n * {@link Collection} interface\n * \n * @author amresh.singh\n */\npublic abstract class AbstractProxyCollection extends AbstractProxyBase\n{\n\n    /**\n     * Default constructor\n     */\n    public AbstractProxyCollection()\n    {\n        super();\n    }\n\n    /**\n     * @param delegator\n     */\n    public AbstractProxyCollection(final PersistenceDelegator delegator, final Relation relation)\n    {\n        super(delegator, relation);\n    }\n\n    @Override\n    public Object getDataCollection()\n    {\n        return dataCollection != null /*&& ! ((Collection) dataCollection).isEmpty() */? dataCollection : null;\n    }\n    \n    protected boolean add(final Object object)\n    {\n        eagerlyLoadDataCollection();\n\n        boolean result = false;\n\n        if (dataCollection == null)\n        {\n            createEmptyDataCollection();\n        }\n\n        if (dataCollection != null && !(dataCollection instanceof ProxyCollection) && ! ((Collection) dataCollection).contains(object)\n                && object != null)\n        {\n            // getPersistenceDelegator().persist(object);\n            ((Collection) dataCollection).add(object);\n            PropertyAccessorHelper.set(getOwner(), getRelation().getProperty(), dataCollection);\n            result = true;\n        }\n        return result;\n    }   \n    \n    protected void clear()\n    {\n        eagerlyLoadDataCollection();\n        if (getDataCollection() != null && !(getDataCollection() instanceof ProxyCollection))\n        {\n            ((Collection)getDataCollection()).clear();\n        }\n    }\n    \n    protected boolean contains(Object arg0)\n    {\n\n        boolean result = false;\n\n        eagerlyLoadDataCollection();\n        if (getDataCollection() != null && !(getDataCollection() instanceof ProxyCollection))\n        {\n            result = ((Collection)getDataCollection()).contains(arg0);\n        }\n        return result;\n    }\n    \n    protected boolean isEmpty()\n    {\n        boolean result = true;\n\n        eagerlyLoadDataCollection();\n        if (getDataCollection() != null && !(getDataCollection() instanceof ProxyCollection))\n        {\n            result = ((Collection)getDataCollection()).isEmpty();\n        }\n        return result;\n    }\n    \n    protected int size()\n    {\n        eagerlyLoadDataCollection();\n        return dataCollection == null || dataCollection instanceof ProxyCollection ? 0 : ((Collection) dataCollection).size();\n    }\n\n    protected boolean addAll(final Collection collection)\n    {\n        eagerlyLoadDataCollection();\n\n        boolean result = false;\n        \n        if (dataCollection == null)\n        {\n            createEmptyDataCollection();\n        }\n\n        if (dataCollection != null && !(dataCollection instanceof ProxyCollection) && collection != null\n                && !collection.isEmpty())\n        {            \n            ((Collection) dataCollection).addAll(collection);\n            result = true;\n        }\n        return result;\n    }\n\n    protected boolean remove(final Object object)\n    {\n        eagerlyLoadDataCollection();\n\n        boolean result = false;\n        \n        if (dataCollection == null)\n        {\n            createEmptyDataCollection();\n        }\n        \n        if (dataCollection != null && !(dataCollection instanceof ProxyCollection) && object != null)\n        {\n            \n            ((Collection) dataCollection).remove(object);            \n            result = true;\n        }\n        return result;\n    }\n\n    protected boolean removeAll(final Collection collection)\n    {\n        eagerlyLoadDataCollection();\n        boolean result = false;\n        \n        if (dataCollection == null)\n        {\n            createEmptyDataCollection();\n        }\n        \n        if (dataCollection != null && !(dataCollection instanceof ProxyCollection) && collection != null\n                && !collection.isEmpty())\n        {\n            ((Collection) dataCollection).removeAll(collection);           \n            result = true;\n        }\n        return result;\n    }\n    \n    protected boolean containsAll(final Collection arg0)\n    {\n        eagerlyLoadDataCollection();\n\n        boolean result = false;\n        \n        if(dataCollection == null)\n        {\n            createEmptyDataCollection();\n        }\n\n        if (getDataCollection() != null && !(dataCollection instanceof ProxyCollection) && arg0 != null && ! arg0.isEmpty())\n        {\n            result = ((Collection)getDataCollection()).containsAll(arg0);\n        }\n        return result;\n    }\n\n    protected boolean retainAll(final Collection collection)\n    {\n        boolean result = false;\n        eagerlyLoadDataCollection();\n\n        if (dataCollection == null)\n        {\n            createEmptyDataCollection();\n        }\n        \n        if (dataCollection != null && !(dataCollection instanceof ProxyCollection) && collection != null\n                && !collection.isEmpty())\n        {\n            result = ((Collection) dataCollection).retainAll(collection);\n        }\n\n        return result;\n    }\n\n    protected Iterator iterator()\n    {\n\n        eagerlyLoadDataCollection();\n        Iterator result = null;\n        if (getDataCollection() != null && !(getDataCollection() instanceof ProxyCollection))\n        {\n            result = ((Collection) getDataCollection()).iterator();\n        }\n        return result;\n    }\n\n    protected Object[] toArray()\n    {\n        eagerlyLoadDataCollection();\n        return dataCollection == null ? new Object[0] : ((Collection) dataCollection).toArray();\n    }\n\n    protected Object[] toArray(final Object[] arg0)\n    {\n        eagerlyLoadDataCollection();\n        return dataCollection == null ? new Object[0] : ((Collection) dataCollection).toArray(arg0);\n    }\n    \n    /**\n     * Creates an a data collection which has no entity inside it\n     */\n    private void createEmptyDataCollection()\n    {\n        Class<?> collectionClass = getRelation().getProperty().getType();\n        if (collectionClass.isAssignableFrom(Set.class))\n        {\n            dataCollection = new HashSet();\n        }\n        else if (collectionClass.isAssignableFrom(List.class))\n        {\n            dataCollection = new ArrayList();\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/collection/ProxyCollection.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.proxy.collection;\n\nimport java.util.Map;\n\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\n\n/**\n * Top level interface for all proxy collections (including maps)\n * \n * @author amresh.singh\n */\npublic interface ProxyCollection\n{\n\n    /**\n     * Returns owning entity that holds this proxy collection\n     */\n    Object getOwner();\n\n    /**\n     * Sets owning entity that holds this collection for later use while eagerly\n     * loading\n     */\n    void setOwner(Object owner);\n\n    /**\n     * Returns instance of {@link PersistenceDelegator} which is required for\n     * eagerly loading associated collection at the time it is requested\n     */\n    PersistenceDelegator getPersistenceDelegator();\n\n    /**\n     * Retrieves {@link Map} of Relation name and values required for eagerly\n     * fetching this proxy collection at the time it is requested\n     */\n    Map<String, Object> getRelationsMap();\n\n    /**\n     * Sets {@link Map} of Relation name and values required for eagerly\n     * fetching this proxy collection at the time it is requested\n     */\n    void setRelationsMap(Map<String, Object> relationsMap);\n\n    /**\n     * Instance of {@link Relation} corresponding to this proxy collection\n     */\n    Relation getRelation();\n\n    /**\n     * Retrieves actual collection data that implementor of this interface\n     * holds. Unless proxy collection is eagerly loaded, this values would\n     * normally be null\n     */\n    Object getDataCollection();\n\n    /**\n     * Retrieves a copy of this proxy collection\n     */\n    ProxyCollection getCopy();\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/collection/ProxyList.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.proxy.collection;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.ListIterator;\n\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\n\n/**\n * Proxy class used to represent instances for {@link List}\n * \n * @author amresh.singh\n */\npublic class ProxyList extends AbstractProxyCollection implements ProxyCollection, List\n{\n\n    /**\n     * Default constructor\n     */\n    public ProxyList()\n    {\n        super();\n    }\n\n    public ProxyList(final PersistenceDelegator delegator, final Relation relation)\n    {\n        super(delegator, relation);\n    }\n\n    @Override\n    public ProxyCollection getCopy()\n    {\n        ProxyCollection proxyCollection = new ProxyList(getPersistenceDelegator(), getRelation());\n        proxyCollection.setRelationsMap(getRelationsMap());\n        return proxyCollection;\n    }\n\n    // ///////////Methods from Collection interface////////////////////////////\n    @Override\n    public boolean contains(final Object arg0)\n    {\n        return super.contains(arg0);\n    }\n\n    @Override\n    public boolean containsAll(final Collection arg0)\n    {\n        return super.containsAll(arg0);\n    }\n\n    @Override\n    public void clear()\n    {\n        super.clear();\n\n    }\n\n    @Override\n    public boolean isEmpty()\n    {\n        return super.isEmpty();\n    }\n\n    @Override\n    public boolean add(final Object arg0)\n    {\n        return super.add(arg0);\n    }\n\n    @Override\n    public boolean addAll(final Collection arg0)\n    {\n        return super.addAll(arg0);\n    }\n\n    @Override\n    public boolean remove(final Object arg0)\n    {\n        return super.remove(arg0);\n    }\n\n    @Override\n    public boolean removeAll(final Collection collection)\n    {\n        return super.removeAll(collection);\n    }\n\n    @Override\n    public boolean retainAll(final Collection collection)\n    {\n        return super.retainAll(collection);\n    }\n\n    @Override\n    public Iterator iterator()\n    {\n        return super.iterator();\n    }\n\n    @Override\n    public Object[] toArray()\n    {\n        return super.toArray();\n    }\n\n    @Override\n    public Object[] toArray(final Object[] arg0)\n    {\n        return super.toArray(arg0);\n    }\n\n    @Override\n    public int size()\n    {\n        return super.size();\n    }\n\n    // ////////////Methods from List interface ///////////////////////\n\n    @Override\n    public void add(final int arg0, final Object arg1)\n    {\n        eagerlyLoadDataCollection();\n\n        List dataList = (List) dataCollection;\n        if(dataList == null)\n        {\n            dataList = new ArrayList();\n        }\n\n        if (arg1 != null && !dataList.contains(arg1))\n        {            \n            dataList.add(arg0, arg1);\n        }\n    }\n\n    @Override\n    public boolean addAll(final int index, final Collection collection)\n    {\n        eagerlyLoadDataCollection();\n\n        boolean result = false;\n\n        List dataList = (List) dataCollection;\n        if(dataList == null)\n        {\n            dataList = new ArrayList();\n        }\n        \n        if (collection != null && !collection.isEmpty())\n        {\n            int position = 0;\n            for (Object o : collection)\n            {\n                if (o != null && !dataList.contains(o))\n                {                    \n                    dataList.add(index + position++, o);\n                }\n            }\n            result = true;\n        }\n        return result;\n    }\n\n    @Override\n    public Object get(final int arg0)\n    {\n        eagerlyLoadDataCollection();\n\n        Object result = null;\n\n        List dataList = (List) dataCollection;\n        if (dataList != null && !dataList.isEmpty())\n        {\n            result = dataList.get(arg0);\n        }\n        return result;\n    }\n\n    @Override\n    public int indexOf(final Object arg0)\n    {\n        eagerlyLoadDataCollection();\n\n        int index = -1;\n        List dataList = (List) dataCollection;\n        if (dataList != null && !dataList.isEmpty())\n        {\n            index = dataList.indexOf(arg0);\n        }\n        return index;\n    }\n\n    @Override\n    public int lastIndexOf(final Object arg0)\n    {\n        eagerlyLoadDataCollection();\n\n        int index = -1;\n\n        List dataList = (List) dataCollection;\n        if (dataList != null && !dataList.isEmpty())\n        {\n            index = dataList.lastIndexOf(arg0);\n        }\n        return index;\n    }\n\n    @Override\n    public ListIterator listIterator()\n    {\n        eagerlyLoadDataCollection();\n\n        ListIterator iterator = null;\n\n        List dataList = (List) dataCollection;\n        if (dataList != null && !dataList.isEmpty())\n        {\n            iterator = dataList.listIterator();\n        }\n        return iterator;\n    }\n\n    @Override\n    public ListIterator listIterator(final int arg0)\n    {\n        eagerlyLoadDataCollection();\n\n        ListIterator iterator = null;\n\n        List dataList = (List) dataCollection;\n        if (dataList != null && !dataList.isEmpty())\n        {\n            iterator = dataList.listIterator(arg0);\n        }\n        return iterator;\n    }\n\n    @Override\n    public Object remove(final int arg0)\n    {\n        eagerlyLoadDataCollection();\n\n        Object result = null;\n\n        List dataList = (List) dataCollection;\n                \n        if (dataList != null && !dataList.isEmpty() && dataList.contains(arg0))\n        {            \n            result = dataList.remove(arg0);\n        }\n        return result;\n    }\n\n    @Override\n    public Object set(final int arg0, final Object arg1)\n    {\n        eagerlyLoadDataCollection();\n        List dataList = (List) dataCollection;\n\n        Object result = null;\n\n        if (dataList != null && !dataList.isEmpty())\n        {\n            if (dataList.get(arg0) == null)\n            {\n                getPersistenceDelegator().persist(arg1);\n                result = dataList.set(arg0, arg1);\n\n            }\n            else\n            {\n                getPersistenceDelegator().merge(arg1);\n                result = dataList.set(arg0, arg1);\n            }\n\n        }\n        return result;\n    }\n\n    @Override\n    public List subList(final int arg0, final int arg1)\n    {\n        eagerlyLoadDataCollection();\n\n        List result = null;\n\n        List dataList = (List) dataCollection;\n        if (dataList != null && !dataList.isEmpty())\n        {\n            result = dataList.subList(arg0, arg1);\n        }\n        return result;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/collection/ProxyMap.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.proxy.collection;\n\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\n\n/**\n * Proxy class used to represent instances for {@link Map}\n * \n * @author amresh.singh\n */\npublic class ProxyMap extends AbstractProxyBase implements ProxyCollection, Map\n{\n\n    /**\n     * Default constructor\n     */\n    public ProxyMap()\n    {\n        super();\n    }\n\n    public ProxyMap(final PersistenceDelegator delegator, final Relation relation)\n    {\n        super(delegator, relation);\n    }\n\n    @Override\n    public ProxyCollection getCopy()\n    {\n        ProxyCollection proxyCollection = new ProxyMap(getPersistenceDelegator(), getRelation());\n        proxyCollection.setRelationsMap(getRelationsMap());\n        return proxyCollection;\n    }\n    \n    @Override\n    public Object getDataCollection()\n    {\n        return dataCollection != null && ! ((Map) dataCollection).isEmpty() ? dataCollection : null;\n    }\n\n    // ///////////////////////Methods from Collection interface ////////////////\n\n    @Override\n    public void clear()\n    {\n        eagerlyLoadDataCollection();\n        if (getDataCollection() != null && !(getDataCollection() instanceof ProxyCollection))\n        {\n            ((Map)getDataCollection()).clear();\n        }\n    }\n\n    @Override\n    public boolean isEmpty()\n    {\n        boolean result = true;\n\n        eagerlyLoadDataCollection();\n        if (getDataCollection() != null && !(getDataCollection() instanceof ProxyCollection))\n        {\n            result = ((Map)getDataCollection()).isEmpty();\n        }\n        return result;\n    }\n\n    @Override\n    public int size()\n    {\n        eagerlyLoadDataCollection();\n        return dataCollection == null || dataCollection instanceof ProxyCollection ? 0 : ((Map) dataCollection).size();\n    }\n\n    // ///////////////////////Methods from Map interface ////////////////\n\n    @Override\n    public boolean containsKey(final Object arg0)\n    {\n        eagerlyLoadDataCollection();\n        final Map dataMap = (Map) dataCollection;\n\n        boolean result = false;\n\n        if (dataMap != null && !(dataMap instanceof ProxyMap) && !dataMap.isEmpty())\n        {\n            result = dataMap.containsKey(arg0);\n        }\n        return result;\n    }\n\n    @Override\n    public boolean containsValue(final Object arg0)\n    {\n        eagerlyLoadDataCollection();\n        final Map dataMap = (Map) dataCollection;\n\n        boolean result = false;\n\n        if (dataMap != null && !dataMap.isEmpty())\n        {\n            result = dataMap.containsValue(arg0);\n        }\n        return result;\n    }\n\n    @Override\n    public Set entrySet()\n    {\n        eagerlyLoadDataCollection();\n        final Map dataMap = (Map) dataCollection;\n\n        Set result = null;\n\n        if (dataMap != null && !dataMap.isEmpty())\n        {\n            result = dataMap.entrySet();\n        }\n        return result;\n    }\n\n    @Override\n    public Object get(final Object arg0)\n    {\n        eagerlyLoadDataCollection();\n        final Map dataMap = (Map) dataCollection;\n\n        Object result = null;\n\n        if (dataMap != null && !dataMap.isEmpty())\n        {\n            result = dataMap.get(arg0);\n        }\n        return result;\n    }\n\n    @Override\n    public Set keySet()\n    {\n        eagerlyLoadDataCollection();\n        final Map dataMap = (Map) dataCollection;\n\n        Set result = null;\n\n        if (dataMap != null && !dataMap.isEmpty())\n        {\n            result = dataMap.keySet();\n        }\n        return result;\n    }\n\n    @Override\n    public Object put(final Object arg0, final Object arg1)\n    {\n        eagerlyLoadDataCollection();\n        Map dataMap = (Map) dataCollection;\n\n        Object result = null;\n\n        if (dataMap != null)\n        {\n            result = dataMap.put(arg0, arg1);\n        }\n        return result;\n    }\n\n    @Override\n    public void putAll(final Map arg0)\n    {\n        eagerlyLoadDataCollection();\n        Map dataMap = (Map) dataCollection;\n\n        if (dataMap != null)\n        {\n            dataMap.putAll(arg0);\n        }\n\n    }\n\n    @Override\n    public Object remove(final Object arg0)\n    {\n        eagerlyLoadDataCollection();\n        Map dataMap = (Map) dataCollection;\n\n        Object result = null;\n\n        if (dataMap != null && !dataMap.isEmpty())\n        {\n            result = dataMap.remove(arg0);\n        }\n        return result;\n    }\n\n    @Override\n    public Collection values()\n    {\n        eagerlyLoadDataCollection();\n        final Map dataMap = (Map) dataCollection;\n\n        Collection result = null;\n\n        if (dataMap != null && !dataMap.isEmpty())\n        {\n            result = dataMap.values();\n        }\n        return result;\n    } \n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/proxy/collection/ProxySet.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.proxy.collection;\n\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.Set;\n\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\n\n/**\n * Proxy class used to represent instances for {@link Set}\n * \n * @author amresh.singh\n */\npublic class ProxySet extends AbstractProxyCollection implements ProxyCollection, Set\n{\n\n    /**\n     * Default constructor\n     */\n    public ProxySet()\n    {\n        super();\n    }\n\n    public ProxySet(final PersistenceDelegator delegator, final Relation relation)\n    {\n        super(delegator, relation);\n    }\n\n    @Override\n    public ProxyCollection getCopy()\n    {\n        ProxyCollection proxyCollection = new ProxySet(getPersistenceDelegator(), getRelation());\n        proxyCollection.setRelationsMap(getRelationsMap());\n        return proxyCollection;\n    }\n\n    // ///////////Methods from Collection interface////////////////////////////\n    @Override\n    public void clear()\n    {\n        super.clear();\n    }\n\n    @Override\n    public boolean contains(final Object arg0)\n    {\n        return super.contains(arg0);\n    }\n\n    @Override\n    public boolean containsAll(final Collection arg0)\n    {\n        return super.containsAll(arg0);\n    }\n\n    @Override\n    public boolean isEmpty()\n    {\n        return super.isEmpty();\n    }\n\n    @Override\n    public int size()\n    {\n        return super.size();\n    }\n\n    @Override\n    public boolean add(final Object object)\n    {\n        return super.add(object);\n    }\n\n    @Override\n    public boolean addAll(final Collection collection)\n    {\n        return super.addAll(collection);\n    }\n\n    @Override\n    public boolean remove(final Object object)\n    {\n        return super.remove(object);\n    }\n\n    @Override\n    public boolean removeAll(final Collection collection)\n    {\n        return super.removeAll(collection);\n    }\n\n    @Override\n    public boolean retainAll(final Collection collection)\n    {\n        return super.retainAll(collection);\n    }\n\n    @Override\n    public Iterator iterator()\n    {\n        return super.iterator();\n    }\n\n    @Override\n    public Object[] toArray()\n    {\n        return super.toArray();\n    }\n\n    @Override\n    public Object[] toArray(final Object[] arg0)\n    {\n        return super.toArray(arg0);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/query/IResultIterator.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.query;\n\nimport java.util.Iterator;\nimport java.util.List;\n\n/**\n * @author vivek.mishra\n * \n * Iterator interface extends {@link Iterator}. Databases(e.g. Cassandra,HBase etc) implementation to implement {@link IResultIterator} \n * for pagination/scrolling support. \n *\n */\npublic interface IResultIterator<E> extends Iterator<E>\n{\n\n    /**\n     * Returns next chunk of records. If no next chunk is available, will return an empty list.\n     * \n     * @param chunkSize   no of records to be fetched.\n     * \n     * @return collection of E entity.\n     */\n    List<E> next(int chunkSize);\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/query/JPQLParseException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\n/**\n * @author amresh\n * \n */\npublic class JPQLParseException extends QueryHandlerException\n{\n\n    /**\n     * \n     */\n    public JPQLParseException()\n    {\n        super();\n    }\n\n    /**\n     * @param paramThrowable\n     */\n    public JPQLParseException(Throwable paramThrowable)\n    {\n        super(paramThrowable);\n    }\n\n    /**\n     * @param errMsg\n     */\n    public JPQLParseException(String errMsg)\n    {\n        super(\n                errMsg\n                        + \". For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\");\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/query/KunderaQuery.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Queue;\nimport java.util.Set;\nimport java.util.StringTokenizer;\n\nimport javax.el.ExpressionFactory;\nimport javax.persistence.Parameter;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.Metamodel;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.commons.lang.builder.HashCodeBuilder;\nimport org.eclipse.persistence.jpa.jpql.parser.DeleteStatement;\nimport org.eclipse.persistence.jpa.jpql.parser.EclipseLinkJPQLGrammar2_4;\nimport org.eclipse.persistence.jpa.jpql.parser.JPQLExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.JPQLGrammar;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectStatement;\nimport org.eclipse.persistence.jpa.jpql.parser.UpdateStatement;\nimport org.eclipse.persistence.jpa.jpql.parser.WhereClause;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * The Class KunderaQuery.\n */\npublic class KunderaQuery {\n    /** The Constant SINGLE_STRING_KEYWORDS. */\n    public static final String[] SINGLE_STRING_KEYWORDS =\n        { \"SELECT\", \"UPDATE\", \"SET\", \"DELETE\", \"UNIQUE\", \"FROM\", \"WHERE\", \"GROUP BY\", \"HAVING\", \"ORDER BY\" };\n\n    /** The Constant INTER_CLAUSE_OPERATORS. */\n    public static final String[] INTER_CLAUSE_OPERATORS = { \"AND\", \"OR\", \"BETWEEN\", \"(\", \")\" };\n\n    /** The Constant INTRA_CLAUSE_OPERATORS. */\n    public static final String[] INTRA_CLAUSE_OPERATORS = { \"=\", \"LIKE\", \"IN\", \">\", \">=\", \"<\", \"<=\", \"<>\", \"NOT IN\" };\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(KunderaQuery.class);\n\n    /** The result. */\n    private String[] result;\n\n    /** The aggregation result. */\n    private String[] aggregationResult;\n\n    /** The from. */\n    private String from;\n\n    /** The filter. */\n    private String filter;\n\n    /** The ordering. */\n    private String ordering;\n\n    /** The entity name. */\n    private String entityName;\n\n    /** The entity alias. */\n    private String entityAlias;\n\n    /** The entity class. */\n    private Class<?> entityClass;\n\n    /** The sort orders. */\n    private List<SortOrdering> sortOrders;\n\n    /** The is aggregate. */\n    private boolean isAggregate;\n\n    /** Persistence Unit(s). */\n    private String persistenceUnit;\n\n    // contains a Queue of alternate FilterClause object and Logical Strings\n    // (AND, OR etc.)\n    /** The filters queue. */\n    private Queue filtersQueue = new LinkedList();\n\n    /** The is delete update. */\n    private boolean isDeleteUpdate;\n\n    /** The update clause queue. */\n    private Queue<UpdateClause> updateClauseQueue = new LinkedList<UpdateClause>();\n\n    /** The typed parameter. */\n    private TypedParameter typedParameter;\n\n    /** The parameters map. */\n    private Map<String, Object> parametersMap = new HashMap<String, Object>();\n\n    /** Bind parameters */\n    private final List<BindParameter> bindParameters = new ArrayList<>();\n\n    /** The is native query. */\n    boolean isNativeQuery;\n\n    /** The jpa query. */\n    private String jpaQuery;\n\n    /** The kundera metadata. */\n    private final KunderaMetadata kunderaMetadata;\n\n    /** The jpql expression. */\n    private JPQLExpression jpqlExpression;\n\n    /** The expression factory. */\n    private ExpressionFactory expressionFactory;\n\n    /** The select statement. */\n    private SelectStatement selectStatement;\n\n    /** The update statement. */\n    private UpdateStatement updateStatement;\n\n    /** The delete statement. */\n    private DeleteStatement deleteStatement;\n\n    /**\n     * Sets the expression factory.\n     * \n     * @param expressionFactory\n     *            the expressionFactory to set\n     */\n    public void setExpressionFactory(ExpressionFactory expressionFactory) {\n        this.expressionFactory = expressionFactory;\n    }\n\n    /**\n     * Gets the jpql expression.\n     * \n     * @return the jpqlExpression\n     */\n    public JPQLExpression getJpqlExpression() {\n        return jpqlExpression;\n    }\n\n    /**\n     * Instantiates a new kundera query.\n     * \n     * @param jpaQuery\n     *            the jpa query\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public KunderaQuery(final String jpaQuery, final KunderaMetadata kunderaMetadata) {\n        this.jpaQuery = jpaQuery;\n        this.kunderaMetadata = kunderaMetadata;\n        initiateJPQLObject(jpaQuery);\n    }\n\n    /**\n     * Initiate jpql object.\n     * \n     * @param jpaQuery\n     *            the jpa query\n     */\n    private void initiateJPQLObject(final String jpaQuery) {\n        JPQLGrammar jpqlGrammar = EclipseLinkJPQLGrammar2_4.instance();\n        this.jpqlExpression = new JPQLExpression(jpaQuery, jpqlGrammar, \"ql_statement\", true);\n        setKunderaQueryTypeObject();\n    }\n\n    /**\n     * Sets the kundera query type object.\n     */\n    private void setKunderaQueryTypeObject() {\n\n        try {\n            if (isSelectStatement()) {\n\n                this.setSelectStatement((SelectStatement) (this.getJpqlExpression().getQueryStatement()));\n\n            } else if (isUpdateStatement()) {\n\n                this.setUpdateStatement((UpdateStatement) (this.getJpqlExpression().getQueryStatement()));\n\n            } else if (isDeleteStatement()) {\n                this.setDeleteStatement((DeleteStatement) (this.getJpqlExpression().getQueryStatement()));\n\n            }\n        } catch (ClassCastException cce) {\n            throw new JPQLParseException(\"Bad query format : \" + cce.getMessage());\n        }\n\n    }\n\n    /**\n     * Gets the select statement.\n     * \n     * @return the selectStatement\n     */\n    public SelectStatement getSelectStatement() {\n        return selectStatement;\n    }\n\n    /**\n     * Sets the select statement.\n     * \n     * @param selectStatement\n     *            the selectStatement to set\n     */\n    public void setSelectStatement(SelectStatement selectStatement) {\n        this.selectStatement = selectStatement;\n    }\n\n    /**\n     * Sets the update statement.\n     * \n     * @param updateStatement\n     *            the updateStatement to set\n     */\n    public void setUpdateStatement(UpdateStatement updateStatement) {\n        this.updateStatement = updateStatement;\n    }\n\n    /**\n     * Gets the update statement.\n     * \n     * @return the updateStatement\n     */\n    public UpdateStatement getUpdateStatement() {\n        return updateStatement;\n    }\n\n    /**\n     * Gets the delete statement.\n     * \n     * @return the deleteStatement\n     */\n    public DeleteStatement getDeleteStatement() {\n        return deleteStatement;\n    }\n\n    /**\n     * Sets the delete statement.\n     * \n     * @param deleteStatement\n     *            the deleteStatement to set\n     */\n    public void setDeleteStatement(DeleteStatement deleteStatement) {\n        this.deleteStatement = deleteStatement;\n    }\n\n    /**\n     * Checks if is select statement.\n     * \n     * @return true, if is select statement\n     */\n    public boolean isSelectStatement() {\n        return this.getJpqlExpression().getQueryStatement().getClass().isAssignableFrom(SelectStatement.class);\n\n    }\n\n    /**\n     * Checks if is delete statement.\n     * \n     * @return true, if is delete statement\n     */\n    public boolean isDeleteStatement() {\n        return this.getJpqlExpression().getQueryStatement().getClass().isAssignableFrom(DeleteStatement.class);\n    }\n\n    /**\n     * Checks if is update statement.\n     * \n     * @return true, if is update statement\n     */\n    public boolean isUpdateStatement() {\n        return this.getJpqlExpression().getQueryStatement().getClass().isAssignableFrom(UpdateStatement.class);\n    }\n\n    /**\n     * Gets the expression factory.\n     * \n     * @return the expressionFactory\n     */\n    public ExpressionFactory getExpressionFactory() {\n        return expressionFactory;\n    }\n\n    /**\n     * Sets the grouping.\n     * \n     * @param groupingClause\n     *            the new grouping\n     */\n    public void setGrouping(String groupingClause) {\n    }\n\n    /**\n     * Sets the result.\n     * \n     * @param result\n     *            the new result\n     */\n    public final void setResult(String[] result) {\n        this.result = result;\n    }\n\n    /**\n     * Sets the aggregation result.\n     * \n     * @param aggResult\n     *            the new result\n     */\n    public final void setAggregationResult(String[] aggResult) {\n        this.aggregationResult = aggResult;\n    }\n\n    /**\n     * Gets the agg result.\n     * \n     * @return Aggregation result set\n     */\n    public final String[] getAggResult() {\n        return aggregationResult;\n    }\n\n    /**\n     * Checks if is aggregated.\n     * \n     * @return Query contains aggregation or not\n     */\n    public boolean isAggregated() {\n        return isAggregate;\n    }\n\n    /**\n     * Sets the aggregated.\n     * \n     * @param isAggregated\n     *            the new aggregated\n     */\n    public void setAggregated(boolean isAggregated) {\n        this.isAggregate = isAggregated;\n    }\n\n    /**\n     * Sets the from.\n     * \n     * @param from\n     *            the new from\n     */\n    public final void setFrom(String from) {\n        this.from = from;\n    }\n\n    /**\n     * Sets the filter.\n     * \n     * @param filter\n     *            the new filter\n     */\n    public final void setFilter(String filter) {\n        this.filter = filter;\n    }\n\n    /**\n     * Sets the ordering.\n     * \n     * @param ordering\n     *            the new ordering\n     */\n    public final void setOrdering(String ordering) {\n        this.ordering = ordering;\n        parseOrdering(this.ordering);\n    }\n\n    /**\n     * Gets the filter.\n     * \n     * @return the filter\n     */\n    public final String getFilter() {\n        return filter;\n    }\n\n    /**\n     * Gets the from.\n     * \n     * @return the from\n     */\n    public final String getFrom() {\n        return from;\n    }\n\n    /**\n     * Gets the ordering.\n     * \n     * @return the ordering\n     */\n    public final List<SortOrdering> getOrdering() {\n        return sortOrders;\n    }\n\n    /**\n     * Gets the result.\n     * \n     * @return the result\n     */\n    public final String[] getResult() {\n        return result;\n    }\n\n    /**\n     * Gets the parameters map.\n     * \n     * @return Map of query parameters.\n     */\n    public Map<String, Object> getParametersMap() {\n        return parametersMap;\n    }\n\n    /**\n     * Gets the bind parameters map.\n     * \n     * @return Map of query parameters.\n     */\n    public List<BindParameter> getBindParameters() {\n        return bindParameters;\n    }\n\n    /**\n     * Method to check if required result is to get complete entity or a select scalar value.\n     * \n     * @return true, if it result is for complete alias.\n     * \n     */\n    public final boolean isAliasOnly() {\n        // TODO\n        return result != null && (result[0].indexOf(\".\") == -1);\n    }\n\n    /**\n     * Returns set of parameters.\n     * \n     * @return jpaParameters\n     */\n    public Set<Parameter<?>> getParameters() {\n        return typedParameter != null ? typedParameter.jpaParameters : null;\n    }\n\n    /**\n     * Parameter is bound if it holds any value, else will return false.\n     * \n     * @param param\n     *            the param\n     * @return true, if is bound\n     */\n    public boolean isBound(Parameter param) {\n        return getClauseValue(param) != null;\n    }\n\n    /**\n     * Returns clause value for supplied parameter.\n     * \n     * @param paramString\n     *            the param string\n     * @return the clause value\n     */\n    public List<Object> getClauseValue(String paramString) {\n        if (typedParameter != null && typedParameter.getParameters() != null) {\n            List<FilterClause> clauses = typedParameter.getParameters().get(paramString);\n            if (clauses != null) {\n                return clauses.get(0).getValue();\n            } else {\n                throw new IllegalArgumentException(\"parameter is not a parameter of the query\");\n            }\n        }\n\n        logger.error(\"Parameter {} is not a parameter of the query.\", paramString);\n        throw new IllegalArgumentException(\"Parameter is not a parameter of the query.\");\n    }\n\n    /**\n     * Returns specific clause value.\n     * \n     * @param param\n     *            parameter\n     * \n     * @return clause value.\n     */\n    public List<Object> getClauseValue(Parameter param) {\n        Parameter match = null;\n        if (typedParameter != null && typedParameter.jpaParameters != null) {\n            for (Parameter p : typedParameter.jpaParameters) {\n                if (p.equals(param)) {\n                    match = p;\n                    if (typedParameter.getType().equals(Type.NAMED)) {\n                        List<FilterClause> clauses = typedParameter.getParameters().get(\":\" + p.getName());\n                        if (clauses != null) {\n                            return clauses.get(0).getValue();\n                        }\n                    } else {\n                        List<FilterClause> clauses = typedParameter.getParameters().get(\"?\" + p.getPosition());\n                        if (clauses != null) {\n                            return clauses.get(0).getValue();\n                        } else {\n                            UpdateClause updateClause = typedParameter.getUpdateParameters().get(\"?\" + p.getPosition());\n                            if (updateClause != null) {\n                                List<Object> value = new ArrayList<Object>();\n                                value.add(updateClause.getValue());\n                                return value;\n                            }\n\n                        }\n                    }\n                    break;\n                }\n            }\n            if (match == null) {\n                throw new IllegalArgumentException(\"parameter is not a parameter of the query\");\n            }\n        }\n\n        logger.error(\"parameter{} is not a parameter of the query\", param);\n        throw new IllegalArgumentException(\"parameter is not a parameter of the query\");\n    }\n\n    // must be executed after parse(). it verifies and populated the query\n    // predicates.\n    /**\n     * Post parsing init.\n     */\n    protected void postParsingInit() {\n        initEntityClass();\n        initFilter();\n        initUpdateClause();\n    }\n\n    /**\n     * Inits the update clause.\n     */\n    private void initUpdateClause() {\n        for (UpdateClause updateClause : updateClauseQueue) {\n\n            onTypedParameter(updateClause.getValue(), updateClause, updateClause.getProperty().trim());\n        }\n\n    }\n\n    /**\n     * Inits the entity class.\n     */\n    private void initEntityClass() {\n        if (from == null) {\n            throw new JPQLParseException(\"Bad query format FROM clause is mandatory for SELECT queries\");\n        }\n        String fromArray[] = from.split(\" \");\n\n        if (!this.isDeleteUpdate) {\n            if (fromArray.length == 3 && fromArray[1].equalsIgnoreCase(\"as\")) {\n                fromArray = new String[] { fromArray[0], fromArray[2] };\n            }\n\n            if (fromArray.length != 2) {\n                throw new JPQLParseException(\"Bad query format: \" + from\n                    + \". Identification variable is mandatory in FROM clause for SELECT queries\");\n            }\n\n            // TODO\n            StringTokenizer tokenizer = new StringTokenizer(result[0], \",\");\n            while (tokenizer.hasMoreTokens()) {\n                String token = tokenizer.nextToken();\n                if (!StringUtils.containsAny(fromArray[1] + \".\", token)) {\n                    throw new QueryHandlerException(\"bad query format with invalid alias:\" + token);\n                }\n            }\n        }\n\n        this.entityName = fromArray[0];\n        if (fromArray.length == 2)\n            this.entityAlias = fromArray[1];\n\n        persistenceUnit = kunderaMetadata.getApplicationMetadata().getMappedPersistenceUnit(entityName);\n\n        // Get specific metamodel.\n        MetamodelImpl model = getMetamodel(persistenceUnit);\n\n        if (model != null) {\n            entityClass = model.getEntityClass(entityName);\n        }\n\n        if (null == entityClass) {\n            logger.error(\n                \"No entity {} found, please verify it is properly annotated with @Entity and not a mapped Super class\",\n                entityName);\n            throw new QueryHandlerException(\"No entity found by the name: \" + entityName);\n        }\n\n        EntityMetadata metadata = model.getEntityMetadata(entityClass);\n\n        if (metadata != null && !metadata.isIndexable()) {\n            throw new QueryHandlerException(entityClass + \" is not indexed. Not possible to run a query on it.\"\n                + \" Check whether it was properly annotated for indexing.\");\n        }\n    }\n\n    /**\n     * Inits the filter.\n     */\n    private void initFilter() {\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(getPersistenceUnit());\n        EntityType entityType = metaModel.entity(entityClass);\n\n        if (null == filter) {\n            List<String> clauses = new ArrayList<String>();\n            addDiscriminatorClause(clauses, entityType);\n            return;\n        }\n        WhereClause whereClause = KunderaQueryUtils.getWhereClause(getJpqlExpression());\n\n        KunderaQueryUtils.traverse(whereClause.getConditionalExpression(), metadata, kunderaMetadata, this, false);\n\n        for (Object filterClause : filtersQueue) {\n\n            if (!(filterClause instanceof String)) {\n                onTypedParameter(((FilterClause) filterClause));\n            }\n\n        }\n\n        addDiscriminatorClause(null, entityType);\n    }\n\n    /**\n     * Adds the discriminator clause.\n     * \n     * @param clauses\n     *            the clauses\n     * @param entityType\n     *            the entity type\n     */\n    private void addDiscriminatorClause(List<String> clauses, EntityType entityType) {\n        if (((AbstractManagedType) entityType).isInherited()) {\n            String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n            String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();\n\n            if (discrColumn != null && discrValue != null) {\n                if (clauses != null && !clauses.isEmpty()) {\n                    filtersQueue.add(\"AND\");\n                }\n\n                FilterClause filterClause = new FilterClause(discrColumn, \"=\", discrValue, discrColumn);\n                filtersQueue.add(filterClause);\n            }\n        }\n    }\n\n    /**\n     * Depending upon filter value, if it starts with \":\" then it is NAMED parameter, else if starts with \"?\", it will\n     * be INDEXED parameter.\n     * \n     * @param value\n     *            the value\n     * @param updateClause\n     *            the update clause\n     * @param fieldName\n     *            the field name\n     */\n    private void onTypedParameter(Object value, UpdateClause updateClause, String fieldName) {\n        String token = value.toString();\n        if (token != null && token.startsWith(\":\")) {\n            addTypedParameter(Type.NAMED, token, updateClause);\n            filterJPAParameterInfo(Type.NAMED, token.substring(1), fieldName);\n        } else if (token != null && token.startsWith(\"?\")) {\n            addTypedParameter(Type.INDEXED, token, updateClause);\n            filterJPAParameterInfo(Type.INDEXED, token.substring(1), fieldName);\n        }\n    }\n\n    /**\n     * Depending upon filter value, if it starts with \":\" then it is NAMED parameter, else if starts with \"?\", it will\n     * be INDEXED parameter.\n     * \n     * @param filterClause\n     *            filter clauses.\n     */\n    private void onTypedParameter(FilterClause filterClause) {\n\n        if (filterClause.value != null && filterClause.value.get(0) == null) {\n            return;\n        }\n\n        if (filterClause.value != null && filterClause.value.get(0).toString().startsWith(\":\")) {\n            addTypedParameter(Type.NAMED, filterClause.value.get(0).toString(), filterClause);\n            filterJPAParameterInfo(Type.NAMED, filterClause.value.get(0).toString().substring(1),\n                filterClause.fieldName);\n        } else if (filterClause.value.toString() != null && filterClause.value.get(0).toString().startsWith(\"?\")) {\n            addTypedParameter(Type.INDEXED, filterClause.value.get(0).toString(), filterClause);\n            filterJPAParameterInfo(Type.INDEXED, filterClause.value.get(0).toString().substring(1),\n                filterClause.fieldName);\n        }\n    }\n\n    /**\n     * Adds typed parameter to {@link TypedParameter}.\n     * \n     * @param type\n     *            type of parameter(e.g. NAMED/INDEXED)\n     * @param parameter\n     *            parameter name.\n     * @param clause\n     *            filter clause.\n     */\n    private void addTypedParameter(Type type, String parameter, FilterClause clause) {\n        if (typedParameter == null) {\n            typedParameter = new TypedParameter(type);\n        }\n\n        if (typedParameter.getType().equals(type)) {\n            typedParameter.addParameters(parameter, clause);\n        } else {\n            logger.warn(\"Invalid type provided, it can either be name or indexes!\");\n        }\n    }\n\n    /**\n     * Adds typed parameter to {@link TypedParameter}.\n     * \n     * @param type\n     *            type of parameter(e.g. NAMED/INDEXED)\n     * @param parameter\n     *            parameter name.\n     * @param clause\n     *            filter clause.\n     */\n    private void addTypedParameter(Type type, String parameter, UpdateClause clause) {\n        if (type != null) {\n            if (typedParameter == null) {\n                typedParameter = new TypedParameter(type);\n            }\n\n            if (typedParameter.getType().equals(type)) {\n                typedParameter.addParameters(parameter, clause);\n            } else {\n                logger.warn(\"Invalid type provided, it can either be name or indexes!\");\n            }\n        }\n    }\n\n    /**\n     * Filter jpa parameter info.\n     * \n     * @param type\n     *            the type\n     * @param name\n     *            the name\n     * @param fieldName\n     *            the field name\n     */\n    private void filterJPAParameterInfo(Type type, String name, String fieldName) {\n        String attributeName = getAttributeName(fieldName);\n        Attribute entityAttribute =\n            ((MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(persistenceUnit))\n                .getEntityAttribute(entityClass, attributeName);\n        Class fieldType = entityAttribute.getJavaType();\n\n        if (type.equals(Type.INDEXED)) {\n            typedParameter.addJPAParameter(new JPAParameter(null, Integer.valueOf(name), fieldType));\n        } else {\n            typedParameter.addJPAParameter(new JPAParameter(name, null, fieldType));\n        }\n    }\n\n    /**\n     * Gets the attribute name.\n     * \n     * @param fieldName\n     *            the field name\n     * @return the attribute name\n     */\n    private String getAttributeName(String fieldName) {\n        String attributeName = fieldName;\n        if (fieldName.indexOf(\".\") != -1) {\n            attributeName = fieldName.substring(0, fieldName.indexOf(\".\"));\n        }\n        return attributeName;\n    }\n\n    /**\n     * Sets the parameter.\n     * \n     * @param name\n     *            the name\n     * @param value\n     *            the value\n     */\n\n    public final void setParameter(String name, Object value) {\n        if (isNative()) {\n            bindParameters.add(new BindParameter(name, value));\n        } else {\n            setParameterValue(\":\" + name, value);\n        }\n\n        parametersMap.put(\":\" + name, value);\n    }\n\n    /**\n     * Sets the parameter.\n     * \n     * @param position\n     *            the position\n     * @param value\n     *            the value\n     */\n    public final void setParameter(int position, Object value) {\n        if (isNative()) {\n            bindParameters.add(new BindParameter(position, value));\n        } else {\n            setParameterValue(\"?\" + position, value);\n        }\n\n        parametersMap.put(\"?\" + position, value);\n    }\n\n    /**\n     * Sets parameter value into filterClause, depending upon {@link Type}.\n     * \n     * @param name\n     *            parameter name.\n     * @param value\n     *            parameter value.\n     */\n    private void setParameterValue(String name, Object value) {\n        if (typedParameter != null) {\n            List<FilterClause> clauses =\n                typedParameter.getParameters() != null ? typedParameter.getParameters().get(name) : null;\n            if (clauses != null) {\n                for (FilterClause clause : clauses) {\n                    clause.setValue(value);\n                }\n            } else {\n                if (typedParameter.getUpdateParameters() != null) {\n                    UpdateClause updateClause = typedParameter.getUpdateParameters().get(name);\n                    updateClause.setValue(value);\n                } else {\n                    logger.error(\"Error while setting parameter.\");\n                    throw new QueryHandlerException(\"named parameter : \" + name + \" not found!\");\n                }\n            }\n        } else {\n            throw new QueryHandlerException(\"No named parameter present for query\");\n        }\n    }\n\n    /**\n     * Gets the entity class.\n     * \n     * @return the entityClass\n     */\n    public final Class getEntityClass() {\n        return entityClass;\n    }\n\n    /**\n     * Gets the entity alias.\n     * \n     * @return the entity alias\n     */\n    public final String getEntityAlias() {\n        return this.entityAlias;\n    }\n\n    /**\n     * Checks if is native.\n     * \n     * @return true, if is native\n     */\n    public boolean isNative() {\n        return isNativeQuery;\n    }\n\n    /**\n     * Gets the entity metadata.\n     * \n     * @return the entity metadata\n     */\n    public final EntityMetadata getEntityMetadata() {\n        EntityMetadata metadata = null;\n        try {\n            metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        } catch (KunderaException e) {\n            logger.info(\"No Entity class provided, Proceeding as Scalar Query\");\n        }\n        if (!this.isNativeQuery && metadata == null) {\n            throw new KunderaException(\"Unable to load entity metadata for : \" + entityClass);\n        }\n        return metadata;\n    }\n\n    /**\n     * Gets the filter clause queue.\n     * \n     * @return the filters\n     */\n    public final Queue getFilterClauseQueue() {\n        return filtersQueue;\n    }\n\n    /**\n     * The FilterClause class to hold a where clause predicate.\n     */\n    public final class FilterClause {\n\n        /** The property. */\n        private String property;\n\n        /** The condition. */\n        private String condition;\n\n        /** The condition. */\n        private String fieldName;\n\n        /**\n         * Gets the field name.\n         * \n         * @return the fieldName\n         */\n        public String getFieldName() {\n            return fieldName;\n        }\n\n        /** The value. */\n        private List<Object> value = new ArrayList<Object>();\n\n        /** Whether to ignore case while evaluating the condition */\n        private boolean ignoreCase;\n\n        /**\n         * The Constructor.\n         * \n         * @param property\n         *            the property\n         * @param condition\n         *            the condition\n         * @param value\n         *            the value\n         * @param fieldName\n         *            the field name\n         */\n        public FilterClause(String property, String condition, Object value, String fieldName) {\n            super();\n            this.property = property;\n            this.condition = condition.trim();\n            this.fieldName = fieldName;\n            if (value instanceof Collection) {\n                for (Object valueObject : (Collection) value) {\n                    this.value.add(KunderaQuery.getValue(valueObject));\n                }\n            } else {\n                this.value.add(KunderaQuery.getValue(value));\n            }\n        }\n\n        /**\n         * Gets the property.\n         * \n         * @return the property\n         */\n        public final String getProperty() {\n            return property;\n        }\n\n        /**\n         * Gets the condition.\n         * \n         * @return the condition\n         */\n        public final String getCondition() {\n            return condition;\n        }\n\n        /**\n         * Gets the value.\n         * \n         * @return the value\n         */\n        public final List<Object> getValue() {\n            return value;\n        }\n\n        /**\n         * Sets the value.\n         * \n         * @param value\n         *            the value to set\n         */\n        protected void setValue(Object value) {\n            List<Object> valObjects = new ArrayList<Object>();\n            if (value instanceof Collection) {\n                for (Object valueObject : (Collection) value) {\n                    valObjects.add(KunderaQuery.getValue(valueObject));\n                }\n            } else {\n                valObjects.add(KunderaQuery.getValue(value));\n            }\n\n            this.value = valObjects;\n        }\n\n        /**\n         * Returns whether to ignore the case when evaluating the filter clause.\n         *\n         * @return whether to ignore the case when evaluating the filter clause\n         */\n        public boolean isIgnoreCase() {\n            return ignoreCase;\n        }\n\n        /**\n         * Sets whether to ignore the case when evaluating the filter clause.\n         *\n         * @param ignoreCase\n         *            true to ignore the case when evaluating the filter clause\n         */\n        public void setIgnoreCase(final boolean ignoreCase) {\n            this.ignoreCase = ignoreCase;\n        }\n\n        /* @see java.lang.Object#toString() */\n        /*\n         * (non-Javadoc)\n         * \n         * @see java.lang.Object#toString()\n         */\n        @Override\n        public String toString() {\n            StringBuilder builder = new StringBuilder();\n            builder.append(\"FilterClause [property=\");\n            builder.append(property);\n            builder.append(\", condition=\");\n            builder.append(condition);\n            builder.append(\", value=\");\n            builder.append(value);\n            builder.append(\", fieldName=\");\n            builder.append(fieldName);\n            builder.append(\"]\");\n            return builder.toString();\n        }\n    }\n\n    /**\n     * The Class UpdateClause.\n     */\n    public final class UpdateClause {\n\n        /** The property. */\n        private String property;\n\n        /** The value. */\n        private Object value;\n\n        /**\n         * Instantiates a new update clause.\n         * \n         * @param property\n         *            the property\n         * @param value\n         *            the value\n         */\n        public UpdateClause(final String property, final Object value) {\n            this.property = property;\n            this.value = KunderaQuery.getValue(value);\n        }\n\n        /**\n         * Gets the property.\n         * \n         * @return the property\n         */\n        public String getProperty() {\n            return property;\n        }\n\n        /**\n         * Gets the value.\n         * \n         * @return the value\n         */\n        public Object getValue() {\n            return value;\n        }\n\n        /**\n         * Sets the value.\n         * \n         * @param value\n         *            the value to set\n         */\n        public void setValue(Object value) {\n            this.value = KunderaQuery.getValue(value);\n        }\n\n    }\n\n    /* @see java.lang.Object#clone() */\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.lang.Object#clone()\n     */\n    @Override\n    public final Object clone() throws CloneNotSupportedException {\n        return super.clone();\n    }\n\n    /* @see java.lang.Object#toString() */\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.lang.Object#toString()\n     */\n    @Override\n    public final String toString() {\n        StringBuilder builder = new StringBuilder();\n        builder.append(\"KunderaQuery [entityName=\");\n        builder.append(entityName);\n        builder.append(\", entityAlias=\");\n        builder.append(entityAlias);\n        builder.append(\", filtersQueue=\");\n        builder.append(filtersQueue);\n        builder.append(\"]\");\n        return builder.toString();\n    }\n\n    /**\n     * Gets the metamodel.\n     * \n     * @param pu\n     *            the pu\n     * @return the metamodel\n     */\n    private MetamodelImpl getMetamodel(String pu) {\n        return KunderaMetadataManager.getMetamodel(kunderaMetadata, pu);\n    }\n\n    /**\n     * Gets the persistence units.\n     * \n     * @return the persistenceUnits\n     */\n    public String getPersistenceUnit() {\n        return persistenceUnit;\n    }\n\n    /**\n     * Sets the persistence unit.\n     * \n     * @param persistenceUnit\n     *            the new persistence unit\n     */\n    public void setPersistenceUnit(String persistenceUnit) {\n        this.persistenceUnit = persistenceUnit;\n    }\n\n    /**\n     * Parses the ordering @See Order By Clause.\n     * \n     * @param ordering\n     *            the ordering\n     */\n    private void parseOrdering(String ordering) {\n        final String comma = \",\";\n        final String space = \" \";\n\n        StringTokenizer tokenizer = new StringTokenizer(ordering, comma);\n\n        sortOrders = new ArrayList<KunderaQuery.SortOrdering>();\n        while (tokenizer.hasMoreTokens()) {\n            String order = (String) tokenizer.nextElement();\n            StringTokenizer token = new StringTokenizer(order, space);\n            SortOrder orderType = SortOrder.ASC;\n\n            String colName = (String) token.nextElement();\n            while (token.hasMoreElements()) {\n                String nextOrder = (String) token.nextElement();\n\n                // more spaces given.\n                if (StringUtils.isNotBlank(nextOrder)) {\n                    try {\n                        orderType = SortOrder.valueOf(nextOrder.toUpperCase());\n                    } catch (IllegalArgumentException e) {\n                        logger.error(\"Error while parsing order by clause:\");\n                        throw new JPQLParseException(\"Invalid sort order provided:\" + nextOrder);\n                    }\n                }\n            }\n            sortOrders.add(new SortOrdering(colName, orderType));\n        }\n    }\n\n    /**\n     * Containing SortOrder.\n     */\n    public class SortOrdering {\n\n        /** The column name. */\n        String columnName;\n\n        /** The order. */\n        SortOrder order;\n\n        /**\n         * Instantiates a new sort ordering.\n         * \n         * @param columnName\n         *            the column name\n         * @param order\n         *            the order\n         */\n        public SortOrdering(String columnName, SortOrder order) {\n            this.columnName = columnName;\n            this.order = order;\n        }\n\n        /**\n         * Gets the column name.\n         * \n         * @return the column name\n         */\n        public String getColumnName() {\n            return columnName;\n        }\n\n        /**\n         * Gets the order.\n         * \n         * @return the order\n         */\n        public SortOrder getOrder() {\n            return order;\n        }\n    }\n\n    /**\n     * The Enum SortOrder.\n     */\n    public enum SortOrder {\n                           /** The ASC. */\n                           ASC,\n                           /** The DESC. */\n                           DESC;\n    }\n\n    /**\n     * Gets the update clause queue.\n     * \n     * @return the updateClauseQueue\n     */\n    public Queue<UpdateClause> getUpdateClauseQueue() {\n        return updateClauseQueue;\n    }\n\n    /**\n     * Checks if is update clause.\n     * \n     * @return true, if is update clause\n     */\n    public boolean isUpdateClause() {\n        return !updateClauseQueue.isEmpty();\n    }\n\n    /**\n     * Adds the update clause.\n     * \n     * @param property\n     *            the property\n     * @param value\n     *            the value\n     */\n    public void addUpdateClause(final String property, final String value) {\n        UpdateClause updateClause = new UpdateClause(property.trim(), value.trim());\n        updateClauseQueue.add(updateClause);\n        addTypedParameter(\n            value.trim().startsWith(\"?\") ? Type.INDEXED : value.trim().startsWith(\":\") ? Type.NAMED : null, property,\n            updateClause);\n    }\n\n    /**\n     * Adds the filter clause.\n     * \n     * @param property\n     *            the property\n     * @param condition\n     *            the condition\n     * @param value\n     *            the value\n     * @param fieldName\n     *            the field name\n     * @param ignoreCase\n     *            to ignore case in the filter\n     */\n    public void addFilterClause(final String property, final String condition, final Object value,\n        final String fieldName, final boolean ignoreCase) {\n        if (property != null && condition != null) {\n            FilterClause filterClause = new FilterClause(property.trim(), condition.trim(), value, fieldName);\n            filterClause.setIgnoreCase(ignoreCase);\n            filtersQueue.add(filterClause);\n        } else {\n            filtersQueue.add(property);\n        }\n    }\n\n    /**\n     * Adds the filter clause.\n     * \n     * @param filterClause\n     *            the filter clause\n     */\n    public void addFilterClause(Object filterClause) {\n\n        filtersQueue.add(filterClause);\n\n    }\n\n    /**\n     * Sets the checks if is delete update.\n     * \n     * @param b\n     *            the new checks if is delete update\n     */\n    public void setIsDeleteUpdate(boolean b) {\n        this.isDeleteUpdate = b;\n    }\n\n    /**\n     * Checks if is delete update.\n     * \n     * @return true, if is delete update\n     */\n    public boolean isDeleteUpdate() {\n        return isDeleteUpdate;\n    }\n\n    /**\n     * Gets the JPA query.\n     * \n     * @return the JPA query\n     */\n    public String getJPAQuery() {\n        return this.jpaQuery;\n    }\n\n    /**\n     * The Class TypedParameter.\n     */\n    private class TypedParameter {\n\n        /** The type. */\n        private Type type;\n\n        /** The jpa parameters. */\n        private Set<Parameter<?>> jpaParameters = new HashSet<Parameter<?>>();\n\n        /** The parameters. */\n        private Map<String, List<FilterClause>> parameters;\n\n        /** The update parameters. */\n        private Map<String, UpdateClause> updateParameters;\n\n        /**\n         * Instantiates a new typed parameter.\n         * \n         * @param type\n         *            the type\n         */\n        public TypedParameter(Type type) {\n            this.type = type;\n        }\n\n        /**\n         * Gets the type.\n         * \n         * @return the type\n         */\n        private Type getType() {\n            return type;\n        }\n\n        /**\n         * Gets the parameters.\n         * \n         * @return the parameters\n         */\n        Map<String, List<FilterClause>> getParameters() {\n            return parameters;\n        }\n\n        /**\n         * Gets the update parameters.\n         * \n         * @return the parameters\n         */\n        Map<String, UpdateClause> getUpdateParameters() {\n            return updateParameters;\n        }\n\n        /**\n         * Adds the parameters.\n         * \n         * @param key\n         *            the key\n         * @param clause\n         *            the clause\n         */\n        void addParameters(String key, FilterClause clause) {\n            if (parameters == null) {\n                parameters = new HashMap<String, List<FilterClause>>();\n            }\n            if (!parameters.containsKey(key)) {\n                parameters.put(key, new ArrayList<KunderaQuery.FilterClause>());\n            }\n            parameters.get(key).add(clause);\n        }\n\n        /**\n         * Adds the parameters.\n         * \n         * @param key\n         *            the key\n         * @param clause\n         *            the clause\n         */\n        void addParameters(String key, UpdateClause clause) {\n            if (updateParameters == null) {\n                updateParameters = new HashMap<String, UpdateClause>();\n            }\n\n            updateParameters.put(key, clause);\n        }\n\n        /**\n         * Adds the jpa parameter.\n         * \n         * @param param\n         *            the param\n         */\n        void addJPAParameter(Parameter param) {\n            jpaParameters.add(param);\n        }\n    }\n\n    /**\n     * The Enum Type.\n     */\n    private enum Type {\n\n                       /** The indexed. */\n                       INDEXED,\n                       /** The named. */\n                       NAMED\n    }\n\n    /*\n     * JPA Parameter type\n     */\n    /**\n     * The Class JPAParameter.\n     * \n     * @param <T>\n     *            the generic type\n     */\n    private class JPAParameter<T> implements Parameter<T> {\n\n        /** The name. */\n        private String name;\n\n        /** The position. */\n        private Integer position;\n\n        /** The type. */\n        private Class<T> type;\n\n        /**\n         * Instantiates a new JPA parameter.\n         * \n         * @param name\n         *            the name\n         * @param position\n         *            the position\n         * @param type\n         *            the type\n         */\n        JPAParameter(String name, Integer position, Class<T> type) {\n            this.name = name;\n            this.position = position;\n            this.type = type;\n        }\n\n        /*\n         * (non-Javadoc)\n         * \n         * @see javax.persistence.Parameter#getName()\n         */\n        @Override\n        public String getName() {\n            return name;\n        }\n\n        /*\n         * (non-Javadoc)\n         * \n         * @see javax.persistence.Parameter#getPosition()\n         */\n        @Override\n        public Integer getPosition() {\n            return position;\n        }\n\n        /*\n         * (non-Javadoc)\n         * \n         * @see javax.persistence.Parameter#getParameterType()\n         */\n        @Override\n        public Class<T> getParameterType() {\n            return type;\n        }\n\n        /*\n         * (non-Javadoc)\n         * \n         * @see java.lang.Object#hashCode()\n         */\n        @Override\n        public int hashCode() {\n            return HashCodeBuilder.reflectionHashCode(this);\n        }\n\n        /*\n         * (non-Javadoc)\n         * \n         * @see java.lang.Object#equals(java.lang.Object)\n         */\n        @Override\n        public boolean equals(Object obj) {\n            if (obj == null) {\n                return false;\n            }\n            if (!obj.getClass().equals(this.getClass())) {\n                return false;\n            }\n\n            Parameter<?> typed = (Parameter<?>) obj;\n\n            if (typed.getParameterType().equals(this.getParameterType())) {\n                if (this.getName() == null && typed.getName() == null) {\n                    return this.getPosition() != null && this.getPosition().equals(typed.getPosition());\n                } else {\n                    return this.getName() != null && this.getName().equals(typed.getName());\n                }\n\n            }\n\n            return false;\n        }\n\n        /*\n         * (non-Javadoc)\n         * \n         * @see java.lang.Object#toString()\n         */\n        @Override\n        public String toString() {\n            StringBuilder strBuilder = new StringBuilder();\n            strBuilder.append(\"[ name = \" + this.getName() + \"]\");\n            strBuilder.append(\"[ position = \" + this.getPosition() + \"]\");\n            strBuilder.append(\"[ type = \" + this.getParameterType() + \"]\");\n            return strBuilder.toString();\n        }\n    }\n\n    /**\n     * Method to skip string literal as per JPA specification. if literal starts is enclose within \"''\" then skip \"'\"\n     * and include \"'\" in case of \"''\" replace it with \"'\".\n     * \n     * @param value\n     *            value.\n     * \n     * @return replaced string in case of string, else will return original value.\n     */\n    private static Object getValue(Object value) {\n        if (value != null && value.getClass().isAssignableFrom(String.class)) {\n            return ((String) value).replaceAll(\"^'\", \"\").replaceAll(\"'$\", \"\").replaceAll(\"''\", \"'\");\n        }\n\n        return value;\n    }\n\n    /*\n     * XXX Indexed or named bind parameter for queries\n     */\n\n    public static class BindParameter implements java.io.Serializable {\n\n        private final String name;\n        private final int index;\n        private final Object value;\n\n        public BindParameter(final String name, final Object value) {\n            this.name = name;\n            this.index = -1;\n            this.value = value;\n        }\n\n        public BindParameter(final int index, final Object value) {\n            this.name = null;\n            this.index = index;\n            this.value = value;\n        }\n\n        public String getName() {\n            return name;\n        }\n\n        public boolean isNamed() {\n            return (getName() != null);\n        }\n\n        public int getIndex() {\n            return index;\n        }\n\n        public Object getValue() {\n            return value;\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/query/KunderaQueryParser.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport java.util.ListIterator;\nimport java.util.StringTokenizer;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.eclipse.persistence.jpa.jpql.parser.AggregateFunction;\nimport org.eclipse.persistence.jpa.jpql.parser.CollectionExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.FromClause;\nimport org.eclipse.persistence.jpa.jpql.parser.GroupByClause;\nimport org.eclipse.persistence.jpa.jpql.parser.HavingClause;\nimport org.eclipse.persistence.jpa.jpql.parser.OrderByClause;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectClause;\nimport org.eclipse.persistence.jpa.jpql.parser.WhereClause;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Parser for handling JPQL Single-String queries. Takes a JPQLQuery and the\n * query string and parses it into its constituent parts, updating the JPQLQuery\n * accordingly with the result that after calling the parse() method the\n * JPQLQuery is populated.\n * \n * <pre>\n * SELECT [ {result} ]\n * [FROM {candidate-classes} ]\n * [WHERE {filter}]\n * [GROUP BY {grouping-clause} ]\n * [HAVING {having-clause} ]\n * [ORDER BY {ordering-clause}]\n * e.g SELECT c FROM Customer c INNER JOIN c.orders o WHERE c.status = 1\n * </pre>\n * \n * @author animesh.kumar\n */\npublic class KunderaQueryParser\n{\n\n    /** The JPQL query to populate. */\n    private KunderaQuery query;\n\n    /** The single-string query string. */\n    private String queryString;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(KunderaQueryParser.class);\n\n    /**\n     * Constructor for the Single-String parser.\n     * \n     * @param query\n     *            The query\n     * @param queryString\n     *            The Single-String query\n     */\n    public KunderaQueryParser(KunderaQuery query)\n    {\n        this.query = query;\n        this.queryString = query.getJPAQuery();\n    }\n\n    /**\n     * Method to parse the Single-String query.\n     */\n    public final void parse()\n    {\n        new Compiler().compile();\n    }\n\n    /**\n     * Method to detect whether this token is a keyword for JPQL Single-String.\n     * \n     * @param token\n     *            The token\n     * \n     * @return Whether it is a keyword\n     */\n    private boolean isKeyword(String token)\n    {\n        // Compare the passed token against the provided keyword list, or their\n        // lowercase form\n        for (int i = 0; i < KunderaQuery.SINGLE_STRING_KEYWORDS.length; i++)\n        {\n            if (token.equalsIgnoreCase(KunderaQuery.SINGLE_STRING_KEYWORDS[i]))\n            {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    /**\n     * Compiler to process keywords contents. In the query the keywords often\n     * have content values following them that represent the constituent parts\n     * of the query. This takes the keyword and sets the constituent part\n     * accordingly.\n     */\n    private class Compiler\n    {\n\n        // Temporary variable since grouping clause is made up of GROUP BY ...\n        // HAVING ...\n        /** The grouping clause. */\n        private String groupingClause;\n\n        /**\n         * Compile.\n         */\n        private void compile()\n        {\n            // if it is not an update statement\n            if (!compileUpdate())\n            {\n                compileSelectOrDelete();\n            }\n        }\n\n        /**\n         * Compile update.\n         * \n         * @return true, if successful\n         */\n        private boolean compileUpdate()\n        {\n            if (query.isUpdateStatement())\n            {\n                query.setIsDeleteUpdate(true);\n                compileFrom();\n                compileUpdateClause();\n\n                compilewhereClause();\n\n                return true;\n            }\n            else\n            {\n                // initiateExpressionFactory(\"SELECT\");\n            }\n            return false;\n        }\n\n        /**\n         * Compile select.\n         */\n        private void compileSelectOrDelete()\n        {\n\n            if (!query.isSelectStatement())\n            {\n                if (query.isDeleteStatement())\n                {\n                    query.setIsDeleteUpdate(true);\n\n                }\n            }\n            else\n            {\n                // initiateExpressionFactory(\"SELECT\");\n            }\n\n            compileFrom();\n            compileResult();\n\n            compilewhereClause();\n        }\n\n        private boolean isWhereClause()\n        {\n            if (query.isSelectStatement())\n            {\n                return query.getSelectStatement().hasWhereClause();\n            }\n            else if (query.isUpdateStatement())\n            {\n                return query.getUpdateStatement().hasWhereClause();\n            }\n            if (query.isDeleteStatement())\n            {\n                return query.getDeleteStatement().hasWhereClause();\n            }\n            return false;\n        }\n\n        private boolean isGroupBy()\n        {\n            if (query.isSelectStatement())\n            {\n                return query.getSelectStatement().hasGroupByClause();\n            }\n            return false;\n        }\n\n        private boolean isHaving()\n        {\n            if (query.isSelectStatement())\n            {\n                return query.getSelectStatement().hasHavingClause();\n            }\n            return false;\n        }\n\n        private boolean isOrderBy()\n        {\n            if (query.isSelectStatement())\n            {\n                return query.getSelectStatement().hasOrderByClause();\n            }\n            return false;\n        }\n\n        /**\n         * Compilewhere clause.\n         */\n        private void compilewhereClause()\n        {\n\n            if (isWhereClause())\n            {\n                compileWhere();\n            }\n            if (isGroupBy())\n            {\n                compileGroup();\n            }\n            if (isHaving())\n            {\n                compileHaving();\n            }\n            if (groupingClause != null)\n            {\n                query.setGrouping(groupingClause);\n            }\n\n            if (isOrderBy())\n            {\n                compileOrder();\n            }\n        }\n\n        /**\n         * Compile result.\n         */\n        private void compileResult()\n        {\n            buildResultColumns();\n        }\n\n        /**\n         * Compile from.\n         */\n        private void compileFrom()\n        {\n            buildFrom();\n        }\n\n        /**\n         * Compile from.\n         */\n        private void compileUpdateClause()\n        {\n            ListIterator<Expression> updateColumnIter = null;\n            if (query.isUpdateStatement() && query.getUpdateStatement().getUpdateClause().hasUpdateItems())\n            {\n\n                if (query.getUpdateStatement().getUpdateClause().getUpdateItems() instanceof CollectionExpression)\n                {\n\n                    updateColumnIter = ((CollectionExpression) query.getUpdateStatement().getUpdateClause()\n                            .getUpdateItems()).children().iterator();\n                    while (updateColumnIter.hasNext())\n                    {\n                        ListIterator<Expression> childUpdateClauseIter = updateColumnIter.next().children().iterator();\n\n                        while (childUpdateClauseIter.hasNext())\n                        {\n                            addUpdateClause(childUpdateClauseIter);\n\n                        }\n\n                    }\n                }\n                else\n                {\n\n                    updateColumnIter = query.getUpdateStatement().getUpdateClause().getUpdateItems().children()\n                            .iterator();\n                    addUpdateClause(updateColumnIter);\n\n                }\n\n            }\n        }\n\n        private void addUpdateClause(ListIterator<Expression> childUpdateClauseIter)\n        {\n            String columnTuple = childUpdateClauseIter.next().toActualText().trim();\n            String value = childUpdateClauseIter.next().toActualText().trim();\n            StringTokenizer tokenizer = new StringTokenizer(columnTuple, \".\");\n            columnTuple = getTokenizedValue(tokenizer);\n\n            query.addUpdateClause(columnTuple, value);\n        }\n\n        private String getTokenizedValue(StringTokenizer tokenizer)\n        {\n            String value = null;\n\n            while (tokenizer.hasMoreTokens())\n            {\n                value = tokenizer.nextToken();\n            }\n            return value;\n        }\n\n        /**\n         * Compile where.\n         */\n        private void compileWhere()\n        {\n            WhereClause whereClause = null;\n\n            if (query.isSelectStatement())\n            {\n                whereClause = (WhereClause) query.getSelectStatement().getWhereClause();\n\n            }\n            else if (query.isUpdateStatement())\n            {\n                whereClause = (WhereClause) query.getUpdateStatement().getWhereClause();\n\n            }\n            if (query.isDeleteStatement())\n            {\n                whereClause = (WhereClause) query.getDeleteStatement().getWhereClause();\n\n            }\n\n            String content = whereClause.getConditionalExpression().toActualText();\n            if (whereClause != null && content.length() == 0)\n            {\n                throw new JPQLParseException(\"keyword without value[WHERE]\");\n            }\n            query.setFilter(content);\n        }\n\n        /**\n         * Compile group.\n         */\n        private void compileGroup()\n        {\n            GroupByClause groupByClause = null;\n\n            if (query.isSelectStatement())\n            {\n                groupByClause = (GroupByClause) query.getSelectStatement().getGroupByClause();\n\n            }\n\n            // content cannot be empty\n            if (groupByClause == null || groupByClause.toActualText().length() == 0)\n            {\n                throw new JPQLParseException(\"keyword without value: GROUP BY\");\n            }\n            groupingClause = groupByClause.toActualText();\n        }\n\n        /**\n         * Compile having.\n         */\n        private void compileHaving()\n        {\n            HavingClause havingClause = null;\n\n            if (query.isSelectStatement())\n            {\n                havingClause = (HavingClause) query.getSelectStatement().getHavingClause();\n\n            }\n\n            // content cannot be empty\n            if (havingClause == null || havingClause.toActualText().length() == 0)\n            {\n                throw new JPQLParseException(\"keyword without value: HAVING\");\n            }\n\n            if (groupingClause != null)\n            {\n                groupingClause = groupingClause.trim() + havingClause.toActualText();\n            }\n            else\n            {\n                groupingClause = havingClause.toActualText();\n            }\n        }\n\n        /**\n         * Compile order.\n         */\n        private void compileOrder()\n        {\n            OrderByClause orderByClause = null;\n\n            if (query.isSelectStatement())\n            {\n                orderByClause = (OrderByClause) query.getSelectStatement().getOrderByClause();\n\n            }\n            if (orderByClause == null || !orderByClause.hasOrderByItems())\n            {\n                throw new JPQLParseException(\"keyword without value: ORDER BY\");\n            }\n            query.setOrdering(orderByClause.getOrderByItems().toActualText());\n        }\n    }\n\n    private void buildResultColumns()\n    {\n        String[] result = null, aggResult = null;\n        if (query.isSelectStatement())\n        {\n            SelectClause selectClause = (SelectClause) (query.getSelectStatement().getSelectClause());\n            ListIterator<Expression> selectColumnIter = null;\n\n            int size = 0;\n            if (selectClause.getSelectExpression() instanceof CollectionExpression)\n            {\n                CollectionExpression selectColumnExpression = (CollectionExpression) selectClause.getSelectExpression();\n                selectColumnIter = selectColumnExpression.children().iterator();\n                size = selectColumnExpression.childrenSize();\n\n            }\n            else\n            {\n                if (selectClause.getSelectExpression().toActualText().indexOf(\".\") > 0)\n                {\n                    size = 1;\n                }\n            }\n\n            int aggregationCount = countAggregation(selectClause.getSelectExpression());\n            query.setAggregated(aggregationCount > 0 || query.getSelectStatement().hasGroupByClause());\n            int count = 0, aggCounter = 0, resultSize = size + 1 - aggregationCount;\n            if (resultSize == 0)\n            {\n                resultSize = 1;\n            }\n            result = new String[resultSize];\n            aggResult = new String[aggregationCount + 1];\n            // content may be empty\n            if (selectColumnIter != null)\n            {\n                while (selectColumnIter.hasNext())\n                {\n                    Expression nextExpression = selectColumnIter.next();\n                    String property = nextExpression.toActualText();\n                    if (isAggregation(nextExpression))\n                    {\n                        aggCounter = buildResult(aggResult, aggCounter,\n                                property.substring(property.indexOf('(') + 1, property.indexOf(')')));\n                    }\n                    else\n                        count = buildResult(result, count, property);\n                }\n            }\n            else\n            {\n                String property = selectClause.getSelectExpression().toActualText();\n                if (isAggregation(selectClause.getSelectExpression()))\n                    aggCounter = buildResult(aggResult, aggCounter,\n                            property.substring(property.indexOf('(') + 1, property.indexOf(')')));\n                else\n                    count = buildResult(result, count, property);\n            }\n            result[0] = result[0] == null ? aggResult[0] : result[0];\n            aggResult[0] = aggResult[0] == null ? result[0] : aggResult[0];\n\n            query.setResult(result);\n            query.setAggregationResult(aggResult);\n        }\n    }\n\n    /**\n     * @param selectExpression\n     * @return Count of aggregation required\n     */\n    private int countAggregation(Expression selectExpression)\n    {\n        int count = 0;\n        if (selectExpression instanceof CollectionExpression)\n        {\n            CollectionExpression selectColumnExpression = (CollectionExpression) selectExpression;\n            ListIterator<Expression> selectColumnIter = selectColumnExpression.children().iterator();\n\n            while (selectColumnIter.hasNext())\n            {\n                count = isAggregation(selectColumnIter.next()) ? ++count : count;\n            }\n        }\n        else\n        {\n            if (isAggregation(selectExpression))\n                count = 1;\n        }\n        return count;\n    }\n\n    private boolean isAggregation(Expression expression)\n    {\n        return expression instanceof AggregateFunction;\n    }\n\n    private int buildResult(String[] result, int count, String property)\n    {\n        if (property != null && property.length() > 0)\n        {\n            if (property.indexOf(\".\") > 0)\n            {\n                result[0] = property.substring(0, property.indexOf(\".\"));\n                String fieldName = property.substring(property.indexOf(\".\") + 1, property.length());\n                if (fieldName == null || fieldName.isEmpty())\n                {\n                    throw new JPQLParseException(\n                            \"You have not given any column name after . ,Column name should not be empty\");\n                }\n                if (result[count] == null)\n                {\n                    throw new JPQLParseException(\"Bad query format\");\n                }\n                result[++count] = fieldName;\n            }\n            else\n            {\n                if (count > 0 && !query.isAggregated())\n                {\n                    throw new JPQLParseException(\"Bad query format\");\n                }\n                result[count] = property;\n                count++;\n            }\n        }\n        return count;\n    }\n\n    private void buildFrom()\n    {\n        ListIterator<Expression> fromIter = null;\n        if (query.isSelectStatement() && query.getSelectStatement().hasFromClause())\n        {\n            FromClause fromClause = (FromClause) query.getSelectStatement().getFromClause();\n            fromIter = fromClause.children().iterator();\n\n        }\n        else if (query.isUpdateStatement())\n        {\n            fromIter = query.getUpdateStatement().getUpdateClause().children().iterator();\n\n        }\n        if (query.isDeleteStatement())\n        {\n            fromIter = query.getDeleteStatement().getDeleteClause().children().iterator();\n\n        }\n\n        if (fromIter != null)\n        {\n            while (fromIter.hasNext())\n            {\n                String textObj = fromIter.next().toActualText().trim();\n\n                if (!StringUtils.isEmpty(textObj))\n                {\n                    query.setFrom(textObj);\n                    break;\n                }\n\n            }\n        }\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/query/KunderaQueryUtils.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.ListIterator;\nimport java.util.Map;\n\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.eclipse.persistence.jpa.jpql.parser.AbstractPathExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.AbstractSingleEncapsulatedExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.AggregateFunction;\nimport org.eclipse.persistence.jpa.jpql.parser.BetweenExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.CollectionExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.ComparisonExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.DeleteStatement;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable;\nimport org.eclipse.persistence.jpa.jpql.parser.InExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.InputParameter;\nimport org.eclipse.persistence.jpa.jpql.parser.JPQLExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.KeywordExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.LikeExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.LogicalExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.LowerExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.NullComparisonExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.NumericLiteral;\nimport org.eclipse.persistence.jpa.jpql.parser.OrExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.OrderByClause;\nimport org.eclipse.persistence.jpa.jpql.parser.OrderByItem;\nimport org.eclipse.persistence.jpa.jpql.parser.RegexpExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectClause;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectStatement;\nimport org.eclipse.persistence.jpa.jpql.parser.StateFieldPathExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.StringLiteral;\nimport org.eclipse.persistence.jpa.jpql.parser.SubExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.UpdateStatement;\nimport org.eclipse.persistence.jpa.jpql.parser.UpperExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.WhereClause;\nimport org.eclipse.persistence.jpa.jpql.utility.iterable.ListIterable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\n\n/**\n * \n * @author Amit Kumar\n */\npublic final class KunderaQueryUtils\n{\n    /** the log used by this class. */\n    private static Logger logger = LoggerFactory.getLogger(KunderaQueryUtils.class);\n\n    /**\n     * Gets the where clause.\n     * \n     * @param jpqlExpression\n     *            the jpql expression\n     * @return the where clause\n     */\n    public static WhereClause getWhereClause(JPQLExpression jpqlExpression)\n    {\n        WhereClause whereClause = null;\n\n        if (hasWhereClause(jpqlExpression))\n        {\n            if (isSelectStatement(jpqlExpression))\n            {\n                whereClause = (WhereClause) ((SelectStatement) jpqlExpression.getQueryStatement()).getWhereClause();\n\n            }\n            else if (isUpdateStatement(jpqlExpression))\n            {\n                whereClause = (WhereClause) ((UpdateStatement) jpqlExpression.getQueryStatement()).getWhereClause();\n\n            }\n            if (isDeleteStatement(jpqlExpression))\n            {\n                whereClause = (WhereClause) ((DeleteStatement) jpqlExpression.getQueryStatement()).getWhereClause();\n            }\n        }\n        return whereClause;\n    }\n\n    public static List<String> getSelectColumns(JPQLExpression jpqlExpression)\n    {\n        List<String> columns;\n        if (isSelectStatement(jpqlExpression))\n        {\n            columns = new ArrayList<>();\n            SelectClause k = (SelectClause) ((SelectStatement) jpqlExpression.getQueryStatement()).getSelectClause();\n\n            Expression selExp = k.getSelectExpression();\n\n            if (selExp instanceof StateFieldPathExpression)\n            {\n                if (selExp.toActualText().indexOf(\".\") > 0)\n                {\n                    columns.add(selExp.toActualText().split(\"[.]\")[1]);\n                }\n            }\n            else if (selExp instanceof CollectionExpression)\n            {\n                CollectionExpression l = ((CollectionExpression) k.getSelectExpression());\n                ListIterable<Expression> list = l.children();\n                for (Expression exp : list)\n                {\n                    if (exp.toActualText().indexOf(\".\") > 0)\n                    {\n                        columns.add(exp.toActualText().split(\"[.]\")[1]);\n                    }\n                }\n            }\n        }\n        else\n        {\n            logger.error(\"Not a select Query\");\n            throw new KunderaException(\"Not a select Query\");\n        }\n        return columns;\n    }\n\n    /**\n     * Gets the order by clause.\n     * \n     * @param jpqlExpression\n     *            the jpql expression\n     * @return the order by clause\n     */\n    public static OrderByClause getOrderByClause(JPQLExpression jpqlExpression)\n    {\n        OrderByClause orderByClause = null;\n\n        if (hasOrderBy(jpqlExpression))\n        {\n            orderByClause = (OrderByClause) ((SelectStatement) jpqlExpression.getQueryStatement()).getOrderByClause();\n        }\n        return orderByClause;\n    }\n\n    /**\n     * Checks for where clause.\n     * \n     * @param jpqlExpression\n     *            the jpql expression\n     * @return true, if successful\n     */\n    public static boolean hasWhereClause(JPQLExpression jpqlExpression)\n    {\n        if (isSelectStatement(jpqlExpression))\n        {\n            return ((SelectStatement) jpqlExpression.getQueryStatement()).hasWhereClause();\n        }\n        else if (isUpdateStatement(jpqlExpression))\n        {\n            return ((UpdateStatement) jpqlExpression.getQueryStatement()).hasWhereClause();\n        }\n        if (isDeleteStatement(jpqlExpression))\n        {\n            return ((DeleteStatement) jpqlExpression.getQueryStatement()).hasWhereClause();\n        }\n        return false;\n    }\n\n    /**\n     * Checks for group by.\n     * \n     * @param jpqlExpression\n     *            the jpql expression\n     * @return true, if successful\n     */\n    public static boolean hasGroupBy(JPQLExpression jpqlExpression)\n    {\n        if (isSelectStatement(jpqlExpression))\n        {\n            return ((SelectStatement) jpqlExpression.getQueryStatement()).hasGroupByClause();\n        }\n        return false;\n    }\n\n    /**\n     * Checks for having.\n     * \n     * @param jpqlExpression\n     *            the jpql expression\n     * @return true, if successful\n     */\n    public static boolean hasHaving(JPQLExpression jpqlExpression)\n    {\n        if (isSelectStatement(jpqlExpression))\n        {\n            return ((SelectStatement) jpqlExpression.getQueryStatement()).hasHavingClause();\n        }\n        return false;\n    }\n\n    /**\n     * Checks for order by.\n     * \n     * @param jpqlExpression\n     *            the jpql expression\n     * @return true, if successful\n     */\n    public static boolean hasOrderBy(JPQLExpression jpqlExpression)\n    {\n        if (isSelectStatement(jpqlExpression))\n        {\n            return ((SelectStatement) jpqlExpression.getQueryStatement()).hasOrderByClause();\n        }\n        return false;\n    }\n\n    /**\n     * Checks if is select statement.\n     * \n     * @param jpqlExpression\n     *            the jpql expression\n     * @return true, if is select statement\n     */\n    public static boolean isSelectStatement(JPQLExpression jpqlExpression)\n    {\n        return jpqlExpression.getQueryStatement().getClass().isAssignableFrom(SelectStatement.class);\n\n    }\n\n    /**\n     * Checks if is delete statement.\n     * \n     * @param jpqlExpression\n     *            the jpql expression\n     * @return true, if is delete statement\n     */\n    public static boolean isDeleteStatement(JPQLExpression jpqlExpression)\n    {\n        return jpqlExpression.getQueryStatement().getClass().isAssignableFrom(DeleteStatement.class);\n    }\n\n    /**\n     * Checks if is update statement.\n     * \n     * @param jpqlExpression\n     *            the jpql expression\n     * @return true, if is update statement\n     */\n    public static boolean isUpdateStatement(JPQLExpression jpqlExpression)\n    {\n        return jpqlExpression.getQueryStatement().getClass().isAssignableFrom(UpdateStatement.class);\n    }\n\n    /**\n     * Checks if is aggregated expression.\n     * \n     * @param expression\n     *            the expression\n     * @return true, if is aggregated expression\n     */\n    public static boolean isAggregatedExpression(Expression expression)\n    {\n        return AggregateFunction.class.isAssignableFrom(expression.getClass());\n    }\n\n    /**\n     * Gets the value.\n     * \n     * @param exp\n     *            the exp\n     * @param clazz\n     *            the clazz\n     * @return the value\n     */\n    public static Object getValue(Expression exp, Class clazz, KunderaQuery kunderaQuery)\n    {\n        if (StringLiteral.class.isAssignableFrom(exp.getClass()))\n        {\n            return ((StringLiteral) exp).getUnquotedText();\n\n        }\n        else if (NumericLiteral.class.isAssignableFrom(exp.getClass()))\n        {\n            return PropertyAccessorFactory.getPropertyAccessor(clazz).fromString(clazz,\n                    ((NumericLiteral) exp).getText());\n        }\n        else if (InputParameter.class.isAssignableFrom(exp.getClass()))\n        {\n            InputParameter ip = (InputParameter) exp;\n            if (kunderaQuery.getParametersMap().containsKey(ip.getParameter()))\n            {\n                return kunderaQuery.getParametersMap().get(ip.getParameter());\n            }\n            else\n            {\n                return ip.getParameter();\n            }\n        }\n        else if (KeywordExpression.class.isAssignableFrom(exp.getClass()))\n        {\n            KeywordExpression keyWordExp = (KeywordExpression) exp;\n            return PropertyAccessorFactory.getPropertyAccessor(clazz).fromString(clazz,\n                    keyWordExp.getActualIdentifier());\n        }\n        else if (IdentificationVariable.class.isAssignableFrom(exp.getClass()))\n        {\n            IdentificationVariable idvExp = (IdentificationVariable) exp;\n            return idvExp.getText();\n        }\n        else\n        {\n            logger.warn(\"Arithmetic expression is not supported \");\n            throw new KunderaException(\"Arithmetic expression is not supported currently\");\n        }\n    }\n\n    /**\n     * Adds the to output columns.\n     * \n     * @param selectExpression\n     *            the select expression\n     * @param m\n     *            the m\n     * @param columnsToOutput\n     *            the columns to output\n     */\n    private static void addToOutputColumns(Expression selectExpression, EntityMetadata m,\n            List<Map<String, Object>> columnsToOutput, KunderaMetadata kunderaMetadata)\n    {\n\n        Map<String, Object> map = setFieldClazzAndColumnFamily(selectExpression, m, kunderaMetadata);\n        columnsToOutput.add(map);\n    }\n\n    /**\n     * Read select clause.\n     * \n     * @param selectExpression\n     *            the select expression\n     * @param m\n     *            the m\n     * @param useLuceneOrES\n     *            the use lucene or es\n     * @param kunderaMetadata\n     * @return the list\n     */\n    public static List<Map<String, Object>> readSelectClause(Expression selectExpression, EntityMetadata m,\n            Boolean useLuceneOrES, KunderaMetadata kunderaMetadata)\n    {\n        List<Map<String, Object>> columnsToOutput = new ArrayList<Map<String, Object>>();\n        if (StateFieldPathExpression.class.isAssignableFrom(selectExpression.getClass()))\n        {\n            Expression sfpExp = selectExpression;\n\n            addToOutputColumns(selectExpression, m, columnsToOutput, kunderaMetadata);\n        }\n        else if (CollectionExpression.class.isAssignableFrom(selectExpression.getClass()))\n        {\n            CollectionExpression collExp = (CollectionExpression) selectExpression;\n            ListIterator<Expression> itr = collExp.children().iterator();\n            while (itr.hasNext())\n            {\n                Expression exp = itr.next();\n                if (StateFieldPathExpression.class.isAssignableFrom(exp.getClass()))\n                {\n                    addToOutputColumns(exp, m, columnsToOutput, kunderaMetadata);\n                }\n            }\n        }\n        return columnsToOutput;\n    }\n\n    /**\n     * Sets the fieldclazz and colfamily.\n     * \n     * @param expression\n     *            the expression\n     * @param m\n     *            the m\n     * @return the map\n     */\n    public static Map<String, Object> setFieldClazzAndColumnFamily(Expression expression, EntityMetadata m,\n            final KunderaMetadata kunderaMetadata)\n    {\n        AbstractPathExpression pathExp = null;\n\n        if (expression instanceof AbstractPathExpression) {\n            pathExp = (AbstractPathExpression) expression;\n\n        } else {\n            if (expression instanceof AbstractSingleEncapsulatedExpression) {\n                pathExp = (AbstractPathExpression) ((AbstractSingleEncapsulatedExpression) expression).getExpression();\n            }\n\n        }\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n\n        EntityType entity = metaModel.entity(m.getEntityClazz());\n        String discriminatorColumn = ((AbstractManagedType) entity).getDiscriminatorColumn();\n        Class fieldClazz = String.class;\n        String colFamily = m.getTableName();\n        String colName = null;\n        Map<String, Object> map = new HashMap<String, Object>();\n\n        boolean isEmbeddable = false;\n        boolean isAssociation = false;\n        int count = 1;\n        String fieldName = pathExp.getPath(count++);\n\n        AbstractAttribute attrib = (AbstractAttribute) entity.getAttribute(fieldName);\n        String dbColName = attrib.getJPAColumnName();\n        isEmbeddable = metaModel.isEmbeddable(attrib.getBindableJavaType());\n        isAssociation = attrib.isAssociation();\n        while (pathExp.pathSize() > count)\n        {\n            if (isEmbeddable)\n            {\n                EmbeddableType embeddableType = metaModel.embeddable(attrib.getBindableJavaType());\n                String attName = pathExp.getPath(count++);\n                fieldName = fieldName + \".\" + attName;\n                attrib = (AbstractAttribute) embeddableType.getAttribute(attName);\n                isEmbeddable = metaModel.isEmbeddable(attrib.getBindableJavaType());\n                isAssociation = attrib.isAssociation();\n                dbColName += (\".\" + attrib.getJPAColumnName());\n            }\n            else if (isAssociation)\n            {\n                String attName = pathExp.getPath(count++);\n                fieldName = fieldName + \".\" + attName;\n                EntityType associatedType = metaModel.entity(attrib.getBindableJavaType());\n                attrib = (AbstractAttribute) associatedType.getAttribute(attName);\n                isEmbeddable = metaModel.isEmbeddable(attrib.getBindableJavaType());\n                isAssociation = attrib.isAssociation();\n                dbColName += (\".\" + attrib.getJPAColumnName());\n            }\n            colName = fieldName;\n        }\n\n        if (!pathExp.getPath(count - 1).equals(discriminatorColumn))\n        {\n            fieldClazz = attrib.getBindableJavaType();\n            colFamily = attrib.getTableName() != null ? attrib.getTableName() : m.getTableName();\n            colName = colName != null ? colName : attrib.getJPAColumnName();\n\n        }\n\n        boolean ignoreCase =\n              (expression instanceof UpperExpression) || (expression instanceof LowerExpression);\n\n        map.put(Constants.FIELD_CLAZZ, fieldClazz);\n        map.put(Constants.COL_FAMILY, colFamily);\n        map.put(Constants.COL_NAME, colName);\n        map.put(Constants.FIELD_NAME, fieldName);\n        map.put(Constants.IS_EMBEDDABLE, isEmbeddable);\n        map.put(Constants.DB_COL_NAME, dbColName);\n        map.put(Constants.IGNORE_CASE, ignoreCase);\n        return map;\n    }\n\n    /**\n     * Traverse.\n     * \n     * @param expression\n     *            the expression\n     * @param m\n     *            the m\n     * @param idColumn\n     *            the id column\n     * @return the filter\n     */\n    public static void traverse(Expression expression, EntityMetadata m, KunderaMetadata kunderaMetadata,\n            KunderaQuery kunderaQuery, boolean isSubExpression)\n    {\n\n        if (ComparisonExpression.class.isAssignableFrom(expression.getClass()))\n        {\n            onComparisonExpression(expression, m, kunderaMetadata, kunderaQuery);\n        }\n        else if (NullComparisonExpression.class.isAssignableFrom(expression.getClass()))\n        {\n            onNullComparisonExpression(expression, m, kunderaMetadata, kunderaQuery);\n        }\n        else if (LogicalExpression.class.isAssignableFrom(expression.getClass()))\n        {\n            onLogicalExpression(expression, m, kunderaMetadata, kunderaQuery);\n        }\n        else if (InExpression.class.isAssignableFrom(expression.getClass()))\n        {\n            onInExpression(expression, m, kunderaMetadata, kunderaQuery);\n        }\n        else if (LikeExpression.class.isAssignableFrom(expression.getClass()))\n        {\n            onLikeExpression(expression, m, kunderaMetadata, kunderaQuery);\n        }\n        else if (RegexpExpression.class.isAssignableFrom(expression.getClass()))\n        {\n            onRegExpression(expression, m, kunderaMetadata, kunderaQuery);\n        }\n        else if (BetweenExpression.class.isAssignableFrom(expression.getClass()))\n        {\n            onBetweenExpression(expression, m, kunderaMetadata, kunderaQuery);\n        }\n        else if (SubExpression.class.isAssignableFrom(expression.getClass()))\n        {\n            onSubExpression(expression, m, kunderaMetadata, kunderaQuery);\n        }\n\n    }\n\n    /**\n     * @param expression\n     * @param m\n     * @param kunderaMetadata\n     * @param kunderaQuery\n     */\n    public static void onSubExpression(Expression expression, EntityMetadata m, KunderaMetadata kunderaMetadata,\n            KunderaQuery kunderaQuery)\n    {\n        kunderaQuery.addFilterClause(\"(\");\n        traverse(((SubExpression) expression).getExpression(), m, kunderaMetadata, kunderaQuery, true);\n        kunderaQuery.addFilterClause(\")\");\n\n    }\n\n    /**\n     * @param expression\n     * @param m\n     * @param kunderaMetadata\n     * @param kunderaQuery\n     * @return\n     */\n    public static Map<String, Object> onBetweenExpression(Expression expression, EntityMetadata m,\n            KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery)\n    {\n        BetweenExpression betweenExp = (BetweenExpression) expression;\n        Expression sfpExp = betweenExp.getExpression();\n\n        Map<String, Object> map = KunderaQueryUtils.setFieldClazzAndColumnFamily(sfpExp, m, kunderaMetadata);\n        String columnName = (String) map.get(Constants.COL_NAME);\n        String fieldName = (String) map.get(Constants.FIELD_NAME);\n        kunderaQuery.addFilterClause(\n              columnName, Expression.GREATER_THAN_OR_EQUAL, betweenExp.getLowerBoundExpression().toActualText(),\n              fieldName, (Boolean) map.get(Constants.IGNORE_CASE));\n        kunderaQuery.addFilterClause(\"AND\");\n        kunderaQuery.addFilterClause(\n              columnName, Expression.LOWER_THAN_OR_EQUAL, betweenExp.getUpperBoundExpression().toActualText(),\n              fieldName, (Boolean) map.get(Constants.IGNORE_CASE));\n\n        return map;\n\n    }\n\n    /**\n     * @param expression\n     * @param m\n     * @param kunderaMetadata\n     * @param kunderaQuery\n     * @return\n     */\n    public static Map<String, Object> onLikeExpression(Expression expression, EntityMetadata m,\n            KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery)\n    {\n        LikeExpression likeExp = (LikeExpression) expression;\n        Expression sfpExp = likeExp.getStringExpression();\n        Map<String, Object> map = KunderaQueryUtils.setFieldClazzAndColumnFamily(sfpExp, m, kunderaMetadata);\n        kunderaQuery.addFilterClause(\n              (String) map.get(Constants.COL_NAME), likeExp.getIdentifier(), likeExp.getPatternValue().toActualText(),\n              (String) map.get(Constants.FIELD_NAME), (Boolean) map.get(Constants.IGNORE_CASE));\n        return map;\n\n    }\n\n    /**\n     * On reg expression.\n     * \n     * @param expression\n     *            the expression\n     * @param m\n     *            the m\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param kunderaQuery\n     *            the kundera query\n     * @return the map\n     */\n    public static Map<String, Object> onRegExpression(Expression expression, EntityMetadata m,\n            KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery)\n    {\n        RegexpExpression regExp = (RegexpExpression) expression;\n        Expression sfpExp = regExp.getStringExpression();\n        Map<String, Object> map = KunderaQueryUtils.setFieldClazzAndColumnFamily(sfpExp, m, kunderaMetadata);\n        kunderaQuery.addFilterClause(\n              (String) map.get(Constants.COL_NAME), regExp.getActualRegexpIdentifier().toUpperCase(),\n              regExp.getPatternValue().toActualText(), (String) map.get(Constants.FIELD_NAME),\n              (Boolean) map.get(Constants.IGNORE_CASE));\n        return map;\n    }\n\n    /**\n     * On logical expression.\n     * \n     * @param expression\n     *            the expression\n     * @param m\n     *            the m\n     * @param idColumn\n     *            the id column\n     * @return the filter\n     */\n    public static void onLogicalExpression(Expression expression, EntityMetadata m, KunderaMetadata kunderaMetadata,\n            KunderaQuery kunderaQuery)\n    {\n        if (expression instanceof OrExpression)\n        {\n            kunderaQuery.addFilterClause(\"(\");\n        }\n\n        traverse(((LogicalExpression) expression).getLeftExpression(), m, kunderaMetadata, kunderaQuery, false);\n\n        if (expression instanceof OrExpression)\n        {\n            kunderaQuery.addFilterClause(\")\");\n        }\n\n        kunderaQuery.addFilterClause(((LogicalExpression) expression).getIdentifier());\n\n        if (expression instanceof OrExpression)\n        {\n            kunderaQuery.addFilterClause(\"(\");\n        }\n\n        traverse(((LogicalExpression) expression).getRightExpression(), m, kunderaMetadata, kunderaQuery, false);\n\n        if (expression instanceof OrExpression)\n        {\n            kunderaQuery.addFilterClause(\")\");\n        }\n    }\n\n    /**\n     * On in expression.\n     * \n     * @param expression\n     *            the expression\n     * @param m\n     *            the m\n     * @param idColumn\n     *            the id column\n     * @param isIdColumn\n     *            the is id column\n     * @return\n     * @return the filter\n     */\n    public static Map<String, Object> onInExpression(Expression expression, EntityMetadata m,\n            KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery)\n    {\n        InExpression inExp = (InExpression) expression;\n        Expression sfpExp = inExp.getExpression();\n        Map<String, Object> map = KunderaQueryUtils.setFieldClazzAndColumnFamily(sfpExp, m, kunderaMetadata);\n        kunderaQuery.addFilterClause(\n              (String) map.get(Constants.COL_NAME), inExp.getIdentifier(), inExp.getInItems(),\n              (String) map.get(Constants.FIELD_NAME), (Boolean) map.get(Constants.IGNORE_CASE));\n        return map;\n    }\n\n    /**\n     * On comparison expression.\n     * \n     * @param expression\n     *            the expression\n     * @param m\n     *            the m\n     * @param idColumn\n     *            the id column\n     * @param isIdColumn\n     *            the is id column\n     * @return\n     * @return the filter\n     */\n    public static Map<String, Object> onComparisonExpression(Expression expression, EntityMetadata m,\n            KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery)\n    {\n        ComparisonExpression compExp = (ComparisonExpression) expression;\n\n        String condition = compExp.getIdentifier();\n        Expression sfpExp = compExp.getLeftExpression();\n        Map<String, Object> map = KunderaQueryUtils.setFieldClazzAndColumnFamily(sfpExp, m, kunderaMetadata);\n        Object value = KunderaQueryUtils.getValue(compExp.getRightExpression(), (Class) map.get(Constants.FIELD_CLAZZ),\n                kunderaQuery);\n        kunderaQuery.addFilterClause(\n              (String) map.get(Constants.COL_NAME), condition, value,\n              (String) map.get(Constants.FIELD_NAME), (Boolean) map.get(Constants.IGNORE_CASE));\n        return map;\n\n    }\n\n    /**\n     * On null-comparison expression.\n     *\n     * @param expression\n     *            the expression\n     * @param m\n     *            the m\n     * @param idColumn\n     *            the id column\n     * @param isIdColumn\n     *            the is id column\n     * @return\n     * @return the filter\n     */\n    public static Map<String, Object> onNullComparisonExpression(Expression expression, EntityMetadata m,\n                                                                 KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery)\n    {\n        NullComparisonExpression compExp = (NullComparisonExpression) expression;\n\n        String condition = compExp.getIdentifier();\n        Expression sfpExp = compExp.getExpression();\n        Map<String, Object> map = KunderaQueryUtils.setFieldClazzAndColumnFamily(sfpExp, m, kunderaMetadata);\n        kunderaQuery.addFilterClause(\n              (String) map.get(Constants.COL_NAME), condition, null,\n              (String) map.get(Constants.FIELD_NAME), (Boolean) map.get(Constants.IGNORE_CASE));\n        return map;\n\n    }\n\n    /**\n     * Gets the order by items.\n     * \n     * @param jpqlExpression\n     *            the jpql expression\n     * @return the order by items\n     */\n    public static List<OrderByItem> getOrderByItems(JPQLExpression jpqlExpression)\n    {\n        List<OrderByItem> orderList = new LinkedList<>();\n\n        if (hasOrderBy(jpqlExpression))\n        {\n            Expression orderByItems = getOrderByClause(jpqlExpression).getOrderByItems();\n\n            if (orderByItems instanceof CollectionExpression)\n            {\n                ListIterator<Expression> iterator = orderByItems.children().iterator();\n                while (iterator.hasNext())\n                {\n                    OrderByItem orderByItem = (OrderByItem) iterator.next();\n                    orderList.add(orderByItem);\n                }\n            }\n            else\n            {\n                orderList.add((OrderByItem) orderByItems);\n            }\n        }\n\n        return orderList;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/query/KunderaTypedQuery.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.FlushModeType;\nimport javax.persistence.LockModeType;\nimport javax.persistence.Parameter;\nimport javax.persistence.Query;\nimport javax.persistence.TemporalType;\nimport javax.persistence.TypedQuery;\n\n/**\n * Implementation class for <code> javax.persitence.TypedQuery </code>\n * interface. More sort of a compile time type check wrapper on top of\n * {@link QueryImpl}.\n * \n * @author vivek.mishra\n * \n */\npublic class KunderaTypedQuery<X> implements TypedQuery<X>, com.impetus.kundera.query.Query\n{\n    /**\n     * Query instance.\n     */\n    private Query query;\n\n    /**\n     * Constructor using query as parameter.\n     * \n     * @param query\n     *            query instance.\n     */\n    public KunderaTypedQuery(Query query)\n    {\n        this.query = query;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#executeUpdate()\n     */\n    @Override\n    public int executeUpdate()\n    {\n        return query.executeUpdate();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getFirstResult()\n     */\n    @Override\n    public int getFirstResult()\n    {\n        return query.getFirstResult();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getFlushMode()\n     */\n    @Override\n    public FlushModeType getFlushMode()\n    {\n        return query.getFlushMode();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getHints()\n     */\n    @Override\n    public Map<String, Object> getHints()\n    {\n        return query.getHints();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getLockMode()\n     */\n    @Override\n    public LockModeType getLockMode()\n    {\n        return query.getLockMode();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getMaxResults()\n     */\n    @Override\n    public int getMaxResults()\n    {\n\n        return query.getMaxResults();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameter(java.lang.String)\n     */\n    @Override\n    public Parameter<?> getParameter(String arg0)\n    {\n\n        return query.getParameter(arg0);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameter(int)\n     */\n    @Override\n    public Parameter<?> getParameter(int arg0)\n    {\n        return query.getParameter(arg0);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameter(java.lang.String,\n     * java.lang.Class)\n     */\n    @Override\n    public <T> Parameter<T> getParameter(String arg0, Class<T> arg1)\n    {\n        return query.getParameter(arg0, arg1);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameter(int, java.lang.Class)\n     */\n    @Override\n    public <T> Parameter<T> getParameter(int arg0, Class<T> arg1)\n    {\n\n        return query.getParameter(arg0, arg1);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.Query#getParameterValue(javax.persistence.Parameter)\n     */\n    @Override\n    public <T> T getParameterValue(Parameter<T> arg0)\n    {\n\n        return query.getParameterValue(arg0);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameterValue(java.lang.String)\n     */\n    @Override\n    public Object getParameterValue(String arg0)\n    {\n        return query.getParameterValue(arg0);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameterValue(int)\n     */\n    @Override\n    public Object getParameterValue(int arg0)\n    {\n        return query.getParameterValue(arg0);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameters()\n     */\n    @Override\n    public Set<Parameter<?>> getParameters()\n    {\n\n        return query.getParameters();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#isBound(javax.persistence.Parameter)\n     */\n    @Override\n    public boolean isBound(Parameter<?> arg0)\n    {\n\n        return query.isBound(arg0);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#unwrap(java.lang.Class)\n     */\n    @Override\n    public <T> T unwrap(Class<T> arg0)\n    {\n        return query.unwrap(arg0);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TypedQuery#getResultList()\n     */\n    @Override\n    public List<X> getResultList()\n    {\n        return (List<X>) query.getResultList();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TypedQuery#getSingleResult()\n     */\n    @Override\n    public X getSingleResult()\n    {\n        return (X) query.getSingleResult();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TypedQuery#setFirstResult(int)\n     */\n    @Override\n    public TypedQuery<X> setFirstResult(int arg0)\n    {\n\n        query.setFirstResult(arg0);\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.TypedQuery#setFlushMode(javax.persistence.FlushModeType\n     * )\n     */\n    @Override\n    public TypedQuery<X> setFlushMode(FlushModeType arg0)\n    {\n        query.setFlushMode(arg0);\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TypedQuery#setHint(java.lang.String,\n     * java.lang.Object)\n     */\n    @Override\n    public TypedQuery<X> setHint(String arg0, Object arg1)\n    {\n        query.setHint(arg0, arg1);\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.TypedQuery#setLockMode(javax.persistence.LockModeType)\n     */\n    @Override\n    public TypedQuery<X> setLockMode(LockModeType arg0)\n    {\n        query.setLockMode(arg0);\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TypedQuery#setMaxResults(int)\n     */\n    @Override\n    public TypedQuery<X> setMaxResults(int arg0)\n    {\n        query.setMaxResults(arg0);\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.TypedQuery#setParameter(javax.persistence.Parameter,\n     * java.lang.Object)\n     */\n    @Override\n    public <T> TypedQuery<X> setParameter(Parameter<T> arg0, T arg1)\n    {\n        query.setParameter(arg0, arg1);\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TypedQuery#setParameter(java.lang.String,\n     * java.lang.Object)\n     */\n    @Override\n    public TypedQuery<X> setParameter(String arg0, Object arg1)\n    {\n        query.setParameter(arg0, arg1);\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TypedQuery#setParameter(int, java.lang.Object)\n     */\n    @Override\n    public TypedQuery<X> setParameter(int arg0, Object arg1)\n    {\n        query.setParameter(arg0, arg1);\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.TypedQuery#setParameter(javax.persistence.Parameter,\n     * java.util.Calendar, javax.persistence.TemporalType)\n     */\n    @Override\n    public TypedQuery<X> setParameter(Parameter<Calendar> arg0, Calendar arg1, TemporalType arg2)\n    {\n        query.setParameter(arg0, arg1, arg2);\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.TypedQuery#setParameter(javax.persistence.Parameter,\n     * java.util.Date, javax.persistence.TemporalType)\n     */\n    @Override\n    public TypedQuery<X> setParameter(Parameter<Date> arg0, Date arg1, TemporalType arg2)\n    {\n        query.setParameter(arg0, arg1, arg2);\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TypedQuery#setParameter(java.lang.String,\n     * java.util.Calendar, javax.persistence.TemporalType)\n     */\n    @Override\n    public TypedQuery<X> setParameter(String arg0, Calendar arg1, TemporalType arg2)\n    {\n        query.setParameter(arg0, arg1, arg2);\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TypedQuery#setParameter(java.lang.String,\n     * java.util.Date, javax.persistence.TemporalType)\n     */\n    @Override\n    public TypedQuery<X> setParameter(String arg0, Date arg1, TemporalType arg2)\n    {\n\n        query.setParameter(arg0, arg1, arg2);\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TypedQuery#setParameter(int, java.util.Calendar,\n     * javax.persistence.TemporalType)\n     */\n    @Override\n    public TypedQuery<X> setParameter(int arg0, Calendar arg1, TemporalType arg2)\n    {\n        query.setParameter(arg0, arg1, arg2);\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.TypedQuery#setParameter(int, java.util.Date,\n     * javax.persistence.TemporalType)\n     */\n    @Override\n    public TypedQuery<X> setParameter(int arg0, Date arg1, TemporalType arg2)\n    {\n        query.setParameter(arg0, arg1, arg2);\n        return this;\n    }\n\n    @Override\n    public void setFetchSize(Integer fetchsize)\n    {\n        ((com.impetus.kundera.query.Query)query).setFetchSize(fetchsize);\n    }\n\n    @Override\n    public Integer getFetchSize()\n    {\n        return ((com.impetus.kundera.query.Query)query).getFetchSize();\n    }\n\n    @Override\n    public void close()\n    {\n        ((com.impetus.kundera.query.Query)query).close();\n        \n    }\n\n    @Override\n    public Iterator<X> iterate()\n    {\n        return ((com.impetus.kundera.query.Query)query).iterate();\n    }\n\n    @Override\n    public void applyTTL(int ttlInSeconds)\n    {\n        ((com.impetus.kundera.query.Query)query).applyTTL(ttlInSeconds);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/query/LuceneQuery.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.query;\r\n\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.Query;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.Constants;\r\nimport com.impetus.kundera.client.Client;\r\nimport com.impetus.kundera.metadata.MetadataBuilder;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\nimport com.impetus.kundera.persistence.EntityReader;\r\nimport com.impetus.kundera.persistence.PersistenceDelegator;\r\nimport com.impetus.kundera.utils.KunderaCoreUtils;\r\n\r\n/**\r\n * The Class LuceneQuery.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class LuceneQuery extends QueryImpl {\r\n\r\n    /** the log used by this class. */\r\n    private static Logger log = LoggerFactory.getLogger(MetadataBuilder.class);\r\n\r\n    /** The max result. */\r\n    int maxResult = Constants.INVALID;\r\n\r\n    /** The lucene query. */\r\n    String luceneQuery;\r\n\r\n    /**\r\n     * Instantiates a new lucene query.\r\n     * \r\n     * @param jpaQuery\r\n     *            the jpa query\r\n     * @param kunderaQuery\r\n     *            the kundera query\r\n     * @param pd\r\n     *            the pd\r\n     * @param persistenceUnits\r\n     *            the persistence units\r\n     */\r\n    public LuceneQuery(KunderaQuery kunderaQuery, PersistenceDelegator pd, final KunderaMetadata kunderaMetadata) {\r\n        super(kunderaQuery, pd, kunderaMetadata);\r\n    }\r\n\r\n    // @see com.impetus.kundera.query.QueryImpl#getResultList()\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.query.QueryImpl#getResultList()\r\n     */\r\n    @Override\r\n    public List<?> getResultList() {\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"JPA Query: \" + getJPAQuery());\r\n\r\n        // get luence query\r\n        String q = luceneQuery;\r\n        if (null == q) {\r\n            q = KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata);\r\n        }\r\n\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"Lucene Query: \" + q);\r\n\r\n        EntityMetadata m = kunderaQuery.getEntityMetadata();\r\n        Client client = persistenceDelegeator.getClient(m);\r\n\r\n        handlePostEvent();\r\n        Map<String, Object> searchFilter = client.getIndexManager().search(m.getEntityClazz(), q, -1, maxResult);\r\n\r\n        if (kunderaQuery.isAliasOnly()) {\r\n            String[] primaryKeys = searchFilter.values().toArray(new String[] {});\r\n            return persistenceDelegeator.find(m.getEntityClazz(), primaryKeys);\r\n        } else {\r\n            return persistenceDelegeator.find(m.getEntityClazz(), searchFilter);\r\n\r\n        }\r\n\r\n    }\r\n\r\n    // @see com.impetus.kundera.query.QueryImpl#setMaxResults(int)\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.query.QueryImpl#setMaxResults(int)\r\n     */\r\n    @Override\r\n    public Query setMaxResults(int maxResult) {\r\n        this.maxResult = maxResult;\r\n        return this;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera .metadata.model.EntityMetadata,\r\n     * com.impetus.kundera.client.Client)\r\n     */\r\n    @Override\r\n    protected List<Object> populateEntities(EntityMetadata m, Client client) {\r\n        throw new UnsupportedOperationException(\"Method not supported for Lucene indexing\");\r\n    }\r\n\r\n    @Override\r\n    protected EntityReader getReader() {\r\n        throw new UnsupportedOperationException(\"Method not supported for Lucene indexing\");\r\n    }\r\n\r\n    @Override\r\n    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client) {\r\n        throw new UnsupportedOperationException(\"Method not supported for Lucene indexing\");\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()\r\n     */\r\n    @Override\r\n    protected int onExecuteUpdate() {\r\n        if (kunderaQuery.isDeleteUpdate()) {\r\n            List result = getResultList();\r\n            return result != null ? result.size() : 0;\r\n        }\r\n\r\n        return 0;\r\n\r\n    }\r\n\r\n    @Override\r\n    public void close() {\r\n        // TODO Auto-generated method stub\r\n\r\n    }\r\n\r\n    @Override\r\n    public Iterator iterate() {\r\n        // TODO Auto-generated method stub\r\n        return null;\r\n    }\r\n\r\n    protected List findUsingLucene(EntityMetadata m, Client client) {\r\n        throw new UnsupportedOperationException(\"Method supported in native clients\");\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/query/LuceneQueryBuilder.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport java.math.BigDecimal;\nimport java.sql.Timestamp;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Pattern;\n\nimport com.impetus.kundera.index.IndexingConstants;\n\n/**\n * Builder interface to build lucene query.\n * \n * @author vivek.mishra\n * \n */\npublic final class LuceneQueryBuilder\n{\n\n    private static final Map<String, condition> conditions = new HashMap<String, LuceneQueryBuilder.condition>();\n\n    private StringBuilder builder = new StringBuilder();\n\n    public static enum condition\n    {\n        EQ, LIKE, GT, LT, LTE, GTE, AND, OR, NOT_EQ, IN;\n    }\n\n    private static final String LUCENE_ESCAPE_CHARS = \"[\\\\\\\\+\\\\-\\\\!\\\\(\\\\)\\\\:\\\\^\\\\]\\\\{\\\\}\\\\~\\\\*\\\\?]\";\n\n    private static final Pattern LUCENE_PATTERN = Pattern.compile(LUCENE_ESCAPE_CHARS);\n\n    private static final String REPLACEMENT_STRING = \"\\\\\\\\$0\";\n\n    static\n    {\n        conditions.put(\"=\", condition.EQ);\n        conditions.put(\"like\", condition.LIKE);\n        conditions.put(\">\", condition.GT);\n        conditions.put(\"<\", condition.LT);\n        conditions.put(\">=\", condition.GTE);\n        conditions.put(\"<=\", condition.LTE);\n        conditions.put(\"and\", condition.AND);\n        conditions.put(\"or\", condition.OR);\n        conditions.put(\"<>\", condition.NOT_EQ);\n        conditions.put(\"in\", condition.IN);\n    }\n\n    /**\n     * @param condition\n     * @param builder\n     *            Code inspired :\n     *            http://www.javalobby.org/java/forums/t86124.html\n     */\n    public final LuceneQueryBuilder buildQuery(final String condition, final String value, final Class valueClazz)\n    {\n\n        condition c = conditions.get(condition.toLowerCase().trim());\n        String lucenevalue = LUCENE_PATTERN.matcher(value).replaceAll(REPLACEMENT_STRING);\n        if (c != null)\n            switch (c)\n            {\n            case EQ:\n                builder.append(\":\");\n                builder.append(\"\\\"\");\n                builder.append(lucenevalue);\n                builder.append(\"\\\"\");\n                break;\n\n            case NOT_EQ:\n                builder.append(\":(* NOT \");\n                builder.append(\"\\\"\");\n                builder.append(lucenevalue);\n                builder.append(\"\\\")\");\n                break;\n\n            case LIKE:\n                builder.append(\":\");\n                builder.append(\"(\");\n                matchMode(lucenevalue.trim());\n                builder.append(\")\");\n                break;\n\n            case GT:\n                builder.append(appendRange(lucenevalue, false, true, valueClazz));\n                break;\n\n            case LT:\n                builder.append(appendRange(lucenevalue, false, false, valueClazz));\n                break;\n\n            case GTE:\n                builder.append(appendRange(lucenevalue, true, true, valueClazz));\n                break;\n\n            case LTE:\n                builder.append(appendRange(lucenevalue, true, false, valueClazz));\n                break;\n\n            case IN:\n                builder.append(\":\");\n                builder.append(\"(\");\n                builder.append(value);\n                builder.append(\")\");\n                break;\n\n            default:\n                builder.append(\" \" + lucenevalue + \" \");\n                break;\n            }\n\n        return this;\n    }\n\n    public LuceneQueryBuilder appendEntityName(final String entityName)\n    {\n\n        // add Entity_CLASS field too.\n        if (builder.length() > 0)\n        {\n            builder.insert(0, \"(\");\n            builder.append(\")\");\n            builder.append(\" AND \");\n        }\n        // sb.append(\"+\");\n        builder.append(IndexingConstants.ENTITY_CLASS_FIELD);\n        builder.append(\":\");\n        // sb.append(getEntityClass().getName());\n        builder.append(entityName);\n        return this;\n    }\n\n    public LuceneQueryBuilder appendIndexName(final String indexName)\n    {\n        builder.append(indexName);\n        builder.append(\".\");\n        return this;\n    }\n\n    public LuceneQueryBuilder appendPropertyName(final String propertyName)\n    {\n        builder.append(propertyName);\n        return this;\n    }\n\n    public final String getQuery()\n    {\n        return builder.toString();\n    }\n\n    /**\n     * Append range.\n     * \n     * @param value\n     *            the value\n     * @param inclusive\n     *            the inclusive\n     * @param isGreaterThan\n     *            the is greater than\n     * @return the string\n     */\n    private String appendRange(final String value, final boolean inclusive, final boolean isGreaterThan,\n            final Class clazz)\n    {\n        String appender = \" \";\n        StringBuilder sb = new StringBuilder();\n        sb.append(\":\");\n        sb.append(inclusive ? \"[\" : \"{\");\n        sb.append(isGreaterThan ? value : \"*\");\n        sb.append(appender);\n        sb.append(\"TO\");\n        sb.append(appender);\n        // composite key over lucene is not working issue #491\n        if (clazz != null\n                && (clazz.isAssignableFrom(int.class) || clazz.isAssignableFrom(Integer.class)\n                        || clazz.isAssignableFrom(short.class) || clazz.isAssignableFrom(long.class)\n                        || clazz.isAssignableFrom(Timestamp.class) || clazz.isAssignableFrom(Long.class)\n                        || clazz.isAssignableFrom(float.class) || clazz.isAssignableFrom(Float.class)\n                        || clazz.isAssignableFrom(BigDecimal.class) || clazz.isAssignableFrom(Double.class) || clazz\n                            .isAssignableFrom(double.class)))\n        {\n            sb.append(isGreaterThan ? \"*\" : value);\n\n        }\n        else\n        {\n\n            sb.append(isGreaterThan ? \"null\" : value);\n        }\n\n        sb.append(inclusive ? \"]\" : \"}\");\n        return sb.toString();\n    }\n\n    /**\n     * @param value\n     *            checks if value contains % and replaces with * default: if no\n     *            % is found.. replaces both sides\n     */\n    private void matchMode(String value)\n    {\n        boolean left = false;\n        boolean right = false;\n\n        if (value.charAt(0) == '%')\n        {\n            value = value.substring(1);\n            left = true;\n        }\n        if (value.charAt(value.length() - 1) == '%')\n        {\n            value = value.substring(0, value.length() - 1);\n            right = true;\n        }\n        if ((left && right) || (!left && !right))\n        {\n            builder.append(\"*\");\n            builder.append(value);\n            builder.append(\"*\");\n        }\n        else if (left)\n        {\n            builder.append(\"*\");\n            builder.append(value);\n        }\n        else if (right)\n        {\n            builder.append(value);\n            builder.append(\"*\");\n        }\n\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/query/Query.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport java.util.Iterator;\n\n/**\n * Query Interface, clients query class must implement these method in order to\n * support pagination.\n * \n * @author Kuldeep.Mishra\n */\npublic interface Query\n{\n    /**\n     * To set fetch size for query.\n     */\n    void setFetchSize(Integer fetchsize);\n\n    /**\n     * \n     * @return fetch size value.\n     */\n    Integer getFetchSize();\n\n    /**\n     * Reinstate .\n     */\n    void close();\n\n    /**\n     * add support to enable TTL for UPDATE/INSERT/DELETE queries.\n     */\n    void applyTTL(int ttlInSeconds);\n\n    /**\n     * Iterates over result.\n     * \n     * @return\n     */\n    <E> Iterator<E> iterate();\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/query/QueryHandlerException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\n/**\n * The Class QueryHandlerException.\n * \n * @author vivek.mishra\n * \n *         Runtime exception handler for query interpretation\n */\npublic class QueryHandlerException extends RuntimeException\n{\n\n    /** Default Serial Version UID. */\n    private static final long serialVersionUID = 1L;\n\n    /**\n     * \n     */\n    public QueryHandlerException()\n    {\n        super();\n    }\n\n    /**\n     * @param paramString\n     */\n    public QueryHandlerException(String paramString)\n    {\n        super(paramString);\n    }\n\n    /**\n     * @param paramThrowable\n     */\n    public QueryHandlerException(Throwable paramThrowable)\n    {\n        super(paramThrowable);\n    }\n\n    /**\n     * @param paramThrowable\n     */\n    public QueryHandlerException(String paramString, Throwable paramThrowable)\n    {\n        super(paramString, paramThrowable);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/query/QueryImpl.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Queue;\nimport java.util.Set;\n\nimport javax.persistence.FlushModeType;\nimport javax.persistence.LockModeType;\nimport javax.persistence.NoResultException;\nimport javax.persistence.NonUniqueResultException;\nimport javax.persistence.Parameter;\nimport javax.persistence.PersistenceException;\nimport javax.persistence.PostLoad;\nimport javax.persistence.Query;\nimport javax.persistence.TemporalType;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.eclipse.persistence.jpa.jpql.parser.AggregateFunction;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.index.IndexingConstants;\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.DefaultEntityType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.persistence.context.PersistenceCacheManager;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.query.KunderaQuery.UpdateClause;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * The Class QueryImpl.\n * \n * @author vivek.mishra\n * @param <E>\n *            the element type\n */\npublic abstract class QueryImpl<E> implements Query, com.impetus.kundera.query.Query\n{\n    /** The kundera query. */\n    protected KunderaQuery kunderaQuery;\n\n    /** The persistence delegeator. */\n    protected PersistenceDelegator persistenceDelegeator;\n\n    /** The kundera metadata. */\n    protected KunderaMetadata kunderaMetadata;\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(QueryImpl.class);\n\n    /** The parameters. */\n    private Set<Parameter<?>> parameters;\n\n    /** The hints. */\n    private Map<String, Object> hints = new HashMap<String, Object>();\n\n    /**\n     * Default maximum result to fetch.\n     */\n    protected int maxResult = 100;\n\n    /** The first result. */\n    protected int firstResult = 0;\n\n    /** The fetch size. */\n    private Integer fetchSize;\n\n    /** The is single result. */\n    protected boolean isSingleResult = false;\n\n    /** The ttl. */\n    protected Integer ttl;\n\n    /**\n     * Instantiates a new query impl.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param persistenceDelegator\n     *            the persistence delegator\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public QueryImpl(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            final KunderaMetadata kunderaMetadata)\n    {\n        this.kunderaQuery = kunderaQuery;\n        this.persistenceDelegeator = persistenceDelegator;\n        this.kunderaMetadata = kunderaMetadata;\n    }\n\n    /**\n     * Gets the jPA query.\n     * \n     * @return the jPA query\n     */\n    public String getJPAQuery()\n    {\n        return kunderaQuery.getJPAQuery();\n    }\n\n    /**\n     * Gets the kundera query.\n     * \n     * @return the kunderaQuery\n     */\n    public KunderaQuery getKunderaQuery()\n    {\n        return kunderaQuery;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#executeUpdate()\n     */\n    @Override\n    public int executeUpdate()\n    {\n        return onExecuteUpdate();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getResultList()\n     */\n    @Override\n    public List<?> getResultList()\n    {\n        if (log.isDebugEnabled())\n            log.info(\"On getResultList() executing query: \" + getJPAQuery());\n\n        // as per JPA post event should happen before fetching data from\n        // database.\n        List results = null;\n\n        if (getEntityMetadata() == null)\n        {\n            // Scalar Query\n            if (kunderaQuery.isDeleteUpdate())\n            {\n                executeUpdate();\n            }\n            else\n            {\n                Client client = persistenceDelegeator.getClient(kunderaQuery.getPersistenceUnit());\n                results = populateEntities(null, client);\n            }\n        }\n        else\n        {\n            handlePostEvent();\n\n            if (kunderaQuery.isDeleteUpdate())\n            {\n                executeUpdate();\n            }\n            else\n            {\n                results = fetch();\n                assignReferenceToProxy(results);\n            }\n        }\n        return results != null ? results : new ArrayList();\n    }\n\n    /**\n     * Sets the relation entities.\n     * \n     * @param enhanceEntities\n     *            the enhance entities\n     * @param client\n     *            the client\n     * @param m\n     *            the m\n     * @return the list\n     */\n    protected List<Object> setRelationEntities(List enhanceEntities, Client client, EntityMetadata m)\n    {\n        // Enhance entities can contain or may not contain relation.\n        // if it contain a relation means it is a child\n        // if it does not then it means it is a parent.\n        List<Object> result = new ArrayList<Object>();\n        // Stack of objects. To be used for referring any similar object found\n        // later.\n        // This prevents infinite recursive loop and hence prevents stack\n        // overflow.\n        Map<Object, Object> relationStack = new HashMap<Object, Object>();\n\n        if (enhanceEntities != null)\n        {\n            for (Object e : enhanceEntities)\n            {\n                addToRelationStack(relationStack, e, m);\n            }\n        }\n\n        if (enhanceEntities != null)\n        {\n            for (Object e : enhanceEntities)\n            {\n                if (!(e instanceof EnhanceEntity))\n                {\n                    e = new EnhanceEntity(e, PropertyAccessorHelper.getId(e, m), null);\n                }\n                EnhanceEntity ee = (EnhanceEntity) e;\n                result.add(getReader().recursivelyFindEntities(ee.getEntity(), ee.getRelations(), m,\n                        persistenceDelegeator, false, relationStack));\n\n            }\n        }\n\n        return result;\n    }\n\n    // Adds an object to the stack for referring\n    /**\n     * Adds the to relation stack.\n     * \n     * @param relationStack\n     *            the relation stack\n     * @param entity\n     *            the entity\n     * @param m\n     *            the m\n     */\n    protected void addToRelationStack(Map<Object, Object> relationStack, Object entity, EntityMetadata m)\n    {\n        Object obj = entity;\n        if (entity instanceof EnhanceEntity)\n        {\n            obj = ((EnhanceEntity) entity).getEntity();\n        }\n        relationStack.put(obj.getClass().getCanonicalName() + \"#\" + PropertyAccessorHelper.getId(obj, m), obj);\n\n    }\n\n    /**\n     * Populate using lucene for embeddeId.\n     * \n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @param result\n     *            the result\n     * @param searchFilter\n     *            the search filter\n     * @param metaModel\n     *            the meta model\n     * @return the list\n     */\n    private List<Object> populateEmbeddedIdUsingLucene(EntityMetadata m, Client client, List<Object> result,\n            Map<String, Object> searchFilter, MetamodelImpl metaModel)\n    {\n        List<Object> compositeIds = new ArrayList<Object>();\n\n        for (String compositeIdName : searchFilter.keySet())\n        {\n            Object compositeId = null;\n            Map<String, String> uniquePKs = (Map<String, String>) searchFilter.get(compositeIdName);\n            compositeId = KunderaCoreUtils.initialize(m.getIdAttribute().getBindableJavaType(), compositeId);\n\n            prepareCompositeIdObject(m.getIdAttribute(), compositeId, uniquePKs, metaModel);\n            compositeIds.add(compositeId);\n        }\n        return findUsingLucene(m, client, compositeIds.toArray());\n    }\n\n    /**\n     * Prepare composite id object.\n     * \n     * @param attribute\n     *            the attribute\n     * @param compositeId\n     *            the composite id\n     * @param uniquePKs\n     *            the unique p ks\n     * @param metaModel\n     *            the meta model\n     * @return the object\n     */\n    private Object prepareCompositeIdObject(final SingularAttribute attribute, Object compositeId,\n            Map<String, String> uniquePKs, MetamodelImpl metaModel)\n    {\n        Field[] fields = attribute.getBindableJavaType().getDeclaredFields();\n        EmbeddableType embeddable = metaModel.embeddable(attribute.getBindableJavaType());\n\n        for (Field field : attribute.getBindableJavaType().getDeclaredFields())\n        {\n            if (!ReflectUtils.isTransientOrStatic(field))\n            {\n                if (metaModel.isEmbeddable(((AbstractAttribute) embeddable.getAttribute(field.getName()))\n                        .getBindableJavaType()))\n                {\n                    try\n                    {\n                        field.setAccessible(true);\n                        Object embeddedObject = prepareCompositeIdObject(\n                                (SingularAttribute) embeddable.getAttribute(field.getName()),\n                                KunderaCoreUtils.initialize(((AbstractAttribute) embeddable.getAttribute(field\n                                        .getName())).getBindableJavaType(), field.get(compositeId)), uniquePKs,\n                                metaModel);\n                        PropertyAccessorHelper.set(compositeId, field, embeddedObject);\n                    }\n                    catch (IllegalAccessException e)\n                    {\n                        log.error(e.getMessage());\n                    }\n                }\n                else\n                {\n                    PropertyAccessorHelper.set(\n                            compositeId,\n                            field,\n                            PropertyAccessorHelper.fromSourceToTargetClass(field.getType(), String.class,\n                                    uniquePKs.get(field.getName())));\n                }\n            }\n        }\n        return compositeId;\n    }\n\n    /**\n     * find data using lucene.\n     * \n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @param primaryKeys\n     *            the primary keys\n     * @return the list\n     */\n    private List<Object> findUsingLucene(EntityMetadata m, Client client, Object[] primaryKeys)\n    {\n\n        String idField = m.getIdAttribute().getName();\n        String equals = \"=\";\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n        String columnName = ((AbstractAttribute) entityType.getAttribute(idField)).getJPAColumnName();\n        List<Object> result = new ArrayList<Object>();\n        Queue queue = getKunderaQuery().getFilterClauseQueue();\n        KunderaQuery kunderaQuery = getKunderaQuery();\n\n        for (Object primaryKey : primaryKeys)\n        {\n            FilterClause filterClause = kunderaQuery.new FilterClause(columnName, equals, primaryKey, idField);\n            kunderaQuery.setFilter(kunderaQuery.getEntityAlias() + \".\" + columnName + \" = \" + primaryKey);\n            queue.clear();\n            queue.add(filterClause);\n            List<Object> object = findUsingLucene(m, client);\n            if (object != null && !object.isEmpty())\n                result.add(object.get(0));\n        }\n        return result;\n    }\n\n    /**\n     * Populate using lucene.\n     * \n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @param result\n     *            the result\n     * @param columnsToSelect\n     *            List of column names to be selected (rest should be ignored)\n     * @return the list\n     */\n    protected List<Object> populateUsingLucene(EntityMetadata m, Client client, List<Object> result,\n            String[] columnsToSelect)\n    {\n        Set<Object> uniquePKs = null;\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        if (client.getIndexManager().getIndexer().getClass().getName().equals(IndexingConstants.LUCENE_INDEXER))\n        {\n            String luceneQ = KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata);\n\n            Map<String, Object> searchFilter = client.getIndexManager().search(m.getEntityClazz(), luceneQ,\n                    Constants.INVALID, Constants.INVALID);\n            // Map<String, Object> searchFilter =\n            // client.getIndexManager().search(kunderaMetadata, kunderaQuery,\n            // persistenceDelegeator, m);\n            boolean isEmbeddedId = metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType());\n\n            if (isEmbeddedId)\n            {\n                return populateEmbeddedIdUsingLucene(m, client, result, searchFilter, metaModel);\n            }\n\n            Object[] primaryKeys = searchFilter.values().toArray(new Object[] {});\n            // Object[] primaryKeys =\n            // ((List)searchFilter.get(\"primaryKeys\")).toArray(new Object[] {});\n\n            uniquePKs = new HashSet<Object>(Arrays.asList(primaryKeys));\n            return findUsingLucene(m, client, uniquePKs.toArray());\n        }\n        else\n        {\n            return populateUsingElasticSearch(client, m);\n\n        }\n\n    }\n\n    /**\n     * Populate using elastic search.\n     * \n     * @param client\n     *            the client\n     * @param EntityMetadata\n     *            the m\n     * @return Result list by fetching from ES\n     */\n    private List populateUsingElasticSearch(Client client, EntityMetadata m)\n    {\n        Map<String, Object> searchFilter = client.getIndexManager().search(kunderaMetadata, kunderaQuery,\n                persistenceDelegeator, m, this.firstResult, this.maxResult);\n        Object[] primaryKeys = ((Map<String, Object>) searchFilter.get(Constants.PRIMARY_KEYS)).values().toArray(\n                new Object[] {});\n        Map<String, Object> aggregations = (Map<String, Object>) searchFilter.get(Constants.AGGREGATIONS);\n\n        Iterable<Expression> resultOrderIterable = (Iterable<Expression>) searchFilter\n                .get(Constants.SELECT_EXPRESSION_ORDER);\n        List<Object> results = new ArrayList<Object>();\n\n        if (!kunderaQuery.isAggregated())\n        {\n            results.addAll(findUsingLucene(m, client, primaryKeys));\n        }\n        else\n        {\n            if (KunderaQueryUtils.hasGroupBy(kunderaQuery.getJpqlExpression()))\n            {\n                populateGroupByResponse(aggregations, resultOrderIterable, results, client, m);\n            }\n            else\n            {\n                Iterator<Expression> resultOrder = resultOrderIterable.iterator();\n                while (resultOrder.hasNext())\n                {\n                    Expression expression = (Expression) resultOrder.next();\n\n                    if (AggregateFunction.class.isAssignableFrom(expression.getClass()))\n                    {\n                        if (aggregations.get(expression.toParsedText()) != null)\n                        {\n                            results.add(aggregations.get(expression.toParsedText()));\n                        }\n                    }\n                    else\n                    {\n                        results.addAll(findUsingLucene(m, client, new Object[] { primaryKeys[0] }));\n                    }\n                }\n            }\n        }\n\n        return results;\n    }\n\n    /**\n     * Populate group by response.\n     * \n     * @param aggregations\n     *            the aggregations\n     * @param resultOrderIterable\n     *            the result order iterable\n     * @param results\n     *            the results\n     * @param client\n     *            the client\n     * @param m\n     *            the m\n     */\n    private void populateGroupByResponse(Map<String, Object> aggregations, Iterable<Expression> resultOrderIterable,\n            List<Object> results, Client client, EntityMetadata m)\n    {\n        List temp;\n        Object entity = null;\n        for (String entry : aggregations.keySet())\n        {\n            entity = null;\n            Object obj = aggregations.get(entry);\n            temp = new ArrayList<>();\n            Iterator<Expression> resultOrder = resultOrderIterable.iterator();\n            while (resultOrder.hasNext())\n            {\n                Expression expression = (Expression) resultOrder.next();\n\n                if (AggregateFunction.class.isAssignableFrom(expression.getClass()))\n                {\n                    if (((Map) obj).get(expression.toParsedText()) != null)\n                    {\n                        temp.add(((Map) obj).get(expression.toParsedText()));\n                    }\n                }\n                else\n                {\n                    if (entity == null)\n                    {\n                        entity = findUsingLucene(m, client, new Object[] { entry }).get(0);\n                    }\n                    temp.add(getEntityFieldValue(m, entity, expression.toParsedText()));\n                }\n            }\n            results.add(temp.size() == 1 ? temp.get(0) : temp);\n        }\n    }\n\n    /**\n     * Gets the entity field value.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @param field\n     *            the field\n     * @return the entity field value\n     */\n    private Object getEntityFieldValue(EntityMetadata entityMetadata, Object entity, String field)\n    {\n        Class clazz = entityMetadata.getEntityClazz();\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(clazz);\n\n        if (field.indexOf(\".\") > 0 && entityMetadata.getEntityClazz().equals(entity.getClass()))\n        {\n            String fieldName = field.substring(field.indexOf(\".\") + 1, field.length());\n            Attribute attribute = entityType.getAttribute(fieldName);\n            return PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());\n        }\n        else\n        {\n            // for hbase v2 client (sends arraylist for specific fields)\n            if (entity instanceof ArrayList)\n            {\n                Object element = ((ArrayList) entity).get(0);\n                ((ArrayList) entity).remove(0);\n                return element;\n            }\n            else\n            {\n                return entity;\n            }\n        }\n    }\n\n    /**\n     * Populate entities, Method to populate data in case no relation exist!.\n     * \n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @return the list\n     */\n    protected abstract List<Object> populateEntities(EntityMetadata m, Client client);\n\n    /**\n     * Find using lucene.\n     * \n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @return the list\n     */\n    protected abstract List findUsingLucene(EntityMetadata m, Client client);\n\n    /**\n     * Recursively populate entities.\n     * \n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @return the list\n     */\n    protected abstract List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client);\n\n    /**\n     * Method returns entity reader.\n     * \n     * @return entityReader entity reader.\n     */\n    protected abstract EntityReader getReader();\n\n    /**\n     * Method to be invoked on query.executeUpdate().\n     * \n     * @return the int\n     */\n    protected abstract int onExecuteUpdate();\n\n    /**\n     * Returns entity metadata, in case of native query mapped class is present\n     * within application metadata.\n     * \n     * @return entityMetadata entity metadata.\n     */\n    protected EntityMetadata getEntityMetadata()\n    {\n        return kunderaQuery.getEntityMetadata();\n    }\n\n    /**\n     * On update delete event.\n     * \n     * @return the int\n     */\n    protected int onUpdateDeleteEvent()\n    {\n        if (kunderaQuery.isDeleteUpdate())\n        {\n            List result = fetch();\n\n            onDeleteOrUpdate(result);\n            return result != null ? result.size() : 0;\n        }\n\n        return 0;\n\n    }\n\n    /**\n     * Performs delete or update based on query.\n     * \n     * @param results\n     *            list of objects to be merged/deleted.\n     */\n    protected void onDeleteOrUpdate(List results)\n    {\n\n        if (results != null)\n        {\n            if (!kunderaQuery.isUpdateClause())\n            {\n                // then case of delete\n                for (Object result : results)\n                {\n                    PersistenceCacheManager.addEntityToPersistenceCache(result, persistenceDelegeator,\n                            PropertyAccessorHelper.getId(result, this.getEntityMetadata()));\n\n                    persistenceDelegeator.remove(result);\n                }\n            }\n            else\n            {\n                EntityMetadata entityMetadata = getEntityMetadata();\n                for (Object result : results)\n                {\n                    PersistenceCacheManager.addEntityToPersistenceCache(result, persistenceDelegeator,\n                            PropertyAccessorHelper.getId(result, this.getEntityMetadata()));\n\n                    for (UpdateClause c : kunderaQuery.getUpdateClauseQueue())\n                    {\n                        String columnName = c.getProperty();\n                        try\n                        {\n\n                            DefaultEntityType entityType = (DefaultEntityType) kunderaMetadata.getApplicationMetadata()\n                                    .getMetamodel(entityMetadata.getPersistenceUnit())\n                                    .entity(entityMetadata.getEntityClazz());\n\n                            // That will always be attribute name.\n\n                            Attribute attribute = entityType.getAttribute(columnName);\n\n                            // TODO : catch column name.\n\n                            if (c.getValue() instanceof String)\n                            {\n                                PropertyAccessorHelper.set(result, (Field) attribute.getJavaMember(), c.getValue()\n                                        .toString());\n                            }\n                            else\n                            {\n                                PropertyAccessorHelper.set(result, (Field) attribute.getJavaMember(), c.getValue());\n                            }\n                            persistenceDelegeator.merge(result);\n                        }\n                        catch (IllegalArgumentException iax)\n                        {\n                            log.error(\"Invalid column name: \" + columnName + \" for class : \"\n                                    + entityMetadata.getEntityClazz());\n                            throw new QueryHandlerException(\"Error while executing query: \" + iax);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * *********************** Methods from {@link Query} interface\n     * ******************************.\n     * \n     * @return the single result\n     */\n\n    /* @see javax.persistence.Query#getSingleResult() */\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getSingleResult()\n     */\n    @Override\n    public Object getSingleResult()\n    {\n        // to fetch a single result form database.\n        isSingleResult = true;\n        List results = getResultList();\n        isSingleResult = false;\n        return onReturnResults(results);\n    }\n\n    /* @see javax.persistence.Query#setFirstResult(int) */\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#setFirstResult(int)\n     */\n    @Override\n    public Query setFirstResult(int startPosition)\n    {\n        this.firstResult = startPosition;\n        return this;\n    }\n\n    /*\n     * @see\n     * javax.persistence.Query#setFlushMode(javax.persistence.FlushModeType)\n     */\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.Query#setFlushMode(javax.persistence.FlushModeType)\n     */\n    @Override\n    public Query setFlushMode(FlushModeType flushMode)\n    {\n        throw new UnsupportedOperationException(\"setFlushMode is unsupported by Kundera\");\n    }\n\n    /**\n     * Sets hint name and value into hints map and returns instance of\n     * {@link Query}.\n     * \n     * @param hintName\n     *            the hint name\n     * @param value\n     *            the value\n     * @return the query\n     */\n    @Override\n    public Query setHint(String hintName, Object value)\n    {\n        hints.put(hintName, value);\n        return this;\n    }\n\n    /* @see javax.persistence.Query#setMaxResults(int) */\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#setMaxResults(int)\n     */\n    @Override\n    public Query setMaxResults(int maxResult)\n    {\n        this.maxResult = maxResult;\n        return this;\n    }\n\n    /*\n     * @see javax.persistence.Query#setParameter(java.lang.String,\n     * java.lang.Object)\n     */\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#setParameter(java.lang.String,\n     * java.lang.Object)\n     */\n    @Override\n    public Query setParameter(String name, Object value)\n    {\n        kunderaQuery.setParameter(name, value);\n        return this;\n    }\n\n    /* @see javax.persistence.Query#setParameter(int, java.lang.Object) */\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#setParameter(int, java.lang.Object)\n     */\n    @Override\n    public Query setParameter(int position, Object value)\n    {\n        kunderaQuery.setParameter(position, value);\n        return this;\n    }\n\n    /*\n     * @see javax.persistence.Query#setParameter(java.lang.String,\n     * java.util.Date, javax.persistence.TemporalType)\n     */\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#setParameter(java.lang.String,\n     * java.util.Date, javax.persistence.TemporalType)\n     */\n    @Override\n    public Query setParameter(String name, Date value, TemporalType temporalType)\n    {\n        // Purpose of temporal type is to set value based on temporal type.\n        throw new UnsupportedOperationException(\"setParameter is unsupported by Kundera\");\n    }\n\n    /*\n     * @see javax.persistence.Query#setParameter(java.lang.String,\n     * java.util.Calendar, javax.persistence.TemporalType)\n     */\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#setParameter(java.lang.String,\n     * java.util.Calendar, javax.persistence.TemporalType)\n     */\n    @Override\n    public Query setParameter(String name, Calendar value, TemporalType temporalType)\n    {\n        throw new UnsupportedOperationException(\"setParameter is unsupported by Kundera\");\n    }\n\n    /*\n     * @see javax.persistence.Query#setParameter(int, java.util.Date,\n     * javax.persistence.TemporalType)\n     */\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#setParameter(int, java.util.Date,\n     * javax.persistence.TemporalType)\n     */\n    @Override\n    public Query setParameter(int position, Date value, TemporalType temporalType)\n    {\n        throw new UnsupportedOperationException(\"setParameter is unsupported by Kundera\");\n    }\n\n    /*\n     * @see javax.persistence.Query#setParameter(int, java.util.Calendar,\n     * javax.persistence.TemporalType)\n     */\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#setParameter(int, java.util.Calendar,\n     * javax.persistence.TemporalType)\n     */\n    @Override\n    public Query setParameter(int position, Calendar value, TemporalType temporalType)\n    {\n        throw new UnsupportedOperationException(\"setParameter is unsupported by Kundera\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getMaxResults()\n     */\n    @Override\n    public int getMaxResults()\n    {\n        return maxResult;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getFirstResult()\n     */\n    @Override\n    public int getFirstResult()\n    {\n        throw new UnsupportedOperationException(\"getFirstResult is unsupported by Kundera\");\n    }\n\n    /**\n     * Returns a {@link Map} containing query hints set by user.\n     * \n     * @return the hints\n     */\n    @Override\n    public Map<String, Object> getHints()\n    {\n        return hints;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#setParameter(javax.persistence.Parameter,\n     * java.lang.Object)\n     */\n    @Override\n    public <T> Query setParameter(Parameter<T> paramParameter, T paramT)\n    {\n        if (!getParameters().contains(paramParameter))\n        {\n            throw new IllegalArgumentException(\"parameter does not correspond to a parameter of the query\");\n        }\n\n        if (paramParameter.getName() != null)\n        {\n            kunderaQuery.setParameter(paramParameter.getName(), paramT);\n        }\n        else\n        {\n            kunderaQuery.setParameter(paramParameter.getPosition(), paramT);\n        }\n\n        return this;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#setParameter(javax.persistence.Parameter,\n     * java.util.Calendar, javax.persistence.TemporalType)\n     */\n    @Override\n    public Query setParameter(Parameter<Calendar> paramParameter, Calendar paramCalendar, TemporalType paramTemporalType)\n    {\n        throw new UnsupportedOperationException(\"setParameter is unsupported by Kundera\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#setParameter(javax.persistence.Parameter,\n     * java.util.Date, javax.persistence.TemporalType)\n     */\n    @Override\n    public Query setParameter(Parameter<Date> paramParameter, Date paramDate, TemporalType paramTemporalType)\n    {\n        throw new UnsupportedOperationException(\"setParameter is unsupported by Kundera\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameters()\n     */\n    @Override\n    public Set<Parameter<?>> getParameters()\n    {\n        if (parameters == null)\n        {\n            parameters = kunderaQuery.getParameters();\n            if (parameters == null)\n            {\n                parameters = new HashSet<Parameter<?>>();\n            }\n        }\n\n        return parameters;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameter(java.lang.String)\n     */\n    @Override\n    public Parameter<?> getParameter(String paramString)\n    {\n        onNativeCondition();\n        getParameters();\n        return getParameterByName(paramString);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameter(java.lang.String,\n     * java.lang.Class)\n     */\n    @Override\n    public <T> Parameter<T> getParameter(String paramString, Class<T> paramClass)\n    {\n        onNativeCondition();\n        Parameter parameter = getParameterByName(paramString);\n        return onTypeCheck(paramClass, parameter);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameter(int)\n     */\n    @Override\n    public Parameter<?> getParameter(int paramInt)\n    {\n        onNativeCondition();\n        getParameters();\n        return getParameterByOrdinal(paramInt);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameter(int, java.lang.Class)\n     */\n    @Override\n    public <T> Parameter<T> getParameter(int paramInt, Class<T> paramClass)\n    {\n        onNativeCondition();\n        getParameters();\n        Parameter parameter = getParameterByOrdinal(paramInt);\n        return onTypeCheck(paramClass, parameter);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#isBound(javax.persistence.Parameter)\n     */\n    @Override\n    public boolean isBound(Parameter<?> paramParameter)\n    {\n        return kunderaQuery.isBound(paramParameter);\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * javax.persistence.Query#getParameterValue(javax.persistence.Parameter)\n     */\n    @Override\n    public <T> T getParameterValue(Parameter<T> paramParameter)\n    {\n        Object value = kunderaQuery.getClauseValue(paramParameter);\n        if (value == null)\n        {\n            throw new IllegalStateException(\"parameter has not been bound\" + paramParameter);\n        }\n        return (T) value;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameterValue(java.lang.String)\n     */\n    @Override\n    public Object getParameterValue(String paramString)\n    {\n\n        return onParameterValue(\":\" + paramString);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getParameterValue(int)\n     */\n    @Override\n    public Object getParameterValue(int paramInt)\n    {\n        return onParameterValue(\"?\" + paramInt);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getFlushMode()\n     */\n    @Override\n    public FlushModeType getFlushMode()\n    {\n        throw new UnsupportedOperationException(\"getFlushMode is unsupported by Kundera\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#setLockMode(javax.persistence.LockModeType)\n     */\n    @Override\n    public Query setLockMode(LockModeType paramLockModeType)\n    {\n        throw new UnsupportedOperationException(\"setLockMode is unsupported by Kundera\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#getLockMode()\n     */\n    @Override\n    public LockModeType getLockMode()\n    {\n        throw new UnsupportedOperationException(\"getLockMode is unsupported by Kundera\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see javax.persistence.Query#unwrap(java.lang.Class)\n     */\n    @Override\n    public <T> T unwrap(Class<T> paramClass)\n    {\n        try\n        {\n            return (T) this;\n        }\n        catch (ClassCastException ccex)\n        {\n            throw new PersistenceException(\"Provider does not support the call for class type:[\" + paramClass + \"]\");\n        }\n    }\n\n    /**\n     * Returns specific parameter instance for given name.\n     * \n     * @param name\n     *            parameter name.\n     * @return parameter\n     */\n    private Parameter getParameterByName(String name)\n    {\n        if (getParameters() != null)\n        {\n            for (Parameter p : parameters)\n            {\n                if (name.equals(p.getName()))\n                {\n                    return p;\n                }\n            }\n        }\n\n        return null;\n    }\n\n    /**\n     * Returns parameter by ordinal.\n     * \n     * @param position\n     *            position\n     * @return parameter instance.\n     */\n    private Parameter getParameterByOrdinal(Integer position)\n    {\n        for (Parameter p : parameters)\n        {\n            if (position.equals(p.getPosition()))\n            {\n                return p;\n            }\n        }\n\n        return null;\n    }\n\n    /**\n     * Method to handle get/set Parameter supplied for native query.\n     */\n    private void onNativeCondition()\n    {\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\n        if (appMetadata.isNative(getJPAQuery()))\n        {\n            throw new IllegalStateException(\n                    \"invoked on a native query when the implementation does not support this use\");\n        }\n    }\n\n    /**\n     * Validated parameter's class with input paramClass. Returns back parameter\n     * if it matches, else throws an {@link IllegalArgumentException}.\n     * \n     * @param <T>\n     *            type of class.\n     * @param paramClass\n     *            expected class type.\n     * @param parameter\n     *            parameter\n     * @return parameter if it matches, else throws an\n     *         {@link IllegalArgumentException}.\n     */\n    private <T> Parameter<T> onTypeCheck(Class<T> paramClass, Parameter<T> parameter)\n    {\n        if (parameter != null && parameter.getParameterType() != null\n                && parameter.getParameterType().equals(paramClass))\n        {\n            return parameter;\n        }\n        throw new IllegalArgumentException(\n                \"The parameter of the specified name does not exist or is not assignable to the type\");\n    }\n\n    /**\n     * Returns parameter value.\n     * \n     * @param paramString\n     *            parameter as string.\n     * \n     * @return value of parameter.\n     */\n    private List<Object> onParameterValue(String paramString)\n    {\n        List<Object> value = kunderaQuery.getClauseValue(paramString);\n        if (value == null)\n        {\n            throw new IllegalStateException(\"parameter has not been bound\" + paramString);\n        }\n        return value;\n    }\n\n    /**\n     * Gets the columns.\n     * \n     * @param columns\n     *            the columns\n     * @param m\n     *            the m\n     * @return the columns\n     */\n    protected String[] getColumns(final String[] columns, final EntityMetadata m)\n    {\n        List<String> columnAsList = new ArrayList<String>();\n        if (columns != null && columns.length > 0)\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n            EntityType entity = metaModel.entity(m.getEntityClazz());\n            for (int i = 1; i < columns.length; i++)\n            {\n                if (columns[i] != null)\n                {\n                    Attribute col = entity.getAttribute(columns[i]);\n                    if (col == null)\n                    {\n                        throw new QueryHandlerException(\"column type is null for: \" + columns);\n                    }\n                    columnAsList.add(((AbstractAttribute) col).getJPAColumnName());\n                }\n            }\n        }\n        return columnAsList.toArray(new String[] {});\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.Query#setFetchSize(java.lang.Integer)\n     */\n    public void setFetchSize(Integer fetchsize)\n    {\n        this.fetchSize = fetchsize;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.Query#getFetchSize()\n     */\n    public Integer getFetchSize()\n    {\n        return this.fetchSize;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.Query#applyTTL(int)\n     */\n    public void applyTTL(int ttlInSeconds)\n    {\n        this.ttl = ttlInSeconds;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.Query#close()\n     */\n    public abstract void close();\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.Query#iterate()\n     */\n    public abstract <E> Iterator<E> iterate();\n\n    /**\n     * Handle post event callbacks.\n     * \n     */\n    protected void handlePostEvent()\n    {\n        EntityMetadata metadata = getEntityMetadata();\n        if (!kunderaQuery.isDeleteUpdate())\n        {\n            persistenceDelegeator.getEventDispatcher().fireEventListeners(metadata, null, PostLoad.class);\n        }\n    }\n\n    /**\n     * Returns collection of fetched entities.\n     * \n     * @return the list\n     */\n    protected List fetch()\n    {\n        EntityMetadata metadata = getEntityMetadata();\n        Client client = persistenceDelegeator.getClient(metadata);\n        List results = isRelational(metadata) ? recursivelyPopulateEntities(metadata, client) : populateEntities(\n                metadata, client);\n        return results;\n    }\n\n    /**\n     * On validate single result.\n     * \n     * @param results\n     *            the results\n     */\n    protected void onValidateSingleResult(List results)\n    {\n        if (results == null || results.isEmpty())\n        {\n            log.error(\"No result found for {} \", kunderaQuery.getJPAQuery());\n            throw new NoResultException(\"No result found!\");\n        }\n\n        if (results.size() > 1)\n        {\n            log.error(\"Non unique results found for query {} \", kunderaQuery.getJPAQuery());\n            throw new NonUniqueResultException(\"Containing more than one result!\");\n        }\n\n    }\n\n    /**\n     * On return results.\n     * \n     * @param results\n     *            the results\n     * @return the object\n     */\n    protected Object onReturnResults(List results)\n    {\n        onValidateSingleResult(results);\n        return results.get(0);\n    }\n\n    /**\n     * Returns true, if associated entity holds relational references(e.g. @OneToMany\n     * etc.) else false.\n     * \n     * @param m\n     *            entity metadata\n     * \n     * @return true, if holds relation else false\n     */\n    private boolean isRelational(EntityMetadata m)\n    {\n        // if related via join table OR contains relations.\n        return m.isRelationViaJoinTable() || (m.getRelationNames() != null && (!m.getRelationNames().isEmpty()));\n    }\n\n    /**\n     * If returned collection of object holds a reference to.\n     * \n     * @param results\n     *            the results\n     */\n    private void assignReferenceToProxy(List results)\n    {\n        if (results != null)\n        {\n            for (Object obj : results)\n            {\n                kunderaMetadata.getCoreMetadata().getLazyInitializerFactory().setProxyOwners(getEntityMetadata(), obj);\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/query/QueryResolver.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.query;\r\n\r\nimport java.lang.reflect.Constructor;\r\nimport java.lang.reflect.Field;\r\nimport java.lang.reflect.InvocationTargetException;\r\n\r\nimport javax.persistence.Query;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.Constants;\r\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\r\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\nimport com.impetus.kundera.persistence.PersistenceDelegator;\r\n\r\n/**\r\n * The Class QueryResolver.\r\n * \r\n * @author amresh.singh\r\n * \r\n */\r\npublic class QueryResolver\r\n{\r\n\r\n    /** The log. */\r\n    private static Logger log = LoggerFactory.getLogger(QueryResolver.class);\r\n\r\n    /**\r\n     * Gets the query implementation.\r\n     * \r\n     * @param jpaQuery\r\n     *            the jpa query\r\n     * @param persistenceDelegator\r\n     *            the persistence delegator\r\n     * @param persistenceUnits\r\n     *            the persistence units\r\n     * @return the query implementation\r\n     */\r\n    public Query getQueryImplementation(String jpaQuery, PersistenceDelegator persistenceDelegator, Class mappedClass,\r\n            boolean isNative, final KunderaMetadata kunderaMetadata)\r\n    {\r\n        if (jpaQuery == null)\r\n        {\r\n            throw new QueryHandlerException(\"Query String should not be null \");\r\n        }\r\n\r\n        if (jpaQuery.trim().endsWith(Constants.SEMI_COLON))\r\n        {\r\n            throw new QueryHandlerException(\"unexpected char: ';' in query [ \" + jpaQuery + \" ]\");\r\n        }\r\n\r\n        KunderaQuery kunderaQuery = null;\r\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\r\n        String mappedQuery = appMetadata.getQuery(jpaQuery);\r\n\r\n        isNative = mappedQuery != null ? appMetadata.isNative(jpaQuery) : isNative;\r\n\r\n        EntityMetadata m = null;\r\n\r\n        // In case of named native query\r\n        if (!isNative)\r\n        {\r\n            kunderaQuery = new KunderaQuery(mappedQuery != null ? mappedQuery : jpaQuery, kunderaMetadata);\r\n            KunderaQueryParser parser = new KunderaQueryParser(kunderaQuery);\r\n\r\n            parser.parse();\r\n\r\n            kunderaQuery.postParsingInit();\r\n            m = kunderaQuery.getEntityMetadata();\r\n        }\r\n        else\r\n        {\r\n            // Means if it is a namedNativeQuery.\r\n            if (appMetadata.isNative(jpaQuery))\r\n            {\r\n                mappedClass = appMetadata.getMappedClass(jpaQuery);\r\n            }\r\n\r\n            kunderaQuery = new KunderaQuery(jpaQuery, kunderaMetadata);\r\n\r\n            kunderaQuery.isNativeQuery = true;\r\n\r\n            m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, mappedClass);\r\n\r\n            Field entityClazzField = null;\r\n            try\r\n            {\r\n                entityClazzField = kunderaQuery.getClass().getDeclaredField(\"entityClass\");\r\n                if (entityClazzField != null && !entityClazzField.isAccessible())\r\n                {\r\n                    entityClazzField.setAccessible(true);\r\n                }\r\n\r\n                entityClazzField.set(kunderaQuery, mappedClass);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                log.error(e.getMessage());\r\n                throw new QueryHandlerException(e);\r\n            }\r\n        }\r\n\r\n        Query query = null;\r\n\r\n        try\r\n        {\r\n            query = getQuery(jpaQuery, persistenceDelegator, m, kunderaQuery, kunderaMetadata);\r\n        }\r\n        catch (Exception e)\r\n        {\r\n            log.error(e.getMessage());\r\n            throw new QueryHandlerException(e);\r\n        }\r\n        return query;\r\n    }\r\n\r\n    /**\r\n     * Gets the query instance.\r\n     * \r\n     * @param jpaQuery\r\n     *            the jpa query\r\n     * @param persistenceDelegator\r\n     *            the persistence delegator\r\n     * @param persistenceUnits\r\n     *            the persistence units\r\n     * @return the query\r\n     * @throws ClassNotFoundException\r\n     *             the class not found exception\r\n     * @throws SecurityException\r\n     *             the security exception\r\n     * @throws NoSuchMethodException\r\n     *             the no such method exception\r\n     * @throws IllegalArgumentException\r\n     *             the illegal argument exception\r\n     * @throws InstantiationException\r\n     *             the instantiation exception\r\n     * @throws IllegalAccessException\r\n     *             the illegal access exception\r\n     * @throws InvocationTargetException\r\n     *             the invocation target exception\r\n     */\r\n    private Query getQuery(String jpaQuery, PersistenceDelegator persistenceDelegator, EntityMetadata m,\r\n            KunderaQuery kunderaQuery, final KunderaMetadata kunderaMetadata) throws ClassNotFoundException,\r\n            SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException,\r\n            IllegalAccessException, InvocationTargetException\r\n    {\r\n        Query query;\r\n\r\n        Class clazz = persistenceDelegator.getClient(m).getQueryImplementor();\r\n\r\n        @SuppressWarnings(\"rawtypes\")\r\n        Constructor constructor = clazz.getConstructor(KunderaQuery.class, PersistenceDelegator.class,\r\n                KunderaMetadata.class);\r\n        query = (Query) constructor.newInstance(kunderaQuery, persistenceDelegator, kunderaMetadata);\r\n\r\n        return query;\r\n    }\r\n\r\n    /**\r\n     * \r\n     * @param jpaQuery\r\n     * @param queryClazz\r\n     * @param persistenceDelegator\r\n     * @param metadata\r\n     * @return\r\n     */\r\n    public Query getQueryImplementation(String jpaQuery, Class queryClazz,\r\n            final PersistenceDelegator persistenceDelegator, EntityMetadata metadata, String persistenceUnit)\r\n    {\r\n        KunderaQuery kunderaQuery = new KunderaQuery(jpaQuery, persistenceDelegator.getKunderaMetadata());\r\n        kunderaQuery.isNativeQuery = true;\r\n        kunderaQuery.setPersistenceUnit(persistenceUnit);\r\n\r\n        try\r\n        {\r\n            if (metadata != null)\r\n            {\r\n                Field entityClazzField = kunderaQuery.getClass().getDeclaredField(\"entityClass\");\r\n                if (entityClazzField != null && !entityClazzField.isAccessible())\r\n                {\r\n                    entityClazzField.setAccessible(true);\r\n                }\r\n\r\n                entityClazzField.set(kunderaQuery, metadata.getEntityClazz());\r\n            }\r\n        }\r\n        catch (Exception e)\r\n        {\r\n            log.error(e.getMessage());\r\n            throw new QueryHandlerException(e);\r\n        }\r\n\r\n        Query query = null;\r\n\r\n        try\r\n        {\r\n            Constructor constructor = queryClazz.getConstructor(KunderaQuery.class, PersistenceDelegator.class,\r\n                    KunderaMetadata.class);\r\n            query = (Query) constructor.newInstance(kunderaQuery, persistenceDelegator,\r\n                    persistenceDelegator.getKunderaMetadata());\r\n        }\r\n        catch (Exception e)\r\n        {\r\n            log.error(e.getMessage());\r\n            throw new QueryHandlerException(e);\r\n        }\r\n        return query;\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/service/Host.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.service;\n\nimport com.impetus.kundera.service.policy.LoadBalancingPolicy;\n\n/**\n * Host interface all module will implement it in order to provide\n * {@link LoadBalancingPolicy }.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic interface Host\n{\n    /**\n     * \n     * @return host.\n     */\n    String getHost();\n\n    /**\n     * \n     * @return port.\n     */\n    int getPort();\n\n    /**\n     * @return the maxTotal\n     */\n    int getMaxTotal();\n\n    /**\n     * @return the maxActive\n     */\n    int getMaxActive();\n\n    /**\n     * @return the maxIdle\n     */\n    int getMaxIdle();\n\n    /**\n     * @return the minIdle\n     */\n    int getMinIdle();\n\n    /**\n     * \n     * @return true/false.\n     */\n    public boolean isRetryHost();\n\n    /**\n     * @return the Username\n     */\n    String getUser();\n\n    /**\n     * @return the Username\n     */\n    String getPassword();\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/service/HostConfiguration.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.service;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.concurrent.CopyOnWriteArrayList;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection.Server;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * Configure host name and port and build Hosts array.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic abstract class HostConfiguration\n{\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(HostConfiguration.class);\n\n    /** Delay time for host retry */\n    protected int retryDelay = 100;\n\n    /**\n     * Persistence unit metadata.\n     */\n    protected PersistenceUnitMetadata persistenceUnitMetadata;\n\n    protected Properties connectionProperties = new Properties();\n\n    /**\n     * External configuration passed at the time of emf creation.\n     */\n    protected Map externalProperties;\n\n    /**\n     * Array of hosts.\n     */\n    protected List<Host> hostsList = new CopyOnWriteArrayList<Host>();\n\n    public HostConfiguration(Map externalProperties, List<Server> servers, String persistenceUnit,\n            final KunderaMetadata kunderaMetadata)\n    {\n        buildHosts(externalProperties, servers, persistenceUnit, kunderaMetadata);\n    }\n\n    /**\n     * Build host array.\n     * \n     * @param externalProperties\n     * @param servers\n     * @param persistenceUnit\n     */\n    private void buildHosts(Map externalProperties, List<Server> servers, String persistenceUnit,\n            final KunderaMetadata kunderaMetadata)\n    {\n        persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit);\n        Properties props = persistenceUnitMetadata.getProperties();\n        this.externalProperties = externalProperties;\n        String hosts = null;\n        String portAsString = null;\n\n        if (externalProperties != null)\n        {\n            hosts = (String) externalProperties.get(PersistenceProperties.KUNDERA_NODES);\n            portAsString = (String) externalProperties.get(PersistenceProperties.KUNDERA_PORT);\n        }\n        if (hosts == null)\n        {\n            hosts = (String) props.get(PersistenceProperties.KUNDERA_NODES);\n        }\n        if (portAsString == null)\n        {\n            portAsString = (String) props.get(PersistenceProperties.KUNDERA_PORT);\n        }\n\n        if (hosts != null && portAsString != null)\n        {\n            buildHosts(hosts, portAsString, this.hostsList);\n        }\n        else if (servers != null && servers.size() >= 1)\n        {\n            buildHosts(servers, this.hostsList);\n        }\n    }\n\n    /**\n     * Validate host and port.\n     * \n     * @param host\n     * @param port\n     */\n    protected void onValidation(final String host, final String port)\n    {\n        if (host == null || !StringUtils.isNumeric(port) || port.isEmpty())\n        {\n            logger.error(\"Host or port should not be null / port should be numeric.\");\n            throw new IllegalArgumentException(\"Host or port should not be null / port should be numeric.\");\n        }\n    }\n\n    /**\n     * \n     * @return Array of hosts.\n     */\n    public List<Host> getHosts()\n    {\n        return hostsList;\n    }\n\n    protected abstract void buildHosts(List<Server> servers, List<Host> hostsList);\n\n    protected abstract void buildHosts(String hosts, String portAsString, List<Host> hostsList);\n\n    protected abstract void setConfig(Host host, Properties props, Map puProperties);\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/service/policy/LeastActiveBalancingPolicy.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.service.policy;\n\nimport java.util.Collection;\n\n/**\n * Abstract class leastActiveBalancingPolicy, all client factory will have a class which will extends it\n * in order to support least active load.\n * balancing policy.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic abstract class LeastActiveBalancingPolicy implements LoadBalancingPolicy\n{\n\n    /**\n     * @return pool object for host which has least active connections.\n     * \n     */\n    @Override\n    public abstract Object getPool(Collection<Object> pools);\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/service/policy/LoadBalancingPolicy.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.service.policy;\n\nimport java.util.Collection;\n\n/**\n * LoadBalancing policy interface for {@link RoundRobinBalancingPolicy} and {@link LeastActiveBalancingPolicy}.\n * \n * @author Kuldeep.mishra\n *\n */\npublic interface LoadBalancingPolicy\n{\n\n    /**\n     * Returns pool on the basis of loadbalancing policy.\n     * \n     * @param pools\n     * @param excludeHosts\n     * @return pool object.\n     */\n    Object getPool(Collection<Object> pools);\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/service/policy/RetryService.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.service.policy;\n\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ScheduledFuture;\n\nimport com.impetus.kundera.service.Host;\nimport com.impetus.kundera.utils.KunderaThreadFactory;\n\npublic abstract class RetryService\n{\n\n    protected final ScheduledExecutorService executor;\n\n    protected ScheduledFuture<?> sf;\n\n    protected int retryDelayInSeconds = 100;\n\n    public RetryService(int retryDelay)\n    {\n        if (retryDelay > 0)\n        {\n            this.retryDelayInSeconds = retryDelay;\n        }\n        this.executor = Executors.newScheduledThreadPool(1, new KunderaThreadFactory(RetryService.class.getName()));\n    }\n\n    protected abstract boolean verifyConnection(Host host);\n\n    public abstract void shutdown();\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/service/policy/RoundRobinBalancingPolicy.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.service.policy;\n\nimport java.util.Collection;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * RoundRobinBalancingPolicy returns pool using round robin algorithm.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic final class RoundRobinBalancingPolicy implements LoadBalancingPolicy\n{\n\n    private int counter;\n\n    public RoundRobinBalancingPolicy()\n    {\n        counter = 0;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.policy.LoadBalancingPolicy#getPool(java.util.Collection\n     * , java.util.Set)\n     */\n    @Override\n    public Object getPool(Collection<Object> pools)\n    {\n        try\n        {\n            return Iterables.get(pools, getAndIncrement(pools.size()));\n        }\n        catch (IndexOutOfBoundsException e)\n        {\n            return pools.iterator().next();\n        }\n    }\n\n    private int getAndIncrement(int size)\n    {\n        int counterToReturn;\n        synchronized (this)\n        {\n            if (counter >= 16384)\n            {\n                counter = 0;\n            }\n            counterToReturn = counter++;\n        }\n\n        return counterToReturn % size;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/DeepEquals.java",
    "content": "/*******************************************************************************\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.utils;\n\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedMap;\nimport java.util.SortedSet;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport javax.persistence.ManyToMany;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.OneToMany;\nimport javax.persistence.OneToOne;\n\nimport com.impetus.kundera.proxy.ProxyHelper;\nimport com.impetus.kundera.proxy.collection.ProxyCollection;\n\n/**\n * Deeply compare two (2) objects. This method will call any overridden equals()\n * methods if they exist. If not, it will then proceed to do a field-by-field\n * comparison, and when a non-primitive field is encountered, recursively\n * continue the deep comparison. When an array is found, it will also ensure\n * that the array contents are deeply equal, not requiring the array instance\n * (container) to be identical. This method will successfully compare object\n * graphs that have cycles (A->B->C->A). There is no need to ever use the\n * Arrays.deepEquals() method as this is a true and more effective super set. *\n * \n * @author John DeRegnaucourt\n */\npublic class DeepEquals\n{\n    private static final Map<Class, Boolean> _customEquals = new ConcurrentHashMap<Class, Boolean>();\n\n    private static final Map<Class, Boolean> _customHash = new ConcurrentHashMap<Class, Boolean>();\n\n    private static final Map<Class, Collection<Field>> _reflectedFields = new ConcurrentHashMap<Class, Collection<Field>>();\n\n    private static class DualKey\n    {\n        private Object _key1;\n\n        private Object _key2;\n\n        private DualKey()\n        {\n        }\n\n        private DualKey(Object k1, Object k2)\n        {\n            _key1 = k1;\n            _key2 = k2;\n        }\n\n        public boolean equals(Object other)\n        {\n            if (other == null)\n            {\n                return false;\n            }\n\n            if (!(other instanceof DualKey))\n            {\n                return false;\n            }\n\n            DualKey that = (DualKey) other;\n            return _key1 == that._key1 && _key2 == that._key2;\n        }\n\n        public int hashCode()\n        {\n            int h1 = _key1 != null ? _key1.hashCode() : 0;\n            int h2 = _key2 != null ? _key2.hashCode() : 0;\n            return h1 + h2;\n        }\n    }\n\n    public static boolean deepEquals(Object a, Object b)\n    {\n        Set<DualKey> visited = new HashSet<DualKey>();\n        return deepEquals(a, b, visited);\n    }\n\n    private static boolean deepEquals(Object a, Object b, Set<DualKey> visited)\n    {\n        LinkedList<DualKey> stack = new LinkedList<DualKey>();\n        stack.addFirst(new DualKey(a, b));\n\n        while (!stack.isEmpty())\n        {\n            DualKey dualKey = stack.removeFirst();\n            visited.add(dualKey);\n\n            if (dualKey._key1 == null || dualKey._key2 == null)\n            {\n                if (dualKey._key1 != dualKey._key2)\n                {\n                    return false;\n                }\n                continue;\n            }\n\n            if (!dualKey._key1.getClass().equals(dualKey._key2.getClass()))\n            {\n                return false;\n            }\n\n            // Handle all [] types. In order to be equal, the arrays must be the\n            // same length, be of the same type, be in the same order, and all\n            // elements within the array must be deeply equivalent.\n            if (dualKey._key1.getClass().isArray())\n            {\n                if (dualKey._key1.getClass().isAssignableFrom(byte[].class))\n                {\n                    if (!Arrays.equals(((byte[]) dualKey._key1), ((byte[]) dualKey._key2)))\n                        return false;\n                }\n\n                else\n                {\n                    int len = Array.getLength(dualKey._key1);\n                    if (len != Array.getLength(dualKey._key2))\n                    {\n                        return false;\n                    }\n\n                    for (int i = 0; i < len; i++)\n                    {\n                        DualKey dk = new DualKey(Array.get(dualKey._key1, i), Array.get(dualKey._key2, i));\n                        if (!visited.contains(dk))\n                        {\n                            stack.addFirst(dk);\n                        }\n                    }\n                }\n                continue;\n            }\n\n            // Special handle SortedSets because they are fast to compare\n            // because their\n            // elements must be in the same order to be equivalent Sets.\n            if (dualKey._key1 instanceof SortedSet)\n            {\n                if (!compareOrdered(dualKey, stack, visited))\n                {\n                    return false;\n                }\n                continue;\n            }\n\n            // Handled unordered Sets. This is an expensive comparison because\n            // order cannot\n            // be assumed, therefore it runs in O(n^2) when the Sets are the\n            // same length.\n            if (dualKey._key1 instanceof Set)\n            {\n                if (!compareUnordered((Set) dualKey._key1, (Set) dualKey._key2, visited))\n                {\n                    return false;\n                }\n                continue;\n            }\n\n            // Check any Collection that is not a Set. In these cases, element\n            // order\n            // matters, therefore this comparison is faster than using unordered\n            // comparison.\n            if (dualKey._key1 instanceof Collection)\n            {\n                if (!compareOrdered(dualKey, stack, visited))\n                {\n                    return false;\n                }\n                continue;\n            }\n\n            // Compare two SortedMaps. This takes advantage of the fact that\n            // these\n            // Maps can be compared in O(N) time due to their ordering.\n            if (dualKey._key1 instanceof SortedMap)\n            {\n                Map map1 = (Map) dualKey._key1;\n                Map map2 = (Map) dualKey._key2;\n\n                if (map1.size() != map2.size())\n                {\n                    return false;\n                }\n\n                Iterator i1 = map1.entrySet().iterator();\n                Iterator i2 = map2.entrySet().iterator();\n\n                while (i1.hasNext())\n                {\n                    Map.Entry entry1 = (Map.Entry) i1.next();\n                    Map.Entry entry2 = (Map.Entry) i2.next();\n\n                    DualKey dk = new DualKey(entry1.getKey(), entry2.getKey());\n                    if (!visited.contains(dk))\n                    { // Keys must match\n                        stack.addFirst(dk);\n                    }\n\n                    dk = new DualKey(entry1.getValue(), entry2.getValue());\n                    if (!visited.contains(dk))\n                    { // Values must match\n                        stack.addFirst(dk);\n                    }\n                }\n\n                continue;\n            }\n\n            // Compare two Unordered Maps. This works in O(N^2) time.\n            if (dualKey._key1 instanceof Map)\n            {\n                Map<Object, Object> map1 = (Map) dualKey._key1;\n                Map<Object, Object> map2 = (Map) dualKey._key2;\n\n                if (map1.size() != map2.size())\n                {\n                    return false;\n                }\n\n                for (Map.Entry entry1 : map1.entrySet())\n                {\n                    Map.Entry saveEntry2 = null;\n                    for (Map.Entry entry2 : map2.entrySet())\n                    { // recurse here\n                      // (yes, that\n                      // makes this a\n                      // Stack-based\n                      // implementation\n                      // with partial\n                      // recursion in\n                      // the case of\n                      // Map keys).\n                        if (deepEquals(entry1.getKey(), entry2.getKey(), visited))\n                        {\n                            saveEntry2 = entry2;\n                            break;\n                        }\n                    }\n\n                    if (saveEntry2 == null)\n                    {\n                        return false;\n                    }\n\n                    // Defer value comparisons to future iterations.\n                    DualKey dk = new DualKey(entry1.getValue(), saveEntry2.getValue());\n                    if (!(visited instanceof ProxyCollection) && !visited.contains(dk))\n                    {\n                        stack.addFirst(dk);\n                    }\n                }\n\n                continue;\n            }\n\n            if (hasCustomEquals(dualKey._key1.getClass()))\n            {\n                if (!dualKey._key1.equals(dualKey._key2))\n                {\n                    return false;\n                }\n                continue;\n            }\n\n            Collection<Field> fields = getDeepDeclaredFields(dualKey._key1.getClass());\n\n            for (Field field : fields)\n            {\n                try\n                {\n                    DualKey dk = new DualKey(field.get(dualKey._key1), field.get(dualKey._key2));\n\n                    if (dk != null)\n                    {\n                        boolean isPersistentCollection = false;\n                        if (dk._key1 != null)\n                        {\n                            isPersistentCollection = ProxyHelper.isProxyCollection(dk._key1);\n                        }\n\n                        if (isPersistentCollection)\n                        {\n                            dk._key1 = null;\n                        }\n\n                        if (!isPersistentCollection && !visited.contains(dk))\n                        {\n                            if (!(field.isAnnotationPresent(OneToOne.class)\n                                    || field.isAnnotationPresent(OneToMany.class)\n                                    || field.isAnnotationPresent(ManyToOne.class) || field\n                                        .isAnnotationPresent(ManyToMany.class)))\n                            {\n                                stack.addFirst(dk);\n                            }\n                        }\n                    }\n                }\n                catch (Exception e)\n                {\n                    continue;\n                }\n            }\n        }\n\n        return true;\n    }\n\n    /**\n     * Compare two Collections that must be same length and in same order.\n     * \n     * @param dualKey\n     *            DualKey represents the two Collections to compare\n     * @param visited\n     *            Collection of objects already compared (prevents cycles)\n     * @param stack\n     *            add items to compare to the Stack (Stack versus recursion)\n     * @return boolean false if the Collections are not the same length,\n     *         otherwise place collection items on Stack to be further compared.\n     */\n    private static boolean compareOrdered(DualKey dualKey, LinkedList<DualKey> stack, Collection visited)\n    {\n        Collection col1 = (Collection) dualKey._key1;\n        Collection col2 = (Collection) dualKey._key2;\n\n        if (ProxyHelper.isProxyCollection(col1) || ProxyHelper.isProxyCollection(col2))\n        {\n            return false;\n        }\n\n        if (col1.size() != col2.size())\n        {\n            return false;\n        }\n\n        Iterator i1 = col1.iterator();\n        Iterator i2 = col2.iterator();\n\n        while (i1.hasNext())\n        {\n            DualKey dk = new DualKey(i1.next(), i2.next());\n            if (!visited.contains(dk))\n            {\n                stack.addFirst(dk);\n            }\n        }\n        return true;\n    }\n\n    /**\n     * Deeply compare the two sets referenced by dualKey. This method attempts\n     * to quickly determine inequality by length, then hash, and finally does a\n     * deepEquals on each element if the two Sets passed by the prior tests.\n     * \n     * @param col1\n     *            Collection one\n     * @param col2\n     *            Collection two\n     * @param visited\n     *            Set containing items that have already been compared, so as to\n     *            prevent cycles.\n     * @return boolean true if the Sets are deeply equals, false otherwise.\n     */\n    private static boolean compareUnordered(Collection col1, Collection col2, Set visited)\n    {\n        if (ProxyHelper.isProxyCollection(col1) || ProxyHelper.isProxyCollection(col2))\n        {\n            return false;\n        }\n\n        if (col1.size() != col2.size())\n        {\n            return false;\n        }\n\n        int h1 = deepHashCode(col1);\n        int h2 = deepHashCode(col2);\n        if (h1 != h2)\n        { // Faster than deep equals compare (O(n^2) comparison\n          // can be skipped\n          // when not equal)\n            return false;\n        }\n\n        List copy = new ArrayList(col2);\n\n        for (Object element1 : col1)\n        {\n            int len = copy.size();\n            for (int i = 0; i < len; i++)\n            { // recurse here (yes, that makes\n              // this a Stack-based implementation\n              // with\n              // partial recursion in the case of\n              // unordered Sets).\n                if (deepEquals(element1, copy.get(i), visited))\n                {\n                    copy.remove(i); // Shrink 2nd Set\n                    break;\n                }\n            }\n\n            if (len == copy.size())\n            { // Nothing found, therefore Collections\n              // are not equivalent\n                return false;\n            }\n\n        }\n\n        return true;\n    }\n\n    public static boolean hasCustomEquals(Class c)\n    {\n        Class origClass = c;\n        if (_customEquals.containsKey(c))\n        {\n            return _customEquals.get(c);\n        }\n\n        while (!Object.class.equals(c))\n        {\n            try\n            {\n                c.getDeclaredMethod(\"equals\", Object.class);\n                _customEquals.put(origClass, true);\n                return true;\n            }\n            catch (Exception ignored)\n            {\n            }\n            c = c.getSuperclass();\n        }\n        _customEquals.put(origClass, false);\n        return false;\n    }\n\n    public static int deepHashCode(Object obj)\n    {\n        Set visited = new HashSet();\n        LinkedList<Object> stack = new LinkedList<Object>();\n        stack.addFirst(obj);\n        int hash = 0;\n\n        while (!stack.isEmpty())\n        {\n            obj = stack.removeFirst();\n            if (obj == null || visited.contains(obj))\n            {\n                continue;\n            }\n\n            visited.add(obj);\n\n            if (obj.getClass().isArray())\n            {\n                int len = Array.getLength(obj);\n                for (int i = 0; i < len; i++)\n                {\n                    stack.addFirst(Array.get(obj, i));\n                }\n                continue;\n            }\n\n            if (obj instanceof Collection && !ProxyHelper.isProxyCollection(obj))\n            {\n                stack.addAll(0, (Collection) obj);\n                continue;\n            }\n\n            if (obj instanceof Map)\n            {\n                stack.addAll(0, ((Map) obj).keySet());\n                stack.addAll(0, ((Map) obj).values());\n                continue;\n            }\n\n            if (hasCustomHashCode(obj.getClass()))\n            { // A real hashCode() method\n              // exists, call it.\n                hash += obj.hashCode();\n                continue;\n            }\n\n            Collection<Field> fields = getDeepDeclaredFields(obj.getClass());\n            for (Field field : fields)\n            {\n                try\n                {\n                    stack.addFirst(field.get(obj));\n                }\n                catch (Exception ignored)\n                {\n                }\n            }\n        }\n        return hash;\n    }\n\n    public static boolean hasCustomHashCode(Class c)\n    {\n        Class origClass = c;\n        if (_customHash.containsKey(c))\n        {\n            return _customHash.get(c);\n        }\n\n        while (!Object.class.equals(c))\n        {\n            try\n            {\n                c.getDeclaredMethod(\"hashCode\");\n                _customHash.put(origClass, true);\n                return true;\n            }\n            catch (Exception ignored)\n            {\n            }\n            c = c.getSuperclass();\n        }\n        _customHash.put(origClass, false);\n        return false;\n    }\n\n    /**\n     * @param c\n     *            Class instance\n     * @return Collection of only the fields in the passed in class that would\n     *         need further processing (reference fields). This makes field\n     *         traversal on a class faster as it does not need to continually\n     *         process known fields like primitives.\n     */\n    public static Collection<Field> getDeepDeclaredFields(Class c)\n    {\n        if (_reflectedFields.containsKey(c))\n        {\n            return _reflectedFields.get(c);\n        }\n        Collection<Field> fields = new ArrayList<Field>();\n        Class curr = c;\n\n        while (curr != null)\n        {\n            try\n            {\n                Field[] local;\n                local = curr.getDeclaredFields();\n\n                for (Field field : local)\n                {\n                    if (!field.isAccessible())\n                    {\n                        try\n                        {\n                            field.setAccessible(true);\n                        }\n                        catch (Exception ignored)\n                        {\n                        }\n                    }\n\n                    int modifiers = field.getModifiers();\n                    if (!Modifier.isStatic(modifiers) && !field.getName().startsWith(\"this$\")\n                            && !Modifier.isTransient(modifiers))\n                    { // speed up:\n                      // do not\n                      // count\n                      // static\n                      // fields,\n                      // not go\n                      // back up\n                      // to\n                      // enclosing\n                      // object in\n                      // nested\n                      // case\n                        fields.add(field);\n                    }\n                }\n            }\n            catch (ThreadDeath t)\n            {\n                throw t;\n            }\n            catch (Throwable ignored)\n            {\n            }\n\n            curr = curr.getSuperclass();\n        }\n        _reflectedFields.put(c, fields);\n        return fields;\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/DefaultTimestampGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.utils;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class DefaultTimestampGenerator implements TimestampGenerator\n{\n\n    @Override\n    public long getTimestamp()\n    {\n        return System.currentTimeMillis();\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/InvalidConfigurationException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.utils;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * @author amresh\n * \n */\npublic class InvalidConfigurationException extends KunderaException\n{\n\n    /**\n\t * \n\t */\n    public InvalidConfigurationException()\n    {\n    }\n\n    /**\n     * @param paramString\n     */\n    public InvalidConfigurationException(String paramString)\n    {\n        super(paramString);\n    }\n\n    /**\n     * @param paramThrowable\n     */\n    public InvalidConfigurationException(Throwable paramThrowable)\n    {\n        super(paramThrowable);\n    }\n\n    /**\n     * @param paramString\n     * @param paramThrowable\n     */\n    public InvalidConfigurationException(String paramString, Throwable paramThrowable)\n    {\n        super(paramString, paramThrowable);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/KunderaCoreUtils.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * \n */\n\npackage com.impetus.kundera.utils;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Queue;\nimport java.util.Set;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.apache.commons.configuration.EnvironmentConfiguration;\nimport org.apache.commons.configuration.SystemConfiguration;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.proxy.ProxyHelper;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.query.LuceneQueryBuilder;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class KunderaCoreUtils\n{\n\n    private static final String COMPOSITE_KEY_SEPERATOR = \"\\001\";\n\n    private static final String LUCENE_COMPOSITE_KEY_SEPERATOR = \"_\";\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(KunderaCoreUtils.class);\n\n    /**\n     * Retrun map of external properties for given pu;\n     * \n     * @param pu\n     * @param externalProperties\n     * @param persistenceUnits\n     * @return\n     */\n    public static Map<String, Object> getExternalProperties(String pu, Map<String, Object> externalProperties,\n            String... persistenceUnits)\n    {\n        Map<String, Object> puProperty;\n        if (persistenceUnits != null && persistenceUnits.length > 1 && externalProperties != null)\n        {\n            puProperty = (Map<String, Object>) externalProperties.get(pu);\n\n            // if property found then return it, if it is null by pass it, else\n            // throw invalidConfiguration.\n            if (puProperty != null)\n            {\n                return fetchPropertyMap(puProperty);\n            }\n            return null;\n        }\n        return externalProperties;\n    }\n\n    /**\n     * @param puProperty\n     * @return\n     */\n    private static Map<String, Object> fetchPropertyMap(Map<String, Object> puProperty)\n    {\n        if (puProperty.getClass().isAssignableFrom(Map.class) || puProperty instanceof Map)\n        {\n            return puProperty;\n        }\n        else\n        {\n            throw new InvalidConfigurationException(\n                    \"For cross data store persistence, please specify as: Map {pu,Map of properties}\");\n        }\n    }\n\n    public static boolean isEmptyOrNull(Object o)\n    {\n        if (o == null)\n        {\n            return true;\n        }\n\n        if (!ProxyHelper.isProxyOrCollection(o))\n        {\n            if (PropertyAccessorHelper.isCollection(o.getClass()))\n            {\n                Collection c = (Collection) o;\n                if (c.isEmpty())\n                {\n                    return true;\n                }\n            }\n            else if (Map.class.isAssignableFrom(o.getClass()))\n            {\n                Map m = (Map) o;\n                if (m.isEmpty())\n                {\n                    return true;\n                }\n            }\n        }\n        return false;\n    }\n\n    /**\n     * Prepares composite key .\n     * \n     * @param m\n     *            entity metadata\n     * @param compositeKey\n     *            composite key instance\n     * @return redis key\n     */\n    public static String prepareCompositeKey(final EntityMetadata m, final Object compositeKey)\n    {\n        Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields();\n\n        StringBuilder stringBuilder = new StringBuilder();\n        for (Field f : fields)\n        {\n            if (!ReflectUtils.isTransientOrStatic(f))\n            {\n                try\n                {\n                    String fieldValue = PropertyAccessorHelper.getString(compositeKey, f);\n\n                    // what if field value is null????\n                    stringBuilder.append(fieldValue);\n                    stringBuilder.append(COMPOSITE_KEY_SEPERATOR);\n                }\n                catch (IllegalArgumentException e)\n                {\n                    logger.error(\"Error during prepare composite key, Caused by {}.\", e);\n                    throw new PersistenceException(e);\n                }\n            }\n        }\n\n        if (stringBuilder.length() > 0)\n        {\n            stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(COMPOSITE_KEY_SEPERATOR));\n        }\n        return stringBuilder.toString();\n    }\n\n    /**\n     * Prepares composite key as a lucene key.\n     * \n     * @param m\n     *            entity metadata\n     * @param metaModel\n     *            meta model.\n     * @param compositeKey\n     *            composite key instance\n     * @return redis key\n     */\n    public static String prepareCompositeKey(final SingularAttribute attribute, final MetamodelImpl metaModel,\n            final Object compositeKey)\n    {\n        Field[] fields = attribute.getBindableJavaType().getDeclaredFields();\n        EmbeddableType embeddable = metaModel.embeddable(attribute.getBindableJavaType());\n        StringBuilder stringBuilder = new StringBuilder();\n\n        try\n        {\n            for (Field f : fields)\n            {\n                if (!ReflectUtils.isTransientOrStatic(f))\n                {\n                    if (metaModel.isEmbeddable(((AbstractAttribute) embeddable.getAttribute(f.getName()))\n                            .getBindableJavaType()))\n                    {\n                        f.setAccessible(true);\n                        stringBuilder.append(\n                                prepareCompositeKey((SingularAttribute) embeddable.getAttribute(f.getName()),\n                                        metaModel, f.get(compositeKey))).append(LUCENE_COMPOSITE_KEY_SEPERATOR);\n                    }\n                    else\n                    {\n                        String fieldValue = PropertyAccessorHelper.getString(compositeKey, f);\n                        fieldValue = fieldValue.replaceAll(\"[^a-zA-Z0-9]\", \"_\");\n\n                        stringBuilder.append(fieldValue);\n                        stringBuilder.append(LUCENE_COMPOSITE_KEY_SEPERATOR);\n                    }\n                }\n            }\n        }\n        catch (IllegalAccessException e)\n        {\n            logger.error(e.getMessage());\n        }\n        catch (IllegalArgumentException e)\n        {\n            logger.error(\"Error during prepare composite key, Caused by {}.\", e);\n            throw new PersistenceException(e);\n        }\n\n        if (stringBuilder.length() > 0)\n        {\n            stringBuilder.deleteCharAt(stringBuilder.lastIndexOf(LUCENE_COMPOSITE_KEY_SEPERATOR));\n        }\n        return stringBuilder.toString();\n    }\n\n    /**\n     * Resolves variable in path given as string\n     * \n     * @param input\n     *            String input url Code inspired by\n     *            :http://stackoverflow.com/questions/2263929/\n     *            regarding-application-properties-file-and-environment-variable\n     */\n    public static String resolvePath(String input)\n    {\n        if (null == input)\n        {\n            return input;\n        }\n\n        // matching for 2 groups match ${VAR_NAME} or $VAR_NAME\n        Pattern pathPattern = Pattern.compile(\"\\\\$\\\\{(.+?)\\\\}\");\n        Matcher matcherPattern = pathPattern.matcher(input); // get a matcher\n                                                             // object\n        StringBuffer sb = new StringBuffer();\n        EnvironmentConfiguration config = new EnvironmentConfiguration();\n        SystemConfiguration sysConfig = new SystemConfiguration();\n\n        while (matcherPattern.find())\n        {\n\n            String confVarName = matcherPattern.group(1) != null ? matcherPattern.group(1) : matcherPattern.group(2);\n            String envConfVarValue = config.getString(confVarName);\n            String sysVarValue = sysConfig.getString(confVarName);\n\n            if (envConfVarValue != null)\n            {\n\n                matcherPattern.appendReplacement(sb, envConfVarValue);\n\n            }\n            else if (sysVarValue != null)\n            {\n\n                matcherPattern.appendReplacement(sb, sysVarValue);\n\n            }\n            else\n            {\n                matcherPattern.appendReplacement(sb, \"\");\n            }\n        }\n        matcherPattern.appendTail(sb);\n        return sb.toString();\n    }\n\n    public static int countNonSyntheticFields(Class<?> clazz)\n    {\n        int count = 0;\n        for (Field f : clazz.getDeclaredFields())\n        {\n            if (!f.isSynthetic() || !ReflectUtils.isTransientOrStatic(f))\n            {\n                count++;\n            }\n        }\n\n        return count;\n    }\n\n    /**\n     * Gets the lucene query from jpa query.\n     * \n     * @return the lucene query from jpa query\n     */\n    public static String getLuceneQueryFromJPAQuery(final KunderaQuery kunderaQuery,\n            final KunderaMetadata kunderaMetadata)\n    {\n\n        LuceneQueryBuilder queryBuilder = new LuceneQueryBuilder();\n        EntityMetadata metadata = kunderaQuery.getEntityMetadata();\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                metadata.getPersistenceUnit());\n        Class valueClazz = null;\n        EntityType entity = metaModel.entity(metadata.getEntityClazz());\n        boolean partitionKeyCheck = true;\n\n        for (Object object : kunderaQuery.getFilterClauseQueue())\n        {\n            if (object instanceof FilterClause)\n            {\n                FilterClause filter = (FilterClause) object;\n                String property = filter.getProperty();\n                String condition = filter.getCondition();\n                String valueAsString = filter.getValue().get(0).toString();\n                String fieldName = metadata.getFieldName(property);\n                boolean isEmbeddedId = metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType());\n                String idColumn = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();\n                valueClazz = getValueType(entity, fieldName);\n\n                if (isEmbeddedId)\n                {\n                    if (idColumn.equals(property))\n                    {\n                        valueAsString = prepareCompositeKey(metadata.getIdAttribute(), metaModel, filter.getValue()\n                                .get(0));\n                        queryBuilder.appendIndexName(metadata.getIndexName()).appendPropertyName(idColumn)\n                                .buildQuery(condition, valueAsString, valueClazz);\n                    }\n                    else\n                    {\n                        valueClazz = metadata.getIdAttribute().getBindableJavaType();\n                        if (property.lastIndexOf('.') != property.indexOf('.') && partitionKeyCheck)\n                        {\n                            isCompletePartitionKeyPresentInQuery(kunderaQuery.getFilterClauseQueue(), metaModel,\n                                    metadata);\n                            partitionKeyCheck = false;\n                        }\n\n                        if (metaModel.isEmbeddable(filter.getValue().get(0).getClass()))\n                        {\n                            prepareLuceneQueryForPartitionKey(queryBuilder, filter.getValue().get(0), metaModel,\n                                    metadata.getIndexName(), valueClazz);\n                        }\n                        else\n                        {\n                            property = property.substring(property.lastIndexOf(\".\") + 1);\n                            queryBuilder.appendIndexName(metadata.getIndexName())\n                                    .appendPropertyName(getPropertyName(metadata, property, kunderaMetadata))\n                                    .buildQuery(condition, valueAsString, valueClazz);\n                        }\n                    }\n                }\n                else\n                {\n                    queryBuilder.appendIndexName(metadata.getIndexName())\n                            .appendPropertyName(getPropertyName(metadata, property, kunderaMetadata))\n                            .buildQuery(condition, valueAsString, valueClazz);\n                }\n            }\n            else\n            {\n                queryBuilder.buildQuery(object.toString(), object.toString(), String.class);\n            }\n        }\n\n        queryBuilder.appendEntityName(kunderaQuery.getEntityClass().getCanonicalName().toLowerCase());\n        return queryBuilder.getQuery();\n    }\n\n    /**\n     * cheking whether all the fields of partition key are present in the jpa\n     * query\n     * \n     * @param filterQueue\n     * @param metaModel\n     * @param metadata\n     */\n    private static void isCompletePartitionKeyPresentInQuery(Queue filterQueue, MetamodelImpl metaModel,\n            EntityMetadata metadata)\n    {\n        Set<String> partitionKeyFields = new HashSet<String>();\n        populateEmbeddedIdFields(metaModel.embeddable(metadata.getIdAttribute().getBindableJavaType()).getAttributes(),\n                metaModel, partitionKeyFields);\n\n        Set<String> queryAttributes = new HashSet<String>();\n        for (Object object : filterQueue)\n        {\n            if (object instanceof FilterClause)\n            {\n                FilterClause filter = (FilterClause) object;\n                String property = filter.getProperty();\n                String filterAttr[] = property.split(\"\\\\.\");\n                for (String s : filterAttr)\n                {\n                    queryAttributes.add(s);\n                }\n            }\n        }\n        if (!queryAttributes.containsAll(partitionKeyFields))\n        {\n            throw new QueryHandlerException(\"Incomplete partition key fields in query\");\n        }\n    }\n\n    /**\n     * recursively populate all the fields present in partition key\n     * \n     * @param embeddedAttributes\n     * @param metaModel\n     * @param embeddedIdFields\n     */\n    private static void populateEmbeddedIdFields(Set<Attribute> embeddedAttributes, MetamodelImpl metaModel,\n            Set<String> embeddedIdFields)\n    {\n        for (Attribute attribute : embeddedAttributes)\n        {\n            if (!ReflectUtils.isTransientOrStatic((Field) attribute.getJavaMember()))\n            {\n                if (metaModel.isEmbeddable(attribute.getJavaType()))\n                {\n                    EmbeddableType embeddable = metaModel.embeddable(attribute.getJavaType());\n                    populateEmbeddedIdFieldsUtil(embeddable.getAttributes(), metaModel, embeddedIdFields);\n                }\n            }\n        }\n    }\n\n    private static void populateEmbeddedIdFieldsUtil(Set<Attribute> embeddedAttributes, MetamodelImpl metaModel,\n            Set<String> embeddedIdFields)\n    {\n        for (Attribute attribute : embeddedAttributes)\n        {\n            if (!ReflectUtils.isTransientOrStatic((Field) attribute.getJavaMember()))\n            {\n                if (metaModel.isEmbeddable(attribute.getJavaType()))\n                {\n                    EmbeddableType embeddable = metaModel.embeddable(attribute.getJavaType());\n                    populateEmbeddedIdFieldsUtil(embeddable.getAttributes(), metaModel, embeddedIdFields);\n                }\n                else\n                {\n                    String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                    embeddedIdFields.add(columnName);\n                }\n            }\n        }\n    }\n\n    private static void prepareLuceneQueryForPartitionKey(LuceneQueryBuilder queryBuilder, Object key,\n            MetamodelImpl metaModel, String indexName, Class valueClazz)\n    {\n        Field[] fields = key.getClass().getDeclaredFields();\n        EmbeddableType embeddable = metaModel.embeddable(key.getClass());\n        boolean appendAnd = false;\n\n        try\n        {\n            for (int i = 0; i < fields.length; i++)\n            {\n                if (!ReflectUtils.isTransientOrStatic(fields[i]))\n                {\n                    if (metaModel.isEmbeddable(((AbstractAttribute) embeddable.getAttribute(fields[i].getName()))\n                            .getBindableJavaType()))\n                    {\n                        fields[i].setAccessible(true);\n                        prepareLuceneQueryForPartitionKey(queryBuilder, fields[i].get(key), metaModel, indexName,\n                                valueClazz);\n                    }\n                    else\n                    {\n                        if (appendAnd)\n                        {\n                            queryBuilder.buildQuery(\"AND\", \"AND\", String.class);\n                        }\n                        appendAnd = true;\n                        String fieldValue = PropertyAccessorHelper.getString(key, fields[i]);\n                        fieldValue = fieldValue.replaceAll(\"[^a-zA-Z0-9]\", \"_\");\n                        queryBuilder.appendIndexName(indexName).appendPropertyName(fields[i].getName())\n                                .buildQuery(\"=\", fieldValue, valueClazz);\n                    }\n                }\n            }\n        }\n        catch (IllegalArgumentException e)\n        {\n            logger.error(\"Error during prepare composite key, Caused by {}.\", e);\n            throw new PersistenceException(e);\n        }\n        catch (IllegalAccessException e)\n        {\n            logger.error(e.getMessage());\n        }\n    }\n\n    private static Class getValueType(EntityType entity, String fieldName)\n    {\n        Class valueClazz = null;\n        if (fieldName != null)\n        {\n            valueClazz = ((AbstractAttribute) entity.getAttribute(fieldName)).getBindableJavaType();\n        }\n        return valueClazz;\n    }\n\n    private static String getPropertyName(final EntityMetadata metadata, final String property,\n            final KunderaMetadata kunderaMetadata)\n    {\n        if (MetadataUtils.getEnclosingEmbeddedFieldName(metadata, property, true, kunderaMetadata) != null)\n        {\n            return property.substring(property.indexOf(\".\") + 1, property.length());\n        }\n\n        return property;\n    }\n\n    public static boolean isShowQueryEnabled(final Map<String, Object> properties, final String persistenceUnit,\n            final KunderaMetadata kunderaMetadata)\n    {\n        boolean showQuery = false;\n        showQuery = properties != null ? Boolean.parseBoolean((String) properties\n                .get(PersistenceProperties.KUNDERA_SHOW_QUERY)) : false;\n        if (!showQuery)\n        {\n            showQuery = persistenceUnit != null ? Boolean.parseBoolean(kunderaMetadata.getApplicationMetadata()\n                    .getPersistenceUnitMetadata(persistenceUnit).getProperties()\n                    .getProperty(PersistenceProperties.KUNDERA_SHOW_QUERY)) : false;\n        }\n        return showQuery;\n    }\n\n    public static void printQuery(String query, boolean showQuery)\n    {\n        if (showQuery)\n        {\n            System.out.println(query);\n        }\n    }\n\n    public static void printQueryWithFilterClause(Queue filterClausequeue, String tableName)\n    {\n        StringBuilder printQuery = new StringBuilder(\"Fetch data from \").append(tableName).append(\" for \");\n        for (Object clause : filterClausequeue)\n        {\n            if (clause instanceof FilterClause)\n            {\n                printQuery.append(((FilterClause) clause).getProperty()).append(\" \")\n                        .append(((FilterClause) clause).getCondition()).append(\" \")\n                        .append(((FilterClause) clause).getValue());\n            }\n            else\n            {\n                printQuery.append(\" \").append(clause.toString()).append(\" \");\n            }\n        }\n        KunderaCoreUtils.printQuery(printQuery.toString(), true);\n    }\n\n    public static Object getEntity(Object e)\n    {\n        if (e != null)\n        {\n            return e.getClass().isAssignableFrom(EnhanceEntity.class) ? ((EnhanceEntity) e).getEntity() : e;\n        }\n        return null;\n    }\n\n    /**\n     * Initialize.\n     * \n     * @param tr\n     *            the tr\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param tr\n     * @return the object\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    public static Object initialize(EntityMetadata m, Object entity, Object id)\n    {\n        try\n        {\n            if (entity == null)\n            {\n                entity = createNewInstance(m.getEntityClazz());\n            }\n            if (id != null)\n            {\n                PropertyAccessorHelper.setId(entity, m, id);\n            }\n            return entity;\n        }\n        catch (Exception e)\n        {\n            throw new PersistenceException(\"Error occured while instantiating entity.\", e);\n        }\n    }\n\n    /**\n     * Initialize.\n     * \n     * @param tr\n     *            the tr\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param tr\n     * @return the object\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    public static Object initialize(Class clazz, Object record)\n    {\n        try\n        {\n            if (record == null)\n            {\n                record = createNewInstance(clazz);\n            }\n            return record;\n        }\n        catch (Exception e)\n        {\n            throw new PersistenceException(\"Error occured while instantiating entity.\", e);\n        }\n    }\n\n    /**\n     * @param clazz\n     * @return\n     */\n    public static Object createNewInstance(Class clazz)\n    {\n        Object target = null;\n        try\n        {\n            Constructor[] constructors = clazz.getDeclaredConstructors();\n            for (Constructor constructor : constructors)\n            {\n                if ((Modifier.isProtected(constructor.getModifiers()) || Modifier.isPublic(constructor.getModifiers()))\n                        && constructor.getParameterTypes().length == 0)\n                {\n                    constructor.setAccessible(true);\n                    target = constructor.newInstance();\n                    constructor.setAccessible(false);\n                    break;\n                }\n            }\n            return target;\n\n        }\n        catch (InstantiationException iex)\n        {\n            logger.error(\"Error while creating an instance of {} .\", clazz);\n            throw new PersistenceException(iex);\n        }\n\n        catch (IllegalAccessException iaex)\n        {\n            logger.error(\"Illegal Access while reading data from {}, Caused by: .\", clazz, iaex);\n            throw new PersistenceException(iaex);\n        }\n\n        catch (Exception e)\n        {\n            logger.error(\"Error while creating an instance of {}, Caused by: .\", clazz, e);\n            throw new PersistenceException(e);\n        }\n    }\n\n    /**\n     * Gets the JPA column name.\n     * \n     * @param field\n     *            the field\n     * @param entityMetadata\n     *            the entity metadata\n     * @param metaModel\n     *            the meta model\n     * @return the JPA column name\n     */\n    public static String getJPAColumnName(String field, EntityMetadata entityMetadata, MetamodelImpl metaModel)\n    {\n        if (field.indexOf('.') > 0)\n        {\n            return ((AbstractAttribute) metaModel.entity(entityMetadata.getEntityClazz()).getAttribute(\n                    field.substring(field.indexOf('.') + 1,\n                            field.indexOf(')') > 0 ? field.indexOf(')') : field.length()))).getJPAColumnName();\n        }\n        else\n        {\n            return ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/KunderaThreadFactory.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.impetus.kundera.utils;\n\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.atomic.AtomicInteger;\n\n/**\n * @author Kuldeep.mishra\n * Implements {@link ThreadFactory}. Implementation to handle thread count and return thread for retry on connection attempt.\n */\npublic class KunderaThreadFactory implements ThreadFactory\n{\n    private ConcurrentHashMap<String, AtomicInteger> counters = new ConcurrentHashMap<String, AtomicInteger>();\n\n    private final String name;\n\n    public KunderaThreadFactory(final String threadName)\n    {\n        this.name = threadName;\n    }\n\n    private int getNext()\n    {\n        AtomicInteger threadCount = counters.get(name);\n        if (threadCount == null)\n        {\n            threadCount = new AtomicInteger();\n            counters.put(name, threadCount);\n        }\n        return threadCount.incrementAndGet();\n    }\n\n    @Override\n    public Thread newThread(Runnable r)\n    {\n        Thread t = new Thread(r);\n        t.setDaemon(true);\n        StringBuilder tdNameBuilder = new StringBuilder(name);\n        tdNameBuilder.append(\"#\");\n        tdNameBuilder.append(getNext());\n        t.setName(tdNameBuilder.toString());\n        return t;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/NumericUtils.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.impetus.kundera.utils;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.commons.lang.math.NumberUtils;\n\n\n/**\n * Utility class to define various numeric functions \n * \n * @author vivek.mishra\n *\n */\n\n\npublic final class NumericUtils\n{\n\n    enum NumberType\n    {\n        INTEGER,FLOAT,LONG,DOUBLE,BIGDECIMAL,SHORT,BIGINTEGER\n    }\n    \n    private static Map<Class, NumberType> numberTypes = new HashMap<Class, NumericUtils.NumberType>();\n    static\n    {\n        numberTypes.put(int.class, NumberType.INTEGER);\n        numberTypes.put(Integer.class, NumberType.INTEGER);\n        numberTypes.put(float.class, NumberType.FLOAT);\n        numberTypes.put(Float.class, NumberType.FLOAT);\n        numberTypes.put(long.class, NumberType.LONG);\n        numberTypes.put(Long.class, NumberType.LONG);\n        numberTypes.put(double.class, NumberType.DOUBLE);\n        numberTypes.put(Double.class, NumberType.DOUBLE);\n        numberTypes.put(BigDecimal.class, NumberType.BIGDECIMAL);\n        numberTypes.put(short.class, NumberType.SHORT);\n        numberTypes.put(Short.class, NumberType.SHORT);\n        numberTypes.put(BigInteger.class, NumberType.BIGINTEGER);\n    }\n    \n    /**\n     *  Check if zero\n     * @param value        value string\n     * @param valueClazz   value class \n     * @return             \n     */\n    public static final boolean checkIfZero(String value, Class valueClazz)\n    {\n        boolean returnValue=false;\n        if(value != null && NumberUtils.isNumber(value) && numberTypes.get(valueClazz) != null)\n        {\n            switch (numberTypes.get(valueClazz))\n            {\n            \n            case INTEGER:\n                returnValue = Integer.parseInt(value) == (NumberUtils.INTEGER_ZERO);\n                break;\n\n            case FLOAT:\n                returnValue = Float.parseFloat(value) == (NumberUtils.FLOAT_ZERO);\n                break;\n\n            case LONG:\n                returnValue = Long.parseLong(value) == (NumberUtils.LONG_ZERO);\n                break;\n\n            case BIGDECIMAL:\n                // Note: cannot use 'equals' here - it would require both BigDecimals to have\n                // the same scale.\n                returnValue = (new BigDecimal(value)).compareTo(BigDecimal.ZERO) == 0;\n                break;\n\n            case BIGINTEGER:\n                returnValue = (new BigInteger(value)).equals(BigInteger.ZERO);\n                break;\n            \n            case SHORT:\n                returnValue = (new Short(value)).shortValue() == NumberUtils.SHORT_ZERO.shortValue();\n                break;\n            }\n        }\n        \n        return returnValue;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/ObjectUtils.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.utils;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.Attribute.PersistentAttributeType;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.Type.PersistenceType;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessor;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.proxy.KunderaProxy;\nimport com.impetus.kundera.proxy.ProxyHelper;\nimport com.impetus.kundera.proxy.collection.ProxyCollection;\n\n/**\n * Provides utility methods for operation on objects.\n * \n * @author amresh.singh\n */\npublic class ObjectUtils\n{\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(ObjectUtils.class);\n\n    /**\n     * Deep copy.\n     * \n     * @param source\n     *            the source\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @return the object\n     */\n    public static final Object deepCopy(Object source, final KunderaMetadata kunderaMetadata)\n    {\n        Map<Object, Object> copiedObjectMap = new HashMap<Object, Object>();\n\n        Object target = deepCopyUsingMetadata(source, copiedObjectMap, kunderaMetadata);\n\n        copiedObjectMap.clear();\n        copiedObjectMap = null;\n\n        return target;\n    }\n\n    /**\n     * Deep copy using metadata.\n     * \n     * @param source\n     *            the source\n     * @param copiedObjectMap\n     *            the copied object map\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @return the object\n     */\n    private static Object deepCopyUsingMetadata(Object source, Map<Object, Object> copiedObjectMap,\n            final KunderaMetadata kunderaMetadata)\n    {\n        Object target = null;\n        try\n        {\n            if (source == null)\n            {\n                return null;\n            }\n            Class<?> sourceObjectClass = source.getClass();\n            EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, sourceObjectClass);\n            if (metadata == null)\n            {\n                return source;\n            }\n\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    metadata.getPersistenceUnit());\n\n            EntityType entityType = metaModel.entity(sourceObjectClass);\n\n            // May break for mapped super class.\n\n            Object id = null;\n            if (metadata.getRelations() != null && !metadata.getRelations().isEmpty())\n            {\n\n                id = PropertyAccessorHelper.getId(source, metadata);\n\n                StringBuilder keyBuilder = new StringBuilder(sourceObjectClass.getName());\n                keyBuilder.append(\"#\");\n                keyBuilder.append(id);\n                Object copiedObjectInMap = copiedObjectMap.get(keyBuilder.toString());\n                if (copiedObjectInMap != null)\n                {\n                    return copiedObjectInMap;\n                }\n            }\n            // Copy Columns (in a table that doesn't have any embedded objects\n\n            target = KunderaCoreUtils.createNewInstance(sourceObjectClass);\n\n            Iterator<Attribute> iter = entityType.getAttributes().iterator();\n            while (iter.hasNext())\n            {\n                Attribute attrib = iter.next();\n\n                Field columnField = (Field) attrib.getJavaMember();\n                if (attrib.getPersistentAttributeType().equals(PersistentAttributeType.EMBEDDED)\n                        || attrib.getPersistentAttributeType().equals(PersistentAttributeType.ELEMENT_COLLECTION))\n                {\n                    EmbeddableType embeddedColumn = metaModel.embeddable(((AbstractAttribute) attrib)\n                            .getBindableJavaType());\n\n                    Object sourceEmbeddedObj = PropertyAccessorHelper.getObject(source, columnField);\n                    if (sourceEmbeddedObj != null)\n                    {\n                        if (metaModel.isEmbeddable(((AbstractAttribute) attrib).getBindableJavaType()))\n                        {\n                            if (attrib.isCollection())\n                            {\n                                Class<?> ecDeclaredClass = columnField.getType();\n                                Class<?> actualEcObjectClass = sourceEmbeddedObj.getClass();\n\n                                Object targetCollectionObject = actualEcObjectClass.newInstance();\n\n                                // Copy element collections for List and Set\n                                if (sourceEmbeddedObj instanceof Collection)\n                                {\n                                    Class<?> genericClass = PropertyAccessorHelper.getGenericClass(columnField);\n\n                                    for (Object sourceEcObj : (Collection) sourceEmbeddedObj)\n                                    {\n                                        Object targetEcObj = null;\n                                        if (sourceEcObj != null\n                                                && PersistenceType.BASIC.equals(embeddedColumn.getPersistenceType()))\n                                        {\n                                            PropertyAccessor accessor = PropertyAccessorFactory\n                                                    .getPropertyAccessor(sourceEcObj.getClass());\n                                            if (accessor != null)\n                                            {\n                                                targetEcObj = accessor.getCopy(sourceEcObj);\n                                            }\n                                        }\n                                        else if (sourceEcObj != null\n                                                && PersistenceType.EMBEDDABLE.equals(embeddedColumn\n                                                        .getPersistenceType()))\n                                        {\n                                            targetEcObj = genericClass.newInstance();\n\n                                            for (Field f : genericClass.getDeclaredFields())\n                                            {\n                                                if (f != null && !Modifier.isStatic(f.getModifiers()))\n                                                {\n                                                    PropertyAccessorHelper.set(targetEcObj, f,\n                                                            PropertyAccessorHelper.getObjectCopy(sourceEcObj, f));\n                                                }\n                                            }\n                                        }\n                                        if (List.class.isAssignableFrom(ecDeclaredClass))\n                                        {\n                                            Method m = actualEcObjectClass.getMethod(\"add\", Object.class);\n                                            m.invoke(targetCollectionObject, targetEcObj);\n\n                                        }\n                                        else if (Set.class.isAssignableFrom(ecDeclaredClass))\n                                        {\n                                            Method m = actualEcObjectClass.getMethod(\"add\", Object.class);\n                                            m.invoke(targetCollectionObject, targetEcObj);\n                                        }\n                                    }\n                                }\n\n                                // Copy element collection for Map\n                                else if (sourceEmbeddedObj instanceof Map)\n                                {\n                                    for (Object sourceKey : ((Map) sourceEmbeddedObj).keySet())\n                                    {\n                                        Object targetKey = null;\n                                        Object targetValue = null;\n                                        if (PersistenceType.BASIC.equals(embeddedColumn.getPersistenceType())\n                                                || PersistenceType.EMBEDDABLE.equals(embeddedColumn\n                                                        .getPersistenceType()))\n                                        {\n                                            // Create copy of map key\n                                            if (sourceKey != null)\n                                            {\n                                                PropertyAccessor keyAccessor = PropertyAccessorFactory\n                                                        .getPropertyAccessor(sourceKey.getClass());\n                                                if (keyAccessor != null)\n                                                {\n                                                    targetKey = keyAccessor.getCopy(sourceKey);\n                                                }\n                                            }\n                                            else\n                                            {\n                                                targetKey = null;\n                                            }\n\n                                            // Create copy of map value\n                                            Object sourceValue = ((Map) sourceEmbeddedObj).get(sourceKey);\n                                            if (sourceValue != null)\n                                            {\n                                                PropertyAccessor valueAccessor = PropertyAccessorFactory\n                                                        .getPropertyAccessor(sourceValue.getClass());\n                                                if (valueAccessor != null)\n                                                {\n                                                    targetValue = valueAccessor.getCopy(sourceValue);\n                                                }\n                                            }\n                                            else\n                                            {\n                                                targetValue = null;\n                                            }\n\n                                            if (Map.class.isAssignableFrom(ecDeclaredClass))\n                                            {\n                                                Method m = actualEcObjectClass.getMethod(\"put\", new Class[] {\n                                                        Object.class, Object.class });\n                                                m.invoke(targetCollectionObject,\n                                                        new Object[] { targetKey, targetValue });\n                                            }\n                                        }\n                                    }\n                                }\n                                PropertyAccessorHelper.set(target, columnField, targetCollectionObject);\n                            }\n                            else\n                            {\n                                // Copy embedded objects\n                                Class<?> embeddedColumnClass = columnField.getType();\n                                Object targetEmbeddedObj = embeddedColumnClass.newInstance();\n\n                                Set<Attribute> columns = embeddedColumn.getAttributes();\n                                for (Attribute column : columns)\n                                {\n                                    PropertyAccessorHelper.set(\n                                            targetEmbeddedObj,\n                                            (Field) column.getJavaMember(),\n                                            PropertyAccessorHelper.getObjectCopy(sourceEmbeddedObj,\n                                                    (Field) column.getJavaMember()));\n                                }\n\n                                PropertyAccessorHelper.set(target, columnField, targetEmbeddedObj);\n                            }\n                        }\n                        else if (((AbstractAttribute) attrib).getJPAColumnName() != null)\n                        {\n                            // Copy columns\n                            PropertyAccessorHelper.set(target, columnField, sourceEmbeddedObj);\n                        }\n                    }\n\n                }\n                else if (attrib.getPersistentAttributeType().equals(PersistentAttributeType.BASIC))\n                {\n\n                    PropertyAccessorHelper.set(target, columnField,\n                            PropertyAccessorHelper.getObjectCopy(source, columnField));\n                }\n            }\n\n            // Put this object into copied object map\n            if (id != null)\n            {\n                StringBuilder keyBuilder = new StringBuilder(sourceObjectClass.getName());\n                keyBuilder.append(\"#\");\n                keyBuilder.append(id);\n                copiedObjectMap.put(keyBuilder.toString(), target);\n            }\n            // Copy Relationships recursively\n            for (Relation relation : metadata.getRelations())\n            {\n                if (relation != null)\n                {\n                    Field relationField = relation.getProperty();\n                    Object sourceRelationObject = PropertyAccessorHelper.getObject(source, relationField);\n\n                    if (sourceRelationObject != null)\n                    {\n                        if (sourceRelationObject instanceof KunderaProxy)\n                        {\n                            PropertyAccessorHelper.set(target, relationField, sourceRelationObject);\n                            continue;\n                        }\n                        else if (ProxyHelper.isPersistentCollection(sourceRelationObject))\n                        {\n                            PropertyAccessorHelper.set(target, relationField, sourceRelationObject);\n                            continue;\n                        }\n                        else if (ProxyHelper.isKunderaProxyCollection(sourceRelationObject))\n                        {\n                            ProxyCollection pc = ((ProxyCollection) sourceRelationObject).getCopy();\n                            pc.setOwner(target);\n                            PropertyAccessorHelper.set(target, relationField, pc);\n                            continue;\n                        }\n\n                        Object targetRelationObject = null;\n\n                        Class<?> relationObjectClass = relation.getProperty().getType();\n                        Class<?> actualRelationObjectClass = sourceRelationObject.getClass();\n\n                        if (Collection.class.isAssignableFrom(relationObjectClass))\n                        {\n                            targetRelationObject = actualRelationObjectClass.newInstance();\n                            Method m = actualRelationObjectClass.getMethod(\"add\", Object.class);\n\n                            for (Object obj : (Collection) sourceRelationObject)\n                            {\n                                Object copyTargetRelObj = searchInCacheThenCopy(copiedObjectMap, obj, kunderaMetadata);\n                                m.invoke(targetRelationObject, copyTargetRelObj);\n                            }\n                        }\n                        else if (Map.class.isAssignableFrom(relationObjectClass))\n                        {\n                            targetRelationObject = actualRelationObjectClass.newInstance();\n                            Method m = actualRelationObjectClass.getMethod(\"put\", new Class<?>[] { Object.class,\n                                    Object.class });\n\n                            for (Object keyObj : ((Map) sourceRelationObject).keySet())\n                            {\n                                Object valObj = ((Map) sourceRelationObject).get(keyObj);\n\n                                Object copyTargetKeyObj = searchInCacheThenCopy(copiedObjectMap, keyObj,\n                                        kunderaMetadata);\n\n                                Object copyTargetValueObj = searchInCacheThenCopy(copiedObjectMap, valObj,\n                                        kunderaMetadata);\n\n                                m.invoke(targetRelationObject, new Object[] { copyTargetKeyObj, copyTargetValueObj });\n                            }\n                        }\n                        else\n                        {\n                            targetRelationObject = searchInCacheThenCopy(copiedObjectMap, sourceRelationObject,\n                                    kunderaMetadata);\n                        }\n                        PropertyAccessorHelper.set(target, relationField, targetRelationObject);\n                    }\n                }\n            }\n        }\n        catch (InstantiationException e)\n        {\n            log.warn(\"Error while instantiating entity/ embeddable class, did you define no-arg constructor?, Caused by:\"\n                    + e.getMessage());\n            return null;\n        }\n        catch (Exception e)\n        {\n            log.warn(\"Returning null as error during clone, Caused by:\" + e.getMessage());\n            return null;\n        }\n\n        return target;\n    }\n\n    /**\n     * Search in cache then copy.\n     * \n     * @param copiedObjectMap\n     *            the copied object map\n     * @param sourceObject\n     *            the source object\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @return the object\n     */\n    private static Object searchInCacheThenCopy(Map<Object, Object> copiedObjectMap, Object sourceObject,\n            final KunderaMetadata kunderaMetadata)\n    {\n        Object copyTargetRelObj = null;\n        copyTargetRelObj = deepCopyUsingMetadata(sourceObject, copiedObjectMap, kunderaMetadata);\n        return copyTargetRelObj;\n    }\n\n    /**\n     * Gets the field instance.\n     * \n     * @param chids\n     *            the chids\n     * @param f\n     *            the f\n     * @return the field instance\n     */\n    public static Object getFieldInstance(List chids, Field f)\n    {\n\n        if (Set.class.isAssignableFrom(f.getType()))\n        {\n            Set col = new HashSet(chids);\n            return col;\n        }\n        return chids;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/ReflectUtils.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.utils;\r\n\r\nimport java.lang.reflect.Field;\r\nimport java.lang.reflect.ParameterizedType;\r\nimport java.lang.reflect.Type;\r\n\r\nimport javassist.Modifier;\r\n\r\nimport javax.persistence.Transient;\r\n\r\nimport com.impetus.kundera.KunderaException;\r\n\r\n/**\r\n * The Class ReflectUtils.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class ReflectUtils\r\n{\r\n\r\n    /**\r\n     * Instantiates a new reflect utils.\r\n     */\r\n    private ReflectUtils()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * Checks for interface \"has\" in class \"in\".\r\n     * \r\n     * @param has\r\n     *            the has\r\n     * @param in\r\n     *            the in\r\n     * \r\n     * @return true, if exists?\r\n     */\r\n    public static boolean hasInterface(Class<?> has, Class<?> in)\r\n    {\r\n        if (has.equals(in))\r\n        {\r\n            return true;\r\n        }\r\n        boolean match = false;\r\n        for (Class<?> intrface : in.getInterfaces())\r\n        {\r\n            if (intrface.getInterfaces().length > 0)\r\n            {\r\n                match = hasInterface(has, intrface);\r\n            }\r\n            else\r\n            {\r\n                match = intrface.equals(has);\r\n            }\r\n\r\n            if (match)\r\n            {\r\n                return true;\r\n            }\r\n        }\r\n        return false;\r\n    }\r\n\r\n    /**\r\n     * Gets the type arguments.\r\n     * \r\n     * @param property\r\n     *            the property\r\n     * \r\n     * @return the type arguments\r\n     */\r\n    public static Type[] getTypeArguments(Field property)\r\n    {\r\n        Type type = property.getGenericType();\r\n        if (type instanceof ParameterizedType)\r\n        {\r\n            return ((ParameterizedType) type).getActualTypeArguments();\r\n        }\r\n        return null;\r\n    }\r\n\r\n    /**\r\n     * Checks for super \"has\" in class \"in\".\r\n     * \r\n     * @param has\r\n     *            the has\r\n     * @param in\r\n     *            the in\r\n     * \r\n     * @return true, if exists?\r\n     */\r\n    public static boolean hasSuperClass(Class<?> has, Class<?> in)\r\n    {\r\n        if (in.equals(has))\r\n        {\r\n            return true;\r\n        }\r\n        boolean match = false;\r\n        // stop if the superclass is Object\r\n        if (in.getSuperclass() != null && in.getSuperclass().equals(Object.class))\r\n        {\r\n            return match;\r\n        }\r\n        match = in.getSuperclass() != null ? hasSuperClass(has, in.getSuperclass()): false;\r\n        return match;\r\n    }\r\n\r\n    /**\r\n     * Loads class with className using classLoader.\r\n     * \r\n     * @param className\r\n     *            the class name\r\n     * @param classLoader\r\n     *            the class loader\r\n     * @return the class\r\n     */\r\n    public static Class<?> classForName(String className, ClassLoader classLoader)\r\n    {\r\n        try\r\n        {\r\n            Class<?> c = null;\r\n            try\r\n            {\r\n                c = Class.forName(className, true, ReflectUtils.class.getClassLoader());\r\n            }\r\n            catch (ClassNotFoundException e)\r\n            {\r\n                try\r\n                {\r\n                    c = Class.forName(className);\r\n                }\r\n                catch (ClassNotFoundException e1)\r\n                {\r\n                    if (classLoader == null)\r\n                    {\r\n                        throw e1;\r\n                    }\r\n                    else\r\n                    {\r\n                        c = classLoader.loadClass(className);\r\n                    }\r\n                }\r\n            }\r\n            return c;\r\n        }\r\n        catch (ClassNotFoundException e)\r\n        {\r\n            throw new KunderaException(e);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Strip enhancer class.\r\n     * \r\n     * @param c\r\n     *            the c\r\n     * @return the class\r\n     */\r\n    public static Class<?> stripEnhancerClass(Class<?> c)\r\n    {\r\n        String className = c.getName();\r\n\r\n        // strip CGLIB from name\r\n        int enhancedIndex = className.indexOf(\"$$EnhancerByCGLIB\");\r\n        if (enhancedIndex != -1)\r\n        {\r\n            className = className.substring(0, enhancedIndex);\r\n        }\r\n\r\n        if (className.equals(c.getName()))\r\n        {\r\n            return c;\r\n        }\r\n        else\r\n        {\r\n            c = classForName(className, c.getClassLoader());\r\n        }\r\n        return c;\r\n    }\r\n\r\n    public static boolean isTransientOrStatic(Field field)\r\n    {\r\n        return field != null\r\n                && (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers()) || field\r\n                        .isAnnotationPresent(Transient.class));\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/utils/TimestampGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.utils;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\npublic interface TimestampGenerator\n{\n\n    public long getTimestamp();\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/AbstractValidationFactory.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation;\n\nimport java.lang.reflect.Field;\n\nimport com.impetus.kundera.validation.rules.EntityRule;\nimport com.impetus.kundera.validation.rules.FieldRule;\nimport com.impetus.kundera.validation.rules.IRule;\nimport com.impetus.kundera.validation.rules.RuleValidationException;\n\n/**\n * @author Chhavi Gangwal\n *\n */\npublic abstract class AbstractValidationFactory\n{\n            \n    /**\n     * rule factory object \n     */\n    protected com.impetus.kundera.validation.ValidationFactory.RuleFactory ruleFactory = new com.impetus.kundera.validation.ValidationFactory.RuleFactory();\n    \n    \n    /**\n     * @param clazz\n     * @param rules\n     * @return\n     * @throws RuleValidationException\n     */\n    public boolean validate(Class clazz, IRule... rules) throws RuleValidationException\n    {\n        \n        for (IRule rule : rules)\n        {\n            ((EntityRule)rule).validate(clazz);\n        }\n        return true;\n       \n        \n    }\n\n    \n    /**\n     * @param field\n     * @param rules\n     * @return\n     * @throws RuleValidationException\n     */\n    public boolean validate(Field field, IRule... rules) throws RuleValidationException\n    {\n       \n        for (IRule rule : rules)\n        {\n            ((FieldRule)rule).validate(field);\n        }\n        return true;\n    }\n    \n   \n    /**\n     * @param field\n     * @param fieldValue\n     * @param rules\n     * @return\n     * @throws RuleValidationException\n     */\n    public boolean validate(Field field, Object fieldValue, IRule... rules) throws RuleValidationException\n    {\n       \n        for (IRule rule : rules)\n        {\n            ((FieldRule)rule).validate(field, fieldValue);\n        }\n        return true;\n    }\n    \n\n    /**\n     * @param clazz\n     * @return\n     * @throws RuleValidationException\n     */\n    public boolean validate(Class clazz) throws RuleValidationException \n    {\n        throw new UnsupportedOperationException(\"Bootstrap level validations are not supported at operation level!\");\n    }\n    \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/BootstrapValidationFactory.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.impetus.kundera.validation.rules.EntityAnnotationRule;\nimport com.impetus.kundera.validation.rules.EntityFieldAnnotationRule;\nimport com.impetus.kundera.validation.rules.IRule;\nimport com.impetus.kundera.validation.rules.RuleValidationException;\n\n\n/**\n * @author Chhavi Gangwal\n *\n */\npublic class BootstrapValidationFactory extends AbstractValidationFactory implements ValidationFactory\n{\n\n    /**\n     * List of rules for BootStrap level validations\n     */\n    static List<IRule> rules = new ArrayList<IRule>();\n    \n    static\n    {\n       rules.add(new EntityAnnotationRule());\n       rules.add(new EntityFieldAnnotationRule());\n    }\n    \n    /**\n     * Constructor\n     * adds static rule list to Rule factory\n     */\n    BootstrapValidationFactory()\n    {\n        this.ruleFactory.addRule(rules);\n    }\n    \n    \n    /* (non-Javadoc)\n     * @see com.impetus.kundera.validation.AbstractValidationFactory#validate(java.lang.Class)\n     */\n    @Override\n    public boolean validate(Class clazz) throws RuleValidationException \n    {\n        return validate(clazz, this.ruleFactory.getJpaRules());\n    }\n        \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/ListenerValidationFactory.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation;\n\nimport com.impetus.kundera.validation.rules.RuleValidationException;\n\n/**\n * @author Chhavi Gangwal\n *\n */\npublic class ListenerValidationFactory extends AbstractValidationFactory implements ValidationFactory\n{\n        /* (non-Javadoc)\n         * @see com.impetus.kundera.validation.AbstractValidationFactory#validate(java.lang.Class)\n         */\n        @Override\n        public boolean validate(Class clazz) throws RuleValidationException\n        {\n            throw new UnsupportedOperationException(\"Listener level validations are not supported!\");\n        }\n\n   \n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/OperationValidationFactory.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.impetus.kundera.validation.rules.IRule;\nimport com.impetus.kundera.validation.rules.RuleValidationException;\n\n/**\n * @author Chhavi Gangwal\n *\n */\npublic class OperationValidationFactory extends AbstractValidationFactory implements ValidationFactory\n{\n    /**\n     * List of rules for operation level validations\n     */\n    static List<IRule> rules = new ArrayList<IRule>();\n\n    static\n    {\n        \n       // rules.add((IRule) new AttributeConstraintRule());\n        \n    }\n    \n    /**\n     * Constructor\n     * adds static rule list to Rule factory\n     */\n    public OperationValidationFactory()\n    {\n        this.ruleFactory.addRule(rules);\n    }\n    \n    \n    /* (non-Javadoc)\n     * @see com.impetus.kundera.validation.AbstractValidationFactory#validate(java.lang.reflect.Field, java.lang.Object, com.impetus.kundera.validation.rules.IRule[])\n     */\n    @Override\n    public boolean validate(Field field, Object fieldValue, IRule... rules) throws RuleValidationException\n    {\n\n        if (rules == null)\n        {\n            return super.validate(field, fieldValue, this.ruleFactory.getJpaRules());\n        }\n        \n        else\n        {\n            return super.validate(field, fieldValue, rules);\n        }\n\n    }\n\n   \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/ValidationFactory.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at  new ValidationFactoryGenerator().getFactory(ValidationType type)\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.impetus.kundera.validation.rules.IRule;\nimport com.impetus.kundera.validation.rules.RuleValidationException;\n\n/**\n * @author Chhavi Gangwal\n *\n */\npublic interface ValidationFactory\n{\n    /**\n     * validates whether a valid entity class or not \n     * \n     * @param clazz\n     * @return\n     * @throws RuleValidationException\n     */\n    boolean validate(Class clazz) throws RuleValidationException;\n    \n    /**\n     * validates a given entity with given set of rules\n     * \n     * @param clazz\n     * @param rules\n     * @return\n     * @throws RuleValidationException\n     */\n    boolean validate(Class clazz, IRule... rules) throws RuleValidationException;\n\n    /**\n     * validates a field of a class with given set of rules\n     * \n     * @param field\n     * @param rules\n     * @return\n     * @throws RuleValidationException\n     */\n    boolean validate(Field field, IRule... rules) throws RuleValidationException;\n    \n    \n    /**\n     * validates a field against its value with given set of rules\n     * \n     * @param field\n     * @param fieldValue\n     * @param rules\n     * @return\n     * @throws RuleValidationException\n     */\n    boolean validate(Field field, Object fieldValue, IRule... rules) throws RuleValidationException;\n       \n    \n    /**\n     * RuleFactory to be used in different validation factories\n     *\n     */\n    class RuleFactory\n    {\n        /**\n         * list of jpa rules to be applied\n         */\n        private List<IRule> jpaRules = new ArrayList<IRule>();\n        \n        /**\n         * @return\n         */\n        IRule[] getJpaRules()\n        {\n            IRule[] jrule = new IRule[jpaRules.size()];\n            return (IRule[]) jpaRules.toArray(jrule);\n        }\n\n        /**\n         * builds static rule list for validation factory\n         * \n         * @param rules\n         */\n        void addRule(List<IRule> rules)\n        {\n            jpaRules.addAll(rules);\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/ValidationFactoryGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation;\n\n/**\n * @author Chhavi Gangwal\n *\n */\npublic final class ValidationFactoryGenerator\n{\n    /**\n     * Defines the levels of validation factory     \n     */\n    public static enum ValidationFactoryType\n    {\n        BOOT_STRAP_VALIDATION, OPERATIONAL_VALIDATION, LISTENER_VALIDATION\n    };\n\n    /**\n     * @param validatorFactoryType\n     * @return\n     */\n    public ValidationFactory getFactory(ValidationFactoryType validatorFactoryType)\n    {\n        ValidationFactory validationFactory = null;\n        switch (validatorFactoryType)\n        {\n        case BOOT_STRAP_VALIDATION:\n            validationFactory = new BootstrapValidationFactory();\n            break;\n        case OPERATIONAL_VALIDATION:\n            validationFactory = new OperationValidationFactory();\n            break;\n        case LISTENER_VALIDATION:\n            validationFactory = new ListenerValidationFactory();\n            break;\n        }\n        return validationFactory;\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/AbstractEntityRule.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation.rules;\n\npublic abstract class AbstractEntityRule\n{\n     \n  /**\n * @param clazz\n * @throws RuleValidationException\n */\npublic void validate(Class<?> clazz) throws RuleValidationException\n  {\n      throw new UnsupportedOperationException(\"Validation Not Supported\");\n      \n  }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/AbstractFieldRule.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation.rules;\n\nimport java.lang.reflect.Field;\n\npublic abstract class AbstractFieldRule\n{\n    \n   \n    /**\n     * @param f\n     * @param fieldValue\n     * @return\n     * @throws RuleValidationException\n     */\n    public boolean validate(Field f, Object fieldValue) throws RuleValidationException\n    {\n        throw new UnsupportedOperationException(\"Validation Not supported.\");\n    }\n\n  \n    /**\n     * @param f\n     * @return\n     * @throws RuleValidationException\n     */\n    public boolean validate(Field f) throws RuleValidationException\n    {\n        throw new UnsupportedOperationException(\"Validation Not supported.\");\n    }\n\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/AttributeConstraintRule.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation.rules;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.math.BigDecimal;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.Collection;\nimport java.util.Date;\nimport java.util.EnumSet;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\n\nimport javax.validation.ValidationException;\nimport javax.validation.constraints.AssertFalse;\nimport javax.validation.constraints.AssertTrue;\nimport javax.validation.constraints.DecimalMax;\nimport javax.validation.constraints.DecimalMin;\nimport javax.validation.constraints.Digits;\nimport javax.validation.constraints.Future;\nimport javax.validation.constraints.Max;\nimport javax.validation.constraints.Min;\nimport javax.validation.constraints.NotNull;\nimport javax.validation.constraints.Null;\nimport javax.validation.constraints.Past;\nimport javax.validation.constraints.Pattern;\nimport javax.validation.constraints.Size;\n\nimport org.apache.commons.lang.math.NumberUtils;\n\nimport com.impetus.kundera.property.PropertyAccessorHelper;\n\n/**\n * @author Chhavi Gangwal\n * \n */\npublic class AttributeConstraintRule extends AbstractFieldRule implements FieldRule\n{\n\n    /** The rules for entity type validation map. */\n    static enum AttributeConstraintType\n    {\n\n        ASSERT_FALSE(AssertFalse.class.getSimpleName()), ASSERT_TRUE(AssertTrue.class.getSimpleName()), DECIMAL_MAX(\n                DecimalMax.class.getSimpleName()), DECIMAL_MIN(DecimalMin.class.getSimpleName()), DIGITS(Digits.class\n                .getSimpleName()), FUTURE(Future.class.getSimpleName()), MAX(Max.class.getSimpleName()), MIN(Min.class\n                .getSimpleName()), NOT_NULL(NotNull.class.getSimpleName()), NULL(Null.class.getSimpleName()), PAST(\n                Past.class.getSimpleName()), PATTERN(Pattern.class.getSimpleName()), SIZE(Size.class.getSimpleName());\n\n        private String clazz;\n\n        private static final Map<String, AttributeConstraintType> lookup = new HashMap<String, AttributeConstraintType>();\n\n        static\n        {\n            for (AttributeConstraintType s : EnumSet.allOf(AttributeConstraintType.class))\n            {\n                lookup.put(s.getClazz(), s);\n            }\n        }\n\n        /**\n         * @param clazz\n         */\n        private AttributeConstraintType(String clazz)\n        {\n            this.clazz = clazz;\n        }\n\n        /**\n         * @return\n         */\n        public String getClazz()\n        {\n            return clazz;\n        }\n\n        /**\n         * @param clazz\n         * @return\n         */\n        public static AttributeConstraintType get(String clazz)\n        {\n            return lookup.get(clazz);\n        }\n    }\n\n    private AttributeConstraintType getERuleType(String annotationType)\n    {\n\n        if (AttributeConstraintType.get(annotationType) != null)\n        {\n            return AttributeConstraintType.get(annotationType);\n        }\n        else\n        {\n            return null;\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.validation.rules.AbstractFieldRule#validate(java.\n     * lang.reflect.Field, java.lang.Object)\n     */\n    @Override\n    public boolean validate(Field f, Object validationObject)\n    {\n        boolean checkvalidation = true;\n\n        for (Annotation annotation : f.getDeclaredAnnotations())\n        {\n\n            AttributeConstraintType eruleType = getERuleType(annotation.annotationType().getSimpleName());\n\n            if (eruleType != null)\n            {\n                Object fieldValue = PropertyAccessorHelper.getObject(validationObject, f);\n\n                switch (eruleType)\n                {\n\n                case ASSERT_FALSE:\n                    checkvalidation = validateFalse(fieldValue, annotation);\n                    break;\n                case ASSERT_TRUE:\n                    checkvalidation = validateTrue(fieldValue, annotation);\n                    break;\n                case DECIMAL_MAX:\n                    checkvalidation = validateMaxDecimal(fieldValue, annotation);\n                    break;\n                case DECIMAL_MIN:\n                    checkvalidation = validateMinDecimal(fieldValue, annotation);\n                    break;\n                case DIGITS:\n                    checkvalidation = validateDigits(fieldValue, annotation);\n                    break;\n                case FUTURE:\n                    checkvalidation = validateFuture(fieldValue, annotation);\n                    break;\n                case MAX:\n                    checkvalidation = validateMaxValue(fieldValue, annotation);\n                    break;\n\n                case MIN:\n                    checkvalidation = validateMinValue(fieldValue, annotation);\n                    break;\n                case NOT_NULL:\n                    checkvalidation = validateNotNull(fieldValue, annotation);\n                    break;\n                case NULL:\n                    checkvalidation = validateNull(fieldValue, annotation);\n                    break;\n                case PAST:\n                    checkvalidation = validatePast(fieldValue, annotation);\n                    break;\n                case PATTERN:\n                    checkvalidation = validatePattern(fieldValue, annotation);\n                    break;\n                case SIZE:\n                    checkvalidation = validateSize(fieldValue, annotation);\n                    break;\n\n                }\n            }\n        }\n\n        return checkvalidation;\n    }\n\n    /**\n     * Checks whether the given attribute's value is within specified limit \n     * \n     * @param validationObject\n     * @param annotate\n     * @return\n     */\n    private boolean validateSize(Object validationObject, Annotation annotate)\n    {\n\n        if (checkNullObject(validationObject))\n        {\n            return true;\n        }\n        \n        int objectSize = 0;\n        int minSize = ((Size) annotate).min();\n        int maxSize = ((Size) annotate).max();\n        if (validationObject != null)\n        {\n            if (String.class.isAssignableFrom(validationObject.getClass()))\n            {\n                objectSize = ((String) validationObject).length();\n\n            }\n            else if (Collection.class.isAssignableFrom(validationObject.getClass()))\n            {\n                \n                objectSize = ((Collection) validationObject).size();\n            }\n            else if (Map.class.isAssignableFrom(validationObject.getClass()))\n            {\n                objectSize = ((Map) validationObject).size();\n            }\n            else if (ArrayList.class.isAssignableFrom(validationObject.getClass()))\n            {\n\n                objectSize = ((ArrayList) validationObject).size();\n\n            }\n            else\n            {\n                throwValidationException(((Size) annotate).message());\n\n            }\n        }\n        return objectSize <= maxSize && objectSize >= minSize;\n\n    }\n\n    /**\n     * Checks whether the given string is a valid pattern or not\n     * \n     * @param validationObject\n     * @param annotate\n     * @return\n     */\n    private boolean validatePattern(Object validationObject, Annotation annotate)\n    {\n        if (checkNullObject(validationObject))\n        {\n            return true;\n        }\n\n        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(((Pattern) annotate).regexp(),\n                ((Pattern) annotate).flags().length);\n        Matcher matcherPattern = pattern.matcher((String) validationObject);\n        if (!matcherPattern.matches())\n        {\n            throwValidationException(((Pattern) annotate).message());\n           \n        }\n\n        return true;\n    }\n\n    /**\n     * Checks whether the object is null or not\n     * \n     * @param validationObject\n     * @param annotate\n     * @return\n     */\n    private boolean validatePast(Object validationObject, Annotation annotate)\n    {\n        if (checkNullObject(validationObject))\n        {\n            return true;\n        }\n\n        int res = 0;\n\n        if (validationObject.getClass().isAssignableFrom(java.util.Date.class))\n        {\n            Date today = new Date();\n            Date pastDate = (Date) validationObject;\n\n            res = pastDate.compareTo(today);\n        }\n        else if (validationObject.getClass().isAssignableFrom(java.util.Calendar.class))\n        {\n\n            Calendar cal = Calendar.getInstance();\n            Calendar pastDate = (Calendar) validationObject;\n            res = pastDate.compareTo(cal);\n\n        }\n        // else\n        // {\n        // ruleExceptionHandler(((Past) annotate).message());\n        // }\n        if (res >= 0)\n        {\n            throwValidationException(((Past) annotate).message());\n        }\n\n        return true;\n    }\n\n    /**\n     * Checks whether a given date is that in future or not\n     * \n     * @param validationObject\n     * @param annotate\n     * @return\n     */\n    private boolean validateFuture(Object validationObject, Annotation annotate)\n    {\n        if (checkNullObject(validationObject))\n        {\n            return true;\n        }\n\n        int res = 0;\n\n        if (validationObject.getClass().isAssignableFrom(java.util.Date.class))\n        {\n            Date today = new Date();\n            Date futureDate = (Date) validationObject;\n\n            res = futureDate.compareTo(today);\n        }\n        else if (validationObject.getClass().isAssignableFrom(java.util.Calendar.class))\n        {\n\n            Calendar cal = Calendar.getInstance();\n            Calendar futureDate = (Calendar) validationObject;\n            res = futureDate.compareTo(cal);\n\n        }\n        // else\n        // {\n        // //ruleExceptionHandler(((Future) annotate).message());\n        // throw new RuleValidationException(((Future)\n        // annotate).message());\n        // }\n        if (res <= 0)\n        {\n            throwValidationException(((Future) annotate).message());\n        }\n\n        return true;\n    }\n\n    /**\n     * Checks whether a given date is that in past or not\n     * \n     * @param validationObject\n     * @param annotate\n     * @return\n     */\n    private boolean validateNull(Object validationObject, Annotation annotate)\n    {\n        if (checkNullObject(validationObject))\n        {\n            return true;\n        }\n\n        if (!validationObject.equals(null) || validationObject != null)\n        {\n            throwValidationException(((Null) annotate).message());\n        }\n\n        return true;\n    }\n\n    /**\n     * \n     * Checks whether a given date is not null\n     * \n     * @param validationObject\n     * @param annotate\n     * @return\n     */\n    private boolean validateNotNull(Object validationObject, Annotation annotate)\n    {\n\n        if (validationObject == null || validationObject.equals(null))\n        {\n            throwValidationException(((NotNull) annotate).message());\n        }\n        return true;\n    }\n\n    /**\n     * Checks whether a given value is greater than given min value or not\n     * \n     * @param validationObject\n     * @param annotate\n     * @return\n     */\n    private boolean validateMinValue(Object validationObject, Annotation annotate)\n    {\n        if (checkNullObject(validationObject))\n        {\n            return true;\n        }\n\n        Long minValue = ((Min) annotate).value();\n        if (checkvalidDigitTypes(validationObject.getClass()))\n        {\n            if ((NumberUtils.toLong(toString(validationObject))) < minValue)\n            {\n\n                throwValidationException(((Min) annotate).message());\n            }\n        }\n\n        return true;\n    }\n\n    /**\n     * Checks whether a given value is lesser than given max value or not\n     * \n     * @param validationObject\n     * @param annotate\n     * @return\n     */\n    private boolean validateMaxValue(Object validationObject, Annotation annotate)\n    {\n        if (checkNullObject(validationObject))\n        {\n            return true;\n        }\n\n        Long maxValue = ((Max) annotate).value();\n        if (checkvalidDigitTypes(validationObject.getClass()))\n        {\n            if ((NumberUtils.toLong(toString(validationObject))) > maxValue)\n            {\n\n                throwValidationException(((Max) annotate).message());\n\n            }\n        }\n\n        return true;\n    }\n\n    /**\n     * Checks whether a given value is is a number or not\n     * \n     * @param validationObject\n     * @param annotate\n     * @return\n     */\n    private boolean validateDigits(Object validationObject, Annotation annotate)\n    {\n        if (checkNullObject(validationObject))\n        {\n            return true;\n        }\n\n        if (checkvalidDigitTypes(validationObject.getClass()))\n        {\n            if (!NumberUtils.isDigits(toString(validationObject)))\n            {\n\n                throwValidationException(((Digits) annotate).message());\n            }\n        }\n\n        return true;\n    }\n\n    /**\n     * Checks whether a given value is a valid minimum decimal digit when compared to given value \n     * or not\n     * \n     * @param validationObject\n     * @param annotate\n     * @return\n     */\n    private boolean validateMinDecimal(Object validationObject, Annotation annotate)\n    {\n\n        if (validationObject != null)\n        {\n            try\n            {\n                if (checkvalidDeciDigitTypes(validationObject.getClass()))\n                {\n                    BigDecimal minValue = NumberUtils.createBigDecimal(((DecimalMin) annotate).value());\n                    BigDecimal actualValue = NumberUtils.createBigDecimal(toString(validationObject));\n                    int res = actualValue.compareTo(minValue);\n                    if (res < 0)\n                    {\n                        throwValidationException(((DecimalMin) annotate).message());\n                    }\n\n                }\n            }\n            catch (NumberFormatException nfe)\n            {\n                throw new RuleValidationException(nfe.getMessage());\n            }\n\n        }\n\n        return true;\n    }\n\n    /**\n     * Checks whether a given value is a valid maximum decimal digit when compared to given value \n     * or not\n     * \n     * @param validationObject\n     * @param annotate\n     * @return\n     */\n    private boolean validateMaxDecimal(Object validationObject, Annotation annotate)\n    {\n        if (validationObject != null)\n        {\n            try\n            {\n                if (checkvalidDeciDigitTypes(validationObject.getClass()))\n                {\n                    BigDecimal maxValue = NumberUtils.createBigDecimal(((DecimalMax) annotate).value());\n                    BigDecimal actualValue = NumberUtils.createBigDecimal(toString(validationObject));\n                    int res = actualValue.compareTo(maxValue);\n                    if (res >  0)\n                    {\n                        throwValidationException(((DecimalMax) annotate).message());\n                    }\n\n                }\n            }\n            catch (NumberFormatException nfe)\n            {\n                throw new RuleValidationException(nfe.getMessage());\n            }\n\n        }\n        return true;\n    }\n\n    /**\n     * @param validationObject\n     * @param annotate\n     * @return\n     */\n    private boolean validateTrue(Object validationObject, Annotation annotate)\n    {\n        if (checkNullObject(validationObject))\n        {\n            return true;\n        }\n\n        if (checkvalidBooleanTypes(validationObject.getClass()) && !(Boolean) validationObject)\n        {\n            throwValidationException(((AssertTrue) annotate).message());\n        }\n\n        return true;\n    }\n\n    /**\n     * @param validationObject\n     * @param annotate\n     * @return\n     */\n    private boolean validateFalse(Object validationObject, Annotation annotate)\n    {\n        if (checkNullObject(validationObject))\n        {\n            return true;\n        }\n\n        if (checkvalidBooleanTypes(validationObject.getClass()) && (Boolean) validationObject)\n        {\n            throwValidationException(((AssertFalse) annotate).message());\n\n        }\n\n        return true;\n    }\n\n    /**\n     * @param javaType\n     * @return\n     */\n    private boolean checkvalidDigitTypes(Class<?> javaType)\n    {\n        return javaType.isAssignableFrom(BigDecimal.class) || javaType.isAssignableFrom(byte.class)\n                || javaType.isAssignableFrom(Byte.class) || javaType.isAssignableFrom(short.class)\n                || javaType.isAssignableFrom(Short.class) || javaType.isAssignableFrom(int.class)\n                || javaType.isAssignableFrom(Integer.class) || javaType.isAssignableFrom(long.class)\n                || javaType.isAssignableFrom(Long.class);\n\n    }\n\n    /**\n     * @param javaType\n     * @return\n     */\n    private boolean checkvalidBooleanTypes(Class<?> javaType)\n    {\n        return javaType.isAssignableFrom(Boolean.class) || javaType.isAssignableFrom(boolean.class);\n\n    }\n\n    /**\n     * @param javaType\n     * @return\n     */\n    private boolean checkvalidDeciDigitTypes(Class<?> javaType)\n    {\n        return javaType.isAssignableFrom(BigDecimal.class) || javaType.isAssignableFrom(String.class)\n                || javaType.isAssignableFrom(byte.class) || javaType.isAssignableFrom(Byte.class)\n                || javaType.isAssignableFrom(short.class) || javaType.isAssignableFrom(Short.class)\n                || javaType.isAssignableFrom(int.class) || javaType.isAssignableFrom(Integer.class)\n                || javaType.isAssignableFrom(long.class) || javaType.isAssignableFrom(Long.class);\n\n    }\n\n    /**\n     * @param validationObject\n     * @return\n     */\n    private String toString(Object validationObject)\n    {\n        String stringObject = null;\n        if (validationObject.getClass().isAssignableFrom(int.class)\n                || validationObject.getClass().isAssignableFrom(Integer.class))\n        {\n            stringObject = Integer.toString((Integer) validationObject);\n\n        }\n        else if (validationObject.getClass().isAssignableFrom(byte.class)\n                || validationObject.getClass().isAssignableFrom(Byte.class))\n        {\n            stringObject = Byte.toString((Byte) validationObject);\n        }\n        else if (validationObject.getClass().isAssignableFrom(short.class)\n                || validationObject.getClass().isAssignableFrom(Short.class))\n        {\n            stringObject = Short.toString((Short) validationObject);\n        }\n\n        else if (validationObject.getClass().isAssignableFrom(BigDecimal.class))\n        {\n            stringObject = validationObject.toString();\n        }\n        else if (validationObject.getClass().isAssignableFrom(Long.class)\n                || validationObject.getClass().isAssignableFrom(long.class))\n        {\n            stringObject = Long.toString((Long) validationObject);\n        }\n\n        else if (validationObject.getClass().isAssignableFrom(String.class)\n                || validationObject.getClass().isAssignableFrom(String.class))\n        {\n            stringObject = (String) validationObject;\n        }\n\n        return stringObject;\n    }\n\n    /**\n     * @param validationObject\n     * @return\n     */\n    private boolean checkNullObject(Object validationObject)\n    {\n\n        return validationObject == null;\n    }\n\n    /**\n     * @param message\n     */\n    private void throwValidationException(String message)\n    {\n        if (!message.isEmpty() || message != null)\n        {\n            throw new ValidationException(message);\n        }\n        else\n        {\n            throw new ValidationException(\"Constraint validation exception\");\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/EntityAnnotationRule.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation.rules;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Modifier;\n\nimport javax.persistence.Embeddable;\nimport javax.persistence.Entity;\nimport javax.persistence.MappedSuperclass;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class EntityAnnotationRule extends AbstractEntityRule implements EntityRule {\n\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(EntityAnnotationRule.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.validation.rules.AbstractEntityRule#validate(java .lang.Class)\n     */\n    @Override\n    public void validate(Class<?> clazz) {\n\n        if (log.isDebugEnabled())\n            log.debug(\"Validating \" + clazz.getName());\n\n        // Is Entity?\n        if (!checkValidClass(clazz)) {\n\n            throw new RuleValidationException(clazz.getName() + \" is not a valid jpa entity.\");\n        }\n\n        // must have a default no-argument constructor\n        boolean flag = false;\n        try {\n            Constructor[] constructors = clazz.getDeclaredConstructors();\n            for (Constructor constructor : constructors) {\n                if ((Modifier.isPublic(constructor.getModifiers()) || Modifier.isProtected(constructor.getModifiers()))\n                    && constructor.getParameterTypes().length == 0) {\n                    flag = true;\n                    break;\n                }\n            }\n            if (!flag) {\n                throw new Exception();\n            }\n        } catch (Exception e) {\n            throw new RuleValidationException(clazz.getName()\n                + \" must have a default public or protected no-argument constructor.\");\n        }\n    }\n\n    /**\n     * checks for a valid entity definition\n     * \n     * @param clazz\n     * @return\n     */\n    private boolean checkValidClass(Class<?> clazz) {\n        return clazz.isAnnotationPresent(Entity.class) || clazz.isAnnotationPresent(MappedSuperclass.class)\n            || clazz.isAnnotationPresent(Embeddable.class);\n\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/EntityFieldAnnotationRule.java",
    "content": "package com.impetus.kundera.validation.rules;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javassist.Modifier;\n\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Embedded;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.MappedSuperclass;\nimport javax.persistence.OneToMany;\nimport javax.persistence.OneToOne;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\nimport javax.persistence.Transient;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class EntityFieldAnnotationRule extends AbstractEntityRule implements EntityRule\n{\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(EntityFieldAnnotationRule.class);\n    @Override\n    public void validate(Class<?> clazz)\n    {\n\n      \n        // Check for @Key and ensure that there is just 1 @Key field of\n        // String\n        // type.\n        List<Field> keys = new ArrayList<Field>();\n        for (Field field : clazz.getDeclaredFields())\n        {\n//            if (checkValidField(field))\n//            {\n                onIdField(field, clazz);\n                if (field.isAnnotationPresent(Id.class))\n                {\n                    keys.add(field);\n                    // validate @GeneratedValue annotation if given\n                    if (field.isAnnotationPresent(GeneratedValue.class))\n                    {\n                        validateGeneratedValueAnnotation(clazz, field);\n                    }\n                }\n                else if (field.isAnnotationPresent(EmbeddedId.class))\n                {\n                    keys.add(field);\n                }\n//            }\n//            else\n//            {\n//\n//                throw new RuleValidationException(\" Invalid attribute annotation defined for : \"\n//                        + field.getName() + \" of class \" + clazz.getName());\n//            }\n        }\n\n        // Check for a class key only in case it's of type entity or\n        // MappedSuperClass\n        if (clazz.isAnnotationPresent(Entity.class) || clazz.isAnnotationPresent(MappedSuperclass.class))\n        {\n            onSuperClass(clazz, keys);\n        }\n\n    }\n\n    /**\n     * Checks whether the defined class is a validone with an id field present\n     * either in class itself or its superclass\n     * \n     * @param clazz\n     * @param keys\n     * @throws RuleValidationException\n     */\n    private void onSuperClass(Class<?> clazz, List<Field> keys)\n    {\n\n        Class<?> superClass = clazz.getSuperclass();\n        if (superClass != null\n                && (superClass.isAnnotationPresent(MappedSuperclass.class) || superClass\n                        .isAnnotationPresent(Entity.class)))\n        {\n\n            while (superClass != null\n                    && (superClass.isAnnotationPresent(MappedSuperclass.class) || superClass\n                            .isAnnotationPresent(Entity.class)))\n            {\n                for (Field field : superClass.getDeclaredFields())\n                {\n\n//                    if (checkValidField(field))\n//                    {\n\n                        onIdField(field, superClass);\n                        if (field.isAnnotationPresent(Id.class))\n                        {\n                            keys.add(field);\n                            // validate @GeneratedValue annotation if given\n                            if (field.isAnnotationPresent(GeneratedValue.class))\n                            {\n                                validateGeneratedValueAnnotation(superClass, field);\n                            }\n                        }\n                        else if (field.isAnnotationPresent(EmbeddedId.class))\n                        {\n                            keys.add(field);\n                        }\n\n                   // }\n                }\n\n                if (keys.size() > 0)\n                {\n                    onEntityKey(keys, superClass);\n                    break;\n                }\n                superClass = superClass.getSuperclass();\n\n            }\n        }\n\n        onEntityKey(keys, clazz);\n\n    }\n\n    /**\n     * @param field\n     * @param clazz\n     */\n    private void onIdField(Field field, Class<?> clazz)\n    {\n\n        if (field.isAnnotationPresent(Id.class) && field.isAnnotationPresent(EmbeddedId.class))\n        {\n\n            throw new RuleValidationException(clazz.getName()\n                    + \" must have either @Id field or @EmbeddedId field\");\n        }\n\n    }\n\n    /**\n     * @param keys\n     * @param clazz\n     */\n    private void onEntityKey(List<Field> keys, Class<?> clazz)\n    {\n\n        if (keys.size() <= 0)\n        {\n\n            throw new RuleValidationException(clazz.getName() + \" must have an @Id field.\");\n\n        }\n        else if (keys.size() > 1)\n        {\n\n            throw new RuleValidationException(clazz.getName() + \" can only have 1 @Id field.\");\n\n        }\n\n    }\n\n    /**\n     * @param field\n     * @return\n     */\n    private boolean checkValidField(Field field)\n    {\n        if (field != null && !Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())\n                && !field.isAnnotationPresent(Transient.class))\n        {\n            return field.isAnnotationPresent(Id.class) || field.isAnnotationPresent(EmbeddedId.class)\n                    || field.isAnnotationPresent(Column.class) || field.isAnnotationPresent(ManyToMany.class)\n                    || field.isAnnotationPresent(ManyToOne.class) || field.isAnnotationPresent(OneToOne.class)\n                    || field.isAnnotationPresent(Embedded.class) || field.isAnnotationPresent(OneToMany.class)\n                    || field.isAnnotationPresent(ElementCollection.class);\n        }\n        else\n        {\n            return true;\n        }\n\n    }\n\n   \n    /**\n     * validate generated value annotation if given.\n     * \n     * @param clazz\n     * @param field\n     * @throws RuleValidationException\n     */\n    private void validateGeneratedValueAnnotation(final Class<?> clazz, Field field)\n    {\n\n        Table table = clazz.getAnnotation(Table.class);\n        // Still we need to validate for this after post metadata\n        // population.\n        if (table != null)\n        {\n            String schemaName = table.schema();\n            if (schemaName != null && schemaName.indexOf('@') > 0)\n            {\n                schemaName = schemaName.substring(0, schemaName.indexOf('@'));\n                GeneratedValue generatedValue = field.getAnnotation(GeneratedValue.class);\n                if (generatedValue != null && generatedValue.generator() != null\n                        && !generatedValue.generator().isEmpty())\n                {\n                    if (!(field.isAnnotationPresent(TableGenerator.class)\n                            || field.isAnnotationPresent(SequenceGenerator.class)\n                            || clazz.isAnnotationPresent(TableGenerator.class) || clazz\n                            .isAnnotationPresent(SequenceGenerator.class)))\n                    {\n\n                        throw new IllegalArgumentException(\"Unknown Id.generator: \" + generatedValue.generator());\n                    }\n                    else\n                    {\n                        checkForGenerator(clazz, field, generatedValue, schemaName);\n                    }\n                }\n            }\n        }\n\n    }\n\n    /**\n     * Validate for generator.\n     * \n     * @param clazz\n     * @param field\n     * @param generatedValue\n     * @param schemaName\n     * @throws RuleValidationException\n     */\n    private void checkForGenerator(final Class<?> clazz, Field field, GeneratedValue generatedValue, String schemaName)\n\n    {\n\n        TableGenerator tableGenerator = field.getAnnotation(TableGenerator.class);\n        SequenceGenerator sequenceGenerator = field.getAnnotation(SequenceGenerator.class);\n        if (tableGenerator == null || !tableGenerator.name().equals(generatedValue.generator()))\n        {\n            tableGenerator = clazz.getAnnotation(TableGenerator.class);\n        }\n        if (sequenceGenerator == null || !sequenceGenerator.name().equals(generatedValue.generator()))\n        {\n            sequenceGenerator = clazz.getAnnotation(SequenceGenerator.class);\n        }\n\n        if ((tableGenerator == null && sequenceGenerator == null)\n                || (tableGenerator != null && !tableGenerator.name().equals(generatedValue.generator()))\n                || (sequenceGenerator != null && !sequenceGenerator.name().equals(generatedValue.generator())))\n        {\n\n            throw new RuleValidationException(\"Unknown Id.generator: \" + generatedValue.generator());\n\n        }\n        else if ((tableGenerator != null && !tableGenerator.schema().isEmpty() && !tableGenerator.schema().equals(\n                schemaName))\n                || (sequenceGenerator != null && !sequenceGenerator.schema().isEmpty() && !sequenceGenerator.schema()\n                        .equals(schemaName)))\n        {\n\n            throw new RuleValidationException(\"Generator \" + generatedValue.generator() + \" in entity : \"\n                    + clazz.getName() + \" has different schema name ,it should be same as entity have\");\n\n        }\n\n    }\n\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/EntityRule.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation.rules;\n\n\n\n/**\n * @author Chhavi Gangwal\n *\n */\npublic interface EntityRule  extends IRule\n{\n  /**\n * @param clazz\n * @throws RuleValidationException\n */\nvoid validate(Class<?> clazz) throws RuleValidationException;\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/FieldRule.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation.rules;\n\nimport java.lang.reflect.Field;\n\n/**\n * @author Chhavi Gangwal\n *\n */\npublic interface FieldRule extends IRule\n{\n    /**\n     * @param f\n     * @param fieldValue\n     * @return\n     * @throws RuleValidationException\n     */\n    boolean validate(Field f, Object fieldValue) throws RuleValidationException;\n    \n    /**\n     * @param f\n     * @return\n     * @throws RuleValidationException\n     */\n    boolean validate(Field f) throws RuleValidationException;\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/IRule.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.impetus.kundera.validation.rules;\n\n\n/**\n * Marker Interface for Business and JPA rules.\n\n * @author vivek.mishra\n *\n */\npublic interface IRule\n{\n    \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/NullOrInvalidEntityRule.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.impetus.kundera.validation.rules;\n\nimport com.impetus.kundera.metadata.model.EntityMetadata;\n\n/**\n * Check if entity is not null and contains valid entity metadata\n * \n * @author vivek.mishra\n * \n * @param <E>\n */\npublic class NullOrInvalidEntityRule<E extends Object>\n{\n\n    private EntityMetadata entityMetadata;\n\n    public NullOrInvalidEntityRule(EntityMetadata entityMetadata)\n    {\n        this.entityMetadata = entityMetadata;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.validation.rules.IRule#validate(java.lang.Object)\n     */\n    \n    public boolean validate(E entity)\n    {\n        if (entity != null)\n        {\n            // entity metadata could be null.\n            if (entityMetadata == null)\n            {\n                throw new IllegalArgumentException(\n                        \"Entity object is invalid, operation failed. Please check previous log message for details\");\n            }\n\n            return false;\n\n        }\n\n        // will return false if entity is null.\n        return true;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/PrimaryKeyNullCheck.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.impetus.kundera.validation.rules;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n\n/**\n * Check if primary key is null \n * \n * @author vivek.mishra\n * \n * @param <E> @Id attribute.\n */\npublic class PrimaryKeyNullCheck<E extends Object>\n{\n    private static final Logger log = LoggerFactory.getLogger(PrimaryKeyNullCheck.class);\n\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.validation.rules.IRule#validate(java.lang.Object)\n     */\n    \n    public boolean validate(E value)\n    {\n        if (value == null)\n        {\n            log.error(\"Entity to be persisted can't have Primary key set to null.\");\n            throw new IllegalArgumentException(\"Entity to be persisted can't have Primary key set to null.\");\n        }\n        \n        return true;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/RelationAttributeRule.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation.rules;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.util.EnumSet;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.AssociationOverride;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Embedded;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.MapKeyClass;\nimport javax.persistence.MapKeyJoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.OneToOne;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.metadata.validator.InvalidEntityDefinitionException;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\n\n/**\n * @author Chhavi Gangwal\n *\n */\npublic class RelationAttributeRule extends AbstractFieldRule implements FieldRule\n{\n\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(RelationAttributeRule.class);\n\n    /** The relation type map. */\n    static enum RelationType\n    {\n\n        MANY_TO_MANY(ManyToMany.class.getSimpleName()), MANY_TO_ONE(ManyToOne.class.getSimpleName()), ONE_TO_MANY(\n                OneToMany.class.getSimpleName()), ONE_TO_ONE(OneToOne.class.getSimpleName()), ELEMENT_COLLECTION(\n                ElementCollection.class.getSimpleName()), EMBEDDED_ID(EmbeddedId.class.getSimpleName()), EMBEDDED(\n                Embedded.class.getSimpleName());\n\n        private String clazz;\n\n        private static final Map<String, RelationType> lookup = new HashMap<String, RelationType>();\n\n        static\n        {\n            for (RelationType s : EnumSet.allOf(RelationType.class))\n            {\n                lookup.put(s.getClazz(), s);\n            }\n        }\n\n        /**\n         * @param clazz\n         */\n        private RelationType(String clazz)\n        {\n            this.clazz = clazz;\n        }\n\n        /**\n         * @return\n         */\n        public String getClazz()\n        {\n            return clazz;\n        }\n\n        /**\n         * @param clazz\n         * @return\n         */\n        public static RelationType get(String clazz)\n        {\n            return lookup.get(clazz);\n        }\n    }\n\n    /**\n     * @param annotationType\n     * @return\n     */\n    private RelationType getRuleType(String annotationType)\n    {\n\n        if (RelationType.get(annotationType) != null)\n        {\n            return RelationType.get(annotationType);\n        }\n        else\n        {\n            return null;\n        }\n\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.validation.rules.AbstractFieldRule#validate(java.lang.reflect.Field)\n     */\n    @Override\n    public boolean validate(Field f) throws RuleValidationException\n    {\n\n        boolean checkvalidation = true;\n        for (Annotation annotate : f.getDeclaredAnnotations())\n        {\n            RelationType eruleType = getRuleType(annotate.annotationType().getSimpleName());\n\n            if (eruleType != null)\n            {\n\n                switch (eruleType)\n                {\n                case MANY_TO_MANY:\n                    checkvalidation = validateManyToMany(f, annotate);\n                    break;\n                case MANY_TO_ONE:\n                    checkvalidation = validateManyToOne(f, annotate);\n                    break;\n                case ONE_TO_MANY:\n                    checkvalidation = validateOneToMany(f, annotate);\n                    break;\n                case ONE_TO_ONE:\n                    checkvalidation = validateOneToOne(f, annotate);\n                    break;\n\n                }\n\n            }\n        }\n\n        return checkvalidation;\n    }\n\n    /**\n     * @param relationField\n     * @param annotate\n     * @return\n     */\n    private Boolean validateOneToOne(Field relationField, Annotation annotate)\n    {\n       \n\n        boolean isJoinedByTable = relationField.isAnnotationPresent(JoinTable.class);\n\n        if (relationField.isAnnotationPresent(AssociationOverride.class))\n        {\n            AssociationOverride annotation = relationField.getAnnotation(AssociationOverride.class);\n            JoinColumn[] joinColumns = annotation.joinColumns();\n\n            validateJoinColumns(joinColumns);\n\n            JoinTable joinTable = annotation.joinTable();\n            onJoinTable(joinTable);\n        }\n        else if (isJoinedByTable)\n        {\n            throw new UnsupportedOperationException(\"@JoinTable not supported for one to one association\");\n        }\n        return true;\n    }\n\n    /**\n     * @param relationField\n     * @param annotate\n     * @return\n     * @throws RuleValidationException\n     */\n    private Boolean validateOneToMany(Field relationField, Annotation annotate) throws RuleValidationException\n    {\n\n        OneToMany ann = (OneToMany) annotate;\n        Class<?> targetEntity = PropertyAccessorHelper.getGenericClass(relationField);\n\n        // now, check annotations\n        if (null != ann.targetEntity() && !ann.targetEntity().getSimpleName().equals(\"void\"))\n        {\n            targetEntity = ann.targetEntity();\n        }\n\n        boolean isJoinedByTable = relationField.isAnnotationPresent(JoinTable.class);\n\n        if (isJoinedByTable)\n        {\n            throw new UnsupportedOperationException(\"@JoinTable not supported for one to many association\");\n        }\n\n        boolean isJoinedByColumn = relationField.isAnnotationPresent(JoinTable.class);\n\n        return true;\n    }\n\n    /**\n     * @param relationField\n     * @param annotate\n     * @return\n     */\n    private Boolean validateManyToOne(Field relationField, Annotation annotate)\n    {\n        // taking field's type as foreign entity, ignoring \"targetEntity\"\n\n        Class<?> targetEntity = relationField.getType();\n\n        boolean isJoinedByTable = relationField.isAnnotationPresent(JoinTable.class);\n          \n        if (relationField.isAnnotationPresent(AssociationOverride.class))\n        {\n            AssociationOverride annotation = relationField.getAnnotation(AssociationOverride.class);\n            JoinColumn[] joinColumns = annotation.joinColumns();\n            \n            //validate if more than one  join column is defined\n            validateJoinColumns(joinColumns);\n\n            JoinTable joinTable = annotation.joinTable();\n            //validate if join table is null\n            onJoinTable(joinTable);\n        }\n        // join table not valid for Many to one check\n        else if (isJoinedByTable)\n        { \n            throw new UnsupportedOperationException(\"@JoinTable not supported for many to one association\");\n        }\n\n        return true;\n    }\n\n    /**\n     * @param relationField\n     * @param annotate\n     * @return\n     * @throws RuleValidationException\n     */\n    private Boolean validateManyToMany(Field relationField, Annotation annotate) throws RuleValidationException\n    {\n        ManyToMany m2mAnnotation = (ManyToMany) annotate;\n\n        boolean isJoinedByFK = relationField.isAnnotationPresent(JoinColumn.class);\n        boolean isJoinedByTable = relationField.isAnnotationPresent(JoinTable.class);\n        boolean isJoinedByMap = false;\n        if (m2mAnnotation != null && relationField.getType().isAssignableFrom(Map.class))\n        {\n            isJoinedByMap = true;\n        }\n\n        Class<?> targetEntity = null;\n        Class<?> mapKeyClass = null;\n\n        if (!isJoinedByMap)\n        {\n\n            targetEntity = PropertyAccessorHelper.getGenericClass(relationField);\n        }\n        else\n        {\n            List<Class<?>> genericClasses = PropertyAccessorHelper.getGenericClasses(relationField);\n\n            if (!genericClasses.isEmpty() && genericClasses.size() == 2)\n            {\n                mapKeyClass = genericClasses.get(0);\n                targetEntity = genericClasses.get(1);\n            }\n\n            MapKeyClass mapKeyClassAnn = relationField.getAnnotation(MapKeyClass.class);\n\n            // Check for Map key class specified at annotation\n            if (mapKeyClass == null && mapKeyClassAnn != null && mapKeyClassAnn.value() != null\n                    && !mapKeyClassAnn.value().getSimpleName().equals(\"void\"))\n            {\n                mapKeyClass = mapKeyClassAnn.value();\n            }\n\n            if (mapKeyClass == null)\n            {\n                throw new InvalidEntityDefinitionException(\n                        \"For a Map relationship field,\"\n                                + \" it is mandatory to specify Map key class either using @MapKeyClass annotation or through generics\");\n            }\n\n        }\n\n        // Check for target class specified at annotation\n        if (targetEntity == null && null != m2mAnnotation.targetEntity()\n                && !m2mAnnotation.targetEntity().getSimpleName().equals(\"void\"))\n        {\n            targetEntity = m2mAnnotation.targetEntity();\n        }\n        //check if target entity is null\n        if (targetEntity == null)\n        {\n            throw new InvalidEntityDefinitionException(\"Could not determine target entity class for relationship.\"\n                    + \" It should either be specified using targetEntity attribute of @ManyToMany or through generics\");\n        }\n        //check if joined by foreign key\n        if (isJoinedByFK)\n        {\n            throw new InvalidEntityDefinitionException(\n                    \"@JoinColumn not allowed for ManyToMany relationship. Use @JoinTable instead\");\n\n        }\n      //check if joined by foreign key and join column name is set\n        if (isJoinedByMap)\n        {\n\n            MapKeyJoinColumn mapKeyJoinColumnAnn = relationField.getAnnotation(MapKeyJoinColumn.class);\n            if (mapKeyJoinColumnAnn != null)\n            {\n                String mapKeyJoinColumnName = mapKeyJoinColumnAnn.name();\n                if (StringUtils.isEmpty(mapKeyJoinColumnName))\n                {\n                    throw new InvalidEntityDefinitionException(\n                            \"It's mandatory to specify name attribute with @MapKeyJoinColumn annotation\");\n                }\n            }\n\n        }\n        //check if not joined by table in many to many\n        if (!isJoinedByTable && !isJoinedByMap\n                && (m2mAnnotation.mappedBy() == null || m2mAnnotation.mappedBy().isEmpty()))\n        {\n            throw new InvalidEntityDefinitionException(\n                    \"It's manadatory to use @JoinTable with parent side of ManyToMany relationship.\");\n        }\n        return true;\n    }\n\n    /**\n     * @param joinTable\n     */\n    private void onJoinTable(JoinTable joinTable)\n    {\n        if (joinTable != null)\n        {\n            throw new UnsupportedOperationException(\"@JoinTable not supported for many to one association\");\n        }\n    }\n\n    /**\n     * @param joinColumns\n     */\n    private void validateJoinColumns(JoinColumn[] joinColumns)\n    {\n        if (joinColumns.length > 1)\n        {\n            throw new UnsupportedOperationException(\"More than one join columns are not supported.\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/java/com/impetus/kundera/validation/rules/RuleValidationException.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validation.rules;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * @author Chhavi Gangwal\n *\n */\npublic class RuleValidationException extends KunderaException\n{\n\n    /**\n     * \n     */\n    public RuleValidationException()\n    {\n    }\n\n    /**\n     * @param arg0\n     */\n    public RuleValidationException(String message)\n    {\n        super(message);\n\n    }\n\n    /**\n     * @param arg0\n     */\n    public RuleValidationException(Throwable arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * @param arg0\n     * @param arg1\n     */\n    public RuleValidationException(String message, Throwable arg1)\n    {\n        super(message, arg1);\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/resources/META-INF/services/javax.persistence.spi.PersistenceProvider",
    "content": "com.impetus.kundera.KunderaPersistence\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/resources/persistence_1_0.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!-- persistence.xml schema -->\r\n<xsd:schema targetNamespace=\"http://java.sun.com/xml/ns/persistence\"\r\n            xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\r\n            xmlns:persistence=\"http://java.sun.com/xml/ns/persistence\"\r\n            elementFormDefault=\"qualified\"\r\n            attributeFormDefault=\"unqualified\"\r\n            version=\"1.0\">\r\n\r\n    <xsd:annotation>\r\n        <xsd:documentation>\r\n            @(#)persistence_1_0.xsd 1.0 Feb 9 2006\r\n        </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:annotation>\r\n        <xsd:documentation><![CDATA[\r\n\r\n     This is the XML Schema for the persistence configuration file.\r\n     The file must be named \"META-INF/persistence.xml\" in the \r\n     persistence archive.\r\n     Persistence configuration files must indicate\r\n     the persistence schema by using the persistence namespace:\r\n\r\n     http://java.sun.com/xml/ns/persistence\r\n\r\n     and indicate the version of the schema by\r\n     using the version element as shown below:\r\n\r\n      <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n        xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n          http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd\"\r\n        version=\"1.0\">\r\n          ...\r\n      </persistence>\r\n\r\n    ]]></xsd:documentation>\r\n    </xsd:annotation>\r\n\r\n    <xsd:simpleType name=\"versionType\">\r\n        <xsd:restriction base=\"xsd:token\">\r\n            <xsd:pattern value=\"[0-9]+(\\.[0-9]+)*\"/>\r\n        </xsd:restriction>\r\n    </xsd:simpleType>\r\n\r\n    <!-- **************************************************** -->\r\n\r\n    <xsd:element name=\"persistence\">\r\n        <xsd:complexType>\r\n            <xsd:sequence>\r\n\r\n                <!-- **************************************************** -->\r\n\r\n                <xsd:element name=\"persistence-unit\"\r\n                             minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                    <xsd:complexType>\r\n                        <xsd:annotation>\r\n                            <xsd:documentation>\r\n\r\n                                Configuration of a persistence unit.\r\n\r\n                            </xsd:documentation>\r\n                        </xsd:annotation>\r\n                        <xsd:sequence>\r\n\r\n                            <!-- **************************************************** -->\r\n\r\n                            <xsd:element name=\"description\" type=\"xsd:string\"\r\n                                         minOccurs=\"0\">\r\n                                <xsd:annotation>\r\n                                    <xsd:documentation>\r\n\r\n                                        Textual description of this persistence unit.\r\n\r\n                                    </xsd:documentation>\r\n                                </xsd:annotation>\r\n                            </xsd:element>\r\n\r\n                            <!-- **************************************************** -->\r\n\r\n                            <xsd:element name=\"provider\" type=\"xsd:string\"\r\n                                         minOccurs=\"0\">\r\n                                <xsd:annotation>\r\n                                    <xsd:documentation>\r\n\r\n                                        Provider class that supplies EntityManagers for this\r\n                                        persistence unit.\r\n\r\n                                    </xsd:documentation>\r\n                                </xsd:annotation>\r\n                            </xsd:element>\r\n\r\n                            <!-- **************************************************** -->\r\n\r\n                            <xsd:element name=\"jta-data-source\" type=\"xsd:string\"\r\n                                         minOccurs=\"0\">\r\n                                <xsd:annotation>\r\n                                    <xsd:documentation>\r\n\r\n                                        The container-specific name of the JTA datasource to use.\r\n\r\n                                    </xsd:documentation>\r\n                                </xsd:annotation>\r\n                            </xsd:element>\r\n\r\n                            <!-- **************************************************** -->\r\n\r\n                            <xsd:element name=\"non-jta-data-source\" type=\"xsd:string\"\r\n                                         minOccurs=\"0\">\r\n                                <xsd:annotation>\r\n                                    <xsd:documentation>\r\n\r\n                                        The container-specific name of a non-JTA datasource to use.\r\n\r\n                                    </xsd:documentation>\r\n                                </xsd:annotation>\r\n                            </xsd:element>\r\n\r\n                            <!-- **************************************************** -->\r\n\r\n                            <xsd:element name=\"mapping-file\" type=\"xsd:string\"\r\n                                         minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                                <xsd:annotation>\r\n                                    <xsd:documentation>\r\n\r\n                                        File containing mapping information. Loaded as a resource\r\n                                        by the persistence provider.\r\n\r\n                                    </xsd:documentation>\r\n                                </xsd:annotation>\r\n                            </xsd:element>\r\n\r\n                            <!-- **************************************************** -->\r\n\r\n                            <xsd:element name=\"jar-file\" type=\"xsd:string\"\r\n                                         minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                                <xsd:annotation>\r\n                                    <xsd:documentation>\r\n\r\n                                        Jar file that should be scanned for entities.\r\n                                        Not applicable to Java SE persistence units.\r\n\r\n                                    </xsd:documentation>\r\n                                </xsd:annotation>\r\n                            </xsd:element>\r\n\r\n                            <!-- **************************************************** -->\r\n\r\n                            <xsd:element name=\"class\" type=\"xsd:string\"\r\n                                         minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                                <xsd:annotation>\r\n                                    <xsd:documentation>\r\n\r\n                                        Class to scan for annotations. It should be annotated\r\n                                        with either @Entity, @Embeddable or @MappedSuperclass.\r\n\r\n                                    </xsd:documentation>\r\n                                </xsd:annotation>\r\n                            </xsd:element>\r\n\r\n                            <!-- **************************************************** -->\r\n\r\n                            <xsd:element name=\"exclude-unlisted-classes\" type=\"xsd:boolean\"\r\n                                         default=\"false\" minOccurs=\"0\">\r\n                                <xsd:annotation>\r\n                                    <xsd:documentation>\r\n\r\n                                        When set to true then only listed classes and jars will\r\n                                        be scanned for persistent classes, otherwise the enclosing\r\n                                        jar or directory will also be scanned. Not applicable to\r\n                                        Java SE persistence units.\r\n\r\n                                    </xsd:documentation>\r\n                                </xsd:annotation>\r\n                            </xsd:element>\r\n\r\n                            <!-- **************************************************** -->\r\n\r\n                            <xsd:element name=\"properties\" minOccurs=\"0\">\r\n                                <xsd:annotation>\r\n                                    <xsd:documentation>\r\n\r\n                                        A list of vendor-specific properties.\r\n\r\n                                    </xsd:documentation>\r\n                                </xsd:annotation>\r\n                                <xsd:complexType>\r\n                                    <xsd:sequence>\r\n                                        <xsd:element name=\"property\"\r\n                                                     minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                                            <xsd:annotation>\r\n                                                <xsd:documentation>\r\n                                                    A name-value pair.\r\n                                                </xsd:documentation>\r\n                                            </xsd:annotation>\r\n                                            <xsd:complexType>\r\n                                                <xsd:attribute name=\"name\" type=\"xsd:string\"\r\n                                                               use=\"required\"/>\r\n                                                <xsd:attribute name=\"value\" type=\"xsd:string\"\r\n                                                               use=\"required\"/>\r\n                                            </xsd:complexType>\r\n                                        </xsd:element>\r\n                                    </xsd:sequence>\r\n                                </xsd:complexType>\r\n                            </xsd:element>\r\n\r\n                        </xsd:sequence>\r\n\r\n                        <!-- **************************************************** -->\r\n\r\n                        <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\">\r\n                            <xsd:annotation>\r\n                                <xsd:documentation>\r\n\r\n                                    Name used in code to reference this persistence unit.\r\n\r\n                                </xsd:documentation>\r\n                            </xsd:annotation>\r\n                        </xsd:attribute>\r\n\r\n                        <!-- **************************************************** -->\r\n\r\n                        <xsd:attribute name=\"transaction-type\"\r\n                                       type=\"persistence:persistence-unit-transaction-type\">\r\n                            <xsd:annotation>\r\n                                <xsd:documentation>\r\n\r\n                                    Type of transactions used by EntityManagers from this\r\n                                    persistence unit.\r\n\r\n                                </xsd:documentation>\r\n                            </xsd:annotation>\r\n                        </xsd:attribute>\r\n\r\n                    </xsd:complexType>\r\n                </xsd:element>\r\n            </xsd:sequence>\r\n            <xsd:attribute name=\"version\" type=\"persistence:versionType\"\r\n                           fixed=\"1.0\" use=\"required\"/>\r\n        </xsd:complexType>\r\n    </xsd:element>\r\n\r\n    <!-- **************************************************** -->\r\n\r\n    <xsd:simpleType name=\"persistence-unit-transaction-type\">\r\n        <xsd:annotation>\r\n            <xsd:documentation>\r\n\r\n                public enum TransactionType { JTA, RESOURCE_LOCAL };\r\n\r\n            </xsd:documentation>\r\n        </xsd:annotation>\r\n        <xsd:restriction base=\"xsd:token\">\r\n            <xsd:enumeration value=\"JTA\"/>\r\n            <xsd:enumeration value=\"RESOURCE_LOCAL\"/>\r\n        </xsd:restriction>\r\n    </xsd:simpleType>\r\n\r\n</xsd:schema>\r\n\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/main/resources/persistence_2_0.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <!-- persistence.xml schema -->\n<xsd:schema targetNamespace=\"http://java.sun.com/xml/ns/persistence\"\n            xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n            xmlns:persistence=\"http://java.sun.com/xml/ns/persistence\"\n            elementFormDefault=\"qualified\"\n            attributeFormDefault=\"unqualified\"\n            version=\"2.0\">\n    <xsd:annotation>\n        <xsd:documentation>\n            @(#)persistence_2_0.xsd 1.0 October 1 2009\n        </xsd:documentation>\n    </xsd:annotation>\n    <xsd:annotation>\n        <xsd:documentation><![CDATA[\nThis is the XML Schema for the persistence configuration file. The file must be named \"META-INF/persistence.xml\" in the persistence archive.\nPersistence configuration files must indicate the persistence schema by using the persistence namespace:\nhttp://java.sun.com/xml/ns/persistence\nand indicate the version of the schema by using the version element as shown below:\n<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\nhttp://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\" version=\"2.0\">\n... </persistence>\n]]></xsd:documentation>\n    </xsd:annotation>\n    <xsd:simpleType name=\"versionType\">\n        <xsd:restriction base=\"xsd:token\">\n            <xsd:pattern value=\"[0-9]+(\\.[0-9]+)*\"/>\n        </xsd:restriction>\n    </xsd:simpleType>\n    <!-- **************************************************** -->\n    <xsd:element name=\"persistence\">\n        <xsd:complexType>\n            <xsd:sequence>\n                <!-- **************************************************** -->\n                <xsd:element name=\"persistence-unit\" minOccurs=\"1\" maxOccurs=\"unbounded\">\n                    <xsd:complexType>\n                        <xsd:annotation>\n                            <xsd:documentation>\n                                Configuration of a persistence unit.\n                            </xsd:documentation>\n                        </xsd:annotation>\n                        <xsd:sequence>\n                            <!-- **************************************************** -->\n                            <xsd:element name=\"description\" type=\"xsd:string\" minOccurs=\"0\">\n                                <xsd:annotation>\n                                    <xsd:documentation>\n                                        Description of this persistence unit.\n                                    </xsd:documentation>\n                                </xsd:annotation>\n                            </xsd:element>\n                            <!-- **************************************************** -->\n                            <xsd:element name=\"provider\" type=\"xsd:string\" minOccurs=\"0\">\n                                <xsd:annotation>\n                                    <xsd:documentation>\n                                        Provider class that supplies EntityManagers for this persistence unit.\n                                    </xsd:documentation>\n                                </xsd:annotation>\n                            </xsd:element>\n                            <!-- **************************************************** -->\n                            <xsd:element name=\"jta-data-source\" type=\"xsd:string\" minOccurs=\"0\">\n                                <xsd:annotation>\n                                    <xsd:documentation>\n                                        The container-specific name of the JTA datasource to use.\n                                    </xsd:documentation>\n                                </xsd:annotation>\n                            </xsd:element>\n                            <!-- **************************************************** -->\n                            <xsd:element name=\"non-jta-data-source\" type=\"xsd:string\" minOccurs=\"0\">\n                                <xsd:annotation>\n                                    <xsd:documentation>\n                                        The container-specific name of a non-JTA datasource to use.\n                                    </xsd:documentation>\n                                </xsd:annotation>\n                            </xsd:element>\n                            <!-- **************************************************** -->\n                            <xsd:element name=\"mapping-file\" type=\"xsd:string\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n                                <xsd:annotation>\n                                    <xsd:documentation>\n                                        File containing mapping information. Loaded as a resource by the persistence\n                                        provider.\n                                    </xsd:documentation>\n                                </xsd:annotation>\n                            </xsd:element>\n                            <!-- **************************************************** -->\n                            <xsd:element name=\"jar-file\" type=\"xsd:string\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n                                <xsd:annotation>\n                                    <xsd:documentation>\n                                        Jar file that is to be scanned for managed classes.\n                                    </xsd:documentation>\n                                </xsd:annotation>\n                            </xsd:element>\n                            <!-- **************************************************** -->\n                            <xsd:element name=\"class\" type=\"xsd:string\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n                                <xsd:annotation>\n                                    <xsd:documentation>\n                                        Managed class to be included in the persistence unit and to scan for\n                                        annotations. It should be annotated with either @Entity, @Embeddable or\n                                        @MappedSuperclass.\n                                    </xsd:documentation>\n                                </xsd:annotation>\n                            </xsd:element>\n                            <!-- **************************************************** -->\n                            <xsd:element name=\"exclude-unlisted-classes\"\n                                         type=\"xsd:boolean\"\n                                         default=\"true\"\n                                         minOccurs=\"0\">\n                                <xsd:annotation>\n                                    <xsd:documentation>\n                                        When set to true then only listed classes and jars will be scanned for\n                                        persistent classes, otherwise the enclosing jar or directory will also be\n                                        scanned. Not applicable to Java SE persistence units.\n                                    </xsd:documentation>\n                                </xsd:annotation>\n                            </xsd:element>\n                            <!-- **************************************************** -->\n                            <xsd:element name=\"shared-cache-mode\" type=\"persistence:persistence-unit-caching-type\"\n                                         minOccurs=\"0\">\n                                <xsd:annotation>\n                                    <xsd:documentation>\n                                        Defines whether caching is enabled for the persistence unit if caching is\n                                        supported by the persistence provider. When set to ALL, all entities will be\n                                        cached. When set to NONE, no entities will be cached. When set to\n                                        ENABLE_SELECTIVE, only entities specified as cacheable will be cached. When set\n                                        to\n                                        JSR-317 Final Release\n                                        323 11/10/09\n                                        Sun Microsystems, Inc.\n                                        Entity Packaging\n                                        Java Persistence 2.0, Final Release persistence.xml Schema\n                                        DISABLE_SELECTIVE, entities specified as not cacheable will not be cached. When\n                                        not specified or when set to UNSPECIFIED, provider defaults may apply.\n                                    </xsd:documentation>\n                                </xsd:annotation>\n                            </xsd:element>\n                            <!-- **************************************************** -->\n                            <xsd:element name=\"validation-mode\" type=\"persistence:persistence-unit-validation-mode-type\"\n                                         minOccurs=\"0\">\n                                <xsd:annotation>\n                                    <xsd:documentation>The validation mode to be used for the persistence unit.\n                                    </xsd:documentation>\n                                </xsd:annotation>\n                            </xsd:element>\n                            <!-- **************************************************** -->\n                            <xsd:element name=\"properties\" minOccurs=\"0\">\n                                <xsd:annotation>\n                                    <xsd:documentation>\n                                        A list of standard and vendor-specific properties and hints.\n                                    </xsd:documentation>\n                                </xsd:annotation>\n                                <xsd:complexType>\n                                    <xsd:sequence>\n                                        <xsd:element name=\"property\"\n                                                     minOccurs=\"0\" maxOccurs=\"unbounded\">\n                                            <xsd:annotation>\n                                                <xsd:documentation>A name-value pair.</xsd:documentation>\n                                            </xsd:annotation>\n                                            <xsd:complexType>\n                                                <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\"/>\n                                                <xsd:attribute name=\"value\" type=\"xsd:string\" use=\"required\"/>\n                                            </xsd:complexType>\n                                        </xsd:element>\n                                    </xsd:sequence>\n                                </xsd:complexType>\n                            </xsd:element>\n                        </xsd:sequence>\n                        <!-- **************************************************** -->\n                        <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\">\n                            <xsd:annotation>\n                                <xsd:documentation>Name used in code to reference this persistence unit.\n                                </xsd:documentation>\n\n                            </xsd:annotation>\n                        </xsd:attribute>\n                        <!-- **************************************************** -->\n                        <xsd:attribute name=\"transaction-type\" type=\"persistence:persistence-unit-transaction-type\">\n                            <xsd:annotation>\n                                <xsd:documentation>\n                                    Type of transactions used by EntityManagers from this persistence unit.\n                                </xsd:documentation>\n                            </xsd:annotation>\n                        </xsd:attribute>\n                    </xsd:complexType>\n                </xsd:element>\n            </xsd:sequence>\n            <xsd:attribute name=\"version\" type=\"persistence:versionType\"\n                           fixed=\"2.0\" use=\"required\"/>\n        </xsd:complexType>\n    </xsd:element>\n    <!-- **************************************************** -->\n    <xsd:simpleType name=\"persistence-unit-transaction-type\">\n        <xsd:annotation>\n            <xsd:documentation>public enum PersistenceUnitTransactionType {JTA, RESOURCE_LOCAL};\n            </xsd:documentation>\n        </xsd:annotation>\n        <xsd:restriction base=\"xsd:token\">\n            <xsd:enumeration value=\"JTA\"/>\n            <xsd:enumeration value=\"RESOURCE_LOCAL\"/>\n        </xsd:restriction>\n    </xsd:simpleType>\n    <!-- **************************************************** -->\n    <xsd:simpleType name=\"persistence-unit-caching-type\">\n        <xsd:annotation>\n            <xsd:documentation>\n                public enum SharedCacheMode { ALL, NONE, ENABLE_SELECTIVE, DISABLE_SELECTIVE, UNSPECIFIED};\n            </xsd:documentation>\n        </xsd:annotation>\n        <xsd:restriction base=\"xsd:token\">\n            <xsd:enumeration value=\"ALL\"/>\n            <xsd:enumeration value=\"NONE\"/>\n            <xsd:enumeration value=\"ENABLE_SELECTIVE\"/>\n            <xsd:enumeration value=\"DISABLE_SELECTIVE\"/>\n            <xsd:enumeration value=\"UNSPECIFIED\"/>\n        </xsd:restriction>\n    </xsd:simpleType>\n\n    <!-- **************************************************** -->\n    <xsd:simpleType name=\"persistence-unit-validation-mode-type\">\n        <xsd:annotation>\n            <xsd:documentation>public enum ValidationMode { AUTO, CALLBACK, NONE};\n            </xsd:documentation>\n        </xsd:annotation>\n        <xsd:restriction base=\"xsd:token\">\n            <xsd:enumeration value=\"AUTO\"/>\n            <xsd:enumeration value=\"CALLBACK\"/>\n            <xsd:enumeration value=\"NONE\"/>\n        </xsd:restriction>\n    </xsd:simpleType>\n</xsd:schema>"
  },
  {
    "path": "src/jpa-engine/core/src/main/resources/persistence_2_1.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- persistence.xml schema -->\n<xsd:schema targetNamespace=\"http://xmlns.jcp.org/xml/ns/persistence\" \n  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n  xmlns:persistence=\"http://xmlns.jcp.org/xml/ns/persistence\"\n  elementFormDefault=\"qualified\" \n  attributeFormDefault=\"unqualified\" \n  version=\"2.1\">\n\n  <xsd:annotation>\n    <xsd:documentation>\n      @(#)persistence_2_1.xsd  2.1  February 4, 2013\n    </xsd:documentation>\n  </xsd:annotation>\n\n  <xsd:annotation>\n    <xsd:documentation>\n\n  Copyright (c) 2008  - 2013 Oracle Corporation. All rights reserved. \n  \n  This program and the accompanying materials are made available under the \n  terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 \n  which accompanies this distribution. \n  The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html\n  and the Eclipse Distribution License is available at \n  http://www.eclipse.org/org/documents/edl-v10.php.\n  \n  Contributors:\n      Linda DeMichiel - Java Persistence 2.1, Version 2.1 (February 4, 2013)\n      Specification available from http://jcp.org/en/jsr/detail?id=338\n \n    </xsd:documentation>\n  </xsd:annotation>\n\n   <xsd:annotation>\n     <xsd:documentation><![CDATA[\n\n     This is the XML Schema for the persistence configuration file.\n     The file must be named \"META-INF/persistence.xml\" in the \n     persistence archive.\n\n     Persistence configuration files must indicate\n     the persistence schema by using the persistence namespace:\n\n     http://xmlns.jcp.org/xml/ns/persistence\n\n     and indicate the version of the schema by\n     using the version element as shown below:\n\n      <persistence xmlns=\"http://xmlns.jcp.org/xml/ns/persistence\"\n        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n        xsi:schemaLocation=\"http://xmlns.jcp.org/xml/ns/persistence\n          http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd\"\n        version=\"2.1\">\n          ...\n      </persistence>\n\n    ]]></xsd:documentation>\n  </xsd:annotation>\n\n  <xsd:simpleType name=\"versionType\">\n    <xsd:restriction base=\"xsd:token\">\n      <xsd:pattern value=\"[0-9]+(\\.[0-9]+)*\"/>\n    </xsd:restriction>\n  </xsd:simpleType>\n\n  <!-- **************************************************** -->\n\n  <xsd:element name=\"persistence\">\n    <xsd:complexType>\n      <xsd:sequence>\n\n        <!-- **************************************************** -->\n\n        <xsd:element name=\"persistence-unit\" \n                     minOccurs=\"1\" maxOccurs=\"unbounded\">\n          <xsd:complexType>\n            <xsd:annotation>\n              <xsd:documentation>\n\n                Configuration of a persistence unit.\n\n              </xsd:documentation>\n            </xsd:annotation>\n            <xsd:sequence>\n\n            <!-- **************************************************** -->\n\n              <xsd:element name=\"description\" type=\"xsd:string\" \n                           minOccurs=\"0\">\n                <xsd:annotation>\n                  <xsd:documentation>\n\n                    Description of this persistence unit.\n\n                  </xsd:documentation>\n                </xsd:annotation>\n              </xsd:element>\n\n              <!-- **************************************************** -->\n\n              <xsd:element name=\"provider\" type=\"xsd:string\" \n                           minOccurs=\"0\">\n                <xsd:annotation>\n                  <xsd:documentation>\n\n                    Provider class that supplies EntityManagers for this \n                    persistence unit.\n\n                  </xsd:documentation>\n                </xsd:annotation>\n              </xsd:element>\n\n              <!-- **************************************************** -->\n\n              <xsd:element name=\"jta-data-source\" type=\"xsd:string\" \n                           minOccurs=\"0\">\n                <xsd:annotation>\n                  <xsd:documentation>\n\n                    The container-specific name of the JTA datasource to use.\n\n                  </xsd:documentation>\n                </xsd:annotation>\n              </xsd:element>\n\n              <!-- **************************************************** -->\n\n              <xsd:element name=\"non-jta-data-source\" type=\"xsd:string\" \n                           minOccurs=\"0\">\n                <xsd:annotation>\n                  <xsd:documentation>\n\n                    The container-specific name of a non-JTA datasource to use.\n\n                  </xsd:documentation>\n                </xsd:annotation>\n              </xsd:element>\n\n              <!-- **************************************************** -->\n\n              <xsd:element name=\"mapping-file\" type=\"xsd:string\" \n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\n                <xsd:annotation>\n                  <xsd:documentation>\n\n                    File containing mapping information. Loaded as a resource \n                    by the persistence provider.\n\n                  </xsd:documentation>\n                </xsd:annotation>\n              </xsd:element>\n\n              <!-- **************************************************** -->\n\n              <xsd:element name=\"jar-file\" type=\"xsd:string\" \n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\n                <xsd:annotation>\n                  <xsd:documentation>\n\n                    Jar file that is to be scanned for managed classes. \n\n                  </xsd:documentation>\n                </xsd:annotation>\n              </xsd:element>\n\n              <!-- **************************************************** -->\n\n              <xsd:element name=\"class\" type=\"xsd:string\" \n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\n                <xsd:annotation>\n                  <xsd:documentation>\n\n                    Managed class to be included in the persistence unit and\n                    to scan for annotations.  It should be annotated \n                    with either @Entity, @Embeddable or @MappedSuperclass.\n\n                  </xsd:documentation>\n                </xsd:annotation>\n              </xsd:element>\n\n              <!-- **************************************************** -->\n\n              <xsd:element name=\"exclude-unlisted-classes\" type=\"xsd:boolean\" \n                           default=\"true\" minOccurs=\"0\">\n                <xsd:annotation>\n                  <xsd:documentation>\n\n                    When set to true then only listed classes and jars will \n                    be scanned for persistent classes, otherwise the \n                    enclosing jar or directory will also be scanned. \n                    Not applicable to Java SE persistence units.\n\n                  </xsd:documentation>\n                </xsd:annotation>\n              </xsd:element>\n\n              <!-- **************************************************** -->\n\n              <xsd:element name=\"shared-cache-mode\" \n                           type=\"persistence:persistence-unit-caching-type\" \n                           minOccurs=\"0\">\n                <xsd:annotation>\n                  <xsd:documentation>\n\n                    Defines whether caching is enabled for the \n                    persistence unit if caching is supported by the\n                    persistence provider. When set to ALL, all entities \n                    will be cached. When set to NONE, no entities will\n                    be cached. When set to ENABLE_SELECTIVE, only entities\n                    specified as cacheable will be cached. When set to\n                    DISABLE_SELECTIVE, entities specified as not cacheable\n                    will not be cached. When not specified or when set to\n                    UNSPECIFIED, provider defaults may apply.\n\n                  </xsd:documentation>\n                </xsd:annotation>\n              </xsd:element>\n\n              <!-- **************************************************** -->\n\n              <xsd:element name=\"validation-mode\" \n                           type=\"persistence:persistence-unit-validation-mode-type\" \n                           minOccurs=\"0\">\n                <xsd:annotation>\n                  <xsd:documentation>\n\n                    The validation mode to be used for the persistence unit.\n\n                  </xsd:documentation>\n                </xsd:annotation>\n              </xsd:element>\n\n\n              <!-- **************************************************** -->\n\n              <xsd:element name=\"properties\" minOccurs=\"0\">\n                <xsd:annotation>\n                  <xsd:documentation>\n\n                    A list of standard and vendor-specific properties \n                    and hints.\n\n                  </xsd:documentation>\n                </xsd:annotation>\n                <xsd:complexType>\n                  <xsd:sequence>\n                    <xsd:element name=\"property\" \n                                 minOccurs=\"0\" maxOccurs=\"unbounded\">\n                      <xsd:annotation>\n                        <xsd:documentation>\n                          A name-value pair.\n                        </xsd:documentation>\n                      </xsd:annotation>\n                      <xsd:complexType>\n                        <xsd:attribute name=\"name\" type=\"xsd:string\" \n                                       use=\"required\"/>\n                        <xsd:attribute name=\"value\" type=\"xsd:string\" \n                                       use=\"required\"/>\n                      </xsd:complexType>\n                    </xsd:element>\n                  </xsd:sequence>\n                </xsd:complexType>\n              </xsd:element>\n\n            </xsd:sequence>\n\n            <!-- **************************************************** -->\n\n            <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\">\n              <xsd:annotation>\n                <xsd:documentation>\n\n                  Name used in code to reference this persistence unit.\n\n                </xsd:documentation>\n              </xsd:annotation>\n            </xsd:attribute>\n\n            <!-- **************************************************** -->\n\n            <xsd:attribute name=\"transaction-type\" \n                           type=\"persistence:persistence-unit-transaction-type\">\n              <xsd:annotation>\n                <xsd:documentation>\n\n                  Type of transactions used by EntityManagers from this \n                  persistence unit.\n\n                </xsd:documentation>\n              </xsd:annotation>\n            </xsd:attribute>\n\n          </xsd:complexType>\n        </xsd:element>\n      </xsd:sequence>\n      <xsd:attribute name=\"version\" type=\"persistence:versionType\" \n                     fixed=\"2.1\" use=\"required\"/>\n    </xsd:complexType>\n  </xsd:element>\n\n  <!-- **************************************************** -->\n\n  <xsd:simpleType name=\"persistence-unit-transaction-type\">\n    <xsd:annotation>\n      <xsd:documentation>\n\n        public enum PersistenceUnitTransactionType {JTA, RESOURCE_LOCAL};\n\n      </xsd:documentation>\n    </xsd:annotation>\n    <xsd:restriction base=\"xsd:token\">\n      <xsd:enumeration value=\"JTA\"/>\n      <xsd:enumeration value=\"RESOURCE_LOCAL\"/>\n    </xsd:restriction>\n  </xsd:simpleType>\n\n<!-- **************************************************** -->\n\n  <xsd:simpleType name=\"persistence-unit-caching-type\">\n    <xsd:annotation>\n      <xsd:documentation>\n\n        public enum SharedCacheMode { ALL, NONE, ENABLE_SELECTIVE, DISABLE_SELECTIVE, UNSPECIFIED};\n\n      </xsd:documentation>\n    </xsd:annotation>\n    <xsd:restriction base=\"xsd:token\">\n      <xsd:enumeration value=\"ALL\"/>\n      <xsd:enumeration value=\"NONE\"/>\n      <xsd:enumeration value=\"ENABLE_SELECTIVE\"/>\n      <xsd:enumeration value=\"DISABLE_SELECTIVE\"/>\n      <xsd:enumeration value=\"UNSPECIFIED\"/>\n    </xsd:restriction>\n  </xsd:simpleType>\n\n<!-- **************************************************** -->\n\n  <xsd:simpleType name=\"persistence-unit-validation-mode-type\">\n    <xsd:annotation>\n      <xsd:documentation>\n\n        public enum ValidationMode { AUTO, CALLBACK, NONE};\n\n      </xsd:documentation>\n    </xsd:annotation>\n    <xsd:restriction base=\"xsd:token\">\n      <xsd:enumeration value=\"AUTO\"/>\n      <xsd:enumeration value=\"CALLBACK\"/>\n      <xsd:enumeration value=\"NONE\"/>\n    </xsd:restriction>\n  </xsd:simpleType>\n\n</xsd:schema>\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/client/crud/EmbeddedEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * \n * @author Kuldeep.Mishra\n *\n */\n@Embeddable\npublic class EmbeddedEntity\n{\n    @Column(name = \"EMAIL_ID\", table = \"SECONDARY_TABLE\")\n    private String emailId;\n\n    @Column(name = \"PHONE_NO\")\n    private long phoneNo;\n\n    public String getEmailId()\n    {\n        return emailId;\n    }\n\n    public void setEmailId(String emailId)\n    {\n        this.emailId = emailId;\n    }\n\n    public long getPhoneNo()\n    {\n        return phoneNo;\n    }\n\n    public void setPhoneNo(long phoneNo)\n    {\n        this.phoneNo = phoneNo;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/client/crud/SecondaryTableEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.SecondaryTable;\nimport javax.persistence.Table;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\n@Table(name = \"PRIMARY_TABLE\")\n@SecondaryTable(name = \"SECONDARY_TABLE\")\n@Entity\npublic class SecondaryTableEntity\n{\n    @Id\n    @Column(name = \"OBJECT_ID\")\n    private String objectId;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    @Column(name = \"AGE\", table = \"SECONDARY_TABLE\")\n    private int age;\n\n    @Embedded\n    private EmbeddedEntity embeddedEntity;\n\n    public String getObjectId()\n    {\n        return objectId;\n    }\n\n    public void setObjectId(String objectId)\n    {\n        this.objectId = objectId;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public EmbeddedEntity getEmbeddedEntity()\n    {\n        return embeddedEntity;\n    }\n\n    public void setEmbeddedEntity(EmbeddedEntity embeddedEntity)\n    {\n        this.embeddedEntity = embeddedEntity;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/client/crud/SecondaryTableTestBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\n\nimport org.junit.Assert;\n\n/**\n * \n * @author Kuldeep.Mishra\n *\n */\npublic class SecondaryTableTestBase\n{\n    protected void testCRUD(EntityManagerFactory emf)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        EmbeddedEntity embeddedEntity = new EmbeddedEntity();\n        embeddedEntity.setEmailId(\"kuldeep.mishra@gmail.com\");\n        embeddedEntity.setPhoneNo(9512345346l);\n\n        SecondaryTableEntity entity = new SecondaryTableEntity();\n        entity.setAge(24);\n        entity.setObjectId(\"123\");\n        entity.setName(\"Kuldeep\");\n        entity.setEmbeddedEntity(embeddedEntity);\n\n        em.persist(entity);\n\n        em.clear();\n\n        SecondaryTableEntity foundEntity = em.find(SecondaryTableEntity.class, \"123\");\n        Assert.assertNotNull(foundEntity);\n        Assert.assertEquals(\"Kuldeep\", foundEntity.getName());\n        Assert.assertEquals(24, foundEntity.getAge());\n        Assert.assertNotNull(foundEntity.getEmbeddedEntity());\n        Assert.assertEquals(\"kuldeep.mishra@gmail.com\", foundEntity.getEmbeddedEntity().getEmailId());\n        Assert.assertEquals(9512345346l, foundEntity.getEmbeddedEntity().getPhoneNo());\n\n        foundEntity.setAge(25);\n        foundEntity.setName(\"kk\");\n        foundEntity.getEmbeddedEntity().setEmailId(\"kuldeep.mishra@yahoo.com\");\n\n        em.merge(foundEntity);\n\n        em.clear();\n\n        foundEntity = em.find(SecondaryTableEntity.class, \"123\");\n        Assert.assertNotNull(foundEntity);\n        Assert.assertEquals(\"kk\", foundEntity.getName());\n        Assert.assertEquals(25, foundEntity.getAge());\n        Assert.assertNotNull(foundEntity.getEmbeddedEntity());\n        Assert.assertEquals(\"kuldeep.mishra@yahoo.com\", foundEntity.getEmbeddedEntity().getEmailId());\n        Assert.assertEquals(9512345346l, foundEntity.getEmbeddedEntity().getPhoneNo());\n\n        em.remove(foundEntity);\n\n        foundEntity = em.find(SecondaryTableEntity.class, \"123\");\n        Assert.assertNull(foundEntity);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/AllTestSuites.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera;\r\n\r\nimport junit.framework.Test;\r\nimport junit.framework.TestSuite;\r\n\r\n/**\r\n * The Class AllTestSuites.\r\n */\r\npublic class AllTestSuites\r\n{\r\n\r\n    /**\r\n     * Suite.\r\n     * \r\n     * @return the test\r\n     */\r\n    public static Test suite()\r\n    {\r\n        TestSuite suite = new TestSuite(AllTestSuites.class.getName());\r\n        // $JUnit-BEGIN$\r\n\r\n//        suite.addTest(JPAImplementationTestSuite.suite());\r\n\r\n        // $JUnit-END$\r\n        return suite;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/CoreTestUtilities.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera;\n\nimport java.lang.reflect.Field;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Parameter;\n\nimport com.impetus.kundera.persistence.PersistenceDelegator;\n\n/**\n * @author vivek.mishra\n * Test utility to serve generic utility method required by various kundera-core junits.\n */\npublic final class CoreTestUtilities\n{\n\n    /**\n     * Returns persistence delegator instance for provided entity manager instance.\n     * \n     * @param em\n     * @return\n     * @throws NoSuchFieldException\n     * @throws SecurityException\n     * @throws IllegalArgumentException\n     * @throws IllegalAccessException\n     */\n    public final static PersistenceDelegator getDelegator(EntityManager em) throws NoSuchFieldException,\n            SecurityException, IllegalArgumentException, IllegalAccessException\n    {\n        Field pdField = em.getClass().getDeclaredField(\"persistenceDelegator\");\n        if (!pdField.isAccessible())\n        {\n            pdField.setAccessible(true);\n        }\n\n        PersistenceDelegator delegator = (PersistenceDelegator) pdField.get(em);\n        return delegator;\n\n    }\n\n    public static Parameter getParameter()\n    {\n        return new CoreTestUtilities.JPAParameter();\n    }\n    \n    public static Parameter getParameter(final String name, Object value)\n    {\n        return new CoreTestUtilities.JPAParameter(name,value);\n    }\n\n    public static Parameter getParameter(final int position, Object value)\n    {\n        return new CoreTestUtilities.JPAParameter(position,value);\n    }\n\n    private static class JPAParameter implements Parameter<String>\n    {\n        private String name = \"jpa\";\n        \n        private int position;\n        \n        private Object value;\n\n        private JPAParameter()\n        {\n        }\n        \n        private JPAParameter(final String paramName, Object value)\n        {\n            this.name = paramName;\n            this.value = value;\n        }\n        \n        private JPAParameter(final int position, Object value)\n        {\n            this.position = position;\n            this.value = value;\n        }\n        \n        @Override\n        public String getName()\n        {\n            return this.name;\n        }\n\n        @Override\n        public Integer getPosition()\n        {\n            return this.position;\n        }\n\n        \n        @Override\n        public Class<String> getParameterType()\n        {\n            return String.class;\n        }\n        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/EntityManagerImplTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera;\n\nimport java.util.HashMap;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.LockModeType;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.commons.lang.NotImplementedException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.DummyDatabase;\nimport com.impetus.kundera.metadata.entities.SampleEntity;\nimport com.impetus.kundera.persistence.EntityManagerImpl;\nimport com.impetus.kundera.polyglot.entities.PersonBMM;\nimport com.impetus.kundera.query.Person;\n\n/**\n * @author vivek.mishra junit for {@link EntityManagerImpl}\n */\npublic class EntityManagerImplTest\n{\n\n    private EntityManager em;\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(EntityManagerImplTest.class);\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp()\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"kunderatest\");\n\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * On test persist.\n     * \n     */\n    @Test\n    public void testPersist()\n    {\n        try\n        {\n            for (int i = 1; i <= 1000000; i++)\n            {\n                final SampleEntity entity = new SampleEntity();\n                entity.setKey(i);\n                entity.setName(\"name\" + i);\n                if (i % 5000 == 0)\n                {\n                    em.clear();\n                }\n\n                em.persist(entity);\n\n            }\n        }\n        catch (Exception e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    @After\n    public void tearDown()\n    {\n        if (em != null)\n            em.close();\n        if (emf != null)\n            emf.close();\n\n        dropDatabase();\n    }\n\n    private void dropDatabase()\n    {\n        DummyDatabase.INSTANCE.dropDatabase();\n    }\n\n    @Test\n    public void testSingleEntityCRUD_EmNotCleared()\n    {\n        // Persist\n        final SampleEntity entity = new SampleEntity();\n        entity.setKey(1);\n        entity.setName(\"Amry\");\n        entity.setCity(\"Delhi\");\n        em.persist(entity);\n        SampleEntity found = em.find(SampleEntity.class, 1);\n        assertSampleEntity(found);\n\n        Assert.assertTrue(em.contains(found));\n\n        found.setName(\"Xamry\");\n        found.setCity(\"Noida\");\n        em.merge(found);\n\n        SampleEntity foundAfterMerge = em.find(SampleEntity.class, 1);\n        assertUpdatedSampleEntity(foundAfterMerge);\n        em.flush();\n\n        em.remove(foundAfterMerge);\n        SampleEntity foundAfterDeletion = em.find(SampleEntity.class, 1);\n        Assert.assertNull(foundAfterDeletion);\n    }\n\n    @Test\n    public void testSingleEntityCRUD_EmCleared()\n    {\n        // Persist\n        final SampleEntity entity = new SampleEntity();\n        entity.setKey(1);\n        entity.setName(\"Amry\");\n        entity.setCity(\"Delhi\");\n        em.persist(entity);\n\n        Assert.assertTrue(em.contains(entity));\n        em.clear();\n        Assert.assertFalse(em.contains(entity));\n\n        SampleEntity found = em.find(SampleEntity.class, 1, new HashMap<String, Object>());\n\n        assertSampleEntity(found);\n\n        found.setName(\"Xamry\");\n        found.setCity(\"Noida\");\n        em.clear();\n        em.merge(found);\n\n        SampleEntity foundAfterMerge = em.find(SampleEntity.class, 1);\n        assertUpdatedSampleEntity(foundAfterMerge);\n\n        // Modify record in dummy database directly\n        SampleEntity se = (SampleEntity) DummyDatabase.INSTANCE.getSchema(\"KunderaTest\").getTable(\"table\")\n                .getRecord(new Integer(1));\n        se.setCity(\"Singapore\");\n\n        em.refresh(foundAfterMerge);\n        SampleEntity found2 = em.find(SampleEntity.class, 1);\n        Assert.assertEquals(\"Singapore\", found2.getCity());\n\n        em.detach(foundAfterMerge);\n        em.clear();\n        found = em.find(SampleEntity.class, 1);\n\n        em.remove(found);\n        em.clear();\n        SampleEntity foundAfterDeletion = em.find(SampleEntity.class, 1);\n        Assert.assertNull(foundAfterDeletion);\n    }\n\n    @Test\n    public void testNativeQuery()\n    {\n        final String nativeQuery = \"Select * from persontable\";\n        Query query = em.createNativeQuery(nativeQuery, SampleEntity.class);\n\n        Assert.assertNotNull(query);\n        // Assert.assertTrue(kunderaMetadata.getApplicationMetadata().isNative(nativeQuery));\n    }\n\n    @Test\n    public void testUnsupportedMethod()\n    {\n\n        try\n        {\n            // find(Class<T> paramClass, Object paramObject, LockModeType\n            // paramLockModeType)\n            em.find(PersonBMM.class, null, LockModeType.NONE);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (NotImplementedException niex)\n        {\n            Assert.assertNotNull(niex);\n        }\n\n        try\n        {\n            // find(Class<T> arg0, Object arg1, LockModeType arg2, Map<String,\n            // Object> arg3)\n            em.find(PersonBMM.class, null, LockModeType.NONE, null);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (NotImplementedException niex)\n        {\n            Assert.assertNotNull(niex);\n        }\n\n        try\n        {\n            // createNativeQuery(String sqlString)\n            em.createNativeQuery(\"Query without class is not supported\");\n        }\n        catch (NotImplementedException niex)\n        {\n            Assert.fail();\n        }\n        try\n        {\n            // createNativeQuery(String sqlString, String resultSetMapping)\n            em.createNativeQuery(\"Query without class is not supported\", \"noreuslt\");\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (NotImplementedException niex)\n        {\n            Assert.assertNotNull(niex);\n        }\n        try\n        {\n            // getReference(Class<T> entityClass, Object primaryKey)\n            em.getReference(Person.class, null);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (NotImplementedException niex)\n        {\n            Assert.assertNotNull(niex);\n        }\n        try\n        {\n            // lock(Object paramObject, LockModeType paramLockModeType,\n            // Map<String, Object> paramMap)\n            em.lock(null, LockModeType.NONE, null);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (NotImplementedException niex)\n        {\n            Assert.assertNotNull(niex);\n        }\n        try\n        {\n            // refresh(Object paramObject, LockModeType paramLockModeType)\n            em.refresh(null, LockModeType.NONE);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (NotImplementedException niex)\n        {\n            Assert.assertNotNull(niex);\n        }\n        try\n        {\n            // refresh(Object paramObject, LockModeType paramLockModeType,\n            // Map<String, Object> paramMap)\n            em.refresh(null, LockModeType.NONE, null);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (NotImplementedException niex)\n        {\n            Assert.assertNotNull(niex);\n        }\n        try\n        {\n            // getLockMode(Object paramObject)\n            em.getLockMode(null);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (NotImplementedException niex)\n        {\n            Assert.assertNotNull(niex);\n        }\n        try\n        {\n            // unwrap(Class<T> paramClass)\n            em.unwrap(null);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (NotImplementedException niex)\n        {\n            Assert.assertNotNull(niex);\n        }\n\n    }\n\n    /**\n     * @param found\n     */\n    private void assertSampleEntity(SampleEntity found)\n    {\n        Assert.assertNotNull(found);\n        Assert.assertEquals(new Integer(1), found.getKey());\n        Assert.assertEquals(\"Amry\", found.getName());\n        Assert.assertEquals(\"Delhi\", found.getCity());\n    }\n\n    /**\n     * @param found\n     */\n    private void assertUpdatedSampleEntity(SampleEntity found)\n    {\n        Assert.assertNotNull(found);\n        Assert.assertEquals(new Integer(1), found.getKey());\n        Assert.assertEquals(\"Xamry\", found.getName());\n        Assert.assertEquals(\"Noida\", found.getCity());\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/EntityTransactionTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.EntityTransaction;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.DummyDatabase;\nimport com.impetus.kundera.query.Person;\n\n/**\n * Test case for Testing {@link EntityTransaction}\n * \n * @author amresh.singh\n * \n */\npublic class EntityTransactionTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"patest\");\n        em = emf.createEntityManager();\n    }\n\n//    @Test\n    public void testRollback()\n    {\n\n        em.getTransaction().begin();\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        // roll back.\n        em.getTransaction().rollback();\n\n        em.getTransaction().begin();\n\n        Person p = findById(Person.class, \"1\", em);\n        Assert.assertNull(p);\n\n        em.getTransaction().commit();\n\n        // Still no record should be flushed as already rollback!\n        p = findById(Person.class, \"1\", em);\n        Assert.assertNull(p);\n    }\n\n    @Test\n    public void testCommit()\n    {\n\n        em.getTransaction().begin();\n\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        // on commit.\n        em.getTransaction().commit();\n\n        Person p = findById(Person.class, \"1\", em);\n        Assert.assertNotNull(p);\n\n        em.getTransaction().begin();\n\n        ((Person) p2).setPersonName(\"rollback\");\n        em.merge(p2);\n\n        // roll back, should roll back person name for p2!\n        em.getTransaction().rollback();\n\n        p = findById(Person.class, \"1\", em);\n        Assert.assertNotNull(p);\n\n        p = findById(Person.class, \"2\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertNotSame(\"rollback\", p.getPersonName());\n    }\n\n    @Test\n    public void testRollbackOnError()\n    {\n        Person p = null;\n        try\n        {\n            Object p1 = prepareData(\"1\", 10);\n            Object p2 = prepareData(\"2\", 20);\n            em.persist(p1);\n            em.persist(p2);\n\n            p = findById(Person.class, \"1\", em);\n            Assert.assertNotNull(p);\n\n            Object p3 = prepareData(\"3\", 15);\n            em.persist(p3);\n\n            // Assert on rollback on error.\n            ((Person) p2).setPersonName(\"rollback\");\n            em.merge(p2);\n            em.merge(null);\n\n            // As this is a runtime exception so rollback should happen and\n            // delete out commited data.\n        }\n        catch (Exception ex)\n        {\n\n            p = findById(Person.class, \"1\", em);\n            Assert.assertNull(p);\n\n            p = findById(Person.class, \"2\", em);\n            Assert.assertNull(p);\n\n            p = findById(Person.class, \"3\", em);\n            Assert.assertNull(p);\n        }\n        em.clear();\n        // persist with 1 em\n        EntityManager em1 = emf.createEntityManager();\n        // em1.setFlushMode(FlushModeType.COMMIT);\n        em1.getTransaction().begin();\n        Object p3 = prepareData(\"4\", 15);\n        em1.persist(p3);\n        em1.getTransaction().commit();\n\n        try\n        {\n            // remove with another em with auto flush.\n            EntityManager em2 = emf.createEntityManager();\n            Person person = em2.find(Person.class, \"4\");\n            em2.remove(person);\n            em2.merge(null);\n        }\n        catch (Exception ex)\n        {\n            // Deleted records cannot be rolled back in cassandra!\n            // em1.clear();\n\n            p = findById(Person.class, \"4\", em1);\n            Assert.assertNotNull(p);\n            Assert.assertEquals(\"vivek\", p.getPersonName());\n\n        }\n    }\n\n    /**\n     * Roll back with multi transactions.\n     */\n    @Test\n    public void testRollbackWithMultiTransactions()\n    {\n        EntityManager em1 = emf.createEntityManager();\n        // em1.setFlushMode(FlushModeType.COMMIT);\n\n        // Begin transaction.\n        em1.getTransaction().begin();\n        Object p1 = prepareData(\"11\", 10);\n        em1.persist(p1);\n\n        // commit p1.\n        em1.getTransaction().commit();\n\n        // another em instance\n        EntityManager em2 = emf.createEntityManager();\n        // em2.setFlushMode(FlushModeType.COMMIT);\n\n        // begin transaction.\n        em2.getTransaction().begin();\n        Person found = em2.find(Person.class, \"11\");\n        found.setPersonName(\"merged\");\n        em2.merge(found);\n\n        // commit p1 after modification.\n        em2.getTransaction().commit();\n\n        // open another entity manager.\n        EntityManager em3 = emf.createEntityManager();\n        found = em3.find(Person.class, \"11\");\n        found.setPersonName(\"lastemerge\");\n        try\n        {\n            em3.merge(found);\n            em3.merge(null);\n        }\n        catch (Exception ex)\n        {\n            Person finalFound = em2.find(Person.class, \"11\");\n            Assert.assertNotNull(finalFound);\n            Assert.assertEquals(\"merged\", finalFound.getPersonName());\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        DummyDatabase.INSTANCE.dropDatabase();\n    }\n\n    private Person prepareData(String rowKey, int age)\n    {\n        Person o = new Person();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age);\n        return o;\n    }\n\n    private <E extends Object> E findById(Class<E> clazz, Object rowKey, EntityManager em)\n    {\n        return em.find(clazz, rowKey);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/KunderaPersistenceProviderUtilTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera;\n\nimport javax.persistence.spi.LoadState;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.query.Person;\n\n/**\n * @author vivek.mishra\n * junit for {@link KunderaPersistenceProviderUtil}\n */\npublic class KunderaPersistenceProviderUtilTest\n{\n\n    private KunderaPersistence persistence;\n    \n    @Before \n    public void setup()\n    {\n        persistence = new KunderaPersistence();\n    }\n    \n    @Test\n    public void testIsLoaded()\n    {\n        KunderaPersistenceProviderUtil providerUtil = new KunderaPersistenceProviderUtil(persistence);\n        LoadState state = providerUtil.isLoaded(null);\n        Assert.assertNotNull(state);\n        Assert.assertEquals(LoadState.NOT_LOADED, state);\n    }\n\n    @Test\n    public void testIsLoadedWithOutReference()\n    {\n        KunderaPersistenceProviderUtil providerUtil = new KunderaPersistenceProviderUtil(persistence);\n        Person p = new Person();\n        p.setAge(32);\n        LoadState state = providerUtil.isLoadedWithoutReference(p,\"age\");\n        Assert.assertNotNull(state);\n        Assert.assertEquals(LoadState.LOADED, state);\n    }\n\n    @Test\n    public void testIsLoadedWithReference()\n    {\n        KunderaPersistenceProviderUtil providerUtil = new KunderaPersistenceProviderUtil(persistence);\n        Person p = new Person();\n        p.setAge(32);\n        LoadState state = providerUtil.isLoadedWithReference(p,\"age\");\n        Assert.assertNotNull(state);\n        Assert.assertEquals(LoadState.UNKNOWN, state);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/KunderaPersistenceTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera;\n\nimport javax.persistence.EntityManagerFactory;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * @author vivek.mishra\n * junit for KunderaPersistence.\n *\n */\npublic class KunderaPersistenceTest\n{\n\n    @Test\n    public void testCreateEMFWithNullPu()\n    {\n        KunderaPersistence persistence = new KunderaPersistence();\n        try\n        {\n            EntityManagerFactory emf = persistence.createEntityManagerFactory(null, null);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (KunderaException kex)\n        {\n            Assert.assertEquals(\"Persistence unit name should not be null\", kex.getMessage());\n        }\n\n    }\n\n    @Test\n    public void testCreateEMFWithPU()\n    {\n        KunderaPersistence persistence = new KunderaPersistence();\n        try\n        {\n            EntityManagerFactory emf = persistence.createEntityManagerFactory(\"patest\", null);\n            Assert.assertNotNull(emf);\n            Assert.assertTrue(emf.getClass().isAssignableFrom(EntityManagerFactoryImpl.class)); // emf should get created.\n            \n            Assert.assertNotNull(persistence.getProviderUtil());  // Assert on provider util.\n            Assert.assertNotNull(persistence.getCache());         // Assert on cache.\n        }\n        catch (KunderaException kex)\n        {\n            Assert.fail();\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/KunderaPersistenceUnitUtilTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.PersistenceUnitUtil;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.query.Person;\n\n/**\n * @author vivek.mishra\n * junit for {@link KunderaPersistenceUnitUtil}\n */\npublic class KunderaPersistenceUnitUtilTest\n{\n    private EntityManagerFactory emf;\n    \n    @Before\n    public void setup()\n    {\n        KunderaPersistence persistence = new KunderaPersistence();\n        emf = persistence.createEntityManagerFactory(\"patest\", null);\n\n    }\n\n    @Test\n    public void testIsLoaded()\n    {\n        PersistenceUnitUtil utils = emf.getPersistenceUnitUtil();\n        \n        Assert.assertNotNull(utils);\n        Assert.assertFalse(utils.isLoaded(null));\n    }\n    \n    @Test\n    public void testIsLoadedWithoutReference()\n    {\n        PersistenceUnitUtil utils = emf.getPersistenceUnitUtil();\n        \n        Person p = new Person();\n        p.setAge(32);\n        p.setPersonId(\"1\");\n      \n        Assert.assertNotNull(utils);\n        Assert.assertTrue(utils.isLoaded(p, \"personId\"));\n        Assert.assertFalse(utils.isLoaded(null, \"personName\"));\n    }\n\n    @Test\n    public void testGetIdentifier()\n    {\n        PersistenceUnitUtil utils = emf.getPersistenceUnitUtil();\n        \n        Person p = new Person();\n        p.setAge(32);\n        p.setPersonId(\"1\");\n        \n        Assert.assertNotNull(utils.getIdentifier(p));\n        Assert.assertEquals(\"1\",utils.getIdentifier(p));\n    }\n\n    @Test\n    public void testInvalidEntity()\n    {\n        PersistenceUnitUtil utils = emf.getPersistenceUnitUtil();\n        \n        Person p = new Person();\n        p.setAge(32);\n        p.setPersonId(\"1\");\n        \n        try\n        {\n            utils.getIdentifier(new String(\"test\"));\n            Assert.fail(\"Should have gone to catch block!\");\n        } catch(IllegalArgumentException iaex)\n        {\n            Assert.assertEquals(String.class + \" is not an entity\", iaex.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/PersistenceUtilHelperTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera;\n\nimport javax.persistence.spi.LoadState;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceUtilHelper.MetadataCache;\nimport com.impetus.kundera.proxy.KunderaProxy;\nimport com.impetus.kundera.proxy.cglib.CglibLazyInitializerFactory;\nimport com.impetus.kundera.query.Person;\n\n/**\n * @author vivek.mishra \n * junit for {@link PersistenceUtilHelper}.\n * \n */\npublic class PersistenceUtilHelperTest\n{\n\n    private MetadataCache cache;\n\n    @Before\n    public void setUp()\n    {\n        this.cache = new PersistenceUtilHelper.MetadataCache();\n    }\n\n    @Test\n    public void testisLoadedWithReferenceAsNull()\n    {\n        LoadState state = PersistenceUtilHelper.isLoadedWithReference(null, null, cache);\n\n        Assert.assertNotNull(state);\n        Assert.assertEquals(LoadState.NOT_LOADED, state);\n    }\n\n    @Test\n    public void testisLoadedWithReferenceAsLoaded()\n    {\n        Person p = new Person();\n        p.setPersonName(\"Vivek\");\n        LoadState state = PersistenceUtilHelper.isLoadedWithReference(p, \"personName\", cache);\n\n        Assert.assertNotNull(state);\n        Assert.assertEquals(LoadState.UNKNOWN, state);\n    }\n\n    @Test\n    public void testisLoadedWithReferenceAsKunderaProxy() throws NoSuchMethodException, SecurityException\n    {\n        CglibLazyInitializerFactory factory = new CglibLazyInitializerFactory();\n        KunderaProxy proxy = factory.getProxy(\"Person\", Person.class,\n                Person.class.getDeclaredMethod(\"getPersonId\", null),\n                Person.class.getDeclaredMethod(\"setPersonId\", String.class), \"personId\", null);\n\n        LoadState state = PersistenceUtilHelper.isLoadedWithReference(proxy, \"personId\", cache);\n\n        Assert.assertNotNull(state);\n        Assert.assertEquals(LoadState.UNKNOWN, state);\n    }\n\n    @Test\n    public void testisLoadedWithoutReferenceAsNull()\n    {\n        LoadState state = PersistenceUtilHelper.isLoadedWithoutReference(null, null, cache);\n\n        Assert.assertNotNull(state);\n        Assert.assertEquals(LoadState.NOT_LOADED, state);\n    }\n\n    @Test\n    public void testisLoadedWithoutReferenceAsLoad()\n    {\n        Person p = new Person();\n        p.setPersonName(\"Vivek\");\n\n        LoadState state = PersistenceUtilHelper.isLoadedWithoutReference(p, \"personName\", cache);\n\n        Assert.assertNotNull(state);\n        Assert.assertEquals(LoadState.LOADED, state);\n    }\n\n    @Test\n    public void testisLoadedWithOutReferenceAsKunderaProxy() throws NoSuchMethodException, SecurityException\n    {\n        CglibLazyInitializerFactory factory = new CglibLazyInitializerFactory();\n        KunderaProxy proxy = factory.getProxy(\"Person\", Person.class,\n                Person.class.getDeclaredMethod(\"getPersonId\", null),\n                Person.class.getDeclaredMethod(\"setPersonId\", String.class), \"personId\", null);\n\n        LoadState state = PersistenceUtilHelper.isLoadedWithoutReference(proxy, \"personName\", cache);\n\n        Assert.assertNotNull(state);\n        Assert.assertEquals(LoadState.NOT_LOADED, state);\n        \n//        factory.\n    }\n    \n    @Test\n    public void testisLoadedWAsKunderaProxy() throws NoSuchMethodException, SecurityException\n    {\n        CglibLazyInitializerFactory factory = new CglibLazyInitializerFactory();\n        KunderaProxy proxy = factory.getProxy(\"Person\", Person.class,\n                Person.class.getDeclaredMethod(\"getPersonId\", null),\n                Person.class.getDeclaredMethod(\"setPersonId\", String.class), \"personId\", null);\n\n        LoadState state = PersistenceUtilHelper.isLoaded(proxy);\n\n        Assert.assertNotNull(state);\n        Assert.assertEquals(LoadState.NOT_LOADED, state);\n        \n//        factory.\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/cache/ElementCollectionCacheManagerTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.cache;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.query.Person;\n\n/**\n * @author vivek.mishra junit for {@link ElementCollectionCacheManager}\n * \n */\npublic class ElementCollectionCacheManagerTest\n{\n\n    @Test\n    public void test()\n    {\n        Person p = new Person(); // create object.\n        p.setAge(23);\n        p.setPersonId(\"personId\");\n\n        ElementCollectionCacheManager manager = ElementCollectionCacheManager.getInstance();\n        Assert.assertTrue(manager.isCacheEmpty());\n        Assert.assertTrue(manager.getElementCollectionCache().isEmpty());\n        Assert.assertNull(manager.getElementCollectionObjectName(\"personId\", p));\n        Assert.assertEquals(-1, manager.getLastElementCollectionObjectCount(\"personId\"));\n\n        manager.addElementCollectionCacheMapping(\"personId\", p, \"age#1\");\n        Assert.assertNotNull(manager.getElementCollectionObjectName(\"personId\", p));\n        Assert.assertEquals(\"age#1\", manager.getElementCollectionObjectName(\"personId\", p));\n        Assert.assertNotNull(manager.getLastElementCollectionObjectCount(\"personId\"));\n        Assert.assertEquals(1, manager.getLastElementCollectionObjectCount(\"personId\"));\n\n        manager.addElementCollectionCacheMapping(\"personId\", p, \"personName#1\");\n        Assert.assertEquals(\"personName#1\", manager.getElementCollectionObjectName(\"personId\", p));\n\n        try\n        {\n            manager.addElementCollectionCacheMapping(\"personId\", p, \"personName\");\n            manager.getLastElementCollectionObjectCount(\"personId\");\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (CacheException cex)\n        {\n            Assert.assertNotNull(cex.getMessage());\n        }\n\n        manager.clearCache();\n        Assert.assertTrue(manager.isCacheEmpty());\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/cache/NonOperationCacheProviderTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.cache;\n\nimport java.util.HashMap;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\n/**\n * @author vivek.mishra\n * junit for {@link NonOperationalCacheProvider}.\n * Current implementation doesn't do anything. So junit needs to modified later.\n *\n */\n\npublic class NonOperationCacheProviderTest\n{\n\n    @Test\n    public void test()\n    {\n\n        NonOperationalCacheProvider cacheProvider = new NonOperationalCacheProvider();\n        \n        cacheProvider.createCache(\"person\");\n        cacheProvider.init(new HashMap());\n        cacheProvider.init(\"none\");\n        \n        // No implementation is in place, hence it will return null.\n        Assert.assertNull(cacheProvider.getCache(\"person\"));\n        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/cache/NonOperationalCacheTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.cache;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.query.Person;\nimport com.impetus.kundera.query.Person.Day;\n\n/**\n * @author vivek.mishra\n * junit for {@link NonOperationalCache}.\n * Current implementation doesn't do anything. So junit needs to modified later.\n *\n */\npublic class NonOperationalCacheTest\n{\n\n    @Test\n    public void test()\n    {\n        NonOperationalCache noOpCache = new NonOperationalCache();\n        Person person = new Person();\n        person.setAge(32);\n        person.setDay(Day.SATURDAY);\n        person.setPersonId(\"p1\");\n        person.setPersonName(\"Milan Kundera\");\n        \n        noOpCache.put(\"p1\", person);\n\n        // Non operational cache doesn't do anything. So such assertions won't work! \n        // \n//        Person cachedPerson = (Person) noOpCache.get(\"p1\");\n//        Assert.assertEquals(person, cachedPerson);\n\n        noOpCache.evict(Person.class);\n        noOpCache.evictAll();\n        noOpCache.evict(Person.class, person);\n        Assert.assertFalse(noOpCache.contains(Person.class, person));\n        Assert.assertNull(noOpCache.get(\"p1\"));\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/classreading/ClassFileIteratorTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.classreading;\n\nimport java.io.File;\nimport java.io.FileInputStream;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n\n\n\n/**\n * @author chhavi.gangwal\n * junit for {@link ClassFileIterator}\n */\npublic class ClassFileIteratorTest {\n\tClassFileIterator iterator;\n    Filter filter;\n    File file;\n    \n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n    \t\n        filter = new FilterImpl();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    \titerator = null;\n        filter = null;\n        file =  null;\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.classreading.ClassFileIterator#next()}.\n     */\n    @Test\n    public void testIterateWithFilter()\n    {\n    \tfile = new File(\".\");\n    \t\n    \t//ClassFilterIterator with filter\n    \titerator = new ClassFileIterator(file, filter);  \n    \tAssert.assertEquals(iterator.next().getClass(),FileInputStream.class);\n    \tAssert.assertNotNull(iterator.next());\n      }\n      \n      /**\n       * Test method for {@link com.impetus.kundera.classreading.ClassFileIterator#next()}.\n       */\n      @Test\n      public void testIterateWithoutFilter()\n      {\n      \t\n        try {\n      \t\n      \t   file = new File(\".\");\n      \t   //ClassFilterIterator without filter\n      \t   iterator = new ClassFileIterator(file);  \n      \t   Assert.assertEquals(iterator.next().getClass(),FileInputStream.class);\n      \t   Assert.assertNotNull(iterator.next());\n      \t\n      }\n        catch (ResourceReadingException e)\n        {\n      \t  \n      \t  Assert.assertEquals(\"Couldn't read file .\",e.getMessage());\n         }\n         \n      }\n      \n      \n      /**\n       * Test method for {@link com.impetus.kundera.classreading.ClassFileIterator#next()}.\n       */\n      @Test\n      public void testNoClassIterate()\n      {\n      \t\n        try {\n      \t     \t    \t\n      \t  //ClassFilterIterator no file found\n      \t   file = new File(\"/com/impetus/kundera/\");\n      \t   iterator = new ClassFileIterator(file);\n      \t}\n        catch (ResourceReadingException e)\n        {\n          Assert.assertNull(iterator.next());\n      \t  Assert.assertEquals(\"Couldn't read file /com/impetus/kundera\",e.getMessage());\n         }\n         \n      }\n       \n    \t\n    \n\n    \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/classreading/ClasspathReaderTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.classreading;\n\nimport java.io.InputStream;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * @author amresh.singh\n *\n */\npublic class ClasspathReaderTest\n{\n    ClasspathReader reader;\n    Filter filter;\n    \n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        \n        filter = new FilterImpl();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        reader = null;\n        filter = null;\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.classreading.ClasspathReader#findResources()}.\n     */\n    @Test\n    public void testFindResources()\n    {\n        reader = new ClasspathReader();\n        URL[] urls = reader.findResources();\n        Assert.assertNull(urls);\n        \n        List<String> classesToScan = new ArrayList<String>();\n        classesToScan.add(\"com.impetus.kundera.PersonnelDTO\");\n        classesToScan.add(\"com.impetus.kundera.query.Person\");\n        reader = new ClasspathReader(classesToScan);\n        urls = reader.findResources();\n        Assert.assertNotNull(urls);\n        Assert.assertTrue(urls.length > 0);    \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.classreading.ClasspathReader#findResourcesAsStream()}.\n     */\n    @Test\n    public void testFindResourcesAsStream()\n    {\n        //When classes to scan is null\n        reader = new ClasspathReader();\n        InputStream[] streams = reader.findResourcesAsStream();\n        Assert.assertNull(streams);\n        \n        List<String> classesToScan = new ArrayList<String>();\n        classesToScan.add(\"com.impetus.kundera.PersonnelDTO\");\n        classesToScan.add(\"com.impetus.kundera.query.Person\");\n        reader = new ClasspathReader(classesToScan);\n        streams = reader.findResourcesAsStream();\n       reader.read();\n        Assert.assertNotNull(streams);\n        Assert.assertTrue(streams.length > 0); \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.classreading.ClasspathReader#findResourcesByClasspath()}.\n     */\n    @Test\n    public void testFindResourcesByClasspath()\n    {\n        reader = new ClasspathReader();\n        URL[] urls = reader.findResourcesByClasspath();\n        Assert.assertNotNull(urls);\n        Assert.assertTrue(urls.length > 0);     \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.classreading.ClasspathReader#setFilter(com.impetus.kundera.classreading.Filter)}.\n     */\n    @Test\n    public void testSetFilter()\n    {\n        reader = new ClasspathReader();\n        reader.setFilter(filter);\n        Assert.assertNotNull(reader.getFilter());\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/classreading/DataRowTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.classreading;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.db.DataRow;\nimport com.impetus.kundera.query.Person;\n\n/**\n * @author vivek.mishra\n * \n * Data row test junit test. Such POJO junits are just to code coverage happy.\n */\npublic class DataRowTest\n{\n\n    @Test\n    public void test()\n    {\n        Person p = new Person();\n        \n        List<String> columns = new ArrayList<String>();\n        columns.add(\"column1\");\n        columns.add(\"column2\");\n        columns.add(\"column3\");\n        \n        DataRow<String> row = new DataRow<String>(\"1\",\"person\",columns);\n        \n        \n        Assert.assertNotNull(row.getColumnFamilyName());\n        Assert.assertNotNull(row.getId());\n        Assert.assertNotNull(row.getColumns());\n        Assert.assertEquals(3,row.getColumns().size());\n        \n        row.addColumn(\"column4\");\n        Assert.assertEquals(4,row.getColumns().size());\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/classreading/FilterTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.classreading;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * @author amresh.singh\n *\n */\npublic class FilterTest\n{\n    Filter filter;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        filter = new FilterImpl();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        filter = null;\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.classreading.Filter#accepts(java.lang.String)}.\n     */\n    @Test\n    public void testAccepts()\n    {\n        String fileName = \"/com/impetus/kundera/entities/User.class\";\n        Assert.assertTrue(filter.accepts(fileName));\n        \n        fileName = \"javax/persistence/EntityManager.class\";\n        Assert.assertFalse(filter.accepts(fileName));\n        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/classreading/RelationHolderTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.classreading;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.persistence.event.AddressEntity;\nimport com.impetus.kundera.query.Person;\n\n/**\n * @author vivek.mishra\n * Relation holder junit test\n */\npublic class RelationHolderTest\n{\n\n    @Test\n    public void test()\n    {\n        Person p = new Person();\n        RelationHolder rlHolder = new RelationHolder(\"parent\", p);\n        \n        Assert.assertEquals(\"parent\", rlHolder.getRelationName());\n        Assert.assertEquals(p, rlHolder.getRelationValue());\n        \n        AddressEntity relationEntity = new AddressEntity();\n        rlHolder = new RelationHolder(\"child\", p, relationEntity);\n        Assert.assertEquals(\"child\", rlHolder.getRelationName());\n        Assert.assertEquals(p, rlHolder.getRelationValue());\n        Assert.assertEquals(relationEntity, rlHolder.getRelationVia());\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/classreading/SearchResultTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.classreading;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.db.SearchResult;\nimport com.impetus.kundera.query.Person;\n\n/**\n * @author vivek.mishra\n * \n * Search result test junit test. Such POJO junits are just for code coverage.\n */\npublic class SearchResultTest\n{\n\n    @Test\n    public void test()\n    {\n        Person p = new Person();\n        SearchResult result = new SearchResult();\n        \n        result.setPrimaryKey(p.getPersonId());\n        result.setEmbeddedColumnName(\"none\");\n        result.addEmbeddedColumnValue(\"embeddedcolumn1\");\n        result.addEmbeddedColumnValue(\"embeddedcolumn2\");\n        \n        Assert.assertNull(result.getPrimaryKey());\n        Assert.assertNotNull(result.getEmbeddedColumnName());\n        Assert.assertNotNull(result.getEmbeddedColumnValues());\n        Assert.assertEquals(2,result.getEmbeddedColumnValues().size());\n        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/ClientResolverTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.loader.ClientFactory;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * @author vivek.mishra\n * \n *         junit for {@link ClientResolver}\n * \n */\npublic class ClientResolverTest\n{\n    private final String persistenceUnit = \"patest\";\n\n    @Test\n    public void test()\n    {\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        ClientResolver.getClientFactory(persistenceUnit, null,\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        ClientFactory clientFactory = ClientResolver.getClientFactory(persistenceUnit);\n        Assert.assertNotNull(clientFactory);\n        Assert.assertTrue(clientFactory.getClass().isAssignableFrom(CoreTestClientFactory.class));\n    }\n\n    @Test\n    public void testInvalidPU()\n    {\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        ClientResolver.getClientFactory(persistenceUnit, null,\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        try\n        {\n            ClientResolver.getClientFactory(\"metadatatest\");\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (ClientResolverException crex)\n        {\n            Assert.assertEquals(\"Client Factory Not Configured For Specified Client Type.\", crex.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/CoreTestClient.java",
    "content": "package com.impetus.kundera.client;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.query.CoreTestEntityReader;\nimport com.impetus.kundera.query.LuceneQuery;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class CoreTestClient.\n */\npublic class CoreTestClient extends ClientBase implements Client<LuceneQuery>, ClientPropertiesSetter\n{\n\n    // private static int idCount;\n\n    /**\n     * Instantiates a new core test client.\n     * \n     * @param indexManager\n     *            the index manager\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public CoreTestClient(IndexManager indexManager, String persistenceUnit, final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata, null, persistenceUnit);\n        this.indexManager = indexManager;\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.metadata\n     * .model.EntityMetadata, java.lang.Object, java.lang.Object,\n     * java.util.List)\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n        DummySchema schema = DummyDatabase.INSTANCE.getSchema(entityMetadata.getSchema());\n\n        if (schema == null)\n        {\n            schema = new DummySchema();\n            DummyTable table = new DummyTable();\n            table.addRecord(id, entity);\n            schema.addTable(entityMetadata.getTableName(), table);\n            DummyDatabase.INSTANCE.addSchema(entityMetadata.getSchema(), schema);\n        }\n        else\n        {\n            DummyTable table = schema.getTable(entityMetadata.getTableName());\n            if (table == null)\n            {\n                table = new DummyTable();\n            }\n            table.addRecord(id, entity);\n            schema.addTable(entityMetadata.getTableName(), table);\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.Object)\n     */\n    @Override\n    public Object find(Class entityClass, Object key)\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        DummySchema schema = DummyDatabase.INSTANCE.getSchema(m.getSchema());\n        if (schema == null)\n            return null;\n\n        DummyTable table = schema.getTable(m.getTableName());\n\n        if (table == null)\n            return null;\n\n        return table.getRecord(key);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    public void delete(Object entity, Object pKey)\n    {\n        if (entity == null)\n            return;\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        DummySchema schema = DummyDatabase.INSTANCE.getSchema(m.getSchema());\n        if (schema == null)\n            return;\n        DummyTable table = schema.getTable(m.getTableName());\n        if (table == null)\n            return;\n\n        table.removeRecord(pKey);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.String[], java.lang.Object[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)\n    {\n        List results = new ArrayList();\n        for (Object key : keys)\n        {\n            Object result = find(entityClass, key);\n            if (result != null)\n            {\n                results.add(result);\n            }\n        }\n        return results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    @Override\n    public void close()\n    {\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientBase#getPersistenceUnit()\n     */\n    @Override\n    public String getPersistenceUnit()\n    {\n        return persistenceUnit;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera\n     * .persistence.context.jointable.JoinTableData)\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        /*\n         * DummySchema schema =\n         * DummyDatabase.INSTANCE.getSchema(joinTableData.getSchemaName()); if\n         * (schema == null) { schema = new DummySchema();\n         * schema.addTable(joinTableData.getJoinTableName(), new DummyTable());\n         * }\n         * \n         * DummyTable table = schema.getTable(joinTableData.getJoinTableName());\n         * Map<Object, Set<Object>> joinTableRecords =\n         * joinTableData.getJoinTableRecords();\n         * \n         * Iterator iter = joinTableRecords.keySet().iterator();\n         * \n         * while (iter.hasNext()) { Object key = iter.next();\n         * table.addRecord(key, joinTableRecords.get(key)); }\n         */}\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return new CoreTestEntityReader(kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<LuceneQuery> getQueryImplementor()\n    {\n        return LuceneQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,\n            Object pKeyColumnValue, Class columnJavaType)\n    {\n\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    @Override\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n\n    }\n\n    /** The core test property. */\n    String coreTestProperty;\n\n    /**\n     * Gets the core test property.\n     * \n     * @return the coreTestProperty\n     */\n    public String getCoreTestProperty()\n    {\n        return coreTestProperty;\n    }\n\n    /**\n     * Sets the core test property.\n     * \n     * @param coreTestProperty\n     *            the coreTestProperty to set\n     */\n    public void setCoreTestProperty(String coreTestProperty)\n    {\n        this.coreTestProperty = coreTestProperty;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientPropertiesSetter#populateClientProperties\n     * (com.impetus.kundera.client.Client, java.util.Map)\n     */\n    @Override\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        if (properties != null)\n        {\n            for (String key : properties.keySet())\n            {\n                Object value = properties.get(key);\n                if (key.equals(\"core.test.property\") && value instanceof String)\n                {\n                    setCoreTestProperty((String) value);\n                }\n            }\n        }\n    }\n\n    /**\n     * Sets the index manager.\n     * \n     * @param im\n     *            the new index manager\n     */\n    public void setIndexManager(IndexManager im)\n    {\n        this.indexManager = im;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        return (Generator) KunderaCoreUtils.createNewInstance(CoreTestIdGenerator.class);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/CoreTestClientFactory.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client;\n\nimport java.util.Map;\n\nimport com.impetus.kundera.configure.schema.api.CoreSchemaManager;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.loader.GenericClientFactory;\n\n/**\n * <Prove description of functionality provided by this Type>\n * \n * @author amresh.singh\n */\npublic class CoreTestClientFactory extends GenericClientFactory\n{\n\n    private  SchemaManager schemaManager;\n    \n    @Override\n    public void destroy()\n    {\n        schemaManager.dropSchema();\n        super.unload();\n    }\n\n    @Override\n    public SchemaManager getSchemaManager(Map<String, Object> puProperties)\n    {\n        if(schemaManager == null)\n        schemaManager =  new CoreSchemaManager(\"com.impetus.kundera.client.CoreTestClientFactory\", puProperties, kunderaMetadata);\n        return schemaManager;\n    }\n\n    @Override\n    public Client getClientInstance()\n    {\n        return super.getClientInstance();\n    }\n\n    @Override\n    protected Client instantiateClient(String persistenceUnit)\n    {\n        setConnectionPoolOrConnection(null);\n        \n        return new CoreTestClient(indexManager, persistenceUnit, kunderaMetadata);\n    }\n\n    @Override\n    public boolean isThreadSafe()\n    {\n        return false;\n    }\n\n    public String getPersistenceUnit()\n    {\n        return super.getPersistenceUnit();\n    }\n\n    public Object getConnectionPoolOrConnection()\n    {\n        \n        return super.getConnectionPoolOrConnection();\n    }\n  \n    public void onValidation(final String host, final String port)\n    {\n        super.onValidation(host, port);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initialize(java.util.Map)\n     */\n    @Override\n    public void initialize(Map<String, Object> puProperties)\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public LoadBalancer getLoadBalancePolicy(final String  policy)\n    {\n        return LoadBalancer.getValue(policy);\n    }\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#createPoolOrConnection\n     * (java.util.Map)\n     */\n    @Override\n    protected Object createPoolOrConnection()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n        throw new UnsupportedOperationException(\"Load balancing feature is not supported in \"\n                + this.getClass().getSimpleName());\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/CoreTestClientNoGenerator.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.query.CoreTestEntityReader;\nimport com.impetus.kundera.query.LuceneQuery;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class CoreTestClientNoGenerator.\n * \n * @author vivek.mishra junit for {@link CoreTestClientNoGenerator}\n */\npublic class CoreTestClientNoGenerator extends ClientBase implements Client<LuceneQuery>\n{\n\n    /**\n     * Instantiates a new core test client no generator.\n     * \n     * @param indexManager\n     *            the index manager\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public CoreTestClientNoGenerator(IndexManager indexManager, String persistenceUnit,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata, null, persistenceUnit);\n        this.indexManager = indexManager;\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.metadata\n     * .model.EntityMetadata, java.lang.Object, java.lang.Object,\n     * java.util.List)\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n        DummySchema schema = DummyDatabase.INSTANCE.getSchema(entityMetadata.getSchema());\n\n        if (schema == null)\n        {\n            schema = new DummySchema();\n            DummyTable table = new DummyTable();\n            table.addRecord(id, entity);\n            schema.addTable(entityMetadata.getTableName(), table);\n            DummyDatabase.INSTANCE.addSchema(entityMetadata.getSchema(), schema);\n        }\n        else\n        {\n            DummyTable table = schema.getTable(entityMetadata.getTableName());\n            if (table == null)\n            {\n                table = new DummyTable();\n            }\n            table.addRecord(id, entity);\n            schema.addTable(entityMetadata.getTableName(), table);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.Object)\n     */\n    @Override\n    public Object find(Class entityClass, Object key)\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        DummySchema schema = DummyDatabase.INSTANCE.getSchema(m.getSchema());\n        if (schema == null)\n            return null;\n\n        DummyTable table = schema.getTable(m.getTableName());\n\n        if (table == null)\n            return null;\n\n        return table.getRecord(key);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    public void delete(Object entity, Object pKey)\n    {\n        if (entity == null)\n            return;\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        DummySchema schema = DummyDatabase.INSTANCE.getSchema(m.getSchema());\n        if (schema == null)\n            return;\n        DummyTable table = schema.getTable(m.getTableName());\n        if (table == null)\n            return;\n\n        table.removeRecord(pKey);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.String[], java.lang.Object[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)\n    {\n        List results = new ArrayList();\n        for (Object key : keys)\n        {\n            Object result = find(entityClass, key);\n            if (result != null)\n            {\n                results.add(result);\n            }\n        }\n        return results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    @Override\n    public void close()\n    {\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientBase#getPersistenceUnit()\n     */\n    @Override\n    public String getPersistenceUnit()\n    {\n        return persistenceUnit;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera\n     * .persistence.context.jointable.JoinTableData)\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return new CoreTestEntityReader(kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<LuceneQuery> getQueryImplementor()\n    {\n        return LuceneQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,\n            Object pKeyColumnValue, Class columnJavaType)\n    {\n\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    @Override\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        return null;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/CoreTestIdGenerator.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client;\n\nimport com.impetus.kundera.generator.AutoGenerator;\nimport com.impetus.kundera.generator.IdentityGenerator;\nimport com.impetus.kundera.generator.SequenceGenerator;\nimport com.impetus.kundera.generator.TableGenerator;\nimport com.impetus.kundera.metadata.model.SequenceGeneratorDiscriptor;\nimport com.impetus.kundera.metadata.model.TableGeneratorDiscriptor;\n\n/**\n * The Class CoreTestIdGenerator.\n * \n * @author: karthikp.manchala\n * \n */\npublic class CoreTestIdGenerator implements AutoGenerator, TableGenerator, SequenceGenerator, IdentityGenerator\n{\n\n    /** The id count. */\n    private static int idCount;\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.TableGenerator#generate(com.impetus.kundera\n     * .metadata.model.TableGeneratorDiscriptor,\n     * com.impetus.kundera.client.ClientBase, java.lang.Object)\n     */\n    @Override\n    public Object generate(TableGeneratorDiscriptor discriptor, ClientBase client, String dataType)\n    {\n        return ++idCount;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.AutoGenerator#generate(com.impetus.kundera\n     * .client.Client, java.lang.Object)\n     */\n    @Override\n    public Object generate(Client<?> client, String dataType)\n    {\n        return ++idCount;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.SequenceGenerator#generate(com.impetus.\n     * kundera.metadata.model.SequenceGeneratorDiscriptor,\n     * com.impetus.kundera.client.Client, java.lang.Object)\n     */\n    @Override\n    public Object generate(SequenceGeneratorDiscriptor discriptor, Client<?> client, String dataType)\n    {\n        return ++idCount;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/DummyDatabase.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Class acting as dummy database for test cases, kind of mocks database\n * @author amresh.singh\n *\n */\npublic class DummyDatabase\n{\n    public static final DummyDatabase INSTANCE = new DummyDatabase();\n    \n    private Map<String, DummySchema> schemas;   \n    \n    /**\n     * @return the schemas\n     */\n    public Map<String, DummySchema> getSchemas()\n    {\n        return schemas;\n    }\n    \n    public DummySchema getSchema(String schemaName)\n    {\n        if(schemas == null) return null;\n        return getSchemas().get(schemaName);\n    }\n\n    /**\n     * @param schemas the schemas to set\n     */\n    public void addSchema(String schemaName, DummySchema schema)\n    {\n        if(schemas == null)\n        {\n            schemas = new HashMap<String, DummySchema>();\n        }\n        schemas.put(schemaName, schema);\n    }\n\n\n\n    public void dropDatabase()\n    {\n        if(schemas != null)\n        {\n            for(DummySchema schema : schemas.values())\n            {\n                schema.dropSchema();\n            }\n            schemas.clear();\n        }\n        \n    }\n}\n\n\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/DummySchema.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Class acting as dummy schema, mocks schemas provided by most of the databases.\n * @author amresh.singh\n *\n */\npublic class DummySchema\n{\n    \n    private Map<String, DummyTable> tables;\n    \n    /**\n     * @return the tables\n     */\n    public Map<String, DummyTable> getTables()\n    {\n        return tables;\n    }\n    \n    public DummyTable getTable(String tableName)\n    {\n     \n        if(tables == null) return null;\n        \n        return tables.get(tableName);\n    }\n\n    /**\n     * @param tables the tables to set\n     */\n    public void addTable(String tableName, DummyTable table)\n    {\n        if(tables == null)\n        {\n            tables = new HashMap<String, DummyTable>();\n        }\n        tables.put(tableName, table);\n    }\n\n\n\n\n    public void dropSchema()\n    {\n        if(tables != null)\n        {\n            for(DummyTable table : tables.values())\n            {\n                table.truncate();\n            }\n        }\n        tables.clear();\n    }   \n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/DummyTable.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * Class used in test cases as dumy table\n * @author amresh.singh\n *\n */\npublic class DummyTable\n{ \n    \n    private Map<Object, Object> records;\n    \n    /**\n     * @return the records\n     */\n    public Map<Object, Object> getRecords()\n    {\n        return records;\n    }\n    \n    public Object getRecord(Object pk)\n    {\n        if(records == null) return null;\n        \n        return records.get(pk);\n    }\n    \n    /**\n     * @param records the records to set\n     */\n    public void addRecord(Object pk, Object record)\n    {\n        if(records == null)\n        {\n            records = new HashMap<Object, Object>();\n        }\n        records.put(pk, record);\n    }\n    \n    public void removeRecord(Object pk)\n    {\n        if(records != null)\n        {\n            records.remove(pk);\n        }\n    }\n    \n    public void truncate()\n    {\n        if(records != null)\n        {\n            records.clear();\n        }\n    }\n    \n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/EnhanceEntityTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.persistence.event.AddressEntity;\n\n/**\n * @author vivek.mishra\n * junit for {@link EnhanceEntity}\n */\npublic class EnhanceEntityTest\n{\n\n    @Test\n    public void test()\n    {\n        AddressEntity address = new AddressEntity();\n        address.setAddressId(\"addr1\");\n        address.setCity(\"noida\");\n        EnhanceEntity enhanceEntity  = new EnhanceEntity(address,\"addr1\",null);\n        Assert.assertNotNull(enhanceEntity);\n        Assert.assertEquals(\"addr1\", enhanceEntity.getEntityId());\n        Assert.assertEquals(address, enhanceEntity.getEntity());\n        Assert.assertNull(enhanceEntity.getRelations());\n        enhanceEntity = new EnhanceEntity();\n        Assert.assertNull(enhanceEntity.getEntity());\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/crud/associations/AssociationsBiDirectionalBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.associations;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\n/**\n * @author Pragalbh Garg\n * \n */\npublic class AssociationsBiDirectionalBase\n{\n\n    protected String _PU = \"kunderatest\";\n\n    /** The emf. */\n    protected static EntityManagerFactory emf;\n\n    /** The em. */\n    protected static EntityManager em;\n\n    protected void setUpInternal() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(_PU);\n        em = emf.createEntityManager();\n    }\n\n    protected void assertBegin()\n    {\n        init();\n\n        MobileHandset mobile = em.find(MobileHandset.class, \"m1\");\n        Assert.assertNotNull(mobile);\n        Assert.assertEquals(\"manufacturer1\", mobile.getManufacturer().getName());\n        \n        String qry = \"select m from MobileHandset m\";\n        Query query = em.createQuery(qry);\n        List<MobileHandset> result = query.getResultList();\n        Assert.assertNotNull(result);\n        Assert.assertNotNull(result.get(0));\n        Assert.assertNotNull(result.get(0).getManufacturer());\n        Assert.assertNotNull(result.get(0).getOs());\n\n        Assert.assertNotNull(result.get(0).getManufacturer().getHandsets());\n        Assert.assertNotNull(result.get(0).getOs().getHandsets());\n\n       \n\n        qry = \"select m from MobileHandset m where m.id = :id\";\n        query = em.createQuery(qry);\n        query.setParameter(\"id\", \"m1\");\n        result = query.getResultList();\n        Assert.assertNotNull(result);\n        Assert.assertEquals(1, result.size());\n        Assert.assertEquals(\"os1\", result.get(0).getOs().getName());\n\n        qry = \"select o from MobileOperatingSystem o\";\n        query = em.createQuery(qry);\n        List<MobileOperatingSystem> result2 = query.getResultList();\n        Assert.assertNotNull(result2);\n        Assert.assertEquals(2, result2.size());\n\n        qry = \"select o from MobileOperatingSystem o where o.id = :id\";\n        query = em.createQuery(qry);\n        query.setParameter(\"id\", \"o1\");\n        result2 = query.getResultList();\n        Assert.assertNotNull(result2);\n        Assert.assertEquals(1, result2.size());\n        Assert.assertEquals(3, result2.get(0).getHandsets().size());\n        Assert.assertEquals(\"os1\", result2.get(0).getName());\n\n        qry = \"select m from MobileManufacturer m\";\n        query = em.createQuery(qry);\n        List<MobileManufacturer> result3 = query.getResultList();\n        Assert.assertNotNull(result3);\n        Assert.assertEquals(2, result3.size());\n\n        qry = \"select m from MobileManufacturer m where m.id = :id\";\n        query = em.createQuery(qry);\n        query.setParameter(\"id\", \"ma1\");\n        result3 = query.getResultList();\n        Assert.assertNotNull(result3);\n        Assert.assertEquals(1, result3.size());\n        Assert.assertEquals(3, result3.get(0).getHandsets().size());\n        Assert.assertEquals(\"manufacturer1\", result3.get(0).getName());\n    }\n    \n    protected void assertCRUD(){\n        init();\n        \n        MobileHandset mobile = em.find(MobileHandset.class, \"m1\");\n        Assert.assertNotNull(mobile);\n        Assert.assertEquals(\"manufacturer1\", mobile.getManufacturer().getName());\n        \n        mobile = em.find(MobileHandset.class, \"m4\");\n        Assert.assertNotNull(mobile);\n        Assert.assertEquals(\"manufacturer2\", mobile.getManufacturer().getName());\n        \n        mobile = em.find(MobileHandset.class, \"m2\");\n        Assert.assertNotNull(mobile);\n        Assert.assertEquals(\"os1\", mobile.getOs().getName());\n        \n        mobile = em.find(MobileHandset.class, \"m3\");\n        Assert.assertNotNull(mobile);\n        Assert.assertEquals(\"os2\", mobile.getOs().getName());\n        \n        MobileOperatingSystem os = em.find(MobileOperatingSystem.class, \"o1\");\n        Assert.assertNotNull(os);\n        Assert.assertEquals(\"os1\", os.getName());\n        \n        os = em.find(MobileOperatingSystem.class, \"o2\");\n        Assert.assertNotNull(os);\n        Assert.assertEquals(\"os2\", os.getName());\n        \n        MobileManufacturer manu = em.find(MobileManufacturer.class, \"ma1\");\n        Assert.assertNotNull(manu);\n        Assert.assertEquals(\"manufacturer1\", manu.getName());\n\n        manu = em.find(MobileManufacturer.class, \"ma2\");\n        Assert.assertNotNull(manu);\n        Assert.assertEquals(\"manufacturer2\", manu.getName());\n    }\n\n    protected void init()\n    {\n        MobileManufacturer manu1 = new MobileManufacturer();\n        manu1.setId(\"ma1\");\n        manu1.setName(\"manufacturer1\");\n\n        MobileManufacturer manu2 = new MobileManufacturer();\n        manu2.setId(\"ma2\");\n        manu2.setName(\"manufacturer2\");\n\n        MobileOperatingSystem os1 = new MobileOperatingSystem();\n        os1.setId(\"o1\");\n        os1.setName(\"os1\");\n\n        MobileOperatingSystem os2 = new MobileOperatingSystem();\n        os2.setId(\"o2\");\n        os2.setName(\"os2\");\n\n        MobileHandset mobile1 = new MobileHandset();\n        mobile1.setId(\"m1\");\n        mobile1.setName(\"mobile1\");\n        mobile1.setManufacturer(manu1);\n        mobile1.setOs(os1);\n\n        MobileHandset mobile2 = new MobileHandset();\n        mobile2.setId(\"m2\");\n        mobile2.setName(\"mobile2\");\n        mobile2.setManufacturer(manu1);\n        mobile2.setOs(os1);\n\n        MobileHandset mobile3 = new MobileHandset();\n        mobile3.setId(\"m3\");\n        mobile3.setName(\"mobile3\");\n        mobile3.setManufacturer(manu1);\n        mobile3.setOs(os2);\n\n        MobileHandset mobile4 = new MobileHandset();\n        mobile4.setId(\"m4\");\n        mobile4.setName(\"mobile4\");\n        mobile4.setManufacturer(manu2);\n        mobile4.setOs(os1);\n\n        em.persist(mobile1);\n        em.persist(mobile2);\n        em.persist(mobile3);\n        em.persist(mobile4);\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    protected void tearDownInternal() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n\n        if (em != null)\n        {\n            em.close();\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/crud/associations/AssociationsBiDirectionalTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.associations;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * @author Pragalbh Garg\n *\n */\npublic class AssociationsBiDirectionalTest extends AssociationsBiDirectionalBase\n{\n\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUpInternal();\n    }\n\n    @Test\n    public void test()\n    {\n        assertCRUD();\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        tearDownInternal();\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/crud/associations/MobileHandset.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.associations;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * @author Pragalbh Garg\n *\n */\n@Entity\n@Table(name = \"mobile_handset\")\npublic class MobileHandset\n{\n\n    @Id\n    private String id;\n    \n    @Column(name=\"mob_name\")\n    private String name;\n    \n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"os\")\n    private MobileOperatingSystem os;\n    \n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name=\"manufacturer\")\n    private MobileManufacturer manufacturer;\n\n    public MobileManufacturer getManufacturer()\n    {\n        return manufacturer;\n    }\n\n    public void setManufacturer(MobileManufacturer manufacturer)\n    {\n        this.manufacturer = manufacturer;\n    }\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public MobileOperatingSystem getOs()\n    {\n        return os;\n    }\n\n    public void setOs(MobileOperatingSystem os)\n    {\n        this.os = os;\n    }\n    \n    \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/crud/associations/MobileManufacturer.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.associations;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * @author Pragalbh Garg\n * \n */\n@Entity\n@Table(name = \"mobile_manufacturer\")\npublic class MobileManufacturer\n{\n\n    @Id\n    @Column(name = \"app_id\")\n    private String id;\n\n    @Column(name = \"app_name\")\n    private String name;\n\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, mappedBy = \"manufacturer\")\n    private Set<MobileHandset> handsets;\n\n    public Set<MobileHandset> getHandsets()\n    {\n        return handsets;\n    }\n\n    public void setHandsets(Set<MobileHandset> handsets)\n    {\n        this.handsets = handsets;\n    }\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/crud/associations/MobileOperatingSystem.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.associations;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * @author Pragalbh Garg\n *\n */\n@Entity\n@Table(name = \"operating_system\")\npublic class MobileOperatingSystem\n{\n    @Id\n    @Column(name = \"os_id\")\n    private String id;\n\n    @Column(name = \"os_name\")\n    private String name;\n\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, mappedBy = \"os\")\n    private Set<MobileHandset> handsets;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public Set<MobileHandset> getHandsets()\n    {\n        return handsets;\n    }\n\n    public void setHandsets(Set<MobileHandset> handsets)\n    {\n        this.handsets = handsets;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/AbstractTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Id;\nimport javax.persistence.MappedSuperclass;\n\n/**\n * @author vivek.mishra\n * Transaction {@link MappedSuperclass}\n */\n\n@MappedSuperclass\npublic class AbstractTransaction\n{\n\n    @Id\n    private String txId;\n    \n    @Column\n    private Date transactionDt;\n\n    public Date getTransactionDt()\n    {\n        return transactionDt;\n    }\n\n    public void setTransactionDt(Date transactionDt)\n    {\n        this.transactionDt = transactionDt;\n    }\n\n    public String getTxId()\n    {\n        return txId;\n    }\n\n    public void setTxId(String txId)\n    {\n        this.txId = txId;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/CreditTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * Credit transaction extends {@link Transaction}\n *\n */\n\n@Entity\n@Table(name = \"TRNX_CREDIT\")\n@DiscriminatorValue(value = \"CREDIT\")\n@AttributeOverride(name=\"bankIdentifier\",column= @Column(name=\"CREDIT_BANK_IDENT\"))\npublic class CreditTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public CreditTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/DebitTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\n\n/**\n * @author vivek.mishra\n * Debit transaction extends {@link Transaction}\n *\n */\n@Entity\n@DiscriminatorValue(value=\"DEBIT\")\n\n@AttributeOverrides(value = { @AttributeOverride(name = \"txId\", column = @Column(name = \"DEBIT_ID\")),\n        @AttributeOverride(name = \"bankIdentifier\", column = @Column(name = \"DEBIT_BANK_IDENT\")),\n        @AttributeOverride(name = \"transactionDt\", column = @Column(name = \"TX_DT\")) })\n\npublic class DebitTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public DebitTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/MappedSuperClassBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.MappedSuperclass;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * @author vivek.mishra junit for {@link MappedSuperclass},\n *         {@link AttributeOverride}, {@link AttributeOverrides}.\n */\npublic abstract class MappedSuperClassBase\n{\n\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(MappedSuperClassBase.class);\n\n    protected String _PU = \"corePu\";\n\n    /** The emf. */\n    protected static EntityManagerFactory emf;\n\n    /** The em. */\n    protected static EntityManager em;\n\n    protected void setUpInternal() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(_PU);\n        em = emf.createEntityManager();\n    }\n\n    protected void assertInternal()\n    {\n        assertInternal(false);\n    }\n\n    protected void assertInternal(boolean wait)\n    {\n        CreditTransaction creditTx = new CreditTransaction();\n        creditTx.setTxId(\"credit1\");\n        creditTx.setTxStatus(Status.APPROVED);\n        creditTx.setBankIdentifier(\"sbi\");\n        creditTx.setTransactionDt(new Date());\n        creditTx.setAmount(10);\n        em.persist(creditTx);\n\n        waitThread(wait);\n\n        DebitTransaction debitTx = new DebitTransaction();\n        debitTx.setTxId(\"debit1\");\n        debitTx.setTxStatus(Status.PENDING);\n        debitTx.setTransactionDt(new Date());\n        debitTx.setBankIdentifier(\"sbi\");\n        debitTx.setAmount(-10);\n        em.persist(debitTx);\n\n        waitThread(wait);\n        em.clear();\n        String creditQuery = \"Select c from CreditTransaction c where c.bankIdentifier = 'sbi'\";\n\n        Query query = em.createQuery(creditQuery);\n\n        List<CreditTransaction> results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"credit1\", results.get(0).getTxId());\n\n        em.clear();\n        String debitQuery = \"Select d from DebitTransaction d where d.bankIdentifier = 'sbi'\";\n\n        query = em.createQuery(debitQuery);\n\n        List<DebitTransaction> debitResults = query.getResultList();\n        Assert.assertEquals(1, debitResults.size());\n        Assert.assertEquals(\"debit1\", debitResults.get(0).getTxId());\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    protected void tearDownInternal() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n\n        if (em != null)\n        {\n            em.close();\n        }\n\n        \n    }\n\n    private void waitThread(boolean toWait)\n    {\n        if (toWait)\n        {\n            try\n            {\n                Thread.sleep(2000);\n            }\n            catch (InterruptedException e)\n            {\n                log.error(\"Error while thread interruption, {}\", e);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/Status.java",
    "content": "package com.impetus.kundera.client.crud.mappedsuperclass;\n\npublic enum Status\n{\n\n    APPROVED,PENDING\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/Transaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorColumn;\nimport javax.persistence.Id;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.MappedSuperclass;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * Transaction {@link MappedSuperclass}\n *\n */\n@MappedSuperclass\n@Table(name = \"TRNX\")\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@DiscriminatorColumn(name = \"tx_type\")\npublic class Transaction \n{\n\n    @Id\n    private String txId;\n    \n    @Column\n    private String bankIdentifier;\n\n    \n    @Column\n    private Date transactionDt;\n\n    public Date getTransactionDt()\n    {\n        return transactionDt;\n    }\n\n    public void setTransactionDt(Date transactionDt)\n    {\n        this.transactionDt = transactionDt;\n    }\n\n\n\n    public String getTxId()\n    {\n        return txId;\n    }\n\n    public void setTxId(String txId)\n    {\n        this.txId = txId;\n    }\n\n    public String getBankIdentifier()\n    {\n        return bankIdentifier;\n    }\n\n    public void setBankIdentifier(String bankIdentifier)\n    {\n        this.bankIdentifier = bankIdentifier;\n    }\n\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/query/AggregationsBaseTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.query;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.query.Person;\nimport com.impetus.kundera.query.Person.Day;\n\n/**\n * The Class AggregationsBaseTest.\n * \n * @author: karthikp.manchala\n * \n */\npublic abstract class AggregationsBaseTest\n{\n\n    /** The emf. */\n    protected EntityManagerFactory emf;\n\n    /** The em. */\n    protected EntityManager em;\n\n    /** The person. */\n    private Person person;\n\n    /**\n     * logger\n     */\n    private Logger logger = LoggerFactory.getLogger(AggregationsBaseTest.class);\n\n    /**\n     * Check if server running.\n     * \n     * @return true, if successful\n     */\n    protected static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 9300);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n    }\n\n    /**\n     * Inits the.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    protected void init() throws InterruptedException\n    {\n\n        createPerson(\"1\", 20, \"Amit\", 100.0);\n        createPerson(\"2\", 10, \"Dev\", 200.0);\n        createPerson(\"3\", 30, \"Karthik\", 300.0);\n        createPerson(\"4\", 40, \"Pragalbh\", 400.0);\n        waitThread();\n    }\n\n    /**\n     * Creates the person.\n     * \n     * @param id\n     *            the id\n     * @param age\n     *            the age\n     * @param name\n     *            the name\n     * @param salary\n     *            the salary\n     */\n    private void createPerson(String id, int age, String name, Double salary)\n    {\n        person = new Person();\n        person.setAge(age);\n//        person.setDay(Day.FRIDAY);\n        person.setPersonId(id);\n        person.setPersonName(name);\n        person.setSalary(salary);\n        em.persist(person);\n    }\n\n    /**\n     * Test min aggregation.\n     */\n    protected void testAggregation()\n    {\n        testMinAggregation();\n        testMultiMinAggregation();\n        testMaxAggregation();\n        testMultiMaxAggregation();\n        testSumAggregation();\n        testMultiSumAggregation();\n        testAvgAggregation();\n        testMultiAvgAggregation();\n        testMaxMinSameFieldAggregation();\n        testMultiAggregation();\n        testMinMaxSumAvgAggregation();\n        testAggregationWithWhereClause();\n        testPositionalQuery();\n        testParameterQuery();\n        testBetween();\n        testBetweenWithExpression();\n        testBetweenMin();\n        testLikeQuery();\n\n    }\n\n    /**\n     * Test min aggregation.\n     */\n    private void testMinAggregation()\n    {\n        Person p = em.find(Person.class, \"1\");\n        String queryString = \"Select min(p.salary) from Person p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(100.0, resultList.get(0));\n    }\n\n    /**\n     * Test multi min aggregation.\n     */\n    private void testMultiMinAggregation()\n    {\n\n        String queryString = \"Select min(p.salary), min(p.age) from Person p where p.age > 20\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(300.0, resultList.get(0));\n        Assert.assertEquals(30.0, resultList.get(1));\n    }\n\n    /**\n     * Test max aggregation.\n     */\n    private void testMaxAggregation()\n    {\n        String queryString = \"Select max(p.age) from Person p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(40.0, resultList.get(0));\n    }\n\n    /**\n     * Test multi max aggregation.\n     */\n    private void testMultiMaxAggregation()\n\n    {\n        String queryString = \"Select max(p.age), max(p.salary) from Person p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(40.0, resultList.get(0));\n        Assert.assertEquals(400.0, resultList.get(1));\n    }\n\n    /**\n     * Test sum aggregation.\n     */\n    private void testSumAggregation()\n    {\n        String queryString = \"Select sum(p.salary) from Person p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(1000.0, resultList.get(0));\n    }\n\n    /**\n     * Test multi sum aggregation.\n     */\n    private void testMultiSumAggregation()\n    {\n        String queryString = \"Select sum(p.salary), sum(p.age) from Person p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(1000.0, resultList.get(0));\n        Assert.assertEquals(100.0, resultList.get(1));\n    }\n\n    /**\n     * Test avg aggregation.\n     */\n    private void testAvgAggregation()\n    {\n        String queryString = \"Select avg(p.salary) from Person p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(250.0, resultList.get(0));\n    }\n\n    /**\n     * Test multi avg aggregation.\n     */\n    private void testMultiAvgAggregation()\n    {\n        String avgQuery = \"Select avg(p.salary), avg(p.age) from Person p\";\n        Query query = em.createQuery(avgQuery);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(250.0, resultList.get(0));\n        Assert.assertEquals(25.0, resultList.get(1));\n    }\n\n    /**\n     * Test max min same field aggregation.\n     */\n    private void testMaxMinSameFieldAggregation()\n    {\n        String queryString = \"Select max(p.age), min(p.age) from Person p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(40.0, resultList.get(0));\n        Assert.assertEquals(10.0, resultList.get(1));\n    }\n\n    /**\n     * Test multi aggregation.\n     */\n    private void testMultiAggregation()\n    {\n        String queryString = \"Select min(p.age), min(p.salary), max(p.age), max(p.salary) from Person p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n        Assert.assertEquals(10.0, resultList.get(0));\n        Assert.assertEquals(100.0, resultList.get(1));\n        Assert.assertEquals(40.0, resultList.get(2));\n        Assert.assertEquals(400.0, resultList.get(3));\n    }\n\n    /**\n     * Test min max sum avg aggregation.\n     */\n    private void testMinMaxSumAvgAggregation()\n    {\n        String queryString = \"Select min(p.salary), max(p.salary), sum(p.salary), avg(p.salary) from Person p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n        Assert.assertEquals(100.0, resultList.get(0));\n        Assert.assertEquals(400.0, resultList.get(1));\n        Assert.assertEquals(1000.0, resultList.get(2));\n        Assert.assertEquals(250.0, resultList.get(3));\n    }\n\n    /**\n     * Test aggregation with where clause.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    private void testAggregationWithWhereClause()\n    {\n        try\n        {\n            waitThread();\n\n            String invalidQueryWithAndClause = \"Select min(p.age) from Person p where p.personName = 'amit' AND p.age = 34\";\n            Query nameQuery = em.createNamedQuery(invalidQueryWithAndClause);\n            List persons = nameQuery.getResultList();\n\n            Assert.assertTrue(persons.isEmpty());\n\n            String queryWithAndClause = \"Select min(p.age) from Person p where p.personName = 'amit' AND p.age = 20\";\n            nameQuery = em.createNamedQuery(queryWithAndClause);\n            persons = nameQuery.getResultList();\n\n            Assert.assertFalse(persons.isEmpty());\n            Assert.assertEquals(1, persons.size());\n            Assert.assertEquals(20.0, persons.get(0));\n\n            String queryWithORClause = \"Select max(p.salary) from Person p where p.personName = 'amit' OR p.personName = 'dev'\";\n            nameQuery = em.createNamedQuery(queryWithORClause);\n            persons = nameQuery.getResultList();\n\n            Assert.assertFalse(persons.isEmpty());\n            Assert.assertEquals(1, persons.size());\n            Assert.assertEquals(200.0, persons.get(0));\n\n            String queryMinMaxWithORClause = \"Select max(p.salary), min(p.age) from Person p where p.personName = 'amit' OR p.personName = 'karthik'\";\n            nameQuery = em.createNamedQuery(queryMinMaxWithORClause);\n            persons = nameQuery.getResultList();\n\n            Assert.assertFalse(persons.isEmpty());\n            Assert.assertEquals(2, persons.size());\n            Assert.assertEquals(300.0, persons.get(0));\n            Assert.assertEquals(20.0, persons.get(1));\n\n            String invalidQueryWithORClause = \"Select sum(p.age) from Person p where p.personName = 'amit' OR p.personName = 'lkl'\";\n            nameQuery = em.createNamedQuery(invalidQueryWithORClause);\n            persons = nameQuery.getResultList();\n\n            Assert.assertFalse(persons.isEmpty());\n            Assert.assertEquals(1, persons.size());\n            Assert.assertEquals(20.0, persons.get(0));\n\n            String testSumWithGreaterThanClause = \"Select sum(p.age) from Person p where p.age > 15\";\n            nameQuery = em.createNamedQuery(testSumWithGreaterThanClause);\n            persons = nameQuery.getResultList();\n\n            Assert.assertFalse(persons.isEmpty());\n            Assert.assertEquals(1, persons.size());\n            Assert.assertEquals(90.0, persons.get(0));\n            waitThread();\n        }\n        catch (InterruptedException e)\n        {\n            logger.error(e.getMessage());\n        }\n    }\n\n    /**\n     * Test positional query.\n     */\n    private void testPositionalQuery()\n    {\n        String queryString = \"Select min(p.salary) from Person p where p.personName = ?1\";\n        Query query = em.createQuery(queryString);\n        query.setParameter(1, \"amit\");\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(100.0, resultList.get(0));\n    }\n\n    /**\n     * Test parameter query.\n     */\n    private void testParameterQuery()\n    {\n        String queryString = \"Select p from Person p where p.personName = :personName\";\n        Query query = em.createQuery(queryString);\n        query.setParameter(\"personName\", \"amit\");\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(100.0, ((Person) resultList.get(0)).getSalary());\n    }\n\n    /**\n     * Test between.\n     */\n    private void testBetween()\n    {\n        String queryString = \"Select p from Person p where p.age between 20 and 34\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n    }\n\n    /**\n     * Test between with expression.\n     */\n    protected void testBetweenWithExpression()\n    {\n        String queryString = \"Select p from Person p where p.age between 15+5 and 40-6\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n    }\n\n    /**\n     * Test between min.\n     */\n    private void testBetweenMin()\n    {\n        String queryString = \"Select min(p.age) from Person p where p.age between 18 and 34\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(20.0, resultList.get(0));\n    }\n\n    /**\n     * Test like query.\n     */\n    private void testLikeQuery()\n    {\n        String queryString = \"Select min(p.age) from Person p where p.personName like '%mit'\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(20.0, resultList.get(0));\n    }\n\n    /**\n     * Wait thread.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    protected void waitThread() throws InterruptedException\n    {\n        Thread.sleep(2000);\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/query/GroupByBaseTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.query;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport com.impetus.kundera.query.Person;\nimport com.impetus.kundera.query.Person.Day;\n\n/**\n * The Class GroupByBaseTest.\n * \n * @author karthikp.manchala\n * \n */\npublic abstract class GroupByBaseTest\n{\n    /** The emf. */\n    protected static EntityManagerFactory emf;\n\n    /** The em. */\n    protected static EntityManager em;\n\n    /** The person. */\n    private static Person person;\n\n    /**\n     * Check if server running.\n     * \n     * @return true, if successful\n     */\n    protected static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 9300);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n    }\n\n    /**\n     * Inits the.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    protected static void init() throws InterruptedException\n    {\n        createPerson(\"1\", 10, \"Amit\", 100.0);\n        createPerson(\"2\", 20, \"Dev\", 200.0);\n        createPerson(\"3\", 30, \"Karthik\", 300.0);\n        createPerson(\"4\", 40, \"Pragalbh\", 400.0);\n        createPerson(\"5\", 10, \"AK\", 500.0);\n        createPerson(\"6\", 20, \"D\", 600.0);\n        createPerson(\"7\", 30, \"KPM\", 700.0);\n        createPerson(\"8\", 40, \"PG\", 800.0);\n        waitThread();\n    }\n\n    /**\n     * Creates the person.\n     * \n     * @param id\n     *            the id\n     * @param age\n     *            the age\n     * @param name\n     *            the name\n     * @param salary\n     *            the salary\n     */\n    private static void createPerson(String id, int age, String name, Double salary)\n    {\n        person = new Person();\n        person.setAge(age);\n        person.setPersonId(id);\n        person.setPersonName(name);\n        person.setSalary(salary);\n//        person.setDay(Day.FRIDAY);\n        em.persist(person);\n    }\n\n    /**\n     * Test aggregation.\n     */\n    protected void testAggregation()\n    {\n        testGroupBy();\n        testGroupByRowKey();\n        testGroupByWithWhereClause();\n        testGroupByWithEntity();\n        testGroupByWithFields();\n        testGroupByWithMetricAgg();\n\n        testHaving();\n        testHavingWithWhereClause();\n        testHavingWithEntity();\n        testHavingWithCount();\n        testHavingWithNoMatch();\n        testHavingWithMetricAgg();\n\n        testHavingWithAnd();\n        testHavingWithOr();\n\n        // testGroupByBuckets();\n    }\n\n    /**\n     * Test group by.\n     */\n    private void testGroupBy()\n    {\n        String queryString = \"Select sum(p.salary) from Person p group by p.age\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        Assert.assertEquals(600.0, (resultList.get(0)));\n        Assert.assertEquals(800.0, (resultList.get(1)));\n        Assert.assertEquals(1000.0, (resultList.get(2)));\n        Assert.assertEquals(1200.0, (resultList.get(3)));\n    }\n\n    /**\n     * Test group by row key.\n     */\n    private void testGroupByRowKey()\n    {\n        String queryString = \"Select sum(p.salary) from Person p group by p.personId\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(8, resultList.size());\n        Assert.assertEquals(100.0, (resultList.get(0)));\n        Assert.assertEquals(200.0, (resultList.get(1)));\n        Assert.assertEquals(300.0, (resultList.get(2)));\n        Assert.assertEquals(400.0, (resultList.get(3)));\n        Assert.assertEquals(500.0, (resultList.get(4)));\n        Assert.assertEquals(600.0, (resultList.get(5)));\n        Assert.assertEquals(700.0, (resultList.get(6)));\n        Assert.assertEquals(800.0, (resultList.get(7)));\n    }\n\n    /**\n     * Test group by with where clause.\n     */\n    private void testGroupByWithWhereClause()\n    {\n        String queryString = \"Select sum(p.salary) from Person p where p.age > 20 group by p.age\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(1000.0, (resultList.get(0)));\n        Assert.assertEquals(1200.0, (resultList.get(1)));\n    }\n\n    /**\n     * Test group by with entity.\n     */\n    private void testGroupByWithEntity()\n    {\n        String queryString = \"Select p from Person p where p.age < 20 group by p.age\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Person person = (Person) (resultList.get(0));\n        Assert.assertEquals(\"5\", person.getPersonId());\n        Assert.assertEquals(\"AK\", person.getPersonName());\n        Assert.assertEquals(10, person.getAge().intValue());\n        Assert.assertEquals(500.0, person.getSalary());\n    }\n\n    /**\n     * Test group by with fields.\n     */\n    private void testGroupByWithFields()\n    {\n        String queryString = \"Select p.age, p.personName, p.personId from Person p where p.age < 30 group by p.age\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n\n        List result = (List) resultList.get(0);\n        Assert.assertEquals(10, result.get(0));\n\n        result = (List) resultList.get(1);\n        Assert.assertEquals(20, result.get(0));\n    }\n\n    /**\n     * Test group by with metric agg.\n     */\n    private void testGroupByWithMetricAgg()\n    {\n        String queryString = \"Select p.salary, sum(p.age), p.personName, p.personId from Person p where p.age < 30 group by p.salary\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        List result = (List) resultList.get(0);\n        Assert.assertEquals(100.0, result.get(0));\n        Assert.assertEquals(10.0, result.get(1));\n        Assert.assertEquals(\"Amit\", result.get(2));\n        Assert.assertEquals(\"1\", result.get(3));\n\n        result = (List) resultList.get(1);\n        Assert.assertEquals(200.0, result.get(0));\n        Assert.assertEquals(20.0, result.get(1));\n        Assert.assertEquals(\"Dev\", result.get(2));\n        Assert.assertEquals(\"2\", result.get(3));\n\n        result = (List) resultList.get(2);\n        Assert.assertEquals(500.0, result.get(0));\n        Assert.assertEquals(10.0, result.get(1));\n        Assert.assertEquals(\"AK\", result.get(2));\n        Assert.assertEquals(\"5\", result.get(3));\n\n        result = (List) resultList.get(3);\n        Assert.assertEquals(600.0, result.get(0));\n        Assert.assertEquals(20.0, result.get(1));\n        Assert.assertEquals(\"D\", result.get(2));\n        Assert.assertEquals(\"6\", result.get(3));\n    }\n\n    /**\n     * Test having.\n     */\n    private void testHaving()\n    {\n        String queryString = \"Select sum(p.salary) from Person p group by p.age having avg(p.age) > 20\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n\n        Assert.assertEquals(1000.0, (resultList.get(0)));\n        Assert.assertEquals(1200.0, (resultList.get(1)));\n    }\n\n    /**\n     * Test having with where clause.\n     */\n    private void testHavingWithWhereClause()\n    {\n        String queryString = \"Select sum(p.salary) from Person p where p.age > 20 group by p.age having sum(p.age) > 70\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(1200.0, (resultList.get(0)));\n    }\n\n    /**\n     * Test having with entity.\n     */\n    private void testHavingWithEntity()\n    {\n        String queryString = \"Select p from Person p where p.age < 40 group by p.age having max(p.salary) > 600\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Person person = (Person) (resultList.get(0));\n        Assert.assertEquals(\"7\", person.getPersonId());\n        Assert.assertEquals(\"KPM\", person.getPersonName());\n        Assert.assertEquals(30, person.getAge().intValue());\n        Assert.assertEquals(700.0, person.getSalary());\n    }\n\n    /**\n     * Test having with count.\n     */\n    private void testHavingWithCount()\n    {\n        String queryString = \"Select p.age, p.personName, p.personId from Person p where p.age < 30 group by p.age having count(p) > 1\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n\n        List result = (List) resultList.get(0);\n        Assert.assertEquals(10, result.get(0));\n\n        result = (List) resultList.get(1);\n        Assert.assertEquals(20, result.get(0));\n    }\n\n    /**\n     * Test having with no match.\n     */\n    private void testHavingWithNoMatch()\n    {\n        String queryString = \"Select p.age, p.personName, p.personId from Person p where p.age < 30 group by p.age having count(p) > 2\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(0, resultList.size());\n    }\n\n    /**\n     * Test having with metric agg.\n     */\n    private void testHavingWithMetricAgg()\n    {\n        String queryString = \"Select p.salary, sum(p.age), p.personName, p.personId from Person p group by p.personId having sum(p.age) < 30\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        List result = (List) resultList.get(0);\n        Assert.assertEquals(100.0, result.get(0));\n        Assert.assertEquals(10.0, result.get(1));\n        Assert.assertEquals(\"Amit\", result.get(2));\n        Assert.assertEquals(\"1\", result.get(3));\n\n        result = (List) resultList.get(1);\n        Assert.assertEquals(200.0, result.get(0));\n        Assert.assertEquals(20.0, result.get(1));\n        Assert.assertEquals(\"Dev\", result.get(2));\n        Assert.assertEquals(\"2\", result.get(3));\n\n        result = (List) resultList.get(2);\n        Assert.assertEquals(500.0, result.get(0));\n        Assert.assertEquals(10.0, result.get(1));\n        Assert.assertEquals(\"AK\", result.get(2));\n        Assert.assertEquals(\"5\", result.get(3));\n\n        result = (List) resultList.get(3);\n        Assert.assertEquals(600.0, result.get(0));\n        Assert.assertEquals(20.0, result.get(1));\n        Assert.assertEquals(\"D\", result.get(2));\n        Assert.assertEquals(\"6\", result.get(3));\n    }\n\n    /**\n     * Test having with and.\n     */\n    private void testHavingWithAnd()\n    {\n        String queryString = \"Select p.age, p.personName, p.personId from Person p where p.age > 20 group by p.age having sum(p.age) > 50 and avg(p.age) < 40\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n\n        List result = (List) resultList.get(0);\n        Assert.assertEquals(30, result.get(0));\n        Assert.assertEquals(\"KPM\", result.get(1));\n        Assert.assertEquals(\"7\", result.get(2));\n    }\n\n    /**\n     * Test having with or.\n     */\n    private void testHavingWithOr()\n    {\n        String queryString = \"Select sum(p.age), count(p.age) from Person p where p.salary > 200.0 group by p.age having sum(p.age) > 50 or avg(p.age) < 40\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        List result = (List) resultList.get(0);\n        Assert.assertEquals(60.0, result.get(0));\n        Assert.assertEquals(2.0, result.get(1));\n\n        result = (List) resultList.get(1);\n        Assert.assertEquals(80.0, result.get(0));\n        Assert.assertEquals(2.0, result.get(1));\n\n        result = (List) resultList.get(2);\n        Assert.assertEquals(10.0, result.get(0));\n        Assert.assertEquals(1.0, result.get(1));\n\n        result = (List) resultList.get(3);\n        Assert.assertEquals(20.0, result.get(0));\n        Assert.assertEquals(1.0, result.get(1));\n    }\n\n    /**\n     * Test group by buckets.\n     */\n    private void testGroupByBuckets()\n    {\n        createPerson(\"9\", 10, \"Amit\", 100.0);\n        createPerson(\"10\", 10, \"Dev\", 200.0);\n        createPerson(\"11\", 10, \"Karthik\", 300.0);\n        createPerson(\"12\", 10, \"Pragalbh\", 400.0);\n        createPerson(\"13\", 10, \"AK\", 500.0);\n        createPerson(\"14\", 10, \"D\", 600.0);\n        createPerson(\"15\", 10, \"KPM\", 700.0);\n        createPerson(\"16\", 10, \"PG\", 800.0);\n        try\n        {\n            waitThread();\n        }\n        catch (InterruptedException e)\n        {\n        }\n\n        String queryString = \"Select sum(p.age) from Person p where p.age < 40 group by p.personId\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(14, resultList.size());\n\n        queryString = \"Select sum(p.age) from Person p where p.age < 40 group by p.age\";\n        query = em.createQuery(queryString);\n        resultList = query.getResultList();\n\n        Assert.assertEquals(3, resultList.size());\n        Assert.assertEquals(100.0, resultList.get(0));\n    }\n\n    /**\n     * Wait thread.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    protected static void waitThread() throws InterruptedException\n    {\n        Thread.sleep(2000);\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/client/query/OrderByBaseTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.query;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.query.Person;\nimport com.impetus.kundera.query.Person.Day;\n\n/**\n * @author Amit Kumar\n * \n */\npublic abstract class OrderByBaseTest\n{\n    /** The emf. */\n    protected static EntityManagerFactory emf;\n\n    /** The em. */\n    protected static EntityManager em;\n\n    /** The node. */\n    protected static Node node = null;\n\n    /** The person. */\n    protected static Person persons[] = new Person[4];\n\n    /**\n     * Check if server running.\n     * \n     * @return true, if successful\n     */\n    protected static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 9300);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n    }\n\n    /**\n     * Inits the.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    protected static void init() throws InterruptedException\n    {\n        persons[0] = createPerson(\"1\", 50, \"karthik\", 500.0);\n        persons[1] = createPerson(\"2\", 20, \"pragalbh\", 700.0);\n        persons[2] = createPerson(\"3\", 60, \"amit\", 300.0);\n        persons[3] = createPerson(\"4\", 40, \"dev\", 400.0);\n\n        waitThread();\n    }\n\n    /**\n     * Creates the person.\n     * \n     * @param id\n     *            the id\n     * @param age\n     *            the age\n     * @param name\n     *            the name\n     * @param salary\n     *            the salary\n     * @return the person es\n     */\n    protected static Person createPerson(String id, int age, String name, Double salary)\n    {\n        Person person = new Person();\n        person.setAge(age);\n        person.setDay(Day.FRIDAY);\n        person.setPersonId(id);\n        person.setPersonName(name);\n        person.setSalary(salary);\n\n        em.persist(person);\n\n        return person;\n    }\n\n    /**\n     * Test query.\n     */\n    public void testQuery()\n    {\n        testOrderBy();\n        testOrderByDescending();\n        testOrderByRowId();\n        testOrderByRowIdDescending();\n        testOrderByAscending();\n        testOrderByDescWithString();\n        testOrderByASCWhereClause();\n        testOrderByASCMultipleFields();\n        testOrderByWithGroupBy();\n        testOrderByWithGroupByDESC();\n        testOrderByWithGroupByString();\n        testOrderByWithGroupByStringDESC();\n    }\n\n    /**\n     * Test order by.\n     */\n    private void testOrderBy()\n    {\n        String queryString = \"Select p from Person p order by p.age\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        assertPerson((Person) resultList.get(0), persons[1]);\n        assertPerson((Person) resultList.get(1), persons[3]);\n        assertPerson((Person) resultList.get(2), persons[0]);\n        assertPerson((Person) resultList.get(3), persons[2]);\n    }\n\n    /**\n     * Test order by descending.\n     */\n    private void testOrderByDescending()\n    {\n        String queryString = \"Select p from Person p order by p.age DESC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        assertPerson((Person) resultList.get(0), persons[2]);\n        assertPerson((Person) resultList.get(1), persons[0]);\n        assertPerson((Person) resultList.get(2), persons[3]);\n        assertPerson((Person) resultList.get(3), persons[1]);\n    }\n\n    /**\n     * Test order by row id.\n     */\n    private void testOrderByRowId()\n    {\n        String queryString = \"Select p from Person p order by p.personId\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        assertPerson((Person) resultList.get(0), persons[0]);\n        assertPerson((Person) resultList.get(1), persons[1]);\n        assertPerson((Person) resultList.get(2), persons[2]);\n        assertPerson((Person) resultList.get(3), persons[3]);\n    }\n\n    /**\n     * Test order by row id descending.\n     */\n    private void testOrderByRowIdDescending()\n    {\n        String queryString = \"Select p from Person p order by p.personId DESC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        assertPerson((Person) resultList.get(0), persons[3]);\n        assertPerson((Person) resultList.get(1), persons[2]);\n        assertPerson((Person) resultList.get(2), persons[1]);\n        assertPerson((Person) resultList.get(3), persons[0]);\n    }\n\n    /**\n     * Test order by ascending.\n     */\n    private void testOrderByAscending()\n    {\n        String queryString = \"Select p.personName from Person p order by p.age ASC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        Assert.assertEquals(\"pragalbh\", ((Person) resultList.get(0)).getPersonName());\n        Assert.assertEquals(\"dev\", ((Person) resultList.get(1)).getPersonName());\n        Assert.assertEquals(\"karthik\", ((Person) resultList.get(2)).getPersonName());\n        Assert.assertEquals(\"amit\", ((Person) resultList.get(3)).getPersonName());\n    }\n\n    /**\n     * Test order by desc with string.\n     */\n    private void testOrderByDescWithString()\n    {\n        String queryString = \"Select p.personName from Person p order by p.personName DESC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        Assert.assertEquals(\"pragalbh\", ((Person) resultList.get(0)).getPersonName());\n        Assert.assertEquals(\"karthik\", ((Person) resultList.get(1)).getPersonName());\n        Assert.assertEquals(\"dev\", ((Person) resultList.get(2)).getPersonName());\n        Assert.assertEquals(\"amit\", ((Person) resultList.get(3)).getPersonName());\n    }\n\n    /**\n     * Test order by asc where clause.\n     */\n    private void testOrderByASCWhereClause()\n    {\n        String queryString = \"Select p.personName from Person p where p.salary > 350.0 order by p.age ASC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(3, resultList.size());\n\n        Assert.assertEquals(\"pragalbh\", ((Person) resultList.get(0)).getPersonName());\n        Assert.assertEquals(\"dev\", ((Person) resultList.get(1)).getPersonName());\n        Assert.assertEquals(\"karthik\", ((Person) resultList.get(2)).getPersonName());\n    }\n\n    /**\n     * Test order by asc multiple fields.\n     */\n    private void testOrderByASCMultipleFields()\n    {\n        String queryString = \"Select p.personName, p.age, p.salary from Person p where p.salary <> 300.0 order by p.age ASC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(3, resultList.size());\n\n        Assert.assertEquals(\"pragalbh\", (((Person) resultList.get(0)).getPersonName()));\n        Assert.assertEquals(20, ((Person) resultList.get(0)).getAge().intValue());\n        Assert.assertEquals(700.0, ((Person) resultList.get(0)).getSalary());\n\n        Assert.assertEquals(\"dev\", ((Person) resultList.get(1)).getPersonName());\n        Assert.assertEquals(40, ((Person) resultList.get(1)).getAge().intValue());\n        Assert.assertEquals(400.0, ((Person) resultList.get(1)).getSalary());\n\n        Assert.assertEquals(\"karthik\", ((Person) resultList.get(2)).getPersonName());\n        Assert.assertEquals(50, ((Person) resultList.get(2)).getAge().intValue());\n        Assert.assertEquals(500.0, ((Person) resultList.get(2)).getSalary());\n    }\n\n    /**\n     * Test order by with group by.\n     */\n    private void testOrderByWithGroupBy()\n    {\n        String queryString = \"Select p from Person p where p.salary <> 300.0 group by p.age order by p.age ASC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(3, resultList.size());\n\n        assertPerson((Person) resultList.get(0), persons[1]);\n        assertPerson((Person) resultList.get(1), persons[3]);\n        assertPerson((Person) resultList.get(2), persons[0]);\n    }\n\n    /**\n     * Test order by with group by desc.\n     */\n    private void testOrderByWithGroupByDESC()\n    {\n        String queryString = \"Select p from Person p group by p.age order by p.age DESC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        assertPerson((Person) resultList.get(0), persons[2]);\n        assertPerson((Person) resultList.get(1), persons[0]);\n        assertPerson((Person) resultList.get(2), persons[3]);\n        assertPerson((Person) resultList.get(3), persons[1]);\n    }\n\n    /**\n     * Test order by with group by string.\n     */\n    private void testOrderByWithGroupByString()\n    {\n        String queryString = \"Select p.personName, p.age, p.salary from Person p where p.salary <> 300.0 group by p.personName order by p.personName ASC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(3, resultList.size());\n\n        Assert.assertEquals(\"dev\", ((List) resultList.get(0)).get(0));\n        Assert.assertEquals(40, ((List) resultList.get(0)).get(1));\n        Assert.assertEquals(400.0, ((List) resultList.get(0)).get(2));\n\n        Assert.assertEquals(\"karthik\", ((List) resultList.get(1)).get(0));\n        Assert.assertEquals(50, ((List) resultList.get(1)).get(1));\n        Assert.assertEquals(500.0, ((List) resultList.get(1)).get(2));\n\n        Assert.assertEquals(\"pragalbh\", ((List) resultList.get(2)).get(0));\n        Assert.assertEquals(20, ((List) resultList.get(2)).get(1));\n        Assert.assertEquals(700.0, ((List) resultList.get(2)).get(2));\n    }\n\n    /**\n     * Test order by with group by string desc.\n     */\n    private void testOrderByWithGroupByStringDESC()\n    {\n        String queryString = \"Select p.personName, p.age, p.salary from Person p where p.salary <> 300.0 group by p.personName order by p.personName DESC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(3, resultList.size());\n\n        Assert.assertEquals(\"pragalbh\", ((List) resultList.get(0)).get(0));\n        Assert.assertEquals(20, ((List) resultList.get(0)).get(1));\n        Assert.assertEquals(700.0, ((List) resultList.get(0)).get(2));\n\n        Assert.assertEquals(\"karthik\", ((List) resultList.get(1)).get(0));\n        Assert.assertEquals(50, ((List) resultList.get(1)).get(1));\n        Assert.assertEquals(500.0, ((List) resultList.get(1)).get(2));\n\n        Assert.assertEquals(\"dev\", ((List) resultList.get(2)).get(0));\n        Assert.assertEquals(40, ((List) resultList.get(2)).get(1));\n        Assert.assertEquals(400.0, ((List) resultList.get(2)).get(2));\n    }\n\n    /**\n     * Assert person.\n     * \n     * @param actual\n     *            the actual\n     * @param person\n     *            the person\n     */\n    private void assertPerson(Object actual, Person person)\n    {\n        Person actualPerson = (Person) actual;\n\n        Assert.assertEquals(actualPerson.getPersonId(), person.getPersonId());\n        Assert.assertEquals(actualPerson.getPersonName(), person.getPersonName());\n        Assert.assertEquals(actualPerson.getAge().intValue(), person.getAge().intValue());\n        Assert.assertEquals(actualPerson.getSalary(), person.getSalary());\n        Assert.assertEquals(actualPerson.getDay(), person.getDay());\n    }\n\n    /**\n     * Wait thread.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    protected static void waitThread() throws InterruptedException\n    {\n        Thread.sleep(2000);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/AbstractPropertyReaderTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * Abstract property reader test\n * \n * @author Kuldeep Mishra\n * \n */\npublic class AbstractPropertyReaderTest\n{\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.configure.AbstractPropertyReader#onParseXML(java.lang.String)}\n     * .\n     */\n    @Test\n    public void testParseXML()\n    {\n        String pu = \"PropertyTest\";\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(pu);\n        PropertyReader reader = new DummyPropertyReader(null, ((EntityManagerFactoryImpl) emf)\n                .getKunderaMetadataInstance().getApplicationMetadata().getPersistenceUnitMetadata(pu));\n        ClientProperties cp = null;\n        reader.read(pu);\n        cp = DummyPropertyReader.dsmd.getClientProperties();\n        assertValues(cp);\n    }\n\n    // @Test\n    public void testParseXMLWithAsolutePath()\n    {\n        String pu = \"PropertyTest\";\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(pu);\n        PropertyReader reader = new DummyPropertyReader(null, ((EntityManagerFactoryImpl) emf)\n                .getKunderaMetadataInstance().getApplicationMetadata().getPersistenceUnitMetadata(pu));\n        ClientProperties cp = null;\n        reader.read(pu);\n        cp = DummyPropertyReader.dsmd.getClientProperties();\n        assertValues(cp);\n    }\n\n    // @Test\n    public void testParseXMLWithVariable()\n    {\n        String pu = \"PropertyTest\";\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(pu);\n        PropertyReader reader = new DummyPropertyReader(null, ((EntityManagerFactoryImpl) emf)\n                .getKunderaMetadataInstance().getApplicationMetadata().getPersistenceUnitMetadata(pu));\n        ClientProperties cp = null;\n        reader.read(pu);\n        cp = DummyPropertyReader.dsmd.getClientProperties();\n        assertValues(cp);\n    }\n\n    private void assertValues(ClientProperties cp)\n    {\n        Assert.assertNotNull(cp);\n        Assert.assertNotNull(cp.getDatastores());\n        Assert.assertEquals(3, cp.getDatastores().size());\n        for (DataStore store : cp.getDatastores())\n        {\n            Assert.assertNotNull(store);\n            Assert.assertNotNull(store.getName());\n            // Test for hbase properties.\n            if (store.getName().trim().equalsIgnoreCase(\"HBase\"))\n            {\n                Assert.assertNotNull(store.getSchemas());\n                Assert.assertEquals(2, store.getSchemas().size());\n                Assert.assertEquals(\"KunderaHbaseXmlTest\", store.getSchemas().get(0).getName());\n                Assert.assertNotNull(store.getSchemas().get(0).getTables());\n                Assert.assertEquals(1, store.getSchemas().get(0).getTables().size());\n                Assert.assertEquals(\"HBASEUSERXYZ\", store.getSchemas().get(0).getTables().get(0).getName());\n\n                Assert.assertNotNull(store.getSchemas().get(0).getTables().get(0).getProperties());\n\n                Assert.assertEquals(5, store.getSchemas().get(0).getTables().get(0).getProperties().size());\n\n                Assert.assertNull(store.getSchemas().get(0).getDataCenters());\n                Assert.assertNull(store.getSchemas().get(0).getSchemaProperties());\n                Assert.assertNotNull(store.getConnection());\n                Assert.assertNotNull(store.getConnection().getProperties());\n                Assert.assertNull(store.getConnection().getServers());\n                Assert.assertEquals(2, store.getConnection().getProperties().size());\n\n            }\n            // Test for mongo properties.\n            else if (store.getName().trim().equalsIgnoreCase(\"Mongo\"))\n            {\n                Assert.assertNull(store.getSchemas());\n                Assert.assertNotNull(store.getConnection());\n                Assert.assertNotNull(store.getConnection().getProperties());\n                Assert.assertEquals(2, store.getConnection().getProperties().size());\n                Assert.assertNotNull(store.getConnection().getServers());\n                Assert.assertEquals(2, store.getConnection().getServers().size());\n            }\n            // Test for cassandra properties.\n            else if (store.getName().trim().equalsIgnoreCase(\"Cassandra\"))\n            {\n                Assert.assertNotNull(store.getSchemas());\n                Assert.assertEquals(3, store.getSchemas().size());\n                Assert.assertEquals(\"KunderaCassandraXmlTest\", store.getSchemas().get(0).getName());\n                Assert.assertNotNull(store.getSchemas().get(0).getTables());\n                Assert.assertEquals(2, store.getSchemas().get(0).getTables().size());\n                Assert.assertEquals(\"CASSANDRAUSERXYZ\", store.getSchemas().get(0).getTables().get(0).getName());\n                Assert.assertNotNull(store.getSchemas().get(0).getTables().get(0).getProperties());\n                Assert.assertEquals(7, store.getSchemas().get(0).getTables().get(0).getProperties().size());\n                Assert.assertNotNull(store.getSchemas().get(0).getDataCenters());\n                Assert.assertEquals(2, store.getSchemas().get(0).getDataCenters().size());\n                Assert.assertNotNull(store.getSchemas().get(0).getSchemaProperties());\n                Assert.assertEquals(3, store.getSchemas().get(0).getSchemaProperties().size());\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/ConfiguratorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.entity.PersonnelDTO;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * junit test case for {@link Configurator}.\n * \n * @author vivek.mishra\n */\npublic class ConfiguratorTest\n{\n    private final String _persistenceUnit = \"kunderatest\";\n\n    private final String kundera_client = \"com.impetus.kundera.client.CoreTestClientFactory\";\n\n    private String _keyspace = \"kunderatest\";\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n    }\n\n    /**\n     * Test valid configure.\n     */\n    @Test\n    public void testValidConfigure()\n    {\n        // invoke configure.\n       EntityManagerFactoryImpl emfImpl = getEntityManagerFactory();\n\n\n        // Assert entity metadata\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(emfImpl.getKunderaMetadataInstance(), PersonnelDTO.class);\n        Assert.assertNotNull(m);\n        Assert.assertNotNull(m.getPersistenceUnit());\n        Assert.assertEquals(_persistenceUnit, m.getPersistenceUnit());\n        Assert.assertEquals(PersonnelDTO.class.getName(), m.getEntityClazz().getName());\n\n        // Assert on persistence unit meta data.\n        PersistenceUnitMetadata puMetadata = emfImpl.getKunderaMetadataInstance().getApplicationMetadata().getPersistenceUnitMetadata(\n                _persistenceUnit);\n        Assert.assertEquals(kundera_client, puMetadata.getClient());\n        Assert.assertEquals(true, puMetadata.getExcludeUnlistedClasses());\n        Assert.assertNotNull(puMetadata.getPersistenceUnitRootUrl());\n        // emf.close();\n    }\n\n    // @Test\n    public void testEntityListener()\n    {\n        EntityManagerFactory emf = getEntityManagerFactory();\n        EntityManager em = emf.createEntityManager();\n        PersonnelDTO dto = new PersonnelDTO();\n        dto.setFirstName(\"Vivek\");\n        dto.setLastName(\"vivek\");\n        dto.setPersonId(\"1_p\");\n        em.persist(dto);\n        PersonnelDTO result = em.find(PersonnelDTO.class, \"1_p\");\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"Mishra\", result.getLastName());\n        emf.close();\n\n    }\n\n    /**\n     * Test invalid configure.\n     */\n    @Test\n    public void testInvalidConfigure()\n    {\n        final String invalidPuName = \"invalid\";\n        PersistenceUnitMetadata puMetadata = null;\n        try\n        {\n            EntityManagerFactoryImpl emf = getEntityManagerFactory();\n            puMetadata = emf.getKunderaMetadataInstance().getApplicationMetadata().getPersistenceUnitMetadata(invalidPuName);\n        }\n        catch (PersistenceUnitConfigurationException iex)\n        {\n            Assert.assertNull(puMetadata);\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory()\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(\"kunderatest\");\n    }\n    /* *//**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    /*\n     * private EntityManagerFactory getEntityManagerFactory() { return\n     * Persistence.createEntityManagerFactory(_persistenceUnit); }\n     */\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/CoreEntityAddressUni1To1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.configure;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class CoreEntityAddressUni1To1.\n */\n@Entity\n@Table(name = \"CoreEntityAddressUni1To1\", schema = \"KunderaCoreExmples@cassandra\")\npublic class CoreEntityAddressUni1To1\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/CoreEntityAddressUni1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.configure;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class CoreEntityAddressUni1ToM.\n */\n@Entity\n@Table(name = \"CoreEntityAddressUni1ToM\", schema = \"KunderaCoreExmples@cassandra\")\npublic class CoreEntityAddressUni1ToM\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/CoreEntityAddressUniMTo1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.configure;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class CoreEntityAddressUniMTo1.\n */\n@Entity\n@Table(name = \"CoreEntityAddressUniMTo1\", schema = \"KunderaCoreExmples@cassandra\")\npublic class CoreEntityAddressUniMTo1\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/CoreEntityPersionUniMto1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.configure;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class CoreEntityPersionUniMto1.\n */\n@Entity\n@Table(name = \"CoreEntityPersionUniMto1\", schema = \"KunderaCoreExmples@cassandra\")\npublic class CoreEntityPersionUniMto1\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The personal data. */\n    @Embedded\n    private PersonalData personalData;\n\n    /** The address. */\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private CoreEntityAddressUniMTo1 address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public PersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(PersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public CoreEntityAddressUniMTo1 getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the address to set\n     */\n    public void setAddress(CoreEntityAddressUniMTo1 address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/CoreEntityPersonUni1To1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.configure;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class CoreEntityPersonUni1To1.\n */\n@Entity\n@Table(name = \"CoreEntityPersonUni1To1\", schema = \"KunderaCoreExmples@cassandra\")\npublic class CoreEntityPersonUni1To1\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The personal data. */\n    @Embedded\n    private PersonalData personalData;\n\n    /** The address. */\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private CoreEntityAddressUni1To1 address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public PersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(PersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public CoreEntityAddressUni1To1 getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the address to set\n     */\n    public void setAddress(CoreEntityAddressUni1To1 address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/CoreEntityPersonUni1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.configure;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * The Class CoreEntityPersonUni1ToM.\n */\n@Entity\n@Table(name = \"CoreEntityPersonUni1ToM\", schema = \"KunderaCoreExmples@cassandra\")\npublic class CoreEntityPersonUni1ToM\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The personal data. */\n    @Embedded\n    private PersonalData personalData;\n\n    /** The addresses. */\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<CoreEntityAddressUni1ToM> addresses;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public PersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(PersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the addresses.\n     * \n     * @return the addresses\n     */\n    public Set<CoreEntityAddressUni1ToM> getAddresses()\n    {\n        return addresses;\n    }\n\n    /**\n     * Sets the addresses.\n     * \n     * @param addresses\n     *            the addresses to set\n     */\n    public void setAddresses(Set<CoreEntityAddressUni1ToM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/CoreEntitySimple.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.configure;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class CoreEntitySimple.\n */\n@Entity\n@Table(name = \"CoreEntitySimple\", schema = \"KunderaCoreExmples@cassandra\")\npublic class CoreEntitySimple\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/CoreEntitySuper.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.configure;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n\n\n/**\n * The Class CoreEntitySuper.\n */\n@Entity\n@Table(name = \"CoreEntitySuper\", schema = \"KunderaCoreExmples@cassandra\")\n@IndexCollection(columns = { @Index(name = \"personName\"),  @Index(name = \"age\")})\npublic class CoreEntitySuper\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The personal data. */\n    @Embedded\n    private PersonalData personalData;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public PersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(PersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/DummyPropertyReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure;\n\nimport java.util.Map;\n\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * Class Dummy Property Reader for test\n * \n * @author Kuldeep Mishra\n * \n */\npublic class DummyPropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n\n    public static DummySchemaMetadata dsmd;\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.AbstractPropertyReader#onXml(com.impetus\n     * .kundera.configure.ClientProperties)\n     */\n\n    public DummyPropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        dsmd = new DummySchemaMetadata();\n    }\n\n    @Override\n    public void onXml(ClientProperties cp)\n    {\n        if (cp != null)\n        {\n            dsmd.setClientProperties(cp);\n        }\n\n    }\n\n    /**\n     * Dummy schema metadata for test.\n     * \n     * @author Kuldeep Mishra\n     * \n     */\n    public class DummySchemaMetadata\n    {\n        /**\n         * client properties.\n         */\n        private ClientProperties clientProperties;\n\n        /**\n         * @return the clientProperties\n         */\n        public ClientProperties getClientProperties()\n        {\n            return clientProperties;\n        }\n\n        /**\n         * @param clientProperties\n         *            the clientProperties to set\n         */\n        private void setClientProperties(ClientProperties clientProperties)\n        {\n            this.clientProperties = clientProperties;\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/PersonalData.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.configure;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\nimport com.impetus.kundera.index.Index;\r\nimport com.impetus.kundera.index.IndexCollection;\r\n\r\n/**\r\n * The Class CorePersonalData.\r\n */\r\n@Embeddable\r\n@IndexCollection(columns = { @Index(name = \"email\"), @Index(name = \"yahooId\")})\r\npublic class PersonalData\r\n{\r\n\r\n    /** The website. */\r\n    @Column(name = \"department_website\")\r\n    private String website;\r\n\r\n    /** The email. */\r\n    @Column(name = \"department_email\")\r\n    private String email;\r\n\r\n    /** The yahoo id. */\r\n    @Column(name = \"department_yahoo_id\")\r\n    private String yahooId;\r\n\r\n    /**\r\n     * Instantiates a new core personal data.\r\n     */\r\n    public PersonalData()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new core personal data.\r\n     * \r\n     * @param website\r\n     *            the website\r\n     * @param email\r\n     *            the email\r\n     * @param yahooId\r\n     *            the yahoo id\r\n     */\r\n    public PersonalData(String website, String email, String yahooId)\r\n    {\r\n        this.website = website;\r\n        this.email = email;\r\n        this.yahooId = yahooId;\r\n    }\r\n\r\n    /**\r\n     * Gets the website.\r\n     * \r\n     * @return the website\r\n     */\r\n    public String getWebsite()\r\n    {\r\n        return website;\r\n    }\r\n\r\n    /**\r\n     * Sets the website.\r\n     * \r\n     * @param website\r\n     *            the new website\r\n     */\r\n    public void setWebsite(String website)\r\n    {\r\n        this.website = website;\r\n    }\r\n\r\n    /**\r\n     * Gets the email.\r\n     * \r\n     * @return the email\r\n     */\r\n    public String getEmail()\r\n    {\r\n        return email;\r\n    }\r\n\r\n    /**\r\n     * Sets the email.\r\n     * \r\n     * @param email\r\n     *            the email to set\r\n     */\r\n    public void setEmail(String email)\r\n    {\r\n        this.email = email;\r\n    }\r\n\r\n    /**\r\n     * Gets the yahoo id.\r\n     * \r\n     * @return the yahoo id\r\n     */\r\n    public String getYahooId()\r\n    {\r\n        return yahooId;\r\n    }\r\n\r\n    /**\r\n     * Sets the yahoo id.\r\n     * \r\n     * @param yahooId\r\n     *            the new yahoo id\r\n     */\r\n    public void setYahooId(String yahooId)\r\n    {\r\n        this.yahooId = yahooId;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/schema/ColumnInfoTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.configure.schema;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\n/**\n * @author vivek.mishra\n * junit for {@link ColumnInfo}\n *\n */\npublic class ColumnInfoTest\n{\n\n    @Test\n    public void testWithSingleValueConstructor()\n    {\n        ColumnInfo columnInfo = new ColumnInfo();\n        columnInfo.setColumnName(\"column1\");\n        columnInfo.setIndexable(true);\n        columnInfo.setType(Integer.class);\n        \n        Assert.assertEquals(\"column1\", columnInfo.getColumnName());\n        Assert.assertTrue(columnInfo.isIndexable());\n        Assert.assertEquals(Integer.class, columnInfo.getType());\n        \n        ColumnInfo col1 = new ColumnInfo();\n        col1.setColumnName(\"column1\");\n        \n        Assert.assertEquals(col1, columnInfo);  //column name comparison.\n        \n        Assert.assertNotNull(col1.toString());\n        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/schema/EmbeddedColumnInfoTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.configure.schema;\n\nimport java.util.ArrayList;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\n/**\n * @author vivek.mishra\n * junit for {@link EmbeddedColumnInfo}\n *\n */\npublic class EmbeddedColumnInfoTest\n{\n\n    @Test\n    public void testWithSingleValueConstructor()\n    {\n        EmbeddedColumnInfo embeddedColumnInfo = new EmbeddedColumnInfo(null);\n        \n        ColumnInfo col1 = new ColumnInfo();\n        col1.setColumnName(\"column1\");\n\n        ColumnInfo columnInfo = new ColumnInfo();\n        columnInfo.setColumnName(\"column1\");\n        columnInfo.setIndexable(true);\n        columnInfo.setType(Integer.class);\n        \n        java.util.List<ColumnInfo> columns = new ArrayList<ColumnInfo>();\n        columns.add(columnInfo);\n        columns.add(col1);\n        \n        embeddedColumnInfo.setColumns(columns);\n        embeddedColumnInfo.setEmbeddedColumnName(\"embeddedColumn\");\n        \n        Assert.assertEquals(\"embeddedColumn\", embeddedColumnInfo.getEmbeddedColumnName());\n        Assert.assertNull(embeddedColumnInfo.getEmbeddable());\n        Assert.assertEquals(2, embeddedColumnInfo.getColumns().size());\n        Assert.assertNotNull(embeddedColumnInfo.toString());\n        \n        EmbeddedColumnInfo embedded2 = new EmbeddedColumnInfo(null);\n        Assert.assertNotSame(embeddedColumnInfo, embedded2);\n        \n        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/schema/IndexInfoTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.configure.schema;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\n/**\n * @author vivek.mishra\n * junit for {@link IndexInfo}\n *\n */\npublic class IndexInfoTest\n{\n\n    @Test\n    public void testWithSingleValueConstructor()\n    {\n        IndexInfo indexInfo = new IndexInfo(\"personName\");\n        indexInfo.setIndexType(\"KEYS\");\n        indexInfo.setMaxValue(12);\n        indexInfo.setMinValue(1);\n        \n        Assert.assertEquals(1, indexInfo.getMinValue().intValue());\n        Assert.assertEquals(1, indexInfo.getMinValue().intValue());\n        Assert.assertEquals(\"KEYS\", indexInfo.getIndexType());\n        \n        Assert.assertEquals(\"personName\", indexInfo.getColumnName());\n        \n    }\n\n    @Test\n    public void testWithMultiValueConstructor()\n    {\n        IndexInfo indexInfo = new IndexInfo(\"personName\",12,1,\"KEYS\", \"personName\");\n        indexInfo.setIndexType(\"KEYS\");\n        indexInfo.setMaxValue(12);\n        indexInfo.setMinValue(1);\n        \n        Assert.assertEquals(12, indexInfo.getMaxValue().intValue());\n        Assert.assertEquals(1, indexInfo.getMinValue().intValue());\n        Assert.assertEquals(\"KEYS\", indexInfo.getIndexType());\n        \n        Assert.assertEquals(\"personName\", indexInfo.getColumnName());\n        \n    }\n\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/schema/TableInfoTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.configure.schema;\n\nimport java.util.ArrayList;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\n/**\n * @author vivek.mishra\n * junit for {@link TableInfo}\n *\n */\npublic class TableInfoTest\n{\n\n    @Test\n    public void testWithSingleValueConstructor()\n    {\n        EmbeddedColumnInfo embeddedColumnInfo = new EmbeddedColumnInfo(null);\n        \n        ColumnInfo col1 = new ColumnInfo();\n        col1.setColumnName(\"column1\");\n\n        ColumnInfo columnInfo = new ColumnInfo();\n        columnInfo.setColumnName(\"column1\");\n        columnInfo.setIndexable(true);\n        columnInfo.setType(Integer.class);\n        \n        java.util.List<ColumnInfo> columns = new ArrayList<ColumnInfo>();\n        columns.add(columnInfo);\n        columns.add(col1);\n        \n        embeddedColumnInfo.setColumns(columns);\n        embeddedColumnInfo.setEmbeddedColumnName(\"embeddedColumn\");\n        \n        Assert.assertEquals(\"embeddedColumn\", embeddedColumnInfo.getEmbeddedColumnName());\n        Assert.assertNull(embeddedColumnInfo.getEmbeddable());\n        Assert.assertEquals(2, embeddedColumnInfo.getColumns().size());\n        Assert.assertNotNull(embeddedColumnInfo.toString());\n        \n        EmbeddedColumnInfo embedded2 = new EmbeddedColumnInfo(null);\n        Assert.assertNotSame(embeddedColumnInfo, embedded2);\n        \n        IndexInfo indexInfo = new IndexInfo(\"personName\");\n        indexInfo.setIndexType(\"KEYS\");\n        indexInfo.setMaxValue(12);\n        indexInfo.setMinValue(1);\n\n        TableInfo tableInfo = new TableInfo(\"table1\", \"column family\", String.class, \"address_id\");\n        tableInfo.addColumnInfo(columnInfo);\n        tableInfo.addToIndexedColumnList(indexInfo);\n        Assert.assertNotNull(tableInfo.getColumnMetadatas());\n        \n        Assert.assertEquals(\"address_id\",tableInfo.getIdColumnName());\n        Assert.assertEquals(String.class,tableInfo.getTableIdType());\n        Assert.assertEquals(\"column family\", tableInfo.getType());\n        \n        Assert.assertNotNull(tableInfo.toString());\n        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/schema/api/CoreSchemaManager.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.configure.schema.api;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport com.impetus.kundera.configure.schema.TableInfo;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * @author vivek.mishra\n */\npublic class CoreSchemaManager extends AbstractSchemaManager implements SchemaManager\n{\n\n    private static List<TableInfo> tables;\n\n    private static String currentAction;\n\n    public CoreSchemaManager(String clientFactory, Map<String, Object> externalProperties, final KunderaMetadata kunderaMetadata)\n    {\n        super(clientFactory, externalProperties, kunderaMetadata);\n    }\n\n    public void exportSchema(final String persistenceUnit, List<TableInfo> schemas)\n    {\n        super.exportSchema(persistenceUnit, schemas);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#initiateClient\n     * ()\n     */\n    @Override\n    protected boolean initiateClient()\n    {\n        return true;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#validate\n     * (java.util.List)\n     */\n    @Override\n    protected void validate(List<TableInfo> tableInfos)\n    {\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#update\n     * (java.util.List)\n     */\n    @Override\n    protected void update(List<TableInfo> tableInfos)\n    {\n        this.tables = tableInfos;\n        currentAction = \"update\";\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#create\n     * (java.util.List)\n     */\n    @Override\n    protected void create(List<TableInfo> tableInfos)\n    {\n        this.tables = tableInfos;\n        currentAction = \"create\";\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#create_drop\n     * (java.util.List)\n     */\n    @Override\n    protected void create_drop(List<TableInfo> tableInfos)\n    {\n        this.tables = tableInfos;\n        currentAction = \"create-drop\";\n    }\n\n    @Override\n    public void dropSchema()\n    {\n        if (operation != null && operation.equalsIgnoreCase(\"create-drop\"))\n        {\n\n            this.tables = null;\n            currentAction = \"drop\";\n        }\n    }\n\n    @Override\n    public boolean validateEntity(Class clazz)\n    {\n        return true;\n    }\n\n    static boolean validateAction(String action)\n    {\n        if ((action.equals(\"create-drop\") || action.equals(\"update\") || action.equals(\"create\"))\n                && action.equals(currentAction))\n        {\n            return tables != null;\n        }\n        else\n        {\n            return action.equals(currentAction) && tables == null;\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/configure/schema/api/SchemaManagerTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.configure.schema.api;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\n\npublic class SchemaManagerTest\n{\n\n    private String persistenceUnit = \"metaDataTest\";\n\n    @Before\n    public void setUp()\n    {\n\n    }\n\n    @Test\n    public void testCreate()\n    {\n        Map<String, Object> props = new HashMap<String, Object>();\n        props.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"metaDataTest\", props);\n        Assert.assertTrue(CoreSchemaManager.validateAction(\"create\"));\n        emf.close();\n        Assert.assertTrue(CoreSchemaManager.validateAction(\"create\"));\n        Assert.assertFalse(CoreSchemaManager.validateAction(\"drop\"));\n    }\n\n    @Test\n    public void testCreateDrop()\n    {\n        Map<String, Object> props = new HashMap<String, Object>();\n        props.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create-drop\");\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"metaDataTest\", props);\n        Assert.assertTrue(CoreSchemaManager.validateAction(\"create-drop\"));\n        Assert.assertFalse(CoreSchemaManager.validateAction(\"create\"));\n\n        emf.close();\n        Assert.assertFalse(CoreSchemaManager.validateAction(\"create-drop\"));\n        Assert.assertTrue(CoreSchemaManager.validateAction(\"drop\"));\n    }\n\n    @Test\n    public void testUpdate()\n    {\n        Map<String, Object> props = new HashMap<String, Object>();\n        props.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"update\");\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"metaDataTest\", props);\n        Assert.assertFalse(CoreSchemaManager.validateAction(\"create-drop\"));\n        Assert.assertFalse(CoreSchemaManager.validateAction(\"create\"));\n        Assert.assertTrue(CoreSchemaManager.validateAction(\"update\"));\n        emf.close();\n        Assert.assertTrue(CoreSchemaManager.validateAction(\"update\"));\n        Assert.assertFalse(CoreSchemaManager.validateAction(\"drop\"));\n    }\n\n    @After\n    public void tearDown()\n    {\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/BigDecimalDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\nimport java.math.BigDecimal;\nimport java.math.MathContext;\n\npublic class BigDecimalDataGenerator implements DataGenerator<BigDecimal>\n{\n    @Override\n    public BigDecimal randomValue()\n    {\n        return new BigDecimal(1234);\n    }\n\n    @Override\n    public BigDecimal maxValue()\n    {\n        return new BigDecimal(23.45, new MathContext(4));\n    }\n\n    @Override\n    public BigDecimal minValue()\n    {\n        return new BigDecimal(0.01, new MathContext(1));\n    }\n\n    @Override\n    public BigDecimal partialValue()\n    {\n        return BigDecimal.ZERO;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/BigIntegerDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\nimport java.math.BigInteger;\n\npublic class BigIntegerDataGenerator implements DataGenerator<BigInteger>\n{\n\n    private static final BigInteger BIG_INTEGER = new BigInteger(\"1234567\");\n\n    @Override\n    public BigInteger randomValue()\n    {\n        return BIG_INTEGER;\n    }\n\n    @Override\n    public BigInteger maxValue()\n    {\n        return BigInteger.TEN;\n    }\n\n    @Override\n    public BigInteger minValue()\n    {\n        return BigInteger.ZERO;\n    }\n\n    @Override\n    public BigInteger partialValue()\n    {\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/BooleanDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\npublic class BooleanDataGenerator implements DataGenerator<Boolean>\n{\n\n    @Override\n    public Boolean randomValue()\n    {\n\n        return true;\n    }\n\n    @Override\n    public Boolean maxValue()\n    {\n\n        return true;\n    }\n\n    @Override\n    public Boolean minValue()\n    {\n\n        return false;\n    }\n\n    @Override\n    public Boolean partialValue()\n    {\n\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/ByteDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\npublic class ByteDataGenerator implements DataGenerator<Byte>\n{\n\n    private static final Byte BYTE = new Byte(\"12\");\n\n    @Override\n    public Byte randomValue()\n    {\n\n        return BYTE;\n    }\n\n    @Override\n    public Byte maxValue()\n    {\n\n        return Byte.MAX_VALUE;\n    }\n\n    @Override\n    public Byte minValue()\n    {\n\n        return Byte.MIN_VALUE;\n    }\n\n    @Override\n    public Byte partialValue()\n    {\n\n        return null;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/CalendarDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\nimport java.util.Calendar;\n\npublic class CalendarDataGenerator implements DataGenerator<Calendar>\n{\n    private static final Calendar INSTANCE = Calendar.getInstance();\n\n    @Override\n    public Calendar randomValue()\n    {\n        return INSTANCE;\n    }\n\n    @Override\n    public Calendar maxValue()\n    {\n        return INSTANCE;\n    }\n\n    @Override\n    public Calendar minValue()\n    {\n        return INSTANCE;\n    }\n\n    @Override\n    public Calendar partialValue()\n    {\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/CharDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\n\n\npublic class CharDataGenerator implements DataGenerator<Character> {\n\n\tprivate static final char CHAR = 'a';\n\n\t@Override\n\tpublic Character randomValue() {\n\n\t\treturn CHAR;\n\t}\n\n\t@Override\n\tpublic Character maxValue() {\n\n\t\treturn 'z';\n\t}\n\n\t@Override\n\tpublic Character minValue() {\n\n\t\treturn Character.MIN_VALUE;\n\t}\n\n\t@Override\n\tpublic Character partialValue() {\n\n\t\treturn null;\n\t}\n\n    public static void main(String[] d)\n    {\n        CharDataGenerator generator = new CharDataGenerator();\n        String query = \"Select s From StudentHBaseChar s where s.id between \" + generator.minValue() + \" and \"\n                + generator.maxValue();       \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/DataGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.datatypes.datagenerator;\n\npublic interface DataGenerator<T>\n{\n    T randomValue();\n\n    T maxValue();\n\n    T minValue();\n\n    T partialValue();\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/DataGeneratorFactory.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.datatypes.datagenerator;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.UUID;\n\n/**\n * The Class DataGeneratorFactory.\n * \n * @author kuldeep.kumar\n */\n\npublic class DataGeneratorFactory\n{\n    /** The map. */\n    private static Map<Class<?>, DataGenerator<?>> map = new HashMap<Class<?>, DataGenerator<?>>();\n\n    static\n    {\n        // Premitive Type generators\n        map.put(boolean.class, new BooleanDataGenerator());\n        map.put(byte.class, new ByteDataGenerator());\n        map.put(short.class, new ShortDataGenerator());\n        map.put(char.class, new CharDataGenerator());\n        map.put(int.class, new IntegerDataGenerator());\n        map.put(long.class, new LongDataGenerator());\n        map.put(float.class, new FloatDataGenerator());\n        map.put(double.class, new DoubleDataGenerator());\n\n        // Wrapper Object generators\n        map.put(Boolean.class, new BooleanDataGenerator());\n        map.put(Byte.class, new ByteDataGenerator());\n        map.put(Short.class, new ShortDataGenerator());\n        map.put(Character.class, new CharDataGenerator());\n        map.put(Integer.class, new IntegerDataGenerator());\n        map.put(Long.class, new LongDataGenerator());\n        map.put(Float.class, new FloatDataGenerator());\n        map.put(Double.class, new DoubleDataGenerator());\n\n        // Date/ Time type generators\n        map.put(Date.class, new DateDataGenerator());\n        map.put(java.sql.Date.class, new SqlDateDataGenerator());\n        map.put(Time.class, new SqlTimeDataGenerator());\n        map.put(Timestamp.class, new SqlTimestampDataGenerator());\n        map.put(Calendar.class, new CalendarDataGenerator());\n\n        // Generators for Math classes\n        map.put(BigInteger.class, new BigIntegerDataGenerator());\n        map.put(BigDecimal.class, new BigDecimalDataGenerator());\n\n        // String class generators\n        map.put(String.class, new StringDataGenerator());\n\n        map.put(UUID.class, new UUIDDataGenerator());\n    }\n\n    // /**\n    // * Instantiates a new data generator factory.\n    // */\n    // private DataGeneratorFactory()\n    // {\n    //\n    // }\n\n    public DataGenerator<?> getDataGenerator(Class<?> clazz)\n    {\n        return map.get(clazz);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/DateDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\nimport java.util.Date;\n\npublic class DateDataGenerator implements DataGenerator<Date>\n{\n\n    private static final LongDataGenerator LONG_DATA_GENERATOR = new LongDataGenerator();\n\n    private static final Date MIN_DATE = new Date(0L);\n\n    private static final Date MAX_DATE = new Date(Long.MAX_VALUE);\n\n    private static final Date DATE = new Date(LONG_DATA_GENERATOR.randomValue());\n\n    @Override\n    public Date randomValue()\n    {\n        return DATE;\n    }\n\n    @Override\n    public Date maxValue()\n    {\n        return MAX_DATE;\n    }\n\n    @Override\n    public Date minValue()\n    {\n        return MIN_DATE;\n    }\n\n    @Override\n    public Date partialValue()\n    {\n\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/DoubleDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\npublic class DoubleDataGenerator implements DataGenerator<Double>\n{\n\n    private static final Double DOUBLE = new Double(\"1235.151\");\n\n    @Override\n    public Double randomValue()\n    {\n\n        return DOUBLE;\n    }\n\n    @Override\n    public Double maxValue()\n    {\n\n        return Double.MAX_VALUE;\n    }\n\n    @Override\n    public Double minValue()\n    {\n\n        return Double.MIN_VALUE;\n    }\n\n    @Override\n    public Double partialValue()\n    {\n\n        return Double.NaN;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/FloatDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\npublic class FloatDataGenerator implements DataGenerator<Float>\n{\n\n    private static final Float FLOAT = new Float(\"121.11\");\n\n    @Override\n    public Float randomValue()\n    {\n\n        return FLOAT;\n    }\n\n    @Override\n    public Float maxValue()\n    {\n\n        return Float.MAX_VALUE;\n    }\n\n    @Override\n    public Float minValue()\n    {\n\n        return Float.MIN_VALUE;\n    }\n\n    @Override\n    public Float partialValue()\n    {\n\n        return Float.NaN;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/IntegerDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\npublic class IntegerDataGenerator implements DataGenerator<Integer>\n{\n\n    private static final Integer INTEGER = new Integer(\"1234\");\n\n    @Override\n    public Integer randomValue()\n    {\n        return INTEGER;\n    }\n\n    @Override\n    public Integer maxValue()\n    {\n        return Integer.MAX_VALUE;\n    }\n\n    @Override\n    public Integer minValue()\n    {\n        return Integer.MIN_VALUE;\n    }\n\n    @Override\n    public Integer partialValue()\n    {\n        return null;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/LongDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\npublic class LongDataGenerator implements DataGenerator<Long>\n{\n\n    private static final Long LONG = new Long(12345678);\n\n    @Override\n    public Long randomValue()\n    {\n        return LONG;\n    }\n\n    @Override\n    public Long maxValue()\n    {\n        return Long.MAX_VALUE;\n    }\n\n    @Override\n    public Long minValue()\n    {\n        return Long.MIN_VALUE;\n    }\n\n    @Override\n    public Long partialValue()\n    {\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/ShortDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\npublic class ShortDataGenerator implements DataGenerator<Short>\n{\n\n    private static final Short SHORT = new Short(\"3\");\n\n    @Override\n    public Short randomValue()\n    {\n        return SHORT;\n    }\n\n    @Override\n    public Short maxValue()\n    {\n        return Short.MAX_VALUE;\n    }\n\n    @Override\n    public Short minValue()\n    {\n        return Short.MIN_VALUE;\n    }\n\n    @Override\n    public Short partialValue()\n    {\n        return (short) 0;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/SqlDateDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\nimport java.sql.Date;\n\npublic class SqlDateDataGenerator implements DataGenerator<Date>\n{\n\n    private static final Long LONG = new Long(123456789);\n\n    @Override\n    public Date randomValue()\n    {\n\n        return new Date(LONG);\n    }\n\n    @Override\n    public Date maxValue()\n    {\n\n        return new Date(Long.MAX_VALUE);\n    }\n\n    @Override\n    public Date minValue()\n    {\n\n        return new Date(0L);\n    }\n\n    @Override\n    public Date partialValue()\n    {\n\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/SqlTimeDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\nimport java.sql.Time;\n\npublic class SqlTimeDataGenerator implements DataGenerator<Time>\n{\n\n    @Override\n    public Time partialValue()\n    {\n\n        return null;\n    }\n    \n    private static final Long LONG_DATA_GENERATOR = new LongDataGenerator().randomValue();\n\n    @Override\n    public Time randomValue()\n    {\n\n        return new Time(LONG_DATA_GENERATOR);\n    }\n\n    @Override\n    public Time maxValue()\n    {\n\n        return new Time(Integer.MAX_VALUE);\n    }\n\n    @Override\n    public Time minValue()\n    {\n\n        return new Time(0L);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/SqlTimestampDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\nimport java.sql.Timestamp;\n\npublic class SqlTimestampDataGenerator implements DataGenerator<Timestamp>\n{\n\n    private static final LongDataGenerator LONG_DATA_GENERATOR = new LongDataGenerator();\n\n    @Override\n    public Timestamp randomValue()\n    {\n\n        return new Timestamp(LONG_DATA_GENERATOR.randomValue());\n    }\n\n    @Override\n    public Timestamp maxValue()\n    {\n\n        return new Timestamp(Integer.MAX_VALUE);\n    }\n\n    @Override\n    public Timestamp minValue()\n    {\n\n        return new Timestamp(0L);\n    }\n\n    @Override\n    public Timestamp partialValue()\n    {\n\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/StringDataGenerator.java",
    "content": "/*\n * \n */\npackage com.impetus.kundera.datatypes.datagenerator;\n\npublic class StringDataGenerator implements DataGenerator<String>\n{\n\n    // private static final String AMRESH = new String(\"Amresh\");\n    // private static final String random = new String(\"Kuldeep\");\n\n    @Override\n    public String randomValue()\n    {\n        return new String(\"Amresh\");\n    }\n\n    @Override\n    public String maxValue()\n    {\n        return new String(\"Vivek\");\n    }\n\n    @Override\n    public String minValue()\n    {\n        return new String(\"Kuldeep\");\n    }\n\n    @Override\n    public String partialValue()\n    {\n        return null;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/datatypes/datagenerator/UUIDDataGenerator.java",
    "content": "package com.impetus.kundera.datatypes.datagenerator;\n\nimport java.util.UUID;\n\npublic class UUIDDataGenerator implements DataGenerator<UUID>\n{\n\n    private static final UUID RANDOM_UUID = UUID.randomUUID();\n\n    private static final UUID MAX_UUID = UUID.randomUUID();\n\n    private static final UUID MIN_UUID = UUID.randomUUID();\n\n    @Override\n    public UUID randomValue()\n    {\n\n        return RANDOM_UUID;\n    }\n\n    @Override\n    public UUID maxValue()\n    {\n\n        return MAX_UUID;\n    }\n\n    @Override\n    public UUID minValue()\n    {\n\n        return MIN_UUID;\n    }\n\n    @Override\n    public UUID partialValue()\n    {\n\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/PersonalDetail.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.entity;\r\n\r\nimport java.util.UUID;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\n/**\r\n * Entity class for user's personal details\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\npublic class PersonalDetail\r\n{\r\n    @Column(name = \"personal_detail_id\")\r\n    private String personalDetailId;\r\n\r\n    @Column(name = \"name\")\r\n    private String name;\r\n\r\n    @Column(name = \"password\")\r\n    private String password;\r\n\r\n    @Column(name = \"rel_status\")\r\n    private String relationshipStatus;\r\n\r\n    public PersonalDetail()\r\n    {\r\n\r\n    }\r\n\r\n    public PersonalDetail(String name, String password, String relationshipStatus)\r\n    {\r\n        setPersonalDetailId(UUID.randomUUID().toString());\r\n        setName(name);\r\n        setPassword(password);\r\n        setRelationshipStatus(relationshipStatus);\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetailId\r\n     */\r\n    public String getPersonalDetailId()\r\n    {\r\n        return personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetailId\r\n     *            the personalDetailId to set\r\n     */\r\n    public void setPersonalDetailId(String personalDetailId)\r\n    {\r\n        this.personalDetailId = personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @return the name\r\n     */\r\n    public String getName()\r\n    {\r\n        return name;\r\n    }\r\n\r\n    /**\r\n     * @param name\r\n     *            the name to set\r\n     */\r\n    public void setName(String name)\r\n    {\r\n        this.name = name;\r\n    }\r\n\r\n    /**\r\n     * @return the password\r\n     */\r\n    public String getPassword()\r\n    {\r\n        return password;\r\n    }\r\n\r\n    /**\r\n     * @param password\r\n     *            the password to set\r\n     */\r\n    public void setPassword(String password)\r\n    {\r\n        this.password = password;\r\n    }\r\n\r\n    /**\r\n     * @return the relationshipStatus\r\n     */\r\n    public String getRelationshipStatus()\r\n    {\r\n        return relationshipStatus;\r\n    }\r\n\r\n    /**\r\n     * @param relationshipStatus\r\n     *            the relationshipStatus to set\r\n     */\r\n    public void setRelationshipStatus(String relationshipStatus)\r\n    {\r\n        this.relationshipStatus = relationshipStatus;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/PersonnelDTO.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.entity;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * The Class PersonnelDTO.\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"person\", schema = \"KunderaTest@kunderatest\")\r\npublic class PersonnelDTO\r\n{\r\n\r\n    /** The person id. */\r\n    @Id\r\n    private String personId;\r\n\r\n    /** The first name. */\r\n    @Column(name = \"first_name\")\r\n    private String firstName;\r\n\r\n    /** The last name. */\r\n    @Column(name = \"last_name\")\r\n    private String lastName;\r\n\r\n    /**\r\n     * Instantiates a new personnel dto.\r\n     * \r\n     * @param personId\r\n     *            the person id\r\n     * @param firstName\r\n     *            the first name\r\n     * @param lastName\r\n     *            the last name\r\n     */\r\n    public PersonnelDTO(String personId, String firstName, String lastName)\r\n    {\r\n        this.personId = personId;\r\n        this.firstName = firstName;\r\n        this.lastName = lastName;\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new personnel dto.\r\n     */\r\n    public PersonnelDTO()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * Gets the person id.\r\n     * \r\n     * @return the personId\r\n     */\r\n    public String getPersonId()\r\n    {\r\n        return personId;\r\n    }\r\n\r\n    /**\r\n     * Sets the person id.\r\n     * \r\n     * @param personId\r\n     *            the personId to set\r\n     */\r\n    public void setPersonId(String personId)\r\n    {\r\n        this.personId = personId;\r\n    }\r\n\r\n    /**\r\n     * Gets the first name.\r\n     * \r\n     * @return the firstName\r\n     */\r\n    public String getFirstName()\r\n    {\r\n        return firstName;\r\n    }\r\n\r\n    /**\r\n     * Sets the first name.\r\n     * \r\n     * @param firstName\r\n     *            the firstName to set\r\n     */\r\n    public void setFirstName(String firstName)\r\n    {\r\n        this.firstName = firstName;\r\n    }\r\n\r\n    /**\r\n     * Gets the last name.\r\n     * \r\n     * @return the lastName\r\n     */\r\n    public String getLastName()\r\n    {\r\n        return lastName;\r\n    }\r\n\r\n    /**\r\n     * Sets the last name.\r\n     * \r\n     * @param lastName\r\n     *            the lastName to set\r\n     */\r\n    public void setLastName(String lastName)\r\n    {\r\n        this.lastName = lastName;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/Tweet.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.entity;\r\n\r\nimport java.util.UUID;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\n/**\r\n * Class for Tweets\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\npublic class Tweet\r\n{\r\n\r\n    @Column(name = \"tweet_id\")\r\n    private String tweetId;\r\n\r\n    @Column(name = \"tweet_body\")\r\n    private String body;\r\n\r\n    @Column(name = \"tweeted_from\")\r\n    private String device;\r\n\r\n    public Tweet(String body, String device)\r\n    {\r\n        this.tweetId = UUID.randomUUID().toString();\r\n        this.body = body;\r\n        this.device = device;\r\n    }\r\n\r\n    public Tweet()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * @return the tweetId\r\n     */\r\n    public String getTweetId()\r\n    {\r\n        return tweetId;\r\n    }\r\n\r\n    /**\r\n     * @param tweetId\r\n     *            the tweetId to set\r\n     */\r\n    public void setTweetId(String tweetId)\r\n    {\r\n        this.tweetId = tweetId;\r\n    }\r\n\r\n    /**\r\n     * @return the body\r\n     */\r\n    public String getBody()\r\n    {\r\n        return body;\r\n    }\r\n\r\n    /**\r\n     * @param body\r\n     *            the body to set\r\n     */\r\n    public void setBody(String body)\r\n    {\r\n        this.body = body;\r\n    }\r\n\r\n    /**\r\n     * @return the device\r\n     */\r\n    public String getDevice()\r\n    {\r\n        return device;\r\n    }\r\n\r\n    /**\r\n     * @param device\r\n     *            the device to set\r\n     */\r\n    public void setDevice(String device)\r\n    {\r\n        this.device = device;\r\n    }\r\n\r\n    /*    *//**\r\n     * @return the timestamp\r\n     */\r\n    /*\r\n     * public long getTimestamp() { return timestamp; }\r\n     *//**\r\n     * @param timestamp\r\n     *            the timestamp to set\r\n     */\r\n    /*\r\n     * public void setTimestamp(long timestamp) { this.timestamp = timestamp; }\r\n     */\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumBi_1_1_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.album;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoBi_1_1_1_1;\nimport com.impetus.kundera.entity.photographer.PhotographerBi_1_1_1_1;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumBi_1_1_1_1\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTO_ID\")\n    private PhotoBi_1_1_1_1 photo;\n\n    @OneToOne(mappedBy = \"album\")\n    private PhotographerBi_1_1_1_1 photographer;\n\n    public AlbumBi_1_1_1_1()\n    {\n\n    }\n\n    public AlbumBi_1_1_1_1(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    /**\n     * @return the albumId\n     */\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    /**\n     * @param albumId\n     *            the albumId to set\n     */\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photo\n     */\n    public PhotoBi_1_1_1_1 getPhoto()\n    {\n        return photo;\n    }\n\n    /**\n     * @param photo\n     *            the photo to set\n     */\n    public void setPhoto(PhotoBi_1_1_1_1 photo)\n    {\n        this.photo = photo;\n    }\n\n    /**\n     * @return the photographer\n     */\n    public PhotographerBi_1_1_1_1 getPhotographer()\n    {\n        return photographer;\n    }\n\n    /**\n     * @param photographer\n     *            the photographer to set\n     */\n    public void setPhotographer(PhotographerBi_1_1_1_1 photographer)\n    {\n        this.photographer = photographer;\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumBi_1_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoBi_1_1_1_M;\nimport com.impetus.kundera.entity.photographer.PhotographerBi_1_1_1_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumBi_1_1_1_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"album\")\n    private List<PhotoBi_1_1_1_M> photos;\n\n    @OneToOne(mappedBy = \"album\")\n    private PhotographerBi_1_1_1_M photographer;\n\n    public AlbumBi_1_1_1_M()\n    {\n\n    }\n\n    public AlbumBi_1_1_1_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoBi_1_1_1_M> getPhotos()\n    {\n        if (photos == null)\n        {\n            photos = new ArrayList<PhotoBi_1_1_1_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoBi_1_1_1_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoBi_1_1_1_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n    /**\n     * @return the photographer\n     */\n    public PhotographerBi_1_1_1_M getPhotographer()\n    {\n        return photographer;\n    }\n\n    /**\n     * @param photographer\n     *            the photographer to set\n     */\n    public void setPhotographer(PhotographerBi_1_1_1_M photographer)\n    {\n        this.photographer = photographer;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumBi_1_M_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoBi_1_M_1_M;\nimport com.impetus.kundera.entity.photographer.PhotographerBi_1_M_1_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumBi_1_M_1_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"album\")\n    private List<PhotoBi_1_M_1_M> photos;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTOGRAPHER_ID\")\n    private PhotographerBi_1_M_1_M photographer;\n\n    public AlbumBi_1_M_1_M()\n    {\n\n    }\n\n    public AlbumBi_1_M_1_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoBi_1_M_1_M> getPhotos()\n    {\n        if (photos == null)\n        {\n            photos = new ArrayList<PhotoBi_1_M_1_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoBi_1_M_1_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoBi_1_M_1_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n    /**\n     * @return the photographer\n     */\n    public PhotographerBi_1_M_1_M getPhotographer()\n    {\n        return photographer;\n    }\n\n    /**\n     * @param photographer\n     *            the photographer to set\n     */\n    public void setPhotographer(PhotographerBi_1_M_1_M photographer)\n    {\n        this.photographer = photographer;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumBi_1_M_M_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoBi_1_M_M_M;\nimport com.impetus.kundera.entity.photographer.PhotographerBi_1_M_M_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumBi_1_M_M_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"ALBUM_PHOTO\", joinColumns = { @JoinColumn(name = \"ALBUM_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"PHOTO_ID\") })\n    private List<PhotoBi_1_M_M_M> photos;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTOGRAPHER_ID\")\n    private PhotographerBi_1_M_M_M photographer;\n\n    public AlbumBi_1_M_M_M()\n    {\n\n    }\n\n    public AlbumBi_1_M_M_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoBi_1_M_M_M> getPhotos()\n    {\n        if (this.photos == null || this.photos.isEmpty())\n        {\n            this.photos = new ArrayList<PhotoBi_1_M_M_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoBi_1_M_M_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoBi_1_M_M_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n    /**\n     * @return the photographer\n     */\n    public PhotographerBi_1_M_M_M getPhotographer()\n    {\n        return photographer;\n    }\n\n    /**\n     * @param photographer\n     *            the photographer to set\n     */\n    public void setPhotographer(PhotographerBi_1_M_M_M photographer)\n    {\n        this.photographer = photographer;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumBi_M_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoBi_M_1_1_M;\nimport com.impetus.kundera.entity.photographer.PhotographerBi_M_1_1_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumBi_M_1_1_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"album\")\n    private List<PhotoBi_M_1_1_M> photos;\n\n    @OneToMany(mappedBy = \"album\", fetch = FetchType.LAZY)\n    private List<PhotographerBi_M_1_1_M> photographers;\n\n    public AlbumBi_M_1_1_M()\n    {\n\n    }\n\n    public AlbumBi_M_1_1_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoBi_M_1_1_M> getPhotos()\n    {\n        if (photos == null)\n        {\n            photos = new ArrayList<PhotoBi_M_1_1_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoBi_M_1_1_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoBi_M_1_1_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n    /**\n     * @return the photographers\n     */\n    public List<PhotographerBi_M_1_1_M> getPhotographers()\n    {\n        return photographers;\n    }\n\n    /**\n     * @param photographers\n     *            the photographers to set\n     */\n    public void setPhotographers(List<PhotographerBi_M_1_1_M> photographers)\n    {\n        this.photographers = photographers;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumBi_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.album;\n\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoBi_M_M_1_1;\nimport com.impetus.kundera.entity.photographer.PhotographerBi_M_M_1_1;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumBi_M_M_1_1\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTO_ID\")\n    private PhotoBi_M_M_1_1 photo;\n\n    @ManyToMany(mappedBy = \"albums\", fetch = FetchType.LAZY)\n    private List<PhotographerBi_M_M_1_1> photographers;\n\n    public AlbumBi_M_M_1_1()\n    {\n\n    }\n\n    public AlbumBi_M_M_1_1(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    /**\n     * @return the albumId\n     */\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    /**\n     * @param albumId\n     *            the albumId to set\n     */\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photo\n     */\n    public PhotoBi_M_M_1_1 getPhoto()\n    {\n        return photo;\n    }\n\n    /**\n     * @param photo\n     *            the photo to set\n     */\n    public void setPhoto(PhotoBi_M_M_1_1 photo)\n    {\n        this.photo = photo;\n    }\n\n    /**\n     * @return the photographers\n     */\n    public List<PhotographerBi_M_M_1_1> getPhotographers()\n    {\n        return photographers;\n    }\n\n    /**\n     * @param photographers\n     *            the photographers to set\n     */\n    public void setPhotographers(List<PhotographerBi_M_M_1_1> photographers)\n    {\n        this.photographers = photographers;\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumBi_M_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoBi_M_M_M_M;\nimport com.impetus.kundera.entity.photographer.PhotographerBi_M_M_M_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumBi_M_M_M_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    @ManyToMany\n    @JoinTable(name = \"ALBUM_PHOTO\", joinColumns = { @JoinColumn(name = \"ALBUM_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"PHOTO_ID\") })\n    private List<PhotoBi_M_M_M_M> photos;\n\n    @ManyToMany(mappedBy = \"albums\", fetch = FetchType.LAZY)\n    private List<PhotographerBi_M_M_M_M> photographers;\n\n    public AlbumBi_M_M_M_M()\n    {\n\n    }\n\n    public AlbumBi_M_M_M_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoBi_M_M_M_M> getPhotos()\n    {\n        if (this.photos == null || this.photos.isEmpty())\n        {\n            this.photos = new ArrayList<PhotoBi_M_M_M_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoBi_M_M_M_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoBi_M_M_M_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n    /**\n     * @return the photographers\n     */\n    public List<PhotographerBi_M_M_M_M> getPhotographers()\n    {\n        return photographers;\n    }\n\n    /**\n     * @param photographers\n     *            the photographers to set\n     */\n    public void setPhotographers(List<PhotographerBi_M_M_M_M> photographers)\n    {\n        this.photographers = photographers;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumUni_1_1_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.album;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoUni_1_1_1_1;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumUni_1_1_1_1\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTO_ID\")\n    private PhotoUni_1_1_1_1 photo;\n\n    public AlbumUni_1_1_1_1()\n    {\n\n    }\n\n    public AlbumUni_1_1_1_1(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    /**\n     * @return the albumId\n     */\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    /**\n     * @param albumId\n     *            the albumId to set\n     */\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photo\n     */\n    public PhotoUni_1_1_1_1 getPhoto()\n    {\n        return photo;\n    }\n\n    /**\n     * @param photo\n     *            the photo to set\n     */\n    public void setPhoto(PhotoUni_1_1_1_1 photo)\n    {\n        this.photo = photo;\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumUni_1_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoUni_1_1_1_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumUni_1_1_1_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private List<PhotoUni_1_1_1_M> photos;\n\n    public AlbumUni_1_1_1_M()\n    {\n\n    }\n\n    public AlbumUni_1_1_1_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoUni_1_1_1_M> getPhotos()\n    {\n        if (photos == null)\n        {\n            photos = new ArrayList<PhotoUni_1_1_1_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoUni_1_1_1_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoUni_1_1_1_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumUni_1_1_M_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.album;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoUni_1_1_M_1;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumUni_1_1_M_1\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTO_ID\")\n    private PhotoUni_1_1_M_1 photo;\n\n    public AlbumUni_1_1_M_1()\n    {\n\n    }\n\n    public AlbumUni_1_1_M_1(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    /**\n     * @return the albumId\n     */\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    /**\n     * @param albumId\n     *            the albumId to set\n     */\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photo\n     */\n    public PhotoUni_1_1_M_1 getPhoto()\n    {\n        return photo;\n    }\n\n    /**\n     * @param photo\n     *            the photo to set\n     */\n    public void setPhoto(PhotoUni_1_1_M_1 photo)\n    {\n        this.photo = photo;\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumUni_1_M_1_M.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.entity.album;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.Table;\r\n\r\nimport com.impetus.kundera.entity.photo.PhotoUni_1_M_1_M;\r\n\r\n/**\r\n * Entity Class for album\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\r\npublic class AlbumUni_1_M_1_M\r\n{\r\n    @Id\r\n    @Column(name = \"ALBUM_ID\")\r\n    private String albumId;\r\n\r\n    @Column(name = \"ALBUM_NAME\")\r\n    private String albumName;\r\n\r\n    @Column(name = \"ALBUM_DESC\")\r\n    private String albumDescription;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\r\n    @JoinColumn(name = \"ALBUM_ID\")\r\n    private List<PhotoUni_1_M_1_M> photos;\r\n\r\n    public AlbumUni_1_M_1_M()\r\n    {\r\n\r\n    }\r\n\r\n    public AlbumUni_1_M_1_M(String albumId, String name, String description)\r\n    {\r\n        this.albumId = albumId;\r\n        this.albumName = name;\r\n        this.albumDescription = description;\r\n    }\r\n\r\n    public String getAlbumId()\r\n    {\r\n        return albumId;\r\n    }\r\n\r\n    public void setAlbumId(String albumId)\r\n    {\r\n        this.albumId = albumId;\r\n    }\r\n\r\n    /**\r\n     * @return the albumName\r\n     */\r\n    public String getAlbumName()\r\n    {\r\n        return albumName;\r\n    }\r\n\r\n    /**\r\n     * @param albumName\r\n     *            the albumName to set\r\n     */\r\n    public void setAlbumName(String albumName)\r\n    {\r\n        this.albumName = albumName;\r\n    }\r\n\r\n    /**\r\n     * @return the albumDescription\r\n     */\r\n    public String getAlbumDescription()\r\n    {\r\n        return albumDescription;\r\n    }\r\n\r\n    /**\r\n     * @param albumDescription\r\n     *            the albumDescription to set\r\n     */\r\n    public void setAlbumDescription(String albumDescription)\r\n    {\r\n        this.albumDescription = albumDescription;\r\n    }\r\n\r\n    /**\r\n     * @return the photos\r\n     */\r\n    public List<PhotoUni_1_M_1_M> getPhotos()\r\n    {\r\n        if (photos == null)\r\n        {\r\n            photos = new ArrayList<PhotoUni_1_M_1_M>();\r\n        }\r\n        return photos;\r\n    }\r\n\r\n    /**\r\n     * @param photos\r\n     *            the photos to set\r\n     */\r\n    public void setPhotos(List<PhotoUni_1_M_1_M> photos)\r\n    {\r\n        this.photos = photos;\r\n    }\r\n\r\n    public void addPhoto(PhotoUni_1_M_1_M photo)\r\n    {\r\n        getPhotos().add(photo);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumUni_1_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoUni_1_M_M_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumUni_1_M_M_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    @ManyToMany\n    @JoinTable(name = \"ALBUM_PHOTO\", joinColumns = { @JoinColumn(name = \"ALBUM_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"PHOTO_ID\") })\n    private List<PhotoUni_1_M_M_M> photos;\n\n    public AlbumUni_1_M_M_M()\n    {\n\n    }\n\n    public AlbumUni_1_M_M_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoUni_1_M_M_M> getPhotos()\n    {\n        if (this.photos == null || this.photos.isEmpty())\n        {\n            this.photos = new ArrayList<PhotoUni_1_M_M_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoUni_1_M_M_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoUni_1_M_M_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumUni_M_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoUni_M_1_1_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumUni_M_1_1_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private List<PhotoUni_M_1_1_M> photos;\n\n    public AlbumUni_M_1_1_M()\n    {\n\n    }\n\n    public AlbumUni_M_1_1_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoUni_M_1_1_M> getPhotos()\n    {\n        if (photos == null)\n        {\n            photos = new ArrayList<PhotoUni_M_1_1_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoUni_M_1_1_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoUni_M_1_1_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumUni_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.album;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoUni_M_M_1_1;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumUni_M_M_1_1\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTO_ID\")\n    private PhotoUni_M_M_1_1 photo;\n\n    public AlbumUni_M_M_1_1()\n    {\n\n    }\n\n    public AlbumUni_M_M_1_1(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    /**\n     * @return the albumId\n     */\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    /**\n     * @param albumId\n     *            the albumId to set\n     */\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photo\n     */\n    public PhotoUni_M_M_1_1 getPhoto()\n    {\n        return photo;\n    }\n\n    /**\n     * @param photo\n     *            the photo to set\n     */\n    public void setPhoto(PhotoUni_M_M_1_1 photo)\n    {\n        this.photo = photo;\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/album/AlbumUni_M_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.photo.PhotoUni_M_M_M_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"KunderaTest@kunderatest\")\npublic class AlbumUni_M_M_M_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    @ManyToMany(cascade = CascadeType.ALL)\n    @JoinTable(name = \"ALBUM_PHOTO\", joinColumns = { @JoinColumn(name = \"ALBUM_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"PHOTO_ID\") })\n    private List<PhotoUni_M_M_M_M> photos;\n\n    public AlbumUni_M_M_M_M()\n    {\n\n    }\n\n    public AlbumUni_M_M_M_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoUni_M_M_M_M> getPhotos()\n    {\n        if (this.photos == null || this.photos.isEmpty())\n        {\n            this.photos = new ArrayList<PhotoUni_M_M_M_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoUni_M_M_M_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoUni_M_M_M_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoBi_1_1_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumBi_1_1_1_1;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoBi_1_1_1_1\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @OneToOne(mappedBy = \"photo\")\n    private AlbumBi_1_1_1_1 album;\n\n    public PhotoBi_1_1_1_1()\n    {\n\n    }\n\n    public PhotoBi_1_1_1_1(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_1_1_1_1 getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_1_1_1_1 album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoBi_1_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumBi_1_1_1_M;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoBi_1_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumBi_1_1_1_M album;\n\n    public PhotoBi_1_1_1_M()\n    {\n\n    }\n\n    public PhotoBi_1_1_1_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_1_1_1_M getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_1_1_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoBi_1_M_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumBi_1_M_1_M;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoBi_1_M_1_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumBi_1_M_1_M album;\n\n    public PhotoBi_1_M_1_M()\n    {\n\n    }\n\n    public PhotoBi_1_M_1_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_1_M_1_M getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_1_M_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoBi_1_M_M_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photo;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumBi_1_M_M_M;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoBi_1_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @ManyToMany(mappedBy = \"photos\", fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    private Set<AlbumBi_1_M_M_M> albums;\n\n    public PhotoBi_1_M_M_M()\n    {\n\n    }\n\n    public PhotoBi_1_M_M_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the albums\n     */\n    public Set<AlbumBi_1_M_M_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void setAlbums(Set<AlbumBi_1_M_M_M> albums)\n    {\n        this.albums = albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumBi_1_M_M_M album)\n    {\n        if (albums == null)\n        {\n            albums = new HashSet<AlbumBi_1_M_M_M>();\n        }\n        albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoBi_M_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumBi_M_1_1_M;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoBi_M_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumBi_M_1_1_M album;\n\n    public PhotoBi_M_1_1_M()\n    {\n\n    }\n\n    public PhotoBi_M_1_1_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_M_1_1_M getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_M_1_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoBi_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumBi_M_M_1_1;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoBi_M_M_1_1\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @OneToOne(mappedBy = \"photo\")\n    private AlbumBi_M_M_1_1 album;\n\n    public PhotoBi_M_M_1_1()\n    {\n\n    }\n\n    public PhotoBi_M_M_1_1(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_M_M_1_1 getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_M_M_1_1 album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoBi_M_M_M_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photo;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumBi_M_M_M_M;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoBi_M_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @ManyToMany(mappedBy = \"photos\", fetch = FetchType.LAZY)\n    private Set<AlbumBi_M_M_M_M> albums;\n\n    public PhotoBi_M_M_M_M()\n    {\n\n    }\n\n    public PhotoBi_M_M_M_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the albums\n     */\n    public Set<AlbumBi_M_M_M_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void setAlbums(Set<AlbumBi_M_M_M_M> albums)\n    {\n        this.albums = albums;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoUni_1_1_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoUni_1_1_1_1\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_1_1_1_1()\n    {\n\n    }\n\n    public PhotoUni_1_1_1_1(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoUni_1_1_1_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoUni_1_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_1_1_1_M()\n    {\n\n    }\n\n    public PhotoUni_1_1_1_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoUni_1_1_M_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoUni_1_1_M_1\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_1_1_M_1()\n    {\n\n    }\n\n    public PhotoUni_1_1_M_1(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoUni_1_M_1_M.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.entity.photo;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * Entity class for photo\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\r\npublic class PhotoUni_1_M_1_M\r\n{\r\n    @Id\r\n    @Column(name = \"PHOTO_ID\")\r\n    private String photoId;\r\n\r\n    @Column(name = \"PHOTO_CAPTION\")\r\n    private String photoCaption;\r\n\r\n    @Column(name = \"PHOTO_DESC\")\r\n    private String photoDescription;\r\n\r\n    public PhotoUni_1_M_1_M()\r\n    {\r\n\r\n    }\r\n\r\n    public PhotoUni_1_M_1_M(String photoId, String caption, String description)\r\n    {\r\n        this.photoId = photoId;\r\n        this.photoCaption = caption;\r\n        this.photoDescription = description;\r\n    }\r\n\r\n    /**\r\n     * @return the photoId\r\n     */\r\n    public String getPhotoId()\r\n    {\r\n        return photoId;\r\n    }\r\n\r\n    /**\r\n     * @param photoId\r\n     *            the photoId to set\r\n     */\r\n    public void setPhotoId(String photoId)\r\n    {\r\n        this.photoId = photoId;\r\n    }\r\n\r\n    /**\r\n     * @return the photoCaption\r\n     */\r\n    public String getPhotoCaption()\r\n    {\r\n        return photoCaption;\r\n    }\r\n\r\n    /**\r\n     * @param photoCaption\r\n     *            the photoCaption to set\r\n     */\r\n    public void setPhotoCaption(String photoCaption)\r\n    {\r\n        this.photoCaption = photoCaption;\r\n    }\r\n\r\n    /**\r\n     * @return the photoDescription\r\n     */\r\n    public String getPhotoDescription()\r\n    {\r\n        return photoDescription;\r\n    }\r\n\r\n    /**\r\n     * @param photoDescription\r\n     *            the photoDescription to set\r\n     */\r\n    public void setPhotoDescription(String photoDescription)\r\n    {\r\n        this.photoDescription = photoDescription;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoUni_1_M_M_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoUni_1_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_1_M_M_M()\n    {\n\n    }\n\n    public PhotoUni_1_M_M_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoUni_M_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoUni_M_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_M_1_1_M()\n    {\n\n    }\n\n    public PhotoUni_M_1_1_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoUni_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoUni_M_M_1_1\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_M_M_1_1()\n    {\n\n    }\n\n    public PhotoUni_M_M_1_1(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photo/PhotoUni_M_M_M_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"KunderaTest@kunderatest\")\npublic class PhotoUni_M_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_M_M_M_M()\n    {\n\n    }\n\n    public PhotoUni_M_M_M_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerBi_1_1_1_1.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumBi_1_1_1_1;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerBi_1_1_1_1\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumBi_1_1_1_1 album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_1_1_1_1 getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_1_1_1_1 album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerBi_1_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumBi_1_1_1_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerBi_1_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumBi_1_1_1_M album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_1_1_1_M getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_1_1_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerBi_1_M_1_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.CollectionTable;\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.PersonalDetail;\nimport com.impetus.kundera.entity.Tweet;\nimport com.impetus.kundera.entity.album.AlbumBi_1_M_1_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerBi_1_M_1_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // Embedded object, will persist co-located\n    @Embedded\n    private PersonalDetail personalDetail;\n\n    // Element collection, will persist co-located\n    @ElementCollection\n    @CollectionTable(name = \"tweeted\")\n    private List<Tweet> tweets;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"photographer\")\n    private List<AlbumBi_1_M_1_M> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumBi_1_M_1_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumBi_1_M_1_M album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumBi_1_M_1_M>();\n        }\n        this.albums.add(album);\n    }\n\n    /**\n     * @return the personalDetail\n     */\n    public PersonalDetail getPersonalDetail()\n    {\n        return personalDetail;\n    }\n\n    /**\n     * @param personalDetail\n     *            the personalDetail to set\n     */\n    public void setPersonalDetail(PersonalDetail personalDetail)\n    {\n        this.personalDetail = personalDetail;\n    }\n\n    /**\n     * @return the tweets\n     */\n    public List<Tweet> getTweets()\n    {\n        return tweets;\n    }\n\n    /**\n     * @param tweets\n     *            the tweets to set\n     */\n    public void setTweets(List<Tweet> tweets)\n    {\n        this.tweets = tweets;\n    }\n\n    /**\n     * @param tweets\n     *            the tweets to set\n     */\n    public void addTweet(Tweet tweet)\n    {\n        if (tweets == null)\n        {\n            tweets = new ArrayList<Tweet>();\n        }\n        tweets.add(tweet);\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void setAlbums(List<AlbumBi_1_M_1_M> albums)\n    {\n        this.albums = albums;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerBi_1_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumBi_1_M_M_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerBi_1_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"photographer\")\n    private List<AlbumBi_1_M_M_M> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumBi_1_M_M_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void setAlbums(List<AlbumBi_1_M_M_M> albums)\n    {\n        this.albums = albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumBi_1_M_M_M album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumBi_1_M_M_M>();\n        }\n        this.albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerBi_M_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumBi_M_1_1_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerBi_M_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumBi_M_1_1_M album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_M_1_1_M getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_M_1_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerBi_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumBi_M_M_1_1;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerBi_M_M_1_1\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    @ManyToMany\n    @JoinTable(name = \"PHOTOGRAPHER_ALBUM\", joinColumns = { @JoinColumn(name = \"PHOTOGRAPHER_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ALBUM_ID\") })\n    private List<AlbumBi_M_M_1_1> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumBi_M_M_1_1> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumBi_M_M_1_1 album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumBi_M_M_1_1>();\n        }\n        this.albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerBi_M_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumBi_M_M_M_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerBi_M_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    @ManyToMany\n    @JoinTable(name = \"PHOTOGRAPHER_ALBUM\", joinColumns = { @JoinColumn(name = \"PHOTOGRAPHER_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ALBUM_ID\") })\n    private List<AlbumBi_M_M_M_M> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumBi_M_M_M_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumBi_M_M_M_M album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumBi_M_M_M_M>();\n        }\n        this.albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerUni_1_1_1_1.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumUni_1_1_1_1;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerUni_1_1_1_1\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumUni_1_1_1_1 album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumUni_1_1_1_1 getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumUni_1_1_1_1 album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerUni_1_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumUni_1_1_1_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerUni_1_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumUni_1_1_1_M album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    public AlbumUni_1_1_1_M getAlbum()\n    {\n        return album;\n    }\n\n    public void setAlbum(AlbumUni_1_1_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerUni_1_1_M_1.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumUni_1_1_M_1;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerUni_1_1_M_1\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumUni_1_1_M_1 album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumUni_1_1_M_1 getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumUni_1_1_M_1 album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerUni_1_M_1_M.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.entity.photographer;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.CollectionTable;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.ElementCollection;\r\nimport javax.persistence.Embedded;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.Table;\r\n\r\nimport com.impetus.kundera.entity.PersonalDetail;\r\nimport com.impetus.kundera.entity.Tweet;\r\nimport com.impetus.kundera.entity.album.AlbumUni_1_M_1_M;\r\n\r\n/**\r\n * Entity class representing a photographer\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\r\npublic class PhotographerUni_1_M_1_M\r\n{\r\n    @Id\r\n    @Column(name = \"PHOTOGRAPHER_ID\")\r\n    private int photographerId;\r\n\r\n    @Column(name = \"PHOTOGRAPHER_NAME\")\r\n    private String photographerName;\r\n\r\n    // Embedded object, will persist co-located\r\n    @Embedded\r\n    private PersonalDetail personalDetail;\r\n\r\n    // Element collection, will persist co-located\r\n    @ElementCollection\r\n    @CollectionTable(name = \"tweeted\")\r\n    private List<Tweet> tweets;    \r\n    \r\n    @ElementCollection\r\n    @Column(name=\"tags\")\r\n    private Set<String> tags;  \r\n    \r\n    @ElementCollection\r\n    @Column(name=\"liked_by\")\r\n    private List<Integer> likedBy;   \r\n    \r\n    @ElementCollection\r\n    @Column(name=\"comments\")\r\n    private Map<Integer, String> comments; \r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\r\n    @JoinColumn(name = \"PHOTOGRAPHER_ID\")\r\n    private List<AlbumUni_1_M_1_M> albums;\r\n\r\n    /**\r\n     * @return the photographerId\r\n     */\r\n    public int getPhotographerId()\r\n    {\r\n        return photographerId;\r\n    }\r\n\r\n    /**\r\n     * @param photographerId\r\n     *            the photographerId to set\r\n     */\r\n    public void setPhotographerId(int photographerId)\r\n    {\r\n        this.photographerId = photographerId;\r\n    }\r\n\r\n    /**\r\n     * @return the photographerName\r\n     */\r\n    public String getPhotographerName()\r\n    {\r\n        return photographerName;\r\n    }\r\n\r\n    /**\r\n     * @param photographerName\r\n     *            the photographerName to set\r\n     */\r\n    public void setPhotographerName(String photographerName)\r\n    {\r\n        this.photographerName = photographerName;\r\n    }\r\n\r\n    /**\r\n     * @return the albums\r\n     */\r\n    public List<AlbumUni_1_M_1_M> getAlbums()\r\n    {\r\n        return albums;\r\n    }\r\n\r\n    /**\r\n     * @param albums\r\n     *            the albums to set\r\n     */\r\n    public void addAlbum(AlbumUni_1_M_1_M album)\r\n    {\r\n        if (this.albums == null || this.albums.isEmpty())\r\n        {\r\n            this.albums = new ArrayList<AlbumUni_1_M_1_M>();\r\n        }\r\n        this.albums.add(album);\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetail\r\n     */\r\n    public PersonalDetail getPersonalDetail()\r\n    {\r\n        return personalDetail;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetail\r\n     *            the personalDetail to set\r\n     */\r\n    public void setPersonalDetail(PersonalDetail personalDetail)\r\n    {\r\n        this.personalDetail = personalDetail;\r\n    }\r\n\r\n    /**\r\n     * @return the tweets\r\n     */\r\n    public List<Tweet> getTweets()\r\n    {\r\n        return tweets;\r\n    }\r\n\r\n    /**\r\n     * @param tweets\r\n     *            the tweets to set\r\n     */\r\n    public void addTweet(Tweet tweet)\r\n    {\r\n        if (tweets == null)\r\n        {\r\n            tweets = new ArrayList<Tweet>();\r\n        }\r\n        tweets.add(tweet);\r\n    }\r\n\r\n    /**\r\n     * @param tweets\r\n     *            the tweets to set\r\n     */\r\n    public void setTweets(List<Tweet> tweets)\r\n    {\r\n        this.tweets = tweets;\r\n    }\r\n\r\n    /**\r\n     * @param albums\r\n     *            the albums to set\r\n     */\r\n    public void setAlbums(List<AlbumUni_1_M_1_M> albums)\r\n    {\r\n        this.albums = albums;\r\n    }\r\n    \r\n    /**\r\n     * @return the tags\r\n     */\r\n    public Set<String> getTags()\r\n    {\r\n        return tags;\r\n    }\r\n\r\n    /**\r\n     * @param tags the tags to set\r\n     */\r\n    public void setTags(Set<String> tags)\r\n    {\r\n        this.tags = tags;\r\n    }\r\n\r\n    /**\r\n     * @return the likedBy\r\n     */\r\n    public List<Integer> getLikedBy()\r\n    {\r\n        return likedBy;\r\n    }\r\n\r\n    /**\r\n     * @param likedBy the likedBy to set\r\n     */\r\n    public void setLikedBy(List<Integer> likedBy)\r\n    {\r\n        this.likedBy = likedBy;\r\n    }\r\n\r\n    /**\r\n     * @return the comments\r\n     */\r\n    public Map<Integer, String> getComments()\r\n    {\r\n        return comments;\r\n    }\r\n\r\n    /**\r\n     * @param comments the comments to set\r\n     */\r\n    public void setComments(Map<Integer, String> comments)\r\n    {\r\n        this.comments = comments;\r\n    }\r\n    \r\n    public void addTag(String tag)\r\n    {\r\n        if(tags == null)\r\n        {\r\n            tags = new HashSet<String>();\r\n        }\r\n        tags.add(tag);\r\n    }\r\n    \r\n    public void addLikedBy(int likedByUserId)\r\n    {\r\n        if(likedBy == null)\r\n        {\r\n            likedBy = new ArrayList<Integer>();\r\n        }\r\n        likedBy.add(likedByUserId);\r\n    }\r\n    \r\n    public void addComment(int userId, String comment)\r\n    {\r\n        if(comments == null)\r\n        {\r\n            comments = new HashMap<Integer, String>();\r\n        }\r\n        comments.put(userId, comment);\r\n    }\r\n }\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerUni_1_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumUni_1_M_M_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerUni_1_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTOGRAPHER_ID\")\n    private List<AlbumUni_1_M_M_M> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumUni_1_M_M_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void setAlbums(List<AlbumUni_1_M_M_M> albums)\n    {\n        this.albums = albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumUni_1_M_M_M album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumUni_1_M_M_M>();\n        }\n        this.albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerUni_M_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.entity.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumUni_M_1_1_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerUni_M_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumUni_M_1_1_M album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumUni_M_1_1_M getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumUni_M_1_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerUni_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumUni_M_M_1_1;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerUni_M_M_1_1\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    @ManyToMany\n    @JoinTable(name = \"PHOTOGRAPHER_ALBUM\", joinColumns = { @JoinColumn(name = \"PHOTOGRAPHER_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ALBUM_ID\") })\n    private List<AlbumUni_M_M_1_1> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumUni_M_M_1_1> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumUni_M_M_1_1 album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumUni_M_M_1_1>();\n        }\n        this.albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/entity/photographer/PhotographerUni_M_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.entity.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.entity.album.AlbumUni_M_M_M_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"KunderaTest@kunderatest\")\npublic class PhotographerUni_M_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    @ManyToMany(cascade = CascadeType.ALL)\n    @JoinTable(name = \"PHOTOGRAPHER_ALBUM\", joinColumns = { @JoinColumn(name = \"PHOTOGRAPHER_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ALBUM_ID\") })\n    private List<AlbumUni_M_M_M_M> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumUni_M_M_M_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumUni_M_M_M_M album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumUni_M_M_M_M>();\n        }\n        this.albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/gis/geometry/CircleTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.gis.geometry;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.gis.SurfaceType;\n\n/**\n * @author vivek.mishra\n * \n * junit for {@link Circle}\n *\n */\npublic class CircleTest\n{\n\n    @Test\n    public void test()\n    {\n        Coordinate coordiates2d = new Coordinate(34.2d,34.4d);\n        Circle twoDCircle = new Circle(coordiates2d, 5d);\n        twoDCircle.setSurfaceType(SurfaceType.SPHERICAL);\n        Assert.assertNotNull(twoDCircle);\n        Assert.assertEquals(coordiates2d, twoDCircle.getCentre());\n        Assert.assertEquals(5d, twoDCircle.getRadius());\n        Assert.assertEquals(SurfaceType.SPHERICAL, twoDCircle.getSurfaceType());\n\n        Coordinate coordiates3d = new Coordinate(34.2d,34.4d,12.3d);\n        Circle threeDCircle = new Circle(coordiates3d, 5);\n        threeDCircle.setSurfaceType(SurfaceType.SPHERICAL);\n        Assert.assertNotNull(threeDCircle);\n        Assert.assertEquals(coordiates3d, threeDCircle.getCentre());\n        Assert.assertEquals(34.2d,threeDCircle.getCentre().x);\n        Assert.assertEquals(34.4d,threeDCircle.getCentre().y);\n        Assert.assertEquals(12.3d,threeDCircle.getCentre().z);\n        Assert.assertTrue(threeDCircle.getCentre().equals3D(coordiates3d));\n        Assert.assertTrue(threeDCircle.getCentre().equals2D(coordiates2d));\n        Assert.assertEquals(0d,threeDCircle.getCentre().distance(coordiates2d));\n        Assert.assertEquals(5d, threeDCircle.getRadius());\n        Assert.assertEquals(SurfaceType.SPHERICAL, threeDCircle.getSurfaceType());\n\n        Circle circle = new Circle(23d,34d,12d);\n        circle.setCentre(coordiates2d);\n        circle.setRadius(3d);\n        Assert.assertNotNull(circle);\n        Assert.assertEquals(coordiates2d, circle.getCentre());\n        Assert.assertEquals(3d, circle.getRadius());\n        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/gis/geometry/EnvelopeTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.gis.geometry;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\n/**\n * @author vivek.mishra\n * junit for {@link Envelope}.\n */\npublic class EnvelopeTest\n{\n\n    @Test\n    public void test()\n    {\n        Coordinate coordiates2d = new Coordinate(34.2d,34.4d);\n\n        Coordinate coordiates3d = new Coordinate(34.2d,34.4d,12.3d);\n\n        Envelope envelope = new Envelope(coordiates2d,coordiates3d);\n        Assert.assertTrue(envelope.contains(coordiates3d));\n        Assert.assertTrue(envelope.covers(coordiates3d));\n\n        envelope = new Envelope(34.2d,34.4d,12.3d,32d);\n        Assert.assertFalse(envelope.contains(coordiates3d));\n        Assert.assertFalse(envelope.covers(coordiates3d));\n        Assert.assertNotNull(envelope.centre());\n        \n        envelope = new Envelope();\n        Assert.assertEquals(0d,envelope.getArea());\n        envelope = new Envelope(coordiates3d);\n        Assert.assertNotNull(envelope.getArea());\n        com.vividsolutions.jts.geom.Envelope rawEnvelope = new com.vividsolutions.jts.geom.Envelope();\n        envelope = new Envelope(rawEnvelope);\n        Assert.assertNull(envelope.centre());\n\n        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/gis/geometry/PointTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.gis.geometry;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.gis.SurfaceType;\nimport com.vividsolutions.jts.geom.Geometry;\nimport com.vividsolutions.jts.geom.GeometryFactory;\nimport com.vividsolutions.jts.geom.PrecisionModel;\n\n/**\n * @author vivek.mishra\n * junit for {@link Point}\n *\n */\npublic class PointTest\n{\n\n    @Test\n    public void test()\n    {\n        Coordinate coordiates2d = new Coordinate(34.2d,34.4d);\n        Coordinate[] coordinates = new Coordinate[1];\n        coordinates[0]=coordiates2d;\n        \n        com.vividsolutions.jts.geom.impl.PackedCoordinateSequence.Float floatSequence = new com.vividsolutions.jts.geom.impl.PackedCoordinateSequence.Float(coordinates, 2);\n\n        GeometryFactory geoFactory = new GeometryFactory(new PrecisionModel(2));\n        Point point = new Point(floatSequence,geoFactory);\n        \n        point.setSRID(2);\n        point.setSurfaceType(SurfaceType.FLAT);\n        \n        Geometry geometry = new com.vividsolutions.jts.geom.Point(floatSequence,geoFactory);\n        Assert.assertTrue(point.contains(geometry));\n        Assert.assertTrue(point.getSurfaceType() != null);\n        Assert.assertEquals(SurfaceType.FLAT,point.getSurfaceType());\n        Assert.assertEquals(2,point.getSRID());\n\n        point = new Point(coordiates2d,new PrecisionModel(2),12);\n        Assert.assertNotNull(point);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/gis/geometry/PolygonTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.gis.geometry;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.vividsolutions.jts.geom.GeometryFactory;\nimport com.vividsolutions.jts.geom.LinearRing;\nimport com.vividsolutions.jts.geom.PrecisionModel;\n\n/**\n * @author vivek.mishra junit for {@link Polygon}\n * \n */\npublic class PolygonTest\n{\n\n    // @Test\n    public void test()\n    {\n        Coordinate coordiates2d = new Coordinate(34.2d, 34.4d);\n        Coordinate coordiates2d1 = new Coordinate(34.2d, 34.4d);\n\n        Coordinate[] coordinates = new Coordinate[2];\n        coordinates[0] = coordiates2d;\n        coordinates[1] = coordiates2d1;\n\n        com.vividsolutions.jts.geom.impl.PackedCoordinateSequence.Float floatSequence = new com.vividsolutions.jts.geom.impl.PackedCoordinateSequence.Float(\n                coordinates, 1);\n        GeometryFactory geoFactory = new GeometryFactory(new PrecisionModel(2));\n\n        com.vividsolutions.jts.geom.impl.PackedCoordinateSequence.Double doubleSequence = new com.vividsolutions.jts.geom.impl.PackedCoordinateSequence.Double(\n                coordinates, 1);\n\n        LinearRing shell = new LinearRing(floatSequence, geoFactory);\n\n        LinearRing[] holes = new LinearRing[1];\n\n        holes[0] = new LinearRing(doubleSequence, geoFactory);\n\n        Polygon polygon = new Polygon(shell, holes, geoFactory);\n\n        Assert.assertNotNull(polygon.getCoordinates());\n    }\n\n    @Test\n    public void dummyTest()\n    {\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/gis/geometry/TriangleTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.gis.geometry;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\n/**\n * @author vivek.mishra\n * \n * junit for {@link Triangle}.\n *\n */\npublic class TriangleTest\n{\n\n    @Test\n    public void test()\n    {\n        Coordinate p0 = new Coordinate(34.2d,34.4d);\n        Coordinate p1 = new Coordinate(31.2d,32.4d);\n        Coordinate p2 = new Coordinate(36.2d,35.4d);\n        Triangle triangle = new Triangle(p0, p1, p2);\n        \n        Assert.assertNotNull(triangle.inCentre());\n        Assert.assertNotNull(triangle.centroid(p0, p1, p2));\n        \n        triangle = new Triangle(2d, 4d, 15d, 23d, 23d, 32d);\n        Assert.assertNotNull(triangle);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/graph/BillingCounter.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.graph;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Dummy BillingCounter enity class\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"BILLING_COUNTER\", schema = \"KunderaTest@kunderatest\")\npublic class BillingCounter\n{\n    @Id\n    @Column(name = \"COUNTER_ID\")\n    private int counterId;\n\n    @Column(name = \"COUNTER_CODE\")\n    private String counterCode;\n\n    public BillingCounter()\n    {\n\n    }\n\n    public BillingCounter(int id, String code)\n    {\n        this.counterId = id;\n        this.counterCode = code;\n    }\n\n    /**\n     * @return the counterId\n     */\n    public int getCounterId()\n    {\n        return counterId;\n    }\n\n    /**\n     * @param counterId\n     *            the counterId to set\n     */\n    public void setCounterId(int counterId)\n    {\n        this.counterId = counterId;\n    }\n\n    /**\n     * @return the counterCode\n     */\n    public String getCounterCode()\n    {\n        return counterCode;\n    }\n\n    /**\n     * @param counterCode\n     *            the counterCode to set\n     */\n    public void setCounterCode(String counterCode)\n    {\n        this.counterCode = counterCode;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/graph/ObjectGraphTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.graph;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.graph.NodeLink.LinkProperty;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\n\n/**\n * Test case for {@link ObjectGraph}\n * \n * @author amresh.singh\n */\npublic class ObjectGraphTest\n{\n    ObjectGraph objectGraph;\n\n    PersistenceCache pc;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        objectGraph = new ObjectGraph();\n        pc = new PersistenceCache();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    /**\n     * Tests one parent and three child nodes\n     */\n    @Test\n    public void testOneParentAndThreeChildNodes()\n    {\n        Store store = new Store();\n        BillingCounter b1 = new BillingCounter();\n        BillingCounter b2 = new BillingCounter();\n        BillingCounter b3 = new BillingCounter();\n\n        String storeId = ObjectGraphUtils.getNodeId(\"1\", store.getClass());\n        String b1Id = ObjectGraphUtils.getNodeId(\"A1\", b1.getClass());\n        String b2Id = ObjectGraphUtils.getNodeId(\"A2\", b2.getClass());\n        String b3Id = ObjectGraphUtils.getNodeId(\"A3\", b3.getClass());\n\n        Node headNode = new Node(storeId, store, null, pc, \"1\", null);\n\n        Node child1 = new Node(b1Id, b1, null, pc, \"A1\", null);\n        Node child2 = new Node(b2Id, b2, null, pc, \"A2\", null);\n        Node child3 = new Node(b3Id, b3, null, pc, \"A3\", null);\n\n        NodeLink linkB1 = new NodeLink(storeId, b1Id);\n        NodeLink linkB2 = new NodeLink(storeId, b2Id);\n        NodeLink linkB3 = new NodeLink(storeId, b3Id);\n\n        linkB1.addLinkProperty(LinkProperty.LINK_NAME, \"STORE_ID\");\n        linkB2.addLinkProperty(LinkProperty.LINK_NAME, \"STORE_ID\");\n        linkB3.addLinkProperty(LinkProperty.LINK_NAME, \"STORE_ID\");\n\n        headNode.addChildNode(linkB1, child1);\n        headNode.addChildNode(linkB2, child2);\n        headNode.addChildNode(linkB3, child3);\n\n        child1.addParentNode(linkB1, headNode);\n        child2.addParentNode(linkB2, headNode);\n        child3.addParentNode(linkB3, headNode);\n\n        assertEquals(storeId, headNode.getNodeId());\n        assertNull(headNode.getParents());\n        assertEquals(3, headNode.getChildren().size());\n\n        assertEquals(b1Id, child1.getNodeId());\n        assertNull(child1.getChildren());\n        assertNotNull(child1.getParents());\n        assertEquals(1, child1.getParents().size());\n\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/graph/ObjectGraphUtilsTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.graph;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.entity.PersonnelDTO;\n\n/**\n * @author amresh.singh\n * \n */\npublic class ObjectGraphUtilsTest\n{\n    ObjectGraphUtils utils = new ObjectGraphUtils();\n\n    String nodeId;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.graph.ObjectGraphUtils#getNodeId(java.lang.Object, java.lang.Class)}\n     * .\n     */\n    @Test\n    public void testGetNodeId()\n    {\n        nodeId = utils.getNodeId(\"1\", PersonnelDTO.class);\n        Assert.assertEquals(\"com.impetus.kundera.entity.PersonnelDTO$1\", nodeId);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.graph.ObjectGraphUtils#getEntityId(java.lang.String)}\n     * .\n     */\n    @Test\n    public void testGetEntityId()\n    {\n        nodeId = utils.getNodeId(\"1\", PersonnelDTO.class);\n        Object entityId = utils.getEntityId(\"com.impetus.kundera.entity.PersonnelDTO$1\");\n        Assert.assertEquals(\"1\", entityId.toString());\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/graph/Store.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.graph;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * Dummy Store entity class\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"STORE\", schema = \"KunderaTest@kunderatest\")\npublic class Store\n{\n    @Id\n    @Column(name = \"STORE_ID\")\n    private int storeId;\n\n    @Column(name = \"STORE_NAME\")\n    private String storeName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"STORE_ID\")\n    private List<BillingCounter> counters;\n\n    public Store()\n    {\n\n    }\n\n    public Store(int id, String name)\n    {\n        this.storeId = id;\n        this.storeName = name;\n    }\n\n    /**\n     * @return the storeId\n     */\n    public int getStoreId()\n    {\n        return storeId;\n    }\n\n    /**\n     * @param storeId\n     *            the storeId to set\n     */\n    public void setStoreId(int storeId)\n    {\n        this.storeId = storeId;\n    }\n\n    /**\n     * @return the storeName\n     */\n    public String getStoreName()\n    {\n        return storeName;\n    }\n\n    /**\n     * @param storeName\n     *            the storeName to set\n     */\n    public void setStoreName(String storeName)\n    {\n        this.storeName = storeName;\n    }\n\n    /**\n     * @return the counters\n     */\n    public List<BillingCounter> getCounters()\n    {\n        return counters;\n    }\n\n    /**\n     * @param counters\n     *            the counters to set\n     */\n    public void addCounter(BillingCounter counter)\n    {\n        if (counters == null)\n        {\n            counters = new ArrayList<BillingCounter>();\n        }\n        counters.add(counter);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/graph/StoreBuilder.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.graph;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\n\nimport com.impetus.kundera.graph.NodeLink.LinkProperty;\nimport com.impetus.kundera.lifecycle.states.NodeState;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\n\n/**\n * @author amresh.singh\n */\npublic class StoreBuilder\n{\n\n    public static Node buildStoreNode(PersistenceCache pc, NodeState initialState, CascadeType cascadeType)\n    {\n\n        Store store = new Store();\n        BillingCounter b1 = new BillingCounter();\n        BillingCounter b2 = new BillingCounter();\n        BillingCounter b3 = new BillingCounter();\n\n        String storeId = ObjectGraphUtils.getNodeId(\"1\", store.getClass());\n        String b1Id = ObjectGraphUtils.getNodeId(\"A1\", b1.getClass());\n        String b2Id = ObjectGraphUtils.getNodeId(\"A2\", b2.getClass());\n        String b3Id = ObjectGraphUtils.getNodeId(\"A3\", b3.getClass());\n\n        Node headNode = new Node(storeId, store, initialState, pc, \"1\", null);\n\n        Node child1 = new Node(b1Id, b1, initialState, pc, \"A1\", null);\n        Node child2 = new Node(b2Id, b2, initialState, pc, \"A2\", null);\n        Node child3 = new Node(b3Id, b3, initialState, pc, \"A3\", null);\n\n        NodeLink linkB1 = new NodeLink(storeId, b1Id);\n        NodeLink linkB2 = new NodeLink(storeId, b2Id);\n        NodeLink linkB3 = new NodeLink(storeId, b3Id);\n\n        List<CascadeType> cascadeTypes = new ArrayList<CascadeType>();\n        cascadeTypes.add(cascadeType);\n\n        linkB1.addLinkProperty(LinkProperty.LINK_NAME, \"STORE_ID\");\n        linkB1.addLinkProperty(LinkProperty.CASCADE, cascadeTypes);\n        linkB2.addLinkProperty(LinkProperty.LINK_NAME, \"STORE_ID\");\n        linkB2.addLinkProperty(LinkProperty.CASCADE, cascadeTypes);\n        linkB3.addLinkProperty(LinkProperty.LINK_NAME, \"STORE_ID\");\n        linkB3.addLinkProperty(LinkProperty.CASCADE, cascadeTypes);\n\n        headNode.addChildNode(linkB1, child1);\n        headNode.addChildNode(linkB2, child2);\n        headNode.addChildNode(linkB3, child3);\n\n        child1.addParentNode(linkB1, headNode);\n        child2.addParentNode(linkB2, headNode);\n        child3.addParentNode(linkB3, headNode);\n\n        return headNode;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/lifecycle/states/DetachedStateTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.lifecycle.states;\n\nimport javax.persistence.CascadeType;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.StoreBuilder;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\n\n/**\n * @author amresh.singh\n * \n */\npublic class DetachedStateTest\n{\n    PersistenceCache pc;\n\n    DetachedState state;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        pc = new PersistenceCache();\n        state = new DetachedState();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        pc = null;\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#initialize(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testInitialize()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.initialize(storeNode);\n        Assert.assertNotNull(pc);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handlePersist(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandlePersist()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        try\n        {\n            state.handlePersist(storeNode);\n            Assert.fail(\"Persist operation in Detached state should have thrown exception\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(IllegalArgumentException.class, e.getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handleRemove(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleRemove()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.REMOVE);\n        try\n        {\n            state.handleRemove(storeNode);\n            Assert.fail(\"Remove operation in Detached state should have thrown exception\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(IllegalArgumentException.class, e.getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handleRefresh(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleRefresh()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.REFRESH);\n        try\n        {\n            state.handleRefresh(storeNode);\n            Assert.fail(\"refresh operation in Detached state should have thrown exception\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(IllegalArgumentException.class, e.getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handleMerge(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleMerge()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.MERGE);\n        state.handleMerge(storeNode);\n\n        Assert.assertEquals(ManagedState.class, storeNode.getCurrentNodeState().getClass());\n        Assert.assertTrue(storeNode.isUpdate());\n\n//        for (Node childNode : storeNode.getChildren().values())\n//        {\n//            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n//            Assert.assertEquals(ManagedState.class, childNode.getCurrentNodeState().getClass());\n//            Assert.assertTrue(childNode.isUpdate());\n//        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handleDetach(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleDetach()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleDetach(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handleClose(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleClose()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleClose(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handleLock(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleLock()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleLock(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handleCommit(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleCommit()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleCommit(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handleRollback(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleRollback()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleRollback(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handleFind(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleFind()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleFind(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handleGetReference(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleGetReference()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleGetReference(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handleContains(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleContains()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleContains(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handleClear(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleClear()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleClear(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.DetachedState#handleFlush(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleFlush()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleFlush(storeNode);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/lifecycle/states/ManagedStateTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.lifecycle.states;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.PersistenceContextType;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.graph.BillingCounter;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.StoreBuilder;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\n\n/**\n * @author amresh.singh\n */\npublic class ManagedStateTest\n{\n    private PersistenceCache pc;\n\n    private ManagedState state;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        pc = new PersistenceCache();\n        state = new ManagedState();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        pc = null;\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#initialize(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testInitialize()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.initialize(storeNode);\n        Assert.assertNotNull(pc);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handlePersist(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandlePersist()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handlePersist(storeNode);\n\n        Assert.assertEquals(ManagedState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n            Assert.assertEquals(ManagedState.class, childNode.getCurrentNodeState().getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handleRemove(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleRemove()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.REMOVE);\n        state.handleRemove(storeNode);\n\n        Assert.assertEquals(RemovedState.class, storeNode.getCurrentNodeState().getClass());\n        Assert.assertTrue(storeNode.isDirty());\n\n        // for (Node childNode : storeNode.getChildren().values())\n        // {\n        // Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n        // Assert.assertEquals(RemovedState.class,\n        // childNode.getCurrentNodeState().getClass());\n        // Assert.assertTrue(childNode.isDirty());\n        // }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handleRefresh(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleRefresh()\n    {\n        try\n        {\n            Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.REFRESH);\n            state.handleRefresh(storeNode);\n            Assert.fail(\"Exception should be thrown because client is not available\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertNotNull(e);\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handleMerge(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     * \n     * @throws InvocationTargetException\n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     * @throws IllegalArgumentException\n     * @throws NoSuchMethodException\n     * @throws SecurityException\n     */\n    @Test\n    public void testHandleMerge() throws IllegalArgumentException, InstantiationException, IllegalAccessException,\n            InvocationTargetException, SecurityException, NoSuchMethodException\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.MERGE);\n\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"kunderatest\");\n        Constructor constructor = PersistenceDelegator.class.getDeclaredConstructor(KunderaMetadata.class,\n                PersistenceCache.class);\n        constructor.setAccessible(true);\n        PersistenceDelegator pd = (PersistenceDelegator) constructor.newInstance(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), new PersistenceCache());\n\n        storeNode.setPersistenceDelegator(pd);\n        \n        state.handleMerge(storeNode);\n\n        Assert.assertEquals(ManagedState.class, storeNode.getCurrentNodeState().getClass());\n        Assert.assertTrue(storeNode.isUpdate());\n        Assert.assertNotNull(storeNode.getPersistenceCache().getMainCache()\n                .getNodeFromCache(storeNode.getNodeId(), null));\n\n        // for (Node childNode : storeNode.getChildren().values())\n        // {\n        // Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n        // Assert.assertEquals(ManagedState.class,\n        // childNode.getCurrentNodeState().getClass());\n        // Assert.assertTrue(childNode.isUpdate());\n        // Assert.assertNotNull(childNode.getPersistenceCache().getMainCache().getNodeFromCache(childNode.getNodeId()));\n        // }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handleDetach(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleDetach()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.DETACH);\n        state.handleDetach(storeNode);\n\n        Assert.assertEquals(DetachedState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n            Assert.assertEquals(DetachedState.class, childNode.getCurrentNodeState().getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handleClear(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleClear()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.DETACH);\n        state.handleClear(storeNode);\n\n        Assert.assertEquals(DetachedState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n            Assert.assertEquals(DetachedState.class, childNode.getCurrentNodeState().getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handleClose(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleClose()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.DETACH);\n        state.handleClose(storeNode);\n\n        Assert.assertEquals(DetachedState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n            Assert.assertEquals(DetachedState.class, childNode.getCurrentNodeState().getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handleLock(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleLock()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleLock(storeNode);\n        Assert.assertTrue(storeNode.getCurrentNodeState().getClass().equals(ManagedState.class));\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handleCommit(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleCommit()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleCommit(storeNode);\n\n        Assert.assertEquals(DetachedState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n            Assert.assertEquals(ManagedState.class, childNode.getCurrentNodeState().getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handleRollback(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    // @Test\n    public void testHandleRollback()\n    {\n        // Extended\n        pc.setPersistenceContextType(PersistenceContextType.EXTENDED);\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleDetach(storeNode);\n\n        Assert.assertEquals(TransientState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n            Assert.assertEquals(ManagedState.class, childNode.getCurrentNodeState().getClass());\n        }\n\n        // Transactional\n        pc.setPersistenceContextType(PersistenceContextType.TRANSACTION);\n        storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleDetach(storeNode);\n\n        Assert.assertEquals(DetachedState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n            Assert.assertEquals(ManagedState.class, childNode.getCurrentNodeState().getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handleFind(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleFind()\n    {\n        try\n        {\n            Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.REFRESH);\n            state.handleFind(storeNode);\n            Assert.fail(\"Exception should be thrown because client is not available\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertNotNull(e);\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handleGetReference(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleGetReference()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleGetReference(storeNode);\n        Assert.assertTrue(storeNode.getCurrentNodeState().getClass().equals(ManagedState.class));\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handleContains(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleContains()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleContains(storeNode);\n        Assert.assertTrue(storeNode.getCurrentNodeState().getClass().equals(ManagedState.class));\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.ManagedState#handleFlush(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleFlush()\n    {\n        try\n        {\n            Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.REFRESH);\n            state.handleFlush(storeNode);\n            Assert.fail(\"Exception should be thrown because client is not available\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertNotNull(e);\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/lifecycle/states/NodeStateTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.lifecycle.states;\n\nimport javax.persistence.CascadeType;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.entity.PersonnelDTO;\nimport com.impetus.kundera.graph.BillingCounter;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.StoreBuilder;\nimport com.impetus.kundera.lifecycle.NodeStateContext;\nimport com.impetus.kundera.lifecycle.states.NodeState.OPERATION;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\n\n/**\n * @author amresh.singh\n */\npublic class NodeStateTest\n{\n\n    PersistenceCache pc;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        pc = new PersistenceCache();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.NodeState#moveNodeToNextState(com.impetus.kundera.lifecycle.NodeStateContext, com.impetus.kundera.lifecycle.states.NodeState)}\n     * .\n     */\n    @Test\n    public void testMoveNodeToNextState()\n    {\n        NodeState nodeState = new TransientState();\n        NodeStateContext node = new Node(\"1\", PersonnelDTO.class, nodeState, pc, \"1\", null);\n        nodeState.moveNodeToNextState(node, new ManagedState());\n        Assert.assertEquals(ManagedState.class, node.getCurrentNodeState().getClass());\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.NodeState#recursivelyPerformOperation(com.impetus.kundera.lifecycle.NodeStateContext, com.impetus.kundera.lifecycle.states.NodeState.OPERATION)}\n     * .\n     */\n    @Test\n    public void testRecursivelyPerformOperation()\n    {\n        // Persist operation\n        NodeState state = new TransientState();\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.recursivelyPerformOperation(storeNode, OPERATION.PERSIST);\n        Assert.assertEquals(TransientState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n//            Assert.assertEquals(ManagedState.class, childNode.getCurrentNodeState().getClass());\n        }\n\n        // Merge operation\n        state = new DetachedState();\n        storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.MERGE);\n        state.recursivelyPerformOperation(storeNode, OPERATION.MERGE);\n        Assert.assertEquals(DetachedState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n//            Assert.assertEquals(ManagedState.class, childNode.getCurrentNodeState().getClass());\n        }\n\n        // Remove Operation\n        state = new ManagedState();\n        storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.REMOVE);\n        state.recursivelyPerformOperation(storeNode, OPERATION.REMOVE);\n        Assert.assertEquals(ManagedState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n//            Assert.assertEquals(RemovedState.class, childNode.getCurrentNodeState().getClass());\n        }\n\n        // Refresh Operation\n        state = new DetachedState();\n        storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.REFRESH);\n        try\n        {\n            state.recursivelyPerformOperation(storeNode, OPERATION.REFRESH);\n            Assert.fail(\"Refresh operation in Detached state should have thrown an exception\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(IllegalArgumentException.class, e.getClass());\n        }\n\n        // Remove Operation\n        state = new ManagedState();\n        storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.DETACH);\n        state.recursivelyPerformOperation(storeNode, OPERATION.DETACH);\n        Assert.assertEquals(ManagedState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n//            Assert.assertEquals(DetachedState.class, childNode.getCurrentNodeState().getClass());\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/lifecycle/states/RemovedStateTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.lifecycle.states;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.PersistenceContextType;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.graph.BillingCounter;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.StoreBuilder;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\n\n/**\n * @author amresh.singh\n * \n */\npublic class RemovedStateTest\n{\n\n    PersistenceCache pc;\n\n    RemovedState state;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        pc = new PersistenceCache();\n        state = new RemovedState();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        pc = null;\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#initialize(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testInitialize()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.initialize(storeNode);\n        Assert.assertNotNull(pc);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handlePersist(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandlePersist()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handlePersist(storeNode);\n\n        Assert.assertEquals(ManagedState.class, storeNode.getCurrentNodeState().getClass());\n\n//        for (Node childNode : storeNode.getChildren().values())\n//        {\n//            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n//            Assert.assertEquals(ManagedState.class, childNode.getCurrentNodeState().getClass());\n//        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handleRemove(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleRemove()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.REMOVE);\n        state.handleRemove(storeNode);\n\n        Assert.assertEquals(RemovedState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n            Assert.assertEquals(RemovedState.class, childNode.getCurrentNodeState().getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handleRefresh(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleRefresh()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.REFRESH);\n        try\n        {\n            state.handleRefresh(storeNode);\n            Assert.fail(\"Refresh operation in Removed state should have thrown exception\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(IllegalArgumentException.class, e.getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handleMerge(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleMerge()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.MERGE);\n        try\n        {\n            state.handleMerge(storeNode);\n            Assert.fail(\"Merge operation in Removed state should have thrown exception\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(IllegalArgumentException.class, e.getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handleDetach(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleDetach()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.DETACH);\n        state.handleDetach(storeNode);\n\n        Assert.assertEquals(DetachedState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n            Assert.assertEquals(DetachedState.class, childNode.getCurrentNodeState().getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handleClose(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleClose()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleClose(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handleLock(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleLock()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleLock(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handleCommit(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleCommit()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleCommit(storeNode);\n\n        Assert.assertEquals(TransientState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n            Assert.assertEquals(RemovedState.class, childNode.getCurrentNodeState().getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handleRollback(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleRollback()\n    {\n        // Extended\n        pc.setPersistenceContextType(PersistenceContextType.EXTENDED);\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleRollback(storeNode);\n\n        Assert.assertEquals(ManagedState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n            Assert.assertEquals(RemovedState.class, childNode.getCurrentNodeState().getClass());\n        }\n\n        // Transactional\n        pc.setPersistenceContextType(PersistenceContextType.TRANSACTION);\n        storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleRollback(storeNode);\n\n        Assert.assertEquals(DetachedState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n            Assert.assertEquals(RemovedState.class, childNode.getCurrentNodeState().getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handleFind(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleFind()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleFind(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handleGetReference(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleGetReference()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleGetReference(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handleContains(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleContains()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleContains(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handleClear(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleClear()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleClear(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.RemovedState#handleFlush(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleFlush()\n    {\n        try\n        {\n            Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n            state.handleFlush(storeNode);\n            Assert.fail(\"Exception should be thrown because client is not available\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertNotNull(e);\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/lifecycle/states/TransientStateTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.lifecycle.states;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.graph.BillingCounter;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.StoreBuilder;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\nimport com.impetus.kundera.utils.DeepEquals;\n\n/**\n * @author amresh.singh\n * \n */\npublic class TransientStateTest\n{\n    PersistenceCache pc;\n\n    TransientState state;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        pc = new PersistenceCache();\n        state = new TransientState();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        pc = null;\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#initialize(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testInitialize()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.initialize(storeNode);\n        Assert.assertNotNull(pc);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handlePersist(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     * \n     * @throws NoSuchMethodException\n     * @throws SecurityException\n     * @throws InvocationTargetException\n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     * @throws IllegalArgumentException\n     */\n    @Test\n    public void testHandlePersist() throws SecurityException, NoSuchMethodException, IllegalArgumentException,\n            InstantiationException, IllegalAccessException, InvocationTargetException\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"kunderatest\");\n        Constructor constructor = PersistenceDelegator.class.getDeclaredConstructor(KunderaMetadata.class,\n                PersistenceCache.class);\n        constructor.setAccessible(true);\n        PersistenceDelegator pd = (PersistenceDelegator) constructor.newInstance(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), new PersistenceCache());\n\n        storeNode.setPersistenceDelegator(pd);\n\n        state.handlePersist(storeNode);\n\n        Assert.assertEquals(ManagedState.class, storeNode.getCurrentNodeState().getClass());\n        Assert.assertTrue(storeNode.isDirty());\n        Assert.assertNotNull(storeNode.getPersistenceCache().getMainCache()\n                .getNodeFromCache(storeNode.getNodeId(), null));\n\n        // for (Node childNode : storeNode.getChildren().values())\n        // {\n        // Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n        // Assert.assertEquals(ManagedState.class,\n        // childNode.getCurrentNodeState().getClass());\n        // Assert.assertTrue(childNode.isDirty());\n        // Assert.assertNotNull(childNode.getPersistenceCache().getMainCache().getNodeFromCache(childNode.getNodeId()));\n        // }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handleRemove(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleRemove()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.REMOVE);\n        state.handleRemove(storeNode);\n\n        Assert.assertEquals(TransientState.class, storeNode.getCurrentNodeState().getClass());\n\n        for (Node childNode : storeNode.getChildren().values())\n        {\n            Assert.assertEquals(BillingCounter.class, childNode.getDataClass());\n            Assert.assertEquals(TransientState.class, childNode.getCurrentNodeState().getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handleRefresh(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleRefresh()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.REFRESH);\n        try\n        {\n            state.handleRefresh(storeNode);\n            Assert.fail(\"Refresh operation in Transient state should have thrown exception\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(IllegalArgumentException.class, e.getClass());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handleMerge(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     * \n     * @throws NoSuchMethodException\n     * @throws SecurityException\n     * @throws InvocationTargetException\n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     * @throws IllegalArgumentException\n     */\n    @Test\n    public void testHandleMerge() throws SecurityException, NoSuchMethodException, IllegalArgumentException,\n            InstantiationException, IllegalAccessException, InvocationTargetException\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.MERGE);\n\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"kunderatest\");\n        Constructor constructor = PersistenceDelegator.class.getDeclaredConstructor(KunderaMetadata.class,\n                PersistenceCache.class);\n        constructor.setAccessible(true);\n        PersistenceDelegator pd = (PersistenceDelegator) constructor.newInstance(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), new PersistenceCache());\n\n        storeNode.setPersistenceDelegator(pd);\n\n        Object data1 = storeNode.getData();\n        state.handleMerge(storeNode);\n        Object data2 = storeNode.getData();\n        Assert.assertTrue(DeepEquals.deepEquals(data1, data2));\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handleDetach(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleDetach()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.DETACH);\n        state.handleDetach(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handleClose(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleClose()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleClose(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handleLock(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleLock()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleLock(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handleCommit(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleCommit()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleCommit(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handleRollback(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleRollback()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleRollback(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handleFind(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleFind()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleFind(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handleGetReference(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleGetReference()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleGetReference(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handleContains(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleContains()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleContains(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handleClear(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleClear()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleClear(storeNode);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.lifecycle.states.TransientState#handleFlush(com.impetus.kundera.lifecycle.NodeStateContext)}\n     * .\n     */\n    @Test\n    public void testHandleFlush()\n    {\n        Node storeNode = StoreBuilder.buildStoreNode(pc, state, CascadeType.PERSIST);\n        state.handleFlush(storeNode);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/loader/GenericClientFactoryTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.loader;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.CoreTestClientFactory;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * @author vivek.mishra\n * junit for {@link GenericClientFactory}\n *\n */\npublic class GenericClientFactoryTest\n{\n    private static final String PU = \"patest\";\n\n    private EntityManagerFactory emf;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n                \n        emf = Persistence.createEntityManagerFactory(PU);\n        emf.createEntityManager();\n\n    }\n\n    @Test\n    public void test() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException\n    {\n        PersistenceUnitMetadata puMetadata = new PersistenceUnitMetadata();\n        Map<String, PersistenceUnitMetadata> puMetadataMap = new HashMap<String, PersistenceUnitMetadata>();\n        puMetadataMap.put(PU, puMetadata);\n        ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance().getApplicationMetadata().addPersistenceUnitMetadata(puMetadataMap);\n        CoreTestClientFactory clientFactory = new CoreTestClientFactory();\n               \n        \n        Method m = GenericClientFactory.class.getDeclaredMethod(\"setKunderaMetadata\", KunderaMetadata.class);\n        if (!m.isAccessible())\n        {\n            m.setAccessible(true);\n        }\n\n        m.invoke(clientFactory, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n        \n        clientFactory.load(PU, null);\n        \n        clientFactory.setExternalProperties(new HashMap<String, Object>());\n        \n        Assert.assertEquals(PU,clientFactory.getPersistenceUnit());\n        Assert.assertNotNull(clientFactory.getClientInstance());\n        Assert.assertNotNull(clientFactory.getSchemaManager(null));\n        Assert.assertNull(clientFactory.getConnectionPoolOrConnection());\n        \n        Assert.assertNotNull(clientFactory.getLoadBalancePolicy(\"ROUNDROBIN\"));\n        \n        Assert.assertNotNull(clientFactory.getLoadBalancePolicy(\"LEASTACTIVE\"));\n        \n        Assert.assertNotNull(clientFactory.getLoadBalancePolicy(\"invalid\"));\n        \n        try\n        {\n            clientFactory.onValidation(null, null);\n            Assert.fail(\"Should have gone to catch block!\");\n        }catch(IllegalArgumentException iaex)\n        {\n            Assert.assertNotNull(iaex.getMessage());\n        }\n        clientFactory.destroy();\n    }\n\n    @Test\n    public void testIndexerClass()\n    {\n//        kunderaMetadata.addClientMetadata(PU, null);\n        Map<String, Object> propertyMap = new HashMap<String, Object>();\n        propertyMap.put(PersistenceProperties.KUNDERA_INDEXER_CLASS, \"com.impetus.kundera.query.CoreIndexer\");\n        propertyMap.put(PersistenceProperties.KUNDERA_INDEX_HOME_DIR, \"\");\n        propertyMap.put(PersistenceProperties.KUNDERA_AUTO_GENERATOR_CLASS, \"\");\n        CoreTestClientFactory clientFactory = new CoreTestClientFactory();\n        clientFactory.load(PU, propertyMap);\n        \n        Assert.assertNotNull(clientFactory.getClientMetadata());\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/DefaultEntityTypeTest.java",
    "content": "package com.impetus.kundera.metadata;\n\nimport javax.persistence.metamodel.Bindable.BindableType;\nimport javax.persistence.metamodel.Type.PersistenceType;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.entities.SingularEntity;\nimport com.impetus.kundera.metadata.model.type.DefaultEntityType;\n\n\n\npublic class DefaultEntityTypeTest{\n\t\n\t\n\t/** The builder. */\n    @SuppressWarnings(\"rawtypes\")\n    private DefaultEntityType defaultTypeEntityObj;\n\n    /**\n     * Sets the up.\n     * \n     * @param <X>\n     *            the generic type\n     * @throws Exception\n     *             the exception\n     */\n    @SuppressWarnings(\"rawtypes\")\n    @Before\n    public <X extends Class> void setUp() throws Exception\n    {\n    \t\n    \tX clazz = (X) SingularEntity.class;\n    \t//AbstractManagedType<X> managedType = null;\n    \tdefaultTypeEntityObj = new DefaultEntityType<X>(clazz, PersistenceType.ENTITY, null);\n    }\n\n\t\n\t/**\n     * Sets the up.\n     * \n     * @param <X>\n     *            the generic type\n     \n     * @throws Exception\n     *             the exception\n     */\n    /*@SuppressWarnings(\"rawtypes\")\n    @Before\n    public <X extends Class> void setUp() throws Exception\n    {\n    \tX clazz = (X) SingularEntity.class;\n    \tAbstractManagedType<X> managedType = null;\n    \tmanagedType = new DefaultEntityType<X>(clazz, PersistenceType.ENTITY, null);\n    }*/\n\n   \n   \n    @Test\n    public void testPersistenceClassBindableType()\n    {\n        \n    \tAssert.assertEquals(defaultTypeEntityObj.getBindableType(), BindableType.ENTITY_TYPE);\n    }\n    \n   \n    \n    @Test\n    public void testName()\n    {\n       \n    \tAssert.assertEquals(defaultTypeEntityObj.getName(), \"SingularEntity\");\n    }\n    \n    \n\n\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/KunderaMetadataManagerTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.metadata;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.metamodel.Metamodel;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.metadata.entities.SingularEntityEmbeddable;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.validator.GeneratedIdStrategyIdentity;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * @author vivek.mishra junit for {@link KunderaMetadataManager}.\n * \n */\npublic class KunderaMetadataManagerTest\n{\n\n    private String persistenceUnit = \"patest\";\n\n    private EntityManagerFactory emf;\n\n    private KunderaMetadata kunderaMetadata;\n\n    @Before\n    public void setup()\n    {\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n    }\n\n    @Test\n    public void test()\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                SingularEntityEmbeddable.class);\n        Assert.assertNotNull(entityMetadata);\n        entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, persistenceUnit,\n                SingularEntityEmbeddable.class);\n        Assert.assertNotNull(entityMetadata);\n\n        try\n        {\n            entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, null);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (KunderaException kex)\n        {\n            Assert.assertNotNull(kex.getMessage());\n        }\n\n        entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, GeneratedIdStrategyIdentity.class);\n        Assert.assertNull(entityMetadata);\n\n        Metamodel metaModel = KunderaMetadataManager.getMetamodel(kunderaMetadata, persistenceUnit);\n        Assert.assertNotNull(metaModel);\n\n        metaModel = KunderaMetadataManager.getMetamodel(kunderaMetadata, persistenceUnit, \"KunderaTests\");\n        Assert.assertNotNull(metaModel);\n\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\n                persistenceUnit);\n\n        Assert.assertNotNull(puMetadata);\n\n        puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata, null);\n\n        Assert.assertNull(puMetadata);\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/MetadataBuilderTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.metadata;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.query.Person;\n\n/**\n * @author vivek.mishra junit for {@link MetadataUtils}.\n * \n */\npublic class MetadataBuilderTest\n{\n\n    private String persistenceUnit = \"patest\";\n\n    private EntityManagerFactory emf;\n\n    private KunderaMetadata kunderaMetadata;\n\n    @Before\n    public void setup()\n    {\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        kunderaMetadata = ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance();\n    }\n\n    @Test\n    public void test()\n    {\n        MetadataBuilder metadataBuilder = new MetadataBuilder(persistenceUnit,\n                \"com.impetus.kundera.client.CoreTestClientFactory\", null, kunderaMetadata);\n\n        metadataBuilder.buildEntityMetadata(Person.class);\n        metadataBuilder.validate(Person.class);\n\n        Assert.assertNotNull(KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Person.class));\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/MetadataUtilsTest.java",
    "content": "/**\n\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.metadata;\n\nimport java.lang.reflect.Field;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedHashSet;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.metadata.entities.Article;\nimport com.impetus.kundera.metadata.entities.EmbeddableEntity;\nimport com.impetus.kundera.metadata.entities.SingularEntityEmbeddable;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.validator.InvalidEntityDefinitionException;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * @author vivek.mishra junit for {@link MetadataUtils}.\n * \n */\npublic class MetadataUtilsTest\n{\n    private String persistenceUnit = \"patest\";\n\n    private EntityManagerFactory emf;\n\n    private KunderaMetadata kunderaMetadata;\n\n    @Before\n    public void setup()\n    {\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n    }\n\n    @Test\n    public void test()\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                SingularEntityEmbeddable.class);\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n\n        EmbeddableType embeddableType = metaModel.embeddable(EmbeddableEntity.class);\n\n        Map<String, Field> embeddableMap = MetadataUtils.createColumnsFieldMap(entityMetadata, embeddableType);\n        Assert.assertNotNull(embeddableMap);\n        Assert.assertEquals(1, embeddableMap.size());\n\n        embeddableMap = MetadataUtils.createSuperColumnsFieldMap(entityMetadata, kunderaMetadata);\n        Assert.assertNotNull(embeddableMap);\n        Assert.assertEquals(2, embeddableMap.size());\n\n        Assert.assertTrue(MetadataUtils.defaultTransactionSupported(persistenceUnit, kunderaMetadata));\n\n        EntityType<SingularEntityEmbeddable> entityType = metaModel.entity(SingularEntityEmbeddable.class);\n\n        Object embeddedObject = MetadataUtils.getEmbeddedGenericObjectInstance((Field) entityType.getAttribute(\n                \"embeddableEntity\").getJavaMember());\n\n        Assert.assertNotNull(embeddedObject);\n        Assert.assertTrue(embeddedObject.getClass().isAssignableFrom(EmbeddableEntity.class));\n\n        try\n        {\n            MetadataUtils.getEmbeddedCollectionInstance((Field) entityType.getAttribute(\"embeddableEntity\")\n                    .getJavaMember());\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (InvalidEntityDefinitionException iedx)\n        {\n            Assert.assertNotNull(iedx);\n        }\n\n        // EntityMetadata invalidMetadata =\n        // KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n        // AddressEntity.class);\n        // Assert.assertNull(invalidMetadata);\n\n    }\n\n    @Test\n    public void testSerializeKeys()\n    {\n        Set<String> foreignKeys = new LinkedHashSet<String>();\n        foreignKeys.add(\"key1\");\n        foreignKeys.add(\"key2\");\n        foreignKeys.add(\"key3\");\n\n        String serializedKey = MetadataUtils.serializeKeys(foreignKeys);\n        Assert.assertNotNull(serializedKey);\n        Assert.assertEquals(\"key1~key2~key3\", serializedKey);\n    }\n\n    @Test\n    public void testDeserializeKeys()\n    {\n        final String serializedKey = \"key1~key2~key3\";\n\n        Set<String> foreignKeys = MetadataUtils.deserializeKeys(serializedKey);\n        Assert.assertNotNull(foreignKeys);\n        Assert.assertEquals(3, foreignKeys.size());\n    }\n\n    @Test\n    public void testWithNullEntity()\n    {\n        try\n        {\n            KunderaMetadataManager.getEntityMetadata(kunderaMetadata, null);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (KunderaException kex)\n        {\n            Assert.assertNotNull(kex);\n        }\n    }\n\n    @Test\n    public void testIsEmbeddedAttributeIndexable()\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, SingularEntityEmbeddable.class);\n        Assert.assertNotNull(m);\n\n        try\n        {\n            Assert.assertTrue(MetadataUtils.isEmbeddedAtributeIndexable(m.getEntityClazz().getDeclaredField(\n                    \"embeddableEntity\")));\n            Assert.assertTrue(MetadataUtils.isEmbeddedAtributeIndexable(m.getEntityClazz().getDeclaredField(\n                    \"embeddableEntityTwo\")));\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n\n    }\n\n    @Test\n    public void testPopulateColumnAndSuperColumnMaps()\n    {\n        Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();\n        Map<String, Field> superColumnNameToFieldMap = new HashMap<String, Field>();\n\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, SingularEntityEmbeddable.class);\n        MetadataUtils.populateColumnAndSuperColumnMaps(m, columnNameToFieldMap, superColumnNameToFieldMap, kunderaMetadata);\n\n        Assert.assertNotNull(columnNameToFieldMap);\n        Assert.assertNotNull(superColumnNameToFieldMap);\n        Assert.assertFalse(columnNameToFieldMap.isEmpty());\n        Assert.assertFalse(superColumnNameToFieldMap.isEmpty());\n    }\n\n    @Test\n    public void testIsColumnInEmbeddableIndexable()\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, SingularEntityEmbeddable.class);\n        Assert.assertNotNull(m);\n\n        try\n        {\n            Assert.assertTrue(MetadataUtils.isColumnInEmbeddableIndexable(\n                    m.getEntityClazz().getDeclaredField(\"embeddableEntityTwo\"), \"field\"));\n            Assert.assertFalse(MetadataUtils.isColumnInEmbeddableIndexable(\n                    m.getEntityClazz().getDeclaredField(\"embeddableEntityTwo\"), \"name\"));\n\n            Assert.assertTrue(MetadataUtils.isColumnInEmbeddableIndexable(\n                    m.getEntityClazz().getDeclaredField(\"embeddableEntity\"), \"field\"));\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    @Test\n    public void testContainsBasicElementCollectionField()\n    {\n        EntityMetadata m1 = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Article.class);\n        Assert.assertNotNull(m1);\n        Assert.assertTrue(MetadataUtils.containsBasicElementCollectionField(m1, kunderaMetadata));\n        Assert.assertNotNull(m1.toString());\n\n        EntityMetadata m2 = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, SingularEntityEmbeddable.class);\n        Assert.assertNotNull(m2);\n        Assert.assertFalse(MetadataUtils.containsBasicElementCollectionField(m2, kunderaMetadata));\n        Assert.assertNotNull(m2.toString());\n    }\n\n    @Test\n    public void testIsBasicElementCollectionField()\n    {\n\n        try\n        {\n            EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Article.class);\n            Assert.assertNotNull(m.toString());\n\n            Field f = Article.class.getDeclaredField(\"body\");\n            Assert.assertFalse(MetadataUtils.isBasicElementCollectionField(f));\n\n            Field f1 = Article.class.getDeclaredField(\"comments\");\n            Assert.assertTrue(MetadataUtils.isBasicElementCollectionField(f1));\n\n            Field f2 = Article.class.getDeclaredField(\"tags\");\n            Assert.assertTrue(MetadataUtils.isBasicElementCollectionField(f2));\n\n            Field f3 = Article.class.getDeclaredField(\"likedBy\");\n            Assert.assertTrue(MetadataUtils.isBasicElementCollectionField(f3));\n\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/Article.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Entity class for Blog post\n * @author amresh.singh\n */\n@Entity\n@Table(name=\"article\", schema=\"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"body\")})\npublic class Article\n{    \n    @Id\n    @Column(name=\"post_id\")\n    private int postId;\n    \n    //Body of the post\n    @Column(name=\"body\")\n    private String body;       \n    \n    //Useful tags specified by author\n    @ElementCollection\n    @Column(name=\"tags\")\n    private Set<String> tags;  \n    \n    //List of user IDs who liked this blog post\n    @ElementCollection\n    @Column(name=\"liked_by\")\n    private List<Integer> likedBy;   \n    \n    //User IDs and their respective comments on this blog\n    @ElementCollection\n    @Column(name=\"comments\")\n    private Map<Integer, String> comments; \n\n    /**\n     * @return the postId\n     */\n    public int getPostId()\n    {\n        return postId;\n    }\n\n    /**\n     * @param postId the postId to set\n     */\n    public void setPostId(int postId)\n    {\n        this.postId = postId;\n    }\n\n    /**\n     * @return the body\n     */\n    public String getBody()\n    {\n        return body;\n    }\n\n    /**\n     * @param body the body to set\n     */\n    public void setBody(String body)\n    {\n        this.body = body;\n    }\n\n    /**\n     * @return the tags\n     */\n    public Set<String> getTags()\n    {\n        return tags;\n    }\n\n    /**\n     * @param tags the tags to set\n     */\n    public void setTags(Set<String> tags)\n    {\n        this.tags = tags;\n    }\n\n    /**\n     * @return the likedBy\n     */\n    public List<Integer> getLikedBy()\n    {\n        return likedBy;\n    }\n\n    /**\n     * @param likedBy the likedBy to set\n     */\n    public void setLikedBy(List<Integer> likedBy)\n    {\n        this.likedBy = likedBy;\n    }\n\n    /**\n     * @return the comments\n     */\n    public Map<Integer, String> getComments()\n    {\n        return comments;\n    }\n\n    /**\n     * @param comments the comments to set\n     */\n    public void setComments(Map<Integer, String> comments)\n    {\n        this.comments = comments;\n    }\n    \n    public void addTag(String tag)\n    {\n        if(tags == null)\n        {\n            tags = new HashSet<String>();\n        }\n        tags.add(tag);\n    }\n    \n    public void addLikedBy(int likedByUserId)\n    {\n        if(likedBy == null)\n        {\n            likedBy = new ArrayList<Integer>();\n        }\n        likedBy.add(likedByUserId);\n    }\n    \n    public void addComment(int userId, String comment)\n    {\n        if(comments == null)\n        {\n            comments = new HashMap<Integer, String>();\n        }\n        comments.put(userId, comment);\n    }\n    \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/AssociationEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"asso_table\", schema = \"testSchema@keyspace\")\npublic class AssociationEntity\n{\n\n    @Id\n    @Column(name = \"Association_ID\")\n    private String assoRowKey;\n\n    @Column(name = \"ADDRESS\")\n    private String address;\n\n    @Column(name = \"AGE\")\n    private int age;\n\n    /**\n     * @return the rowKey\n     */\n    public String getRowKey()\n    {\n        return assoRowKey;\n    }\n\n    /**\n     * @param rowKey\n     *            the rowKey to set\n     */\n    public void setRowKey(String rowKey)\n    {\n        this.assoRowKey = rowKey;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/AttributeOverrideSubClass.java",
    "content": "package com.impetus.kundera.metadata.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"table\", schema = \"testSchema@keyspace\")\n@AttributeOverride(name=\"mappedInt\", column=@Column(name=\"MAPPED_INT\"))\npublic class AttributeOverrideSubClass extends MappedSuperClass\n{\n\n    @Id\n    private String subClassAStr;\n\n    @Column\n    private Date subClassADt;\n\n    @Column\n    private long subClassALng;\n\n    /**\n     * @return the subClassAStr\n     */\n    public String getSubClassAStr()\n    {\n        return subClassAStr;\n    }\n\n    /**\n     * @param subClassAStr\n     *            the subClassAStr to set\n     */\n    public void setSubClassAStr(String subClassAStr)\n    {\n        this.subClassAStr = subClassAStr;\n    }\n\n    /**\n     * @return the subClassADt\n     */\n    public Date getSubClassADt()\n    {\n        return subClassADt;\n    }\n\n    /**\n     * @param subClassADt\n     *            the subClassADt to set\n     */\n    public void setSubClassADt(Date subClassADt)\n    {\n        this.subClassADt = subClassADt;\n    }\n\n    /**\n     * @return the subClassALng\n     */\n    public long getSubClassALng()\n    {\n        return subClassALng;\n    }\n\n    /**\n     * @param subClassALng\n     *            the subClassALng to set\n     */\n    public void setSubClassALng(long subClassALng)\n    {\n        this.subClassALng = subClassALng;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/CollectionTypeAssociationEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\npublic class CollectionTypeAssociationEntity\n{\n\n    @Id\n    private String colKey;\n\n    @Column\n    private byte[] bytes;\n\n    /**\n     * @return the setKey\n     */\n    public String getSetKey()\n    {\n        return colKey;\n    }\n\n    /**\n     * @param setKey\n     *            the setKey to set\n     */\n    public void setSetKey(String setKey)\n    {\n        this.colKey = setKey;\n    }\n\n    /**\n     * @return the bytes\n     */\n    public byte[] getBytes()\n    {\n        return bytes;\n    }\n\n    /**\n     * @param bytes\n     *            the bytes to set\n     */\n    public void setBytes(byte[] bytes)\n    {\n        this.bytes = bytes;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/EmbeddableEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Entity with singular attributes for meta model processing.\n * \n * @author vivek.mishra\n * \n */\n\n@Embeddable\n@IndexCollection(columns = { @Index(name = \"field\")})\npublic class EmbeddableEntity\n{\n    @Column(name = \"field\")\n    private String embeddedField;\n\n    /**\n     * @return the field\n     */\n    public String getField()\n    {\n        return embeddedField;\n    }\n\n    /**\n     * @param field\n     *            the field to set\n     */\n    public void setField(String field)\n    {\n        this.embeddedField = field;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/EmbeddableEntityTwo.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Entity with singular attributes for meta model processing.\n * \n * @author vivek.mishra\n * \n */\n\n@Embeddable\n@IndexCollection(columns={@Index(name=\"field\")})\npublic class EmbeddableEntityTwo\n{\n    @Column(name = \"field\")\n    private Float embeddedField;\n\n    @Column(name = \"name\")\n    private String embeddedName;\n\n    /**\n     * @return the field\n     */\n    public Float getField()\n    {\n        return embeddedField;\n    }\n\n    /**\n     * @param field\n     *            the field to set\n     */\n    public void setField(Float field)\n    {\n        this.embeddedField = field;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return embeddedName;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.embeddedName = name;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/EmbeddableTransientEntity.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Embeddable\npublic class EmbeddableTransientEntity\n{\n\n    @Column(name = \"field\")\n    private Float embeddedField;\n\n    @Column(name = \"name\")\n    private transient String embeddedName;\n\n    /**\n     * @return the field\n     */\n    public Float getField()\n    {\n        return embeddedField;\n    }\n\n    /**\n     * @param field\n     *            the field to set\n     */\n    public void setField(Float field)\n    {\n        this.embeddedField = field;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return embeddedName;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.embeddedName = name;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/EmbeddedIdOwnerEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"table\", schema = \"testSchema@keyspace\")\npublic class EmbeddedIdOwnerEntity\n{\n\n    @EmbeddedId\n    private EmbeddableEntity id;\n\n    @Column\n    private long logColumn;\n\n    /**\n     * @return the logColumn\n     */\n    public long getLogColumn()\n    {\n        return logColumn;\n    }\n\n    /**\n     * @param logColumn\n     *            the logColumn to set\n     */\n    public void setLogColumn(long logColumn)\n    {\n        this.logColumn = logColumn;\n    }\n\n    /**\n     * @return the id\n     */\n    public EmbeddableEntity getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(EmbeddableEntity id)\n    {\n        this.id = id;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/EntityWithAttributeOverrides.java",
    "content": "package com.impetus.kundera.metadata.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"table\", schema = \"testSchema@keyspace\")\n@AttributeOverrides(value = { @AttributeOverride(name = \"mappedInt\", column = @Column(name = \"MAPPED_INT\")),\n        @AttributeOverride(name = \"mappedFloat\", column = @Column(name = \"MAPPED_FLOAT\")) })\npublic class EntityWithAttributeOverrides extends MappedSuperClass\n{\n\n    @Id\n    private String subClassAStr;\n\n    @Column\n    private Date subClassADt;\n\n    @Column\n    private long subClassALng;\n\n    /**\n     * @return the subClassAStr\n     */\n    public String getSubClassAStr()\n    {\n        return subClassAStr;\n    }\n\n    /**\n     * @param subClassAStr\n     *            the subClassAStr to set\n     */\n    public void setSubClassAStr(String subClassAStr)\n    {\n        this.subClassAStr = subClassAStr;\n    }\n\n    /**\n     * @return the subClassADt\n     */\n    public Date getSubClassADt()\n    {\n        return subClassADt;\n    }\n\n    /**\n     * @param subClassADt\n     *            the subClassADt to set\n     */\n    public void setSubClassADt(Date subClassADt)\n    {\n        this.subClassADt = subClassADt;\n    }\n\n    /**\n     * @return the subClassALng\n     */\n    public long getSubClassALng()\n    {\n        return subClassALng;\n    }\n\n    /**\n     * @param subClassALng\n     *            the subClassALng to set\n     */\n    public void setSubClassALng(long subClassALng)\n    {\n        this.subClassALng = subClassALng;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/EntityWithIdAttributeOverride.java",
    "content": "package com.impetus.kundera.metadata.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"table\", schema = \"testSchema@keyspace\")\n@AttributeOverrides(value = { @AttributeOverride(name = \"id\", column = @Column(name = \"ID_ATTRIB\")),\n        @AttributeOverride(name = \"mappedFloat\", column = @Column(name = \"MAPPED_FLOAT\")) })\npublic class EntityWithIdAttributeOverride extends IdMappedSuperClass\n{\n\n    @Column\n    private Date subClassADt;\n\n    @Column\n    private long subClassALng;\n\n\n    /**\n     * @return the subClassADt\n     */\n    public Date getSubClassADt()\n    {\n        return subClassADt;\n    }\n\n    /**\n     * @param subClassADt\n     *            the subClassADt to set\n     */\n    public void setSubClassADt(Date subClassADt)\n    {\n        this.subClassADt = subClassADt;\n    }\n\n    /**\n     * @return the subClassALng\n     */\n    public long getSubClassALng()\n    {\n        return subClassALng;\n    }\n\n    /**\n     * @param subClassALng\n     *            the subClassALng to set\n     */\n    public void setSubClassALng(long subClassALng)\n    {\n        this.subClassALng = subClassALng;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/IDClassEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class IDClassEntity\n{\n\n    private int key;\n\n    private String str;\n\n    /**\n     * @return the key\n     */\n    public int getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @param key\n     *            the key to set\n     */\n    public void setKey(int key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the str\n     */\n    public String getStr()\n    {\n        return str;\n    }\n\n    /**\n     * @param str\n     *            the str to set\n     */\n    public void setStr(String str)\n    {\n        this.str = str;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/IDClassOwnerEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.IdClass;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n@IdClass(value = IDClassEntity.class)\n@Entity\n@Table(name = \"table\", schema = \"testSchema@keyspace\")\npublic class IDClassOwnerEntity\n{\n\n    @Id\n    private String id;\n\n    @Column\n    private long logColumn;\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the logColumn\n     */\n    public long getLogColumn()\n    {\n        return logColumn;\n    }\n\n    /**\n     * @param logColumn\n     *            the logColumn to set\n     */\n    public void setLogColumn(long logColumn)\n    {\n        this.logColumn = logColumn;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/IdMappedSuperClass.java",
    "content": "package com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Id;\nimport javax.persistence.MappedSuperclass;\n\n/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\n/**\n * @author vivek.mishra\n * \n */\n@MappedSuperclass\npublic class IdMappedSuperClass extends RootMappedSuperClass\n{\n    @Id\n    private int id;\n\n    @Column\n    private int mappedInt;\n\n    @Column\n    private Float mappedFloat;\n\n    /**\n     * @return the mappedInt\n     */\n    public int getMappedInt()\n    {\n        return mappedInt;\n    }\n\n    /**\n     * @param mappedInt\n     *            the mappedInt to set\n     */\n    public void setMappedInt(int mappedInt)\n    {\n        this.mappedInt = mappedInt;\n    }\n\n    /**\n     * @return the mappedFloat\n     */\n    public Float getMappedFloat()\n    {\n        return mappedFloat;\n    }\n\n    /**\n     * @param mappedFloat\n     *            the mappedFloat to set\n     */\n    public void setMappedFloat(Float mappedFloat)\n    {\n        this.mappedFloat = mappedFloat;\n    }\n\n    public int getId()\n    {\n        return id;\n    }\n\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/ListTypeAssociationEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\npublic class ListTypeAssociationEntity\n{\n\n    @Id\n    private String listKey;\n\n    @Column\n    private byte[] bytes;\n\n    /**\n     * @return the setKey\n     */\n    public String getSetKey()\n    {\n        return listKey;\n    }\n\n    /**\n     * @param setKey\n     *            the setKey to set\n     */\n    public void setSetKey(String setKey)\n    {\n        this.listKey = setKey;\n    }\n\n    /**\n     * @return the bytes\n     */\n    public byte[] getBytes()\n    {\n        return bytes;\n    }\n\n    /**\n     * @param bytes\n     *            the bytes to set\n     */\n    public void setBytes(byte[] bytes)\n    {\n        this.bytes = bytes;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/MapTypeAssociationEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\npublic class MapTypeAssociationEntity\n{\n\n    @Id\n    private String mapKey;\n\n    @Column\n    private byte[] bytes;\n\n    /**\n     * @return the setKey\n     */\n    public String getSetKey()\n    {\n        return mapKey;\n    }\n\n    /**\n     * @param setKey\n     *            the setKey to set\n     */\n    public void setSetKey(String setKey)\n    {\n        this.mapKey = setKey;\n    }\n\n    /**\n     * @return the bytes\n     */\n    public byte[] getBytes()\n    {\n        return bytes;\n    }\n\n    /**\n     * @param bytes\n     *            the bytes to set\n     */\n    public void setBytes(byte[] bytes)\n    {\n        this.bytes = bytes;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/MappedSuperClass.java",
    "content": "package com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.MappedSuperclass;\n\n/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\n/**\n * @author vivek.mishra\n * \n */\n@MappedSuperclass\npublic class MappedSuperClass extends RootMappedSuperClass\n{\n    @Column\n    private int mappedInt;\n\n    @Column\n    private Float mappedFloat;\n\n    /**\n     * @return the mappedInt\n     */\n    public int getMappedInt()\n    {\n        return mappedInt;\n    }\n\n    /**\n     * @param mappedInt\n     *            the mappedInt to set\n     */\n    public void setMappedInt(int mappedInt)\n    {\n        this.mappedInt = mappedInt;\n    }\n\n    /**\n     * @return the mappedFloat\n     */\n    public Float getMappedFloat()\n    {\n        return mappedFloat;\n    }\n\n    /**\n     * @param mappedFloat\n     *            the mappedFloat to set\n     */\n    public void setMappedFloat(Float mappedFloat)\n    {\n        this.mappedFloat = mappedFloat;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/OToMOwnerEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport java.util.Collection;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"table\", schema = \"testSchema@keyspace\")\npublic class OToMOwnerEntity\n{\n\n    @Id\n    @Column(name = \"ROW_KEY\")\n    private byte rowKey;\n\n    @Column(name = \"name\")\n    private String name;\n\n    @Column(name = \"AMOUNT\")\n    private int amount;\n\n    @OneToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)\n    @Column(name = \"Association_ID\")\n    private Collection<AssociationEntity> association;\n\n    /**\n     * @return the rowKey\n     */\n    public byte getRowKey()\n    {\n        return rowKey;\n    }\n\n    /**\n     * @param rowKey\n     *            the rowKey to set\n     */\n    public void setRowKey(byte rowKey)\n    {\n        this.rowKey = rowKey;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the amount\n     */\n    public int getAmount()\n    {\n        return amount;\n    }\n\n    /**\n     * @param amount\n     *            the amount to set\n     */\n    public void setAmount(int amount)\n    {\n        this.amount = amount;\n    }\n\n    /**\n     * @return the association\n     */\n    public Collection<AssociationEntity> getAssociation()\n    {\n        return association;\n    }\n\n    /**\n     * @param association\n     *            the association to set\n     */\n    public void setAssociation(Collection<AssociationEntity> association)\n    {\n        this.association = association;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/OToOOwnerEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"table\", schema = \"testSchema@keyspace\")\npublic class OToOOwnerEntity\n{\n\n    @Id\n    @Column(name = \"ROW_KEY\")\n    private byte rowKey;\n\n    @Column(name = \"name\")\n    private String name;\n\n    @Column(name = \"AMOUNT\")\n    private int amount;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @Column(name = \"Association_ID\")\n    private AssociationEntity association;\n\n    /**\n     * @return the rowKey\n     */\n    public byte getRowKey()\n    {\n        return rowKey;\n    }\n\n    /**\n     * @param rowKey\n     *            the rowKey to set\n     */\n    public void setRowKey(byte rowKey)\n    {\n        this.rowKey = rowKey;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the amount\n     */\n    public int getAmount()\n    {\n        return amount;\n    }\n\n    /**\n     * @param amount\n     *            the amount to set\n     */\n    public void setAmount(int amount)\n    {\n        this.amount = amount;\n    }\n\n    /**\n     * @return the association\n     */\n    public AssociationEntity getAssociation()\n    {\n        return association;\n    }\n\n    /**\n     * @param association\n     *            the association to set\n     */\n    public void setAssociation(AssociationEntity association)\n    {\n        this.association = association;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/PluralOwnerType.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.OneToMany;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\npublic class PluralOwnerType\n{\n    @Id\n    @Column(name = \"P_KEY\")\n    private Double primaryKey;\n\n    @OneToMany\n    @Column(name = \"set_type\")\n    private Set<SetTypeAssociationEntity> setAssocition;\n\n    @ManyToMany\n    @JoinTable(name = \"OWNER_LIST\", joinColumns = { @JoinColumn(name = \"P_KEY\") }, inverseJoinColumns = { @JoinColumn(name = \"listKey\") })\n    @Column(name = \"list_type\")\n    private List<ListTypeAssociationEntity> listAssociation;\n\n    @OneToMany\n    @Column(name = \"col_type\")\n    private Collection<CollectionTypeAssociationEntity> collectionAssociation;\n\n    @Column(name = \"map_type\")\n    @OneToMany\n    private Map<Integer, MapTypeAssociationEntity> mapAssociation;\n\n    /**\n     * @return the primaryKey\n     */\n    public Double getPrimaryKey()\n    {\n        return primaryKey;\n    }\n\n    /**\n     * @param primaryKey\n     *            the primaryKey to set\n     */\n    public void setPrimaryKey(Double primaryKey)\n    {\n        this.primaryKey = primaryKey;\n    }\n\n    /**\n     * @return the setAssocition\n     */\n    public Set<SetTypeAssociationEntity> getSetAssocition()\n    {\n        return setAssocition;\n    }\n\n    /**\n     * @param setAssocition\n     *            the setAssocition to set\n     */\n    public void setSetAssocition(Set<SetTypeAssociationEntity> setAssocition)\n    {\n        this.setAssocition = setAssocition;\n    }\n\n    /**\n     * @return the listAssociation\n     */\n    public List<ListTypeAssociationEntity> getListAssociation()\n    {\n        return listAssociation;\n    }\n\n    /**\n     * @param listAssociation\n     *            the listAssociation to set\n     */\n    public void setListAssociation(List<ListTypeAssociationEntity> listAssociation)\n    {\n        this.listAssociation = listAssociation;\n    }\n\n    /**\n     * @return the collectionAssociation\n     */\n    public Collection<CollectionTypeAssociationEntity> getCollectionAssociation()\n    {\n        return collectionAssociation;\n    }\n\n    /**\n     * @param collectionAssociation\n     *            the collectionAssociation to set\n     */\n    public void setCollectionAssociation(Collection<CollectionTypeAssociationEntity> collectionAssociation)\n    {\n        this.collectionAssociation = collectionAssociation;\n    }\n\n    /**\n     * @return the mapAssociation\n     */\n    public Map<Integer, MapTypeAssociationEntity> getMapAssociation()\n    {\n        return mapAssociation;\n    }\n\n    /**\n     * @param mapAssociation\n     *            the mapAssociation to set\n     */\n    public void setMapAssociation(Map<Integer, MapTypeAssociationEntity> mapAssociation)\n    {\n        this.mapAssociation = mapAssociation;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/RootMappedSuperClass.java",
    "content": "package com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\n\n/**\n * @author vivek.mishra\n * \n */\n\npublic class RootMappedSuperClass\n{\n\n    @Column\n    private String rootStr;\n\n    @Column\n    private Long rootLong;\n\n    /**\n     * @return the rootStr\n     */\n    public String getRootStr()\n    {\n        return rootStr;\n    }\n\n    /**\n     * @param rootStr\n     *            the rootStr to set\n     */\n    public void setRootStr(String rootStr)\n    {\n        this.rootStr = rootStr;\n    }\n\n    /**\n     * @return the rootLong\n     */\n    public Long getRootLong()\n    {\n        return rootLong;\n    }\n\n    /**\n     * @param rootLong\n     *            the rootLong to set\n     */\n    public void setRootLong(Long rootLong)\n    {\n        this.rootLong = rootLong;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/SampleEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity with singular attributes for meta model processing.\n * \n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"table\", schema = \"KunderaTest@kunderatest\")\npublic class SampleEntity\n{\n\n    @Id\n    private Integer key;   \n\n    @Column(name = \"name\")\n    private String name;\n    \n    @Column(name = \"city\", nullable = false)\n    private String city;\n\n    public SampleEntity()\n    {\n\n    }\n\n    /**\n     * @return the key\n     */\n    public Integer getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @param key\n     *            the key to set\n     */\n    public void setKey(Integer key)\n    {\n        this.key = key;\n    }   \n\n    /**\n     * @return the city\n     */\n    public String getCity()\n    {\n        return city;\n    }\n\n    /**\n     * @param city the city to set\n     */\n    public void setCity(String city)\n    {\n        this.city = city;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/SetTypeAssociationEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\npublic class SetTypeAssociationEntity\n{\n\n    @Id\n    private String setKey;\n\n    @Column\n    private byte[] bytes;\n\n    /**\n     * @return the setKey\n     */\n    public String getSetKey()\n    {\n        return setKey;\n    }\n\n    /**\n     * @param setKey\n     *            the setKey to set\n     */\n    public void setSetKey(String setKey)\n    {\n        this.setKey = setKey;\n    }\n\n    /**\n     * @return the bytes\n     */\n    public byte[] getBytes()\n    {\n        return bytes;\n    }\n\n    /**\n     * @param bytes\n     *            the bytes to set\n     */\n    public void setBytes(byte[] bytes)\n    {\n        this.bytes = bytes;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/SingularEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.Table;\n\n/**\n * Entity with singular attributes for meta model processing.\n * \n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"table\", schema = \"testSchema@keyspace\")\n@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)\npublic class SingularEntity\n{\n\n    @Id\n    private Integer key;\n\n    @Column(name = \"field\", nullable = false)\n    private String field;\n\n    @Column(name = \"name\")\n    private String name;\n\n    /**\n     * @return the key\n     */\n    public Integer getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @param key\n     *            the key to set\n     */\n    public void setKey(Integer key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the field\n     */\n    public String getField()\n    {\n        return field;\n    }\n\n    /**\n     * @param field\n     *            the field to set\n     */\n    public void setField(String field)\n    {\n        this.field = field;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/SingularEntityEmbeddable.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity with singular attributes for meta model processing.\n * \n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"embeddable\", schema = \"KunderaTests@patest\")\npublic class SingularEntityEmbeddable\n{\n\n    @Id\n    private Integer key;\n\n    @Column(name = \"field\", nullable = false)\n    private String field;\n\n    @Column(name = \"name\")\n    private String name;\n\n    @Embedded\n    private EmbeddableEntity embeddableEntity;\n\n    @Embedded\n    private EmbeddableEntityTwo embeddableEntityTwo;\n\n    /**\n     * @return the key\n     */\n    public Integer getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @param key\n     *            the key to set\n     */\n    public void setKey(Integer key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the field\n     */\n    public String getField()\n    {\n        return field;\n    }\n\n    /**\n     * @param field\n     *            the field to set\n     */\n    public void setField(String field)\n    {\n        this.field = field;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the embeddableEntity\n     */\n    public EmbeddableEntity getEmbeddableEntity()\n    {\n        return embeddableEntity;\n    }\n\n    /**\n     * @param embeddableEntity\n     *            the embeddableEntity to set\n     */\n    public void setEmbeddableEntity(EmbeddableEntity embeddableEntity)\n    {\n        this.embeddableEntity = embeddableEntity;\n    }\n\n    /**\n     * @return the embeddableEntityTwo\n     */\n    public EmbeddableEntityTwo getEmbeddableEntityTwo()\n    {\n        return embeddableEntityTwo;\n    }\n\n    /**\n     * @param embeddableEntityTwo\n     *            the embeddableEntityTwo to set\n     */\n    public void setEmbeddableEntityTwo(EmbeddableEntityTwo embeddableEntityTwo)\n    {\n        this.embeddableEntityTwo = embeddableEntityTwo;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/SubClassA.java",
    "content": "package com.impetus.kundera.metadata.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"table\", schema = \"testSchema@keyspace\")\npublic class SubClassA extends MappedSuperClass\n{\n\n    @Id\n    private String subClassAStr;\n\n    @Column\n    private Date subClassADt;\n\n    @Column\n    private long subClassALng;\n\n    /**\n     * @return the subClassAStr\n     */\n    public String getSubClassAStr()\n    {\n        return subClassAStr;\n    }\n\n    /**\n     * @param subClassAStr\n     *            the subClassAStr to set\n     */\n    public void setSubClassAStr(String subClassAStr)\n    {\n        this.subClassAStr = subClassAStr;\n    }\n\n    /**\n     * @return the subClassADt\n     */\n    public Date getSubClassADt()\n    {\n        return subClassADt;\n    }\n\n    /**\n     * @param subClassADt\n     *            the subClassADt to set\n     */\n    public void setSubClassADt(Date subClassADt)\n    {\n        this.subClassADt = subClassADt;\n    }\n\n    /**\n     * @return the subClassALng\n     */\n    public long getSubClassALng()\n    {\n        return subClassALng;\n    }\n\n    /**\n     * @param subClassALng\n     *            the subClassALng to set\n     */\n    public void setSubClassALng(long subClassALng)\n    {\n        this.subClassALng = subClassALng;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/SubClassB.java",
    "content": "package com.impetus.kundera.metadata.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"table\", schema = \"testSchema@keyspace\")\npublic class SubClassB extends MappedSuperClass\n{\n    @Id\n    private String subClassBStr;\n\n    @Column\n    private Date subClassBDt;\n\n    @Column\n    private long subClassBLng;\n\n    /**\n     * @return the subClassBStr\n     */\n    public String getSubClassBStr()\n    {\n        return subClassBStr;\n    }\n\n    /**\n     * @param subClassBStr\n     *            the subClassBStr to set\n     */\n    public void setSubClassBStr(String subClassBStr)\n    {\n        this.subClassBStr = subClassBStr;\n    }\n\n    /**\n     * @return the subClassBDt\n     */\n    public Date getSubClassBDt()\n    {\n        return subClassBDt;\n    }\n\n    /**\n     * @param subClassBDt\n     *            the subClassBDt to set\n     */\n    public void setSubClassBDt(Date subClassBDt)\n    {\n        this.subClassBDt = subClassBDt;\n    }\n\n    /**\n     * @return the subClassBLng\n     */\n    public long getSubClassBLng()\n    {\n        return subClassBLng;\n    }\n\n    /**\n     * @param subClassBLng\n     *            the subClassBLng to set\n     */\n    public void setSubClassBLng(long subClassBLng)\n    {\n        this.subClassBLng = subClassBLng;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/SubSingularEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.Table;\n\n/**\n * Entity with sub singular attributes for meta model processing {@link InheritanceType} .\n * \n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"subTable\", schema = \"testSchema@keyspace\")\npublic class SubSingularEntity extends SingularEntity\n{\n\n    @Id\n    private Integer key;\n\n    @Column(name = \"field\", nullable = false)\n    private String field;\n\n    @Column(name = \"name\")\n    private String name;\n\n    /**\n     * @return the key\n     */\n    public Integer getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @param key\n     *            the key to set\n     */\n    public void setKey(Integer key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the field\n     */\n    public String getField()\n    {\n        return field;\n    }\n\n    /**\n     * @param field\n     *            the field to set\n     */\n    public void setField(String field)\n    {\n        this.field = field;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/TransientEntity.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.metadata.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"transient_entity_table\", schema = \"testSchema@keyspace\")\npublic class TransientEntity\n{\n\n    @Id\n    @Column(name = \"TransientEntity_Id\")\n    private String assoRowKey;\n\n    @Column(name = \"ADDRESS\")\n    private String address;\n\n    @Column(name = \"AGE\")\n    private transient int age;\n\n    @Embedded\n    private EmbeddableTransientEntity embeddableTransientField;\n\n    /**\n     * @return the rowKey\n     */\n    public String getRowKey()\n    {\n        return assoRowKey;\n    }\n\n    /**\n     * @param rowKey\n     *            the rowKey to set\n     */\n    public void setRowKey(String rowKey)\n    {\n        this.assoRowKey = rowKey;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the embeddableTransientEntity\n     */\n    public EmbeddableTransientEntity getEmbeddableTransientEntity()\n    {\n        return embeddableTransientField;\n    }\n\n    /**\n     * @param embeddableTransientEntity\n     *            the embeddableTransientEntity to set\n     */\n    public void setEmbeddableTransientEntity(EmbeddableTransientEntity embeddableTransientEntity)\n    {\n        this.embeddableTransientField = embeddableTransientEntity;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/bi/AssociationBiEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities.bi;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"asso_table\", schema = \"testSchema@keyspace\")\npublic class AssociationBiEntity\n{\n\n    @Id\n    @Column(name = \"Association_ID\")\n    private String assoRowKey;\n\n    @Column(name = \"ADDRESS\")\n    private String address;\n\n    @Column(name = \"AGE\")\n    private int age;\n\n    @OneToOne(mappedBy = \"association\")\n    private OToOOwnerBiEntity owner;\n\n    /**\n     * @return the rowKey\n     */\n    public String getRowKey()\n    {\n        return assoRowKey;\n    }\n\n    /**\n     * @param rowKey\n     *            the rowKey to set\n     */\n    public void setRowKey(String rowKey)\n    {\n        this.assoRowKey = rowKey;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the assoRowKey\n     */\n    public String getAssoRowKey()\n    {\n        return assoRowKey;\n    }\n\n    /**\n     * @param assoRowKey\n     *            the assoRowKey to set\n     */\n    public void setAssoRowKey(String assoRowKey)\n    {\n        this.assoRowKey = assoRowKey;\n    }\n\n    /**\n     * @return the owner\n     */\n    public OToOOwnerBiEntity getOwner()\n    {\n        return owner;\n    }\n\n    /**\n     * @param owner\n     *            the owner to set\n     */\n    public void setOwner(OToOOwnerBiEntity owner)\n    {\n        this.owner = owner;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/entities/bi/OToOOwnerBiEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.entities.bi;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"table\", schema = \"testSchema@keyspace\")\npublic class OToOOwnerBiEntity\n{\n\n    @Id\n    @Column(name = \"ROW_KEY\")\n    private byte rowKey;\n\n    @Column(name = \"name\")\n    private String name;\n\n    @Column(name = \"AMOUNT\")\n    private int amount;\n\n    @OneToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)\n    @Column(name = \"Association_ID\")\n    private AssociationBiEntity association;\n\n    /**\n     * @return the rowKey\n     */\n    public byte getRowKey()\n    {\n        return rowKey;\n    }\n\n    /**\n     * @param rowKey\n     *            the rowKey to set\n     */\n    public void setRowKey(byte rowKey)\n    {\n        this.rowKey = rowKey;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the amount\n     */\n    public int getAmount()\n    {\n        return amount;\n    }\n\n    /**\n     * @param amount\n     *            the amount to set\n     */\n    public void setAmount(int amount)\n    {\n        this.amount = amount;\n    }\n\n    /**\n     * @return the association\n     */\n    public AssociationBiEntity getAssociation()\n    {\n        return association;\n    }\n\n    /**\n     * @param association\n     *            the association to set\n     */\n    public void setAssociation(AssociationBiEntity association)\n    {\n        this.association = association;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/mappedsuperclass/Employee.java",
    "content": "package com.impetus.kundera.metadata.mappedsuperclass;\n\nimport java.math.BigInteger;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\n\n@Entity\npublic class Employee extends MappedPerson\n{\n\n    @Column\n    private BigInteger salary;\n    \n    @Column\n    private Integer departmentId;\n\n    public Employee()\n    {\n        \n    }\n    \n    public BigInteger getSalary()\n    {\n        return salary;\n    }\n\n    public void setSalary(BigInteger salary)\n    {\n        this.salary = salary;\n    }\n\n    public Integer getDepartmentId()\n    {\n        return departmentId;\n    }\n\n    public void setDepartmentId(Integer departmentId)\n    {\n        this.departmentId = departmentId;\n    }\n    \n    \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/mappedsuperclass/EntityWithoutFieldsBase.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.metadata.mappedsuperclass;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * @author amitkumar\n *\n *\tClass to verify that at least one field in entity class is not mandatory if the \n *\tsuperclass contains all the mandatory fields\n */\npublic class EntityWithoutFieldsBase {\n\n\tprotected static EntityManagerFactory emf;\n\n\tprotected static EntityManager em;\n\n\tprotected static String persistenceUnit = \"inheritanceTest\";\n\t\n\tprivate static Logger logger = LoggerFactory.getLogger(EntityWithoutFieldsBase.class);\n\n\tprotected void setupInternal()\n\t{\n\t\temf = Persistence.createEntityManagerFactory(persistenceUnit);\n\t\tem = emf.createEntityManager();\n\t}\n\n\tprotected void testEntityWithNoFieldsBase()\n\t{\n\t\tlogger.info(\"Test entity with no fields, all the fields declared in mappedsuperclass.\");\n\n\t\t// Persist Person\n\t\tPerson person = new Person();\n\t\tperson.setId(\"1\");\n\t\tperson.setFirstName(\"Amit\");\n\t\tperson.setLastName(\"Kumar\");\n\n\t\tem.persist(person);\n\n\t\tPerson fetchPerson = em.find(Person.class, \"1\");\n\n\t\t// Assertions to validate persisted object\n\t\tAssert.assertNotNull(fetchPerson);\n\t\tAssert.assertEquals(\"1\", fetchPerson.getId());\n\t\tAssert.assertEquals(\"Amit\", fetchPerson.getFirstName());\n\t\tAssert.assertEquals(\"Kumar\", fetchPerson.getLastName());\n\n\t\t// Assert to verify that person has been removed\n\t\tem.remove(fetchPerson);\n\t\tAssert.assertNull(em.find(Person.class, \"1\"));\n\t}\n\n\tprotected void testEntityWithNoFields2LevelInheritanceBase()\n\t{\n\t\tlogger.info(\"Test entity with no fields with two level inheritance, all the fields declared in mappedsuperclass.\");\n\n\t\t// Persist Person\n\t\tPersonChild person = new PersonChild();\n\t\tperson.setId(\"1\");\n\t\tperson.setFirstName(\"Amit\");\n\t\tperson.setLastName(\"Kumar\");\n\n\t\tem.persist(person);\n\n\t\tPersonChild fetchPerson = em.find(PersonChild.class, \"1\");\n\n\t\t// Assertions to validate persisted object\n\t\tAssert.assertNotNull(fetchPerson);\n\t\tAssert.assertEquals(\"1\", fetchPerson.getId());\n\t\tAssert.assertEquals(\"Amit\", fetchPerson.getFirstName());\n\t\tAssert.assertEquals(\"Kumar\", fetchPerson.getLastName());\n\n\t\t// Assert to verify that person has been removed\n\t\tem.remove(fetchPerson);\n\t\tAssert.assertNull(em.find(PersonChild.class, \"1\"));\n\t}\n\n\tprotected void tearDownInternal()\n\t{\n\t\tif (em != null)\n\t\t{\n\t\t\tem.close();\n\t\t\tem = null;\n\t\t}\n\n\t\tif (emf != null)\n\t\t{\n\t\t\temf.close();\n\t\t\temf = null;\n\t\t}\n\t}\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/mappedsuperclass/EntityWithoutFieldsTest.java",
    "content": "package com.impetus.kundera.metadata.mappedsuperclass;\n\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * @author amitkumar\n *\n *\tClass to verify that at least one field in entity class is not mandatory if the \n *\tsuperclass contains all the mandatory fields\n */\npublic class EntityWithoutFieldsTest extends EntityWithoutFieldsBase \n{\n\t\n\t@Before\n\tpublic void setup()\n\t{\n\t\tsetupInternal();\n\t}\n\t\n\t@Test\n\tpublic void testEntityWithNoFields()\n\t{\n\t\ttestEntityWithNoFieldsBase();\n\t}\n\t\n\t@Test\n\tpublic void testEntityWithNoFields2LevelInheritance()\n\t{\n\t\ttestEntityWithNoFields2LevelInheritanceBase();\n\t}\n\n\t@After\n\tpublic void tearDown()\n\t{\n\t\ttearDownInternal();\n\t}\n}\n\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/mappedsuperclass/InvalidPersonEntity.java",
    "content": "package com.impetus.kundera.metadata.mappedsuperclass;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.MappedSuperclass;\n\n//TODOO: While doing for attribute override, i need to verify with hibernate if i am having id attribute\n\n@MappedSuperclass\n@Entity\npublic class InvalidPersonEntity\n{\n\n    @Id\n    private String id;\n\n    @Column\n    private String firstName;\n\n    @Column\n    private String lastName;\n\n    // try with @Id attribute on Employee as well.\n    // @Column\n    private transient int version;\n\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n    public int getVersion()\n    {\n        return version;\n    }\n\n    public void setVersion(int version)\n    {\n        this.version = version;\n    }\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/mappedsuperclass/InvalidSuperClassTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.mappedsuperclass;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.junit.Test;\n\nimport com.impetus.kundera.loader.MetamodelLoaderException;\n\n/**\n * @author vivek.mishra\n * \n *         MappedSuper class junit.\n * \n */\npublic class InvalidSuperClassTest\n{\n    private String persistenceUnit = \"invalidmappedsu\";\n\n    @Test\n    public void setup()\n    {\n        try\n        {\n            EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (MetamodelLoaderException mlex)\n        {\n            Assert.assertTrue(StringUtils.startsWith(mlex.getMessage(),\n                    \"Class:class com.impetus.kundera.metadata.mappedsuperclass.InvalidPersonEntityis annotated with @MappedSuperClass and @Entity not allowed\"));\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/mappedsuperclass/MappedPerson.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.mappedsuperclass;\n\nimport javax.persistence.Column;\nimport javax.persistence.Id;\nimport javax.persistence.MappedSuperclass;\n\n//TODOO: While doing for attribute override, i need to verify with hibernate if i am having id attribute \n@MappedSuperclass\npublic class MappedPerson\n{\n\n    @Id\n    private String id;\n\n    @Column\n    private String firstName;\n\n    @Column\n    private String lastName;\n\n    // try with @Id attribute on Employee as well.\n//    @Column\n    private transient int version;\n\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n    public int getVersion()\n    {\n        return version;\n    }\n\n    public void setVersion(int version)\n    {\n        this.version = version;\n    }\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/mappedsuperclass/MappedSuperClassTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.mappedsuperclass;\n\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.query.QueryHandlerException;\n\n/**\n * @author vivek.mishra\n * \n *         MappedSuper class junit.\n * \n */\npublic class MappedSuperClassTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private String persistenceUnit = \"mappedsu\";\n\n    @Before\n    public void setup()\n    {\n        emf = Persistence.createEntityManagerFactory(\"mappedsu\");\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testMappedMetamodel()\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), Employee.class);\n        MetamodelImpl metaModel = (MetamodelImpl) ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance()\n                .getApplicationMetadata().getMetamodel(persistenceUnit);\n\n        EntityType entityType = metaModel.entity(Employee.class);\n\n        Set<Attribute> attributes = entityType.getAttributes();\n\n        Assert.assertEquals(5, attributes.size());\n        Assert.assertNotNull(entityMetadata.getIdAttribute());\n        Assert.assertNotNull(\"id\", entityMetadata.getIdAttribute().getName());\n\n    }\n\n    @Test\n    public void testValidateQuery()\n    {\n        String query = \" Select p from MappedPerson p\";\n\n        try\n        {\n            em.createQuery(query);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (QueryHandlerException qhex)\n        {\n            Assert.assertEquals(\"No entity found by the name: MappedPerson\", qhex.getMessage());\n        }\n\n    }\n\n    @Test\n    public void testEntityOperations()\n    {\n\n        try\n        {\n            MappedPerson p = new MappedPerson();\n            p.setId(\"dd\");\n            p.setFirstName(\"mapped\");\n            p.setLastName(\"superclass\");\n\n            em.persist(p);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (KunderaException kex)\n        {\n            Assert.assertNotNull(kex.getMessage());\n        }\n\n    }\n\n    @Test\n    public void testValidOperations()\n    {\n        Employee emp = new Employee();\n        emp.setId(\"emp_1\");\n        emp.setDepartmentId(1);\n        emp.setFirstName(\"vivek\");\n        em.persist(emp);\n\n        em.clear();\n        Employee result = em.find(Employee.class, \"emp_1\");\n        Assert.assertNotNull(result);\n        Assert.assertEquals(emp.getFirstName(), result.getFirstName());\n        Assert.assertEquals(emp.getDepartmentId(), result.getDepartmentId());\n\n        em.remove(result);\n\n        result = em.find(Employee.class, \"emp_1\");\n        Assert.assertNull(result);\n    }\n\n    @After\n    public void tearDown()\n    {\n        if (em != null)\n        {\n            em.close();\n            em = null;\n        }\n\n        if (emf != null)\n        {\n            emf.close();\n            emf = null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/mappedsuperclass/Person.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.mappedsuperclass;\n\nimport javax.persistence.Entity;\n\n/**\n * @author amitkumar\n *\n */\n\n@Entity\npublic class Person extends MappedPerson{\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/mappedsuperclass/PersonChild.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.mappedsuperclass;\n\nimport javax.persistence.Entity;\n\n/**\n * @author amitkumar\n *\n */\n@Entity\npublic class PersonChild extends Person\n\n{\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/model/ApplicationMetadataTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.entities.Article;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * @author amresh.singh\n * \n */\npublic class ApplicationMetadataTest\n{\n\n    private String persistenceUnit = \"patest\";\n\n    private EntityManagerFactory emf;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance().getApplicationMetadata()\n                .unloadApplicationMatadata(persistenceUnit);\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.metadata.model.ApplicationMetadata#addEntityMetadata(java.lang.String, java.lang.Class, com.impetus.kundera.metadata.model.EntityMetadata)}\n     * .\n     */\n    @Test\n    public void testAddEntityMetadata()\n    {\n        ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance().getApplicationMetadata()\n                .addEntityMetadata(persistenceUnit, Article.class, new EntityMetadata(Article.class));\n        Assert.assertNotNull(KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), Article.class));\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/model/Department.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\nimport com.impetus.kundera.gis.geometry.Point;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Embeddable\n@IndexCollection(columns = { @com.impetus.kundera.index.Index(name = \"email\", type = \"ASC\"),\n        @com.impetus.kundera.index.Index(name = \"location\", type = \"GEO2D\", min = -200, max = 200) })\npublic class Department\n{\n\n    /** The website. */\n    @Column(name = \"d_website\")\n    private String website;\n\n    /** The email. */\n    @Column(name = \"d_email\")\n    private String email;\n\n    /** The yahoo id. */\n    @Column(name = \"location\")\n    private Point location;\n\n    /**\n     * Instantiates a new core personal data.\n     */\n    public Department()\n    {\n\n    }\n\n    /**\n     * Instantiates a new core personal data.\n     * \n     * @param website\n     *            the website\n     * @param email\n     *            the email\n     * @param yahooId\n     *            the yahoo id\n     */\n    public Department(String website, String email, Point location)\n    {\n        this.website = website;\n        this.email = email;\n        this.location = location;\n    }\n\n    /**\n     * Gets the website.\n     * \n     * @return the website\n     */\n    public String getWebsite()\n    {\n        return website;\n    }\n\n    /**\n     * Sets the website.\n     * \n     * @param website\n     *            the new website\n     */\n    public void setWebsite(String website)\n    {\n        this.website = website;\n    }\n\n    /**\n     * Gets the email.\n     * \n     * @return the email\n     */\n    public String getEmail()\n    {\n        return email;\n    }\n\n    /**\n     * Sets the email.\n     * \n     * @param email\n     *            the email to set\n     */\n    public void setEmail(String email)\n    {\n        this.email = email;\n    }\n\n    /**\n     * Gets the yahoo id.\n     * \n     * @return the yahoo id\n     */\n    public Point getLocation()\n    {\n        return location;\n    }\n\n    /**\n     * Sets the yahoo id.\n     * \n     * @param yahooId\n     *            the new yahoo id\n     */\n    public void setLocation(Point location)\n    {\n        this.location = location;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/model/Employe.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"EMPLOYE\", schema = \"KunderaMetaDataTest@metaDataTest\")\n@IndexCollection(columns = { @Index(name = \"empName\"), @Index(name = \"age\")})\npublic class Employe\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"EMP_ID\")\n    private String empId;\n\n    /** The person name. */\n    @Column(name = \"EMP_NAME\")\n    private String empName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The personal data. */\n    @Embedded\n    private Department departmentData;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getEmpId()\n    {\n        return empId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getEmpName()\n    {\n        return empName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setEmpName(String empName)\n    {\n        this.empName = empName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setEmpId(String empId)\n    {\n        this.empId = empId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public Department getDepartmentData()\n    {\n        return departmentData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setDepartmentData(Department departmentData)\n    {\n        this.departmentData = departmentData;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/model/EntityMetadataTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model;\n\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.processor.IndexProcessor;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class EntityMetadataTest\n{\n    private String persistenceUnit = \"metaDataTest\";\n\n    private EntityManagerFactory emf;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = getEntityManagerFactory(null);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n    }\n\n    @Test\n    public void test()\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), Employe.class);\n        Assert.assertNotNull(entityMetadata);\n        Assert.assertNotNull(entityMetadata.getIndexProperties());\n        Assert.assertFalse(entityMetadata.getIndexProperties().isEmpty());\n        Assert.assertEquals(2, entityMetadata.getIndexProperties().size());\n        Assert.assertNotNull(entityMetadata.getIndexProperties().get(\"AGE\"));\n        Assert.assertNotNull(entityMetadata.getIndexProperties().get(\"EMP_NAME\"));\n        Assert.assertNull(entityMetadata.getIndexProperties().get(\"departmentData\"));\n        Assert.assertNotNull(entityMetadata.toString());\n\n        Map<String, PropertyIndex> indexes = IndexProcessor.getIndexesOnEmbeddable(Department.class);\n        Assert.assertNotNull(indexes);\n        Assert.assertFalse(indexes.isEmpty());\n        Assert.assertEquals(2, indexes.size());\n\n        Assert.assertNotNull(indexes.get(\"email\"));\n        Assert.assertEquals(\"ASC\", indexes.get(\"email\").getIndexType());\n        Assert.assertEquals(new Integer(Integer.MAX_VALUE), indexes.get(\"email\").getMax());\n        Assert.assertEquals(new Integer(Integer.MIN_VALUE), indexes.get(\"email\").getMin());\n\n        Assert.assertNotNull(indexes.get(\"location\"));\n        Assert.assertEquals(\"GEO2D\", indexes.get(\"location\").getIndexType());\n        Assert.assertEquals(new Integer(200), indexes.get(\"location\").getMax());\n        Assert.assertEquals(new Integer(-200), indexes.get(\"location\").getMin());\n\n    }\n\n    @Test\n    public void testEmbeddedCollection()\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), KunderaUser.class);\n        Assert.assertNotNull(entityMetadata);\n        Assert.assertTrue(entityMetadata.getIndexProperties().isEmpty());\n        Assert.assertEquals(EntityMetadata.Type.SUPER_COLUMN_FAMILY, entityMetadata.getType());\n        Assert.assertNotNull(entityMetadata.toString());\n\n        entityMetadata.setCounterColumnType(false);\n        Assert.assertFalse(entityMetadata.isCounterColumnType());\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory(String property)\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(persistenceUnit);\n    }\n\n    @Test\n    public void testColumn()\n    {\n        try\n        {\n            Column column = new Column(\"EMP_NAME\", Employe.class.getDeclaredField(\"empName\"));\n            column.setIndexable(true);\n            Assert.assertTrue(column.isIndexable());\n            Assert.assertEquals(\"empName\", column.getField().getName());\n            Assert.assertEquals(\"EMP_NAME\", column.getName());\n\n            column = new Column(\"AGE\", Employe.class.getDeclaredField(\"age\"), true);\n            Assert.assertTrue(column.isIndexable());\n            Assert.assertEquals(\"age\", column.getField().getName());\n            Assert.assertEquals(\"AGE\", column.getName());\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/model/KunderaUser.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.model;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.CollectionTable;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.ElementCollection;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * @author impetus\r\n * \r\n */\r\n@Entity\r\n@Table(name = \"KunderaUser\", schema = \"KunderaMetaDataTest@metaDataTest\")\r\npublic class KunderaUser\r\n{\r\n\r\n    @Id\r\n    @Column(name = \"USER_ID\")\r\n    private String userId;\r\n\r\n    // Element collection, will persist co-located\r\n    @ElementCollection\r\n    @CollectionTable(name = \"tweeted\")\r\n    private List<TweetKundera> tweets;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"FRIEND_ID\")\r\n    private List<KunderaUser> friends; // List of users whom I follow\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"FOLLOWER_ID\")\r\n    private List<KunderaUser> followers; // List of users who are following me\r\n\r\n    public KunderaUser()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * @return the userId\r\n     */\r\n    public String getUserId()\r\n    {\r\n        return userId;\r\n    }\r\n\r\n    /**\r\n     * @param userId\r\n     *            the userId to set\r\n     */\r\n    public void setUserId(String userId)\r\n    {\r\n        this.userId = userId;\r\n    }\r\n\r\n    /**\r\n     * @return the tweets\r\n     */\r\n    public List<TweetKundera> getTweets()\r\n    {\r\n        return tweets;\r\n    }\r\n\r\n    /**\r\n     * @param tweets\r\n     *            the tweets to set\r\n     */\r\n    public void addTweet(TweetKundera tweet)\r\n    {\r\n        if (this.tweets == null || this.tweets.isEmpty())\r\n        {\r\n            this.tweets = new ArrayList<TweetKundera>();\r\n        }\r\n        this.tweets.add(tweet);\r\n    }\r\n\r\n    /**\r\n     * @return the friends\r\n     */\r\n    public List<KunderaUser> getFriends()\r\n    {\r\n        return friends;\r\n    }\r\n\r\n    /**\r\n     * @param friends\r\n     *            the friends to set\r\n     */\r\n    public void addFriend(KunderaUser friend)\r\n    {\r\n        if (this.friends == null || this.friends.isEmpty())\r\n        {\r\n            this.friends = new ArrayList<KunderaUser>();\r\n        }\r\n        this.friends.add(friend);\r\n    }\r\n\r\n    /**\r\n     * @return the followers\r\n     */\r\n    public List<KunderaUser> getFollowers()\r\n    {\r\n        return followers;\r\n    }\r\n\r\n    /**\r\n     * @param followers\r\n     *            the followers to set\r\n     */\r\n    public void addFollower(KunderaUser follower)\r\n    {\r\n        if (this.followers == null || this.followers.isEmpty())\r\n        {\r\n            this.followers = new ArrayList<KunderaUser>();\r\n        }\r\n\r\n        this.followers.add(follower);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/model/PersistenceUnitMetadataTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.metadata.model;\n\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.Enumeration;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.loader.PersistenceXMLLoader;\n\n/**\n * @author kuldeep.mishra\n * junit for {@link PersistenceUnitMetadata}\n *\n */\npublic class PersistenceUnitMetadataTest\n{\n    private static List<PersistenceUnitMetadata> metadatas;\n\n    @BeforeClass\n    public static void setUp() throws Exception\n    {\n        Enumeration<URL> xmls = PersistenceUnitMetadata.class.getClassLoader().getResources(\"META-INF/persistence.xml\");\n\n        while (xmls.hasMoreElements())\n        {\n            String[] persistenceUnits = new String[1];\n            persistenceUnits[0] = \"kunderatest\";\n            \n            metadatas = PersistenceXMLLoader.findPersistenceUnits(xmls.nextElement(), persistenceUnits);\n        }\n    }\n\n    @AfterClass\n    public static void tearDown() throws Exception\n    {\n        metadatas = null;\n    }\n\n    @Test\n    public void testGetPersistenceUnitName()\n    {\n        Assert.assertNotNull(metadatas);\n        Assert.assertFalse(metadatas.isEmpty());\n        Assert.assertNotNull(metadatas.get(0));\n        Assert.assertNotNull(metadatas.get(0).toString());\n        Assert.assertEquals(\"kunderatest\", metadatas.get(0).getPersistenceUnitName());\n    }\n\n    @Test\n    public void testGetPersistenceProviderClassName()\n    {\n        Assert.assertNotNull(metadatas);\n        Assert.assertFalse(metadatas.isEmpty());\n        Assert.assertNotNull(metadatas.get(0));\n        Assert.assertEquals(\"com.impetus.kundera.KunderaPersistence\", metadatas.get(0)\n                .getPersistenceProviderClassName());\n    }\n\n    @Test\n    public void testGetPersistenceXMLSchemaVersion()\n    {\n        Assert.assertNotNull(metadatas);\n        Assert.assertFalse(metadatas.isEmpty());\n        Assert.assertNotNull(metadatas.get(0));\n        Assert.assertEquals(\"2.0\", metadatas.get(0).getPersistenceXMLSchemaVersion());\n    }\n\n    @Test\n    public void testGetClassLoader()\n    {\n        Assert.assertNotNull(metadatas);\n        Assert.assertFalse(metadatas.isEmpty());\n        Assert.assertNotNull(metadatas.get(0));\n        Assert.assertNotNull(metadatas.get(0).getClassLoader());\n    }\n    \n    @Test\n    public void testAddJarFile()\n    {\n        Assert.assertNotNull(metadatas);\n        Assert.assertFalse(metadatas.isEmpty());\n        Assert.assertNotNull(metadatas.get(0));\n        PersistenceUnitMetadata puMetadata = metadatas.get(0);\n        puMetadata.addJarFile(\"myJarFile.jar\");\n        Assert.assertNotNull(puMetadata.getJarFiles());\n        Assert.assertFalse(puMetadata.getJarFiles().isEmpty());\n        Assert.assertNotNull(puMetadata.getJarFileUrls());\n        Assert.assertFalse(puMetadata.getJarFileUrls().isEmpty());        \n    }\n    \n    @Test\n    public void testGetFields()\n    {\n        Assert.assertNotNull(metadatas);\n        Assert.assertFalse(metadatas.isEmpty());\n        Assert.assertNotNull(metadatas.get(0));\n        PersistenceUnitMetadata puMetadata = metadatas.get(0);\n        \n        Assert.assertFalse(puMetadata.getClasses().isEmpty());\n        Assert.assertTrue(puMetadata.getPackages().isEmpty());\n        List<String> classes = new ArrayList<String>(); classes.add(\"MyClass\");\n        List<String> packages = new ArrayList<String>(); packages.add(\"com.impetus.my.package\");\n        \n        puMetadata.setClasses(classes);\n        puMetadata.setPackages(packages);\n        \n        Assert.assertFalse(puMetadata.getClasses().isEmpty());\n        Assert.assertFalse(puMetadata.getPackages().isEmpty());\n        \n        Assert.assertNull(puMetadata.getJtaDataSource());\n        Assert.assertNull(puMetadata.getNonJtaDataSource());\n        Assert.assertNull(puMetadata.getMappingFileNames());\n        Assert.assertNull(puMetadata.getSharedCacheMode());\n        Assert.assertNull(puMetadata.getValidationMode());\n        Assert.assertNull(puMetadata.getNewTempClassLoader());\n        Assert.assertNotNull(puMetadata.getMappedUrl());\n        Assert.assertNotNull(puMetadata.getProperties());\n        Assert.assertTrue(puMetadata.getExcludeUnlistedClasses());\n        Assert.assertTrue(puMetadata.excludeUnlistedClasses());\n        Assert.assertEquals(0, puMetadata.getBatchSize());     \n        \n        for(PersistenceUnitMetadata pmd : metadatas)\n        {\n            try\n            {\n                pmd.getBatchSize();\n            }\n            catch (Exception e)\n            {                \n                Assert.fail(e.getMessage());\n             }\n            \n        }\n        \n    }  \n    \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/model/ProcessAnnotationsTest.java",
    "content": "package com.impetus.kundera.metadata.model;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Persistence;\nimport javax.persistence.metamodel.Metamodel;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.validator.GeneratedIdDefault;\nimport com.impetus.kundera.metadata.validator.GeneratedIdStrategyAuto;\nimport com.impetus.kundera.metadata.validator.GeneratedIdStrategyIdentity;\nimport com.impetus.kundera.metadata.validator.GeneratedIdStrategySequence;\nimport com.impetus.kundera.metadata.validator.GeneratedIdStrategyTable;\nimport com.impetus.kundera.metadata.validator.GeneratedIdWithOutSequenceGenerator;\nimport com.impetus.kundera.metadata.validator.GeneratedIdWithOutTableGenerator;\nimport com.impetus.kundera.metadata.validator.GeneratedIdWithSequenceGenerator;\nimport com.impetus.kundera.metadata.validator.GeneratedIdWithTableGenerator;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class ProcessAnnotationsTest\n{\n\n    EntityManagerFactory emf;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n    }\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"GeneratedValue,kunderatest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testProcess()\n    {\n        Metamodel metamodel = KunderaMetadataManager.getMetamodel(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), \"GeneratedValue\");\n\n        // for entity GeneratedIdDefault.\n        IdDiscriptor keyValue = ((MetamodelImpl) metamodel).getKeyValue(GeneratedIdDefault.class.getName());\n        Assert.assertNotNull(keyValue);\n        Assert.assertEquals(GenerationType.AUTO, keyValue.getStrategy());\n        Assert.assertNull(keyValue.getTableDiscriptor());\n        Assert.assertNull(keyValue.getSequenceDiscriptor());\n        keyValue = null;\n\n        // for entity GeneratedIdStrategyAuto.\n        keyValue = ((MetamodelImpl) metamodel).getKeyValue(GeneratedIdStrategyAuto.class.getName());\n        Assert.assertNotNull(keyValue);\n        Assert.assertEquals(GenerationType.AUTO, keyValue.getStrategy());\n        Assert.assertNull(keyValue.getTableDiscriptor());\n        Assert.assertNull(keyValue.getSequenceDiscriptor());\n        keyValue = null;\n\n        keyValue = ((MetamodelImpl) metamodel).getKeyValue(GeneratedIdStrategyIdentity.class.getName());\n        Assert.assertNotNull(keyValue);\n        Assert.assertEquals(GenerationType.IDENTITY, keyValue.getStrategy());\n        Assert.assertNull(keyValue.getTableDiscriptor());\n        Assert.assertNull(keyValue.getSequenceDiscriptor());\n        keyValue = null;\n\n        // for entity GeneratedIdStrategySequence.\n        keyValue = ((MetamodelImpl) metamodel).getKeyValue(GeneratedIdStrategySequence.class.getName());\n        Assert.assertNotNull(keyValue);\n        Assert.assertEquals(GenerationType.SEQUENCE, keyValue.getStrategy());\n        Assert.assertNull(keyValue.getTableDiscriptor());\n        Assert.assertNotNull(keyValue.getSequenceDiscriptor());\n        Assert.assertEquals(50, keyValue.getSequenceDiscriptor().getAllocationSize());\n        Assert.assertEquals(1, keyValue.getSequenceDiscriptor().getInitialValue());\n        Assert.assertEquals(\"KunderaTest\", keyValue.getSequenceDiscriptor().getSchemaName());\n        Assert.assertEquals(\"sequence_name\", keyValue.getSequenceDiscriptor().getSequenceName());\n        Assert.assertNull(keyValue.getSequenceDiscriptor().getCatalog());\n        keyValue = null;\n\n        // for entity GeneratedIdStrategyTable.\n        keyValue = ((MetamodelImpl) metamodel).getKeyValue(GeneratedIdStrategyTable.class.getName());\n        Assert.assertNotNull(keyValue);\n        Assert.assertEquals(GenerationType.TABLE, keyValue.getStrategy());\n        Assert.assertNull(keyValue.getSequenceDiscriptor());\n        Assert.assertNotNull(keyValue.getTableDiscriptor());\n        Assert.assertEquals(50, keyValue.getTableDiscriptor().getAllocationSize());\n        Assert.assertEquals(1, keyValue.getTableDiscriptor().getInitialValue());\n        Assert.assertEquals(\"KunderaTest\", keyValue.getTableDiscriptor().getSchema());\n        Assert.assertEquals(\"kundera_sequences\", keyValue.getTableDiscriptor().getTable());\n        Assert.assertEquals(\"sequence_name\", keyValue.getTableDiscriptor().getPkColumnName());\n        Assert.assertEquals(\"GeneratedIdStrategyTable\", keyValue.getTableDiscriptor().getPkColumnValue());\n        Assert.assertEquals(\"sequence_value\", keyValue.getTableDiscriptor().getValueColumnName());\n        Assert.assertNull(keyValue.getTableDiscriptor().getCatalog());\n        Assert.assertNull(keyValue.getTableDiscriptor().getUniqueConstraints());\n        keyValue = null;\n\n        // for entity GeneratedIdWithSequenceGenerator.\n        keyValue = ((MetamodelImpl) metamodel).getKeyValue(GeneratedIdWithSequenceGenerator.class.getName());\n        Assert.assertNotNull(keyValue);\n        Assert.assertEquals(GenerationType.SEQUENCE, keyValue.getStrategy());\n        Assert.assertNull(keyValue.getTableDiscriptor());\n        Assert.assertNotNull(keyValue.getSequenceDiscriptor());\n        Assert.assertEquals(20, keyValue.getSequenceDiscriptor().getAllocationSize());\n        Assert.assertEquals(80, keyValue.getSequenceDiscriptor().getInitialValue());\n        Assert.assertEquals(\"KunderaTest\", keyValue.getSequenceDiscriptor().getSchemaName());\n        Assert.assertEquals(\"newSequence\", keyValue.getSequenceDiscriptor().getSequenceName());\n        Assert.assertNull(keyValue.getSequenceDiscriptor().getCatalog());\n        keyValue = null;\n\n        // for entity GeneratedIdWithTableGenerator.\n        keyValue = ((MetamodelImpl) metamodel).getKeyValue(GeneratedIdWithTableGenerator.class.getName());\n        Assert.assertNotNull(keyValue);\n        Assert.assertEquals(GenerationType.TABLE, keyValue.getStrategy());\n        Assert.assertNull(keyValue.getSequenceDiscriptor());\n        Assert.assertNotNull(keyValue.getTableDiscriptor());\n        Assert.assertEquals(30, keyValue.getTableDiscriptor().getAllocationSize());\n        Assert.assertEquals(100, keyValue.getTableDiscriptor().getInitialValue());\n        Assert.assertEquals(\"KunderaTest\", keyValue.getTableDiscriptor().getSchema());\n        Assert.assertEquals(\"kundera\", keyValue.getTableDiscriptor().getTable());\n        Assert.assertEquals(\"sequence\", keyValue.getTableDiscriptor().getPkColumnName());\n        Assert.assertEquals(\"kk\", keyValue.getTableDiscriptor().getPkColumnValue());\n        Assert.assertEquals(\"sequenceValue\", keyValue.getTableDiscriptor().getValueColumnName());\n        Assert.assertNull(keyValue.getTableDiscriptor().getCatalog());\n        Assert.assertNull(keyValue.getTableDiscriptor().getUniqueConstraints());\n        keyValue = null;\n\n        // for entity GeneratedIdStrategySequence.\n        keyValue = ((MetamodelImpl) metamodel).getKeyValue(GeneratedIdWithOutSequenceGenerator.class.getName());\n        Assert.assertNotNull(keyValue);\n        Assert.assertEquals(GenerationType.SEQUENCE, keyValue.getStrategy());\n        Assert.assertNull(keyValue.getTableDiscriptor());\n        Assert.assertNotNull(keyValue.getSequenceDiscriptor());\n        Assert.assertEquals(50, keyValue.getSequenceDiscriptor().getAllocationSize());\n        Assert.assertEquals(1, keyValue.getSequenceDiscriptor().getInitialValue());\n        Assert.assertEquals(\"KunderaTest\", keyValue.getSequenceDiscriptor().getSchemaName());\n        Assert.assertEquals(\"sequence_name\", keyValue.getSequenceDiscriptor().getSequenceName());\n        Assert.assertNull(keyValue.getSequenceDiscriptor().getCatalog());\n        keyValue = null;\n\n        // for entity GeneratedIdStrategyTable.\n        keyValue = ((MetamodelImpl) metamodel).getKeyValue(GeneratedIdWithOutTableGenerator.class.getName());\n        Assert.assertNotNull(keyValue);\n        Assert.assertEquals(GenerationType.TABLE, keyValue.getStrategy());\n        Assert.assertNull(keyValue.getSequenceDiscriptor());\n        Assert.assertNotNull(keyValue.getTableDiscriptor());\n        Assert.assertEquals(50, keyValue.getTableDiscriptor().getAllocationSize());\n        Assert.assertEquals(1, keyValue.getTableDiscriptor().getInitialValue());\n        Assert.assertEquals(\"KunderaTest\", keyValue.getTableDiscriptor().getSchema());\n        Assert.assertEquals(\"kundera_sequences\", keyValue.getTableDiscriptor().getTable());\n        Assert.assertEquals(\"sequence_name\", keyValue.getTableDiscriptor().getPkColumnName());\n        Assert.assertEquals(\"GeneratedIdWithOutTableGenerator\", keyValue.getTableDiscriptor().getPkColumnValue());\n        Assert.assertEquals(\"sequence_value\", keyValue.getTableDiscriptor().getValueColumnName());\n        Assert.assertNull(keyValue.getTableDiscriptor().getCatalog());\n        Assert.assertNull(keyValue.getTableDiscriptor().getUniqueConstraints());\n        keyValue = null;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/model/TweetKundera.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.metadata.model;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\nimport com.impetus.kundera.index.Index;\r\nimport com.impetus.kundera.index.IndexCollection;\r\n\r\n/**\r\n * Class for Tweets\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\n@IndexCollection(columns = { @Index(name = \"body\"), @Index(name = \"device\") })\r\npublic class TweetKundera\r\n{\r\n\r\n    @Column(name = \"tweet_id\")\r\n    private String tweetId;\r\n\r\n    @Column(name = \"tweet_body\")\r\n    private String body;\r\n\r\n    @Column(name = \"tweeted_from\")\r\n    private String device;\r\n\r\n    // private long timestamp;\r\n\r\n    public TweetKundera(String body, String device)\r\n    {\r\n        this.tweetId = \"123\";\r\n        this.body = body;\r\n        this.device = device;\r\n        // this.timestamp = ExampleUtils.getCurrentTimestamp();\r\n    }\r\n\r\n    public TweetKundera()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * @return the tweetId\r\n     */\r\n    public String getTweetId()\r\n    {\r\n        return tweetId;\r\n    }\r\n\r\n    /**\r\n     * @param tweetId\r\n     *            the tweetId to set\r\n     */\r\n    public void setTweetId(String tweetId)\r\n    {\r\n        this.tweetId = tweetId;\r\n    }\r\n\r\n    /**\r\n     * @return the body\r\n     */\r\n    public String getBody()\r\n    {\r\n        return body;\r\n    }\r\n\r\n    /**\r\n     * @param body\r\n     *            the body to set\r\n     */\r\n    public void setBody(String body)\r\n    {\r\n        this.body = body;\r\n    }\r\n\r\n    /**\r\n     * @return the device\r\n     */\r\n    public String getDevice()\r\n    {\r\n        return device;\r\n    }\r\n\r\n    /**\r\n     * @param device\r\n     *            the device to set\r\n     */\r\n    public void setDevice(String device)\r\n    {\r\n        this.device = device;\r\n    }\r\n\r\n    /*    *//**\r\n     * @return the timestamp\r\n     */\r\n    /*\r\n     * public long getTimestamp() { return timestamp; }\r\n     *//**\r\n     * @param timestamp\r\n     *            the timestamp to set\r\n     */\r\n    /*\r\n     * public void setTimestamp(long timestamp) { this.timestamp = timestamp; }\r\n     */\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/AbstractResource.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor;\n\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Id;\nimport javax.persistence.MappedSuperclass;\n\n/**\n * @author vivek.mishra Transaction {@link MappedSuperclass}\n */\n\n@MappedSuperclass\npublic abstract class AbstractResource\n{\n\n    @Id\n    private String cprId;\n\n    @Column\n    private String resourceName;\n    \n    @Embedded\n    private CarEngine engine;\n\n    public String getCarPartResourceId()\n    {\n        return cprId;\n    }\n\n    public void setCarPartResourceId(String cprId)\n    {\n        this.cprId = cprId;\n    }\n\n    public String getCarPartResourceName()\n    {\n        return resourceName;\n    }\n\n    public void setCarPartResourceName(String resourceName)\n    {\n        this.resourceName = resourceName;\n    }\n    \n    public CarEngine getEngine()\n    {\n        return engine;\n    }\n\n    public void setEngine(CarEngine engine)\n    {\n        this.engine = engine;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/AttributeTypeTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.metadata.processor;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.gis.geometry.Point;\nimport com.impetus.kundera.metadata.model.attributes.AttributeType;\nimport com.impetus.kundera.query.Person.Day;\n\n/**\n * @author vivek.mishra\n * junit for {@link AttributeType}\n *\n */\npublic class AttributeTypeTest\n{\n\n    @Test\n    public void testGetType()\n    {\n        Assert.assertEquals(AttributeType.SET,AttributeType.getType(Set.class));\n        Assert.assertEquals(AttributeType.LIST,AttributeType.getType(List.class));\n        Assert.assertEquals(AttributeType.ENUM,AttributeType.getType(Day.class));\n        Assert.assertEquals(AttributeType.MAP,AttributeType.getType(Map.class));\n        Assert.assertEquals(AttributeType.POINT,AttributeType.getType(Point.class));\n        Assert.assertEquals(AttributeType.PRIMITIVE,AttributeType.getType(int.class));\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/CarEngine.java",
    "content": "package com.impetus.kundera.metadata.processor;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Embeddable\n@IndexCollection(columns={@Index(name=\"engineId\")})\npublic class CarEngine\n{\n\n    @Column(name = \"ENGINE_ID\")\n    private String engineId;\n\n    @Column(name = \"SERIES\")\n    private String series;\n\n  \n    public String getEngineId()\n    {\n        return engineId;\n    }\n\n    public void setEngineId(String engineId)\n    {\n        this.engineId = engineId;\n    }\n\n    public String getSeries()\n    {\n        return series;\n    }\n\n    public void setSeries(String series)\n    {\n        this.series = series;\n    }\n\n   \n\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/CarPart.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor;\n\n\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToOne;\n\n\n\n\n\n@Entity\npublic class CarPart\n{\n    @Id\n    private String id;\n\n    @ManyToOne\n    private CarPartResource resource;\n    \n \n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public CarPartResource getResource()\n    {\n        return resource;\n    }\n\n    public void setResource(CarPartResource resource)\n    {\n        this.resource = resource;\n    }\n    \n   \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/CarPartResource.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\n\n\n\n\n/**\n * @author impadmin\n * \n */\n@Entity\npublic class CarPartResource extends AbstractResource\n{\n    @Column\n    private String col;\n    \n    @Embedded\n    private CarTyre tyre;\n\n    public String getCol()\n    {\n        return col;\n    }\n\n    public void setCol(String col)\n    {\n        this.col = col;\n    }\n    \n  \n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/CarTyre.java",
    "content": "package com.impetus.kundera.metadata.processor;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Embeddable\n@IndexCollection(columns={@Index(name=\"tyreId\")})\npublic class CarTyre\n{\n\n    @Column(name = \"TYRE_ID\")\n    private String tyreId;\n\n    @Column(name = \"TYRE_TYPE\")\n    private String tyreType;\n\n  \n    public String getTyreId()\n    {\n        return tyreId;\n    }\n\n    public void setTyreId(String tyreId)\n    {\n        this.tyreId = tyreId;\n    }\n\n    public String getTyreType()\n    {\n        return tyreType;\n    }\n\n    public void setTyreType(String tyreType)\n    {\n        this.tyreType = tyreType;\n    }\n\n   \n\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/Circle.java",
    "content": "package com.impetus.kundera.metadata.processor;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\n\n@Entity\npublic class Circle extends Shape\n{\n    @Column(name = \"radius\")\n    private int radius;\n\n \n  \n    public int getRadius()\n    {\n        return radius;\n    }\n\n    public void setRadius(int radius)\n    {\n        this.radius = radius;\n    }\n\n   \n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/EntitySample.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.NamedNativeQueries;\nimport javax.persistence.NamedNativeQuery;\nimport javax.persistence.NamedQueries;\nimport javax.persistence.NamedQuery;\nimport javax.persistence.Table;\n\n/**\n * Test Entity\n * \n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"table\", schema = \"testSchema\")\n@NamedQuery(name = \"test.named.query\", query = \"Select t from TestEntity t where t.field = :field\")\n@NamedQueries({\n        @NamedQuery(name = \"test.named.queries1\", query = \"Select t1 from TestEntity t1 where t1.field = :field\"),\n        @NamedQuery(name = \"test.named.queries2\", query = \"Select t2 from TestEntity t2 where t2.field = :field\") })\n@NamedNativeQuery(name = \"test.native.query\", query = \"Select native from TestEntity native where native.field = :field\")\n@NamedNativeQueries({\n        @NamedNativeQuery(name = \"test.native.query1\", query = \"Select native1 from TestEntity native1 where native1.field = :field\"),\n        @NamedNativeQuery(name = \"test.native.query2\", query = \"Select native2 from TestEntity native2 where native2.field = :field\") })\npublic class EntitySample\n{\n\n    @Id\n    private Integer key;\n\n    @Column(name = \"field\")\n    private String field;\n\n    /**\n     * @return the key\n     */\n    public Integer getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @param key\n     *            the key to set\n     */\n    public void setKey(Integer key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the field\n     */\n    public String getField()\n    {\n        return field;\n    }\n\n    /**\n     * @param field\n     *            the field to set\n     */\n    public void setField(String field)\n    {\n        this.field = field;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/Geometry.java",
    "content": "package com.impetus.kundera.metadata.processor;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\n\n\n\n@Entity\npublic class Geometry\n{\n    @Id\n    private String geoId;\n    \n    @Column(name = \"name\")\n    private String name;\n    \n    @OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n  //  @JoinColumn(name = \"shape_id\")\n    private Shape shape;\n\n   \n    public String getGeoId()\n    {\n        return geoId;\n    }\n\n    public void setGeoId(String geoId)\n    {\n        this.geoId = geoId;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n    \n    public Shape getShape()\n    {\n        return shape;\n    }\n\n    public void setShape(Shape shape)\n    {\n        this.shape = shape;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/MetaModelBuilderForTransientEntityTest.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.metadata.processor;\n\nimport java.lang.reflect.Field;\nimport java.util.Map;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.Attribute.PersistentAttributeType;\nimport javax.persistence.metamodel.Bindable.BindableType;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.SingularAttribute;\nimport javax.persistence.metamodel.Type.PersistenceType;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.metadata.entities.EmbeddableTransientEntity;\nimport com.impetus.kundera.metadata.entities.TransientEntity;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class MetaModelBuilderForTransientEntityTest\n{\n\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(MetaModelBuilderForTransientEntityTest.class);\n\n    /** The builder. */\n    @SuppressWarnings(\"rawtypes\")\n    private MetaModelBuilder builder;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public <X extends Class, T extends Object> void setUp() throws Exception\n    {\n        builder = new MetaModelBuilder<X, T>();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        builder = null;\n    }\n\n    @Test\n    public <X extends Class, T extends Object> void testEntityWithTransientAttribute()\n    {\n\n        X clazz = (X) TransientEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        Field[] field = TransientEntity.class.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(TransientEntity.class, f);\n        }\n\n        MetaModelBuilder.class.getDeclaredFields();\n        Field embeddableField;\n        try\n        {\n            embeddableField = builder.getClass().getDeclaredField(\"embeddables\");\n            if (!embeddableField.isAccessible())\n            {\n                embeddableField.setAccessible(true);\n            }\n            Map<Class<?>, AbstractManagedType<?>> embeddables = ((Map<Class<?>, AbstractManagedType<?>>) embeddableField\n                    .get(builder));\n            Assert.assertEquals(1, embeddables.size());\n\n            Field managedTypeField = builder.getClass().getDeclaredField(\"managedType\");\n            if (!managedTypeField.isAccessible())\n            {\n                managedTypeField.setAccessible(true);\n            }\n\n            AbstractManagedType<X> managedType = assertOnManagedType(builder, managedTypeField, TransientEntity.class);\n\n            // assert on embeddable first attribute\n            SingularAttribute embeddableAttrib = managedType.getSingularAttribute(\"embeddableTransientField\");\n            assertOnEmbeddable(embeddableAttrib, EmbeddableTransientEntity.class);\n            EmbeddableType<X> embeddableType = (EmbeddableType<X>) embeddableAttrib.getType();\n            Attribute<X, String> attribute = (Attribute<X, String>) embeddableType.getAttribute(\"embeddedField\");\n            assertOnEmbeddableType(EmbeddableTransientEntity.class, attribute, embeddableType, \"embeddedField\",\n                    Float.class);\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Assert on managed type.\n     * \n     * @param <X>\n     *            the generic type\n     * @param builder\n     *            the builder\n     * @param managedTypeField\n     *            the managed type field\n     * @param clazz\n     *            the clazz\n     * @return the abstract managed type\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    private <X> AbstractManagedType<X> assertOnManagedType(MetaModelBuilder builder, Field managedTypeField,\n            Class<?> clazz) throws IllegalAccessException\n    {\n        log.info(\"Assert on managedType\");\n        AbstractManagedType<X> managedType = (AbstractManagedType<X>) managedTypeField.get(builder);\n        Assert.assertNotNull(managedType);\n        Assert.assertEquals(clazz, ((EntityType<X>) managedType).getBindableJavaType());\n        Assert.assertEquals(BindableType.ENTITY_TYPE, ((EntityType<X>) managedType).getBindableType());\n        Assert.assertEquals(PersistenceType.ENTITY, ((EntityType<X>) managedType).getPersistenceType());\n        Assert.assertEquals(clazz.getSimpleName(), ((EntityType<X>) managedType).getName());\n        Assert.assertNotSame(clazz.getDeclaredFields().length, managedType.getSingularAttributes().size());\n        Assert.assertEquals(3, managedType.getSingularAttributes().size());\n        return managedType;\n    }\n\n    /**\n     * Assert on embeddable type.\n     * \n     * @param <X>\n     *            the generic type\n     * @param entityClazz\n     *            the entity clazz\n     * @param attribute\n     *            the attribute\n     * @param embeddableType\n     *            the embeddable type\n     * @param attributeName\n     *            the attribute name\n     * @param attributeClazz\n     *            the attribute clazz\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    private <X> void assertOnEmbeddableType(Class entityClazz, Attribute<X, String> attribute,\n            EmbeddableType<X> embeddableType, String attributeName, Class attributeClazz)\n    {\n        Assert.assertNotSame(entityClazz.getDeclaredFields().length, embeddableType.getAttributes().size());\n        Assert.assertEquals(1, embeddableType.getAttributes().size());\n        Assert.assertEquals(entityClazz, embeddableType.getJavaType());\n        Attribute attributeTwo = (Attribute) embeddableType.getAttribute(attributeName);\n        Assert.assertNotNull(attribute);\n        Assert.assertEquals(attributeClazz, attributeTwo.getJavaType());\n        Assert.assertEquals(attributeName, attributeTwo.getName());\n    }\n\n    /**\n     * Assert on embeddable.\n     * \n     * @param embeddableAttrib\n     *            the embeddable attrib\n     * @param clazz\n     *            the clazz\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    private void assertOnEmbeddable(SingularAttribute embeddableAttrib, Class clazz)\n    {\n        Assert.assertNotNull(embeddableAttrib);\n        Assert.assertEquals(PersistentAttributeType.EMBEDDED, embeddableAttrib.getPersistentAttributeType());\n        Assert.assertEquals(PersistenceType.EMBEDDABLE, embeddableAttrib.getType().getPersistenceType());\n        Assert.assertEquals(clazz, embeddableAttrib.getType().getJavaType());\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/MetaModelBuilderTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor;\n\nimport java.lang.reflect.Field;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.InheritanceType;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.Attribute.PersistentAttributeType;\nimport javax.persistence.metamodel.Bindable;\nimport javax.persistence.metamodel.Bindable.BindableType;\nimport javax.persistence.metamodel.CollectionAttribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.IdentifiableType;\nimport javax.persistence.metamodel.ListAttribute;\nimport javax.persistence.metamodel.MapAttribute;\nimport javax.persistence.metamodel.PluralAttribute;\nimport javax.persistence.metamodel.SetAttribute;\nimport javax.persistence.metamodel.SingularAttribute;\nimport javax.persistence.metamodel.Type;\nimport javax.persistence.metamodel.Type.PersistenceType;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.metadata.entities.AssociationEntity;\nimport com.impetus.kundera.metadata.entities.AttributeOverrideSubClass;\nimport com.impetus.kundera.metadata.entities.CollectionTypeAssociationEntity;\nimport com.impetus.kundera.metadata.entities.EmbeddableEntity;\nimport com.impetus.kundera.metadata.entities.EmbeddableEntityTwo;\nimport com.impetus.kundera.metadata.entities.EmbeddedIdOwnerEntity;\nimport com.impetus.kundera.metadata.entities.EntityWithAttributeOverrides;\nimport com.impetus.kundera.metadata.entities.EntityWithIdAttributeOverride;\nimport com.impetus.kundera.metadata.entities.IDClassEntity;\nimport com.impetus.kundera.metadata.entities.IDClassOwnerEntity;\nimport com.impetus.kundera.metadata.entities.ListTypeAssociationEntity;\nimport com.impetus.kundera.metadata.entities.MapTypeAssociationEntity;\nimport com.impetus.kundera.metadata.entities.OToMOwnerEntity;\nimport com.impetus.kundera.metadata.entities.OToOOwnerEntity;\nimport com.impetus.kundera.metadata.entities.PluralOwnerType;\nimport com.impetus.kundera.metadata.entities.SetTypeAssociationEntity;\nimport com.impetus.kundera.metadata.entities.SingularEntity;\nimport com.impetus.kundera.metadata.entities.SingularEntityEmbeddable;\nimport com.impetus.kundera.metadata.entities.SubClassA;\nimport com.impetus.kundera.metadata.entities.SubClassB;\nimport com.impetus.kundera.metadata.entities.SubSingularEntity;\nimport com.impetus.kundera.metadata.entities.bi.AssociationBiEntity;\nimport com.impetus.kundera.metadata.entities.bi.OToOOwnerBiEntity;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractIdentifiableType;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * MetaModelBuilderTest.\n * \n * @author vivek.mishra\n * \n */\npublic class MetaModelBuilderTest\n{\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(MetaModelBuilderTest.class);\n\n    /** The builder. */\n    @SuppressWarnings(\"rawtypes\")\n    private MetaModelBuilder builder;\n\n    /**\n     * Sets the up.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     * @throws Exception\n     *             the exception\n     */\n    @SuppressWarnings(\"rawtypes\")\n    @Before\n    public <X extends Class, T extends Object> void setUp() throws Exception\n    {\n        builder = new MetaModelBuilder<X, T>();\n    }\n\n    /**\n     * Test construct.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    @Test\n    public <X extends Class, T extends Object> void testEntityWithSingularAttribute()\n    {\n        X clazz = (X) SingularEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        Field[] field = SingularEntity.class.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(SingularEntity.class, f);\n        }\n\n        try\n        {\n            Field managedTypeField = builder.getClass().getDeclaredField(\"managedType\");\n            if (!managedTypeField.isAccessible())\n            {\n                managedTypeField.setAccessible(true);\n            }\n\n            AbstractManagedType<X> managedType = assertOnManagedType(builder, managedTypeField, SingularEntity.class);\n            assertOnIdAttribute(managedType, \"key\", Integer.class);\n            // illeagaltypesTest(managedType);\n\n            // on optional attribute\n            log.info(\"Assert on optional attribute\");\n            Assert.assertEquals(\"name\", managedType.getSingularAttribute(\"name\").getName());\n            Assert.assertTrue(managedType.getSingularAttribute(\"name\").isOptional());\n            Assert.assertEquals(String.class, managedType.getSingularAttribute(\"name\").getJavaType());\n\n            Boolean found = null;\n            try\n            {\n                found = managedType.getSingularAttribute(\"name\", Integer.class) != null;\n                Assert.fail(\"should not be called\");\n            }\n            catch (IllegalArgumentException iaex)\n            {\n                log.info(\"Assert on invalid case\");\n                Assert.assertNull(found);\n            }\n\n            try\n            {\n                found = managedType.getSingularAttribute(\"name\", String.class) != null;\n                Assert.assertNotNull(found);\n                Assert.assertTrue(found);\n            }\n            catch (IllegalArgumentException iaex)\n            {\n                log.info(\"Error on positive case\");\n                Assert.fail(iaex.getMessage());\n            }\n\n            // on not optional attribute\n            Assert.assertEquals(\"field\", managedType.getSingularAttribute(\"field\").getName());\n            Assert.assertFalse(managedType.getSingularAttribute(\"field\").isOptional());\n            Assert.assertEquals(String.class, managedType.getSingularAttribute(\"field\").getJavaType());\n\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test on entity with embeddable.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    @Test\n    public <X extends Class, T extends Object> void testOnEntityWithEmbeddable()\n\n    {\n        X clazz = (X) SingularEntityEmbeddable.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        Field[] field = SingularEntityEmbeddable.class.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(SingularEntityEmbeddable.class, f);\n        }\n\n        MetaModelBuilder.class.getDeclaredFields();\n        Field embeddableField;\n        try\n        {\n            embeddableField = builder.getClass().getDeclaredField(\"embeddables\");\n            if (!embeddableField.isAccessible())\n            {\n                embeddableField.setAccessible(true);\n            }\n            Map<Class<?>, AbstractManagedType<?>> embeddables = ((Map<Class<?>, AbstractManagedType<?>>) embeddableField\n                    .get(builder));\n            Assert.assertEquals(2, embeddables.size());\n\n            Field managedTypeField = builder.getClass().getDeclaredField(\"managedType\");\n            if (!managedTypeField.isAccessible())\n            {\n                managedTypeField.setAccessible(true);\n            }\n\n            AbstractManagedType<X> managedType = assertOnManagedType(builder, managedTypeField,\n                    SingularEntityEmbeddable.class);\n\n            assertOnIdAttribute(managedType, \"key\", Integer.class);\n\n            // assert on embeddable first attribute\n            SingularAttribute embeddableAttrib = managedType.getSingularAttribute(\"embeddableEntity\");\n            assertOnEmbeddable(embeddableAttrib, EmbeddableEntity.class);\n            EmbeddableType<X> embeddableType = (EmbeddableType<X>) embeddableAttrib.getType();\n            Attribute<X, String> attribute = (Attribute<X, String>) embeddableType.getAttribute(\"embeddedField\");\n            assertOnEmbeddableType(EmbeddableEntity.class, attribute, embeddableType, \"embeddedField\", String.class);\n\n            // assert on embeddable second attribute\n            SingularAttribute embeddableAttribTwo = managedType.getSingularAttribute(\"embeddableEntityTwo\",\n                    EmbeddableEntityTwo.class);\n            EmbeddableType<X> embeddableTypeTwo = (EmbeddableType<X>) embeddableAttribTwo.getType();\n            assertOnEmbeddable(embeddableAttribTwo, EmbeddableEntityTwo.class);\n            assertOnEmbeddableType(EmbeddableEntityTwo.class, attribute, embeddableTypeTwo, \"embeddedField\",\n                    Float.class);\n\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n\n    }\n\n    /**\n     * Combined test.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    @Test\n    public <X extends Class, T extends Object> void combinedTest()\n    {\n        X clazz = (X) SingularEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        Field[] field = SingularEntity.class.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(SingularEntity.class, f);\n        }\n\n        clazz = (X) SingularEntityEmbeddable.class;\n\n        builder.process(clazz);\n        field = SingularEntityEmbeddable.class.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(SingularEntityEmbeddable.class, f);\n        }\n        Map<Class<?>, AbstractManagedType<?>> managedTypes = getManagedTypes();\n        Assert.assertEquals(2, managedTypes.size());\n    }\n\n    /**\n     * test case for 1-1 uni association.\n     * \n     * @param <X>\n     *            entity class\n     * @param <T>\n     *            field type.\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    @Test\n    public <X extends Class, T extends Object> void testOneToOneUniAssociation()\n    {\n        X clazz = (X) OToOOwnerEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        Field[] field = OToOOwnerEntity.class.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(OToOOwnerEntity.class, f);\n        }\n\n        clazz = (X) AssociationEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        field = AssociationEntity.class.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(AssociationEntity.class, f);\n\n        }\n\n        Map<Class<?>, AbstractManagedType<?>> managedTypes = getManagedTypes();\n        Assert.assertNotNull(managedTypes);\n        Assert.assertEquals(2, managedTypes.size());\n\n        // Assertion on owner Entity\n        AbstractManagedType<?> managedType = managedTypes.get(OToOOwnerEntity.class);\n        Assert.assertNotNull(managedType);\n        // Assert.assertEquals(OToOOwnerEntity.class.getDeclaredFields().length,\n        // managedType.getAttributes().size());\n        // Assert.assertEquals(OToOOwnerEntity.class.getDeclaredFields().length,\n        // managedType.getDeclaredAttributes()\n        // .size());\n\n        Assert.assertEquals(KunderaCoreUtils.countNonSyntheticFields(OToOOwnerEntity.class), managedType\n                .getAttributes().size());\n        Assert.assertEquals(KunderaCoreUtils.countNonSyntheticFields(OToOOwnerEntity.class), managedType\n                .getDeclaredAttributes().size());\n\n        assertOnIdAttribute(managedType, \"rowKey\", byte.class);\n\n        // asssert on association attribute.\n        Attribute<? super X, ?> associationAttribute = (Attribute<? super X, ?>) managedType\n                .getAttribute(\"association\");\n        Assert.assertNotNull(associationAttribute);\n        Assert.assertEquals(PersistentAttributeType.ONE_TO_ONE, associationAttribute.getPersistentAttributeType());\n        Assert.assertEquals(AssociationEntity.class, associationAttribute.getJavaType());\n        Assert.assertEquals(true, associationAttribute.isAssociation());\n        Assert.assertEquals(OToOOwnerEntity.class, associationAttribute.getDeclaringType().getJavaType());\n        Assert.assertEquals(\"association\", associationAttribute.getName());\n\n        // Assertion on AssociationEntity.\n        managedType = managedTypes.get(AssociationEntity.class);\n        Assert.assertNotNull(managedType);\n        // Assert.assertEquals(AssociationEntity.class.getDeclaredFields().length,\n        // managedType.getAttributes().size());\n        // Assert.assertEquals(AssociationEntity.class,\n        // managedType.getJavaType());\n        // Assert.assertEquals(AssociationEntity.class.getDeclaredFields().length,\n        // managedType.getDeclaredAttributes()\n        // .size());\n        Assert.assertEquals(KunderaCoreUtils.countNonSyntheticFields(AssociationEntity.class), managedType\n                .getAttributes().size());\n        Assert.assertEquals(AssociationEntity.class, managedType.getJavaType());\n        Assert.assertEquals(KunderaCoreUtils.countNonSyntheticFields(AssociationEntity.class), managedType\n                .getDeclaredAttributes().size());\n        assertOnIdAttribute(managedType, \"assoRowKey\", String.class);\n\n    }\n\n    /**\n     * test case for 1-1 uni association.\n     * \n     * @param <X>\n     *            entity class\n     * @param <T>\n     *            field type.\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    @Test\n    public <X extends Class, T extends Object> void testOneToOneBiAssociation()\n    {\n        X clazz = (X) OToOOwnerBiEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        Field[] field = OToOOwnerBiEntity.class.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(OToOOwnerBiEntity.class, f);\n        }\n\n        clazz = (X) AssociationBiEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        field = AssociationBiEntity.class.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(AssociationBiEntity.class, f);\n        }\n\n        Map<Class<?>, AbstractManagedType<?>> managedTypes = getManagedTypes();\n        Assert.assertNotNull(managedTypes);\n        Assert.assertEquals(2, managedTypes.size());\n\n        // Assertion on owner Entity\n        AbstractManagedType<?> managedType = managedTypes.get(OToOOwnerBiEntity.class);\n        Assert.assertNotNull(managedType);\n        // Assert.assertEquals(OToOOwnerBiEntity.class.getDeclaredFields().length,\n        // managedType.getAttributes().size());\n        // Assert.assertEquals(OToOOwnerBiEntity.class.getDeclaredFields().length,\n        // managedType.getDeclaredAttributes()\n        // .size());\n\n        Assert.assertEquals(KunderaCoreUtils.countNonSyntheticFields(OToOOwnerBiEntity.class), managedType\n                .getAttributes().size());\n        Assert.assertEquals(KunderaCoreUtils.countNonSyntheticFields(OToOOwnerBiEntity.class), managedType\n                .getDeclaredAttributes().size());\n\n        assertOnIdAttribute(managedType, \"rowKey\", byte.class);\n\n        // asssert on association attribute.\n        Attribute<? super X, ?> associationAttribute = (Attribute<? super X, ?>) managedType\n                .getAttribute(\"association\");\n        Assert.assertNotNull(associationAttribute);\n        Assert.assertEquals(PersistentAttributeType.ONE_TO_ONE, associationAttribute.getPersistentAttributeType());\n        Assert.assertEquals(AssociationBiEntity.class, associationAttribute.getJavaType());\n        Assert.assertEquals(true, associationAttribute.isAssociation());\n        Assert.assertEquals(OToOOwnerBiEntity.class, associationAttribute.getDeclaringType().getJavaType());\n        Assert.assertEquals(\"association\", associationAttribute.getName());\n\n        // Assertion on AssociationBiEntity.\n        managedType = managedTypes.get(AssociationBiEntity.class);\n        Assert.assertNotNull(managedType);\n        // Assert.assertEquals(AssociationBiEntity.class.getDeclaredFields().length,\n        // managedType.getAttributes().size());\n        // Assert.assertEquals(AssociationBiEntity.class,\n        // managedType.getJavaType());\n        // Assert.assertEquals(AssociationBiEntity.class.getDeclaredFields().length,\n        // managedType.getDeclaredAttributes()\n        // .size());\n\n        Assert.assertEquals(KunderaCoreUtils.countNonSyntheticFields(AssociationBiEntity.class), managedType\n                .getAttributes().size());\n        Assert.assertEquals(AssociationBiEntity.class, managedType.getJavaType());\n        Assert.assertEquals(KunderaCoreUtils.countNonSyntheticFields(AssociationBiEntity.class), managedType\n                .getDeclaredAttributes().size());\n\n        assertOnIdAttribute(managedType, \"assoRowKey\", String.class);\n\n        // assert on owner attribute\n        Attribute<? super X, ?> ownerAttribute = (Attribute<? super X, ?>) managedType.getAttribute(\"owner\");\n        Assert.assertNotNull(ownerAttribute);\n        Assert.assertEquals(PersistentAttributeType.ONE_TO_ONE, ownerAttribute.getPersistentAttributeType());\n        Assert.assertEquals(OToOOwnerBiEntity.class, ownerAttribute.getJavaType());\n        Assert.assertEquals(true, ownerAttribute.isAssociation());\n        Assert.assertEquals(AssociationBiEntity.class, ownerAttribute.getDeclaringType().getJavaType());\n        Assert.assertEquals(\"owner\", ownerAttribute.getName());\n        Assert.assertEquals(managedTypes.get(AssociationBiEntity.class), ownerAttribute.getDeclaringType());\n        Assert.assertEquals(AssociationBiEntity.class, ownerAttribute.getJavaMember().getDeclaringClass());\n        Assert.assertEquals(OToOOwnerBiEntity.class, ownerAttribute.getJavaType());\n        Assert.assertEquals(managedTypes.get(OToOOwnerBiEntity.class),\n                ((SingularAttribute<? super X, ?>) ownerAttribute).getType());\n\n    }\n\n    /**\n     * Test on collection.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    @Test\n    public <X extends Class, T extends Object> void testOnUniOneToManyCollection()\n    {\n        X clazz = (X) OToMOwnerEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        Field[] field = OToMOwnerEntity.class.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(OToMOwnerEntity.class, f);\n        }\n\n        clazz = (X) AssociationEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        field = AssociationEntity.class.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(AssociationEntity.class, f);\n        }\n        Map<Class<?>, AbstractManagedType<?>> managedTypes = getManagedTypes();\n        Assert.assertNotNull(managedTypes);\n        Assert.assertEquals(2, managedTypes.size());\n\n        // Assertion on owner Entity\n        AbstractManagedType<?> managedType = managedTypes.get(OToMOwnerEntity.class);\n        Assert.assertNotNull(managedType);\n        // Assert.assertEquals(OToMOwnerEntity.class.getDeclaredFields().length,\n        // managedType.getAttributes().size());\n        // Assert.assertEquals(OToMOwnerEntity.class.getDeclaredFields().length,\n        // managedType.getDeclaredAttributes()\n        // .size());\n\n        Assert.assertEquals(KunderaCoreUtils.countNonSyntheticFields(OToMOwnerEntity.class), managedType\n                .getAttributes().size());\n        Assert.assertEquals(KunderaCoreUtils.countNonSyntheticFields(OToMOwnerEntity.class), managedType\n                .getDeclaredAttributes().size());\n\n        assertOnIdAttribute(managedType, \"rowKey\", byte.class);\n\n        // assert on getCollection.\n        CollectionAttribute<? super X, ?> collectionAttribute = (CollectionAttribute<? super X, ?>) managedType\n                .getCollection(\"association\", AssociationEntity.class);\n        Assert.assertNotNull(collectionAttribute);\n\n        // assert on getDeclaredCollection.\n        CollectionAttribute<? super X, ?> declaredCollectionAttribute = (CollectionAttribute<? super X, ?>) managedType\n                .getDeclaredCollection(\"association\", AssociationEntity.class);\n        Assert.assertNotNull(declaredCollectionAttribute);\n\n        // assert on getDeclaredCollection.\n        CollectionAttribute<? super X, ?> declaredCollectionAttributeParam = (CollectionAttribute<? super X, ?>) managedType\n                .getDeclaredCollection(\"association\");\n        Assert.assertNotNull(declaredCollectionAttributeParam);\n\n        // assert with invalid collection type class.\n        try\n        {\n            collectionAttribute = null;\n            collectionAttribute = (CollectionAttribute<? super X, ?>) managedType.getCollection(\"association\",\n                    AssociationBiEntity.class);\n            Assert.fail();\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            log.info(\"on invalid case with getCollection\");\n            Assert.assertNull(collectionAttribute);\n        }\n\n        try\n        {\n            collectionAttribute = null;\n            collectionAttribute = (CollectionAttribute<? super X, ?>) managedType.getCollection(\"associationInvalid\");\n            Assert.fail();\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            log.info(\"on invalid case with getCollection\");\n            Assert.assertNull(collectionAttribute);\n        }\n        // asssert on association attribute.\n        Attribute<? super X, ?> associationAttribute = (Attribute<? super X, ?>) managedType\n                .getAttribute(\"association\");\n        Assert.assertNotNull(associationAttribute);\n        Assert.assertEquals(PersistentAttributeType.ONE_TO_MANY, associationAttribute.getPersistentAttributeType());\n        Assert.assertEquals(Collection.class, associationAttribute.getJavaType());\n        Assert.assertEquals(AssociationEntity.class, ((Bindable) associationAttribute).getBindableJavaType());\n        Assert.assertEquals(true, associationAttribute.isAssociation());\n        Assert.assertEquals(OToMOwnerEntity.class, associationAttribute.getDeclaringType().getJavaType());\n        Assert.assertEquals(\"association\", associationAttribute.getName());\n    }\n\n    /**\n     * Test on list.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     */\n    @SuppressWarnings(\"unchecked\")\n    @Test\n    public <X extends Class, T extends Object> void testOnAllUniPlural()\n    {\n        X clazz = (X) PluralOwnerType.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        Field[] field = PluralOwnerType.class.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(PluralOwnerType.class, f);\n        }\n\n        onCollectionAssociation((X) SetTypeAssociationEntity.class);\n\n        onCollectionAssociation((X) ListTypeAssociationEntity.class);\n\n        onCollectionAssociation((X) MapTypeAssociationEntity.class);\n\n        onCollectionAssociation((X) CollectionTypeAssociationEntity.class);\n\n        Map<Class<?>, AbstractManagedType<?>> managedTypes = getManagedTypes();\n        Assert.assertNotNull(managedTypes);\n        Assert.assertEquals(5, managedTypes.size());\n\n        // assert on set association entity.\n        AbstractManagedType<? super X> managedType = (AbstractManagedType<? super X>) managedTypes\n                .get(SetTypeAssociationEntity.class);\n        assertOnCollectionAttribute(managedType, \"setKey\", \"bytes\", SetTypeAssociationEntity.class);\n\n        // assert on map association entity.\n        managedType = (AbstractManagedType<? super X>) managedTypes.get(MapTypeAssociationEntity.class);\n        assertOnCollectionAttribute(managedType, \"mapKey\", \"bytes\", MapTypeAssociationEntity.class);\n\n        // assert on map association entity.\n        managedType = (AbstractManagedType<? super X>) managedTypes.get(CollectionTypeAssociationEntity.class);\n        assertOnCollectionAttribute(managedType, \"colKey\", \"bytes\", CollectionTypeAssociationEntity.class);\n\n        // assert on map association entity.\n        managedType = (AbstractManagedType<? super X>) managedTypes.get(ListTypeAssociationEntity.class);\n        assertOnCollectionAttribute(managedType, \"listKey\", \"bytes\", ListTypeAssociationEntity.class);\n\n        // Assert on owner class.\n        managedType = (AbstractManagedType<? super X>) managedTypes.get(PluralOwnerType.class);\n        assertOnOwnerTypeAttributes(managedType, \"setAssocition\", SetTypeAssociationEntity.class, Set.class);\n        assertOnOwnerTypeAttributes(managedType, \"listAssociation\", ListTypeAssociationEntity.class, List.class);\n        assertOnOwnerTypeAttributes(managedType, \"collectionAssociation\", CollectionTypeAssociationEntity.class,\n                Collection.class);\n        assertOnOwnerTypeAttributes(managedType, \"mapAssociation\", MapTypeAssociationEntity.class, Map.class);\n\n        // Assert on set attribute class.\n        assertOnSetAttribute(managedType, \"setAssocition\", SetTypeAssociationEntity.class, Set.class);\n        // Assert on list attribute class.\n        assertOnListAttribute(managedType, \"listAssociation\", ListTypeAssociationEntity.class, List.class);\n        // Assert on map attribute class.\n        assertOnMapAttribute(managedType, \"mapAssociation\", Integer.class, MapTypeAssociationEntity.class);\n\n    }\n\n    /**\n     * On id class test.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     */\n    @Test\n    public <X extends Class, T extends Object> void onIdClassTest()\n    {\n        X clazz = (X) IDClassOwnerEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        Field[] field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n\n        Map<Class<?>, AbstractManagedType<?>> managedTypes = getManagedTypes();\n        Assert.assertNotNull(managedTypes);\n        Assert.assertEquals(1, managedTypes.size());\n        AbstractManagedType managedType = managedTypes.get(IDClassOwnerEntity.class);\n        Assert.assertNotNull(managedType);\n        Assert.assertEquals(2, managedType.getAttributes().size());\n        Attribute idAttribute = managedType.getAttribute(\"id\");\n\n        SingularAttribute idAttrib = null;\n        try\n        {\n            idAttrib = ((IdentifiableType) managedType).getId(IDClassEntity.class);\n            Assert.fail();\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertNull(idAttrib);\n        }\n        Assert.assertEquals(2, ((IdentifiableType) managedType).getIdClassAttributes().size());\n        Assert.assertNotNull(idAttribute);\n        Assert.assertTrue(((SingularAttribute) idAttribute).isId());\n    }\n\n    /**\n     * On embedded id test.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     */\n    @Test\n    public <X extends Class, T extends Object> void onEmbeddedIdTest()\n    {\n        X clazz = (X) EmbeddedIdOwnerEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        Field[] field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n\n        Map<Class<?>, AbstractManagedType<?>> managedTypes = getManagedTypes();\n        Assert.assertNotNull(managedTypes);\n        Assert.assertEquals(1, managedTypes.size());\n        AbstractManagedType managedType = managedTypes.get(clazz);\n        Assert.assertNotNull(managedType);\n        Assert.assertEquals(2, managedType.getAttributes().size());\n        Attribute idAttribute = managedType.getAttribute(\"id\");\n\n        SingularAttribute idAttrib = null;\n        try\n        {\n            idAttrib = ((IdentifiableType) managedType).getId(EmbeddableEntity.class);\n            Assert.fail();\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertNull(idAttrib);\n        }\n        Assert.assertEquals(1, ((IdentifiableType) managedType).getIdClassAttributes().size());\n        Assert.assertNotNull(idAttribute);\n        Assert.assertTrue(((SingularAttribute) idAttribute).isId());\n    }\n\n    /**\n     * Test mapped super class.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     */\n    @Test\n    public <X extends Class, T extends Object> void testMappedSuperClass()\n    {\n        X clazz = (X) SubClassA.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        Field[] field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n\n        clazz = (X) SubClassB.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n\n        Map<Class<?>, AbstractManagedType<?>> managedTypes = getManagedTypes();\n        Assert.assertNotNull(managedTypes);\n        Assert.assertEquals(2, managedTypes.size());\n\n        Assert.assertEquals(1, builder.getMappedSuperClassTypes().size());\n\n        // on subClass A\n        AbstractManagedType managedType = managedTypes.get(SubClassA.class);\n        Assert.assertNotNull(managedType);\n        Assert.assertEquals(5, managedType.getAttributes().size());\n        Assert.assertNotNull(managedType.getAttribute(\"mappedInt\"));\n        Assert.assertNotNull(managedType.getSingularAttribute(\"mappedInt\", int.class));\n\n        // on subClass A\n        managedType = managedTypes.get(SubClassB.class);\n        Assert.assertNotNull(managedType);\n        Assert.assertEquals(5, managedType.getAttributes().size());\n        Assert.assertNotNull(managedType.getAttribute(\"mappedInt\"));\n        Assert.assertNotNull(managedType.getSingularAttribute(\"mappedInt\", int.class));\n    }\n    \n    /**\n     * Test mapped super class.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     */\n    @Test\n    public <X extends Class, T extends Object> void testAssociationMappedSuperClass()\n    {\n        X clazz = (X) CarPart.class;\n      \n        builder.process(clazz);\n        \n        Map<Class<?>, AbstractManagedType<?>> managedTypes = getManagedTypes();\n        Assert.assertNotNull(managedTypes);\n        Assert.assertEquals(0, builder.getMappedSuperClassTypes().size());\n        \n        Field[] field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n\n        clazz = (X) CarPartResource.class;\n       \n        builder.process(clazz);\n        field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n\n        managedTypes = getManagedTypes();\n        Assert.assertNotNull(managedTypes);\n        Assert.assertEquals(2, managedTypes.size());\n\n        Assert.assertEquals(1, builder.getMappedSuperClassTypes().size());\n\n        // on class CarPart\n        AbstractManagedType managedType = managedTypes.get(CarPart.class);\n        Assert.assertNotNull(managedType);\n        Assert.assertEquals(2, managedType.getAttributes().size());\n    \n\n        // on class CarPartResource\n        managedType = managedTypes.get(CarPartResource.class);\n        Assert.assertNotNull(managedType);\n        Assert.assertEquals(5, managedType.getAttributes().size());\n       \n    }\n    \n    /**\n     * Test mapped super class.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     */\n    @Test\n    public <X extends Class, T extends Object> void testEmbeddableForMappedSuperClass()\n    {\n        Field embeddableField;\n        \n        X clazz = (X) CarPart.class;\n      \n        builder.process(clazz);\n        \n        Map<Class<?>, AbstractManagedType<?>> managedTypes = getManagedTypes();\n        Assert.assertNotNull(managedTypes);\n        Assert.assertEquals(0, builder.getMappedSuperClassTypes().size());\n     \n        \n        Field[] field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n\n        clazz = (X) CarPartResource.class;\n       \n        builder.process(clazz);\n        field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n\n        managedTypes = getManagedTypes();\n        Assert.assertNotNull(managedTypes);\n        Assert.assertEquals(2, managedTypes.size());\n\n       \n        Assert.assertEquals(1, builder.getMappedSuperClassTypes().size());\n\n       \n    \n\n        // on class CarPartResource\n        AbstractManagedType managedType = managedTypes.get(CarPartResource.class);\n        Assert.assertNotNull(managedType);\n       \n        \n       \n        \n        try\n        {\n            embeddableField = builder.getClass().getDeclaredField(\"embeddables\");\n         \n            if (!embeddableField.isAccessible())\n            {\n                embeddableField.setAccessible(true);\n            }\n            Map<Class<?>, AbstractManagedType<?>> embeddables = ((Map<Class<?>, AbstractManagedType<?>>) embeddableField\n                    .get(builder));\n            Assert.assertEquals(2, embeddables.size());\n\n            Field managedTypeField = builder.getClass().getDeclaredField(\"managedType\");\n            if (!managedTypeField.isAccessible())\n            {\n                managedTypeField.setAccessible(true);\n            }\n\n         \n\n            // assert on embeddable first attribute\n            SingularAttribute embeddableAttrib = managedType.getSingularAttribute(\"engine\");\n            assertOnEmbeddable(embeddableAttrib, CarEngine.class);\n            EmbeddableType<X> embeddableType = (EmbeddableType<X>) embeddableAttrib.getType();\n            Attribute<X, String> attribute = (Attribute<X, String>) embeddableType.getAttribute(\"engineId\");\n            assertOnEmbeddableType(CarEngine.class, attribute, embeddableType, \"engineId\", String.class);\n\n           \n\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n       \n    }\n\n\n    @Test\n    public <X extends Class, T extends Object> void testAttributeOverride()\n    {\n\n        X clazz = (X) AttributeOverrideSubClass.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        Field[] field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n\n        clazz = (X) EntityWithAttributeOverrides.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n\n        Map<Class<?>, AbstractManagedType<?>> managedTypes = getManagedTypes();\n        Assert.assertNotNull(managedTypes);\n        Assert.assertEquals(2, managedTypes.size());\n\n        Assert.assertEquals(1, builder.getMappedSuperClassTypes().size());\n\n        // on subClass EntityWithAttributeOverrides\n        AbstractManagedType managedType = managedTypes.get(EntityWithAttributeOverrides.class);\n        Assert.assertNotNull(managedType);\n        Assert.assertEquals(5, managedType.getAttributes().size());\n        Assert.assertNotNull(managedType.getAttribute(\"mappedInt\"));\n\n        String jpaName1 = ((AbstractAttribute<X, T>) managedType.getAttribute(\"mappedInt\")).getJPAColumnName();\n\n        String jpaName2 = ((AbstractAttribute<X, T>) managedType.getAttribute(\"mappedFloat\")).getJPAColumnName();\n\n        Assert.assertEquals(\"MAPPED_INT\", jpaName1);\n        Assert.assertEquals(\"MAPPED_FLOAT\", jpaName2);\n\n        Assert.assertNotNull(managedType.getSingularAttribute(\"mappedInt\", int.class));\n\n        // on subClass AttributeOverrideSubClass\n        managedType = managedTypes.get(AttributeOverrideSubClass.class);\n\n        jpaName1 = ((AbstractAttribute<X, T>) managedType.getAttribute(\"mappedInt\")).getJPAColumnName();\n\n        jpaName2 = ((AbstractAttribute<X, T>) managedType.getAttribute(\"mappedFloat\")).getJPAColumnName();\n\n        Assert.assertEquals(\"MAPPED_INT\", jpaName1);\n        Assert.assertEquals(\"mappedFloat\", jpaName2);\n\n        Assert.assertNotNull(managedType);\n        Assert.assertEquals(5, managedType.getAttributes().size());\n        Assert.assertNotNull(managedType.getAttribute(\"mappedInt\"));\n        Assert.assertNotNull(managedType.getSingularAttribute(\"mappedInt\", int.class));\n\n        clazz = (X) EntityWithIdAttributeOverride.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n\n        managedType = managedTypes.get(EntityWithIdAttributeOverride.class);\n\n        jpaName1 = ((AbstractAttribute<X, T>) managedType.getAttribute(\"id\")).getJPAColumnName();\n\n        jpaName2 = ((AbstractAttribute<X, T>) managedType.getAttribute(\"mappedFloat\")).getJPAColumnName();\n\n        String jpaName3 = ((AbstractAttribute<X, T>) managedType.getAttribute(\"mappedInt\")).getJPAColumnName();\n\n        Assert.assertEquals(\"ID_ATTRIB\", jpaName1);\n        Assert.assertEquals(\"MAPPED_FLOAT\", jpaName2);\n        Assert.assertEquals(\"mappedInt\", jpaName3);\n\n    }\n\n    @Test\n    public <X extends Class, T extends Object> void testInheritenceStrategy()\n    {\n        X clazz = (X) SubSingularEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        Field[] field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n        \n        EntityType<X> managedType = (EntityType<X>) builder.getManagedTypes().get(SubSingularEntity.class);\n        \n        InheritanceType type = ((AbstractManagedType<X>)managedType).getInheritenceType();\n        \n        Assert.assertEquals(InheritanceType.TABLE_PER_CLASS, type);\n        \n        \n         clazz = (X) SingularEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n        \n    }\n\n    /**\n     * Assert on owner type attributes.\n     * \n     * @param managedType\n     *            the managed type\n     * @param fieldName\n     *            the field name\n     * @param fieldClazz\n     *            the field clazz\n     * @param javaClazz\n     *            the java clazz\n     */\n    private void assertOnOwnerTypeAttributes(AbstractManagedType managedType, String fieldName, Class fieldClazz,\n            Class javaClazz)\n    {\n        Assert.assertNotNull(managedType);\n        Assert.assertNotNull(managedType.getPluralAttributes());\n        Assert.assertEquals(4, managedType.getPluralAttributes().size());\n        Assert.assertNotNull(managedType.getAttribute(fieldName));\n        Assert.assertEquals(javaClazz, managedType.getAttribute(fieldName).getJavaType());\n        Assert.assertEquals(fieldClazz, ((PluralAttribute) managedType.getAttribute(fieldName)).getElementType()\n                .getJavaType());\n        Assert.assertEquals(BindableType.PLURAL_ATTRIBUTE,\n                ((PluralAttribute) managedType.getAttribute(fieldName)).getBindableType());\n        Assert.assertNotNull(((PluralAttribute) managedType.getAttribute(fieldName)).getJavaMember());\n        Assert.assertNotNull(fieldName, ((PluralAttribute) managedType.getAttribute(fieldName)).getJavaMember()\n                .getName());\n\n    }\n\n    /**\n     * Assert on collection attribute.\n     * \n     * @param <X>\n     *            the generic type\n     * @param managedType\n     *            the managed type\n     * @param id\n     *            the id\n     * @param otherAttribute\n     *            the other attribute\n     * @param clazz\n     *            the clazz\n     */\n    private <X> void assertOnCollectionAttribute(AbstractManagedType<? super X> managedType, String id,\n            String otherAttribute, Class clazz)\n    {\n        Assert.assertNotNull(managedType);\n        Assert.assertEquals(clazz, managedType.getJavaType());\n        SingularAttribute<? super X, String> rowId = (SingularAttribute<? super X, String>) managedType\n                .getDeclaredSingularAttribute(id);\n        Assert.assertNotNull(rowId);\n        Assert.assertTrue(rowId.isId());\n        Assert.assertEquals(String.class, rowId.getBindableJavaType());\n        // other attribute\n        SingularAttribute<? super X, String> byteAttribute = (SingularAttribute<? super X, String>) managedType\n                .getDeclaredAttribute(otherAttribute);\n        Assert.assertNotNull(byteAttribute);\n        Assert.assertFalse(byteAttribute.isId());\n        Assert.assertEquals(byte[].class, byteAttribute.getBindableJavaType());\n\n    }\n\n    /**\n     * On collection association.\n     * \n     * @param <X>\n     *            the generic type\n     * @param clazz\n     *            the clazz\n     */\n    private <X extends Class> void onCollectionAssociation(X clazz)\n    {\n        Field[] field;\n        // X clazz = (X) SetTypeAssociationEntity.class;\n        // MetaModelBuilder builder = new MetaModelBuilder<X, T>();\n        builder.process(clazz);\n        field = clazz.getDeclaredFields();\n        for (Field f : field)\n        {\n            builder.construct(clazz, f);\n        }\n    }\n\n    /**\n     * Assert on embeddable type.\n     * \n     * @param <X>\n     *            the generic type\n     * @param entityClazz\n     *            the entity clazz\n     * @param attribute\n     *            the attribute\n     * @param embeddableType\n     *            the embeddable type\n     * @param attributeName\n     *            the attribute name\n     * @param attributeClazz\n     *            the attribute clazz\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    private <X> void assertOnEmbeddableType(Class entityClazz, Attribute<X, String> attribute,\n            EmbeddableType<X> embeddableType, String attributeName, Class attributeClazz)\n    {\n        // Assert.assertEquals(entityClazz.getDeclaredFields().length,\n        // embeddableType.getAttributes().size());\n        Assert.assertEquals(KunderaCoreUtils.countNonSyntheticFields(entityClazz), embeddableType.getAttributes()\n                .size());\n        Assert.assertEquals(entityClazz, embeddableType.getJavaType());\n        Attribute attributeTwo = (Attribute) embeddableType.getAttribute(attributeName);\n        Assert.assertNotNull(attribute);\n        Assert.assertEquals(attributeClazz, attributeTwo.getJavaType());\n        Assert.assertEquals(attributeName, attributeTwo.getName());\n    }\n\n    /**\n     * Assert on embeddable.\n     * \n     * @param embeddableAttrib\n     *            the embeddable attrib\n     * @param clazz\n     *            the clazz\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    private void assertOnEmbeddable(SingularAttribute embeddableAttrib, Class clazz)\n    {\n        Assert.assertNotNull(embeddableAttrib);\n        Assert.assertEquals(PersistentAttributeType.EMBEDDED, embeddableAttrib.getPersistentAttributeType());\n        Assert.assertEquals(PersistenceType.EMBEDDABLE, embeddableAttrib.getType().getPersistenceType());\n        Assert.assertEquals(clazz, embeddableAttrib.getType().getJavaType());\n    }\n\n    /**\n     * Assert on managed type.\n     * \n     * @param <X>\n     *            the generic type\n     * @param builder\n     *            the builder\n     * @param managedTypeField\n     *            the managed type field\n     * @param clazz\n     *            the clazz\n     * @return the abstract managed type\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    private <X> AbstractManagedType<X> assertOnManagedType(MetaModelBuilder builder, Field managedTypeField,\n            Class<?> clazz) throws IllegalAccessException\n    {\n        log.info(\"Assert on managedType\");\n        AbstractManagedType<X> managedType = (AbstractManagedType<X>) managedTypeField.get(builder);\n        Assert.assertNotNull(managedType);\n        Assert.assertEquals(clazz, ((EntityType<X>) managedType).getBindableJavaType());\n        Assert.assertEquals(BindableType.ENTITY_TYPE, ((EntityType<X>) managedType).getBindableType());\n        Assert.assertEquals(PersistenceType.ENTITY, ((EntityType<X>) managedType).getPersistenceType());\n        Assert.assertEquals(clazz.getSimpleName(), ((EntityType<X>) managedType).getName());\n        // Assert.assertEquals(clazz.getDeclaredFields().length,\n        // managedType.getSingularAttributes().size());\n        Assert.assertEquals(KunderaCoreUtils.countNonSyntheticFields(clazz), managedType.getSingularAttributes()\n                .size());\n        return managedType;\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        builder = null;\n    }\n\n    /**\n     * Assert on id attribute.\n     * \n     * @param <X>\n     *            the generic type\n     * @param managedType\n     *            the managed type\n     * @param key\n     *            the key\n     * @param clazz\n     *            the clazz\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    private <X> void assertOnIdAttribute(AbstractManagedType<X> managedType, String key, Class clazz)\n    {\n        // assert on id attribute.\n        log.info(\"Assert on id attribute\");\n        Assert.assertEquals(key, managedType.getSingularAttribute(key).getName());\n        Assert.assertTrue(((AbstractIdentifiableType<X>) managedType).hasSingleIdAttribute());\n\n        SingularAttribute<? super X, Integer> idAttribute = ((AbstractIdentifiableType<X>) managedType).getId(clazz);\n\n        Assert.assertNotNull(idAttribute);\n        Assert.assertTrue(idAttribute.isId());\n        Assert.assertFalse(idAttribute.isOptional());\n        Assert.assertEquals(idAttribute.getName(), key);\n        Assert.assertEquals(clazz, idAttribute.getJavaType());\n\n        SingularAttribute<? super X, Integer> idAttributeDeclared = ((AbstractIdentifiableType<X>) managedType)\n                .getDeclaredId(clazz);\n\n        Assert.assertNotNull(idAttributeDeclared);\n        Assert.assertTrue(idAttributeDeclared.isId());\n        Assert.assertFalse(idAttributeDeclared.isOptional());\n        Assert.assertEquals(idAttributeDeclared.getName(), key);\n        Assert.assertEquals(clazz, idAttributeDeclared.getJavaType());\n\n        Type<?> idType = ((AbstractIdentifiableType<X>) managedType).getIdType();\n        Assert.assertNotNull(idType);\n\n        IdentifiableType<? super X> idIdentifiableType = ((AbstractIdentifiableType<X>) managedType).getSupertype();\n        Assert.assertNull(idIdentifiableType);\n\n    }\n\n    /**\n     * Assert on set attributes.\n     * \n     * @param managedType\n     *            the managed type\n     * @param fieldName\n     *            the field name\n     * @param fieldClazz\n     *            the field clazz\n     * @param javaClazz\n     *            the java clazz\n     */\n    private <X> void assertOnSetAttribute(AbstractManagedType<? super X> managedType, String fieldName,\n            Class fieldClazz, Class javaClazz)\n    {\n        SetAttribute<? super X, ?> rowSetId = (SetAttribute<? super X, ?>) managedType.getSet(fieldName);\n        Assert.assertNotNull(rowSetId);\n        Assert.assertEquals(rowSetId.getName(), fieldName);\n        Assert.assertEquals(Set.class, rowSetId.getJavaType());\n\n        SetAttribute<? super X, ?> rowDeclaredId = (SetAttribute<? super X, ?>) managedType.getDeclaredSet(fieldName);\n        Assert.assertNotNull(rowDeclaredId);\n        Assert.assertEquals(rowDeclaredId.getName(), fieldName);\n        Assert.assertEquals(Set.class, rowDeclaredId.getJavaType());\n\n        SetAttribute<? super X, ?> rowClassSetId = (SetAttribute<? super X, ?>) managedType.getSet(fieldName,\n                fieldClazz);\n        Assert.assertNotNull(rowClassSetId);\n        Assert.assertEquals(rowClassSetId.getName(), fieldName);\n        Assert.assertEquals(Set.class, rowClassSetId.getJavaType());\n\n        SetAttribute<? super X, ?> rowClassDeclaredId = (SetAttribute<? super X, ?>) managedType.getDeclaredSet(\n                fieldName, fieldClazz);\n        Assert.assertNotNull(rowClassSetId);\n        Assert.assertEquals(rowClassDeclaredId.getName(), fieldName);\n        Assert.assertEquals(Set.class, rowClassDeclaredId.getJavaType());\n\n    }\n\n    /**\n     * Assert on List attributes.\n     * \n     * @param managedType\n     *            the managed type\n     * @param fieldName\n     *            the field name\n     * @param fieldClazz\n     *            the field clazz\n     * @param javaClazz\n     *            the java clazz\n     */\n    private <X> void assertOnListAttribute(AbstractManagedType<? super X> managedType, String fieldName,\n            Class fieldClazz, Class javaClazz)\n    {\n        ListAttribute<? super X, ?> rowListId = (ListAttribute<? super X, ?>) managedType.getList(fieldName);\n        Assert.assertNotNull(rowListId);\n        Assert.assertEquals(rowListId.getName(), fieldName);\n        Assert.assertEquals(List.class, rowListId.getJavaType());\n\n        ListAttribute<? super X, ?> listDeclaredId = (ListAttribute<? super X, ?>) managedType\n                .getDeclaredList(fieldName);\n        Assert.assertNotNull(listDeclaredId);\n        Assert.assertEquals(listDeclaredId.getName(), fieldName);\n        Assert.assertEquals(List.class, listDeclaredId.getJavaType());\n\n        ListAttribute<? super X, ?> listClassSetId = (ListAttribute<? super X, ?>) managedType.getList(fieldName,\n                fieldClazz);\n        Assert.assertNotNull(listClassSetId);\n        Assert.assertEquals(listClassSetId.getName(), fieldName);\n        Assert.assertEquals(List.class, listClassSetId.getJavaType());\n\n        ListAttribute<? super X, ?> listClassDeclaredId = (ListAttribute<? super X, ?>) managedType.getDeclaredList(\n                fieldName, fieldClazz);\n        Assert.assertNotNull(listClassDeclaredId);\n        Assert.assertEquals(listClassDeclaredId.getName(), fieldName);\n        Assert.assertEquals(List.class, listClassDeclaredId.getJavaType());\n\n    }\n\n    /**\n     * Assert on Map attributes.\n     * \n     * @param managedType\n     *            the managed type\n     * @param fieldName\n     *            the field name\n     * @param fieldClazz\n     *            the field clazz\n     * @param javaClazz\n     *            the java clazz\n     */\n    private <X> void assertOnMapAttribute(AbstractManagedType<? super X> managedType, String fieldName,\n            Class fieldClazz, Class javaClazz)\n    {\n        MapAttribute<? super X, ?, ?> mapSetId = (MapAttribute<? super X, ?, ?>) managedType.getMap(fieldName);\n        Assert.assertNotNull(mapSetId);\n        Assert.assertEquals(mapSetId.getName(), fieldName);\n        Assert.assertEquals(Map.class, mapSetId.getJavaType());\n\n        MapAttribute<? super X, ?, ?> mapDeclaredId = (MapAttribute<? super X, ?, ?>) managedType\n                .getDeclaredMap(fieldName);\n        Assert.assertNotNull(mapDeclaredId);\n        Assert.assertEquals(mapDeclaredId.getName(), fieldName);\n        Assert.assertEquals(Map.class, mapDeclaredId.getJavaType());\n\n        /*\n         * MapAttribute<? super X, ?, ?> rowClassSetId = (MapAttribute<? super\n         * X, ?, ?>) managedType .getMap(fieldName,int.class,String.class);\n         * Assert.assertNotNull(rowClassSetId);\n         * \n         * \n         * MapAttribute<? super X, ?, ?> rowClassDeclaredId = (MapAttribute<?\n         * super X, ?, ?> ) managedType .getDeclaredMap(fieldName, fieldClazz,\n         * javaClazz); Assert.assertNotNull(rowClassSetId);\n         */\n\n    }\n\n    /**\n     * Gets the managed types.\n     * \n     * @return the managed types\n     */\n    @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n    private Map<Class<?>, AbstractManagedType<?>> getManagedTypes()\n    {\n        try\n        {\n            Field managedTypesFields = builder.getClass().getDeclaredField(\"managedTypes\");\n            if (!managedTypesFields.isAccessible())\n            {\n                managedTypesFields.setAccessible(true);\n            }\n\n            return ((Map<Class<?>, AbstractManagedType<?>>) managedTypesFields.get(builder));\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        return null;\n    }\n\n    /**\n     * On embedded id test.\n     * \n     * @param <X>\n     *            the generic type\n     * @param <T>\n     *            the generic type\n     */\n\n    private <X> void illeagaltypesTest(AbstractManagedType<X> managedType)\n    {\n        try\n        {\n\n            SingularAttribute<? super X, Double> idNullAttribute = ((AbstractIdentifiableType<X>) managedType)\n                    .getId(Double.class);\n\n        }\n\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/Polygon.java",
    "content": "package com.impetus.kundera.metadata.processor;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\n\n@Entity\npublic class Polygon extends Shape\n{\n    \n    @Column(name = \"sides\")\n    private int sides;\n\n    @Column(name = \"type\")\n    private String type;\n\n  \n    public int getSides()\n    {\n        return sides;\n    }\n\n    public void setSides(int sides)\n    {\n        this.sides = sides;\n    }\n\n    public String getType()\n    {\n        return type;\n    }\n\n    public void setgetType(String type)\n    {\n        this.type = type;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/Rectangle.java",
    "content": "package com.impetus.kundera.metadata.processor;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\n\n\n@Entity\npublic class Rectangle extends Polygon\n{\n   \n    @Column(name = \"length\")\n    private int length;\n\n    @Column(name = \"breadth\")\n    private int breadth;\n    \n     \n    public int getLength()\n    {\n        return length;\n    }\n\n    public void setLength(int length)\n    {\n        this.length = length;\n    }\n\n    public int getBreadth()\n    {\n        return breadth;\n    }\n\n    public void setBreadth(int breadth)\n    {\n        this.breadth = breadth;\n    }\n    \n    \n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/Shape.java",
    "content": "package com.impetus.kundera.metadata.processor;\n/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.validation.constraints.NotNull;\n\n\n\n@Entity\npublic class Shape\n{\n    \n    @Id\n    @Column(name = \"shape_id\")\n    private String id;\n    \n    @Column(name = \"name\")\n    @NotNull(message=\"Name of the object should be defined\")\n    private String name;\n    \n    @OneToOne(mappedBy = \"shape\",fetch = FetchType.EAGER)\n    private Geometry geometry;\n\n   \n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n    \n    public Geometry getGeometry()\n    {\n        return geometry;\n    }\n\n    public void setGeometry(Geometry geometry)\n    {\n        this.geometry = geometry;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/TableProcessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.processor;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.CoreTestClient;\nimport com.impetus.kundera.metadata.MetadataBuilder;\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * Junit Test case for @See TableProcessor.\n * \n * @author vivek.mishra\n * \n */\npublic class TableProcessorTest\n{\n\n    private EntityManagerFactory emf;\n\n    private KunderaMetadata kunderaMetadata;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"kunderatest\");\n        kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n    }\n\n    /**\n     * Test process query metadata.\n     * \n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    @Test\n    public void testProcessQueryMetadata() throws InstantiationException, IllegalAccessException\n    {\n        final String persistenceUnit = \"rdbms\";\n        final String named_query = \"Select t from TestEntity t where t.field = :field\";\n        final String named_query1 = \"Select t1 from TestEntity t1 where t1.field = :field\";\n        final String named_query2 = \"Select t2 from TestEntity t2 where t2.field = :field\";\n        final String native_query = \"Select native from TestEntity native where native.field = :field\";\n        final String native_query1 = \"Select native1 from TestEntity native1 where native1.field = :field\";\n        final String native_query2 = \"Select native2 from TestEntity native2 where native2.field = :field\";\n\n        EntityMetadata metadata = new EntityMetadata(EntitySample.class);\n        metadata.setPersistenceUnit(\"rdbms\");\n\n        PersistenceUnitMetadata puMetadata = new PersistenceUnitMetadata();\n        puMetadata.setPersistenceUnitName(persistenceUnit);\n\n        Map<String, Object> props = new HashMap<String, Object>();\n        props.put(Constants.PERSISTENCE_UNIT_NAME, persistenceUnit);\n        props.put(PersistenceProperties.KUNDERA_NODES, \"localhost\");\n        props.put(PersistenceProperties.KUNDERA_PORT, \"9160\");\n        props.put(PersistenceProperties.KUNDERA_KEYSPACE, \"KunderaHbaseExamples\");\n        props.put(PersistenceProperties.KUNDERA_CLIENT_FACTORY, \"com.impetus.client.CoreTestClientFactory\");\n\n        Properties p = new Properties();\n        p.putAll(props);\n        puMetadata.setProperties(p);\n\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\n\n        Map<String, PersistenceUnitMetadata> metadataCol = new HashMap<String, PersistenceUnitMetadata>();\n\n        metadataCol.put(persistenceUnit, puMetadata);\n        appMetadata.addPersistenceUnitMetadata(metadataCol);\n\n        MetadataBuilder metadataBuilder = new MetadataBuilder(persistenceUnit, CoreTestClient.class.getSimpleName(),\n                null, kunderaMetadata);\n        metadataBuilder.buildEntityMetadata(metadata.getEntityClazz());\n\n        // Named query asserts.\n        Assert.assertNotNull(appMetadata.getQuery(\"test.named.query\"));\n        Assert.assertEquals(appMetadata.getQuery(\"test.named.query\"), named_query);\n        Assert.assertNotNull(appMetadata.getQuery(\"test.named.queries1\"));\n        Assert.assertEquals(appMetadata.getQuery(\"test.named.queries1\"), named_query1);\n        Assert.assertNotNull(appMetadata.getQuery(\"test.named.queries2\"));\n        Assert.assertEquals(appMetadata.getQuery(\"test.named.queries2\"), named_query2);\n        Assert.assertNotNull(appMetadata.getQuery(\"test.named.queries2\"));\n\n        // Native query asserts\n        Assert.assertNotNull(appMetadata.getQuery(\"test.native.query\"));\n        Assert.assertEquals(appMetadata.getQuery(\"test.native.query\"), native_query);\n        Assert.assertNotNull(appMetadata.getQuery(\"test.native.query1\"));\n        Assert.assertEquals(appMetadata.getQuery(\"test.native.query1\"), native_query1);\n        Assert.assertNotNull(appMetadata.getQuery(\"test.native.query2\"));\n        Assert.assertEquals(appMetadata.getQuery(\"test.native.query2\"), native_query2);\n    }\n\n    /**\n     * Test process query metadata.\n     * \n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    @Test\n    public void testProcessInheritedClass() throws InstantiationException, IllegalAccessException\n    {\n        final String persistenceUnit = \"rdbms\";\n\n        EntityMetadata metadata;\n\n        PersistenceUnitMetadata puMetadata = new PersistenceUnitMetadata();\n        puMetadata.setPersistenceUnitName(persistenceUnit);\n\n        Map<String, Object> props = new HashMap<String, Object>();\n        props.put(Constants.PERSISTENCE_UNIT_NAME, persistenceUnit);\n        props.put(PersistenceProperties.KUNDERA_NODES, \"localhost\");\n        props.put(PersistenceProperties.KUNDERA_PORT, \"9160\");\n        props.put(PersistenceProperties.KUNDERA_KEYSPACE, \"KunderaHbaseExamples\");\n        props.put(PersistenceProperties.KUNDERA_CLIENT_FACTORY, \"com.impetus.client.CoreTestClientFactory\");\n\n        Properties p = new Properties();\n        p.putAll(props);\n        puMetadata.setProperties(p);\n\n        TableProcessor t1 = new TableProcessor(p, kunderaMetadata);\n\n        metadata = new EntityMetadata(Rectangle.class);\n        metadata.setPersistenceUnit(persistenceUnit);\n        t1.process(Rectangle.class, metadata);\n        Assert.assertNotNull(metadata.getIdAttribute());\n\n        metadata = new EntityMetadata(Circle.class);\n        metadata.setPersistenceUnit(persistenceUnit);\n        t1.process(Circle.class, metadata);\n        Assert.assertNotNull(metadata.getIdAttribute());\n\n        metadata = new EntityMetadata(Shape.class);\n        metadata.setPersistenceUnit(persistenceUnit);\n        t1.process(Shape.class, metadata);\n        Assert.assertNotNull(metadata.getIdAttribute());\n\n    }\n\n    /**\n     * Test process query metadata.\n     * \n     */\n    @Test\n    public void testInheritedRelations()\n    {\n        final String persistenceUnit = \"inheritanceTest\";\n\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        EntityManager em = emf.createEntityManager();\n\n        Rectangle rect1 = new Rectangle();\n        rect1.setId(\"r1\");\n        rect1.setName(\"Rect1\");\n\n        Geometry geo1 = new Geometry();\n        geo1.setGeoId(\"g1\");\n        geo1.setName(\"Two D\");\n\n        rect1.setGeometry(geo1);\n\n        Circle circle = new Circle();\n        circle.setId(\"c1\");\n        circle.setName(\"Circle1\");\n        circle.setGeometry(geo1);\n\n        em.persist(rect1);\n        em.persist(circle);\n        em.clear();\n\n        Geometry geo2 = new Geometry();\n        geo2.setGeoId(\"g2\");\n        geo2.setName(\"Closed\");\n\n        Rectangle rectangle = em.find(Rectangle.class, \"r1\");\n\n        Assert.assertNotNull(rectangle.getGeometry());\n        Assert.assertEquals(\"Two D\", rectangle.getGeometry().getName());\n\n        rectangle.setGeometry(geo2);\n\n        em.merge(rectangle);\n        em.clear();\n\n        circle = em.find(Circle.class, \"c1\");\n        Assert.assertNotNull(circle.getGeometry());\n        Assert.assertEquals(\"Two D\", circle.getGeometry().getName());\n        em.clear();\n\n        em.close();\n        emf.close();\n    }\n\n    /**\n     * Test constraints on inherited objects\n     * \n     */\n    @Test\n    public void testInheritedConstraints()\n    {\n        try\n        {\n\n            final String persistenceUnit = \"inheritanceTest\";\n\n            EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);\n            EntityManager em = emf.createEntityManager();\n\n            Rectangle rect1 = new Rectangle();\n            rect1.setId(\"r1\");\n            // rect1.setName(\"Rect1\");\n\n            Geometry geo1 = new Geometry();\n            geo1.setGeoId(\"g1\");\n            geo1.setName(\"Two D\");\n\n            rect1.setGeometry(geo1);\n\n            em.persist(rect1);\n\n            em.clear();\n\n            em.close();\n            emf.close();\n        }\n        catch (Exception e)\n        {\n\n            Assert.assertEquals(\"javax.validation.ValidationException: Name of the object should be defined\",\n                    e.getMessage());\n\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        // Do nothing.\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/processor/relation/RelationProcessorTest.java",
    "content": "package com.impetus.kundera.metadata.processor.relation;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.loader.MetamodelLoaderException;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.polyglot.entities.PersonU11FK;\nimport com.impetus.kundera.polyglot.entities.PersonU1M;\nimport com.impetus.kundera.polyglot.entities.PersonUM1;\nimport com.impetus.kundera.polyglot.entities.PersonUMM;\nimport com.impetus.kundera.polyglot.entities.PersonUMMByMap;\n\npublic class RelationProcessorTest\n{\n\n    private static EntityManagerFactory emf;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"patest\");\n    }\n\n    @Test\n    public void testManyToMany() throws NoSuchFieldException, SecurityException\n    {\n        ManyToManyRelationMetadataProcessor processor = new ManyToManyRelationMetadataProcessor(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonUMMByMap.class);\n        Assert.assertNotNull(metadata.getRelation(\"addresses\"));\n        // processor.addRelationIntoMetadata(PersonB11FK.class.getDeclaredField(\"address\"),metadata);\n\n        try\n        {\n            processor.process(PersonUMM.class, metadata);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (MetamodelLoaderException mlex)\n        {\n            Assert.assertNotNull(mlex.getMessage());\n        }\n    }\n\n    @Test\n    public void testOneToMany() throws NoSuchFieldException, SecurityException\n    {\n        OneToManyRelationMetadataProcessor processor = new OneToManyRelationMetadataProcessor(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonU1M.class);\n        Assert.assertNotNull(metadata.getRelation(\"addresses\"));\n\n        try\n        {\n            processor.process(PersonU1M.class, metadata);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (MetamodelLoaderException mlex)\n        {\n            Assert.assertNotNull(mlex.getMessage());\n        }\n\n        /*\n         * try {\n         * processor.addRelationIntoMetadata(PersonUMMByMap.class.getDeclaredField\n         * (\"addresses\"), metadata);\n         * Assert.fail(\"Should have gone to catch block!\"); } catch\n         * (UnsupportedOperationException uoex) {\n         * Assert.assertNotNull(uoex.getMessage()); }\n         */\n    }\n\n    @Test\n    public void testManyToOne() throws NoSuchFieldException, SecurityException\n    {\n        ManyToOneRelationMetadataProcessor processor = new ManyToOneRelationMetadataProcessor(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonUM1.class);\n        Assert.assertNotNull(metadata.getRelation(\"address\"));\n\n        try\n        {\n            processor.process(PersonUM1.class, metadata);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (MetamodelLoaderException mlex)\n        {\n            Assert.assertNotNull(mlex.getMessage());\n        }\n\n        /*\n         * try {\n         * processor.addRelationIntoMetadata(PersonUMMByMap.class.getDeclaredField\n         * (\"addresses\"), metadata);\n         * Assert.fail(\"Should have gone to catch block!\"); } catch\n         * (UnsupportedOperationException uoex) {\n         * Assert.assertNotNull(uoex.getMessage()); }\n         */}\n\n    @Test\n    public void testOneToOne() throws NoSuchFieldException, SecurityException\n    {\n        OneToOneRelationMetadataProcessor processor = new OneToOneRelationMetadataProcessor(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonU11FK.class);\n        Assert.assertNotNull(metadata.getRelation(\"address\"));\n\n        try\n        {\n            processor.process(PersonU11FK.class, metadata);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (MetamodelLoaderException mlex)\n        {\n            Assert.assertNotNull(mlex.getMessage());\n        }\n\n        /*\n         * try {\n         * processor.addRelationIntoMetadata(PersonUMMByMap.class.getDeclaredField\n         * (\"addresses\"), metadata);\n         * Assert.fail(\"Should have gone to catch block!\"); } catch\n         * (UnsupportedOperationException uoex) {\n         * Assert.assertNotNull(uoex.getMessage()); }\n         */\n    }\n\n    @AfterClass\n    public static void tearDown()\n    {\n        emf.close();\n        emf = null;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/EntityValidatorImplTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.metadata.validator;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * @author Kuldeep\n *  Entity validator impl test.\n */\npublic class EntityValidatorImplTest\n{\n    private EntityValidatorImpl validator;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        validator = new EntityValidatorImpl();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        validator = null;\n    }\n\n    @Test\n    public void testValidate()\n    {\n        try\n        {\n            validator.validate(GeneratedIdDefault.class);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail();\n        }\n        try\n        {\n            validator.validate(GeneratedIdStrategyAuto.class);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail();\n        }\n        try\n        {\n            validator.validate(GeneratedIdStrategyIdentity.class);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail();\n        }\n        try\n        {\n            validator.validate(GeneratedIdStrategySequence.class);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail();\n        }\n        try\n        {\n            validator.validate(GeneratedIdWithSequenceGenerator.class);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail();\n        }\n        try\n        {\n            validator.validate(GeneratedIdWithTableGenerator.class);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail();\n        }\n        try\n        {\n            validator.validate(GeneratedIdWithOutSequenceGenerator.class);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail();\n        }\n        try\n        {\n            validator.validate(GeneratedIdWithOutTableGenerator.class);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail();\n        }\n        try\n        {\n            validator.validate(GeneratedIdStrategyTable.class);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail();\n        }\n\n        try\n        {\n            validator.validate(GeneratedIdWithNoGenerator.class);\n            Assert.fail();\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.assertEquals(\"Unknown Id.generator: id\", e.getMessage());\n        }\n\n        try\n        {\n            validator.validate(GeneratedIdWithInvalidGenerator.class);\n            Assert.fail();\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.assertEquals(\"Unknown Id.generator: id\", e.getMessage());\n        }\n        \n        try\n        {\n            validator.validate(String.class);\n        } catch(InvalidEntityDefinitionException iedfx)\n        {\n            Assert.assertEquals(String.class.getName() + \" is not annotated with @Entity.\", iedfx.getMessage());\n        }\n        \n        try\n        {\n            validator.validate(EntityWithOutTableAnnotation.class);\n        } catch(InvalidEntityDefinitionException iedfx)\n        {\n            Assert.assertEquals(EntityWithOutTableAnnotation.class.getName() + \" must be annotated with @Table.\", iedfx.getMessage());\n        }\n        \n        try\n        {\n            validator.validate(EntityWithOutConstructor.class);\n        } catch(InvalidEntityDefinitionException iedfx)\n        {\n            Assert.assertEquals(EntityWithOutConstructor.class.getName() + \" must have a default no-argument constructor.\", iedfx.getMessage());\n        }\n        \n        try\n        {\n            validator.validate(EntityWithOutId.class);\n        } catch(InvalidEntityDefinitionException iedfx)\n        {\n            Assert.assertEquals(EntityWithOutId.class.getName() + \" must have an @Id field.\", iedfx.getMessage());\n        }\n\n        try\n        {\n            validator.validate(EntityWithMultipleId.class);\n        } catch(InvalidEntityDefinitionException iedfx)\n        {\n            Assert.assertEquals(EntityWithMultipleId.class.getName() + \" can only have 1 @Id field.\", iedfx.getMessage());\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/EntityWithMultipleId.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * Invalid entity definition with multiple @Id annotated fields. \n */\n@Entity\n@Table\npublic class EntityWithMultipleId\n{\n\n    @Id\n    private String id1;\n    \n    @Id\n    private int id2;\n    \n    @Column\n    private String name;\n\n    public EntityWithMultipleId()\n    {\n        \n    }\n    \n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public String getId1()\n    {\n        return id1;\n    }\n\n    public int getId2()\n    {\n        return id2;\n    }\n        \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/EntityWithOutConstructor.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * Invalid entity definition without no-arg-constructor.\n */\n@Entity\n@Table\npublic class EntityWithOutConstructor\n{\n\n    private String name;\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n    \n    \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/EntityWithOutId.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * Invalid entity definition without @Id annotated field.\n */\n@Entity\n@Table\npublic class EntityWithOutId\n{\n\n    private String name;\n\n    public EntityWithOutId()\n    {\n        \n    }\n    \n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n    \n    \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/EntityWithOutTableAnnotation.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Entity;\n\n/**\n * @author vivek.mishra\n * Invalid entity definition without @Table annotated field.\n */\n@Entity\npublic class EntityWithOutTableAnnotation\n{\n\n    private String name;\n    \n    public EntityWithOutTableAnnotation()\n    {\n        \n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n    \n    \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/GeneratedIdDefault.java",
    "content": "package com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"GeneratedIdDefault\", schema = \"KunderaTest@GeneratedValue\")\npublic class GeneratedIdDefault\n{\n    @Id\n    @GeneratedValue\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/GeneratedIdStrategyAuto.java",
    "content": "package com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"GeneratedIdStrategyAuto\", schema = \"KunderaTest@GeneratedValue\")\n@TableGenerator(name = \"id_gen\")\npublic class GeneratedIdStrategyAuto\n{\n    @Id\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.AUTO)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/GeneratedIdStrategyIdentity.java",
    "content": "package com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"GeneratedIdStrategyIdentity\", schema = \"KunderaTest@GeneratedValue\")\npublic class GeneratedIdStrategyIdentity\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/GeneratedIdStrategySequence.java",
    "content": "package com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"GeneratedIdStrategySequence\", schema = \"KunderaTest@GeneratedValue\")\npublic class GeneratedIdStrategySequence\n{\n    @Id\n    @SequenceGenerator(name = \"seq_gen\")\n    @GeneratedValue(generator = \"seq_gen\", strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/GeneratedIdStrategyTable.java",
    "content": "package com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"GeneratedIdStrategyTable\", schema = \"KunderaTest@GeneratedValue\")\n@TableGenerator(name = \"table_gen\")\npublic class GeneratedIdStrategyTable\n{\n\n    @Id\n    @TableGenerator(name = \"table_gen_1\")\n    @GeneratedValue(generator = \"table_gen\", strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/GeneratedIdWithInvalidGenerator.java",
    "content": "package com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"GeneratedIdWithNoGenerator\", schema = \"KunderaTest@GeneratedValue\")\n@TableGenerator(name = \"id_gen\")\npublic class GeneratedIdWithInvalidGenerator\n{\n    @Id\n    @SequenceGenerator(name = \"seq_gen\")\n    @GeneratedValue(generator = \"id\")\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/GeneratedIdWithNoGenerator.java",
    "content": "package com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"GeneratedIdWithNoGenerator\", schema = \"KunderaTest@GeneratedValue\")\npublic class GeneratedIdWithNoGenerator\n{\n\n    @Id\n    @GeneratedValue(generator = \"id\")\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/GeneratedIdWithOutSequenceGenerator.java",
    "content": "package com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"GeneratedIdWithOutSequenceGenerator\", schema = \"KunderaTest@GeneratedValue\")\npublic class GeneratedIdWithOutSequenceGenerator\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/GeneratedIdWithOutTableGenerator.java",
    "content": "package com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"GeneratedIdWithOutTableGenerator\", schema = \"KunderaTest@GeneratedValue\")\npublic class GeneratedIdWithOutTableGenerator\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/GeneratedIdWithSequenceGenerator.java",
    "content": "package com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"GeneratedIdWithSequenceGenerator\", schema = \"KunderaTest@GeneratedValue\")\npublic class GeneratedIdWithSequenceGenerator\n{\n    @Id\n    @SequenceGenerator(name = \"id_gen\", allocationSize = 20, initialValue = 80, schema = \"KunderaTest\", sequenceName = \"newSequence\")\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/metadata/validator/GeneratedIdWithTableGenerator.java",
    "content": "package com.impetus.kundera.metadata.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"GeneratedIdWithTableGenerator\", schema = \"KunderaTest@GeneratedValue\")\npublic class GeneratedIdWithTableGenerator\n{\n\n    @Id\n    @TableGenerator(name = \"id_gen\", allocationSize = 30, initialValue = 100, schema = \"KunderaTest\", table = \"kundera\", pkColumnName = \"sequence\", valueColumnName = \"sequenceValue\", pkColumnValue = \"kk\")\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/AssociationBuilderTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.CoreTestUtilities;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.polyglot.entities.AddressU11FK;\nimport com.impetus.kundera.polyglot.entities.PersonU11FK;\nimport com.impetus.kundera.proxy.ProxyHelper;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * @author vivek.mishra junit for {@link AssociationBuilder}\n * \n */\npublic class AssociationBuilderTest\n{\n\n    private static final String PU = \"patest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(PU);\n        em = emf.createEntityManager();\n\n    }\n\n    @Test\n    public void testAssociatedEntitiesFromIndex() throws NoSuchFieldException, SecurityException,\n            IllegalArgumentException, IllegalAccessException\n    {\n        AddressU11FK address = new AddressU11FK();\n        address.setAddressId(\"addr1\");\n        address.setStreet(\"street\");\n\n        PersonU11FK p1 = new PersonU11FK();\n        p1.setPersonName(\"vivek\");\n        p1.setPersonId(\"1\");\n        p1.setAddress(address);\n\n        em.persist(p1);\n\n        em.clear();\n\n        AssociationBuilder builder = new AssociationBuilder();\n\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n        Client associationEntityClient = delegator.getClient(KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), AddressU11FK.class));\n        java.util.List results = builder.getAssociatedEntitiesFromIndex(PersonU11FK.class, \"1\", AddressU11FK.class,\n                associationEntityClient);\n        Assert.assertNotNull(results);\n\n        // TODO: This is failing . Vivek to look into this.\n        // Assert.assertFalse(results.isEmpty());\n\n        // builder.setProxyRelationObject(entity, relationsMap, m, pd, entityId,\n        // relation);\n\n        Map<String, Object> relationMap = new HashMap<String, Object>();\n        relationMap.put(\"ADDRESS_ID\", \"addr1\");\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonU11FK.class);\n        builder.setProxyRelationObject(p1, relationMap, metadata, delegator, \"1\", metadata.getRelation(\"address\"));\n\n        Assert.assertTrue(ProxyHelper.isKunderaProxy(p1.getAddress()));\n        //\n        // builder.populateRelationForM2M(entity, entityMetadata, delegator,\n        // relation, relObject, relationsMap);\n\n    }\n\n    @After\n    public void tearDown()\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n\n        if (em != null)\n        {\n            em.close();\n        }\n\n        LuceneCleanupUtilities.cleanLuceneDirectory(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance().getApplicationMetadata().getPersistenceUnitMetadata(PU));\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/ExternalPropertyLoaderTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * Junit to test load persistence unit specfic properties via external map.\n * \n * @author shaheed.hussain\n * \n */\npublic class ExternalPropertyLoaderTest\n{\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUpBefore() throws Exception\n    {\n        Map propertyMap = new HashMap();\n        propertyMap.put(\"kundera.nodes\", \"localhost\");\n        propertyMap.put(\"kundera.port\", \"9160\");\n        propertyMap.put(\"kundera.keyspace\", \"sprint\");\n        propertyMap.put(\"kundera.client.lookup.class\", \"com.impetus.kundera.client.CoreTestClientFactory\");\n        emf = Persistence.createEntityManagerFactory(\"extConfig\", propertyMap);\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    /**\n     * Junit to verify, if emf has been successfully loaded and user object has\n     * been persisted.\n     */\n    @Test\n    public void test()\n    {\n        EntityManager em = emf.createEntityManager();\n        User user = new User();\n        user.setFirstName(\"John\");\n        user.setLastName(\"Smith\");\n        user.setCity(\"London\");\n        em.persist(user);\n\n        em.clear();\n\n        User found = em.find(User.class, user.getUserId()); // it is auto generated in-memory\n                                              // id\n        Assert.assertNotNull(found);\n        Assert.assertEquals(user.getCity(), found.getCity());\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/FlushStackManagerTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence;\n\nimport java.util.Collection;\nimport java.util.Deque;\nimport java.util.Set;\n\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.configure.PersistenceUnitConfiguration;\nimport com.impetus.kundera.entity.album.AlbumBi_1_1_1_1;\nimport com.impetus.kundera.entity.album.AlbumUni_1_1_1_1;\nimport com.impetus.kundera.entity.album.AlbumUni_1_1_1_M;\nimport com.impetus.kundera.entity.album.AlbumUni_1_1_M_1;\nimport com.impetus.kundera.entity.album.AlbumUni_1_M_1_M;\nimport com.impetus.kundera.entity.album.AlbumUni_1_M_M_M;\nimport com.impetus.kundera.entity.album.AlbumUni_M_1_1_M;\nimport com.impetus.kundera.entity.album.AlbumUni_M_M_1_1;\nimport com.impetus.kundera.entity.album.AlbumUni_M_M_M_M;\nimport com.impetus.kundera.entity.photo.PhotoBi_1_1_1_1;\nimport com.impetus.kundera.entity.photo.PhotoUni_1_1_1_1;\nimport com.impetus.kundera.entity.photo.PhotoUni_1_1_1_M;\nimport com.impetus.kundera.entity.photo.PhotoUni_1_1_M_1;\nimport com.impetus.kundera.entity.photo.PhotoUni_1_M_1_M;\nimport com.impetus.kundera.entity.photo.PhotoUni_1_M_M_M;\nimport com.impetus.kundera.entity.photo.PhotoUni_M_1_1_M;\nimport com.impetus.kundera.entity.photo.PhotoUni_M_M_1_1;\nimport com.impetus.kundera.entity.photo.PhotoUni_M_M_M_M;\nimport com.impetus.kundera.entity.photographer.PhotographerBi_1_1_1_1;\nimport com.impetus.kundera.entity.photographer.PhotographerUni_1_1_1_1;\nimport com.impetus.kundera.entity.photographer.PhotographerUni_1_1_1_M;\nimport com.impetus.kundera.entity.photographer.PhotographerUni_1_1_M_1;\nimport com.impetus.kundera.entity.photographer.PhotographerUni_1_M_1_M;\nimport com.impetus.kundera.entity.photographer.PhotographerUni_1_M_M_M;\nimport com.impetus.kundera.entity.photographer.PhotographerUni_M_1_1_M;\nimport com.impetus.kundera.entity.photographer.PhotographerUni_M_M_1_1;\nimport com.impetus.kundera.entity.photographer.PhotographerUni_M_M_M_M;\nimport com.impetus.kundera.graph.BillingCounter;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.ObjectGraph;\nimport com.impetus.kundera.graph.ObjectGraphBuilder;\nimport com.impetus.kundera.graph.ObjectGraphUtils;\nimport com.impetus.kundera.graph.Store;\nimport com.impetus.kundera.persistence.context.EventLog.EventType;\nimport com.impetus.kundera.persistence.context.FlushManager;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\n\n/**\n * Test case for {@link FlushManager}\n * \n * @author amresh.singh\n */\npublic class FlushStackManagerTest\n{\n    private PersistenceCache pc;\n\n    private ObjectGraphBuilder graphBuilder;\n\n    private String _persistenceUnit = \"kunderatest\";\n\n    private EntityManagerFactoryImpl emfImpl;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emfImpl = getEntityManagerFactory();\n        new PersistenceUnitConfiguration(null, emfImpl.getKunderaMetadataInstance(), \"kunderatest\").configure();\n        pc = new PersistenceCache();\n        graphBuilder = new ObjectGraphBuilder(pc, new PersistenceDelegator(emfImpl.getKunderaMetadataInstance(), pc));\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emfImpl.close();\n    }\n\n    @Test\n    public void testFlashStockForStore()\n    {\n\n        FlushManager flushManager = new FlushManager();\n\n        Store store = new Store(1, \"Food Bazaar, Noida\");\n        store.addCounter(new BillingCounter(1, \"A\"));\n        store.addCounter(new BillingCounter(2, \"B\"));\n        store.addCounter(new BillingCounter(3, \"C\"));\n\n        ObjectGraph graph = graphBuilder.getObjectGraph(store, null);\n\n        pc.getMainCache().addGraphToCache(graph, pc);\n\n        Assert.assertNotNull(pc.getMainCache());\n        Assert.assertEquals(1, pc.getMainCache().getHeadNodes().size());\n\n        PersistenceDelegator pd = new PersistenceDelegator(emfImpl.getKunderaMetadataInstance(), pc);\n\n        Node headNode = pc.getMainCache().getNodeFromCache(ObjectGraphUtils.getNodeId(\"1\", Store.class), pd);\n\n        Assert.assertNotNull(headNode);\n        Assert.assertNull(headNode.getParents());\n        Assert.assertEquals(3, headNode.getChildren().size());\n\n        Assert.assertEquals(4, pc.getMainCache().size());\n\n        markAllNodeAsDirty();\n        flushManager.buildFlushStack(headNode, EventType.INSERT);\n\n        Deque<Node> fs = flushManager.getFlushStack();\n        Assert.assertEquals(4, fs.size());\n    }\n\n    @Test\n    public void test_1_1_1_1()\n    {\n        FlushManager flushManager = new FlushManager();\n        PhotographerUni_1_1_1_1 a = new PhotographerUni_1_1_1_1();\n        a.setPhotographerId(1);\n        AlbumUni_1_1_1_1 b = new AlbumUni_1_1_1_1();\n        b.setAlbumId(\"b1\");\n        PhotoUni_1_1_1_1 c = new PhotoUni_1_1_1_1();\n        c.setPhotoId(\"c1\");\n        a.setAlbum(b);\n        b.setPhoto(c);\n\n        ObjectGraph graph = graphBuilder.getObjectGraph(a, null);\n        pc.getMainCache().addGraphToCache(graph, pc);\n\n        PersistenceDelegator pd = new PersistenceDelegator(emfImpl.getKunderaMetadataInstance(), pc);\n\n        Node headNode = pc.getMainCache()\n                .getNodeFromCache(ObjectGraphUtils.getNodeId(\"c1\", PhotoUni_1_1_1_1.class), pd);\n\n        markAllNodeAsDirty();\n        flushManager.buildFlushStack(graph.getHeadNode(), EventType.INSERT);\n\n        Deque<Node> fs = flushManager.getFlushStack();\n        Assert.assertEquals(3, fs.size());\n    }\n\n    @Test\n    public void test_multi_1_1_1_1()\n    {\n        FlushManager flushManager = new FlushManager();\n\n        PhotographerBi_1_1_1_1 a = new PhotographerBi_1_1_1_1();\n        a.setPhotographerId(1);\n\n        AlbumBi_1_1_1_1 b = new AlbumBi_1_1_1_1();\n        b.setAlbumId(\"b1\");\n\n        PhotoBi_1_1_1_1 c = new PhotoBi_1_1_1_1();\n        c.setPhotoId(\"c1\");\n\n        b.setPhotographer(a);\n        b.setPhoto(c);\n\n        ObjectGraph graph = graphBuilder.getObjectGraph(b, null);\n        pc.getMainCache().addGraphToCache(graph, pc);\n\n        markAllNodeAsDirty();\n        flushManager.buildFlushStack(graph.getHeadNode(), EventType.INSERT);\n\n        Deque<Node> fs = flushManager.getFlushStack();\n        Assert.assertEquals(2, fs.size());\n    }\n\n    @Test\n    public void test_1_1_1_M()\n    {\n        FlushManager flushManager = new FlushManager();\n        PhotographerUni_1_1_1_M a = new PhotographerUni_1_1_1_M();\n        a.setPhotographerId(1);\n        AlbumUni_1_1_1_M b = new AlbumUni_1_1_1_M();\n        b.setAlbumId(\"b1\");\n        PhotoUni_1_1_1_M c1 = new PhotoUni_1_1_1_M();\n        c1.setPhotoId(\"c1\");\n        PhotoUni_1_1_1_M c2 = new PhotoUni_1_1_1_M();\n        c2.setPhotoId(\"c2\");\n        PhotoUni_1_1_1_M c3 = new PhotoUni_1_1_1_M();\n        c3.setPhotoId(\"c3\");\n        a.setAlbum(b);\n        b.addPhoto(c1);\n        b.addPhoto(c2);\n        b.addPhoto(c3);\n\n        ObjectGraph graph = graphBuilder.getObjectGraph(a, null);\n        pc.getMainCache().addGraphToCache(graph, pc);\n\n        markAllNodeAsDirty();\n        flushManager.buildFlushStack(graph.getHeadNode(), EventType.INSERT);\n        Deque<Node> fs = flushManager.getFlushStack();\n        Assert.assertEquals(5, fs.size());\n    }\n\n    @Test\n    public void test_1_1_M_1()\n    {\n        FlushManager flushManager = new FlushManager();\n        PhotographerUni_1_1_M_1 a = new PhotographerUni_1_1_M_1();\n        a.setPhotographerId(1);\n        AlbumUni_1_1_M_1 b1 = new AlbumUni_1_1_M_1();\n        b1.setAlbumId(\"b1\");\n        AlbumUni_1_1_M_1 b2 = new AlbumUni_1_1_M_1();\n        b2.setAlbumId(\"b2\");\n        AlbumUni_1_1_M_1 b3 = new AlbumUni_1_1_M_1();\n        b3.setAlbumId(\"b3\");\n\n        PhotoUni_1_1_M_1 c = new PhotoUni_1_1_M_1();\n        c.setPhotoId(\"c\");\n        a.setAlbum(b1);\n        b1.setPhoto(c);\n        b2.setPhoto(c);\n        b3.setPhoto(c);\n\n        ObjectGraph graph = graphBuilder.getObjectGraph(a, null);\n        ObjectGraph graphb2 = graphBuilder.getObjectGraph(b2, null);\n        ObjectGraph graphb3 = graphBuilder.getObjectGraph(b3, null);\n\n        pc.getMainCache().addGraphToCache(graph, pc);\n        pc.getMainCache().addGraphToCache(graphb2, pc);\n        pc.getMainCache().addGraphToCache(graphb3, pc);\n\n        markAllNodeAsDirty();\n        flushManager.buildFlushStack(graph.getHeadNode(), EventType.INSERT);\n        Deque<Node> fs = flushManager.getFlushStack();\n        Assert.assertEquals(3, fs.size());\n        flushManager.clearFlushStack();\n        flushManager = new FlushManager();\n        flushManager.buildFlushStack(graphb2.getHeadNode(), EventType.INSERT);\n        fs = flushManager.getFlushStack();\n        Assert.assertEquals(2, fs.size());\n        flushManager.clearFlushStack();\n        flushManager = new FlushManager();\n        flushManager.buildFlushStack(graphb3.getHeadNode(), EventType.INSERT);\n        fs = flushManager.getFlushStack();\n        Assert.assertEquals(2, fs.size());\n        flushManager.clearFlushStack();\n    }\n\n    @Test\n    public void test_1_M_1_M()\n    {\n        FlushManager flushManager = new FlushManager();\n        PhotographerUni_1_M_1_M a = new PhotographerUni_1_M_1_M();\n        a.setPhotographerId(1);\n        AlbumUni_1_M_1_M b1 = new AlbumUni_1_M_1_M();\n        b1.setAlbumId(\"b1\");\n        AlbumUni_1_M_1_M b2 = new AlbumUni_1_M_1_M();\n        b2.setAlbumId(\"b2\");\n\n        PhotoUni_1_M_1_M c1 = new PhotoUni_1_M_1_M();\n        c1.setPhotoId(\"c1\");\n        PhotoUni_1_M_1_M c2 = new PhotoUni_1_M_1_M();\n        c2.setPhotoId(\"c2\");\n        PhotoUni_1_M_1_M c3 = new PhotoUni_1_M_1_M();\n        c3.setPhotoId(\"c3\");\n        PhotoUni_1_M_1_M c4 = new PhotoUni_1_M_1_M();\n        c4.setPhotoId(\"c4\");\n\n        b1.addPhoto(c1);\n        b1.addPhoto(c2);\n        b2.addPhoto(c3);\n        b2.addPhoto(c4);\n        a.addAlbum(b1);\n        a.addAlbum(b2);\n\n        ObjectGraph graph = graphBuilder.getObjectGraph(a, null);\n        pc.getMainCache().addGraphToCache(graph, pc);\n\n        markAllNodeAsDirty();\n        flushManager.buildFlushStack(graph.getHeadNode(), EventType.INSERT);\n        Deque<Node> fs = flushManager.getFlushStack();\n        Assert.assertEquals(7, fs.size());\n    }\n\n    @Test\n    public void test_1_M_M_M()\n    {\n        FlushManager flushManager = new FlushManager();\n        PhotographerUni_1_M_M_M a = new PhotographerUni_1_M_M_M();\n        a.setPhotographerId(1);\n        AlbumUni_1_M_M_M b1 = new AlbumUni_1_M_M_M();\n        b1.setAlbumId(\"b1\");\n        AlbumUni_1_M_M_M b2 = new AlbumUni_1_M_M_M();\n        b2.setAlbumId(\"b2\");\n\n        PhotoUni_1_M_M_M c1 = new PhotoUni_1_M_M_M();\n        c1.setPhotoId(\"c1\");\n        PhotoUni_1_M_M_M c2 = new PhotoUni_1_M_M_M();\n        c2.setPhotoId(\"c2\");\n        PhotoUni_1_M_M_M c3 = new PhotoUni_1_M_M_M();\n        c3.setPhotoId(\"c3\");\n\n        b1.addPhoto(c1);\n        b1.addPhoto(c2);\n        b2.addPhoto(c2);\n        b2.addPhoto(c3);\n        a.addAlbum(b1);\n        a.addAlbum(b2);\n\n        ObjectGraph graph = graphBuilder.getObjectGraph(a, null);\n        pc.getMainCache().addGraphToCache(graph, pc);\n\n        markAllNodeAsDirty();\n        flushManager.buildFlushStack(graph.getHeadNode(), EventType.INSERT);\n        Deque<Node> fs = flushManager.getFlushStack();\n        Assert.assertEquals(3, fs.size());\n    }\n\n    @Test\n    public void test_M_1_1_M()\n    {\n        FlushManager flushManager = new FlushManager();\n        PhotographerUni_M_1_1_M a1 = new PhotographerUni_M_1_1_M();\n        a1.setPhotographerId(1);\n        PhotographerUni_M_1_1_M a2 = new PhotographerUni_M_1_1_M();\n        a2.setPhotographerId(2);\n        PhotographerUni_M_1_1_M a3 = new PhotographerUni_M_1_1_M();\n        a3.setPhotographerId(3);\n\n        AlbumUni_M_1_1_M b = new AlbumUni_M_1_1_M();\n        b.setAlbumId(\"b\");\n\n        PhotoUni_M_1_1_M c1 = new PhotoUni_M_1_1_M();\n        c1.setPhotoId(\"c1\");\n        PhotoUni_M_1_1_M c2 = new PhotoUni_M_1_1_M();\n        c2.setPhotoId(\"c2\");\n        PhotoUni_M_1_1_M c3 = new PhotoUni_M_1_1_M();\n        c3.setPhotoId(\"c3\");\n\n        b.addPhoto(c1);\n        b.addPhoto(c2);\n        b.addPhoto(c3);\n        a1.setAlbum(b);\n\n        ObjectGraph graph1 = graphBuilder.getObjectGraph(a1, null);\n        ObjectGraph graph2 = graphBuilder.getObjectGraph(a2, null);\n        ObjectGraph graph3 = graphBuilder.getObjectGraph(a3, null);\n\n        pc.getMainCache().addGraphToCache(graph1, pc);\n\n        markAllNodeAsDirty();\n\n        flushManager.buildFlushStack(graph1.getHeadNode(), EventType.INSERT);\n        Deque<Node> fs = flushManager.getFlushStack();\n        Assert.assertEquals(5, fs.size());\n        flushManager.clearFlushStack();\n\n        a2.setAlbum(b);\n        pc.getMainCache().addGraphToCache(graph2, pc);\n        markAllNodeAsDirty();\n        flushManager = new FlushManager();\n        flushManager.buildFlushStack(graph2.getHeadNode(), EventType.INSERT);\n        fs = flushManager.getFlushStack();\n        Assert.assertEquals(1, fs.size());\n        flushManager.clearFlushStack();\n\n        a3.setAlbum(b);\n        pc.getMainCache().addGraphToCache(graph3, pc);\n        markAllNodeAsDirty();\n        flushManager = new FlushManager();\n        flushManager.buildFlushStack(graph3.getHeadNode(), EventType.INSERT);\n        fs = flushManager.getFlushStack();\n        Assert.assertEquals(1, fs.size());\n        flushManager.clearFlushStack();\n    }\n\n    @Test\n    public void test_M_M_1_1()\n    {\n        FlushManager flushManager = new FlushManager();\n        PhotographerUni_M_M_1_1 a1 = new PhotographerUni_M_M_1_1();\n        a1.setPhotographerId(1);\n        PhotographerUni_M_M_1_1 a2 = new PhotographerUni_M_M_1_1();\n        a2.setPhotographerId(2);\n\n        AlbumUni_M_M_1_1 b1 = new AlbumUni_M_M_1_1();\n        b1.setAlbumId(\"b1\");\n        AlbumUni_M_M_1_1 b2 = new AlbumUni_M_M_1_1();\n        b2.setAlbumId(\"b2\");\n        AlbumUni_M_M_1_1 b3 = new AlbumUni_M_M_1_1();\n        b3.setAlbumId(\"b3\");\n\n        PhotoUni_M_M_1_1 c1 = new PhotoUni_M_M_1_1();\n        c1.setPhotoId(\"c1\");\n        PhotoUni_M_M_1_1 c2 = new PhotoUni_M_M_1_1();\n        c2.setPhotoId(\"c2\");\n        PhotoUni_M_M_1_1 c3 = new PhotoUni_M_M_1_1();\n        c3.setPhotoId(\"c3\");\n\n        b1.setPhoto(c1);\n        b2.setPhoto(c2);\n        b3.setPhoto(c3);\n        a1.addAlbum(b1);\n        a1.addAlbum(b2);\n\n        ObjectGraph graph1 = graphBuilder.getObjectGraph(a1, null);\n\n        pc.getMainCache().addGraphToCache(graph1, pc);\n\n        markAllNodeAsDirty();\n\n        flushManager.buildFlushStack(graph1.getHeadNode(), EventType.INSERT);\n        Deque<Node> fs = flushManager.getFlushStack();\n        Assert.assertEquals(1, fs.size());\n        flushManager.clearFlushStack();\n\n        a2.addAlbum(b2);\n        a2.addAlbum(b3);\n        ObjectGraph graph2 = graphBuilder.getObjectGraph(a2, null);\n        pc.getMainCache().addGraphToCache(graph2, pc);\n        markAllNodeAsDirty();\n        flushManager = new FlushManager();\n        flushManager.buildFlushStack(graph2.getHeadNode(), EventType.INSERT);\n        fs = flushManager.getFlushStack();\n        Assert.assertEquals(1, fs.size());\n    }\n\n    @Test\n    public void test_M_M_M_M()\n    {\n        FlushManager flushManager = new FlushManager();\n\n        PhotographerUni_M_M_M_M a1 = new PhotographerUni_M_M_M_M();\n        a1.setPhotographerId(1);\n        PhotographerUni_M_M_M_M a2 = new PhotographerUni_M_M_M_M();\n        a2.setPhotographerId(2);\n\n        AlbumUni_M_M_M_M b1 = new AlbumUni_M_M_M_M();\n        b1.setAlbumId(\"b1\");\n        AlbumUni_M_M_M_M b2 = new AlbumUni_M_M_M_M();\n        b2.setAlbumId(\"b2\");\n        AlbumUni_M_M_M_M b3 = new AlbumUni_M_M_M_M();\n        b3.setAlbumId(\"b3\");\n\n        PhotoUni_M_M_M_M c1 = new PhotoUni_M_M_M_M();\n        c1.setPhotoId(\"c1\");\n        PhotoUni_M_M_M_M c2 = new PhotoUni_M_M_M_M();\n        c2.setPhotoId(\"c2\");\n        PhotoUni_M_M_M_M c3 = new PhotoUni_M_M_M_M();\n        c3.setPhotoId(\"c3\");\n        PhotoUni_M_M_M_M c4 = new PhotoUni_M_M_M_M();\n        c4.setPhotoId(\"c4\");\n\n        b1.addPhoto(c1);\n        b1.addPhoto(c2);\n        b2.addPhoto(c2);\n        b2.addPhoto(c3);\n        b3.addPhoto(c3);\n        b3.addPhoto(c4);\n        a1.addAlbum(b1);\n        a1.addAlbum(b2);\n\n        ObjectGraph graph1 = graphBuilder.getObjectGraph(a1, null);\n\n        pc.getMainCache().addGraphToCache(graph1, pc);\n\n        markAllNodeAsDirty();\n        flushManager.buildFlushStack(graph1.getHeadNode(), EventType.INSERT);\n        Deque<Node> fs = flushManager.getFlushStack();\n        Assert.assertEquals(6, fs.size());\n        flushManager.clearFlushStack();\n\n        a2.addAlbum(b2);\n        a2.addAlbum(b3);\n        ObjectGraph graph2 = graphBuilder.getObjectGraph(a2, null);\n        pc.getMainCache().addGraphToCache(graph2, pc);\n\n        markAllNodeAsDirty();\n        flushManager = new FlushManager();\n        flushManager.buildFlushStack(graph2.getHeadNode(), EventType.INSERT);\n        fs = flushManager.getFlushStack();\n        Assert.assertEquals(3, fs.size());\n    }\n\n    /**\n     * \n     */\n    private void markAllNodeAsDirty()\n    {\n        if (pc.getMainCache() != null)\n        {\n            Set<Node> headNodes = pc.getMainCache().getHeadNodes();\n            if (headNodes != null)\n            {\n\n                for (Node hn : headNodes)\n                {\n                    if (hn != null)\n                        hn.setDirty(true);\n\n                }\n            }\n\n            Collection<Node> allNodes = pc.getMainCache().getAllNodes();\n            if (allNodes != null)\n            {\n                for (Node node : allNodes)\n                {\n                    if (node != null)\n                        node.setDirty(true);\n                }\n            }\n        }\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory()\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(_persistenceUnit);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/IdGeneratorTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.CoreTestUtilities;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.CoreTestClientNoGenerator;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.validator.GeneratedIdStrategyAuto;\nimport com.impetus.kundera.metadata.validator.GeneratedIdStrategyIdentity;\nimport com.impetus.kundera.metadata.validator.GeneratedIdStrategySequence;\nimport com.impetus.kundera.metadata.validator.GeneratedIdStrategyTable;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.thoughtworks.xstream.core.ReferenceByIdMarshaller.IDGenerator;\n\n/**\n * @author vivek.mishra\n * \n *         junit for {@link IDGenerator}\n * \n */\npublic class IdGeneratorTest\n{\n    private static String persistenceUnit = \"GeneratedValue\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private KunderaMetadata kunderaMetadata;\n\n    @Before\n    public void setup()\n    {\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testAutoStrategy() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException\n    {\n        IdGenerator idGenerator = new IdGenerator();\n\n        GeneratedIdStrategyAuto autoStrategy = new GeneratedIdStrategyAuto();\n        autoStrategy.setName(\"auto strategy\");\n\n        Assert.assertEquals(0, autoStrategy.getId());\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                GeneratedIdStrategyAuto.class);\n\n        // on auto strategy\n        idGenerator.generateAndSetId(autoStrategy, entityMetadata, CoreTestUtilities.getDelegator(em), kunderaMetadata);\n        Assert.assertTrue(autoStrategy.getId() > 0);\n    }\n\n    @Test\n    public void testSequenceStrategy() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException\n    {\n        IdGenerator idGenerator = new IdGenerator();\n\n        GeneratedIdStrategySequence seqStrategy = new GeneratedIdStrategySequence();\n        seqStrategy.setName(\"sequence strategy\");\n\n        Assert.assertEquals(0, seqStrategy.getId());\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                GeneratedIdStrategySequence.class);\n\n        // on auto strategy\n        idGenerator.generateAndSetId(seqStrategy, entityMetadata, CoreTestUtilities.getDelegator(em), kunderaMetadata);\n        Assert.assertTrue(seqStrategy.getId() > 0);\n\n        try\n        {\n            setInvalidClient(CoreTestUtilities.getDelegator(em));\n            idGenerator.generateAndSetId(seqStrategy, entityMetadata, CoreTestUtilities.getDelegator(em),\n                    kunderaMetadata);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertNotNull(iaex);\n        }\n    }\n\n    @Test\n    public void testIdentityStrategy() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException\n    {\n        IdGenerator idGenerator = new IdGenerator();\n\n        GeneratedIdStrategyIdentity identityStrategy = new GeneratedIdStrategyIdentity();\n        identityStrategy.setName(\"identity strategy\");\n\n        Assert.assertEquals(0, identityStrategy.getId());\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                GeneratedIdStrategyIdentity.class);\n\n        // on auto strategy\n\n        try\n        {\n            idGenerator.generateAndSetId(identityStrategy, entityMetadata, CoreTestUtilities.getDelegator(em),\n                    kunderaMetadata);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertNotNull(usex);\n        }\n    }\n\n    @Test\n    public void testTableStrategy() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException\n    {\n        IdGenerator idGenerator = new IdGenerator();\n\n        GeneratedIdStrategyTable tableStrategy = new GeneratedIdStrategyTable();\n        tableStrategy.setName(\"table strategy\");\n\n        Assert.assertEquals(0, tableStrategy.getId());\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                GeneratedIdStrategyTable.class);\n\n        // on auto strategy\n        idGenerator\n                .generateAndSetId(tableStrategy, entityMetadata, CoreTestUtilities.getDelegator(em), kunderaMetadata);\n        Assert.assertTrue(tableStrategy.getId() > 0);\n\n        try\n        {\n            setInvalidClient(CoreTestUtilities.getDelegator(em));\n            idGenerator.generateAndSetId(tableStrategy, entityMetadata, CoreTestUtilities.getDelegator(em),\n                    kunderaMetadata);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertNotNull(iaex);\n        }\n    }\n\n    private void setInvalidClient(PersistenceDelegator pd) throws NoSuchFieldException, SecurityException\n    {\n        Map<String, Client> clientMap = new HashMap<String, Client>();\n        clientMap.put(persistenceUnit, new CoreTestClientNoGenerator(null, persistenceUnit, kunderaMetadata));\n        PropertyAccessorHelper.set(pd, pd.getClass().getDeclaredField(\"clientMap\"), clientMap);\n    }\n\n    @After\n    public void tearDown()\n    {\n        if (em != null)\n            em.close();\n\n        if (emf != null)\n            emf.close();\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/KunderaCriteriaBuilderTest.java",
    "content": "package com.impetus.kundera.persistence;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Root;\nimport javax.persistence.criteria.Selection;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.query.Person;\n\n/**\n * Junit for {@link CriteriaBuilder}\n * \n * TODO:: \n * 1) support for IN clause\n * 2) Composite object in where clause {Select u from CassandraPrimeUser u where u.key = :key}\n * @author vivek.mishra\n *\n */\npublic class KunderaCriteriaBuilderTest\n{\n    private static final String PU = \"patest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(PU);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testWithoutWhereClause()\n    {\n        String expected = \"Select p from Person p\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n\n        // Check for multi column select\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testSelectedClause()\n    {\n        String expected = \"Select p.personName from Person p\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n\n        // Check for multi column select\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select((Selection) from.get(\"personName\").alias(\"p\"));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testCountClause()\n    {\n        String expected = \"Select Count(p) from Person p\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n\n        CriteriaQuery<Long> personQuery = criteriaBuilder.createQuery(Long.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(criteriaBuilder.count((Expression<?>) from.alias(\"p\")));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testCountWithWhereClause()\n    {\n        String expected = \"Select Count(p) from Person p where p.personName = \\\"vivek\\\" AND p.age = 32\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n\n        CriteriaQuery<Long> personQuery = criteriaBuilder.createQuery(Long.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(criteriaBuilder.count((Expression<?>) from.alias(\"p\")));\n        personQuery.where(criteriaBuilder.and(criteriaBuilder.equal(from.get(\"personName\"), \"vivek\"),\n                criteriaBuilder.equal(from.get(\"age\"), 32)));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testWithWhereClause()\n    {\n        String expected = \"Select p from Person p where p.personName = \\\"vivek\\\"\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        personQuery.where(criteriaBuilder.equal(from.get(\"personName\"), \"vivek\"));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testWithANDClause()\n    {\n        String expected = \"Select p from Person p where p.personName = \\\"vivek\\\" AND p.age = 32\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        personQuery.where(criteriaBuilder.and(criteriaBuilder.equal(from.get(\"personName\"), \"vivek\"),\n                criteriaBuilder.equal(from.get(\"age\"), 32)));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testWithANDGTClause()\n    {\n        String expected = \"Select p from Person p where p.personName = \\\"vivek\\\" AND p.age > 32\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        personQuery.where(criteriaBuilder.and(criteriaBuilder.equal(from.get(\"personName\"), \"vivek\"),\n                criteriaBuilder.gt((Expression) from.get(\"age\"), new Integer(32))));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testWithANDGTEClause()\n    {\n        String expected = \"Select p from Person p where p.personName = \\\"vivek\\\" AND p.age >= 32\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        personQuery.where(criteriaBuilder.and(criteriaBuilder.equal(from.get(\"personName\"), \"vivek\"),\n                criteriaBuilder.ge((Expression) from.get(\"age\"), new Integer(32))));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testWithANDLTClause()\n    {\n        String expected = \"Select p from Person p where p.personName = \\\"vivek\\\" OR p.age < 32\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        personQuery.where(criteriaBuilder.or(criteriaBuilder.equal(from.get(\"personName\"), \"vivek\"),\n                criteriaBuilder.lt((Expression) from.get(\"age\"), new Integer(32))));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testWithORLTEClause()\n    {\n        String expected = \"Select p from Person p where p.personName = \\\"vivek\\\" OR p.age <= 32\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        personQuery.where(criteriaBuilder.or(criteriaBuilder.equal(from.get(\"personName\"), \"vivek\"),\n                criteriaBuilder.le((Expression) from.get(\"age\"), new Integer(32))));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testWithORClause()\n    {\n        String expected = \"Select p from Person p where p.personName = \\\"vivek\\\" OR p.age = 32\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        personQuery.where(criteriaBuilder.or(criteriaBuilder.equal(from.get(\"personName\"), \"vivek\"),\n                criteriaBuilder.equal(from.get(\"age\"), 32)));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testWithBTWClause()\n    {\n        String expected = \"Select p from Person p where p.age BETWEEN 10 AND 20\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        personQuery.where(criteriaBuilder.between((Expression) from.get(\"age\"), 10, 20));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testWithANDBTWClause()\n    {\n        String expected = \"Select p from Person p where p.personName = \\\"'vivek'\\\" AND p.age BETWEEN 10 AND 20\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        personQuery.where(criteriaBuilder.and(criteriaBuilder.equal(from.get(\"personName\"), \"'vivek'\"),\n                criteriaBuilder.between((Expression) from.get(\"age\"), 10, 20)));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testWithMultiANDClause()\n    {\n        String expected = \"Select p from Person p where p.personName = \\\"vivek\\\" AND p.age = 32 AND p.salary = 3200.01\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        personQuery.where(criteriaBuilder.and(criteriaBuilder.equal(from.get(\"personName\"), \"vivek\"),\n                criteriaBuilder.equal(from.get(\"age\"), 32), criteriaBuilder.equal(from.get(\"salary\"), 3200.01)));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testWithANDGTLTClause()\n    {\n        String expected = \"Select p from Person p where p.personName = \\\"vivek\\\" AND p.age > 32 AND p.salary <= 3200.01\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        personQuery.where(criteriaBuilder.and(criteriaBuilder.equal(from.get(\"personName\"), \"vivek\"),\n                criteriaBuilder.gt((Expression) from.get(\"age\"), 32),\n                criteriaBuilder.le((Expression) from.get(\"salary\"), 3200.01)));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testOrderByWithCompositeClause()\n    {\n        final String expected = \"Select u from PersonnelEmbedded u where u.personalDetail.phoneNo = 91234567 ORDER BY u.personalDetail.emailId ASC\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<PersonnelEmbedded> embedQuery = criteriaBuilder.createQuery(PersonnelEmbedded.class);\n        Root<PersonnelEmbedded> from = embedQuery.from(PersonnelEmbedded.class);\n        embedQuery.select(from.alias(\"u\"));\n        embedQuery.orderBy(criteriaBuilder.asc(from.get(\"personalDetail\").get(\"emailId\")));\n        embedQuery.where(criteriaBuilder.equal(from.get(\"personalDetail\").get(\"phoneNo\"), \"91234567\"));\n\n        String actual = CriteriaQueryTranslator.translate(embedQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testOrderByClause()\n    {\n        String expected = \"Select p from Person p ORDER BY p.personName DESC\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n\n        // Check for multi column select\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        personQuery.orderBy(criteriaBuilder.desc(from.get(\"personName\")));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testOrderByWithWhereClause()\n    {\n        String expected = \"Select p from Person p where p.personName = \\\"vivek\\\" AND p.age > 32 AND p.salary <= 3200.01 ORDER BY p.personName DESC\";\n\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.select(from.alias(\"p\"));\n        personQuery.where(criteriaBuilder.and(criteriaBuilder.equal(from.get(\"personName\"), \"vivek\"),\n                criteriaBuilder.gt((Expression) from.get(\"age\"), 32),\n                criteriaBuilder.le((Expression) from.get(\"salary\"), 3200.01)));\n        personQuery.orderBy(criteriaBuilder.desc(from.get(\"personName\")));\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n    @Test\n    public void testMultiSelectedClause()\n    {\n        String expected = \"Select p.personName,p.age from Person p\";\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n\n        // Check for multi column select\n        CriteriaQuery<Person> personQuery = criteriaBuilder.createQuery(Person.class);\n        Root<Person> from = personQuery.from(Person.class);\n        personQuery.multiselect((Selection) from.get(\"personName\").alias(\"p\"), (Selection) from.get(\"age\").alias(\"p\"));\n\n        String actual = CriteriaQueryTranslator.translate(personQuery);\n        Assert.assertEquals(expected.trim(), actual.trim());\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/ObjectGraphBuilderTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence;\n\nimport java.util.Map;\n\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.configure.PersistenceUnitConfiguration;\nimport com.impetus.kundera.graph.BillingCounter;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.ObjectGraph;\nimport com.impetus.kundera.graph.ObjectGraphBuilder;\nimport com.impetus.kundera.graph.Store;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\n\n/**\n * Test case for {@link ObjectGraphBuilder}\n * \n * @author amresh.singh\n */\npublic class ObjectGraphBuilderTest\n{\n    private ObjectGraphBuilder graphBuilder;\n\n    private String _persistenceUnit = \"kunderatest\";\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        EntityManagerFactoryImpl emfImpl = getEntityManagerFactory();\n        new PersistenceUnitConfiguration(null, emfImpl.getKunderaMetadataInstance(), \"kunderatest\").configure();\n        PersistenceCache persistenceCache = new PersistenceCache();\n\n        graphBuilder = new ObjectGraphBuilder(persistenceCache, new PersistenceDelegator(\n                emfImpl.getKunderaMetadataInstance(), persistenceCache));\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.graph.ObjectGraphBuilder#getObjectGraph(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testGetObjectGraph()\n    {\n        Store store = new Store(1, \"Food Bazaar, Noida\");\n        store.addCounter(new BillingCounter(1, \"A\"));\n        store.addCounter(new BillingCounter(2, \"B\"));\n        store.addCounter(new BillingCounter(3, \"C\"));\n\n        ObjectGraph graph = graphBuilder.getObjectGraph(store, null);\n\n        Assert.assertNotNull(graph);\n        Node headNode = graph.getHeadNode();\n        Map<String, Node> nodeMappings = graph.getNodeMapping();\n\n        Assert.assertNotNull(headNode);\n        Assert.assertNotNull(nodeMappings);\n        Assert.assertFalse(nodeMappings.isEmpty());\n        Assert.assertEquals(4, nodeMappings.size());\n\n        Assert.assertTrue(headNode.getParents() == null);\n        Assert.assertEquals(3, headNode.getChildren().size());\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory()\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(_persistenceUnit);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/PersistenceCacheTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence;\n\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.configure.PersistenceUnitConfiguration;\nimport com.impetus.kundera.graph.BillingCounter;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.graph.ObjectGraph;\nimport com.impetus.kundera.graph.ObjectGraphBuilder;\nimport com.impetus.kundera.graph.ObjectGraphUtils;\nimport com.impetus.kundera.graph.Store;\nimport com.impetus.kundera.persistence.context.PersistenceCache;\n\n/**\n * Test case for {@link PersistenceCache}\n * \n * @author amresh.singh\n */\npublic class PersistenceCacheTest\n{\n\n    private PersistenceCache pc;\n\n    private ObjectGraphBuilder graphBuilder;\n\n    private String _persistenceUnit = \"kunderatest\";\n    \n    private EntityManagerFactoryImpl emfImpl;\n\n    // Configurator configurator = new Configurator(\"kunderatest\");\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        pc = new PersistenceCache();\n        emfImpl = getEntityManagerFactory();\n        graphBuilder = new ObjectGraphBuilder(pc, new PersistenceDelegator(emfImpl.getKunderaMetadataInstance(), pc));\n\n        // configurator.configure();\n        new PersistenceUnitConfiguration(null, emfImpl.getKunderaMetadataInstance(), \"kunderatest\").configure();\n        // new MetamodelConfiguration(\"kunderatest\").configure();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    @Test\n    public void testPersistenceCache()\n    {\n        Store store = new Store(1, \"Food Bazaar, Noida\");\n        store.addCounter(new BillingCounter(1, \"A\"));\n        store.addCounter(new BillingCounter(2, \"B\"));\n        store.addCounter(new BillingCounter(3, \"C\"));\n\n        ObjectGraph graph = graphBuilder.getObjectGraph(store, null);\n\n        pc.getMainCache().addGraphToCache(graph, pc);\n\n        Assert.assertNotNull(pc.getMainCache());\n        Assert.assertEquals(1, pc.getMainCache().getHeadNodes().size());\n        \n        PersistenceDelegator pd = new PersistenceDelegator(emfImpl.getKunderaMetadataInstance(), pc);\n\n        Node headNode = pc.getMainCache().getNodeFromCache(ObjectGraphUtils.getNodeId(\"1\", Store.class), pd);\n\n        Assert.assertNotNull(headNode);\n        Assert.assertNull(headNode.getParents());\n        Assert.assertEquals(3, headNode.getChildren().size());\n\n        Assert.assertEquals(4, pc.getMainCache().size());\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory()\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(_persistenceUnit);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/PersistenceDelegatorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.CoreTestClient;\nimport com.impetus.kundera.configure.CoreEntityAddressUni1To1;\nimport com.impetus.kundera.entity.PersonnelDTO;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.entities.AssociationEntity;\nimport com.impetus.kundera.metadata.entities.OToOOwnerEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class PersistenceDelegatorTest\n{\n    private static EntityManagerFactory emf;\n\n    private static EntityManager em;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        \n        emf = Persistence.createEntityManagerFactory(\"kunderatest\");\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    @Test\n    public void testPersist()\n    {\n        try\n        {\n            em.persist(null);\n            Assert.fail(\"A null entity should have thrown exception while persisting\");\n        }\n        catch (Exception e1)\n        {\n            Assert.assertTrue(e1.getCause().getClass().equals(IllegalArgumentException.class));\n        }\n\n        PersonnelDTO dto = new PersonnelDTO();\n        try\n        {\n            em.persist(dto);\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: Entity to be persisted can't have Primary key set to null.\",\n                    e.getMessage());\n        }\n        try\n        {\n            CoreEntityAddressUni1To1 Oneto1 = new CoreEntityAddressUni1To1();\n            em.persist(Oneto1);\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertNotNull(e.getMessage());\n        }\n\n        em.clear();\n\n        dto = new PersonnelDTO();\n        dto.setPersonId(\"123\");\n        em.persist(dto);\n        dto = em.find(PersonnelDTO.class, \"123\");\n        Assert.assertNotNull(dto);\n        Assert.assertEquals(\"123\", dto.getPersonId());\n    }\n\n    @Test\n    public void testFindById()\n    {\n        PersonnelDTO dto = new PersonnelDTO();\n        dto.setPersonId(\"123\");\n        em.persist(dto);\n        try\n        {\n            em.find(null, null);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.assertEquals(\"PrimaryKey value must not be null for object you want to find.\", e.getMessage());\n        }\n        try\n        {\n            em.find(null, 123);\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\"Invalid class provided \" + null, e.getMessage());\n        }\n\n        try\n        {\n            em.find(PersonnelDTO.class, null);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.assertEquals(\"PrimaryKey value must not be null for object you want to find.\", e.getMessage());\n        }\n\n        try\n        {\n            em.find(PersonnelDTO.class, null);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.assertEquals(\"PrimaryKey value must not be null for object you want to find.\", e.getMessage());\n        }\n        dto = em.find(PersonnelDTO.class, \"123\");\n        Assert.assertNotNull(dto);\n    }\n\n    @Test\n    public void testFindForObjectArray()\n    {\n        PersonnelDTO dto = new PersonnelDTO();\n        dto.setPersonId(\"111\");\n        em.persist(dto);\n\n        dto = new PersonnelDTO();\n        dto.setPersonId(\"222\");\n        em.persist(dto);\n\n        dto = new PersonnelDTO();\n        dto.setPersonId(\"333\");\n        em.persist(dto);\n\n        PersistenceDelegator pd = ((EntityManagerImpl) em).getPersistenceDelegator();\n\n        List<PersonnelDTO> persons = pd.find(PersonnelDTO.class, new String[] { \"111\", \"222\", \"333\" });\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n    }\n\n    @Test\n    public void testRemove()\n    {\n        PersonnelDTO paramObject = new PersonnelDTO();\n        PersonnelDTO dto = new PersonnelDTO();\n        dto.setPersonId(\"123\");\n        em.persist(dto);\n        dto = em.find(PersonnelDTO.class, 123);\n        try\n        {\n            em.remove(null);\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\"java.lang.IllegalArgumentException: Entity to be removed must not be null.\",\n                    e.getMessage());\n        }\n\n        em.remove(dto);\n\n        dto = em.find(PersonnelDTO.class, \"123\");\n        Assert.assertNull(dto);\n        try\n        {\n            em.remove(paramObject);\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\"123\", \"123\");\n        }\n\n    }\n\n    @Test\n    public void testMerge()\n    {\n        PersonnelDTO dto = new PersonnelDTO();\n        dto.setPersonId(\"123\");\n        em.persist(dto);\n        dto = em.find(PersonnelDTO.class, 123);\n        Assert.assertNotNull(dto);\n\n        dto.setFirstName(\"kuldeep\");\n        em.merge(dto);\n        dto = em.find(PersonnelDTO.class, 123);\n        Assert.assertNotNull(dto);\n        Assert.assertEquals(\"kuldeep\", dto.getFirstName());\n        try\n        {\n            em.merge(null);\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\"java.lang.IllegalArgumentException: Entity to be merged must not be null.\",\n                    e.getMessage());\n        }\n\n        try\n        {\n            em.merge(new PersonnelDTO());\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\"java.lang.IllegalArgumentException: Entity to be persisted can't have Primary key set to null.\",\n                    e.getMessage());\n        }\n    }\n\n    @Test\n    public void testDetach()\n    {\n        PersonnelDTO dto = new PersonnelDTO();\n        PersistenceDelegator pd = ((EntityManagerImpl) em).getPersistenceDelegator();\n        try\n        {\n            pd.detach(dto);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.assertEquals(\"Primary key not set into entity\", e.getMessage());\n        }\n\n        dto.setPersonId(\"123\");\n        try\n        {\n            pd.detach(dto);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail();\n        }\n\n        Assert.assertFalse(pd.contains(dto));\n\n        em.persist(dto);\n\n        pd.detach(dto);\n\n        Assert.assertFalse(pd.contains(dto));\n    }\n\n    @Test\n    public void testGetClient()\n    {\n        PersonnelDTO dto = new PersonnelDTO();\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance(), dto.getClass());\n        PersistenceDelegator pd = ((EntityManagerImpl) em).getPersistenceDelegator();\n        Client c = pd.getClient(entityMetadata);\n        Assert.assertNotNull(c);\n        Assert.assertTrue(c instanceof CoreTestClient);\n\n    }\n\n    @Test\n    public void testIsOpen()\n    {\n        PersistenceDelegator pd = ((EntityManagerImpl) em).getPersistenceDelegator();\n        Assert.assertTrue(pd.isOpen());\n\n        pd.close();\n        Assert.assertFalse(pd.isOpen());\n    }\n\n    @Test\n    public void testClose()\n    {\n        PersistenceDelegator pd = ((EntityManagerImpl) em).getPersistenceDelegator();\n        Assert.assertTrue(pd.isOpen());\n\n        pd.close();\n        Assert.assertFalse(pd.isOpen());\n        Assert.assertTrue(pd.getDelegate().isEmpty());\n\n    }\n\n    @Test\n    public void testContains()\n    {\n        PersonnelDTO dto = new PersonnelDTO();\n        dto.setPersonId(\"123\");\n        PersistenceDelegator pd = ((EntityManagerImpl) em).getPersistenceDelegator();\n\n        Assert.assertFalse(pd.contains(dto));\n\n        em.persist(dto);\n        pd = ((EntityManagerImpl) em).getPersistenceDelegator();\n        Assert.assertTrue(pd.contains(dto));\n\n        em.clear();\n\n        pd = ((EntityManagerImpl) em).getPersistenceDelegator();\n        Assert.assertFalse(pd.contains(dto));\n    }\n\n    @Test\n    public void testRefresh()\n    {\n        PersonnelDTO dto = new PersonnelDTO();\n        dto.setPersonId(\"123\");\n        PersistenceDelegator pd = ((EntityManagerImpl) em).getPersistenceDelegator();\n\n        try\n        {\n            pd.refresh(dto);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.assertEquals(\"This is not a valid or managed entity, can't be refreshed\", e.getMessage());\n        }\n\n        em.persist(dto);\n        pd = ((EntityManagerImpl) em).getPersistenceDelegator();\n\n        try\n        {\n            em.refresh(dto);\n        }\n        catch (NullPointerException e)\n        {\n            Assert.assertTrue(true);\n        }\n        em.clear();\n\n        pd = ((EntityManagerImpl) em).getPersistenceDelegator();\n        try\n        {\n            pd.refresh(dto);\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.assertEquals(\"This is not a valid or managed entity, can't be refreshed\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testCreateQueryWithNull()\n    {\n        PersistenceDelegator pd = ((EntityManagerImpl) em).getPersistenceDelegator();\n        try\n        {\n            pd.createQuery(null);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (QueryHandlerException qhex)\n        {\n            Assert.assertEquals(\"Query String should not be null \", qhex.getMessage());\n        }\n    }\n\n    @Test\n    public void testPopulateClientProperties()\n    {\n        Map props = new HashMap();\n        props.put(\"core.test.property\", \"core-test-property-value\");\n\n        PersistenceDelegator pd = ((EntityManagerImpl) em).getPersistenceDelegator();\n        pd.populateClientProperties(props);\n\n        Map map = em.getProperties();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        CoreTestClient client = (CoreTestClient) clients.get(\"kunderatest\");\n        Assert.assertEquals(\"core-test-property-value\", client.getCoreTestProperty());\n\n    }\n\n    @Test\n    public void testEntityState()\n    {/*\n        EntityManagerFactory emf1 = Persistence.createEntityManagerFactory(\"keyspace\");\n        EntityManager em1 = emf1.createEntityManager();\n\n        PersistenceDelegator pd = ((EntityManagerImpl) em1).getPersistenceDelegator();\n\n        persist(pd);\n\n        OToOOwnerEntity found = pd.find(OToOOwnerEntity.class, (byte) 1);\n\n        assertOnFind(found);\n\n        AssociationEntity association = new AssociationEntity();\n        association.setAddress(\"noida\");\n        association.setAge(12);\n        association.setRowKey(\"address1\");\n\n        applyOperations(pd, found, association, true);\n\n        pd.doFlush();\n        pd.clear();\n\n        found = pd.find(OToOOwnerEntity.class, (byte) 1); // as already removed.\n        Assert.assertNull(found);\n\n        persist(pd); // again persist.\n\n        found = pd.find(OToOOwnerEntity.class, (byte) 1);\n        assertOnFind(found);\n\n        found.setAssociation(association);\n\n        applyOperations(pd, found, association, false);\n\n        pd.detach(association);\n\n        try\n        {\n            pd.remove(found);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (IllegalArgumentException iex)\n        {\n            Assert.assertNotNull(iex.getMessage());\n        }\n    */}\n\n    private void assertOnFind(OToOOwnerEntity found)\n    {\n        Assert.assertNotNull(found);\n        Assert.assertNull(found.getAssociation());\n    }\n\n    private void persist(PersistenceDelegator pd)\n    {\n        OToOOwnerEntity owner;\n        owner = new OToOOwnerEntity();\n        owner.setAmount(10);\n        owner.setName(\"owner1\");\n        owner.setRowKey((byte) 1);\n        // pd = ((EntityManagerImpl) em1).getPersistenceDelegator();\n\n        pd.persist(owner);\n\n        pd.doFlush();\n        pd.clear();\n    }\n\n    private void applyOperations(PersistenceDelegator pd, OToOOwnerEntity found, AssociationEntity association,\n            boolean remove)\n    {\n        found.setAssociation(association);\n        pd.merge(found);\n\n        pd.doFlush();\n\n        pd.detach(association);\n\n        pd.merge(found); // detach over association entity should work.\n\n        if (remove)\n            pd.remove(found); // since we have called merge, so association\n                              // entity should be in MANAGED_STATE and cascade\n                              // should work.\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/PersistenceUnitLoaderTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Enumeration;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.loader.PersistenceXMLLoader;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * Unit test case to load persistence.xml properties.\n * \n * @author vivek.mishra\n * \n */\npublic class PersistenceUnitLoaderTest\n{\n    /** logger instance */\n    private static final Logger log = LoggerFactory.getLogger(PersistenceUnitLoaderTest.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        // do nothing.\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        // do nothing.\n    }\n\n    /**\n     * Test method on persistence unit loading.\n     */\n    @Test\n    public void testLoadPersistenceUnitLoading()\n    {\n        try\n        {\n            Enumeration<URL> xmls = this.getClass().getClassLoader()\n                    .getResources(\"META-INF/persistence.xml\");\n\n            while (xmls.hasMoreElements())\n            {\n                String[] persistenceUnits = new String[12];\n                persistenceUnits[0] = \"kunderatest\";\n                persistenceUnits[1] = \"PropertyTest\";\n                persistenceUnits[2] = \"PropertyTestwithvaraiable\";\n                persistenceUnits[3] = \"PropertyTestwithabsolutepath\";\n                persistenceUnits[4] = \"metaDataTest\";\n                persistenceUnits[5] = \"GeneratedValue\";\n                persistenceUnits[6] = \"patest\";\n                persistenceUnits[7] = \"mappedsu\";\n                persistenceUnits[8] = \"invalidmappedsu\";\n                persistenceUnits[9] = \"keyspace\";\n                persistenceUnits[10] = \"inheritanceTest\";\n                persistenceUnits[11] = \"extConfig\";\n                \n                final String _pattern = \"/core/target/test-classes/\";\n                List<PersistenceUnitMetadata> metadatas = PersistenceXMLLoader.findPersistenceUnits(xmls.nextElement(), persistenceUnits);\n                Assert.assertNotNull(metadatas);\n                Assert.assertEquals(12, metadatas.size());\n\n                // commented out to keep ConfiguratorTest happy! as it tries to\n                // load it.\n                // Assert.assertEquals(2,\n                // metadatas.get(0).getJarFiles().size());\n\n                Assert.assertEquals(56, metadatas.get(0).getClasses().size());\n                Assert.assertNotNull(metadatas.get(0).getPersistenceUnitRootUrl());\n                Assert.assertTrue(metadatas.get(0).getPersistenceUnitRootUrl().getPath().endsWith(_pattern));\n            }\n        }\n        catch (IOException ioex)\n        {\n            log.error(ioex.getMessage());\n            Assert.fail();\n        }\n        catch (Exception e)\n        {\n            log.error(e.getMessage());\n            Assert.fail();\n        }\n\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/PersistenceValidatorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * @author amresh.singh\n *\n */\npublic class PersistenceValidatorTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.persistence.PersistenceValidator#isValidEntityObject(java.lang.Object)}.\n     */\n    @Test\n    public void testIsValidEntityObject()\n    {\n        Assert.assertFalse(new PersistenceValidator().isValidEntityObject(null, null));\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/PersonalDetailEmbedded.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.persistence;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Embeddable\npublic class PersonalDetailEmbedded\n{\n    @Column(name=\"PHONENO\")\n    private long phoneNo;\n\n    private String emailId;\n\n    private String address;\n\n\n    public String getEmailId()\n    {\n        return emailId;\n    }\n\n    public void setEmailId(String emailId)\n    {\n        this.emailId = emailId;\n    }\n\n    public String getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    public long getPhoneNo()\n    {\n        return phoneNo;\n    }\n\n    public void setPhoneNo(long phoneNo)\n    {\n        this.phoneNo = phoneNo;\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/PersonnelEmbedded.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * \n * @author Kuldeep Mishra\n *\n */\n@Table(name = \"PERSONNEL\")\n@Entity\npublic class PersonnelEmbedded\n{\n    @Id\n    @Column\n    private int id;\n\n    @Column\n    private String name;\n\n    @Column\n    private int age;\n\n    @Embedded\n    private PersonalDetailEmbedded personalDetail;\n\n    public int getId()\n    {\n        return id;\n    }\n\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public PersonalDetailEmbedded getPersonalDetail()\n    {\n        return personalDetail;\n    }\n\n    public void setPersonalDetail(PersonalDetailEmbedded personalDetail)\n    {\n        this.personalDetail = personalDetail;\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/User.java",
    "content": "package com.impetus.kundera.persistence;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"user\")\npublic class User\n{\n    @Id\n    @GeneratedValue(strategy = GenerationType.TABLE)\n    @Column(name = \"key\")\n    private Long userId;\n\n    @Column(name = \"first_name\")\n    private String firstName;\n\n    @Column(name = \"last_name\")\n    private String lastName;\n\n    @Column(name = \"city\")\n    private String city;\n\n    public User()\n    {\n    }\n\n    public Long getUserId()\n    {\n        return userId;\n    }\n\n    public void setUserId(Long userId)\n    {\n        this.userId = userId;\n    }\n\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n    public String getCity()\n    {\n        return city;\n    }\n\n    public void setCity(String city)\n    {\n        this.city = city;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/context/FlushStackTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.persistence.context;\n\nimport java.util.Deque;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.graph.Node;\n\n/**\n * Test case for {@link FlushStack}\n * \n * @author amresh.singh\n */\npublic class FlushStackTest\n{\n\n    Deque<Node> fs;\n\n    FlushManager flushManager;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        flushManager = new FlushManager();\n\n        fs = flushManager.getFlushStack();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    @Test\n    public void testFlushStackPush()\n    {\n        PersistenceCache pc = new PersistenceCache();\n        fs.push(new Node(\"A\", new Object().getClass(), null, pc, \"A\", null));\n        fs.push(new Node(\"B\", new Object().getClass(), null, pc, \"B\", null));\n        fs.push(new Node(\"C\", new Object().getClass(), null, pc, \"C\", null));\n        fs.push(new Node(\"D\", new Object().getClass(), null, pc, \"D\", null));\n\n        Assert.assertEquals(4, fs.size());\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/context/PersistenceCacheManagerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.context;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * Test case for {@link PersistenceCacheManager}\n * @author amresh.singh\n *\n */\npublic class PersistenceCacheManagerTest\n{\n    PersistenceCacheManager pcm;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        PersistenceCache pc = new PersistenceCache();\n        pcm = new PersistenceCacheManager(pc);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        pcm = null;\n        \n    }\n\n\n    /**\n     * Test method for {@link com.impetus.kundera.persistence.context.PersistenceCacheManager#clearPersistenceCache()}.\n     */\n    @Test\n    public void testClearPersistenceCache()\n    {\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.persistence.context.PersistenceCacheManager#markAllNodesNotTraversed()}.\n     */\n    @Test\n    public void testMarkAllNodesNotTraversed()\n    {\n\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.persistence.context.PersistenceCacheManager#addEntityToPersistenceCache(java.lang.Object, com.impetus.kundera.persistence.PersistenceDelegator, java.lang.Object)}.\n     */\n    @Test\n    public void testAddEntityToPersistenceCache()\n    {\n\n    }\n    \n    private void buildNodes()\n    {\n       // pcm.addEntityToPersistenceCache(new Perso, pd, entityId)\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/context/jointable/JoinTableMetadataTest.java",
    "content": "package com.impetus.kundera.persistence.context.jointable;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData.OPERATION;\nimport com.impetus.kundera.polyglot.entities.PersonBMM;\n\npublic class JoinTableMetadataTest\n{\n\n    @Test\n    public void test()\n    {\n        JoinTableData joinTableData = new JoinTableData(OPERATION.INSERT,\"test\",null,null,null,null);\n        Assert.assertNotNull(joinTableData);\n        Assert.assertEquals(OPERATION.INSERT, joinTableData.getOperation());\n        Assert.assertNull(joinTableData.getJoinColumnName());\n        joinTableData.setJoinColumnName(\"testjoinColumn\");\n        Assert.assertNotNull(joinTableData.getJoinColumnName());\n        Assert.assertNull(joinTableData.getInverseJoinColumnName());\n        joinTableData.setInverseJoinColumnName(\"testInverseJoinColumn\");\n        Assert.assertNotNull(joinTableData.getInverseJoinColumnName());\n        Assert.assertNull(joinTableData.getJoinTableName());\n        joinTableData.setJoinTableName(\"testJoinTable\");\n        Assert.assertNotNull(joinTableData.getJoinTableName());\n        joinTableData.setOperation(OPERATION.DELETE);\n        \n       Assert.assertNull(joinTableData.getEntityClass());\n       joinTableData.setEntityClass(PersonBMM.class);\n       Assert.assertNotNull(joinTableData.getEntityClass());\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/event/AddressEntity.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.event;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.PrePersist;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *  Address entity with internal call backs.\n */\n@Entity\n@Table(name = \"ADDRESS\", schema = \"KunderaTest@kunderatest\")\npublic class AddressEntity\n{\n    @Id\n    private String addressId;\n    \n    @Column\n    private String street;\n    \n    @Column\n    private String city;\n\n    @Column \n    private String fullAddress;\n    \n    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)\n    private Set<AddressEntity> subaddresses;\n    \n    \n    public AddressEntity()\n    {\n        \n    }\n    \n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public String getCity()\n    {\n        return city;\n    }\n\n    public void setCity(String city)\n    {\n        this.city = city;\n    }\n    \n    @PrePersist\n    public void  populateFullAddress()\n    {\n        this.fullAddress = street+\",\"+city;\n    }\n    \n    public String getFullAddress()\n    {\n        return this.fullAddress;\n    }\n\n    public Set<AddressEntity> getSubaddresses()\n    {\n        return subaddresses;\n    }\n\n    public void setSubaddresses(Set<AddressEntity> subaddresses)\n    {\n        this.subaddresses = subaddresses;\n    }\n\n \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/event/AddressEntityWithList.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.event;\n\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.PrePersist;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *  Address entity with internal call backs.\n */\n@Entity\n@Table(name = \"ADDRESS\", schema = \"KunderaTest@kunderatest\")\npublic class AddressEntityWithList\n{\n    @Id\n    private String addressId;\n    \n    @Column\n    private String street;\n    \n    @Column\n    private String city;\n\n    @Column \n    private String fullAddress;\n    \n    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)\n    private List<AddressEntityWithList> subaddresses;\n    \n    \n    public AddressEntityWithList()\n    {\n        \n    }\n    \n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public String getCity()\n    {\n        return city;\n    }\n\n    public void setCity(String city)\n    {\n        this.city = city;\n    }\n    \n    @PrePersist\n    public void  populateFullAddress()\n    {\n        this.fullAddress = street+\",\"+city;\n    }\n    \n    public String getFullAddress()\n    {\n        return this.fullAddress;\n    }\n\n    public List<AddressEntityWithList> getSubaddresses()\n    {\n        return subaddresses;\n    }\n\n    public void setSubaddresses(List<AddressEntityWithList> subaddresses)\n    {\n        this.subaddresses = subaddresses;\n    }\n\n \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/event/EntityEventDispatcherTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.event;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.PostLoad;\nimport javax.persistence.PostPersist;\nimport javax.persistence.PrePersist;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * Test case for {@link EntityEventDispatcher}\n * \n * @author amresh.singh\n * \n */\npublic class EntityEventDispatcherTest\n{\n\n    private EntityEventDispatcher eventDispatcher;\n\n    private EntityManager em;\n\n    private EntityManagerFactory emf;\n\n    private KunderaMetadata kunderaMetadata;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        eventDispatcher = new EntityEventDispatcher();\n\n        emf = Persistence.createEntityManagerFactory(\"kunderatest\");\n        kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        eventDispatcher = null;\n        em.close();\n        emf.close();\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.persistence.event.EntityEventDispatcher#fireEventListeners(com.impetus.kundera.metadata.model.EntityMetadata, java.lang.Object, java.lang.Class)}\n     * .\n     * \n     * @throws SecurityException\n     * @throws NoSuchMethodException\n     */\n    @Test\n    public void testExternalFireEventListeners() throws NoSuchMethodException, SecurityException\n    {\n        PersonEventDispatch person = new PersonEventDispatch(\"1\", \"John\", \"Smith\");\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, person.getClass());\n        eventDispatcher.fireEventListeners(m, person, PrePersist.class);\n        Assert.assertEquals(\"Amresh\", person.getFirstName());\n        Assert.assertEquals(\"Smith\", person.getLastName());\n        eventDispatcher.fireEventListeners(m, person, PostPersist.class);\n        Assert.assertEquals(\"Amresh\", person.getFirstName());\n        Assert.assertEquals(\"Singh\", person.getLastName());\n\n        eventDispatcher.fireEventListeners(m, person, PostLoad.class);\n        eventDispatcher.fireEventListeners(m, null, PostLoad.class);\n        Assert.assertEquals(\"Amresh\", person.getFirstName());\n        Assert.assertEquals(\"Post Load\", person.getLastName());\n\n        try\n        {\n            ExternalCallbackMethod callback = new ExternalCallbackMethod(PersonEventDispatch.class,\n                    PersonEventDispatch.class.getDeclaredMethod(\"getFirstName\", null));\n            AddressEntity address = new AddressEntity();\n            address.setAddressId(\"addr1\");\n            address.setStreet(\"street\");\n            address.setCity(\"noida\");\n            callback.invoke(address);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (EventListenerException elex)\n        {\n            Assert.assertNotNull(elex);\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.persistence.event.EntityEventDispatcher#fireEventListeners(com.impetus.kundera.metadata.model.EntityMetadata, java.lang.Object, java.lang.Class)}\n     * .\n     * \n     * @throws SecurityException\n     * @throws NoSuchMethodException\n     */\n    @Test\n    public void testInternalFireEventListeners() throws NoSuchMethodException, SecurityException\n    {\n        AddressEntity address = new AddressEntity();\n        address.setAddressId(\"addr1\");\n        address.setStreet(\"street\");\n        address.setCity(\"noida\");\n\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, address.getClass());\n        eventDispatcher.fireEventListeners(m, address, PrePersist.class);\n        eventDispatcher.fireEventListeners(m, null, PrePersist.class);\n        Assert.assertEquals(\"addr1\", address.getAddressId());\n        Assert.assertEquals(\"noida\", address.getCity());\n        Assert.assertEquals(\"street,noida\", address.getFullAddress());\n\n        try\n        {\n            InternalCallbackMethod callback = new InternalCallbackMethod(m, AddressEntity.class.getDeclaredMethod(\n                    \"getStreet\", null));\n            PersonEventDispatch person = new PersonEventDispatch(\"1\", \"John\", \"Smith\");\n            callback.invoke(person);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (EventListenerException elex)\n        {\n            Assert.assertNotNull(elex);\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/event/PersonEventDispatch.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.persistence.event;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.EntityListeners;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * The Class PersonnelDTO.\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"person\", schema = \"KunderaTest@kunderatest\")\r\n@EntityListeners({ PersonHandler.class })\r\npublic class PersonEventDispatch\r\n{\r\n\r\n    /** The person id. */\r\n    @Id\r\n    private String personId;\r\n\r\n    /** The first name. */\r\n    @Column(name = \"first_name\")\r\n    private String firstName;\r\n\r\n    /** The last name. */\r\n    @Column(name = \"last_name\")\r\n    private String lastName;\r\n\r\n    /**\r\n     * Instantiates a new personnel dto.\r\n     * \r\n     * @param personId\r\n     *            the person id\r\n     * @param firstName\r\n     *            the first name\r\n     * @param lastName\r\n     *            the last name\r\n     */\r\n    public PersonEventDispatch(String personId, String firstName, String lastName)\r\n    {\r\n        this.personId = personId;\r\n        this.firstName = firstName;\r\n        this.lastName = lastName;\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new personnel dto.\r\n     */\r\n    public PersonEventDispatch()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * Gets the person id.\r\n     * \r\n     * @return the personId\r\n     */\r\n    public String getPersonId()\r\n    {\r\n        return personId;\r\n    }\r\n\r\n    /**\r\n     * Sets the person id.\r\n     * \r\n     * @param personId\r\n     *            the personId to set\r\n     */\r\n    public void setPersonId(String personId)\r\n    {\r\n        this.personId = personId;\r\n    }\r\n\r\n    /**\r\n     * Gets the first name.\r\n     * \r\n     * @return the firstName\r\n     */\r\n    public String getFirstName()\r\n    {\r\n        return firstName;\r\n    }\r\n\r\n    /**\r\n     * Sets the first name.\r\n     * \r\n     * @param firstName\r\n     *            the firstName to set\r\n     */\r\n    public void setFirstName(String firstName)\r\n    {\r\n        this.firstName = firstName;\r\n    }\r\n\r\n    /**\r\n     * Gets the last name.\r\n     * \r\n     * @return the lastName\r\n     */\r\n    public String getLastName()\r\n    {\r\n        return lastName;\r\n    }\r\n\r\n    /**\r\n     * Sets the last name.\r\n     * \r\n     * @param lastName\r\n     *            the lastName to set\r\n     */\r\n    public void setLastName(String lastName)\r\n    {\r\n        this.lastName = lastName;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/event/PersonHandler.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.event;\n\nimport javax.persistence.PostLoad;\nimport javax.persistence.PostPersist;\nimport javax.persistence.PrePersist;\n\npublic class PersonHandler\n{\n\n    @PrePersist\n    public void handledPrePersist(PersonEventDispatch user)\n    {\n        user.setFirstName(\"Amresh\");\n    }\n\n    @PostPersist\n    public void handledPostPersist(PersonEventDispatch user)\n    {\n        user.setLastName(\"Singh\");\n    }\n    \n    @PostLoad\n    public void handledPostLoad(PersonEventDispatch user)\n    {\n        //if(user != null)\n        {\n            user.setLastName(\"Post Load\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/jta/KunderaJTAUserTransactionTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.jta;\n\nimport javax.naming.Context;\nimport javax.naming.InitialContext;\nimport javax.transaction.HeuristicMixedException;\nimport javax.transaction.HeuristicRollbackException;\nimport javax.transaction.NotSupportedException;\nimport javax.transaction.RollbackException;\nimport javax.transaction.Status;\nimport javax.transaction.SystemException;\nimport javax.transaction.UserTransaction;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * Junit test case for {@link KunderaJTAUserTransaction}.\n * \n * @author vivek.mishra\n * \n */\npublic class KunderaJTAUserTransactionTest\n{\n    private UserTransaction utx;\n\n    /**\n     * Static initialisation and binding UserTransaction.\n     * \n     * @throws java.lang.Exception\n     */\n    @BeforeClass\n    public static void setUp() throws Exception\n    {\n        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.naming.java.javaURLContextFactory\");\n        System.setProperty(Context.URL_PKG_PREFIXES, \"org.apache.naming\");\n\n        Context ctx = new InitialContext();\n        ctx.createSubcontext(\"java:comp\");\n        // This is what we need to bind to get handle of JTA's\n        // UserTransaction.\n\n        ctx.bind(\"java:comp/UserTransaction\", new KunderaJTAUserTransaction());\n\n    }\n\n    /**\n     * Context lookup on before running each method.\n     * \n     * @throws Exception\n     */\n    @Before\n    public void setup() throws Exception\n    {\n        Context ctx = new InitialContext();\n        utx = (UserTransaction) ctx.lookup(\"java:comp/UserTransaction\");\n\n    }\n\n    /**\n     * Method to test positive scenario: A) begin transaction. B) assertion on\n     * invocation of commit method.\n     */\n    @Test\n    public void testInitializeViaLookup()\n    {\n        try\n        {\n            Assert.assertNotNull(utx);\n            Assert.assertSame(KunderaJTAUserTransaction.class, utx.getClass());\n            utx.begin();\n            Assert.assertEquals(Status.STATUS_ACTIVE, utx.getStatus());\n            // pass true, as transaction has already begun.\n            assertOnCommit(utx, true);\n        }\n\n        catch (NotSupportedException nsuex)\n        {\n            Assert.fail(nsuex.getMessage());\n        }\n        catch (SystemException ex)\n        {\n            Assert.fail(ex.getMessage());\n        }\n    }\n\n    /**\n     * Test case for: A) utx.begin was not invoked. B) Assert on invalid commit.\n     */\n    @Test\n    public void testInvalidCommit()\n    {\n        try\n        {\n            Assert.assertNotNull(utx);\n            Assert.assertSame(KunderaJTAUserTransaction.class, utx.getClass());\n            // pass false, as transaction has not begun.\n            assertOnCommit(utx, false);\n        }\n        catch (SystemException ex)\n        {\n            Assert.fail(ex.getMessage());\n        }\n    }\n\n    private void assertOnCommit(UserTransaction utx, boolean isValid) throws SystemException\n    {\n        try\n        {\n            utx.commit();\n            Assert.assertEquals(Status.STATUS_NO_TRANSACTION, utx.getStatus());\n        }\n        catch (KunderaException kex)\n        {\n            if (!isValid)\n            {\n                Assert.assertSame(\"No transaction in progress.\", kex.getMessage());\n            }\n            else\n            {\n                Assert.fail(kex.getMessage());\n            }\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalStateException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (RollbackException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (HeuristicMixedException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (HeuristicRollbackException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Method to test rollback\n     */\n    @Test\n    public void testRollback()\n    {\n        try\n        {\n            Assert.assertNotNull(utx);\n            Assert.assertSame(KunderaJTAUserTransaction.class, utx.getClass());\n\n            // Rollback without begin of transaction.\n            try\n            {\n                utx.rollback();\n                Assert.fail(\"Should have gone to catch block1\");\n            }\n            catch (IllegalStateException isex)\n            {\n                Assert.assertEquals(\"Cannot locate a Transaction for rollback.\", isex.getMessage());\n            }\n\n            utx.begin();\n            Assert.assertEquals(Status.STATUS_ACTIVE, utx.getStatus());\n\n            // rollback transaction.\n            utx.rollback();\n            Assert.assertEquals(Status.STATUS_NO_TRANSACTION, utx.getStatus());\n\n        }\n\n        catch (NotSupportedException nsuex)\n        {\n            Assert.fail(nsuex.getMessage());\n        }\n        catch (SystemException ex)\n        {\n            Assert.fail(ex.getMessage());\n        }\n    }\n\n    @Test\n    public void testTransactionTimeOut() throws SystemException, NotSupportedException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException\n    {\n        Assert.assertNotNull(utx);\n        Assert.assertSame(KunderaJTAUserTransaction.class, utx.getClass());\n\n        // set timeout before running transaction.\n        utx.setTransactionTimeout(20);\n        Assert.assertEquals(20, ((KunderaJTAUserTransaction) utx).getTransactionTimeout());\n\n        utx.setTransactionTimeout(0);\n        // try after beginning transaction.\n        utx.begin();\n\n        utx.setTransactionTimeout(202);\n        Assert.assertEquals(0, ((KunderaJTAUserTransaction) utx).getTransactionTimeout());\n        \n        utx.commit();\n    }\n\n    @Test\n    public void testMarkedRollback() throws SystemException, NotSupportedException\n    {\n        Assert.assertNotNull(utx);\n        Assert.assertSame(KunderaJTAUserTransaction.class, utx.getClass());\n\n        try\n        {\n            utx.setRollbackOnly();\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (IllegalStateException iaex)\n        {\n            Assert.assertEquals(\"Cannot get Transaction for setRollbackOnly\", iaex.getMessage());\n        }\n\n        // try after beginning transaction.\n        utx.begin();\n        utx.setRollbackOnly();\n        Assert.assertEquals(Status.STATUS_MARKED_ROLLBACK, utx.getStatus());\n        utx.rollback();\n    }\n\n    \n    @After\n    public void tearDown()\n    {\n        utx = null;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/persistence/jta/KunderaTransactionTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.persistence.jta;\n \nimport javax.transaction.HeuristicMixedException;\nimport javax.transaction.HeuristicRollbackException;\nimport javax.transaction.RollbackException;\nimport javax.transaction.Status;\nimport javax.transaction.SystemException;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.persistence.ResourceManager;\n\n/**\n * @author vivek.mishra\n * junit for {@link KunderaTransaction}\n *\n */\npublic class KunderaTransactionTest\n{\n\n    @Test\n    public void test() throws SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException, SystemException\n    {\n        KunderaTransaction tx = new KunderaTransaction(1000); //create new instance.\n        tx.setImplementor(new DummyResourceImplementor()); // add resource implementor\n        Assert.assertEquals(Status.STATUS_ACTIVE, tx.getStatus());\n        tx.commit(); // on commit                                      \n        Assert.assertEquals(Status.STATUS_COMMITTED, tx.getStatus());\n        tx.setRollbackOnly(); // set rollback only\n        Assert.assertEquals(Status.STATUS_MARKED_ROLLBACK, tx.getStatus());\n        \n        tx.commit();\n        Assert.assertNotSame(Status.STATUS_COMMITTED, tx.getStatus());\n        Assert.assertFalse(tx.delistResource(null, 0));  // no implementation, will always return false.\n        Assert.assertFalse(tx.enlistResource(null));     // no implementation, will always return false.\n        Assert.assertEquals(1000,tx.getTransactionTimeout());  // get transaction time out\n        \n        tx.rollback();\n        Assert.assertEquals(Status.STATUS_ROLLEDBACK, tx.getStatus());\n        \n        try\n        {\n            tx.registerSynchronization(null);\n            Assert.fail(\"Should have gone to catch block!\");\n        }catch(UnsupportedOperationException uoex)\n        {\n            Assert.assertNotNull(uoex.getMessage());\n        }\n        \n        \n        \n    }\n\n    \n    private class DummyResourceImplementor implements ResourceManager\n    {\n\n        @Override\n        public void doCommit()\n        {\n            // Do nothing.\n            \n        }\n\n        @Override\n        public void doRollback()\n        {\n            // Do nothing.\n            \n        }\n        \n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/dao/BaseDao.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.dao;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\npublic class BaseDao\n{\n\n    EntityManagerFactory emf;\n\n    EntityManager em;\n\n    Map propertyMap=null;\n    \n            public EntityManager getEntityManager(String pu)\n    {\n        if (emf == null)\n        {\n            propertyMap=new HashMap<String, String>();\n            propertyMap.put(\"index.home.dir\",\"./lucene\");\n            emf = Persistence.createEntityManagerFactory(pu, propertyMap);\n            em = emf.createEntityManager();\n        }\n\n        if (em == null)\n        {\n            em = emf.createEntityManager();\n        }\n\n        return em;\n    }\n\n    public void closeEntityManager()\n    {\n        if (em != null)\n        {\n            em.close();\n            em = null;\n        }\n    }\n\n    public void closeEntityManagerFactory()\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n        emf = null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/dao/PersonAddressDaoImpl.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.dao;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\npublic class PersonAddressDaoImpl extends BaseDao\n{\n    private String persistenceUnit;\n\n    public PersonAddressDaoImpl(String pu)\n    {\n        this.persistenceUnit = pu;\n    }\n\n    public Query createQuery(String query)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n        Query q = em.createQuery(query);\n        return q;\n    }\n\n    public void insert(Object person)\n    {\n        em = getEntityManager(persistenceUnit);\n        em.persist(person);\n        closeEntityManager();\n    }\n\n    public void update(Object obj)\n    {\n        em.merge(obj);\n        closeEntityManager();\n    }\n\n    public Object findPerson(Class entityClass, Object personId)\n    {\n        em = getEntityManager(persistenceUnit);\n        Object personnel = em.find(entityClass, personId);\n        return personnel;\n    }\n\n    public void savePersons(Set<?> personnels)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n\n        for (Object personnel : personnels)\n        {\n            em.persist(personnel);\n        }\n\n        closeEntityManager();\n    }\n\n    public void remove(Object pKey, Class clazz)\n    {\n        em = getEntityManager(persistenceUnit);\n        Object obj = em.find(clazz, pKey);\n        em.remove(obj);\n        closeEntityManager();\n    }\n\n    public void merge(Object modifiedObj)\n    {\n        em = getEntityManager(persistenceUnit);\n        em.merge(modifiedObj);\n        closeEntityManager();\n\n    }\n\n    public List<?> getAllPersons(String className)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n        Query q = em.createQuery(\"select p from \" + className + \" p\");\n        List<?> persons = q.getResultList();\n        closeEntityManager();\n        return persons;\n    }\n\n    public Object findPersonByIdColumn(Class entityClass, Object personId)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n        String query = \"Select p from \" + entityClass.getSimpleName() + \" p where p.personId = \" + personId;\n        Query q = em.createQuery(query);\n        List persons = q.getResultList();\n        //closeEntityManager();\n        assert persons != null;\n        assert !persons.isEmpty();\n        assert persons.size() == 1;\n\n        return persons.get(0);\n    }\n\n    public List findPersonByName(Class entityClass, String personName)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n        String query = \"Select p from \" + entityClass.getSimpleName() + \" p where p.personName = \" + personName;\n        Query q = em.createQuery(query);\n        List persons = q.getResultList();\n        //closeEntityManager();\n\n        return persons;\n    }\n\n    public Object findAddressByIdColumn(Class entityClass, Object addressId)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n        String query = \"Select a from \" + entityClass.getSimpleName() + \" a where a.addressId = \" + addressId;\n        Query q = em.createQuery(query);\n        List addresses = q.getResultList();\n        closeEntityManager();\n        assert addresses != null;\n        assert !addresses.isEmpty();\n        assert addresses.size() == 1;\n\n        return addresses.get(0);\n    }\n\n    public List findAddressByStreet(Class entityClass, String street)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n        String query = \"Select a from \" + entityClass.getSimpleName() + \" a where a.street = \" + street;\n        Query q = em.createQuery(query);\n        List addresses = q.getResultList();\n        closeEntityManager();\n\n        return addresses;\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/AddressB11FK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressB11FK\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @OneToOne(mappedBy = \"address\", fetch = FetchType.LAZY)\n    private PersonB11FK person;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public PersonB11FK getPerson()\n    {\n        return person;\n    }\n\n    public void setPerson(PersonB11FK person)\n    {\n        this.person = person;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/AddressB11PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressB11PK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @OneToOne(mappedBy = \"address\", fetch = FetchType.LAZY)\n    private PersonB11PK person;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public PersonB11PK getPerson()\n    {\n        return person;\n    }\n\n    public void setPerson(PersonB11PK person)\n    {\n        this.person = person;\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/AddressB1M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressB1M\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private PersonB1M person;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public PersonB1M getPerson()\n    {\n        return person;\n    }\n\n    public void setPerson(PersonB1M person)\n    {\n        this.person = person;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/AddressBM1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@IndexCollection(columns = { @Index(name = \"street\") })\n@Table(name = \"ADDRESS\", schema = \"KunderaTests@patest\")\npublic class AddressBM1\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @OneToMany(mappedBy = \"address\", fetch = FetchType.LAZY)\n    private Set<PersonBM1> people;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public Set<PersonBM1> getPeople()\n    {\n        return people;\n    }\n\n    public void setPeople(Set<PersonBM1> people)\n    {\n        this.people = people;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/AddressBMM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressBMM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @ManyToMany(mappedBy = \"addresses\", fetch = FetchType.LAZY)\n    private Set<PersonBMM> people;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public Set<PersonBMM> getPeople()\n    {\n        return people;\n    }\n\n    public void setPeople(Set<PersonBMM> people)\n    {\n        this.people = people;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/AddressU11FK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressU11FK\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/AddressU11PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressU11PK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/AddressU1M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressU1M\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/AddressUM1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressUM1\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/AddressUMM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressUMM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/PersonB11FK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonB11FK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressB11FK address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressB11FK getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressB11FK address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/PersonB11PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonB11PK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)\n    @PrimaryKeyJoinColumn\n    private AddressB11PK address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressB11PK getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressB11PK address)\n    {\n        this.address = address;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/PersonB1M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonB1M\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"person\")\n//    @JoinColumn(name=\"PERSON_ID\")\n    private Set<AddressB1M> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressB1M> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressB1M> addresses)\n    {\n        this.addresses = addresses;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/PersonBM1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@IndexCollection(columns = { @Index(name = \"personName\") })\n@Table(name = \"PERSON\", schema = \"KunderaTests@patest\")\npublic class PersonBM1\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressBM1 address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressBM1 getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressBM1 address)\n    {\n        this.address = address;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/PersonBMM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonBMM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"PERSONNEL_ADDRESS\", schema = \"KunderaTests\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Set<AddressBMM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressBMM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressBMM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/PersonU11FK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonU11FK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressU11FK address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressU11FK getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressU11FK address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/PersonU11PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonU11PK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)\n    @PrimaryKeyJoinColumn\n    private AddressU11PK address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressU11PK getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressU11PK address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/PersonU1M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonU1M\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<AddressU1M> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressU1M> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressU1M> addresses)\n    {\n        this.addresses = addresses;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/PersonUM1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonUM1\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressUM1 address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressUM1 getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressUM1 address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/PersonUMM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonUMM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"PERSONNEL_ADDRESS\", schema = \"KunderaTests\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Set<AddressUMM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressUMM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressUMM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/polyglot/entities/PersonUMMByMap.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.entities;\n\nimport java.util.Map;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonUMMByMap\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"PERSONNEL_ADDRESS\", schema = \"KunderaTests\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Map<String,AddressUMM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Map<String, AddressUMM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Map<String, AddressUMM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/PropertyAccessorHelperTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property;\n\nimport java.lang.reflect.Field;\nimport java.sql.Date;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.entity.PersonnelDTO;\nimport com.impetus.kundera.entity.album.AlbumUni_1_M_1_M;\nimport com.impetus.kundera.entity.photographer.PhotographerUni_1_M_1_M;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.persistence.context.CacheBase;\nimport com.impetus.kundera.property.accessor.StringAccessor;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * @author amresh.singh\n *\n */\npublic class PropertyAccessorHelperTest\n{   \n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#set(java.lang.Object, java.lang.reflect.Field, byte[])}.\n     */\n    @Test\n    public void testSetObjectFieldByteArray()\n    {\n        PersonnelDTO person = new PersonnelDTO();    \n        try\n        {\n            PropertyAccessorHelper.set(person, person.getClass().getDeclaredField(\"personId\"), \"1\".getBytes());\n            PropertyAccessorHelper.set(person, person.getClass().getDeclaredField(\"firstName\"), \"Amresh\".getBytes());\n            PropertyAccessorHelper.set(person, person.getClass().getDeclaredField(\"lastName\"), \"Singh\".getBytes());\n            \n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"Amresh\", person.getFirstName());\n            Assert.assertEquals(\"Singh\", person.getLastName());\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {            \n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#set(java.lang.Object, java.lang.reflect.Field, java.lang.String)}.\n     */\n    @Test\n    public void testSetObjectFieldString()\n    {\n        PersonnelDTO person = new PersonnelDTO();    \n        try\n        {\n            PropertyAccessorHelper.set(person, person.getClass().getDeclaredField(\"personId\"), \"1\");\n            PropertyAccessorHelper.set(person, person.getClass().getDeclaredField(\"firstName\"), \"Amresh\");\n            PropertyAccessorHelper.set(person, person.getClass().getDeclaredField(\"lastName\"), \"Singh\");\n            \n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"Amresh\", person.getFirstName());\n            Assert.assertEquals(\"Singh\", person.getLastName());\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {            \n            Assert.fail(e.getMessage());\n        }\n        \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#set(java.lang.Object, java.lang.reflect.Field, java.lang.Object)}.\n     */\n    @Test\n    public void testSetObjectFieldObject()\n    {\n        PersonnelDTO person = new PersonnelDTO();    \n        try\n        {\n            Object id = \"1\";\n            Object fn = \"Amresh\";\n            Object ln = \"Singh\";\n            \n            PropertyAccessorHelper.set(person, person.getClass().getDeclaredField(\"personId\"), id);\n            PropertyAccessorHelper.set(person, person.getClass().getDeclaredField(\"firstName\"), fn);\n            PropertyAccessorHelper.set(person, person.getClass().getDeclaredField(\"lastName\"), ln);\n            \n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"Amresh\", person.getFirstName());\n            Assert.assertEquals(\"Singh\", person.getLastName());\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {            \n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#getObject(java.lang.Object, java.lang.reflect.Field)}.\n     */\n    @Test\n    public void testGetObjectObjectField()\n    {\n        PersonnelDTO person = new PersonnelDTO(\"1\", \"Amresh\", \"Singh\");\n        \n        try\n        {\n            Object id = PropertyAccessorHelper.getObject(person, person.getClass().getDeclaredField(\"personId\"));\n            Object fn = PropertyAccessorHelper.getObject(person, person.getClass().getDeclaredField(\"firstName\"));\n            Object ln = PropertyAccessorHelper.getObject(person, person.getClass().getDeclaredField(\"lastName\"));\n            \n            Assert.assertEquals(\"1\", id);\n            Assert.assertEquals(\"Amresh\", fn);\n            Assert.assertEquals(\"Singh\", ln);\n        }\n        catch (SecurityException e)\n        {            \n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#getObjectCopy(java.lang.Object, java.lang.reflect.Field)}.\n     */\n    @Test\n    public void testGetObjectCopy()\n    {\n        PersonnelDTO person = new PersonnelDTO(\"1\", \"Amresh\", \"Singh\");\n        try\n        {\n            Object fn = PropertyAccessorHelper.getObjectCopy(person, person.getClass().getDeclaredField(\"firstName\"));\n            Assert.assertEquals(\"Amresh\", fn);\n        }\n        catch (SecurityException e)\n        {            \n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#getString(java.lang.Object, java.lang.reflect.Field)}.\n     */\n    @Test\n    public void testGetStringObjectField()\n    {\n        PersonnelDTO person = new PersonnelDTO(\"1\", \"Amresh\", \"Singh\");        \n        try\n        {\n            String id = PropertyAccessorHelper.getString(person, person.getClass().getDeclaredField(\"personId\"));\n            String fn = PropertyAccessorHelper.getString(person, person.getClass().getDeclaredField(\"firstName\"));\n            String ln = PropertyAccessorHelper.getString(person, person.getClass().getDeclaredField(\"lastName\"));\n            \n            Assert.assertEquals(\"1\", id);\n            Assert.assertEquals(\"Amresh\", fn);\n            Assert.assertEquals(\"Singh\", ln);\n        }\n        catch (SecurityException e)\n        {            \n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#get(java.lang.Object, java.lang.reflect.Field)}.\n     */\n    @Test\n    public void testGet()\n    {\n        PersonnelDTO person = new PersonnelDTO(\"1\", \"Amresh\", \"Singh\");        \n        try\n        {\n            byte[] id = PropertyAccessorHelper.get(person, person.getClass().getDeclaredField(\"personId\"));\n            byte[] fn = PropertyAccessorHelper.get(person, person.getClass().getDeclaredField(\"firstName\"));\n            byte[] ln = PropertyAccessorHelper.get(person, person.getClass().getDeclaredField(\"lastName\"));\n            \n            Assert.assertEquals(\"1\", new StringAccessor().fromBytes(String.class, id));\n            Assert.assertEquals(\"Amresh\", new StringAccessor().fromBytes(String.class, fn));\n            Assert.assertEquals(\"Singh\", new StringAccessor().fromBytes(String.class, ln));\n        }\n        catch (SecurityException e)\n        {            \n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#getId(java.lang.Object, com.impetus.kundera.metadata.model.EntityMetadata)}.\n     */\n    @Test\n    public void testGetId()\n    {\n \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#setId(java.lang.Object, com.impetus.kundera.metadata.model.EntityMetadata, java.lang.Object)}.\n     */\n    @Test\n    public void testSetIdObjectEntityMetadataObject()\n    {\n \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#setId(java.lang.Object, com.impetus.kundera.metadata.model.EntityMetadata, byte[])}.\n     */\n    @Test\n    public void testSetIdObjectEntityMetadataByteArray()\n    {\n \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#getObject(java.lang.Object, java.lang.String)}.\n     */\n    @Test\n    public void testGetObjectObjectString()\n    {\n        PersonnelDTO person = new PersonnelDTO(\"1\", \"Amresh\", \"Singh\");        \n        try\n        {\n            Object id = PropertyAccessorHelper.getObject(person, \"personId\");\n            Object fn = PropertyAccessorHelper.getObject(person, \"firstName\");\n            Object ln = PropertyAccessorHelper.getObject(person, \"lastName\");\n            \n            Assert.assertEquals(\"1\", id);\n            Assert.assertEquals(\"Amresh\", fn);\n            Assert.assertEquals(\"Singh\", ln);\n        }\n        catch (SecurityException e)\n        {            \n            Assert.fail(e.getMessage());\n        }        \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#getGenericClass(java.lang.reflect.Field)}.\n     */\n    @Test\n    public void testGetGenericClass()\n    {\n        Assert.assertNull(PropertyAccessorHelper.getGenericClass(null));\n        try\n        {\n            Class<?> genericClass = PropertyAccessorHelper.getGenericClass(PhotographerUni_1_M_1_M.class.getDeclaredField(\"albums\"));\n            Assert.assertEquals(AlbumUni_1_M_1_M.class, genericClass);            \n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#getGenericClasses(java.lang.reflect.Field)}.\n     */\n    @Test\n    public void testGetGenericClasses()\n    {\n        Assert.assertNull(PropertyAccessorHelper.getGenericClass(null));\n        try\n        {\n            List<Class<?>> genericClasses = PropertyAccessorHelper.getGenericClasses(CacheBase.class.getDeclaredField(\"nodeMappings\"));\n            \n            Assert.assertNotNull(genericClasses);\n            Assert.assertFalse(genericClasses.isEmpty());\n            Assert.assertEquals(2, genericClasses.size());\n            Assert.assertEquals(String.class, genericClasses.get(0));\n            Assert.assertEquals(Node.class, genericClasses.get(1));\n                        \n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#getDeclaredFields(java.lang.reflect.Field)}.\n     */\n    @Test\n    public void testGetDeclaredFields()\n    {\n        try\n        {\n            Field[] fields = PropertyAccessorHelper.getDeclaredFields(PhotographerUni_1_M_1_M.class.getDeclaredField(\"albums\"));\n            Assert.assertNotNull(fields);\n            Assert.assertEquals(8, KunderaCoreUtils.countNonSyntheticFields(PhotographerUni_1_M_1_M.class));            \n        }\n        catch (SecurityException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n        \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#isCollection(java.lang.Class)}.\n     */\n    @Test\n    public void testIsCollection()\n    {\n        try\n        {\n            Assert.assertTrue(PropertyAccessorHelper.isCollection(PhotographerUni_1_M_1_M.class.getDeclaredField(\"albums\").getType()));\n        }\n        catch (SecurityException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#getObject(java.lang.Class)}.\n     */\n    @Test\n    public void testGetObjectClassOfQ()\n    {\n        Object o = PropertyAccessorHelper.getObject(PhotographerUni_1_M_1_M.class);\n        Assert.assertNotNull(o);\n        Assert.assertTrue(o instanceof PhotographerUni_1_M_1_M);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#toBytes(java.lang.Object, java.lang.reflect.Field)}.\n     */\n    @Test\n    public void testToBytesObjectField()\n    {\n        PersonnelDTO person = new PersonnelDTO(\"1\", \"Amresh\", \"Singh\");        \n        try\n        {\n            byte[] b = PropertyAccessorHelper.toBytes(\"1\" , person.getClass().getDeclaredField(\"personId\"));           \n            Assert.assertEquals(\"1\", new StringAccessor().fromBytes(String.class, b));            \n        }\n        catch (SecurityException e)\n        {            \n            Assert.fail(e.getMessage());\n        }     \n        catch (NoSuchFieldException e)\n        {            \n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#toBytes(java.lang.Object, java.lang.Class)}.\n     */\n    @Test\n    public void testToBytesObjectClass()\n    {                \n        try\n        {\n            byte[] b = PropertyAccessorHelper.toBytes(\"1\" , String.class);           \n            Assert.assertEquals(\"1\", new StringAccessor().fromBytes(String.class, b));            \n        }\n        catch (SecurityException e)\n        {            \n            Assert.fail(e.getMessage());\n        }       \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#fromSourceToTargetClass(java.lang.Class, java.lang.Class, java.lang.Object)}.\n     */\n    @Test\n    public void testFromSourceToTargetClass()\n    {\n        try\n        {\n            Object o = PropertyAccessorHelper.fromSourceToTargetClass(String.class, String.class, \"1\");\n            Assert.assertEquals(\"1\", o);            \n        }\n        catch (SecurityException e)\n        {            \n            Assert.fail(e.getMessage());\n        }    \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#fromDate(java.lang.Class, java.lang.Class, java.lang.Object)}.\n     */\n    @Test\n    public void testFromDate()\n    {\n        Object o = PropertyAccessorHelper.fromDate(String.class, Date.class, new Date(System.currentTimeMillis()));\n        Assert.assertNotNull(o);\n    }   \n\n    /**\n     * Test method for {@link com.impetus.kundera.property.PropertyAccessorHelper#getCollectionInstance(java.lang.reflect.Field)}.\n     */\n    @Test\n    public void testGetCollectionInstance()\n    {\n        try\n        {\n            Collection c = PropertyAccessorHelper.getCollectionInstance(PhotographerUni_1_M_1_M.class.getDeclaredField(\"albums\"));\n            Assert.assertNotNull(c);\n            Assert.assertTrue(c instanceof ArrayList);\n            \n            c = PropertyAccessorHelper.getCollectionInstance(CacheBase.class.getDeclaredField(\"headNodes\"));\n            Assert.assertNotNull(c);\n            Assert.assertTrue(c instanceof HashSet);\n        }\n        catch (SecurityException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/BigDecimalAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.math.BigDecimal;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n *\n */\npublic class BigDecimalAccessorTest\n{\n    PropertyAccessor<BigDecimal> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new BigDecimalAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.BigDecimalAccessor#fromBytes(java.lang.Class, byte[])}.\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertNull(accessor.fromBytes(BigDecimal.class, null));\n        \n        BigDecimal v1 = new BigDecimal(1111111111.11111);\n        byte[] b = accessor.toBytes(v1);\n        \n        BigDecimal v2 = accessor.fromBytes(BigDecimal.class, b);        \n        Assert.assertEquals(v1, v2);\n      \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.BigDecimalAccessor#toBytes(java.lang.Object)}.\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toString(null));\n        BigDecimal v1 = new BigDecimal(1111111111);\n        byte[] b = accessor.toBytes(v1);\n        \n        BigDecimal v2 = accessor.fromBytes(BigDecimal.class, b);        \n        Assert.assertEquals(v1, v2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.BigDecimalAccessor#toString(java.lang.Object)}.\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n        BigDecimal v1 = new BigDecimal(1111111111);\n        String s1 = v1.toString();\n        \n        String s2 = accessor.toString(v1);\n        Assert.assertTrue(s1.equals(s2));\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.BigDecimalAccessor#fromString(java.lang.Class, java.lang.String)}.\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(BigDecimal.class, null));\n        \n        BigDecimal v1 = new BigDecimal(1111111111);\n        String s = v1.toString();\n        \n        BigDecimal v2 = accessor.fromString(BigDecimal.class, s);\n        \n        Assert.assertEquals(v1, v2);\n      \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.BigDecimalAccessor#getCopy(java.lang.Object)}.\n     */\n    @Test\n    public void testGetCopy()\n    {\n        Assert.assertNull(accessor.getCopy(null));\n        \n        BigDecimal v1 = new BigDecimal(1111111111);\n        BigDecimal v2 = accessor.getCopy(v1);\n        \n        Assert.assertEquals(v1, v2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.BigDecimalAccessor#getInstance(java.lang.Class)}.\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Assert.assertEquals(BigDecimal.TEN, accessor.getInstance(BigDecimal.class));\n      \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/BigIntegerAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.math.BigInteger;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n *\n */\npublic class BigIntegerAccessorTest\n{\n    PropertyAccessor<BigInteger> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new BigIntegerAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.BigIntegerAccessor#fromBytes(java.lang.Class, byte[])}.\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertNull(accessor.fromBytes(BigInteger.class, null));\n        \n        BigInteger v1 = new BigInteger(\"1111111111\");\n        byte[] b = accessor.toBytes(v1);\n        \n        BigInteger v2 = accessor.fromBytes(BigInteger.class, b);        \n        Assert.assertEquals(v1, v2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.BigIntegerAccessor#toBytes(java.lang.Object)}.\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toString(null));\n        BigInteger v1 = new BigInteger(\"1111111111\");\n        byte[] b = accessor.toBytes(v1);\n        \n        BigInteger v2 = accessor.fromBytes(BigInteger.class, b);        \n        Assert.assertEquals(v1, v2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.BigIntegerAccessor#toString(java.lang.Object)}.\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n        BigInteger v1 = new BigInteger(\"1111111111\");\n        String s1 = v1.toString();\n        \n        String s2 = accessor.toString(v1);\n        Assert.assertTrue(s1.equals(s2));\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.BigIntegerAccessor#fromString(java.lang.Class, java.lang.String)}.\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(BigInteger.class, null));\n        \n        BigInteger v1 = new BigInteger(\"1111111111\");\n        String s = v1.toString();\n        \n        BigInteger v2 = accessor.fromString(BigInteger.class, s);\n        \n        Assert.assertEquals(v1, v2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.BigIntegerAccessor#getCopy(java.lang.Object)}.\n     */\n    @Test\n    public void testGetCopy()\n    {\n        Assert.assertNull(accessor.getCopy(null));\n        \n        BigInteger v1 = new BigInteger(\"1111111111\");\n        BigInteger v2 = accessor.getCopy(v1);\n        \n        Assert.assertEquals(v1, v2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.BigIntegerAccessor#getInstance(java.lang.Class)}.\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Assert.assertEquals(BigInteger.TEN, accessor.getInstance(BigInteger.class));\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/BooleanAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n * \n */\npublic class BooleanAccessorTest\n{\n    PropertyAccessor<Boolean> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new BooleanAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.BooleanAccessor#fromBytes(java.lang.Class, byte[])}\n     * .\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertFalse(accessor.fromBytes(Boolean.class, null));\n        \n        byte[] b = accessor.toBytes(new Boolean(true));\n        \n        Boolean bb = accessor.fromBytes(Boolean.class, b);\n        Assert.assertEquals(true, bb.booleanValue());\n        \n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.BooleanAccessor#toBytes(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n        byte[] b = accessor.toBytes(new Boolean(true));\n        \n        Boolean bb = accessor.fromBytes(Boolean.class, b);\n        Assert.assertEquals(true, bb.booleanValue());\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.BooleanAccessor#toString(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n\n        Assert.assertEquals(\"true\", accessor.toString(new Boolean(true)));\n        Assert.assertEquals(\"false\", accessor.toString(new Boolean(false)));\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.BooleanAccessor#fromString(java.lang.Class, java.lang.String)}\n     * .\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(Boolean.class, null));\n\n        Assert.assertTrue(accessor.fromString(Boolean.class, \"true\"));\n        Assert.assertFalse(accessor.fromString(Boolean.class, \"false\"));\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.BooleanAccessor#getCopy(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testGetCopy()\n    {\n        Assert.assertNull(accessor.getCopy(null));\n\n        Assert.assertTrue(accessor.getCopy(new Boolean(true)));\n        Assert.assertFalse(accessor.getCopy(new Boolean(false)));\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.BooleanAccessor#getInstance(java.lang.Class)}\n     * .\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Assert.assertTrue((Boolean) accessor.getInstance(Boolean.class));\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/ByteAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n *\n */\npublic class ByteAccessorTest\n{\n    PropertyAccessor<Byte> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new ByteAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.ByteAccessor#fromBytes(java.lang.Class, byte[])}.\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertNull(accessor.fromBytes(Byte.class, null));\n        Byte v1 = new Byte(\"7\");\n        byte[] b = accessor.toBytes(v1);\n        \n        Byte v2 = accessor.fromBytes(Byte.class, b);\n        Assert.assertEquals(v1, v2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.ByteAccessor#toBytes(java.lang.Object)}.\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n        Byte v1 = new Byte(\"7\");\n        byte[] b = accessor.toBytes(v1);\n        \n        Byte v2 = accessor.fromBytes(Byte.class, b);\n        Assert.assertEquals(v1, v2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.ByteAccessor#toString(java.lang.Object)}.\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n        Byte v1 = new Byte(\"7\");\n        \n        String s = accessor.toString(v1);\n        \n        Assert.assertEquals(\"7\", s);\n        \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.ByteAccessor#fromString(java.lang.Class, java.lang.String)}.\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(Byte.class, null));\n        \n        Byte v1 = new Byte(\"7\");\n        Byte v2 = accessor.fromString(Byte.class, \"7\");\n        Assert.assertEquals(v1, v2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.ByteAccessor#getCopy(java.lang.Object)}.\n     */\n    @Test\n    public void testGetCopy()\n    {\n        Assert.assertNull(accessor.getCopy(null));\n        \n        Byte v1 = new Byte(\"7\");\n        Byte v2 = accessor.getCopy(v1);\n        Assert.assertEquals(v1, v2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.ByteAccessor#getInstance(java.lang.Class)}.\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Assert.assertNotNull(accessor.getInstance(Byte.class));\n        Assert.assertTrue(accessor.getInstance(Byte.class) instanceof Byte);\n        Assert.assertEquals(Byte.MAX_VALUE, accessor.getInstance(Byte.class));        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/CalendarAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.util.Calendar;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n * \n */\npublic class CalendarAccessorTest\n{\n    PropertyAccessor<Calendar> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new CalendarAccessor();\n\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.CalendarAccessor#fromBytes(java.lang.Class, byte[])}\n     * .\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertNull(accessor.fromBytes(Calendar.class, null));\n        \n        Calendar v1 = Calendar.getInstance();\n        byte[] b = accessor.toBytes(v1);\n        \n        Calendar v2 = accessor.fromBytes(Calendar.class, b);\n        Assert.assertEquals(v1, v2);        \n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.CalendarAccessor#toBytes(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n        Calendar v1 = Calendar.getInstance();\n        byte[] b = accessor.toBytes(v1);\n        \n        Calendar v2 = accessor.fromBytes(Calendar.class, b);\n        Assert.assertEquals(v1, v2);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.CalendarAccessor#toString(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n        Calendar v1 = Calendar.getInstance();\n        String s1 = v1.getTime().getTime() + \"\";\n        \n        String s2 = accessor.toString(v1);\n        Assert.assertTrue(s1.equals(s2));       \n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.CalendarAccessor#fromString(java.lang.Class, java.lang.String)}\n     * .\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(Calendar.class, null));\n\n        Calendar v1 = Calendar.getInstance();\n\n        String s = v1.getTime().getTime() + \"\";\n        Calendar v2 = accessor.fromString(Calendar.class, s);\n        Assert.assertEquals(v1, v2);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.CalendarAccessor#getCopy(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testGetCopy()\n    {\n        Assert.assertNull(accessor.getCopy(null));\n\n        Calendar v1 = Calendar.getInstance();\n        Calendar v2 = accessor.getCopy(v1);\n\n        Assert.assertEquals(v1, v2);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.CalendarAccessor#getInstance(java.lang.Class)}\n     * .\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Assert.assertNotNull(accessor.getInstance(Calendar.class));\n        Assert.assertTrue(accessor.getInstance(Calendar.class) instanceof Calendar);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/CharAccessorTest.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.property.accessor;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * @author impadmin\n * \n */\npublic class CharAccessorTest\n{\n\n    CharAccessor accessor = new CharAccessor();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.CharAccessor#fromBytes(java.lang.Class, byte[])}\n     * .\n     */\n    @Test\n    public void testFromBytes()\n    {\n        byte[] b = { 0, 65 };\n        char a = accessor.fromBytes(Character.class, b);\n        Assert.assertEquals('A', a);\n    }\n\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.CharAccessor#fromString(java.lang.Class, java.lang.String)}\n     * .\n     */\n    @Test\n    public void testFromString()\n    {\n        String a = \"A\";\n        char c = accessor.fromString(Character.class, a);\n        Assert.assertEquals('A',c);\n    }\n    \n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n\n        Character d1 = new Character('c');\n        \n        byte[] b = accessor.toBytes(d1);\n        \n        Character d2 = accessor.fromBytes(Character.class, b);\n        \n        Assert.assertEquals(d1, d2);\n\n    }\n\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n\n        Character d1 = new Character('c');\n        String s1 = d1.toString();\n        \n        String s2 = accessor.toString(d1);\n        \n        Assert.assertTrue(s1.equals(s2));   \n    }\n    \n    @Test\n    public void testGetCopy()\n    {\n        Character d1 = new Character('c');\n        Character d2 = accessor.getCopy(d1);\n        Assert.assertEquals(d1, d2);\n    }\n\n \n    @Test\n    public void testGetInstance()\n    {\n        Object o = accessor.getInstance(Character.class);\n        Assert.assertNotNull(o);        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/DateAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.util.Date;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessException;\n\n/**\n * The Class DateAccessorTest.\n * \n * @author vivek.mishra\n */\npublic class DateAccessorTest\n{\n\n    /** The accessor. */\n    private DateAccessor accessor;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new DateAccessor();\n    }\n\n    /**\n     * Test date from string.\n     * \n     * @throws PropertyAccessException\n     *             the property access exception\n     */\n    @Test\n    public void testDateFromString() throws PropertyAccessException\n    {\n        String dateInMMddYYHHmmss = \"02/01/2012 00:00:00\";\n        String newDateAsStr = \"Wed Feb 01 07:58:02 IST 2012\";\n        String dateInMMddYY = \"02/01/2012\";\n        String dateInMMddYYDash = \"02-01-2012\";\n        String dateInMMMddYYYY = \"Feb/02/2012\";\n        String dateInMilliSeconds = \"1351667541111\";\n        Assert.assertNotNull(accessor.fromString(Date.class, dateInMMddYYDash));\n        Assert.assertNotNull(accessor.fromString(Date.class, dateInMMddYYHHmmss));\n        Assert.assertNotNull(accessor.fromString(Date.class, newDateAsStr));\n        Assert.assertNotNull(accessor.fromString(Date.class, dateInMMMddYYYY));\n        Assert.assertNotNull(accessor.fromString(Date.class, dateInMMddYY));\n        Assert.assertNotNull(accessor.fromString(Date.class, dateInMilliSeconds));\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertNull(accessor.fromBytes(Date.class, null));\n\n        Date d1 = new Date(4);\n        byte[] b = accessor.toBytes(d1);\n\n        Date d2 = accessor.fromBytes(Date.class, b);\n\n        Assert.assertEquals(d1, d2);\n    }\n\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n\n        Date d1 = new Date(4);\n\n        byte[] b = accessor.toBytes(d1);\n\n        Date d2 = accessor.fromBytes(Date.class, b);\n\n        Assert.assertEquals(d1, d2);\n\n    }\n\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n\n        Date d1 = new Date();\n        String s1 = d1.getTime() + \"\";\n\n        String s2 = accessor.toString(d1);\n\n        Assert.assertTrue(s1.equals(s2));\n    }\n\n    @Test\n    public void testGetCopy()\n    {\n        Date d1 = new Date();\n        Date d2 = accessor.getCopy(d1);\n        Assert.assertEquals(d1, d2);\n    }\n\n    @Test\n    public void testGetInstance()\n    {\n        Object o = accessor.getInstance(Date.class);\n        Assert.assertNotNull(o);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/DoubleAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n *\n */\npublic class DoubleAccessorTest\n{\n    PropertyAccessor<Double> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new DoubleAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.DoubleAccessor#fromBytes(java.lang.Class, byte[])}.\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertEquals(0.0, accessor.fromBytes(Double.class, null));\n        \n        Double d1 = new Double(4.555);\n        byte[] b = accessor.toBytes(d1);\n        \n        Double d2 = accessor.fromBytes(Double.class, b);\n        \n        Assert.assertEquals(d1, d2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.DoubleAccessor#toBytes(java.lang.Object)}.\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n\n        Double d1 = new Double(4.555);\n        \n        byte[] b = accessor.toBytes(d1);\n        \n        Double d2 = accessor.fromBytes(Double.class, b);\n        \n        Assert.assertEquals(d1, d2);\n\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.DoubleAccessor#toString(java.lang.Object)}.\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n\n        Double d1 = new Double(4.555);\n        String s1 = d1.toString();\n        \n        String s2 = accessor.toString(d1);\n        \n        Assert.assertTrue(s1.equals(s2));   \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.DoubleAccessor#fromString(java.lang.Class, java.lang.String)}.\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(Double.class, null));\n        Double d1 = new Double(4.555);\n        String s = d1.toString();\n        \n        Double d2 = accessor.fromString(Double.class, s);\n        Assert.assertEquals(d1, d2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.DoubleAccessor#getCopy(java.lang.Object)}.\n     */\n    @Test\n    public void testGetCopy()\n    {\n        Double d1 = new Double(4.555);\n        Double d2 = accessor.getCopy(d1);\n        Assert.assertEquals(d1, d2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.DoubleAccessor#getInstance(java.lang.Class)}.\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Object o = accessor.getInstance(Double.class);\n        Assert.assertNotNull(o);\n        Assert.assertEquals(Double.MAX_VALUE, (Double) o);\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/EnumAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.io.UnsupportedEncodingException;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.property.PropertyAccessException;\n\n/**\n * @author amresh.singh\n * \n */\npublic class EnumAccessorTest\n{\n\n    enum Day\n    {\n        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY\n    }\n\n    Day day1 = Day.MONDAY;\n\n    Day day2 = Day.TUESDAY;\n\n    EnumAccessor accessor = new EnumAccessor();\n\n    @Before\n    public void setUp() throws Exception\n    {\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.EnumAccessor#fromBytes(byte[])}\n     * .\n     */\n    @Test\n    public void testFromBytes()\n    {\n        try\n        {\n            byte[] b = day1.name().getBytes(Constants.ENCODING);\n\n            Day dd = (Day) accessor.fromBytes(Day.class, b);\n\n            Assert.assertEquals(day1, dd);\n\n            Object o = accessor.fromBytes(Day.class, null);\n\n            Assert.assertNull(o);\n\n        }\n        catch (UnsupportedEncodingException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (PropertyAccessException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.EnumAccessor#toBytes(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testToBytes()\n    {\n        try\n        {\n            byte[] b = accessor.toBytes(day1);\n            String s = new String(b, Constants.ENCODING);\n            Assert.assertEquals(day1.MONDAY.name(), s);\n\n            b = accessor.toBytes(null);\n\n            Assert.assertNull(b);\n\n        }\n        catch (PropertyAccessException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (UnsupportedEncodingException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.EnumAccessor#toString(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testToStringObject()\n    {\n        String s = accessor.toString(day1);\n        Assert.assertEquals(Day.MONDAY.name(), s);\n\n        s = accessor.toString(null);\n        Assert.assertNull(s);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.EnumAccessor#fromString(java.lang.String)}\n     * .\n     */\n    @Test\n    public void testFromString()\n    {\n        try\n        {\n            Day day11 = (Day) accessor.fromString(Day.class, day1.name());\n            Assert.assertEquals(day1, day11);\n\n            Day day22 = (Day) accessor.fromString(Day.class, day2.name());\n            Assert.assertEquals(day2, day22);\n\n            Day day = (Day) accessor.fromString(Day.class, null);\n            Assert.assertNull(day);\n\n            day = (Day) accessor.fromString(null, day1.name());\n            Assert.assertNull(day);\n\n            day = (Day) accessor.fromString(null, null);\n            Assert.assertNull(day);\n        }\n        catch (PropertyAccessException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.EnumAccessor#fromString(java.lang.String)}\n     * .\n     */\n    @Test\n    public void testGetCopy()\n    {\n        try\n        {\n            Day day = Day.MONDAY;\n            Day d = (Day) accessor.getCopy(day);\n            Assert.assertNotNull(d);\n            Assert.assertTrue(day.equals(d));\n\n            d = (Day) accessor.getCopy(null);\n            Assert.assertNull(d);\n        }\n        catch (PropertyAccessException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.EnumAccessor#fromString(java.lang.String)}\n     * .\n     */\n    @Test\n    public void testGetInstance()\n    {\n        try\n        {\n            Day d = (Day) accessor.getInstance(Day.class);\n            Assert.assertNull(d);\n\n        }\n        catch (PropertyAccessException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/FloatAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n *\n */\npublic class FloatAccessorTest\n{\n    PropertyAccessor<Float> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new FloatAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.FloatAccessor#fromBytes(java.lang.Class, byte[])}.\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertEquals(0.0f, accessor.fromBytes(Float.class, null));\n        \n        Float f1 = new Float(4.555);\n        byte[] b = accessor.toBytes(f1);\n        \n        Float f2 = accessor.fromBytes(Float.class, b);\n        \n        Assert.assertEquals(f1, f2);\n        \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.FloatAccessor#toBytes(java.lang.Object)}.\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n\n        Float f1 = new Float(4.555);        \n        byte[] b = accessor.toBytes(f1);        \n        Float f2 = accessor.fromBytes(Float.class, b);\n        \n        Assert.assertEquals(f1, f2);        \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.FloatAccessor#toString(java.lang.Object)}.\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n\n        Float f1 = new Float(4.555);\n        String s1 = f1.toString();\n        \n        String s2 = accessor.toString(f1);\n        \n        Assert.assertTrue(s1.equals(s2)); \n        \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.FloatAccessor#fromString(java.lang.Class, java.lang.String)}.\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(Float.class, null));\n        Float f1 = new Float(4.555);\n        String s = f1.toString();\n        \n        Float f2 = accessor.fromString(Float.class, s);\n        Assert.assertEquals(f1, f2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.FloatAccessor#getCopy(java.lang.Object)}.\n     */\n    @Test\n    public void testGetCopy()\n    {\n        Float f1 = new Float(4.555);\n        Float f2 = accessor.getCopy(f1);\n        Assert.assertEquals(f1, f2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.FloatAccessor#getInstance(java.lang.Class)}.\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Object o = accessor.getInstance(Float.class);\n        Assert.assertNotNull(o);\n        Assert.assertEquals(Float.MAX_VALUE, (Float) o);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/IntegerAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n *\n */\npublic class IntegerAccessorTest\n{\n    \n    PropertyAccessor<Integer> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new IntegerAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n    \n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.IntegerAccessor#fromBytes(java.lang.Class, byte[])}.\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertNull(accessor.fromBytes(Integer.class, null));\n        \n        Integer d1 = new Integer(4);\n        byte[] b = accessor.toBytes(d1);\n        \n        Integer d2 = accessor.fromBytes(Integer.class, b);\n        \n        Assert.assertEquals(d1, d2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.IntegerAccessor#toBytes(java.lang.Object)}.\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n\n        Integer d1 = new Integer(4);\n        \n        byte[] b = accessor.toBytes(d1);\n        \n        Integer d2 = accessor.fromBytes(Integer.class, b);\n        \n        Assert.assertEquals(d1, d2);\n\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.IntegerAccessor#toString(java.lang.Object)}.\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n\n        Integer d1 = new Integer(4);\n        String s1 = d1.toString();\n        \n        String s2 = accessor.toString(d1);\n        \n        Assert.assertTrue(s1.equals(s2));   \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.IntegerAccessor#fromString(java.lang.Class, java.lang.String)}.\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(Integer.class, null));\n        Integer d1 = new Integer(4);\n        String s = d1.toString();\n        \n        Integer d2 = accessor.fromString(Integer.class, s);\n        Assert.assertEquals(d1, d2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.IntegerAccessor#getCopy(java.lang.Object)}.\n     */\n    @Test\n    public void testGetCopy()\n    {\n        Integer d1 = new Integer(4);\n        Integer d2 = accessor.getCopy(d1);\n        Assert.assertEquals(d1, d2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.IntegerAccessor#getInstance(java.lang.Class)}.\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Object o = accessor.getInstance(Integer.class);\n        Assert.assertNotNull(o);        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/LongAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class LongAccessorTest\n{\n\n    private PropertyAccessor<Long> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new LongAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    @Test\n    public void testFromBytes()\n    {\n        byte[] bytes = new byte[] {};\n        Assert.assertNull(accessor.fromBytes(LongAccessor.class, bytes));\n        Long l = 49L;\n        bytes = accessor.toBytes(l);\n        Assert.assertEquals(l, accessor.fromBytes(LongAccessor.class, bytes));\n\n        l = 12l;\n        bytes = accessor.toBytes(l);\n        Assert.assertEquals(l, (Long) accessor.fromBytes(LongAccessor.class, bytes));\n\n    }\n\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n\n        Long d1 = new Long(4);\n\n        byte[] b = accessor.toBytes(d1);\n\n        Long d2 = accessor.fromBytes(Long.class, b);\n\n        Assert.assertEquals(d1, d2);\n\n    }\n\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n\n        Long d1 = new Long(4);\n        String s1 = d1.toString();\n\n        String s2 = accessor.toString(d1);\n\n        Assert.assertTrue(s1.equals(s2));\n    }\n\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(Long.class, null));\n        Long d1 = new Long(4);\n        String s = d1.toString();\n\n        Long d2 = accessor.fromString(Long.class, s);\n        Assert.assertEquals(d1, d2);\n    }\n\n    @Test\n    public void testGetCopy()\n    {\n        Long d1 = new Long(4);\n        Long d2 = accessor.getCopy(d1);\n        Assert.assertEquals(d1, d2);\n    }\n\n    @Test\n    public void testGetInstance()\n    {\n        Object o = accessor.getInstance(Long.class);\n        Assert.assertNotNull(o);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/ObjectAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n *\n */\npublic class ObjectAccessorTest\n{\n    \n    private PropertyAccessor<Object> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new ObjectAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.ObjectAccessor#fromBytes(java.lang.Class, byte[])}.\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertNull(accessor.fromBytes(PersonalDetail.class, null));\n        PersonalDetail pd = new PersonalDetail(\"Amresh\", \"password\", \"single\");\n        byte[] b = accessor.toBytes(pd);\n        \n        Object o = accessor.fromBytes(PersonalDetail.class, b);\n        \n        Assert.assertNotNull(o);\n        Assert.assertTrue(o instanceof PersonalDetail);\n        Assert.assertTrue(o.equals(pd));\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.ObjectAccessor#toBytes(java.lang.Object)}.\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n        PersonalDetail pd = new PersonalDetail(\"Amresh\", \"password\", \"single\");\n        byte[] b = accessor.toBytes(pd);\n        Object o = accessor.fromBytes(PersonalDetail.class, b);\n        Assert.assertNotNull(o);\n        Assert.assertTrue(pd.equals(o));\n\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.ObjectAccessor#toString(java.lang.Object)}.\n     */\n    @Test\n    public void testToStringObject()\n    {\n        PersonalDetail pd = new PersonalDetail(\"Amresh\", \"password\", \"single\");  \n        String s = accessor.toString(pd);\n        Assert.assertNotNull(s);\n\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.ObjectAccessor#fromString(java.lang.Class, java.lang.String)}.\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(String.class, null));\n        \n        Object o = accessor.fromString(String.class, \"Hello\");\n        Assert.assertNotNull(o);\n        Assert.assertTrue(o instanceof String);\n        Assert.assertEquals(\"Hello\", (String)o);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.ObjectAccessor#getCopy(java.lang.Object)}.\n     */\n    @Test\n    public void testGetCopy()\n    {\n        Assert.assertNull(accessor.getCopy(null));\n        \n        PersonalDetail pd = new PersonalDetail(\"Amresh\", \"password\", \"single\");       \n        \n        Object pdCopy = accessor.getCopy(pd);\n        Assert.assertNotNull(pdCopy);\n        Assert.assertTrue(pdCopy instanceof PersonalDetail);\n        Assert.assertTrue(pd == pdCopy);\n        Assert.assertTrue(pd.getPersonalDetailId() == ((PersonalDetail)pdCopy).getPersonalDetailId());\n        Assert.assertTrue(pd.getName() == ((PersonalDetail)pdCopy).getName());\n        Assert.assertTrue(pd.getPassword() == ((PersonalDetail)pdCopy).getPassword());\n        Assert.assertTrue(pd.getRelationshipStatus() == ((PersonalDetail)pdCopy).getRelationshipStatus());\n        \n        byte[] b = \"Hello\".getBytes();\n        Object bCopy = accessor.getCopy(b);\n        Assert.assertNotNull(bCopy);\n        Assert.assertTrue(bCopy instanceof byte[]);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.ObjectAccessor#getInstance(java.lang.Class)}.\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Object o = accessor.getInstance(PersonalDetail.class);\n        Assert.assertNotNull(o);\n        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/PersonalDetail.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2013 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.property.accessor;\r\n\r\nimport java.io.Serializable;\r\nimport java.util.UUID;\r\n\r\nimport javax.persistence.Column;\r\n\r\n/**\r\n * Class used as an object for conversion within test cases \r\n * @author amresh.singh\r\n */\r\n\r\npublic class PersonalDetail implements Serializable\r\n{\r\n    @Column(name = \"personal_detail_id\")\r\n    private String personalDetailId;\r\n\r\n    @Column(name = \"name\")\r\n    private String name;\r\n\r\n    @Column(name = \"password\")\r\n    private String password;\r\n\r\n    @Column(name = \"rel_status\")\r\n    private String relationshipStatus;\r\n\r\n    public PersonalDetail()\r\n    {\r\n\r\n    }\r\n\r\n    public PersonalDetail(String name, String password, String relationshipStatus)\r\n    {\r\n        setPersonalDetailId(UUID.randomUUID().toString());\r\n        setName(name);\r\n        setPassword(password);\r\n        setRelationshipStatus(relationshipStatus);\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetailId\r\n     */\r\n    public String getPersonalDetailId()\r\n    {\r\n        return personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetailId\r\n     *            the personalDetailId to set\r\n     */\r\n    public void setPersonalDetailId(String personalDetailId)\r\n    {\r\n        this.personalDetailId = personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @return the name\r\n     */\r\n    public String getName()\r\n    {\r\n        return name;\r\n    }\r\n\r\n    /**\r\n     * @param name\r\n     *            the name to set\r\n     */\r\n    public void setName(String name)\r\n    {\r\n        this.name = name;\r\n    }\r\n\r\n    /**\r\n     * @return the password\r\n     */\r\n    public String getPassword()\r\n    {\r\n        return password;\r\n    }\r\n\r\n    /**\r\n     * @param password\r\n     *            the password to set\r\n     */\r\n    public void setPassword(String password)\r\n    {\r\n        this.password = password;\r\n    }\r\n\r\n    /**\r\n     * @return the relationshipStatus\r\n     */\r\n    public String getRelationshipStatus()\r\n    {\r\n        return relationshipStatus;\r\n    }\r\n\r\n    /**\r\n     * @param relationshipStatus\r\n     *            the relationshipStatus to set\r\n     */\r\n    public void setRelationshipStatus(String relationshipStatus)\r\n    {\r\n        this.relationshipStatus = relationshipStatus;\r\n    }\r\n    \r\n    @Override\r\n    public boolean equals(Object o)\r\n    {\r\n        if (this == o ) return true;       \r\n        if (!(o instanceof PersonalDetail) ) return false;\r\n        \r\n        PersonalDetail that = (PersonalDetail)o;\r\n        \r\n        return that.getPersonalDetailId().equals(this.getPersonalDetailId())\r\n        && that.getName().equals(this.getName())\r\n        && that.getPassword().equals(this.getPassword())\r\n        && that.getRelationshipStatus().equals(this.getRelationshipStatus());\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/PointAccessorTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.property.accessor;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.gis.geometry.Point;\nimport com.impetus.kundera.property.PropertyAccessor;\nimport com.vividsolutions.jts.io.WKTWriter;\n\n/**\n * Test case for {@link PropertyAccessor}\n * \n * @author amresh.singh\n */\npublic class PointAccessorTest\n{\n    PointAccessor pa;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        pa = new PointAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        pa = null;\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.PointAccessor#fromBytes(java.lang.Class, byte[])}\n     * .\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Point point = new Point(4.5, 6.3);\n        byte[] input = pa.toBytes(point);\n\n        Point point2 = pa.fromBytes(Point.class, input);\n        Assert.assertTrue(point.equals(point2));\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.PointAccessor#toBytes(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testToBytes()\n    {\n        Point point = new Point(4.5, 6.3);\n        byte[] input = pa.toBytes(point);\n\n        Point point2 = pa.fromBytes(Point.class, input);\n        Assert.assertTrue(point.equals(point2));\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.PointAccessor#toString(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Point point = new Point(4.5, 6.3);\n        String pointStr = pa.toString(point);\n\n        WKTWriter writer = new WKTWriter();\n        String wktStr = writer.write(point);\n\n        Assert.assertEquals(wktStr, pointStr);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.PointAccessor#fromString(java.lang.Class, java.lang.String)}\n     * .\n     */\n    @Test\n    public void testFromString()\n    {\n        Point point = new Point(4.5, 6.3);\n        WKTWriter writer = new WKTWriter();\n        String wktStr = writer.write(point);\n\n        Point point2 = pa.fromString(com.vividsolutions.jts.geom.Point.class, wktStr);\n\n        Assert.assertNotNull(point2);\n        Assert.assertEquals(point.getX(), point2.getX());\n        Assert.assertEquals(point.getY(), point2.getY());\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.PointAccessor#getCopy(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testGetCopy()\n    {\n        Point point = new Point(4.5, 6.3);\n        Point point2 = pa.getCopy(point);\n        Assert.assertFalse(point == point2);\n        Assert.assertTrue(point.equals(point2));\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.PointAccessor#getInstance(java.lang.Class)}\n     * .\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Point point = (Point) pa.getInstance(Point.class);\n        Assert.assertNotNull(point);\n        Assert.assertEquals(0.0, point.getX());\n        Assert.assertEquals(0.0, point.getY());\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/SQLDateAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.sql.Date;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n *\n */\npublic class SQLDateAccessorTest\n{\n    PropertyAccessor<Date> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new SQLDateAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.SQLDateAccessor#fromBytes(java.lang.Class, byte[])}.\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertNull(accessor.fromBytes(Date.class, null));\n        \n        long l = System.currentTimeMillis();        \n        Date d = new Date(l);\n        byte[] b = accessor.toBytes(d);\n        \n        Date d2 = accessor.fromBytes(Date.class, b);\n        \n        Assert.assertEquals(d, d2);       \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.SQLDateAccessor#toBytes(java.lang.Object)}.\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n        \n        long l = System.currentTimeMillis();        \n        Date d = new Date(l);       \n        byte[] b = accessor.toBytes(d);\n        \n        Date d2 = accessor.fromBytes(Date.class, b);\n        \n        Assert.assertEquals(d, d2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.SQLDateAccessor#toString(java.lang.Object)}.\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n        \n        long l = System.currentTimeMillis();        \n        Date d = new Date(l);        \n        \n        Assert.assertEquals(String.valueOf(d.getTime()), accessor.toString(d));\n        \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.SQLDateAccessor#fromString(java.lang.Class, java.lang.String)}.\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(Date.class, null));\n        \n        long l = System.currentTimeMillis();        \n        Date d = new Date(l);        \n        Date d2 = accessor.fromString(Date.class, \"\" + l);\n        Assert.assertEquals(d, d2);\n        \n        Assert.assertEquals(d.getYear(), accessor.fromString(Date.class, d2.toString()).getYear());\n        Assert.assertEquals(d.getMonth(), accessor.fromString(Date.class, d2.toString()).getMonth());\n        Assert.assertEquals(d.getDate(), accessor.fromString(Date.class, d2.toString()).getDate());        \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.SQLDateAccessor#getCopy(java.lang.Object)}.\n     */\n    @Test\n    public void testGetCopy()\n    {\n        long l = System.currentTimeMillis();\n        Date d = new Date(l);\n        \n        Date d2 = accessor.getCopy(d);\n        Assert.assertNotNull(d2);\n        Assert.assertTrue(d.equals(d2));        \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.SQLDateAccessor#getInstance(java.lang.Class)}.\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Object o = accessor.getInstance(Date.class);\n        Assert.assertNotNull(o);\n        \n        Assert.assertEquals(Integer.MAX_VALUE, ((Date) o).getTime());        \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/SQLTimeAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.sql.Time;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n * \n */\npublic class SQLTimeAccessorTest\n{\n    PropertyAccessor<Time> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new SQLTimeAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.SQLTimeAccessor#fromBytes(java.lang.Class, byte[])}\n     * .\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertNull(accessor.fromBytes(Time.class, null));\n\n        long l = System.currentTimeMillis();\n        Time d = new Time(l);\n        byte[] b = accessor.toBytes(d);\n\n        Time d2 = accessor.fromBytes(Time.class, b);\n\n        Assert.assertEquals(d, d2);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.SQLTimeAccessor#toBytes(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n\n        long l = System.currentTimeMillis();\n        Time d = new Time(l);\n        byte[] b = accessor.toBytes(d);\n\n        Time d2 = accessor.fromBytes(Time.class, b);\n\n        Assert.assertEquals(d, d2);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.SQLTimeAccessor#toString(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n\n        long l = System.currentTimeMillis();\n        Time d = new Time(l);\n\n        Assert.assertEquals(\"\" + l, accessor.toString(d));\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.SQLTimeAccessor#fromString(java.lang.Class, java.lang.String)}\n     * .\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(Time.class, null));\n\n        long l = System.currentTimeMillis();\n        Time d = new Time(l);\n        Time d2 = accessor.fromString(Time.class, \"\" + l);\n        Assert.assertEquals(d, d2);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.SQLTimeAccessor#getCopy(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testGetCopy()\n    {\n        long l = System.currentTimeMillis();\n        Time d = new Time(l);\n\n        Time d2 = accessor.getCopy(d);\n        Assert.assertNotNull(d2);\n        Assert.assertTrue(d.equals(d2));\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.SQLTimeAccessor#getInstance(java.lang.Class)}\n     * .\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Object o = accessor.getInstance(Time.class);\n        Assert.assertNotNull(o);\n\n        Assert.assertEquals(Integer.MAX_VALUE, ((Time) o).getTime());\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/SQLTimestampAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.sql.Timestamp;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n *\n */\npublic class SQLTimestampAccessorTest\n{\n    PropertyAccessor<Timestamp> accessor;\n    \n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new SQLTimestampAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.SQLTimestampAccessor#fromBytes(java.lang.Class, byte[])}.\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertNull(accessor.fromBytes(Timestamp.class, null));\n        \n        long l = System.currentTimeMillis();\n        Timestamp t = new Timestamp(l);\n        byte[] b = accessor.toBytes(t);\n        \n        Timestamp t2 = accessor.fromBytes(Timestamp.class, b);\n        Assert.assertEquals(t, t2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.SQLTimestampAccessor#toBytes(java.lang.Object)}.\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n        \n        long l = System.currentTimeMillis();\n        Timestamp t = new Timestamp(l);\n        byte[] b = accessor.toBytes(t);\n        \n        Timestamp t2 = accessor.fromBytes(Timestamp.class, b);\n        Assert.assertEquals(t, t2);        \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.SQLTimestampAccessor#toString(java.lang.Object)}.\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n        \n        long l = System.currentTimeMillis();\n        Timestamp t = new Timestamp(l);        \n        Assert.assertEquals(\"\" + l, accessor.toString(t));      \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.SQLTimestampAccessor#fromString(java.lang.Class, java.lang.String)}.\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(Timestamp.class, null));        \n        long currTime = System.currentTimeMillis();\n        Timestamp t = accessor.fromString(Timestamp.class, currTime + \"\");\n        Assert.assertEquals(currTime, t.getTime());\n        \n        String s = t.toString();\n        Timestamp t2 = accessor.fromString(Timestamp.class, s);\n        Assert.assertEquals(currTime, t2.getTime());        \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.SQLTimestampAccessor#getCopy(java.lang.Object)}.\n     */\n    @Test\n    public void testGetCopy()\n    {\n        Assert.assertNull(accessor.getCopy(null));\n        \n        long currTime = System.currentTimeMillis();\n        Timestamp t1 = new Timestamp(currTime);\n        Timestamp t2 = accessor.getCopy(t1);\n        Assert.assertNotNull(t2);\n        Assert.assertEquals(currTime, t2.getTime());        \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.SQLTimestampAccessor#getInstance(java.lang.Class)}.\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Object o = accessor.getInstance(Timestamp.class);\n        Assert.assertNotNull(o);\n        Assert.assertTrue(o instanceof Timestamp);\n        Assert.assertEquals(Integer.MAX_VALUE, ((Timestamp) o).getTime());\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/ShortAccessorTest.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.property.accessor;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * @author impadmin\n * \n */\npublic class ShortAccessorTest\n{\n\n    ShortAccessor accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new ShortAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertEquals(new Short((short)0), accessor.fromBytes(Short.class, null));\n        \n        Short d1 = new Short((short)4);\n        byte[] b = accessor.toBytes(d1);\n        \n        Short d2 = accessor.fromBytes(Short.class, b);\n        \n        Assert.assertEquals(d1, d2);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.ShortAccessor#toBytes(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testToBytes()\n    {\n        short s = -1;\n        byte[] b = accessor.toBytes(s);\n        short s2 = accessor.fromBytes(Short.class, b);\n        Assert.assertEquals(s, s2);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.ShortAccessor#toString(java.lang.Object)}\n     * .\n     */\n     @Test\n    public void testToStringObject()\n    {\n         Assert.assertNull(accessor.toString(null));\n\n         Short d1 = new Short((short)4);\n         String s1 = d1.toString();\n         \n         String s2 = accessor.toString(d1);\n         \n         Assert.assertTrue(s1.equals(s2));  \n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.property.accessor.ShortAccessor#fromString(java.lang.Class, java.lang.String)}\n     * .\n     */\n     @Test\n    public void testFromString()\n    {\n         Assert.assertNull(accessor.fromString(Short.class, null));\n         Short d1 = new Short((short)4);\n         String s = d1.toString();\n         \n         Short d2 = accessor.fromString(Short.class, s);\n         Assert.assertEquals(d1, d2);\n    }\n     \n     @Test\n     public void testGetCopy()\n     {\n         Short d1 = new Short((short)4);\n         Short d2 = accessor.getCopy(d1);\n         Assert.assertEquals(d1, d2);\n     }\n\n\n     @Test\n     public void testGetInstance()\n     {\n         Object o = accessor.getInstance(Short.class);\n         Assert.assertNotNull(o);        \n     }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/StringAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n *\n */\npublic class StringAccessorTest\n{\n    PropertyAccessor<String> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new StringAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.StringAccessor#fromBytes(java.lang.Class, byte[])}.\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertNull(accessor.fromBytes(String.class, null));\n        \n        String d1 = new String(\"AAA\");\n        byte[] b = accessor.toBytes(d1);\n        \n        String d2 = accessor.fromBytes(String.class, b);\n        \n        Assert.assertEquals(d1, d2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.StringAccessor#toBytes(java.lang.Object)}.\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n\n        String d1 = new String(\"AAA\");\n        \n        byte[] b = accessor.toBytes(d1);\n        \n        String d2 = accessor.fromBytes(String.class, b);\n        \n        Assert.assertEquals(d1, d2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.StringAccessor#toString(java.lang.Object)}.\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n\n        String d1 = new String(\"AAA\");\n        String s1 = d1.toString();\n        \n        String s2 = accessor.toString(d1);\n        \n        Assert.assertTrue(s1.equals(s2));   \n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.StringAccessor#fromString(java.lang.Class, java.lang.String)}.\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(String.class, null));\n        String d1 = new String(\"AAA\");\n        String s = d1.toString();\n        \n        String d2 = accessor.fromString(String.class, s);\n        Assert.assertEquals(d1, d2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.StringAccessor#getCopy(java.lang.Object)}.\n     */\n    @Test\n    public void testGetCopy()\n    {\n        String d1 = new String(\"AAA\");\n        String d2 = accessor.getCopy(d1);\n        Assert.assertEquals(d1, d2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.StringAccessor#getInstance(java.lang.Class)}.\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Object o = accessor.getInstance(String.class);\n        Assert.assertNotNull(o);  \n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/property/accessor/UUIDAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.property.accessor;\n\nimport java.util.UUID;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.property.PropertyAccessor;\n\n/**\n * @author amresh.singh\n *\n */\npublic class UUIDAccessorTest\n{\n    PropertyAccessor<UUID> accessor;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        accessor = new UUIDAccessor();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        accessor = null;\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.UUIDAccessor#fromBytes(java.lang.Class, byte[])}.\n     */\n    @Test\n    public void testFromBytes()\n    {\n        Assert.assertNull(accessor.fromBytes(UUID.class, null));\n        UUID uuid = UUID.randomUUID();\n        byte[] b = accessor.toBytes(uuid);\n        \n        UUID uuid2 = accessor.fromBytes(UUID.class, b);\n        Assert.assertEquals(uuid, uuid2);\n\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.UUIDAccessor#toBytes(java.lang.Object)}.\n     */\n    @Test\n    public void testToBytes()\n    {\n        Assert.assertNull(accessor.toBytes(null));\n        UUID uuid = UUID.randomUUID();\n        byte[] b = accessor.toBytes(uuid);\n        \n        UUID uuid2 = accessor.fromBytes(UUID.class, b);\n        Assert.assertEquals(uuid, uuid2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.UUIDAccessor#toString(java.lang.Object)}.\n     */\n    @Test\n    public void testToStringObject()\n    {\n        Assert.assertNull(accessor.toString(null));\n        UUID uuid = UUID.randomUUID();\n        String s1 = uuid.toString();\n        String s2 = accessor.toString(uuid);\n        Assert.assertTrue(s1.equals(s2));\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.UUIDAccessor#fromString(java.lang.Class, java.lang.String)}.\n     */\n    @Test\n    public void testFromString()\n    {\n        Assert.assertNull(accessor.fromString(UUID.class, null));\n        \n        UUID uuid = UUID.randomUUID();\n        String s = uuid.toString();\n        \n        UUID uuid2 = accessor.fromString(UUID.class, s);\n        Assert.assertEquals(uuid, uuid2);\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.UUIDAccessor#getCopy(java.lang.Object)}.\n     */\n    @Test\n    public void testGetCopy()\n    {\n        UUID uuid = UUID.randomUUID();\n        \n        UUID uuid2 = accessor.getCopy(uuid);\n        Assert.assertEquals(uuid, uuid2);\n\n    }\n\n    /**\n     * Test method for {@link com.impetus.kundera.property.accessor.UUIDAccessor#getInstance(java.lang.Class)}.\n     */\n    @Test\n    public void testGetInstance()\n    {\n        Object o = accessor.getInstance(UUID.class);\n        Assert.assertNotNull(o);\n        Assert.assertTrue(o instanceof UUID);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/proxy/cglib/CglibLazyInitializerFactoryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.proxy.cglib;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.entity.PersonnelDTO;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.proxy.KunderaProxy;\nimport com.impetus.kundera.proxy.LazyInitializer;\nimport com.impetus.kundera.proxy.LazyInitializerFactory;\n\n/**\n * @author amresh.singh\n */\npublic class CglibLazyInitializerFactoryTest\n{\n\n    private static EntityManagerFactory emf;\n\n    private static EntityManager em;\n    \n    private static KunderaMetadata kunderaMetadata;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        \n        emf = Persistence.createEntityManagerFactory(\"kunderatest\");\n        kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n        em = emf.createEntityManager();\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.proxy.cglib.CglibLazyInitializerFactory#getProxy(java.lang.String, java.lang.Class, java.lang.reflect.Method, java.lang.reflect.Method, java.lang.Object, com.impetus.kundera.persistence.PersistenceDelegator)}\n     * .\n     */\n    @Test\n    public void testGetProxy()\n    {\n\n        LazyInitializerFactory factory = kunderaMetadata.getCoreMetadata().getLazyInitializerFactory();\n        KunderaProxy proxy = factory.getProxy(\"personnel\", PersonnelDTO.class, null, null, \"1\", null);\n        LazyInitializer li = proxy.getKunderaLazyInitializer();\n        Assert.assertEquals(CglibLazyInitializer.class, li.getClass());\n        Assert.assertTrue(li.isUninitialized());\n        Assert.assertFalse(li.isUnwrap());\n        Assert.assertEquals(\"personnel\", li.getEntityName());\n        Assert.assertEquals(\"1\", li.getIdentifier());\n        Assert.assertNull(li.getOwner());\n        Assert.assertNull(li.getPersistenceDelegator());\n        Assert.assertEquals(PersonnelDTO.class, li.getPersistentClass());\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/proxy/cglib/CglibLazyInitializerTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.proxy.cglib;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.CoreTestUtilities;\nimport com.impetus.kundera.entity.PersonnelDTO;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.proxy.KunderaProxy;\nimport com.impetus.kundera.proxy.LazyInitializationException;\nimport com.impetus.kundera.proxy.LazyInitializer;\nimport com.impetus.kundera.proxy.LazyInitializerFactory;\n\n/**\n * @author amresh.singh\n */\npublic class CglibLazyInitializerTest\n{\n\n    private static EntityManagerFactory emf;\n\n    private static EntityManager em;\n    \n    private static KunderaMetadata kunderaMetadata;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        \n        emf = Persistence.createEntityManagerFactory(\"kunderatest\");\n        kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n        em = emf.createEntityManager();\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.proxy.cglib.CglibLazyInitializerFactory#getProxy(java.lang.String, java.lang.Class, java.lang.reflect.Method, java.lang.reflect.Method, java.lang.Object, com.impetus.kundera.persistence.PersistenceDelegator)}\n     * .\n     */\n    @Test\n    public void testWithNullPD()\n    {\n\n        LazyInitializerFactory factory = kunderaMetadata.getCoreMetadata().getLazyInitializerFactory();\n        KunderaProxy proxy = factory.getProxy(\"personnel\", PersonnelDTO.class, null, null, \"1\", null);\n        LazyInitializer li = proxy.getKunderaLazyInitializer();\n        Assert.assertEquals(CglibLazyInitializer.class, li.getClass());\n        \n        try\n        {\n            li.initialize();\n        }catch(LazyInitializationException liex)\n        {\n//            Assert.assertEquals(\"could not initialize proxy \" + PersonnelDTO.class.getName() + \"_\"\n//                        + \"1\" + \" - no EntityManager\", liex.getMessage());\n        }\n\n    }\n\n    @Test\n    public void testWithPDInstance() throws NoSuchMethodException, Throwable\n    {\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n        PersonnelDTO dto = new PersonnelDTO(\"1\", \"vivek\", \"mishra\");\n        em.persist(dto);\n        LazyInitializerFactory factory = kunderaMetadata.getCoreMetadata().getLazyInitializerFactory();\n        KunderaProxy proxy = factory.getProxy(\"personnel#1\", PersonnelDTO.class, null, null, \"1\", delegator);\n        LazyInitializer li = proxy.getKunderaLazyInitializer();\n        ((CglibLazyInitializer)li).setPersistenceDelegator(delegator);\n        li.setImplementation(proxy);\n        \n        li.initialize();\n        Assert.assertNotNull(((CglibLazyInitializer)li).getTarget());\n        Assert.assertNotNull(((CglibLazyInitializer)li).getEntityName());\n        Assert.assertEquals(\"personnel#1\",((CglibLazyInitializer)li).getEntityName());\n        Assert.assertNotNull(li.getPersistenceDelegator());\n        Assert.assertSame(delegator,li.getPersistenceDelegator());\n        \n        Assert.assertFalse(li.isUninitialized());\n        \n        Assert.assertSame(PersonnelDTO.class,li.getPersistentClass());\n        Assert.assertEquals(\"1\",li.getIdentifier());\n        \n        li.setIdentifier(\"12\");\n        Assert.assertEquals(\"12\", li.getIdentifier());\n        Assert.assertNotNull(li.getImplementation());\n        \n//        Object firstName = ((CglibLazyInitializer)li).invoke(proxy, dto.getClass().getDeclaredMethod(\"getFirstName\", null),new String[]{});\n//        Assert.assertEquals(\"vivek\", firstName);\n        \n        ((CglibLazyInitializer)li).unsetPersistenceDelegator();\n        ((CglibLazyInitializer)li).setUnwrap(true);\n        Assert.assertTrue(((CglibLazyInitializer)li).isUnwrap());\n\n\n    }\n    \n    @Test\n    public void testWithClosedPDInstance() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException\n    {\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n        PersonnelDTO dto = new PersonnelDTO(\"1\", \"vivek\", \"mishra\");\n        em.persist(dto);\n        em.close();\n\n        LazyInitializerFactory factory = kunderaMetadata.getCoreMetadata().getLazyInitializerFactory();\n        KunderaProxy proxy = factory.getProxy(\"personnel\", PersonnelDTO.class, null, null, \"1\", delegator);\n        LazyInitializer li = proxy.getKunderaLazyInitializer();\n        \n        try\n        {\n            li.initialize();\n            Assert.fail(\"Should have gone to catch block!\");\n        } catch(LazyInitializationException liex)\n        {\n            Assert.assertEquals(\"could not initialize proxy \" + PersonnelDTO.class.getName() + \"_\"\n                    + \"1\" + \" - the owning Session was closed\",liex.getMessage());\n        }\n        \n        em = emf.createEntityManager();\n    }\n        \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/proxy/collection/ProxyListTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.proxy.collection;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.ListIterator;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.FetchType;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.CoreTestUtilities;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.Relation.ForeignKey;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.persistence.event.AddressEntityWithList;\n\n/**\n * @author vivek.mishra\n *  junit for {@link ProxyList}\n */\npublic class ProxyListTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    @Before\n    public void setup()\n    {\n\n        \n        emf = Persistence.createEntityManagerFactory(\"kunderatest\");\n        em = emf.createEntityManager();\n\n    }\n\n    @Test\n    public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException\n    {\n        AddressEntityWithList p = new AddressEntityWithList();\n        p.setAddressId(\"addr1\");\n        p.setCity(\"noida\");\n        p.setStreet(\"street\");\n        AddressEntityWithList subaddress = new AddressEntityWithList();\n        \n        subaddress.setAddressId(\"subaddr1\");\n        p.setCity(\"noida\");\n        p.setStreet(\"sector 50\");\n        \n\n        List<AddressEntityWithList> subaddresses = new ArrayList<AddressEntityWithList>(1);\n        subaddresses.add(subaddress);\n\n        p.setSubaddresses(subaddresses);\n\n        Relation relation = new Relation(AddressEntityWithList.class.getDeclaredField(\"subaddresses\"), AddressEntityWithList.class,\n                List.class, FetchType.LAZY, null, false, null, ForeignKey.ONE_TO_MANY);\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n        ProxyList proxyList = new ProxyList(delegator, relation);\n\n        proxyList.setOwner(p);\n        proxyList.add(0,p);\n        \n        \n        \n        Assert.assertTrue(proxyList.contains(p));\n        Assert.assertEquals(p, proxyList.getOwner());\n        Assert.assertNotNull(proxyList.getDataCollection());\n        Assert.assertNotNull(proxyList.getRelation());\n        Assert.assertEquals(relation, proxyList.getRelation());\n        Assert.assertEquals(delegator, proxyList.getPersistenceDelegator());\n        Assert.assertNotNull(proxyList.getCopy());\n        Assert.assertEquals(proxyList.getRelation(),proxyList.getCopy().getRelation());\n\n        proxyList.addAll(1,subaddresses);\n        Assert.assertNotNull(proxyList.getDataCollection());\n        Assert.assertEquals(2, ((Collection)proxyList.getDataCollection()).size());\n        Assert.assertTrue(proxyList.contains(p));\n        Assert.assertTrue(proxyList.containsAll(subaddresses));\n\n\n        // TODO: This needs to fixed. There is an issue(runtime error) with proxy.remove(). Amresh need to fix it.\n//        ProxyList.remove(p);\n//        Assert.assertNotNull(ProxyList.getDataCollection());\n//        Assert.assertEquals(1,ProxyList.getDataCollection().size());\n//\n//        ProxyList.removeAll(subaddresses);\n//        Assert.assertNull(ProxyList.getDataCollection());\n\n        proxyList.retainAll(subaddresses);\n        Assert.assertNotNull(proxyList.getDataCollection());\n        Assert.assertEquals(2, ((Collection)proxyList.getDataCollection()).size());\n        \n        Assert.assertNotNull(proxyList.get(0));\n        Assert.assertNotNull(proxyList.get(1));\n        Assert.assertSame(p,proxyList.get(0));\n        Assert.assertSame(subaddress,proxyList.get(1));\n        Assert.assertEquals(0,proxyList.indexOf(p));\n        Assert.assertEquals(1,proxyList.lastIndexOf(subaddress));\n        \n        Assert.assertNotNull(proxyList.toArray());\n        Assert.assertEquals(2,proxyList.size());\n        Iterator<AddressEntityWithList> iter = proxyList.iterator();\n        int counter = 0;\n        while(iter.hasNext())\n        {\n            Assert.assertNotNull(iter.next());\n            ++counter;\n        }\n        \n        Assert.assertEquals(2, counter);\n        \n        Assert.assertNotNull(proxyList.subList(0, 1));\n        Assert.assertEquals(2, proxyList.subList(0, 2).size());\n        \n       \n        \n        ListIterator<AddressEntityWithList> iterList = proxyList.listIterator();\n        int counterList = 0;\n        while(iterList.hasNext())\n        {\n            Assert.assertNotNull(iterList.next());\n            ++counterList;\n            \n        }\n        \n        ListIterator<AddressEntityWithList> iterListWithArg = proxyList.listIterator(1);\n        int counterListArg = 0;\n        \n        while(iterListWithArg.hasNext())\n        {\n        \t\n            Assert.assertNotNull(iterListWithArg.next());\n            ++counterListArg;\n            \n        }\n        \n        proxyList.remove(1);\n        Assert.assertEquals(2,proxyList.size());\n        \n        proxyList.set(1,p);\n        \n        proxyList.removeAll(new ArrayList());\n        Assert.assertEquals(2,proxyList.size());\n        \n        proxyList.add(\"vivek1\");\n        Assert.assertEquals(3,proxyList.size());\n        \n        \n        List lst = new ArrayList();\n        lst.add(\"vivek\");\n        proxyList.addAll(lst);\n        \n        Assert.assertEquals(4,proxyList.size());\n        \n        proxyList.add(\"vivek1\");\n        \n        Assert.assertEquals(4,proxyList.size());\n        \n        Assert.assertFalse(proxyList.isEmpty());\n        \n        proxyList.remove(\"vivek\");\n        Assert.assertEquals(3,proxyList.size());\n        \n      \n\n        proxyList.clear();\n        Assert.assertTrue(proxyList.isEmpty());\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/proxy/collection/ProxyMapTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.proxy.collection;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.FetchType;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.CoreTestUtilities;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.Relation.ForeignKey;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.persistence.event.AddressEntity;\nimport com.impetus.kundera.polyglot.entities.AddressUMM;\nimport com.impetus.kundera.polyglot.entities.PersonUMMByMap;\n\n/**\n * @author vivek.mishra\n * junit for {@link ProxyMap}\n */\npublic class ProxyMapTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    public void setup(final String persistenceUnit)\n    {\n\n        \n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException\n    {\n        setup(\"kunderatest\");\n        \n        AddressEntity p = new AddressEntity();\n\n        AddressEntity subaddress = new AddressEntity();\n\n        Set<AddressEntity> subaddresses = new HashSet<AddressEntity>(1);\n        subaddresses.add(subaddress);\n\n        p.setSubaddresses(subaddresses);\n\n        Relation relation = new Relation(AddressEntity.class.getDeclaredField(\"subaddresses\"), AddressEntity.class,\n                Set.class, FetchType.LAZY, null, false, null, ForeignKey.ONE_TO_MANY);\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n        ProxyMap proxyMap = new ProxyMap(delegator, relation);\n\n        proxyMap.setOwner(p);\n\n        assertOnProxyMap(p, relation, delegator, proxyMap);\n        \n    }\n    \n    @Test\n    public void testByMap() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException\n    {\n        setup(\"patest\");\n        PersonUMMByMap person = new PersonUMMByMap();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"personName\");\n        \n        AddressUMM address = new AddressUMM();\n        \n        Map<String,AddressUMM> addresses = new HashMap<String,AddressUMM>();\n        addresses.put(\"addr1\",address);\n        \n        person.setAddresses(addresses);\n\n        Relation relation = new Relation(PersonUMMByMap.class.getDeclaredField(\"addresses\"), AddressUMM.class,\n                Set.class, FetchType.LAZY, null, false, null, ForeignKey.MANY_TO_MANY);\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n        ProxyMap proxyMap = new ProxyMap(delegator, relation);\n\n        proxyMap.setOwner(person);\n\n        assertOnProxyMap(person, relation, delegator, proxyMap);\n        \n        java.util.List<PersonUMMByMap> personList = new ArrayList<PersonUMMByMap>();\n        personList.add(person);\n        \n        Assert.assertEquals(1,proxyMap.size());\n        Assert.assertEquals(1,proxyMap.values().size());\n        \n        Assert.assertNotNull(proxyMap.keySet());\n        Assert.assertTrue(proxyMap.values().iterator().next() instanceof AddressUMM);\n        \n        Assert.assertTrue(proxyMap.containsKey(\"addr1\"));\n        Assert.assertTrue(proxyMap.containsValue(address));\n        \n        Assert.assertNotNull(proxyMap.get(\"addr1\"));\n        \n        proxyMap.remove(\"addr1\");\n        \n        Assert.assertNull(proxyMap.entrySet()); \n        \n        proxyMap.clear();\n\n        Assert.assertTrue(proxyMap.isEmpty());\n        \n        Assert.assertFalse(proxyMap.containsKey(\"addr1\"));\n        \n        proxyMap.put(\"addr1\", address);\n        proxyMap.putAll(addresses);\n\n        Assert.assertTrue(proxyMap.containsKey(\"addr1\"));\n        Assert.assertTrue(proxyMap.containsValue(address));\n\n    }\n\n    private void assertOnProxyMap(Object person, Relation relation, PersistenceDelegator delegator,\n            ProxyMap proxyMap)\n    {\n        Assert.assertEquals(person, proxyMap.getOwner());\n        Assert.assertNull(proxyMap.getDataCollection());\n        Assert.assertNotNull(proxyMap.getRelation());\n        Assert.assertEquals(relation, proxyMap.getRelation());\n        Assert.assertEquals(delegator, proxyMap.getPersistenceDelegator());\n        Assert.assertNotNull(proxyMap.getCopy());\n        Assert.assertEquals(proxyMap.getRelation(),proxyMap.getCopy().getRelation());\n    }\n    \n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/proxy/collection/ProxySetTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.proxy.collection;\n\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.FetchType;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.CoreTestUtilities;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.Relation.ForeignKey;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.persistence.event.AddressEntity;\n\n/**\n * @author vivek.mishra junit for {@link ProxySet}\n */\npublic class ProxySetTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    @Before\n    public void setup()\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"kunderatest\");\n        em = emf.createEntityManager();\n\n    }\n\n    @Test\n    public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException\n    {\n        AddressEntity p = new AddressEntity();\n\n        AddressEntity subaddress = new AddressEntity();\n\n        Set<AddressEntity> subaddresses = new HashSet<AddressEntity>(1);\n        subaddresses.add(subaddress);\n\n        p.setSubaddresses(subaddresses);\n\n        Relation relation = new Relation(AddressEntity.class.getDeclaredField(\"subaddresses\"), AddressEntity.class,\n                Set.class, FetchType.LAZY, null, false, null, ForeignKey.ONE_TO_MANY);\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n        ProxySet proxySet = new ProxySet(delegator, relation);\n\n        proxySet.setOwner(p);\n        proxySet.add(p);\n\n        Assert.assertTrue(proxySet.contains(p));\n        Assert.assertEquals(p, proxySet.getOwner());\n        Assert.assertNotNull(proxySet.getDataCollection());\n        Assert.assertNotNull(proxySet.getRelation());\n        Assert.assertEquals(relation, proxySet.getRelation());\n        Assert.assertEquals(delegator, proxySet.getPersistenceDelegator());\n        Assert.assertNotNull(proxySet.getCopy());\n        Assert.assertEquals(proxySet.getRelation(), proxySet.getCopy().getRelation());\n\n        proxySet.addAll(subaddresses);\n        Assert.assertNotNull(proxySet.getDataCollection());\n        Assert.assertEquals(2, ((Collection) proxySet.getDataCollection()).size());\n        Assert.assertTrue(proxySet.contains(p));\n        Assert.assertTrue(proxySet.containsAll(subaddresses));\n\n        // TODO: This needs to fixed. There is an issue(runtime error) with\n        // proxy.remove(). Amresh need to fix it.\n        // proxySet.remove(p);\n        // Assert.assertNotNull(proxySet.getDataCollection());\n        // Assert.assertEquals(1,proxySet.getDataCollection().size());\n        //\n        // proxySet.removeAll(subaddresses);\n        // Assert.assertNull(proxySet.getDataCollection());\n\n        proxySet.retainAll(subaddresses);\n        Assert.assertNotNull(proxySet.getDataCollection());\n        Assert.assertEquals(2, ((Collection) proxySet.getDataCollection()).size());\n\n        Iterator<AddressEntity> iter = proxySet.iterator();\n        int counter = 0;\n        while (iter.hasNext())\n        {\n            Assert.assertNotNull(iter.next());\n            ++counter;\n        }\n\n        Assert.assertEquals(2, counter);\n\n        Assert.assertNotNull(proxySet.toArray());\n        Assert.assertEquals(2, proxySet.toArray().length);\n        Assert.assertEquals(2, proxySet.size());\n\n        proxySet.remove(p);\n        Assert.assertNotNull(proxySet.getDataCollection());\n        Assert.assertEquals(1, proxySet.size());\n\n        proxySet.removeAll(subaddresses);\n        Assert.assertNotNull(proxySet.getDataCollection());\n        Assert.assertTrue(((HashSet)proxySet.getDataCollection()).isEmpty());\n\n        proxySet.clear();\n        Assert.assertTrue(proxySet.isEmpty());\n\n    }\n\n    @After\n    public void tearDown()\n    {\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/query/CoreIndexer.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.query;\n\nimport java.util.Map;\n\nimport com.impetus.kundera.index.Indexer;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\n\n/**\n * @author vivek.mishra\n * \n *         Implementation of {@link Indexer} interface.\n * \n */\npublic class CoreIndexer implements Indexer\n{\n\n    @Override\n    public void index(Class entityClazz, EntityMetadata entityMetadata, Map<String, Object> values, Object parentId,\n            final Class parentClazz)\n    {\n    }\n\n    @Override\n    public Map<String, Object> search(Class<?> clazz, EntityMetadata m, String luceneQuery, int start, int count)\n    {\n\n        return null;\n    }\n\n    @Override\n    public Map<String, Object> search(String query, Class<?> parentClass, EntityMetadata parentMetadata,\n            Class<?> childClass, EntityMetadata childMetadata, Object entityId, int start, int count)\n    {\n        return null;\n    }\n\n    @Override\n    public void unIndex(Class entityClazz, Object entity, EntityMetadata metadata, MetamodelImpl metamodel)\n    {\n    }\n\n    @Override\n    public void close()\n    {\n    }\n\n    @Override\n    public Map<String, Object> search(KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery,\n            PersistenceDelegator persistenceDelegator, EntityMetadata m, int firstResult, int maxResults)\n    {\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/query/CoreQuery.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.query;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * @author vivek.mishra\n * Test implementation for {@link Query} interface.\n *\n */\npublic class CoreQuery<E> extends QueryImpl<E>\n{\n\n    public CoreQuery(final KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator, final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n    }\n\n\n    public List getResutList()\n    {\n        return super.getResultList();\n    }\n    \n    @Override\n    protected List<Object> populateEntities(EntityMetadata m, Client client)\n    {\n        // Only find by id queries supported.\n        \n        EntityMetadata entityMetadata = getEntityMetadata();\n        Object value = null;\n        for(Object clause: getKunderaQuery().getFilterClauseQueue())\n        {\n            if(clause instanceof FilterClause)\n            {\n                String property = ((FilterClause)clause).getProperty();\n                String condition = ((FilterClause)clause).getCondition();\n                value = ((FilterClause)clause).getValue().get(0);\n            }\n            \n            \n            \n        }\n\n        Object result = client.find(m.getEntityClazz(), value);\n        List results = new ArrayList();\n        if(result != null)\n        {\n            results.add(result);\n        }\n        return results;\n    }\n\n    public String getLuceneQuery()\n    {\n        return KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata);\n    }\n    \n    /*public Set<String> fetchByLuceneQuery()\n    {\n        return fetchDataFromLucene(getEntityMetadata().getEntityClazz(), persistenceDelegeator.getClient(getEntityMetadata()));\n    }*/\n    \n    public List<Object> populateUsingLucene()\n    {\n        return populateUsingLucene(getEntityMetadata(),persistenceDelegeator.getClient(getEntityMetadata()),new ArrayList(),new String[]{});\n    }\n    \n    \n    @Override\n    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n//        setRelationEntities(enhanceEntities, client, m)\n        List results = populateUsingLucene(m,client,new ArrayList(),new String[]{});\n        return setRelationEntities(results, client, m);\n    }\n\n    @Override\n    protected EntityReader getReader()\n    {\n        return new CoreTestEntityReader(kunderaMetadata);\n    }\n\n    @Override\n    protected int onExecuteUpdate()\n    {\n        return onUpdateDeleteEvent();\n    }\n\n    @Override\n    public void close()\n    {\n        // Do nothing.\n        \n    }\n\n    @Override\n    public Iterator<E> iterate()\n    {\n        return null;\n    }\n    \n    protected String[] getColumns(final String[] columns, final EntityMetadata m)\n    {\n        return super.getColumns(columns, m);\n    }\n\n\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n        return populateEntities(m, client);\n    }\n\n\n   \n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/query/CoreTestEntityReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\n\n/**\n * @author amresh.singh\n *  \n *  \n */\npublic class CoreTestEntityReader extends AbstractEntityReader implements EntityReader\n{\n\n    /**\n     * \n     */\n    public CoreTestEntityReader(KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        return null;\n    }\n\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        \n        return super.findById(primaryKey, m, client);\n    }   \n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/query/KunderaQueryParserTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.query.KunderaQuery.SortOrder;\nimport com.impetus.kundera.query.KunderaQuery.SortOrdering;\nimport com.impetus.kundera.query.KunderaQuery.UpdateClause;\n\n/**\n * The Class KunderaQueryParserTest.\n * \n * @author vivek.mishra\n */\npublic class KunderaQueryParserTest\n{\n\n    private EntityManagerFactory emf;\n\n    private KunderaMetadata kunderaMetadata;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"kunderatest\");\n        kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n    }\n\n    /**\n     * On query parse.\n     */\n    @Test\n    public void onQueryParse()\n    {\n\n        // Valid Query with clause.\n        String validQuery = \"SELECT c FROM Country c ORDER BY c.currency, c.population DESC\";\n        KunderaQuery kunderQuery = new KunderaQuery(validQuery, kunderaMetadata);\n\n        KunderaQueryParser parser = new KunderaQueryParser(kunderQuery);\n        parser.parse();\n\n        List<SortOrdering> sortOrders = kunderQuery.getOrdering();\n        Assert.assertNotNull(sortOrders);\n        Assert.assertEquals(2, sortOrders.size());\n        Assert.assertEquals(\"c.currency\", sortOrders.get(0).getColumnName());\n        Assert.assertEquals(SortOrder.ASC.name(), sortOrders.get(0).getOrder().name());\n        Assert.assertEquals(\"c.population\", sortOrders.get(1).getColumnName());\n        Assert.assertEquals(SortOrder.DESC.name(), sortOrders.get(1).getOrder().name());\n\n        // valid query with default ASC clause.\n        String validQueryWithDefaultClause = \"SELECT c FROM Country c ORDER BY c.currency, c.population\";\n\n        kunderQuery = new KunderaQuery(validQueryWithDefaultClause, kunderaMetadata);\n        parser = new KunderaQueryParser(kunderQuery);\n        parser.parse();\n\n        sortOrders = kunderQuery.getOrdering();\n        Assert.assertNotNull(sortOrders);\n        Assert.assertEquals(2, sortOrders.size());\n        Assert.assertEquals(\"c.currency\", sortOrders.get(0).getColumnName());\n        Assert.assertEquals(SortOrder.ASC.name(), sortOrders.get(0).getOrder().name());\n        Assert.assertEquals(\"c.population\", sortOrders.get(1).getColumnName());\n        Assert.assertEquals(SortOrder.ASC.name(), sortOrders.get(1).getOrder().name());\n\n        String invalidQuery = \"SELECT c FROM Country c where currency, c.population DESCS\";\n\n        kunderQuery = new KunderaQuery(invalidQuery, kunderaMetadata);\n        parser = new KunderaQueryParser(kunderQuery);\n        parser.parse();\n\n    }\n\n    @Test\n    public void onUpdateDeleteQueryParse()\n    {\n\n        // update with single set value in SET clause.\n        String updateQuery = \"UPDATE Country SET population = 10 where currency = INR\";\n\n        KunderaQuery kunderaQuery = new KunderaQuery(updateQuery, kunderaMetadata);\n        KunderaQueryParser parser = new KunderaQueryParser(kunderaQuery);\n        parser.parse();\n\n        Assert.assertEquals(\"Country\", kunderaQuery.getFrom());\n        Assert.assertEquals(\"currency = INR\", kunderaQuery.getFilter());\n        Assert.assertNull(kunderaQuery.getResult());\n        Assert.assertTrue(kunderaQuery.isUpdateClause());\n        Assert.assertEquals(true, kunderaQuery.isDeleteUpdate());\n        for (UpdateClause q : kunderaQuery.getUpdateClauseQueue())\n        {\n            Assert.assertEquals(\"population\", q.getProperty());\n            Assert.assertEquals(\"10\", q.getValue());\n        }\n\n        // Update with multi valued SET clause.\n        String multiValueUpdaeQuery = \"UPDATE Country SET population = 10,name=vivek where currency = INR\";\n        kunderaQuery = new KunderaQuery(multiValueUpdaeQuery, kunderaMetadata);\n\n        parser = new KunderaQueryParser(kunderaQuery);\n        parser.parse();\n\n        Assert.assertEquals(\"Country\", kunderaQuery.getFrom());\n        Assert.assertEquals(\"currency = INR\", kunderaQuery.getFilter());\n        Assert.assertNull(kunderaQuery.getResult());\n        Assert.assertTrue(kunderaQuery.isUpdateClause());\n        Assert.assertEquals(true, kunderaQuery.isDeleteUpdate());\n        Assert.assertEquals(2, kunderaQuery.getUpdateClauseQueue().size());\n\n        UpdateClause[] result = kunderaQuery.getUpdateClauseQueue().toArray(new UpdateClause[] {});\n        Assert.assertEquals(\"population\", result[0].getProperty());\n        Assert.assertEquals(\"10\", result[0].getValue());\n\n        Assert.assertEquals(\"name\", result[1].getProperty());\n        Assert.assertEquals(\"vivek\", result[1].getValue());\n\n        // Delete query.\n        String deleteQuery = \"Delete from Country where currency = INR\";\n\n        kunderaQuery = new KunderaQuery(deleteQuery, kunderaMetadata);\n        parser = new KunderaQueryParser(kunderaQuery);\n        parser.parse();\n\n        Assert.assertEquals(\"Country\", kunderaQuery.getFrom());\n        Assert.assertEquals(\"currency = INR\", kunderaQuery.getFilter());\n        Assert.assertNull(kunderaQuery.getResult());\n        Assert.assertFalse(kunderaQuery.isUpdateClause());\n        Assert.assertEquals(true, kunderaQuery.isDeleteUpdate());\n    }\n\n    @Test\n    public void onInvalidQueryParse()\n    {\n\n        // Valid Query with where clause.\n        String validQuery = \"SELECT c,c.currency FROM Country c where c.currency = INR\";\n\n        KunderaQuery kunderQuery = new KunderaQuery(validQuery, kunderaMetadata);\n        KunderaQueryParser parser = new KunderaQueryParser(kunderQuery);\n        try\n        {\n            parser.parse();\n        }\n        catch (JPQLParseException jpqlpe)\n        {\n            Assert.assertTrue(jpqlpe.getMessage().startsWith(\"Bad query format\"));\n        }\n\n        // Valid Query with where clause.\n        validQuery = \"SELECT c.currency,c FROM Country c where c.currency = INR\";\n\n        kunderQuery = new KunderaQuery(validQuery, kunderaMetadata);\n        parser = new KunderaQueryParser(kunderQuery);\n        try\n        {\n            parser.parse();\n        }\n        catch (JPQLParseException jpqlpe)\n        {\n            Assert.assertTrue(jpqlpe.getMessage().startsWith(\"Bad query format\"));\n        }\n\n        // Valid Query with where clause.\n        validQuery = \"SELECT c. FROM Country c where c.currency = INR\";\n\n        kunderQuery = new KunderaQuery(validQuery, kunderaMetadata);\n\n        parser = new KunderaQueryParser(kunderQuery);\n        try\n        {\n            parser.parse();\n        }\n        catch (JPQLParseException jpqlpe)\n        {\n\n            Assert.assertTrue(jpqlpe.getMessage().startsWith(\n                    \"You have not given any column name after . ,Column name should not be empty\"));\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/query/KunderaQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Parameter;\nimport javax.persistence.Persistence;\nimport javax.persistence.PersistenceException;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.query.KunderaQuery.UpdateClause;\n\n/**\n * The Class KunderaQueryTest.\n * \n * @author vivek.mishra Junit for Kundera query test.\n */\npublic class KunderaQueryTest\n{\n\n    /** The Constant PU. */\n    private static final String PU = \"patest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The kundera metadata. */\n    private KunderaMetadata kunderaMetadata;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(PU);\n        kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        String query = \"Select p from Person p\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        Assert.assertNotNull(kunderaQuery.getEntityClass());\n        Assert.assertEquals(Person.class, kunderaQuery.getEntityClass());\n        Assert.assertNotNull(kunderaQuery.getEntityMetadata());\n        Assert.assertTrue(KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Person.class).equals(\n                kunderaQuery.getEntityMetadata()));\n        Assert.assertNull(kunderaQuery.getFilter());\n        Assert.assertTrue(kunderaQuery.getFilterClauseQueue().isEmpty());\n        Assert.assertNotNull(kunderaQuery.getFrom());\n        Assert.assertTrue(kunderaQuery.getUpdateClauseQueue().isEmpty());\n        Assert.assertNotNull(kunderaQuery.getResult());\n        Assert.assertEquals(PU, kunderaQuery.getPersistenceUnit());\n        Assert.assertNull(kunderaQuery.getOrdering());\n\n        query = \"Select p from Person as p\";\n        kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        Assert.assertNotNull(kunderaQuery.getEntityClass());\n        Assert.assertEquals(Person.class, kunderaQuery.getEntityClass());\n        Assert.assertNotNull(kunderaQuery.getEntityMetadata());\n        Assert.assertTrue(KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Person.class).equals(\n                kunderaQuery.getEntityMetadata()));\n        Assert.assertNull(kunderaQuery.getFilter());\n        Assert.assertTrue(kunderaQuery.getFilterClauseQueue().isEmpty());\n        Assert.assertNotNull(kunderaQuery.getFrom());\n        Assert.assertTrue(kunderaQuery.getUpdateClauseQueue().isEmpty());\n        Assert.assertNotNull(kunderaQuery.getResult());\n        Assert.assertEquals(PU, kunderaQuery.getPersistenceUnit());\n        Assert.assertNull(kunderaQuery.getOrdering());\n\n        try\n        {\n            query = \"Select p from p\";\n            kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n            Assert.fail();\n        }\n        catch (JPQLParseException e)\n        {\n            Assert.assertEquals(\n                    \"Bad query format: p. Identification variable is mandatory in FROM clause for SELECT queries. For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\",\n                    e.getMessage());\n        }\n        try\n        {\n            query = \"Select p form Person p\";\n            kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n            Assert.fail();\n        }\n        catch (JPQLParseException e)\n        {\n            Assert.assertEquals(\n                    \"Bad query format FROM clause is mandatory for SELECT queries. For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\",\n                    e.getMessage());\n        }\n        try\n        {\n            query = \"Selct p from Person p\";\n            kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n            Assert.assertNotNull(kunderaQuery.getEntityClass());\n            Assert.assertEquals(Person.class, kunderaQuery.getEntityClass());\n            Assert.assertNotNull(kunderaQuery.getEntityMetadata());\n            Assert.assertTrue(KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Person.class).equals(\n                    kunderaQuery.getEntityMetadata()));\n            Assert.assertNull(kunderaQuery.getFilter());\n            Assert.assertTrue(kunderaQuery.getFilterClauseQueue().isEmpty());\n            Assert.assertNotNull(kunderaQuery.getFrom());\n            Assert.assertTrue(kunderaQuery.getUpdateClauseQueue().isEmpty());\n            Assert.assertNotNull(kunderaQuery.getResult());\n            Assert.assertEquals(PU, kunderaQuery.getPersistenceUnit());\n            Assert.assertNull(kunderaQuery.getOrdering());\n        }\n        catch (JPQLParseException e)\n        {\n            // Assert.fail();\n            Assert.assertEquals(\n                    \"Bad query format FROM clause is mandatory for SELECT queries. For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\",\n                    e.getMessage());\n        }\n        try\n        {\n            query = \"Select p from Person p where\";\n            kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n            Assert.fail();\n        }\n        catch (JPQLParseException e)\n        {\n            Assert.assertEquals(\n                    \"keyword without value[WHERE]. For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\",\n                    e.getMessage());\n        }\n        try\n        {\n            query = \"Select p from Person p where p\";\n            kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n            // Assert.fail();\n        }\n        catch (PersistenceException e)\n        {\n            Assert.assertEquals(\"bad jpa query: p\", e.getMessage());\n        }\n\n        try\n        {\n            query = \"Select p from invalidPerson p\";\n            kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n        }\n        catch (QueryHandlerException qhex)\n        {\n            Assert.assertEquals(\"No entity found by the name: invalidPerson\", qhex.getMessage());\n        }\n\n        try\n        {\n            query = \"Select p.ABC from Person p\";\n            kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n        }\n        catch (JPQLParseException e)\n        {\n            Assert.assertEquals(\"invalid column nameABC\", e.getMessage());\n        }\n\n        try\n        {\n            query = \"Select p from Person p order by p.personName ASCENDING\";\n            kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n        }\n        catch (JPQLParseException e)\n        {\n            Assert.assertTrue(e.getMessage().startsWith(\"Invalid sort order provided:ASCENDING\"));\n        }\n\n    }\n\n    /**\n     * Test on index parameter.\n     */\n    @Test\n    public void testOnIndexParameter()\n    {\n        String query = \"Select p from Person p where p.personName = ?1 and p.age= ?2\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(1, \"pname\");\n        kunderaQuery.setParameter(2, 32);\n\n        List<String> nameList = new ArrayList<String>();\n        List<Integer> ageList = new ArrayList<Integer>();\n        ageList.add(32);\n\n        Object value = kunderaQuery.getClauseValue(\"?1\");\n        nameList.add(value.toString());\n        Assert.assertNotNull(value);\n        Assert.assertEquals(value, value);\n        value = kunderaQuery.getClauseValue(\"?2\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(ageList, value);\n        Assert.assertEquals(2, kunderaQuery.getParameters().size());\n\n        try\n        {\n            kunderaQuery.getClauseValue(\"invalidparam\");\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertEquals(\"parameter is not a parameter of the query\", iaex.getMessage());\n        }\n\n        Assert.assertNotNull(kunderaQuery.getFilterClauseQueue());\n\n        for (Object clause : kunderaQuery.getFilterClauseQueue())\n        {\n            Assert.assertNotNull(clause);\n            Assert.assertNotNull(clause.toString());\n            if (clause.getClass().isAssignableFrom(FilterClause.class))\n            {\n                Assert.assertNotNull(((FilterClause) clause).getProperty());\n                Assert.assertNotNull(((FilterClause) clause).getValue().get(0));\n                Assert.assertNotNull(((FilterClause) clause).getCondition());\n            }\n            else\n            {\n                Assert.assertEquals(\"AND\", clause.toString().trim());\n            }\n        }\n\n        Iterator<Parameter<?>> parameters = kunderaQuery.getParameters().iterator();\n\n        while (parameters.hasNext())\n        {\n            Assert.assertTrue(kunderaQuery.isBound(parameters.next()));\n        }\n\n        query = \"Select p from Person p where p.age between ?1 and ?2 \";\n        kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(1, 32);\n        kunderaQuery.setParameter(2, 35);\n\n        value = kunderaQuery.getClauseValue(\"?1\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(ageList, value);\n\n        ageList = new ArrayList<Integer>();\n        ageList.add(35);\n\n        value = kunderaQuery.getClauseValue(\"?2\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(ageList, value);\n        Assert.assertEquals(2, kunderaQuery.getParameters().size());\n\n    }\n\n    /**\n     * Test on name parameter.\n     */\n    @Test\n    public void testOnNameParameter()\n    {\n        String query = \"Select p from Person p where p.personName = :name and p.age= :age\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(\"name\", \"pname\");\n        kunderaQuery.setParameter(\"age\", 32);\n\n        Assert.assertEquals(2, kunderaQuery.getParameters().size());\n\n        Iterator<Parameter<?>> parameters = kunderaQuery.getParameters().iterator();\n\n        while (parameters.hasNext())\n        {\n            Assert.assertTrue(kunderaQuery.isBound(parameters.next()));\n        }\n\n        List<String> nameList = new ArrayList<String>();\n        nameList.add(\"pname\");\n        List<Integer> ageList = new ArrayList<Integer>();\n        ageList.add(32);\n\n        Object value = kunderaQuery.getClauseValue(\":name\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(nameList, value);\n        value = kunderaQuery.getClauseValue(\":age\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(ageList, value);\n        Assert.assertEquals(2, kunderaQuery.getParameters().size());\n\n    }\n\n    /**\n     * Test invalid index parameter.\n     */\n    @Test\n    public void testInvalidIndexParameter()\n    {\n        String query = \"Select p from Person p where p.personName = ?1 and p.age= ?2\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(1, \"pname\");\n        kunderaQuery.setParameter(2, 32);\n\n        try\n        {\n            kunderaQuery.getClauseValue(\"?3\");\n            Assert.fail(\"Should be catch block\");\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertEquals(\"parameter is not a parameter of the query\", iaex.getMessage());\n        }\n    }\n\n    /**\n     * Test invalid name parameter.\n     */\n    @Test\n    public void testInvalidNameParameter()\n    {\n        String query = \"Select p from Person p where p.personName = :name and p.age= :age\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(\"name\", \"pname\");\n        kunderaQuery.setParameter(\"age\", 32);\n\n        try\n        {\n            kunderaQuery.getClauseValue(\":naame\");\n            Assert.fail(\"Should be catch block\");\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertEquals(\"parameter is not a parameter of the query\", iaex.getMessage());\n        }\n    }\n\n    /**\n     * Test update clause.\n     */\n    @Test\n    public void testUpdateClause()\n    {\n        String query = \"Update Person p set p.age= ?1, p.personId = ?5 where p.personName = ?2 and p.age = ?3\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(1, 33);\n        kunderaQuery.setParameter(2, \"pname\");\n        kunderaQuery.setParameter(3, 32);\n\n        Assert.assertEquals(4, kunderaQuery.getParameters().size());\n\n        Iterator<Parameter<?>> parameters = kunderaQuery.getParameters().iterator();\n\n        Assert.assertNotNull(kunderaQuery.getUpdateClauseQueue());\n\n        for (UpdateClause clause : kunderaQuery.getUpdateClauseQueue())\n        {\n            Assert.assertNotNull(clause);\n            Assert.assertNotNull(clause.getProperty());\n            Assert.assertNotNull(clause.getValue());\n            Assert.assertNotNull(clause.getClass());\n            Assert.assertNotNull(clause.toString());\n        }\n\n        while (parameters.hasNext())\n        {\n            Parameter parameter = parameters.next();\n            Assert.assertTrue(kunderaQuery.isBound(parameter));\n            Assert.assertNull(parameter.getName());\n            Assert.assertNotNull(parameter.getPosition());\n            Assert.assertNotNull(parameter.toString());\n        }\n\n        try\n        {\n            kunderaQuery.getClauseValue(\":naame\");\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertNotNull(kunderaQuery.toString());\n            Assert.assertEquals(\"parameter is not a parameter of the query\", iaex.getMessage());\n        }\n\n        try\n        {\n            kunderaQuery.getClauseValue(new JPAParameter());\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertNotNull(kunderaQuery.toString());\n            Assert.assertEquals(\"parameter is not a parameter of the query\", iaex.getMessage());\n        }\n\n    }\n\n    /**\n     * Test with in clause.\n     */\n    @Test\n    public void testWithInClause()\n    {\n        final String query = \"Select p from Person p where p.personName <> :name and p.age in('kk', 'dk', 'sk') \";\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n    }\n\n    /**\n     * Test in not in not equals.\n     */\n    @Test\n    public void testInNotInNotEquals()\n    {\n        String query = \"Select p from Person p where p.personName <> :name and p.age IN :ageList\"\n                + \" and p.salary NOT IN :salaryList and (p.personId = :personId)\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(\"name\", \"pname\");\n        kunderaQuery.setParameter(\"ageList\", new ArrayList<Integer>()\n        {\n            {\n                add(20);\n                add(21);\n            }\n        });\n        kunderaQuery.setParameter(\"salaryList\", new ArrayList<Double>()\n        {\n            {\n                add(2000D);\n                add(3000D);\n            }\n        });\n        kunderaQuery.setParameter(\"personId\", \"personId\");\n\n        assertSubQuery(kunderaQuery);\n\n    }\n\n    /**\n     * Test with sub query in mid.\n     */\n    @Test\n    public void testWithSubQueryInMid()\n    {\n        String query = \"Select p from Person p where p.personName <> :name and p.age IN :ageList\"\n                + \" and (p.personId = :personId) and p.salary NOT IN :salaryList\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(\"name\", \"pname\");\n        kunderaQuery.setParameter(\"ageList\", new ArrayList<Integer>()\n        {\n            {\n                add(20);\n                add(21);\n            }\n        });\n        kunderaQuery.setParameter(\"salaryList\", new ArrayList<Double>()\n        {\n            {\n                add(2000D);\n                add(3000D);\n            }\n        });\n        kunderaQuery.setParameter(\"personId\", \"personId\");\n\n        assertSubQuery(kunderaQuery);\n\n    }\n\n    /**\n     * Test with sub query in mid without set param.\n     */\n    @Test\n    public void testWithSubQueryInMidWithoutSetParam()\n    {\n        String query = \"Select p from Person p where p.personName <> pname and p.age IN (20,21,32)\"\n                + \" and (p.personId = :personId) and p.salary NOT IN :salaryList\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(\"salaryList\", new ArrayList<Double>()\n        {\n            {\n                add(2000D);\n                add(3000D);\n            }\n        });\n        kunderaQuery.setParameter(\"personId\", \"personId\");\n\n        assertMixSubQuery(kunderaQuery, 2);\n\n        query = \"Select p from Person p where p.personName <> 'in' and p.age IN (20,21,32)\"\n                + \" and (p.personId = :personId) and p.salary NOT IN :salaryList\";\n        kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(\"salaryList\", new ArrayList<Double>()\n        {\n            {\n                add(2000D);\n                add(3000D);\n            }\n        });\n        kunderaQuery.setParameter(\"personId\", \"personId\");\n        assertMixSubQuery(kunderaQuery, 2);\n\n    }\n\n    /**\n     * Test order by.\n     */\n    @Test\n    public void testOrderBy()\n    {\n        // with uppercase sort order\n        String query = \"Select p from Person p order by p.age ASC\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        Assert.assertNotNull(kunderaQuery.getEntityClass());\n        Assert.assertEquals(Person.class, kunderaQuery.getEntityClass());\n        Assert.assertNotNull(kunderaQuery.getEntityMetadata());\n        Assert.assertTrue(KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Person.class).equals(\n                kunderaQuery.getEntityMetadata()));\n        Assert.assertNull(kunderaQuery.getFilter());\n        Assert.assertTrue(kunderaQuery.getFilterClauseQueue().isEmpty());\n        Assert.assertNotNull(kunderaQuery.getFrom());\n        Assert.assertTrue(kunderaQuery.getUpdateClauseQueue().isEmpty());\n        Assert.assertNotNull(kunderaQuery.getResult());\n        Assert.assertEquals(PU, kunderaQuery.getPersistenceUnit());\n        Assert.assertNotNull(kunderaQuery.getOrdering());\n        Assert.assertEquals(1, kunderaQuery.getOrdering().size());\n        Assert.assertEquals(\"p.age\", kunderaQuery.getOrdering().get(0).getColumnName());\n        Assert.assertEquals(KunderaQuery.SortOrder.ASC, kunderaQuery.getOrdering().get(0).getOrder());\n\n        // with lowercase sort order\n        query = \"Select p from Person p order by p.salary desc\";\n        kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        Assert.assertNotNull(kunderaQuery.getEntityClass());\n        Assert.assertEquals(Person.class, kunderaQuery.getEntityClass());\n        Assert.assertNotNull(kunderaQuery.getEntityMetadata());\n        Assert.assertTrue(KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Person.class).equals(\n                kunderaQuery.getEntityMetadata()));\n        Assert.assertNull(kunderaQuery.getFilter());\n        Assert.assertTrue(kunderaQuery.getFilterClauseQueue().isEmpty());\n        Assert.assertNotNull(kunderaQuery.getFrom());\n        Assert.assertTrue(kunderaQuery.getUpdateClauseQueue().isEmpty());\n        Assert.assertNotNull(kunderaQuery.getResult());\n        Assert.assertEquals(PU, kunderaQuery.getPersistenceUnit());\n        Assert.assertNotNull(kunderaQuery.getOrdering());\n        Assert.assertEquals(1, kunderaQuery.getOrdering().size());\n        Assert.assertEquals(\"p.salary\", kunderaQuery.getOrdering().get(0).getColumnName());\n        Assert.assertEquals(KunderaQuery.SortOrder.DESC, kunderaQuery.getOrdering().get(0).getOrder());\n    }\n\n    @Test\n    public void testComplexQuery()\n    {\n        String query =\n              \"SELECT p FROM Person p \" +\n                    \"WHERE (p.age > :maxAge OR p.age < :minAge) \" +\n                    \"AND UPPER(p.personName) LIKE '%TEST%' \" +\n                    \"ORDER BY p.personId ASC\";\n\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        Assert.assertNotNull(kunderaQuery.getEntityClass());\n        Assert.assertEquals(Person.class, kunderaQuery.getEntityClass());\n        Assert.assertNotNull(kunderaQuery.getEntityMetadata());\n        Assert.assertTrue(KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Person.class).equals(\n              kunderaQuery.getEntityMetadata()));\n        Assert.assertNotNull(kunderaQuery.getFilter());\n        Assert.assertFalse(kunderaQuery.getFilterClauseQueue().isEmpty());\n        Assert.assertNotNull(kunderaQuery.getFrom());\n        Assert.assertTrue(kunderaQuery.getUpdateClauseQueue().isEmpty());\n        Assert.assertNotNull(kunderaQuery.getResult());\n        Assert.assertEquals(PU, kunderaQuery.getPersistenceUnit());\n        Assert.assertNotNull(kunderaQuery.getOrdering());\n        Assert.assertEquals(1, kunderaQuery.getOrdering().size());\n        Assert.assertEquals(\"p.personId\", kunderaQuery.getOrdering().get(0).getColumnName());\n        Assert.assertEquals(KunderaQuery.SortOrder.ASC, kunderaQuery.getOrdering().get(0).getOrder());\n\n        List<String> expectedConditions = Arrays.asList(\">\", \"<\", \"LIKE\");\n        List<Boolean> expectedIgnoreCaseSettings = Arrays.asList(false, false, true);\n\n        int index = 0;\n\n        for (Object filterObject : kunderaQuery.getFilterClauseQueue()) {\n            if (filterObject instanceof FilterClause) {\n                FilterClause clause = (FilterClause) filterObject;\n\n                Assert.assertEquals(expectedConditions.get(index), clause.getCondition());\n                Assert.assertEquals(expectedIgnoreCaseSettings.get(index), clause.isIgnoreCase());\n\n                index++;\n            }\n        }\n    }\n\n    /**\n     * Assert mix sub query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param paramSize\n     *            the param size\n     */\n    private void assertMixSubQuery(KunderaQuery kunderaQuery, int paramSize)\n    {\n        Assert.assertEquals(paramSize, kunderaQuery.getParameters().size());\n\n        Iterator<Parameter<?>> parameters = kunderaQuery.getParameters().iterator();\n\n        while (parameters.hasNext())\n        {\n            Assert.assertTrue(kunderaQuery.isBound(parameters.next()));\n        }\n\n        List<String> nameList = new ArrayList<String>();\n        nameList.add(\"pname\");\n        List<Integer> ageList = new ArrayList<Integer>()\n        {\n            {\n                add(20);\n                add(21);\n            }\n        };\n        List<Double> salaryList = new ArrayList<Double>()\n        {\n            {\n                add(2000D);\n                add(3000D);\n            }\n        };\n        List<String> personIdList = new ArrayList<String>();\n        personIdList.add(\"personId\");\n\n        Object value = kunderaQuery.getClauseValue(\":salaryList\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(salaryList, value);\n        value = kunderaQuery.getClauseValue(\":personId\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(personIdList, value);\n        Assert.assertEquals(paramSize, kunderaQuery.getParameters().size());\n    }\n\n    /**\n     * Assert sub query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     */\n    private void assertSubQuery(KunderaQuery kunderaQuery)\n    {\n        Assert.assertEquals(4, kunderaQuery.getParameters().size());\n\n        Iterator<Parameter<?>> parameters = kunderaQuery.getParameters().iterator();\n\n        while (parameters.hasNext())\n        {\n            Assert.assertTrue(kunderaQuery.isBound(parameters.next()));\n        }\n\n        List<String> nameList = new ArrayList<String>();\n        nameList.add(\"pname\");\n        List<Integer> ageList = new ArrayList<Integer>()\n        {\n            {\n                add(20);\n                add(21);\n            }\n        };\n        List<Double> salaryList = new ArrayList<Double>()\n        {\n            {\n                add(2000D);\n                add(3000D);\n            }\n        };\n        List<String> personIdList = new ArrayList<String>();\n        personIdList.add(\"personId\");\n\n        Object value = kunderaQuery.getClauseValue(\":name\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(nameList, value);\n        value = kunderaQuery.getClauseValue(\":ageList\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(ageList, value);\n        value = kunderaQuery.getClauseValue(\":salaryList\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(salaryList, value);\n        value = kunderaQuery.getClauseValue(\":personId\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(personIdList, value);\n        Assert.assertEquals(4, kunderaQuery.getParameters().size());\n    }\n\n    /**\n     * The Class JPAParameter.\n     */\n    private class JPAParameter implements Parameter<String>\n    {\n\n        /*\n         * (non-Javadoc)\n         * \n         * @see javax.persistence.Parameter#getName()\n         */\n        @Override\n        public String getName()\n        {\n            return \"jpa\";\n        }\n\n        /*\n         * (non-Javadoc)\n         * \n         * @see javax.persistence.Parameter#getPosition()\n         */\n        @Override\n        public Integer getPosition()\n        {\n            return 0;\n        }\n\n        /*\n         * (non-Javadoc)\n         * \n         * @see javax.persistence.Parameter#getParameterType()\n         */\n        @Override\n        public Class<String> getParameterType()\n        {\n            return String.class;\n        }\n\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/query/KunderaTypedQueryTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.query;\n\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.FlushModeType;\nimport javax.persistence.LockModeType;\nimport javax.persistence.NoResultException;\nimport javax.persistence.Persistence;\nimport javax.persistence.TemporalType;\nimport javax.persistence.TypedQuery;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.entities.SampleEntity;\n\n/**\n * @author vivek.mishra\n * \n *         junit for {@link KunderaTypedQuery}\n * \n */\npublic class KunderaTypedQueryTest\n{\n\n    private EntityManager em;\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp()\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"kunderatest\");\n\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testTypedQuery()\n    {\n        final String namedQuery = \"Select s from SampleEntity s where s.name = :name\";\n\n        TypedQuery<SampleEntity> query = em.createNamedQuery(namedQuery, SampleEntity.class);\n\n        Assert.assertTrue(query.getClass().isAssignableFrom(KunderaTypedQuery.class));\n\n        query.setMaxResults(100);\n        Assert.assertEquals(100, query.getMaxResults());\n\n        Assert.assertEquals(0, query.executeUpdate());\n\n        Assert.assertEquals(0, query.getHints().size());\n        query.setHint(\"test\", \"test\");\n        Assert.assertNotNull(query.getHints());\n\n        assertOnUnsupportedMethod(query);\n        Assert.assertEquals(FlushModeType.AUTO, FlushModeType.AUTO);\n\n        ((Query) query).setFetchSize(100);\n        Assert.assertNotNull(((Query) query).getFetchSize());\n        Assert.assertEquals(100, ((Query) query).getFetchSize().intValue());\n\n        Assert.assertNotNull(query.getParameter(\"name\"));\n\n        Assert.assertNotNull(query.getParameterValue(\"name\"));\n\n        Assert.assertNotNull(query.getParameterValue(query.getParameter(\"name\")));\n        Assert.assertEquals(1, query.getParameters().size());\n        Assert.assertTrue(query.isBound(query.getParameter(\"name\")));\n\n        Assert.assertNull(query.getParameter(1));\n\n        Assert.assertNull(((Query) query).iterate());\n\n        try\n        {\n            query.getSingleResult();\n        }\n        catch (NoResultException e)\n        {\n            Assert.assertEquals(\"No result found!\", e.getMessage());\n        }\n        ((Query) query).close();\n    }\n\n    /**\n     * @param query\n     */\n    private void assertOnUnsupportedMethod(TypedQuery<SampleEntity> query)\n    {\n        try\n        {\n            query.setFlushMode(FlushModeType.AUTO);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setFlushMode is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setFirstResult(1);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setFirstResult is unsupported by Kundera\", usex.getMessage());\n        }\n\n        // try\n        // {\n        // query.getSingleResult();\n        // } catch(UnsupportedOperationException usex)\n        // {\n        // Assert.assertEquals(\"getSingleResult is unsupported by Kundera\",\n        // usex.getMessage());\n        // }\n\n        try\n        {\n            query.getFirstResult();\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"getFirstResult is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setLockMode(LockModeType.NONE);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setLockMode is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.getLockMode();\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"getLockMode is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setParameter(0, new Date(), TemporalType.DATE);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setParameter(\"param\", new Date(), TemporalType.DATE);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setParameter(0, Calendar.getInstance(), TemporalType.DATE);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setParameter(\"param\", Calendar.getInstance(), TemporalType.DATE);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.getFlushMode();\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"getFlushMode is unsupported by Kundera\", usex.getMessage());\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/query/Person.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\"), @Index(name = \"salary\") })\npublic class Person\n{\n    /** The person id. */\n    @Id\n     @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n    \n    /** The salary. */\n    @Column(name = \"SALARY\")\n    private Double salary;\n\n    @Column(name = \"DAY\")\n    @Enumerated(EnumType.STRING)\n    private Day day;   \n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the day\n     */\n    public Day getDay()\n    {\n        return day;\n    }\n\n    public enum Day\n    {\n        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n    }\n\n    /**\n     * @param age the age to set\n     */\n    public void setAge(Integer age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @param day the day to set\n     */\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n    \n    /**\n     * @param salary the salary to set\n     */\n    public void setSalary(Double salary)\n    {\n        this.salary = salary;\n    }\n\n    /**\n     * @param day the day to set\n     */\n    public Double getSalary()\n    {\n        return this.salary;\n    }\n    \n    \n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/query/PersonEntityNameAnnotation.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity(name=\"PF\")\n@Table(name = \"PERSON\", schema = \"KunderaTests@patest\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\npublic class PersonEntityNameAnnotation\n{\n/*    public static final String UID = \"uid\";\n\n    public static final String EID = \"eid\";\n\n    public static final String FIRST_NAME = \"firstName\";\n\n    public static final String LAST_NAME = \"lastName\";\n\n    public static final String CITY = \"city\";\n\n    public static final String CREATED = \"created\";\n\n    public static final String LAST_MODIFIED = \"lastModified\";*/\n\n    /** The person id. */\n    @Id\n     @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;   \n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the day\n     */\n    public Day getDay()\n    {\n        return day;\n    }\n\n    public enum Day\n    {\n        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n    }\n\n    /**\n     * @param age the age to set\n     */\n    public void setAge(Integer age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @param day the day to set\n     */\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n    \n    \n\n}\n\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/query/QueryExceptionTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.query;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.cache.CacheException;\nimport com.impetus.kundera.classreading.ResourceReadingException;\nimport com.impetus.kundera.client.ClientResolverException;\nimport com.impetus.kundera.configure.PersistenceUnitConfigurationException;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.index.IndexingException;\nimport com.impetus.kundera.index.LuceneIndexingException;\nimport com.impetus.kundera.loader.ClientLoaderException;\nimport com.impetus.kundera.loader.KunderaAuthenticationException;\nimport com.impetus.kundera.loader.MetamodelLoaderException;\nimport com.impetus.kundera.loader.PersistenceLoaderException;\nimport com.impetus.kundera.metadata.model.ApplicationLoaderException;\nimport com.impetus.kundera.metadata.validator.InvalidEntityDefinitionException;\nimport com.impetus.kundera.persistence.EntityReaderException;\nimport com.impetus.kundera.persistence.KunderaTransactionException;\nimport com.impetus.kundera.persistence.event.EventListenerException;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.proxy.LazyInitializationException;\nimport com.impetus.kundera.utils.InvalidConfigurationException;\n\n/**\n * @author vivek.mishra junit for {@link QueryHandlerException},\n *         {@link JPQLParseException}, {@link EntityReaderException} etc. Somehow\n *         coverage is not getting count. So this junit is purly from coverage\n *         purpose only.\n */\npublic class QueryExceptionTest\n{\n\n    @Test\n    public void testQueryHandlerException()\n    {\n        QueryHandlerException exception = new QueryHandlerException();\n        Assert.assertNotNull(exception);\n\n        exception = new QueryHandlerException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        exception = new QueryHandlerException(\"Error with string and runtime error\", new RuntimeException());\n        Assert.assertNotNull(exception);\n        exception = new QueryHandlerException(new RuntimeException());\n        Assert.assertNotNull(exception);\n    }\n\n    @Test\n    public void testJPQLParseException()\n    {\n        JPQLParseException exception = new JPQLParseException();\n        Assert.assertNotNull(exception);\n\n        exception = new JPQLParseException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        exception = new JPQLParseException(new RuntimeException());\n        Assert.assertNotNull(exception);\n    }\n\n    @Test\n    public void testLazyInitializationException()\n    {\n        LazyInitializationException exception = new LazyInitializationException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        exception = new LazyInitializationException(new RuntimeException());\n        Assert.assertNotNull(exception);\n    }\n\n    @Test\n    public void testEntityReaderException()\n    {\n        EntityReaderException exception = new EntityReaderException();\n        Assert.assertNotNull(exception);\n\n        exception = new EntityReaderException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        exception = new EntityReaderException(new RuntimeException());\n        Assert.assertNotNull(exception);\n    }\n\n    @Test\n    public void testKunderaTransactionException()\n    {\n        KunderaTransactionException exception = new KunderaTransactionException();\n        Assert.assertNotNull(exception);\n\n        exception = new KunderaTransactionException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        exception = new KunderaTransactionException(new RuntimeException());\n        Assert.assertNotNull(exception);\n        \n        exception = new KunderaTransactionException(\"Error with string\", new RuntimeException());\n        Assert.assertNotNull(exception);\n        \n        exception = new KunderaTransactionException(\"Error with string\", new RuntimeException());\n        Assert.assertNotNull(exception);\n    }\n\n    @Test\n    public void testMetaModelLoaderException()\n    {\n        MetamodelLoaderException exception = new MetamodelLoaderException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        \n        exception = new MetamodelLoaderException(new RuntimeException());\n        Assert.assertNotNull(exception);\n    \n        exception = new MetamodelLoaderException(\"KunderaTests\",new RuntimeException());\n        Assert.assertNotNull(exception);\n        \n        exception = new MetamodelLoaderException();\n        Assert.assertNotNull(exception);\n    }\n\n    @Test\n    public void testClientLoaderException()\n    {\n        ClientLoaderException exception = new ClientLoaderException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        \n        exception = new ClientLoaderException(new RuntimeException());\n        Assert.assertNotNull(exception);\n    \n        exception = new ClientLoaderException(\"KunderaTests\",new RuntimeException());\n        Assert.assertNotNull(exception);\n        \n        exception = new ClientLoaderException();\n        Assert.assertNotNull(exception);\n    }\n\n\n    @Test\n    public void testPersistenceLoaderException()\n    {\n        PersistenceLoaderException exception = new PersistenceLoaderException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        \n        exception = new PersistenceLoaderException(new RuntimeException());\n        Assert.assertNotNull(exception);\n    \n        exception = new PersistenceLoaderException(\"KunderaTests\",new RuntimeException());\n        Assert.assertNotNull(exception);\n        \n        exception = new PersistenceLoaderException();\n        Assert.assertNotNull(exception);\n    }\n\n    @Test\n    public void testKunderaAuthenticationException()\n    {\n        KunderaAuthenticationException exception = new KunderaAuthenticationException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        \n        exception = new KunderaAuthenticationException(new RuntimeException());\n        Assert.assertNotNull(exception);\n    \n        exception = new KunderaAuthenticationException(\"KunderaTests\",new RuntimeException());\n        Assert.assertNotNull(exception);\n        \n        exception = new KunderaAuthenticationException();\n        Assert.assertNotNull(exception);\n    }\n\n    @Test\n    public void testLuceneIndexingException()\n    {\n        LuceneIndexingException exception = new LuceneIndexingException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        \n        exception = new LuceneIndexingException(new RuntimeException());\n        Assert.assertNotNull(exception);\n    \n        exception = new LuceneIndexingException(\"KunderaTests\",new RuntimeException());\n        Assert.assertNotNull(exception);\n        \n        exception = new LuceneIndexingException();\n        Assert.assertNotNull(exception);\n    }\n\n    @Test\n    public void testIndexingException()\n    {\n        IndexingException exception = new IndexingException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        \n        exception = new IndexingException(new RuntimeException());\n        Assert.assertNotNull(exception);\n    \n        exception = new IndexingException(\"KunderaTests\",new RuntimeException());\n        Assert.assertNotNull(exception);\n        \n        exception = new IndexingException();\n        Assert.assertNotNull(exception);\n    }\n\n    @Test\n    public void testInvalidEntityDefintionException()\n    {\n        InvalidEntityDefinitionException exception = new InvalidEntityDefinitionException(\"Error with string\");\n        Assert.assertNotNull(exception);\n    \n        exception = new InvalidEntityDefinitionException();\n        Assert.assertNotNull(exception);\n    }\n    \n    @Test\n    public void testInvalidConfigurationException()\n    {\n        InvalidConfigurationException exception = new InvalidConfigurationException(\"Error with string\");\n        Assert.assertNotNull(exception);\n    \n\n        exception = new InvalidConfigurationException(new RuntimeException());\n        Assert.assertNotNull(exception);\n        \n        exception = new InvalidConfigurationException();\n        Assert.assertNotNull(exception);        \n        \n        exception = new InvalidConfigurationException(\"Error with string\", new RuntimeException());\n        Assert.assertNotNull(exception);\n    }\n    \n    @Test\n    public void testResourceReadingException()\n    {\n        ResourceReadingException exception = new com.impetus.kundera.classreading.ResourceReadingException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        \n        exception = new ResourceReadingException(new RuntimeException());\n        Assert.assertNotNull(exception);\n    \n        exception = new ResourceReadingException(\"KunderaTests\",new RuntimeException());\n        Assert.assertNotNull(exception);\n        \n        exception = new ResourceReadingException();\n        Assert.assertNotNull(exception);\n    }\n\n    @Test\n    public void testSchemaGenerationException()\n    {\n\n        SchemaGenerationException exception = new SchemaGenerationException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        \n        exception = new SchemaGenerationException(new RuntimeException());\n        Assert.assertNotNull(exception);\n\n    \n        exception = new SchemaGenerationException(new RuntimeException(),\"KunderaTests\");\n        Assert.assertNotNull(exception);\n\n        exception = new SchemaGenerationException(new RuntimeException(),\"KunderaTests\",\"test\");\n        Assert.assertNotNull(exception);\n\n        exception = new SchemaGenerationException(new RuntimeException(),\"KunderaTests\",\"test\");\n        Assert.assertNotNull(exception);\n\n        exception = new SchemaGenerationException(\"error with string \",new RuntimeException(),\"KunderaTests\",\"test\");\n        Assert.assertNotNull(exception);\n        \n        exception = new SchemaGenerationException(\"error with string \", \"cassandra\", \"KunderaTests\",\"test\");\n        Assert.assertNotNull(exception);\n\n        exception = new SchemaGenerationException(\"error with string \",\"KunderaTests\",\"test\");\n        Assert.assertNotNull(exception);\n\n        exception = new SchemaGenerationException(\"error with string \",new RuntimeException(),\"KunderaTests\");\n        Assert.assertNotNull(exception);\n    }\n\n    @Test\n    public void testPersistenceUnitConfigurationException()\n    {\n        PersistenceUnitConfigurationException exception = new PersistenceUnitConfigurationException(\"Error with string\");\n        Assert.assertNotNull(exception);\n        \n        exception = new PersistenceUnitConfigurationException(new RuntimeException());\n        Assert.assertNotNull(exception);   \n\n        exception = new PersistenceUnitConfigurationException();\n        Assert.assertNotNull(exception);\n\n        exception = new PersistenceUnitConfigurationException(\"KunderaTests\", new RuntimeException());\n        Assert.assertNotNull(exception);\n\n        exception = new PersistenceUnitConfigurationException(\"error with string \");\n        Assert.assertNotNull(exception);\n\n        exception = new PersistenceUnitConfigurationException(new RuntimeException());\n        Assert.assertNotNull(exception);\n    }\n\n    @Test\n    public void testApplicationLoaderException()\n    {\n        ApplicationLoaderException exception = new ApplicationLoaderException(\"Error with string\");\n        Assert.assertNotNull(exception);        \n    }\n    \n    @Test\n    public void testPropertyAccessException()\n    {\n        PropertyAccessException exception = new PropertyAccessException(\"Error with string\");\n        Assert.assertNotNull(exception); \n        \n        exception = new PropertyAccessException();\n        Assert.assertNotNull(exception);   \n        \n        exception = new PropertyAccessException(new RuntimeException());\n        Assert.assertNotNull(exception);   \n    }\n    \n    @Test\n    public void testEventListenerException()\n    {\n        EventListenerException exception = new EventListenerException(\"Error with string\");\n        Assert.assertNotNull(exception); \n        \n        exception = new EventListenerException(\"Error with string\", new RuntimeException());\n        Assert.assertNotNull(exception); \n        \n        exception = new EventListenerException(new RuntimeException());\n        Assert.assertNotNull(exception); \n        \n        exception = new EventListenerException();\n        Assert.assertNotNull(exception);      \n       \n    }\n    \n    @Test\n    public void testCacheException()\n    {\n        CacheException exception = new CacheException(\"Error with string\");\n        Assert.assertNotNull(exception); \n        \n        exception = new CacheException(\"Error with string\", new RuntimeException());\n        Assert.assertNotNull(exception); \n        \n        exception = new CacheException(new RuntimeException());\n        Assert.assertNotNull(exception); \n        \n       \n    }\n    \n    @Test\n    public void testClientResolverException()\n    {\n        ClientResolverException exception = new ClientResolverException(\"Error with string\");\n        Assert.assertNotNull(exception); \n        \n        exception = new ClientResolverException(\"Error with string\", new RuntimeException());\n        Assert.assertNotNull(exception); \n        \n        exception = new ClientResolverException(new RuntimeException());\n        Assert.assertNotNull(exception); \n        \n        exception = new ClientResolverException();\n        Assert.assertNotNull(exception); \n    }\n        \n       \n        \n       \n    \n    \n    \n    \n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/query/QueryImplTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.query;\n\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.FlushModeType;\nimport javax.persistence.LockModeType;\nimport javax.persistence.NoResultException;\nimport javax.persistence.Persistence;\nimport javax.persistence.TemporalType;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.CoreTestUtilities;\nimport com.impetus.kundera.client.DummyDatabase;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * @author vivek.mishra junit for {@link QueryImpl}\n * \n */\npublic class QueryImplTest\n{\n\n    private static final String PU = \"patest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private KunderaMetadata kunderaMetadata;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(PU);\n        kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n        em = emf.createEntityManager();\n\n    }\n\n    private KunderaQuery parseQuery(final String query)\n    {\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        return kunderaQuery;\n    }\n\n    @After\n    public void tearDown()\n    {\n        DummyDatabase.INSTANCE.dropDatabase();\n        LuceneCleanupUtilities.cleanLuceneDirectory(kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(PU));\n    }\n\n    /**\n     * @param query\n     * @throws IllegalAccessException\n     * @throws IllegalArgumentException\n     * @throws SecurityException\n     * @throws NoSuchFieldException\n     */\n    @Test\n    public void assertOnUnsupportedMethod() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException\n    {\n        String queryStr = \"Select p from Person p where p.personId = :personId\";\n\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n\n        KunderaQueryParser queryParser;\n        KunderaQuery kunderaQuery = parseQuery(queryStr);\n\n        CoreQuery query = new CoreQuery(kunderaQuery, delegator, kunderaMetadata);\n\n        try\n        {\n            query.setFlushMode(FlushModeType.AUTO);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setFlushMode is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setFirstResult(1);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setFirstResult is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.getSingleResult();\n        }\n        catch (NoResultException e)\n        {\n            Assert.assertEquals(\"No result found!\", e.getMessage());\n        }\n        \n        try\n        {\n            query.getFirstResult();\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"getFirstResult is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setLockMode(LockModeType.NONE);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setLockMode is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.getLockMode();\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"getLockMode is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setParameter(0, new Date(), TemporalType.DATE);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setParameter(\"param\", new Date(), TemporalType.DATE);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setParameter(0, Calendar.getInstance(), TemporalType.DATE);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setParameter(\"param\", Calendar.getInstance(), TemporalType.DATE);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setParameter(CoreTestUtilities.getParameter(), Calendar.getInstance(), TemporalType.DATE);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setParameter(CoreTestUtilities.getParameter(), new Date(), TemporalType.DATE);\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.getFlushMode();\n        }\n        catch (UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"getFlushMode is unsupported by Kundera\", usex.getMessage());\n        }\n\n    }\n\n    @Test\n    public void testGetColumns()\n    {\n        try\n        {\n            String queryStr = \"Select p from Person p where p.personId = :personId\";\n\n            PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n\n            KunderaQueryParser queryParser;\n            KunderaQuery kunderaQuery = parseQuery(queryStr);\n\n            CoreQuery query = new CoreQuery(kunderaQuery, delegator, kunderaMetadata);\n\n            EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Person.class);\n            String[] columns = query.getColumns(new String[] { \"personName\", \"age\" }, m);\n            Assert.assertNotNull(columns);\n            Assert.assertTrue(columns.length > 0);\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    @Test\n    public void testGroupByAndOrderBy()\n    {\n        try\n        {\n            String queryStr = \"Select p from Person p where p.personId = :personId GROUP BY personId\";\n            KunderaQuery kunderaQuery = new KunderaQuery(queryStr, kunderaMetadata);\n            KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n\n            queryStr = \"Select p from Person p where p.personId = :personId GROUP BY personId HAVING 1\";\n            kunderaQuery = new KunderaQuery(queryStr, kunderaMetadata);\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n\n            queryStr = \"Select p from Person p where p.personId = :personId GROUP BY personId ORDER BY personName\";\n            kunderaQuery = new KunderaQuery(queryStr, kunderaMetadata);\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n        }\n        catch (Exception e)\n        {\n            Assert.fail(e.getMessage());\n        }\n\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/service/CoreHostConfiguration.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.service;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection.Server;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * @author vivek.mishra\n *\n *  Dummy core host configuration class.\n */\npublic class CoreHostConfiguration extends HostConfiguration\n{\n\n    String hosts;\n    String port;\n\n    public CoreHostConfiguration(Map externalProperties, List<Server> servers, String persistenceUnit, KunderaMetadata kunderaMetadata)\n    {\n        super(externalProperties, servers, persistenceUnit, kunderaMetadata);\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.service.HostConfiguration#buildHosts(java.util.List, java.util.List)\n     */\n    @Override\n    protected void buildHosts(List<Server> servers, List<Host> hostsList)\n    {\n     // do nothing\n\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.service.HostConfiguration#buildHosts(java.lang.String, java.lang.String, java.util.List)\n     */\n    @Override\n    protected void buildHosts(String hosts, String portAsString, List<Host> hostsList)\n    {\n        this.hosts = hosts;\n        this.port = portAsString;\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.service.HostConfiguration#setConfig(com.impetus.kundera.service.Host, java.util.Properties, java.util.Map)\n     */\n    @Override\n    protected void setConfig(Host host, Properties props, Map puProperties)\n    {\n        // do nothing\n\n    }\n    \n    public void onValidation(final String host, final String port)\n    {\n        super.onValidation(host, port);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/service/HostconfigurationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.service;\n\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * @author vivek.mishra\n * \n *         junit test case for HostConfiguration.\n * \n */\npublic class HostconfigurationTest\n{\n    /* persistence unit. */\n    private String persistenceUnit = \"metaDataTest\";\n\n    private EntityManagerFactoryImpl emf;\n\n    /**\n     * on setup\n     */\n    @Before\n    public void setUp()\n    {\n        emf = getEntityManagerFactory(\"create\");\n    }\n\n    /**\n     * test method.\n     */\n    @Test\n    public void test()\n    {\n        CoreHostConfiguration hostConfiguration = new CoreHostConfiguration(null, null, persistenceUnit, emf.getKunderaMetadataInstance());\n        Assert.assertNotNull(hostConfiguration.hosts);\n        Assert.assertNotNull(hostConfiguration.port);\n        Assert.assertTrue(hostConfiguration.getHosts().isEmpty());\n        Assert.assertEquals(\"localhost\", hostConfiguration.hosts);\n        Assert.assertEquals(\"9160\", hostConfiguration.port);\n\n        try\n        {\n            hostConfiguration.onValidation(null, null);\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertNotNull(iaex.getMessage());\n        }\n\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory(final String schemaProperty)\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(persistenceUnit);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/service/policy/RetryServiceTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.service.policy;\n\nimport java.util.concurrent.ScheduledExecutorService;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.service.Host;\n\npublic class RetryServiceTest\n{\n\n    @Test\n    public void test()\n    {\n        TestRetryService retryService = new TestRetryService(10);\n        \n        Assert.assertNotNull(retryService.getExecutorService());\n    }\n\n    \n    class TestRetryService extends RetryService\n    {\n        public TestRetryService(int retryDelay)\n        {\n            super(retryDelay);\n        }\n\n        @Override\n        protected boolean verifyConnection(Host host)\n        {\n            return false;\n        }\n\n        public ScheduledExecutorService getExecutorService()\n        {\n            return executor;\n        }\n        \n        @Override\n        public void shutdown()\n        {\n            // Do nothing.\n            \n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/service/policy/RoundRobinBalancingPolicyTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.service.policy;\n\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * To test round robin algo.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class RoundRobinBalancingPolicyTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.service.policy.RoundRobinBalancingPolicy#getPool(java.util.Collection)}\n     * .\n     */\n    @Test\n    public void testGetPool()\n    {\n        Map<String, Object> map = new LinkedHashMap<String, Object>();\n        Object o1 = new Object();\n        Object o2 = new Object();\n        Object o3 = new Object();\n        map.put(\"first\", o1);\n        map.put(\"second\", o2);\n        map.put(\"third\", o3);\n\n        RoundRobinBalancingPolicy balancingPolicy = new RoundRobinBalancingPolicy();\n\n        for (int i = 0; i < 1300; i++)\n        {\n            Object o = balancingPolicy.getPool(map.values());\n            Assert.assertNotNull(o);\n            if (i % 3 == 0)\n            {\n                Assert.assertEquals(o1, o);\n            }\n            else if (i % 3 == 1)\n            {\n                Assert.assertEquals(o2, o);\n            }\n            else if (i % 3 == 2)\n            {\n                Assert.assertEquals(o3, o);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/utils/DeepEqualsTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.utils;\n\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.Collection;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.TreeMap;\nimport java.util.TreeSet;\n\nimport junit.framework.TestCase;\n\nimport com.impetus.kundera.entity.album.AlbumUni_1_M_1_M;\nimport com.impetus.kundera.entity.photo.PhotoUni_1_M_1_M;\nimport com.impetus.kundera.entity.photographer.PhotographerUni_1_M_1_M;\n\n/**\n * Test for DeepEquals (equals() and hashCode())\n * \n * @author John DeRegnaucourt (jdereg@gmail.com) <br/>\n *         Copyright [2010] John DeRegnaucourt <br/>\n * <br/>\n *         Licensed under the Apache License, Version 2.0 (the \"License\"); you\n *         may not use this file except in compliance with the License. You may\n *         obtain a copy of the License at <br/>\n * <br/>\n *         http://www.apache.org/licenses/LICENSE-2.0 <br/>\n * <br/>\n *         Unless required by applicable law or agreed to in writing, software\n *         distributed under the License is distributed on an \"AS IS\" BASIS,\n *         WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n *         implied. See the License for the specific language governing\n *         permissions and limitations under the License.\n */\npublic class DeepEqualsTest extends TestCase\n{\n    public DeepEqualsTest()\n    {\n    }\n\n    private class Person\n    {\n        String first;\n\n        String last;\n\n        Pet pet;\n    }\n\n    private class Pet\n    {\n        Pet(String nm, String t)\n        {\n            name = new String(nm);\n            type = new String(t);\n        }\n\n        String name;\n\n        String type;\n    }\n\n    private class Pathelogical\n    {\n    }\n\n    private class ComparablePet extends Pet implements Comparable\n    {\n        ComparablePet(String nm, String t)\n        {\n            super(nm, t);\n        }\n\n        public int compareTo(Object o)\n        {\n            if (o == null || !(o instanceof ComparablePet))\n            {\n                return 1;\n            }\n            ComparablePet that = (ComparablePet) o;\n            if (name.compareTo(that.name) == 0)\n            {\n                return type.compareTo(that.type);\n            }\n            return name.compareTo(that.name);\n        }\n\n    }\n\n    private class ArrayClass\n    {\n        String name;\n\n        Object[] items;\n    }\n\n    private class Cycle\n    {\n        String value;\n\n        Object next;\n    }\n\n    private class FixedHierarchy\n    {\n        String value;\n\n        Object child1;\n\n        Object child2;\n\n        Object child3;\n    }\n\n    private class CollectionClass\n    {\n        String value;\n\n        Collection items;\n    }\n\n    private class MapClass\n    {\n        String value;\n\n        Map items;\n    }\n\n    private class SmartPet extends Pet\n    {\n        SmartPet(String nm, String t)\n        {\n            super(nm, t);\n        }\n\n        // Pathological equals!!! Intentionally wrong to prove that it is\n        // called.\n        public boolean equals(Object o)\n        {\n            if (o == null || !(o instanceof Pet))\n            {\n                return false;\n            }\n\n            Pet that = (Pet) o;\n            boolean nameEquals;\n            if (name == null || that.name == null)\n            {\n                nameEquals = name != that.name;\n            }\n            else\n            {\n                nameEquals = !name.equals(that.name);\n            }\n\n            if (!nameEquals)\n            {\n                return false;\n            }\n            boolean typeEquals;\n            if (type == null || that.type == null)\n            {\n                typeEquals = type != that.type;\n            }\n            else\n            {\n                typeEquals = !type.equals(that.type);\n            }\n            return typeEquals;\n        }\n\n        public int hashCode()\n        {\n            int h1 = (name == null) ? 0 : name.hashCode();\n            int h2 = (type == null) ? 0 : type.hashCode();\n            return h1 + h2;\n        }\n    }\n\n    public void testHashCodeAndEquals()\n    {\n        Person p1 = new Person();\n        p1.first = new String(\"John\");\n        p1.last = new String(\"DeRegnaucourt\");\n        int a = DeepEquals.deepHashCode(p1);\n        int b = \"John\".hashCode();\n        int c = \"DeRegnaucourt\".hashCode();\n        assertTrue(a != b && b != c);\n\n        Pet pet1 = new Pet(\"Eddie\", \"dog\");\n        Pet pet2 = new Pet(\"Penny\", \"dog\");\n        p1.pet = pet1;\n\n        Person p2 = new Person();\n        p2.first = new String(\"John\");\n        p2.last = new String(\"DeRegnaucourt\");\n\n        p2.pet = pet2;\n\n        assertTrue(p1.first != p2.first); // Ensure that the Strings are not ==\n\n        assertTrue(!DeepEquals.deepEquals(p1, p2));\n        assertTrue(!p1.equals(p2));\n\n        p2.pet = pet1;\n        assertTrue(DeepEquals.deepEquals(p1, p2));\n        assertTrue(!p1.equals(p2)); // should be different because it would use\n                                    // Object.equals() which is instance based\n    }\n\n    public void testCycleHandlingHashCode()\n    {\n        Cycle a = new Cycle();\n        a.value = new String(\"foo\");\n        Cycle b = new Cycle();\n        b.value = new String(\"bar\");\n        Cycle c = new Cycle();\n        c.value = new String(\"baz\");\n\n        a.next = b;\n        b.next = c;\n        c.next = a;\n\n        int ha = DeepEquals.deepHashCode(a);\n        int hb = DeepEquals.deepHashCode(b);\n        int hc = DeepEquals.deepHashCode(c);\n\n        assertTrue(ha == hb && hb == hc);\n    }\n\n    public void testCycleHandlingEquals()\n    {\n        Cycle a1 = new Cycle();\n        a1.value = new String(\"foo\");\n        Cycle b1 = new Cycle();\n        b1.value = new String(\"bar\");\n        Cycle c1 = new Cycle();\n        c1.value = new String(\"baz\");\n\n        a1.next = b1;\n        b1.next = c1;\n        c1.next = a1;\n\n        Cycle a2 = new Cycle();\n        a2.value = new String(\"foo\");\n        Cycle b2 = new Cycle();\n        b2.value = new String(\"bar\");\n        Cycle c2 = new Cycle();\n        c2.value = new String(\"baz\");\n\n        a2.next = b2;\n        b2.next = c2;\n        c2.next = a2;\n\n        assertTrue(DeepEquals.deepEquals(a1, a2));\n        assertTrue(DeepEquals.deepEquals(b1, b2));\n        assertTrue(DeepEquals.deepEquals(c1, c2));\n        assertFalse(DeepEquals.deepEquals(a1, b2));\n        assertFalse(DeepEquals.deepEquals(b1, c2));\n        assertFalse(DeepEquals.deepEquals(c1, a2));\n    }\n\n    public void testHierarchyCycleEquals()\n    {\n        FixedHierarchy h1 = new FixedHierarchy();\n        h1.value = new String(\"root\");\n        FixedHierarchy c1 = new FixedHierarchy();\n        c1.value = new String(\"child1\");\n        FixedHierarchy c2 = new FixedHierarchy();\n        c2.value = new String(\"child2\");\n\n        h1.child1 = c1;\n        h1.child2 = c2;\n        h1.child3 = c1;\n\n        FixedHierarchy h2 = new FixedHierarchy();\n        h2.value = new String(\"root\");\n        FixedHierarchy k1 = new FixedHierarchy();\n        k1.value = new String(\"child1\");\n        FixedHierarchy k2 = new FixedHierarchy();\n        k2.value = new String(\"child2\");\n\n        h2.child1 = k1;\n        h2.child2 = k2;\n        h2.child3 = k1;\n\n        assertTrue(DeepEquals.deepEquals(h1, h2));\n    }\n\n    public void testDeepEquals()\n    {\n        SmartPet smartPet1 = new SmartPet(\"Fido\", \"Terrier\");\n        SmartPet smartPet2 = new SmartPet(\"Fido\", \"Terrier\");\n\n        assertFalse(DeepEquals.deepEquals(smartPet1, smartPet2)); // Only way to\n                                                                  // get false\n                                                                  // is if it\n                                                                  // calls\n                                                                  // .equals()\n\n        ArrayClass ac1 = new ArrayClass();\n        ac1.name = new String(\"Object Array\");\n        ac1.items = new Object[] { new String(\"Hello\"), 16, 16L, null, 'c', new Boolean(true), 0.04,\n                new Object[] { \"a\", 2, 'c' }, new String[] { \"larry\", \"curly\", new String(\"mo\") } };\n        ArrayClass ac2 = new ArrayClass();\n        ac2.name = new String(\"Object Array\");\n        ac2.items = new Object[] { new String(\"Hello\"), 16, 16L, null, 'c', Boolean.TRUE, new Double(0.04),\n                new Object[] { \"a\", 2, 'c' }, new String[] { \"larry\", new String(\"curly\"), \"mo\" } };\n\n        assertTrue(DeepEquals.deepEquals(ac1, ac2));\n    }\n\n    public void testBasicEquals()\n    {\n        String one = new String(\"One\");\n        String two = new String(\"Two\");\n        String a = new String(\"One\");\n\n        assertFalse(DeepEquals.deepEquals(one, two));\n        assertTrue(DeepEquals.deepEquals(one, a));\n\n        Double x = 1.04;\n        Double y = 1.039999;\n        Double z = 1.04;\n\n        assertFalse(DeepEquals.deepEquals(x, y));\n        assertTrue(DeepEquals.deepEquals(x, z));\n    }\n\n    public void testBasicHashCode()\n    {\n        String one = new String(\"One\");\n        assertTrue(DeepEquals.deepHashCode(one) == one.hashCode());\n\n        Double pi = 3.14159;\n        assertTrue(DeepEquals.deepHashCode(pi) == pi.hashCode());\n\n        Calendar c = Calendar.getInstance();\n        assertTrue(DeepEquals.deepHashCode(c) == c.hashCode());\n\n        Date date = new Date();\n        assertTrue(DeepEquals.deepHashCode(date) == date.hashCode());\n    }\n\n    public void testCollection()\n    {\n        Pet p1 = new Pet(\"Eddie\", \"Terrier\");\n        Pet p2 = new Pet(\"Eddie\", \"Terrier\");\n        Pet p3 = new Pet(\"Penny\", \"Chihuahua\");\n        Pet p4 = new Pet(\"Penny\", \"Chihuahua\");\n\n        CollectionClass c1 = new CollectionClass();\n        c1.value = new String(\"Animals\");\n        c1.items = new ArrayList();\n        c1.items.add(p1);\n        c1.items.add(p3);\n\n        CollectionClass c2 = new CollectionClass();\n        c2.value = new String(\"Animals\");\n        c2.items = new ArrayList();\n        c2.items.add(p2);\n        c2.items.add(p4);\n\n        assertTrue(DeepEquals.deepHashCode(c1) == DeepEquals.deepHashCode(c2));\n        assertTrue(DeepEquals.deepEquals(c1, c2));\n        c1.items.add(new Pet(\"Tinker\", \"Doberman\"));\n        c2.items.add(new Pet(\"Tinker\", \"Terrier\"));\n        assertFalse(DeepEquals.deepHashCode(c1) == DeepEquals.deepHashCode(c2));\n        assertFalse(DeepEquals.deepEquals(c1, c2));\n\n        // Try HashSet() [not ordered]\n        c1.items = new HashSet();\n        c2.items = new HashSet();\n\n        c1.items.add(p1);\n        c2.items.add(p2);\n\n        c1.items.add(p3);\n        c2.items.add(p4);\n\n        assertTrue(DeepEquals.deepHashCode(c1) == DeepEquals.deepHashCode(c2));\n        assertTrue(DeepEquals.deepEquals(c1, c2));\n        c1.items.add(new Pet(\"Tinker\", \"Doberman\"));\n        c2.items.add(new Pet(\"Tinker\", \"Terrier\"));\n        assertFalse(DeepEquals.deepHashCode(c1) == DeepEquals.deepHashCode(c2));\n        assertFalse(DeepEquals.deepEquals(c1, c2));\n\n        // Try TreeSet() [ordered]\n        p1 = new ComparablePet(\"Eddie\", \"Terrier\");\n        p2 = new ComparablePet(\"Eddie\", \"Terrier\");\n        p3 = new ComparablePet(\"Penny\", \"Chihuahua\");\n        p4 = new ComparablePet(\"Penny\", \"Chihuahua\");\n\n        c1.items = new TreeSet();\n        c2.items = new TreeSet();\n\n        c1.items.add(p1);\n        c2.items.add(p2);\n\n        c1.items.add(p3);\n        c2.items.add(p4);\n\n        assertTrue(DeepEquals.deepHashCode(c1) == DeepEquals.deepHashCode(c2));\n        assertTrue(DeepEquals.deepEquals(c1, c2));\n        c1.items.add(new ComparablePet(\"Tinker\", \"Doberman\"));\n        c2.items.add(new ComparablePet(\"Tinker\", \"Terrier\"));\n        assertFalse(DeepEquals.deepHashCode(c1) == DeepEquals.deepHashCode(c2));\n        assertFalse(DeepEquals.deepEquals(c1, c2));\n    }\n\n    public void testMap()\n    {\n        Pet p1 = new Pet(\"Eddie\", \"Terrier\");\n        Pet p2 = new Pet(\"Eddie\", \"Terrier\");\n        Pet p3 = new Pet(\"Penny\", \"Chihuahua\");\n        Pet p4 = new Pet(\"Penny\", \"Chihuahua\");\n\n        MapClass m1 = new MapClass();\n        m1.value = new String(\"Hat\");\n        m1.items = new HashMap();\n\n        MapClass m2 = new MapClass();\n        m2.value = new String(\"Hat\");\n        m2.items = new HashMap();\n\n        m1.items.put(p1, new String(\"Cool dog\"));\n        m1.items.put(p3, new Long(16));\n        m2.items.put(p2, new String(\"Cool dog\"));\n        m2.items.put(p4, new Long(16));\n\n        assertTrue(DeepEquals.deepHashCode(m1) == DeepEquals.deepHashCode(m2));\n        assertTrue(DeepEquals.deepEquals(m1, m2));\n        m1.items.put(new Pet(\"Tinker\", \"Doberman\"), \"mean dog\");\n        m1.items.put(new Pet(\"Tinker\", \"Terrier\"), \"mean dog\");\n        assertFalse(DeepEquals.deepHashCode(m1) == DeepEquals.deepHashCode(m2));\n        assertFalse(DeepEquals.deepEquals(m1, m2));\n\n        m1.items = new HashMap();\n        m2.items = new HashMap();\n\n        long now = System.currentTimeMillis();\n        Date d1 = new Date(now);\n        Date d2 = new Date(now);\n        m1.items.put(p1, d1);\n        m1.items.put(p3, \"2nd\");\n        m2.items.put(p2, d2);\n        m2.items.put(p4, \"2nd\");\n\n        assertTrue(DeepEquals.deepHashCode(m1) == DeepEquals.deepHashCode(m2));\n        assertTrue(DeepEquals.deepEquals(m1, m2));\n\n        Map map1 = new HashMap();\n        Map map2 = new HashMap();\n\n        map1.put(\"Alpha\", \"One\");\n        map1.put(\"Bravo\", \"Two\");\n\n        map2.put(\"Alpha\", \"Two\");\n        map2.put(\"Bravo\", \"One\");\n\n        assertTrue(DeepEquals.deepHashCode(map1) == DeepEquals.deepHashCode(map2));\n        assertFalse(DeepEquals.deepEquals(map1, map2));\n        m1.items.put(new Pet(\"Tinker\", \"Doberman\"), \"mean dog\");\n        m1.items.put(new Pet(\"Tinker\", \"Terrier\"), \"mean dog\");\n        assertFalse(DeepEquals.deepHashCode(m1) == DeepEquals.deepHashCode(m2));\n        assertFalse(DeepEquals.deepEquals(m1, m2));\n\n        m1.items = new TreeMap();\n        m2.items = new TreeMap();\n\n        p1 = new ComparablePet(\"Eddie\", \"Terrier\");\n        p2 = new ComparablePet(\"Eddie\", \"Terrier\");\n        p3 = new ComparablePet(\"Penny\", \"Chihuahua\");\n        p4 = new ComparablePet(\"Penny\", \"Chihuahua\");\n\n        now = System.currentTimeMillis();\n        d1 = new Date(now);\n        d2 = new Date(now);\n        m1.items.put(p1, d1);\n        m1.items.put(p3, \"2nd\");\n        m2.items.put(p2, d2);\n        m2.items.put(p4, \"2nd\");\n\n        assertTrue(DeepEquals.deepHashCode(m1) == DeepEquals.deepHashCode(m2));\n        assertTrue(DeepEquals.deepEquals(m1, m2));\n        m1.items.put(new ComparablePet(\"Tinker\", \"Doberman\"), \"mean dog\");\n        m1.items.put(new ComparablePet(\"Tinker\", \"Terrier\"), \"mean dog\");\n        assertFalse(DeepEquals.deepHashCode(m1) == DeepEquals.deepHashCode(m2));\n        assertFalse(DeepEquals.deepEquals(m1, m2));\n\n        map1 = new TreeMap();\n        map2 = new TreeMap();\n\n        map1.put(\"Alpha\", \"One\");\n        map1.put(\"Bravo\", \"Two\");\n\n        map2.put(\"Alpha\", \"Two\");\n        map2.put(\"Bravo\", \"One\");\n\n        assertTrue(DeepEquals.deepHashCode(map1) == DeepEquals.deepHashCode(map2));\n        assertFalse(DeepEquals.deepEquals(map1, map2));\n    }\n\n    public void testPathelogical()\n    {\n        Pathelogical a = new Pathelogical();\n        Pathelogical b = new Pathelogical();\n\n        assertTrue(DeepEquals.deepEquals(a, b));\n    }\n\n    public void testPhotographer()\n    {\n        // Object 1\n        PhotographerUni_1_M_1_M a1 = new PhotographerUni_1_M_1_M();\n        a1.setPhotographerId(1);\n        AlbumUni_1_M_1_M b11 = new AlbumUni_1_M_1_M();\n        b11.setAlbumId(\"b1\");\n        AlbumUni_1_M_1_M b12 = new AlbumUni_1_M_1_M();\n        b12.setAlbumId(\"b2\");\n\n        PhotoUni_1_M_1_M c11 = new PhotoUni_1_M_1_M();\n        c11.setPhotoId(\"c1\");\n        PhotoUni_1_M_1_M c12 = new PhotoUni_1_M_1_M();\n        c12.setPhotoId(\"c2\");\n        PhotoUni_1_M_1_M c13 = new PhotoUni_1_M_1_M();\n        c13.setPhotoId(\"c3\");\n        PhotoUni_1_M_1_M c14 = new PhotoUni_1_M_1_M();\n        c14.setPhotoId(\"c4\");\n\n        b11.addPhoto(c11);\n        b11.addPhoto(c12);\n        b12.addPhoto(c13);\n        b12.addPhoto(c14);\n        a1.addAlbum(b11);\n        a1.addAlbum(b12);\n\n        // Object2\n        PhotographerUni_1_M_1_M a2 = new PhotographerUni_1_M_1_M();\n        a2.setPhotographerId(1);\n        AlbumUni_1_M_1_M b21 = new AlbumUni_1_M_1_M();\n        b21.setAlbumId(\"b1\");\n        AlbumUni_1_M_1_M b22 = new AlbumUni_1_M_1_M();\n        b22.setAlbumId(\"b2\");\n\n        PhotoUni_1_M_1_M c21 = new PhotoUni_1_M_1_M();\n        c21.setPhotoId(\"c1\");\n        PhotoUni_1_M_1_M c22 = new PhotoUni_1_M_1_M();\n        c22.setPhotoId(\"c2\");\n        PhotoUni_1_M_1_M c23 = new PhotoUni_1_M_1_M();\n        c23.setPhotoId(\"c3\");\n        PhotoUni_1_M_1_M c24 = new PhotoUni_1_M_1_M();\n        c24.setPhotoId(\"c4\");\n\n        b21.addPhoto(c21);\n        b21.addPhoto(c22);\n        b22.addPhoto(c23);\n        b22.addPhoto(c24);\n        a2.addAlbum(b21);\n        a2.addAlbum(b22);\n\n        // Equality test\n        assertTrue(DeepEquals.deepEquals(a1, a2));\n\n        // Inequality test\n        a2.setPhotographerId(2);\n        assertFalse(DeepEquals.deepEquals(a1, a2));\n        a2.setPhotographerId(1);\n\n        // Case 1: All same\n        assertTrue(DeepEquals.deepEquals(a1, a2));\n        assertTrue(DeepEquals.deepEquals(b12, b22));\n        assertTrue(DeepEquals.deepEquals(c14, c24));\n\n        // Case 2: Change Photo object\n        String originalPhotoCaption = c24.getPhotoCaption();\n        c24.setPhotoCaption(\"AAAAAAAAAAAAA\");\n\n        assertTrue(DeepEquals.deepEquals(a1, a2));\n        assertTrue(DeepEquals.deepEquals(b12, b22));\n        assertFalse(DeepEquals.deepEquals(c14, c24));\n\n        c24.setPhotoCaption(originalPhotoCaption);\n\n        // Case 3: Change Album object\n        String originalAlbumDiscription = b22.getAlbumDescription();\n        b22.setAlbumDescription(\"Second Album of Second Photographer\");\n\n        assertTrue(DeepEquals.deepEquals(a1, a2));\n        assertFalse(DeepEquals.deepEquals(b12, b22));\n        assertTrue(DeepEquals.deepEquals(c14, c24));\n\n        b22.setAlbumDescription(originalAlbumDiscription);\n\n        // Case 4: Change album and photo object\n        c24.setPhotoCaption(\"AAAAAAAAAAAAA\");\n        b22.setAlbumDescription(\"Second Album of Second Photographer\");\n\n        assertTrue(DeepEquals.deepEquals(a1, a2));\n        assertFalse(DeepEquals.deepEquals(b12, b22));\n        assertFalse(DeepEquals.deepEquals(c14, c24));\n\n        b22.setAlbumDescription(originalAlbumDiscription);\n        c24.setPhotoCaption(originalPhotoCaption);\n\n        // Case 5: Change Photographer object\n        String originalPhotographerName = a2.getPhotographerName();\n        a2.setPhotographerName(\"Kuldeep\");\n\n        assertFalse(DeepEquals.deepEquals(a1, a2));\n        assertTrue(DeepEquals.deepEquals(b12, b22));\n        assertTrue(DeepEquals.deepEquals(c14, c24));\n\n        a2.setPhotographerName(originalPhotographerName);\n\n        // Case 6: Change Photographer and photo object\n        c24.setPhotoCaption(\"AAAAAAAAAAAAA\");\n        a2.setPhotographerName(\"Kuldeep\");\n\n        assertFalse(DeepEquals.deepEquals(a1, a2));\n        assertTrue(DeepEquals.deepEquals(b12, b22));\n        assertFalse(DeepEquals.deepEquals(c14, c24));\n\n        a2.setPhotographerName(originalPhotographerName);\n        c24.setPhotoCaption(originalPhotoCaption);\n\n        // Case 7: Change Photographer and album object\n        b22.setAlbumDescription(\"Second Album of Second Photographer\");\n        a2.setPhotographerName(\"Kuldeep\");\n\n        assertFalse(DeepEquals.deepEquals(a1, a2));\n        assertFalse(DeepEquals.deepEquals(b12, b22));\n        assertTrue(DeepEquals.deepEquals(c14, c24));\n\n        a2.setPhotographerName(originalPhotographerName);\n        b22.setAlbumDescription(originalAlbumDiscription);\n\n        // Case 8: Change Photographer, album and photo object\n        c24.setPhotoCaption(\"AAAAAAAAAAAAA\");\n        b22.setAlbumDescription(\"Second Album of Second Photographer\");\n        a2.setPhotographerName(\"Kuldeep\");\n\n        assertFalse(DeepEquals.deepEquals(a1, a2));\n        assertFalse(DeepEquals.deepEquals(b12, b22));\n        assertFalse(DeepEquals.deepEquals(c14, c24));\n\n        a2.setPhotographerName(originalPhotographerName);\n        b22.setAlbumDescription(originalAlbumDiscription);\n        c24.setPhotoCaption(originalPhotoCaption);\n    }\n}"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/utils/KunderaCoreUtilsTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.impetus.kundera.utils;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\n\n/**\n * @author vivek.mishra junit for {@link KunderaCoreUtils}\n * \n */\npublic class KunderaCoreUtilsTest\n{\n\n    @Test\n    public void getExternalProperties()\n    {\n        Map<String, Object> propertiesMap = new HashMap<String, Object>();\n\n        // Assert with empty map\n        String[] persistenceUnits = new String[] { \"metaDataTest\", \"patest\" };\n\n        Assert.assertNull(KunderaCoreUtils.getExternalProperties(\"patest\", propertiesMap, persistenceUnits));\n        Assert.assertTrue(KunderaCoreUtils.getExternalProperties(\"patest\", propertiesMap, null).isEmpty());\n\n        Map<String, Object> puProperties = new HashMap<String, Object>();\n        puProperties.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n\n        propertiesMap.put(\"patest\", puProperties);\n\n        Map<String, Object> persistenceUnitProps = KunderaCoreUtils.getExternalProperties(\"patest\", propertiesMap,\n                persistenceUnits);\n        Assert.assertNotNull(persistenceUnitProps);\n        Assert.assertEquals(puProperties, persistenceUnitProps);\n\n        propertiesMap.put(\"patest\", null);\n        Assert.assertNull(KunderaCoreUtils.getExternalProperties(\"patest\", propertiesMap, persistenceUnits));\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/utils/KunderaThreadFactoryTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.impetus.kundera.utils;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * @author vivek.mishra\n * junit for {@link KunderaThreadFactory}\n *\n */\npublic class KunderaThreadFactoryTest\n{\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(KunderaThreadFactoryTest.class);\n    @Test\n    public void testGetNext()\n    {\n        KunderaThreadFactory threadFactory = new KunderaThreadFactory(\"thread1\");\n        Thread t = threadFactory.newThread(new Runnable()\n        {\n            \n            @Override\n            public void run()\n            {\n                log.info(\"running\");\n            }\n        });\n        \n        Assert.assertNotNull(t);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/utils/LuceneCleanupUtilities.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.utils;\n\nimport java.io.File;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * Provides utility methods for all Kundera Examples test cases\n * \n * @author amresh.singh\n */\npublic class LuceneCleanupUtilities\n{\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(LuceneCleanupUtilities.class);\n\n    public static void cleanLuceneDirectory(PersistenceUnitMetadata puMetadata)\n    {\n        if (puMetadata != null)\n        {\n            String luceneDir = puMetadata.getProperty(PersistenceProperties.KUNDERA_INDEX_HOME_DIR);\n            cleanDir(luceneDir);\n        }\n    }\n\n    public static void cleanDir(final String luceneDir)\n    {\n            if (luceneDir != null && luceneDir.length() > 0)\n            {\n                File directory = new File(luceneDir);\n                // Get all files in directory\n                File[] files = directory.listFiles();\n                if (files != null)\n                {\n                    for (File file : files)\n                    {\n                    \tif(file.isDirectory() && !(file.list().length==0)){\n                    \t\n                    \t\t\tcleanDir(file.getPath());\n                    \t\t\tfile.delete();\n                    \t}else{\n                    \t\tfile.delete();\n                    \t}\n                        \n                    }\n                }\n            }\n        }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/utils/ObjectUtilsCloneBidirectionalM2MTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.utils;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.entity.PersonalDetail;\nimport com.impetus.kundera.entity.Tweet;\nimport com.impetus.kundera.entity.album.AlbumBi_1_M_1_M;\nimport com.impetus.kundera.entity.album.AlbumBi_1_M_M_M;\nimport com.impetus.kundera.entity.photo.PhotoBi_1_M_1_M;\nimport com.impetus.kundera.entity.photo.PhotoBi_1_M_M_M;\nimport com.impetus.kundera.entity.photographer.PhotographerBi_1_M_1_M;\nimport com.impetus.kundera.entity.photographer.PhotographerBi_1_M_M_M;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * Test case for {@link ObjectUtils} for cloning for bidirectional object\n * \n * @author amresh.singh\n */\npublic class ObjectUtilsCloneBidirectionalM2MTest\n{\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(ObjectUtilsCloneBidirectionalM2MTest.class);\n\n    private String _persistenceUnit = \"kunderatest\";\n\n    private EntityManagerFactoryImpl emf;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = getEntityManagerFactory();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    @Test\n    public void testPhotographer()\n    {\n        // Construct photographer object\n        PhotographerBi_1_M_M_M a1 = new PhotographerBi_1_M_M_M();\n        a1.setPhotographerId(1);\n        a1.setPhotographerName(\"Amresh\");\n\n        AlbumBi_1_M_M_M album1 = new AlbumBi_1_M_M_M(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n        AlbumBi_1_M_M_M album2 = new AlbumBi_1_M_M_M(\"album_2\", \"Office Pics\", \"Annual office party photos\");\n\n        PhotoBi_1_M_M_M photo1 = new PhotoBi_1_M_M_M(\"photo_1\", \"One beach\", \"On beach with friends\");\n        PhotoBi_1_M_M_M photo2 = new PhotoBi_1_M_M_M(\"photo_2\", \"In Hotel\", \"Chilling out in room\");\n        PhotoBi_1_M_M_M photo3 = new PhotoBi_1_M_M_M(\"photo_3\", \"At Airport\", \"So tired\");\n        PhotoBi_1_M_M_M photo4 = new PhotoBi_1_M_M_M(\"photo_4\", \"Office Team event\", \"Shot at Fun park\");\n        PhotoBi_1_M_M_M photo5 = new PhotoBi_1_M_M_M(\"photo_5\", \"My Team\", \"My team is the best\");\n\n        album1.addPhoto(photo1);\n        album1.addPhoto(photo2);\n        album1.addPhoto(photo3);\n        album1.addPhoto(photo4);\n\n        album2.addPhoto(photo2);\n        album2.addPhoto(photo3);\n        album2.addPhoto(photo4);\n        album2.addPhoto(photo5);\n\n        photo1.addAlbum(album1);\n        photo2.addAlbum(album1);\n        photo2.addAlbum(album2);\n        photo3.addAlbum(album1);\n        photo3.addAlbum(album2);\n        photo4.addAlbum(album1);\n        photo4.addAlbum(album2);\n        photo5.addAlbum(album2);\n\n        album1.setPhotographer(a1);\n        album2.setPhotographer(a1);\n\n        a1.addAlbum(album1);\n        a1.addAlbum(album2);\n\n        // Create a deep copy using Kundera\n        long t3 = System.currentTimeMillis();\n        // metadata =\n        // KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n        // PhotographerBi_1_M_1_M.class);\n        PhotographerBi_1_M_M_M a2 = (PhotographerBi_1_M_M_M) ObjectUtils.deepCopy(a1, emf.getKunderaMetadataInstance());\n        long t4 = System.currentTimeMillis();\n        log.info(\"Time taken by Kundera to copy 1 entity:\" + (t4 - t3));\n\n        // Check for reference inequality\n\n        assertObjectReferenceInequality(a1, a2);\n\n        // Check for deep clone object equality\n        Assert.assertTrue(DeepEquals.deepEquals(a1, a2));\n\n        // Change original object\n\n        // modifyPhotographer(a1);\n\n        // Check whether clones are unaffected from change in original object\n        // assertOriginalObjectValues(a2);\n\n    }\n\n    private void modifyPhotographer(PhotographerBi_1_M_1_M p)\n    {\n        p.setPhotographerId(2);\n        p.setPhotographerName(\"Vivek\");\n\n        p.getPersonalDetail().setName(\"mevivs\");\n        p.getPersonalDetail().setPersonalDetailId(\"11111111111111\");\n        p.getPersonalDetail().setPassword(\"password2\");\n        p.getPersonalDetail().setRelationshipStatus(\"unknown\");\n\n        Tweet tweet1 = new Tweet(\"My First Tweet2\", \"Web2\");\n        tweet1.setTweetId(\"t1\");\n        Tweet tweet2 = new Tweet(\"My Second Tweet2\", \"iPad2\");\n        tweet2.setTweetId(\"t2\");\n        Tweet tweet3 = new Tweet(\"My Third Tweet2\", \"Text2\");\n        tweet3.setTweetId(\"t3\");\n\n        List<Tweet> tweets = new ArrayList<Tweet>();\n        tweets.add(tweet1);\n        tweets.add(tweet2);\n        tweets.add(tweet3);\n        p.setTweets(tweets);\n\n        AlbumBi_1_M_1_M b11 = new AlbumBi_1_M_1_M(\"Xb1\", \"XAlbum 1\", \"XThis is album 1\");\n        AlbumBi_1_M_1_M b12 = new AlbumBi_1_M_1_M(\"Xb2\", \"XAlbum 2\", \"XThis is album 2\");\n\n        PhotoBi_1_M_1_M c11 = new PhotoBi_1_M_1_M(\"Xc1\", \"XPhoto 1\", \"XThis is Photo 1\");\n        PhotoBi_1_M_1_M c12 = new PhotoBi_1_M_1_M(\"Xc2\", \"Photo 2\", \"XThis is Photo 2\");\n        PhotoBi_1_M_1_M c13 = new PhotoBi_1_M_1_M(\"Xc3\", \"XPhoto 3\", \"XThis is Photo 3\");\n        PhotoBi_1_M_1_M c14 = new PhotoBi_1_M_1_M(\"Xc4\", \"XPhoto 4\", \"XThis is Photo 4\");\n\n        b11.addPhoto(c11);\n        b11.addPhoto(c12);\n        b12.addPhoto(c13);\n        b12.addPhoto(c14);\n\n        b11.setPhotographer(p);\n        b12.setPhotographer(p);\n        c11.setAlbum(b11);\n        c12.setAlbum(b11);\n        c13.setAlbum(b12);\n        c14.setAlbum(b12);\n\n        List<AlbumBi_1_M_1_M> albums = new ArrayList<AlbumBi_1_M_1_M>();\n        albums.add(b11);\n        albums.add(b12);\n        p.setAlbums(albums);\n    }\n\n    private void assertOriginalObjectValues(PhotographerBi_1_M_1_M p)\n    {\n        Assert.assertTrue(p.getPhotographerId() == 1);\n        Assert.assertTrue(p.getPhotographerName().equals(\"Amresh\"));\n\n        PersonalDetail pd = p.getPersonalDetail();\n        Assert.assertFalse(pd.getPersonalDetailId().equals(\"11111111111111\"));\n        Assert.assertTrue(pd.getName().equals(\"xamry\"));\n        Assert.assertTrue(pd.getPassword().equals(\"password1\"));\n        Assert.assertTrue(pd.getRelationshipStatus().equals(\"Single\"));\n\n        List<Tweet> tweets = p.getTweets();\n        Tweet t1 = tweets.get(0);\n        Tweet t2 = tweets.get(1);\n        Tweet t3 = tweets.get(2);\n\n        Assert.assertFalse(t1.getTweetId().equals(\"t1\"));\n        Assert.assertTrue(t1.getBody().equals(\"My First Tweet\"));\n        Assert.assertTrue(t1.getDevice().equals(\"Web\"));\n\n        Assert.assertFalse(t2.getTweetId().equals(\"t2\"));\n        Assert.assertTrue(t2.getBody().equals(\"My Second Tweet\"));\n        Assert.assertTrue(t2.getDevice().equals(\"Android\"));\n\n        Assert.assertFalse(t3.getTweetId().equals(\"t3\"));\n        Assert.assertTrue(t3.getBody().equals(\"My Third Tweet\"));\n        Assert.assertTrue(t3.getDevice().equals(\"iPad\"));\n\n        for (AlbumBi_1_M_1_M album : p.getAlbums())\n        {\n            Assert.assertFalse(album.getAlbumId().startsWith(\"X\"));\n            Assert.assertFalse(album.getAlbumName().startsWith(\"X\"));\n            Assert.assertFalse(album.getAlbumDescription().startsWith(\"X\"));\n\n            for (PhotoBi_1_M_1_M photo : album.getPhotos())\n            {\n                Assert.assertFalse(photo.getPhotoId().startsWith(\"X\"));\n                Assert.assertFalse(photo.getPhotoCaption().startsWith(\"X\"));\n                Assert.assertFalse(photo.getPhotoDescription().startsWith(\"X\"));\n            }\n\n        }\n\n    }\n\n    private void assertObjectReferenceInequality(PhotographerBi_1_M_M_M p1, PhotographerBi_1_M_M_M p2)\n    {\n\n        Assert.assertFalse(p1 == p2);\n        // Assert.assertFalse(p1.getPersonalDetail() == p2.getPersonalDetail());\n        // Assert.assertFalse(p1.getTweets() == p2.getTweets());\n\n        /*\n         * for (int i = 0; i < p1.getTweets().size(); i++) {\n         * Assert.assertFalse(p1.getTweets().get(i) == p2.getTweets().get(i)); }\n         */\n\n        Assert.assertFalse(p1.getAlbums() == p2.getAlbums());\n        for (int i = 0; i < p1.getAlbums().size(); i++)\n        {\n            Assert.assertFalse(p1.getAlbums().get(i) == p2.getAlbums().get(i));\n            Assert.assertFalse(p1.getAlbums().get(i).getPhotos() == p2.getAlbums().get(i).getPhotos());\n            Assert.assertFalse(p1.getAlbums().get(i).getPhotographer() == p2.getAlbums().get(i).getPhotographer());\n\n            for (int j = 0; j < p1.getAlbums().get(i).getPhotos().size(); j++)\n            {\n                PhotoBi_1_M_M_M photo1 = p1.getAlbums().get(i).getPhotos().get(j);\n                PhotoBi_1_M_M_M photo2 = p2.getAlbums().get(i).getPhotos().get(j);\n\n                Assert.assertFalse(photo1 == photo2);\n                Assert.assertFalse(photo1.getAlbums() == photo2.getAlbums());\n            }\n        }\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory()\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(_persistenceUnit);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/utils/ObjectUtilsCloneBidirectionalTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.utils;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.entity.PersonalDetail;\nimport com.impetus.kundera.entity.Tweet;\nimport com.impetus.kundera.entity.album.AlbumBi_1_M_1_M;\nimport com.impetus.kundera.entity.photo.PhotoBi_1_M_1_M;\nimport com.impetus.kundera.entity.photographer.PhotographerBi_1_M_1_M;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * Test case for {@link ObjectUtils} for cloning for bidirectional object\n * \n * @author amresh.singh\n */\npublic class ObjectUtilsCloneBidirectionalTest\n{\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(ObjectUtilsCloneBidirectionalTest.class);\n\n    private String _persistenceUnit = \"kunderatest\";\n\n    private EntityManagerFactoryImpl emf;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = getEntityManagerFactory();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    @Test\n    public void testPhotographer()\n    {\n        // Construct photographer object\n        PhotographerBi_1_M_1_M a1 = new PhotographerBi_1_M_1_M();\n        a1.setPhotographerId(1);\n        a1.setPhotographerName(\"Amresh\");\n\n        a1.setPersonalDetail(new PersonalDetail(\"xamry\", \"password1\", \"Single\"));\n\n        a1.addTweet(new Tweet(\"My First Tweet\", \"Web\"));\n        a1.addTweet(new Tweet(\"My Second Tweet\", \"Android\"));\n        a1.addTweet(new Tweet(\"My Third Tweet\", \"iPad\"));\n\n        AlbumBi_1_M_1_M b11 = new AlbumBi_1_M_1_M(\"b1\", \"Album 1\", \"This is album 1\");\n        AlbumBi_1_M_1_M b12 = new AlbumBi_1_M_1_M(\"b2\", \"Album 2\", \"This is album 2\");\n\n        PhotoBi_1_M_1_M c11 = new PhotoBi_1_M_1_M(\"c1\", \"Photo 1\", \"This is Photo 1\");\n        PhotoBi_1_M_1_M c12 = new PhotoBi_1_M_1_M(\"c2\", \"Photo 2\", \"This is Photo 2\");\n        PhotoBi_1_M_1_M c13 = new PhotoBi_1_M_1_M(\"c3\", \"Photo 3\", \"This is Photo 3\");\n        PhotoBi_1_M_1_M c14 = new PhotoBi_1_M_1_M(\"c4\", \"Photo 4\", \"This is Photo 4\");\n\n        b11.addPhoto(c11);\n        b11.addPhoto(c12);\n        b12.addPhoto(c13);\n        b12.addPhoto(c14);\n        a1.addAlbum(b11);\n        a1.addAlbum(b12);\n\n        b11.setPhotographer(a1);\n        b12.setPhotographer(a1);\n        c11.setAlbum(b11);\n        c12.setAlbum(b11);\n        c13.setAlbum(b12);\n        c14.setAlbum(b12);\n\n        // Create a deep copy using Kundera\n        long t1 = System.currentTimeMillis();\n        PhotographerBi_1_M_1_M a2 = (PhotographerBi_1_M_1_M) ObjectUtils.deepCopy(a1, emf.getKunderaMetadataInstance());\n        long t2 = System.currentTimeMillis();\n        log.info(\"Time taken by Kundera:\" + (t2 - t1));\n\n        // Check for reference inequality\n        assertObjectReferenceInequality(a1, a2);\n\n        // Check for deep clone object equality\n        Assert.assertTrue(DeepEquals.deepEquals(a1, a2));\n\n        // Change original object\n        modifyPhotographer(a1);\n\n        // Check whether clones are unaffected from change in original object\n        assertOriginalObjectValues(a2);\n    }\n\n    private void modifyPhotographer(PhotographerBi_1_M_1_M p)\n    {\n        p.setPhotographerId(2);\n        p.setPhotographerName(\"Vivek\");\n\n        p.getPersonalDetail().setName(\"mevivs\");\n        p.getPersonalDetail().setPersonalDetailId(\"11111111111111\");\n        p.getPersonalDetail().setPassword(\"password2\");\n        p.getPersonalDetail().setRelationshipStatus(\"unknown\");\n\n        Tweet tweet1 = new Tweet(\"My First Tweet2\", \"Web2\");\n        tweet1.setTweetId(\"t1\");\n        Tweet tweet2 = new Tweet(\"My Second Tweet2\", \"iPad2\");\n        tweet2.setTweetId(\"t2\");\n        Tweet tweet3 = new Tweet(\"My Third Tweet2\", \"Text2\");\n        tweet3.setTweetId(\"t3\");\n\n        List<Tweet> tweets = new ArrayList<Tweet>();\n        tweets.add(tweet1);\n        tweets.add(tweet2);\n        tweets.add(tweet3);\n        p.setTweets(tweets);\n\n        AlbumBi_1_M_1_M b11 = new AlbumBi_1_M_1_M(\"Xb1\", \"XAlbum 1\", \"XThis is album 1\");\n        AlbumBi_1_M_1_M b12 = new AlbumBi_1_M_1_M(\"Xb2\", \"XAlbum 2\", \"XThis is album 2\");\n\n        PhotoBi_1_M_1_M c11 = new PhotoBi_1_M_1_M(\"Xc1\", \"XPhoto 1\", \"XThis is Photo 1\");\n        PhotoBi_1_M_1_M c12 = new PhotoBi_1_M_1_M(\"Xc2\", \"Photo 2\", \"XThis is Photo 2\");\n        PhotoBi_1_M_1_M c13 = new PhotoBi_1_M_1_M(\"Xc3\", \"XPhoto 3\", \"XThis is Photo 3\");\n        PhotoBi_1_M_1_M c14 = new PhotoBi_1_M_1_M(\"Xc4\", \"XPhoto 4\", \"XThis is Photo 4\");\n\n        b11.addPhoto(c11);\n        b11.addPhoto(c12);\n        b12.addPhoto(c13);\n        b12.addPhoto(c14);\n\n        b11.setPhotographer(p);\n        b12.setPhotographer(p);\n        c11.setAlbum(b11);\n        c12.setAlbum(b11);\n        c13.setAlbum(b12);\n        c14.setAlbum(b12);\n\n        List<AlbumBi_1_M_1_M> albums = new ArrayList<AlbumBi_1_M_1_M>();\n        albums.add(b11);\n        albums.add(b12);\n        p.setAlbums(albums);\n    }\n\n    private void assertOriginalObjectValues(PhotographerBi_1_M_1_M p)\n    {\n        Assert.assertTrue(p.getPhotographerId() == 1);\n        Assert.assertTrue(p.getPhotographerName().equals(\"Amresh\"));\n\n        PersonalDetail pd = p.getPersonalDetail();\n        Assert.assertFalse(pd.getPersonalDetailId().equals(\"11111111111111\"));\n        Assert.assertTrue(pd.getName().equals(\"xamry\"));\n        Assert.assertTrue(pd.getPassword().equals(\"password1\"));\n        Assert.assertTrue(pd.getRelationshipStatus().equals(\"Single\"));\n\n        List<Tweet> tweets = p.getTweets();\n        Tweet t1 = tweets.get(0);\n        Tweet t2 = tweets.get(1);\n        Tweet t3 = tweets.get(2);\n\n        Assert.assertFalse(t1.getTweetId().equals(\"t1\"));\n        Assert.assertTrue(t1.getBody().equals(\"My First Tweet\"));\n        Assert.assertTrue(t1.getDevice().equals(\"Web\"));\n\n        Assert.assertFalse(t2.getTweetId().equals(\"t2\"));\n        Assert.assertTrue(t2.getBody().equals(\"My Second Tweet\"));\n        Assert.assertTrue(t2.getDevice().equals(\"Android\"));\n\n        Assert.assertFalse(t3.getTweetId().equals(\"t3\"));\n        Assert.assertTrue(t3.getBody().equals(\"My Third Tweet\"));\n        Assert.assertTrue(t3.getDevice().equals(\"iPad\"));\n\n        for (AlbumBi_1_M_1_M album : p.getAlbums())\n        {\n            Assert.assertFalse(album.getAlbumId().startsWith(\"X\"));\n            Assert.assertFalse(album.getAlbumName().startsWith(\"X\"));\n            Assert.assertFalse(album.getAlbumDescription().startsWith(\"X\"));\n\n            for (PhotoBi_1_M_1_M photo : album.getPhotos())\n            {\n                Assert.assertFalse(photo.getPhotoId().startsWith(\"X\"));\n                Assert.assertFalse(photo.getPhotoCaption().startsWith(\"X\"));\n                Assert.assertFalse(photo.getPhotoDescription().startsWith(\"X\"));\n            }\n\n        }\n\n    }\n\n    private void assertObjectReferenceInequality(PhotographerBi_1_M_1_M p1, PhotographerBi_1_M_1_M p2)\n    {\n\n        Assert.assertFalse(p1 == p2);\n        Assert.assertFalse(p1.getPhotographerName() == p2.getPhotographerName());\n        Assert.assertFalse(p1.getPersonalDetail() == p2.getPersonalDetail());\n        Assert.assertFalse(p1.getPersonalDetail().getPersonalDetailId() == p2.getPersonalDetail().getPersonalDetailId());\n        Assert.assertFalse(p1.getPersonalDetail().getName() == p2.getPersonalDetail().getName());\n        Assert.assertFalse(p1.getPersonalDetail().getPassword() == p2.getPersonalDetail().getPassword());\n        Assert.assertFalse(p1.getPersonalDetail().getRelationshipStatus() == p2.getPersonalDetail()\n                .getRelationshipStatus());\n        Assert.assertFalse(p1.getTweets() == p2.getTweets());\n\n        for (int i = 0; i < p1.getTweets().size(); i++)\n        {\n            Tweet p1Tweet = p1.getTweets().get(i);\n            Tweet p2Tweet = p2.getTweets().get(i);\n            Assert.assertFalse(p1Tweet == p2Tweet);\n            Assert.assertFalse(p1Tweet.getTweetId() == p2Tweet.getTweetId());\n            Assert.assertFalse(p1Tweet.getBody() == p2Tweet.getBody());\n            Assert.assertFalse(p1Tweet.getDevice() == p2Tweet.getDevice());\n        }\n\n        Assert.assertFalse(p1.getAlbums() == p2.getAlbums());\n        for (int i = 0; i < p1.getAlbums().size(); i++)\n        {\n            AlbumBi_1_M_1_M p1Album = p1.getAlbums().get(i);\n            AlbumBi_1_M_1_M p2Album = p2.getAlbums().get(i);\n            Assert.assertFalse(p1Album == p2Album);\n            Assert.assertFalse(p1Album.getAlbumId() == p2Album.getAlbumId());\n            Assert.assertFalse(p1Album.getAlbumName() == p2Album.getAlbumName());\n            Assert.assertFalse(p1Album.getAlbumDescription() == p2Album.getAlbumDescription());\n\n            Assert.assertFalse(p1.getAlbums().get(i).getPhotos() == p2.getAlbums().get(i).getPhotos());\n            Assert.assertFalse(p1.getAlbums().get(i).getPhotographer() == p2.getAlbums().get(i).getPhotographer());\n\n            for (int j = 0; j < p1.getAlbums().get(i).getPhotos().size(); j++)\n            {\n                PhotoBi_1_M_1_M photo1 = p1.getAlbums().get(i).getPhotos().get(j);\n                PhotoBi_1_M_1_M photo2 = p2.getAlbums().get(i).getPhotos().get(j);\n\n                Assert.assertFalse(photo1 == photo2);\n                Assert.assertFalse(photo1.getPhotoId() == photo2.getPhotoId());\n                Assert.assertFalse(photo1.getPhotoCaption() == photo2.getPhotoCaption());\n                Assert.assertFalse(photo1.getPhotoDescription() == photo2.getPhotoDescription());\n                Assert.assertFalse(photo1.getAlbum() == photo2.getAlbum());\n            }\n        }\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory()\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(_persistenceUnit);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/utils/ObjectUtilsCloneUnidirectionalTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.utils;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.entity.PersonalDetail;\nimport com.impetus.kundera.entity.Tweet;\nimport com.impetus.kundera.entity.album.AlbumUni_1_M_1_M;\nimport com.impetus.kundera.entity.photo.PhotoUni_1_M_1_M;\nimport com.impetus.kundera.entity.photographer.PhotographerUni_1_M_1_M;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * Test case for {@link ObjectUtils} for cloning for unidirectional object\n * \n * @author amresh.singh\n */\npublic class ObjectUtilsCloneUnidirectionalTest\n{\n    private final String _persistenceUnit = \"kunderatest\";\n\n    private String _keyspace = \"KunderaTest\";\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(ObjectUtils.class);\n\n    private EntityManagerFactoryImpl emf;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = getEntityManagerFactory(null);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    @Test\n    public void testPhotographer()\n    {\n        // Construct photographer object\n        PhotographerUni_1_M_1_M a1 = constructPhotographer(1);\n\n        // Create a deep copy using Kundera\n        long t1 = System.currentTimeMillis();\n        PhotographerUni_1_M_1_M a2 = (PhotographerUni_1_M_1_M) ObjectUtils.deepCopy(a1,\n                emf.getKunderaMetadataInstance());\n        long t2 = System.currentTimeMillis();\n        log.info(\"Time taken by Kundera:\" + (t2 - t1));\n\n        // Check for reference inequality\n        assertObjectReferenceInequality(a1, a2);\n\n        // Check for deep clone object equality\n        Assert.assertTrue(DeepEquals.deepEquals(a1, a2));\n\n        // Change original object\n        modifyPhotographer(a1);\n\n        // Check whether clones are unaffected from change in original object\n        assertOriginalObjectValues(a2);\n    }\n\n    // @Test\n    public void testBulkCopyUsingKunderaCloner()\n    {\n        int n = 100000;\n        long t1 = System.currentTimeMillis();\n        for (int i = 0; i < n; i++)\n        {\n            PhotographerUni_1_M_1_M a1 = constructPhotographer(i + 1);\n            PhotographerUni_1_M_1_M a2 = (PhotographerUni_1_M_1_M) ObjectUtils.deepCopy(a1, emf.getKunderaMetadataInstance());\n        }\n        long t2 = System.currentTimeMillis();\n        log.info(\"Time taken by Kundera Cloner for \" + n + \" records:\" + (t2 - t1));\n    }\n\n    /**\n     * @return\n     */\n    private PhotographerUni_1_M_1_M constructPhotographer(int photographerId)\n    {\n        PhotographerUni_1_M_1_M a1 = new PhotographerUni_1_M_1_M();\n        a1.setPhotographerId(photographerId);\n        a1.setPhotographerName(\"Amresh\");\n\n        a1.setPersonalDetail(new PersonalDetail(\"xamry\", \"password1\", \"Single\"));\n\n        a1.addTweet(new Tweet(\"My First Tweet\", \"Web\"));\n        a1.addTweet(new Tweet(\"My Second Tweet\", \"Android\"));\n        a1.addTweet(new Tweet(\"My Third Tweet\", \"iPad\"));\n\n        a1.addTag(\"nosql\");\n        a1.addTag(\"kundera\");\n        a1.addTag(\"mongo\");\n\n        a1.addLikedBy(111);\n        a1.addLikedBy(222);\n\n        a1.addComment(111, \"What a post!\");\n        a1.addComment(222, \"I am getting NPE on line no. 145\");\n        a1.addComment(333, \"My hobby is to spam blogs\");\n\n        AlbumUni_1_M_1_M b11 = new AlbumUni_1_M_1_M(\"b1\", \"Album 1\", \"This is album 1\");\n        AlbumUni_1_M_1_M b12 = new AlbumUni_1_M_1_M(\"b2\", \"Album 2\", \"This is album 2\");\n\n        PhotoUni_1_M_1_M c11 = new PhotoUni_1_M_1_M(\"c1\", \"Photo 1\", \"This is Photo 1\");\n        PhotoUni_1_M_1_M c12 = new PhotoUni_1_M_1_M(\"c2\", \"Photo 2\", \"This is Photo 2\");\n        PhotoUni_1_M_1_M c13 = new PhotoUni_1_M_1_M(\"c3\", \"Photo 3\", \"This is Photo 3\");\n        PhotoUni_1_M_1_M c14 = new PhotoUni_1_M_1_M(\"c4\", \"Photo 4\", \"This is Photo 4\");\n\n        b11.addPhoto(c11);\n        b11.addPhoto(c12);\n        b12.addPhoto(c13);\n        b12.addPhoto(c14);\n        a1.addAlbum(b11);\n        a1.addAlbum(b12);\n        return a1;\n    }\n\n    private void modifyPhotographer(PhotographerUni_1_M_1_M p)\n    {\n        p.setPhotographerId(2);\n        p.setPhotographerName(\"Vivek\");\n\n        p.getPersonalDetail().setName(\"mevivs\");\n        p.getPersonalDetail().setPersonalDetailId(\"11111111111111\");\n        p.getPersonalDetail().setPassword(\"password2\");\n        p.getPersonalDetail().setRelationshipStatus(\"unknown\");\n\n        Tweet tweet1 = new Tweet(\"My First Tweet2\", \"Web2\");\n        tweet1.setTweetId(\"t1\");\n        Tweet tweet2 = new Tweet(\"My Second Tweet2\", \"iPad2\");\n        tweet2.setTweetId(\"t2\");\n        Tweet tweet3 = new Tweet(\"My Third Tweet2\", \"Text2\");\n        tweet3.setTweetId(\"t3\");\n\n        List<Tweet> tweets = new ArrayList<Tweet>();\n        tweets.add(tweet1);\n        tweets.add(tweet2);\n        tweets.add(tweet3);\n        p.setTweets(tweets);\n\n        AlbumUni_1_M_1_M b11 = new AlbumUni_1_M_1_M(\"Xb1\", \"XAlbum 1\", \"XThis is album 1\");\n        AlbumUni_1_M_1_M b12 = new AlbumUni_1_M_1_M(\"Xb2\", \"XAlbum 2\", \"XThis is album 2\");\n\n        PhotoUni_1_M_1_M c11 = new PhotoUni_1_M_1_M(\"Xc1\", \"XPhoto 1\", \"XThis is Photo 1\");\n        PhotoUni_1_M_1_M c12 = new PhotoUni_1_M_1_M(\"Xc2\", \"Photo 2\", \"XThis is Photo 2\");\n        PhotoUni_1_M_1_M c13 = new PhotoUni_1_M_1_M(\"Xc3\", \"XPhoto 3\", \"XThis is Photo 3\");\n        PhotoUni_1_M_1_M c14 = new PhotoUni_1_M_1_M(\"Xc4\", \"XPhoto 4\", \"XThis is Photo 4\");\n\n        b11.addPhoto(c11);\n        b11.addPhoto(c12);\n        b12.addPhoto(c13);\n        b12.addPhoto(c14);\n\n        List<AlbumUni_1_M_1_M> albums = new ArrayList<AlbumUni_1_M_1_M>();\n        albums.add(b11);\n        albums.add(b12);\n        p.setAlbums(albums);\n    }\n\n    private void assertOriginalObjectValues(PhotographerUni_1_M_1_M p)\n    {\n        Assert.assertTrue(p.getPhotographerId() == 1);\n        Assert.assertTrue(p.getPhotographerName().equals(\"Amresh\"));\n\n        PersonalDetail pd = p.getPersonalDetail();\n        Assert.assertFalse(pd.getPersonalDetailId().equals(\"11111111111111\"));\n        Assert.assertTrue(pd.getName().equals(\"xamry\"));\n        Assert.assertTrue(pd.getPassword().equals(\"password1\"));\n        Assert.assertTrue(pd.getRelationshipStatus().equals(\"Single\"));\n\n        List<Tweet> tweets = p.getTweets();\n        Tweet t1 = tweets.get(0);\n        Tweet t2 = tweets.get(1);\n        Tweet t3 = tweets.get(2);\n\n        Assert.assertFalse(t1.getTweetId().equals(\"t1\"));\n        Assert.assertTrue(t1.getBody().equals(\"My First Tweet\"));\n        Assert.assertTrue(t1.getDevice().equals(\"Web\"));\n\n        Assert.assertFalse(t2.getTweetId().equals(\"t2\"));\n        Assert.assertTrue(t2.getBody().equals(\"My Second Tweet\"));\n        Assert.assertTrue(t2.getDevice().equals(\"Android\"));\n\n        Assert.assertFalse(t3.getTweetId().equals(\"t3\"));\n        Assert.assertTrue(t3.getBody().equals(\"My Third Tweet\"));\n        Assert.assertTrue(t3.getDevice().equals(\"iPad\"));\n\n        Assert.assertNotNull(p.getTags());\n        Assert.assertFalse(p.getTags().isEmpty());\n        Assert.assertEquals(3, p.getTags().size());\n        for (String tag : p.getTags())\n        {\n            Assert.assertTrue(tag.equals(\"nosql\") || tag.equals(\"kundera\") || tag.equals(\"mongo\"));\n        }\n\n        Assert.assertNotNull(p.getLikedBy());\n        Assert.assertFalse(p.getLikedBy().isEmpty());\n        Assert.assertEquals(2, p.getLikedBy().size());\n        for (int likedUserId : p.getLikedBy())\n        {\n            Assert.assertTrue(likedUserId == 111 || likedUserId == 222);\n        }\n\n        Assert.assertNotNull(p.getComments());\n        Assert.assertFalse(p.getComments().isEmpty());\n        Assert.assertEquals(3, p.getComments().size());\n        for (int commentedBy : p.getComments().keySet())\n        {\n            String commentText = p.getComments().get(commentedBy);\n            Assert.assertTrue(commentedBy == 111 || commentedBy == 222 || commentedBy == 333);\n            Assert.assertTrue(commentText.equals(\"What a post!\")\n                    || commentText.equals(\"I am getting NPE on line no. 145\")\n                    || commentText.equals(\"My hobby is to spam blogs\"));\n        }\n\n        for (AlbumUni_1_M_1_M album : p.getAlbums())\n        {\n            Assert.assertFalse(album.getAlbumId().startsWith(\"X\"));\n            Assert.assertFalse(album.getAlbumName().startsWith(\"X\"));\n            Assert.assertFalse(album.getAlbumDescription().startsWith(\"X\"));\n\n            for (PhotoUni_1_M_1_M photo : album.getPhotos())\n            {\n                Assert.assertFalse(photo.getPhotoId().startsWith(\"X\"));\n                Assert.assertFalse(photo.getPhotoCaption().startsWith(\"X\"));\n                Assert.assertFalse(photo.getPhotoDescription().startsWith(\"X\"));\n            }\n\n        }\n\n    }\n\n    private void assertObjectReferenceInequality(PhotographerUni_1_M_1_M p1, PhotographerUni_1_M_1_M p2)\n    {\n\n        Assert.assertFalse(p1 == p2);\n        Assert.assertFalse(p1.getPhotographerName() == p2.getPhotographerName());\n        Assert.assertFalse(p1.getPersonalDetail() == p2.getPersonalDetail());\n        Assert.assertFalse(p1.getPersonalDetail().getPersonalDetailId() == p2.getPersonalDetail().getPersonalDetailId());\n        Assert.assertFalse(p1.getPersonalDetail().getName() == p2.getPersonalDetail().getName());\n        Assert.assertFalse(p1.getPersonalDetail().getPassword() == p2.getPersonalDetail().getPassword());\n        Assert.assertFalse(p1.getPersonalDetail().getRelationshipStatus() == p2.getPersonalDetail()\n                .getRelationshipStatus());\n        Assert.assertFalse(p1.getTweets() == p2.getTweets());\n\n        for (int i = 0; i < p1.getTweets().size(); i++)\n        {\n            Tweet p1Tweet = p1.getTweets().get(i);\n            Tweet p2Tweet = p2.getTweets().get(i);\n            Assert.assertFalse(p1Tweet == p2Tweet);\n            Assert.assertFalse(p1Tweet.getTweetId() == p2Tweet.getTweetId());\n            Assert.assertFalse(p1Tweet.getBody() == p2Tweet.getBody());\n            Assert.assertFalse(p1Tweet.getDevice() == p2Tweet.getDevice());\n        }\n\n        Assert.assertFalse(p1.getAlbums() == p2.getAlbums());\n        for (int i = 0; i < p1.getAlbums().size(); i++)\n        {\n            AlbumUni_1_M_1_M p1Album = p1.getAlbums().get(i);\n            AlbumUni_1_M_1_M p2Album = p2.getAlbums().get(i);\n            Assert.assertFalse(p1Album == p2Album);\n            Assert.assertFalse(p1Album.getAlbumId() == p2Album.getAlbumId());\n            Assert.assertFalse(p1Album.getAlbumName() == p2Album.getAlbumName());\n            Assert.assertFalse(p1Album.getAlbumDescription() == p2Album.getAlbumDescription());\n\n            Assert.assertFalse(p1.getAlbums().get(i).getPhotos() == p2.getAlbums().get(i).getPhotos());\n\n            for (int j = 0; j < p1.getAlbums().get(i).getPhotos().size(); j++)\n            {\n                PhotoUni_1_M_1_M photo1 = p1.getAlbums().get(i).getPhotos().get(j);\n                PhotoUni_1_M_1_M photo2 = p2.getAlbums().get(i).getPhotos().get(j);\n\n                Assert.assertFalse(photo1 == photo2);\n                Assert.assertFalse(photo1.getPhotoId() == photo2.getPhotoId());\n                Assert.assertFalse(photo1.getPhotoCaption() == photo2.getPhotoCaption());\n                Assert.assertFalse(photo1.getPhotoDescription() == photo2.getPhotoDescription());\n            }\n        }\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory(String property)\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(_persistenceUnit);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/utils/ReflectUtilsTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.utils;\n\nimport java.lang.reflect.Field;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.CoreTestClient;\nimport com.impetus.kundera.query.Person;\n\n/**\n * @author vivek.mishra\n * junit for {@link ReflectUtils}\n *\n */\npublic class ReflectUtilsTest\n{\n\n    @Test\n    public void test() throws NoSuchFieldException, SecurityException\n    {\n        try\n        {\n            Class clazz = ReflectUtils.classForName(\"Person\", this.getClass().getClassLoader());\n            \n        }catch(KunderaException cfex)\n        {\n            Assert.assertNotNull(cfex.getMessage());\n        }\n        \n        Class clazz = ReflectUtils.classForName(\"com.impetus.kundera.query.Person\", this.getClass().getClassLoader());\n        Assert.assertNotNull(clazz);\n        Assert.assertEquals(Person.class, clazz);\n        \n        \n        Field field = Person.class.getDeclaredField(\"personName\");\n        Assert.assertFalse(ReflectUtils.isTransientOrStatic(field));\n        \n        Assert.assertFalse(ReflectUtils.hasInterface(Client.class, Person.class));\n        Assert.assertTrue(ReflectUtils.hasInterface(Client.class, Client.class));\n        Assert.assertTrue(ReflectUtils.hasInterface(Client.class,CoreTestClient.class));\n        \n        Assert.assertTrue(ReflectUtils.hasSuperClass(ClientBase.class, CoreTestClient.class));\n        Assert.assertTrue(ReflectUtils.hasSuperClass(ClientBase.class, ClientBase.class));\n        Assert.assertFalse(ReflectUtils.hasSuperClass(ClientBase.class, Client.class));\n        \n        Assert.assertEquals(ClientBase.class,ReflectUtils.stripEnhancerClass(ClientBase.class));\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/validator/BookEntity.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n/**\n * @author Devender Yadav\n * \n */\n@Entity\npublic class BookEntity\n{\n\n    @Id\n    @Column(name = \"ID\")\n    private int bookId;\n\n    @Column(name = \"TITLE\")\n    private String title;\n\n    @Column(name = \"AUTHOR\")\n    private String author;\n\n    @Column(name = \"PAGES\")\n    private int pages;\n\n    public BookEntity()\n    {\n    }\n\n    public int getBookId()\n    {\n        return bookId;\n    }\n\n    public void setBookId(int bookId)\n    {\n        this.bookId = bookId;\n    }\n\n    public String getTitle()\n    {\n        return title;\n    }\n\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    public int getPages()\n    {\n        return pages;\n    }\n\n    public void setPages(int pages)\n    {\n        this.pages = pages;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/validator/ConstructorValidationTest.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.validator;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\n/**\n * @author Devender Yadav\n * \n */\npublic class ConstructorValidationTest {\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    @Test\n    public void validConstructorTest() throws Exception {\n        emf = Persistence.createEntityManagerFactory(\"patest\");\n        em = emf.createEntityManager();\n        BookEntity book = new BookEntity();\n        book.setBookId(1);\n        book.setTitle(\"The Complete Reference\");\n        book.setAuthor(\"Herbert Schildt\");\n        book.setPages(500);\n\n        em.persist(book);\n\n        em.clear();\n\n        BookEntity book1 = em.find(BookEntity.class, 1);\n\n        Assert.assertNotNull(book1);\n        Assert.assertEquals(1, book1.getBookId());\n        Assert.assertEquals(\"The Complete Reference\", book1.getTitle());\n        Assert.assertEquals(\"Herbert Schildt\", book1.getAuthor());\n        Assert.assertEquals(500, book1.getPages());\n\n        em.remove(book1);\n\n        BookEntity book2 = em.find(BookEntity.class, 1);\n        Assert.assertNull(book2);\n\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void invalidConstructorTest() throws Exception {\n\n        try {\n            emf = Persistence.createEntityManagerFactory(\"invalidJpaEntityPU\");\n            em = emf.createEntityManager();\n            int bookId = 2;\n            String title = \"Head First Java\";\n            String author = \"Kathy Sierra\";\n            int pages = 400;\n            InvalidBookEntity book = new InvalidBookEntity(bookId, title, author, pages);\n            em.persist(book);\n\n        } catch (Exception e) {\n            Assert.assertNull(emf);\n            Assert\n                .assertEquals(\n                    \"com.impetus.kundera.validator.InvalidBookEntity must have a default public or protected no-argument constructor.\",\n                    e.getMessage());\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/validator/InvalidBookEntity.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n/**\n * @author Devender Yadav\n * \n */\n@Entity\npublic class InvalidBookEntity\n{\n\n    @Id\n    @Column(name = \"ID\")\n    private int bookId;\n\n    @Column(name = \"TITLE\")\n    private String title;\n\n    @Column(name = \"AUTHOR\")\n    private String author;\n\n    @Column(name = \"PAGES\")\n    private int pages;\n\n    protected InvalidBookEntity(int bookId, String title, String author, int pages)\n    {\n        this.bookId = bookId;\n        this.title = title;\n        this.author = author;\n        this.pages = pages;\n    }\n\n    public int getBookId()\n    {\n        return bookId;\n    }\n\n    public void setBookId(int bookId)\n    {\n        this.bookId = bookId;\n    }\n\n    public String getTitle()\n    {\n        return title;\n    }\n\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    public int getPages()\n    {\n        return pages;\n    }\n\n    public void setPages(int pages)\n    {\n        this.pages = pages;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/validator/ValidationEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.validation.constraints.AssertFalse;\nimport javax.validation.constraints.AssertTrue;\nimport javax.validation.constraints.DecimalMax;\nimport javax.validation.constraints.DecimalMin;\nimport javax.validation.constraints.Digits;\nimport javax.validation.constraints.Future;\nimport javax.validation.constraints.Max;\nimport javax.validation.constraints.Min;\nimport javax.validation.constraints.NotNull;\nimport javax.validation.constraints.Null;\nimport javax.validation.constraints.Past;\nimport javax.validation.constraints.Pattern;\nimport javax.validation.constraints.Size;\n\n/**\n * @author Chhavi Gangwal\n *\n */\n@Entity\npublic class ValidationEntity\n{\n    \n    @Id\n    private String  eId;\n    \n    @Column\n    @NotNull(message=\"Age should not be null\")\n    private int age;\n    \n    @Column\n    @Null(message=\"The value should be null.\")\n    private String nullField;\n    \n    @Column\n    @AssertFalse(message=\"The  person type must be human\")\n    private boolean isHuman;\n    \n    @Column\n    @AssertTrue(message=\"The person type must be I-human\")\n    private boolean isIHuman;\n    \n    @Column\n    @DecimalMax(message=\"Invalid Decimal max value.\", value = \"20\")\n    private int decimalMax;\n    \n        \n    @Column\n    @DecimalMin(message=\"Invalid Decimal min value.\", value = \"50\")\n    private int decimalMin;\n    \n      \n    @Column\n    @Digits(message=\"Invalid number.\", fraction = 0, integer = 0)\n    private int digits;\n    \n    @Column\n    @Future(message=\"Invalid future date.\")\n    private java.util.Date future;\n    \n    @Column\n    @Past(message=\"Invalid past date\")\n    private java.util.Date past;\n    \n    @Column\n    @Pattern(message=\"Invalid pattern.\", regexp = \"^.+@.+\\\\.\")\n    private String pattern;\n    \n    @Column\n    @Size(message=\"Invalid size.\", max= 50, min=10)\n    private String size;\n    \n    @Column\n    @Max(message=\"Invalid max value.\", value = 100)\n    private String max;\n    \n    @Column\n    @Min(message=\"Invalid min value.\", value = -20)\n    private int min;\n    \n    @NotNull\n    @Size(min = 1, max = 256)\n    @Pattern(regexp=\"^.+@.+\\\\..+$\")\n    @Column(name=\"email\")\n    private String email;\n   \n\n    /**\n     * @param age the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param eId the eId to set\n     */\n    public void seteId(String eId)\n    {\n        this.eId = eId;\n    }\n\n    /**\n     * @return the eId\n     */\n    public String geteId()\n    {\n        return eId;\n    }\n\n    /**\n     * @param isHuman the isHuman to set\n     */\n    public void setHuman(boolean isHuman)\n    {\n        this.isHuman = isHuman;\n    }\n\n    /**\n     * @return the isHuman\n     */\n    public boolean isHuman()\n    {\n        return isHuman;\n    }\n\n    /**\n     * @param nullField the nullField to set\n     */\n    public void setNullField(String nullField)\n    {\n        this.nullField = nullField;\n    }\n\n    /**\n     * @return the nullField\n     */\n    public String getNullField()\n    {\n        return nullField;\n    }\n\n    /**\n     * @param isIHuman the isIHuman to set\n     */\n    public void setIHuman(boolean isIHuman)\n    {\n        this.isIHuman = isIHuman;\n    }\n\n    /**\n     * @return the isIHuman\n     */\n    public boolean isIHuman()\n    {\n        return isIHuman;\n    }\n\n    /**\n     * @param decimalMax the decimalMax to set\n     */\n    public void setDecimalMax(int decimalMax)\n    {\n        this.decimalMax = decimalMax;\n    }\n\n    /**\n     * @return the decimalMax\n     */\n    public int getDecimalMax()\n    {\n        return decimalMax;\n    }\n\n    /**\n     * @param decimalMin the decimalMin to set\n     */\n    public void setDecimalMin(int decimalMin)\n    {\n        this.decimalMin = decimalMin;\n    }\n\n    /**\n     * @return the decimalMin\n     */\n    public int getDecimalMin()\n    {\n        return decimalMin;\n    }\n\n    /**\n     * @param digits the digits to set\n     */\n    public void setDigits(int digits)\n    {\n        this.digits = digits;\n    }\n\n    /**\n     * @return the digits\n     */\n    public int getDigits()\n    {\n        return digits;\n    }\n\n    /**\n     * @param future the future to set\n     */\n    public void setFuture(java.util.Date future)\n    {\n        this.future = future;\n    }\n\n    /**\n     * @return the future\n     */\n    public java.util.Date getFuture()\n    {\n        return future;\n    }\n\n    /**\n     * @param pastDate the past to set\n     */\n    public void setPast(java.util.Date pastDate)\n    {\n        this.past = pastDate;\n    }\n\n    /**\n     * @return the past\n     */\n    public java.util.Date getPast()\n    {\n        return past;\n    }\n\n    /**\n     * @param pattern the pattern to set\n     */\n    public void setPattern(String pattern)\n    {\n        this.pattern = pattern;\n    }\n\n    /**\n     * @return the pattern\n     */\n    public String getPattern()\n    {\n        return pattern;\n    }\n\n    /**\n     * @param size the size to set\n     */\n    public void setSize(String  size)\n    {\n        this.size = size;\n    }\n\n    /**\n     * @return the size\n     */\n    public String getSize()\n    {\n        return size;\n    }\n\n    /**\n     * @param max the max to set\n     */\n    public void setMax(String max)\n    {\n        this.max = max;\n    }\n\n    /**\n     * @return the max\n     */\n    public String getMax()\n    {\n        return max;\n    }\n\n    /**\n     * @param min the min to set\n     */\n    public void setMin(int min)\n    {\n        this.min = min;\n    }\n\n    /**\n     * @return the min\n     */\n    public int getMin()\n    {\n        return min;\n    }\n\n    /**\n     * @param email the email to set\n     */\n    public void setEmail(String email)\n    {\n        this.email = email;\n    }\n\n    /**\n     * @return the email\n     */\n    public String getEmail()\n    {\n        return email;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/java/com/impetus/kundera/validator/ValidationProcessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.validator;\n\nimport java.lang.reflect.Field;\nimport java.text.DateFormat;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.metamodel.EntityType;\nimport javax.validation.ValidationException;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.processor.MetaModelBuilder;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.validation.ValidationFactory;\nimport com.impetus.kundera.validation.ValidationFactoryGenerator;\nimport com.impetus.kundera.validation.ValidationFactoryGenerator.ValidationFactoryType;\nimport com.impetus.kundera.validation.rules.AttributeConstraintRule;\n\n/**\n * @author Chhavi Gangwal\n * \n */\npublic class ValidationProcessorTest\n{\n\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(ValidationProcessorTest.class);\n\n    private static final String PU = \"kunderatest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    protected Map propertyMap = null;\n\n    private KunderaMetadata kunderaMetadata;\n\n    private ValidationFactoryGenerator generator = new ValidationFactoryGenerator();\n\n    private ValidationFactory factory = generator.getFactory(ValidationFactoryType.BOOT_STRAP_VALIDATION);\n\n    /**\n     * @throws Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU, propertyMap);\n        kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n        // kunderaMetadata.setApplicationMetadata(null);\n\n        em = emf.createEntityManager();\n\n    }\n\n    /**\n     * @throws ParseException\n     */\n    @Test\n    public void testValid() throws ParseException\n    {\n        try\n        {\n            String pastStr = \"11-11-2012\";\n            String futStr = \"11-11-2015\";\n            DateFormat df = new SimpleDateFormat(\"dd-mm-yyyy\");\n            Date pastDate = df.parse(pastStr);\n            Date futDate = df.parse(futStr);\n\n            ValidationEntity entity = new ValidationEntity();\n            entity.setAge(13);\n            entity.seteId(\"e1\");\n            entity.setHuman(false);\n            entity.setDecimalMax(5);\n            entity.setDecimalMin(59);\n            entity.setDigits(123);\n            entity.setIHuman(true);\n            entity.setMax(\"90\");\n            entity.setMin(20);\n            entity.setNullField(null);\n            entity.setPast(pastDate);\n            entity.setFuture(futDate);\n            entity.setSize(\"hello232141423423535353453\");\n            entity.setEmail(\"abc@gcd.com\");\n            \n            validateEntityAttribute(\"age\", entity, \"Age should not be null\");\n            validateEntityAttribute(\"nullField\", entity, \"The value should be null.\");\n            validateEntityAttribute(\"isHuman\", entity, \"The  person type must be human\");\n            validateEntityAttribute(\"isIHuman\", entity, \"The person type must be I-human\");\n            validateEntityAttribute(\"decimalMax\", entity, \"Invalid Decimal max value.\");\n            validateEntityAttribute(\"decimalMin\", entity, \"Invalid Decimal min value.\");\n            validateEntityAttribute(\"digits\", entity, \"Invalid number.\");\n            validateEntityAttribute(\"future\", entity, \"Invalid future date.\");\n            validateEntityAttribute(\"past\", entity, \"Invalid past date\");\n            validateEntityAttribute(\"pattern\", entity, \"Invalid pattern.\");\n            validateEntityAttribute(\"size\", entity, \"Invalid size.\");\n            validateEntityAttribute(\"max\", entity, \"Invalid max value.\");\n            validateEntityAttribute(\"min\", entity, \"Invalid min value.\");\n\n            //em.persist(entity);\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertNotNull(e.getMessage());\n        }\n\n    }\n\n    /**\n     * @throws ParseException\n     */\n    @Test\n    public void testNull() throws ParseException\n    {\n        try\n        {\n\n            ValidationEntity entity = new ValidationEntity();\n            entity.setAge(13);\n            entity.seteId(\"e1\");\n            entity.setHuman(false);\n            entity.setDecimalMax(5);\n            entity.setDecimalMin(59);\n            entity.setDigits(123);\n            entity.setIHuman(true);\n            entity.setMax(\"90\");\n            entity.setMin(21);\n            entity.setNullField(null);\n            entity.setPast(null);\n            entity.setFuture(null);\n            entity.setSize(null);\n            entity.setEmail(null);\n\n            validateEntityAttribute(\"age\", entity, \"\");\n            validateEntityAttribute(\"nullField\", entity, \"\");\n            validateEntityAttribute(\"isHuman\", entity, \"\");\n            validateEntityAttribute(\"isIHuman\", entity, \"\");\n            validateEntityAttribute(\"decimalMax\", entity, \"\");\n            validateEntityAttribute(\"decimalMin\", entity, \"\");\n            validateEntityAttribute(\"digits\", entity, \"\");\n            validateEntityAttribute(\"future\", entity, \"\");\n            validateEntityAttribute(\"past\", entity, \"\");\n            validateEntityAttribute(\"pattern\", entity, \"\");\n            validateEntityAttribute(\"size\", entity, \"\");\n            validateEntityAttribute(\"max\", entity, \"\");\n            validateEntityAttribute(\"min\", entity, \"\");\n        }\n        catch (KunderaException e)\n        {\n\n            Assert.assertNotNull(e.getMessage());\n        }\n\n    }\n\n    /**\n     * @throws ParseException\n     */\n    @Test\n    public void testInValid() throws ParseException\n    {\n        try\n        {\n            String pastStr = \"11-11-2015\";\n            String futStr = \"11-11-2012\";\n            DateFormat df = new SimpleDateFormat(\"dd-mm-yyyy\");\n            Date pastDate = df.parse(pastStr);\n            Date futDate = df.parse(futStr);\n\n            ValidationEntity entity = new ValidationEntity();\n            entity.setAge(13);\n            entity.seteId(\"e1\");\n            entity.setHuman(true);\n            entity.setDecimalMax(50);\n            entity.setDecimalMin(5);\n            entity.setDigits(123);\n            entity.setIHuman(false);\n            entity.setMax(\"90\");\n            entity.setMin(20);\n            entity.setNullField(\"hello\");\n            entity.setPast(pastDate);\n            entity.setFuture(futDate);\n            entity.setSize(\"123\");\n            entity.setEmail(\"axc\");\n\n            validateEntityAttribute(\"age\", entity, \"Age should not be null\");\n            validateEntityAttribute(\"nullField\", entity, \"The value should be null.\");\n            validateEntityAttribute(\"isHuman\", entity, \"The  person type must be human\");\n            validateEntityAttribute(\"isIHuman\", entity, \"The person type must be I-human\");\n            validateEntityAttribute(\"decimalMax\", entity, \"Invalid Decimal max value.\");\n            validateEntityAttribute(\"decimalMin\", entity, \"Invalid Decimal min value.\");\n            validateEntityAttribute(\"digits\", entity, \"Invalid number.\");\n            validateEntityAttribute(\"future\", entity, \"Invalid future date.\");\n            validateEntityAttribute(\"past\", entity, \"Invalid past date\");\n            validateEntityAttribute(\"pattern\", entity, \"Invalid pattern.\");\n            validateEntityAttribute(\"size\", entity, \"Invalid size.\");\n            validateEntityAttribute(\"max\", entity, \"Invalid max value.\");\n            validateEntityAttribute(\"min\", entity, \"Invalid min value.\");\n\n            em.persist(entity);\n        }\n        catch (KunderaException e)\n        {\n\n            Assert.assertNotNull(e.getMessage());\n        }\n\n    }\n\n    /**\n     * @param <X>\n     * @param <T>\n     * @return\n     */\n    private <X extends Class, T extends Object> void validateEntityAttribute(String fieldname, Object validationObject,\n            String message)\n    {\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                validationObject.getClass());\n        MetaModelBuilder<X, T> metaModelBuilder = kunderaMetadata.getApplicationMetadata().getMetaModelBuilder(\n                entityMetadata.getPersistenceUnit());\n        EntityType entityType = (EntityType) metaModelBuilder.getManagedTypes().get(entityMetadata.getEntityClazz());\n\n        Field field = (Field) entityType.getAttribute(fieldname).getJavaMember();\n\n        try\n        {\n            factory.validate(field, validationObject, new AttributeConstraintRule());\n\n        }\n        catch (ValidationException e)\n        {\n           \n            Assert.assertEquals(message, e.getMessage());\n            Assert.assertNotNull(e.getMessage());\n        }\n\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"kunderatest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<!-- <jar-file>/home/impetus/perf_n.jar</jar-file> <jar-file>/home/impetus/perf.jar</jar-file> -->\r\n\t\t<class>com.impetus.kundera.entity.PersonnelDTO</class>\r\n\t\t<class>com.impetus.kundera.persistence.event.PersonEventDispatch</class>\r\n\t\t<class>com.impetus.kundera.persistence.event.AddressEntity</class>\r\n\t\t<class>com.impetus.kundera.persistence.event.AddressEntityWithList</class>\r\n\t\t<class>com.impetus.kundera.graph.Store</class>\r\n\t\t<class>com.impetus.kundera.graph.BillingCounter</class>\r\n\t\t<class>com.impetus.kundera.validator.ValidationEntity</class>\r\n\t\t<!-- <class>com.impetus.kundera.configure.CoreEntityAddressUni1To1</class> \r\n\t\t\t<class>com.impetus.kundera.configure.CoreEntityAddressUni1ToM</class> <class>com.impetus.kundera.configure.CoreEntityAddressUniMTo1</class> \r\n\t\t\t<class>com.impetus.kundera.configure.CoreEntityPersonUni1To1</class> <class>com.impetus.kundera.configure.CoreEntityPersonUni1ToM</class> \r\n\t\t\t<class>com.impetus.kundera.configure.CoreEntityPersionUniMTo1</class> -->\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_1_1_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_1_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_1_1_M_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_1_M_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_1_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_M_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_M_M_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_M_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_1_1_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_1_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_1_1_M_1</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_1_M_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_1_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_M_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_M_M_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_M_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_1_1_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_1_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_1_1_M_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_1_M_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_1_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_M_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_M_M_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_M_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_1_1_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_1_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_1_M_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_1_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_M_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_M_M_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_M_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_1_1_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_1_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_1_M_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_1_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_M_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_M_M_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_M_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_1_1_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_1_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_1_M_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_1_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_M_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_M_M_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_M_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.metadata.entities.SampleEntity</class>\r\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileHandset</class>\r\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileManufacturer</class>\r\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileOperatingSystem</class>\r\n\t\t<!-- <class>com.impetus.kundera.metadata.entities.bi.AssociationBiEntity</class> \r\n\t\t\t<class>com.impetus.kundera.metadata.entities.bi.OToOOwnerBiEntity</class> -->\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"rdbms\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"PropertyTest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaXmlTest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"PropertyTestwithvaraiable\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaXmlTest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t\t<property name=\"kundera.client.property\"\r\n\t\t\t\tvalue=\"${HOME}/Desktop/kunderaExternalProperties.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"PropertyTestwithabsolutepath\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaXmlTest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t\t<property name=\"kundera.client.property\"\r\n\t\t\t\tvalue=\"/home/impadmin/Desktop/kunderaExternalProperties.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"metaDataTest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.persistence.event.PersonEventDispatch</class>\r\n\t\t<class>com.impetus.kundera.metadata.model.Employe</class>\r\n\t\t<class>com.impetus.kundera.metadata.model.KunderaUser</class>\r\n\t\t<class>com.impetus.kundera.metadata.model.TweetKundera</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaMetaDataTest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"GeneratedValue\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdDefault</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdStrategyAuto</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdStrategyIdentity</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdStrategySequence</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdStrategyTable</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdWithSequenceGenerator</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdWithTableGenerator</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdWithOutSequenceGenerator</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdWithOutTableGenerator</class>\r\n\t\t<!-- <class>com.impetus.kundera.metadata.validator.FTEmployee</class> <class>com.impetus.kundera.metadata.validator.PartTimeEmployee</class> -->\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"patest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.query.Person</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonU11FK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressU11FK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonB11FK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressB11FK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonU11PK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressU11PK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonB11PK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressB11PK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonU1M</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressU1M</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonB1M</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressB1M</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonUM1</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressUM1</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonBM1</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressBM1</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonUMM</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonUMMByMap</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressUMM</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonBMM</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressBMM</class>\r\n\t\t<class>com.impetus.kundera.metadata.entities.SingularEntityEmbeddable</class>\r\n\t\t<class>com.impetus.kundera.metadata.entities.Article</class>\r\n\t\t<class>com.impetus.kundera.query.PersonEntityNameAnnotation</class>\r\n\t\t<class>com.impetus.kundera.persistence.PersonnelEmbedded</class>\r\n\t\t<class>com.impetus.kundera.validator.BookEntity</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"rdbms\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"./lucene\" /> -->\r\n\t\t\t<property name=\"kundera.batch.size\" value=\"5\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\t\r\n\t<persistence-unit name=\"invalidJpaEntityPU\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.validator.InvalidBookEntity</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"rdbms\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<property name=\"kundera.batch.size\" value=\"5\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"mappedsu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.Employee</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTest\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"invalidmappedsu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.InvalidPersonEntity</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTest\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\r\n\t<persistence-unit name=\"keyspace\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.metadata.entities.OToOOwnerEntity</class>\r\n\t\t<class>com.impetus.kundera.metadata.entities.AssociationEntity</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"testSchema\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"inheritanceTest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.metadata.processor.Rectangle</class>\r\n\t\t<class>com.impetus.kundera.metadata.processor.Circle</class>\r\n\t\t<class>com.impetus.kundera.metadata.processor.Geometry</class>\r\n\t\t<class>com.impetus.kundera.metadata.processor.Shape</class>\r\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.Person</class>\r\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.PersonChild</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"testSchema\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\t<persistence-unit name=\"extConfig\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.persistence.User</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\t\r\n\t\r\n</persistence>\r\n\r\n\r\n\r\n\r\n\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/resources/META-INF/persistence_2_0.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!-- persistence.xml schema -->\r\n<xsd:schema targetNamespace=\"http://java.sun.com/xml/ns/persistence\" \r\n  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\r\n  xmlns:persistence=\"http://java.sun.com/xml/ns/persistence\"\r\n  elementFormDefault=\"qualified\" \r\n  attributeFormDefault=\"unqualified\" \r\n  version=\"2.0\">\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n      @(#)persistence_2_0.xsd  1.0  October 1 2009\r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n\r\n  Copyright (c) 2008, 2009 Sun Microsystems. All rights reserved. \r\n  \r\n  This program and the accompanying materials are made available under the \r\n  terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 \r\n  which accompanies this distribution. \r\n  The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html\r\n  and the Eclipse Distribution License is available at \r\n  http://www.eclipse.org/org/documents/edl-v10.php.\r\n  \r\n  Contributors:\r\n      Linda DeMichiel - Java Persistence 2.0, Version 2.0 (October 1, 2009)\r\n      Specification available from http://jcp.org/en/jsr/detail?id=317\r\n \r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n   <xsd:annotation>\r\n     <xsd:documentation><![CDATA[\r\n\r\n     This is the XML Schema for the persistence configuration file.\r\n     The file must be named \"META-INF/persistence.xml\" in the \r\n     persistence archive.\r\n\r\n     Persistence configuration files must indicate\r\n     the persistence schema by using the persistence namespace:\r\n\r\n     http://java.sun.com/xml/ns/persistence\r\n\r\n     and indicate the version of the schema by\r\n     using the version element as shown below:\r\n\r\n      <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n        xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n          http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\"\r\n        version=\"2.0\">\r\n          ...\r\n      </persistence>\r\n\r\n    ]]></xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:simpleType name=\"versionType\">\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:pattern value=\"[0-9]+(\\.[0-9]+)*\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:element name=\"persistence\">\r\n    <xsd:complexType>\r\n      <xsd:sequence>\r\n\r\n        <!-- **************************************************** -->\r\n\r\n        <xsd:element name=\"persistence-unit\" \r\n                     minOccurs=\"1\" maxOccurs=\"unbounded\">\r\n          <xsd:complexType>\r\n            <xsd:annotation>\r\n              <xsd:documentation>\r\n\r\n                Configuration of a persistence unit.\r\n\r\n              </xsd:documentation>\r\n            </xsd:annotation>\r\n            <xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"description\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Description of this persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"provider\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Provider class that supplies EntityManagers for this \r\n                    persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of the JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"non-jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of a non-JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"mapping-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    File containing mapping information. Loaded as a resource \r\n                    by the persistence provider.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jar-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Jar file that is to be scanned for managed classes. \r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"class\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Managed class to be included in the persistence unit and\r\n                    to scan for annotations.  It should be annotated \r\n                    with either @Entity, @Embeddable or @MappedSuperclass.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"exclude-unlisted-classes\" type=\"xsd:boolean\" \r\n                           default=\"true\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    When set to true then only listed classes and jars will \r\n                    be scanned for persistent classes, otherwise the \r\n                    enclosing jar or directory will also be scanned. \r\n                    Not applicable to Java SE persistence units.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"shared-cache-mode\" \r\n                           type=\"persistence:persistence-unit-caching-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Defines whether caching is enabled for the \r\n                    persistence unit if caching is supported by the\r\n                    persistence provider. When set to ALL, all entities \r\n                    will be cached. When set to NONE, no entities will\r\n                    be cached. When set to ENABLE_SELECTIVE, only entities\r\n                    specified as cacheable will be cached. When set to\r\n                    DISABLE_SELECTIVE, entities specified as not cacheable\r\n                    will not be cached. When not specified or when set to\r\n                    UNSPECIFIED, provider defaults may apply.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"validation-mode\" \r\n                           type=\"persistence:persistence-unit-validation-mode-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The validation mode to be used for the persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"properties\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    A list of standard and vendor-specific properties \r\n                    and hints.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n                <xsd:complexType>\r\n                  <xsd:sequence>\r\n                    <xsd:element name=\"property\" \r\n                                 minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                      <xsd:annotation>\r\n                        <xsd:documentation>\r\n                          A name-value pair.\r\n                        </xsd:documentation>\r\n                      </xsd:annotation>\r\n                      <xsd:complexType>\r\n                        <xsd:attribute name=\"name\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                        <xsd:attribute name=\"value\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                      </xsd:complexType>\r\n                    </xsd:element>\r\n                  </xsd:sequence>\r\n                </xsd:complexType>\r\n              </xsd:element>\r\n\r\n            </xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Name used in code to reference this persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"transaction-type\" \r\n                           type=\"persistence:persistence-unit-transaction-type\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Type of transactions used by EntityManagers from this \r\n                  persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n          </xsd:complexType>\r\n        </xsd:element>\r\n      </xsd:sequence>\r\n      <xsd:attribute name=\"version\" type=\"persistence:versionType\" \r\n                     fixed=\"2.0\" use=\"required\"/>\r\n    </xsd:complexType>\r\n  </xsd:element>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-transaction-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum PersistenceUnitTransactionType {JTA, RESOURCE_LOCAL};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"JTA\"/>\r\n      <xsd:enumeration value=\"RESOURCE_LOCAL\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-caching-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum SharedCacheMode { ALL, NONE, ENABLE_SELECTIVE, DISABLE_SELECTIVE, UNSPECIFIED};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"ALL\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n      <xsd:enumeration value=\"ENABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"DISABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"UNSPECIFIED\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-validation-mode-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum ValidationMode { AUTO, CALLBACK, NONE};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"AUTO\"/>\r\n      <xsd:enumeration value=\"CALLBACK\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n</xsd:schema>\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/resources/ehcache-test.xml",
    "content": "<ehcache xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"ehcache.xsd\">\r\n\r\n\t<diskStore path=\"java.io.tmpdir\"/>\r\n\t\r\n\t<defaultCache maxElementsInMemory=\"10000\" eternal=\"false\" timeToIdleSeconds=\"120\"\r\n\t\ttimeToLiveSeconds=\"300\" overflowToDisk=\"true\" diskSpoolBufferSizeMB=\"30\"\r\n\t\tmaxElementsOnDisk=\"100000\" diskPersistent=\"false\" diskExpiryThreadIntervalSeconds=\"120\"\r\n\t\tmemoryStoreEvictionPolicy=\"LRU\" />\r\n\r\n\t<cache name=\"com.impetus.kundera.entity.PersonEhcache\" maxElementsInMemory=\"10000\"\r\n\t\tmaxElementsOnDisk=\"1000\" eternal=\"false\" overflowToDisk=\"true\" diskSpoolBufferSizeMB=\"20\"\r\n\t\ttimeToIdleSeconds=\"300\" timeToLiveSeconds=\"600\" />\r\n</ehcache>\r\n"
  },
  {
    "path": "src/jpa-engine/core/src/test/resources/kunderaTest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>mongo</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"read.preference\" value=\"primary\"></property>\n\t\t\t\t\t<property name=\"socket.timeout\" value=\"100000\"></property>\n\t\t\t\t</properties>\n\t\t\t\t<servers>\n\t\t\t\t\t<server>\n\t\t\t\t\t\t<host>192.168.145.168</host>\n\t\t\t\t\t\t<port>27017</port>\n\t\t\t\t\t</server>\n\t\t\t\t\t<server>\n\t\t\t\t\t\t<host>192.168.145.66</host>\n\t\t\t\t\t\t<port>27018</port>\n\t\t\t\t\t</server>\n\t\t\t\t</servers>\n\t\t\t</connection>\n\t\t</dataStore>\n\t\t<dataStore>\n\t\t\t<name>cassandra</name>\n\t\t\t<schemas>\n\t\t\t\t<schema>\n\t\t\t\t\t<name>KunderaCassandraXmlTest</name>\n\t\t\t\t\t<properties>\n\t\t\t\t\t\t<property name=\"strategy.class\" value=\"SimpleStrategy\" />\n\t\t\t\t\t\t<property name=\"replcation.factor\" value=\"1\" />\n\t\t\t\t\t\t<property name=\"durable.writes\" value=\"true\" />\n\t\t\t\t\t</properties>\n\t\t\t\t\t<dataCenters>\n\t\t\t\t\t\t<dataCenter>\n\t\t\t\t\t\t\t<name>DC1</name>\n\t\t\t\t\t\t\t<value>3</value>\n\t\t\t\t\t\t</dataCenter>\n\t\t\t\t\t\t<dataCenter>\n\t\t\t\t\t\t\t<name>DC2</name>\n\t\t\t\t\t\t\t<value>2</value>\n\t\t\t\t\t\t</dataCenter>\n\t\t\t\t\t</dataCenters>\n\t\t\t\t\t<tables>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>CASSANDRAUSERXYZ</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"default.validation.class\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t\t<property name=\"key.validation.class\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t\t<property name=\"comment\" value=\"User Column Family\"></property>\n\t\t\t\t\t\t\t\t<property name=\"max.compaction.threshold\" value=\"64\"></property>\n\t\t\t\t\t\t\t\t<property name=\"min.compaction.threshold\" value=\"16\"></property>\n\t\t\t\t\t\t\t\t<property name=\"replicate.on.write\" value=\"true\"></property>\n\t\t\t\t\t\t\t\t<property name=\"comparator.type\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>CASSANDRASUPERUSER</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"default.validation.class\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t\t<property name=\"key.validation.class\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t\t<property name=\"comment\" value=\"User Super Column Family\"></property>\n\t\t\t\t\t\t\t\t<property name=\"comparator.type\" value=\"BytesType\"></property>\n\t\t\t\t\t\t\t\t<property name=\"subcomparator.type\" value=\"BytesType\"></property>\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</tables>\n\t\t\t\t</schema>\n\t\t\t\t<schema>\n\t\t\t\t\t<name>KunderaCounterColumn</name>\n\t\t\t\t\t<tables>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>counters</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"default.validation.class\" value=\"CounterColumnType\"></property>\n\t\t\t\t\t\t\t\t<property name=\"key.validation.class\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>CountersWithString</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"default.validation.class\" value=\"CounterColumnType\"></property>\n\t\t\t\t\t\t\t\t<property name=\"key.validation.class\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>SuperCounters</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"default.validation.class\" value=\"CounterColumnType\"></property>\n\t\t\t\t\t\t\t\t<property name=\"key.validation.class\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>InvalidCounterColumnEntity</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"default.validation.class\" value=\"CounterColumnType\"></property>\n\t\t\t\t\t\t\t\t<property name=\"key.validation.class\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>ValidCounterColumnFamily</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"default.validation.class\" value=\"CounterColumnType\"></property>\n\t\t\t\t\t\t\t\t<property name=\"key.validation.class\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</tables>\n\t\t\t\t</schema>\n\t\t\t\t<schema>\n\t\t\t\t\t<name>KunderaExamples</name>\n\t\t\t\t\t<properties>\n\t\t\t\t\t\t<property name=\"strategy.class\" value=\"SimpleStrategy\" />\n\t\t\t\t\t\t<property name=\"replcation.factor\" value=\"1\" />\n\t\t\t\t\t\t<property name=\"durable.writes\" value=\"true\" />\n\t\t\t\t\t\t<property name=\"inverted.indexing.enabled\" value=\"true\" />\n\t\t\t\t\t</properties>\n\t\t\t\t</schema>\n\t\t\t</schemas>\n\t\t</dataStore>\n\t\t<dataStore>\n\t\t\t<name>hbase</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"hbase.zookeeper.quorum\" value=\"localhost\"></property>\n\t\t\t\t\t<property name=\"hbase.zookeeper.property.clientPort\"\n\t\t\t\t\t\tvalue=\"2181\"></property>\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t\t<schemas>\n\t\t\t\t<schema>\n\t\t\t\t\t<name>KunderaHbaseXmlTest</name>\n\t\t\t\t\t<tables>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>HBASEUSERXYZ</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"TTL\" value=\"12345678\" />\n\t\t\t\t\t\t\t\t<property name=\"VERSIONS\" value=\"6\" />\n\t\t\t\t\t\t\t\t<property name=\"MIN_VERSIONS\" value=\"3\" />\n\t\t\t\t\t\t\t\t<property name=\"COMPRESSION\" value=\"GZ\" />\n\t\t\t\t\t\t\t\t<property name=\"COMPRESSION_COMPACT\" value=\"GZ\" />\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</tables>\n\t\t\t\t</schema>\n\t\t\t\t<schema>\n\t\t\t\t\t<name>KunderaExamples</name>\n\t\t\t\t\t<tables>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>AGE</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"TTL\" value=\"123456\" />\n\t\t\t\t\t\t\t\t<property name=\"MAX_VERSIONS\" value=\"5\" />\n\t\t\t\t\t\t\t\t<property name=\"MIN_VERSIONS\" value=\"2\" />\n\t\t\t\t\t\t\t\t<property name=\"COMPRESSION\" value=\"GZ\" />\n\t\t\t\t\t\t\t\t<property name=\"COMPRESSION_COMPACT\" value=\"GZ\" />\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>PERSON_NAME</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"TTL\" value=\"123456\" />\n\t\t\t\t\t\t\t\t<property name=\"MAX_VERSIONS\" value=\"5\" />\n\t\t\t\t\t\t\t\t<property name=\"MIN_VERSIONS\" value=\"2\" />\n\t\t\t\t\t\t\t\t<property name=\"COMPRESSION\" value=\"GZ\" />\n\t\t\t\t\t\t\t\t<property name=\"COMPRESSION_COMPACT\" value=\"GZ\" />\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</tables>\n\t\t\t\t</schema>\n\t\t\t</schemas>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "src/jpa-engine/core/src/test/resources/kunderaTestDataType.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>cassandra</name>\n\t\t\t<schemas>\n\t\t\t\t<schema>\n\t\t\t\t\t<name>CompositeCassandra</name>\n\t\t\t\t\t<properties>\n\t\t\t\t\t\t<property name=\"strategy.class\" value=\"SimpleStrategy\" />\n\t\t\t\t\t\t<property name=\"replcation.factor\" value=\"1\" />\n\t\t\t\t\t\t<property name=\"durable.writes\" value=\"true\" />\n\t\t\t\t\t</properties>\n\t\t\t\t\t<dataCenters>\n\t\t\t\t\t\t<dataCenter>\n\t\t\t\t\t\t\t<name>DC1</name>\n\t\t\t\t\t\t\t<value>3</value>\n\t\t\t\t\t\t</dataCenter>\n\t\t\t\t\t\t<dataCenter>\n\t\t\t\t\t\t\t<name>DC2</name>\n\t\t\t\t\t\t\t<value>2</value>\n\t\t\t\t\t\t</dataCenter>\n\t\t\t\t\t</dataCenters>\n\t\t\t\t\t<tables>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>CompositeUserDataType</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"default.validation.class\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t\t<property name=\"key.validation.class\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t\t<property name=\"comment\" value=\"User Column Family\"></property>\n\t\t\t\t\t\t\t\t<property name=\"max.compaction.threshold\" value=\"64\"></property>\n\t\t\t\t\t\t\t\t<property name=\"min.compaction.threshold\" value=\"16\"></property>\n\t\t\t\t\t\t\t\t<property name=\"replicate.on.write\" value=\"true\"></property>\n\t\t\t\t\t\t\t\t<property name=\"comparator.type\" value=\"UTF8Type\"></property>\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</tables>\n\t\t\t\t</schema>\n\t\t\t</schemas>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "src/jpa-engine/core/src/test/resources/log4j.properties",
    "content": "log4j.rootLogger=ERROR,CONSOLE\r\n\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t<artifactId>core-parent</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.core</groupId>\n\t<artifactId>fallback-impl</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-fallback-impl</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<lucene.version>5.5.0</lucene.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.lucene</groupId>\n\t\t\t<artifactId>lucene-core</artifactId>\n\t\t\t<version>${lucene.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.lucene</groupId>\n\t\t\t<artifactId>lucene-analyzers-common</artifactId>\n\t\t\t<version>${lucene.version}</version>\n\t\t\t<scope>compile</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.lucene</groupId>\n\t\t\t<artifactId>lucene-queryparser</artifactId>\n\t\t\t<version>${lucene.version}</version>\n\t\t\t<scope>compile</scope>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<artifactId>jakarta-regexp</artifactId>\n\t\t\t\t\t<groupId>jakarta-regexp</groupId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>cglib</groupId>\n\t\t\t<artifactId>cglib</artifactId>\n\t\t\t<version>2.2.2</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>commons-logging</groupId>\n\t\t\t<artifactId>commons-logging</artifactId>\n\t\t\t<version>1.1.1</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>net.sf.ehcache</groupId>\n\t\t\t<artifactId>ehcache-core</artifactId>\n\t\t\t<version>2.5.2</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>javassist</groupId>\n\t\t\t<artifactId>javassist</artifactId>\n\t\t\t<version>3.12.1.GA</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.google.guava</groupId>\n\t\t\t<artifactId>guava</artifactId>\n\t\t\t<version>18.0</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>javax.transaction</groupId>\n\t\t\t<artifactId>jta</artifactId>\n\t\t\t<version>1.1</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.slf4j</groupId>\n\t\t\t<artifactId>slf4j-api</artifactId>\n\t\t\t<version>1.7.5</version>\n\t\t</dependency>\n\n\t\t<!-- Conti-perf -->\n\t\t<dependency>\n\t\t\t<groupId>org.databene</groupId>\n\t\t\t<artifactId>contiperf</artifactId>\n\t\t\t<version>2.2.0</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<!-- apache commons -->\n\t\t<dependency>\n\t\t\t<groupId>commons-configuration</groupId>\n\t\t\t<artifactId>commons-configuration</artifactId>\n\t\t\t<version>1.9</version>\n\t\t</dependency>\n\n\t</dependencies>\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t<version>2.8.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<show>private</show>\n\t\t\t\t\t<nohelp>true</nohelp>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\t  <profiles>\n  <profile>\n    <id>doclint-java8-disable</id>\n    <activation>\n      <jdk>[1.8,)</jdk>\n    </activation>\n\n    <build>\n      <plugins>\n        <plugin>\n          <groupId>org.apache.maven.plugins</groupId>\n          <artifactId>maven-javadoc-plugin</artifactId>\n          <configuration>\n            <additionalparam>-Xdoclint:none</additionalparam>\n          </configuration>\n        </plugin>\n      </plugins>\n    </build>\n  </profile>\n</profiles>\n\t\n\n</project>"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/main/java/com/impetus/kundera/cache/ehcache/EhCacheProvider.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.cache.ehcache;\r\n\r\nimport java.net.URL;\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.Cache;\r\n\r\nimport net.sf.ehcache.CacheManager;\r\nimport net.sf.ehcache.Ehcache;\r\nimport net.sf.ehcache.event.CacheEventListener;\r\nimport net.sf.ehcache.util.ClassLoaderUtil;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.cache.CacheException;\r\nimport com.impetus.kundera.cache.CacheProvider;\r\n\r\n/**\r\n * Cache provider implementation using Ehcache.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class EhCacheProvider implements CacheProvider\r\n{\r\n\r\n    /** The Constant log. */\r\n    private static final Logger log = LoggerFactory.getLogger(EhCacheProvider.class);\r\n\r\n    /** The manager. */\r\n    private CacheManager manager;\r\n\r\n    /** The cache. */\r\n    private Cache cache;\r\n\r\n    /** The Constant NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME. */\r\n    private static final String NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME = \"net.sf.ehcache.configurationResourceName\";\r\n\r\n    /** The initializing. */\r\n    private boolean initializing;\r\n\r\n    /** The listeners. */\r\n    private List<CacheEventListener> listeners = new ArrayList<CacheEventListener>();\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.CacheProvider#init(java.lang.String)\r\n     */\r\n    @Override\r\n    public void init(String cacheResourceName)\r\n    {\r\n        if (manager != null)\r\n        {\r\n            log.warn(\"Attempt to restart an already started CacheFactory. Using previously created EhCacheFactory.\");\r\n            return;\r\n        }\r\n        initializing = true;\r\n        try\r\n        {\r\n            String configurationResourceName = cacheResourceName;\r\n            if (configurationResourceName == null || configurationResourceName.length() == 0)\r\n            {\r\n                manager = CacheManager.create();\r\n            }\r\n            else\r\n            {\r\n                if (!configurationResourceName.startsWith(\"/\"))\r\n                {\r\n                    configurationResourceName = \"/\" + configurationResourceName;\r\n                    log.info(\"prepending / to \" + configurationResourceName + \". It should be placed in the root\"\r\n                            + \"of the classpath rather than in a package.\");\r\n                }\r\n                URL url = loadResource(configurationResourceName);\r\n//                manager = new CacheManager(url);\r\n                manager = CacheManager.create(url);\r\n            }\r\n        }\r\n        catch (net.sf.ehcache.CacheException e)\r\n        {\r\n            if (e.getMessage().startsWith(\r\n                    \"Cannot parseConfiguration CacheManager. Attempt to create a new instance of \"\r\n                            + \"CacheManager using the diskStorePath\"))\r\n            {\r\n                throw new CacheException(\"Could not init EhCacheFactory.\", e);\r\n            }\r\n            else\r\n            {\r\n                throw e;\r\n            }\r\n        }\r\n        finally\r\n        {\r\n            initializing = false;\r\n        }\r\n\r\n    }\r\n\r\n    /* @see com.impetus.kundera.cache.CacheProvider#init(java.util.Map) */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.CacheProvider#init(java.util.Map)\r\n     */\r\n    @Override\r\n    public synchronized void init(Map<?, ?> properties)\r\n    {\r\n        if (manager != null)\r\n        {\r\n            log.warn(\"Attempt to restart an already started CacheFactory. Using previously created EhCacheFactory.\");\r\n            return;\r\n        }\r\n        initializing = true;\r\n        try\r\n        {\r\n            String configurationResourceName = null;\r\n            if (properties != null)\r\n            {\r\n                configurationResourceName = (String) properties.get(NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME);\r\n            }\r\n            if (configurationResourceName == null || configurationResourceName.length() == 0)\r\n            {\r\n                manager = CacheManager.create();\r\n            }\r\n            else\r\n            {\r\n                if (!configurationResourceName.startsWith(\"/\"))\r\n                {\r\n                    configurationResourceName = \"/\" + configurationResourceName;\r\n                    log.info(\"prepending / to \" + configurationResourceName + \". It should be placed in the root\"\r\n                            + \"of the classpath rather than in a package.\");\r\n                }\r\n                URL url = loadResource(configurationResourceName);\r\n                manager = CacheManager.create(url);\r\n            }\r\n        }\r\n        catch (net.sf.ehcache.CacheException e)\r\n        {\r\n            if (e.getMessage().startsWith(\r\n                    \"Cannot parseConfiguration CacheManager. Attempt to create a new instance of \"\r\n                            + \"CacheManager using the diskStorePath\"))\r\n            {\r\n                throw new CacheException(\"Could not init EhCacheFactory.\", e);\r\n            }\r\n            else\r\n            {\r\n                throw new CacheException(e);\r\n            }\r\n        }\r\n        finally\r\n        {\r\n            initializing = false;\r\n        }\r\n\r\n    }\r\n\r\n    /**\r\n     * Load resource.\r\n     * \r\n     * @param configurationResourceName\r\n     *            the configuration resource name\r\n     * @return the uRL\r\n     */\r\n    private URL loadResource(String configurationResourceName)\r\n    {\r\n        ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader();\r\n        URL url = null;\r\n        if (standardClassloader != null)\r\n        {\r\n            url = standardClassloader.getResource(configurationResourceName);\r\n        }\r\n        if (url == null)\r\n        {\r\n            url = this.getClass().getResource(configurationResourceName);\r\n        }\r\n        log.info(\"Creating EhCacheFactory from a specified resource: \" + configurationResourceName\r\n                + \" Resolved to URL: \" + url);\r\n\r\n        if (url == null)\r\n        {\r\n            log.warn(\"A configurationResourceName was set to {} but the resource could not be loaded from the classpath.Ehcache will configure itself using defaults.\" ,configurationResourceName);\r\n        }\r\n        return url;\r\n    }\r\n\r\n    @Override\r\n    public Cache createCache(String name)\r\n    {\r\n        if (manager == null)\r\n        {\r\n            throw new CacheException(\"CacheFactory was not initialized. Call init() before creating a cache.\");\r\n        }\r\n        try\r\n        {\r\n            net.sf.ehcache.Cache cache = manager.getCache(name);\r\n            if (cache == null)\r\n            {\r\n                log.warn(\"Could not find a specific ehcache configuration for cache named [\" + name\r\n                        + \"]; using defaults.\");\r\n                manager.addCache(name);\r\n                cache = manager.getCache(name);\r\n            }\r\n            Ehcache backingCache = cache;\r\n            if (!backingCache.getCacheEventNotificationService().hasCacheEventListeners())\r\n            {\r\n                if (listeners.size() > 0)\r\n                {\r\n                    for (CacheEventListener listener : listeners)\r\n                    {\r\n                        if (!backingCache.getCacheEventNotificationService().getCacheEventListeners()\r\n                                .contains(listener))\r\n                        {\r\n                            backingCache.getCacheEventNotificationService().registerListener(listener);\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n\r\n            this.cache = new EhCacheWrapper(cache);\r\n            return this.cache;\r\n        }\r\n        catch (net.sf.ehcache.CacheException e)\r\n        {\r\n            throw new CacheException(\"Could not create cache: \" + name, e);\r\n        }\r\n\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.CacheProvider#getCache(java.lang.String)\r\n     */\r\n    @Override\r\n    public Cache getCache(String cacheName) throws CacheException\r\n    {\r\n        if (this.cache == null)\r\n        {\r\n            this.cache = createCache(cacheName);\r\n        }\r\n\r\n        return this.cache;\r\n    }\r\n\r\n    /* @see com.impetus.kundera.cache.CacheProvider#shutdown() */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.CacheProvider#shutdown()\r\n     */\r\n    @Override\r\n    public void shutdown()\r\n    {\r\n        if (manager != null)\r\n        {\r\n            manager.removalAll();\r\n            manager = null;\r\n        }\r\n        cache = null;\r\n    }\r\n\r\n    /**\r\n     * Clear all.\r\n     */\r\n    public void clearAll()\r\n    {\r\n        manager.clearAll();\r\n    }\r\n\r\n    /**\r\n     * Gets the cache manager.\r\n     * \r\n     * @return the cache manager\r\n     */\r\n    public CacheManager getCacheManager()\r\n    {\r\n        return manager;\r\n    }\r\n\r\n    /**\r\n     * Adds the default listener.\r\n     * \r\n     * @param cacheEventListener\r\n     *            the cache event listener\r\n     */\r\n    public void addDefaultListener(CacheEventListener cacheEventListener)\r\n    {\r\n        listeners.add(cacheEventListener);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/main/java/com/impetus/kundera/cache/ehcache/EhCacheWrapper.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.cache.ehcache;\r\n\r\nimport net.sf.ehcache.Element;\r\nimport net.sf.ehcache.Status;\r\n\r\nimport org.apache.commons.lang.NotImplementedException;\r\n\r\nimport com.impetus.kundera.cache.Cache;\r\n\r\n/**\r\n * Cache implementation using Ehcache.\r\n * \r\n * @author animesh.kumar\r\n */\r\npublic class EhCacheWrapper implements Cache\r\n{\r\n\r\n    /** The ehcache. */\r\n    private net.sf.ehcache.Cache ehcache;\r\n\r\n    /**\r\n     * Instantiates a new eh cache wrapper.\r\n     * \r\n     * @param ehcache\r\n     *            the ehcache\r\n     */\r\n    public EhCacheWrapper(net.sf.ehcache.Cache ehcache)\r\n    {\r\n        this.ehcache = ehcache;\r\n    }\r\n\r\n    /* @see com.impetus.kundera.cache.Cache#get(java.lang.Object) */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.Cache#get(java.lang.Object)\r\n     */\r\n    @Override\r\n    public Object get(Object key)\r\n    {\r\n        Element element = null;\r\n        if(isAlive())\r\n        {\r\n            element = ehcache.get(key);\r\n        }\r\n        return element == null ? null : element.getObjectValue();\r\n    }\r\n\r\n    /*\r\n     * @see com.impetus.kundera.cache.Cache#put(java.lang.Object,\r\n     * java.lang.Object)\r\n     */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.Cache#put(java.lang.Object,\r\n     * java.lang.Object)\r\n     */\r\n    @Override\r\n    public void put(Object key, Object value)\r\n    {\r\n        if(isAlive())\r\n        ehcache.put(new Element(key, value));\r\n    }\r\n\r\n    /* @see com.impetus.kundera.cache.Cache#size() */\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.cache.Cache#size()\r\n     */\r\n    @Override\r\n    public int size()\r\n    {\r\n        if(isAlive())\r\n        {\r\n            return ehcache.getSize();\r\n        }\r\n        return 0;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.Cache#contains(java.lang.Class, java.lang.Object)\r\n     */\r\n    @Override\r\n    public boolean contains(Class arg0, Object arg1)\r\n    {\r\n        if(isAlive())\r\n        {\r\n            return (ehcache.get(arg1) != null);\r\n        }\r\n        \r\n        return false;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.Cache#evict(java.lang.Class)\r\n     */\r\n    @Override\r\n    public void evict(Class arg0)\r\n    {\r\n        // TODO Can we use Class with ehcache\r\n        throw new NotImplementedException(\"TODO\");\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.Cache#evict(java.lang.Class, java.lang.Object)\r\n     */\r\n    @Override\r\n    public void evict(Class arg0, Object arg1)\r\n    {\r\n        // TODO Can we use Class with ehcache\r\n        if(isAlive())\r\n        ehcache.remove(arg1);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see javax.persistence.Cache#evictAll()\r\n     */\r\n    @Override\r\n    public void evictAll()\r\n    {\r\n        if(isAlive())\r\n        {\r\n            ehcache.removeAll();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public <T> T unwrap(Class<T> arg0)\r\n    {\r\n        // Not yet supported.\r\n        //TODO: See https://github.com/impetus-opensource/Kundera/issues/457\r\n        \r\n        return null;\r\n    }\r\n    \r\n    private boolean isAlive()\r\n    {\r\n        return ehcache.getStatus().equals(Status.STATUS_ALIVE);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/main/java/com/impetus/kundera/index/DocumentIndexer.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.index;\n\nimport java.io.CharArrayReader;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Id;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.apache.lucene.analysis.Analyzer;\nimport org.apache.lucene.analysis.Tokenizer;\nimport org.apache.lucene.analysis.core.LetterTokenizer;\nimport org.apache.lucene.analysis.standard.StandardAnalyzer;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.document.Field;\nimport org.apache.lucene.document.Field.Store;\nimport org.apache.lucene.util.Version;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PropertyIndex;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.Relation.ForeignKey;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * The Class KunderaIndexer.\n * \n * @author animesh.kumar\n */\n@SuppressWarnings(value = { \"all\" })\npublic abstract class DocumentIndexer implements com.impetus.kundera.index.lucene.Indexer {\n\n    /** log for this class. */\n    private static final Logger LOG = LoggerFactory.getLogger(DocumentIndexer.class);\n\n    /** The INDEX_NAME. */\n    protected static final String INDEX_NAME = \"kundera-alpha\";// is\n\n    /** The Constant UUID. */\n    private static final long UUID = 6077004083174677888L;\n\n    /** The Constant DEFAULT_SEARCHABLE_FIELD. */\n    protected static final String DEFAULT_SEARCHABLE_FIELD = UUID + \".default_property\";\n\n    /** The Constant SUPERCOLUMN_INDEX. */\n    protected static final String SUPERCOLUMN_INDEX = UUID + \".entity.super.indexname\";\n\n    /** The doc number. */\n    protected static int docNumber = 1;\n\n    /** The analyzer. */\n    protected Analyzer analyzer;\n\n    /** The tokenizer. */\n    protected Tokenizer tokenizer;\n\n    /**\n     * Instantiates a new lucandra indexer.\n     * \n     * @param analyzer\n     *            the analyzer\n     */\n    public DocumentIndexer() {\n        final String empty = \"\";\n        this.analyzer = new StandardAnalyzer();\n        tokenizer = new LetterTokenizer();\n    }\n\n    /**\n     * Prepare document.\n     * \n     * @param metadata\n     *            the metadata\n     * @param object\n     *            the object\n     * @param embeddedColumnName\n     *            the super column name\n     * @param parentId\n     *            the parent id\n     * @param clazz\n     *            the clazz\n     * @return the document\n     */\n    protected Document prepareDocumentForSuperColumn(EntityMetadata metadata, Object object, String embeddedColumnName,\n        String parentId, Class<?> clazz) {\n        Document currentDoc;\n        currentDoc = new Document();\n\n        // Add entity class and row key info to document\n        addEntityClassToDocument(metadata, object, currentDoc, null);\n\n        // Add super column name to document\n        addSuperColumnNameToDocument(embeddedColumnName, currentDoc);\n\n        addParentKeyToDocument(parentId, currentDoc, clazz);\n        return currentDoc;\n    }\n\n    /**\n     * Index parent key.\n     * \n     * @param parentId\n     *            the parent id\n     * @param currentDoc\n     *            the current doc\n     * @param clazz\n     *            the clazz\n     */\n    protected void addParentKeyToDocument(String parentId, Document currentDoc, Class<?> clazz) {\n        // if (parentId != null)\n        if (clazz != null && parentId != null) {\n            Field luceneField =\n                new Field(IndexingConstants.PARENT_ID_FIELD, parentId, Field.Store.YES, Field.Index.ANALYZED_NO_NORMS);\n            currentDoc.add(luceneField);\n            Field fieldClass =\n                new Field(IndexingConstants.PARENT_ID_CLASS, clazz.getCanonicalName().toLowerCase(), Field.Store.YES,\n                    Field.Index.ANALYZED);\n            currentDoc.add(fieldClass);\n        }\n    }\n\n    /**\n     * Index super column.\n     * \n     * @param metadata\n     *            the metadata\n     * @param object\n     *            the object\n     * @param currentDoc\n     *            the current doc\n     * @param embeddedObject\n     *            the embedded object\n     * @param superColumn\n     *            the super column\n     * @param metamodel\n     */\n    protected void createSuperColumnDocument(EntityMetadata metadata, Object object, Document currentDoc,\n        Object embeddedObject, EmbeddableType superColumn, MetamodelImpl metamodel) {\n\n        // Add all super column fields into document\n        Set<Attribute> attributes = superColumn.getAttributes();\n        Iterator<Attribute> iter = attributes.iterator();\n        while (iter.hasNext()) {\n            Attribute attr = iter.next();\n            java.lang.reflect.Field field = (java.lang.reflect.Field) attr.getJavaMember();\n            String colName = field.getName();\n            String indexName = metadata.getIndexName();\n            addFieldToDocument(embeddedObject, currentDoc, field, colName, indexName);\n        }\n\n        // Add all entity fields to document\n        addEntityFieldsToDocument(metadata, object, currentDoc, metamodel);\n\n    }\n\n    /**\n     * Index super column.\n     * \n     * @param metadata\n     *            the metadata\n     * @param object\n     *            the object\n     * @param currentDoc\n     *            the current doc\n     * @param embeddedObject\n     *            the embedded object\n     * @param superColumn\n     *            the super column\n     * @param metamodel\n     */\n    protected void indexSuperColumn(EntityMetadata metadata, Object object, Document currentDoc, Object embeddedObject,\n        EmbeddableType superColumn, MetamodelImpl metamodel) {\n\n        // Add all super column fields into document\n        Set<Attribute> attributes = superColumn.getAttributes();\n        Iterator<Attribute> iter = attributes.iterator();\n        while (iter.hasNext()) {\n            Attribute attr = iter.next();\n            java.lang.reflect.Field field = (java.lang.reflect.Field) attr.getJavaMember();\n            String colName = field.getName();\n            String indexName = metadata.getIndexName();\n            addFieldToDocument(embeddedObject, currentDoc, field, colName, indexName);\n        }\n\n        // Add all entity fields to document\n        addEntityFieldsToDocument(metadata, object, currentDoc, metamodel);\n\n        // Store document into Index\n        indexDocument(metadata, currentDoc);\n\n    }\n\n    /**\n     * Index super column name.\n     * \n     * @param superColumnName\n     *            the super column name\n     * @param currentDoc\n     *            the current doc\n     */\n    private void addSuperColumnNameToDocument(String superColumnName, Document currentDoc) {\n        Field luceneField = new Field(SUPERCOLUMN_INDEX, superColumnName, Store.YES, Field.Index.NO);\n        currentDoc.add(luceneField);\n    }\n\n    /**\n     * Adds the index properties.\n     * \n     * @param metadata\n     *            the metadata\n     * @param entity\n     *            the object\n     * @param document\n     *            the document\n     * @param metaModel\n     */\n    protected void addEntityFieldsToDocument(EntityMetadata metadata, Object entity, Document document,\n        MetamodelImpl metaModel) {\n        String indexName = metadata.getIndexName();\n        Map<String, PropertyIndex> indexProperties = metadata.getIndexProperties();\n        for (String columnName : indexProperties.keySet()) {\n            PropertyIndex index = indexProperties.get(columnName);\n            java.lang.reflect.Field property = index.getProperty();\n            String propertyName = index.getName();\n            addFieldToDocument(entity, document, property, propertyName, indexName);\n        }\n\n        if (metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {\n            Object id = PropertyAccessorHelper.getId(entity, metadata);\n            EmbeddableType embeddableId = metaModel.embeddable(metadata.getIdAttribute().getBindableJavaType());\n            Set<Attribute> embeddedAttributes = embeddableId.getAttributes();\n            indexCompositeKey(embeddedAttributes, metadata, id, document, metaModel);\n        }\n    }\n\n    /**\n     * @param metadata\n     * @param entity\n     * @param document\n     * @param metaModel\n     * \n     *            Add indexes for associated columns\n     */\n    protected void addAssociatedEntitiesToDocument(EntityMetadata metadata, Object entity, Document document,\n        MetamodelImpl metaModel) {\n        try {\n            IndexCollection indexes = metadata.getEntityClazz().getAnnotation(IndexCollection.class);\n            if (indexes != null) {\n                List<String> columnsNameToBeIndexed = new ArrayList<String>();\n                for (com.impetus.kundera.index.Index indexedColumn : indexes.columns()) {\n                    Attribute attrib = metaModel.getEntityAttribute(entity.getClass(), indexedColumn.name());\n                    columnsNameToBeIndexed.add(((AbstractAttribute) attrib).getJPAColumnName());\n                }\n\n                String indexName = metadata.getIndexName();\n                List<Relation> relations = metadata.getRelations();\n                for (Relation relation : relations) {\n                    if (relation.getType().equals(ForeignKey.MANY_TO_ONE)\n                        || relation.getType().equals(ForeignKey.ONE_TO_ONE)) {\n                        String propertyName = relation.getJoinColumnName(null);\n                        if (propertyName != null && columnsNameToBeIndexed.contains(propertyName)) {\n                            java.lang.reflect.Field property = relation.getProperty();\n                            Object obj = PropertyAccessorHelper.getObject(entity, property);\n                            if (obj != null) {\n                                EntityMetadata relMetaData = metaModel.getEntityMetadata(obj.getClass());\n                                Object id = PropertyAccessorHelper.getId(obj, relMetaData);\n                                if (id != null) {\n                                    Field luceneField =\n                                        new Field(getCannonicalPropertyName(indexName, propertyName), id.toString(),\n                                            Field.Store.YES, Field.Index.ANALYZED_NO_NORMS);\n\n                                    document.add(luceneField);\n                                } else {\n                                    LOG.warn(\"value is null for field\" + property.getName());\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        } catch (PropertyAccessException e) {\n            LOG.error(\"Error in accessing field, Caused by:\" + e.getMessage());\n            throw new LuceneIndexingException(\"Error in creating indexes on associated columns\", e);\n        }\n    }\n\n    /**\n     * index compositekey\n     * \n     * @param metadata\n     * @param id\n     * @param document\n     * @param metaModel\n     */\n    protected void indexCompositeKey(Set<Attribute> embeddedAttributes, EntityMetadata metadata, Object id,\n        Document document, final MetamodelImpl metaModel) {\n        // indexing individual fields of the composite key\n        try {\n            for (Attribute attribute : embeddedAttributes) {\n                if (!ReflectUtils.isTransientOrStatic((java.lang.reflect.Field) attribute.getJavaMember())) {\n                    if (metaModel.isEmbeddable(attribute.getJavaType())) {\n                        EmbeddableType embeddable = metaModel.embeddable(attribute.getJavaType());\n                        indexCompositeKey(embeddable.getAttributes(), metadata,\n                            ((java.lang.reflect.Field) attribute.getJavaMember()).get(id), document, metaModel);\n                    } else {\n                        String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                        addFieldToDocument(id, document, (java.lang.reflect.Field) attribute.getJavaMember(),\n                            columnName, metadata.getEntityClazz().getSimpleName());\n                    }\n                }\n            }\n        } catch (IllegalAccessException e) {\n            LOG.error(e.getMessage());\n        }\n    }\n\n    /**\n     * Prepare index document.\n     * \n     * @param metadata\n     *            the metadata\n     * @param entity\n     *            the object\n     * @param document\n     *            the document\n     */\n    protected void addEntityClassToDocument(EntityMetadata metadata, Object entity, Document document,\n        final MetamodelImpl metaModel) {\n        try {\n            Field luceneField;\n            Object id;\n            id = PropertyAccessorHelper.getId(entity, metadata);\n\n            // Indexing composite keys\n            if (metaModel != null && metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {\n                id = KunderaCoreUtils.prepareCompositeKey(metadata.getIdAttribute(), metaModel, id);\n            }\n\n            luceneField =\n                new Field(IndexingConstants.ENTITY_ID_FIELD, id.toString(), Field.Store.YES, Field.Index.ANALYZED);\n\n            // luceneField.set\n            // adding class\n            // namespace\n            // /*Field.Store.YES, Field.Index.ANALYZED_NO_NORMS*/);\n            document.add(luceneField);\n\n            // index namespace for unique deletion\n            luceneField =\n                new Field(IndexingConstants.KUNDERA_ID_FIELD, getKunderaId(metadata, id), Field.Store.YES,\n                    Field.Index.ANALYZED); // adding\n            // class\n            // namespace\n            // Field.Store.YES/*, Field.Index.ANALYZED_NO_NORMS*/);\n            document.add(luceneField);\n\n            // index entity class\n            luceneField =\n                new Field(IndexingConstants.ENTITY_CLASS_FIELD, metadata.getEntityClazz().getCanonicalName()\n                    .toLowerCase(), Field.Store.YES, Field.Index.ANALYZED);\n            document.add(luceneField);\n            //\n            luceneField = new Field(\"timestamp\", System.currentTimeMillis() + \"\", Field.Store.YES, Field.Index.NO);\n            document.add(luceneField);\n\n            // index index name\n            luceneField =\n                new Field(IndexingConstants.ENTITY_INDEXNAME_FIELD, metadata.getIndexName(), Field.Store.NO,\n                    Field.Index.ANALYZED_NO_NORMS);\n            document.add(luceneField);\n\n            luceneField =\n                new Field(getCannonicalPropertyName(metadata.getEntityClazz().getSimpleName(),\n                    ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName()), id.toString(),\n                    Field.Store.YES, Field.Index.ANALYZED_NO_NORMS);\n            document.add(luceneField);\n        } catch (PropertyAccessException e) {\n            throw new IllegalArgumentException(\"Id could not be read from object \" + entity);\n        }\n    }\n\n    /**\n     * Index field.\n     * \n     * @param object\n     *            the object\n     * @param document\n     *            the document\n     * @param field\n     *            the field\n     * @param colName\n     *            the col name\n     * @param indexName\n     *            the index name\n     */\n    private void addFieldToDocument(Object object, Document document, java.lang.reflect.Field field, String colName,\n        String indexName) {\n        try {\n            Object obj = PropertyAccessorHelper.getObject(object, field);\n            // String str =\n            // String value = (obj == null) ? null : obj.toString();\n            if (obj != null) {\n                Field luceneField =\n                    new Field(getCannonicalPropertyName(indexName, colName), obj.toString(), Field.Store.YES,\n                        Field.Index.ANALYZED_NO_NORMS);\n\n                document.add(luceneField);\n            } else {\n                LOG.warn(\"value is null for field\" + field.getName());\n            }\n        } catch (PropertyAccessException e) {\n            LOG.error(\"Error in accessing field, Caused by:\" + e.getMessage());\n            throw new LuceneIndexingException(\"Error in accessing field:\" + field.getName(), e);\n        }\n    }\n\n    @Override\n    public Map<String, Object> search(String query, Class<?> parentClass, EntityMetadata parentMetadata,\n        Class<?> childClass, EntityMetadata childMetadata, Object entityId, int start, int count) {\n        return null;\n    }\n\n    /**\n     * Gets the kundera id.\n     * \n     * @param metadata\n     *            the metadata\n     * @param id\n     *            the id\n     * \n     * @return the kundera id\n     */\n    protected String getKunderaId(EntityMetadata metadata, Object id) {\n        return metadata.getEntityClazz().getCanonicalName() + IndexingConstants.DELIMETER + id;\n    }\n\n    /**\n     * Gets the cannonical property name.\n     * \n     * @param indexName\n     *            the index name\n     * @param propertyName\n     *            the property name\n     * \n     * @return the cannonical property name\n     */\n    protected String getCannonicalPropertyName(String indexName, String propertyName) {\n        return indexName + \".\" + propertyName;\n    }\n\n    /**\n     * Index document.\n     * \n     * @param metadata\n     *            the metadata\n     * @param currentDoc\n     *            the current doc\n     */\n    protected abstract void indexDocument(EntityMetadata metadata, Document currentDoc);\n\n}"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/main/java/com/impetus/kundera/index/LuceneIndexer.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.index;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.lang.reflect.Field;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.lucene.analysis.standard.StandardAnalyzer;\nimport org.apache.lucene.document.Document;\nimport org.apache.lucene.index.DirectoryReader;\nimport org.apache.lucene.index.IndexNotFoundException;\nimport org.apache.lucene.index.IndexReader;\nimport org.apache.lucene.index.IndexWriter;\nimport org.apache.lucene.index.IndexWriterConfig;\nimport org.apache.lucene.index.LogDocMergePolicy;\nimport org.apache.lucene.index.Term;\nimport org.apache.lucene.queryparser.classic.QueryParser;\nimport org.apache.lucene.search.IndexSearcher;\nimport org.apache.lucene.search.Query;\nimport org.apache.lucene.search.ScoreDoc;\nimport org.apache.lucene.search.TopDocs;\nimport org.apache.lucene.store.Directory;\nimport org.apache.lucene.store.FSDirectory;\nimport org.apache.lucene.store.IOContext;\nimport org.apache.lucene.store.RAMDirectory;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.cache.ElementCollectionCacheManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * Provides indexing functionality using lucene library.\n * \n * @author amresh.singh\n */\npublic class LuceneIndexer extends DocumentIndexer\n{\n\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(LuceneIndexer.class);\n\n    /** The w. */\n    private static IndexWriter w;\n\n    /** The reader. */\n    private static IndexReader reader;\n\n    /** The index. */\n    private static Directory index;\n\n    /** The is initialized. */\n    private static boolean isInitialized;\n\n    /** The indexer. */\n    private static LuceneIndexer indexer;\n\n    /** The ready for commit. */\n    private static boolean readyForCommit;\n\n    /** The lucene dir path. */\n    private static String luceneDirPath;\n\n    /**\n     * Instantiates a new lucene indexer.\n     * \n     * @param analyzer\n     *            the analyzer\n     * @param lucDirPath\n     *            the luc dir path\n     */\n    private LuceneIndexer(String lucDirPath)\n    {\n        try\n        {\n            luceneDirPath = lucDirPath;\n            File file = new File(luceneDirPath);\n            if (file.exists())\n            {\n                FSDirectory sourceDir = FSDirectory.open(getIndexDirectory().toPath());\n\n                // TODO initialize context.\n                index = new RAMDirectory(sourceDir, IOContext.DEFAULT);\n            }\n            else\n            {\n                index = new RAMDirectory();\n            }\n            /*\n             * FSDirectory.open(getIndexDirectory( ))\n             */\n            // isInitialized\n            /* writer */\n            IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);\n            LogDocMergePolicy logDocMergePolicy = new LogDocMergePolicy();\n            logDocMergePolicy.setMergeFactor(1000);\n            indexWriterConfig.setMergePolicy(logDocMergePolicy);\n            w = new IndexWriter(index, indexWriterConfig);\n            w.getConfig().setRAMBufferSizeMB(32);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while instantiating LuceneIndexer, Caused by :.\", e);\n            throw new LuceneIndexingException(e);\n        }\n    }\n\n    /**\n     * Gets the single instance of LuceneIndexer.\n     * \n     * @param analyzer\n     *            the analyzer\n     * @param lucDirPath\n     *            the luc dir path\n     * @return single instance of LuceneIndexer\n     */\n    public static synchronized LuceneIndexer getInstance(String lucDirPath)\n    {\n        // super(analyzer);\n        if (indexer == null && lucDirPath != null)\n        {\n            indexer = new LuceneIndexer(lucDirPath);\n\n        }\n        return indexer;\n    }\n\n    /**\n     * Added for HBase support.\n     * \n     * @return default index writer\n     */\n    private IndexWriter getIndexWriter()\n    {\n        return w;\n    }\n\n    /**\n     * Returns default index reader.\n     * \n     * @return index reader.\n     */\n    private IndexReader getIndexReader()\n    {\n        // removed flushInternal() call while reading\n        if (reader == null)\n        {\n            try\n            {\n                if (!isInitialized)\n                {\n                    Directory sourceDir = FSDirectory.open(getIndexDirectory().toPath());\n                    copy(sourceDir, index);\n                    isInitialized = true;\n                }\n                reader = DirectoryReader.open(index);\n            }\n            catch (IndexNotFoundException infex)\n            {\n                log.warn(\"No index found in given directory, caused by:\", infex.getMessage());\n            }\n            catch (Exception e)\n            {\n                log.error(\"Error while instantiating LuceneIndexer, Caused by :.\", e);\n                throw new LuceneIndexingException(e);\n            }\n        }\n        return reader;\n    }\n\n    /**\n     * Creates a Lucene index directory if it does not exist.\n     * \n     * @return the index directory\n     */\n    private File getIndexDirectory()\n    {\n        File file = new File(luceneDirPath);\n\n        if (!file.isDirectory())\n        {\n            file.mkdir();\n        }\n        return file;\n    }\n\n    @Override\n    public final void index(EntityMetadata metadata, final MetamodelImpl metaModel, Object object)\n    {\n        indexDocument(metadata, metaModel, object, null, null);\n        onCommit();\n    }\n\n    @Override\n    public final void unindex(EntityMetadata metadata, Object id, KunderaMetadata kunderaMetadata, Class<?> parentClazz)\n            throws LuceneIndexingException\n    {\n        if (log.isDebugEnabled())\n            log.debug(\"Unindexing @Entity[{}] for key:{}\", metadata.getEntityClazz().getName(), id);\n        String luceneQuery = null;\n        boolean isEmbeddedId = false;\n\n        MetamodelImpl metaModel = null;\n        if (kunderaMetadata != null && metadata != null)\n        {\n            metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    metadata.getPersistenceUnit());\n            isEmbeddedId = metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType());\n        }\n\n        try\n        {\n            QueryParser qp = new QueryParser(DEFAULT_SEARCHABLE_FIELD, new StandardAnalyzer());\n\n            qp.setLowercaseExpandedTerms(false);\n            qp.setAllowLeadingWildcard(true);\n            luceneQuery = getLuceneQuery(metadata, id, isEmbeddedId, metaModel, parentClazz);\n            Query q = qp.parse(luceneQuery);\n\n            w.deleteDocuments(q);\n            w.commit();\n            w.close();\n            IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);\n            LogDocMergePolicy logDocMergePolicy = new LogDocMergePolicy();\n            logDocMergePolicy.setMergeFactor(1000);\n            indexWriterConfig.setMergePolicy(logDocMergePolicy);\n            w = new IndexWriter(index, indexWriterConfig);\n\n            w.getConfig().setRAMBufferSizeMB(32);\n            // flushInternal();\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while instantiating LuceneIndexer, Caused by :.\", e);\n            throw new LuceneIndexingException(e);\n        }\n    }\n\n    /**\n     * @param metadata\n     * @param id\n     * @param isEmbeddedId\n     * @param metaModel\n     * @return\n     */\n    private String getLuceneQuery(EntityMetadata metadata, Object id, boolean isEmbeddedId, MetamodelImpl metaModel,\n            Class<?> parentClazz)\n    {\n        StringBuilder luceneQuery = new StringBuilder(\"+\").append(IndexingConstants.ENTITY_CLASS_FIELD).append(\":\")\n                .append(QueryParser.escape(metadata.getEntityClazz().getCanonicalName().toLowerCase()))\n                .append(\" AND +\");\n        if (isEmbeddedId)\n        {\n            id = KunderaCoreUtils.prepareCompositeKey(metadata.getIdAttribute(), metaModel, id);\n            luceneQuery.append(IndexingConstants.ENTITY_ID_FIELD).append(\":\").append(QueryParser.escape(id.toString()));\n        }\n        else\n        {\n            luceneQuery\n                    .append(getCannonicalPropertyName(QueryParser.escape(metadata.getEntityClazz().getSimpleName()),\n                            QueryParser.escape(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName())))\n                    .append(\":\").append(QueryParser.escape(id.toString()));\n\n        }\n        if (parentClazz != null)\n        {\n            luceneQuery.append(\" AND +\").append(IndexingConstants.PARENT_ID_CLASS).append(\":\")\n                    .append(parentClazz.getCanonicalName().toLowerCase());\n        }\n        return luceneQuery.toString();\n    }\n\n    @Override\n    public final void update(EntityMetadata metadata, final MetamodelImpl metaModel, Object entity, Object id,\n            String parentId)\n    {\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"Updating @Entity[{}] for key:{}\", metadata.getEntityClazz().getName(), id);\n        }\n\n        updateDocument(metadata, metaModel, entity, parentId, entity.getClass(), true);\n    }\n\n    /**\n     * search the data from lucene for embeddedid\n     * \n     * @param docs\n     * @param indexCol\n     * @param searcher\n     * @param metadata\n     * @param metaModel\n     */\n    public void prepareEmbeddedId(TopDocs docs, Map<String, Object> indexCol, IndexSearcher searcher,\n            EntityMetadata metadata, MetamodelImpl metaModel)\n    {\n        try\n        {\n            for (ScoreDoc sc : docs.scoreDocs)\n            {\n                Document doc = searcher.doc(sc.doc);\n                Map<String, Object> embeddedIdFields = new HashMap<String, Object>();\n                EmbeddableType embeddableId = metaModel.embeddable(metadata.getIdAttribute().getBindableJavaType());\n                Set<Attribute> embeddedAttributes = embeddableId.getAttributes();\n\n                prepareEmbeddedIdFields(embeddedAttributes, metaModel, embeddedIdFields, doc, metadata);\n\n                String entityId = doc.get(IndexingConstants.ENTITY_ID_FIELD);\n                indexCol.put(entityId, embeddedIdFields);\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while parsing Lucene Query {} \", e);\n            throw new LuceneIndexingException(e);\n        }\n    }\n\n    private void prepareEmbeddedIdFields(Set<Attribute> embeddedAttributes, MetamodelImpl metaModel,\n            Map<String, Object> embeddedIdFields, Document doc, EntityMetadata metadata)\n    {\n\n        for (Attribute attribute : embeddedAttributes)\n        {\n            if (!ReflectUtils.isTransientOrStatic((Field) attribute.getJavaMember()))\n            {\n                if (metaModel.isEmbeddable(attribute.getJavaType()))\n                {\n                    EmbeddableType embeddable = metaModel.embeddable(attribute.getJavaType());\n                    prepareEmbeddedIdFields(embeddable.getAttributes(), metaModel, embeddedIdFields, doc, metadata);\n                }\n                else\n                {\n                    String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                    embeddedIdFields.put(columnName,\n                            doc.get(metadata.getEntityClazz().getSimpleName() + \".\" + columnName));\n                }\n            }\n        }\n    }\n\n    @Override\n    public final Map<String, Object> search(String luceneQuery, int start, int count, boolean fetchRelation,\n            KunderaMetadata kunderaMetadata, EntityMetadata metadata)\n    {\n        boolean isEmbeddedId = false;\n\n        MetamodelImpl metaModel = null;\n        if (kunderaMetadata != null && metadata != null)\n        {\n            metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    metadata.getPersistenceUnit());\n            isEmbeddedId = metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType());\n        }\n        reader = getIndexReader();\n\n        if (Constants.INVALID == count)\n        {\n            count = 100;\n        }\n\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"Searching index with query[{}], start:{} , count:\" + count, luceneQuery, start);\n        }\n\n        // Set<String> entityIds = new HashSet<String>();\n        Map<String, Object> indexCol = new HashMap<String, Object>();\n\n        if (reader == null)\n        {\n\n            return indexCol;\n            // throw new\n            // LuceneIndexingException(\"Index reader is not initialized!\");\n        }\n        QueryParser qp = null;\n        IndexSearcher searcher = new IndexSearcher(reader);\n\n        qp = new QueryParser(DEFAULT_SEARCHABLE_FIELD, new StandardAnalyzer());\n\n        try\n        {\n            // to make like query case insensitive\n            // qp.setLowercaseExpandedTerms(true);\n            qp.setAllowLeadingWildcard(true);\n            // qp.set\n            Query q = qp.parse(luceneQuery);\n\n            TopDocs docs = searcher.search(q, count);\n\n            int nullCount = 0;\n\n            // Assuming Supercol will be null in case if alias only.\n            // This is a quick fix\n            if (isEmbeddedId)\n            {\n                prepareEmbeddedId(docs, indexCol, searcher, metadata, metaModel);\n            }\n            else\n            {\n                for (ScoreDoc sc : docs.scoreDocs)\n                {\n\n                    Document doc = searcher.doc(sc.doc);\n                    String entityId = doc.get(fetchRelation ? IndexingConstants.PARENT_ID_FIELD\n                            : IndexingConstants.ENTITY_ID_FIELD);\n                    String superCol = doc.get(SUPERCOLUMN_INDEX);\n\n                    if (superCol == null)\n                    {\n                        superCol = \"SuperCol\" + nullCount++;\n                    }\n                    // In case of super column and association.\n                    indexCol.put(superCol + \"|\" + entityId, entityId);\n                }\n\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while parsing Lucene Query {} \", luceneQuery, e);\n            throw new LuceneIndexingException(e);\n        }\n\n        reader = null;\n        return indexCol;\n    }\n\n    /**\n     * Indexes document in file system using lucene.\n     * \n     * @param metadata\n     *            the metadata\n     * @param document\n     *            the document\n     */\n    public void indexDocument(EntityMetadata metadata, Document document)\n    {\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"Indexing document: {} for in file system using Lucene\", document);\n        }\n\n        IndexWriter w = getIndexWriter();\n        try\n        {\n            w.addDocument(document);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while indexing document {} into Lucene, Caused by:{} \", document, e);\n            throw new LuceneIndexingException(\"Error while indexing document \" + document + \" into Lucene.\", e);\n        }\n    }\n\n    /**\n     * Indexes document in file system using lucene.\n     * \n     * @param metadata\n     *            the metadata\n     * @param document\n     *            the document\n     */\n    public void updateDocument(String id, Document document, String EmbeddedEntityFieldName)\n    {\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"Updateing indexed document: {} for in file system using Lucene\", document);\n        }\n\n        IndexWriter w = getIndexWriter();\n        try\n        {\n            Term term = null;\n            if (EmbeddedEntityFieldName == null)\n            {\n                term = new Term(IndexingConstants.ENTITY_ID_FIELD, id);\n            }\n            else\n            {\n                term = new Term(EmbeddedEntityFieldName, id);\n            }\n            w.updateDocument(term, document);\n\n        }\n        catch (LuceneIndexingException lie)\n        {\n            log.error(\"Error while updating LuceneIndexer, Caused by :.\", lie);\n            throw new LuceneIndexingException(lie);\n        }\n        catch (IOException ioe)\n        {\n            log.error(\"Error while reading Lucene indexes, Caused by :.\", ioe);\n\n        }\n    }\n\n    /**\n     * Flush internal.\n     */\n    private void flushInternal()\n    {\n        try\n        {\n            if (w != null && readyForCommit)\n            {\n                // w.optimize();\n                w.commit();\n                copy(index, FSDirectory.open(getIndexDirectory().toPath()));\n                readyForCommit = false;\n                reader = null;\n                isInitialized = false;\n            }\n        }\n\n        catch (Exception e)\n        {\n            log.error(\"Error while Flushing Lucene Indexes, Caused by: \", e);\n            throw new LuceneIndexingException(\"Error while Flushing Lucene Indexes\", e);\n        }\n    }\n\n    /**\n     * Close of transaction.\n     */\n    public void close()\n    {\n        try\n        {\n            if (w != null && readyForCommit)\n            {\n                w.commit();\n                copy(index, FSDirectory.open(getIndexDirectory().toPath()));\n            }\n        }\n\n        catch (Exception e)\n        {\n            log.error(\"Error while closing lucene indexes, Caused by: \", e);\n            throw new LuceneIndexingException(\"Error while closing lucene indexes.\", e);\n        }\n    }\n\n    @Override\n    public void flush()\n    {\n        /*\n         * if (w != null) {\n         * \n         * try { w.commit(); // w.close(); // index.copy(index,\n         * FSDirectory.open(getIndexDirectory()), false); } catch\n         * (CorruptIndexException e) { } catch (IOException e) { } }\n         */\n    }\n\n    @Override\n    public void index(EntityMetadata metadata, final MetamodelImpl metaModel, Object object, String parentId,\n            Class<?> clazz)\n    {\n\n        indexDocument(metadata, metaModel, object, parentId, clazz);\n        onCommit();\n    }\n\n    @Override\n    public boolean entityExistsInIndex(Class<?> entityClass, KunderaMetadata kunderaMetadata, EntityMetadata metadata)\n    {\n        String luceneQuery = \"+\" + IndexingConstants.ENTITY_CLASS_FIELD + \":\"\n                + entityClass.getCanonicalName().toLowerCase();\n        Map<String, Object> results;\n        try\n        {\n            results = search(luceneQuery, 0, 10, false, kunderaMetadata, metadata);\n        }\n        catch (LuceneIndexingException e)\n        {\n            return false;\n        }\n        if (results == null || results.isEmpty())\n        {\n            return false;\n        }\n        else\n        {\n            return true;\n        }\n    }\n\n    @Override\n    public boolean documentExistsInIndex(EntityMetadata metadata, Object id, KunderaMetadata kunderaMetadata,\n            boolean isEmbeddedId, Class<?> parentClazz)\n    {\n        String luceneQuery = null;\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                metadata.getPersistenceUnit());\n\n        luceneQuery = getLuceneQuery(metadata, id, isEmbeddedId, metaModel, parentClazz);\n        Map<String, Object> results;\n        try\n        {\n            results = search(luceneQuery, 0, 10, false, kunderaMetadata, metadata);\n        }\n        catch (LuceneIndexingException e)\n        {\n            results = null;\n        }\n\n        return !(results == null || results.isEmpty());\n    }\n\n    /**\n     * Index document.\n     * \n     * @param metadata\n     *            the metadata\n     * @param object\n     *            the object\n     * @param parentId\n     *            the parent id\n     * @param clazz\n     *            the clazz\n     * @return the document\n     */\n    private Document indexDocument(EntityMetadata metadata, final MetamodelImpl metaModel, Object object,\n            String parentId, Class<?> clazz)\n    {\n\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"Indexing @Entity[{}],{} \", metadata.getEntityClazz().getName(), object);\n        }\n\n        // In case defined entity is Super column family.\n        // we need to create seperate lucene document for indexing.\n        Document currentDoc = updateOrCreateIndex(metadata, metaModel, object, parentId, clazz, false);\n\n        return currentDoc;\n\n    }\n\n    /**\n     * Update/Index document.\n     * \n     * @param metadata\n     *            the metadata\n     * @param entity\n     *            the object\n     * @param parentId\n     *            the parent id\n     * @param clazz\n     *            the clazz\n     * @return the document\n     */\n    private Document updateOrCreateIndex(EntityMetadata metadata, final MetamodelImpl metaModel, Object entity,\n            String parentId, Class<?> clazz, boolean isUpdate)\n    {\n        boolean isEmbeddedId = metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType());\n        if (!metadata.isIndexable())\n        {\n            return null;\n        }\n\n        Document document = null;\n        Object embeddedObject = null;\n        Object rowKey = null;\n\n        try\n        {\n            rowKey = PropertyAccessorHelper.getId(entity, metadata);\n        }\n        catch (PropertyAccessException e1)\n        {\n            throw new LuceneIndexingException(\"Can't access Primary key property from \" + metadata.getEntityClazz(), e1);\n        }\n\n        if (metadata.getType().equals(EntityMetadata.Type.SUPER_COLUMN_FAMILY))\n        {\n            Map<String, EmbeddableType> embeddables = metaModel.getEmbeddables(metadata.getEntityClazz());\n\n            Iterator<String> iter = embeddables.keySet().iterator();\n\n            while (iter.hasNext())\n            {\n\n                String attributeName = iter.next();\n                EmbeddableType embeddableAttribute = embeddables.get(attributeName);\n                EntityType entityType = metaModel.entity(metadata.getEntityClazz());\n\n                embeddedObject = PropertyAccessorHelper.getObject(entity, (Field) entityType\n                        .getAttribute(attributeName).getJavaMember());\n\n                if (embeddedObject == null)\n                {\n                    continue;\n                }\n                if (embeddedObject instanceof Collection<?>)\n                {\n                    document = updateOrCreateIndexCollectionTypeEmbeddedObject(metadata, metaModel, entity, parentId,\n                            clazz, isUpdate, document, embeddedObject, rowKey, attributeName, embeddableAttribute);\n                }\n                else\n                {\n                    document = prepareDocumentForSuperColumn(metadata, entity, attributeName, parentId, clazz);\n                    createSuperColumnDocument(metadata, entity, document,\n                            metaModel.isEmbeddable(embeddedObject.getClass()) ? embeddedObject : entity,\n                            embeddableAttribute, metaModel);\n                    if (isUpdate)\n                    {\n                        updateDocument(parentId, document, null);\n                    }\n                    else\n                    {\n                        indexDocument(metadata, document);\n                    }\n                }\n            }\n        }\n        else\n        {\n            document = updateOrCreateIndexNonSuperColumnFamily(metadata, metaModel, entity, parentId, clazz, isUpdate,\n                    isEmbeddedId, rowKey);\n        }\n        return document;\n\n    }\n\n    /**\n     * update or Create Index for non super columnfamily\n     * \n     * @param metadata\n     * @param metaModel\n     * @param entity\n     * @param parentId\n     * @param clazz\n     * @param isUpdate\n     * @param isEmbeddedId\n     * @param rowKey\n     * @return\n     */\n    private Document updateOrCreateIndexNonSuperColumnFamily(EntityMetadata metadata, final MetamodelImpl metaModel,\n            Object entity, String parentId, Class<?> clazz, boolean isUpdate, boolean isEmbeddedId, Object rowKey)\n    {\n\n        Document document = new Document();\n\n        // Add entity class, PK info into document\n\n        addEntityClassToDocument(metadata, entity, document, metaModel);\n\n        // Add all entity fields(columns) into document\n        addEntityFieldsToDocument(metadata, entity, document, metaModel);\n\n        addAssociatedEntitiesToDocument(metadata, entity, document, metaModel);\n        addParentKeyToDocument(parentId, document, clazz);\n        if (isUpdate)\n        {\n            if (isEmbeddedId)\n            {\n                // updating delimited composite key\n                String compositeId = KunderaCoreUtils.prepareCompositeKey(metadata.getIdAttribute(), metaModel, rowKey);\n                updateDocument(compositeId, document, null);\n                // updating sub parts of composite key\n                EmbeddableType embeddableId = metaModel.embeddable(metadata.getIdAttribute().getBindableJavaType());\n                Set<Attribute> embeddedAttributes = embeddableId.getAttributes();\n\n                updateOrCreateIndexEmbeddedIdFields(embeddedAttributes, metaModel, document, metadata, rowKey);\n            }\n            else\n            {\n                updateDocument(rowKey.toString(), document, null);\n            }\n        }\n        else\n        {\n            indexDocument(metadata, document);\n        }\n        return document;\n    }\n\n    private void updateOrCreateIndexEmbeddedIdFields(Set<Attribute> embeddedAttributes, MetamodelImpl metaModel,\n            Document document, EntityMetadata metadata, Object rowKey)\n    {\n        try\n        {\n            for (Attribute attribute : embeddedAttributes)\n            {\n                if (!ReflectUtils.isTransientOrStatic((Field) attribute.getJavaMember()))\n                {\n                    if (metaModel.isEmbeddable(attribute.getJavaType()))\n                    {\n                        EmbeddableType embeddable = metaModel.embeddable(attribute.getJavaType());\n                        updateOrCreateIndexEmbeddedIdFields(embeddable.getAttributes(), metaModel, document, metadata,\n                                ((Field) attribute.getJavaMember()).get(rowKey));\n                    }\n                    else\n                    {\n                        String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                        Object embeddedColumn = PropertyAccessorHelper.getObject(rowKey,\n                                (Field) attribute.getJavaMember());\n                        updateDocument(embeddedColumn.toString(), document, columnName);\n                    }\n                }\n            }\n        }\n        catch (IllegalAccessException e)\n        {\n            log.error(e.getMessage());\n        }\n    }\n\n    /**\n     * update or create indexes when embedded object is of collection type\n     * \n     * @param metadata\n     * @param metaModel\n     * @param entity\n     * @param parentId\n     * @param clazz\n     * @param isUpdate\n     * @param document\n     * @param embeddedObject\n     * @param rowKey\n     * @param attributeName\n     * @param embeddableAttribute\n     * @return\n     */\n    private Document updateOrCreateIndexCollectionTypeEmbeddedObject(EntityMetadata metadata,\n            final MetamodelImpl metaModel, Object entity, String parentId, Class<?> clazz, boolean isUpdate,\n            Document document, Object embeddedObject, Object rowKey, String attributeName,\n            EmbeddableType embeddableAttribute)\n    {\n        ElementCollectionCacheManager ecCacheHandler = ElementCollectionCacheManager.getInstance();\n        // Check whether it's first time insert or updation\n        if (ecCacheHandler.isCacheEmpty())\n        { // First time\n          // insert\n            int count = 0;\n            for (Object obj : (Collection<?>) embeddedObject)\n            {\n                String elementCollectionObjectName = attributeName + Constants.EMBEDDED_COLUMN_NAME_DELIMITER + count;\n\n                document = prepareDocumentForSuperColumn(metadata, entity, elementCollectionObjectName, parentId, clazz);\n                createSuperColumnDocument(metadata, entity, document, obj, embeddableAttribute, metaModel);\n                if (isUpdate)\n                {\n                    updateDocument(parentId, document, null);\n                }\n                else\n                {\n                    indexDocument(metadata, document);\n                }\n                count++;\n            }\n        }\n        else\n        {\n            // Updation, Check whether this object is already in\n            // cache, which means we already have an embedded\n            // column\n            // Otherwise we need to generate a fresh embedded\n            // column name\n            int lastEmbeddedObjectCount = ecCacheHandler.getLastElementCollectionObjectCount(rowKey);\n            for (Object obj : (Collection<?>) embeddedObject)\n            {\n                document = indexCollectionObject(metadata, entity, parentId, clazz, isUpdate, rowKey, attributeName,\n                        embeddableAttribute, ecCacheHandler, lastEmbeddedObjectCount, obj, metaModel);\n            }\n        }\n        return document;\n    }\n\n    private Document indexCollectionObject(EntityMetadata metadata, Object entity, String parentId, Class<?> clazz,\n            boolean isUpdate, Object rowKey, String attributeName, EmbeddableType embeddableAttribute,\n            ElementCollectionCacheManager ecCacheHandler, int lastEmbeddedObjectCount, Object obj,\n            MetamodelImpl metamodel)\n    {\n        Document currentDoc;\n        String elementCollectionObjectName = ecCacheHandler.getElementCollectionObjectName(rowKey, obj);\n        if (elementCollectionObjectName == null)\n        { // Fresh\n          // row\n            elementCollectionObjectName = attributeName + Constants.EMBEDDED_COLUMN_NAME_DELIMITER\n                    + (++lastEmbeddedObjectCount);\n        }\n\n        currentDoc = prepareDocumentForSuperColumn(metadata, entity, elementCollectionObjectName, parentId, clazz);\n        createSuperColumnDocument(metadata, entity, currentDoc, obj, embeddableAttribute, metamodel);\n        if (isUpdate)\n        {\n            updateDocument(parentId, currentDoc, null);\n        }\n        else\n        {\n            indexDocument(metadata, currentDoc);\n        }\n        return currentDoc;\n    }\n\n    /**\n     * On commit.\n     */\n    private void onCommit()\n    {\n        // TODO: Sadly this required to keep lucene happy, in case of indexing\n        // and searching with same entityManager.\n        // Other alternative would be to issue flush on each search\n        // try\n        // {\n        // w.commit();\n        isInitialized = true;\n        readyForCommit = true;\n        // }\n        // catch (CorruptIndexException e)\n        // {\n        // throw new IndexingException(e.getMessage());\n        // }\n        // catch (IOException e)\n        // {\n        // throw new IndexingException(e.getMessage());\n        // }\n        flushInternal();\n    }\n\n    @Override\n    public void index(Class entityClazz, EntityMetadata entityMetadata, Map<String, Object> values, Object parentId,\n            final Class parentClazz)\n    {\n        throw new UnsupportedOperationException(\"Method not supported\");\n    }\n\n    @Override\n    public void unIndex(Class entityClazz, Object entity, EntityMetadata metadata, MetamodelImpl metamodel)\n    {\n        throw new UnsupportedOperationException(\"Method not supported\");\n    }\n\n    @Override\n    public Map<String, Object> search(Class<?> clazz, EntityMetadata m, String luceneQuery, int start, int end)\n    {\n        throw new UnsupportedOperationException(\"Method not supported\");\n    }\n\n    private void copy(Directory src, Directory to) throws IOException\n    {\n        for (String file : src.listAll())\n        {\n            src.copyFrom(src, file, to.toString(), IOContext.DEFAULT);\n        }\n    }\n\n    /**\n     * Updates document.\n     * \n     * @param metadata\n     *            the metadata\n     * @param entity\n     *            the object\n     * @param parentId\n     *            the parent id\n     * @param clazz\n     *            the clazz\n     * @return the document\n     */\n    private void updateDocument(EntityMetadata metadata, final MetamodelImpl metaModel, Object entity, String parentId,\n            Class<? extends Object> class1, boolean b)\n    {\n        updateOrCreateIndex(metadata, metaModel, entity, parentId, entity.getClass(), true);\n        onCommit();\n    }\n\n    @Override\n    public Map<String, Object> search(KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery,\n            PersistenceDelegator persistenceDelegator, EntityMetadata m, int firstResult, int maxResults)\n    {\n        return null;\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/cache/ehcache/EhCacheProviderTest.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.cache.ehcache;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.Cache;\r\n\r\nimport junit.framework.TestCase;\r\n\r\nimport org.junit.Assert;\r\n\r\nimport com.impetus.kundera.cache.CacheException;\r\nimport com.impetus.kundera.entity.PersonnelDTO;\r\n\r\n/**\r\n * The Class EhCacheProviderTest.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class EhCacheProviderTest extends TestCase\r\n{\r\n\r\n    /** The cache provider. */\r\n    EhCacheProvider cacheProvider;\r\n\r\n    /** The cache resource. */\r\n    String cacheResource = \"/ehcache-test.xml\";\r\n\r\n    /** The cache name. */\r\n    String cacheName = \"Kundera\";\r\n\r\n    /** The person1. */\r\n    PersonnelDTO person1;\r\n\r\n    /** The person2. */\r\n    PersonnelDTO person2;\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see junit.framework.TestCase#setUp()\r\n     */\r\n    protected void setUp() throws Exception\r\n    {\r\n        super.setUp();\r\n\r\n        cacheProvider = new EhCacheProvider();\r\n\r\n        person1 = new PersonnelDTO(\"1\", \"Amresh\", \"Singh\");\r\n        person2 = new PersonnelDTO(\"2\", \"Vivek\", \"Mishra\");\r\n\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see junit.framework.TestCase#tearDown()\r\n     */\r\n    protected void tearDown() throws Exception\r\n    {\r\n        super.tearDown();\r\n        cacheProvider.shutdown();\r\n    }\r\n\r\n    /**\r\n     * Test method for.\r\n     * \r\n     * {@link com.impetus.kundera.cache.ehcache.EhCacheProvider#createCache(java.lang.String)}\r\n     * .\r\n     */\r\n    public void testCreateCache()\r\n    {\r\n        // Initialize Cache Provider\r\n        assertNotNull(cacheProvider);\r\n        try\r\n        {\r\n            cacheProvider.init(cacheResource);\r\n        }\r\n        catch (CacheException e)\r\n        {\r\n            fail(e.getMessage());\r\n        }\r\n\r\n        assertNotNull(cacheProvider.getCacheManager());\r\n\r\n        // Initialize Cache\r\n        Cache cache = null;\r\n        try\r\n        {\r\n            cache = cacheProvider.createCache(cacheName);\r\n        }\r\n        catch (CacheException e)\r\n        {\r\n            fail(e.getMessage());\r\n        }\r\n        assertNotNull(cache);\r\n        assertEquals(cache.getClass(), EhCacheWrapper.class);\r\n\r\n        EhCacheWrapper ehCache = (EhCacheWrapper) cache;\r\n\r\n        assertEquals(0, ehCache.size());\r\n\r\n        // Store objects into cache\r\n        ehCache.put(person1.getClass() + \"_\" + person1.getPersonId(), person1);\r\n        assertEquals(1, ehCache.size());\r\n        ehCache.put(person2.getClass() + \"_\" + person2.getPersonId(), person2);\r\n        assertEquals(2, ehCache.size());\r\n\r\n        // Lookup objects from cache\r\n        Object o = ehCache.get(person1.getClass() + \"_\" + person1.getPersonId());\r\n        assertEquals(PersonnelDTO.class, o.getClass());\r\n        PersonnelDTO p1 = (PersonnelDTO) o;\r\n        assertNotNull(p1);\r\n        assertEquals(\"1\", p1.getPersonId());\r\n        assertEquals(\"Amresh\", p1.getFirstName());\r\n        assertEquals(\"Singh\", p1.getLastName());\r\n\r\n        // Remove object from cache\r\n        ehCache.evict(PersonnelDTO.class, PersonnelDTO.class + \"_\" + person1.getPersonId());\r\n        assertEquals(1, ehCache.size());\r\n\r\n        cache = cacheProvider.getCache(cacheName);\r\n        Assert.assertNotNull(cache);\r\n\r\n        // Clear cache\r\n        cacheProvider.clearAll();\r\n        assertEquals(0, ehCache.size());\r\n\r\n        // trying when manager is not null.\r\n\r\n        Assert.assertNotNull(cacheProvider.getCacheManager());\r\n        try\r\n        {\r\n            Map map = new HashMap();\r\n            cacheProvider.init(map);\r\n        }\r\n        catch (CacheException e)\r\n        {\r\n            fail(e.getMessage());\r\n        }\r\n\r\n        // Shutting down.\r\n        cacheProvider.shutdown();\r\n\r\n        try\r\n        {\r\n            cache = cacheProvider.getCache(cacheName);\r\n        }\r\n        catch (Exception e)\r\n        {\r\n            Assert.assertEquals(\"CacheFactory was not initialized. Call init() before creating a cache.\",\r\n                    e.getMessage());\r\n        }\r\n        Assert.assertNotNull(cache);\r\n        Assert.assertNull(cacheProvider.getCacheManager());\r\n        // trying after manager is null.\r\n        try\r\n        {\r\n            Map map = new HashMap();\r\n            cacheProvider.init(map);\r\n        }\r\n        catch (CacheException e)\r\n        {\r\n            fail(e.getMessage());\r\n        }\r\n\r\n        // Shutting down.\r\n        cacheProvider.shutdown();\r\n        try\r\n        {\r\n            Map map = new HashMap();\r\n            map.put(\"net.sf.ehcache.configurationResourceName\", \"Kundera\");\r\n            cacheProvider.init(map);\r\n            Assert.assertNotNull(cacheProvider.getCacheManager());\r\n        }\r\n        catch (CacheException e)\r\n        {\r\n            fail(e.getMessage());\r\n        }\r\n\r\n        // Shutting down.\r\n        cacheProvider.shutdown();\r\n\r\n        try\r\n        {\r\n            Map map = new HashMap();\r\n            map.put(\"net.sf.ehcache.configurationResourceName\", null);\r\n            cacheProvider.init(map);\r\n            Assert.assertNotNull(cacheProvider.getCacheManager());\r\n        }\r\n        catch (CacheException e)\r\n        {\r\n            fail(e.getMessage());\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/cache/ehcache/EhcacheTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.impetus.kundera.cache.ehcache;\n\nimport java.lang.reflect.Field;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.cache.Cache;\nimport com.impetus.kundera.entity.EhCacheEntity;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.Person.Day;\n\n/**\n * Junit for ehcache.\n * \n * @author vivek.mishra\n * \n */\npublic class EhcacheTest\n{\n\n    private static final String PU = \"ehacheTest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    protected Map propertyMap = null;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(PU, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testDummy()\n    {\n        // do nothing.\n    }\n\n    // TODO:: enable it with #494.\n    // @Test\n    public void testEhCache()\n    {\n        EhCacheEntity entity1 = prepareData(\"1\", 32);\n        em.persist(entity1); // persist entity 1\n\n        EhCacheEntity entity2 = prepareData(\"2\", 32);\n        em.persist(entity2); // persist entity 1\n\n        Cache l2Cache = (Cache) em.getEntityManagerFactory().getCache();\n\n        PersistenceDelegator persistenceDelegator = null;\n        persistenceDelegator = getPersistenceDelegator(persistenceDelegator);\n\n        // get node from first level cache.\n        Node node1 = persistenceDelegator\n                .getPersistenceCache()\n                .getMainCache()\n                .getNodeFromCache(\n                        entity1,\n                        KunderaMetadataManager.getEntityMetadata(persistenceDelegator.getKunderaMetadata(),\n                                entity1.getClass()), persistenceDelegator);\n\n        // check if it is present in second level cache.\n        EhCacheEntity foundNode1 = (EhCacheEntity) l2Cache.get(node1.getNodeId());\n\n        Assert.assertNotNull(foundNode1);\n        Assert.assertEquals(foundNode1, node1.getData()); // should be same\n                                                          // object.\n\n        // remove entity 1.\n        em.remove(entity1);\n\n        Node node2 = persistenceDelegator\n                .getPersistenceCache()\n                .getMainCache()\n                .getNodeFromCache(\n                        entity2,\n                        KunderaMetadataManager.getEntityMetadata(persistenceDelegator.getKunderaMetadata(),\n                                entity1.getClass()), persistenceDelegator);\n\n        Assert.assertNotNull(l2Cache.get(node2.getNodeId()));\n\n        EhCacheEntity foundNode2 = (EhCacheEntity) l2Cache.get(node2.getNodeId());\n        Assert.assertEquals(foundNode2, node2.getData()); // should be same\n                                                          // object.\n        Assert.assertNull(l2Cache.get(node1.getNodeId()));\n\n        entity1.setAge(99);\n        em.persist(entity1);\n        em.flush();\n\n        // get node from first level cache.\n        node1 = persistenceDelegator\n                .getPersistenceCache()\n                .getMainCache()\n                .getNodeFromCache(\n                        entity1,\n                        KunderaMetadataManager.getEntityMetadata(persistenceDelegator.getKunderaMetadata(),\n                                entity1.getClass()), persistenceDelegator);\n\n        // check if it is present in second level cache.\n        foundNode1 = (EhCacheEntity) l2Cache.get(node1.getNodeId());\n\n        Assert.assertNotNull(foundNode1);\n        Assert.assertEquals(foundNode1, node1.getData()); // should be same\n                                                          // object.\n\n        Assert.assertEquals(foundNode1.getAge(), new Integer(99));\n        Assert.assertEquals(foundNode1.getAge(), entity1.getAge());\n\n        em.clear(); // evict all.\n\n        Assert.assertNull(l2Cache.get(node2.getNodeId()));\n\n    }\n\n    private PersistenceDelegator getPersistenceDelegator(PersistenceDelegator persistenceDelegator)\n    {\n        try\n        {\n            Field pd = em.getClass().getDeclaredField(\"persistenceDelegator\");\n\n            if (!pd.isAccessible())\n            {\n                pd.setAccessible(true);\n            }\n\n            persistenceDelegator = (PersistenceDelegator) pd.get(em);\n\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(\"Invalid configuration\");\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(\"Invalid configuration\");\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail(\"Invalid configuration\");\n        }\n        catch (IllegalAccessException e)\n        {\n            Assert.fail(\"Invalid configuration\");\n        }\n        return persistenceDelegator;\n    }\n\n    private EhCacheEntity prepareData(String rowKey, int age)\n    {\n        EhCacheEntity o = new EhCacheEntity();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age);\n        o.setDay(Day.THURSDAY);\n        return o;\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/entity/EhCacheEntity.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.impetus.kundera.entity;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\n\nimport com.impetus.kundera.query.Person.Day;\n\n/**\n *  eh cache entity\n * @author vivek.mishra\n *\n */\n@Entity\npublic class EhCacheEntity implements Serializable\n{\n\n    /**\n     * \n     */\n    private static final long serialVersionUID = 1L;\n\n    /** The person id. */\n    @Id\n    // @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"AGEss\")\n    private byte[] a;\n\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    public void setAge(Integer age)\n    {\n        this.age = age;\n    }\n\n    public byte[] getA()\n    {\n        return a;\n    }\n\n    public void setA(byte[] a)\n    {\n        this.a = a;\n    }\n\n    public Day getDay()\n    {\n        return day;\n    }\n\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/index/IndexManagerTest.java",
    "content": "package com.impetus.kundera.index;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.CoreTestClient;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.entities.EmbeddableEntity;\nimport com.impetus.kundera.metadata.entities.EmbeddableEntityTwo;\nimport com.impetus.kundera.metadata.entities.SingularEntityEmbeddable;\nimport com.impetus.kundera.metadata.model.Employe;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.PropertyIndex;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.query.CoreIndexer;\nimport com.impetus.kundera.query.Person;\nimport com.impetus.kundera.query.Person.Day;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\npublic class IndexManagerTest\n{\n\n    private static final String LUCENE_DIR_PATH = \"./lucene\";\n    \n    private EntityManagerFactory emf;\n    private EntityManager em;\n    Map propertyMap=null;\n\n    @Before\n    public void setup()\n    {\n        propertyMap=new HashMap<String, String>();\n        propertyMap.put(\"index.home.dir\",\"./lucene\");\n        emf = Persistence.createEntityManagerFactory(\"patest\",propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        LuceneIndexer indexer = LuceneIndexer.getInstance(LUCENE_DIR_PATH);\n        IndexManager ixManager = new IndexManager(indexer, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance(), Person.class);\n        Person p = new Person();\n        p.setAge(32);\n        p.setDay(Day.TUESDAY);\n        p.setPersonId(\"p1\");\n\n        Assert.assertNotNull(ixManager.getIndexer());\n        Assert.assertEquals(indexer, ixManager.getIndexer());\n        \n        ixManager.write(metadata, p);\n\n        String luceneQuery = \"+Person.AGE:32 AND +entity.class:com.impetus.kundera.query.Person\";\n\n        try\n        {\n            Map<String, Object> results = ixManager.search(metadata.getEntityClazz(), luceneQuery, 0, 10, false);\n            Assert.assertTrue(!results.isEmpty());\n        }\n        catch (LuceneIndexingException liex)\n        {\n            Assert.fail();\n        }\n\n        p.setAge(35);\n        \n        ixManager.update(metadata, p, null, Person.class);\n        luceneQuery = \"+Person.AGE:35 AND +entity.class:com.impetus.kundera.query.Person\";\n        \n        try\n        {\n            Map<String, Object> results = ixManager.search(metadata.getEntityClazz(), luceneQuery,1);\n            Assert.assertTrue(!results.isEmpty());\n        }\n        catch (LuceneIndexingException liex)\n        {\n            Assert.fail();\n        }\n        \n        // Remove indexes.\n        ixManager.remove(metadata, p, \"p1\");\n        \n        luceneQuery = \"+Person.AGE:32 AND +entity.class:com.impetus.kundera.query.Person\";\n        \n        try\n        {\n            Map<String, Object> results = ixManager.search(metadata.getEntityClazz(), luceneQuery, 0, 10, false);\n            Assert.assertTrue(results.isEmpty());\n        }\n        catch (LuceneIndexingException liex)\n        {\n            Assert.fail();\n        }\n    }\n\n\n    @Test\n    public void testEmbeddable()\n    {\n        LuceneIndexer indexer = LuceneIndexer.getInstance(LUCENE_DIR_PATH);\n        IndexManager ixManager = new IndexManager(indexer, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance(), SingularEntityEmbeddable.class);\n        SingularEntityEmbeddable entity = new SingularEntityEmbeddable();\n        entity.setKey(1);\n        entity.setName(\"entity\");\n        entity.setField(\"name\");\n        \n        EmbeddableEntity embed1 = new EmbeddableEntity();\n        embed1.setField(\"embeddedField1\");\n        \n        EmbeddableEntityTwo embed2 = new EmbeddableEntityTwo();\n        embed2.setField(1f);\n        embed2.setName(\"name\");\n\n        entity.setEmbeddableEntity(embed1);\n        entity.setEmbeddableEntityTwo(embed2);\n        \n        em.persist(entity);\n        \n        String luceneQuery = \"+entity.class:com.impetus.kundera.metadata.entities.SingularEntityEmbeddable AND +SingularEntityEmbeddable.embeddedField:embeddedField1\";\n        \n        Map<String, Object> results = ixManager.search(metadata.getEntityClazz(), luceneQuery, 0, 10, false);\n        \n        Assert.assertFalse(results.isEmpty());\n        \n    }\n    \n    @Test\n    public void testEmbeddableCustomIndexer()\n    {\n        try\n        {\n            CoreIndexer indexer = new CoreIndexer();\n            IndexManager ixManager = new IndexManager(indexer, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n            \n            Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n            CoreTestClient client = (CoreTestClient)clients.get(\"patest\");\n            client.setIndexManager(ixManager);\n\n            EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance(), SingularEntityEmbeddable.class);\n            SingularEntityEmbeddable entity = new SingularEntityEmbeddable();\n            entity.setKey(1);\n            entity.setName(\"entity\");\n            entity.setField(\"name\");\n            \n            EmbeddableEntity embed1 = new EmbeddableEntity();\n            embed1.setField(\"embeddedField1\");\n            \n            EmbeddableEntityTwo embed2 = new EmbeddableEntityTwo();\n            embed2.setField(1f);\n            embed2.setName(\"name\");\n\n            entity.setEmbeddableEntity(embed1);\n            entity.setEmbeddableEntityTwo(embed2);\n            \n            em.persist(entity);\n        }\n        catch (Exception e)\n        {\n            Assert.fail(e.getMessage());\n        }       \n    }\n    \n    @Test \n    public void testPropertyIndex()\n    {\n        try\n        {\n            PropertyIndex pi = new PropertyIndex(Employe.class.getDeclaredField(\"empName\"), \"EMP_NAME\", \"ASC\");\n            pi.setBoost(1.2f);\n            \n            Assert.assertEquals(1.2f, pi.getBoost());\n            Assert.assertEquals(\"ASC\", pi.getIndexType());            \n        }\n        catch (SecurityException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n    \n    @After\n    public void tearDown()\n    {\n        LuceneCleanupUtilities.cleanDir(LUCENE_DIR_PATH);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/index/LuceneIndexerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.index;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.query.Person;\nimport com.impetus.kundera.query.Person.Day;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * Junit for {@link LuceneIndexer}\n * \n * @author vivek.mishra\n * \n */\npublic class LuceneIndexerTest\n{\n    private EntityManagerFactory emf;\n\n    private static final String LUCENE_DIR_PATH = \"./lucene\";\n\n    @Before\n    public void setup()\n    {\n        emf = Persistence.createEntityManagerFactory(\"patest\");\n    }\n\n    @Test\n    public void testGetInstance()\n    {\n        LuceneIndexer indexer = LuceneIndexer.getInstance(LUCENE_DIR_PATH);\n        Assert.assertNotNull(indexer);\n        indexer.close();\n    }\n\n    @Test\n    public void testSearchWithNoResult()\n    {\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), Person.class);\n        \n        LuceneIndexer indexer = LuceneIndexer.getInstance(LUCENE_DIR_PATH);\n        Assert.assertNotNull(indexer);\n\n        String luceneQuery = LuceneQueryUtils.getQuery(\"addressId\", \"address\", \"addressId\", \"1\");\n\n        try\n        {\n            indexer.search(luceneQuery, 0, 10, false, ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), metadata);\n        }\n        catch (LuceneIndexingException liex)\n        {\n            Assert.assertNotNull(liex.getMessage()); // as there is no index\n                                                     // directory created.\n        }\n\n        indexer.close();\n    }\n\n    @Test\n    public void invalidLuceneQueryTest()\n    {\n        LuceneIndexer indexer = LuceneIndexer.getInstance(LUCENE_DIR_PATH);\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), Person.class);\n        Person p = new Person();\n        p.setAge(32);\n        p.setDay(Day.TUESDAY);\n        p.setPersonId(\"p1\");\n        indexer.index(metadata, (MetamodelImpl) ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance()\n                .getApplicationMetadata().getMetamodel(\"patest\"), p);\n        Assert.assertNotNull(indexer);\n\n        final String luceneQuery = \"Invalid lucene query\";\n        try\n        {\n            indexer.search(luceneQuery, 0, 10, false, ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), metadata);\n        }\n        catch (LuceneIndexingException liex)\n        {\n            Assert.assertEquals(\"Error while parsing Lucene Query \" + luceneQuery, liex.getMessage());\n        }\n\n        indexer.close();\n    }\n\n    @Test\n    public void invalidValidQueryTest()\n    {\n        LuceneIndexer indexer = LuceneIndexer.getInstance(LUCENE_DIR_PATH);\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), Person.class);\n        Person p = new Person();\n        p.setAge(32);\n        p.setDay(Day.TUESDAY);\n        p.setPersonId(\"p1\");\n        indexer.index(metadata, (MetamodelImpl) ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance()\n                .getApplicationMetadata().getMetamodel(\"patest\"), p);\n\n        indexer.flush();\n        Assert.assertNotNull(indexer);\n\n        String luceneQuery = \"+Person.AGE:32 AND +entity.class:com.impetus.kundera.query.Person\";\n\n        try\n        {\n            Map<String, Object> results = indexer.search(luceneQuery, 0, 10, false, ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), metadata);\n            Assert.assertTrue(!results.isEmpty());\n        }\n        catch (LuceneIndexingException liex)\n        {\n            Assert.fail();\n        }\n\n        indexer.close();\n    }\n\n    @Test\n    public void testOnUnsupportedMethods()\n    {\n        String luceneQuery = \"+Person.AGE:32 AND +entity.class:com.impetus.kundera.query.Person\";\n        Indexer indexer = LuceneIndexer.getInstance(LUCENE_DIR_PATH);\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), Person.class);\n        try\n        {\n            indexer.index(Person.class, m, null, null, null);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (UnsupportedOperationException uoex)\n        {\n            Assert.assertNotNull(uoex);\n        }\n\n        try\n        {\n            indexer.search(m.getEntityClazz(), m, luceneQuery, 0, 100);\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (UnsupportedOperationException uoex)\n        {\n            Assert.assertNotNull(uoex);\n        }\n\n        try\n        {\n            indexer.unIndex(Person.class, null, m, (MetamodelImpl) ((EntityManagerFactoryImpl) emf)\n                    .getKunderaMetadataInstance().getApplicationMetadata().getMetamodel(\"patest\"));\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (UnsupportedOperationException uoex)\n        {\n            Assert.assertNotNull(uoex);\n        }\n\n    }\n\n    @After\n    public void tearDown()\n    {\n        LuceneCleanupUtilities.cleanDir(LUCENE_DIR_PATH);\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/metadata/model/EntityMetadataTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.metadata.model;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.event.PersonEventDispatch;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class EntityMetadataTest\n{\n    private String persistenceUnit = \"metaDataTest\";\n\n    private EntityManagerFactoryImpl emf;\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = getEntityManagerFactory(null);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory(String property)\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(persistenceUnit);\n    }\n\n    @Test\n    public void testCallbackMethodsForLucene()\n    {\n        Map<String, Object> props = new HashMap<String, Object>();\n        props.put(\"index.home.dir\", \"lucene\");\n\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"kunderatest\", props);\n        EntityManager em = emf.createEntityManager();\n\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance(), PersonEventDispatch.class);\n        Assert.assertNotNull(m.toString());\n\n        PersonEventDispatch person = new PersonEventDispatch();\n        person.setFirstName(\"vivek\");\n        person.setLastName(\"mishra\");\n        person.setPersonId(\"1_p\");\n\n        em.persist(person);\n\n        em.clear();\n\n        PersonEventDispatch result = em.find(PersonEventDispatch.class, \"1_p\");\n        Assert.assertEquals(result.getLastName(), \"Post Load\");\n\n        onFindCallBack(em);\n        em.refresh(result);\n\n        Assert.assertEquals(result.getLastName(), \"Post Load\");\n\n        em.close();\n        emf.close();\n    }\n\n    private void onFindCallBack(EntityManager em)\n    {\n        String query = \"Select p from PersonEventDispatch p\";\n\n        Query q = em.createQuery(query);\n\n        List<PersonEventDispatch> results = q.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(1, results.size());\n    }\n\n    @Test\n    public void testColumn()\n    {\n        try\n        {\n            Column column = new Column(\"EMP_NAME\", Employe.class.getDeclaredField(\"empName\"));\n            column.setIndexable(true);\n            Assert.assertTrue(column.isIndexable());\n            Assert.assertEquals(\"empName\", column.getField().getName());\n            Assert.assertEquals(\"EMP_NAME\", column.getName());\n\n            column = new Column(\"AGE\", Employe.class.getDeclaredField(\"age\"), true);\n            Assert.assertTrue(column.isIndexable());\n            Assert.assertEquals(\"age\", column.getField().getName());\n            Assert.assertEquals(\"AGE\", column.getName());\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/persistence/EntityManagerSessionTest.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.persistence;\r\n\r\nimport junit.framework.TestCase;\r\n\r\nimport com.impetus.kundera.cache.Cache;\r\nimport com.impetus.kundera.cache.CacheProvider;\r\nimport com.impetus.kundera.entity.PersonnelDTO;\r\n\r\n/**\r\n * The Class EntityManagerSessionTest.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class EntityManagerSessionTest extends TestCase\r\n{\r\n\r\n    /** The ems. */\r\n    EntityManagerSession ems;\r\n\r\n    /** The cache provider. */\r\n    CacheProvider cacheProvider;\r\n\r\n    /** The cache. */\r\n    Cache cache;\r\n\r\n    /** The cache resource. */\r\n    String cacheResource = \"/ehcache-test.xml\";;\r\n\r\n    /** The cache provider class name. */\r\n    String cacheProviderClassName = \"com.impetus.kundera.cache.ehcache.EhCacheProvider\";\r\n\r\n    /** The person1. */\r\n    PersonnelDTO person1;\r\n\r\n    /** The person2. */\r\n    PersonnelDTO person2;\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see junit.framework.TestCase#setUp()\r\n     */\r\n    protected void setUp() throws Exception\r\n    {\r\n        super.setUp();\r\n\r\n        Class<CacheProvider> cacheProviderClass = (Class<CacheProvider>) Class.forName(cacheProviderClassName);\r\n        cacheProvider = cacheProviderClass.newInstance();\r\n        cacheProvider.init(cacheResource);\r\n\r\n        cache = (Cache) cacheProvider.createCache(\"Kundera\");\r\n        ems = new EntityManagerSession(cache);\r\n\r\n        person1 = new PersonnelDTO(\"1\", \"Amresh\", \"Singh\");\r\n        person2 = new PersonnelDTO(\"2\", \"Vivek\", \"Mishra\");\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see junit.framework.TestCase#tearDown()\r\n     */\r\n    protected void tearDown() throws Exception\r\n    {\r\n        super.tearDown();\r\n        ems.clear();\r\n        cacheProvider.shutdown();\r\n        cache = null;\r\n    }\r\n\r\n    /**\r\n     * Test.\r\n     */\r\n    public void test()\r\n    {\r\n        assertNotNull(ems);\r\n\r\n        // Store objects into session\r\n        ems.store(person1.getPersonId(), person1);\r\n        assertEquals(1, ems.getL2Cache().size());\r\n        ems.store(person2.getPersonId(), person2);\r\n        assertEquals(2, ems.getL2Cache().size());\r\n\r\n        // Lookup object from session\r\n        PersonnelDTO p1 = ems.lookup(PersonnelDTO.class, person1.getPersonId());\r\n        assertNotNull(p1);\r\n        assertEquals(person1.getPersonId(), p1.getPersonId());\r\n        assertEquals(person1.getFirstName(), p1.getFirstName());\r\n        assertEquals(person1.getLastName(), p1.getLastName());\r\n\r\n        // Remove object from session\r\n        ems.remove(PersonnelDTO.class, person1.getPersonId());\r\n        assertNotNull(ems);\r\n        assertEquals(1, ems.getL2Cache().size());\r\n\r\n        // Clear session\r\n        ems.clear();\r\n        assertNotNull(ems);\r\n        assertEquals(0, ems.getL2Cache().size());\r\n\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/persistence/EntityReaderTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.kundera.persistence;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.CoreTestUtilities;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.polyglot.entities.AddressB11FK;\nimport com.impetus.kundera.polyglot.entities.AddressB1M;\nimport com.impetus.kundera.polyglot.entities.AddressBM1;\nimport com.impetus.kundera.polyglot.entities.AddressU11FK;\nimport com.impetus.kundera.polyglot.entities.AddressU1M;\nimport com.impetus.kundera.polyglot.entities.AddressUM1;\nimport com.impetus.kundera.polyglot.entities.AddressUMM;\nimport com.impetus.kundera.polyglot.entities.PersonB11FK;\nimport com.impetus.kundera.polyglot.entities.PersonB1M;\nimport com.impetus.kundera.polyglot.entities.PersonBM1;\nimport com.impetus.kundera.polyglot.entities.PersonU11FK;\nimport com.impetus.kundera.polyglot.entities.PersonU1M;\nimport com.impetus.kundera.polyglot.entities.PersonUM1;\nimport com.impetus.kundera.polyglot.entities.PersonUMM;\nimport com.impetus.kundera.polyglot.entities.PersonUMMByMap;\nimport com.impetus.kundera.proxy.ProxyHelper;\nimport com.impetus.kundera.query.CoreTestEntityReader;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * @author vivek.mishra junit for {@link AbstractEntityReader}.\n * \n *         TODO: do not delete commented out code. some cases failing for\n *         lucene.\n */\npublic class EntityReaderTest\n{\n\n    private static final String PU = \"patest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private KunderaMetadata kunderaMetadata;\n    \n    Map propertyMap=null;\n    \n    Map<Object,Object> relationStack;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        propertyMap=new HashMap<String, String>();\n        propertyMap.put(\"index.home.dir\",\"./lucene\");\n        emf = Persistence.createEntityManagerFactory(PU,propertyMap);\n        kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n        em = emf.createEntityManager();\n        relationStack = new HashMap<Object, Object>();\n\n        \n    }\n\n    @Test\n    public void testOneToOne() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException\n    {\n        AddressU11FK address = new AddressU11FK();\n        address.setAddressId(\"addr1\");\n        address.setStreet(\"street\");\n\n        PersonU11FK p1 = new PersonU11FK();\n        p1.setPersonName(\"vivek\");\n        p1.setPersonId(\"1\");\n        p1.setAddress(address);\n\n        em.persist(p1);\n\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n\n        Map<String, Object> relationMap = new HashMap<String, Object>();\n        relationMap.put(\"ADDRESS_ID\", \"addr1\");\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonU11FK.class);\n\n        p1.setAddress(null);\n\n        CoreTestEntityReader reader = new CoreTestEntityReader(kunderaMetadata);\n\n        reader.recursivelyFindEntities(p1, relationMap, metadata, delegator, false, relationStack);\n\n        Assert.assertNotNull(p1.getAddress());\n\n        Assert.assertTrue(ProxyHelper.isKunderaProxy(p1.getAddress()));\n\n        p1.setAddress(null);\n\n        reader.recursivelyFindEntities(p1, relationMap, metadata, delegator, true, relationStack);\n\n        Assert.assertNotNull(p1.getAddress());\n\n        Assert.assertFalse(ProxyHelper.isKunderaProxy(p1.getAddress()));\n\n    }\n\n    @Test\n    public void testBiOneToOne() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException\n    {\n        AddressB11FK address = new AddressB11FK();\n        address.setAddressId(\"addr1\");\n        address.setStreet(\"street\");\n\n        PersonB11FK p1 = new PersonB11FK();\n        p1.setPersonName(\"vivek\");\n        p1.setPersonId(\"1\");\n        p1.setAddress(address);\n\n        em.persist(p1);\n\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n\n        Map<String, Object> relationMap = new HashMap<String, Object>();\n        relationMap.put(\"ADDRESS_ID\", \"addr1\");\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonB11FK.class);\n\n        p1.setAddress(null);\n\n        CoreTestEntityReader reader = new CoreTestEntityReader(kunderaMetadata);\n\n        reader.recursivelyFindEntities(p1, relationMap, metadata, delegator, false, relationStack);\n\n        Assert.assertNotNull(p1.getAddress());\n\n        Assert.assertTrue(ProxyHelper.isKunderaProxy(p1.getAddress()));\n\n        p1.setAddress(null);\n\n        reader.recursivelyFindEntities(p1, relationMap, metadata, delegator, true,relationStack);\n\n        Assert.assertNotNull(p1.getAddress());\n\n        Assert.assertFalse(ProxyHelper.isKunderaProxy(p1.getAddress()));\n\n        Assert.assertEquals(p1, p1.getAddress().getPerson());\n\n    }\n\n    @Test\n    public void testManyToOne() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException\n    {\n        PersonUM1 person1 = new PersonUM1();\n        person1.setPersonId(\"person1\");\n        person1.setPersonName(\"vivek\");\n\n        PersonUM1 person2 = new PersonUM1();\n        person2.setPersonId(\"person2\");\n        person2.setPersonName(\"vivek\");\n\n        AddressUM1 address = new AddressUM1();\n        address.setAddressId(\"addr1\");\n        address.setStreet(\"streetmto1\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n\n        Map<String, Object> relationMap = new HashMap<String, Object>();\n        relationMap.put(\"ADDRESS_ID\", \"addr1\");\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonUM1.class);\n\n        CoreTestEntityReader reader = new CoreTestEntityReader(kunderaMetadata);\n\n        person1.setAddress(null);\n\n        reader.recursivelyFindEntities(person1, relationMap, metadata, delegator, false,relationStack);\n\n        Assert.assertNotNull(person1.getAddress());\n\n        Assert.assertTrue(ProxyHelper.isKunderaProxy(person1.getAddress()));\n\n        person1.setAddress(null);\n\n        reader.recursivelyFindEntities(person1, relationMap, metadata, delegator, true,relationStack);\n\n        Assert.assertNotNull(person1.getAddress());\n\n        Assert.assertFalse(ProxyHelper.isKunderaProxy(person1.getAddress()));\n\n    }\n\n    @Test\n    public void testBiManyToOne() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException\n    {\n        PersonBM1 person1 = new PersonBM1();\n        person1.setPersonId(\"person1\");\n        person1.setPersonName(\"vivek\");\n\n        PersonBM1 person2 = new PersonBM1();\n        person2.setPersonId(\"person2\");\n        person2.setPersonName(\"vivek\");\n\n        AddressBM1 address = new AddressBM1();\n        address.setAddressId(\"addr1\");\n        address.setStreet(\"streetmto1\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n\n        Map<String, Object> relationMap = new HashMap<String, Object>();\n        relationMap.put(\"ADDRESS_ID\", \"addr1\");\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonBM1.class);\n\n        CoreTestEntityReader reader = new CoreTestEntityReader(kunderaMetadata);\n\n        person1.setAddress(null);\n\n        reader.recursivelyFindEntities(person1, relationMap, metadata, delegator, false,relationStack);\n\n        Assert.assertNotNull(person1.getAddress());\n\n        Assert.assertTrue(ProxyHelper.isKunderaProxy(person1.getAddress()));\n\n        // Assert.assertEquals(2, person1.getAddress().getPeople().size());\n\n        person1.setAddress(null);\n\n        reader.recursivelyFindEntities(person1, relationMap, metadata, delegator, true,relationStack);\n\n        Assert.assertNotNull(person1.getAddress());\n\n        Assert.assertFalse(ProxyHelper.isKunderaProxy(person1.getAddress()));\n        // Assert.assertEquals(2, person1.getAddress().getPeople().size());\n\n    }\n\n    @Test\n    public void testManyToMany() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException\n    {\n        PersonUMM person = new PersonUMM();\n        person.setPersonId(\"person1\");\n        person.setPersonName(\"personName\");\n\n        AddressUMM address = new AddressUMM();\n        address.setAddressId(\"addr1\");\n        address.setStreet(\"mtmstreet\");\n\n        Set<AddressUMM> addresses = new HashSet<AddressUMM>();\n        addresses.add(address);\n        person.setAddresses(addresses);\n\n        em.persist(person);\n\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n\n        Map<String, Object> relationMap = new HashMap<String, Object>();\n        relationMap.put(\"ADDRESS_ID\", \"addr1\");\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonUMM.class);\n\n        CoreTestEntityReader reader = new CoreTestEntityReader(kunderaMetadata);\n\n        person.setAddresses(null);\n\n        reader.recursivelyFindEntities(person, relationMap, metadata, delegator, false,relationStack);\n\n        Assert.assertNotNull(person.getAddresses());\n\n        Assert.assertTrue(ProxyHelper.isKunderaProxyCollection(person.getAddresses()));\n\n        reader.recursivelyFindEntities(person, relationMap, metadata, delegator, true,relationStack);\n\n        Assert.assertTrue(person.getAddresses().isEmpty()); // code to fetch\n                                                            // from join table\n                                                            // data in dummy\n                                                            // client is\n                                                            // missing.\n\n        // Assert.assertFalse(ProxyHelper.isKunderaProxyCollection(person.getAddresses()));\n\n    }\n\n    @Test\n    public void testManyToManyByMap() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException\n    {\n        PersonUMMByMap person = new PersonUMMByMap();\n        person.setPersonId(\"person1\");\n        person.setPersonName(\"personName\");\n\n        AddressUMM address = new AddressUMM();\n        address.setAddressId(\"addr1\");\n        address.setStreet(\"mtmstreet\");\n\n        Map<String, AddressUMM> addresses = new HashMap<String, AddressUMM>();\n        addresses.put(\"addr1\", address);\n\n        person.setAddresses(addresses);\n\n        em.persist(person);\n\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n\n        Map<String, Object> relationMap = new HashMap<String, Object>();\n        relationMap.put(\"ADDRESS_ID\", \"addr1\");\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonUMMByMap.class);\n\n        CoreTestEntityReader reader = new CoreTestEntityReader(kunderaMetadata);\n\n        person.setAddresses(null);\n\n        reader.recursivelyFindEntities(person, relationMap, metadata, delegator, false,relationStack);\n\n        Assert.assertNotNull(person.getAddresses());\n\n        Assert.assertTrue(ProxyHelper.isKunderaProxyCollection(person.getAddresses()));\n\n        reader.recursivelyFindEntities(person, relationMap, metadata, delegator, true,relationStack);\n\n        Assert.assertTrue(person.getAddresses().isEmpty()); // code to fetch\n                                                            // from join table\n                                                            // data in dummy\n                                                            // client is\n                                                            // missing.\n\n        // Assert.assertFalse(ProxyHelper.isKunderaProxyCollection(person.getAddresses()));\n\n    }\n\n    @Test\n    public void testOneToMany() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException\n    {\n        AddressU1M address1 = new AddressU1M();\n        address1.setAddressId(\"addr1\");\n        address1.setStreet(\"street\");\n\n        AddressU1M address2 = new AddressU1M();\n        address2.setAddressId(\"addr1\");\n        address2.setStreet(\"street\");\n\n        Set<AddressU1M> addressess = new HashSet<AddressU1M>();\n        addressess.add(address1);\n        addressess.add(address2);\n\n        PersonU1M p1 = new PersonU1M();\n        p1.setPersonName(\"vivek\");\n        p1.setPersonId(\"1\");\n        p1.setAddresses(addressess);\n\n        em.persist(p1);\n\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n\n        Map<String, Object> relationMap = null;\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonU1M.class);\n\n        CoreTestEntityReader reader = new CoreTestEntityReader(kunderaMetadata);\n\n        p1.setAddresses(null);\n        \n        reader.recursivelyFindEntities(p1, relationMap, metadata, delegator, false,relationStack);\n\n        Assert.assertNotNull(p1.getAddresses());\n\n        Assert.assertTrue(ProxyHelper.isKunderaProxyCollection(p1.getAddresses()));\n\n         p1.setAddresses(null);\n\n        reader.recursivelyFindEntities(p1, relationMap, metadata, delegator, true,relationStack);\n\n        Assert.assertNotNull(p1.getAddresses());\n\n        Assert.assertFalse(ProxyHelper.isKunderaProxyCollection(p1.getAddresses()));\n\n    }\n\n    @Test\n    public void testBiOneToMany() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException\n    {\n        AddressB1M address1 = new AddressB1M();\n        address1.setAddressId(\"addr1\");\n        address1.setStreet(\"street\");\n\n        AddressB1M address2 = new AddressB1M();\n        address2.setAddressId(\"addr1\");\n        address2.setStreet(\"street\");\n\n        Set<AddressB1M> addressess = new HashSet<AddressB1M>();\n        addressess.add(address1);\n        addressess.add(address2);\n\n        PersonB1M p1 = new PersonB1M();\n        p1.setPersonName(\"vivek\");\n        p1.setPersonId(\"1\");\n        p1.setAddresses(addressess);\n\n        em.persist(p1);\n\n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n\n        Map<String, Object> relationMap = null;\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonB1M.class);\n\n        CoreTestEntityReader reader = new CoreTestEntityReader(kunderaMetadata);\n\n        p1.setAddresses(null);\n\n        reader.recursivelyFindEntities(p1, relationMap, metadata, delegator, false,relationStack);\n\n        Assert.assertNotNull(p1.getAddresses());\n\n        Assert.assertTrue(ProxyHelper.isKunderaProxyCollection(p1.getAddresses()));\n        // Assert.assertEquals(p1,\n        // p1.getAddresses().iterator().next().getPerson());\n        // Assert.assertEquals(p1,\n        // p1.getAddresses().iterator().next().getPerson());\n\n        p1.setAddresses(null);\n\n        reader.recursivelyFindEntities(p1, relationMap, metadata, delegator, true,relationStack);\n\n        Assert.assertNotNull(p1.getAddresses());\n\n        Assert.assertFalse(ProxyHelper.isKunderaProxyCollection(p1.getAddresses()));\n\n        // Assert.assertEquals(p1,\n        // p1.getAddresses().iterator().next().getPerson());\n        // Assert.assertEquals(p1,\n        // p1.getAddresses().iterator().next().getPerson());\n    }\n\n    @After\n    public void tearDown()\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n\n        if (em != null)\n        {\n            em.close();\n        }\n\n\n        LuceneCleanupUtilities.cleanDir((String) propertyMap.get(PersistenceProperties.KUNDERA_INDEX_HOME_DIR));\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/persistence/JPAImplementationTestSuite.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.persistence;\r\n\r\nimport junit.framework.Test;\r\nimport junit.framework.TestSuite;\r\n\r\n/**\r\n * The Class JPAImplementationTestSuite.\r\n */\r\npublic class JPAImplementationTestSuite\r\n{\r\n\r\n    /**\r\n     * Suite.\r\n     * \r\n     * @return the test\r\n     */\r\n    public static Test suite()\r\n    {\r\n        TestSuite suite = new TestSuite(JPAImplementationTestSuite.class.getName());\r\n        // $JUnit-BEGIN$\r\n        suite.addTestSuite(EntityManagerSessionTest.class);\r\n\r\n        // TODO: add more test suites/ test cases here\r\n\r\n        // $JUnit-END$\r\n        return suite;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/polyglot/tests/MMBPolyglotTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.tests;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.polyglot.entities.AddressBMM;\nimport com.impetus.kundera.polyglot.entities.PersonBMM;\n\npublic class MMBPolyglotTest extends PersonAddressTestBase\n{\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n      super.init();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n       executeAllTests();\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonBMM person1 = new PersonBMM();\n        person1.setPersonId(\"bimanytomany_1\");\n        person1.setPersonName(\"Amresh\");\n\n        PersonBMM person2 = new PersonBMM();\n        person2.setPersonId(\"bimanytomany_2\");\n        person2.setPersonName(\"Vivek\");\n\n        AddressBMM address1 = new AddressBMM();\n        address1.setAddressId(\"bimanytomany_a\");\n        address1.setStreet(\"AAAAAAAAAAAAA\");\n\n        AddressBMM address2 = new AddressBMM();\n        address2.setAddressId(\"bimanytomany_b\");\n        address2.setStreet(\"BBBBBBBBBBBBBBB\");\n\n        AddressBMM address3 = new AddressBMM();\n        address3.setAddressId(\"bimanytomany_c\");\n        address3.setStreet(\"CCCCCCCCCCC\");\n\n        Set<AddressBMM> person1Addresses = new HashSet<AddressBMM>();\n        Set<AddressBMM> person2Addresses = new HashSet<AddressBMM>();\n\n        person1Addresses.add(address1);\n        person1Addresses.add(address2);\n\n        person2Addresses.add(address2);\n        person2Addresses.add(address3);\n\n        person1.setAddresses(person1Addresses);\n        person2.setAddresses(person2Addresses);\n\n        Set<PersonBMM> persons = new HashSet<PersonBMM>();\n        persons.add(person1);\n        persons.add(person2);\n\n        dao.savePersons(persons);\n     }\n\n    @Override\n    protected void find()\n    {\n        PersonBMM person1 = (PersonBMM) dao.findPerson(PersonBMM.class, \"bimanytomany_1\");\n        assertPerson1(person1);\n\n        PersonBMM person2 = (PersonBMM) dao.findPerson(PersonBMM.class, \"bimanytomany_2\");\n        assertPerson2(person2);\n\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        // Find Person 1\n        PersonBMM p1 = (PersonBMM) dao.findPersonByIdColumn(PersonBMM.class, \"bimanytomany_1\");\n        assertPerson1(p1);\n\n        // Find Person 2\n        PersonBMM p2 = (PersonBMM) dao.findPersonByIdColumn(PersonBMM.class, \"bimanytomany_2\");\n        assertPerson2(p2);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonBMM> persons = dao.findPersonByName(PersonBMM.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        assertPerson1(persons.get(0));\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n    }\n\n    @Override\n    protected void update()\n    {\n    }\n\n    @Override\n    protected void remove()\n    {\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.close();      \n    }\n\n    /**\n     * @param person2\n     */\n    private void assertPerson2(PersonBMM person2)\n    {\n        Assert.assertNotNull(person2);\n\n        Assert.assertEquals(\"bimanytomany_2\", person2.getPersonId());\n        Assert.assertEquals(\"Vivek\", person2.getPersonName());\n\n        Set<AddressBMM> addresses2 = person2.getAddresses();\n        Assert.assertNotNull(addresses2);\n        Assert.assertFalse(addresses2.isEmpty());\n        Assert.assertEquals(2, addresses2.size());\n        AddressBMM address21 = (AddressBMM) addresses2.toArray()[0];\n        Assert.assertNotNull(address21);\n        AddressBMM address22 = (AddressBMM) addresses2.toArray()[1];\n        Assert.assertNotNull(address22);\n    }\n\n    /**\n     * @param person1\n     */\n    private void assertPerson1(PersonBMM person1)\n    {\n        Assert.assertNotNull(person1);\n        Assert.assertEquals(\"bimanytomany_1\", person1.getPersonId());\n        Assert.assertEquals(\"Amresh\", person1.getPersonName());\n\n        Set<AddressBMM> addresses1 = person1.getAddresses();\n        Assert.assertNotNull(addresses1);\n        Assert.assertFalse(addresses1.isEmpty());\n        Assert.assertEquals(2, addresses1.size());\n        AddressBMM address11 = (AddressBMM) addresses1.toArray()[0];\n        Assert.assertNotNull(address11);\n        /*Assert.assertNotNull(address11.getPeople());\n        Assert.assertFalse(address11.getPeople().isEmpty());\n        AddressBMM address12 = (AddressBMM) addresses1.toArray()[1];\n        Assert.assertNotNull(address12.getPeople());\n        Assert.assertFalse(address12.getPeople().isEmpty());*/\n    }  \n\n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/polyglot/tests/MMUPolyglotTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.tests;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.polyglot.entities.AddressUMM;\nimport com.impetus.kundera.polyglot.entities.PersonUMM;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class MMUPolyglotTest extends PersonAddressTestBase\n{\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n       super.init();\n    }\n\n    /**\n     * Test insert.\n     */\n    @Test\n    public void testCRUD()\n    {\n       executeAllTests();\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonUMM person1 = new PersonUMM();\n        person1.setPersonId(\"unimanytomany_1\");\n        person1.setPersonName(\"Amresh\");\n\n        PersonUMM person2 = new PersonUMM();\n        person2.setPersonId(\"unimanytomany_2\");\n        person2.setPersonName(\"Vivek\");\n\n        AddressUMM address1 = new AddressUMM();\n        address1.setAddressId(\"unimanytomany_a\");\n        address1.setStreet(\"AAAAAAAAAAAAA\");\n\n        AddressUMM address2 = new AddressUMM();\n        address2.setAddressId(\"unimanytomany_b\");\n        address2.setStreet(\"BBBBBBBBBBBBBBB\");\n\n        AddressUMM address3 = new AddressUMM();\n        address3.setAddressId(\"unimanytomany_c\");\n        address3.setStreet(\"CCCCCCCCCCC\");\n\n        Set<AddressUMM> person1Addresses = new HashSet<AddressUMM>();\n        Set<AddressUMM> person2Addresses = new HashSet<AddressUMM>();\n\n        person1Addresses.add(address1);\n        person1Addresses.add(address2);\n\n        person2Addresses.add(address2);\n        person2Addresses.add(address3);\n\n        person1.setAddresses(person1Addresses);\n        person2.setAddresses(person2Addresses);\n\n        Set<PersonUMM> persons = new HashSet<PersonUMM>();\n        persons.add(person1);\n        persons.add(person2);\n\n        dao.savePersons(persons);\n      \n    }\n\n    @Override\n    protected void find()\n    {\n\n        PersonUMM person1 = (PersonUMM) dao.findPerson(PersonUMM.class, \"unimanytomany_1\");\n        assertPerson1(person1);\n\n        PersonUMM person2 = (PersonUMM) dao.findPerson(PersonUMM.class, \"unimanytomany_2\");\n        assertPerson2(person2);\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        // Find Person 1\n        PersonUMM p1 = (PersonUMM) dao.findPersonByIdColumn(PersonUMM.class, \"unimanytomany_1\");\n        assertPerson1(p1);\n\n        // Find Person 2\n        PersonUMM p2 = (PersonUMM) dao.findPersonByIdColumn(PersonUMM.class, \"unimanytomany_2\");\n        assertPerson2(p2);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonUMM> persons = dao.findPersonByName(PersonUMM.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        assertPerson1(persons.get(0));\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        AddressUMM a = (AddressUMM) dao.findAddressByIdColumn(AddressUMM.class, \"unimanytomany_a\");\n        assertAddressForPerson1(a);\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        List<AddressUMM> adds = dao.findAddressByStreet(AddressUMM.class, \"AAAAAAAAAAAAA\");\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertTrue(adds.size() == 1);\n\n        assertAddressForPerson1(adds.get(0));\n    }\n\n    @Override\n    protected void update()\n    {\n        PersonUMM p1 = (PersonUMM) dao.findPerson(PersonUMM.class, \"unimanytomany_1\");\n        Assert.assertNotNull(p1);\n        p1.setPersonName(\"Saurabh\");\n        Assert.assertEquals(2, p1.getAddresses().size());\n        for (AddressUMM address : p1.getAddresses())\n        {\n            address.setStreet(\"Brand New Street\");\n        }\n        dao.merge(p1);\n        PersonUMM p1AfterMerge = (PersonUMM) dao.findPerson(PersonUMM.class, \"unimanytomany_1\");\n        Assert.assertNotNull(p1AfterMerge);\n        Assert.assertEquals(\"Saurabh\", p1AfterMerge.getPersonName());\n        Assert.assertEquals(2, p1AfterMerge.getAddresses().size());\n        for (AddressUMM address : p1AfterMerge.getAddresses())\n        {\n            Assert.assertEquals(\"Brand New Street\", address.getStreet());\n        }\n\n        PersonUMM p2 = (PersonUMM) dao.findPerson(PersonUMM.class, \"unimanytomany_2\");\n        Assert.assertNotNull(p2);\n        Assert.assertEquals(2, p2.getAddresses().size());\n        p2.setPersonName(\"Vijay\");\n        for (AddressUMM address : p2.getAddresses())\n        {\n            address.setStreet(\"Brand New Street\");\n        }\n        dao.merge(p2);\n        PersonUMM p2AfterMerge = (PersonUMM) dao.findPerson(PersonUMM.class, \"unimanytomany_2\");\n        Assert.assertNotNull(p2AfterMerge);\n        Assert.assertEquals(\"Vijay\", p2AfterMerge.getPersonName());\n        Assert.assertEquals(2, p2AfterMerge.getAddresses().size());\n        for (AddressUMM address : p2AfterMerge.getAddresses())\n        {\n            Assert.assertEquals(\"Brand New Street\", address.getStreet());\n        }\n    }\n\n    @Override\n    protected void remove()\n    {\n        dao.remove(\"unimanytomany_1\", PersonUMM.class);\n        PersonUMM person1AfterRemoval = (PersonUMM) dao.findPerson(PersonUMM.class,\n                \"unimanytomany_1\");\n        Assert.assertNull(person1AfterRemoval);\n\n        dao.remove(\"unimanytomany_2\", PersonUMM.class);\n        PersonUMM person2AfterRemoval = (PersonUMM) dao.findPerson(PersonUMM.class,\n                \"unimanytomany_2\");\n        Assert.assertNull(person2AfterRemoval);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {       \n        super.close();\n    }\n\n    /**\n     * @param person1\n     */\n    private void assertPerson1(PersonUMM person1)\n    {\n        Assert.assertNotNull(person1);\n        Assert.assertEquals(\"unimanytomany_1\", person1.getPersonId());\n        Assert.assertEquals(\"Amresh\", person1.getPersonName());\n\n        Set<AddressUMM> addresses1 = person1.getAddresses();\n        Assert.assertNotNull(addresses1);\n        Assert.assertFalse(addresses1.isEmpty());\n        Assert.assertEquals(2, addresses1.size());\n        AddressUMM address11 = (AddressUMM) addresses1.toArray()[0];\n        assertAddressForPerson1(address11);\n        AddressUMM address12 = (AddressUMM) addresses1.toArray()[1];\n        assertAddressForPerson1(address12);\n    }\n\n    /**\n     * @param person2\n     */\n    private void assertPerson2(PersonUMM person2)\n    {\n        Assert.assertNotNull(person2);\n\n        Assert.assertEquals(\"unimanytomany_2\", person2.getPersonId());\n        Assert.assertEquals(\"Vivek\", person2.getPersonName());\n\n        Set<AddressUMM> addresses2 = person2.getAddresses();\n        Assert.assertNotNull(addresses2);\n        Assert.assertFalse(addresses2.isEmpty());\n        Assert.assertEquals(2, addresses2.size());\n        AddressUMM address21 = (AddressUMM) addresses2.toArray()[0];\n        assertAddressForPerson2(address21);\n        AddressUMM address22 = (AddressUMM) addresses2.toArray()[1];\n        assertAddressForPerson2(address22);\n    }\n\n    /**\n     * @param address11\n     */\n    private void assertAddressForPerson1(AddressUMM address)\n    {\n        Assert.assertNotNull(address);\n        Assert.assertTrue(\"unimanytomany_a\".equals(address.getAddressId())\n                || \"unimanytomany_b\".equals(address.getAddressId()));\n        Assert.assertTrue(\"AAAAAAAAAAAAA\".equals(address.getStreet()) || \"BBBBBBBBBBBBBBB\".equals(address.getStreet()));\n    }\n\n    /**\n     * @param address12\n     */\n    private void assertAddressForPerson2(AddressUMM address)\n    {\n        Assert.assertNotNull(address);\n\n        Assert.assertTrue(\"unimanytomany_b\".equals(address.getAddressId())\n                || \"unimanytomany_b\".equals(address.getAddressId()) || \"unimanytomany_c\".equals(address.getAddressId()));\n        Assert.assertTrue(\"CCCCCCCCCCC\".equals(address.getStreet()) || \"BBBBBBBBBBBBBBB\".equals(address.getStreet()));\n\n    }  \n\n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/polyglot/tests/MOBPolyglotTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.tests;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.polyglot.entities.AddressBM1;\nimport com.impetus.kundera.polyglot.entities.PersonBM1;\n\npublic class MOBPolyglotTest extends PersonAddressTestBase\n{\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n       super.init();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n       executeAllTests();\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonBM1 person1 = new PersonBM1();\n        person1.setPersonId(\"bimanytoone_1\");\n        person1.setPersonName(\"Amresh\");\n\n        PersonBM1 person2 = new PersonBM1();\n        person2.setPersonId(\"bimanytoone_2\");\n        person2.setPersonName(\"Vivek\");\n\n        AddressBM1 address = new AddressBM1();\n        address.setAddressId(\"bimanytoone_b\");\n        address.setStreet(\"AAAAAAAAAAAAA\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        Set<PersonBM1> persons = new HashSet<PersonBM1>();\n        persons.add(person1);\n        persons.add(person2);\n\n        dao.savePersons(persons);\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person 1\n        PersonBM1 p1 = (PersonBM1) dao.findPerson(PersonBM1.class, \"bimanytoone_1\");\n        assertPerson1(p1);\n\n        // Find Person 2\n        PersonBM1 p2 = (PersonBM1) dao.findPerson(PersonBM1.class, \"bimanytoone_2\");\n        assertPerson2(p2);\n\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonBM1 p = (PersonBM1) dao.findPersonByIdColumn(PersonBM1.class, \"bimanytoone_1\");\n        assertPerson1(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonBM1> persons = dao.findPersonByName(PersonBM1.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonBM1 person = persons.get(0);\n        assertPerson1(person);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n    }\n\n    @Override\n    protected void update()\n    {\n    }\n\n    @Override\n    protected void remove()\n    {\n    }\n\n    /**\n     * @param p2\n     */\n    private void assertPerson2(PersonBM1 p2)\n    {\n        Assert.assertNotNull(p2);\n        Assert.assertEquals(\"bimanytoone_2\", p2.getPersonId());\n        Assert.assertEquals(\"Vivek\", p2.getPersonName());\n\n        AddressBM1 add2 = p2.getAddress();\n        Assert.assertNotNull(add2);\n\n        Assert.assertEquals(\"bimanytoone_b\", add2.getAddressId());\n        Set<PersonBM1> people2 = add2.getPeople();\n        /*Assert.assertNotNull(people2);\n        Assert.assertFalse(people2.isEmpty());\n        Assert.assertEquals(2, people2.size());*/\n    }\n\n    /**\n     * @param p1\n     */\n    private void assertPerson1(PersonBM1 p1)\n    {\n        Assert.assertNotNull(p1);\n        Assert.assertEquals(\"bimanytoone_1\", p1.getPersonId());\n        Assert.assertEquals(\"Amresh\", p1.getPersonName());\n\n        AddressBM1 add = p1.getAddress();\n        Assert.assertNotNull(add);\n\n        Assert.assertEquals(\"bimanytoone_b\", add.getAddressId());\n        Set<PersonBM1> people = add.getPeople();\n        /*Assert.assertNotNull(people);\n        Assert.assertFalse(people.isEmpty());\n        Assert.assertEquals(2, people.size());*/\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n      super.close();\n    }\n\n   \n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/polyglot/tests/MOUPolyglotTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.tests;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.polyglot.entities.AddressUM1;\nimport com.impetus.kundera.polyglot.entities.PersonUM1;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class MOUPolyglotTest extends PersonAddressTestBase\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n      super.init();\n    }\n\n    /**\n     * Test CRUD.\n     */\n    @Test\n    public void testCRUD()\n    {\n      executeAllTests();\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonUM1 person1 = new PersonUM1();\n        person1.setPersonId(\"unimanytoone_1\");\n        person1.setPersonName(\"Amresh\");\n\n        PersonUM1 person2 = new PersonUM1();\n        person2.setPersonId(\"unimanytoone_2\");\n        person2.setPersonName(\"Vivek\");\n\n        AddressUM1 address = new AddressUM1();\n        address.setAddressId(\"unimanytoone_a\");\n        address.setStreet(\"AAAAAAAAAAAAA\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        Set<PersonUM1> persons = new HashSet<PersonUM1>();\n        persons.add(person1);\n        persons.add(person2);\n\n        dao.savePersons(persons);\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person 1\n        PersonUM1 p1 = (PersonUM1) dao.findPerson(PersonUM1.class, \"unimanytoone_1\");\n        assertPerson1(p1);\n\n        // Find Person 2\n        PersonUM1 p2 = (PersonUM1) dao.findPerson(PersonUM1.class, \"unimanytoone_2\");\n        assertPerson2(p2);\n\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonUM1 p = (PersonUM1) dao.findPersonByIdColumn(PersonUM1.class, \"unimanytoone_1\");\n        assertPerson1(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonUM1> persons = dao.findPersonByName(PersonUM1.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonUM1 person = persons.get(0);\n        assertPerson1(person);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        AddressUM1 a = (AddressUM1) dao.findAddressByIdColumn(AddressUM1.class, \"unimanytoone_a\");\n        assertAddress(a);\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        List<AddressUM1> adds = dao.findAddressByStreet(AddressUM1.class, \"AAAAAAAAAAAAA\");\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertTrue(adds.size() == 1);\n\n        assertAddress(adds.get(0));\n    }\n\n    @Override\n    protected void update()\n    {\n        // Find Person 1\n        PersonUM1 p1 = (PersonUM1) dao.findPerson(PersonUM1.class, \"unimanytoone_1\");\n        Assert.assertNotNull(p1);\n        p1.setPersonName(\"Saurabh\");\n        p1.getAddress().setStreet(\"Brand New Street\");\n        dao.merge(p1);\n        PersonUM1 p1AfterMerge = (PersonUM1) dao.findPerson(PersonUM1.class, \"unimanytoone_1\");\n        Assert.assertNotNull(p1AfterMerge);\n        Assert.assertEquals(\"Saurabh\", p1AfterMerge.getPersonName());\n        Assert.assertEquals(\"Brand New Street\", p1AfterMerge.getAddress().getStreet());\n\n        // Find Person 2\n        PersonUM1 p2 = (PersonUM1) dao.findPerson(PersonUM1.class, \"unimanytoone_2\");\n        Assert.assertNotNull(p2);\n        p2.setPersonName(\"Prateek\");\n        dao.merge(p2);\n        PersonUM1 p2AfterMerge = (PersonUM1) dao.findPerson(PersonUM1.class, \"unimanytoone_2\");\n        Assert.assertNotNull(p2AfterMerge);\n        Assert.assertEquals(\"Prateek\", p2AfterMerge.getPersonName());\n    }\n\n    @Override\n    protected void remove()\n    {\n        // Remove Person 1\n        dao.remove(\"unimanytoone_1\", PersonUM1.class);\n        PersonUM1 p1AfterRemoval = (PersonUM1) dao.findPerson(PersonUM1.class, \"unimanytoone_1\");\n        Assert.assertNull(p1AfterRemoval);\n\n        // Remove Person 2\n        dao.remove(\"unimanytoone_2\", PersonUM1.class);\n        PersonUM1 p2AfterRemoval = (PersonUM1) dao.findPerson(PersonUM1.class, \"unimanytoone_2\");\n        Assert.assertNull(p2AfterRemoval);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.close();\n    }\n\n    /**\n     * @param p2\n     */\n    private void assertPerson2(PersonUM1 p2)\n    {\n        Assert.assertNotNull(p2);\n        Assert.assertEquals(\"unimanytoone_2\", p2.getPersonId());\n        Assert.assertEquals(\"Vivek\", p2.getPersonName());\n\n        AddressUM1 add2 = p2.getAddress();\n        assertAddress(add2);\n    }\n\n    /**\n     * @param p1\n     */\n    private void assertPerson1(PersonUM1 p1)\n    {\n        Assert.assertNotNull(p1);\n        Assert.assertEquals(\"unimanytoone_1\", p1.getPersonId());\n        Assert.assertEquals(\"Amresh\", p1.getPersonName());\n\n        AddressUM1 add = p1.getAddress();\n        assertAddress(add);\n    }\n\n    /**\n     * @param add2\n     */\n    private void assertAddress(AddressUM1 add2)\n    {\n        Assert.assertNotNull(add2);\n\n        Assert.assertEquals(\"unimanytoone_a\", add2.getAddressId());\n        Assert.assertEquals(\"AAAAAAAAAAAAA\", add2.getStreet());\n    }\n\n   \n\n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/polyglot/tests/OMBPolyglotTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.tests;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.polyglot.entities.AddressB1M;\nimport com.impetus.kundera.polyglot.entities.PersonB1M;\n\npublic class OMBPolyglotTest extends PersonAddressTestBase\n{\n\n    @Before\n    public void setUp() throws Exception\n    {   \n        super.init();\n    }\n\n    /**\n     * Test insert.\n     */\n    @Test\n    public void testCRUD()\n    {\n       executeAllTests();\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonB1M personnel = new PersonB1M();\n        personnel.setPersonId(\"bionetomany_1\");\n        personnel.setPersonName(\"Amresh\");\n\n        Set<AddressB1M> addresses = new HashSet<AddressB1M>();\n        AddressB1M address1 = new AddressB1M();\n        address1.setAddressId(\"bionetomany_a\");\n        address1.setStreet(\"AAAAAAAAAAAAA\");\n\n        AddressB1M address2 = new AddressB1M();\n        address2.setAddressId(\"bionetomany_b\");\n        address2.setStreet(\"BBBBBBBBBBB\");\n\n        addresses.add(address1);\n        addresses.add(address2);\n        personnel.setAddresses(addresses);\n        dao.insert(personnel);\n     }\n\n    @Override\n    protected void find()\n    {\n        // Find Person\n        PersonB1M p = (PersonB1M) dao.findPerson(PersonB1M.class, \"bionetomany_1\");\n        assertPerson(p);\n\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonB1M p = (PersonB1M) dao.findPersonByIdColumn(PersonB1M.class, \"bionetomany_1\");\n        assertPerson(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonB1M> persons = dao.findPersonByName(PersonB1M.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonB1M person = persons.get(0);\n        assertPerson(person);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n    }\n\n    @Override\n    protected void update()\n    {\n        // Find Person\n        PersonB1M p = (PersonB1M) dao.findPerson(PersonB1M.class, \"bionetomany_1\");\n        assertPerson(p);\n\n        p.setPersonName(\"Saurabh\");\n        for (AddressB1M address : p.getAddresses())\n        {\n            address.setStreet(\"Brand New Street\");\n        }\n        dao.merge(p);\n        PersonB1M pAfterMerge = (PersonB1M) dao.findPerson(PersonB1M.class, \"bionetomany_1\");\n\n        assertPersonAfterUpdate(pAfterMerge);\n    }\n\n    @Override\n    protected void remove()\n    {\n        // Find Person\n        PersonB1M p = (PersonB1M) dao.findPerson(PersonB1M.class, \"bionetomany_1\");\n        assertPersonAfterUpdate(p);\n\n        dao.remove(\"bionetomany_1\", PersonB1M.class);\n        PersonB1M pAfterRemoval = (PersonB1M) dao.findPerson(PersonB1M.class, \"bionetomany_1\");\n        Assert.assertNull(pAfterRemoval);\n    }\n\n    private void assertPerson(PersonB1M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"bionetomany_1\", p.getPersonId());\n        Assert.assertEquals(\"Amresh\", p.getPersonName());\n\n        Set<AddressB1M> adds = p.getAddresses();\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertEquals(2, adds.size());\n\n        for (AddressB1M address : adds)\n        {\n            Assert.assertNotNull(address);\n            PersonB1M person = address.getPerson();\n            /*Assert.assertNotNull(person);\n            Assert.assertEquals(p.getPersonId(), person.getPersonId());\n            Assert.assertEquals(p.getPersonName(), person.getPersonName());\n            Assert.assertNotNull(person.getAddresses());\n            Assert.assertFalse(person.getAddresses().isEmpty());\n            Assert.assertEquals(2, person.getAddresses().size());*/\n        }\n    }\n\n    private void assertPersonAfterUpdate(PersonB1M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"bionetomany_1\", p.getPersonId());\n        Assert.assertEquals(\"Saurabh\", p.getPersonName());\n\n        Set<AddressB1M> adds = p.getAddresses();\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertEquals(2, adds.size());\n\n        for (AddressB1M address : adds)\n        {\n            Assert.assertNotNull(address);\n            Assert.assertEquals(\"Brand New Street\", address.getStreet());\n            PersonB1M person = address.getPerson();\n            /*Assert.assertNotNull(person);\n            Assert.assertEquals(p.getPersonId(), person.getPersonId());\n            Assert.assertEquals(p.getPersonName(), person.getPersonName());\n            Assert.assertNotNull(person.getAddresses());\n            Assert.assertFalse(person.getAddresses().isEmpty());\n            Assert.assertEquals(2, person.getAddresses().size());*/\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n      super.close();\n    }  \n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/polyglot/tests/OMUPolyglotTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.tests;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.polyglot.entities.AddressU1M;\nimport com.impetus.kundera.polyglot.entities.PersonU1M;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class OMUPolyglotTest extends PersonAddressTestBase\n{\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        super.init();\n    }\n\n    /**\n     * Test insert.\n     */\n    @Test\n    public void testCRUD()\n    {\n      executeAllTests();\n    }\n\n    @Override\n    protected void insert()\n    {\n        // Save Person\n        PersonU1M personnel = new PersonU1M();\n        personnel.setPersonId(\"unionetomany_1\");\n        personnel.setPersonName(\"Amresh\");\n\n        Set<AddressU1M> addresses = new HashSet<AddressU1M>();\n        AddressU1M address1 = new AddressU1M();\n        address1.setAddressId(\"unionetomany_a\");\n        address1.setStreet(\"AAAAAAAAAAAAA\");\n\n        AddressU1M address2 = new AddressU1M();\n        address2.setAddressId(\"unionetomany_b\");\n        address2.setStreet(\"BBBBBBBBBBB\");\n\n        addresses.add(address1);\n        addresses.add(address2);\n        personnel.setAddresses(addresses);\n        dao.insert(personnel);\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person\n        PersonU1M p = (PersonU1M) dao.findPerson(PersonU1M.class, \"unionetomany_1\");\n        assertPerson(p);\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonU1M p = (PersonU1M) dao.findPersonByIdColumn(PersonU1M.class, \"unionetomany_1\");\n        assertPerson(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonU1M> persons = dao.findPersonByName(PersonU1M.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonU1M person = persons.get(0);\n        assertPerson(person);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        AddressU1M a = (AddressU1M) dao.findAddressByIdColumn(AddressU1M.class, \"unionetomany_a\");\n        Assert.assertNotNull(a);\n        Assert.assertEquals(\"unionetomany_a\", a.getAddressId());\n        Assert.assertEquals(\"AAAAAAAAAAAAA\", a.getStreet());\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        List<AddressU1M> adds = dao.findAddressByStreet(AddressU1M.class, \"AAAAAAAAAAAAA\");\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertTrue(adds.size() == 1);\n\n        AddressU1M a = adds.get(0);\n        Assert.assertNotNull(a);\n        Assert.assertEquals(\"unionetomany_a\", a.getAddressId());\n        Assert.assertEquals(\"AAAAAAAAAAAAA\", a.getStreet());\n    }\n\n    @Override\n    protected void update()\n    {\n        try\n        {\n            PersonU1M p = (PersonU1M) dao.findPerson(PersonU1M.class, \"unionetomany_1\");\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getAddresses().size());\n            p.setPersonName(\"Saurabh\");\n\n            for (AddressU1M address : p.getAddresses())\n            {\n                address.setStreet(\"Brand New Street\");\n            }\n            dao.merge(p);\n            assertPersonAfterUpdate();\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail();\n        }\n    }\n\n    @Override\n    protected void remove()\n    {\n        try\n        {\n            // PersonU1M p = (PersonU1M)\n            // dao.findPerson(PersonU1M.class, );\n            dao.remove(\"unionetomany_1\", PersonU1M.class);\n            PersonU1M pAfterRemoval = (PersonU1M) dao\n                    .findPerson(PersonU1M.class, \"unionetomany_1\");\n            Assert.assertNull(pAfterRemoval);\n\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail();\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {    \n        super.close();\n    }\n\n    /**\n     * @param p\n     */\n    private void assertPerson(PersonU1M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"unionetomany_1\", p.getPersonId());\n        Assert.assertEquals(\"Amresh\", p.getPersonName());\n\n        Set<AddressU1M> adds = p.getAddresses();\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertEquals(2, adds.size());\n\n        for (AddressU1M address : adds)\n        {\n            Assert.assertNotNull(address.getStreet());\n        }\n    }\n\n    /**\n     * \n     */\n    private void assertPersonAfterUpdate()\n    {\n        PersonU1M pAfterMerge = (PersonU1M) dao.findPerson(PersonU1M.class, \"unionetomany_1\");\n        Assert.assertNotNull(pAfterMerge);\n        Assert.assertEquals(\"Saurabh\", pAfterMerge.getPersonName());\n        Assert.assertEquals(2, pAfterMerge.getAddresses().size());\n\n        for (AddressU1M address : pAfterMerge.getAddresses())\n        {\n            Assert.assertEquals(\"Brand New Street\", address.getStreet());\n        }\n    }  \n\n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/polyglot/tests/OOBPolyglotTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.tests;\n\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.polyglot.entities.AddressB11FK;\nimport com.impetus.kundera.polyglot.entities.PersonB11FK;\n\npublic class OOBPolyglotTest extends PersonAddressTestBase\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.init();    \n    }\n\n    /**\n     * Test CRUD\n     */\n    @Test\n    public void testCRUD()\n    {\n      executeAllTests();\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonB11FK person = new PersonB11FK();\n        person.setPersonId(\"bionetoonefk_1\");\n        person.setPersonName(\"Amresh\");\n\n        AddressB11FK address = new AddressB11FK();\n        address.setAddressId(\"bionetoonefk_a\");\n        address.setStreet(\"123, New street\");\n        person.setAddress(address);\n        address.setPerson(person);\n\n        dao.insert(person);\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person\n        PersonB11FK p = (PersonB11FK) dao.findPerson(PersonB11FK.class, \"bionetoonefk_1\");\n        assertPersonnel(p);       \n \n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonB11FK p = (PersonB11FK) dao.findPersonByIdColumn(PersonB11FK.class, \"bionetoonefk_1\");\n        assertPersonnel(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonB11FK> persons = dao.findPersonByName(PersonB11FK.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        assertPersonnel(persons.get(0));\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        /*\n         * AddressB11FK a = (AddressB11FK)\n         * dao.findAddressByIdColumn(AddressB11FK.class, \"bionetoonefk_a\");\n         * assertAddress(a);\n         */\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        /*\n         * List<AddressB11FK> adds =\n         * dao.findAddressByStreet(AddressB11FK.class, \"123, New street\");\n         * Assert.assertNotNull(adds); Assert.assertFalse(adds.isEmpty());\n         * Assert.assertTrue(adds.size() == 1);\n         * \n         * assertAddress(adds.get(0));\n         */\n    }\n\n    @Override\n    protected void update()\n    {\n        try\n        {\n            PersonB11FK p = (PersonB11FK) dao.findPerson(PersonB11FK.class, \"bionetoonefk_1\");\n            assertPersonnel(p);\n\n            dao.merge(p); // This merge operation should do nothing since\n                          // nothing has changed\n\n            p = (PersonB11FK) dao.findPerson(PersonB11FK.class, \"bionetoonefk_1\");\n            assertPersonnel(p);\n\n            p.setPersonName(\"Saurabh\");\n            p.getAddress().setStreet(\"Brand New Street\");\n            dao.merge(p);\n\n            PersonB11FK pAfterMerge = (PersonB11FK) dao.findPerson(PersonB11FK.class,\n                    \"bionetoonefk_1\");\n            assertPersonnelAfterUpdate(pAfterMerge);\n\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail();\n        }\n    }\n\n    @Override\n    protected void remove()\n    {\n        PersonB11FK p = (PersonB11FK) dao.findPerson(PersonB11FK.class, \"bionetoonefk_1\");\n        assertPersonnelAfterUpdate(p);\n\n        dao.remove(\"bionetoonefk_1\", PersonB11FK.class);\n\n        PersonB11FK pAfterRemoval = (PersonB11FK) dao.findPerson(PersonB11FK.class, \"bionetoonefk_1\");\n        Assert.assertNull(pAfterRemoval);\n    }\n\n    private void assertPersonnel(PersonB11FK p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"bionetoonefk_1\", p.getPersonId());\n        Assert.assertEquals(\"Amresh\", p.getPersonName());\n\n        AddressB11FK address = p.getAddress();       \n        assertAddress(address);\n    }\n\n    /**\n     * @param address\n     */\n    private void assertAddress(AddressB11FK address)\n    {\n        Assert.assertNotNull(address);\n        Assert.assertEquals(\"bionetoonefk_a\", address.getAddressId());\n        Assert.assertEquals(\"123, New street\", address.getStreet());\n\n        PersonB11FK pp = address.getPerson();\n        Assert.assertNotNull(pp);\n        Assert.assertEquals(\"bionetoonefk_1\", pp.getPersonId());\n        Assert.assertEquals(\"Amresh\", pp.getPersonName());\n    }\n\n    private void assertPersonnelAfterUpdate(PersonB11FK pAfterMerge)\n    {\n        Assert.assertNotNull(pAfterMerge);\n        Assert.assertEquals(\"Saurabh\", pAfterMerge.getPersonName());\n        AddressB11FK addressAfterMerge = pAfterMerge.getAddress();\n        Assert.assertNotNull(addressAfterMerge);\n        Assert.assertEquals(\"Brand New Street\", addressAfterMerge.getStreet());\n\n        PersonB11FK pp = addressAfterMerge.getPerson();\n        Assert.assertNotNull(pp);\n        Assert.assertEquals(\"bionetoonefk_1\", pp.getPersonId());\n        Assert.assertEquals(\"Saurabh\", pp.getPersonName());\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {    \n        super.close();\n    }\n   \n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/polyglot/tests/OOUPolyglotTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.tests;\n\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.polyglot.entities.AddressU11FK;\nimport com.impetus.kundera.polyglot.entities.PersonU11FK;\n\n/**\n\n */\npublic class OOUPolyglotTest extends PersonAddressTestBase\n{\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        super.init();\n    }\n\n    /**\n     * Test CRUD\n     */\n    @Test\n    public void testCRUD()\n    {\n       executeAllTests();\n    }\n\n    protected void insert()\n    {\n        try\n        {\n            PersonU11FK person = new PersonU11FK();\n            AddressU11FK address = new AddressU11FK();\n            person.setPersonId(\"unionetoonefk_1\");\n            person.setPersonName(\"Amresh\");\n            address.setAddressId(\"unionetoonefk_a\");\n            address.setStreet(\"123, New street\");\n            person.setAddress(address);\n            dao.insert(person);\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail();\n        }\n    }\n\n    protected void find()\n    {\n        // Find Person\n        try\n        {\n            PersonU11FK p = (PersonU11FK) dao.findPerson(PersonU11FK.class, \"unionetoonefk_1\");\n            assertPersonBeforeUpdate(p);\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail();\n        }\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonU11FK p = (PersonU11FK) dao.findPersonByIdColumn(PersonU11FK.class,\n                \"unionetoonefk_1\");\n        assertPersonBeforeUpdate(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonU11FK> persons = dao.findPersonByName(PersonU11FK.class, \"Amresh\");\n        assertPersons(persons);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        AddressU11FK a = (AddressU11FK) dao.findAddressByIdColumn(AddressU11FK.class, \"unionetoonefk_a\");\n        assertAddressBeforeUpdate(a);\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        List<AddressU11FK> adds = dao.findAddressByStreet(AddressU11FK.class, \"123, New street\");\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertTrue(adds.size() == 1);\n\n        assertAddressBeforeUpdate(adds.get(0));\n    }\n\n    protected void update()\n    {\n        try\n        {\n            PersonU11FK p = (PersonU11FK) dao.findPerson(PersonU11FK.class, \"unionetoonefk_1\");\n            Assert.assertNotNull(p);\n            p.setPersonName(\"Saurabh\");\n            AddressU11FK address = p.getAddress();\n            address.setStreet(\"Brand New Street\");\n            p.setAddress(address);\n            dao.merge(p);\n\n            PersonU11FK pAfterMerge = (PersonU11FK) dao.findPerson(PersonU11FK.class,\n                    \"unionetoonefk_1\");\n            assertPersonAfterUpdate(pAfterMerge);\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail();\n        }\n    }\n\n    protected void remove()\n    {\n        try\n        {\n            PersonU11FK p = (PersonU11FK) dao.findPerson(PersonU11FK.class, \"unionetoonefk_1\");\n            Assert.assertNotNull(p);\n            dao.remove(\"unionetoonefk_1\", PersonU11FK.class);\n\n            PersonU11FK pAfterRemoval = (PersonU11FK) dao.findPerson(PersonU11FK.class,\n                    \"unionetoonefk_1\");\n            Assert.assertNull(pAfterRemoval);\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail();\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.close();\n    }\n\n\n    /**\n     * @param p\n     */\n    private void assertPersonBeforeUpdate(PersonU11FK p)\n    {\n        Assert.assertNotNull(p);\n\n        Assert.assertEquals(\"unionetoonefk_1\", p.getPersonId());\n        Assert.assertEquals(\"Amresh\", p.getPersonName());\n\n        assertAddressBeforeUpdate(p.getAddress());\n    }\n\n    /**\n     * @param p\n     */\n    private void assertAddressBeforeUpdate(AddressU11FK add)\n    {\n        Assert.assertNotNull(add);\n\n        String addressId = add.getAddressId();\n        String street = add.getStreet();\n\n        Assert.assertNotNull(addressId);\n        Assert.assertEquals(\"unionetoonefk_a\", addressId);\n        Assert.assertEquals(\"123, New street\", street);\n    }\n\n    /**\n     * @param pAfterMerge\n     */\n    private void assertPersonAfterUpdate(PersonU11FK pAfterMerge)\n    {\n        Assert.assertNotNull(pAfterMerge);\n        Assert.assertEquals(\"Saurabh\", pAfterMerge.getPersonName());\n        AddressU11FK addressAfterMerge = pAfterMerge.getAddress();\n        Assert.assertNotNull(addressAfterMerge);\n        Assert.assertEquals(\"Brand New Street\", addressAfterMerge.getStreet());\n    }\n\n    /**\n     * @param persons\n     */\n    private void assertPersons(List<PersonU11FK> persons)\n    {\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonU11FK person = persons.get(0);\n        assertPersonBeforeUpdate(person);\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/polyglot/tests/PersonAddressTestBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.polyglot.tests;\n\nimport com.impetus.kundera.client.DummyDatabase;\nimport com.impetus.kundera.polyglot.dao.PersonAddressDaoImpl;\n\n/**\n * @author amresh.singh\n *\n */\npublic abstract class PersonAddressTestBase\n{  \n    PersonAddressDaoImpl dao;\n    String pu = \"patest\";\n    \n    protected void init()\n    {\n        dao = new PersonAddressDaoImpl(pu);\n    }\n    \n    protected void close()\n    {\n        dao.closeEntityManagerFactory();\n        dao = null;\n        \n        DummyDatabase.INSTANCE.dropDatabase();\n    }\n    \n    /** Insert person with address */\n    protected abstract void insert();\n\n    /** Find person by ID */\n    protected abstract void find();\n\n    /** Find person by ID using query */\n    protected abstract void findPersonByIdColumn();\n\n    /** Find person by name using query */\n    protected abstract void findPersonByName();\n\n    /** Find Address by ID using query */\n    protected abstract void findAddressByIdColumn();\n\n    /** Find Address by street using query */\n    protected abstract void findAddressByStreet();\n\n    /** Update Person */\n    protected abstract void update();\n\n    /** Remove Person */\n    protected abstract void remove();\n    \n    protected void executeAllTests()\n    {\n      insert();\n      find();\n      findPersonByIdColumn();\n      findPersonByName();\n      findAddressByIdColumn();\n      //findAddressByStreet();\n      update();\n      remove();\n    }\n\n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/query/LuceneQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.entities.EmbeddableEntity;\nimport com.impetus.kundera.metadata.entities.EmbeddableEntityTwo;\nimport com.impetus.kundera.metadata.entities.SingularEntityEmbeddable;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.query.Person.Day;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * @author vivek.mishra Junit test case for invalid lucene query scenarios. Rest\n *         are tested via EM and persistence delegator.\n */\npublic class LuceneQueryTest\n{\n    private static final String LUCENE_DIR_PATH = \"./lucene\";\n\n    private static final String PU = \"patest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    Map propertyMap = new HashMap<String, String>();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        propertyMap.put(\"index.home.dir\", \"./lucene\");\n        emf = Persistence.createEntityManagerFactory(PU, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void test()\n    {\n        String query = \"Select p from Person p\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query,\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n\n        LuceneQuery luceneQuery = new LuceneQuery(kunderaQuery, null,\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n\n        try\n        {\n            luceneQuery.populateEntities(null, null);\n        }\n        catch (UnsupportedOperationException uoex)\n        {\n            Assert.assertEquals(\"Method not supported for Lucene indexing\", uoex.getMessage());\n        }\n\n        try\n        {\n            luceneQuery.recursivelyPopulateEntities(null, null);\n        }\n        catch (UnsupportedOperationException uoex)\n        {\n            Assert.assertEquals(\"Method not supported for Lucene indexing\", uoex.getMessage());\n        }\n\n        try\n        {\n            luceneQuery.getReader();\n        }\n        catch (UnsupportedOperationException uoex)\n        {\n            Assert.assertEquals(\"Method not supported for Lucene indexing\", uoex.getMessage());\n        }\n\n        Assert.assertEquals(0, luceneQuery.onExecuteUpdate());\n    }\n\n    @Test\n    public void testOnWhereClause()\n    {\n\n        Person p1 = new Person();\n        p1.setAge(32);\n        p1.setDay(Day.TUESDAY);\n        p1.setPersonId(\"p1\");\n        p1.setSalary(6000.345);\n\n        em.persist(p1);\n        em.clear();\n\n        Person p2 = new Person();\n        p2.setAge(24);\n        p2.setDay(Day.MONDAY);\n        p2.setPersonId(\"p2\");\n        p2.setSalary(8000.345);\n\n        em.persist(p2);\n        em.clear();\n\n        String query = \"Select p from Person p WHERE p.salary > 500.0\";\n        Query findQuery = em.createQuery(query, Person.class);\n        List<Person> allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(2, allPersons.size());\n\n        query = \"Select p from Person p WHERE p.salary >= 500.0\";\n        findQuery = em.createQuery(query, Person.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(2, allPersons.size());\n\n        query = \"Select p from Person p WHERE p.salary = 6000.345\";\n        findQuery = em.createQuery(query, Person.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(1, allPersons.size());\n\n        query = \"Select p from Person p WHERE p.salary <= 7000.345\";\n        findQuery = em.createQuery(query, Person.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(1, allPersons.size());\n        Assert.assertEquals(new Integer(32), allPersons.get(0).getAge());\n\n        query = \"Select p from Person p WHERE p.salary < 7000.345\";\n        findQuery = em.createQuery(query, Person.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(1, allPersons.size());\n        Assert.assertEquals(new Integer(32), allPersons.get(0).getAge());\n\n        query = \"Select p from Person p WHERE p.salary < 6000.345\";\n        findQuery = em.createQuery(query, Person.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertEquals(0, allPersons.size());\n\n        query = \"Select p from Person p WHERE p.salary < 6000.345\";\n        findQuery = em.createQuery(query, Person.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertEquals(0, allPersons.size());\n\n        query = \"Select p from Person p WHERE p.salary > -2000\";\n        findQuery = em.createQuery(query, Person.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertEquals(2, allPersons.size());\n\n        query = \"Select p from Person p WHERE p.salary = -200.00\";\n        findQuery = em.createQuery(query, Person.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertEquals(0, allPersons.size());\n\n        query = \"Select p from Person p WHERE p.salary >= -200.00\";\n        findQuery = em.createQuery(query, Person.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertEquals(2, allPersons.size());\n\n        query = \"Select p from Person p WHERE p.salary < -400.00\";\n        findQuery = em.createQuery(query, Person.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertEquals(0, allPersons.size());\n\n        query = \"Select p from Person p WHERE p.salary <> 6000.345\";\n        findQuery = em.createQuery(query, Person.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertEquals(1, allPersons.size());\n        Assert.assertEquals(\"p2\", allPersons.get(0).getPersonId());\n        Assert.assertEquals(new Integer(24), allPersons.get(0).getAge());\n\n        query = \"Select p from Person p WHERE p.salary in (2000.415, 6000.345)\";\n        findQuery = em.createQuery(query, Person.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertEquals(1, allPersons.size());\n        Assert.assertEquals(\"p1\", allPersons.get(0).getPersonId());\n        Assert.assertEquals(new Integer(32), allPersons.get(0).getAge());\n\n        em.remove(em.find(Person.class, \"p1\"));\n        em.remove(em.find(Person.class, \"p2\"));\n    }\n\n    @Test\n    public void testOnUpdate()\n    {\n\n        Person p1 = new Person();\n        p1.setPersonName(\"vivek\");\n        p1.setAge(32);\n        p1.setDay(Day.TUESDAY);\n        p1.setPersonId(\"p1\");\n        p1.setSalary(6000.345);\n\n        em.persist(p1);\n        em.clear();\n\n        Person p = em.find(Person.class, \"p1\");\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        p.setAge(12);\n        p.setPersonName(\"newvivek\");\n\n        em.merge(p);\n        em.clear();\n\n        Query findQuery = em.createQuery(\"Select p from Person p WHERE p.personName = vivek\");\n        List<Person> allPersons = findQuery.getResultList();\n        Assert.assertEquals(0, allPersons.size());\n\n        findQuery = em.createQuery(\"Select p from Person p WHERE p.personName = newvivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertEquals(new Integer(12), allPersons.get(0).getAge());\n\n        em.remove(em.find(Person.class, \"p1\"));\n    }\n\n    @Test\n    public void testEmbeddable()\n    {\n\n        SingularEntityEmbeddable entity = new SingularEntityEmbeddable();\n        entity.setKey(1);\n        entity.setName(\"entity\");\n        entity.setField(\"name\");\n\n        EmbeddableEntity embed1 = new EmbeddableEntity();\n        embed1.setField(\"embeddedField1\");\n\n        EmbeddableEntityTwo embed2 = new EmbeddableEntityTwo();\n        embed2.setField(1f);\n        embed2.setName(\"name\");\n\n        entity.setEmbeddableEntity(embed1);\n        entity.setEmbeddableEntityTwo(embed2);\n\n        em.persist(entity);\n\n        SingularEntityEmbeddable p = em.find(SingularEntityEmbeddable.class, 1);\n        Assert.assertNotNull(p);\n        p.getEmbeddableEntity().setField(\"embeddedFieldChange\");\n\n        em.merge(p);\n\n        p = em.find(SingularEntityEmbeddable.class, 1);\n        Assert.assertEquals(\"embeddedFieldChange\", p.getEmbeddableEntity().getField());\n\n        em.remove(em.find(SingularEntityEmbeddable.class, 1));\n\n    }\n\n    @Test\n    public void testCollection()\n    {\n\n        SingularEntityEmbeddable entity = new SingularEntityEmbeddable();\n        entity.setKey(1);\n        entity.setName(\"entity\");\n        entity.setField(\"name\");\n\n        EmbeddableEntity embed1 = new EmbeddableEntity();\n        embed1.setField(\"embeddedField1\");\n\n        EmbeddableEntityTwo embed2 = new EmbeddableEntityTwo();\n        embed2.setField(1f);\n        embed2.setName(\"name\");\n\n        entity.setEmbeddableEntity(embed1);\n        entity.setEmbeddableEntityTwo(embed2);\n\n        em.persist(entity);\n\n        SingularEntityEmbeddable p = em.find(SingularEntityEmbeddable.class, 1);\n        Assert.assertNotNull(p);\n        p.getEmbeddableEntity().setField(\"embeddedFieldChange\");\n\n        em.merge(p);\n\n        p = em.find(SingularEntityEmbeddable.class, 1);\n        Assert.assertEquals(\"embeddedFieldChange\", p.getEmbeddableEntity().getField());\n\n        em.remove(em.find(SingularEntityEmbeddable.class, 1));\n\n    }\n\n    @Test\n    public void likeQueryTest()\n    {\n        Person p1 = new Person();\n        p1.setAge(32);\n        p1.setDay(Day.TUESDAY);\n        p1.setPersonId(\"p1\");\n        p1.setSalary(6000.345);\n        p1.setPersonName(\"vivek\");\n        em.persist(p1);\n        em.clear();\n\n        Person p2 = new Person();\n        p2.setAge(24);\n        p2.setDay(Day.MONDAY);\n        p2.setPersonId(\"p2\");\n        p2.setSalary(8000.345);\n        p2.setPersonName(\"vivek\");\n        em.persist(p2);\n        em.clear();\n\n        Person p3 = new Person();\n        p3.setAge(24);\n        p3.setDay(Day.MONDAY);\n        p3.setPersonId(\"p3\");\n        p3.setSalary(8000.345);\n        p3.setPersonName(\"vivek\");\n        em.persist(p3);\n        em.clear();\n\n        String qry = \"Select p from Person p where p.personName like :name\";\n        Query q = em.createQuery(qry);\n        q.setParameter(\"name\", \"vi\");\n        List<Person> persons = q.getResultList();\n        assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n\n        qry = \"Select p from Person p where p.personName like :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"pragalbh\");\n        persons = q.getResultList();\n        assertEquals(0, persons.size());\n\n        Person p = new Person();\n        p.setAge(20);\n        p.setDay(Day.MONDAY);\n        p.setPersonId(\"p4\");\n        p.setPersonName(\"pragalbh garg\");\n\n        Person g = new Person();\n        g.setAge(20);\n        g.setDay(Day.MONDAY);\n        g.setPersonId(\"p5\");\n        g.setPersonName(\"karthik prasad\");\n\n        em.persist(p);\n        em.persist(g);\n\n        qry = \"Select p from Person p where p.personName like :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"garg\");\n        persons = q.getResultList();\n        assertEquals(1, persons.size());\n\n        qry = \"Select p from Person p where p.personName like :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"karthik \");\n        persons = q.getResultList();\n        assertEquals(1, persons.size());\n\n        qry = \"Select p from Person p where p.personName like :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"%garg\");\n        persons = q.getResultList();\n        assertEquals(1, persons.size());\n\n        qry = \"Select p from Person p where p.personName like :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"karthik%\");\n        persons = q.getResultList();\n        assertEquals(1, persons.size());\n\n        qry = \"Select p from Person p where p.personName like :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"%kar\");\n        persons = q.getResultList();\n        assertEquals(0, persons.size());\n\n        em.remove(em.find(Person.class, \"p1\"));\n        em.remove(em.find(Person.class, \"p2\"));\n        em.remove(em.find(Person.class, \"p3\"));\n        em.remove(em.find(Person.class, \"p4\"));\n        em.remove(em.find(Person.class, \"p5\"));\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        LuceneCleanupUtilities.cleanDir(LUCENE_DIR_PATH);\n    }\n\n}"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/query/PersonEntityNameTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.DummyDatabase;\nimport com.impetus.kundera.query.PersonEntityNameAnnotation.Day;\n\n/**\n * Test case to perform check entity name annotation support\n * select)\n */\npublic class PersonEntityNameTest \n{\n    private static final String PU = \"patest\";\n\n\n    private EntityManagerFactory emf;\n    private EntityManager em;\n\n    protected Map<String, String> propertyMap = null;\n\n    @Before\n    public void setUp() throws Exception\n    {\n                \n        propertyMap=new HashMap<String, String>();\n        propertyMap.put(\"index.home.dir\",\"./lucene\");\n        emf = Persistence.createEntityManagerFactory(PU, propertyMap);\n        em = emf.createEntityManager();\n\n    }\n\n    @Test\n    public void test() throws Exception\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n\n        Query findQuery = em.createQuery(\"Select p from PF p\", PersonEntityNameAnnotation.class);\n        List<PersonEntityNameAnnotation> allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        findQuery = em.createQuery(\"Select p from PF p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        findQuery = em.createQuery(\"Select p.age from PF p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        PersonEntityNameAnnotation personWithKey = new PersonEntityNameAnnotation();\n        personWithKey.setPersonId(\"111\");\n        em.persist(personWithKey);        \n\n        em.clear();\n        PersonEntityNameAnnotation p = findById(PersonEntityNameAnnotation.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertEquals(Day.THURSDAY, p.getDay());\n\n        em.clear();\n        String qry = \"Select p.personId,p.personName from PF p where p.personId >= 1\";\n        Query q = em.createQuery(qry);\n        List<PersonEntityNameAnnotation> persons = q.getResultList();\n\n        assertFindByName(em, \"PersonEntityNameAnnotation\", PersonEntityNameAnnotation.class, \"vivek\", \"personName\");  \n        \n        // Delete without WHERE clause.\n        String deleteQuery = \"DELETE from PF\";\n        q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n\n    }\n \n   \n\n   \n\n   \n\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        DummyDatabase.INSTANCE.dropDatabase();\n    }\n    \n\n    private PersonEntityNameAnnotation prepareData(String rowKey, int age)\n    {\n        PersonEntityNameAnnotation o = new PersonEntityNameAnnotation();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age);\n        o.setDay(Day.THURSDAY);\n        return o;\n    }\n\n \n    private <E extends Object> E findById(Class<E> clazz, Object rowKey, EntityManager em)\n    {\n        return em.find(clazz, rowKey);\n    }\n\n \n    private <E extends Object> void assertFindByName(EntityManager em, String clazz, E e, String name,\n            String fieldName)\n    {\n\n        String query = \"Select p from PF p where p.\" + fieldName + \" = \" + name;\n        // // find by name.\n        Query q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n    }\n\n   \n   \n\n \n    private <E extends Object> String getPersonName(E e, Object result)\n    {\n\n        return ((PersonEntityNameAnnotation) result).getPersonName();\n    }\n}\n\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/query/PersonTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport javax.persistence.TypedQuery;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.DummyDatabase;\nimport com.impetus.kundera.entity.PersonnelDTO;\nimport com.impetus.kundera.query.Person.Day;\n\n/**\n * Test case to perform simple CRUD operation.(insert, delete, merge, and\n * select)\n */\npublic class PersonTest\n{\n    private static final String PU = \"patest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    protected Map propertyMap = null;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        propertyMap = new HashMap<String, String>();\n        propertyMap.put(\"index.home.dir\", \"./lucene\");\n        emf = Persistence.createEntityManagerFactory(PU, propertyMap);\n        em = emf.createEntityManager();\n\n    }\n\n    @Test\n    public void testInsertions() throws Exception\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n\n        Query findQuery = em.createQuery(\"Select p from Person p\", Person.class);\n        List<Person> allPersons = findQuery.getResultList();\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = em.createQuery(\"Select p from Person p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = em.createQuery(\"Select p.age from Person p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertTrue(allPersons.isEmpty());\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        findQuery = em.createQuery(\"Select p from Person p where p.personName = vivek ORDER BY p.age ASC\");\n        findQuery.setFirstResult(2);\n        findQuery.setMaxResults(2);\n        allPersons = findQuery.getResultList();\n        Assert.assertEquals(2, allPersons.size());\n        Assert.assertEquals(new Integer(10), allPersons.get(0).getAge());\n        Assert.assertEquals(new Integer(20), allPersons.get(1).getAge());\n\n        Person personWithKey = new Person();\n        personWithKey.setPersonId(\"111\");\n        em.persist(personWithKey);\n\n        em.clear();\n        Person p = findById(Person.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertEquals(Day.THURSDAY, p.getDay());\n\n        em.clear();\n        String qry = \"Select p.personId,p.personName from Person p where p.personId >= 1\";\n        Query q = em.createQuery(qry);\n        List<Person> persons = q.getResultList();\n\n        assertFindByName(em, \"Person\", Person.class, \"vivek\", \"personName\");\n\n        // Delete without WHERE clause.\n        String deleteQuery = \"DELETE from Person\";\n        q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n\n    }\n\n    @Test\n    public void testUpdation() throws Exception\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        em.clear();\n        Person p = findById(Person.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        // modify record.\n        p.setPersonName(\"newvivek\");\n        em.merge(p);\n\n        assertUpdation(em, \"Person\", Person.class, \"vivek\", \"newvivek\", \"personName\");\n    }\n\n    @Test\n    public void testDeletion() throws Exception\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        Person p = findById(Person.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        em.remove(p);\n        em.clear();\n\n        TypedQuery<Person> query = em.createQuery(\"Select p from Person p\", Person.class);\n\n        List<Person> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n    }\n\n    @Test\n    public void testRefresh() throws Exception\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        // Check for contains\n        Object pp1 = prepareData(\"1\", 10);\n        Object pp2 = prepareData(\"2\", 20);\n        Object pp3 = prepareData(\"3\", 15);\n        Assert.assertTrue(em.contains(pp1));\n        Assert.assertTrue(em.contains(pp2));\n        Assert.assertTrue(em.contains(pp3));\n\n        // Check for detach\n        em.detach(pp1);\n        em.detach(pp2);\n        Assert.assertFalse(em.contains(pp1));\n        Assert.assertFalse(em.contains(pp2));\n        Assert.assertTrue(em.contains(pp3));\n\n        // Modify value in database directly, refresh and then check PC\n        em.clear();\n        em = emf.createEntityManager();\n        Object o1 = em.find(Person.class, \"1\");\n\n        em.refresh(o1);\n        Object oo1 = em.find(Person.class, \"1\");\n        Assert.assertTrue(em.contains(o1));\n    }\n\n    @Test\n    public void testTypedQuery()\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        TypedQuery<Person> query = em.createQuery(\"Select p from Person p\", Person.class);\n\n        List<Person> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n    }\n\n    @Test\n    public void testGenericTypedQuery()\n    {\n\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        TypedQuery<Object> query = em.createQuery(\"Select p from Person p\", Object.class);\n\n        List<Object> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n    }\n\n    @Test\n    public void testInvalidTypedQuery()\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        TypedQuery<PersonnelDTO> query = null;\n        try\n        {\n            query = em.createQuery(\"Select p from Person p\", PersonnelDTO.class);\n            Assert.fail(\"Should have gone to catch block, as it is an invalid scenario!\");\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertNull(query);\n        }\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        DummyDatabase.INSTANCE.dropDatabase();\n    }\n\n    private Person prepareData(String rowKey, int age)\n    {\n        Person o = new Person();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age);\n        o.setDay(Day.THURSDAY);\n        return o;\n    }\n\n    private <E extends Object> E findById(Class<E> clazz, Object rowKey, EntityManager em)\n    {\n        return em.find(clazz, rowKey);\n    }\n\n    private <E extends Object> void assertFindByName(EntityManager em, String clazz, E e, String name, String fieldName)\n    {\n\n        String query = \"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name;\n        // // find by name.\n        Query q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n    }\n\n    protected <E extends Object> void assertUpdation(EntityManager em, String clazz, E e, String oldName,\n            String newName, String fieldName)\n    {\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + oldName);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + newName);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotSame(oldName, getPersonName(e, results.get(0)));\n        Assert.assertEquals(newName, getPersonName(e, results.get(0)));\n    }\n\n    private <E extends Object> String getPersonName(E e, Object result)\n    {\n\n        return ((Person) result).getPersonName();\n    }\n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/java/com/impetus/kundera/query/QueryImplTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.query;\n\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.FlushModeType;\nimport javax.persistence.LockModeType;\nimport javax.persistence.NoResultException;\nimport javax.persistence.Persistence;\nimport javax.persistence.TemporalType;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.CoreTestUtilities;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.DummyDatabase;\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.polyglot.entities.AddressB1M;\nimport com.impetus.kundera.polyglot.entities.AddressBM1;\nimport com.impetus.kundera.polyglot.entities.PersonB1M;\nimport com.impetus.kundera.polyglot.entities.PersonBM1;\nimport com.impetus.kundera.query.Person.Day;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * @author vivek.mishra\n * junit for {@link QueryImpl}\n *\n */\npublic class QueryImplTest\n{\n\n    private static final String PU = \"patest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private KunderaMetadata kunderaMetadata;\n    \n    Map propertyMap=null;\n    \n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        propertyMap=new HashMap<String, String>();\n        propertyMap.put(\"index.home.dir\",\"./lucene\");      \n        emf = Persistence.createEntityManagerFactory(PU,propertyMap);\n        kunderaMetadata = ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance();\n        em = emf.createEntityManager();\n\n    }\n\n    @Test\n    public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException\n    {\n        Person p1 = new Person();\n        p1.setAge(98);\n        p1.setPersonId(\"1\");\n        p1.setDay(Day.SATURDAY);\n        p1.setSalary(6000.345);\n        \n        em.persist(p1);\n        \n        \n        Person p2 = new Person();\n        p2.setAge(100);\n        p2.setPersonId(\"2\");\n        p2.setDay(Day.SATURDAY);\n        p2.setSalary(10000.345);\n        \n        em.persist(p2);\n        \n        String query = \"Select p from Person p where p.personId = :personId\";\n        \n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n        \n        KunderaQueryParser queryParser;\n        KunderaQuery kunderaQuery = parseQuery(query);\n\n        CoreQuery queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n        \n        queryObj.setParameter(\"personId\", \"1\");\n        List<Person> results = queryObj.getResultList();\n        \n        Assert.assertEquals(1,results.size());\n        Assert.assertNotNull(KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery,kunderaMetadata)); //assert on lucene query transformation.\n        Assert.assertNotNull(queryObj.populateUsingLucene()); //assert on lucene query transformation.\n\n\n        final String deleteQuery = \"Delete from Person p where p.personId = ?1\";\n\n        kunderaQuery = parseQuery(deleteQuery);\n        \n        \n        queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n        \n        try\n        {\n            Assert.assertNull(queryObj.getParameter(\"personId\", String.class));\n        }catch(IllegalArgumentException iaex)\n        {\n            Assert.assertEquals(\"The parameter of the specified name does not exist or is not assignable to the type\", iaex.getMessage());\n        }\n        Assert.assertNotNull(queryObj.getParameter(1, String.class));\n        Assert.assertNotNull(queryObj.getParameterValue(1));\n        Assert.assertNotNull(KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata)); \n        Assert.assertNotNull(queryObj.populateUsingLucene()); \n\n        try\n        {\n            queryObj.getParameterValue(1);\n        } catch(IllegalStateException usex)\n        {\n            Assert.assertEquals(\"parameter has not been bound\" + 1, usex.getMessage());\n        }\n\n        queryObj.setParameter(1, \"1\");\n        \n        queryObj.executeUpdate();\n        \n        em.clear();\n        \n        kunderaQuery = parseQuery(query);\n        queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n        \n        try\n        {\n            queryObj.setParameter(CoreTestUtilities.getParameter(), \"test\");\n            Assert.fail(\"Should have gone to catch block!\");\n        }catch(IllegalArgumentException iaex)\n        {\n            Assert.assertNotNull(iaex);\n        }\n        \n        try\n        {\n            queryObj.setParameter(CoreTestUtilities.getParameter(\"personId\",\"1\"), \"1\");\n            Assert.fail(\"Should have gone to catch block!\");\n        }catch(IllegalArgumentException iaex)\n        {\n            Assert.assertNotNull(iaex);\n        }\n        \n        queryObj.setParameter(queryObj.getParameter(\"personId\"),\"1\");\n        \n        results = queryObj.getResultList();\n        \n        Assert.assertEquals(0,results.size());\n        \n        queryObj.setHint(\"test\", \"test\");\n        \n        queryObj.setMaxResults(100);\n        Assert.assertEquals(100, queryObj.getMaxResults());\n\n        Assert.assertNotNull(queryObj.getHints());\n        \n        queryObj.setFetchSize(100);\n\n        Assert.assertEquals(new Integer(100),queryObj.getFetchSize());\n        \n        \n        query = \"Select p from Person p where p.personId = ?1\";\n\n        queryObj.setParameter(queryObj.getParameter(\"personId\"),\"1\");\n        \n        results = queryObj.getResultList();\n        \n        Assert.assertEquals(0,results.size());\n        Assert.assertNotNull(KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata)); \n        Assert.assertNotNull(queryObj.populateUsingLucene()); \n        \n\n        //TODO:: commented out a single methoda have been introduced in QueryImpl, used from test package only!\n       /* Set luceneResults = queryObj.fetchByLuceneQuery();\n        Assert.assertNotNull(luceneResults);            // assert of lucene index search result.\n        Assert.assertEquals(1,luceneResults.size());\n        */\n        Assert.assertNotNull(queryObj.getParameter(\"personId\", String.class));\n        \n        Assert.assertTrue(queryObj.isBound(queryObj.getParameter(\"personId\", String.class)));\n        \n        Assert.assertNotNull(queryObj.getParameterValue(queryObj.getParameter(\"personId\", String.class)));\n        Assert.assertNotNull(queryObj.getParameterValue(\"personId\"));\n        \n        try\n        {\n            Assert.assertNull(queryObj.getParameter(1, String.class));\n            Assert.fail(\"Should have gone to catch block!\");\n        }catch(IllegalArgumentException iaex)\n        {\n            Assert.assertNotNull(iaex);\n        }\n       \n        try\n        {\n            queryObj.getParameter(1);\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertNotNull(iaex);\n        }\n        //assert on native query.\n        try\n        {\n            ApplicationMetadata appMetadata = ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance().getApplicationMetadata();\n            appMetadata.addQueryToCollection(query, query, true, null);\n            kunderaQuery = parseQuery(query);\n            queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n            Assert.assertNull(queryObj.getParameter(1, String.class));\n            Assert.fail(\"Should have gone to catch block!\");\n        }catch(IllegalStateException iaex)\n        {\n            Assert.assertEquals(\"invoked on a native query when the implementation does not support this use\", iaex.getMessage());\n        }\n\n        \n        try\n        {\n            final String updateQuery = \"Update Person p set p.personName=Amresh where p.personId = 1\";\n            kunderaQuery = parseQuery(updateQuery);       \n            queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n            queryObj.executeUpdate();\n            Assert.assertNotNull(KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata)); \n            Assert.assertNotNull(queryObj.populateUsingLucene()); \n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }        \n        \n        try\n        {\n            queryObj.unwrap(Client.class);\n        } catch(ClassCastException usex)\n        {\n            Assert.assertEquals(\"Provider does not support the call for class type:[\" + Integer.class + \"]\", usex.getMessage());\n        }\n        \n        try\n        {\n            queryObj.getParameterValue(\"invalidParameter\");\n        } catch(IllegalArgumentException usex)\n        {\n            Assert.assertEquals(\"Parameter is not a parameter of the query.\", usex.getMessage());\n        }\n        \n        \n        query = \"Select p from Person p where p.age >:age\";        \n        delegator = CoreTestUtilities.getDelegator(em);  \n        kunderaQuery = parseQuery(query);\n        queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());        \n        queryObj.setParameter(\"age\", new Integer(32));       \n        Assert.assertNotNull(KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata)); \n        Assert.assertNotNull(queryObj.populateUsingLucene());\n        \n        query = \"Select p from Person p where p.age >=:age\";        \n        delegator = CoreTestUtilities.getDelegator(em);  \n        kunderaQuery = parseQuery(query);\n        queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());        \n        queryObj.setParameter(\"age\", new Integer(32));       \n        Assert.assertNotNull(KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata)); \n        Assert.assertNotNull(queryObj.populateUsingLucene());\n        \n        query = \"Select p from Person p where p.age <:age\";        \n        delegator = CoreTestUtilities.getDelegator(em);  \n        kunderaQuery = parseQuery(query);\n        queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());        \n        queryObj.setParameter(\"age\", new Integer(32));       \n        Assert.assertNotNull(KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata)); \n        Assert.assertNotNull(queryObj.populateUsingLucene());\n        \n        query = \"Select p from Person p where p.age <=:age\";        \n        delegator = CoreTestUtilities.getDelegator(em);  \n        kunderaQuery = parseQuery(query);\n        queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());        \n        queryObj.setParameter(\"age\", new Integer(32));       \n        Assert.assertNotNull(KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata )); \n        Assert.assertNotNull(queryObj.populateUsingLucene());\n        \n        query = \"Select p from Person p where p.personName like :personName\";        \n        delegator = CoreTestUtilities.getDelegator(em);  \n        kunderaQuery = parseQuery(query);\n        queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());        \n        queryObj.setParameter(\"personName\", \"Amresh\");       \n        Assert.assertNotNull(KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata)); \n        Assert.assertNotNull(queryObj.populateUsingLucene()); \n        \n        query = \"Select p from Person p where p.salary >=:salary\";        \n        delegator = CoreTestUtilities.getDelegator(em);  \n        kunderaQuery = parseQuery(query);\n        queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());        \n        queryObj.setParameter(\"salary\", 500.0);       \n        Assert.assertNotNull(KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata)); \n        Assert.assertNotNull(queryObj.populateUsingLucene());\n        \n        onassertBi1MAssociation(delegator);\n        onassertBiM1Association(delegator);\n\n}\n\n    private void onassertBi1MAssociation(PersistenceDelegator delegator)\n    {\n        KunderaQuery kunderaQuery;\n        CoreQuery queryObj;\n        PersonB1M personBi1M = new PersonB1M();\n        \n        personBi1M.setPersonId(\"personBi1M1\");\n        personBi1M.setPersonName(\"impetus-opensource\");\n        \n        AddressB1M addressBi1M = new AddressB1M();\n        addressBi1M.setAddressId(\"addrBi1M1\");\n        addressBi1M.setStreet(\"meri gali\");\n        Set<AddressB1M> addresses = new HashSet<AddressB1M>();\n        addresses.add(addressBi1M);\n//        personBi1M.setAddresses(addresses);\n        \n        AddressB1M addressBi1M_copy = new AddressB1M();\n        addressBi1M_copy.setAddressId(\"addrBi1M2\");\n        addressBi1M_copy.setStreet(\"meri gali\");\n        addresses.add(addressBi1M_copy);\n        personBi1M.setAddresses(addresses);\n\n        em.persist(personBi1M);\n        \n        em.clear();\n        \n        String query = \"Select p from PersonB1M p where p.personId = 'personBi1M1'\";\n\n        kunderaQuery = parseQuery(query);\n        \n        \n        queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n        \n        List<PersonB1M> associationResults = queryObj.getResultList();\n        \n        Assert.assertTrue(!associationResults.isEmpty());\n        \n        Assert.assertNotNull(associationResults.get(0).getAddresses());\n        \n        Assert.assertEquals(2,associationResults.get(0).getAddresses().size());\n        \n        \n        query = \"Select p from PersonB1M p where p.personId = 'invalid'\";\n\n        kunderaQuery = parseQuery(query);\n        \n        \n        queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n        \n        associationResults = queryObj.getResultList();\n\n        Assert.assertTrue(associationResults.isEmpty());\n\n    }\n\n    private void onassertBiM1Association(PersistenceDelegator delegator)\n    {\n        KunderaQuery kunderaQuery;\n        CoreQuery queryObj;\n        \n        PersonBM1 personBiM11 = new PersonBM1();\n        personBiM11.setPersonId(\"personBiM11\");\n        personBiM11.setPersonName(\"impetus-opensource\");\n        \n\n        PersonBM1 personBiM12 = new PersonBM1();\n        personBiM12.setPersonId(\"personBiM12\");\n        personBiM12.setPersonName(\"impetus-opensource\");\n\n        AddressBM1 addressBiM1 = new AddressBM1();\n        addressBiM1.setAddressId(\"addrBiM11\");\n        addressBiM1.setStreet(\"meri gali\");\n\n        \n        personBiM11.setAddress(addressBiM1);\n        personBiM12.setAddress(addressBiM1);\n\n        em.persist(personBiM11);\n        em.persist(personBiM12);\n        \n        em.clear();\n        \n        String selectAssociationQuery = \"Select p from PersonBM1 p\";\n\n        kunderaQuery = parseQuery(selectAssociationQuery);\n        \n        \n        queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n        \n        List<PersonBM1> associationResults = queryObj.getResultList();\n        \n        Assert.assertTrue(!associationResults.isEmpty());\n        \n        Assert.assertNotNull(associationResults.get(0).getAddress());\n        \n        \n        selectAssociationQuery = \"Select p from PersonBM1 p where p.personId = 'invalid'\";\n\n        kunderaQuery = parseQuery(selectAssociationQuery);        \n        \n        queryObj = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n        \n        associationResults = queryObj.getResultList();\n\n        Assert.assertTrue(associationResults.isEmpty());\n        \n        try\n        {\n            queryObj.getSingleResult();\n        }\n        catch (NoResultException e)\n        {\n            Assert.assertEquals(\"No result found!\", e.getMessage());\n        }\n\n    }\n\n    private KunderaQuery parseQuery(final String query)\n    {\n        KunderaQuery kunderaQuery = new KunderaQuery(query, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        return kunderaQuery;\n    }\n\n\n    @After\n    public void tearDown()\n    {\n        DummyDatabase.INSTANCE.dropDatabase();\n        LuceneCleanupUtilities.cleanLuceneDirectory(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance()\n                .getApplicationMetadata().getPersistenceUnitMetadata(PU));\n    }\n\n    /**\n     * @param query\n     * @throws IllegalAccessException \n     * @throws IllegalArgumentException \n     * @throws SecurityException \n     * @throws NoSuchFieldException \n     */\n    @Test\n    public void assertOnUnsupportedMethod() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException\n    {\n        String queryStr = \"Select p from Person p where p.personId = :personId\";\n        \n        PersistenceDelegator delegator = CoreTestUtilities.getDelegator(em);\n        \n        KunderaQueryParser queryParser;\n        KunderaQuery kunderaQuery = parseQuery(queryStr);\n\n        CoreQuery query = new CoreQuery(kunderaQuery, delegator, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance());\n\n        try\n        {\n            query.setFlushMode(FlushModeType.AUTO);\n        } catch(UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setFlushMode is unsupported by Kundera\", usex.getMessage());\n        }\n        \n        try\n        {\n            query.setFirstResult(1);\n        } catch(UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setFirstResult is unsupported by Kundera\", usex.getMessage());\n        }\n                       \n        try\n        {\n            query.getFirstResult();\n        } catch(UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"getFirstResult is unsupported by Kundera\", usex.getMessage());\n        }\n        \n        try\n        {\n            query.setLockMode(LockModeType.NONE);\n        } catch(UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setLockMode is unsupported by Kundera\", usex.getMessage());\n        }\n        \n        try\n        {\n            query.getLockMode();\n        } catch(UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"getLockMode is unsupported by Kundera\", usex.getMessage());\n        }\n        \n        try\n        {\n            query.setParameter(0,new Date(),TemporalType.DATE);\n        } catch(UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setParameter(\"param\",new Date(),TemporalType.DATE);\n        } catch(UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n        \n        try\n        {\n            query.setParameter(0,Calendar.getInstance(),TemporalType.DATE);\n        } catch(UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n        \n        try\n        {\n            query.setParameter(\"param\",Calendar.getInstance(),TemporalType.DATE);\n        } catch(UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setParameter(CoreTestUtilities.getParameter(),Calendar.getInstance(),TemporalType.DATE);\n        } catch(UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.setParameter(CoreTestUtilities.getParameter(),new Date(),TemporalType.DATE);\n        } catch(UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"setParameter is unsupported by Kundera\", usex.getMessage());\n        }\n\n        try\n        {\n            query.getFlushMode();\n        } catch(UnsupportedOperationException usex)\n        {\n            Assert.assertEquals(\"getFlushMode is unsupported by Kundera\", usex.getMessage());\n        }\n\n    }\n    \n}\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"kunderatest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<!-- <jar-file>/home/impetus/perf_n.jar</jar-file> <jar-file>/home/impetus/perf.jar</jar-file> -->\r\n\t\t<class>com.impetus.kundera.entity.PersonnelDTO</class>\r\n\t\t<class>com.impetus.kundera.persistence.event.PersonEventDispatch</class>\r\n\t\t<class>com.impetus.kundera.persistence.event.AddressEntity</class>\r\n\t\t<class>com.impetus.kundera.persistence.event.AddressEntityWithList</class>\r\n\t\t<class>com.impetus.kundera.graph.Store</class>\r\n\t\t<class>com.impetus.kundera.graph.BillingCounter</class>\r\n\t\t<!-- <class>com.impetus.kundera.configure.CoreEntityAddressUni1To1</class> \r\n\t\t\t<class>com.impetus.kundera.configure.CoreEntityAddressUni1ToM</class> <class>com.impetus.kundera.configure.CoreEntityAddressUniMTo1</class> \r\n\t\t\t<class>com.impetus.kundera.configure.CoreEntityPersonUni1To1</class> <class>com.impetus.kundera.configure.CoreEntityPersonUni1ToM</class> \r\n\t\t\t<class>com.impetus.kundera.configure.CoreEntityPersionUniMTo1</class> -->\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_1_1_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_1_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_1_1_M_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_1_M_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_1_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_M_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_M_M_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerUni_M_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_1_1_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_1_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_1_1_M_1</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_1_M_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_1_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_M_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_M_M_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumUni_M_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_1_1_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_1_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_1_1_M_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_1_M_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_1_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_M_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_M_M_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoUni_M_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_1_1_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_1_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_1_M_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_1_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_M_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_M_M_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photographer.PhotographerBi_M_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_1_1_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_1_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_1_M_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_1_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_M_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_M_M_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.album.AlbumBi_M_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_1_1_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_1_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_1_M_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_1_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_M_1_1_M</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_M_M_1_1</class>\r\n\t\t<class>com.impetus.kundera.entity.photo.PhotoBi_M_M_M_M</class>\r\n\t\t<class>com.impetus.kundera.metadata.entities.SampleEntity</class>\r\n\t\t<!-- <class>com.impetus.kundera.metadata.entities.bi.AssociationBiEntity</class> \r\n\t\t\t<class>com.impetus.kundera.metadata.entities.bi.OToOOwnerBiEntity</class> -->\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"rdbms\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<property name=\"kundera.cache.provider.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\r\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"PropertyTest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaXmlTest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<property name=\"kundera.cache.provider.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\r\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\r\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"PropertyTestwithvaraiable\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaXmlTest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<property name=\"kundera.cache.provider.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\r\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\r\n\t\t\t<property name=\"kundera.client.property\"\r\n\t\t\t\tvalue=\"${HOME}/Desktop/kunderaExternalProperties.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"PropertyTestwithabsolutepath\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaXmlTest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<property name=\"kundera.cache.provider.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\r\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\r\n\t\t\t<property name=\"kundera.client.property\"\r\n\t\t\t\tvalue=\"/home/impadmin/Desktop/kunderaExternalProperties.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"metaDataTest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.persistence.event.PersonEventDispatch</class>\r\n\t\t<class>com.impetus.kundera.metadata.model.Employe</class>\r\n\t\t<class>com.impetus.kundera.metadata.model.KunderaUser</class>\r\n\t\t<class>com.impetus.kundera.metadata.model.TweetKundera</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaMetaDataTest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<property name=\"kundera.cache.provider.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\r\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\r\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\r\n\t\t\t<property name=\"index.home.dir\" value=\"./lucene\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"GeneratedValue\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdDefault</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdStrategyAuto</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdStrategyIdentity</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdStrategySequence</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdStrategyTable</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdWithSequenceGenerator</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdWithTableGenerator</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdWithOutSequenceGenerator</class>\r\n\t\t<class>com.impetus.kundera.metadata.validator.GeneratedIdWithOutTableGenerator</class>\r\n\t\t<!-- <class>com.impetus.kundera.metadata.validator.FTEmployee</class> <class>com.impetus.kundera.metadata.validator.PartTimeEmployee</class> -->\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<property name=\"kundera.cache.provider.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\r\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\r\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"patest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.query.Person</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonU11FK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressU11FK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonB11FK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressB11FK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonU11PK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressU11PK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonB11PK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressB11PK</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonU1M</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressU1M</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonB1M</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressB1M</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonUM1</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressUM1</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonBM1</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressBM1</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonUMM</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonUMMByMap</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressUMM</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.PersonBMM</class>\r\n\t\t<class>com.impetus.kundera.polyglot.entities.AddressBMM</class>\r\n\t\t<class>com.impetus.kundera.metadata.entities.SingularEntityEmbeddable</class>\r\n\t\t<class>com.impetus.kundera.metadata.entities.Article</class>\r\n\t\t<class>com.impetus.kundera.query.PersonEntityNameAnnotation</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"rdbms\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<property name=\"kundera.cache.provider.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\r\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\r\n\t\t\t<property name=\"index.home.dir\" value=\"./lucene\" />\r\n\t\t\t<property name=\"kundera.batch.size\" value=\"5\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"mappedsu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.Employee</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTest\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"invalidmappedsu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.InvalidPersonEntity</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTest\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\r\n\t<persistence-unit name=\"keyspace\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.metadata.entities.OToOOwnerEntity</class>\r\n\t\t<class>com.impetus.kundera.metadata.entities.AssociationEntity</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"testSchema\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"inheritanceTest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.metadata.processor.Rectangle</class>\r\n\t\t<class>com.impetus.kundera.metadata.processor.Circle</class>\r\n\t\t<class>com.impetus.kundera.metadata.processor.Geometry</class>\r\n\t\t<class>com.impetus.kundera.metadata.processor.Shape</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"testSchema\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\r\n\t<persistence-unit name=\"ehacheTest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.entity.EhCacheEntity</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"testSchema\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.client.CoreTestClientFactory\" />\r\n\t\t\t<property name=\"kundera.cache.provider.class\"\r\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\r\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n</persistence>\r\n\r\n\r\n\r\n\r\n\r\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/resources/META-INF/persistence_2_0.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!-- persistence.xml schema -->\r\n<xsd:schema targetNamespace=\"http://java.sun.com/xml/ns/persistence\" \r\n  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\r\n  xmlns:persistence=\"http://java.sun.com/xml/ns/persistence\"\r\n  elementFormDefault=\"qualified\" \r\n  attributeFormDefault=\"unqualified\" \r\n  version=\"2.0\">\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n      @(#)persistence_2_0.xsd  1.0  October 1 2009\r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n\r\n  Copyright (c) 2008, 2009 Sun Microsystems. All rights reserved. \r\n  \r\n  This program and the accompanying materials are made available under the \r\n  terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 \r\n  which accompanies this distribution. \r\n  The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html\r\n  and the Eclipse Distribution License is available at \r\n  http://www.eclipse.org/org/documents/edl-v10.php.\r\n  \r\n  Contributors:\r\n      Linda DeMichiel - Java Persistence 2.0, Version 2.0 (October 1, 2009)\r\n      Specification available from http://jcp.org/en/jsr/detail?id=317\r\n \r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n   <xsd:annotation>\r\n     <xsd:documentation><![CDATA[\r\n\r\n     This is the XML Schema for the persistence configuration file.\r\n     The file must be named \"META-INF/persistence.xml\" in the \r\n     persistence archive.\r\n\r\n     Persistence configuration files must indicate\r\n     the persistence schema by using the persistence namespace:\r\n\r\n     http://java.sun.com/xml/ns/persistence\r\n\r\n     and indicate the version of the schema by\r\n     using the version element as shown below:\r\n\r\n      <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n        xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n          http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\"\r\n        version=\"2.0\">\r\n          ...\r\n      </persistence>\r\n\r\n    ]]></xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:simpleType name=\"versionType\">\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:pattern value=\"[0-9]+(\\.[0-9]+)*\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:element name=\"persistence\">\r\n    <xsd:complexType>\r\n      <xsd:sequence>\r\n\r\n        <!-- **************************************************** -->\r\n\r\n        <xsd:element name=\"persistence-unit\" \r\n                     minOccurs=\"1\" maxOccurs=\"unbounded\">\r\n          <xsd:complexType>\r\n            <xsd:annotation>\r\n              <xsd:documentation>\r\n\r\n                Configuration of a persistence unit.\r\n\r\n              </xsd:documentation>\r\n            </xsd:annotation>\r\n            <xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"description\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Description of this persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"provider\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Provider class that supplies EntityManagers for this \r\n                    persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of the JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"non-jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of a non-JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"mapping-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    File containing mapping information. Loaded as a resource \r\n                    by the persistence provider.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jar-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Jar file that is to be scanned for managed classes. \r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"class\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Managed class to be included in the persistence unit and\r\n                    to scan for annotations.  It should be annotated \r\n                    with either @Entity, @Embeddable or @MappedSuperclass.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"exclude-unlisted-classes\" type=\"xsd:boolean\" \r\n                           default=\"true\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    When set to true then only listed classes and jars will \r\n                    be scanned for persistent classes, otherwise the \r\n                    enclosing jar or directory will also be scanned. \r\n                    Not applicable to Java SE persistence units.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"shared-cache-mode\" \r\n                           type=\"persistence:persistence-unit-caching-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Defines whether caching is enabled for the \r\n                    persistence unit if caching is supported by the\r\n                    persistence provider. When set to ALL, all entities \r\n                    will be cached. When set to NONE, no entities will\r\n                    be cached. When set to ENABLE_SELECTIVE, only entities\r\n                    specified as cacheable will be cached. When set to\r\n                    DISABLE_SELECTIVE, entities specified as not cacheable\r\n                    will not be cached. When not specified or when set to\r\n                    UNSPECIFIED, provider defaults may apply.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"validation-mode\" \r\n                           type=\"persistence:persistence-unit-validation-mode-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The validation mode to be used for the persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"properties\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    A list of standard and vendor-specific properties \r\n                    and hints.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n                <xsd:complexType>\r\n                  <xsd:sequence>\r\n                    <xsd:element name=\"property\" \r\n                                 minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                      <xsd:annotation>\r\n                        <xsd:documentation>\r\n                          A name-value pair.\r\n                        </xsd:documentation>\r\n                      </xsd:annotation>\r\n                      <xsd:complexType>\r\n                        <xsd:attribute name=\"name\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                        <xsd:attribute name=\"value\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                      </xsd:complexType>\r\n                    </xsd:element>\r\n                  </xsd:sequence>\r\n                </xsd:complexType>\r\n              </xsd:element>\r\n\r\n            </xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Name used in code to reference this persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"transaction-type\" \r\n                           type=\"persistence:persistence-unit-transaction-type\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Type of transactions used by EntityManagers from this \r\n                  persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n          </xsd:complexType>\r\n        </xsd:element>\r\n      </xsd:sequence>\r\n      <xsd:attribute name=\"version\" type=\"persistence:versionType\" \r\n                     fixed=\"2.0\" use=\"required\"/>\r\n    </xsd:complexType>\r\n  </xsd:element>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-transaction-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum PersistenceUnitTransactionType {JTA, RESOURCE_LOCAL};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"JTA\"/>\r\n      <xsd:enumeration value=\"RESOURCE_LOCAL\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-caching-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum SharedCacheMode { ALL, NONE, ENABLE_SELECTIVE, DISABLE_SELECTIVE, UNSPECIFIED};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"ALL\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n      <xsd:enumeration value=\"ENABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"DISABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"UNSPECIFIED\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-validation-mode-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum ValidationMode { AUTO, CALLBACK, NONE};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"AUTO\"/>\r\n      <xsd:enumeration value=\"CALLBACK\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n</xsd:schema>\r\n"
  },
  {
    "path": "src/jpa-engine/fallback-impl/src/test/resources/ehcache-test.xml",
    "content": "<ehcache xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"ehcache.xsd\">\r\n\r\n\t<diskStore path=\"java.io.tmpdir\"/>\r\n\t\r\n\t<defaultCache maxElementsInMemory=\"10000\" eternal=\"false\" timeToIdleSeconds=\"120\"\r\n\t\ttimeToLiveSeconds=\"300\" overflowToDisk=\"true\" diskSpoolBufferSizeMB=\"30\"\r\n\t\tmaxElementsOnDisk=\"100000\" diskPersistent=\"false\" diskExpiryThreadIntervalSeconds=\"120\"\r\n\t\tmemoryStoreEvictionPolicy=\"LRU\" />\r\n\r\n\t<cache name=\"com.impetus.kundera.entity.EhCacheEntity\" maxElementsInMemory=\"10000\"\r\n\t\tmaxElementsOnDisk=\"1000\" eternal=\"false\" overflowToDisk=\"true\" diskSpoolBufferSizeMB=\"20\"\r\n\t\ttimeToIdleSeconds=\"300\" timeToLiveSeconds=\"600\" />\r\n</ehcache>\r\n"
  },
  {
    "path": "src/jpa-engine/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n\n  <parent>\n        <groupId>com.impetus</groupId>\n        <artifactId>kundera</artifactId>\n\t<version>3.14-SNAPSHOT</version>\n  </parent>\n\n  <groupId>com.impetus.kundera.core</groupId>\n  <artifactId>core-parent</artifactId>\n  <version>3.14-SNAPSHOT</version>\n  <packaging>pom</packaging>\n\n  <name>kundera-core-parent</name>\n  <url>https://github.com/impetus-opensource/Kundera</url>\n\n <licenses>\n    <license>\n      <name>The Apache Software License, Version 2.0</name>\n      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>\n      <distribution>repo</distribution>\n    </license>\n  </licenses>\n\n  <!-- Build profiles -->\n  <profiles>\n\n    <profile>\n      <id>all</id>\n      <activation>\n        <activeByDefault>true</activeByDefault>\n      </activation>\n      <modules>\n        <module>core</module>\n        <module>fallback-impl</module>\n      </modules>\n    </profile>\n    <profile>\n      <id>core</id>\n      <activation>\n        <activeByDefault>false</activeByDefault>\n      </activation>\n      <modules>\n        <module>core</module>\n      </modules>\n    </profile>\n\n    <profile>\n      <id>fallback</id>\n      <activation>\n        <activeByDefault>false</activeByDefault>\n      </activation>\n      <modules>\n        <module>fallback-imple</module>\n      </modules>\n    </profile>\n  </profiles>\n</project>\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t<artifactId>kundera-cassandra-parent</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-cassandra</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-cassandra</name>\n\t<url>http://maven.apache.org</url>\n\n\t<!-- Dependencies -->\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<!-- <dependency> -->\n\t\t<!-- <groupId>log4j</groupId> -->\n\t\t<!-- <artifactId>log4j</artifactId> -->\n\t\t<!-- <version>1.2.17</version> -->\n\t\t<!-- </dependency> -->\n\n\t\t<dependency>\n\t\t\t<groupId>org.apache.cassandra</groupId>\n\t\t\t<artifactId>cassandra-all</artifactId>\n\t\t\t<version>${cassandra.version}</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>com.ning</groupId>\n\t\t\t\t\t<artifactId>compress-lzf</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t</dependencies>\n\n\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-clean-plugin</artifactId>\n\t\t\t\t<version>2.4.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<filesets>\n\t\t\t\t\t\t<fileset>\n\t\t\t\t\t\t\t<directory>${basedir}</directory>\n\t\t\t\t\t\t\t<excludes>\n\t\t\t\t\t\t\t\t<exclude>.git/**</exclude>\n\t\t\t\t\t\t\t\t<exclude>.gitignore</exclude>\n\t\t\t\t\t\t\t</excludes>\n\t\t\t\t\t\t\t<includes>\n\t\t\t\t\t\t\t\t<include>lucene/**</include>\n\t\t\t\t\t\t\t</includes>\n\t\t\t\t\t\t</fileset>\n\t\t\t\t\t</filesets>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n\n</project>\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/CassandraClientBase.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra;\n\nimport java.io.UnsupportedEncodingException;\nimport java.lang.reflect.Field;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javassist.Modifier;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.Transient;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.ManagedType;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.apache.cassandra.db.marshal.AbstractType;\nimport org.apache.cassandra.db.marshal.TypeParser;\nimport org.apache.cassandra.exceptions.ConfigurationException;\nimport org.apache.cassandra.exceptions.SyntaxException;\nimport org.apache.cassandra.serializers.CollectionSerializer;\nimport org.apache.cassandra.thrift.Cassandra;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.ColumnOrSuperColumn;\nimport org.apache.cassandra.thrift.ColumnPath;\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.CounterColumn;\nimport org.apache.cassandra.thrift.CounterSuperColumn;\nimport org.apache.cassandra.thrift.CqlMetadata;\nimport org.apache.cassandra.thrift.CqlResult;\nimport org.apache.cassandra.thrift.CqlRow;\nimport org.apache.cassandra.thrift.IndexClause;\nimport org.apache.cassandra.thrift.IndexExpression;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KeySlice;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.Mutation;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.SuperColumn;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.cassandra.transport.ProtocolVersion;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.thrift.TException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.common.CassandraUtilities;\nimport com.impetus.client.cassandra.config.CassandraPropertyReader;\nimport com.impetus.client.cassandra.datahandler.CassandraDataHandler;\nimport com.impetus.client.cassandra.schemamanager.CassandraDataTranslator;\nimport com.impetus.client.cassandra.schemamanager.CassandraValidationClassMapper;\nimport com.impetus.client.cassandra.thrift.CQLTranslator;\nimport com.impetus.client.cassandra.thrift.CQLTranslator.TranslationType;\nimport com.impetus.client.cassandra.thrift.ThriftDataResultHelper;\nimport com.impetus.client.cassandra.thrift.ThriftRow;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.db.DataRow;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.db.SearchResult;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.lifecycle.states.RemovedState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata.Type;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.model.annotation.DefaultEntityAnnotationProcessor;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.property.accessor.StringAccessor;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.TimestampGenerator;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * Base Class for all Cassandra Clients Contains methods that are applicable to (but not specific to) different\n * Cassandra clients.\n * \n * @author amresh.singh\n */\npublic abstract class CassandraClientBase extends ClientBase implements ClientPropertiesSetter {\n\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(CassandraClientBase.class);\n\n    /** The cql version. */\n    private String cqlVersion = CassandraConstants.CQL_VERSION_2_0;\n\n    /** The consistency level. */\n    protected ConsistencyLevel consistencyLevel = ConsistencyLevel.ONE;\n\n    /** The ttl per request. */\n    private boolean ttlPerRequest = false;\n\n    /** The ttl per session. */\n    private boolean ttlPerSession = false;\n\n    /** The ttl values. */\n    private Map<String, Object> ttlValues = new HashMap<String, Object>();\n\n    /** The closed. */\n    private volatile boolean closed = false;\n\n    /** list of nodes for batch processing. */\n    private List<Node> nodes = new ArrayList<Node>();\n\n    /** batch size. */\n    private int batchSize;\n\n    /** The cql client. */\n    protected final CQLClient cqlClient;\n\n    /** The generator. */\n    protected final TimestampGenerator generator;\n\n    /** The cql metadata. */\n    private CqlMetadata cqlMetadata;\n\n    /**\n     * constructor using fields.\n     * \n     * @param persistenceUnit\n     *            the persistence unit\n     * @param externalProperties\n     *            the external properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param generator\n     *            the generator\n     */\n    protected CassandraClientBase(String persistenceUnit, Map<String, Object> externalProperties,\n        final KunderaMetadata kunderaMetadata, final TimestampGenerator generator) {\n        super(kunderaMetadata, externalProperties, persistenceUnit);\n        this.cqlClient = new CQLClient();\n        this.generator = generator;\n        setBatchSize(persistenceUnit, this.externalProperties);\n        populateCqlVersion(externalProperties);\n    }\n\n    /**\n     * Populates foreign key as column.\n     * \n     * @param rlName\n     *            relation name\n     * @param rlValue\n     *            relation value\n     * @param timestamp\n     *            the timestamp\n     * @return the column\n     * @throws PropertyAccessException\n     *             the property access exception\n     */\n    protected Column populateFkey(String rlName, Object rlValue, long timestamp) throws PropertyAccessException {\n        Column col = new Column();\n        col.setName(PropertyAccessorFactory.STRING.toBytes(rlName));\n        col.setValue(PropertyAccessorHelper.getBytes(rlValue));\n        col.setTimestamp(timestamp);\n        return col;\n    }\n\n    /**\n     * On counter column.\n     * \n     * @param m\n     *            the m\n     * @param isRelation\n     *            the is relation\n     * @param relations\n     *            the relations\n     * @param ks\n     *            the ks\n     * @return the list\n     */\n    protected List<Object> onCounterColumn(EntityMetadata m, boolean isRelation, List<String> relations,\n        List<KeySlice> ks) {\n        List<Object> entities;\n\n        if (m.getType().isSuperColumnFamilyMetadata()) {\n            if (log.isInfoEnabled()) {\n                log.info(\"On counter column for super column family of entity {}.\", m.getEntityClazz());\n            }\n\n            // TODO:: change it. remove column or super column helper\n            Map<byte[], List<CounterSuperColumn>> results = new HashMap<byte[], List<CounterSuperColumn>>();\n\n            List<CounterSuperColumn> counterColumns = null;\n            for (KeySlice slice : ks) {\n                counterColumns = new ArrayList<CounterSuperColumn>(slice.getColumnsSize());\n                for (ColumnOrSuperColumn column : slice.columns) {\n                    counterColumns.add(column.counter_super_column);\n                }\n\n                results.put(slice.getKey(), counterColumns);\n            }\n\n            entities = new ArrayList<Object>(results.size());\n\n            for (byte[] key : results.keySet()) {\n                Object e = null;\n                Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key);\n                List<CounterSuperColumn> counterSuperColumns = results.get(key);\n                ThriftRow tr = new ThriftRow(id, m.getTableName(), new ArrayList<Column>(0),\n                    new ArrayList<SuperColumn>(0), new ArrayList<CounterColumn>(0), counterSuperColumns);\n                e = getDataHandler().populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relations, isRelation);\n                entities.add(e);\n            }\n        } else {\n            if (log.isInfoEnabled()) {\n                log.info(\"On counter column for column family of entity {}\", m.getEntityClazz());\n            }\n\n            Map<byte[], List<CounterColumn>> results = new HashMap<byte[], List<CounterColumn>>();\n\n            List<CounterColumn> counterColumns = null;\n\n            for (KeySlice slice : ks) {\n                counterColumns = new ArrayList<CounterColumn>(slice.getColumnsSize());\n                for (ColumnOrSuperColumn column : slice.columns) {\n                    counterColumns.add(column.counter_column);\n                }\n\n                results.put(slice.getKey(), counterColumns);\n            }\n\n            entities = new ArrayList<Object>(results.size());\n\n            for (byte[] key : results.keySet()) {\n                Object e = null;\n                Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key);\n\n                List<CounterColumn> columns = results.get(key);\n                ThriftRow tr = new ThriftRow(id, m.getTableName(), new ArrayList<Column>(0),\n                    new ArrayList<SuperColumn>(0), columns, new ArrayList<CounterSuperColumn>(0));\n                e = getDataHandler().populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relations, isRelation);\n\n                if (e != null) {\n                    entities.add(e);\n                }\n            }\n        }\n        return entities;\n    }\n\n    /**\n     * Compute entity via columns.\n     * \n     * @param m\n     *            the m\n     * @param isRelation\n     *            the is relation\n     * @param relations\n     *            the relations\n     * @param entities\n     *            the entities\n     * @param qResults\n     *            the q results\n     */\n    protected void computeEntityViaColumns(EntityMetadata m, boolean isRelation, List<String> relations,\n        List<Object> entities, Map<ByteBuffer, List<Column>> qResults) {\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());\n\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n        List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n\n        for (ByteBuffer key : qResults.keySet()) {\n            onColumn(m, isRelation, relations, entities, qResults.get(key), subManagedType, key);\n        }\n    }\n\n    /**\n     * On column.\n     * \n     * @param m\n     *            the m\n     * @param isRelation\n     *            the is relation\n     * @param relations\n     *            the relations\n     * @param entities\n     *            the entities\n     * @param columns\n     *            the columns\n     * @param subManagedType\n     *            the sub managed type\n     * @param key\n     *            the key\n     */\n    protected void onColumn(EntityMetadata m, boolean isRelation, List<String> relations, List<Object> entities,\n        List<Column> columns, List<AbstractManagedType> subManagedType, ByteBuffer key) {\n        if (!columns.isEmpty()) {\n            Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key.array());\n            ThriftRow tr = new ThriftRow(id, m.getTableName(), columns, new ArrayList<SuperColumn>(0),\n                new ArrayList<CounterColumn>(0), new ArrayList<CounterSuperColumn>(0));\n            Object o = null;\n\n            if (!subManagedType.isEmpty()) {\n                for (AbstractManagedType subEntity : subManagedType) {\n                    EntityMetadata subEntityMetadata =\n                        KunderaMetadataManager.getEntityMetadata(kunderaMetadata, subEntity.getJavaType());\n\n                    o = getDataHandler().populateEntity(tr, subEntityMetadata, KunderaCoreUtils.getEntity(o),\n                        subEntityMetadata.getRelationNames(), isRelation);\n                    if (o != null) {\n                        break;\n                    }\n                }\n            } else {\n                o = getDataHandler().populateEntity(tr, m, KunderaCoreUtils.getEntity(o), relations, isRelation);\n            }\n\n            if (log.isInfoEnabled()) {\n                log.info(\"Populating data for entity of clazz {} and row key {}.\", m.getEntityClazz(), tr.getId());\n            }\n\n            if (o != null) {\n                entities.add(o);\n            }\n        }\n    }\n\n    /**\n     * Compute entity via super columns.\n     * \n     * @param m\n     *            the m\n     * @param isRelation\n     *            the is relation\n     * @param relations\n     *            the relations\n     * @param entities\n     *            the entities\n     * @param qResults\n     *            the q results\n     */\n    protected void computeEntityViaSuperColumns(EntityMetadata m, boolean isRelation, List<String> relations,\n        List<Object> entities, Map<ByteBuffer, List<SuperColumn>> qResults) {\n        for (ByteBuffer key : qResults.keySet()) {\n            onSuperColumn(m, isRelation, relations, entities, qResults.get(key), key);\n        }\n    }\n\n    /**\n     * On super column.\n     * \n     * @param m\n     *            the m\n     * @param isRelation\n     *            the is relation\n     * @param relations\n     *            the relations\n     * @param entities\n     *            the entities\n     * @param superColumns\n     *            the super columns\n     * @param key\n     *            the key\n     */\n    protected void onSuperColumn(EntityMetadata m, boolean isRelation, List<String> relations, List<Object> entities,\n        List<SuperColumn> superColumns, ByteBuffer key) {\n        Object e = null;\n        Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key.array());\n\n        ThriftRow tr = new ThriftRow(id, m.getTableName(), new ArrayList<Column>(0), superColumns,\n            new ArrayList<CounterColumn>(0), new ArrayList<CounterSuperColumn>(0));\n\n        e = getDataHandler().populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relations, isRelation);\n        if (log.isInfoEnabled()) {\n            log.info(\"Populating data for super column family of clazz {} and row key {}.\", m.getEntityClazz(),\n                tr.getId());\n        }\n\n        if (e != null) {\n            entities.add(e);\n        }\n    }\n\n    /**\n     * Adds relation foreign key values as thrift column/ value to thrift row.\n     * \n     * @param metadata\n     *            the metadata\n     * @param tf\n     *            the tf\n     * @param relations\n     *            the relations\n     */\n    protected void addRelationsToThriftRow(EntityMetadata metadata, ThriftRow tf, List<RelationHolder> relations) {\n        if (relations != null) {\n            long timestamp = generator.getTimestamp();\n            MetamodelImpl metaModel =\n                (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());\n            for (RelationHolder rh : relations) {\n                String linkName = rh.getRelationName();\n                Object linkValue = rh.getRelationValue();\n\n                if (linkName != null && linkValue != null) {\n                    if (metaModel.getEmbeddables(metadata.getEntityClazz()).isEmpty()) {\n                        if (metadata.isCounterColumnType()) {\n                            CounterColumn col = populateCounterFkey(linkName, linkValue);\n                            tf.addCounterColumn(col);\n                        } else {\n                            Column col = populateFkey(linkName, linkValue, timestamp);\n                            tf.addColumn(col);\n                        }\n\n                    } else {\n                        if (metadata.isCounterColumnType()) {\n                            CounterSuperColumn counterSuperColumn = new CounterSuperColumn();\n                            counterSuperColumn.setName(linkName.getBytes());\n                            CounterColumn column = populateCounterFkey(linkName, linkValue);\n                            counterSuperColumn.addToColumns(column);\n                            tf.addCounterSuperColumn(counterSuperColumn);\n                        } else {\n                            SuperColumn superColumn = new SuperColumn();\n                            superColumn.setName(linkName.getBytes());\n                            Column column = populateFkey(linkName, linkValue, timestamp);\n                            superColumn.addToColumns(column);\n                            tf.addSuperColumn(superColumn);\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * Populate counter fkey.\n     * \n     * @param rlName\n     *            the rl name\n     * @param rlValue\n     *            the rl value\n     * @return the counter column\n     */\n    private CounterColumn populateCounterFkey(String rlName, Object rlValue) {\n        CounterColumn counterCol = new CounterColumn();\n        counterCol.setName(PropertyAccessorFactory.STRING.toBytes(rlName));\n        counterCol.setValue((Long) rlValue);\n        return counterCol;\n    }\n\n    /**\n     * Deletes record for given primary key from counter column family.\n     * \n     * @param pKey\n     *            the key\n     * @param tableName\n     *            the table name\n     * @param metadata\n     *            the metadata\n     * @param consistencyLevel\n     *            the consistency level\n     */\n    protected void deleteRecordFromCounterColumnFamily(Object pKey, String tableName, EntityMetadata metadata,\n        ConsistencyLevel consistencyLevel) {\n        ColumnPath path = new ColumnPath(tableName);\n\n        Cassandra.Client conn = null;\n        Object pooledConnection = null;\n        try {\n            pooledConnection = getConnection();\n            conn = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);\n\n            if (log.isInfoEnabled()) {\n                log.info(\"Removing data for counter column family {}.\", tableName);\n            }\n\n            conn.remove_counter((CassandraUtilities.toBytes(pKey, metadata.getIdAttribute().getJavaType())), path,\n                consistencyLevel);\n\n        } catch (Exception e) {\n            log.error(\"Error during executing delete, Caused by: .\", e);\n            throw new PersistenceException(e);\n        } finally {\n            releaseConnection(pooledConnection);\n        }\n    }\n\n    /**\n     * Creates secondary indexes on columns if not already created.\n     * \n     * @param m\n     *            the m\n     * @param tableName\n     *            Column family name\n     * @param columns\n     *            List of columns\n     * @param columnType\n     *            the column type\n     */\n    protected void createIndexesOnColumns(EntityMetadata m, String tableName, List<Column> columns, Class columnType) {\n        Object pooledConnection = null;\n        try {\n            Cassandra.Client api = null;\n            pooledConnection = getConnection();\n            api = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);\n            KsDef ksDef = api.describe_keyspace(m.getSchema());\n            List<CfDef> cfDefs = ksDef.getCf_defs();\n\n            // Column family definition on which secondary index creation is\n            // required\n            CfDef columnFamilyDefToUpdate = null;\n            boolean isUpdatable = false;\n            for (CfDef cfDef : cfDefs) {\n                if (cfDef.getName().equals(tableName)) {\n                    columnFamilyDefToUpdate = cfDef;\n                    break;\n                }\n            }\n\n            if (columnFamilyDefToUpdate == null) {\n                log.error(\"Join table {} not available.\", tableName);\n                throw new PersistenceException(\"table\" + tableName + \" not found!\");\n            }\n            // create a column family, in case it is not already available.\n\n            // Get list of indexes already created\n            List<ColumnDef> columnMetadataList = columnFamilyDefToUpdate.getColumn_metadata();\n            List<String> indexList = new ArrayList<String>();\n\n            if (columnMetadataList != null) {\n                for (ColumnDef columnDef : columnMetadataList) {\n                    indexList.add(new StringAccessor().fromBytes(String.class, columnDef.getName()));\n                }\n                // need to set them to null else it is giving problem on update\n                // column family and trying to add again existing indexes.\n                // columnFamilyDefToUpdate.column_metadata = null;\n            }\n\n            // Iterate over all columns for creating secondary index on them\n            for (Column column : columns) {\n\n                ColumnDef columnDef = new ColumnDef();\n\n                columnDef.setName(column.getName());\n                columnDef.setValidation_class(CassandraValidationClassMapper.getValidationClass(columnType, false));\n                columnDef.setIndex_type(IndexType.KEYS);\n\n                // Add secondary index only if it's not already created\n                // (if already created, it would be there in column family\n                // definition)\n                if (!indexList.contains(new StringAccessor().fromBytes(String.class, column.getName()))) {\n                    isUpdatable = true;\n                    columnFamilyDefToUpdate.addToColumn_metadata(columnDef);\n                }\n            }\n\n            // Finally, update column family with modified column family\n            // definition\n            if (isUpdatable) {\n                columnFamilyDefToUpdate.setKey_validation_class(CassandraValidationClassMapper\n                    .getValidationClass(m.getIdAttribute().getJavaType(), isCql3Enabled(m)));\n                api.system_update_column_family(columnFamilyDefToUpdate);\n            }\n\n        } catch (Exception e) {\n            log.warn(\"Could not create secondary index on column family {}, Caused by: . \", tableName, e);\n\n        } finally {\n            releaseConnection(pooledConnection);\n        }\n    }\n\n    /**\n     * Finds an entiry from database.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param rowId\n     *            the row id\n     * @return the object\n     */\n    public Object find(Class entityClass, Object rowId) {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        List<String> relationNames = entityMetadata.getRelationNames();\n        return find(entityClass, entityMetadata, rowId, relationNames);\n    }\n\n    /**\n     * Finds a {@link List} of entities from database.\n     * \n     * @param <E>\n     *            the element type\n     * @param entityClass\n     *            the entity class\n     * @param columnsToSelect\n     *            TODO\n     * @param rowIds\n     *            the row ids\n     * @return the list\n     */\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... rowIds) {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        List<E> results = new ArrayList<E>();\n        results = find(entityClass, entityMetadata.getRelationNames(),\n            entityMetadata.getRelationNames() != null && !entityMetadata.getRelationNames().isEmpty(), entityMetadata,\n            rowIds);\n        return results.isEmpty() ? null : results;\n    }\n\n    /**\n     * Find.\n     * \n     * @param clazz\n     *            the clazz\n     * @param metadata\n     *            the metadata\n     * @param rowId\n     *            the row id\n     * @param relationNames\n     *            the relation names\n     * @return the object\n     */\n    private final Object find(Class<?> clazz, EntityMetadata metadata, Object rowId, List<String> relationNames) {\n\n        List<Object> result = null;\n        try {\n            MetamodelImpl metaModel =\n                (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());\n\n            EntityType entityType = metaModel.entity(clazz);\n\n            List<ManagedType> subTypes = ((AbstractManagedType) entityType).getSubManagedType();\n\n            if (!subTypes.isEmpty()) {\n                for (ManagedType subEntity : subTypes) {\n                    EntityMetadata subEntityMetadata =\n                        KunderaMetadataManager.getEntityMetadata(kunderaMetadata, subEntity.getJavaType());\n                    result = populate(clazz, subEntityMetadata, rowId, subEntityMetadata.getRelationNames(), metaModel);\n                    if (result != null && !result.isEmpty()) {\n                        break;\n                    }\n                }\n            } else {\n                result = populate(clazz, metadata, rowId, relationNames, metaModel);\n            }\n        } catch (Exception e) {\n            log.error(\"Error while retrieving records from database for entity {} and key {}, Caused by: .\", clazz,\n                rowId, e);\n\n            throw new PersistenceException(e);\n        }\n\n        return result != null && !result.isEmpty() ? result.get(0) : null;\n    }\n\n    /**\n     * Populate.\n     * \n     * @param clazz\n     *            the clazz\n     * @param metadata\n     *            the metadata\n     * @param rowId\n     *            the row id\n     * @param relationNames\n     *            the relation names\n     * @param metaModel\n     *            the meta model\n     * @return the list\n     */\n    private List<Object> populate(Class<?> clazz, EntityMetadata metadata, Object rowId, List<String> relationNames,\n        MetamodelImpl metaModel) {\n        List<Object> result;\n        if (isCql3Enabled(metadata)) {\n            result = cqlClient.find(metaModel, metadata, rowId, relationNames);\n        } else {\n            result = (List<Object>) find(clazz, relationNames, relationNames != null, metadata, rowId);\n        }\n        return result;\n    }\n\n    /**\n     * Returns true in case of, composite Id and if cql3 opted and not a embedded entity.\n     * \n     * @param metadata\n     *            the metadata\n     * @return true, if is cql3 enabled\n     */\n    public boolean isCql3Enabled(EntityMetadata metadata) {\n        if (metadata != null) {\n\n            MetamodelImpl metaModel =\n                (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());\n\n            if (metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {\n                return true;\n            }\n            // added for embeddables support on cql3\n            AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(metadata.getEntityClazz());\n            if (managedType.hasEmbeddableAttribute()) {\n                return getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0);\n            }\n\n            if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0)\n                && metadata.getType().equals(Type.SUPER_COLUMN_FAMILY)) {\n                log.warn(\n                    \"Super Columns not supported by cql, Any operation on supercolumn family will be executed using thrift, returning false.\");\n                return false;\n            }\n            return getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0);\n        }\n        return getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0);\n    }\n\n    /**\n     * Returns true in case of, composite Id and if cql3 opted and not a embedded entity.\n     * \n     * @return true, if is cql3 enabled\n     */\n    public boolean isCql3Enabled() {\n        return isCql3Enabled(null);\n    }\n\n    /**\n     * Find.\n     * \n     * @param <E>\n     *            the element type\n     * @param entityClass\n     *            the entity class\n     * @param superColumnMap\n     *            the super column map\n     * @param dataHandler\n     *            the data handler\n     * @return the list\n     */\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> superColumnMap,\n        CassandraDataHandler dataHandler) {\n        List<E> entities = null;\n        String entityId = null;\n        try {\n            EntityMetadata entityMetadata =\n                KunderaMetadataManager.getEntityMetadata(kunderaMetadata, getPersistenceUnit(), entityClass);\n            entities = new ArrayList<E>();\n            for (String superColumnName : superColumnMap.keySet()) {\n                entityId = superColumnMap.get(superColumnName);\n                List<SuperColumn> superColumnList =\n                    loadSuperColumns(entityMetadata.getSchema(), entityMetadata.getTableName(), entityId,\n                        new String[] { superColumnName.substring(0, superColumnName.indexOf(\"|\")) });\n                E e = (E) dataHandler.fromThriftRow(entityMetadata.getEntityClazz(), entityMetadata,\n                    new DataRow<SuperColumn>(entityId, entityMetadata.getTableName(), superColumnList));\n                if (e != null) {\n                    entities.add(e);\n                }\n            }\n        } catch (Exception e) {\n            log.error(\"Error while retrieving records from database for entity {} and key {}, Caused by: . \",\n                entityClass, entityId, e);\n            throw new KunderaException(e);\n        }\n        return entities;\n    }\n\n    /**\n     * Executes Select CQL Query.\n     * \n     * @param clazz\n     *            the clazz\n     * @param relationalField\n     *            the relational field\n     * @param dataHandler\n     *            the data handler\n     * @param isNative\n     *            the is native\n     * @param cqlQuery\n     *            the cql query\n     * @return the list\n     */\n    public List executeSelectQuery(Class clazz, List<String> relationalField, CassandraDataHandler dataHandler,\n        boolean isNative, String cqlQuery) {\n        if (log.isDebugEnabled()) {\n            log.debug(\"Executing cql query {}.\", cqlQuery);\n        }\n\n        List entities = new ArrayList<Object>();\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(entityMetadata.getPersistenceUnit());\n\n        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n\n        List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n\n        if (subManagedType.isEmpty()) {\n            entities.addAll(cqlClient.executeQuery(clazz, relationalField, dataHandler, true, isNative, cqlQuery));\n        } else {\n            for (AbstractManagedType subEntity : subManagedType) {\n                EntityMetadata subEntityMetadata =\n                    KunderaMetadataManager.getEntityMetadata(kunderaMetadata, subEntity.getJavaType());\n\n                entities.addAll(cqlClient.executeQuery(subEntityMetadata.getEntityClazz(), relationalField, dataHandler,\n                    true, isNative, cqlQuery));\n            }\n        }\n        return entities;\n    }\n\n    /**\n     * Execute scalar query.\n     * \n     * @param cqlQuery\n     *            the cql query\n     * @return the list\n     */\n    public List executeScalarQuery(String cqlQuery) {\n        CqlResult cqlResult = null;\n        List results = new ArrayList();\n        try {\n            if (log.isDebugEnabled()) {\n                log.debug(\"Executing query {}.\", cqlQuery);\n            }\n            cqlResult = (CqlResult) executeCQLQuery(cqlQuery, true);\n\n            if (cqlResult != null && (cqlResult.getRows() != null || cqlResult.getRowsSize() > 0)) {\n                results = new ArrayList<Object>(cqlResult.getRowsSize());\n                Iterator<CqlRow> iter = cqlResult.getRowsIterator();\n                while (iter.hasNext()) {\n                    Map<String, Object> entity = new HashMap<String, Object>();\n\n                    CqlRow row = iter.next();\n                    for (Column column : row.getColumns()) {\n                        if (column != null) {\n                            String thriftColumnName =\n                                PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());\n\n                            if (column.getValue() == null) {\n                                entity.put(thriftColumnName, null);\n                            } else {\n                                entity.put(thriftColumnName,\n                                    composeColumnValue(cqlResult.getSchema(), column.getValue(), column.getName()));\n                            }\n                        }\n                    }\n                    results.add(entity);\n                }\n            }\n        } catch (Exception e) {\n            log.error(\"Error while executing native CQL query Caused by {}.\", e);\n            throw new PersistenceException(e);\n        }\n        return results;\n    }\n\n    /**\n     * Compose column value.\n     * \n     * @param cqlMetadata\n     *            the cql metadata\n     * @param thriftColumnValue\n     *            the thrift column value\n     * @param thriftColumnName\n     *            the thrift column name\n     * @return the object\n     */\n    private Object composeColumnValue(CqlMetadata cqlMetadata, byte[] thriftColumnValue, byte[] thriftColumnName) {\n        Map<ByteBuffer, String> schemaTypes = cqlMetadata.getValue_types();\n        AbstractType<?> type = null;\n        try {\n            type = TypeParser.parse(schemaTypes.get(ByteBuffer.wrap(thriftColumnName)));\n        } catch (SyntaxException | ConfigurationException ex) {\n            log.error(ex.getMessage());\n            throw new KunderaException(\"Error while deserializing column value \" + ex);\n        }\n        if (type.isCollection()) {\n            return ((CollectionSerializer) type.getSerializer())\n                .deserializeForNativeProtocol(ByteBuffer.wrap(thriftColumnValue), ProtocolVersion.V2);\n        }\n        return type.compose(ByteBuffer.wrap(thriftColumnValue));\n    }\n\n    /**\n     * Executes Update/ Delete CQL query.\n     * \n     * @param cqlQuery\n     *            the cql query\n     * @return the int\n     */\n    public int executeUpdateDeleteQuery(String cqlQuery) {\n        if (log.isDebugEnabled()) {\n            log.debug(\"Executing cql query {}.\", cqlQuery);\n        }\n        try {\n            CqlResult result = (CqlResult) executeCQLQuery(cqlQuery, true);\n            return result.getNum();\n        } catch (Exception e) {\n            log.error(\"Error while executing updated query: {}, Caused by: . \", cqlQuery, e);\n            return 0;\n        }\n\n    }\n\n    /**\n     * Gets the external properties.\n     * \n     * @return the external properties\n     */\n    public Map<String, Object> getExternalProperties() {\n        return externalProperties;\n    }\n\n    /**\n     * Populate entities from key slices.\n     * \n     * @param m\n     *            the m\n     * @param isWrapReq\n     *            the is wrap req\n     * @param relations\n     *            the relations\n     * @param keys\n     *            the keys\n     * @param dataHandler\n     *            the data handler\n     * @return the list\n     * @throws Exception\n     *             the exception\n     */\n    protected List populateEntitiesFromKeySlices(EntityMetadata m, boolean isWrapReq, List<String> relations,\n        List<KeySlice> keys, CassandraDataHandler dataHandler) throws Exception {\n        List results;\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());\n\n        Set<String> superColumnAttribs = metaModel.getEmbeddables(m.getEntityClazz()).keySet();\n        results = new ArrayList(keys.size());\n\n        ThriftDataResultHelper dataGenerator = new ThriftDataResultHelper();\n        for (KeySlice key : keys) {\n            List<ColumnOrSuperColumn> columns = key.getColumns();\n\n            byte[] rowKey = key.getKey();\n\n            Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), rowKey);\n\n            Object e = null;\n            Map<ByteBuffer, List<ColumnOrSuperColumn>> data = new HashMap<ByteBuffer, List<ColumnOrSuperColumn>>(1);\n            data.put(ByteBuffer.wrap(rowKey), columns);\n            ThriftRow tr = new ThriftRow();\n            tr.setId(id);\n            tr.setColumnFamilyName(m.getTableName());\n            tr = dataGenerator.translateToThriftRow(data, m.isCounterColumnType(), m.getType(), tr);\n\n            e = dataHandler.populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relations, isWrapReq);\n\n            if (e != null) {\n                results.add(e);\n            }\n        }\n        return results;\n    }\n\n    /**\n     * Return insert query string for given entity.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @param cassandra_client\n     *            the cassandra_client\n     * @param rlHolders\n     *            the rl holders\n     * @param ttlColumns\n     *            TTL values for each columns\n     * @return the list\n     */\n    protected List<String> createInsertQuery(EntityMetadata entityMetadata, Object entity,\n        Cassandra.Client cassandra_client, List<RelationHolder> rlHolders, Object ttlColumns) {\n        List<String> insert_Queries = new ArrayList<String>();\n        CQLTranslator translator = new CQLTranslator();\n        HashMap<TranslationType, Map<String, StringBuilder>> translation = translator.prepareColumnOrColumnValues(\n            entity, entityMetadata, TranslationType.ALL, externalProperties, kunderaMetadata);\n\n        Map<String, StringBuilder> columnNamesMap = translation.get(TranslationType.COLUMN);\n        Map<String, StringBuilder> columnValuesMap = translation.get(TranslationType.VALUE);\n\n        for (String tableName : columnNamesMap.keySet()) {\n            String insert_Query = translator.INSERT_QUERY;\n\n            insert_Query = StringUtils.replace(insert_Query, CQLTranslator.COLUMN_FAMILY,\n                translator.ensureCase(new StringBuilder(), tableName, false).toString());\n            String columnNames = columnNamesMap.get(tableName).toString();\n            String columnValues = columnValuesMap.get(tableName).toString();\n\n            StringBuilder columnNameBuilder = new StringBuilder(columnNames);\n            StringBuilder columnValueBuilder = new StringBuilder(columnValues);\n\n            for (RelationHolder rl : rlHolders) {\n                columnValueBuilder =\n                    onRelationColumns(columnNames, columnValues, columnNameBuilder, columnValueBuilder, rl);\n\n                columnNameBuilder.append(\",\");\n                columnValueBuilder.append(\",\");\n                translator.appendColumnName(columnNameBuilder, rl.getRelationName());\n                translator.appendValue(columnValueBuilder, rl.getRelationValue().getClass(), rl.getRelationValue(),\n                    true, false);\n\n            }\n\n            insert_Query =\n                StringUtils.replace(insert_Query, CQLTranslator.COLUMN_VALUES, columnValueBuilder.toString());\n            insert_Query = StringUtils.replace(insert_Query, CQLTranslator.COLUMNS, columnNameBuilder.toString());\n\n            if (log.isDebugEnabled()) {\n                log.debug(\"Returning cql query {}.\", insert_Query);\n            }\n\n            if (ttlColumns != null && ttlColumns instanceof Integer) {\n                int ttl = ((Integer) ttlColumns).intValue();\n                if (ttl != 0) {\n                    insert_Query = insert_Query + \" USING TTL \" + ttl;\n                }\n            }\n            insert_Queries.add(insert_Query);\n        }\n        return insert_Queries;\n    }\n\n    /**\n     * On relation columns.\n     * \n     * @param columnNames\n     *            the column names\n     * @param columnValues\n     *            the column values\n     * @param columnNameBuilder\n     *            the column name builder\n     * @param columnValueBuilder\n     *            the column value builder\n     * @param rl\n     *            the rl\n     * @return To remove redundant columns in insert query\n     */\n    private StringBuilder onRelationColumns(String columnNames, String columnValues, StringBuilder columnNameBuilder,\n        StringBuilder columnValueBuilder, RelationHolder rl) {\n        int relnameIndx = columnNameBuilder.indexOf(\"\\\"\" + rl.getRelationName() + \"\\\"\");\n        if (relnameIndx != -1 && rl.getRelationValue() != null) {\n\n            List<String> cNameArray = Arrays.asList(columnNames.split(\",\"));\n            List<String> cValueArray = new ArrayList<String>(Arrays.asList(columnValues.split(\",\")));\n            int cValueIndex = cNameArray.indexOf(\"\\\"\" + rl.getRelationName() + \"\\\"\");\n\n            if (cValueArray.get(cValueIndex).equals(\"null\")) {\n                columnNameBuilder.delete(relnameIndx - 1, relnameIndx + rl.getRelationName().length() + 2);\n                cValueArray.remove(cValueIndex);\n                columnValueBuilder =\n                    new StringBuilder(cValueArray.toString().substring(1, cValueArray.toString().length() - 1));\n\n            }\n\n        }\n        return columnValueBuilder;\n    }\n\n    /**\n     * Return update query string for given entity intended for counter column family.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @param cassandra_client\n     *            the cassandra_client\n     * @param rlHolders\n     *            the rl holders\n     * @return the list\n     */\n    protected List<String> createUpdateQueryForCounter(EntityMetadata entityMetadata, Object entity,\n        Cassandra.Client cassandra_client, List<RelationHolder> rlHolders) {\n        Map<String, String> builders = new HashMap<String, String>();\n\n        CQLTranslator translator = new CQLTranslator();\n\n        Object rowId = PropertyAccessorHelper.getId(entity, entityMetadata);\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(entityMetadata.getPersistenceUnit());\n\n        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n\n        Set<Attribute> attributes = entityType.getAttributes();\n\n        for (Attribute attrib : attributes) {\n            if (!entityMetadata.getIdAttribute().getName().equals(attrib.getName())\n                && !metaModel.isEmbeddable(attrib.getJavaType()) && !attrib.isAssociation()) {\n                String tableName = ((AbstractAttribute) attrib).getTableName() != null\n                    ? ((AbstractAttribute) attrib).getTableName() : entityMetadata.getTableName();\n\n                String queryString = builders.get(tableName);\n                StringBuilder builder;\n                if (queryString == null) {\n                    builder = new StringBuilder();\n                } else {\n                    builder = new StringBuilder(queryString);\n                }\n                translator.buildSetClauseForCounters(builder, ((AbstractAttribute) attrib).getJPAColumnName(),\n                    PropertyAccessorHelper.getObject(entity, attrib.getName()));\n                builders.put(tableName, builder.toString());\n            }\n        }\n        for (RelationHolder rl : rlHolders) {\n            translator.buildSetClauseForCounters(new StringBuilder(builders.get(entityMetadata.getTableName())),\n                rl.getRelationName(), rl.getRelationValue());\n        }\n\n        for (String tableName : builders.keySet()) {\n            StringBuilder builder = new StringBuilder(builders.get(tableName));\n\n            String update_Query = translator.UPDATE_QUERY;\n\n            update_Query = StringUtils.replace(update_Query, CQLTranslator.COLUMN_FAMILY,\n                translator.ensureCase(new StringBuilder(), tableName, false).toString());\n\n            // strip last \",\" clause.\n            builder.delete(builder.lastIndexOf(CQLTranslator.COMMA_STR), builder.length());\n\n            builder.append(CQLTranslator.ADD_WHERE_CLAUSE);\n            onWhereClause(entityMetadata, rowId, translator, builder, metaModel, entityMetadata.getIdAttribute());\n\n            // strip last \"AND\" clause.\n            builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length());\n\n            StringBuilder queryBuilder = new StringBuilder(update_Query);\n            queryBuilder.append(CQLTranslator.ADD_SET_CLAUSE);\n            queryBuilder.append(builder);\n\n            if (log.isDebugEnabled()) {\n                log.debug(\"Returning update query {}.\", queryBuilder.toString());\n            }\n\n            builders.put(tableName, queryBuilder.toString());\n        }\n        return new ArrayList(builders.values());\n    }\n\n    /**\n     * Gets the persist queries.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @param conn\n     *            the conn\n     * @param rlHolders\n     *            the rl holders\n     * @param ttlColumns\n     *            the ttl columns\n     * @return the persist queries\n     */\n    protected List<String> getPersistQueries(EntityMetadata entityMetadata, Object entity,\n        org.apache.cassandra.thrift.Cassandra.Client conn, List<RelationHolder> rlHolders, Object ttlColumns) {\n        List<String> queries;\n        if (entityMetadata.isCounterColumnType()) {\n            queries = createUpdateQueryForCounter(entityMetadata, entity, conn, rlHolders);\n        } else {\n            queries = createInsertQuery(entityMetadata, entity, conn, rlHolders, ttlColumns);\n        }\n        return queries;\n    }\n\n    /**\n     * Gets the cql version.\n     * \n     * @return the cqlVersion\n     */\n    protected String getCqlVersion() {\n        return this.cqlVersion;\n    }\n\n    /**\n     * Sets the cql version.\n     * \n     * @param cqlVersion\n     *            the cqlVersion to set\n     */\n    public void setCqlVersion(String cqlVersion) {\n        this.cqlVersion = cqlVersion;\n    }\n\n    /**\n     * Sets the consistency level.\n     * \n     * @param cLevel\n     *            the new consistency level\n     */\n    public void setConsistencyLevel(ConsistencyLevel cLevel) {\n        if (cLevel != null) {\n            this.consistencyLevel = cLevel;\n        } else {\n            log.warn(\"Invalid consistency level {null} provided, default level will be used.\");\n        }\n    }\n\n    /**\n     * Close.\n     */\n    public void close() {\n        clear();\n        setCqlVersion(CassandraConstants.CQL_VERSION_2_0);\n        closed = true;\n        externalProperties = null;\n    }\n\n    /**\n     * Checks if is open.\n     * \n     * @return true, if is open\n     */\n    protected final boolean isOpen() {\n        return !closed;\n    }\n\n    /**\n     * Gets the consistency level.\n     * \n     * @return the consistency level\n     */\n    public ConsistencyLevel getConsistencyLevel() {\n        return consistencyLevel;\n    }\n\n    /**\n     * On delete query.\n     * \n     * @param metadata\n     *            the metadata\n     * @param tableName\n     *            TODO\n     * @param metaModel\n     *            the meta model\n     * @param keyObject\n     *            the compound key object\n     * @return the string\n     */\n    protected String onDeleteQuery(EntityMetadata metadata, String tableName, MetamodelImpl metaModel,\n        Object keyObject) {\n        CQLTranslator translator = new CQLTranslator();\n        String deleteQuery = CQLTranslator.DELETE_QUERY;\n\n        deleteQuery = StringUtils.replace(deleteQuery, CQLTranslator.COLUMN_FAMILY,\n            translator.ensureCase(new StringBuilder(), tableName, false).toString());\n\n        StringBuilder deleteQueryBuilder = new StringBuilder(deleteQuery);\n\n        deleteQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE);\n        onWhereClause(metadata, keyObject, translator, deleteQueryBuilder, metaModel, metadata.getIdAttribute());\n\n        // strip last \"AND\" clause.\n        deleteQueryBuilder.delete(deleteQueryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE),\n            deleteQueryBuilder.length());\n\n        if (log.isDebugEnabled()) {\n            log.debug(\"Returning delete query {}.\", deleteQueryBuilder.toString());\n        }\n        return deleteQueryBuilder.toString();\n    }\n\n    /**\n     * On where clause.\n     * \n     * @param metadata\n     *            the metadata\n     * @param key\n     *            the compound key object\n     * @param translator\n     *            the translator\n     * @param queryBuilder\n     *            the query builder\n     * @param metaModel\n     *            the meta model\n     * @param attribute\n     *            the attribute\n     */\n    protected void onWhereClause(EntityMetadata metadata, Object key, CQLTranslator translator,\n        StringBuilder queryBuilder, MetamodelImpl metaModel, SingularAttribute attribute) {\n        // SingularAttribute idAttribute = metadata.getIdAttribute();\n        if (metaModel.isEmbeddable(attribute.getBindableJavaType())) {\n            Field[] fields = attribute.getBindableJavaType().getDeclaredFields();\n            EmbeddableType compoundKey = metaModel.embeddable(attribute.getBindableJavaType());\n\n            for (Field field : fields) {\n                if (field != null && !Modifier.isStatic(field.getModifiers())\n                    && !Modifier.isTransient(field.getModifiers()) && !field.isAnnotationPresent(Transient.class)) {\n                    attribute = (SingularAttribute) compoundKey.getAttribute(field.getName());\n                    Object valueObject = PropertyAccessorHelper.getObject(key, field);\n                    if (metaModel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) {\n                        onWhereClause(metadata, valueObject, translator, queryBuilder, metaModel, attribute);\n                    } else {\n                        String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                        translator.buildWhereClause(queryBuilder, field.getType(), columnName, valueObject,\n                            CQLTranslator.EQ_CLAUSE, false);\n                    }\n                }\n            }\n        } else {\n            translator.buildWhereClause(\n                queryBuilder, ((AbstractAttribute) attribute).getBindableJavaType(), CassandraUtilities\n                    .getIdColumnName(kunderaMetadata, metadata, getExternalProperties(), isCql3Enabled(metadata)),\n                key, translator.EQ_CLAUSE, false);\n        }\n    }\n\n    /**\n     * Find.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @param metadata\n     *            the metadata\n     * @param rowIds\n     *            the row ids\n     * @return the list\n     */\n    public abstract List find(Class entityClass, List<String> relationNames, boolean isWrapReq, EntityMetadata metadata,\n        Object... rowIds);\n\n    /**\n     * Load super columns.\n     * \n     * @param keyspace\n     *            the keyspace\n     * @param columnFamily\n     *            the column family\n     * @param rowId\n     *            the row id\n     * @param superColumnNames\n     *            the super column names\n     * @return the list\n     */\n    protected abstract List<SuperColumn> loadSuperColumns(String keyspace, String columnFamily, String rowId,\n        String... superColumnNames);\n\n    /**\n     * Query related methods.\n     * \n     * @param clazz\n     *            the clazz\n     * @param relationalField\n     *            the relational field\n     * @param isNative\n     *            the is native\n     * @param cqlQuery\n     *            the cql query\n     * @return the list\n     */\n    public abstract List executeQuery(Class clazz, List<String> relationalField, boolean isNative, String cqlQuery);\n\n    // XXX\n    public List executeQuery(Class clazz, List<String> relationalField, boolean isNative, String cqlQuery,\n        final List<KunderaQuery.BindParameter> parameters) {\n        throw new KunderaException(\"not implemented\");\n    }\n\n    /**\n     * Find.\n     * \n     * @param ixClause\n     *            the ix clause\n     * @param m\n     *            the m\n     * @param isRelation\n     *            the is relation\n     * @param relations\n     *            the relations\n     * @param maxResult\n     *            the max result\n     * @param columns\n     *            the columns\n     * @return the list\n     */\n    public abstract List find(List<IndexClause> ixClause, EntityMetadata m, boolean isRelation, List<String> relations,\n        int maxResult, List<String> columns);\n\n    /**\n     * Find by range.\n     * \n     * @param muinVal\n     *            the muin val\n     * @param maxVal\n     *            the max val\n     * @param m\n     *            the m\n     * @param isWrapReq\n     *            the is wrap req\n     * @param relations\n     *            the relations\n     * @param columns\n     *            the columns\n     * @param conditions\n     *            the conditions\n     * @param maxResults\n     *            the max results\n     * @return the list\n     * @throws Exception\n     *             the exception\n     */\n    public abstract List findByRange(byte[] muinVal, byte[] maxVal, EntityMetadata m, boolean isWrapReq,\n        List<String> relations, List<String> columns, List<IndexExpression> conditions, int maxResults)\n        throws Exception;\n\n    /**\n     * Search in inverted index.\n     * \n     * @param columnFamilyName\n     *            the column family name\n     * @param m\n     *            the m\n     * @param indexClauseMap\n     *            the index clause map\n     * @return the list\n     */\n    public abstract List<SearchResult> searchInInvertedIndex(String columnFamilyName, EntityMetadata m,\n        Map<Boolean, List<IndexClause>> indexClauseMap);\n\n    /**\n     * Find.\n     * \n     * @param m\n     *            the m\n     * @param relationNames\n     *            the relation names\n     * @param conditions\n     *            the conditions\n     * @param maxResult\n     *            the max result\n     * @param columns\n     *            the columns\n     * @return the list\n     */\n    public abstract List<EnhanceEntity> find(EntityMetadata m, List<String> relationNames, List<IndexClause> conditions,\n        int maxResult, List<String> columns);\n\n    /**\n     * Gets the data handler.\n     * \n     * @return the data handler\n     */\n    protected abstract CassandraDataHandler getDataHandler();\n\n    /**\n     * Delete.\n     * \n     * @param entity\n     *            the entity\n     * @param pKey\n     *            the key\n     */\n    protected abstract void delete(Object entity, Object pKey);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#addBatch(com.impetus.kundera .graph.Node)\n     */\n    /**\n     * Adds the batch.\n     * \n     * @param node\n     *            the node\n     */\n    public void addBatch(Node node) {\n\n        if (node != null) {\n            nodes.add(node);\n        }\n\n        onBatchLimit();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#getBatchSize()\n     */\n    /**\n     * Gets the batch size.\n     * \n     * @return the batch size\n     */\n    public int getBatchSize() {\n        return batchSize;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#clear()\n     */\n    /**\n     * Clear.\n     */\n    public void clear() {\n        if (nodes != null) {\n            nodes.clear();\n            nodes = new ArrayList<Node>();\n        }\n\n        if (ttlPerSession) {\n            ttlValues.clear();\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#executeBatch()\n     */\n    /**\n     * Execute batch.\n     * \n     * @return the int\n     */\n    public int executeBatch() {\n        Cassandra.Client conn = null;\n        Object pooledConnection = null;\n\n        /**\n         * Key -> Entity Class Value -> Map containing Row ID as Key and Mutation List as Value\n         */\n        Map<Class<?>, Map<ByteBuffer, Map<String, List<Mutation>>>> batchMutationMap =\n            new HashMap<Class<?>, Map<ByteBuffer, Map<String, List<Mutation>>>>();\n\n        int recordsExecuted = 0;\n        boolean setCounter = true;\n        String batchQuery = CQLTranslator.BATCH_QUERY;\n        batchQuery = StringUtils.replace(batchQuery, CQLTranslator.STATEMENT, \"\");\n        StringBuilder batchQueryBuilder = new StringBuilder(batchQuery);\n        try {\n            boolean isCql3Enabled = false;\n            for (Node node : nodes) {\n                if (node.isDirty()) {\n                    node.handlePreEvent();\n                    Object entity = node.getData();\n                    Object id = node.getEntityId();\n                    EntityMetadata metadata =\n                        KunderaMetadataManager.getEntityMetadata(kunderaMetadata, node.getDataClass());\n                    if (metadata.isCounterColumnType() && setCounter) {\n                        batchQueryBuilder = new StringBuilder(StringUtils.replace(batchQueryBuilder.toString(),\n                            CQLTranslator.BEGIN_BATCH, CQLTranslator.BEGIN_COUNTER_BATCH));\n                        setCounter = false;\n                    }\n                    persistenceUnit = metadata.getPersistenceUnit();\n                    isUpdate = node.isUpdate();\n\n                    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                        .getMetamodel(metadata.getPersistenceUnit());\n\n                    // delete can not be executed in batch\n\n                    if (isCql3Enabled(metadata)) {\n                        isCql3Enabled = true;\n                        List<RelationHolder> relationHolders = getRelationHolders(node);\n                        if (node.isInState(RemovedState.class)) {\n                            String query;\n                            query = onDeleteQuery(metadata, metadata.getTableName(), metaModel, id);\n                            batchQueryBuilder.append(Constants.SPACE);\n                            batchQueryBuilder.append(query);\n                        } else {\n                            List<String> insertQueries = getPersistQueries(metadata, entity, conn, relationHolders,\n                                getTtlValues().get(metadata.getTableName()));\n                            for (String query : insertQueries) {\n                                batchQueryBuilder.append(Constants.SPACE);\n                                batchQueryBuilder.append(query);\n                            }\n                        }\n                    } else {\n                        if (node.isInState(RemovedState.class)) {\n                            delete(entity, id);\n                        } else {\n                            List<RelationHolder> relationHolders = getRelationHolders(node);\n                            Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap =\n                                new HashMap<ByteBuffer, Map<String, List<Mutation>>>();\n                            mutationMap = prepareMutation(metadata, entity, id, relationHolders, mutationMap);\n\n                            recordsExecuted += mutationMap.size();\n                            if (!batchMutationMap.containsKey(metadata.getEntityClazz())) {\n                                batchMutationMap.put(metadata.getEntityClazz(), mutationMap);\n                            } else {\n                                batchMutationMap.get(metadata.getEntityClazz()).putAll(mutationMap);\n                            }\n\n                            indexNode(node, metadata);\n                        }\n                    }\n                    node.handlePostEvent();\n                }\n            }\n\n            // Write Mutation map to database\n\n            if (!batchMutationMap.isEmpty()) {\n                pooledConnection = getConnection();\n                conn = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);\n\n                for (Class<?> entityClass : batchMutationMap.keySet()) {\n                    conn.batch_mutate(batchMutationMap.get(entityClass), consistencyLevel);\n                }\n            }\n\n            if (!nodes.isEmpty() && isCql3Enabled) {\n                batchQueryBuilder.append(CQLTranslator.APPLY_BATCH);\n                executeCQLQuery(batchQueryBuilder.toString(), isCql3Enabled);\n            }\n        } catch (Exception e) {\n            log.error(\"Error while persisting record. Caused by: .\", e);\n            throw new KunderaException(e);\n        } finally {\n            clear();\n            if (pooledConnection != null) {\n                releaseConnection(pooledConnection);\n            }\n        }\n\n        return recordsExecuted;\n    }\n\n    /**\n     * Prepare mutation.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @param id\n     *            the id\n     * @param relationHolders\n     *            the relation holders\n     * @param mutationMap\n     *            the mutation map\n     * @return the map\n     */\n    protected Map<ByteBuffer, Map<String, List<Mutation>>> prepareMutation(EntityMetadata entityMetadata, Object entity,\n        Object id, List<RelationHolder> relationHolders, Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap) {\n\n        if (!isOpen()) {\n            throw new PersistenceException(\"ThriftClient is closed.\");\n        }\n\n        // check for counter column\n        if (isUpdate && entityMetadata.isCounterColumnType()) {\n            log.warn(\"Invalid operation! {} is not possible over counter column of entity {}.\", \"Merge\",\n                entityMetadata.getEntityClazz());\n            throw new UnsupportedOperationException(\"Invalid operation! Merge is not possible over counter column.\");\n        }\n\n        Collection<ThriftRow> tfRows = null;\n        try {\n            String columnFamily = entityMetadata.getTableName();\n            tfRows = getDataHandler().toThriftRow(entity, id, entityMetadata, columnFamily,\n                getTtlValues().get(columnFamily));\n        } catch (Exception e) {\n            log.error(\"Error during persisting record for entity {}, Caused by: .\", entityMetadata.getEntityClazz(),\n                entityMetadata.getTableName(), e);\n            throw new KunderaException(e);\n        }\n\n        Map<String, List<Mutation>> columnFamilyValues = new HashMap<String, List<Mutation>>();\n\n        for (ThriftRow tf : tfRows) {\n            if (tf.getColumnFamilyName().equals(entityMetadata.getTableName())) {\n                addRelationsToThriftRow(entityMetadata, tf, relationHolders);\n            }\n\n            String columnFamily = tf.getColumnFamilyName();\n            // Create Insertion List\n            List<Mutation> mutationList = new ArrayList<Mutation>();\n\n            /*********** Handling for counter column family ************/\n\n            if (entityMetadata.isCounterColumnType()) {\n                List<CounterColumn> thriftCounterColumns = tf.getCounterColumns();\n                List<CounterSuperColumn> thriftCounterSuperColumns = tf.getCounterSuperColumns();\n\n                if (thriftCounterColumns != null && !thriftCounterColumns.isEmpty()) {\n                    for (CounterColumn column : thriftCounterColumns) {\n                        Mutation mut = new Mutation();\n                        mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setCounter_column(column));\n                        mutationList.add(mut);\n                    }\n                }\n\n                if (thriftCounterSuperColumns != null && !thriftCounterSuperColumns.isEmpty()) {\n                    for (CounterSuperColumn sc : thriftCounterSuperColumns) {\n                        Mutation mut = new Mutation();\n                        mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setCounter_super_column(sc));\n                        mutationList.add(mut);\n                    }\n                }\n            } else\n            /********* Handling for column family and super column family *********/\n            {\n                List<Column> thriftColumns = tf.getColumns();\n                List<SuperColumn> thriftSuperColumns = tf.getSuperColumns();\n\n                // Populate Insertion list for columns\n                if (thriftColumns != null && !thriftColumns.isEmpty()) {\n                    for (Column column : thriftColumns) {\n                        Mutation mut = new Mutation();\n                        mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setColumn(column));\n                        mutationList.add(mut);\n                    }\n                }\n\n                // Populate Insertion list for super columns\n                if (thriftSuperColumns != null && !thriftSuperColumns.isEmpty()) {\n                    for (SuperColumn superColumn : thriftSuperColumns) {\n                        Mutation mut = new Mutation();\n                        mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setSuper_column(superColumn));\n                        mutationList.add(mut);\n                    }\n                }\n            }\n            columnFamilyValues.put(columnFamily, mutationList);\n        }\n        // Create Mutation Map\n\n        ByteBuffer b = CassandraUtilities.toBytes(id, entityMetadata.getIdAttribute().getBindableJavaType());\n        mutationMap.put(b, columnFamilyValues);\n\n        return mutationMap;\n    }\n\n    /**\n     * Check on batch limit.\n     */\n    private void onBatchLimit() {\n        if (batchSize > 0 && batchSize == nodes.size()) {\n            executeBatch();\n            nodes.clear();\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientPropertiesSetter#populateClientProperties\n     * (com.impetus.kundera.client.Client, java.util.Map)\n     */\n    @Override\n    public void populateClientProperties(Client client, Map<String, Object> properties) {\n        new CassandraClientProperties().populateClientProperties(client, properties);\n    }\n\n    /**\n     * Returns raw cassandra client from thrift connection pool.\n     * \n     * @param schema\n     *            schema or keyspace.\n     * @return raw cassandra client.\n     */\n    public Cassandra.Client getRawClient(final String schema) {\n        Cassandra.Client client = null;\n        Object pooledConnection;\n        pooledConnection = getConnection();\n        client = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);\n        try {\n            client.set_cql_version(getCqlVersion());\n        } catch (Exception e) {\n            log.error(\"Error during borrowing a connection , Caused by: {}.\", e);\n            throw new KunderaException(e);\n        } finally {\n            releaseConnection(pooledConnection);\n        }\n        return client;\n\n    }\n\n    /**\n     * Executes query string using cql3.\n     * \n     * @param cqlQuery\n     *            the cql query\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return the object\n     */\n    protected Object executeCQLQuery(String cqlQuery, boolean isCql3Enabled) {\n        Cassandra.Client conn = null;\n        Object pooledConnection = null;\n        pooledConnection = getConnection();\n        conn = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);\n        try {\n            if (isCql3Enabled || isCql3Enabled()) {\n                return execute(cqlQuery, conn);\n            }\n            KunderaCoreUtils.printQuery(cqlQuery, showQuery);\n            if (log.isDebugEnabled()) {\n                log.debug(\"Executing cql query {}.\", cqlQuery);\n            }\n            return conn.execute_cql_query(ByteBufferUtil.bytes(cqlQuery), org.apache.cassandra.thrift.Compression.NONE);\n        } catch (Exception ex) {\n            if (log.isErrorEnabled()) {\n                log.error(\"Error during executing query {}, Caused by: {} .\", cqlQuery, ex);\n            }\n            throw new PersistenceException(ex);\n        } finally {\n            releaseConnection(pooledConnection);\n        }\n    }\n\n    /**\n     * Find List of objects based on value {@columnValue} of column {@columnName}.\n     * \n     * @param m\n     *            the m\n     * @param columnName\n     *            the column name\n     * @param columnValue\n     *            the column value\n     * @param clazz\n     *            the clazz\n     * @param dataHandler\n     *            the data handler\n     * @return the list\n     */\n    protected List<Object> findByRelationQuery(EntityMetadata m, String columnName, Object columnValue, Class clazz,\n        CassandraDataHandler dataHandler) {\n        return cqlClient.findByRelationQuery(m, columnName, columnValue, clazz, dataHandler);\n    }\n\n    /**\n     * Sets the batch size.\n     * \n     * @param persistenceUnit\n     *            the persistence unit\n     * @param puProperties\n     *            the pu properties\n     */\n    private void setBatchSize(String persistenceUnit, Map<String, Object> puProperties) {\n        String batch_Size = null;\n\n        PersistenceUnitMetadata puMetadata =\n            KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata, persistenceUnit);\n\n        String externalBatchSize =\n            puProperties != null ? (String) puProperties.get(PersistenceProperties.KUNDERA_BATCH_SIZE) : null;\n\n        Integer intbatch = null;\n        if (puMetadata.getBatchSize() > 0) {\n            intbatch = new Integer(puMetadata.getBatchSize());\n        }\n        batch_Size =\n            (String) (externalBatchSize != null ? externalBatchSize : intbatch != null ? intbatch.toString() : null);\n\n        setBatchSize(batch_Size);\n    }\n\n    /**\n     * Sets the batch size.\n     * \n     * @param batch_Size\n     *            the new batch size\n     */\n    void setBatchSize(String batch_Size) {\n        if (!StringUtils.isBlank(batch_Size)) {\n            batchSize = Integer.valueOf(batch_Size);\n            if (batchSize == 0) {\n                throw new IllegalArgumentException(\"kundera.batch.size property must be numeric and > 0.\");\n            }\n        }\n    }\n\n    /**\n     * Populate cql version.\n     * \n     * @param externalProperties\n     *            the external properties\n     */\n    private void populateCqlVersion(Map<String, Object> externalProperties) {\n        String cqlVersion =\n            externalProperties != null ? (String) externalProperties.get(CassandraConstants.CQL_VERSION) : null;\n        if (cqlVersion == null || !(cqlVersion != null && (cqlVersion.equals(CassandraConstants.CQL_VERSION_2_0)\n            || cqlVersion.equals(CassandraConstants.CQL_VERSION_3_0)))) {\n            cqlVersion = (CassandraPropertyReader.csmd != null ? CassandraPropertyReader.csmd.getCqlVersion()\n                : CassandraConstants.CQL_VERSION_2_0);\n        }\n\n        if (cqlVersion.equals(CassandraConstants.CQL_VERSION_3_0)) {\n            setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n        } else {\n            setCqlVersion(CassandraConstants.CQL_VERSION_2_0);\n        }\n    }\n\n    /**\n     * Gets the connection.\n     * \n     * @return the connection\n     */\n    protected abstract Object getConnection();\n\n    /**\n     * Gets the connection.\n     * \n     * @param connection\n     *            the connection\n     * @return the connection\n     */\n    protected abstract Object getConnection(Object connection);\n\n    /**\n     * Release connection.\n     * \n     * @param conn\n     *            the conn\n     */\n    protected abstract void releaseConnection(Object conn);\n\n    /**\n     * Use CqlClient class for crud when cql enable.\n     * \n     * \n     * @author Kuldeep Mishra\n     * \n     */\n    protected class CQLClient {\n\n        /**\n         * Persist.\n         * \n         * @param entityMetadata\n         *            the entity metadata\n         * @param entity\n         *            the entity\n         * @param conn\n         *            the conn\n         * @param rlHolders\n         *            the rl holders\n         * @param ttlColumns\n         *            the ttl columns\n         * @throws UnsupportedEncodingException\n         *             the unsupported encoding exception\n         * @throws InvalidRequestException\n         *             the invalid request exception\n         * @throws TException\n         *             the t exception\n         * @throws UnavailableException\n         *             the unavailable exception\n         * @throws TimedOutException\n         *             the timed out exception\n         * @throws SchemaDisagreementException\n         *             the schema disagreement exception\n         */\n        public void persist(EntityMetadata entityMetadata, Object entity,\n            org.apache.cassandra.thrift.Cassandra.Client conn, List<RelationHolder> rlHolders, Object ttlColumns)\n            throws UnsupportedEncodingException, InvalidRequestException, TException, UnavailableException,\n            TimedOutException, SchemaDisagreementException {\n            List<String> queries = getPersistQueries(entityMetadata, entity, conn, rlHolders, ttlColumns);\n\n            for (String query : queries) {\n                execute(query, conn);\n\n            }\n        }\n\n        /**\n         * Execute query and Return list of Objects.\n         * \n         * @param clazz\n         *            the clazz\n         * @param relationalField\n         *            the relational field\n         * @param dataHandler\n         *            the data handler\n         * @param isCql3Enabled\n         *            the is cql3 enabled\n         * @param isNative\n         *            the is native\n         * @param cqlQuery\n         *            the cql query\n         * @return the list\n         */\n        public List executeQuery(Class clazz, List<String> relationalField, CassandraDataHandler dataHandler,\n            boolean isCql3Enabled, boolean isNative, String cqlQuery) {\n            EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n\n            CqlResult result = null;\n            List returnedEntities = new ArrayList();\n            try {\n                if (log.isDebugEnabled()) {\n                    log.debug(\"Executing query {}.\", cqlQuery);\n                }\n                result = (CqlResult) executeCQLQuery(cqlQuery, isCql3Enabled);\n\n                setCqlMetadata(result.getSchema());\n\n                if (result != null && (result.getRows() != null || result.getRowsSize() > 0)) {\n                    returnedEntities = new ArrayList<Object>(result.getRowsSize());\n                    Iterator<CqlRow> iter = result.getRowsIterator();\n                    while (iter.hasNext()) {\n                        Object e = null;\n\n                        CqlRow row = iter.next();\n                        Object rowKey = null;\n\n                        ThriftRow thriftRow = null;\n                        thriftRow = new ThriftRow(rowKey, entityMetadata.getTableName(), row.getColumns(),\n                            new ArrayList<SuperColumn>(0), new ArrayList<CounterColumn>(0),\n                            new ArrayList<CounterSuperColumn>(0));\n                        // send cqlmetadata\n\n                        e = dataHandler.populateEntity(thriftRow, entityMetadata, KunderaCoreUtils.getEntity(e),\n                            relationalField, relationalField != null && !relationalField.isEmpty());\n\n                        e = populateSecondaryTableData(relationalField, dataHandler, isCql3Enabled, entityMetadata, e);\n\n                        if (e != null) {\n                            returnedEntities.add(e);\n                        } else if (isNative) {\n                            returnedEntities.add(row.getColumns().get(0));\n                        }\n                    }\n                }\n            } catch (Exception e) {\n                log.error(\"Error while executing native CQL query Caused by {}.\", e);\n                throw new PersistenceException(e);\n            }\n            return returnedEntities;\n        }\n\n        /**\n         * Populate secondary table data.\n         * \n         * @param relationalField\n         *            the relational field\n         * @param dataHandler\n         *            the data handler\n         * @param isCql3Enabled\n         *            the is cql3 enabled\n         * @param entityMetadata\n         *            the entity metadata\n         * @param e\n         *            the e\n         * @return the object\n         */\n        private Object populateSecondaryTableData(List<String> relationalField, CassandraDataHandler dataHandler,\n            boolean isCql3Enabled, EntityMetadata entityMetadata, Object e) {\n            CqlResult result;\n            // For secondary tables.\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(entityMetadata.getPersistenceUnit());\n            if (!metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())) {\n                AbstractManagedType managedType =\n                    (AbstractManagedType) metaModel.entity(entityMetadata.getEntityClazz());\n                List<String> secondaryTables =\n                    ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation()).getSecondaryTablesName();\n\n                CQLTranslator translator = new CQLTranslator();\n\n                for (String tableName : secondaryTables) {\n                    // Building query.\n                    StringBuilder queryBuilder = new StringBuilder(\"select * from \\\"\" + tableName + \"\\\" where \");\n                    Attribute attribute = entityMetadata.getIdAttribute();\n                    translator.buildWhereClause(queryBuilder,\n                        ((AbstractAttribute) entityMetadata.getIdAttribute()).getBindableJavaType(),\n                        CassandraUtilities.getIdColumnName(kunderaMetadata, entityMetadata, getExternalProperties(),\n                            isCql3Enabled(entityMetadata)),\n                        PropertyAccessorHelper.getId(e, entityMetadata), translator.EQ_CLAUSE, false);\n                    // strip last \"AND\" clause.\n                    queryBuilder.delete(queryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE), queryBuilder.length());\n\n                    // Executing.\n                    result = (CqlResult) executeCQLQuery(queryBuilder.toString(), isCql3Enabled);\n\n                    if (result != null && (result.getRows() != null || result.getRowsSize() > 0)) {\n                        Iterator<CqlRow> iterator = result.getRowsIterator();\n                        while (iterator.hasNext()) {\n                            CqlRow cqlRow = iterator.next();\n\n                            ThriftRow tr = null;\n                            tr = new ThriftRow(null, entityMetadata.getTableName(), cqlRow.getColumns(),\n                                new ArrayList<SuperColumn>(0), new ArrayList<CounterColumn>(0),\n                                new ArrayList<CounterSuperColumn>(0));\n\n                            e = dataHandler.populateEntity(tr, entityMetadata, KunderaCoreUtils.getEntity(e),\n                                relationalField, relationalField != null && !relationalField.isEmpty());\n                            break;\n                        }\n                    }\n                }\n            }\n            return e;\n        }\n\n        /**\n         * Finds entity on the basis of rowid and return list of objects.\n         * \n         * @param metaModel\n         *            the meta model\n         * @param metadata\n         *            the metadata\n         * @param rowId\n         *            the row id\n         * @param relationNames\n         *            the relation names\n         * @return the list\n         */\n        public List<Object> find(MetamodelImpl metaModel, EntityMetadata metadata, Object rowId,\n            List<String> relationNames) {\n            CQLTranslator translator = new CQLTranslator();\n\n            String tableName = metadata.getTableName();\n            String select_Query = translator.SELECTALL_QUERY;\n            select_Query = StringUtils.replace(select_Query, CQLTranslator.COLUMN_FAMILY,\n                translator.ensureCase(new StringBuilder(), tableName, false).toString());\n            StringBuilder builder = new StringBuilder(select_Query);\n            builder.append(CQLTranslator.ADD_WHERE_CLAUSE);\n            onWhereClause(metadata, rowId, translator, builder, metaModel, metadata.getIdAttribute());\n\n            // strip last \"AND\" clause.\n            builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length());\n            return CassandraClientBase.this.executeQuery(metadata.getEntityClazz(), relationNames, false,\n                builder.toString());\n        }\n\n        /**\n         * Find List of objects based on value {@columnValue} of column {@columnName}.\n         * \n         * @param m\n         *            the m\n         * @param columnName\n         *            the column name\n         * @param columnValue\n         *            the column value\n         * @param clazz\n         *            the clazz\n         * @param dataHandler\n         *            the data handler\n         * @return the list\n         */\n        protected List<Object> findByRelationQuery(EntityMetadata m, String columnName, Object columnValue, Class clazz,\n            CassandraDataHandler dataHandler) {\n            CQLTranslator translator = new CQLTranslator();\n            String selectQuery = translator.SELECTALL_QUERY;\n            selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMN_FAMILY,\n                translator.ensureCase(new StringBuilder(), m.getTableName(), false).toString());\n\n            StringBuilder selectQueryBuilder = new StringBuilder(selectQuery);\n            selectQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE);\n\n            translator.buildWhereClause(selectQueryBuilder, columnValue.getClass(), columnName, columnValue,\n                CQLTranslator.EQ_CLAUSE, false);\n            selectQueryBuilder.delete(selectQueryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE),\n                selectQueryBuilder.length());\n            return this.executeQuery(clazz, m.getRelationNames(), dataHandler, true, false,\n                selectQueryBuilder.toString());\n        }\n    }\n\n    /**\n     * Checks if is ttl per request.\n     * \n     * @return the ttlPerRequest\n     */\n    public boolean isTtlPerRequest() {\n        return ttlPerRequest;\n    }\n\n    /**\n     * Sets the ttl per request.\n     * \n     * @param ttlPerRequest\n     *            the ttlPerRequest to set\n     */\n    public void setTtlPerRequest(boolean ttlPerRequest) {\n        this.ttlPerRequest = ttlPerRequest;\n    }\n\n    /**\n     * Checks if is ttl per session.\n     * \n     * @return the ttlPerSession\n     */\n    public boolean isTtlPerSession() {\n        return ttlPerSession;\n    }\n\n    /**\n     * Sets the ttl per session.\n     * \n     * @param ttlPerSession\n     *            the ttlPerSession to set\n     */\n    public void setTtlPerSession(boolean ttlPerSession) {\n        this.ttlPerSession = ttlPerSession;\n    }\n\n    /**\n     * Gets the ttl values.\n     * \n     * @return the ttlValues\n     */\n    public Map<String, Object> getTtlValues() {\n        return ttlValues;\n    }\n\n    /**\n     * Sets the ttl values.\n     * \n     * @param ttlValues\n     *            the ttlValues to set\n     */\n    public void setTtlValues(Map<String, Object> ttlValues) {\n        this.ttlValues = ttlValues;\n    }\n\n    /**\n     * Finds a {@link List} of entities from database.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @param metadata\n     *            the metadata\n     * @param rowIds\n     *            the row ids\n     * @return the list\n     */\n    public final List findByRowKeys(Class entityClass, List<String> relationNames, boolean isWrapReq,\n        EntityMetadata metadata, Object... rowIds) {\n        List entities = null;\n\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());\n\n        EntityType entityType = metaModel.entity(metadata.getEntityClazz());\n\n        List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n\n        try {\n            if (!subManagedType.isEmpty()) {\n                for (AbstractManagedType subEntity : subManagedType) {\n                    EntityMetadata subEntityMetadata =\n                        KunderaMetadataManager.getEntityMetadata(kunderaMetadata, subEntity.getJavaType());\n                    entities = getDataHandler().fromThriftRow(entityClass, subEntityMetadata,\n                        subEntityMetadata.getRelationNames(), isWrapReq, getConsistencyLevel(), rowIds);\n\n                    if (entities != null && !entities.isEmpty()) {\n                        break;\n                    }\n                }\n            } else {\n                entities = getDataHandler().fromThriftRow(entityClass, metadata, relationNames, isWrapReq,\n                    getConsistencyLevel(), rowIds);\n            }\n        } catch (Exception e) {\n            log.error(\"Error while retrieving records for entity {}, row keys {}\", entityClass, rowIds);\n            throw new KunderaException(e);\n        }\n        return entities;\n    }\n\n    // XXX\n    /**\n     * Execute with bind parameters\n     * \n     * @param <T>\n     *            the generic type\n     * @param query\n     *            the query\n     * @param connection\n     *            the connection\n     * @return the t\n     */\n    public <T> T execute(final String query, final Object connection,\n        final List<KunderaQuery.BindParameter> parameters) {\n        throw new KunderaException(\"not implemented\");\n    }\n\n    /**\n     * Execute.\n     * \n     * @param <T>\n     *            the generic type\n     * @param query\n     *            the query\n     * @param connection\n     *            the connection\n     * @return the t\n     */\n    public <T> T execute(final String query, Object connection) {\n        try {\n            org.apache.cassandra.thrift.Cassandra.Client conn =\n                (org.apache.cassandra.thrift.Cassandra.Client) connection;\n            conn.set_cql_version(CassandraConstants.CQL_VERSION_3_0);\n            KunderaCoreUtils.printQuery(query, showQuery);\n            return (T) conn.execute_cql3_query(ByteBuffer.wrap(query.getBytes(Constants.CHARSET_UTF8)),\n                Compression.NONE, getConsistencyLevel());\n        } catch (Exception e) {\n            log.error(\"Error while executing query {}\", query);\n            throw new KunderaException(e);\n        }\n    }\n\n    /**\n     * Persist join table by cql.\n     * \n     * @param joinTableData\n     *            the join table data\n     * @param conn\n     *            the conn\n     */\n    protected void persistJoinTableByCql(JoinTableData joinTableData, Cassandra.Client conn) {\n        String joinTableName = joinTableData.getJoinTableName();\n        String invJoinColumnName = joinTableData.getInverseJoinColumnName();\n        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();\n\n        EntityMetadata entityMetadata =\n            KunderaMetadataManager.getEntityMetadata(kunderaMetadata, joinTableData.getEntityClass());\n\n        // need to bring in an insert query for this\n        // add columns & execute query\n        CQLTranslator translator = new CQLTranslator();\n\n        String batch_Query = CQLTranslator.BATCH_QUERY;\n\n        String insert_Query = translator.INSERT_QUERY;\n\n        StringBuilder builder = new StringBuilder();\n        builder.append(CQLTranslator.DEFAULT_KEY_NAME);\n        builder.append(CQLTranslator.COMMA_STR);\n        builder.append(translator.ensureCase(new StringBuilder(), joinTableData.getJoinColumnName(), false));\n        builder.append(CQLTranslator.COMMA_STR);\n        builder.append(translator.ensureCase(new StringBuilder(), joinTableData.getInverseJoinColumnName(), false));\n\n        insert_Query = StringUtils.replace(insert_Query, CQLTranslator.COLUMN_FAMILY,\n            translator.ensureCase(new StringBuilder(), joinTableName, false).toString());\n\n        insert_Query = StringUtils.replace(insert_Query, CQLTranslator.COLUMNS, builder.toString());\n\n        StringBuilder columnValueBuilder = new StringBuilder();\n\n        StringBuilder statements = new StringBuilder();\n\n        // insert query for each row key\n\n        for (Object key : joinTableRecords.keySet()) {\n            PropertyAccessor accessor =\n                PropertyAccessorFactory.getPropertyAccessor((Field) entityMetadata.getIdAttribute().getJavaMember());\n\n            Set<Object> values = joinTableRecords.get(key); // join column value\n\n            for (Object value : values) {\n                if (value != null) {\n                    String insertQuery = insert_Query;\n                    columnValueBuilder.append(CQLTranslator.QUOTE_STR);\n                    columnValueBuilder.append(\n                        PropertyAccessorHelper.getString(key) + \"\\001\" + PropertyAccessorHelper.getString(value));\n                    columnValueBuilder.append(CQLTranslator.QUOTE_STR);\n                    columnValueBuilder.append(CQLTranslator.COMMA_STR);\n                    translator.appendValue(columnValueBuilder, key.getClass(), key, true, false);\n                    columnValueBuilder.append(CQLTranslator.COMMA_STR);\n                    translator.appendValue(columnValueBuilder, value.getClass(), value, true, false);\n\n                    insertQuery =\n                        StringUtils.replace(insertQuery, CQLTranslator.COLUMN_VALUES, columnValueBuilder.toString());\n                    statements.append(insertQuery);\n                    statements.append(\" \");\n                }\n            }\n        }\n\n        if (!StringUtils.isBlank(statements.toString())) {\n            batch_Query = StringUtils.replace(batch_Query, CQLTranslator.STATEMENT, statements.toString());\n            StringBuilder batchBuilder = new StringBuilder();\n            batchBuilder.append(batch_Query);\n            batchBuilder.append(CQLTranslator.APPLY_BATCH);\n            execute(batchBuilder.toString(), conn);\n        }\n\n    }\n\n    /**\n     * Find inverse join column values for join column.\n     * \n     * @param <E>\n     *            the element type\n     * @param schemaName\n     *            the schema name\n     * @param tableName\n     *            the table name\n     * @param pKeyColumnName\n     *            the key column name\n     * @param columnName\n     *            the column name\n     * @param pKeyColumnValue\n     *            the key column value\n     * @param columnJavaType\n     *            the column java type\n     * @return the columns by id using cql\n     */\n    protected <E> List<E> getColumnsByIdUsingCql(String schemaName, String tableName, String pKeyColumnName,\n        String columnName, Object pKeyColumnValue, Class columnJavaType) {\n        // select columnName from tableName where pKeyColumnName =\n        // pKeyColumnValue\n        List results = new ArrayList();\n        CQLTranslator translator = new CQLTranslator();\n        String selectQuery = translator.SELECT_QUERY;\n        selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMN_FAMILY,\n            translator.ensureCase(new StringBuilder(), tableName, false).toString());\n        selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMNS,\n            translator.ensureCase(new StringBuilder(), columnName, false).toString());\n\n        StringBuilder selectQueryBuilder = new StringBuilder(selectQuery);\n\n        selectQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE);\n\n        translator.buildWhereClause(selectQueryBuilder, columnJavaType, pKeyColumnName, pKeyColumnValue,\n            CQLTranslator.EQ_CLAUSE, false);\n        selectQueryBuilder.delete(selectQueryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE),\n            selectQueryBuilder.length());\n\n        CqlResult cqlResult = execute(selectQueryBuilder.toString(), getRawClient(schemaName));\n\n        Iterator<CqlRow> rowIter = cqlResult.getRows().iterator();\n        while (rowIter.hasNext()) {\n            CqlRow row = rowIter.next();\n\n            if (!row.getColumns().isEmpty()) {\n                Column column = row.getColumns().get(0);\n                Object columnValue = CassandraDataTranslator.decompose(columnJavaType, column.getValue(), true);\n                results.add(columnValue);\n            }\n        }\n        return results;\n    }\n\n    /**\n     * Find join column values for inverse join column.\n     * \n     * @param <E>\n     *            the element type\n     * @param schemaName\n     *            the schema name\n     * @param tableName\n     *            the table name\n     * @param pKeyName\n     *            the key name\n     * @param columnName\n     *            the column name\n     * @param columnValue\n     *            the column value\n     * @param entityClazz\n     *            the entity clazz\n     * @return the list\n     */\n    protected <E> List<E> findIdsByColumnUsingCql(String schemaName, String tableName, String pKeyName,\n        String columnName, Object columnValue, Class entityClazz) {\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n\n        return getColumnsByIdUsingCql(schemaName, tableName, columnName,\n            ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName(), columnValue,\n            metadata.getIdAttribute().getBindableJavaType());\n    }\n\n    /**\n     * Gets the cql metadata.\n     * \n     * @return the cql metadata\n     */\n    public CqlMetadata getCqlMetadata() {\n        return cqlMetadata;\n    }\n\n    /**\n     * Sets the cql metadata.\n     * \n     * @param cqlMetadata\n     *            the new cql metadata\n     */\n    public void setCqlMetadata(CqlMetadata cqlMetadata) {\n        this.cqlMetadata = cqlMetadata;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/CassandraClientProperties.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra;\n\nimport java.util.Map;\n\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.commons.lang.StringUtils;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\n\n/**\n * Cassandra implementation of {@link ClientPropertiesSetter}.\n *\n * @author amresh.singh\n */\nclass CassandraClientProperties\n{\n    \n    /** The Constant TTL_VALUES. */\n    private static final String TTL_VALUES = \"ttl.values\";\n\n    /** The Constant TTL_PER_REQUEST. */\n    private static final String TTL_PER_REQUEST = \"ttl.per.request\";\n\n    /** The Constant TTL_PER_SESSION. */\n    private static final String TTL_PER_SESSION = \"ttl.per.session\";\n\n    /** The Constant CONSISTENCY_LEVEL. */\n    private static final String CONSISTENCY_LEVEL = \"consistency.level\";\n\n    /** The Constant CQL_VERSION. */\n    private static final String CQL_VERSION = CassandraConstants.CQL_VERSION;\n\n    /** The cassandra client base. */\n    private CassandraClientBase cassandraClientBase;\n\n    /**\n     * Populate client properties.\n     *\n     * @param client the client\n     * @param properties the properties\n     */\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        this.cassandraClientBase = (CassandraClientBase) client;\n\n        if (properties != null)\n        {\n            for (String key : properties.keySet())\n            {\n\n                Object value = properties.get(key);\n\n                if (checkNull(key, value))\n                {\n\n                    if (key.equals(CONSISTENCY_LEVEL))\n                    {\n                        setConsistencylevel(value);\n                    }\n                    else if (key.equals(CQL_VERSION) && value instanceof String)\n                    {\n                        this.cassandraClientBase.setCqlVersion((String) value);\n                    }\n                    else if (key.equals(TTL_PER_SESSION))\n                    {\n                        setTTLPerSession(value);\n                    }\n                    else if (key.equals(TTL_PER_REQUEST))\n                    {\n                        setTTLPerRequest(value);\n                    }\n                    else if (key.equals(TTL_VALUES) && value instanceof Map)\n                    {\n                        this.cassandraClientBase.setTtlValues((Map) value);\n                    }\n                    else if (key.equals(PersistenceProperties.KUNDERA_BATCH_SIZE)\n                            && !StringUtils.isBlank(value.toString()) && StringUtils.isNumeric(value.toString()))\n                    {\n                        this.cassandraClientBase.setBatchSize(value.toString());\n                    }\n\n                    // Add more properties as needed\n                }\n            }\n        }\n    }\n\n    /**\n     * set ttl per request.\n     *\n     * @param value the new TTL per request\n     */\n    private void setTTLPerRequest(Object value)\n    {\n        if (value instanceof String)\n        {\n            if (Boolean.valueOf((String) value).booleanValue())\n            {\n                this.cassandraClientBase.setTtlPerSession(false);\n            }\n            this.cassandraClientBase.setTtlPerRequest(Boolean.valueOf((String) value));\n\n        }\n        else if (value instanceof Boolean)\n        {\n            if (((Boolean) value).booleanValue())\n            {\n                this.cassandraClientBase.setTtlPerSession(false);\n            }\n\n            this.cassandraClientBase.setTtlPerRequest((Boolean) value);\n\n        }\n\n    }\n\n    /**\n     * set ttl per session.\n     *\n     * @param value the new TTL per session\n     */\n    private void setTTLPerSession(Object value)\n    {\n        if (value instanceof String)\n        {\n            if (Boolean.valueOf((String) value).booleanValue())\n            {\n                this.cassandraClientBase.setTtlPerRequest(false);\n            }\n            this.cassandraClientBase.setTtlPerSession(Boolean.valueOf((String) value));\n\n        }\n        else if (value instanceof Boolean)\n        {\n            if (((Boolean) value).booleanValue())\n            {\n                this.cassandraClientBase.setTtlPerRequest(false);\n            }\n\n            this.cassandraClientBase.setTtlPerSession((Boolean) value);\n\n        }\n\n    }\n\n    /**\n     * set consistency level.\n     *\n     * @param value the new consistencylevel\n     */\n    private void setConsistencylevel(Object value)\n    {\n        if (value instanceof String)\n        {\n            this.cassandraClientBase.setConsistencyLevel(ConsistencyLevel.valueOf((String) value));\n        }\n        else if (value instanceof ConsistencyLevel)\n        {\n            this.cassandraClientBase.setConsistencyLevel((ConsistencyLevel) value);\n        }\n\n    }\n\n    /**\n     * check key value map not null.\n     *\n     * @param key the key\n     * @param value the value\n     * @return true, if successful\n     */\n    private boolean checkNull(String key, Object value)\n    {\n        return key != null && value != null;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/CassandraIdGenerator.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra;\n\nimport java.nio.ByteBuffer;\nimport java.util.UUID;\n\nimport org.apache.cassandra.db.marshal.TimeUUIDType;\nimport org.apache.cassandra.thrift.Cassandra;\nimport org.apache.cassandra.thrift.ColumnParent;\nimport org.apache.cassandra.thrift.ColumnPath;\nimport org.apache.cassandra.thrift.CounterColumn;\nimport org.apache.cassandra.thrift.CqlResult;\nimport org.apache.cassandra.thrift.CqlRow;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.thrift.CQLTranslator;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.generator.AutoGenerator;\nimport com.impetus.kundera.generator.TableGenerator;\nimport com.impetus.kundera.metadata.model.TableGeneratorDiscriptor;\n\n/**\n * The Class CassandraIdGenerator.\n * \n * @author: karthikp.manchala\n */\npublic class CassandraIdGenerator implements AutoGenerator, TableGenerator\n{\n\n    /** The Constant SYSTEM. */\n    private static final String SYSTEM = \"system\";\n\n    /** The Constant UUID. */\n    private static final String UUID = \"uuid\";\n\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(CassandraIdGenerator.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.AutoGenerator#generate(com.impetus.kundera\n     * .client.Client, java.lang.Object)\n     */\n    @Override\n    public Object generate(Client<?> client, String dataType)\n    {\n        CqlResult cqlResult = ((CassandraClientBase) client).execute(\"SELECT NOW() FROM system_schema.columns LIMIT 1\",\n                ((CassandraClientBase) client).getRawClient(SYSTEM));\n\n        CqlRow cqlRow = cqlResult.getRowsIterator().next();\n        TimeUUIDType t = TimeUUIDType.instance;\n        UUID timeUUID = t.compose(ByteBuffer.wrap(cqlRow.getColumns().get(0).getValue()));\n\n        switch (dataType.toLowerCase())\n        {\n        case UUID:\n            return timeUUID;\n\n        default:\n            return java.util.UUID.randomUUID();\n\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.TableGenerator#generate(com.impetus.kundera\n     * .metadata.model.TableGeneratorDiscriptor,\n     * com.impetus.kundera.client.ClientBase, java.lang.Object)\n     */\n    @Override\n    public Object generate(TableGeneratorDiscriptor discriptor, ClientBase client, String dataType)\n    {\n        Cassandra.Client conn = ((CassandraClientBase) client).getRawClient(discriptor.getSchema());\n        long latestCount = 0l;\n        try\n        {\n            conn.set_keyspace(discriptor.getSchema());\n\n            if (((CassandraClientBase) client).isCql3Enabled())\n            {\n                CQLTranslator translator = new CQLTranslator();\n                ((CassandraClientBase) client).execute(translator.buildUpdateQuery(discriptor).toString(), conn);\n\n                CqlResult result = ((CassandraClientBase) client).execute(translator.buildSelectQuery(discriptor)\n                        .toString(), conn);\n\n                for (CqlRow row : result.getRows())\n                {\n                    latestCount = ByteBufferUtil.toLong(ByteBuffer.wrap(row.getColumns().get(0).getValue()));\n                }\n            }\n            else\n            {\n\n                ColumnPath columnPath = new ColumnPath(discriptor.getTable());\n                columnPath.setColumn(discriptor.getValueColumnName().getBytes());\n\n                try\n                {\n                    latestCount = conn.get(ByteBuffer.wrap(discriptor.getPkColumnValue().getBytes()), columnPath,\n                            ((CassandraClientBase) client).getConsistencyLevel()).counter_column.value;\n                }\n                catch (NotFoundException e)\n                {\n                    log.warn(\"Counter value not found for {}, resetting it to zero.\", discriptor.getPkColumnName());\n                    latestCount = 0;\n                }\n                ColumnParent columnParent = new ColumnParent(discriptor.getTable());\n\n                CounterColumn counterColumn = new CounterColumn(ByteBuffer.wrap(discriptor.getValueColumnName()\n                        .getBytes()), 1);\n\n                conn.add(ByteBuffer.wrap(discriptor.getPkColumnValue().getBytes()), columnParent, counterColumn,\n                        ((CassandraClientBase) client).getConsistencyLevel());\n            }\n            if (latestCount == 0)\n            {\n                return (long) discriptor.getInitialValue();\n            }\n            else\n            {\n                return (latestCount + 1) * discriptor.getAllocationSize();\n            }\n        }\n        catch (UnavailableException e)\n        {\n            log.error(\"Error while reading counter value from table{}, Caused by: .\", discriptor.getTable(), e);\n            throw new KunderaException(e);\n        }\n        catch (TimedOutException e)\n        {\n            log.error(\"Error while reading counter value from table{}, Caused by: .\", discriptor.getTable(), e);\n            throw new KunderaException(e);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while using keyspace. Caused by: .\", e);\n            throw new KunderaException(e);\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/common/CassandraClientFactory.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.common;\n\nimport java.util.Map;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.config.CassandraPropertyReader;\nimport com.impetus.client.cassandra.service.CassandraHost;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.utils.DefaultTimestampGenerator;\nimport com.impetus.kundera.utils.TimestampGenerator;\n\n/**\n * Client factory interface to provide common method declaration across multiple\n * clients.\n * \n * @author vivek.mishra\n * \n */\npublic abstract class CassandraClientFactory extends GenericClientFactory\n{\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(CassandraClientFactory.class);\n\n    /** The Timestamp Generator. */\n    protected TimestampGenerator timestampGenerator = new DefaultTimestampGenerator();;\n\n    /**\n     * Add cassandra host.\n     * \n     * @param host\n     *            cassandra host configuration object\n     * @return true, if it is added successfully to connection else false.\n     */\n    public abstract boolean addCassandraHost(CassandraHost host);\n\n    /**\n     * \n     * Initialize time stamp generator class.\n     * \n     * @param externalProperty\n     */\n    protected void initializeTimestampGenerator(Map<String, Object> externalProperty)\n    {\n        String timestampGeneratorClass = externalProperty != null ?(String) externalProperty.get(Constants.DEFAULT_TIMESTAMP_GENERATOR):null;\n        if (timestampGeneratorClass == null)\n        {\n            timestampGeneratorClass = CassandraPropertyReader.csmd != null ? CassandraPropertyReader.csmd\n                    .getDatastoreProperties().getProperty(Constants.DEFAULT_TIMESTAMP_GENERATOR, null) : null;\n        }\n\n        if (!StringUtils.isBlank(timestampGeneratorClass))\n        {\n            try\n            {\n                timestampGenerator = (TimestampGenerator) Class.forName(timestampGeneratorClass).newInstance();\n            }\n            catch (Exception ex)\n            {\n                logger.error(\"Error while initialzing timestamp generator class {}, caused by {}.\",\n                        timestampGeneratorClass, ex);\n                throw new KunderaException(ex);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/common/CassandraConstants.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.common;\n\n/**\n * Holds constants for kundera-cassandra module\n * \n * @author amresh.singh\n */\npublic interface CassandraConstants\n{\n    public static final String CQL_VERSION_2_0 = \"2.0.0\";\n\n    public static final String CQL_VERSION_3_0 = \"3.0.0\";\n\n    // properties to set during creation of keyspace.\n    public static final String PLACEMENT_STRATEGY = \"strategy.class\";\n\n    public static final String REPLICATION_FACTOR = \"replication.factor\";\n\n    public static final String CF_DEFS = \"cf.defs\";\n\n    public static final String DATA_CENTERS = \"datacenters\";\n\n    public static final String INVERTED_INDEXING_ENABLED = \"inverted.indexing.enabled\";\n\n    /**\n     * \n     */\n    public static final String DEFAULT_REPLICATION_FACTOR = \"1\";\n\n    public static final String DURABLE_WRITES = \"durable.writes\";\n    \n    /** The Constant THRIFT BINARY Port. */\n    public static final String THRIFT_PORT = \"rpc.port\";\n\n    // properties to set during creation of column family.\n\n    public static final String DEFAULT_VALIDATION_CLASS = \"default.validation.class\";\n\n    public static final String KEY_VALIDATION_CLASS = \"key.validation.class\";\n\n    public static final String COMPARATOR_TYPE = \"comparator.type\";\n\n    public static final String SUBCOMPARATOR_TYPE = \"subcomparator.type\";\n\n    public static final String REPLICATE_ON_WRITE = \"replicate.on.write\";\n\n    public static final String COMPACTION_STRATEGY = \"compaction.strategy\";\n\n    public static final String MAX_COMPACTION_THRESHOLD = \"max.compaction.threshold\";\n\n    public static final String MIN_COMPACTION_THRESHOLD = \"min.compaction.threshold\";\n\n    public static final String COMMENT = \"comment\";\n\n    public static final String ID = \"id\";\n\n    public static final String CACHING = \"caching\";\n\n    public static final String BLOOM_FILTER_FP_CHANCE = \"bloom.filter.fp.chance\";\n\n    public static final String GC_GRACE_SECONDS = \"gc.grace.seconds\";\n\n    public static final String READ_REPAIR_CHANCE = \"read.repair.chance\";\n\n    public static final String DCLOCAL_READ_REPAIR_CHANCE = \"dclocal.read.repair.chance\";\n\n    public static final String CQL_VERSION = \"cql.version\";\n\n    /** Name of Row key column when stored using CQL insert statement */\n    public static final String CQL_KEY = \"key\";\n\n    public static final String TEST_ON_BORROW = \"testonborrow\";\n\n    public static final String TEST_ON_CONNECT = \"testonconnect\";\n\n    public static final String TEST_WHILE_IDLE = \"testwhileidle\";\n\n    public static final String TEST_ON_RETURN = \"testonretrun\";\n\n    public static final String SOCKET_TIMEOUT = \"socket.timeout\";\n\n    public static final String MAX_WAIT = \"max.wait\";\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/common/CassandraUtilities.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.common;\n\nimport java.io.IOException;\nimport java.lang.reflect.Field;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.Charset;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.UUID;\n\nimport javax.persistence.PersistenceException;\n\nimport net.dataforte.cassandra.pool.HostFailoverPolicy;\nimport net.dataforte.cassandra.pool.PoolConfiguration;\n\nimport org.apache.cassandra.db.marshal.BooleanType;\nimport org.apache.cassandra.db.marshal.BytesType;\nimport org.apache.cassandra.db.marshal.DateType;\nimport org.apache.cassandra.db.marshal.DoubleType;\nimport org.apache.cassandra.db.marshal.FloatType;\nimport org.apache.cassandra.db.marshal.Int32Type;\nimport org.apache.cassandra.db.marshal.LongType;\nimport org.apache.cassandra.db.marshal.UTF8Type;\nimport org.apache.cassandra.db.marshal.UUIDType;\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.thrift.CQLTranslator;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.property.accessor.DateAccessor;\n\n/**\n * Provides utilities methods\n * \n * @author amresh.singh\n */\npublic class CassandraUtilities\n{\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(CassandraUtilities.class);\n\n    public static String toUTF8(byte[] value)\n    {\n        return value == null ? null : new String(value, Charset.forName(Constants.CHARSET_UTF8));\n    }\n\n    public static String getKeyspace(final KunderaMetadata kunderaMetadata, String persistenceUnit)\n    {\n        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(persistenceUnit);\n        Properties props = persistenceUnitMetadata.getProperties();\n        String keyspace = (String) props.get(PersistenceProperties.KUNDERA_KEYSPACE);\n        return keyspace;\n    }\n\n    public static ByteBuffer toBytes(Object value, Field f)\n    {\n        return toBytes(value, f.getType());\n\n    }\n\n    public static byte[] toBytes(final Object value)\n    {\n        if (value != null)\n        {\n            return toBytes(value, value.getClass()).array();\n        }\n\n        return null;\n    }\n\n    /**\n     * @param value\n     * @param f\n     * @return\n     */\n    public static ByteBuffer toBytes(Object value, Class<?> clazz)\n    {\n        if (clazz.isAssignableFrom(String.class))\n        {\n            return UTF8Type.instance.decompose((String) value);\n        }\n        else if (clazz.equals(int.class) || clazz.isAssignableFrom(Integer.class))\n        {\n            return Int32Type.instance.decompose(Integer.parseInt(value.toString()));\n        }\n        else if (clazz.equals(long.class) || clazz.isAssignableFrom(Long.class))\n        {\n            return LongType.instance.decompose(Long.parseLong(value.toString()));\n        }\n        else if (clazz.equals(boolean.class) || clazz.isAssignableFrom(Boolean.class))\n        {\n            return BooleanType.instance.decompose(Boolean.valueOf(value.toString()));\n        }\n        else if (clazz.equals(double.class) || clazz.isAssignableFrom(Double.class))\n        {\n            return DoubleType.instance.decompose(Double.valueOf(value.toString()));\n        }\n        else if (clazz.isAssignableFrom(java.util.UUID.class))\n        {\n            return UUIDType.instance.decompose(UUID.fromString(value.toString()));\n        }\n        else if (clazz.equals(float.class) || clazz.isAssignableFrom(Float.class))\n        {\n            return FloatType.instance.decompose(Float.valueOf(value.toString()));\n        }\n        else if (clazz.isAssignableFrom(Date.class))\n        {\n            DateAccessor dateAccessor = new DateAccessor();\n            return DateType.instance.decompose((Date) value);\n        }\n        else\n        {\n            if (value.getClass().isAssignableFrom(String.class))\n            {\n                value = PropertyAccessorFactory.getPropertyAccessor(clazz).fromString(clazz, value.toString());\n            }\n            return BytesType.instance.decompose(ByteBuffer.wrap(PropertyAccessorFactory.getPropertyAccessor(clazz)\n                    .toBytes(value)));\n        }\n    }\n\n    /**\n     * Append columns.\n     * \n     * @param builder\n     *            the builder\n     * @param columns\n     *            the columns\n     * @param selectQuery\n     *            the select query\n     * @param translator\n     *            the translator\n     */\n    public static StringBuilder appendColumns(StringBuilder builder, List<String> columns, String selectQuery,\n            CQLTranslator translator)\n    {\n        if (columns != null)\n        {\n            for (String column : columns)\n            {\n                translator.appendColumnName(builder, column);\n                builder.append(\",\");\n            }\n        }\n        if (builder.lastIndexOf(\",\") != -1)\n        {\n            builder.deleteCharAt(builder.length() - 1);\n            selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMNS, builder.toString());\n        }\n\n        builder = new StringBuilder(selectQuery);\n        return builder;\n    }\n\n    /**\n     * Return name if Idcolumn for cql, returns {@CassandraConstants.CQL_KEY\n     * \n     * \n     * \n     * \n     *     \n     * } if user opted for\n     * {@PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE\n     * \n     * \n     * \n     * \n     *       \n     * } otherwise returns\n     * JPAColumnName of id attribute.\n     * \n     * @param m\n     * @param externalProperties\n     * @return\n     */\n    public static String getIdColumnName(final KunderaMetadata kunderaMetadata, final EntityMetadata m,\n            final Map<String, Object> externalProperties, final boolean isCql3Enabled)\n    {\n        // key for auto schema generation.\n        String persistenceUnit = m.getPersistenceUnit();\n        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(persistenceUnit);\n        String autoDdlOption = externalProperties != null ? (String) externalProperties\n                .get(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE) : null;\n        if (autoDdlOption == null)\n        {\n            autoDdlOption = persistenceUnitMetadata != null ? persistenceUnitMetadata\n                    .getProperty(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE) : null;\n        }\n\n        boolean containsBasicCollectionField = MetadataUtils.containsBasicElementCollectionField(m, kunderaMetadata);\n\n        if (!StringUtils.isBlank(autoDdlOption) && !(isCql3Enabled || containsBasicCollectionField))\n        {\n            return CassandraConstants.CQL_KEY;\n        }\n        else\n        {\n            return ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n        }\n    }\n\n     /**\n     * \n     * @param host\n     * @param port\n     * @return\n     */\n    public static boolean verifyConnection(String host, int port)\n    {\n        Socket socket = null;\n        try\n        {\n            socket = new Socket(host, port);\n            socket.setReuseAddress(true);\n            socket.setSoLinger(true, 0);\n            boolean isConnected = socket.isConnected();\n            return isConnected;\n        }\n        catch (UnknownHostException e)\n        {\n            logger.warn(\"{}:{} is still down\", host, port);\n            return false;\n        }\n        catch (IOException e)\n        {\n            logger.warn(\"{}:{} is still down\", host, port);\n            return false;\n        }\n        finally\n        {\n            try\n            {\n                if (socket != null)\n                {\n                    socket.close();\n                }\n            }\n            catch (IOException e)\n            {\n                logger.warn(\"{}:{} is still down\", host, port);\n            }\n        }\n    }\n\n    /**\n     * Gets the pool config policy.\n     * \n     * @param persistenceUnitMetadata\n     *            the persistence unit metadata\n     * @param puProperties\n     * @return the pool config policy\n     */\n    public static PoolConfiguration setPoolConfigPolicy(\n            com.impetus.client.cassandra.service.CassandraHost cassandraHost, PoolConfiguration prop)\n    {\n        int maxActivePerNode = cassandraHost.getMaxActive();\n        int maxIdlePerNode = cassandraHost.getMaxIdle();\n        int minIdlePerNode = cassandraHost.getMinIdle();\n        int maxTotal = cassandraHost.getMaxTotal();\n        boolean testOnBorrow = cassandraHost.isTestOnBorrow();\n        boolean testWhileIdle = cassandraHost.isTestWhileIdle();\n        boolean testOnConnect = cassandraHost.isTestOnConnect();\n        boolean testOnReturn = cassandraHost.isTestOnReturn();\n        int socketTimeOut = cassandraHost.getSocketTimeOut();\n        int maxWaitInMilli = cassandraHost.getMaxWait();\n        HostFailoverPolicy paramHostFailoverPolicy = cassandraHost.getHostFailoverPolicy();\n        if (maxActivePerNode > 0)\n        {\n            prop.setInitialSize(maxActivePerNode);\n            prop.setMaxActive(maxActivePerNode);\n            logger.info(\"kundera.pool.size.max.active is set to: {}\", maxActivePerNode);\n        }\n        else\n        {\n            logger.info(\"kundera.pool.size.max.active is set to default value: 100\");\n        }\n        if (maxIdlePerNode > 0)\n        {\n            prop.setMaxIdle(maxIdlePerNode);\n            logger.info(\"kundera.pool.size.max.idle is set to: {}\", maxIdlePerNode);\n        }\n        else\n        {\n            logger.info(\"kundera.pool.size.max.idle is set to default value: 10\");\n        }\n        if (minIdlePerNode > 0)\n        {\n            prop.setMinIdle(minIdlePerNode);\n            logger.info(\"kundera.pool.size.min.idle is set to: {}\", minIdlePerNode);\n        }\n        else\n        {\n            logger.info(\"kundera.pool.size.min.idle is set to default value: 100\");\n        }\n        if (maxTotal > 0)\n        {\n            prop.setMaxActive(maxTotal);\n            logger.info(\"kundera.pool.size.max.total is set to: {}\", maxTotal);\n        }\n        if (cassandraHost.getUser() != null)\n        {\n            prop.setUsername(cassandraHost.getUser());\n            prop.setPassword(cassandraHost.getPassword());\n        }\n\n        prop.setSocketTimeout(socketTimeOut);\n        prop.setTestOnBorrow(testOnBorrow);\n        prop.setTestOnConnect(testOnConnect);\n        prop.setTestOnReturn(testOnReturn);\n        prop.setTestWhileIdle(testWhileIdle);\n        prop.setFailoverPolicy(paramHostFailoverPolicy);\n        prop.setMaxWait(maxWaitInMilli);\n        return prop;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/config/CassandraPropertyReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.config;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.apache.cassandra.db.marshal.CounterColumnType;\nimport org.apache.cassandra.locator.SimpleStrategy;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection.Server;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Schema;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Schema.Table;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * Cassandra Property Reader reads cassandra properties from property file\n * {kundera-cassandra.properties} and put it into cassandra schema metadata.\n * \n * @author kuldeep.mishra\n * \n */\npublic class CassandraPropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n    /** The log instance. */\n    private Logger logger = LoggerFactory.getLogger(CassandraPropertyReader.class);\n\n    /** csmd instance of CassandraSchemaMetadata */\n\n    public static CassandraSchemaMetadata csmd;\n\n    private static final String dataStoreName = \"cassandra\";\n\n    public CassandraPropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        csmd = new CassandraSchemaMetadata();\n    }\n\n    public void onXml(ClientProperties cp)\n    {\n        if (cp != null)\n        {\n            csmd.setClientProperties(cp);\n        }\n    }\n\n    /**\n     * Cassandra schema metadata holds metadata information.\n     * \n     * @author kuldeep.mishra\n     * \n     */\n    public class CassandraSchemaMetadata extends AbstractSchemaMetadata\n    {\n\n        /**\n         * @return the replication_factor\n         */\n        public String getReplication_factor(String schemaName)\n        {\n            Schema schema = getSchema(schemaName);\n            String replication = \"1\";\n            if (schema != null && schema.getSchemaProperties() != null && !schema.getSchemaProperties().isEmpty())\n            {\n                replication = schema.getSchemaProperties().getProperty(CassandraConstants.REPLICATION_FACTOR);\n            }\n\n            if (logger.isInfoEnabled())\n            {\n                logger.info(\"Returning replication factor value {}\", replication);\n            }\n            return replication;\n        }\n\n        /**\n         * @return the placement_strategy\n         */\n        public String getPlacement_strategy(String schemaName)\n        {\n            Schema schema = getSchema(schemaName);\n            String placementStrategy = SimpleStrategy.class.getName();\n            if (schema != null && schema.getSchemaProperties() != null && !schema.getSchemaProperties().isEmpty())\n            {\n                placementStrategy = schema.getSchemaProperties().getProperty(CassandraConstants.PLACEMENT_STRATEGY);\n            }\n\n            if (logger.isInfoEnabled())\n            {\n                logger.info(\"Returning placement strategy value {}\", placementStrategy);\n            }\n            return placementStrategy;\n        }\n\n        public boolean isCounterColumn(String schemaName, String cfName)\n        {\n            Table table = getColumnFamily(schemaName, cfName);\n            if (table != null)\n            {\n                return table.getProperties().getProperty(CassandraConstants.DEFAULT_VALIDATION_CLASS)\n                        .equalsIgnoreCase(CounterColumnType.class.getSimpleName()) ? true : false;\n            }\n            return false;\n        }\n\n        public boolean isInvertedIndexingEnabled(String schemaName)\n        {\n            DataStore dataStore = getDataStore(dataStoreName);\n            boolean result = false;\n            if (schemaName != null && dataStore != null && dataStore.getSchemas() != null)\n            {\n                for (Schema schema : dataStore.getSchemas())\n                {\n                    if (schema != null && schemaName.equals(schema.getName()) && schema.getSchemaProperties() != null\n                            && schema.getSchemaProperties() != null)\n                    {\n                        result = Boolean.parseBoolean((String) schema.getSchemaProperties().get(\n                                CassandraConstants.INVERTED_INDEXING_ENABLED));\n                        break;\n                    }\n                }\n\n            }\n            return result;\n        }\n\n        public String getCqlVersion()\n        {\n            DataStore dataStore = getDataStore(dataStoreName);\n\n            if (dataStore != null)\n            {\n                Properties properties = dataStore.getConnection() != null ? dataStore.getConnection().getProperties()\n                        : null;\n\n                if (properties != null)\n                {\n                    String cqlVersion = properties.getProperty(CassandraConstants.CQL_VERSION);\n                    if (cqlVersion != null)\n                    {\n                        if (cqlVersion.equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0)\n                                || cqlVersion.equalsIgnoreCase(CassandraConstants.CQL_VERSION_2_0))\n                        {\n                            return cqlVersion;\n                        }\n                        else\n                        {\n                            logger.warn(\"Invalid {} cql version provided, valid are {},{}.\", cqlVersion,\n                                    CassandraConstants.CQL_VERSION_2_0, CassandraConstants.CQL_VERSION_3_0);\n                        }\n                    }\n                }\n            }\n            return CassandraConstants.CQL_VERSION_2_0;\n        }\n\n        public Schema getSchema(String schemaName)\n        {\n            DataStore dataStore = getDataStore(dataStoreName);\n\n            if (dataStore != null)\n            {\n                List<Schema> schemas = dataStore.getSchemas();\n                if (schemas != null && !schemas.isEmpty())\n                {\n                    for (Schema s : schemas)\n                    {\n                        if (s != null && s.getName() != null && s.getName().equalsIgnoreCase(schemaName))\n                        {\n                            return s;\n                        }\n                    }\n                }\n            }\n            return null;\n        }\n\n        public Table getColumnFamily(String schemaName, String cfName)\n        {\n            Schema schema = getSchema(schemaName);\n            if (schema != null)\n            {\n                if (schema.getTables() != null)\n                {\n                    for (Table table : schema.getTables())\n                    {\n                        if (table != null && table.getName() != null && table.getName().equalsIgnoreCase(cfName))\n                        {\n                            return table;\n                        }\n                    }\n                    if (logger.isWarnEnabled())\n                    {\n                        logger.warn(\"No column family schema found, returning null.\");\n                    }\n                }\n            }\n            return null;\n        }\n\n        public Properties getConnectionProperties()\n        {\n            DataStore ds = getDataStore(dataStoreName);\n            Properties properties = new Properties();\n            if (ds != null)\n            {\n                if (ds.getConnection() != null)\n                {\n                    properties = ds.getConnection().getProperties();\n                    return properties != null ? properties : new Properties();\n                }\n                if (logger.isWarnEnabled())\n                {\n                    logger.warn(\"No connection properties found, returning none.\");\n                }\n            }\n            return properties;\n        }\n\n        public List<Server> getConnectionServers()\n        {\n            DataStore ds = getDataStore(dataStoreName);\n            List<Server> servers = new ArrayList<Server>();\n            if (ds != null && ds.getConnection() != null)\n            {\n                servers = ds.getConnection().getServers();\n                return servers;\n            }\n            return servers;\n        }\n\n        public Properties getDatastoreProperties()\n        {\n            DataStore ds = getDataStore(dataStoreName);\n            Properties properties = new Properties();\n            if (ds != null && ds.getProperties() != null)\n            {\n                properties.putAll(ds.getProperties());\n            }\n            return properties;\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/datahandler/CassandraDataHandler.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.datahandler;\n\nimport java.util.Collection;\nimport java.util.List;\n\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.SuperColumn;\n\nimport com.impetus.client.cassandra.thrift.ThriftRow;\nimport com.impetus.kundera.db.DataRow;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\n\n/**\n * Defines low level translation methods for Cassandra.\n * \n * @author amresh.singh\n */\npublic interface CassandraDataHandler\n{\n\n    /**\n     * From thrift row.\n     * \n     * @param <E>\n     *            the element type\n     * @param clazz\n     *            the clazz\n     * @param m\n     *            the m\n     * @param tr\n     *            the tr\n     * @return the e\n     * @throws Exception\n     *             the exception\n     */\n    <E> E fromThriftRow(Class<E> clazz, EntityMetadata m, DataRow<SuperColumn> tr) throws Exception;\n\n    /**\n     * From thrift row.\n     * \n     * @param clazz\n     *            the clazz\n     * @param m\n     *            the m\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @param consistencyLevel\n     *            the consistency level\n     * @param rowIds\n     *            the row ids\n     * @return the list\n     * @throws Exception\n     *             the exception\n     */\n    List<Object> fromThriftRow(Class<?> clazz, EntityMetadata m, List<String> relationNames, boolean isWrapReq,\n            ConsistencyLevel consistencyLevel, Object... rowIds) throws Exception;\n\n    /**\n     * From thrift row.\n     * \n     * @param clazz\n     *            the clazz\n     * @param m\n     *            the m\n     * @param rowKey\n     *            the row key\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @param consistencyLevel\n     *            the consistency level\n     * @return the object\n     * @throws Exception\n     *             the exception\n     */\n    Object fromThriftRow(Class<?> clazz, EntityMetadata m, Object rowKey, List<String> relationNames,\n            boolean isWrapReq, ConsistencyLevel consistencyLevel) throws Exception;\n\n    /**\n     * Populate entity.\n     * \n     * @param tr\n     *            the tr\n     * @param m\n     *            the m\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @return the object\n     */\n    Object populateEntity(ThriftRow tr, EntityMetadata m, Object entity, List<String> relationNames, boolean isWrapReq);\n\n    /**\n     * To thrift row.\n     *\n     * @param e the e\n     * @param id the id\n     * @param m the m\n     * @param columnFamily the column family\n     * @param columnTTLs TODO\n     * @return the collection\n     * @throws Exception the exception\n     */\n    Collection<ThriftRow> toThriftRow(Object e, Object id, EntityMetadata m, String columnFamily, Object columnTTLs) throws Exception;\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/datahandler/CassandraDataHandlerBase.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.datahandler;\n\nimport java.lang.reflect.Field;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.StringTokenizer;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.PluralAttribute;\n\nimport org.apache.cassandra.cql3.FieldIdentifier;\nimport org.apache.cassandra.db.marshal.AbstractType;\nimport org.apache.cassandra.db.marshal.ListType;\nimport org.apache.cassandra.db.marshal.MapType;\nimport org.apache.cassandra.db.marshal.SetType;\nimport org.apache.cassandra.db.marshal.TypeParser;\nimport org.apache.cassandra.db.marshal.UserType;\nimport org.apache.cassandra.exceptions.ConfigurationException;\nimport org.apache.cassandra.exceptions.SyntaxException;\nimport org.apache.cassandra.serializers.ListSerializer;\nimport org.apache.cassandra.serializers.MapSerializer;\nimport org.apache.cassandra.serializers.SetSerializer;\nimport org.apache.cassandra.serializers.TypeSerializer;\nimport org.apache.cassandra.serializers.UTF8Serializer;\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.CounterColumn;\nimport org.apache.cassandra.thrift.CounterSuperColumn;\nimport org.apache.cassandra.thrift.CqlMetadata;\nimport org.apache.cassandra.thrift.SuperColumn;\nimport org.apache.cassandra.transport.ProtocolVersion;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.schemamanager.CassandraDataTranslator;\nimport com.impetus.client.cassandra.thrift.ThriftDataResultHelper;\nimport com.impetus.client.cassandra.thrift.ThriftRow;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.cache.ElementCollectionCacheManager;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.db.DataRow;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata.Type;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.property.accessor.LongAccessor;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.TimestampGenerator;\n\n/**\n * Base class for all Cassandra Data Handlers.\n * \n * @author amresh.singh\n */\npublic abstract class CassandraDataHandlerBase\n{\n\n    /** The Constant SYS_SUM. */\n    private static final String SYS_SUM = \"system.sum\";\n\n    /** The Constant SYS_AVG. */\n    private static final String SYS_AVG = \"system.avg\";\n\n    /** The Constant SYS_MAX. */\n    private static final String SYS_MAX = \"system.max\";\n\n    /** The Constant SYS_MIN. */\n    private static final String SYS_MIN = \"system.min\";\n\n    /** The Constant SYS_COUNT. */\n    private static final String SYS_COUNT = \"system.count\";\n\n    /** The Constant SUM. */\n    private static final String SUM = \"sum\";\n\n    /** The Constant AVG. */\n    private static final String AVG = \"avg\";\n\n    /** The Constant MAX. */\n    private static final String MAX = \"max\";\n\n    /** The Constant MIN. */\n    private static final String MIN = \"min\";\n\n    /** The Constant COUNT. */\n    private static final String COUNT = \"count\";\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(CassandraDataHandlerBase.class);\n\n    /** The thrift translator. */\n    protected final ThriftDataResultHelper thriftTranslator = new ThriftDataResultHelper();\n\n    /** The client base. */\n    private final CassandraClientBase clientBase;\n\n    /** The kundera metadata. */\n    protected final KunderaMetadata kunderaMetadata;\n\n    /** The generator. */\n    protected final TimestampGenerator generator;\n\n    /**\n     * Instantiates a new cassandra data handler base.\n     * \n     * @param clientBase\n     *            the client base\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param generator\n     *            the generator\n     */\n    public CassandraDataHandlerBase(final CassandraClientBase clientBase, final KunderaMetadata kunderaMetadata,\n            final TimestampGenerator generator)\n    {\n        this.generator = generator;\n        this.clientBase = clientBase;\n        this.kunderaMetadata = kunderaMetadata;\n    }\n\n    /**\n     * From thrift row.\n     * \n     * @param <E>\n     *            the element type\n     * @param clazz\n     *            the clazz\n     * @param m\n     *            the m\n     * @param tr\n     *            the cr\n     * @return the e\n     * @throws Exception\n     *             the exception\n     */\n\n    public <E> E fromThriftRow(Class<E> clazz, EntityMetadata m, DataRow<SuperColumn> tr) throws Exception\n    {\n\n        // Instantiate a new instance\n        E e = null;\n\n        // Set row-key. Note:\n\n        // Get a name->field map for super-columns\n        Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();\n        Map<String, Field> superColumnNameToFieldMap = new HashMap<String, Field>();\n        MetadataUtils.populateColumnAndSuperColumnMaps(m, columnNameToFieldMap, superColumnNameToFieldMap,\n                kunderaMetadata);\n\n        Collection embeddedCollection = null;\n        Field embeddedCollectionField = null;\n        for (SuperColumn sc : tr.getColumns())\n        {\n            if (e == null)\n            {\n                // Instantiate a new instance\n                e = clazz.newInstance();\n\n                // Set row-key.\n                PropertyAccessorHelper.setId(e, m, tr.getId());\n            }\n\n            String scName = PropertyAccessorFactory.STRING.fromBytes(String.class, sc.getName());\n            String scNamePrefix = null;\n\n            if (scName.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) != -1)\n            {\n                scNamePrefix = MetadataUtils.getEmbeddedCollectionPrefix(scName);\n                embeddedCollectionField = superColumnNameToFieldMap.get(scNamePrefix);\n                embeddedCollection = MetadataUtils.getEmbeddedCollectionInstance(embeddedCollectionField);\n                Object embeddedObject = populateEmbeddedObject(sc, m);\n                embeddedCollection.add(embeddedObject);\n                PropertyAccessorHelper.set(e, embeddedCollectionField, embeddedCollection);\n            }\n            else\n            {\n                boolean intoRelations = false;\n                if (scName.equals(Constants.FOREIGN_KEY_EMBEDDED_COLUMN_NAME))\n                {\n                    intoRelations = true;\n                }\n\n                for (Column column : sc.getColumns())\n                {\n                    if (column != null)\n                    {\n                        String name = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());\n                        byte[] value = column.getValue();\n\n                        if (value == null)\n                        {\n                            continue;\n                        }\n\n                        if (intoRelations)\n                        {\n                            String foreignKeys = PropertyAccessorFactory.STRING.fromBytes(String.class, value);\n                            Set<String> keys = MetadataUtils.deserializeKeys(foreignKeys);\n                        }\n                        else\n                        {\n                            // set value of the field in the bean\n                            Field field = columnNameToFieldMap.get(name);\n                            Object embeddedObject = PropertyAccessorHelper.getObject(e, scName);\n                            PropertyAccessorHelper.set(embeddedObject, field, value);\n                        }\n                    }\n                }\n            }\n        }\n\n        if (log.isInfoEnabled())\n        {\n            log.info(\"Returning entity {} for class {}\", e, clazz);\n        }\n        return e;\n    }\n\n    /**\n     * From thrift row.\n     * \n     * @param clazz\n     *            the clazz\n     * @param m\n     *            the m\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @param consistencyLevel\n     *            the consistency level\n     * @param rowIds\n     *            the row ids\n     * @return the list\n     * @throws Exception\n     *             the exception\n     */\n    public List<Object> fromThriftRow(Class<?> clazz, EntityMetadata m, List<String> relationNames, boolean isWrapReq,\n            ConsistencyLevel consistencyLevel, Object... rowIds) throws Exception\n    {\n        List<Object> entities = new ArrayList<Object>();\n        if (rowIds != null)\n        {\n            for (Object rowKey : rowIds)\n            {\n                Object e = fromThriftRow(clazz, m, rowKey, relationNames, isWrapReq, consistencyLevel);\n                if (e != null)\n                {\n                    entities.add(e);\n                }\n            }\n        }\n        return entities;\n    }\n\n    /**\n     * From thrift row.\n     * \n     * @param clazz\n     *            the clazz\n     * @param m\n     *            the m\n     * @param rowKey\n     *            the row key\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @param consistencyLevel\n     *            the consistency level\n     * @return the object\n     * @throws Exception\n     *             the exception\n     */\n    public abstract Object fromThriftRow(Class<?> clazz, EntityMetadata m, Object rowKey, List<String> relationNames,\n            boolean isWrapReq, ConsistencyLevel consistencyLevel) throws Exception;\n\n    /**\n     * Populate embedded object.\n     * \n     * @param sc\n     *            the sc\n     * @param m\n     *            the m\n     * @return the object\n     * @throws Exception\n     *             the exception\n     */\n    private Object populateEmbeddedObject(SuperColumn sc, EntityMetadata m) throws Exception\n    {\n        Field embeddedCollectionField = null;\n        Object embeddedObject = null;\n        String scName = PropertyAccessorFactory.STRING.fromBytes(String.class, sc.getName());\n        String scNamePrefix = null;\n\n        // Get a name->field map for super-columns\n        Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();\n        Map<String, Field> superColumnNameToFieldMap = new HashMap<String, Field>();\n        MetadataUtils.populateColumnAndSuperColumnMaps(m, columnNameToFieldMap, superColumnNameToFieldMap,\n                kunderaMetadata);\n\n        // If this super column is variable in number (name#sequence format)\n        if (scName.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) != -1)\n        {\n            StringTokenizer st = new StringTokenizer(scName, Constants.EMBEDDED_COLUMN_NAME_DELIMITER);\n            if (st.hasMoreTokens())\n            {\n                scNamePrefix = st.nextToken();\n            }\n\n            embeddedCollectionField = superColumnNameToFieldMap.get(scNamePrefix);\n            Class<?> embeddedClass = PropertyAccessorHelper.getGenericClass(embeddedCollectionField);\n\n            // must have a default no-argument constructor\n            try\n            {\n                embeddedClass.getConstructor();\n            }\n            catch (NoSuchMethodException nsme)\n            {\n                throw new PersistenceException(embeddedClass.getName()\n                        + \" is @Embeddable and must have a default no-argument constructor.\");\n            }\n            embeddedObject = embeddedClass.newInstance();\n\n            for (Column column : sc.getColumns())\n            {\n                String name = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());\n                byte[] value = column.getValue();\n                if (value == null)\n                {\n                    continue;\n                }\n                Field columnField = columnNameToFieldMap.get(name);\n                PropertyAccessorHelper.set(embeddedObject, columnField, value);\n            }\n        }\n        else\n        {\n            Field superColumnField = superColumnNameToFieldMap.get(scName);\n            Class superColumnClass = superColumnField.getType();\n            embeddedObject = superColumnClass.newInstance();\n\n            for (Column column : sc.getColumns())\n            {\n                String name = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());\n                byte[] value = column.getValue();\n\n                if (value == null)\n                {\n                    continue;\n                }\n                // set value of the field in the bean\n                Field columnField = columnNameToFieldMap.get(name);\n                PropertyAccessorHelper.set(embeddedObject, columnField, value);\n            }\n        }\n        return embeddedObject;\n    }\n\n    /**\n     * Helper method to convert @Entity to ThriftRow.\n     * \n     * @param e\n     *            the e\n     * @param id\n     *            the id\n     * @param m\n     *            the m\n     * @param columnFamily\n     *            the colmun family\n     * @param columnTTLs\n     *            TODO\n     * @return the base data accessor. thrift row\n     * @throws Exception\n     *             the exception\n     */\n    public Collection<ThriftRow> toThriftRow(Object e, Object id, EntityMetadata m, String columnFamily,\n            Object columnTTLs) throws Exception\n    {\n        // timestamp to use in thrift column objects\n        long timestamp = generator.getTimestamp();\n        // Add super columns to thrift row\n        return onColumnOrSuperColumnThriftRow(/* tr, */m, e, id, timestamp, columnTTLs);\n    }\n\n    /**\n     * Gets the thrift row.\n     * \n     * @param id\n     *            the id\n     * @param columnFamily\n     *            the column family\n     * @param thriftRows\n     *            the thrift rows\n     * @return the thrift row\n     */\n    private ThriftRow getThriftRow(Object id, String columnFamily, Map<String, ThriftRow> thriftRows)\n    {\n        ThriftRow tr = thriftRows.get(columnFamily);\n        if (tr == null)\n        {\n            tr = new ThriftRow();\n            tr.setColumnFamilyName(columnFamily); // column-family name\n            tr.setId(id); // Id\n            thriftRows.put(columnFamily, tr);\n        }\n        return tr;\n    }\n\n    /**\n     * To index thrift row.\n     * \n     * @param e\n     *            the e\n     * @param m\n     *            the m\n     * @param columnFamily\n     *            the column family\n     * @return the list\n     */\n    public List<ThriftRow> toIndexThriftRow(Object e, EntityMetadata m, String columnFamily)\n    {\n        List<ThriftRow> indexThriftRows = new ArrayList<ThriftRow>();\n\n        byte[] rowKey = getThriftColumnValue(e, m.getIdAttribute());\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n\n        // Add thrift rows for embeddables\n        Map<String, EmbeddableType> embeddables = metaModel.getEmbeddables(m.getEntityClazz());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n        for (String embeddedFieldName : embeddables.keySet())\n        {\n            EmbeddableType embeddedColumn = embeddables.get(embeddedFieldName);\n\n            // Index embeddable only when specified by user\n            Field embeddedField = (Field) entityType.getAttribute(embeddedFieldName).getJavaMember();\n            if (!MetadataUtils.isEmbeddedAtributeIndexable(embeddedField))\n            {\n                continue;\n            }\n\n            Object embeddedObject = PropertyAccessorHelper.getObject(e,\n                    (Field) entityType.getAttribute(embeddedFieldName).getJavaMember());\n            if (embeddedObject == null)\n            {\n                continue;\n            }\n            if (embeddedObject instanceof Collection)\n            {\n                ElementCollectionCacheManager ecCacheHandler = ElementCollectionCacheManager.getInstance();\n\n                for (Object obj : (Collection) embeddedObject)\n                {\n                    for (Object column : embeddedColumn.getAttributes())\n                    {\n\n                        Attribute columnAttribute = (Attribute) column;\n                        String columnName = columnAttribute.getName();\n                        if (!MetadataUtils.isColumnInEmbeddableIndexable(embeddedField, columnName))\n                        {\n                            continue;\n                        }\n                        // Column Value\n                        String id = (String) CassandraDataTranslator.decompose(\n                                ((AbstractAttribute) m.getIdAttribute()).getBindableJavaType(), rowKey, false);\n                        String superColumnName = ecCacheHandler.getElementCollectionObjectName(id, obj);\n\n                        ThriftRow tr = constructIndexTableThriftRow(columnFamily, embeddedFieldName, obj,\n                                columnAttribute, rowKey, superColumnName);\n                        if (tr != null)\n                        {\n                            indexThriftRows.add(tr);\n                        }\n                    }\n                }\n            }\n            else\n            {\n                for (Object column : embeddedColumn.getAttributes())\n                {\n                    Attribute columnAttribute = (Attribute) column;\n                    String columnName = columnAttribute.getName();\n                    Class<?> columnClass = ((AbstractAttribute) columnAttribute).getBindableJavaType();\n                    if (!MetadataUtils.isColumnInEmbeddableIndexable(embeddedField, columnName)\n                            || columnClass.equals(byte[].class))\n                    {\n                        continue;\n                    }\n\n                    // No EC Name\n                    ThriftRow tr = constructIndexTableThriftRow(columnFamily, embeddedFieldName, embeddedObject,\n                            (Attribute) column, rowKey, \"\");\n                    if (tr != null)\n                    {\n                        indexThriftRows.add(tr);\n                    }\n                }\n            }\n        }\n        return indexThriftRows;\n    }\n\n    /**\n     * Constructs Thrift Tow (each record) for Index Table.\n     * \n     * @param columnFamily\n     *            Column family Name for Index Table\n     * @param embeddedFieldName\n     *            the embedded field name\n     * @param obj\n     *            Embedded Object instance\n     * @param column\n     *            Instance of {@link Column}\n     * @param rowKey\n     *            Name of Index Column\n     * @param ecValue\n     *            Name of embeddable object in Element Collection cache (usually\n     *            in the form of <element collection field name>#<integer\n     *            counter>\n     * @return Instance of {@link ThriftRow}\n     */\n    private ThriftRow constructIndexTableThriftRow(String columnFamily, String embeddedFieldName, Object obj,\n            Attribute column, byte[] rowKey, String ecValue)\n    {\n        // Column Name\n        Field columnField = (Field) column.getJavaMember();\n        byte[] indexColumnName = PropertyAccessorHelper.get(obj, columnField);\n\n        ThriftRow tr = null;\n        if (indexColumnName != null && indexColumnName.length != 0 && rowKey != null)\n        {\n            // Construct Index Table Thrift Row\n            tr = new ThriftRow();\n            tr.setColumnFamilyName(columnFamily); // Index column-family name\n            tr.setId(embeddedFieldName + Constants.INDEX_TABLE_ROW_KEY_DELIMITER + column.getName()); // Id\n\n            SuperColumn thriftSuperColumn = new SuperColumn();\n            thriftSuperColumn.setName(indexColumnName);\n\n            Column thriftColumn = new Column();\n            thriftColumn.setName(rowKey);\n            thriftColumn.setValue(ecValue.getBytes());\n            thriftColumn.setTimestamp(generator.getTimestamp());\n\n            thriftSuperColumn.addToColumns(thriftColumn);\n\n            tr.addSuperColumn(thriftSuperColumn);\n        }\n        return tr;\n    }\n\n    /**\n     * Gets the foreign keys from join table.\n     * \n     * @param <E>\n     *            the element type\n     * @param inverseJoinColumnName\n     *            the inverse join column name\n     * @param columns\n     *            the columns\n     * @param columnJavaType\n     *            the column java type\n     * @return the foreign keys from join table\n     */\n    public <E> List<Object> getForeignKeysFromJoinTable(String inverseJoinColumnName, List<Column> columns,\n            Class columnJavaType)\n    {\n        List<Object> foreignKeys = new ArrayList<Object>();\n\n        if (columns == null || columns.isEmpty())\n        {\n            return foreignKeys;\n        }\n\n        for (Column c : columns)\n        {\n            try\n            {\n                // Thrift Column name\n                String thriftColumnName = PropertyAccessorFactory.STRING.fromBytes(String.class, c.getName());\n\n                // Thrift Column Value\n                byte[] thriftColumnValue = c.getValue();\n                if (null == thriftColumnValue)\n                {\n                    continue;\n                }\n\n                if (thriftColumnName != null && thriftColumnName.startsWith(inverseJoinColumnName))\n                {\n                    Object val = PropertyAccessorHelper.getObject(columnJavaType, thriftColumnValue);\n                    foreignKeys.add(val);\n                }\n            }\n            catch (PropertyAccessException e)\n            {\n                continue;\n            }\n\n        }\n        return foreignKeys;\n    }\n\n    /**\n     * Populate entity.\n     * \n     * @param tr\n     *            the tr\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @return the object\n     */\n    public Object populateEntity(ThriftRow tr, EntityMetadata m, Object entity, List<String> relationNames,\n            boolean isWrapReq)\n    {\n        Map<String, Object> relations = new HashMap<String, Object>();\n        try\n        {\n            boolean isCql3Enabled = clientBase.isCql3Enabled(m);\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n            EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n            for (Column column : tr.getColumns())\n            {\n                if (column != null)\n                {\n                    String thriftColumnName = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());\n                    if ((CassandraConstants.CQL_KEY.equalsIgnoreCase(thriftColumnName) || ((AbstractAttribute) m\n                            .getIdAttribute()).getJPAColumnName().equals(thriftColumnName)) && tr.getId() == null)\n                    {\n                        entity = KunderaCoreUtils.initialize(m, entity, null);\n                        setId(m, entity, column.getValue(), isCql3Enabled);\n                    }\n                    else\n                    {\n                        entity = onColumn(column, m, entity, entityType, relationNames, isWrapReq, relations,\n                                isCql3Enabled);\n\n                        String discriminatorColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n                        String discriminatorValue = ((AbstractManagedType) entityType).getDiscriminatorValue();\n\n                        if (thriftColumnName != null\n                                && thriftColumnName.equals(discriminatorColumn)\n                                && column.getValue() != null\n                                && !PropertyAccessorFactory.STRING.fromBytes(String.class, column.getValue()).equals(\n                                        discriminatorValue))\n                        {\n                            entity = null;\n                            break;\n                        }\n                    }\n                }\n            }\n\n            // Add all super columns to entity\n            Collection embeddedCollection = null;\n            Field embeddedCollectionField = null;\n\n            boolean mappingProcessed = false;\n            Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();\n            Map<String, Field> superColumnNameToFieldMap = new HashMap<String, Field>();\n\n            for (SuperColumn superColumn : tr.getSuperColumns())\n            {\n                if (superColumn != null)\n                {\n\n                    entity = KunderaCoreUtils.initialize(m, entity, tr.getId());\n                    String scName = PropertyAccessorFactory.STRING.fromBytes(String.class, superColumn.getName());\n                    String scNamePrefix = null;\n\n                    // Map to hold property-name=>foreign-entity relations\n                    Map<String, Set<String>> foreignKeysMap = new HashMap<String, Set<String>>();\n\n                    // Get a name->field map for super-columns\n                    if (!mappingProcessed)\n                    {\n                        MetadataUtils.populateColumnAndSuperColumnMaps(m, columnNameToFieldMap,\n                                superColumnNameToFieldMap, kunderaMetadata);\n                        mappingProcessed = true;\n                    }\n\n                    if (scName.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) != -1)\n                    {\n                        scNamePrefix = MetadataUtils.getEmbeddedCollectionPrefix(scName);\n                        embeddedCollectionField = superColumnNameToFieldMap.get(scNamePrefix);\n\n                        if (embeddedCollection == null)\n                        {\n                            embeddedCollection = MetadataUtils.getEmbeddedCollectionInstance(embeddedCollectionField);\n                        }\n\n                        Object embeddedObject = MetadataUtils.getEmbeddedGenericObjectInstance(embeddedCollectionField);\n\n                        scrollOverSuperColumn(m, relationNames, isWrapReq, relations, entityType, superColumn,\n                                embeddedObject, columnNameToFieldMap);\n\n                        Collection collection = PropertyAccessorHelper.getCollectionInstance(embeddedCollectionField);\n                        collection.add(embeddedObject);\n\n                        PropertyAccessorHelper.set(entity, embeddedCollectionField, collection);\n\n                        embeddedCollection.add(embeddedObject);\n\n                        // Add this embedded object to cache\n                        ElementCollectionCacheManager.getInstance().addElementCollectionCacheMapping(tr.getId(),\n                                embeddedObject, scName);\n                    }\n                    else\n                    {\n                        if (superColumnNameToFieldMap.containsKey(scName))\n                        {\n                            Field field = superColumnNameToFieldMap.get(scName);\n\n                            Object embeddedObj = PropertyAccessorHelper.getObject(entity, field);\n                            if (embeddedObj == null)\n                            {\n                                embeddedObj = field.getType().newInstance();\n                            }\n                            // column\n                            scrollOverSuperColumn(m, relationNames, isWrapReq, relations, entityType, superColumn,\n                                    embeddedObj, columnNameToFieldMap);\n                            PropertyAccessorHelper.set(entity, field, embeddedObj);\n                        }\n                        else\n                        {\n                            scrollOverSuperColumn(m, relationNames, isWrapReq, relations, entityType, superColumn,\n                                    entity, isCql3Enabled);\n                        }\n\n                    }\n                }\n            }\n\n            mappingProcessed = false;\n\n            for (CounterColumn counterColumn : tr.getCounterColumns())\n            {\n                if (counterColumn != null)\n                {\n                    entity = KunderaCoreUtils.initialize(m, entity, tr.getId());\n                    onCounterColumn(counterColumn, m, entity, entityType, relationNames, isWrapReq, relations,\n                            isCql3Enabled);\n                }\n            }\n\n            for (CounterSuperColumn counterSuperColumn : tr.getCounterSuperColumns())\n            {\n                if (counterSuperColumn != null)\n                {\n                    entity = KunderaCoreUtils.initialize(m, entity, tr.getId());\n                    String scName = PropertyAccessorFactory.STRING\n                            .fromBytes(String.class, counterSuperColumn.getName());\n                    String scNamePrefix = null;\n\n                    // Map to hold property-name=>foreign-entity relations\n                    Map<String, Set<String>> foreignKeysMap = new HashMap<String, Set<String>>();\n\n                    // Get a name->field map for super-columns\n                    if (!mappingProcessed)\n                    {\n                        MetadataUtils.populateColumnAndSuperColumnMaps(m, columnNameToFieldMap,\n                                superColumnNameToFieldMap, kunderaMetadata);\n                        mappingProcessed = true;\n                    }\n\n                    if (scName.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) != -1)\n                    {\n                        scNamePrefix = MetadataUtils.getEmbeddedCollectionPrefix(scName);\n                        embeddedCollectionField = superColumnNameToFieldMap.get(scNamePrefix);\n\n                        if (embeddedCollection == null)\n                        {\n                            embeddedCollection = MetadataUtils.getEmbeddedCollectionInstance(embeddedCollectionField);\n                        }\n\n                        Object embeddedObject = MetadataUtils.getEmbeddedGenericObjectInstance(embeddedCollectionField);\n\n                        scrollOverCounterSuperColumn(m, relationNames, isWrapReq, relations, entityType,\n                                counterSuperColumn, embeddedObject, columnNameToFieldMap);\n                        embeddedCollection.add(embeddedObject);\n\n                        // Add this embedded object to cache\n                        ElementCollectionCacheManager.getInstance().addElementCollectionCacheMapping(tr.getId(),\n                                embeddedObject, scName);\n                    }\n                    else\n                    {\n                        if (superColumnNameToFieldMap.containsKey(scName))\n                        {\n                            Field field = superColumnNameToFieldMap.get(scName);\n                            Object embeddedObj = field.getType().newInstance();\n                            // column\n                            scrollOverCounterSuperColumn(m, relationNames, isWrapReq, relations, entityType,\n                                    counterSuperColumn, embeddedObj, columnNameToFieldMap);\n                            PropertyAccessorHelper.set(entity, field, embeddedObj);\n                        }\n                        else\n                        {\n                            scrollOverCounterSuperColumn(m, relationNames, isWrapReq, relations, entityType,\n                                    counterSuperColumn, entity, isCql3Enabled);\n                        }\n                    }\n                }\n            }\n\n            if (embeddedCollection != null && !embeddedCollection.isEmpty())\n            {\n                PropertyAccessorHelper.set(entity, embeddedCollectionField, embeddedCollection);\n            }\n\n        }\n        catch (Exception e)\n        {\n            log.error(\"Eror while retrieving data, Caused by: .\", e);\n            throw new PersistenceException(e);\n        }\n\n        if (entity != null && tr.getId() != null)\n        {\n            PropertyAccessorHelper.setId(entity, m, tr.getId());\n        }\n        return isWrapReq && relations != null && !relations.isEmpty() ? new EnhanceEntity(entity,\n                PropertyAccessorHelper.getId(entity, m), relations) : entity;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param columnValue\n     *            the column value\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     */\n    private void setId(EntityMetadata m, Object entity, Object columnValue, boolean isCql3Enabled)\n    {\n        if (isCql3Enabled && !m.getType().equals(Type.SUPER_COLUMN_FAMILY))\n        {\n            setFieldValueViaCQL(entity, columnValue, m.getIdAttribute());\n        }\n        else\n        {\n            setFieldValue(entity, columnValue, m.getIdAttribute());\n        }\n    }\n\n    /**\n     * Scroll over super column.\n     * \n     * @param m\n     *            the m\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @param relations\n     *            the relations\n     * @param entityType\n     *            the entity type\n     * @param superColumn\n     *            the super column\n     * @param embeddedObject\n     *            the embedded object\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    private void scrollOverSuperColumn(EntityMetadata m, List<String> relationNames, boolean isWrapReq,\n            Map<String, Object> relations, EntityType entityType, SuperColumn superColumn, Object embeddedObject,\n            boolean isCql3Enabled) throws InstantiationException, IllegalAccessException\n    {\n        for (Column column : superColumn.getColumns())\n        {\n            embeddedObject = onColumn(column, m, embeddedObject, entityType, relationNames, isWrapReq, relations,\n                    isCql3Enabled);\n        }\n    }\n\n    /**\n     * Scroll over counter super column.\n     * \n     * @param m\n     *            the m\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @param relations\n     *            the relations\n     * @param entityType\n     *            the entity type\n     * @param superColumn\n     *            the super column\n     * @param embeddedObject\n     *            the embedded object\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    private void scrollOverCounterSuperColumn(EntityMetadata m, List<String> relationNames, boolean isWrapReq,\n            Map<String, Object> relations, EntityType entityType, CounterSuperColumn superColumn,\n            Object embeddedObject, boolean isCql3Enabled) throws InstantiationException, IllegalAccessException\n    {\n        for (CounterColumn column : superColumn.getColumns())\n        {\n            onCounterColumn(column, m, embeddedObject, entityType, relationNames, isWrapReq, relations, isCql3Enabled);\n        }\n    }\n\n    /**\n     * Scroll over counter super column.\n     * \n     * @param m\n     *            the m\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @param relations\n     *            the relations\n     * @param entityType\n     *            the entity type\n     * @param superColumn\n     *            the super column\n     * @param embeddedObject\n     *            the embedded object\n     * @param superColumnFieldMap\n     *            the super column field map\n     */\n    private void scrollOverCounterSuperColumn(EntityMetadata m, List<String> relationNames, boolean isWrapReq,\n            Map<String, Object> relations, EntityType entityType, CounterSuperColumn superColumn,\n            Object embeddedObject, Map<String, Field> superColumnFieldMap)\n    {\n        for (CounterColumn column : superColumn.getColumns())\n        {\n            String thriftColumnName = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());\n            String thriftColumnValue = new Long(column.getValue()).toString();\n            PropertyAccessorHelper.set(embeddedObject, superColumnFieldMap.get(thriftColumnName), thriftColumnValue);\n        }\n    }\n\n    /**\n     * Scroll over super column.\n     * \n     * @param m\n     *            the m\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @param relations\n     *            the relations\n     * @param entityType\n     *            the entity type\n     * @param superColumn\n     *            the super column\n     * @param embeddedObject\n     *            the embedded object\n     * @param superColumnFieldMap\n     *            the super column field map\n     */\n    private void scrollOverSuperColumn(EntityMetadata m, List<String> relationNames, boolean isWrapReq,\n            Map<String, Object> relations, EntityType entityType, SuperColumn superColumn, Object embeddedObject,\n            Map<String, Field> superColumnFieldMap)\n    {\n        for (Column column : superColumn.getColumns())\n        {\n            String thriftColumnName = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());\n            byte[] thriftColumnValue = column.getValue();\n            PropertyAccessorHelper.set(embeddedObject, superColumnFieldMap.get(thriftColumnName), thriftColumnValue);\n        }\n    }\n\n    /**\n     * On column.\n     * \n     * @param column\n     *            the column\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param entityType\n     *            the entity type\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @param relations\n     *            the relations\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return the object\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    private Object onColumn(Column column, EntityMetadata m, Object entity, EntityType entityType,\n            List<String> relationNames, boolean isWrapReq, Map<String, Object> relations, boolean isCql3Enabled)\n            throws InstantiationException, IllegalAccessException\n    {\n        String thriftColumnName = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());\n        byte[] thriftColumnValue = column.getValue();\n\n        String discriminatorColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n        String discriminatorValue = ((AbstractManagedType) entityType).getDiscriminatorValue();\n\n        if (!thriftColumnName.equals(discriminatorColumn))\n        {\n            if (m.isCounterColumnType())\n            {\n                if (thriftColumnName.equals(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName()))\n                {\n                    return populateViaThrift(m, entity, entityType, relationNames, relations, thriftColumnName,\n                            column.getValue(), isCql3Enabled);\n                }\n                else\n                {\n                    LongAccessor accessor = new LongAccessor();\n                    Long value = accessor.fromBytes(Long.class, column.getValue());\n                    return populateViaThrift(m, entity, entityType, relationNames, relations, thriftColumnName,\n                            value != null ? value.toString() : null, isCql3Enabled);\n                }\n            }\n\n            return populateViaThrift(m, entity, entityType, relationNames, relations, thriftColumnName,\n                    thriftColumnValue, isCql3Enabled);\n        }\n        return entity;\n    }\n\n    /**\n     * On counter column.\n     * \n     * @param column\n     *            the column\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param entityType\n     *            the entity type\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @param relations\n     *            the relations\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    private void onCounterColumn(CounterColumn column, EntityMetadata m, Object entity, EntityType entityType,\n            List<String> relationNames, boolean isWrapReq, Map<String, Object> relations, boolean isCql3Enabled)\n            throws InstantiationException, IllegalAccessException\n    {\n        String thriftColumnName = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());\n        String thriftColumnValue = new Long(column.getValue()).toString();\n        populateViaThrift(m, entity, entityType, relationNames, relations, thriftColumnName, thriftColumnValue,\n                isCql3Enabled);\n    }\n\n    /**\n     * Populate via thrift.\n     * \n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param entityType\n     *            the entity type\n     * @param relationNames\n     *            the relation names\n     * @param relations\n     *            the relations\n     * @param thriftColumnName\n     *            the thrift column name\n     * @param thriftColumnValue\n     *            the thrift column value\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return the object\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    private Object populateViaThrift(EntityMetadata m, Object entity, EntityType entityType,\n            List<String> relationNames, Map<String, Object> relations, String thriftColumnName,\n            Object thriftColumnValue, boolean isCql3Enabled) throws InstantiationException, IllegalAccessException\n    {\n        if (relationNames == null || !relationNames.contains(thriftColumnName))\n        {\n            if (thriftColumnValue != null)\n            {\n                MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                        m.getPersistenceUnit());\n                String fieldName = m.getFieldName(thriftColumnName);\n                Attribute attribute = fieldName != null ? entityType.getAttribute(fieldName) : null;\n\n                if (attribute != null)\n                {\n                    entity = KunderaCoreUtils.initialize(m, entity, null);\n                    if (!attribute.isAssociation())\n                    {\n                        String idColumnName = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n                        if (!metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())\n                                && thriftColumnName.equals(idColumnName))\n                        {\n                            setId(m, entity, thriftColumnValue, isCql3Enabled);\n                            PropertyAccessorHelper.setId(entity, m, (byte[]) thriftColumnValue);\n                        }\n                        // remove super column family check and populate\n                        // embedded\n\n                        if (isCql3Enabled && !m.isCounterColumnType())\n                        {\n                            if (metaModel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType()))\n                            {\n                                if (attribute.isCollection())\n                                {\n                                    // element collection\n                                    entity = setElementCollection(entity, thriftColumnValue, metaModel, attribute);\n                                }\n                                else\n                                {\n                                    entity = setUdtValue(entity, thriftColumnValue, metaModel, attribute);\n                                }\n                            }\n                            else\n                            {\n                                setFieldValueViaCQL(entity, thriftColumnValue, attribute);\n                            }\n                        }\n                        else\n                        {\n                            setFieldValue(entity, thriftColumnValue, attribute);\n                        }\n                    }\n                }\n                else if (metaModel.isEmbeddable(((AbstractAttribute) m.getIdAttribute()).getBindableJavaType())\n                        && !isAggregate(thriftColumnName))\n                {\n                    entity = populateCompositeId(m, entity, thriftColumnName, thriftColumnValue, metaModel,\n                            m.getIdAttribute(), m.getEntityClazz());\n                }\n                else if (clientBase.getCqlMetadata() != null)\n                {\n                    if (entity == null)\n                    {\n                        entity = new HashMap();\n                    }\n                    if (entity instanceof HashMap)\n                    {\n                        composeAndAdd((HashMap) entity, clientBase.getCqlMetadata(), thriftColumnValue,\n                                thriftColumnName);\n                    }\n                }\n            }\n        }\n        else\n        {\n            // populate relation.\n            if (relationNames != null && relationNames.contains(thriftColumnName) && thriftColumnValue != null)\n            {\n\n                String fieldName = m.getFieldName(thriftColumnName);\n                Attribute attribute = fieldName != null ? entityType.getAttribute(fieldName) : null;\n\n                EntityMetadata relationMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                        ((AbstractAttribute) attribute).getBindableJavaType());\n                Object value;\n                if (isCql3Enabled && !m.getType().equals(Type.SUPER_COLUMN_FAMILY))\n                {\n                    value = getFieldValueViaCQL(thriftColumnValue, relationMetadata.getIdAttribute());\n                }\n                else\n                {\n                    value = PropertyAccessorHelper.getObject(relationMetadata.getIdAttribute().getJavaType(),\n                            (byte[]) thriftColumnValue);\n                }\n                relations.put(thriftColumnName, value);\n\n                if (entity == null)\n                {\n                    entity = KunderaCoreUtils.initialize(m, entity, null);\n                }\n                // prepare EnhanceEntity and return it\n            }\n\n        }\n        return entity;\n    }\n\n    /**\n     * Checks if is aggregate.\n     * \n     * @param thriftColumnName\n     *            the thrift column name\n     * @return true, if is aggregate\n     */\n    private boolean isAggregate(String thriftColumnName)\n    {\n        if (thriftColumnName.startsWith(SYS_COUNT) || thriftColumnName.startsWith(SYS_MIN)\n                || thriftColumnName.startsWith(SYS_MAX) || thriftColumnName.startsWith(SYS_AVG)\n                || thriftColumnName.startsWith(SYS_SUM))\n        {\n            return true;\n        }\n        else if (thriftColumnName.startsWith(COUNT) || thriftColumnName.startsWith(MIN)\n                || thriftColumnName.startsWith(MAX) || thriftColumnName.startsWith(AVG)\n                || thriftColumnName.startsWith(SUM))\n        {\n            return true;\n        }\n        return false;\n    }\n\n    /**\n     * Compose and add.\n     * \n     * @param entity\n     *            the entity\n     * @param cqlMetadata\n     *            the cql metadata\n     * @param thriftColumnValue\n     *            the thrift column value\n     * @param thriftColumnName\n     *            the thrift column name\n     */\n    private void composeAndAdd(HashMap entity, CqlMetadata cqlMetadata, Object thriftColumnValue,\n            String thriftColumnName)\n    {\n        byte[] columnName = thriftColumnName.getBytes();\n\n        Map<ByteBuffer, String> schemaTypes = this.clientBase.getCqlMetadata().getValue_types();\n        AbstractType<?> type = null;\n        try\n        {\n            type = TypeParser.parse(schemaTypes.get(ByteBuffer.wrap((byte[]) columnName)));\n        }\n        catch (SyntaxException | ConfigurationException e)\n        {\n            log.error(e.getMessage());\n            throw new KunderaException(\"Error while parsing CQL Type \" + e);\n        }\n\n        entity.put(thriftColumnName, type.compose(ByteBuffer.wrap((byte[]) thriftColumnValue)));\n    }\n\n    /**\n     * Sets the udt value.\n     * \n     * @param entity\n     *            the entity\n     * @param thriftColumnValue\n     *            the thrift column value\n     * @param metaModel\n     *            the meta model\n     * @param attribute\n     *            the attribute\n     * @return the object\n     */\n    private Object setUdtValue(Object entity, Object thriftColumnValue, MetamodelImpl metaModel, Attribute attribute)\n    {\n        List<FieldIdentifier> fieldNames = new ArrayList<FieldIdentifier>();\n        List<AbstractType<?>> fieldTypes = new ArrayList<AbstractType<?>>();\n\n        String val = null;\n\n        // get from cqlMetadata, details of types and names (for maintaining\n        // order)\n        Map<ByteBuffer, String> schemaTypes = this.clientBase.getCqlMetadata().getValue_types();\n        for (Map.Entry<ByteBuffer, String> schemaType : schemaTypes.entrySet())\n        {\n            UTF8Serializer utf8Serializer = UTF8Serializer.instance;\n            String key = utf8Serializer.deserialize((schemaType.getKey()));\n            if (key.equals(((AbstractAttribute) attribute).getJavaMember().getName()))\n            {\n                val = schemaType.getValue();\n                break;\n            }\n        }\n\n        UserType userType = null;\n\n        try\n        {\n            userType = UserType.getInstance(new TypeParser(val.substring(val.indexOf(\"UserType(\") + 8, val.length())));\n        }\n        catch (ConfigurationException | SyntaxException e)\n        {\n            log.error(e.getMessage());\n            throw new KunderaException(\"Error while getting instance of UserType \" + e);\n        }\n\n        fieldNames = userType.fieldNames();\n        fieldTypes = userType.allTypes();\n\n        Field field = (Field) ((AbstractAttribute) attribute).getJavaMember();\n        Class embeddedClass = ((AbstractAttribute) attribute).getBindableJavaType();\n\n        Object embeddedObject = KunderaCoreUtils.createNewInstance(embeddedClass);\n\n        Object finalValue = populateEmbeddedRecursive((ByteBuffer.wrap((byte[]) thriftColumnValue)), fieldTypes,\n                fieldNames, embeddedObject, metaModel);\n\n        PropertyAccessorHelper.set(entity, field, finalValue);\n\n        return entity;\n    }\n\n    /**\n     * Populate embedded recursive.\n     * \n     * @param value\n     *            the value\n     * @param types\n     *            the types\n     * @param fieldNames\n     *            the field names\n     * @param entity\n     *            the entity\n     * @param metaModel\n     *            the meta model\n     * @return the object\n     */\n    public Object populateEmbeddedRecursive(ByteBuffer value, List<AbstractType<?>> types, List<FieldIdentifier> fieldNames,\n            Object entity, MetamodelImpl metaModel)\n    {\n        ByteBuffer input = value.duplicate();\n        EmbeddableType emb = metaModel.embeddable(entity.getClass());\n\n        for (int i = 0; i < types.size(); i++)\n        {\n\n            if (!input.hasRemaining())\n                return entity;\n\n            AbstractType<?> type = types.get(i);\n            String name = fieldNames.get(i).toString(); \t\t // JPA name,\n                                                                 // convert to\n                                                                 // column name\n\n            Field fieldToSet = null;\n            AbstractAttribute attribute = null;\n            // change this if possible\n            for (Object attr : emb.getAttributes())\n            {\n                if (((AbstractAttribute) attr).getJPAColumnName().equals(name))\n                {\n                    attribute = (AbstractAttribute) attr;\n                    break;\n                }\n            }\n            fieldToSet = (Field) attribute.getJavaMember();\n            Class embeddedClass = attribute.getBindableJavaType();\n\n            int size = input.getInt();\n            if (size < 0)\n            {\n                continue;\n            }\n\n            ByteBuffer field = ByteBufferUtil.readBytes(input, size);\n\n            if (type.getClass().getSimpleName().equals(\"UserType\"))\n            {\n                List<FieldIdentifier> subFieldNames = ((UserType) type).fieldNames();// ok\n                List<AbstractType<?>> subfieldTypes = ((UserType) type).fieldTypes();\n\n                // create entity with type_name and populate fields, set entity\n                // in parent object after exit\n                Object embeddedObjectChild = KunderaCoreUtils.createNewInstance(embeddedClass);\n\n                Object processedEntity = populateEmbeddedRecursive(field, subfieldTypes, subFieldNames,\n                        embeddedObjectChild, metaModel);\n                PropertyAccessorHelper.set(entity, fieldToSet, processedEntity);\n            }\n            else\n            {\n                boolean flag = true;\n\n                if (type.getClass().getSimpleName().equals(\"MapType\"))\n                {\n                    if (((MapType) type).getValuesType().getClass().getSimpleName().equals(\"UserType\"))\n                    {\n                        flag = false;\n                        // create instance of embedded object (UserType)\n                        setElementCollectionMap((MapType) type, field, entity, fieldToSet, metaModel, embeddedClass,\n                                false);\n                    }\n                }\n                else if (type.getClass().getSimpleName().equals(\"ListType\"))\n                {\n                    if (((ListType) type).getElementsType().getClass().getSimpleName().equals(\"UserType\"))\n                    {\n                        flag = false;\n                        setElementCollectionList((ListType) type, field, entity, fieldToSet, metaModel, embeddedClass,\n                                false);\n                    }\n                }\n                else if (type.getClass().getSimpleName().equals(\"SetType\"))\n                {\n                    if (((SetType) type).getElementsType().getClass().getSimpleName().equals(\"UserType\"))\n                    {\n                        flag = false;\n                        setElementCollectionSet((SetType) type, field, entity, fieldToSet, metaModel, embeddedClass,\n                                false);\n                    }\n                }\n                if (flag)\n                {\n                    TypeSerializer serializer = type.getSerializer();\n                    serializer.validate(field);\n\n                    Object finalValue = serializer.deserialize(field);\n                    if (type.getClass().getSimpleName().equals(\"UTF8Type\"))\n                    {\n                        PropertyAccessorHelper.set(entity, fieldToSet, ((String) finalValue).getBytes());\n                    }\n                    else\n                    {\n                        PropertyAccessorHelper.set(entity, fieldToSet, finalValue);\n                    }\n                }\n\n            }\n\n        }\n        return entity;\n    }\n\n    /**\n     * Sets the field value.\n     * \n     * @param entity\n     *            the entity\n     * @param thriftColumnValue\n     *            the thrift column value\n     * @param attribute\n     *            the attribute\n     */\n    private void setFieldValue(Object entity, Object thriftColumnValue, Attribute attribute)\n    {\n        if (attribute != null)\n        {\n            try\n            {\n                if (thriftColumnValue.getClass().isAssignableFrom(String.class))\n                {\n                    PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), (String) thriftColumnValue);\n                }\n                else if (CassandraDataTranslator.isCassandraDataTypeClass(((AbstractAttribute) attribute)\n                        .getBindableJavaType()))\n                {\n                    Object decomposed = null;\n                    try\n                    {\n                        Class<?> clazz = ((AbstractAttribute) attribute).getBindableJavaType();\n                        decomposed = CassandraDataTranslator.decompose(clazz, thriftColumnValue, false);\n                    }\n                    catch (Exception e)\n                    {\n                        String tableName = entity.getClass().getSimpleName();\n                        String fieldName = attribute.getName();\n                        String msg = \"Decomposing failed for `\" + tableName + \"`.`\" + fieldName\n                                + \"`, did you set the correct type in your entity class?\";\n                        log.error(msg, e);\n                        throw new KunderaException(msg, e);\n                    }\n                    PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), decomposed);\n                }\n                else\n                {\n                    PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), (byte[]) thriftColumnValue);\n                }\n\n            }\n            catch (PropertyAccessException pae)\n            {\n                log.warn(\"Error while setting field value, Caused by: .\", pae);\n            }\n        }\n    }\n\n    /**\n     * Sets the field value via cql.\n     * \n     * @param entity\n     *            the entity\n     * @param thriftColumnValue\n     *            the thrift column value\n     * @param attribute\n     *            the attribute\n     */\n    private void setFieldValueViaCQL(Object entity, Object thriftColumnValue, Attribute attribute)\n    {\n        if (attribute != null)\n        {\n            try\n            {\n                if (attribute.isCollection())\n                {\n                    setCollectionValue(entity, thriftColumnValue, attribute);\n                }\n                else if (CassandraDataTranslator.isCassandraDataTypeClass(((AbstractAttribute) attribute)\n                        .getBindableJavaType()))\n                {\n                    PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), CassandraDataTranslator\n                            .decompose(((AbstractAttribute) attribute).getBindableJavaType(), thriftColumnValue, true));\n                }\n                else\n                {\n                    PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), (byte[]) thriftColumnValue);\n                }\n            }\n            catch (PropertyAccessException pae)\n            {\n                log.warn(\"Error while setting field{} value via CQL, Caused by: .\", attribute.getName(), pae);\n            }\n        }\n    }\n\n    /**\n     * Sets the element collection.\n     * \n     * @param entity\n     *            the entity\n     * @param thriftColumnValue\n     *            the thrift column value\n     * @param metaModel\n     *            the meta model\n     * @param attribute\n     *            the attribute\n     * @return the object\n     */\n    private Object setElementCollection(Object entity, Object thriftColumnValue, MetamodelImpl metaModel,\n            Attribute attribute)\n    {\n        String cqlColumnMetadata = null;\n        Map<ByteBuffer, String> schemaTypes = this.clientBase.getCqlMetadata().getValue_types();\n        for (Map.Entry<ByteBuffer, String> schemaType : schemaTypes.entrySet())\n        {\n\n            String key = UTF8Serializer.instance.deserialize((schemaType.getKey()));\n            if (key.equals(((AbstractAttribute) attribute).getJPAColumnName()))\n            {\n                cqlColumnMetadata = schemaType.getValue();\n                break;\n            }\n        }\n\n        Field field = (Field) ((AbstractAttribute) attribute).getJavaMember();\n        Class embeddedClass = ((AbstractAttribute) attribute).getBindableJavaType();\n\n        if (List.class.isAssignableFrom(((Field) attribute.getJavaMember()).getType()))\n        {\n            ListType listType = null;\n            try\n            {\n                listType = ListType.getInstance(new TypeParser(cqlColumnMetadata.substring(\n                        cqlColumnMetadata.indexOf(\"(\"), cqlColumnMetadata.length())));\n            }\n            catch (ConfigurationException | SyntaxException e)\n            {\n                log.error(e.getMessage());\n                throw new KunderaException(\"Error while getting instance of ListType \" + e);\n            }\n            return setElementCollectionList(listType, ByteBuffer.wrap((byte[]) thriftColumnValue), entity, field,\n                    metaModel, embeddedClass, true);\n\n        }\n        else if (Set.class.isAssignableFrom(((Field) attribute.getJavaMember()).getType()))\n        {\n            SetType setType = null;\n            try\n            {\n                setType = SetType.getInstance(new TypeParser(cqlColumnMetadata.substring(\n                        cqlColumnMetadata.indexOf(\"(\"), cqlColumnMetadata.length())));\n            }\n            catch (ConfigurationException | SyntaxException e)\n            {\n                log.error(e.getMessage());\n                throw new KunderaException(\"Error while getting instance of SetType \" + e);\n            }\n            return setElementCollectionSet(setType, ByteBuffer.wrap((byte[]) thriftColumnValue), entity, field,\n                    metaModel, embeddedClass, true);\n\n        }\n        else if (Map.class.isAssignableFrom(((Field) attribute.getJavaMember()).getType()))\n        {\n            MapType mapType = null;\n            try\n            {\n                mapType = MapType.getInstance(new TypeParser(cqlColumnMetadata.substring(\n                        cqlColumnMetadata.indexOf(\"(\"), cqlColumnMetadata.length())));\n            }\n            catch (ConfigurationException | SyntaxException e)\n            {\n                log.error(e.getMessage());\n                throw new KunderaException(\"Error while getting instance of MapType \" + e);\n            }\n            return setElementCollectionMap(mapType, ByteBuffer.wrap((byte[]) thriftColumnValue), entity, field,\n                    metaModel, embeddedClass, true);\n        }\n\n        return entity;\n\n    }\n\n    /**\n     * Sets the element collection map.\n     * \n     * @param mapType\n     *            the cql column metadata\n     * @param thriftColumnValue\n     *            the thrift column value\n     * @param entity\n     *            the entity\n     * @param field\n     *            the field\n     * @param metaModel\n     *            the meta model\n     * @param embeddedClass\n     *            the embedded class\n     * @param useNativeProtocol2\n     *            the use native protocol2\n     * @return the object\n     */\n    private Object setElementCollectionMap(MapType mapType, ByteBuffer thriftColumnValue, Object entity, Field field,\n            MetamodelImpl metaModel, Class embeddedClass, boolean useNativeProtocol2)\n    {\n\n        Map result = new HashMap();\n        MapSerializer mapSerializer = mapType.getSerializer();\n        Map outputCollection = new HashMap();\n        if (useNativeProtocol2)\n        {\n            outputCollection.putAll(mapSerializer.deserializeForNativeProtocol(thriftColumnValue, ProtocolVersion.V2));\n        }\n        else\n        {\n            outputCollection.putAll((Map) mapSerializer.deserialize(thriftColumnValue));\n        }\n\n        UserType usertype = (UserType) mapType.getValuesType();\n\n        for (Object key : outputCollection.keySet())\n        {\n            Object embeddedObject = KunderaCoreUtils.createNewInstance(embeddedClass);\n            Object value = populateEmbeddedRecursive((ByteBuffer) outputCollection.get(key), usertype.allTypes(),\n                    usertype.fieldNames(), embeddedObject, metaModel);\n            result.put(key, value);\n        }\n        PropertyAccessorHelper.set(entity, field, result);\n        return entity;\n    }\n\n    /**\n     * Sets the element collection set.\n     * \n     * @param setType\n     *            the cql column metadata\n     * @param thriftColumnValue\n     *            the thrift column value\n     * @param entity\n     *            the entity\n     * @param field\n     *            the field\n     * @param metaModel\n     *            the meta model\n     * @param embeddedClass\n     *            the embedded class\n     * @param useNativeProtocol2\n     *            the use native protocol2\n     * @return the object\n     */\n    private Object setElementCollectionSet(SetType setType, ByteBuffer thriftColumnValue, Object entity, Field field,\n            MetamodelImpl metaModel, Class embeddedClass, boolean useNativeProtocol2)\n    {\n\n        SetSerializer setSerializer = setType.getSerializer();\n        Collection outputCollection = new ArrayList();\n        if (useNativeProtocol2)\n        {\n            outputCollection.addAll((Collection) setSerializer.deserializeForNativeProtocol(thriftColumnValue, ProtocolVersion.V2));\n        }\n        else\n        {\n            outputCollection.addAll((Collection) setSerializer.deserialize(thriftColumnValue));\n        }\n\n        UserType usertype = (UserType) setType.getElementsType();\n        Collection result = new HashSet();\n        Iterator collectionItems = outputCollection.iterator();\n        while (collectionItems.hasNext())\n        {\n            Object embeddedObject = KunderaCoreUtils.createNewInstance(embeddedClass);\n            Object value = populateEmbeddedRecursive((ByteBuffer) collectionItems.next(), usertype.allTypes(),\n                    usertype.fieldNames(), embeddedObject, metaModel);\n            result.add(value);\n        }\n        PropertyAccessorHelper.set(entity, field, result);\n        return entity;\n    }\n\n    /**\n     * Sets the element collection list.\n     * \n     * @param listType\n     *            the cql column metadata\n     * @param thriftColumnValue\n     *            the thrift column value\n     * @param entity\n     *            the entity\n     * @param field\n     *            the field\n     * @param metaModel\n     *            the meta model\n     * @param embeddedClass\n     *            the embedded class\n     * @param useNativeProtocol2\n     *            the use native protocol2\n     * @return the object\n     */\n    private Object setElementCollectionList(ListType listType, ByteBuffer thriftColumnValue, Object entity,\n            Field field, MetamodelImpl metaModel, Class embeddedClass, boolean useNativeProtocol2)\n    {\n\n        ListSerializer listSerializer = listType.getSerializer();\n        Collection outputCollection = new ArrayList();\n        if (useNativeProtocol2)\n        {\n            outputCollection.addAll((Collection) listSerializer.deserializeForNativeProtocol(thriftColumnValue, ProtocolVersion.V2));\n        }\n        else\n        {\n            outputCollection.addAll((Collection) listSerializer.deserialize(thriftColumnValue));\n        }\n\n        UserType usertype = (UserType) listType.getElementsType();\n        Collection result = new ArrayList();\n        Iterator collectionItems = outputCollection.iterator();\n        while (collectionItems.hasNext())\n        {\n            Object embeddedObject = KunderaCoreUtils.createNewInstance(embeddedClass);\n            Object value = populateEmbeddedRecursive((ByteBuffer) collectionItems.next(), usertype.allTypes(),\n                    usertype.fieldNames(), embeddedObject, metaModel);\n            result.add(value);\n        }\n        PropertyAccessorHelper.set(entity, field, result);\n        return entity;\n    }\n\n    /**\n     * Gets the field value via cql.\n     * \n     * @param thriftColumnValue\n     *            the thrift column value\n     * @param attribute\n     *            the attribute\n     * @return the field value via cql\n     */\n    private Object getFieldValueViaCQL(Object thriftColumnValue, Attribute attribute)\n    {\n        PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor((Field) attribute.getJavaMember());\n        Object objValue;\n        try\n        {\n            if (CassandraDataTranslator.isCassandraDataTypeClass(((AbstractAttribute) attribute).getBindableJavaType()))\n            {\n                objValue = CassandraDataTranslator.decompose(((AbstractAttribute) attribute).getBindableJavaType(),\n                        thriftColumnValue, true);\n                return objValue;\n            }\n            else\n            {\n                objValue = accessor.fromBytes(((AbstractAttribute) attribute).getBindableJavaType(),\n                        (byte[]) thriftColumnValue);\n                return objValue;\n            }\n        }\n        catch (PropertyAccessException pae)\n        {\n            log.warn(\"Error while setting field{} value via CQL, Caused by: .\", attribute.getName(), pae);\n        }\n        return null;\n    }\n\n    /**\n     * On column or super column thrift row.\n     * \n     * @param m\n     *            the m\n     * @param e\n     *            the e\n     * @param id\n     *            the id\n     * @param timestamp\n     *            the timestamp2\n     * @param columnTTLs\n     *            TODO\n     * @return the collection\n     */\n\n    private Collection<ThriftRow> onColumnOrSuperColumnThriftRow(EntityMetadata m, Object e, Object id, long timestamp,\n            Object columnTTLs)\n    {\n        // Iterate through Super columns\n\n        Map<String, ThriftRow> thriftRows = new HashMap<String, ThriftRow>();\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n        Set<Attribute> attributes = entityType.getAttributes();\n        for (Attribute attribute : attributes)\n        {\n            String tableName = ((AbstractAttribute) attribute).getTableName() != null ? ((AbstractAttribute) attribute)\n                    .getTableName() : m.getTableName();\n\n            ThriftRow tr = getThriftRow(id, tableName, thriftRows);\n            if (!attribute.getName().equals(m.getIdAttribute().getName()) && !attribute.isAssociation())\n            {\n                Field field = (Field) ((Attribute) attribute).getJavaMember();\n                byte[] name = ByteBufferUtil.bytes(((AbstractAttribute) attribute).getJPAColumnName()).array();\n\n                // if attribute is embeddable.\n                if (metaModel.isEmbeddable(attribute.isCollection() ? ((PluralAttribute) attribute)\n                        .getBindableJavaType() : attribute.getJavaType()))\n                {\n                    Map<String, Object> thriftSuperColumns = onEmbeddable(timestamp, tr, m, e, id, attribute);\n                    if (thriftSuperColumns != null)\n                    {\n                        for (String columnFamilyName : thriftSuperColumns.keySet())\n                        {\n                            ThriftRow thriftRow = getThriftRow(id, columnFamilyName, thriftRows);\n                            if (m.isCounterColumnType())\n                            {\n                                thriftRow.addCounterSuperColumn((CounterSuperColumn) thriftSuperColumns\n                                        .get(columnFamilyName));\n                            }\n                            else\n                            {\n                                thriftRow.addSuperColumn((SuperColumn) thriftSuperColumns.get(columnFamilyName));\n                            }\n                        }\n                    }\n                }\n                else\n                {\n                    Object value = getColumnValue(m, e, attribute);\n\n                    if (m.getType().equals(Type.SUPER_COLUMN_FAMILY))\n                    {\n                        prepareSuperColumn(tr, m, value, name, timestamp);\n                    }\n                    else\n                    {\n                        int ttl = getTTLForColumn(columnTTLs, attribute);\n                        prepareColumn(tr, m, value, name, timestamp, ttl);\n                    }\n                }\n            }\n        }\n\n        // Add discriminator column.\n        onDiscriminatorColumn(thriftRows.get(m.getTableName()), timestamp, entityType);\n        return thriftRows.values();\n    }\n\n    /**\n     * On discriminator column.\n     * \n     * @param tr\n     *            the tr\n     * @param timestamp\n     *            the timestamp\n     * @param entityType\n     *            the entity type\n     */\n    private void onDiscriminatorColumn(ThriftRow tr, long timestamp, EntityType entityType)\n    {\n        String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n        String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();\n\n        // No need to check for empty or blank, as considering it as valid name\n        // for nosql!\n        if (discrColumn != null && discrValue != null)\n        {\n            Column column = prepareColumn(PropertyAccessorHelper.getBytes(discrValue),\n                    PropertyAccessorHelper.getBytes(discrColumn), timestamp, 0);\n            tr.addColumn(column);\n        }\n    }\n\n    /**\n     * Determined TTL for a given column.\n     * \n     * @param columnTTLs\n     *            the column tt ls\n     * @param attribute\n     *            the attribute\n     * @return the TTL for column\n     */\n    private int getTTLForColumn(Object columnTTLs, Attribute attribute)\n    {\n        Integer ttl = null;\n        if (columnTTLs != null)\n        {\n            if (columnTTLs instanceof Map)\n            {\n                ttl = (Integer) (columnTTLs == null ? 0 : ((Map) columnTTLs).get(((AbstractAttribute) attribute)\n                        .getJPAColumnName()));\n            }\n            else if (columnTTLs instanceof Integer)\n            {\n                ttl = (Integer) columnTTLs;\n            }\n        }\n        return ttl == null ? 0 : ttl;\n    }\n\n    /**\n     * Gets the column value.\n     * \n     * @param m\n     *            the m\n     * @param e\n     *            the e\n     * @param attribute\n     *            the attribute\n     * @return the column value\n     */\n    private Object getColumnValue(EntityMetadata m, Object e, Attribute attribute)\n    {\n        Field field = (Field) ((Attribute) attribute).getJavaMember();\n        Object value;\n        if (!m.isCounterColumnType())\n        {\n            value = getThriftColumnValue(e, attribute);\n        }\n        else\n        {\n            value = PropertyAccessorHelper.getString(e, field);\n        }\n        return value;\n    }\n\n    /**\n     * Gets the thrift column value.\n     * \n     * @param e\n     *            the e\n     * @param attribute\n     *            the attribute\n     * @return the thrift column value\n     */\n    protected byte[] getThriftColumnValue(Object e, Attribute attribute)\n    {\n        byte[] value = null;\n        Field field = (Field) ((Attribute) attribute).getJavaMember();\n        try\n        {\n            if (attribute != null && field.get(e) != null)\n            {\n\n                if (CassandraDataTranslator.isCassandraDataTypeClass(((AbstractAttribute) attribute)\n                        .getBindableJavaType()))\n                {\n                    value = CassandraDataTranslator.compose(((AbstractAttribute) attribute).getBindableJavaType(),\n                            field.get(e), false);\n                }\n                else\n                {\n                    value = PropertyAccessorHelper.get(e, field);\n                }\n            }\n        }\n        catch (IllegalArgumentException iae)\n        {\n            log.error(\"Error while persisting data, Caused by: .\", iae);\n            throw new IllegalArgumentException(iae);\n        }\n        catch (IllegalAccessException iace)\n        {\n            log.error(\"Error while persisting data, Caused by: .\", iace);\n        }\n        return value;\n    }\n\n    /**\n     * Prepare column.\n     * \n     * @param tr\n     *            the tr\n     * @param m\n     *            the m\n     * @param value\n     *            the value\n     * @param name\n     *            the name\n     * @param timestamp\n     *            the timestamp\n     * @param ttl\n     *            TODO\n     */\n    private void prepareColumn(ThriftRow tr, EntityMetadata m, Object value, byte[] name, long timestamp, int ttl)\n    {\n        if (value != null)\n        {\n            if (m.isCounterColumnType())\n            {\n                CounterColumn counterColumn = prepareCounterColumn((String) value, name);\n                tr.addCounterColumn(counterColumn);\n            }\n            else\n            {\n                Column column = prepareColumn((byte[]) value, name, timestamp, ttl);\n                tr.addColumn(column);\n            }\n        }\n    }\n\n    /**\n     * Prepare super column.\n     * \n     * @param tr\n     *            the tr\n     * @param m\n     *            the m\n     * @param value\n     *            the value\n     * @param name\n     *            the name\n     * @param timestamp\n     *            the timestamp\n     */\n    private void prepareSuperColumn(ThriftRow tr, EntityMetadata m, Object value, byte[] name, long timestamp)\n    {\n        if (value != null)\n        {\n            if (m.isCounterColumnType())\n            {\n                CounterSuperColumn counterSuper = new CounterSuperColumn();\n                counterSuper.setName(name);\n                CounterColumn counterColumn = prepareCounterColumn((String) value, name);\n                List<CounterColumn> subCounterColumn = new ArrayList<CounterColumn>();\n                subCounterColumn.add(counterColumn);\n                counterSuper.setColumns(subCounterColumn);\n                tr.addCounterSuperColumn(counterSuper);\n            }\n            else\n            {\n                SuperColumn superCol = new SuperColumn();\n                superCol.setName(name);\n                Column column = prepareColumn((byte[]) value, name, timestamp, 0);\n                List<Column> subColumn = new ArrayList<Column>();\n                subColumn.add(column);\n                superCol.setColumns(subColumn);\n                tr.addSuperColumn(superCol);\n            }\n        }\n    }\n\n    /**\n     * Prepare column.\n     * \n     * @param value\n     *            the value\n     * @param name\n     *            the name\n     * @param timestamp\n     *            the timestamp\n     * @param ttl\n     *            TODO\n     * @return the column\n     */\n    private Column prepareColumn(byte[] value, byte[] name, long timestamp, int ttl)\n    {\n        Column column = new Column();\n        column.setName(name);\n        column.setValue(value);\n        column.setTimestamp(timestamp);\n        if (ttl != 0)\n        {\n            column.setTtl(ttl);\n        }\n        return column;\n    }\n\n    /**\n     * Prepare counter column.\n     * \n     * @param value\n     *            the value\n     * @param name\n     *            the name\n     * @return the counter column\n     */\n    private CounterColumn prepareCounterColumn(String value, byte[] name)\n    {\n        CounterColumn counterColumn = new CounterColumn();\n        counterColumn.setName(name);\n        LongAccessor accessor = new LongAccessor();\n        counterColumn.setValue(accessor.fromString(LongAccessor.class, value));\n        return counterColumn;\n    }\n\n    /**\n     * On embeddable.\n     * \n     * @param timestamp2\n     *            the timestamp2\n     * @param tr\n     *            the tr\n     * @param m\n     *            the m\n     * @param e\n     *            the e\n     * @param id\n     *            the id\n     * @param embeddableAttrib\n     *            the embeddable attrib\n     * @return the map\n     */\n    private Map<String, Object> onEmbeddable(long timestamp2, ThriftRow tr, EntityMetadata m, Object e, Object id,\n            Attribute embeddableAttrib)\n    {\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n\n        EmbeddableType superColumn = metaModel.embeddable(((AbstractAttribute) embeddableAttrib).getBindableJavaType());\n\n        Field superColumnField = (Field) embeddableAttrib.getJavaMember();\n        Object superColumnObject = PropertyAccessorHelper.getObject(e, superColumnField);\n\n        // If Embedded object is a Collection, there will be variable number\n        // of super columns one for each object in collection.\n        // Key for each super column will be of the format \"<Embedded object\n        // field name>#<Unique sequence number>\n\n        // On the other hand, if embedded object is not a Collection, it\n        // would simply be embedded as ONE super column.\n        String superColumnName = null;\n        if (superColumnObject != null && superColumnObject instanceof Collection)\n        {\n\n            ElementCollectionCacheManager ecCacheHandler = ElementCollectionCacheManager.getInstance();\n\n            // Check whether it's first time insert or updation\n            if (ecCacheHandler.isCacheEmpty())\n            { // First time insert\n                int count = 0;\n                for (Object obj : (Collection) superColumnObject)\n                {\n                    superColumnName = ((AbstractAttribute) embeddableAttrib).getJPAColumnName()\n                            + Constants.EMBEDDED_COLUMN_NAME_DELIMITER + count;\n\n                    if (m.isCounterColumnType())\n                    {\n                        CounterSuperColumn thriftSuperColumn = (CounterSuperColumn) buildThriftCounterSuperColumn(\n                                m.getTableName(), superColumnName, superColumn, obj).get(m.getTableName());\n                        tr.addCounterSuperColumn(thriftSuperColumn);\n                    }\n                    else\n                    {\n                        SuperColumn thriftSuperColumn = (SuperColumn) buildThriftSuperColumn(m.getTableName(),\n                                superColumnName, timestamp2, superColumn, obj).get(m.getTableName());\n                        tr.addSuperColumn(thriftSuperColumn);\n                    }\n                    ecCacheHandler.addElementCollectionCacheMapping(id, obj, superColumnName);\n                    count++;\n                }\n            }\n            else\n            {\n                // Updation, Check whether this object is already in cache,\n                // which means we already have a super column\n                // Otherwise we need to generate a fresh embedded column\n                // name\n                int lastEmbeddedObjectCount = ecCacheHandler.getLastElementCollectionObjectCount(id);\n                for (Object obj : (Collection) superColumnObject)\n                {\n                    superColumnName = ecCacheHandler.getElementCollectionObjectName(id, obj);\n                    if (superColumnName == null)\n                    { // Fresh row\n                        superColumnName = ((AbstractAttribute) embeddableAttrib).getJPAColumnName()\n                                + Constants.EMBEDDED_COLUMN_NAME_DELIMITER + (++lastEmbeddedObjectCount);\n                    }\n                    Map<String, Object> thriftSuperColumn = buildThriftSuperColumn(timestamp2, m, id, superColumn,\n                            superColumnName, obj);\n                    if (m.isCounterColumnType())\n                    {\n                        tr.addCounterSuperColumn((CounterSuperColumn) thriftSuperColumn.get(m.getTableName()));\n                    }\n                    else\n                    {\n                        tr.addSuperColumn((SuperColumn) thriftSuperColumn.get(m.getTableName()));\n                    }\n                    ecCacheHandler.addElementCollectionCacheMapping(id, obj, superColumnName);\n                }\n            }\n        }\n        else if (superColumnObject != null)\n        {\n            superColumnName = ((AbstractAttribute) embeddableAttrib).getJPAColumnName();\n            return buildThriftSuperColumn(timestamp2, m, id, superColumn, superColumnName, superColumnObject);\n        }\n        return null;\n    }\n\n    /**\n     * Builds the thrift super column.\n     * \n     * @param timestamp2\n     *            the timestamp2\n     * @param m\n     *            the m\n     * @param id\n     *            the id\n     * @param superColumn\n     *            the super column\n     * @param superColumnName\n     *            the super column name\n     * @param obj\n     *            the obj\n     * @return the map\n     */\n    private Map<String, Object> buildThriftSuperColumn(long timestamp2, EntityMetadata m, Object id,\n            EmbeddableType superColumn, String superColumnName, Object obj)\n    {\n        Map<String, Object> thriftSuperColumns = null;\n        if (m.isCounterColumnType())\n        {\n            thriftSuperColumns = buildThriftCounterSuperColumn(m.getTableName(), superColumnName, superColumn, obj);\n        }\n        else\n        {\n            thriftSuperColumns = buildThriftSuperColumn(m.getTableName(), superColumnName, timestamp2, superColumn, obj);\n        }\n        return thriftSuperColumns;\n    }\n\n    /**\n     * Builds the thrift counter super column.\n     * \n     * @param tableName\n     *            the table name\n     * @param superColumnName\n     *            the super column name\n     * @param superColumn\n     *            the super column\n     * @param counterSuperColumnObject\n     *            the counter super column object\n     * @return the counter super column\n     */\n    private Map<String, Object> buildThriftCounterSuperColumn(String tableName, String superColumnName,\n            EmbeddableType superColumn, Object counterSuperColumnObject)\n    {\n\n        Map<String, Object> thriftCounterSuperColumns = new HashMap<String, Object>();\n\n        Iterator<Attribute> iter = superColumn.getAttributes().iterator();\n\n        List<CounterColumn> thriftColumns = new ArrayList<CounterColumn>();\n\n        while (iter.hasNext())\n        {\n            Attribute column = iter.next();\n            Field field = (Field) column.getJavaMember();\n            String name = ((AbstractAttribute) column).getJPAColumnName();\n            String value = null;\n            try\n            {\n                value = PropertyAccessorHelper.getString(counterSuperColumnObject, field);\n            }\n            catch (PropertyAccessException exp)\n            {\n                // This is an entity column to be persisted in a super column\n                // family. It will be stored as a super column that would\n                // have just one column with the same name\n                if (log.isInfoEnabled())\n                {\n                    log.info(exp.getMessage()\n                            + \". Possible case of entity column in a super column family. Will be treated as a super column.\");\n                }\n\n                value = counterSuperColumnObject.toString();\n            }\n            if (null != value)\n            {\n                try\n                {\n                    CounterColumn thriftColumn = new CounterColumn();\n                    thriftColumn.setName(PropertyAccessorFactory.STRING.toBytes(name));\n                    thriftColumn.setValue(Long.parseLong(value));\n                    thriftColumns.add(thriftColumn);\n\n                    tableName = ((AbstractAttribute) column).getTableName() != null ? ((AbstractAttribute) column)\n                            .getTableName() : tableName;\n                    CounterSuperColumn thriftSuperColumn = (CounterSuperColumn) thriftCounterSuperColumns\n                            .get(tableName);\n                    if (thriftSuperColumn == null)\n                    {\n                        thriftSuperColumn = new CounterSuperColumn();\n                        thriftSuperColumn.setName(PropertyAccessorFactory.STRING.toBytes(superColumnName));\n                        thriftCounterSuperColumns.put(tableName, thriftSuperColumn);\n                    }\n                    thriftSuperColumn.addToColumns(thriftColumn);\n                }\n                catch (NumberFormatException nfe)\n                {\n                    log.error(\"For counter column arguments should be numeric type, Caused by: .\", nfe);\n                    throw new KunderaException(nfe);\n                }\n            }\n        }\n        return thriftCounterSuperColumns;\n    }\n\n    /**\n     * Builds the thrift super column.\n     * \n     * @param tableName\n     *            the table name\n     * @param superColumnName\n     *            the super column name\n     * @param timestamp\n     *            the timestamp\n     * @param superColumn\n     *            the super column\n     * @param superColumnObject\n     *            the super column object\n     * @return the super column\n     * @throws PropertyAccessException\n     *             the property access exception\n     */\n    private Map<String, Object> buildThriftSuperColumn(String tableName, String superColumnName, long timestamp,\n            EmbeddableType superColumn, Object superColumnObject) throws PropertyAccessException\n    {\n        Map<String, Object> tableToSuperColumns = new HashMap<String, Object>();\n\n        List<Column> thriftColumns = new ArrayList<Column>();\n\n        Iterator<Attribute> iter = superColumn.getAttributes().iterator();\n\n        while (iter.hasNext())\n        {\n            AbstractAttribute column = (AbstractAttribute) iter.next();\n\n            Field field = (Field) column.getJavaMember();\n            String name = column.getJPAColumnName();\n            byte[] value = null;\n            try\n            {\n                value = PropertyAccessorHelper.get(superColumnObject, field);\n            }\n            catch (PropertyAccessException exp)\n            {\n                // This is an entity column to be persisted in a super column\n                // family. It will be stored as a super column that would\n                // have just one column with the same name\n                if (log.isInfoEnabled())\n                {\n                    log.info(exp.getMessage()\n                            + \". Possible case of entity column in a super column family. Will be treated as a super column.\");\n                }\n                value = superColumnObject.toString().getBytes();\n            }\n            if (null != value)\n            {\n                Column thriftColumn = new Column();\n                thriftColumn.setName(PropertyAccessorFactory.STRING.toBytes(name));\n                thriftColumn.setValue(value);\n                thriftColumn.setTimestamp(timestamp);\n                thriftColumns.add(thriftColumn);\n                String columnFamilyName = ((AbstractAttribute) column).getTableName() != null ? ((AbstractAttribute) column)\n                        .getTableName() : tableName;\n                SuperColumn thriftSuperColumn = (SuperColumn) tableToSuperColumns.get(tableName);\n                if (thriftSuperColumn == null)\n                {\n                    thriftSuperColumn = new SuperColumn();\n                    thriftSuperColumn.setName(PropertyAccessorFactory.STRING.toBytes(superColumnName));\n                    tableToSuperColumns.put(columnFamilyName, thriftSuperColumn);\n                }\n                thriftSuperColumn.addToColumns(thriftColumn);\n            }\n        }\n        return tableToSuperColumns;\n    }\n\n    /**\n     * Populate composite id.\n     * \n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param thriftColumnName\n     *            the thrift column name\n     * @param thriftColumnValue\n     *            the thrift column value\n     * @param metaModel\n     *            the meta model\n     * @param attribute\n     *            the attribute\n     * @param entityClazz\n     *            the entity clazz\n     * @return the object\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    private Object populateCompositeId(EntityMetadata m, Object entity, String thriftColumnName,\n            Object thriftColumnValue, MetamodelImpl metaModel, Attribute attribute, Class entityClazz)\n            throws InstantiationException, IllegalAccessException\n    {\n        Class javaType = ((AbstractAttribute) attribute).getBindableJavaType();\n\n        if (metaModel.isEmbeddable(javaType))\n        {\n            EmbeddableType compoundKey = metaModel.embeddable(javaType);\n            Object compoundKeyObject = null;\n            try\n            {\n                Set<Attribute> attributes = compoundKey.getAttributes();\n                entity = KunderaCoreUtils.initialize(entityClazz, entity);\n\n                for (Attribute compoundAttribute : attributes)\n                {\n                    compoundKeyObject = compoundKeyObject == null ? getCompoundKey(attribute, entity)\n                            : compoundKeyObject;\n\n                    if (metaModel.isEmbeddable(((AbstractAttribute) compoundAttribute).getBindableJavaType()))\n                    {\n                        Object compoundObject = populateCompositeId(m, compoundKeyObject, thriftColumnName,\n                                thriftColumnValue, metaModel, compoundAttribute, javaType);\n                        PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), compoundObject);\n                    }\n                    else if (((AbstractAttribute) compoundAttribute).getJPAColumnName().equals(thriftColumnName))\n                    {\n                        setFieldValueViaCQL(compoundKeyObject, thriftColumnValue, compoundAttribute);\n                        PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), compoundKeyObject);\n                        break;\n                    }\n                }\n            }\n            catch (IllegalArgumentException iaex)\n            {\n                // ignore as it might not represented within entity.\n                // No need for any logger message\n            }\n            catch (Exception e)\n            {\n                log.error(\"Error while retrieving data, Caused by: .\", e);\n                throw new PersistenceException(e);\n            }\n        }\n        return entity;\n    }\n\n    /**\n     * Gets the compound key.\n     * \n     * @param attribute\n     *            the attribute\n     * @param entity\n     *            the entity\n     * @return the compound key\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    private Object getCompoundKey(Attribute attribute, Object entity) throws InstantiationException,\n            IllegalAccessException\n    {\n        Object compoundKeyObject = null;\n        if (entity != null)\n        {\n            compoundKeyObject = PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());\n            if (compoundKeyObject == null)\n            {\n                compoundKeyObject = ((AbstractAttribute) attribute).getBindableJavaType().newInstance();\n            }\n        }\n        return compoundKeyObject;\n    }\n\n    /**\n     * Populates collection field(s) into entity.\n     * \n     * @param entity\n     *            the entity\n     * @param thriftColumnValue\n     *            the thrift column value\n     * @param attribute\n     *            the attribute\n     */\n    private void setCollectionValue(Object entity, Object thriftColumnValue, Attribute attribute)\n    {\n        try\n        {\n            ByteBuffer valueByteBuffer = ByteBuffer.wrap((byte[]) thriftColumnValue);\n            if (Collection.class.isAssignableFrom(((Field) attribute.getJavaMember()).getType()))\n            {\n\n                Class<?> genericClass = PropertyAccessorHelper.getGenericClass((Field) attribute.getJavaMember());\n\n                PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), CassandraDataTranslator\n                        .decompose(((Field) attribute.getJavaMember()).getType(), valueByteBuffer, genericClass, true));\n            }\n\n            else if (((Field) attribute.getJavaMember()).getType().isAssignableFrom(Map.class))\n            {\n\n                List<Class<?>> mapGenericClasses = PropertyAccessorHelper.getGenericClasses((Field) attribute\n                        .getJavaMember());\n\n                PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), CassandraDataTranslator\n                        .decompose(((Field) attribute.getJavaMember()).getType(), valueByteBuffer, mapGenericClasses,\n                                true));\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while setting field{} value via CQL, Caused by: .\", attribute.getName(), e);\n            throw new PersistenceException(e);\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/index/CassandraIndexHelper.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.index;\n\nimport org.apache.cassandra.thrift.IndexType;\n\nimport com.impetus.client.cassandra.config.CassandraPropertyReader;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\n\n/**\n * Provides functionalities related to indexing in cassandra\n * \n * @author amresh.singh\n */\npublic class CassandraIndexHelper\n{\n    /**\n     * Generates inverted index table name for a given table\n     * \n     * @param tableName\n     * @return\n     */\n    public static String getInvertedIndexTableName(String tableName)\n    {\n        return tableName + Constants.INDEX_TABLE_SUFFIX;\n    }\n\n    /**\n     * Checks whether Inverted indexing is applicable for a given entity whose\n     * metadata is passed as parameter\n     * \n     * @param m\n     * @return\n     */\n    public static boolean isInvertedIndexingApplicable(EntityMetadata m, boolean useSecondryIndex)\n    {\n        boolean invertedIndexingApplicable = useSecondryIndex\n                && CassandraPropertyReader.csmd.isInvertedIndexingEnabled(m.getSchema())\n                && m.getType().isSuperColumnFamilyMetadata() && !m.isCounterColumnType();\n\n        return invertedIndexingApplicable;\n    }\n\n    /**\n     * @param indexType\n     * @return\n     */\n    public static IndexType getIndexType(String indexType)\n    {\n        if (indexType != null)\n        {\n            if (indexType.equals(IndexType.KEYS.name()))\n            {\n                return IndexType.KEYS;\n            }\n            else if (indexType.equals(IndexType.CUSTOM.name()))\n            {\n                return IndexType.CUSTOM;\n            }\n        }\n        return IndexType.KEYS;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/index/InvertedIndexHandler.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.index;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.IndexClause;\n\nimport com.impetus.client.cassandra.datahandler.CassandraDataHandler;\nimport com.impetus.kundera.db.SearchResult;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * This interface defines methods for operation on inverted indexes\n * \n * @author amresh.singh\n */\npublic interface InvertedIndexHandler\n{\n\n    /**\n     * Writes a record into inverted index table.\n     * \n     * @param node\n     * @param entityMetadata\n     * @param persistenceUnit\n     * @param consistencyLevel\n     * @param cdHandler\n     */\n    void write(Node node, EntityMetadata entityMetadata, String persistenceUnit, ConsistencyLevel consistencyLevel,\n            CassandraDataHandler cdHandler);\n\n    /**\n     * Searches records from Inverted index table.\n     * \n     * @param m\n     * @param filterClauseQueue\n     * @param persistenceUnit\n     * @param consistencyLevel\n     * @return\n     */\n    List<SearchResult> search(EntityMetadata m, String persistenceUnit, ConsistencyLevel consistencyLevel,\n            Map<Boolean, List<IndexClause>> indexClauseMap);\n\n    /**\n     * Deletes a record from inverted index table.\n     * \n     * @param entity\n     * @param metadata\n     * @param consistencyLevel\n     */\n    void delete(Object entity, EntityMetadata metadata, ConsistencyLevel consistencyLevel, final KunderaMetadata kunderaMetadata);\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/index/InvertedIndexHandlerBase.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.index;\n\nimport java.lang.reflect.Field;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.CharacterCodingException;\nimport java.nio.charset.Charset;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.cassandra.db.marshal.UTF8Type;\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.IndexClause;\nimport org.apache.cassandra.thrift.IndexExpression;\nimport org.apache.cassandra.thrift.IndexOperator;\nimport org.apache.cassandra.thrift.SuperColumn;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.db.SearchResult;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.DefaultSingularAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.QueryHandlerException;\nimport com.impetus.kundera.utils.TimestampGenerator;\n\n/**\n * Base class for\n * \n * @author amresh.singh\n */\npublic abstract class InvertedIndexHandlerBase\n{\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(InvertedIndexHandlerBase.class);\n\n    protected boolean useSecondryIndex;\n\n    /** For time stamp generation. */\n    protected final TimestampGenerator generator;\n\n    public InvertedIndexHandlerBase(final TimestampGenerator generator)\n    {\n        this.generator = generator;\n    }\n\n    public List<SearchResult> search(EntityMetadata m, String persistenceUnit, ConsistencyLevel consistencyLevel,\n            Map<Boolean, List<IndexClause>> indexClauseMap)\n    {\n        String columnFamilyName = m.getTableName() + Constants.INDEX_TABLE_SUFFIX;\n\n        List<SearchResult> searchResults = new ArrayList<SearchResult>();\n\n        boolean isRowKeyQuery = indexClauseMap.keySet().iterator().next();\n\n        for (IndexClause o : indexClauseMap.get(isRowKeyQuery))\n        {\n            for (IndexExpression expression : o.getExpressions())\n            {\n                searchAndAddToResults(m, persistenceUnit, consistencyLevel, columnFamilyName, searchResults,\n                        expression, isRowKeyQuery);\n            }\n\n        }\n        return searchResults;\n    }\n\n    /**\n     * Searches into inverted index based on <code>expression</code> and adds\n     * search result to <code>searchResults</code>\n     */\n    private void searchAndAddToResults(EntityMetadata m, String persistenceUnit, ConsistencyLevel consistencyLevel,\n            String columnFamilyName, List<SearchResult> searchResults, IndexExpression expression, boolean isRowKeyQuery)\n    {\n        SearchResult searchResult = new SearchResult();\n\n        byte[] superColumnName = expression.getValue();\n        String superColumnNameStr = null;\n        String rowKey = null;\n        try\n        {\n            rowKey = ByteBufferUtil.string(ByteBuffer.wrap(expression.getColumn_name()),\n                    Charset.forName(Constants.CHARSET_UTF8));\n            superColumnNameStr = new String(expression.getValue(), Charset.forName(Constants.CHARSET_UTF8));\n        }\n        catch (CharacterCodingException e)\n        {\n            log.error(\"Error while retrieving records {}, Caused by:\", e);\n            throw new PersistenceException(e);\n        }\n        Object pk = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), superColumnName);\n        IndexOperator condition = expression.getOp();\n\n        if (log.isInfoEnabled())\n        {\n            log.info(\"RowKey: {} ; Super column Name: {} on condition.\", rowKey, superColumnNameStr, condition);\n        }\n\n        // TODO: Second check unnecessary but unavoidable as filter clause\n        // property is incorrectly passed as column name\n\n        // Search based on Primary key\n        if (isRowKeyQuery\n                && (rowKey.equals(m.getIdAttribute().getName()) || rowKey.equals(((DefaultSingularAttribute) m\n                        .getIdAttribute()).getJPAColumnName())))\n        {\n            if (searchResults.isEmpty())\n            {\n                searchResult.setPrimaryKey(pk);\n                searchResults.add(searchResult);\n            }\n            else\n            {\n                SearchResult existing = searchResults.get(0);\n                if (existing.getPrimaryKey() != null && existing.getPrimaryKey().equals(superColumnNameStr))\n                {\n                    searchResults.add(searchResult);\n                }\n                else\n                {\n                    searchResults.remove(0);\n                }\n            }\n        }\n        else\n        {\n            // Search results in the form of thrift super columns\n            List<SuperColumn> thriftSuperColumns = new ArrayList<SuperColumn>();\n\n            switch (condition)\n            {\n            // EQUAL Operator\n            case EQ:\n                SuperColumn thriftSuperColumn = getSuperColumnForRow(consistencyLevel, columnFamilyName, rowKey,\n                        superColumnName, persistenceUnit);\n\n                if (thriftSuperColumn != null)\n                    thriftSuperColumns.add(thriftSuperColumn);\n                break;\n\n            // LIKE operation not available\n            // Greater than operator\n            case GT:\n                searchSuperColumnsInRange(columnFamilyName, consistencyLevel, persistenceUnit, rowKey, superColumnName,\n                        thriftSuperColumns, superColumnName, new byte[0]);\n                break;\n            // Less than Operator\n            case LT:\n                searchSuperColumnsInRange(columnFamilyName, consistencyLevel, persistenceUnit, rowKey, superColumnName,\n                        thriftSuperColumns, new byte[0], superColumnName);\n                break;\n            // Greater than-equals to operator\n            case GTE:\n                searchSuperColumnsInRange(columnFamilyName, consistencyLevel, persistenceUnit, rowKey, superColumnName,\n                        thriftSuperColumns, superColumnName, new byte[0]);\n                break;\n            // Less than equal to operator\n            case LTE:\n                searchSuperColumnsInRange(columnFamilyName, consistencyLevel, persistenceUnit, rowKey, superColumnName,\n                        thriftSuperColumns, new byte[0], superColumnName);\n                break;\n\n            default:\n                throw new QueryHandlerException(condition\n                        + \" comparison operator not supported currently for Cassandra Inverted Index.\");\n            }\n\n            // Construct search results out of these thrift columns\n            for (SuperColumn thriftSuperColumn : thriftSuperColumns)\n            {\n\n                for (Column column : thriftSuperColumn.getColumns())\n                {\n                    byte[] columnName = column.getName();\n                    searchResult.setPrimaryKey(PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(),\n                            columnName));\n                    byte[] columnValue = column.getValue();\n                    String ecValue = UTF8Type.instance.compose(ByteBuffer.wrap(columnValue));\n\n                    if (ecValue != null && !\"\".equals(ecValue.trim()))\n                    {\n                        searchResult.setEmbeddedColumnName(rowKey.substring(0,\n                                rowKey.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER)));\n                        searchResult.addEmbeddedColumnValue(ecValue);\n                    }\n                }\n\n                if (searchResults.isEmpty())\n                {\n                    searchResults.add(searchResult);\n                }\n                else\n                {\n                    SearchResult existing = searchResults.get(0);\n                    if (existing.getPrimaryKey() != null\n                            && existing.getPrimaryKey().equals(searchResult.getPrimaryKey()))\n                    {\n                        searchResults.add(searchResult);\n                    }\n                    else\n                    {\n                        searchResults.remove(0);\n                    }\n                }\n\n            }\n        }\n    }\n\n    public void delete(Object entity, EntityMetadata metadata, ConsistencyLevel consistencyLevel,\n            final KunderaMetadata kunderaMetadata)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                metadata.getPersistenceUnit());\n        if (CassandraIndexHelper.isInvertedIndexingApplicable(metadata, useSecondryIndex))\n        {\n\n            String indexColumnFamily = CassandraIndexHelper.getInvertedIndexTableName(metadata.getTableName());\n            Map<String, EmbeddableType> embeddables = metaModel.getEmbeddables(metadata.getEntityClazz());\n            EntityType entityType = metaModel.entity(metadata.getEntityClazz());\n\n            byte[] columnName = PropertyAccessorHelper.get(entity, (Field) metadata.getIdAttribute().getJavaMember());\n\n            for (String fieldName : embeddables.keySet())\n            {\n                EmbeddableType embeddedColumn = embeddables.get(fieldName);\n                Attribute embeddedAttribute = entityType.getAttribute(fieldName);\n                Object embeddedObject = PropertyAccessorHelper.getObject(entity,\n                        (Field) embeddedAttribute.getJavaMember());\n\n                if (embeddedObject != null)\n                {\n                    if (embeddedObject instanceof Collection)\n                    {\n                        for (Object obj : (Collection) embeddedObject)\n                        {\n                            Iterator<Attribute> iter = embeddedColumn.getAttributes().iterator();\n                            while (iter.hasNext())\n                            {\n                                Attribute attrib = iter.next();\n                                String rowKey = embeddedAttribute.getName() + Constants.INDEX_TABLE_ROW_KEY_DELIMITER\n                                        + attrib.getName();\n                                byte[] superColumnName = PropertyAccessorHelper\n                                        .get(obj, (Field) attrib.getJavaMember());\n                                if (superColumnName != null)\n                                {\n                                    deleteColumn(indexColumnFamily, rowKey, superColumnName,\n                                            metadata.getPersistenceUnit(), consistencyLevel, columnName);\n                                }\n                            }\n                        }\n                    }\n                    else\n                    {\n\n                        Iterator<Attribute> iter = embeddedColumn.getAttributes().iterator();\n                        while (iter.hasNext())\n                        {\n                            Attribute attrib = iter.next();\n                            String rowKey = embeddedAttribute.getName() + Constants.INDEX_TABLE_ROW_KEY_DELIMITER\n                                    + attrib.getName();\n                            byte[] superColumnName = PropertyAccessorHelper.get(embeddedObject,\n                                    (Field) attrib.getJavaMember());\n                            if (superColumnName != null)\n                            {\n                                deleteColumn(indexColumnFamily, rowKey, superColumnName, metadata.getPersistenceUnit(),\n                                        consistencyLevel, columnName);\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * @param indexColumnFamily\n     * @param rowKey\n     * @param superColumnName\n     * @param columnName\n     *            TODO\n     */\n    protected abstract void deleteColumn(String indexColumnFamily, String rowKey, byte[] superColumnName,\n            String persistenceUnit, ConsistencyLevel consistencyLevel, byte[] columnName);\n\n    /**\n     * @param consistencyLevel\n     * @param columnFamilyName\n     * @param rowKey\n     * @param superColumnName\n     * @return\n     */\n    protected abstract SuperColumn getSuperColumnForRow(ConsistencyLevel consistencyLevel, String columnFamilyName,\n            String rowKey, byte[] superColumnName, String persistenceUnit);\n\n    protected abstract void searchSuperColumnsInRange(String columnFamilyName, ConsistencyLevel consistencyLevel,\n            String persistenceUnit, String rowKey, byte[] searchSuperColumnName, List<SuperColumn> thriftSuperColumns,\n            byte[] start, byte[] finish);\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/query/CassQuery.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.query;\n\nimport java.lang.reflect.Field;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javassist.Modifier;\n\nimport javax.persistence.Embeddable;\nimport javax.persistence.Transient;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.Metamodel;\n\nimport org.apache.cassandra.thrift.IndexClause;\nimport org.apache.cassandra.thrift.IndexExpression;\nimport org.apache.cassandra.thrift.IndexOperator;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.apache.commons.lang.StringUtils;\nimport org.eclipse.persistence.jpa.jpql.parser.CountFunction;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectClause;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.client.cassandra.common.CassandraUtilities;\nimport com.impetus.client.cassandra.index.CassandraIndexHelper;\nimport com.impetus.client.cassandra.thrift.CQLTranslator;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.query.KunderaQuery.SortOrdering;\nimport com.impetus.kundera.query.KunderaQuery.UpdateClause;\nimport com.impetus.kundera.query.QueryHandlerException;\nimport com.impetus.kundera.query.QueryImpl;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * The Class CassQuery.\n * \n * @author vivek.mishra\n * \n *         Query implementation for Cassandra.\n */\n@SuppressWarnings(\"unchecked\")\npublic class CassQuery extends QueryImpl {\n\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(CassQuery.class);\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /** The external properties. */\n    protected Map<String, Object> externalProperties;\n\n    /**\n     * Instantiates a new cass query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param persistenceDelegator\n     *            the persistence delegator\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public CassQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n        final KunderaMetadata kunderaMetadata) {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera .metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List<Object> populateEntities(EntityMetadata m, Client client) {\n        if (log.isDebugEnabled()) {\n            log.debug(\"Populating entities for Cassandra query {}.\", getJPAQuery());\n        }\n        List<Object> result = new ArrayList<Object>();\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\n        externalProperties = ((CassandraClientBase) client).getExternalProperties();\n\n        // if id attribute is embeddable, it is meant for CQL translation.\n        // make it independent of embedded stuff and allow even to add non\n        // composite into where clause and let cassandra complain for it.\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n            .getMetamodel(m != null ? m.getPersistenceUnit() : client.getPersistenceUnit());\n\n        String query = appMetadata.getQuery(getJPAQuery());\n        boolean isNative = kunderaQuery.isNative();\n        if (!isNative && !MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())) {\n            result = populateUsingLucene(m, client, result, getKunderaQuery().getResult());\n        }\n        // change for embeddable\n        else if (!isNative && ((CassandraClientBase) client).isCql3Enabled(m)\n            && MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())) {\n            result = ((CassandraClientBase) client).executeQuery(m.getEntityClazz(), null, isNative,\n                onQueryOverCQL3(m, client, metaModel, null));\n        } else {\n            if (isNative) {\n                // XXX\n                if (!kunderaQuery.getBindParameters().isEmpty()) {\n                    result = ((CassandraClientBase) client).executeQuery(null, null, isNative,\n                        query != null ? query : getJPAQuery(), kunderaQuery.getBindParameters());\n                } else {\n                    result = ((CassandraClientBase) client).executeQuery(m != null ? m.getEntityClazz() : null, null,\n                        isNative, query != null ? query : getJPAQuery());\n                }\n            } else {\n                if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())) {\n                    // Index in Inverted Index table if applicable\n                    boolean useInvertedIndex = CassandraIndexHelper.isInvertedIndexingApplicable(m,\n                        MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()));\n                    Map<Boolean, List<IndexClause>> ixClause = prepareIndexClause(m, useInvertedIndex);\n                    if (useInvertedIndex && !getKunderaQuery().getFilterClauseQueue().isEmpty()) {\n                        result = (List) ((CassandraEntityReader) getReader()).readFromIndexTable(m, client, ixClause);\n                    } else {\n                        boolean isRowKeyQuery = ixClause.keySet().iterator().next();\n                        if (!isRowKeyQuery) {\n                            result = ((CassandraClientBase) client).find(ixClause.get(isRowKeyQuery), m, false, null,\n                                isSingleResult ? 1 : this.maxResult,\n                                getColumnList(m, metaModel, getKunderaQuery().getResult(), null));\n                        } else {\n                            result =\n                                ((CassandraEntityReader) getReader()).handleFindByRange(m, client, result, ixClause,\n                                    isRowKeyQuery, getColumnList(m, metaModel, getKunderaQuery().getResult(), null),\n                                    isSingleResult ? 1 : this.maxResult);\n                        }\n                    }\n                }\n\n            }\n        }\n        return result;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#findUsingLucene(com.impetus.kundera .metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    protected List findUsingLucene(EntityMetadata m, Client client) {\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());\n        boolean useInvertedIndex = CassandraIndexHelper.isInvertedIndexingApplicable(m,\n            MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()));\n        Map<Boolean, List<IndexClause>> ixClause = prepareIndexClause(m, useInvertedIndex);\n        List<Object> result = new ArrayList<Object>();\n        if (((CassandraClientBase) client).isCql3Enabled(m)) {\n            result = ((CassandraClientBase) client).executeQuery(m.getEntityClazz(), m.getRelationNames(), false,\n                onQueryOverCQL3(m, client, metaModel, m.getRelationNames()));\n        } else {\n            result = ((CassandraEntityReader) getReader()).handleFindByRange(m, client, result, ixClause, true,\n                getColumnList(m, metaModel, getKunderaQuery().getResult(), null), isSingleResult ? 1 : this.maxResult);\n        }\n        return result;\n    }\n\n    /**\n     * (non-Javadoc).\n     * \n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @return the list\n     * @see com.impetus.kundera.query.QueryImpl#recursivelyPopulateEntities(com.impetus\n     *      .kundera.metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @SuppressWarnings(\"unchecked\")\n    @Override\n    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client) {\n        List<EnhanceEntity> ls = null;\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\n        externalProperties = ((CassandraClientBase) client).getExternalProperties();\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());\n\n        String query = appMetadata.getQuery(getJPAQuery());\n        boolean isNative = kunderaQuery.isNative();\n\n        if (isNative) {\n            ls = (List<EnhanceEntity>) ((CassandraClientBase) client).executeQuery(m.getEntityClazz(),\n                m.getRelationNames(), isNative, query != null ? query : getJPAQuery());\n        } else if (!isNative && ((CassandraClientBase) client).isCql3Enabled(m)) {\n            // edited\n            // check if lucene or indexer are enabled then populate\n            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())) {\n                ls = ((CassandraClientBase) client).executeQuery(m.getEntityClazz(), m.getRelationNames(), isNative,\n\n                    onQueryOverCQL3(m, client, metaModel, m.getRelationNames()));\n            } else {\n                ls = populateUsingLucene(m, client, null, getKunderaQuery().getResult());\n            }\n        } else {\n            // Index in Inverted Index table if applicable\n            boolean useInvertedIndex = CassandraIndexHelper.isInvertedIndexingApplicable(m,\n                MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()));\n            Map<Boolean, List<IndexClause>> ixClause =\n                MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())\n                    ? prepareIndexClause(m, useInvertedIndex) : null;\n\n            if (useInvertedIndex && !getKunderaQuery().getFilterClauseQueue().isEmpty()) {\n                ls = ((CassandraEntityReader) getReader()).readFromIndexTable(m, client, ixClause);\n            } else {\n                ((CassandraEntityReader) getReader()).setConditions(ixClause);\n                ls = reader.populateRelation(m, client, isSingleResult ? 1 : this.maxResult);\n            }\n        }\n        return setRelationEntities(ls, client, m);\n    }\n\n    /**\n     * On executeUpdate.\n     * \n     * @return zero\n     */\n    @Override\n    protected int onExecuteUpdate() {\n        EntityMetadata m = getEntityMetadata();\n        Client client = m != null ? persistenceDelegeator.getClient(m)\n            : persistenceDelegeator.getClient(kunderaQuery.getPersistenceUnit());\n        externalProperties = ((CassandraClientBase) client).getExternalProperties();\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\n\n        String query = appMetadata.getQuery(getJPAQuery());\n\n        boolean isNative = kunderaQuery.isNative();\n\n        if (isNative) {\n            ((CassandraClientBase) client).executeQuery(m == null ? null : m.getEntityClazz(), null, isNative,\n                query != null ? query : getJPAQuery());\n        } else if (kunderaQuery.isDeleteUpdate()) {\n            // If query is not convertible to CQL, fetch and merge records usual\n            // way, otherwise\n            // convert to CQL and execute\n            if (!isQueryConvertibleToCQL(kunderaQuery)) {\n                return onUpdateDeleteEvent();\n            } else {\n                query = null;\n                if (kunderaQuery.isUpdateClause()) {\n                    query = createUpdateQuery(kunderaQuery);\n                } else {\n                    query = createDeleteQuery(kunderaQuery);\n                }\n                return ((CassandraClientBase) client).executeUpdateDeleteQuery(query);\n            }\n        }\n        return 0;\n    }\n\n    /**\n     * Checks whether a given JPA DML query is convertible to CQL.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @return true, if is query convertible to cql\n     */\n    private boolean isQueryConvertibleToCQL(KunderaQuery kunderaQuery) {\n        EntityMetadata m = kunderaQuery.getEntityMetadata();\n        if (kunderaQuery.isUpdateClause() && m.isCounterColumnType())\n            return false;\n\n        List<String> opsNotAllowed = Arrays.asList(new String[] { \">\", \"<\", \">=\", \"<=\" });\n        boolean result = false;\n        if (!kunderaQuery.getFilterClauseQueue().isEmpty()) {\n            String idColumn = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n            for (Object o : kunderaQuery.getFilterClauseQueue()) {\n                if (o instanceof FilterClause) {\n                    FilterClause filterClause = (FilterClause) o;\n                    if (!idColumn.equals(filterClause.getProperty())\n                        || opsNotAllowed.contains(filterClause.getCondition())) {\n                        result = false;\n                        break;\n                    }\n                    result = true;\n                }\n            }\n        }\n        return result;\n    }\n\n    /**\n     * Gets the column list.\n     * \n     * @param m\n     *            the m\n     * @param metamodel\n     *            the metamodel\n     * @param results\n     *            the results\n     * @param compoundKey\n     *            the compound key\n     * @return the column list\n     */\n    List<String> getColumnList(EntityMetadata m, MetamodelImpl metamodel, String[] results,\n        EmbeddableType compoundKey) {\n        List<String> columns = new ArrayList<String>();\n        if (results != null && results.length > 0) {\n            MetamodelImpl metaModel =\n                (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());\n            EntityType entity = metaModel.entity(m.getEntityClazz());\n\n            String keyFieldName = CassandraUtilities.getIdColumnName(kunderaMetadata, m, externalProperties,\n                ((CassandraClientBase) persistenceDelegeator.getClient(m)).isCql3Enabled(m));\n            for (int i = 1; i < results.length; i++) {\n                if (results[i] != null) {\n                    if (results[i].indexOf(\".\") > 0) {\n                        String fieldName = results[i].substring(0, results[i].indexOf(\".\"));\n                        String embeddedFieldName =\n                            results[i].substring(results[i].indexOf(\".\") + 1, results[i].length());\n                        AbstractAttribute attribute = (AbstractAttribute) entity.getAttribute(fieldName);\n                        EmbeddableType embeddable = metamodel.embeddable(attribute.getBindableJavaType());\n                        Attribute embeddableAttribute = embeddable.getAttribute(embeddedFieldName);\n                        columns.add(((AbstractAttribute) embeddableAttribute).getJPAColumnName());\n                    } else {\n                        Attribute attribute = entity.getAttribute(results[i]);\n                        if (attribute == null) {\n                            throw new QueryHandlerException(\"Column type is null for : \" + results);\n                        } else if (m.getIdAttribute().equals(attribute) && compoundKey != null) {\n                            Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields();\n                            for (Field field : fields) {\n                                addCompositeIdToColumns(metamodel, compoundKey, columns, field);\n                            }\n                        } else if (m.getIdAttribute().equals(attribute) && compoundKey == null) {\n                            columns.add(keyFieldName);\n                        } else {\n                            columns.add(((AbstractAttribute) attribute).getJPAColumnName());\n                        }\n                    }\n                }\n            }\n            return columns;\n        }\n\n        if (log.isInfoEnabled()) {\n            log.info(\"No record found, returning null.\");\n        }\n        return null;\n    }\n\n    /**\n     * Adds the composite id to columns.\n     * \n     * @param metamodel\n     *            the metamodel\n     * @param compoundKey\n     *            the compound key\n     * @param columns\n     *            the columns\n     * @param field\n     *            the field\n     */\n    private void addCompositeIdToColumns(MetamodelImpl metamodel, EmbeddableType compoundKey, List<String> columns,\n        Field field) {\n        if (!ReflectUtils.isTransientOrStatic(field)) {\n            Attribute compositeColumn = compoundKey.getAttribute(field.getName());\n            if (compositeColumn.getJavaType().isAnnotationPresent(Embeddable.class)) {\n                // partition key\n                EmbeddableType partitionCol = metamodel.embeddable(compositeColumn.getJavaType());\n                Set<Attribute> cols = partitionCol.getAttributes();\n                for (Attribute col : cols) {\n                    Field f = (Field) col.getJavaMember();\n                    if (!ReflectUtils.isTransientOrStatic(f)) {\n                        columns.add(((AbstractAttribute) col).getJPAColumnName());\n                    }\n                }\n            } else {\n                columns.add(((AbstractAttribute) compositeColumn).getJPAColumnName());\n            }\n        }\n    }\n\n    /**\n     * Prepare index clause.\n     * \n     * @param m\n     *            the m\n     * @param isQueryForInvertedIndex\n     *            the is query for inverted index\n     * @return the map\n     */\n    Map<Boolean, List<IndexClause>> prepareIndexClause(EntityMetadata m, boolean isQueryForInvertedIndex) {\n        IndexClause indexClause =\n            new IndexClause(new ArrayList<IndexExpression>(), ByteBufferUtil.EMPTY_BYTE_BUFFER, maxResult);\n\n        List<IndexClause> clauses = new ArrayList<IndexClause>();\n        List<IndexExpression> expr = new ArrayList<IndexExpression>();\n\n        Map<Boolean, List<IndexClause>> idxClauses = new HashMap<Boolean, List<IndexClause>>(1);\n        // check if id column are mixed with other columns or not?\n        String idColumn = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n        boolean idPresent = false;\n\n        if (log.isInfoEnabled()) {\n            log.info(\"Preparing index clause for query {}\", getJPAQuery());\n        }\n\n        for (Object o : getKunderaQuery().getFilterClauseQueue()) {\n            if (o instanceof FilterClause) {\n                FilterClause clause = ((FilterClause) o);\n                String fieldName = clause.getProperty();\n                // in case id column matches with field name, set it for first\n                // time.\n                if (!idPresent && idColumn.equalsIgnoreCase(fieldName)) {\n                    idPresent = true;\n                }\n\n                String condition = clause.getCondition();\n                List<Object> value = clause.getValue();\n                if (value != null && value.size() > 1) {\n                    log.error(\"IN clause is not enabled for thrift, use cql3.\");\n                    throw new QueryHandlerException(\"IN clause is not enabled for thrift, use cql3.\");\n                }\n                IndexOperator operator = getOperator(condition, idPresent);\n\n                IndexExpression expression = new IndexExpression(ByteBufferUtil.bytes(fieldName), operator,\n                    getBytesValue(fieldName, m, value.get(0)));\n\n                expr.add(expression);\n            } else {\n                // Case of AND and OR clause.\n                String opr = o.toString();\n                if (opr.equalsIgnoreCase(\"or\")) {\n                    log.error(\"Support for OR clause is not enabled within cassandra.\");\n                    throw new QueryHandlerException(\"Unsupported clause \" + opr + \" for cassandra.\");\n                }\n            }\n        }\n\n        if (!StringUtils.isBlank(getKunderaQuery().getFilter())) {\n            indexClause.setExpressions(expr);\n            clauses.add(indexClause);\n        }\n        idxClauses.put(idPresent, clauses);\n\n        return idxClauses;\n    }\n\n    /**\n     * Gets the operator.\n     * \n     * @param condition\n     *            the condition\n     * @param idPresent\n     *            the id present\n     * @return the operator\n     */\n    private IndexOperator getOperator(String condition, boolean idPresent) {\n        if (/* !idPresent && */condition.equals(\"=\")) {\n            return IndexOperator.EQ;\n        } else if (/* !idPresent && */condition.equals(\">\")) {\n            return IndexOperator.GT;\n        } else if (/* !idPresent && */condition.equals(\"<\")) {\n            return IndexOperator.LT;\n        } else if (condition.equals(\">=\")) {\n            return IndexOperator.GTE;\n        } else if (condition.equals(\"<=\")) {\n            return IndexOperator.LTE;\n        } else {\n            if (!idPresent) {\n                throw new UnsupportedOperationException(\"Condition \" + condition + \" is not suported in  cassandra.\");\n            } else {\n                throw new UnsupportedOperationException(\n                    \"Condition \" + condition + \" is not suported for query on row key.\");\n            }\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#getReader()\n     */\n    @Override\n    protected EntityReader getReader() {\n        if (reader == null) {\n            reader = new CassandraEntityReader(kunderaQuery, kunderaMetadata);\n        }\n        return reader;\n    }\n\n    /**\n     * Returns bytes value for given value.\n     * \n     * @param jpaFieldName\n     *            field name.\n     * @param m\n     *            entity metadata\n     * @param value\n     *            value.\n     * @return bytes value.\n     */\n    ByteBuffer getBytesValue(String jpaFieldName, EntityMetadata m, Object value) {\n        Attribute idCol = m.getIdAttribute();\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());\n\n        EntityType entity = metaModel.entity(m.getEntityClazz());\n        Field f = null;\n        boolean isId = false;\n        if (((AbstractAttribute) idCol).getJPAColumnName().equals(jpaFieldName)) {\n            f = (Field) idCol.getJavaMember();\n            isId = true;\n        } else {\n            if (jpaFieldName != null && jpaFieldName.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER) > 0) {\n                String embeddedFieldName =\n                    jpaFieldName.substring(0, jpaFieldName.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER));\n                String columnFieldName = jpaFieldName.substring(\n                    jpaFieldName.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER) + 1, jpaFieldName.length());\n\n                Attribute embeddedAttr = entity.getAttribute(embeddedFieldName);\n                try {\n                    Class<?> embeddedClass = embeddedAttr.getJavaType();\n                    if (Collection.class.isAssignableFrom(embeddedClass)) {\n                        Class<?> genericClass =\n                            PropertyAccessorHelper.getGenericClass((Field) embeddedAttr.getJavaMember());\n                        f = genericClass.getDeclaredField(columnFieldName);\n                    } else {\n                        f = embeddedClass.getDeclaredField(columnFieldName);\n                    }\n\n                } catch (SecurityException e) {\n                    log.error(\"Error while extrating \" + jpaFieldName + \", Caused by: \", e);\n                    throw new QueryHandlerException(\"Error while extrating \" + jpaFieldName + \".\");\n                } catch (NoSuchFieldException e) {\n                    log.error(\"Error while extrating \" + jpaFieldName + \", Caused by: \", e);\n                    throw new QueryHandlerException(\"Error while extrating \" + jpaFieldName + \".\");\n                }\n            } else {\n                String discriminatorColumn = ((AbstractManagedType) entity).getDiscriminatorColumn();\n\n                if (!jpaFieldName.equals(discriminatorColumn)) {\n                    String fieldName = m.getFieldName(jpaFieldName);\n\n                    Attribute col = entity.getAttribute(fieldName);\n                    if (col == null) {\n                        throw new QueryHandlerException(\"column type is null for: \" + jpaFieldName);\n                    }\n                    f = (Field) col.getJavaMember();\n                }\n            }\n        }\n\n        // need to do integer.parseInt..as value will be string in case of\n        // create query.\n        if (f != null && f.getType() != null) {\n            return CassandraUtilities.toBytes(value, f);\n        } else {\n            // default is String type\n            return CassandraUtilities.toBytes(value, String.class);\n        }\n    }\n\n    /**\n     * On query over composite columns.\n     * \n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @param metaModel\n     *            the meta model\n     * @param relations\n     *            the relations\n     * @return the list\n     */\n    public String onQueryOverCQL3(EntityMetadata m, Client client, MetamodelImpl metaModel, List<String> relations) {\n        // select column will always be of entity field only!\n        // where clause ordering\n\n        Class compoundKeyClass = m.getIdAttribute().getBindableJavaType();\n        EmbeddableType compoundKey = null;\n        String idColumn;\n        if (metaModel.isEmbeddable(compoundKeyClass)) {\n            compoundKey = metaModel.embeddable(compoundKeyClass);\n            idColumn = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n        } else {\n            idColumn = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n        }\n        StringBuilder builder = new StringBuilder();\n\n        boolean isPresent = false;\n        List<String> columns = getColumnList(m, metaModel, getKunderaQuery().getResult(), compoundKey);\n        String selectQuery = setSelectQuery(columns);\n\n        CQLTranslator translator = new CQLTranslator();\n\n        selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMN_FAMILY,\n            translator.ensureCase(new StringBuilder(), m.getTableName(), false).toString());\n\n        builder = CassandraUtilities.appendColumns(builder, columns, selectQuery, translator);\n\n        addWhereClause(builder);\n\n        onCondition(m, metaModel, compoundKey, idColumn, builder, isPresent, translator, true);\n\n        return builder.toString();\n    }\n\n    /**\n     * Sets the select query.\n     * \n     * @param columns\n     *            the columns\n     * @return the string\n     */\n    private String setSelectQuery(List<String> columns) {\n        if (columns != null && !columns.isEmpty()) {\n            return CQLTranslator.SELECT_QUERY;\n        }\n        if (kunderaQuery.isAggregated()) {\n            Expression selectExpression =\n                ((SelectClause) kunderaQuery.getSelectStatement().getSelectClause()).getSelectExpression();\n            // create query depending on function\n            if (selectExpression instanceof CountFunction) {\n                return CQLTranslator.SELECT_COUNT_QUERY;\n            }\n        }\n        return CQLTranslator.SELECTALL_QUERY;\n    }\n\n    /**\n     * Add provided max result limit.\n     * \n     * @param builder\n     *            string builder.\n     */\n    private void onLimit(StringBuilder builder) {\n        if (Integer.MAX_VALUE != maxResult) {\n            builder.append(CQLTranslator.LIMIT);\n            builder.append(isSingleResult ? 1 : this.maxResult);\n        }\n    }\n\n    /**\n     * On condition.\n     * \n     * @param m\n     *            the m\n     * @param metaModel\n     *            the meta model\n     * @param keyObj\n     *            the compound key\n     * @param idColumn\n     *            the id column\n     * @param builder\n     *            the builder\n     * @param isPresent\n     *            the is present\n     * @param translator\n     *            the translator\n     * @param use\n     *            the use\n     * @return true, if successful\n     */\n    private boolean onCondition(EntityMetadata m, MetamodelImpl metaModel, EmbeddableType keyObj, String idColumn,\n        StringBuilder builder, boolean isPresent, CQLTranslator translator, boolean use) {\n        String partitionKey = null;\n        boolean allowFiltering = false;\n        for (Object o : getKunderaQuery().getFilterClauseQueue()) {\n            if (o instanceof FilterClause) {\n                FilterClause clause = ((FilterClause) o);\n                String fieldName = clause.getProperty();\n                String condition = clause.getCondition();\n                List<Object> value = clause.getValue();\n                boolean useInClause = condition.trim().equalsIgnoreCase(\"IN\");\n\n                // if compound key field is given in where clause.\n                isPresent = true;\n\n                if (keyObj != null && idColumn.equals(fieldName)) {\n                    Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields();\n\n                    Map<Attribute, List<Object>> columnValues = new HashMap<Attribute, List<Object>>();\n\n                    for (Field field : fields) {\n                        if (!ReflectUtils.isTransientOrStatic(field)) {\n                            extractCompositeKey(metaModel, keyObj, builder, translator, value, useInClause,\n                                columnValues, field);\n                        }\n                    }\n\n                    // Composite key always contains clusterKey.\n                    allowFiltering = true;\n                    if (useInClause) {\n                        for (Attribute columnAttribute : columnValues.keySet()) {\n                            isPresent = appendInClause(builder, translator, columnValues.get(columnAttribute),\n                                ((AbstractAttribute) columnAttribute).getBindableJavaType(),\n                                ((AbstractAttribute) columnAttribute).getJPAColumnName(), isPresent);\n                        }\n                    }\n                } else if (keyObj != null && metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())\n                    && StringUtils.contains(fieldName, '.')) {\n                    // Means it is a case of composite column.\n                    isPresent = getCompoundKeyColumn(metaModel, keyObj, builder, isPresent, translator, fieldName,\n                        condition, value, useInClause);\n\n                    allowFiltering = true;\n                } else if (idColumn.equals(fieldName)) {\n                    // dont use token for equals query on id column (#856)\n                    boolean useToken = use;\n                    if (condition.equals(\"=\")) {\n                        useToken = false;\n                    }\n                    isPresent = buildWhereClause(builder, isPresent, translator, condition, value, useInClause,\n                        ((AbstractAttribute) m.getIdAttribute()),\n                        CassandraUtilities.getIdColumnName(kunderaMetadata, m, externalProperties,\n                            ((CassandraClientBase) persistenceDelegeator.getClient(m)).isCql3Enabled(m)),\n                        useToken);\n                } else {\n                    EntityType entity = metaModel.entity(m.getEntityClazz());\n                    // Metamodel metamodel =\n                    // KunderaMetadataManager.getMetamodel(kunderaMetadata,\n                    // m.getPersistenceUnit());\n                    String discriminatorColumn = ((AbstractManagedType) entity).getDiscriminatorColumn();\n                    if (fieldName.equals(discriminatorColumn)) {\n                        translator.buildWhereClause(builder, String.class, fieldName,\n                            value.isEmpty() ? null : value.get(0), condition, false);\n                        isPresent = true;\n\n                    } else {\n                        Metamodel metamodel =\n                            KunderaMetadataManager.getMetamodel(kunderaMetadata, m.getPersistenceUnit());\n                        Attribute attribute = ((MetamodelImpl) metamodel).getEntityAttribute(m.getEntityClazz(),\n                            m.getFieldName(fieldName));\n\n                        isPresent = buildWhereClause(builder, isPresent, translator, condition, value, useInClause,\n                            ((AbstractAttribute) attribute), fieldName, false);\n                    }\n\n                    allowFiltering = true;\n                }\n            }\n        }\n\n        // Strip last AND clause.\n        if (isPresent) {\n            builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length());\n        }\n\n        // Append order by clause into query\n        builder = appendOrderByClause(metaModel, m, keyObj, builder, translator);\n\n        if (allowFiltering && use) {\n            onLimit(builder);\n            builder.append(\" \");\n            translator.buildFilteringClause(builder);\n        } else if (use) {\n            onLimit(builder);\n        }\n\n        return isPresent;\n    }\n\n    /**\n     * Gets the compound key column.\n     * \n     * @param metamodel\n     *            the metamodel\n     * @param keyObj\n     *            the key obj\n     * @param builder\n     *            the builder\n     * @param isPresent\n     *            the is present\n     * @param translator\n     *            the translator\n     * @param fieldName\n     *            the field name\n     * @param condition\n     *            the condition\n     * @param value\n     *            the value\n     * @param useInClause\n     *            the use in clause\n     * @return the compound key column\n     */\n    private boolean getCompoundKeyColumn(MetamodelImpl metamodel, EmbeddableType keyObj, StringBuilder builder,\n        boolean isPresent, CQLTranslator translator, String fieldName, String condition, List<Object> value,\n        boolean useInClause) {\n        fieldName = fieldName.substring(fieldName.indexOf(\".\") + 1);\n\n        // If partition key part age given in query, i.e. restriction on\n        // id.compositekey.compositePartitionkey.partitionkeyColumn.\n        if (fieldName.indexOf(\".\") > 0) {\n            String compositePartitionkeyName = fieldName.substring(0, fieldName.indexOf(\".\"));\n            AbstractAttribute attribute = (AbstractAttribute) keyObj.getAttribute(compositePartitionkeyName);\n            fieldName = fieldName.substring(fieldName.indexOf(\".\") + 1);\n\n            EmbeddableType compositePartitionkey = metamodel.embeddable(attribute.getBindableJavaType());\n\n            attribute = (AbstractAttribute) compositePartitionkey.getAttribute(fieldName);\n\n            String columnName = attribute.getJPAColumnName();\n\n            isPresent = buildWhereClause(builder, isPresent, translator, condition, value, useInClause, attribute,\n                columnName, false);\n        }\n        // if composite partition key object is given in query, i.e. restriction\n        // on id.compositekey.compositePartitionkey\n        else if (metamodel.isEmbeddable(((AbstractAttribute) keyObj.getAttribute(fieldName)).getBindableJavaType())) {\n            AbstractAttribute attribute = (AbstractAttribute) keyObj.getAttribute(fieldName);\n            Set<Attribute> attributes = metamodel.embeddable(attribute.getBindableJavaType()).getAttributes();\n\n            if (!useInClause) {\n                // Iterating and appending each column of composite partition\n                // key in query builder.\n                for (Attribute nestedAttribute : attributes) {\n                    String columnName = ((AbstractAttribute) nestedAttribute).getJPAColumnName();\n                    Object valueObject = PropertyAccessorHelper.getObject(value.isEmpty() ? null : value.get(0),\n                        (Field) nestedAttribute.getJavaMember());\n                    translator.buildWhereClause(builder, nestedAttribute.getJavaType(), columnName, valueObject,\n                        condition, false);\n                }\n            } else {\n                throw new IllegalArgumentException(\"In clause is not supported on first part of partition key.\");\n            }\n            isPresent = true;\n        }\n        // if Not a composite partition key,\n        // id.compositekey.partitionkey/clusterKey.\n        else {\n            AbstractAttribute attribute = (AbstractAttribute) keyObj.getAttribute(fieldName);\n            String columnName = attribute.getJPAColumnName();\n            isPresent = buildWhereClause(builder, isPresent, translator, condition, value, useInClause, attribute,\n                columnName, false);\n        }\n        return isPresent;\n    }\n\n    /**\n     * Append order by clause.\n     * \n     * @param metaModel\n     *            the meta model\n     * @param m\n     *            the m\n     * @param keyObj\n     *            the key obj\n     * @param builder\n     *            the builder\n     * @param translator\n     *            the translator\n     * @return the string builder\n     */\n    private StringBuilder appendOrderByClause(MetamodelImpl metaModel, EntityMetadata m, EmbeddableType keyObj,\n        StringBuilder builder, CQLTranslator translator) {\n        List<SortOrdering> orders = getKunderaQuery().getOrdering();\n\n        if (orders != null) {\n            builder.append(CQLTranslator.SPACE_STRING);\n            builder.append(CQLTranslator.SORT_CLAUSE);\n\n            for (SortOrdering order : orders) {\n                String orderColumnName = order.getColumnName();\n\n                orderColumnName = orderColumnName.substring(orderColumnName.indexOf(\".\") + 1, orderColumnName.length());\n\n                String orderByColumnName;\n\n                if (StringUtils.contains(orderColumnName, '.')) {\n                    String propertyName = orderColumnName.substring(0, orderColumnName.indexOf(\".\"));\n                    Attribute embeddableAttribute = metaModel.getEntityAttribute(m.getEntityClazz(), propertyName);\n                    EmbeddableType embeddableType =\n                        metaModel.embeddable(((AbstractAttribute) embeddableAttribute).getBindableJavaType());\n                    orderColumnName = orderColumnName.substring(orderColumnName.indexOf(\".\") + 1);\n                    AbstractAttribute attribute = (AbstractAttribute) embeddableType.getAttribute(orderColumnName);\n                    orderByColumnName = attribute.getJPAColumnName();\n\n                } else {\n                    Attribute attribute = metaModel.getEntityAttribute(m.getEntityClazz(), orderColumnName);\n                    orderByColumnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                }\n\n                builder = translator.ensureCase(builder, orderByColumnName, false);\n                builder.append(CQLTranslator.SPACE_STRING);\n                builder.append(order.getOrder());\n                builder.append(CQLTranslator.COMMA_STR);\n            }\n\n            if (!orders.isEmpty()) {\n                builder.deleteCharAt(builder.lastIndexOf(CQLTranslator.COMMA_STR));\n            }\n        }\n        return builder;\n    }\n\n    /**\n     * Extract composite key.\n     * \n     * @param metaModel\n     *            the meta model\n     * @param keyObj\n     *            the key obj\n     * @param builder\n     *            the builder\n     * @param translator\n     *            the translator\n     * @param value\n     *            the value\n     * @param useInClause\n     *            the use in clause\n     * @param columnValues\n     *            the column values\n     * @param field\n     *            the field\n     * @return true, if successful\n     */\n    private boolean extractCompositeKey(MetamodelImpl metaModel, EmbeddableType keyObj, StringBuilder builder,\n        CQLTranslator translator, List<Object> value, boolean useInClause, Map<Attribute, List<Object>> columnValues,\n        Field field) {\n        Attribute compositeColumn = keyObj.getAttribute(field.getName());\n        String jpaColumnName = ((AbstractAttribute) compositeColumn).getJPAColumnName();\n\n        if (useInClause) {\n            for (Object embeddedObject : value) {\n\n                Object valueObject = PropertyAccessorHelper.getObject(embeddedObject, field);\n                // Checking for composite partition key.\n                if (metaModel.isEmbeddable(((AbstractAttribute) compositeColumn).getBindableJavaType())) {\n                    Set<Attribute> attributes = metaModel\n                        .embeddable(((AbstractAttribute) compositeColumn).getBindableJavaType()).getAttributes();\n\n                    // Iterating over composite partition key columns.\n                    for (Attribute nestedAttribute : attributes) {\n                        List<Object> valueList = columnValues.get(compositeColumn);\n\n                        if (valueList == null) {\n                            valueList = new ArrayList<Object>();\n                        }\n\n                        Object obj =\n                            PropertyAccessorHelper.getObject(valueObject, (Field) nestedAttribute.getJavaMember());\n                        valueList.add(obj);\n                        columnValues.put(nestedAttribute, valueList);\n                    }\n                } else {\n                    List<Object> valueList = columnValues.get(compositeColumn);\n\n                    if (valueList == null) {\n                        valueList = new ArrayList<Object>();\n                    }\n                    valueList.add(valueObject);\n                    columnValues.put(compositeColumn, valueList);\n                }\n            }\n        } else {\n            Object valueObject = PropertyAccessorHelper.getObject(value.isEmpty() ? null : value.get(0), field);\n\n            // Checking for composite partition key.\n            if (metaModel.isEmbeddable(((AbstractAttribute) compositeColumn).getBindableJavaType())) {\n                Set<Attribute> attributes =\n                    metaModel.embeddable(((AbstractAttribute) compositeColumn).getBindableJavaType()).getAttributes();\n\n                // Iterating over composite partition key columns.\n                for (Attribute nestedAttribute : attributes) {\n                    String columnName = ((AbstractAttribute) nestedAttribute).getJPAColumnName();\n                    Object obj = PropertyAccessorHelper.getObject(valueObject, (Field) nestedAttribute.getJavaMember());\n                    translator.buildWhereClause(builder, nestedAttribute.getJavaType(), columnName, obj,\n                        CQLTranslator.EQ_CLAUSE, false);\n                }\n                // returning true because builder has AND clause at end.\n                return true;\n            } else {\n                translator.buildWhereClause(builder, field.getType(), jpaColumnName, valueObject,\n                    CQLTranslator.EQ_CLAUSE, false);\n                // returning true because builder has AND clause at end.\n                return true;\n            }\n        }\n        // returning false because builder does not have AND clause at end.\n        return false;\n    }\n\n    /**\n     * Builds the where clause.\n     * \n     * @param builder\n     *            the builder\n     * @param isPresent\n     *            the is present\n     * @param translator\n     *            the translator\n     * @param condition\n     *            the condition\n     * @param value\n     *            the value\n     * @param useInClause\n     *            the use in clause\n     * @param idAttributeColumn\n     *            the id attribute column\n     * @param columnName\n     *            the column name\n     * @param useToken\n     *            the use token\n     * @return true, if successful\n     */\n    private boolean buildWhereClause(StringBuilder builder, boolean isPresent, CQLTranslator translator,\n        String condition, List<Object> value, boolean useInClause, AbstractAttribute idAttributeColumn,\n        String columnName, boolean useToken) {\n        if (value.isEmpty()) {\n            isPresent = appendIn(builder, translator, columnName);\n            builder.append(\"( )\");\n            builder.append(\" AND \");\n        }\n        // handle relations in Id\n        else if (useInClause && value.size() > 1) {\n            isPresent = appendInClause(builder, translator, value, idAttributeColumn.getBindableJavaType(), columnName,\n                isPresent);\n        } else {\n            // TODO for partition key in case of embedded key.\n            // idAttributeColumn.getBindableJavaType() was sending this class,\n            // changed to getJavaType()\n            translator.buildWhereClause(builder, ((Attribute) idAttributeColumn).getJavaType(), columnName,\n                value.isEmpty() ? null : value.get(0), condition, useToken);\n        }\n        return isPresent;\n    }\n\n    /**\n     * Append in.\n     * \n     * @param builder\n     *            the builder\n     * @param translator\n     *            the translator\n     * @param columnName\n     *            the column name\n     * @return true, if successful\n     */\n    private boolean appendIn(StringBuilder builder, CQLTranslator translator, String columnName) {\n        boolean isPresent;\n        isPresent = true;\n        translator.ensureCase(builder, columnName, false);\n        builder.append(\" IN \");\n        return isPresent;\n    }\n\n    /**\n     * Append in clause.\n     * \n     * @param queryBuilder\n     *            the query builder\n     * @param translator\n     *            the translator\n     * @param value\n     *            the value\n     * @param fieldClazz\n     *            the field clazz\n     * @param columnName\n     *            the column name\n     * @param isPresent\n     *            the is present\n     * @return true, if successful\n     */\n    private boolean appendInClause(StringBuilder queryBuilder, CQLTranslator translator, List<Object> value,\n        Class fieldClazz, String columnName, boolean isPresent) {\n        isPresent = appendIn(queryBuilder, translator, columnName);\n        queryBuilder.append(\"(\");\n        for (Object objectvalue : value) {\n            translator.appendValue(queryBuilder, fieldClazz, objectvalue, isPresent, false);\n            queryBuilder.append(\", \");\n        }\n\n        queryBuilder.deleteCharAt(queryBuilder.lastIndexOf(\", \"));\n        queryBuilder.append(\") \");\n\n        queryBuilder.append(\" AND \");\n        return isPresent;\n    }\n\n    /**\n     * Adds the where clause.\n     * \n     * @param builder\n     *            the builder\n     */\n    void addWhereClause(StringBuilder builder) {\n        if (!getKunderaQuery().getFilterClauseQueue().isEmpty()) {\n            builder.append(CQLTranslator.ADD_WHERE_CLAUSE);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#close()\n     */\n    @Override\n    public void close() {\n        // Nothing to close.\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#iterate()\n     */\n    @Override\n    public Iterator iterate() {\n        if (kunderaQuery.isNative()) {\n            throw new UnsupportedOperationException(\"Iteration not supported over native queries\");\n        }\n        EntityMetadata m = getEntityMetadata();\n        Client client = persistenceDelegeator.getClient(m);\n        externalProperties = ((CassandraClientBase) client).getExternalProperties();\n\n        if (!MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())) {\n            throw new UnsupportedOperationException(\"Scrolling over cassandra is unsupported for lucene queries\");\n        }\n\n        return new ResultIterator(this, m, persistenceDelegeator.getClient(m), this.getReader(),\n            getFetchSize() != null ? getFetchSize() : this.maxResult, kunderaMetadata);\n    }\n\n    /**\n     * Sets the relational entities.\n     * \n     * @param enhanceEntities\n     *            the enhance entities\n     * @param client\n     *            the client\n     * @param m\n     *            the m\n     */\n    public void setRelationalEntities(List enhanceEntities, Client client, EntityMetadata m) {\n        super.setRelationEntities(enhanceEntities, client, m);\n    }\n\n    /**\n     * Create Update CQL query from a given JPA query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @return the string\n     */\n    public String createUpdateQuery(KunderaQuery kunderaQuery) {\n        EntityMetadata metadata = kunderaQuery.getEntityMetadata();\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());\n\n        CQLTranslator translator = new CQLTranslator();\n        String update_Query = translator.UPDATE_QUERY;\n\n        String tableName = metadata.getTableName();\n        update_Query = StringUtils.replace(update_Query, CQLTranslator.COLUMN_FAMILY,\n            translator.ensureCase(new StringBuilder(), tableName, false).toString());\n\n        StringBuilder builder = new StringBuilder(update_Query);\n\n        Object ttlColumns = ((CassandraClientBase) persistenceDelegeator.getClient(metadata)).getTtlValues()\n            .get(metadata.getTableName());\n\n        if ((ttlColumns != null && ttlColumns instanceof Integer) || this.ttl != null) {\n            int ttl = this.ttl != null ? this.ttl : ((Integer) ttlColumns).intValue();\n            if (ttl != 0) {\n                builder.append(\" USING TTL \");\n                builder.append(ttl);\n                builder.append(\" \");\n            }\n        }\n\n        builder.append(CQLTranslator.ADD_SET_CLAUSE);\n\n        for (UpdateClause updateClause : kunderaQuery.getUpdateClauseQueue()) {\n\n            String property = updateClause.getProperty();\n\n            String jpaColumnName = getColumnName(metadata, property);\n\n            Object value = updateClause.getValue();\n\n            translator.buildSetClause(metadata, builder, jpaColumnName, value);\n        }\n        builder.delete(builder.lastIndexOf(CQLTranslator.COMMA_STR), builder.length());\n        builder.append(CQLTranslator.ADD_WHERE_CLAUSE);\n\n        Class compoundKeyClass = metadata.getIdAttribute().getBindableJavaType();\n        EmbeddableType compoundKey = null;\n        String idColumn;\n        if (metaModel.isEmbeddable(compoundKeyClass)) {\n            compoundKey = metaModel.embeddable(compoundKeyClass);\n            idColumn = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();\n        } else {\n            idColumn = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();\n        }\n\n        onCondition(metadata, metaModel, compoundKey, idColumn, builder, false, translator, false);\n\n        return builder.toString();\n    }\n\n    /**\n     * Create Delete query from a given JPA query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @return the string\n     */\n    public String createDeleteQuery(KunderaQuery kunderaQuery) {\n        EntityMetadata metadata = kunderaQuery.getEntityMetadata();\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());\n        CQLTranslator translator = new CQLTranslator();\n        String delete_query = translator.DELETE_QUERY;\n\n        String tableName = kunderaQuery.getEntityMetadata().getTableName();\n        delete_query = StringUtils.replace(delete_query, CQLTranslator.COLUMN_FAMILY,\n            translator.ensureCase(new StringBuilder(), tableName, false).toString());\n\n        StringBuilder builder = new StringBuilder(delete_query);\n        builder.append(CQLTranslator.ADD_WHERE_CLAUSE);\n\n        Class compoundKeyClass = metadata.getIdAttribute().getBindableJavaType();\n        EmbeddableType compoundKey = null;\n        String idColumn;\n        if (metaModel.isEmbeddable(compoundKeyClass)) {\n            compoundKey = metaModel.embeddable(compoundKeyClass);\n            idColumn = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();\n        } else {\n            idColumn = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();\n        }\n\n        onCondition(metadata, metaModel, compoundKey, idColumn, builder, false, translator, false);\n\n        return builder.toString();\n    }\n\n    /**\n     * Builds where Clause.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param metadata\n     *            the metadata\n     * @param metaModel\n     *            the meta model\n     * @param translator\n     *            the translator\n     * @param builder\n     *            the builder\n     */\n    private void buildWhereClause(KunderaQuery kunderaQuery, EntityMetadata metadata, MetamodelImpl metaModel,\n        CQLTranslator translator, StringBuilder builder) {\n        for (Object clause : kunderaQuery.getFilterClauseQueue()) {\n            FilterClause filterClause = (FilterClause) clause;\n            Field f = (Field) metaModel.entity(metadata.getEntityClazz())\n                .getAttribute(metadata.getFieldName(filterClause.getProperty())).getJavaMember();\n            String jpaColumnName = getColumnName(metadata, filterClause.getProperty());\n\n            if (metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {\n                Field[] fields = metadata.getIdAttribute().getBindableJavaType().getDeclaredFields();\n                EmbeddableType compoundKey = metaModel.embeddable(metadata.getIdAttribute().getBindableJavaType());\n                for (Field field : fields) {\n                    if (field != null && !Modifier.isStatic(field.getModifiers())\n                        && !Modifier.isTransient(field.getModifiers()) && !field.isAnnotationPresent(Transient.class)) {\n                        Attribute attribute = compoundKey.getAttribute(field.getName());\n                        String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                        Object value = PropertyAccessorHelper.getObject(filterClause.getValue().get(0), field);\n                        // TODO\n                        translator.buildWhereClause(builder, field.getType(), columnName, value,\n                            filterClause.getCondition(), false);\n                    }\n                }\n            } else {\n                translator.buildWhereClause(builder, f.getType(), jpaColumnName, filterClause.getValue().get(0),\n                    filterClause.getCondition(), false);\n            }\n        }\n        builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length());\n    }\n\n    /**\n     * Gets column name for a given field name.\n     * \n     * @param metadata\n     *            the metadata\n     * @param property\n     *            the property\n     * @return the column name\n     */\n    private String getColumnName(EntityMetadata metadata, String property) {\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());\n        String jpaColumnName = null;\n\n        if (property.equals(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName())) {\n            jpaColumnName = CassandraUtilities.getIdColumnName(kunderaMetadata, metadata,\n                ((CassandraClientBase) persistenceDelegeator.getClient(metadata)).getExternalProperties(),\n                ((CassandraClientBase) persistenceDelegeator.getClient(metadata)).isCql3Enabled(metadata));\n        } else {\n            jpaColumnName = ((AbstractAttribute) metaModel.getEntityAttribute(metadata.getEntityClazz(), property))\n                .getJPAColumnName();\n        }\n        return jpaColumnName;\n    }\n\n    /**\n     * Checks if is native.\n     * \n     * @return true, if is native\n     */\n    boolean isNative() {\n        return kunderaQuery.isNative();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/query/CassandraEntityReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.query;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.apache.cassandra.thrift.IndexClause;\nimport org.apache.cassandra.thrift.IndexExpression;\nimport org.apache.cassandra.thrift.IndexOperator;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.db.SearchResult;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.QueryHandlerException;\n\n/**\n * The Class CassandraEntityReader.\n * \n * @author vivek.mishra\n */\npublic class CassandraEntityReader extends AbstractEntityReader implements EntityReader\n{\n    \n    /** The Constant MIN_. */\n    private static final String MIN_ = \"min\";\n\n    /** The Constant MAX_. */\n    private static final String MAX_ = \"max\";\n\n    /** The conditions. */\n    private Map<Boolean, List<IndexClause>> conditions = new HashMap<Boolean, List<IndexClause>>();\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(CassandraEntityReader.class);\n\n    /**\n     * Instantiates a new cassandra entity reader.\n     *\n     * @param kunderaQuery the kundera query\n     * @param kunderaMetadata the kundera metadata\n     */\n    public CassandraEntityReader(KunderaQuery kunderaQuery, final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n        this.kunderaQuery = kunderaQuery;\n    }\n\n    /**\n     * Instantiates a new cassandra entity reader.\n     *\n     * @param kunderaMetadata the kundera metadata\n     */\n    public CassandraEntityReader(final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.persistence.AbstractEntityReader#findById(java.lang.Object, com.impetus.kundera.metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        return super.findById(primaryKey, m, client);\n    }\n\n    /**\n     * Method responsible for reading back entity and relations using secondary\n     * indexes(if it holds any relation), else retrieve row keys using lucene.\n     *\n     * @param m            entity meta data\n     * @param client            client instance\n     * @param maxResults the max results\n     * @return list of wrapped enhance entities.\n     */\n\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        if (log.isInfoEnabled())\n        {\n            log.info(\"On populate relation via JPQL\");\n        }\n        List<EnhanceEntity> ls = null;\n        List<String> relationNames = m.getRelationNames();\n        boolean isParent = m.isParent();\n\n        boolean isRowKeyQuery = conditions != null ? conditions.keySet().iterator().next() : false;\n\n        // If Query is not for find by range.\n        if (!isRowKeyQuery)\n        {\n            // If holding associations.\n            if (!isParent)\n            {\n                // In case need to use secondary indexes.\n                if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))\n                {\n                    ls = ((CassandraClientBase) client).find(m, relationNames, this.conditions.get(isRowKeyQuery),\n                            maxResults, null);\n                }\n                else\n                {\n                    // prepare lucene query and find.\n                    Set<String> rSet = fetchDataFromLucene(m.getEntityClazz(), client);\n\n                    try\n                    {\n                        ls = (List<EnhanceEntity>) ((CassandraClientBase) client).find(m.getEntityClazz(),\n                                relationNames, true, m, rSet.toArray(new Object[] {}));\n                    }\n                    catch (Exception e)\n                    {\n                        log.error(\"Error while executing handleAssociation for cassandra, Caused by: \", e);\n                        throw new QueryHandlerException(e);\n                    }\n                }\n            }\n            else\n            {\n                if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))\n                {\n                    // in case need to search on secondry columns and it is not\n                    // set\n                    // to true!\n                    ls = ((CassandraClientBase) client).find(this.conditions.get(isRowKeyQuery), m, true,\n                            m.getRelationNames(), maxResults, null);\n                }\n                else\n                {\n                    ls = onAssociationUsingLucene(m, client, ls);\n                }\n            }\n        }\n        else\n        {\n            ls = handleFindByRange(m, client, ls, conditions, isRowKeyQuery, null, maxResults);\n        }\n        return ls;\n    }\n\n    /**\n     * Handle find by range.\n     *\n     * @param m            the m\n     * @param client            the client\n     * @param result            the result\n     * @param ixClause            the ix clause\n     * @param isRowKeyQuery            the is row key query\n     * @param columns the columns\n     * @param maxResults the max results\n     * @return the list\n     */\n    public List handleFindByRange(EntityMetadata m, Client client, List result,\n            Map<Boolean, List<IndexClause>> ixClause, boolean isRowKeyQuery, List<String> columns, int maxResults)\n    {\n        List<IndexExpression> expressions = ixClause.get(isRowKeyQuery).get(0).getExpressions();\n\n        if (expressions == null)\n        {\n            return null;\n        }\n\n        Map<String, byte[]> rowKeys = getRowKeyValue(expressions,\n                ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName());\n\n        byte[] minValue = rowKeys.get(MIN_);\n        byte[] maxVal = rowKeys.get(MAX_);\n\n        try\n        {\n            result = ((CassandraClientBase) client).findByRange(minValue, maxVal, m, m.getRelationNames() != null\n                    && !m.getRelationNames().isEmpty(), m.getRelationNames(), columns, expressions, maxResults);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while executing find by range, Caused by: \", e);\n            throw new QueryHandlerException(e);\n        }\n        return result;\n    }\n\n    /**\n     * Read from index table.\n     *\n     * @param m the m\n     * @param client the client\n     * @param indexClauseMap the index clause map\n     * @return the list\n     */\n    public List<EnhanceEntity> readFromIndexTable(EntityMetadata m, Client client,\n            Map<Boolean, List<IndexClause>> indexClauseMap)\n    {\n        List<SearchResult> searchResults = new ArrayList<SearchResult>();\n        List<Object> primaryKeys = new ArrayList<Object>();\n\n        String columnFamilyName = m.getTableName() + Constants.INDEX_TABLE_SUFFIX;\n        searchResults = ((CassandraClientBase) client).searchInInvertedIndex(columnFamilyName, m, indexClauseMap);\n\n        Map<String, String> embeddedColumns = new HashMap<String, String>();\n        for (SearchResult searchResult : searchResults)\n        {\n            if (searchResult.getEmbeddedColumnValues() != null)\n            {\n                for (String embeddedColVal : searchResult.getEmbeddedColumnValues())\n                {\n                    if (embeddedColVal != null)\n                    {\n                        StringBuilder strBuilder = new StringBuilder(embeddedColVal);\n                        strBuilder.append(\"|\");\n                        strBuilder.append(searchResult.getPrimaryKey().toString());\n                        embeddedColumns.put(strBuilder.toString(), searchResult.getPrimaryKey().toString());\n                    }\n                }\n            }\n        }\n        List<EnhanceEntity> enhanceEntityList = new ArrayList<EnhanceEntity>();\n        if (embeddedColumns != null && !embeddedColumns.isEmpty())\n        {\n            enhanceEntityList = client.find(m.getEntityClazz(), embeddedColumns);\n        }\n        else\n        {\n            for (SearchResult searchResult : searchResults)\n            {\n                primaryKeys.add(searchResult.getPrimaryKey());\n            }\n            enhanceEntityList = (List<EnhanceEntity>) ((CassandraClientBase) client).find(m.getEntityClazz(),\n                    m.getRelationNames(), true, m, primaryKeys.toArray(new String[] {}));\n        }\n\n        return enhanceEntityList;\n    }\n\n    /**\n     * Method to set indexcluase conditions.\n     * \n     * @param conditions\n     *            index conditions.\n     */\n    public void setConditions(Map<Boolean, List<IndexClause>> conditions)\n    {\n        this.conditions = conditions;\n    }\n\n    /**\n     * Returns list of row keys. First element will be min value and second will\n     * be major value.\n     *\n     * @param expressions the expressions\n     * @param primaryKeyName the primary key name\n     * @return the row key value\n     */\n    Map<String, byte[]> getRowKeyValue(List<IndexExpression> expressions, String primaryKeyName)\n    {\n        Map<String, byte[]> rowKeys = new HashMap<String, byte[]>();\n\n        List<IndexExpression> rowExpressions = new ArrayList<IndexExpression>();\n\n        if (expressions != null)\n        {\n            for (IndexExpression e : expressions)\n            {\n                if (primaryKeyName.equals(new String(e.getColumn_name())))\n                {\n                    IndexOperator operator = e.op;\n                    if (operator.equals(IndexOperator.LTE) || operator.equals(IndexOperator.LT))\n                    {\n                        rowKeys.put(MAX_, e.getValue());\n                        rowExpressions.add(e);\n                    }\n                    else if (operator.equals(IndexOperator.GTE) || operator.equals(IndexOperator.GT))\n                    {\n                        rowKeys.put(MIN_, e.getValue());\n                        rowExpressions.add(e);\n                    }\n                    else if (operator.equals(IndexOperator.EQ))\n                    {\n                        rowKeys.put(MAX_, e.getValue());\n                        rowKeys.put(MIN_, e.getValue());\n                        rowExpressions.add(e);\n                    }\n                }\n            }\n            expressions.removeAll(rowExpressions);\n        }\n        return rowKeys;\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/query/ResultIterator.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.query;\n\nimport java.lang.reflect.Field;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.Query;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.apache.cassandra.thrift.IndexClause;\nimport org.apache.cassandra.thrift.IndexExpression;\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.client.cassandra.common.CassandraUtilities;\nimport com.impetus.client.cassandra.index.CassandraIndexHelper;\nimport com.impetus.client.cassandra.thrift.CQLTranslator;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.IResultIterator;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.query.QueryImpl;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * The Class ResultIterator.\n * \n * @author vivek.mishra .\n * \n *         Implementation of Cassandra result iteration.\n * \n *         TODO::: Need to add support for relational entities and a junit for\n *         Composite key test\n * @param <E>\n *            the element type\n */\npublic class ResultIterator<E> implements IResultIterator<E>\n{\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(ResultIterator.class);\n\n    /** The query. */\n    protected final CassQuery query;\n\n    /** The entity metadata. */\n    protected final EntityMetadata entityMetadata;\n\n    /** The client. */\n    protected final Client client;\n\n    /** The reader. */\n    private final EntityReader reader;\n\n    /** The max result. */\n    private int maxResult = 1;\n\n    /** The results. */\n    protected List<E> results;\n\n    /** The start. */\n    private byte[] start;\n\n    /** The Constant MIN_. */\n    private static final String MIN_ = \"min\";\n\n    /** The Constant MAX_. */\n    private static final String MAX_ = \"max\";\n\n    /** The fetch size. */\n    protected int fetchSize;\n\n    /** The count. */\n    protected int count;\n\n    /** The scroll complete. */\n    protected boolean scrollComplete;\n\n    /** The external properties. */\n    protected Map<String, Object> externalProperties;\n\n    /** The current. */\n    protected E current;\n\n    /** The kundera metadata. */\n    protected final KunderaMetadata kunderaMetadata;\n\n    /**\n     * Constructor with parameters.\n     * \n     * @param query\n     *            the query\n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @param reader\n     *            the reader\n     * @param fetchSize\n     *            the fetch size\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    protected ResultIterator(final Query query, final EntityMetadata m, final Client client, final EntityReader reader,\n            final int fetchSize, final KunderaMetadata kunderaMetadata)\n    {\n        this.client = client;\n        this.query = (CassQuery) query;\n        this.entityMetadata = m;\n        this.reader = reader;\n        this.scrollComplete = false;\n        this.fetchSize = fetchSize;\n        this.kunderaMetadata = kunderaMetadata;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.util.Iterator#hasNext()\n     */\n    @Override\n    public boolean hasNext()\n    {\n        if (checkOnFetchSize())\n        {\n            onCheckRelation();\n            if (!checkOnEmptyResult())\n            {\n                scrollComplete = true;\n                return false;\n            }\n            return true;\n        }\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.util.Iterator#next()\n     */\n    @Override\n    public E next()\n    {\n        if (current != null && checkOnEmptyResult() && current.equals(results.get(results.size() - 1)))\n        {\n            hasNext();\n        }\n\n        if (scrollComplete)\n        {\n            throw new NoSuchElementException(\"Nothing to scroll further for:\" + entityMetadata.getEntityClazz());\n        }\n\n        E lastFetchedEntity = getEntity(results.get(results.size() - 1));\n        start = lastFetchedEntity != null ? idValueInByteArr() : null;\n        current = getEntity(results.get(results.size() - 1));\n\n        return current;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.util.Iterator#remove()\n     */\n    @Override\n    public void remove()\n    {\n        throw new UnsupportedOperationException(\"remove method is not supported over pagination\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.IResultIterator#next(int)\n     */\n    @Override\n    public List<E> next(int chunkSize)\n    {\n        throw new UnsupportedOperationException(\"fetch in chunks is not yet supported\");\n    }\n\n    /**\n     * Check on fetch size. returns true, if count on fetched rows is less than\n     * fetch size.\n     * \n     * @return true, if successful\n     */\n    private boolean checkOnFetchSize()\n    {\n        if (count++ < fetchSize)\n        {\n            return true;\n        }\n        count = 0;\n        scrollComplete = true;\n        return false;\n    }\n\n    /**\n     * on check relation event, invokes populate entities and set relational\n     * entities, in case relations are present.\n     */\n    private void onCheckRelation()\n    {\n        try\n        {\n            results = populateEntities(entityMetadata, client);\n\n            if (entityMetadata.isRelationViaJoinTable()\n                    || (entityMetadata.getRelationNames() != null && !(entityMetadata.getRelationNames().isEmpty())))\n            {\n                query.setRelationalEntities(results, client, entityMetadata);\n            }\n        }\n        catch (Exception e)\n        {\n            throw new PersistenceException(\"Error while scrolling over results, Caused by :.\", e);\n        }\n    }\n\n    /**\n     * Method parse provided JPQL query into: 1. CQL3 query, in case cql3 is\n     * enabled or is a native query. 2. list of index clause, if cql2 is\n     * enabled. Then executes query for given min & max values for scrolling\n     * over results.\n     * \n     * @param m\n     *            entity metadata\n     * @param client\n     *            client\n     * @return list of database values wrapped into entities.\n     * @throws Exception\n     *             throws exception, in case of run time error.\n     */\n    protected List<E> populateEntities(EntityMetadata m, Client client) throws Exception\n    {\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"Populating entities for Cassandra query {}.\", ((QueryImpl) query).getJPAQuery());\n        }\n        List<E> result = new ArrayList<E>();\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\n        externalProperties = ((CassandraClientBase) client).getExternalProperties();\n\n        // if id attribute is embeddable, it is meant for CQL translation.\n        // make it independent of embedded stuff and allow even to add non\n        // composite into where clause and let cassandra complain for it.\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n\n        String queryString = appMetadata.getQuery(((QueryImpl) query).getJPAQuery());\n\n        boolean isNative = ((CassQuery) query).isNative();\n\n        if (((CassandraClientBase) client).isCql3Enabled(m))\n        {\n            String parsedQuery = query.onQueryOverCQL3(m, client, metaModel, null);\n\n            parsedQuery = appendWhereClauseWithScroll(parsedQuery);\n            results = parsedQuery != null ? ((CassandraClientBase) client).executeQuery(m.getEntityClazz(),\n                    m.getRelationNames(), isNative, parsedQuery) : null;\n        }\n        else\n        {\n            // Index in Inverted Index table if applicable\n            boolean useInvertedIndex = CassandraIndexHelper.isInvertedIndexingApplicable(m,\n                    MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()));\n            Map<Boolean, List<IndexClause>> ixClause = query.prepareIndexClause(m, useInvertedIndex);\n            if (useInvertedIndex && !((QueryImpl) query).getKunderaQuery().getFilterClauseQueue().isEmpty())\n            {\n                result = (List) ((CassandraEntityReader) this.reader).readFromIndexTable(m, client, ixClause);\n            }\n            else\n            {\n                boolean isRowKeyQuery = ixClause.keySet().iterator().next();\n\n                List<IndexExpression> expressions = !ixClause.get(isRowKeyQuery).isEmpty() ? ixClause\n                        .get(isRowKeyQuery).get(0).getExpressions() : null;\n\n                Map<String, byte[]> rowKeys = ((CassandraEntityReader) this.reader).getRowKeyValue(expressions,\n                        ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName());\n\n                byte[] minValue = start == null ? rowKeys.get(MIN_) : start;\n                byte[] maxVal = rowKeys.get(MAX_);\n\n                results = ((CassandraClientBase) client).findByRange(minValue, maxVal, m, m.getRelationNames() != null\n                        && !m.getRelationNames().isEmpty(), m.getRelationNames(),\n                        query.getColumnList(m, metaModel, ((QueryImpl) query).getKunderaQuery().getResult(), null),\n                        expressions, maxResult);\n\n                if (maxResult == 1)\n                {\n                    maxResult++;\n                }\n                else if (maxResult > 1 && checkOnEmptyResult() && maxResult != results.size())\n                {\n                    // means iterating over last record only, so need for\n                    // database trip anymore!.\n                    results = null;\n                }\n            }\n        }\n        return results;\n    }\n\n    /**\n     * Appends where claues and prepare for next fetch. Method to be called in\n     * case cql3 enabled.\n     * \n     * @param parsedQuery\n     *            parsed query.\n     * \n     * @return cql3 query to be executed.\n     */\n    private String appendWhereClauseWithScroll(String parsedQuery)\n    {\n\n        String queryWithoutLimit = parsedQuery.replaceAll(\n                parsedQuery.substring(parsedQuery.lastIndexOf(CQLTranslator.LIMIT), parsedQuery.length()), \"\");\n\n        CQLTranslator translator = new CQLTranslator();\n\n        final String tokenCondition = prepareNext(translator, queryWithoutLimit);\n\n        StringBuilder builder = new StringBuilder(queryWithoutLimit);\n\n        if (tokenCondition != null)\n        {\n            if (query.getKunderaQuery().getFilterClauseQueue().isEmpty())\n            {\n                builder.append(CQLTranslator.ADD_WHERE_CLAUSE);\n            }\n            else\n            {\n                builder.append(CQLTranslator.AND_CLAUSE);\n            }\n            builder.append(tokenCondition);\n        }\n\n        String replaceQuery = replaceAndAppendLimit(builder.toString());\n        builder.replace(0, builder.toString().length(), replaceQuery);\n        translator.buildFilteringClause(builder);\n\n        // in case of fetch by ID, token condition will be null and results will\n        // not be empty.\n        return checkOnEmptyResult() && tokenCondition == null ? null : builder.toString();\n    }\n\n    /**\n     * Replace and append limit.\n     * \n     * @param parsedQuery\n     *            parsed cql3 query.\n     * \n     * @return cql3 query appended with limit clause.\n     */\n    private String replaceAndAppendLimit(String parsedQuery)\n    {\n        StringBuilder builder = new StringBuilder(parsedQuery);\n        onLimit(builder);\n        parsedQuery = builder.toString();\n        return parsedQuery;\n    }\n\n    /**\n     * Append limit to sql3 query.\n     * \n     * @param builder\n     *            builder instance.\n     */\n    private void onLimit(StringBuilder builder)\n    {\n        builder.append(CQLTranslator.LIMIT);\n        builder.append(this.maxResult);\n    }\n\n    /**\n     * Parse and append cql3 token function for iter.next() call.\n     * \n     * @param translator\n     *            cql translator.\n     * @param query\n     *            the query\n     * @return parsed/append cql3 query.\n     */\n    private String prepareNext(CQLTranslator translator, String query)\n    {\n        if (checkOnEmptyResult())\n        {\n            String idName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();\n            Map<Boolean, String> filterOnId = getConditionOnIdColumn(idName);\n\n            if (filterOnId.get(true) != null)\n            {\n                String condition = filterOnId.get(true);\n                // means id clause present in query.\n                // now if id attribute is embeddable then fetch partition key\n                // for token\n                // if condition is with equals then no need to go for another\n                // fetch.\n\n                if (condition.equals(\"=\"))\n                {\n                    // no need to fetch another record, as there will be only\n                    // one\n                    return null;\n                }\n                else if (condition.endsWith(\">\") || condition.equals(\">=\"))\n                {\n                    query = replaceAppliedToken(query);\n                    return query;\n                }\n            }\n\n            // Means there is an previous entity.\n            Object entity = results.get(results.size() - 1);\n            Class idClazz = ((AbstractAttribute) entityMetadata.getIdAttribute()).getBindableJavaType();\n            Object id = PropertyAccessorHelper.getId(entity, entityMetadata);\n            StringBuilder builder = new StringBuilder(CQLTranslator.TOKEN);\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    entityMetadata.getPersistenceUnit());\n\n            EmbeddableType keyObj = null;\n            // Bytes bytes = null;\n            String columnName = null;\n            if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n            {\n                keyObj = metaModel.embeddable(entityMetadata.getIdAttribute().getBindableJavaType());\n                Field embeddedField = getPartitionKeyField();\n                Attribute partitionKey = keyObj.getAttribute(embeddedField.getName());\n                Object partitionKeyValue = PropertyAccessorHelper.getObject(id, (Field) partitionKey.getJavaMember());\n                columnName = ((AbstractAttribute) partitionKey).getJPAColumnName();\n                id = partitionKeyValue;\n                idClazz = ((AbstractAttribute) partitionKey).getBindableJavaType();\n                // StringBuilder pkNameTokens = new StringBuilder(\"token(\");\n                // StringBuilder pkValueTokens = new StringBuilder(\"token(\");\n                // buildPartitionKeyTokens(metaModel,\n                // entityMetadata.getIdAttribute(), id, translator,\n                // pkNameTokens,\n                // pkValueTokens);\n\n            }\n            else\n            {\n                columnName = CassandraUtilities.getIdColumnName(kunderaMetadata, entityMetadata, externalProperties,\n                        ((CassandraClientBase) client).isCql3Enabled(entityMetadata));\n            }\n\n            translator.appendColumnName(builder, columnName);\n            builder.append(CQLTranslator.CLOSE_BRACKET);\n            builder.append(\" > \");\n            builder.append(CQLTranslator.TOKEN);\n            translator.appendValue(builder, idClazz, id, false, false);\n            builder.append(CQLTranslator.CLOSE_BRACKET);\n            return builder.toString();\n        }\n        return null;\n    }\n\n    private void buildPartitionKeyTokens(MetamodelImpl metaModel, SingularAttribute idAttribute, Object id,\n            CQLTranslator translator, StringBuilder pkNameTokens, StringBuilder pkValueTokens)\n    {\n        EmbeddableType keyObj = metaModel.embeddable(entityMetadata.getIdAttribute().getBindableJavaType());\n        Field embeddedField = getPartitionKeyField();\n\n        if (embeddedField == null)\n        {\n            // use tokens on the fields (no clustering keys\n            Field[] fields = entityMetadata.getIdAttribute().getBindableJavaType().getDeclaredFields();\n\n            for (Field field : fields)\n            {\n                Object value = PropertyAccessorHelper.getObject(id, field);\n                String columnName = ((AbstractAttribute) keyObj.getAttribute(field.getName())).getJPAColumnName();\n                translator.appendColumnName(pkNameTokens, columnName);\n                translator.appendValue(pkValueTokens, field.getType(), value, false, false);\n            }\n        }\n        else\n        {\n            // use tokens for partition key fields (fields in embeddedField) and\n            // where clause for clustering fields\n            Attribute partitionKey = keyObj.getAttribute(embeddedField.getName());\n            EmbeddableType partitionKeyObj = metaModel.embeddable(partitionKey.getJavaType());\n            Object partitionKeyValue = PropertyAccessorHelper.getObject(id, (Field) partitionKey.getJavaMember());\n            Field[] fields = partitionKey.getJavaType().getDeclaredFields();\n            // handle for part keys\n            for (Field field : fields)\n            {\n                if (!ReflectUtils.isTransientOrStatic(field))\n                {\n                    Object value = PropertyAccessorHelper.getObject(partitionKeyValue, field);\n                    String columnName = ((AbstractAttribute) partitionKeyObj.getAttribute(field.getName()))\n                            .getJPAColumnName();\n                    translator.appendColumnName(pkNameTokens, columnName);\n                    translator.appendValue(pkValueTokens, field.getType(), value, false, false);\n                    pkNameTokens.append(CQLTranslator.COMMA_STR);\n                    pkValueTokens.append(CQLTranslator.COMMA_STR);\n                }\n            }\n            pkNameTokens.delete(pkNameTokens.lastIndexOf(CQLTranslator.COMMA_STR), pkNameTokens.length());\n            pkValueTokens.delete(pkValueTokens.lastIndexOf(CQLTranslator.COMMA_STR), pkValueTokens.length());\n            pkNameTokens.append(CQLTranslator.CLOSE_BRACKET);\n            pkValueTokens.append(CQLTranslator.CLOSE_BRACKET);\n\n            // TODO: handle for cluster keys\n            throw new UnsupportedOperationException(\n                    \"Pagination is not suported via ThriftClient on primary key with clustering keys...\");\n        }\n\n    }\n\n    /**\n     * Gets the condition on id column.\n     * \n     * @param idColumn\n     *            the id column\n     * @return the condition on id column\n     */\n    private Map<Boolean, String> getConditionOnIdColumn(String idColumn)\n    {\n\n        Map<Boolean, String> filterIdResult = new HashMap<Boolean, String>();\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n\n        EmbeddableType keyObj = null;\n        if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n        {\n            keyObj = metaModel.embeddable(entityMetadata.getIdAttribute().getBindableJavaType());\n        }\n\n        for (Object o : query.getKunderaQuery().getFilterClauseQueue())\n        {\n            if (o instanceof FilterClause)\n            {\n                FilterClause clause = ((FilterClause) o);\n                String fieldName = clause.getProperty();\n                String condition = clause.getCondition();\n\n                if (keyObj != null && fieldName.equals(idColumn)\n                        || (keyObj != null && StringUtils.contains(fieldName, '.')) || (idColumn.equals(fieldName)))\n                {\n                    filterIdResult.put(true, condition);\n                    break;\n                }\n            }\n        }\n        return filterIdResult;\n    }\n\n    /**\n     * Id value in byte arr.\n     * \n     * @return the byte[]\n     */\n    private byte[] idValueInByteArr()\n    {\n        Object entity = results.get(results.size() - 1);\n        Object id = PropertyAccessorHelper.getId(entity, entityMetadata);\n        String idName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();\n        Class idClazz = ((AbstractAttribute) entityMetadata.getIdAttribute()).getBindableJavaType();\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n\n        EmbeddableType keyObj = null;\n        ByteBuffer bytes = null;\n\n        // if the key attribute is composite\n        if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n        {\n            keyObj = metaModel.embeddable(entityMetadata.getIdAttribute().getBindableJavaType());\n            Field embeddedField = getPartitionKeyField();\n            Attribute partitionKey = keyObj.getAttribute(embeddedField.getName());\n            Object partitionKeyValue = PropertyAccessorHelper.getObject(id, (Field) partitionKey.getJavaMember());\n            bytes = CassandraUtilities.toBytes(partitionKeyValue, (Field) partitionKey.getJavaMember());\n        }\n        else\n        {\n            bytes = query.getBytesValue(idName, entityMetadata, id);\n        }\n        return bytes.array();\n    }\n\n    /**\n     * Will return partition key part of composite id.\n     * \n     * @return the partition key field\n     */\n    private Field getPartitionKeyField()\n    {\n        Field[] embeddedFields = entityMetadata.getIdAttribute().getBindableJavaType().getDeclaredFields();\n\n        Field field = null;\n        for (Field embeddedField : embeddedFields)\n        {\n            if (!ReflectUtils.isTransientOrStatic(embeddedField))\n            {\n                field = embeddedField;\n                break;\n            }\n        }\n        return field;\n    }\n\n    /**\n     * check if result list is null or empty. Returns true, if it is not empty\n     * or null.\n     * \n     * @return boolean value (true/false).\n     * \n     */\n    private boolean checkOnEmptyResult()\n    {\n        return results != null && !results.isEmpty();\n    }\n\n    /**\n     * Extract wrapped entity object from enhanced entity.\n     * \n     * @param entity\n     *            enhanced entity.\n     * \n     * @return returns extracted instance of E.\n     */\n    private E getEntity(Object entity)\n    {\n        return (E) (entity.getClass().isAssignableFrom(EnhanceEntity.class) ? ((EnhanceEntity) entity).getEntity()\n                : entity);\n    }\n\n    /**\n     * Replace applied token.\n     * \n     * @param query\n     *            the query\n     * @return the string\n     */\n    private String replaceAppliedToken(String query)\n    {\n        final String tokenRegex = \"\\\\btoken\\\\(\";\n        final String pattern = \"#TOKENKUNDERA#\"; // need to replace with this as\n                                                 // pattern matcher was\n                                                 // returning false.\n        query = query.replaceAll(tokenRegex, pattern);\n\n        if (query.indexOf(pattern) > -1) // Means token( has been present and\n                                         // replaced.\n        {\n            CQLTranslator translator = new CQLTranslator();\n\n            int closingIndex = query.indexOf(CQLTranslator.CLOSE_BRACKET, query.lastIndexOf(pattern));\n\n            String object = query.substring(query.lastIndexOf(pattern) + pattern.length(), closingIndex);\n\n            Object entity = results.get(results.size() - 1);\n            Class idClazz = ((AbstractAttribute) entityMetadata.getIdAttribute()).getBindableJavaType();\n            Object id = PropertyAccessorHelper.getId(entity, entityMetadata);\n            StringBuilder builder = new StringBuilder();\n\n            translator.appendValue(builder, idClazz, id, false, false);\n\n            query = query.replaceAll(pattern + object, pattern + builder.toString());\n            query = query.replaceAll(pattern, CQLTranslator.TOKEN);\n        }\n        return query;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraDataTranslator.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.impetus.client.cassandra.schemamanager;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.CharacterCodingException;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.Collection;\nimport java.util.Comparator;\nimport java.util.Date;\nimport java.util.EnumSet;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport javax.persistence.PersistenceException;\n\nimport org.apache.cassandra.db.marshal.AbstractType;\nimport org.apache.cassandra.db.marshal.AsciiType;\nimport org.apache.cassandra.db.marshal.BooleanType;\nimport org.apache.cassandra.db.marshal.BytesType;\nimport org.apache.cassandra.db.marshal.CounterColumnType;\nimport org.apache.cassandra.db.marshal.DateType;\nimport org.apache.cassandra.db.marshal.DecimalType;\nimport org.apache.cassandra.db.marshal.DoubleType;\nimport org.apache.cassandra.db.marshal.FloatType;\nimport org.apache.cassandra.db.marshal.InetAddressType;\nimport org.apache.cassandra.db.marshal.Int32Type;\nimport org.apache.cassandra.db.marshal.IntegerType;\nimport org.apache.cassandra.db.marshal.ListType;\nimport org.apache.cassandra.db.marshal.LongType;\nimport org.apache.cassandra.db.marshal.MapType;\nimport org.apache.cassandra.db.marshal.SetType;\nimport org.apache.cassandra.db.marshal.UTF8Type;\nimport org.apache.cassandra.db.marshal.UUIDType;\nimport org.apache.cassandra.serializers.ListSerializer;\nimport org.apache.cassandra.serializers.MapSerializer;\nimport org.apache.cassandra.serializers.SetSerializer;\nimport org.apache.cassandra.serializers.TypeSerializer;\nimport org.apache.cassandra.thrift.CounterColumn;\nimport org.apache.cassandra.transport.ProtocolVersion;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.property.accessor.ByteAccessor;\nimport com.impetus.kundera.property.accessor.CalendarAccessor;\nimport com.impetus.kundera.property.accessor.CharAccessor;\nimport com.impetus.kundera.property.accessor.DateAccessor;\nimport com.impetus.kundera.property.accessor.EnumAccessor;\nimport com.impetus.kundera.property.accessor.IntegerAccessor;\nimport com.impetus.kundera.property.accessor.SQLDateAccessor;\nimport com.impetus.kundera.property.accessor.SQLTimeAccessor;\nimport com.impetus.kundera.property.accessor.SQLTimestampAccessor;\nimport com.impetus.kundera.property.accessor.ShortAccessor;\n\n\n/**\n * Class to decompose and compose Cassandra data type objects.\n * \n * @author chhavi.gangwal\n */\n\npublic final class CassandraDataTranslator\n{\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(CassandraDataTranslator.class);\n\n    /** The cassandra data type map. */\n    private static Map<Class<?>, CassandraType> typeToClazz = new HashMap<Class<?>, CassandraDataTranslator.CassandraType>();\n\n    /**\n     * CassandradataType enum.\n     */\n    public static enum CassandraType\n    {\n\n        /** The IN t32. */\n        INT32(Int32Type.class.getSimpleName()), /** The double. */\n        DOUBLE(DoubleType.class.getSimpleName()), /** The float. */\n        FLOAT(FloatType.class.getSimpleName()),\n        /** The long. */\n        LONG(LongType.class.getSimpleName()),\n        /** The string. */\n        STRING(UTF8Type.class.getSimpleName()),\n        /** The uuid. */\n        UUID(UUIDType.class.getSimpleName()),\n        /** The bytes. */\n        BYTES(BytesType.class.getSimpleName()),\n        /** The ascii. */\n        ASCII(AsciiType.class.getSimpleName()),\n        /** The boolean. */\n        BOOLEAN(BooleanType.class.getSimpleName()),\n        /** The date. */\n        DATE(DateType.class.getSimpleName()),\n        /** The int. */\n        INT(IntegerType.class.getSimpleName()),\n        /** The decimal. */\n        DECIMAL(DecimalType.class.getSimpleName()),\n        /** The counter. */\n        COUNTER(CounterColumnType.class.getSimpleName()),\n        /** The list. */\n        LIST(ListType.class.getSimpleName()),\n        /** The map. */\n        MAP(MapType.class.getSimpleName()),\n        /** The set. */\n        SET(SetType.class.getSimpleName()),\n        /** The inet. */\n        INET(InetAddressType.class.getSimpleName()),\n        /** The short. */\n        SHORT(Short.class.getSimpleName()),\n        /** The enum. */\n        ENUM(Enum.class.getSimpleName()),\n        /** The character. */\n        CHARACTER(UTF8Type.class.getSimpleName()),\n        /** The bigint. */\n        BIGINT(IntegerType.class.getSimpleName()),\n        /** The timestamp. */\n        TIMESTAMP(DateType.class.getSimpleName()),\n        /** The sql date. */\n        SQL_DATE(DateType.class.getSimpleName()),\n        /** The sql time. */\n        SQL_TIME(DateType.class.getSimpleName()),\n        /** The sql timestamp. */\n        SQL_TIMESTAMP(DateType.class.getSimpleName()),\n        /** The calendar. */\n        CALENDAR(DateType.class.getSimpleName());\n\n        /** The clazz. */\n        private String clazz;\n\n        /** The Constant lookup. */\n        private static final Map<String, CassandraType> lookup = new HashMap<String, CassandraType>();\n\n        static\n        {\n            for (CassandraType s : EnumSet.allOf(CassandraType.class))\n                lookup.put(s.getClazz(), s);\n        }\n\n        /**\n         * Instantiates a new cassandra type.\n         * \n         * @param clazz\n         *            the clazz\n         */\n        private CassandraType(String clazz)\n        {\n            this.clazz = clazz;\n        }\n\n        /**\n         * Gets the clazz.\n         * \n         * @return the clazz\n         */\n        public String getClazz()\n        {\n            return clazz;\n        }\n\n        /**\n         * Gets the.\n         * \n         * @param clazz\n         *            the clazz\n         * @return the cassandra type\n         */\n        public static CassandraType get(String clazz)\n        {\n            return lookup.get(clazz);\n        }\n    }\n\n    static\n    {\n        typeToClazz.put(java.lang.String.class, CassandraType.STRING);\n\n        typeToClazz.put(Character.class, CassandraType.CHARACTER);\n        typeToClazz.put(char.class, CassandraType.CHARACTER);\n\n        typeToClazz.put(java.lang.Integer.class, CassandraType.INT);\n        typeToClazz.put(int.class, CassandraType.INT);\n\n        typeToClazz.put(Short.class, CassandraType.SHORT);\n        typeToClazz.put(short.class, CassandraType.SHORT);\n\n        typeToClazz.put(java.math.BigDecimal.class, CassandraType.DECIMAL);\n\n        typeToClazz.put(java.math.BigInteger.class, CassandraType.BIGINT);\n\n        typeToClazz.put(java.lang.Double.class, CassandraType.DOUBLE);\n        typeToClazz.put(double.class, CassandraType.DOUBLE);\n\n        typeToClazz.put(Calendar.class, CassandraType.CALENDAR);\n        typeToClazz.put(java.sql.Date.class, CassandraType.SQL_DATE);\n        typeToClazz.put(java.util.Date.class, CassandraType.TIMESTAMP);\n        typeToClazz.put(java.sql.Time.class, CassandraType.SQL_TIME);\n        typeToClazz.put(java.sql.Timestamp.class, CassandraType.SQL_TIMESTAMP);\n\n        typeToClazz.put(boolean.class, CassandraType.BOOLEAN);\n        typeToClazz.put(Boolean.class, CassandraType.BOOLEAN);\n\n        typeToClazz.put(java.lang.Long.class, CassandraType.LONG);\n        typeToClazz.put(long.class, CassandraType.LONG);\n\n        typeToClazz.put(Byte.class, CassandraType.BYTES);\n        typeToClazz.put(byte.class, CassandraType.BYTES);\n\n        typeToClazz.put(Float.class, CassandraType.FLOAT);\n        typeToClazz.put(float.class, CassandraType.FLOAT);\n\n        typeToClazz.put(UUID.class, CassandraType.UUID);\n\n        typeToClazz.put(List.class, CassandraType.LIST);\n        typeToClazz.put(Set.class, CassandraType.SET);\n        typeToClazz.put(Map.class, CassandraType.MAP);\n\n        typeToClazz.put(CounterColumn.class, CassandraType.COUNTER);\n    }\n\n    /**\n     * Gets the cassandra data type class.\n     * \n     * @param clazz\n     *            the clazz\n     * @return the cassandra data type class\n     */\n    public static CassandraType getCassandraDataTypeClass(Class clazz)\n    {\n        if(clazz.isEnum()){\n            return CassandraType.STRING;\n        }\n        return typeToClazz.get(clazz);\n    }\n\n    /**\n     * Checks whether the data type object is that of cassandra.\n     * \n     * @param clazz\n     *            the clazz\n     * @return true, if is cassandra data type class\n     */\n    public static boolean isCassandraDataTypeClass(Class clazz)\n    {\n\n        if (typeToClazz.get(clazz) == null)\n        {\n            return false;\n        }\n        return true;\n    }\n\n    /**\n     * Calls compose function of respective data type of object.\n     * \n     * @param dataTypeClazz\n     *            the data type clazz\n     * @param dataValue\n     *            the data value\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return the byte[]\n     */\n    public static byte[] compose(Class<?> dataTypeClazz, Object dataValue, boolean isCql3Enabled)\n    {\n\n        if (isCql3Enabled || (!isCql3Enabled && dataValue != null))\n        {\n\n            switch (getCassandraDataTypeClass(dataTypeClazz))\n            {\n            case INT:\n                return IntegerTypeBuilder.compose(dataValue, dataTypeClazz);\n            case DATE:\n                return DateTypeBuilder.compose(dataValue, dataTypeClazz);\n            case FLOAT:\n                return FloatTypeBuilder.compose(dataValue, dataTypeClazz);\n            case LONG:\n                return LongTypeBuilder.compose(dataValue, dataTypeClazz);\n            case DOUBLE:\n                return DoubleTypeBuilder.compose(dataValue, dataTypeClazz);\n            case STRING:\n                return StringTypeBuilder.compose(dataValue, dataTypeClazz);\n            case ASCII:\n                return AsciiTypeBuilder.compose(dataValue, dataTypeClazz);\n            case UUID:\n                return UUIDTypeBuilder.compose(dataValue, dataTypeClazz);\n            case BYTES:\n                return BytesTypeBuilder.compose(dataValue, dataTypeClazz);\n            case BOOLEAN:\n                return BooleanTypeBuilder.compose(dataValue, dataTypeClazz);\n            case INT32:\n                return IntegerTypeBuilder.compose(dataValue, dataTypeClazz);\n            case DECIMAL:\n                return DecimalTypeBuilder.compose(dataValue, dataTypeClazz);\n            case COUNTER:\n                return CounterTypeBuilder.compose(dataValue, dataTypeClazz);\n            case ENUM:\n                return EnumTypeBuilder.compose(dataValue, dataTypeClazz);\n            case CHARACTER:\n                return CharacterTypeBuilder.compose(dataValue, dataTypeClazz);\n            case SHORT:\n                return ShortTypeBuilder.compose(dataValue, dataTypeClazz);\n            case BIGINT:\n                return BigIntegerTypeBuilder.compose(dataValue, dataTypeClazz);\n            case TIMESTAMP:\n                return TimeStampTypeBuilder.compose(dataValue, dataTypeClazz);\n            case SQL_DATE:\n                return SQLDateTypeBuilder.compose(dataValue, dataTypeClazz);\n            case SQL_TIME:\n                return SQLTimeTypeBuilder.compose(dataValue, dataTypeClazz);\n            case SQL_TIMESTAMP:\n                return SQLTimeStampTypeBuilder.compose(dataValue, dataTypeClazz);\n            case CALENDAR:\n                return CalendarTypeBuilder.compose(dataValue, dataTypeClazz);\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Calls compose function of respective data type of object.\n     * \n     * @param dataTypeClazz\n     *            the data type clazz\n     * @param dataValue\n     *            the data value\n     * @param mapGenericClassses\n     *            the map generic classses\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return the byte[]\n     */\n    public static byte[] compose(Class<?> dataTypeClazz, Object dataValue, List<Class<?>> mapGenericClassses,\n            boolean isCql3Enabled)\n    {\n        if (isCql3Enabled || (!isCql3Enabled && dataValue != null))\n        {\n            if (dataTypeClazz.isAssignableFrom(Map.class))\n            {\n                return MapTypeBuilder.compose(dataValue, mapGenericClassses);\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Calls compose function of respective data type of object.\n     * \n     * @param dataTypeClazz\n     *            the data type clazz\n     * @param dataValue\n     *            the data value\n     * @param mapGenericClassses\n     *            the map generic classses\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return the byte[]\n     */\n    public static byte[] compose(Class<?> dataTypeClazz, Object dataValue, Class<?> mapGenericClassses,\n            boolean isCql3Enabled)\n    {\n        if (isCql3Enabled || (!isCql3Enabled && dataValue != null))\n        {\n            switch (getCassandraDataTypeClass(dataTypeClazz))\n            {\n            case LIST:\n                return ListTypeBuilder.compose(dataValue, dataTypeClazz, mapGenericClassses);\n            case SET:\n                return SetTypeBuilder.compose(dataValue, dataTypeClazz, mapGenericClassses);\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Calls decompose function of respective data type of object.\n     * \n     * @param dataTypeClazz\n     *            the data type clazz\n     * @param dataValue\n     *            the data value\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return the object\n     */\n    public static Object decompose(Class<?> dataTypeClazz, Object dataValue, boolean isCql3Enabled)\n    {\n\n        if (isCql3Enabled || (!isCql3Enabled && dataValue != null))\n        {\n\n            switch (getCassandraDataTypeClass(dataTypeClazz))\n            {\n            case INT:\n                return IntegerTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case DATE:\n                return DateTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case FLOAT:\n                return FloatTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case LONG:\n                return LongTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case DOUBLE:\n                return DoubleTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case STRING:\n                return StringTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case ASCII:\n                return AsciiTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case UUID:\n                return UUIDTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case BYTES:\n                if (isCql3Enabled)\n                {\n                    return BytesTypeBuilder.decompose(dataValue, dataTypeClazz);\n                }\n                else\n                {\n                    return BytesTypeBuilder.decomposeCQL2(dataValue, dataTypeClazz);\n                }\n            case BOOLEAN:\n                return BooleanTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case INT32:\n                return IntegerTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case DECIMAL:\n                return DecimalTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case COUNTER:\n                return CounterTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case ENUM:\n                return EnumTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case CHARACTER:\n                if (isCql3Enabled)\n                {\n                    return CharacterTypeBuilder.decompose(dataValue, dataTypeClazz);\n                }\n                else\n                {\n                    return CharacterTypeBuilder.decomposeCQL2(dataValue, dataTypeClazz);\n                }\n            case SHORT:\n                if (isCql3Enabled)\n                {\n                    return ShortTypeBuilder.decompose(dataValue, dataTypeClazz);\n                }\n                else\n                {\n                    return ShortTypeBuilder.decomposeCQL2(dataValue, dataTypeClazz);\n                }\n            case BIGINT:\n                return BigIntegerTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case TIMESTAMP:\n                return TimeStampTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case SQL_DATE:\n                return SQLDateTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case SQL_TIME:\n                return SQLTimeTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case SQL_TIMESTAMP:\n                return SQLTimeStampTypeBuilder.decompose(dataValue, dataTypeClazz);\n            case CALENDAR:\n                return CalendarTypeBuilder.decompose(dataValue, dataTypeClazz);\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Calls decompose function of respective data type of object.\n     * \n     * @param dataTypeClazz\n     *            the data type clazz\n     * @param dataValue\n     *            the data value\n     * @param mapGenericClassses\n     *            the map generic classses\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return the object\n     */\n    public static Object decompose(Class<?> dataTypeClazz, Object dataValue, List<Class<?>> mapGenericClassses,\n            boolean isCql3Enabled)\n    {\n\n        if (isCql3Enabled || (!isCql3Enabled && dataValue != null))\n        {\n            switch (getCassandraDataTypeClass(dataTypeClazz))\n            {\n            case MAP:\n                return MapTypeBuilder.decompose(dataValue, mapGenericClassses);\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Calls decompose function of respective data type of object.\n     * \n     * @param dataTypeClazz\n     *            the data type clazz\n     * @param dataValue\n     *            the data value\n     * @param mapGenericClassses\n     *            the map generic classses\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return the object\n     */\n    public static Object decompose(Class<?> dataTypeClazz, Object dataValue, Class<?> mapGenericClassses,\n            boolean isCql3Enabled)\n    {\n        if (isCql3Enabled || (!isCql3Enabled && dataValue != null))\n        {\n            switch (getCassandraDataTypeClass(dataTypeClazz))\n            {\n            case LIST:\n                return ListTypeBuilder.decompose(dataValue, dataTypeClazz, mapGenericClassses);\n            case SET:\n                return SetTypeBuilder.decompose(dataValue, dataTypeClazz, mapGenericClassses);\n            }\n        }\n        return null;\n    }\n\n    /**\n     * In case, key or value class is of type blob. Iterate and populate\n     * corresponding byte[]\n     * \n     * @param mapGenericClasses\n     *            the map generic classes\n     * @param keyClass\n     *            the key class\n     * @param valueClass\n     *            the value class\n     * @param rawMap\n     *            the raw map\n     * @return the map\n     */\n    public static Map marshalMap(List<Class<?>> mapGenericClasses, Class keyClass, Class valueClass, Map rawMap)\n    {\n        Map dataCollection = new HashMap();\n\n        if (keyClass.isAssignableFrom(BytesType.class) || valueClass.isAssignableFrom(BytesType.class))\n        {\n            Iterator iter = rawMap.keySet().iterator();\n\n            while (iter.hasNext())\n            {\n\n                Object key = iter.next();\n                Object value = rawMap.get(key);\n\n                if (keyClass.isAssignableFrom(BytesType.class))\n                {\n                    byte[] keyAsBytes = new byte[((ByteBuffer) value).remaining()];\n                    ((ByteBuffer) key).get(keyAsBytes);\n                    key = PropertyAccessorHelper.getObject(mapGenericClasses.get(0), keyAsBytes);\n                }\n\n                if (valueClass.isAssignableFrom(BytesType.class))\n                {\n                    byte[] valueAsBytes = new byte[((ByteBuffer) value).remaining()];\n                    ((ByteBuffer) value).get(valueAsBytes);\n                    value = PropertyAccessorHelper.getObject(mapGenericClasses.get(1), valueAsBytes);\n                }\n\n                dataCollection.put(key, value);\n            }\n        }\n        return dataCollection;\n    }\n\n    /**\n     * Marshal collection.\n     * \n     * @param cassandraTypeClazz\n     *            the cassandra type clazz\n     * @param result\n     *            the result\n     * @param clazz\n     *            the clazz\n     * @return the collection\n     */\n    public static Collection marshalCollection(Class cassandraTypeClazz, Collection result, Class clazz, Class resultTypeClass)\n    {\n        Collection mappedCollection = result;\n\n        if (cassandraTypeClazz.isAssignableFrom(BytesType.class))\n        {\n            mappedCollection = (Collection) PropertyAccessorHelper.getObject(resultTypeClass);\n            for (Object value : result)\n            {\n                byte[] valueAsBytes = new byte[((ByteBuffer) value).remaining()];\n                ((ByteBuffer) value).get(valueAsBytes);\n                 mappedCollection.add(PropertyAccessorHelper.getObject(clazz, valueAsBytes));\n            }\n        }\n        return mappedCollection;\n    }\n\n    /**\n     * Used to decompose and compose long type data objects.\n     */\n    private static class LongTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            return ByteBufferUtil.bytes((Long) value).array();\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            return ByteBufferUtil.toLong(buf);\n        }\n    }\n\n    /**\n     * Used to decompose and compose float type data objects.\n     */\n    private static class FloatTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            return ByteBufferUtil.bytes((Float) value).array();\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            return ByteBufferUtil.toFloat(buf);\n        }\n    }\n\n    /**\n     * Used to decompose and compose double type data objects.\n     */\n    private static class DoubleTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            return ByteBufferUtil.bytes((Double) value).array();\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            return ByteBufferUtil.toDouble(buf);\n        }\n    }\n\n    /**\n     * Used to decompose and compose string type data objects.\n     */\n    private static class StringTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n\n            return ByteBufferUtil.bytes((String) value).array();\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            try\n            {\n\n                return ByteBufferUtil.string(buf);\n            }\n            catch (CharacterCodingException e)\n            {\n                log.warn(\"Error while setting field value, Caused by: .\", e);\n            }\n            return null;\n        }\n    }\n\n    /**\n     * Used to decompose and compose bytes type data objects.\n     */\n    private static class BytesTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            ByteAccessor accessor = new ByteAccessor();\n            return accessor.toBytes(value);\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            IntegerAccessor accessor = new IntegerAccessor();\n            int thriftColumnValue = accessor.fromBytes(byte.class, (byte[]) value);\n            ByteAccessor byteAccessor = new ByteAccessor();\n            return byteAccessor.fromString(clazz, String.valueOf(thriftColumnValue));\n        }\n\n        /**\n         * Decompose cq l2.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decomposeCQL2(Object value, Class clazz)\n        {\n            ByteAccessor byteAccessor = new ByteAccessor();\n            return byteAccessor.fromBytes(clazz, (byte[]) value);\n        }\n\n    }\n\n    /**\n     * Used to decompose and compose decimal type data objects.\n     */\n    private static class DecimalTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            return DecimalType.instance.decompose((BigDecimal) value).array();\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            return DecimalType.instance.compose(buf);\n        }\n    }\n\n    /**\n     * Used to decompose and compose boolean type data objects.\n     */\n    private static class BooleanTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            return BooleanType.instance.decompose((Boolean) value).array();\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            return BooleanType.instance.compose(buf);\n        }\n    }\n\n    /**\n     * Used to decompose and compose UUID type data objects.\n     */\n    private static class UUIDTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            return UUIDType.instance.decompose((UUID) value).array();\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            return UUIDType.instance.compose(buf);\n        }\n    }\n\n    /**\n     * Used to decompose and compose ascii type data objects.\n     */\n    private static class AsciiTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            return AsciiType.instance.decompose((String) value).array();\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            return AsciiType.instance.compose(buf);\n        }\n    }\n\n    /**\n     * Used to decompose and compose integer type data objects.\n     */\n    private static class IntegerTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            return ByteBufferUtil.bytes((Integer) value).array();\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            return ByteBufferUtil.toInt(buf);\n        }\n    }\n\n    /**\n     * Used to decompose and compose set type data objects.\n     */\n    private static class SetTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @param mapGenericClassses\n         *            the map generic classses\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz, Class<?> mapGenericClassses)\n        {\n            Class<?> valueValidationClass = CassandraValidationClassMapper.getValidationClassInstance(\n                    mapGenericClassses, true);\n\n            Object valueClassInstance;\n            try\n            {\n                valueClassInstance = valueValidationClass.getDeclaredField(\"instance\").get(null);\n                // false added after 2.1.3 upgrade (isMulticell check)\n                SetType setType = SetType.getInstance((AbstractType) valueClassInstance, false);\n                return setType.decompose((Set) value).array();\n            }\n            catch (NoSuchFieldException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", clazz.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n            catch (SecurityException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", clazz.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n            catch (IllegalArgumentException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", clazz.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n            catch (IllegalAccessException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", clazz.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @param mapGenericClassses\n         *            the map generic classses\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz, Class<?> genericClass)\n        {\n            Class<?> valueValidationClass = CassandraValidationClassMapper.getValidationClassInstance(genericClass,\n                    true);\n            TypeSerializer valueClassInstance = CassandraValidationClassMapper.getValidationSerializerClassInstance(\n                    genericClass, true);\n            Collection outputCollection = new HashSet();\n            try\n            {\n                outputCollection = new HashSet();\n                Comparator<ByteBuffer> test = null;\n\t\t\t\tSetSerializer setSerializer = SetSerializer.getInstance(valueClassInstance, test );\n                outputCollection.addAll((Collection) setSerializer.deserializeForNativeProtocol((ByteBuffer) value, ProtocolVersion.V2));\n                return marshalCollection(valueValidationClass, outputCollection, genericClass, outputCollection.getClass());\n            }\n            catch (SecurityException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", clazz.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n            catch (IllegalArgumentException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", clazz.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n        }\n    }\n\n    /**\n     * Used to decompose and compose map type data objects.\n     */\n    private static class MapTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param mapGenericClasses\n         *            the map generic classes\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, List<Class<?>> mapGenericClasses)\n        {\n            Class keyClass = CassandraValidationClassMapper.getValidationClassInstance(mapGenericClasses.get(0), true);\n            Class valueClass = CassandraValidationClassMapper\n                    .getValidationClassInstance(mapGenericClasses.get(1), true);\n\n            try\n            {\n                Object keyClassInstance = keyClass.getDeclaredField(\"instance\").get(null);\n                Object valueClassInstance = valueClass.getDeclaredField(\"instance\").get(null);\n\n                MapType mapType = MapType.getInstance((AbstractType) keyClassInstance,\n                        (AbstractType) valueClassInstance, false);\n\n                return mapType.decompose((Map) value).array();\n            }\n            catch (NoSuchFieldException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", keyClass.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n            catch (SecurityException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", keyClass.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n            catch (IllegalArgumentException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", keyClass.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n            catch (IllegalAccessException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", keyClass.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param mapGenericClasses\n         *            the map generic classes\n         * @return the object\n         */\n        private static Object decompose(Object value, List<Class<?>> mapGenericClasses)\n        {\n            Class keyClass = null;\n            Class valueClass = null;\n            try\n            {\n\n                keyClass = CassandraValidationClassMapper.getValidationClassInstance(mapGenericClasses.get(0), true);\n                valueClass = CassandraValidationClassMapper.getValidationClassInstance(mapGenericClasses.get(1), true);\n\n                TypeSerializer keyClassInstance = CassandraValidationClassMapper.getValidationSerializerClassInstance(\n                        mapGenericClasses.get(0), true);\n                TypeSerializer valueClassInstance = CassandraValidationClassMapper\n                        .getValidationSerializerClassInstance(mapGenericClasses.get(1), true);\n\n                Map rawMap = new HashMap();\n                MapSerializer mapSerializer = MapSerializer.getInstance(keyClassInstance, valueClassInstance, null);\n\n                rawMap.putAll(mapSerializer.deserializeForNativeProtocol((ByteBuffer) value, ProtocolVersion.V2));\n\n                Map dataCollection = marshalMap(mapGenericClasses, keyClass, valueClass, rawMap);\n                return dataCollection.isEmpty() ? rawMap : dataCollection;\n            }\n            catch (SecurityException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", keyClass.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n            catch (IllegalArgumentException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", keyClass.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n        }\n    }\n\n    /**\n     * Used to decompose and compose list type data objects.\n     */\n    private static class ListTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @param mapGenericClassses\n         *            the map generic classses\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz, Class<?> mapGenericClassses)\n        {\n            Class<?> valueValidationClass = CassandraValidationClassMapper.getValidationClassInstance(\n                    mapGenericClassses, true);\n\n            Object valueClassInstance;\n            try\n            {\n                valueClassInstance = valueValidationClass.getDeclaredField(\"instance\").get(null);\n                ListType listType = ListType.getInstance((AbstractType) valueClassInstance, false);\n                return listType.decompose((List) value).array();\n            }\n            catch (NoSuchFieldException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", clazz.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n            catch (SecurityException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", clazz.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n            catch (IllegalArgumentException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", clazz.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n            catch (IllegalAccessException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", clazz.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @param mapGenericClassses\n         *            the map generic classses\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz, Class<?> genericClass)\n        {\n            Class<?> valueValidationClass = CassandraValidationClassMapper.getValidationClassInstance(genericClass,\n                    true);\n            TypeSerializer valueClassInstance = CassandraValidationClassMapper.getValidationSerializerClassInstance(\n                    genericClass, true);\n            Collection outputCollection = new ArrayList();\n            try\n            {\n                ListSerializer listSerializer = ListSerializer.getInstance(valueClassInstance);\n                outputCollection\n                        .addAll((Collection) listSerializer.deserializeForNativeProtocol((ByteBuffer) value, ProtocolVersion.V2));\n\n                return marshalCollection(valueValidationClass, outputCollection, genericClass, outputCollection.getClass());\n            }\n            catch (SecurityException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", clazz.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n            catch (IllegalArgumentException e)\n            {\n                log.error(\"Error while retrieving field{} value via CQL, Caused by: .\", clazz.getSimpleName(), e);\n                throw new PersistenceException(e);\n            }\n        }\n    }\n\n    /**\n     * Used to decompose and compose counter type data objects.\n     */\n    private static class CounterTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            return CounterColumnType.instance.decompose((Long) value).array();\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            return CounterColumnType.instance.compose(buf);\n        }\n    }\n\n    /**\n     * Used to decompose and compose date type data objects.\n     */\n    private static class DateTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            return DateType.instance.decompose((Date) value).array();\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            return DateType.instance.compose(buf);\n        }\n    }\n\n    /**\n     * Used to decompose and compose enum type data objects.\n     */\n    private static class EnumTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            EnumAccessor accessor = new EnumAccessor();\n            return accessor.toBytes(value);\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            EnumAccessor accessor = new EnumAccessor();\n            return accessor.fromBytes(clazz, ((byte[]) value));\n        }\n    }\n\n    /**\n     * Used to decompose and compose character type data objects.\n     */\n    private static class CharacterTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            CharAccessor accessor = new CharAccessor();\n            return accessor.toBytes(value);\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            CharAccessor accessor = new CharAccessor();\n            return accessor.fromString(clazz, new String((byte[]) value));\n        }\n\n        /**\n         * Decompose cq l2.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decomposeCQL2(Object value, Class clazz)\n        {\n            CharAccessor charAccessor = new CharAccessor();\n            return charAccessor.fromBytes(clazz, (byte[]) value);\n        }\n    }\n\n    /**\n     * Used to decompose and compose short type data objects.\n     */\n    private static class ShortTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            ShortAccessor accessor = new ShortAccessor();\n            return accessor.toBytes(value);\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            IntegerAccessor accessor = new IntegerAccessor();\n            int thriftColumnValue = accessor.fromBytes(short.class, (byte[]) value);\n            ShortAccessor shortAccessor = new ShortAccessor();\n            return shortAccessor.fromString(clazz, String.valueOf(thriftColumnValue));\n        }\n\n        /**\n         * Decompose cq l2.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decomposeCQL2(Object value, Class clazz)\n        {\n            ShortAccessor shortAccessor = new ShortAccessor();\n            return shortAccessor.fromBytes(clazz, (byte[]) value);\n        }\n    }\n\n    /**\n     * Used to decompose and compose big integer type data objects.\n     */\n    private static class BigIntegerTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            return IntegerType.instance.decompose((BigInteger) value).array();\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            return IntegerType.instance.compose(buf);\n        }\n    }\n\n    /**\n     * Used to decompose and compose timestamp type data objects.\n     */\n    private static class TimeStampTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            DateAccessor accessor = new DateAccessor();\n            return accessor.toBytes(value);\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            DateAccessor accessor = new DateAccessor();\n            return accessor.fromBytes(clazz, ((byte[]) value));\n        }\n    }\n\n    /**\n     * Used to decompose and compose sql date type data objects.\n     */\n    private static class SQLDateTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            SQLDateAccessor accessor = new SQLDateAccessor();\n            return accessor.toBytes(value);\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            SQLDateAccessor accessor = new SQLDateAccessor();\n            return accessor.fromBytes(clazz, ((byte[]) value));\n        }\n    }\n\n    /**\n     * Used to decompose and compose sql time type data objects.\n     */\n    private static class SQLTimeTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            SQLTimeAccessor accessor = new SQLTimeAccessor();\n            return accessor.toBytes(value);\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            SQLTimeAccessor accessor = new SQLTimeAccessor();\n            return accessor.fromBytes(clazz, ((byte[]) value));\n        }\n    }\n\n    /**\n     * Used to decompose and compose sql timestamp type data objects.\n     */\n    private static class SQLTimeStampTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            SQLTimestampAccessor accessor = new SQLTimestampAccessor();\n            return accessor.toBytes(value);\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            SQLTimestampAccessor accessor = new SQLTimestampAccessor();\n            return accessor.fromBytes(clazz, ((byte[]) value));\n        }\n    }\n\n    /**\n     * Used to decompose and compose calendar type data objects.\n     */\n    private static class CalendarTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            CalendarAccessor accessor = new CalendarAccessor();\n            return accessor.toBytes(value);\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            CalendarAccessor accessor = new CalendarAccessor();\n            return accessor.fromBytes(clazz, ((byte[]) value));\n        }\n    }\n\n    /**\n     * Used to decompose and compose bytes array type data objects.\n     */\n    private static class BytesArrayTypeBuilder\n    {\n\n        /**\n         * Compose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the byte[]\n         */\n        private static byte[] compose(Object value, Class clazz)\n        {\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            return ByteBufferUtil.hexToBytes((String) value).array();\n        }\n\n        /**\n         * Decompose.\n         * \n         * @param value\n         *            the value\n         * @param clazz\n         *            the clazz\n         * @return the object\n         */\n        private static Object decompose(Object value, Class clazz)\n        {\n            ByteBuffer buf = ByteBuffer.wrap((byte[]) value, 0, ((byte[]) value).length);\n            return ByteBufferUtil.bytesToHex(buf);\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.schemamanager;\n\nimport java.io.UnsupportedEncodingException;\nimport java.lang.reflect.Field;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.CharacterCodingException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport javax.persistence.Embeddable;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.Type.PersistenceType;\n\nimport org.apache.cassandra.db.marshal.CounterColumnType;\nimport org.apache.cassandra.db.marshal.ListType;\nimport org.apache.cassandra.db.marshal.MapType;\nimport org.apache.cassandra.db.marshal.SetType;\nimport org.apache.cassandra.db.marshal.UTF8Type;\nimport org.apache.cassandra.locator.NetworkTopologyStrategy;\nimport org.apache.cassandra.locator.SimpleStrategy;\nimport org.apache.cassandra.thrift.AuthenticationRequest;\nimport org.apache.cassandra.thrift.Cassandra;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.CqlMetadata;\nimport org.apache.cassandra.thrift.CqlResult;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.thrift.TException;\nimport org.apache.thrift.protocol.TBinaryProtocol;\nimport org.apache.thrift.protocol.TProtocol;\nimport org.apache.thrift.transport.TFramedTransport;\nimport org.apache.thrift.transport.TSocket;\nimport org.apache.thrift.transport.TTransport;\nimport org.apache.thrift.transport.TTransportException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.config.CassandraPropertyReader;\nimport com.impetus.client.cassandra.config.CassandraPropertyReader.CassandraSchemaMetadata;\nimport com.impetus.client.cassandra.index.CassandraIndexHelper;\nimport com.impetus.client.cassandra.thrift.CQLTranslator;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Schema;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Schema.DataCenter;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Schema.Table;\nimport com.impetus.kundera.configure.schema.CollectionColumnInfo;\nimport com.impetus.kundera.configure.schema.ColumnInfo;\nimport com.impetus.kundera.configure.schema.EmbeddedColumnInfo;\nimport com.impetus.kundera.configure.schema.IndexInfo;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.configure.schema.TableInfo;\nimport com.impetus.kundera.configure.schema.api.AbstractSchemaManager;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata.Type;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.Relation.ForeignKey;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * Manages auto schema operation defined in {@code ScheamOperationType}.\n * \n * @author Kuldeep.kumar\n * \n */\npublic class CassandraSchemaManager extends AbstractSchemaManager implements SchemaManager\n{\n\n    /** The Constant STANDARDCOLUMNFAMILY. */\n    private static final String STANDARDCOLUMNFAMILY = \"Standard\";\n\n    /** Cassandra client variable holds the client. */\n    private Cassandra.Client cassandra_client;\n\n    /** The cql_version. */\n    private String cql_version = CassandraConstants.CQL_VERSION_2_0;\n\n    /**\n     * logger used for logging statement.\n     */\n    private static final Logger log = LoggerFactory.getLogger(CassandraSchemaManager.class);\n\n    /** The csmd. */\n    private CassandraSchemaMetadata csmd = CassandraPropertyReader.csmd;\n\n    /** The tables. */\n    private List<Table> tables;\n\n    /** The created keyspaces. */\n    private List<String> createdKeyspaces = new ArrayList<String>();\n\n    /** The created userTypes. */\n    private List<String> createdPuEmbeddables = new ArrayList<String>();\n\n    /**\n     * Instantiates a new cassandra schema manager.\n     * \n     * @param clientFactory\n     *            the configured client clientFactory\n     * @param puProperties\n     *            the pu properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public CassandraSchemaManager(String clientFactory, Map<String, Object> puProperties,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(clientFactory, puProperties, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#exportSchema\n     * (java.lang.String, java.util.List)\n     */\n    @Override\n    /**\n     * Export schema handles the handleOperation method.\n     */\n    public void exportSchema(final String persistenceUnit, List<TableInfo> schemas)\n    {\n        cql_version = externalProperties != null ? (String) externalProperties.get(CassandraConstants.CQL_VERSION)\n                : CassandraConstants.CQL_VERSION_2_0;\n        super.exportSchema(persistenceUnit, schemas);\n    }\n\n    /**\n     * drop schema method drop the table from keyspace.\n     * \n     */\n    public void dropSchema()\n    {\n        if (operation != null && operation.equalsIgnoreCase(\"create-drop\"))\n        {\n            try\n            {\n                dropKeyspaceOrCFs();\n            }\n            catch (Exception ex)\n            {\n                log.error(\"Error during dropping schema in cassandra, Caused by: .\", ex);\n                throw new SchemaGenerationException(ex, \"Cassandra\");\n            }\n        }\n        cassandra_client = null;\n    }\n\n    /**\n     * Drop keyspace or c fs.\n     * \n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     * @throws TException\n     *             the t exception\n     * @throws Exception\n     *             the exception\n     */\n    private void dropKeyspaceOrCFs() throws InvalidRequestException, SchemaDisagreementException, TException, Exception\n    {\n        if (createdKeyspaces.contains(databaseName))// drop if created during\n                                                    // create-drop call.\n        {\n            cassandra_client.system_drop_keyspace(databaseName);\n        }\n        else\n        {\n            cassandra_client.set_keyspace(databaseName);\n            for (TableInfo tableInfo : tableInfos)\n            {\n                dropColumnFamily(tableInfo);\n            }\n        }\n    }\n\n    /**\n     * Drops column family specified in table info.\n     * \n     * @param tableInfo\n     *            the table info\n     * @throws Exception\n     *             the exception\n     */\n    private void dropColumnFamily(TableInfo tableInfo) throws Exception\n    {\n        if (isCql3Enabled(tableInfo))\n        {\n            dropTableUsingCql(tableInfo);\n        }\n        else\n        {\n            cassandra_client.system_drop_column_family(tableInfo.getTableName());\n        }\n    }\n\n    /**\n     * create_drop method creates schema and table for the list of tableInfos.\n     * \n     * @param tableInfos\n     *            list of TableInfos.\n     */\n    protected void create_drop(List<TableInfo> tableInfos)\n    {\n        create(tableInfos);\n    }\n\n    /**\n     * Creates schema and table for the list of tableInfos.\n     * \n     * @param tableInfos\n     *            list of TableInfos.\n     */\n    protected void create(List<TableInfo> tableInfos)\n    {\n        try\n        {\n            createOrUpdateKeyspace(tableInfos);\n        }\n        catch (Exception ex)\n        {\n            throw new SchemaGenerationException(ex);\n        }\n    }\n\n    /**\n     * Creates schema and table for the list of tableInfos.\n     * \n     * @param tableInfos\n     *            list of TableInfos.\n     * @throws Exception\n     *             the exception\n     */\n    private void createOrUpdateKeyspace(List<TableInfo> tableInfos) throws Exception\n    {\n        KsDef ksDef = onCreateKeyspace(); // create keyspace event.\n        createColumnFamilies(tableInfos, ksDef); // create column family event.\n    }\n\n    /**\n     * On create keyspace.\n     * \n     * @return the ks def\n     * @throws Exception\n     *             the exception\n     */\n    private KsDef onCreateKeyspace() throws Exception\n    {\n        try\n        {\n            createdKeyspaces.add(databaseName);\n            createKeyspace();\n        }\n        catch (InvalidRequestException irex)\n        {\n            // Ignore and add a log.debug\n            // keyspace already exists.\n            // remove from list if already created.\n            createdKeyspaces.remove(databaseName);\n        }\n        cassandra_client.set_keyspace(databaseName);\n        return cassandra_client.describe_keyspace(databaseName);\n    }\n\n    /**\n     * Creates keyspace.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    private void createKeyspace() throws Exception\n    {\n        if (cql_version != null && cql_version.equals(CassandraConstants.CQL_VERSION_3_0))\n        {\n            onCql3CreateKeyspace();\n        }\n        else\n        {\n            Map<String, String> strategy_options = new HashMap<String, String>();\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            KsDef ksDef = new KsDef(databaseName, csmd.getPlacement_strategy(databaseName), cfDefs);\n            setProperties(ksDef, strategy_options);\n            ksDef.setStrategy_options(strategy_options);\n            cassandra_client.system_add_keyspace(ksDef);\n        }\n    }\n\n    /**\n     * On cql3 create keyspace.\n     * \n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     * @throws TException\n     *             the t exception\n     * @throws UnsupportedEncodingException\n     *             the unsupported encoding exception\n     */\n    private void onCql3CreateKeyspace() throws InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException, TException, UnsupportedEncodingException\n    {\n        String createKeyspace = CQLTranslator.CREATE_KEYSPACE;\n        String placement_strategy = csmd.getPlacement_strategy(databaseName);\n        String replication_conf = CQLTranslator.SIMPLE_REPLICATION;\n        createKeyspace = createKeyspace.replace(\"$KEYSPACE\", Constants.ESCAPE_QUOTE + databaseName\n                + Constants.ESCAPE_QUOTE);\n\n        Schema schema = CassandraPropertyReader.csmd.getSchema(databaseName);\n\n        if (schema != null && schema.getName() != null && schema.getName().equalsIgnoreCase(databaseName)\n                && schema.getSchemaProperties() != null)\n        {\n            Properties schemaProperties = schema.getSchemaProperties();\n            if (placement_strategy.equalsIgnoreCase(SimpleStrategy.class.getSimpleName())\n                    || placement_strategy.equalsIgnoreCase(SimpleStrategy.class.getName()))\n            {\n                String replicationFactor = schemaProperties.getProperty(CassandraConstants.REPLICATION_FACTOR,\n                        CassandraConstants.DEFAULT_REPLICATION_FACTOR);\n\n                replication_conf = replication_conf.replace(\"$REPLICATION_FACTOR\", replicationFactor);\n                createKeyspace = createKeyspace.replace(\"$CLASS\", placement_strategy);\n            }\n            else if (placement_strategy.equalsIgnoreCase(NetworkTopologyStrategy.class.getSimpleName())\n                    || placement_strategy.equalsIgnoreCase(NetworkTopologyStrategy.class.getName()))\n            {\n\n                if (schema.getDataCenters() != null && !schema.getDataCenters().isEmpty())\n                {\n                    StringBuilder builder = new StringBuilder();\n\n                    for (DataCenter dc : schema.getDataCenters())\n                    {\n                        builder.append(CQLTranslator.QUOTE_STR);\n                        builder.append(dc.getName());\n                        builder.append(CQLTranslator.QUOTE_STR);\n                        builder.append(\":\");\n                        builder.append(dc.getValue());\n                        builder.append(CQLTranslator.COMMA_STR);\n                    }\n\n                    builder.delete(builder.lastIndexOf(CQLTranslator.COMMA_STR), builder.length());\n\n                    replication_conf = builder.toString();\n                }\n            }\n\n            createKeyspace = createKeyspace.replace(\"$CLASS\", placement_strategy);\n            createKeyspace = createKeyspace.replace(\"$REPLICATION\", replication_conf);\n\n            boolean isDurableWrites = Boolean.parseBoolean(schemaProperties.getProperty(\n                    CassandraConstants.DURABLE_WRITES, \"true\"));\n            createKeyspace = createKeyspace.replace(\"$DURABLE_WRITES\", isDurableWrites + \"\");\n        }\n        else\n        {\n            createKeyspace = createKeyspace.replace(\"$CLASS\", placement_strategy);\n            replication_conf = replication_conf.replace(\"$REPLICATION_FACTOR\",\n                    (CharSequence) externalProperties.getOrDefault(CassandraConstants.REPLICATION_FACTOR,\n                    \t\tCassandraConstants.DEFAULT_REPLICATION_FACTOR));\n            createKeyspace = createKeyspace.replace(\"$REPLICATION\", replication_conf);\n            createKeyspace = createKeyspace.replace(\"$DURABLE_WRITES\", \"true\");\n        }\n        cassandra_client.execute_cql3_query(ByteBuffer.wrap(createKeyspace.getBytes(Constants.CHARSET_UTF8)),\n                Compression.NONE, ConsistencyLevel.ONE);\n        KunderaCoreUtils.printQuery(createKeyspace, showQuery);\n    }\n\n    /**\n     * Creates the column families.\n     * \n     * @param tableInfos\n     *            the table infos\n     * @param ksDef\n     *            the ks def\n     * @throws Exception\n     *             the exception\n     */\n    private void createColumnFamilies(List<TableInfo> tableInfos, KsDef ksDef) throws Exception\n    {\n        for (TableInfo tableInfo : tableInfos)\n        {\n            if (isCql3Enabled(tableInfo))\n            {\n                createOrUpdateUsingCQL3(tableInfo, ksDef);\n                createIndexUsingCql(tableInfo);\n            }\n            else\n            {\n                createOrUpdateColumnFamily(tableInfo, ksDef);\n            }\n\n            // Create Inverted Indexed Table if required.\n            createInvertedIndexTable(tableInfo, ksDef);\n        }\n    }\n\n    /**\n     * Creates the or update column family.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param ksDef\n     *            the ks def\n     * @throws Exception\n     *             the exception\n     */\n    private void createOrUpdateColumnFamily(TableInfo tableInfo, KsDef ksDef) throws Exception\n    {\n        MetaDataHandler handler = new MetaDataHandler();\n\n        if (containsCompositeKey(tableInfo))\n        {\n            validateCompoundKey(tableInfo);\n            createOrUpdateUsingCQL3(tableInfo, ksDef);\n\n            // After successful schema operation, perform index creation.\n            createIndexUsingCql(tableInfo);\n        }\n        else if (containsCollectionColumns(tableInfo) || isCql3Enabled(tableInfo))\n        {\n            createOrUpdateUsingCQL3(tableInfo, ksDef);\n            createIndexUsingCql(tableInfo);\n        }\n        else\n        {\n\n            CfDef cf_def = handler.getTableMetadata(tableInfo);\n            try\n            {\n                cassandra_client.system_add_column_family(cf_def);\n            }\n            catch (InvalidRequestException irex)\n            {\n                updateExistingColumnFamily(tableInfo, ksDef, irex);\n            }\n        }\n    }\n\n    /**\n     * Contains collection columns.\n     * \n     * @param tableInfo\n     *            the table info\n     * @return true, if successful\n     */\n    private boolean containsCollectionColumns(TableInfo tableInfo)\n    {\n        return !tableInfo.getCollectionColumnMetadatas().isEmpty();\n    }\n\n    /**\n     * Contains embedded columns.\n     * \n     * @param tableInfo\n     *            the table info\n     * @return true, if successful\n     */\n    private boolean containsEmbeddedColumns(TableInfo tableInfo)\n    {\n        return !tableInfo.getEmbeddedColumnMetadatas().isEmpty();\n    }\n\n    /**\n     * Contains element collection columns.\n     * \n     * @param tableInfo\n     *            the table info\n     * @return true, if successful\n     */\n    private boolean containsElementCollectionColumns(TableInfo tableInfo)\n    {\n        return !tableInfo.getElementCollectionMetadatas().isEmpty();\n    }\n\n    /**\n     * Contains composite key.\n     * \n     * @param tableInfo\n     *            the table info\n     * @return true, if successful\n     */\n    private boolean containsCompositeKey(TableInfo tableInfo)\n    {\n        return tableInfo.getTableIdType() != null && tableInfo.getTableIdType().isAnnotationPresent(Embeddable.class);\n    }\n\n    /**\n     * Update existing column family.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param ksDef\n     *            the ks def\n     * @param irex\n     *            the irex\n     * @throws Exception\n     *             the exception\n     */\n    private void updateExistingColumnFamily(TableInfo tableInfo, KsDef ksDef, InvalidRequestException irex)\n            throws Exception\n    {\n        StringBuilder builder = new StringBuilder(\"^Cannot add already existing (?:column family|table) .*$\");\n\n        if (irex.getWhy() != null && irex.getWhy().matches(builder.toString()))\n        {\n            SchemaOperationType operationType = SchemaOperationType.getInstance(operation);\n            switch (operationType)\n            {\n            case create:\n                handleCreate(tableInfo, ksDef);\n                break;\n\n            case createdrop:\n                handleCreate(tableInfo, ksDef);\n                break;\n\n            case update:\n                if (isCql3Enabled(tableInfo))\n                {\n                    for (ColumnInfo column : tableInfo.getColumnMetadatas())\n                    {\n                        addColumnToTable(tableInfo, column);\n                    }\n                    createIndexUsingCql(tableInfo);\n                }\n                else\n                {\n                    updateTable(ksDef, tableInfo);\n                }\n                break;\n\n            default:\n                break;\n            }\n        }\n        else\n        {\n            log.error(\"Error occurred while creating table {}, Caused by: {}.\", tableInfo.getTableName(), irex);\n            throw new SchemaGenerationException(\"Error occurred while creating table \" + tableInfo.getTableName(),\n                    irex, \"Cassandra\", databaseName);\n        }\n    }\n\n    /**\n     * Handle create.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param ksDef\n     *            the ks def\n     * @throws Exception\n     *             the exception\n     */\n    private void handleCreate(TableInfo tableInfo, KsDef ksDef) throws Exception\n    {\n        if (containsCompositeKey(tableInfo))\n        {\n            validateCompoundKey(tableInfo);\n            // First drop existing column family.\n            dropTableUsingCql(tableInfo);\n        }\n        else\n        {\n            onDrop(tableInfo);\n        }\n        createOrUpdateColumnFamily(tableInfo, ksDef);\n    }\n\n    /**\n     * On drop.\n     * \n     * @param tableInfo\n     *            the table info\n     * @throws Exception\n     *             the exception\n     */\n    private void onDrop(TableInfo tableInfo) throws Exception\n    {\n        dropColumnFamily(tableInfo);\n        dropInvertedIndexTable(tableInfo);\n    }\n\n    /**\n     * update method update schema and table for the list of tableInfos.\n     * \n     * @param tableInfos\n     *            list of TableInfos.\n     */\n    protected void update(List<TableInfo> tableInfos)\n    {\n        try\n        {\n            createOrUpdateKeyspace(tableInfos);\n        }\n        catch (Exception ex)\n        {\n            log.error(\"Error occurred while creating {}, Caused by: .\", databaseName, ex);\n            throw new SchemaGenerationException(ex);\n        }\n    }\n\n    /**\n     * validate method validate schema and table for the list of tableInfos.\n     * \n     * @param tableInfos\n     *            list of TableInfos.\n     */\n    protected void validate(List<TableInfo> tableInfos)\n    {\n        try\n        {\n            KsDef ksDef = cassandra_client.describe_keyspace(databaseName);\n            onValidateTables(tableInfos, ksDef);\n        }\n        catch (Exception ex)\n        {\n            log.error(\"Error occurred while validating {}, Caused by: .\", databaseName, ex);\n            throw new SchemaGenerationException(ex);\n        }\n    }\n\n    /**\n     * initiate client method initiates the client.\n     * \n     * @return boolean value ie client started or not.\n     * \n     */\n    protected boolean initiateClient()\n    {\n        Throwable message = null;\n\n        for (String host : hosts)\n        {\n            if (host == null || !StringUtils.isNumeric(port) || port.isEmpty())\n            {\n                log.error(\"Host or port should not be null, Port should be numeric.\");\n                throw new IllegalArgumentException(\"Host or port should not be null, Port should be numeric.\");\n            }\n            int thriftPort = externalProperties.get(CassandraConstants.THRIFT_PORT) != null ? Integer\n                    .parseInt((String) externalProperties.get(CassandraConstants.THRIFT_PORT)) : Integer.parseInt(port);\n            TSocket socket = new TSocket(host, thriftPort);\n            TTransport transport = new TFramedTransport(socket);\n            TProtocol protocol = new TBinaryProtocol(transport, true, true);\n            cassandra_client = new Cassandra.Client(protocol);\n            try\n            {\n                if (!socket.isOpen())\n                {\n                    socket.open();\n                    if (userName != null)\n                    {\n                        Map<String, String> credentials = new HashMap<String, String>();\n                        credentials.put(\"username\", userName);\n                        credentials.put(\"password\", password);\n                        AuthenticationRequest auth_request = new AuthenticationRequest(credentials);\n                        cassandra_client.login(auth_request);\n                    }\n                }\n                return true;\n            }\n            catch (TTransportException e)\n            {\n                message = e;\n                log.warn(\"Error while opening socket for host {}, skipping for next available node \", host);\n            }\n            catch (Exception e)\n            {\n                log.error(\"Error during creating schema in cassandra, Caused by: .\", e);\n                throw new SchemaGenerationException(e, \"Cassandra\");\n            }\n        }\n        throw new SchemaGenerationException(\"Error while opening socket, Caused by: .\", message, \"Cassandra\");\n    }\n\n    /**\n     * Creates (or updates) a column family definition using CQL 3 Should\n     * replace onCompoundKey.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param ksDef\n     *            the ks def\n     * @throws Exception\n     *             the exception\n     */\n    private void createOrUpdateUsingCQL3(TableInfo tableInfo, KsDef ksDef) throws Exception\n    {\n        try\n        {\n\n            cassandra_client.set_cql_version(CassandraConstants.CQL_VERSION_3_0);\n            cassandra_client.set_keyspace(databaseName);\n            MetaDataHandler handler = new MetaDataHandler();\n            CQLTranslator translator = new CQLTranslator();\n            String columnFamilyQuery = CQLTranslator.CREATE_COLUMNFAMILY_QUERY;\n            columnFamilyQuery = StringUtils.replace(columnFamilyQuery, CQLTranslator.COLUMN_FAMILY, translator\n                    .ensureCase(new StringBuilder(), tableInfo.getTableName(), false).toString());\n\n            List<ColumnInfo> columns = tableInfo.getColumnMetadatas();\n\n            Properties cfProperties = getColumnFamilyProperties(tableInfo);\n\n            String defaultValidationClass = cfProperties != null ? cfProperties\n                    .getProperty(CassandraConstants.DEFAULT_VALIDATION_CLASS) : null;\n\n            StringBuilder queryBuilder = new StringBuilder();\n\n            // For normal columns\n            boolean isCounterColumnType = isCounterColumnType(tableInfo, defaultValidationClass);\n            onCompositeColumns(translator, columns, queryBuilder, null, isCounterColumnType);\n            onCollectionColumns(translator, tableInfo.getCollectionColumnMetadatas(), queryBuilder);\n\n            // ideally it will always be one as more super column families\n            // are not allowed with compound/composite key.\n            List<EmbeddedColumnInfo> compositeColumns = tableInfo.getEmbeddedColumnMetadatas();\n            EmbeddableType compoEmbeddableType = null;\n\n            if (!compositeColumns.isEmpty() && tableInfo.getTableIdType().isAnnotationPresent(Embeddable.class))\n            {\n                EmbeddedColumnInfo compositeId = null;\n                for (EmbeddedColumnInfo compositeCol : compositeColumns)\n                {\n                    if (compositeCol.getEmbeddedColumnName().equals(tableInfo.getIdColumnName()))\n                    {\n                        compositeId = compositeCol;\n                        break;\n                    }\n                }\n                MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                        puMetadata.getPersistenceUnitName());\n                // get list of names of all embeddables in compositeid\n                List compositeEmbeddables = new ArrayList<String>();\n                getCompositeIdEmbeddables(compositeId.getEmbeddable(), compositeEmbeddables, metaModel);\n\n                if (compositeColumns.size() > 1 || !tableInfo.getElementCollectionMetadatas().isEmpty())\n                {\n                    createTypeforEmbeddables(compositeEmbeddables);\n                    onEmbeddedColumns(translator, tableInfo, queryBuilder, compositeEmbeddables);\n                    onElementCollectionColumns(translator, tableInfo.getElementCollectionMetadatas(), queryBuilder);\n\n                }\n\n                compoEmbeddableType = compositeId.getEmbeddable();\n                onCompositeColumns(translator, compositeId.getColumns(), queryBuilder, columns, isCounterColumnType);\n            }\n            else\n            {\n                if (!compositeColumns.isEmpty() || !tableInfo.getElementCollectionMetadatas().isEmpty())\n                {\n                    // embedded create udts\n                    // check for multiple embedded and collections in embedded\n                    // entity\n                    createTypeforEmbeddables(new ArrayList<String>());\n                    onEmbeddedColumns(translator, tableInfo, queryBuilder, new ArrayList<String>());\n                    onElementCollectionColumns(translator, tableInfo.getElementCollectionMetadatas(), queryBuilder);\n\n                }\n                String dataType = CassandraValidationClassMapper.getValidationClass(tableInfo.getTableIdType(), true);\n                String cqlType = translator.getCQLType(dataType);\n                translator.appendColumnName(queryBuilder, tableInfo.getIdColumnName(), cqlType);\n                queryBuilder.append(Constants.SPACE_COMMA);\n            }\n\n            queryBuilder = replaceColumnsAndStripLastChar(columnFamilyQuery, queryBuilder);\n\n            // append primary key clause\n            queryBuilder.append(translator.ADD_PRIMARYKEY_CLAUSE);\n\n            // To ensure field ordering\n            // check if embedded is also an id\n            if (compoEmbeddableType != null && tableInfo.getTableIdType().isAnnotationPresent(Embeddable.class))\n            {\n                Field[] fields = tableInfo.getTableIdType().getDeclaredFields();\n                StringBuilder primaryKeyBuilder = new StringBuilder();\n                appendPrimaryKey(translator, compoEmbeddableType, fields, primaryKeyBuilder);\n                // should not be null.\n                primaryKeyBuilder.deleteCharAt(primaryKeyBuilder.length() - 1);\n                queryBuilder = new StringBuilder(StringUtils.replace(queryBuilder.toString(), CQLTranslator.COLUMNS,\n                        primaryKeyBuilder.toString()));\n\n                StringBuilder clusterKeyOrderingBuilder = new StringBuilder();\n                appendClusteringOrder(translator, compositeColumns.get(0).getColumns(), clusterKeyOrderingBuilder,\n                        primaryKeyBuilder);\n                if (clusterKeyOrderingBuilder.length() != 0)\n                {\n                    // append cluster key order clause\n                    queryBuilder.append(translator.CREATE_COLUMNFAMILY_CLUSTER_ORDER.replace(CQLTranslator.COLUMNS,\n                            clusterKeyOrderingBuilder.toString()));\n                }\n            }\n            else\n            {\n                queryBuilder = new StringBuilder(StringUtils.replace(queryBuilder.toString(), CQLTranslator.COLUMNS,\n                        Constants.ESCAPE_QUOTE + tableInfo.getIdColumnName() + Constants.ESCAPE_QUOTE));\n            }\n\n            // set column family properties defined in configuration\n            // property/xml\n            // files.\n            setColumnFamilyProperties(null, cfProperties, queryBuilder);\n            KunderaCoreUtils.printQuery(queryBuilder.toString(), showQuery);\n\n            cassandra_client.execute_cql3_query(\n                    ByteBuffer.wrap(queryBuilder.toString().getBytes(Constants.CHARSET_UTF8)), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (InvalidRequestException irex)\n        {\n            updateExistingColumnFamily(tableInfo, ksDef, irex);\n        }\n\n    }\n\n    /**\n     * Gets the composite id embeddables.\n     * \n     * @param embeddable\n     *            the embeddable\n     * @param compositeEmbeddables\n     *            the composite embeddables\n     * @param metaModel\n     *            the meta model\n     * @return the composite id embeddables\n     */\n    private void getCompositeIdEmbeddables(EmbeddableType embeddable, List compositeEmbeddables, MetamodelImpl metaModel)\n    {\n        compositeEmbeddables.add(embeddable.getJavaType().getSimpleName());\n\n        for (Object column : embeddable.getAttributes())\n        {\n\n            Attribute columnAttribute = (Attribute) column;\n            Field f = (Field) columnAttribute.getJavaMember();\n\n            if (columnAttribute.getJavaType().isAnnotationPresent(Embeddable.class))\n            {\n                getCompositeIdEmbeddables(metaModel.embeddable(columnAttribute.getJavaType()), compositeEmbeddables,\n                        metaModel);\n            }\n        }\n    }\n\n    /**\n     * On element collection columns.\n     * \n     * @param translator\n     *            the translator\n     * @param collectionColumnInfos\n     *            the collection column infos\n     * @param queryBuilder\n     *            the query builder\n     */\n    private void onElementCollectionColumns(CQLTranslator translator, List<CollectionColumnInfo> collectionColumnInfos,\n            StringBuilder queryBuilder)\n    {\n        for (CollectionColumnInfo cci : collectionColumnInfos)\n        {\n            String dataType = CassandraValidationClassMapper.getValidationClass(cci.getType(), true);\n\n            // CQL Type of collection column\n            String collectionCqlType = translator.getCQLType(dataType);\n\n            // Collection Column Name\n            String collectionColumnName = new String(cci.getCollectionColumnName());\n\n            // Generic Type list\n            StringBuilder genericTypesBuilder = null;\n            List<Class<?>> genericClasses = cci.getGenericClasses();\n            if (!genericClasses.isEmpty())\n            {\n                genericTypesBuilder = new StringBuilder();\n                if (MapType.class.getSimpleName().equals(dataType) && genericClasses.size() == 2)\n                {\n                    genericTypesBuilder.append(Constants.STR_LT);\n                    if (genericClasses.get(0).getAnnotation(Embeddable.class) != null)\n                    {\n                        String frozenKey = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE\n                                + genericClasses.get(0).getSimpleName() + Constants.ESCAPE_QUOTE + Constants.STR_GT;\n                        genericTypesBuilder.append(frozenKey);\n                    }\n                    else\n                    {\n                        String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(0),\n                                true);\n                        genericTypesBuilder.append(translator.getCQLType(keyDataType));\n                    }\n                    genericTypesBuilder.append(Constants.SPACE_COMMA);\n                    if (genericClasses.get(1).getAnnotation(Embeddable.class) != null)\n                    {\n                        String frozenKey = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE\n                                + genericClasses.get(1).getSimpleName() + Constants.ESCAPE_QUOTE + Constants.STR_GT;\n                        genericTypesBuilder.append(frozenKey);\n                    }\n                    else\n                    {\n                        String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(1),\n                                true);\n                        genericTypesBuilder.append(translator.getCQLType(keyDataType));\n                    }\n                    genericTypesBuilder.append(Constants.STR_GT);\n                }\n                else if ((ListType.class.getSimpleName().equals(dataType) || SetType.class.getSimpleName().equals(\n                        dataType))\n                        && genericClasses.size() == 1)\n                {\n                    genericTypesBuilder.append(Constants.STR_LT);\n                    if (genericClasses.get(0).getAnnotation(Embeddable.class) != null)\n                    {\n                        String frozenKey = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE\n                                + genericClasses.get(0).getSimpleName() + Constants.ESCAPE_QUOTE + Constants.STR_GT;\n                        genericTypesBuilder.append(frozenKey);\n                    }\n                    else\n                    {\n                        String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(0),\n                                true);\n                        genericTypesBuilder.append(translator.getCQLType(keyDataType));\n                    }\n                    genericTypesBuilder.append(Constants.STR_GT);\n                }\n                else\n                {\n                    throw new SchemaGenerationException(\"Incorrect collection field definition for \"\n                            + cci.getCollectionColumnName() + \". Generic Types must be defined correctly.\");\n                }\n            }\n\n            if (genericTypesBuilder != null)\n            {\n                collectionCqlType += genericTypesBuilder.toString();\n            }\n\n            translator.appendColumnName(queryBuilder, collectionColumnName, collectionCqlType);\n            queryBuilder.append(Constants.SPACE_COMMA);\n\n        }\n\n    }\n\n    /**\n     * On embedded columns.\n     * \n     * @param translator\n     *            the translator\n     * @param tableInfo\n     *            the table info\n     * @param queryBuilder\n     *            the query builder\n     * @param compositeEmbeddables\n     *            the composite embeddables\n     */\n    private void onEmbeddedColumns(CQLTranslator translator, TableInfo tableInfo, StringBuilder queryBuilder,\n            List compositeEmbeddables)\n    {\n        List<EmbeddedColumnInfo> embeddedColumns = tableInfo.getEmbeddedColumnMetadatas();\n        for (EmbeddedColumnInfo embColInfo : embeddedColumns)\n        {\n            if (!compositeEmbeddables.contains(embColInfo.getEmbeddable().getJavaType().getSimpleName()))\n            {\n                String cqlType = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE\n                        + embColInfo.getEmbeddable().getJavaType().getSimpleName() + Constants.ESCAPE_QUOTE\n                        + Constants.STR_GT + translator.COMMA_STR;\n                translator.appendColumnName(queryBuilder, embColInfo.getEmbeddedColumnName(), cqlType);\n            }\n        }\n    }\n\n    /**\n     * Creates the typefor embeddables.\n     * \n     * @param compositeEmbeddables\n     *            the composite embeddables\n     */\n    private void createTypeforEmbeddables(List compositeEmbeddables)\n    {\n        if (!createdPuEmbeddables.contains(puMetadata.getPersistenceUnitName()))\n        {\n            CQLTranslator translator = new CQLTranslator();\n\n            Map<String, String> embNametoUDTQuery = new HashMap<String, String>();\n            Map<String, List<String>> embNametoDependentList = new HashMap<String, List<String>>();\n\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    puMetadata.getPersistenceUnitName());\n\n            Iterator iter = metaModel.getEmbeddables().iterator();\n            while (iter.hasNext())\n            {\n                List<String> childEmb = new ArrayList<String>();\n\n                String typeQuery = CQLTranslator.CREATE_TYPE;\n                EmbeddableType embeddedColumn = (EmbeddableType) iter.next();\n                if (!embeddedColumn.getPersistenceType().equals(PersistenceType.EMBEDDABLE)\n                        || compositeEmbeddables.contains(embeddedColumn.getJavaType().getSimpleName()))\n                {\n                    continue;\n                }\n\n                typeQuery = StringUtils.replace(typeQuery, CQLTranslator.TYPE,\n                        translator.ensureCase(new StringBuilder(), embeddedColumn.getJavaType().getSimpleName(), false)\n                                .toString());\n\n                StringBuilder typeQueryBuilder = new StringBuilder();\n\n                for (Object column : embeddedColumn.getAttributes())\n                {\n\n                    Attribute columnAttribute = (Attribute) column;\n                    Field f = (Field) columnAttribute.getJavaMember();\n\n                    if (columnAttribute.getJavaType().isAnnotationPresent(Embeddable.class))\n                    {\n                        // handle embeddable\n                        String cqlType = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE\n                                + columnAttribute.getJavaType().getSimpleName() + Constants.ESCAPE_QUOTE\n                                + Constants.STR_GT;\n                        translator.appendColumnName(typeQueryBuilder, columnAttribute.getName(), cqlType);\n                        typeQueryBuilder.append(Constants.SPACE_COMMA);\n                        childEmb.add(columnAttribute.getJavaType().getSimpleName());\n                    }\n                    else if (columnAttribute.isCollection())\n                    {\n                        // handle element collection with embeddables\n                        handleElementCollectionAttribute(translator, columnAttribute, typeQueryBuilder);\n                        if (!MetadataUtils.isBasicElementCollectionField((Field) columnAttribute.getJavaMember()))\n                        {\n                            childEmb.add(((AbstractAttribute) columnAttribute).getBindableJavaType().getSimpleName());\n                        }\n\n                    }\n                    else\n                    {\n                        String cqlType = null;\n                        String dataType = CassandraValidationClassMapper.getValidationClass(f.getType(), true);\n                        cqlType = translator.getCQLType(dataType);\n                        // check for JPA names\n                        translator.appendColumnName(typeQueryBuilder,\n                                ((AbstractAttribute) columnAttribute).getJPAColumnName(), cqlType);\n                        typeQueryBuilder.append(Constants.SPACE_COMMA);\n\n                    }\n\n                }\n                typeQueryBuilder = replaceColumnsAndStripLastChar(typeQuery, typeQueryBuilder);\n                typeQueryBuilder.append(CQLTranslator.CLOSE_BRACKET);\n                embNametoUDTQuery.put(embeddedColumn.getJavaType().getSimpleName(), typeQueryBuilder.toString());\n                embNametoDependentList.put(embeddedColumn.getJavaType().getSimpleName(), childEmb);\n                // run query final\n\n            }\n            postProcessEmbedded(embNametoUDTQuery, embNametoDependentList);\n            createdPuEmbeddables.add(puMetadata.getPersistenceUnitName());\n        }\n    }\n\n    /**\n     * Handle element collection attribute.\n     * \n     * @param translator\n     *            the translator\n     * @param attribute\n     *            the attribute\n     * @param typeQueryBuilder\n     *            the type query builder\n     */\n    private void handleElementCollectionAttribute(CQLTranslator translator, Attribute attribute,\n            StringBuilder typeQueryBuilder)\n    {\n        String dataType = CassandraValidationClassMapper.getValidationClass(attribute.getJavaType(), true);\n\n        // CQL Type of collection column\n        String collectionCqlType = translator.getCQLType(dataType);\n\n        // Collection Column Name\n        String collectionColumnName = new String(((AbstractAttribute) attribute).getJPAColumnName());\n\n        // Generic Type list\n        StringBuilder genericTypesBuilder = null;\n        List<Class<?>> genericClasses = PropertyAccessorHelper.getGenericClasses((Field) attribute.getJavaMember());\n        if (!genericClasses.isEmpty())\n        {\n            genericTypesBuilder = new StringBuilder();\n            if (MapType.class.getSimpleName().equals(dataType) && genericClasses.size() == 2)\n            {\n                genericTypesBuilder.append(Constants.STR_LT);\n                if (genericClasses.get(0).getAnnotation(Embeddable.class) != null)\n                {\n                    String frozenKey = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE\n                            + genericClasses.get(0).getSimpleName() + Constants.ESCAPE_QUOTE + Constants.STR_GT;\n                    genericTypesBuilder.append(frozenKey);\n                }\n                else\n                {\n                    String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(0), true);\n                    genericTypesBuilder.append(translator.getCQLType(keyDataType));\n                }\n                genericTypesBuilder.append(Constants.SPACE_COMMA);\n                if (genericClasses.get(1).getAnnotation(Embeddable.class) != null)\n                {\n                    String frozenKey = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE\n                            + genericClasses.get(1).getSimpleName() + Constants.ESCAPE_QUOTE + Constants.STR_GT;\n                    genericTypesBuilder.append(frozenKey);\n                }\n                else\n                {\n                    String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(1), true);\n                    genericTypesBuilder.append(translator.getCQLType(keyDataType));\n                }\n                genericTypesBuilder.append(Constants.STR_GT);\n            }\n            else if ((ListType.class.getSimpleName().equals(dataType) || SetType.class.getSimpleName().equals(dataType))\n                    && genericClasses.size() == 1)\n            {\n                genericTypesBuilder.append(Constants.STR_LT);\n                if (genericClasses.get(0).getAnnotation(Embeddable.class) != null)\n                {\n                    String frozenKey = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE\n                            + genericClasses.get(0).getSimpleName() + Constants.ESCAPE_QUOTE + Constants.STR_GT;\n                    genericTypesBuilder.append(frozenKey);\n                }\n                else\n                {\n                    String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(0), true);\n                    genericTypesBuilder.append(translator.getCQLType(keyDataType));\n                }\n                genericTypesBuilder.append(Constants.STR_GT);\n            }\n            else\n            {\n                throw new SchemaGenerationException(\"Incorrect collection field definition for \"\n                        + ((AbstractAttribute) attribute).getJPAColumnName()\n                        + \". Generic Types must be defined correctly.\");\n            }\n        }\n\n        if (genericTypesBuilder != null)\n        {\n            collectionCqlType += genericTypesBuilder.toString();\n        }\n\n        translator.appendColumnName(typeQueryBuilder, collectionColumnName, collectionCqlType);\n        typeQueryBuilder.append(Constants.SPACE_COMMA);\n\n    }\n\n    /**\n     * Post process embedded.\n     * \n     * @param embNametoUDTQuery\n     *            the emb nameto udt query\n     * @param embNametoDependentList\n     *            the emb nameto dependent list\n     * \n     */\n    private void postProcessEmbedded(Map<String, String> embNametoUDTQuery,\n            Map<String, List<String>> embNametoDependentList)\n    {\n        for (Map.Entry<String, List<String>> entry : embNametoDependentList.entrySet())\n        {\n            checkRelationAndExecuteQuery(entry.getKey(), embNametoDependentList, embNametoUDTQuery);\n        }\n    }\n\n    /**\n     * Check relation and execute query.\n     * \n     * @param embeddableKey\n     *            the embeddable key\n     * @param embeddableToDependentEmbeddables\n     *            the embeddable to dependent embeddables\n     * @param queries\n     *            the queries\n     * \n     */\n    private void checkRelationAndExecuteQuery(String embeddableKey,\n            Map<String, List<String>> embeddableToDependentEmbeddables, Map<String, String> queries)\n    {\n        List<String> dependentEmbeddables = embeddableToDependentEmbeddables.get(embeddableKey);\n\n        if (!dependentEmbeddables.isEmpty())\n        {\n            for (String dependentEmbeddable : dependentEmbeddables)\n            {\n                checkRelationAndExecuteQuery(dependentEmbeddable, embeddableToDependentEmbeddables, queries);\n            }\n        }\n        KunderaCoreUtils.printQuery(queries.get(embeddableKey), showQuery);\n\n        try\n        {\n            cassandra_client.execute_cql3_query(\n                    ByteBuffer.wrap(queries.get(embeddableKey).getBytes(Constants.CHARSET_UTF8)), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception e)\n        {\n            throw new KunderaException(\"Error while creating type: \" + queries.get(embeddableKey), e);\n        }\n\n    }\n\n    /**\n     * Append primary key.\n     * \n     * @param translator\n     *            the translator\n     * @param compoEmbeddableType\n     *            the compo embeddable type\n     * @param fields\n     *            the fields\n     * @param queryBuilder\n     *            the query builder\n     */\n    private void appendPrimaryKey(CQLTranslator translator, EmbeddableType compoEmbeddableType, Field[] fields,\n            StringBuilder queryBuilder)\n    {\n        for (Field f : fields)\n        {\n            if (!ReflectUtils.isTransientOrStatic(f))\n            {\n                if (f.getType().isAnnotationPresent(Embeddable.class))\n                { // compound partition key\n                    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                            puMetadata.getPersistenceUnitName());\n                    queryBuilder.append(translator.OPEN_BRACKET);\n                    queryBuilder.append(translator.SPACE_STRING);\n                    appendPrimaryKey(translator, (EmbeddableType) metaModel.embeddable(f.getType()), f.getType()\n                            .getDeclaredFields(), queryBuilder);\n                    queryBuilder.deleteCharAt(queryBuilder.length() - 1);\n                    queryBuilder.append(translator.CLOSE_BRACKET);\n                    queryBuilder.append(Constants.SPACE_COMMA);\n\n                }\n                else\n                {\n                    Attribute attribute = compoEmbeddableType.getAttribute(f.getName());\n                    translator.appendColumnName(queryBuilder, ((AbstractAttribute) attribute).getJPAColumnName());\n                    queryBuilder.append(Constants.SPACE_COMMA);\n                }\n            }\n        }\n    }\n\n    /**\n     * Append clustering order.\n     * \n     * @param translator\n     *            the translator\n     * @param compositeColumns\n     *            the composite columns\n     * @param clusterKeyOrderingBuilder\n     *            the cluster key ordering builder\n     * @param primaryKeyBuilder\n     *            the primary key builder\n     */\n    private void appendClusteringOrder(CQLTranslator translator, List<ColumnInfo> compositeColumns,\n            StringBuilder clusterKeyOrderingBuilder, StringBuilder primaryKeyBuilder)\n    {\n        // to retrieve the order in which cluster key is formed\n        String[] primaryKeys = primaryKeyBuilder.toString().split(\"\\\\s*,\\\\s*\");\n        for (String primaryKey : primaryKeys)\n        {\n            // to compare the objects without enclosing quotes\n            primaryKey = primaryKey.trim().substring(1, primaryKey.trim().length() - 1);\n            for (ColumnInfo colInfo : compositeColumns)\n            {\n\n                if (primaryKey.equals(colInfo.getColumnName()))\n                {\n                    if (colInfo.getOrderBy() != null)\n                    {\n                        translator.appendColumnName(clusterKeyOrderingBuilder, colInfo.getColumnName());\n                        clusterKeyOrderingBuilder.append(translator.SPACE_STRING);\n                        clusterKeyOrderingBuilder.append(colInfo.getOrderBy());\n                        clusterKeyOrderingBuilder.append(translator.COMMA_STR);\n                    }\n\n                }\n            }\n        }\n        if (clusterKeyOrderingBuilder.length() != 0)\n        {\n            clusterKeyOrderingBuilder.deleteCharAt(clusterKeyOrderingBuilder.toString().lastIndexOf(\",\"));\n            clusterKeyOrderingBuilder.append(translator.CLOSE_BRACKET);\n        }\n\n    }\n\n    /**\n     * Strip last char.\n     * \n     * @param columnFamilyQuery\n     *            the column family query\n     * @param queryBuilder\n     *            the query builder\n     * @return the string builder\n     */\n    private StringBuilder replaceColumnsAndStripLastChar(String columnFamilyQuery, StringBuilder queryBuilder)\n    {\n        // strip last \",\".\n        if (queryBuilder.length() > 0)\n        {\n            queryBuilder.deleteCharAt(queryBuilder.length() - 1);\n\n            columnFamilyQuery = StringUtils.replace(columnFamilyQuery, CQLTranslator.COLUMNS, queryBuilder.toString());\n            queryBuilder = new StringBuilder(columnFamilyQuery);\n        }\n        return queryBuilder;\n    }\n\n    /**\n     * Creates the index using thrift.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param cfDef\n     *            the cf def\n     * @throws Exception\n     *             the exception\n     */\n    private void createIndexUsingThrift(TableInfo tableInfo, CfDef cfDef) throws Exception\n    {\n        for (IndexInfo indexInfo : tableInfo.getColumnsToBeIndexed())\n        {\n            for (ColumnDef columnDef : cfDef.getColumn_metadata())\n            {\n                if (new String(columnDef.getName(), Constants.ENCODING).equals(indexInfo.getColumnName()))\n                {\n                    columnDef.setIndex_type(CassandraIndexHelper.getIndexType(indexInfo.getIndexType()));\n                    // columnDef.setIndex_name(indexInfo.getIndexName());\n                }\n            }\n        }\n        cassandra_client.system_update_column_family(cfDef);\n    }\n\n    /**\n     * Create secondary indexes on columns.\n     * \n     * @param tableInfo\n     *            the table info\n     * @throws Exception\n     *             the exception\n     */\n    private void createIndexUsingCql(TableInfo tableInfo) throws Exception\n    {\n\n        List<String> embeddedIndexes = new ArrayList<String>();\n        for (EmbeddedColumnInfo embeddedColumnInfo : tableInfo.getEmbeddedColumnMetadatas())\n        {\n            for (ColumnInfo columnInfo : embeddedColumnInfo.getColumns())\n            {\n                if (columnInfo.isIndexable())\n                {\n                    embeddedIndexes.add(columnInfo.getColumnName());\n                }\n            }\n        }\n\n        StringBuilder indexQueryBuilder = new StringBuilder(\"create index if not exists on \\\"\");\n        indexQueryBuilder.append(tableInfo.getTableName());\n        indexQueryBuilder.append(\"\\\"(\\\"$COLUMN_NAME\\\")\");\n        tableInfo.getColumnsToBeIndexed();\n        for (IndexInfo indexInfo : tableInfo.getColumnsToBeIndexed())\n        {\n            ColumnInfo columnInfo = new ColumnInfo();\n            columnInfo.setColumnName(indexInfo.getColumnName());\n\n            // indexes on embeddables not supported in cql3\n            if (!embeddedIndexes.contains(indexInfo.getColumnName()))\n            {\n                String replacedWithindexName = StringUtils.replace(indexQueryBuilder.toString(), \"$COLUMN_NAME\",\n                        indexInfo.getColumnName());\n\n                try\n                {\n                    KunderaCoreUtils.printQuery(replacedWithindexName, showQuery);\n                    cassandra_client.execute_cql3_query(ByteBuffer.wrap(replacedWithindexName.getBytes()),\n                            Compression.NONE, ConsistencyLevel.ONE);\n                }\n                catch (InvalidRequestException ire)\n                {\n                    if (ire.getWhy() != null && !ire.getWhy().equals(\"Index already exists\")\n                            && operation.equalsIgnoreCase(SchemaOperationType.update.name()))\n                    {\n                        log.error(\"Error occurred while creating indexes on column{} of table {}, , Caused by: .\",\n                                indexInfo.getColumnName(), tableInfo.getTableName(), ire);\n                        throw new SchemaGenerationException(\"Error occurred while creating indexes on column \"\n                                + indexInfo.getColumnName() + \" of table \" + tableInfo.getTableName(), ire,\n                                \"Cassandra\", databaseName);\n                    }\n                }\n            }\n\n        }\n    }\n\n    /**\n     * Drops table using cql3.\n     * \n     * @param tableInfo\n     *            the table info\n     * @throws Exception\n     *             the exception\n     */\n    private void dropTableUsingCql(TableInfo tableInfo) throws Exception\n    {\n\n        CQLTranslator translator = new CQLTranslator();\n        StringBuilder dropQuery = new StringBuilder(\"drop table \");\n        translator.ensureCase(dropQuery, tableInfo.getTableName(), false);\n\n        KunderaCoreUtils.printQuery(dropQuery.toString(), showQuery);\n\n        cassandra_client.execute_cql3_query(ByteBuffer.wrap(dropQuery.toString().getBytes()), Compression.NONE,\n                ConsistencyLevel.ONE);\n    }\n\n    /**\n     * Adds column to table if not exists previously i.e. alter table.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param column\n     *            the column\n     * @throws Exception\n     *             the exception\n     */\n    private void addColumnToTable(TableInfo tableInfo, ColumnInfo column) throws Exception\n    {\n        CQLTranslator translator = new CQLTranslator();\n        StringBuilder addColumnQuery = new StringBuilder(\"ALTER TABLE \");\n        translator.ensureCase(addColumnQuery, tableInfo.getTableName(), false);\n        addColumnQuery.append(\" ADD \");\n        translator.ensureCase(addColumnQuery, column.getColumnName(), false);\n        addColumnQuery.append(\" \"\n                + translator.getCQLType(CassandraValidationClassMapper.getValidationClass(column.getType(),\n                        isCql3Enabled(tableInfo))));\n        try\n        {\n            KunderaCoreUtils.printQuery(addColumnQuery.toString(), showQuery);\n            cassandra_client.execute_cql3_query(ByteBuffer.wrap(addColumnQuery.toString().getBytes()),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (InvalidRequestException ireforAddColumn)\n        {\n            StringBuilder ireforAddColumnbBuilder = new StringBuilder(\"Invalid column name \");\n            ireforAddColumnbBuilder.append(column.getColumnName() + \" because it conflicts with an existing column\");\n            if (ireforAddColumn.getWhy() != null && ireforAddColumn.getWhy().equals(ireforAddColumnbBuilder.toString()))\n            {\n                // alterColumnType(tableInfo, translator, column);\n            }\n            else\n            {\n                log.error(\"Error occurred while altering column type of  table {}, Caused by: .\",\n                        tableInfo.getTableName(), ireforAddColumn);\n                throw new SchemaGenerationException(\"Error occurred while adding column into table \"\n                        + tableInfo.getTableName(), ireforAddColumn, \"Cassandra\", databaseName);\n            }\n        }\n\n    }\n\n    /**\n     * showSchema Alters column type of an existing column.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param translator\n     *            the translator\n     * @param column\n     *            the column\n     * @throws Exception\n     *             the exception\n     */\n    private void alterColumnType(TableInfo tableInfo, CQLTranslator translator, ColumnInfo column) throws Exception\n    {\n        StringBuilder alterColumnTypeQuery = new StringBuilder(\"ALTER TABLE \");\n        translator.ensureCase(alterColumnTypeQuery, tableInfo.getTableName(), false);\n        alterColumnTypeQuery.append(\" ALTER \");\n        translator.ensureCase(alterColumnTypeQuery, column.getColumnName(), false);\n        alterColumnTypeQuery.append(\" TYPE \"\n                + translator.getCQLType(CassandraValidationClassMapper.getValidationClass(column.getType(),\n                        isCql3Enabled(tableInfo))));\n        cassandra_client.execute_cql3_query(ByteBuffer.wrap(alterColumnTypeQuery.toString().getBytes()),\n                Compression.NONE, ConsistencyLevel.ONE);\n\n        KunderaCoreUtils.printQuery(alterColumnTypeQuery.toString(), showQuery);\n    }\n\n    /**\n     * On composite columns.\n     * \n     * @param translator\n     *            the translator\n     * @param compositeColumns\n     *            the composite columns\n     * @param queryBuilder\n     *            the query builder\n     * @param columns\n     *            the columns\n     * @param isCounterColumnFamily\n     *            the is counter column family\n     */\n    private void onCompositeColumns(CQLTranslator translator, List<ColumnInfo> compositeColumns,\n            StringBuilder queryBuilder, List<ColumnInfo> columns, boolean isCounterColumnFamily)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                puMetadata.getPersistenceUnitName());\n        for (ColumnInfo colInfo : compositeColumns)\n        {\n            if (columns == null || (columns != null && !columns.contains(colInfo)))\n            {\n                String cqlType = null;\n                if (isCounterColumnFamily)\n                {\n                    cqlType = \"counter\";\n                    translator.appendColumnName(queryBuilder, colInfo.getColumnName(), cqlType);\n                    queryBuilder.append(Constants.SPACE_COMMA);\n                }\n                // check for composite partition keys #734\n                else if (colInfo.getType().isAnnotationPresent(Embeddable.class))\n                {\n                    EmbeddableType embeddedObject = (EmbeddableType) metaModel.embeddable(colInfo.getType());\n                    for (Field embeddedColumn : colInfo.getType().getDeclaredFields())\n                    {\n                        if (!ReflectUtils.isTransientOrStatic(embeddedColumn))\n                        {\n                            validateAndAppendColumnName(translator, queryBuilder,\n                                    ((AbstractAttribute) embeddedObject.getAttribute(embeddedColumn.getName()))\n                                            .getJPAColumnName(), embeddedColumn.getType());\n                        }\n                    }\n\n                }\n                else\n                {\n                    validateAndAppendColumnName(translator, queryBuilder, colInfo.getColumnName(), colInfo.getType());\n                }\n\n            }\n        }\n    }\n\n    /**\n     * Validate and append column name.\n     * \n     * @param translator\n     *            the translator\n     * @param queryBuilder\n     *            the query builder\n     * @param b\n     *            the b\n     * @param clazz\n     *            the clazz\n     */\n    private void validateAndAppendColumnName(CQLTranslator translator, StringBuilder queryBuilder, String b,\n            Class<?> clazz)\n    {\n        String dataType = CassandraValidationClassMapper.getValidationClass(clazz, true);\n        translator.appendColumnName(queryBuilder, b, translator.getCQLType(dataType));\n        queryBuilder.append(Constants.SPACE_COMMA);\n    }\n\n    /**\n     * Generates schema for Collection columns.\n     * \n     * @param translator\n     *            the translator\n     * @param collectionColumnInfos\n     *            the collection column infos\n     * @param queryBuilder\n     *            the query builder\n     */\n    private void onCollectionColumns(CQLTranslator translator, List<CollectionColumnInfo> collectionColumnInfos,\n            StringBuilder queryBuilder)\n    {\n        for (CollectionColumnInfo cci : collectionColumnInfos)\n        {\n            String dataType = CassandraValidationClassMapper.getValidationClass(cci.getType(), true);\n\n            // CQL Type of collection column\n            String collectionCqlType = translator.getCQLType(dataType);\n\n            // Collection Column Name\n            String collectionColumnName = new String(cci.getCollectionColumnName());\n\n            // Generic Type list\n            StringBuilder genericTypesBuilder = null;\n            List<Class<?>> genericClasses = cci.getGenericClasses();\n            if (!genericClasses.isEmpty())\n            {\n                genericTypesBuilder = new StringBuilder();\n                if (MapType.class.getSimpleName().equals(dataType) && genericClasses.size() == 2)\n                {\n                    genericTypesBuilder.append(Constants.STR_LT);\n                    String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(0), true);\n                    genericTypesBuilder.append(translator.getCQLType(keyDataType));\n                    genericTypesBuilder.append(Constants.SPACE_COMMA);\n                    String valueDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(1),\n                            true);\n                    genericTypesBuilder.append(translator.getCQLType(valueDataType));\n                    genericTypesBuilder.append(Constants.STR_GT);\n                }\n                else if ((ListType.class.getSimpleName().equals(dataType) || SetType.class.getSimpleName().equals(\n                        dataType))\n                        && genericClasses.size() == 1)\n                {\n                    genericTypesBuilder.append(Constants.STR_LT);\n                    String valueDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(0),\n                            true);\n                    genericTypesBuilder.append(translator.getCQLType(valueDataType));\n                    genericTypesBuilder.append(Constants.STR_GT);\n                }\n                else\n                {\n                    throw new SchemaGenerationException(\"Incorrect collection field definition for \"\n                            + cci.getCollectionColumnName() + \". Generic Types must be defined correctly.\");\n                }\n            }\n\n            if (genericTypesBuilder != null)\n            {\n                collectionCqlType += genericTypesBuilder.toString();\n            }\n\n            translator.appendColumnName(queryBuilder, collectionColumnName, collectionCqlType);\n            queryBuilder.append(Constants.SPACE_COMMA);\n\n        }\n    }\n\n    /**\n     * Creates the inverted index table.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param ksDef\n     *            the ks def\n     * @throws Exception\n     *             the exception\n     */\n    private void createInvertedIndexTable(TableInfo tableInfo, KsDef ksDef) throws Exception\n    {\n        CfDef cfDef = getInvertedIndexCF(tableInfo);\n        if (cfDef != null)\n        {\n            try\n            {\n                cassandra_client.system_add_column_family(cfDef);\n            }\n            catch (InvalidRequestException irex)\n            {\n                updateExistingColumnFamily(tableInfo, ksDef, irex);\n            }\n        }\n\n    }\n\n    /**\n     * Gets the inverted index cf.\n     * \n     * @param tableInfo\n     *            the table info\n     * @return the inverted index cf\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     * @throws TException\n     *             the t exception\n     */\n    private CfDef getInvertedIndexCF(TableInfo tableInfo) throws InvalidRequestException, SchemaDisagreementException,\n            TException\n    {\n        boolean indexTableRequired = CassandraPropertyReader.csmd.isInvertedIndexingEnabled(databaseName)\n                && !tableInfo.getEmbeddedColumnMetadatas().isEmpty();\n        if (indexTableRequired)\n        {\n            CfDef cfDef = new CfDef();\n            cfDef.setKeyspace(databaseName);\n            cfDef.setColumn_type(\"Super\");\n            cfDef.setName(tableInfo.getTableName() + Constants.INDEX_TABLE_SUFFIX);\n            cfDef.setKey_validation_class(UTF8Type.class.getSimpleName());\n            return cfDef;\n        }\n        return null;\n    }\n\n    /**\n     * Drop inverted index table.\n     * \n     * @param tableInfo\n     *            the table info\n     */\n    private void dropInvertedIndexTable(TableInfo tableInfo)\n    {\n        boolean indexTableRequired = CassandraPropertyReader.csmd.isInvertedIndexingEnabled(databaseName)/* ) */\n                && !tableInfo.getEmbeddedColumnMetadatas().isEmpty();\n        if (indexTableRequired)\n        {\n            try\n            {\n                cassandra_client.system_drop_column_family(tableInfo.getTableName() + Constants.INDEX_TABLE_SUFFIX);\n            }\n            catch (Exception ex)\n            {\n                if (log.isWarnEnabled())\n                {\n                    log.warn(\"Error while dropping inverted index table, Caused by: \", ex);\n                }\n            }\n        }\n    }\n\n    /**\n     * check for Tables method check the existence of schema and table.\n     * \n     * @param tableInfos\n     *            list of TableInfos and ksDef object of KsDef\n     * @param ksDef\n     *            the ks def\n     * @throws Exception\n     *             the exception\n     */\n    private void onValidateTables(List<TableInfo> tableInfos, KsDef ksDef) throws Exception\n    {\n        cassandra_client.set_keyspace(ksDef.getName());\n        for (TableInfo tableInfo : tableInfos)\n        {\n            if (isCql3Enabled(tableInfo) && !tableInfo.getType().equals(Type.SUPER_COLUMN_FAMILY.name()))\n            {\n                CqlMetadata metadata = new CqlMetadata();\n                Map<ByteBuffer, String> name_types = new HashMap<ByteBuffer, String>();\n                Map<ByteBuffer, String> value_types = new HashMap<ByteBuffer, String>();\n                List<ColumnInfo> columnInfos = tableInfo.getColumnMetadatas();\n\n                List<EmbeddedColumnInfo> compositeColumns = tableInfo.getEmbeddedColumnMetadatas();\n                if (compositeColumns != null && !compositeColumns.isEmpty())\n                {\n                    EmbeddableType embeddableType = compositeColumns.get(0).getEmbeddable();\n                    for (ColumnInfo columnInfo : compositeColumns.get(0).getColumns())\n                    {\n                        name_types\n                                .put(ByteBufferUtil.bytes(columnInfo.getColumnName()), UTF8Type.class.getSimpleName());\n                        value_types.put(ByteBufferUtil.bytes(columnInfo.getColumnName()),\n                                CassandraValidationClassMapper.getValidationClassInstance(columnInfo.getType(), true)\n                                        .getName());\n                    }\n\n                }\n                else\n                {\n                    name_types.put(ByteBufferUtil.bytes(tableInfo.getIdColumnName()), UTF8Type.class.getSimpleName());\n                    value_types.put(ByteBufferUtil.bytes(tableInfo.getIdColumnName()), CassandraValidationClassMapper\n                            .getValidationClassInstance(tableInfo.getTableIdType(), true).getName());\n                }\n\n                for (ColumnInfo info : columnInfos)\n                {\n                    name_types.put(ByteBufferUtil.bytes(info.getColumnName()), UTF8Type.class.getSimpleName());\n                    value_types.put(ByteBufferUtil.bytes(info.getColumnName()), CassandraValidationClassMapper\n                            .getValidationClassInstance(info.getType(), true).getName());\n                }\n\n                for (CollectionColumnInfo info : tableInfo.getCollectionColumnMetadatas())\n                {\n                    name_types\n                            .put(ByteBufferUtil.bytes(info.getCollectionColumnName()), UTF8Type.class.getSimpleName());\n                    value_types.put(ByteBufferUtil.bytes(info.getCollectionColumnName()),\n                            CassandraValidationClassMapper.getValueTypeName(info.getType(), info.getGenericClasses(),\n                                    true));\n                }\n\n                metadata.setDefault_name_type(UTF8Type.class.getSimpleName());\n                metadata.setDefault_value_type(UTF8Type.class.getSimpleName());\n                metadata.setName_types(name_types);\n                metadata.setValue_types(value_types);\n                CQLTranslator translator = new CQLTranslator();\n                final String describeTable = \"select * from \";\n                StringBuilder builder = new StringBuilder(describeTable);\n                translator.ensureCase(builder, tableInfo.getTableName(), false);\n                builder.append(\"LIMIT 1\");\n                cassandra_client.set_cql_version(CassandraConstants.CQL_VERSION_3_0);\n                CqlResult cqlResult = cassandra_client.execute_cql3_query(ByteBufferUtil.bytes(builder.toString()),\n                        Compression.NONE, ConsistencyLevel.ONE);\n\n                KunderaCoreUtils.printQuery(builder.toString(), showQuery);\n                CqlMetadata originalMetadata = cqlResult.getSchema();\n\n                int compareResult = originalMetadata.compareTo(metadata);\n                if (compareResult > 0)\n                {\n                    onLog(tableInfo, metadata, value_types, originalMetadata);\n                    throw new SchemaGenerationException(\n                            \"Schema mismatch!, validation failed. see above table for mismatch\");\n                }\n            }\n            else\n            {\n                onValidateTable(ksDef, tableInfo);\n            }\n        }\n    }\n\n    /**\n     * On validate table.\n     * \n     * @param ksDef\n     *            the ks def\n     * @param tableInfo\n     *            the table info\n     * @throws Exception\n     *             the exception\n     */\n    private void onValidateTable(KsDef ksDef, TableInfo tableInfo) throws Exception\n    {\n        boolean tablefound = false;\n        for (CfDef cfDef : ksDef.getCf_defs())\n        {\n            if (cfDef.getName().equals(tableInfo.getTableName())/*\n                                                                 * && (cfDef.\n                                                                 * getColumn_type\n                                                                 * ().equals(\n                                                                 * ColumnFamilyType\n                                                                 * .\n                                                                 * getInstanceOf\n                                                                 * (\n                                                                 * tableInfo.getType\n                                                                 * ()).name()))\n                                                                 */)\n            {\n                if (cfDef.getColumn_type().equals(ColumnFamilyType.Standard.name()))\n                {\n                    for (ColumnInfo columnInfo : tableInfo.getColumnMetadatas())\n                    {\n                        onValidateColumn(tableInfo, cfDef, columnInfo);\n                    }\n                    tablefound = true;\n                    break;\n                }\n                else if (cfDef.getColumn_type().equals(ColumnFamilyType.Super.name()))\n                {\n                    tablefound = true;\n                }\n            }\n        }\n        if (!tablefound)\n        {\n            throw new SchemaGenerationException(\"Column family \" + tableInfo.getTableName()\n                    + \" does not exist in keyspace \" + databaseName + \"\", \"Cassandra\", databaseName,\n                    tableInfo.getTableName());\n        }\n    }\n\n    /**\n     * On validate column.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param cfDef\n     *            the cf def\n     * @param columnInfo\n     *            the column info\n     * @throws Exception\n     *             the exception\n     */\n    private void onValidateColumn(TableInfo tableInfo, CfDef cfDef, ColumnInfo columnInfo) throws Exception\n    {\n        boolean columnfound = false;\n\n        boolean isCounterColumnType = isCounterColumnType(tableInfo, null);\n\n        for (ColumnDef columnDef : cfDef.getColumn_metadata())\n        {\n            if (isMetadataSame(columnDef, columnInfo, isCql3Enabled(tableInfo), isCounterColumnType))\n            {\n                columnfound = true;\n                break;\n            }\n        }\n        if (!columnfound)\n        {\n            throw new SchemaGenerationException(\"Column \" + columnInfo.getColumnName()\n                    + \" does not exist in column family \" + tableInfo.getTableName() + \"\", \"Cassandra\", databaseName,\n                    tableInfo.getTableName());\n        }\n    }\n\n    /**\n     * is metadata same method returns true if ColumnDef and columnInfo have\n     * same metadata.\n     * \n     * @param columnDef\n     *            the column def\n     * @param columnInfo\n     *            the column info\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @param isCounterColumnType\n     *            the is counter column type\n     * @return true, if is metadata same\n     * @throws Exception\n     *             the exception\n     */\n    private boolean isMetadataSame(ColumnDef columnDef, ColumnInfo columnInfo, boolean isCql3Enabled,\n            boolean isCounterColumnType) throws Exception\n    {\n        return isIndexPresent(columnInfo, columnDef, isCql3Enabled, isCounterColumnType);\n    }\n\n    /**\n     * Update table.\n     * \n     * @param ksDef\n     *            the ks def\n     * @param tableInfo\n     *            the table info\n     * @throws Exception\n     *             the exception\n     */\n    private void updateTable(KsDef ksDef, TableInfo tableInfo) throws Exception\n    {\n        for (CfDef cfDef : ksDef.getCf_defs())\n        {\n            if (cfDef.getName().equals(tableInfo.getTableName())\n                    && cfDef.getColumn_type().equals(ColumnFamilyType.getInstanceOf(tableInfo.getType()).name()))\n            {\n                boolean toUpdate = false;\n                if (cfDef.getColumn_type().equals(STANDARDCOLUMNFAMILY))\n                {\n                    for (ColumnInfo columnInfo : tableInfo.getColumnMetadatas())\n                    {\n                        toUpdate = isCfDefUpdated(columnInfo, cfDef, isCql3Enabled(tableInfo),\n                                isCounterColumnType(tableInfo, null), tableInfo) ? true : toUpdate;\n                    }\n                }\n                if (toUpdate)\n                {\n                    cassandra_client.system_update_column_family(cfDef);\n                }\n                createIndexUsingThrift(tableInfo, cfDef);\n                break;\n            }\n        }\n    }\n\n    /**\n     * Checks if is cf def updated.\n     * \n     * @param columnInfo\n     *            the column info\n     * @param cfDef\n     *            the cf def\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @param isCounterColumnType\n     *            the is counter column type\n     * @param tableInfo\n     *            the table info\n     * @return true, if is cf def updated\n     * @throws Exception\n     *             the exception\n     */\n    private boolean isCfDefUpdated(ColumnInfo columnInfo, CfDef cfDef, boolean isCql3Enabled,\n            boolean isCounterColumnType, TableInfo tableInfo) throws Exception\n    {\n        boolean columnPresent = false;\n        boolean isUpdated = false;\n        for (ColumnDef columnDef : cfDef.getColumn_metadata())\n        {\n            if (isColumnPresent(columnInfo, columnDef, isCql3Enabled))\n            {\n                if (!isValidationClassSame(columnInfo, columnDef, isCql3Enabled, isCounterColumnType))\n                {\n                    columnDef.setValidation_class(CassandraValidationClassMapper.getValidationClass(\n                            columnInfo.getType(), isCql3Enabled));\n                    // if (columnInfo.isIndexable() &&\n                    // !columnDef.isSetIndex_type())\n                    // {\n                    // IndexInfo indexInfo =\n                    // tableInfo.getColumnToBeIndexed(columnInfo.getColumnName());\n                    // columnDef.setIndex_type(CassandraIndexHelper.getIndexType(indexInfo.getIndexType()));\n                    // columnDef.isSetIndex_type();\n                    // columnDef.setIndex_typeIsSet(true);\n                    // columnDef.setIndex_nameIsSet(true);\n                    // }\n                    // else\n                    // {\n                    columnDef.setIndex_nameIsSet(false);\n                    columnDef.setIndex_typeIsSet(false);\n                    // }\n                    isUpdated = true;\n                }\n                columnPresent = true;\n                break;\n            }\n        }\n        if (!columnPresent)\n        {\n            cfDef.addToColumn_metadata(getColumnMetadata(columnInfo, tableInfo));\n            isUpdated = true;\n        }\n        return isUpdated;\n    }\n\n    /**\n     * isInedexesPresent method return whether indexes present or not on\n     * particular column.\n     * \n     * @param columnInfo\n     *            the column info\n     * @param columnDef\n     *            the column def\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return true, if is indexes present\n     * @throws Exception\n     *             the exception\n     */\n    private boolean isColumnPresent(ColumnInfo columnInfo, ColumnDef columnDef, boolean isCql3Enabled) throws Exception\n    {\n        return (new String(columnDef.getName(), Constants.ENCODING).equals(columnInfo.getColumnName()));\n    }\n\n    /**\n     * isInedexesPresent method return whether indexes present or not on\n     * particular column.\n     * \n     * @param columnInfo\n     *            the column info\n     * @param columnDef\n     *            the column def\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @param isCounterColumnType\n     *            the is counter column type\n     * @return true, if is indexes present\n     * @throws Exception\n     *             the exception\n     */\n    private boolean isValidationClassSame(ColumnInfo columnInfo, ColumnDef columnDef, boolean isCql3Enabled,\n            boolean isCounterColumnType) throws Exception\n    {\n        return (isColumnPresent(columnInfo, columnDef, isCql3Enabled) && columnDef.getValidation_class().endsWith(\n                isCounterColumnType ? CounterColumnType.class.getSimpleName() : CassandraValidationClassMapper\n                        .getValidationClass(columnInfo.getType(), isCql3Enabled)));\n    }\n\n    /**\n     * isInedexesPresent method return whether indexes present or not on\n     * particular column.\n     * \n     * @param columnInfo\n     *            the column info\n     * @param columnDef\n     *            the column def\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @param isCounterColumnType\n     *            the is counter column type\n     * @return true, if is indexes present\n     * @throws Exception\n     *             the exception\n     */\n    private boolean isIndexPresent(ColumnInfo columnInfo, ColumnDef columnDef, boolean isCql3Enabled,\n            boolean isCounterColumnType) throws Exception\n    {\n        return (isValidationClassSame(columnInfo, columnDef, isCql3Enabled, isCounterColumnType) && (columnDef\n                .isSetIndex_type() == columnInfo.isIndexable() || (columnDef.isSetIndex_type())));\n    }\n\n    /**\n     * getColumnMetadata use for getting column metadata for specific\n     * columnInfo.\n     * \n     * @param columnInfo\n     *            the column info\n     * @param tableInfo\n     *            the table info\n     * @return the column metadata\n     */\n    private ColumnDef getColumnMetadata(ColumnInfo columnInfo, TableInfo tableInfo)\n    {\n        ColumnDef columnDef = new ColumnDef();\n        columnDef.setName(columnInfo.getColumnName().getBytes());\n        columnDef.setValidation_class(CassandraValidationClassMapper.getValidationClass(columnInfo.getType(),\n                isCql3Enabled(tableInfo)));\n\n        if (columnInfo.isIndexable())\n        {\n            IndexInfo indexInfo = tableInfo.getColumnToBeIndexed(columnInfo.getColumnName());\n            columnDef.setIndex_type(CassandraIndexHelper.getIndexType(indexInfo.getIndexType()));\n            // if (!indexInfo.getIndexName().equals(indexInfo.getColumnName()))\n            // {\n            // columnDef.setIndex_name(indexInfo.getIndexName());\n            // }\n        }\n        return columnDef;\n    }\n\n    /**\n     * Sets the properties.\n     * \n     * @param ksDef\n     *            the ks def\n     * @param strategy_options\n     *            the strategy_options\n     */\n    private void setProperties(KsDef ksDef, Map<String, String> strategy_options)\n    {\n        Schema schema = CassandraPropertyReader.csmd.getSchema(databaseName);\n        if (schema != null && schema.getName() != null && schema.getName().equalsIgnoreCase(databaseName)\n                && schema.getSchemaProperties() != null)\n        {\n            setKeyspaceProperties(ksDef, schema.getSchemaProperties(), strategy_options, schema.getDataCenters());\n        }\n        else\n        {\n            setDefaultReplicationFactor(strategy_options);\n        }\n    }\n\n    /**\n     * Sets the default replication factor.\n     * \n     * @param strategy_options\n     *            the strategy_options\n     */\n    private void setDefaultReplicationFactor(Map<String, String> strategy_options)\n    {\n        strategy_options.put(\"replication_factor\", CassandraConstants.DEFAULT_REPLICATION_FACTOR);\n    }\n\n    /**\n     * Sets the keyspace properties.\n     * \n     * @param ksDef\n     *            the ks def\n     * @param schemaProperties\n     *            the schema properties\n     * @param strategyOptions\n     *            the strategy options\n     * @param dcs\n     *            the dcs\n     */\n    private void setKeyspaceProperties(KsDef ksDef, Properties schemaProperties, Map<String, String> strategyOptions,\n            List<DataCenter> dcs)\n    {\n        String placementStrategy = schemaProperties.getProperty(CassandraConstants.PLACEMENT_STRATEGY,\n                SimpleStrategy.class.getSimpleName());\n        if (placementStrategy.equalsIgnoreCase(SimpleStrategy.class.getSimpleName())\n                || placementStrategy.equalsIgnoreCase(SimpleStrategy.class.getName()))\n        {\n            String replicationFactor = schemaProperties.getProperty(CassandraConstants.REPLICATION_FACTOR,\n                    CassandraConstants.DEFAULT_REPLICATION_FACTOR);\n            strategyOptions.put(\"replication_factor\", replicationFactor);\n        }\n        else if (placementStrategy.equalsIgnoreCase(NetworkTopologyStrategy.class.getSimpleName())\n                || placementStrategy.equalsIgnoreCase(NetworkTopologyStrategy.class.getName()))\n        {\n            if (dcs != null && !dcs.isEmpty())\n            {\n                for (DataCenter dc : dcs)\n                {\n                    strategyOptions.put(dc.getName(), dc.getValue());\n                }\n            }\n        }\n        else\n        {\n            strategyOptions.put(\"replication_factor\", CassandraConstants.DEFAULT_REPLICATION_FACTOR);\n        }\n\n        ksDef.setStrategy_class(placementStrategy);\n        ksDef.setDurable_writes(Boolean.parseBoolean(schemaProperties.getProperty(CassandraConstants.DURABLE_WRITES)));\n    }\n\n    /**\n     * Gets the column family properties.\n     * \n     * @param tableInfo\n     *            the table info\n     * @return the column family properties\n     */\n    private Properties getColumnFamilyProperties(TableInfo tableInfo)\n    {\n        if (tables != null)\n        {\n            for (Table table : tables)\n            {\n                if (table != null && table.getName() != null\n                        && table.getName().equalsIgnoreCase(tableInfo.getTableName()))\n                {\n                    return table.getProperties();\n                }\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Enum ColumnFamilyType for type of column family in cassandra ie Super or\n     * Standard.\n     * \n     */\n    private enum ColumnFamilyType\n    {\n\n        /** The Standard. */\n        Standard,\n        /** The Super. */\n        Super;\n\n        /**\n         * Gets the instance of.\n         * \n         * @param type\n         *            the type\n         * @return the instance of\n         */\n        private static ColumnFamilyType getInstanceOf(String type)\n        {\n            if (type.equals(Type.COLUMN_FAMILY.name()))\n            {\n                return ColumnFamilyType.Standard;\n            }\n            else\n            {\n                return ColumnFamilyType.Super;\n            }\n        }\n    }\n\n    /**\n     * validates entity for CounterColumnType.\n     * \n     * @param clazz\n     *            the clazz\n     * @return true, if successful\n     */\n    @Override\n    public boolean validateEntity(Class clazz)\n    {\n        EntityValidatorAgainstCounterColumn entityValidatorAgainstSchema = new EntityValidatorAgainstCounterColumn();\n        return entityValidatorAgainstSchema.validateEntity(clazz);\n    }\n\n    /**\n     * Sets the column family properties.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the c f properties\n     * @param builder\n     *            the builder\n     */\n    private void setColumnFamilyProperties(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        if ((cfDef != null && cfProperties != null) || (builder != null && cfProperties != null))\n        {\n            if (builder != null)\n            {\n                builder.append(CQLTranslator.WITH_CLAUSE);\n            }\n            onSetKeyValidation(cfDef, cfProperties, builder);\n\n            onSetCompactionStrategy(cfDef, cfProperties, builder);\n\n            onSetComparatorType(cfDef, cfProperties, builder);\n\n            onSetSubComparator(cfDef, cfProperties, builder);\n\n            // onSetReplicateOnWrite(cfDef, cfProperties, builder);\n\n            onSetCompactionThreshold(cfDef, cfProperties, builder);\n\n            onSetComment(cfDef, cfProperties, builder);\n\n            onSetTableId(cfDef, cfProperties, builder);\n\n            onSetGcGrace(cfDef, cfProperties, builder);\n\n            onSetCaching(cfDef, cfProperties, builder);\n\n            onSetBloomFilter(cfDef, cfProperties, builder);\n\n            onSetRepairChance(cfDef, cfProperties, builder);\n\n            onSetReadRepairChance(cfDef, cfProperties, builder);\n\n            // Strip last AND clause.\n            if (builder != null && StringUtils.contains(builder.toString(), CQLTranslator.AND_CLAUSE))\n            {\n                builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length());\n                // builder.deleteCharAt(builder.length() - 2);\n            }\n\n            // Strip last WITH clause.\n            if (builder != null && StringUtils.contains(builder.toString(), CQLTranslator.WITH_CLAUSE))\n            {\n                builder.delete(builder.lastIndexOf(CQLTranslator.WITH_CLAUSE), builder.length());\n                // builder.deleteCharAt(builder.length() - 2);\n            }\n        }\n    }\n\n    /**\n     * On set read repair chance.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the cf properties\n     * @param builder\n     *            the builder\n     */\n    private void onSetReadRepairChance(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        String dclocalReadRepairChance = cfProperties.getProperty(CassandraConstants.DCLOCAL_READ_REPAIR_CHANCE);\n        if (dclocalReadRepairChance != null)\n        {\n            try\n            {\n                if (builder != null)\n                {\n                    appendPropertyToBuilder(builder, dclocalReadRepairChance,\n                            CassandraConstants.DCLOCAL_READ_REPAIR_CHANCE);\n\n                }\n                else\n                {\n                    cfDef.setDclocal_read_repair_chance(Double.parseDouble(dclocalReadRepairChance));\n                }\n            }\n            catch (NumberFormatException nfe)\n            {\n                log.error(\"READ_REPAIR_CHANCE should be double type, Caused by: {}.\", nfe);\n                throw new SchemaGenerationException(nfe);\n            }\n        }\n    }\n\n    /**\n     * On set repair chance.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the cf properties\n     * @param builder\n     *            the builder\n     */\n    private void onSetRepairChance(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        String readRepairChance = cfProperties.getProperty(CassandraConstants.READ_REPAIR_CHANCE);\n        if (readRepairChance != null)\n        {\n            try\n            {\n                if (builder != null)\n                {\n                    appendPropertyToBuilder(builder, readRepairChance, CassandraConstants.READ_REPAIR_CHANCE);\n                }\n                else\n                {\n                    cfDef.setRead_repair_chance(Double.parseDouble(readRepairChance));\n                }\n            }\n            catch (NumberFormatException nfe)\n            {\n                log.error(\"READ_REPAIR_CHANCE should be double type, Caused by: .\", nfe);\n                throw new SchemaGenerationException(nfe);\n            }\n        }\n    }\n\n    /**\n     * On set bloom filter.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the cf properties\n     * @param builder\n     *            the builder\n     */\n    private void onSetBloomFilter(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        String bloomFilterFpChance = cfProperties.getProperty(CassandraConstants.BLOOM_FILTER_FP_CHANCE);\n        if (bloomFilterFpChance != null)\n        {\n            try\n            {\n                if (builder != null)\n                {\n                    appendPropertyToBuilder(builder, bloomFilterFpChance, CassandraConstants.BLOOM_FILTER_FP_CHANCE);\n                }\n                else\n                {\n                    cfDef.setBloom_filter_fp_chance(Double.parseDouble(bloomFilterFpChance));\n                }\n            }\n            catch (NumberFormatException nfe)\n            {\n                log.error(\"BLOOM_FILTER_FP_CHANCE should be double type, Caused by: .\", nfe);\n                throw new SchemaGenerationException(nfe);\n            }\n        }\n    }\n\n    /**\n     * On set caching.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the cf properties\n     * @param builder\n     *            the builder\n     */\n    private void onSetCaching(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        String caching = cfProperties.getProperty(CassandraConstants.CACHING);\n        if (caching != null)\n        {\n            if (builder != null)\n            {\n                appendPropertyToBuilder(builder, caching, CassandraConstants.CACHING);\n            }\n            else\n            {\n                cfDef.setCaching(caching);\n            }\n        }\n    }\n\n    /**\n     * On set gc grace.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the cf properties\n     * @param builder\n     *            the builder\n     */\n    private void onSetGcGrace(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        String gcGraceSeconds = cfProperties.getProperty(CassandraConstants.GC_GRACE_SECONDS);\n        if (gcGraceSeconds != null)\n        {\n            try\n            {\n                if (builder != null)\n                {\n                    appendPropertyToBuilder(builder, gcGraceSeconds, CassandraConstants.GC_GRACE_SECONDS);\n                }\n                else\n                {\n                    cfDef.setGc_grace_seconds(Integer.parseInt(gcGraceSeconds));\n                }\n            }\n            catch (NumberFormatException nfe)\n            {\n                log.error(\"GC_GRACE_SECONDS should be numeric type, Caused by: .\", nfe);\n                throw new SchemaGenerationException(nfe);\n            }\n        }\n    }\n\n    /**\n     * On set table id.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the cf properties\n     * @param builder\n     *            the builder\n     */\n    private void onSetTableId(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        String id = cfProperties.getProperty(CassandraConstants.ID);\n        if (id != null)\n        {\n            try\n            {\n                if (builder != null)\n                {\n                    // TODO::::not available with composite key?\n                }\n                else\n                {\n                    cfDef.setId(Integer.parseInt(id));\n                }\n            }\n            catch (NumberFormatException nfe)\n            {\n                log.error(\"Id should be numeric type, Caused by: \", nfe);\n                throw new SchemaGenerationException(nfe);\n            }\n        }\n    }\n\n    /**\n     * On set comment.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the cf properties\n     * @param builder\n     *            the builder\n     */\n    private void onSetComment(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        String comment = cfProperties.getProperty(CassandraConstants.COMMENT);\n        if (comment != null)\n        {\n            if (builder != null)\n            {\n                String comment_Str = CQLTranslator.getKeyword(CassandraConstants.COMMENT);\n                builder.append(comment_Str);\n                builder.append(CQLTranslator.EQ_CLAUSE);\n                builder.append(CQLTranslator.QUOTE_STR);\n                builder.append(comment);\n                builder.append(CQLTranslator.QUOTE_STR);\n                builder.append(CQLTranslator.AND_CLAUSE);\n\n            }\n            else\n            {\n                cfDef.setComment(comment);\n            }\n        }\n    }\n\n    /**\n     * On set replicate on write.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the cf properties\n     * @param builder\n     *            the builder\n     */\n    private void onSetReplicateOnWrite(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        String replicateOnWrite = cfProperties.getProperty(CassandraConstants.REPLICATE_ON_WRITE);\n        if (builder != null)\n        {\n            String replicateOn_Write = CQLTranslator.getKeyword(CassandraConstants.REPLICATE_ON_WRITE);\n            builder.append(replicateOn_Write);\n            builder.append(CQLTranslator.EQ_CLAUSE);\n            builder.append(Boolean.parseBoolean(replicateOnWrite));\n            builder.append(CQLTranslator.AND_CLAUSE);\n        }\n        else if (cfDef != null)\n        {\n            cfDef.setReplicate_on_write(false);\n        }\n    }\n\n    /**\n     * On set compaction threshold.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the cf properties\n     * @param builder\n     *            the builder\n     */\n    private void onSetCompactionThreshold(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        String maxCompactionThreshold = cfProperties.getProperty(CassandraConstants.MAX_COMPACTION_THRESHOLD);\n        if (maxCompactionThreshold != null)\n        {\n            try\n            {\n                if (builder != null)\n                {\n                    // Somehow these are not working for cassandra 1.1\n                    // though they claim it should work.\n                    // appendPropertyToBuilder(builder,\n                    // maxCompactionThreshold,\n                    // CassandraConstants.MAX_COMPACTION_THRESHOLD);\n                }\n                else\n                {\n                    cfDef.setMax_compaction_threshold(Integer.parseInt(maxCompactionThreshold));\n                }\n            }\n            catch (NumberFormatException nfe)\n            {\n                log.error(\"Max_Compaction_Threshold should be numeric type, Caused by: .\", nfe);\n                throw new SchemaGenerationException(nfe);\n            }\n        }\n        String minCompactionThreshold = cfProperties.getProperty(CassandraConstants.MIN_COMPACTION_THRESHOLD);\n        if (minCompactionThreshold != null)\n        {\n            try\n            {\n                if (builder != null)\n                {\n                    // Somehow these are not working for cassandra 1.1\n                    // though they claim it should work.\n                    // appendPropertyToBuilder(builder,\n                    // minCompactionThreshold,\n                    // CassandraConstants.MIN_COMPACTION_THRESHOLD);\n                }\n                else\n                {\n                    cfDef.setMin_compaction_threshold(Integer.parseInt(minCompactionThreshold));\n                }\n            }\n            catch (NumberFormatException nfe)\n            {\n                log.error(\"Min_Compaction_Threshold should be numeric type, Caused by: . \", nfe);\n                throw new SchemaGenerationException(nfe);\n            }\n        }\n    }\n\n    /**\n     * On set sub comparator.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the cf properties\n     * @param builder\n     *            the builder\n     */\n    private void onSetSubComparator(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        String subComparatorType = cfProperties.getProperty(CassandraConstants.SUBCOMPARATOR_TYPE);\n        if (subComparatorType != null && ColumnFamilyType.valueOf(cfDef.getColumn_type()) == ColumnFamilyType.Super)\n        {\n            if (builder != null)\n            {\n                // super column are not supported for composite key as of\n                // now, leaving blank place holder..\n            }\n            else\n            {\n                cfDef.setSubcomparator_type(subComparatorType);\n            }\n        }\n    }\n\n    /**\n     * On set comparator type.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the cf properties\n     * @param builder\n     *            the builder\n     */\n    private void onSetComparatorType(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        String comparatorType = cfProperties.getProperty(CassandraConstants.COMPARATOR_TYPE);\n        if (comparatorType != null)\n        {\n            if (builder != null)\n            {\n                // TODO:::nothing available.\n            }\n            else\n            {\n                cfDef.setComparator_type(comparatorType);\n            }\n        }\n    }\n\n    /**\n     * On set compaction strategy.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the cf properties\n     * @param builder\n     *            the builder\n     */\n    private void onSetCompactionStrategy(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        String compactionStrategy = cfProperties.getProperty(CassandraConstants.COMPACTION_STRATEGY);\n        if (compactionStrategy != null)\n        {\n            if (builder != null)\n            {\n                String strategy_class = CQLTranslator.getKeyword(CassandraConstants.COMPACTION_STRATEGY);\n                builder.append(strategy_class);\n                builder.append(CQLTranslator.EQ_CLAUSE);\n                builder.append(CQLTranslator.QUOTE_STR);\n                builder.append(compactionStrategy);\n                builder.append(CQLTranslator.QUOTE_STR);\n                builder.append(CQLTranslator.AND_CLAUSE);\n            }\n            else\n            {\n                cfDef.setCompaction_strategy(compactionStrategy);\n            }\n        }\n    }\n\n    /**\n     * On set key validation.\n     * \n     * @param cfDef\n     *            the cf def\n     * @param cfProperties\n     *            the cf properties\n     * @param builder\n     *            the builder\n     */\n    private void onSetKeyValidation(CfDef cfDef, Properties cfProperties, StringBuilder builder)\n    {\n        String keyValidationClass = cfProperties.getProperty(CassandraConstants.KEY_VALIDATION_CLASS);\n        if (keyValidationClass != null)\n        {\n            if (builder != null)\n            {\n                // nothing available.\n            }\n            else\n            {\n                cfDef.setKey_validation_class(keyValidationClass);\n            }\n        }\n    }\n\n    /**\n     * Checks if is cql3 enabled.\n     * \n     * @param tableInfo\n     *            the table info\n     * @return true, if is cql3 enabled\n     */\n    private boolean isCql3Enabled(TableInfo tableInfo)\n    {\n        Properties cfProperties = getColumnFamilyProperties(tableInfo);\n\n        String defaultValidationClass = cfProperties != null ? cfProperties\n                .getProperty(CassandraConstants.DEFAULT_VALIDATION_CLASS) : null;\n\n        // For normal columns\n        boolean isCounterColumnType = isCounterColumnType(tableInfo, defaultValidationClass);\n        return containsCompositeKey(tableInfo)\n                || containsCollectionColumns(tableInfo)\n                || ((cql_version != null && cql_version.equals(CassandraConstants.CQL_VERSION_3_0)) && (containsEmbeddedColumns(tableInfo) || containsElementCollectionColumns(tableInfo)))\n                && !isCounterColumnType\n                || ((cql_version != null && cql_version.equals(CassandraConstants.CQL_VERSION_3_0)) && !tableInfo\n                        .getType().equals(Type.SUPER_COLUMN_FAMILY.name()));\n    }\n\n    /**\n     * Append property to builder.\n     * \n     * @param builder\n     *            the builder\n     * @param replicateOnWrite\n     *            the replicate on write\n     * @param keyword\n     *            the keyword\n     */\n    private void appendPropertyToBuilder(StringBuilder builder, String replicateOnWrite, String keyword)\n    {\n        String replicateOn_Write = CQLTranslator.getKeyword(keyword);\n        builder.append(replicateOn_Write);\n        builder.append(CQLTranslator.EQ_CLAUSE);\n        builder.append(replicateOnWrite);\n        builder.append(CQLTranslator.AND_CLAUSE);\n    }\n\n    /**\n     * Validate compound key.\n     * \n     * @param tableInfo\n     *            the table info\n     */\n    private void validateCompoundKey(TableInfo tableInfo)\n    {\n        if (tableInfo.getType() != null && tableInfo.getType().equals(Type.SUPER_COLUMN_FAMILY.name()))\n        {\n            throw new SchemaGenerationException(\n                    \"Composite/Compound columns are not yet supported over Super column family by Cassandra\",\n                    \"cassandra\", databaseName);\n        }\n    }\n\n    /**\n     * MetaDataHandler responsible for creating column family matadata for\n     * tableInfos.\n     * \n     * @author Kuldeep.Mishra\n     * \n     */\n    private class MetaDataHandler\n    {\n        /**\n         * get Table metadata method returns the metadata of table for given\n         * tableInfo.\n         * \n         * @param tableInfo\n         *            the table info\n         * @return the table metadata\n         */\n        /**\n         * @param tableInfo\n         * @return CfDef object\n         */\n        private CfDef getTableMetadata(TableInfo tableInfo)\n        {\n            CfDef cfDef = new CfDef();\n            cfDef.setKeyspace(databaseName);\n            cfDef.setName(tableInfo.getTableName());\n            cfDef.setKey_validation_class(CassandraValidationClassMapper.getValidationClass(tableInfo.getTableIdType(),\n                    isCql3Enabled(tableInfo)));\n\n            Schema schema = CassandraPropertyReader.csmd.getSchema(databaseName);\n            tables = schema != null ? schema.getTables() : null;\n\n            Properties cfProperties = getColumnFamilyProperties(tableInfo);\n            String defaultValidationClass = null;\n            if (tableInfo.getType() != null && tableInfo.getType().equals(Type.SUPER_COLUMN_FAMILY.name()))\n            {\n                getSuperColumnFamilyMetadata(tableInfo, cfDef, defaultValidationClass);\n            }\n            else if (tableInfo.getType() != null)\n            {\n                getColumnFamilyMetadata(tableInfo, cfDef, cfProperties);\n            }\n            setColumnFamilyProperties(cfDef, cfProperties, null);\n            return cfDef;\n        }\n\n        /**\n         * Gets the super column family metadata.\n         * \n         * @param tableInfo\n         *            the table info\n         * @param cfDef\n         *            the cf def\n         * @param defaultValidationClass\n         *            the default validation class\n         * @return the super column family metadata\n         */\n        private void getSuperColumnFamilyMetadata(TableInfo tableInfo, CfDef cfDef, String defaultValidationClass)\n        {\n            if (isCounterColumnType(tableInfo, defaultValidationClass))\n            {\n                cfDef.setDefault_validation_class(CounterColumnType.class.getSimpleName());\n            }\n            cfDef.setColumn_type(\"Super\");\n            cfDef.setComparator_type(UTF8Type.class.getSimpleName());\n            cfDef.setSubcomparator_type(UTF8Type.class.getSimpleName());\n        }\n\n        /**\n         * Gets the column family metadata.\n         * \n         * @param tableInfo\n         *            the table info\n         * @param cfDef\n         *            the cf def\n         * @param cfProperties\n         *            the cf properties\n         * @return the column family metadata\n         */\n        private void getColumnFamilyMetadata(TableInfo tableInfo, CfDef cfDef, Properties cfProperties)\n        {\n            String defaultValidationClass = cfProperties != null ? cfProperties\n                    .getProperty(CassandraConstants.DEFAULT_VALIDATION_CLASS) : null;\n            cfDef.setColumn_type(STANDARDCOLUMNFAMILY);\n            cfDef.setComparator_type(UTF8Type.class.getSimpleName());\n            if (isCounterColumnType(tableInfo, defaultValidationClass))\n            {\n                getCounterColumnFamilyMetadata(tableInfo, cfDef);\n            }\n            else\n            {\n                List<ColumnDef> columnDefs = new ArrayList<ColumnDef>();\n                List<ColumnInfo> columnInfos = tableInfo.getColumnMetadatas();\n                if (columnInfos != null)\n                {\n                    for (ColumnInfo columnInfo : columnInfos)\n                    {\n                        ColumnDef columnDef = new ColumnDef();\n                        if (columnInfo.isIndexable())\n                        {\n                            IndexInfo indexInfo = tableInfo.getColumnToBeIndexed(columnInfo.getColumnName());\n                            columnDef.setIndex_type(CassandraIndexHelper.getIndexType(indexInfo.getIndexType()));\n                            // if\n                            // (!indexInfo.getIndexName().equals(indexInfo.getColumnName()))\n                            // {\n                            // columnDef.setIndex_name(indexInfo.getIndexName());\n                            // }\n                        }\n                        columnDef.setName(columnInfo.getColumnName().getBytes());\n                        columnDef.setValidation_class(CassandraValidationClassMapper.getValidationClass(\n                                columnInfo.getType(), isCql3Enabled(tableInfo)));\n                        columnDefs.add(columnDef);\n                    }\n                }\n                cfDef.setColumn_metadata(columnDefs);\n            }\n        }\n\n        /**\n         * Gets the counter column family metadata.\n         * \n         * @param tableInfo\n         *            the table info\n         * @param cfDef\n         *            the cf def\n         * @return the counter column family metadata\n         */\n        private void getCounterColumnFamilyMetadata(TableInfo tableInfo, CfDef cfDef)\n        {\n            cfDef.setDefault_validation_class(CounterColumnType.class.getSimpleName());\n            List<ColumnDef> counterColumnDefs = new ArrayList<ColumnDef>();\n            List<ColumnInfo> columnInfos = tableInfo.getColumnMetadatas();\n            if (columnInfos != null)\n            {\n                for (ColumnInfo columnInfo : columnInfos)\n                {\n                    ColumnDef columnDef = new ColumnDef();\n                    if (columnInfo.isIndexable())\n                    {\n                        IndexInfo indexInfo = tableInfo.getColumnToBeIndexed(columnInfo.getColumnName());\n                        columnDef.setIndex_type(CassandraIndexHelper.getIndexType(indexInfo.getIndexType()));\n                        // if\n                        // (!indexInfo.getIndexName().equals(indexInfo.getColumnName()))\n                        // {\n                        // columnDef.setIndex_name(indexInfo.getIndexName());\n                        // }\n                    }\n                    columnDef.setName(columnInfo.getColumnName().getBytes());\n                    columnDef.setValidation_class(CounterColumnType.class.getName());\n                    counterColumnDefs.add(columnDef);\n                }\n            }\n            cfDef.setColumn_metadata(counterColumnDefs);\n        }\n    }\n\n    /**\n     * EntityValidatorAgainstCounterColumn class responsible for validating\n     * classes against counter column family.\n     * \n     * @author Kuldeep.Mishra\n     * \n     */\n    private class EntityValidatorAgainstCounterColumn\n    {\n        /**\n         * validates entity for CounterColumnType.\n         * \n         * @param clazz\n         *            the clazz\n         * @return true, if successful\n         */\n        private boolean validateEntity(Class clazz)\n        {\n            boolean isvalid = false;\n            EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    metadata.getPersistenceUnit());\n            String tableName = metadata.getTableName();\n            if (csmd.isCounterColumn(metadata.getSchema(), tableName))\n            {\n                metadata.setCounterColumnType(true);\n                Map<String, EmbeddableType> embeddables = metaModel.getEmbeddables(clazz);\n                if (!embeddables.isEmpty())\n                {\n                    isvalid = validateEmbeddedColumns(metadata, embeddables.values()) ? true : false;\n                }\n                else\n                {\n                    EntityType entity = metaModel.entity(clazz);\n                    isvalid = validateColumns(metadata, entity.getAttributes()) ? true : false;\n                }\n                isvalid = isvalid && validateRelations(metadata) ? true : false;\n            }\n            else\n            {\n                return true;\n            }\n            return isvalid;\n        }\n\n        /**\n         * validates entity relations if any present.\n         * \n         * @param metadata\n         *            the metadata\n         * @return true, if successful\n         */\n        private boolean validateRelations(EntityMetadata metadata)\n        {\n            boolean isValid = true;\n            for (Relation relation : metadata.getRelations())\n            {\n                if (relation != null)\n                {\n                    EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                            relation.getTargetEntity());\n                    if (((relation.getType().equals(ForeignKey.ONE_TO_ONE) && !relation.isJoinedByPrimaryKey()) || relation\n                            .getType().equals(ForeignKey.MANY_TO_MANY)) && relation.getMappedBy() == null)\n                    {\n                        // validate Id column of target entity\n                        validateColumn(targetEntityMetadata.getIdAttribute().getJavaType());\n                    }\n                    else if (relation.getType().equals(ForeignKey.ONE_TO_MANY) && relation.getMappedBy() == null)\n                    {\n                        // if target entity is also counter column the validate\n                        // source\n                        // IdColumn\n                        String targetTableName = targetEntityMetadata.getTableName();\n                        if (csmd.isCounterColumn(targetEntityMetadata.getSchema(), targetTableName))\n                        {\n                            isValid = validateColumn(metadata.getIdAttribute().getJavaType()) ? true : false;\n                        }\n                    }\n                }\n            }\n            return isValid;\n        }\n\n        /**\n         * validate embedded column .\n         * \n         * @param metadata\n         *            the metadata\n         * @param embeddedColumns\n         *            the embedded columns\n         * @return true, if successful\n         */\n        private boolean validateEmbeddedColumns(EntityMetadata metadata, Collection<EmbeddableType> embeddedColumns)\n        {\n            boolean isValid = false;\n            Iterator<EmbeddableType> iter = embeddedColumns.iterator();\n            while (iter.hasNext())\n            {\n                isValid = validateColumns(metadata, iter.next().getAttributes()) ? true : false;\n            }\n            return isValid;\n        }\n\n        /**\n         * validate columns.\n         * \n         * @param metadata\n         *            the metadata\n         * @param attributes\n         *            the attributes\n         * @return true, if successful\n         */\n        private boolean validateColumns(EntityMetadata metadata, Set<Attribute> attributes)\n        {\n            boolean isValid = true;\n            for (Attribute column : attributes)\n            {\n                if (!metadata.getIdAttribute().equals(column) && !validateColumn(column.getJavaType()))\n                {\n                    isValid = false;\n                    break;\n                }\n            }\n            return isValid;\n        }\n\n        /**\n         * validate a single column.\n         * \n         * @param clazz\n         *            the clazz\n         * @return true, if successful\n         */\n        private boolean validateColumn(Class clazz)\n        {\n            boolean isValid = true;\n            if (!(clazz.equals(Integer.class) || clazz.equals(int.class) || clazz.equals(Long.class) || clazz\n                    .equals(long.class)))\n            {\n                log.warn(\n                        \"Default valdation class :{}, For counter column type, fields of Entity should be either long type or integer type.\",\n                        CounterColumnType.class.getSimpleName());\n                return isValid = false;\n            }\n            return isValid;\n        }\n    }\n\n    /**\n     * Print log in case schema doesn't match!.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param metadata\n     *            the metadata\n     * @param value_types\n     *            the value_types\n     * @param originalMetadata\n     *            the original metadata\n     * @throws CharacterCodingException\n     *             the character coding exception\n     */\n    private void onLog(TableInfo tableInfo, CqlMetadata metadata, Map<ByteBuffer, String> value_types,\n            CqlMetadata originalMetadata) throws CharacterCodingException\n    {\n        System.out.format(\"Persisted Schema for \" + tableInfo.getTableName());\n        System.out.format(\"\\n\");\n\n        System.out.format(\"Column Name: \\t\\t  Column name type\");\n        System.out.format(\"\\n\");\n\n        printInfo(originalMetadata);\n\n        System.out.format(\"\\n\");\n        System.out.format(\"Mapped schema for \" + tableInfo.getTableName());\n\n        System.out.format(\"\\n\");\n        System.out.format(\"Column Name: \\t\\t  Column name type\");\n        System.out.format(\"\\n\");\n        printInfo(metadata);\n    }\n\n    /**\n     * TODO:: need to use Message formatter for formatting message.\n     * \n     * @param metadata\n     *            CQL metadata\n     * @throws CharacterCodingException\n     *             the character coding exception\n     */\n    private void printInfo(CqlMetadata metadata) throws CharacterCodingException\n    {\n\n        Iterator<ByteBuffer> nameIter = metadata.getName_types().keySet().iterator();\n        Iterator<ByteBuffer> valueIter = metadata.getValue_types().keySet().iterator();\n\n        while (nameIter.hasNext())\n        {\n            ByteBuffer key = nameIter.next();\n            System.out.format(ByteBufferUtil.string(key) + \" \\t\\t \" + metadata.getName_types().get(key));\n            System.out.format(\"\\n\");\n        }\n\n        System.out.format(\"Column Name: \\t\\t  Column Value type\");\n        System.out.format(\"\\n\");\n        while (valueIter.hasNext())\n        {\n            ByteBuffer key = valueIter.next();\n            System.out.format(ByteBufferUtil.string(key) + \" \\t\\t \" + metadata.getValue_types().get(key));\n            System.out.format(\"\\n\");\n        }\n        System.out.format(\"\\n\");\n    }\n\n    /**\n     * Checks if is counter column type.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param defaultValidationClass\n     *            the default validation class\n     * @return true, if is counter column type\n     */\n    private boolean isCounterColumnType(TableInfo tableInfo, String defaultValidationClass)\n    {\n        return (csmd != null && csmd.isCounterColumn(databaseName, tableInfo.getTableName()))\n                || (defaultValidationClass != null\n                        && (defaultValidationClass.equalsIgnoreCase(CounterColumnType.class.getSimpleName()) || defaultValidationClass\n                                .equalsIgnoreCase(CounterColumnType.class.getName())) || (tableInfo.getType()\n                        .equals(CounterColumnType.class.getSimpleName())));\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraValidationClassMapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.schemamanager;\n\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport org.apache.cassandra.db.marshal.AbstractType;\nimport org.apache.cassandra.db.marshal.AsciiType;\nimport org.apache.cassandra.db.marshal.BooleanType;\nimport org.apache.cassandra.db.marshal.BytesType;\nimport org.apache.cassandra.db.marshal.CounterColumnType;\nimport org.apache.cassandra.db.marshal.DateType;\nimport org.apache.cassandra.db.marshal.DecimalType;\nimport org.apache.cassandra.db.marshal.DoubleType;\nimport org.apache.cassandra.db.marshal.FloatType;\nimport org.apache.cassandra.db.marshal.Int32Type;\nimport org.apache.cassandra.db.marshal.IntegerType;\nimport org.apache.cassandra.db.marshal.ListType;\nimport org.apache.cassandra.db.marshal.LongType;\nimport org.apache.cassandra.db.marshal.MapType;\nimport org.apache.cassandra.db.marshal.SetType;\nimport org.apache.cassandra.db.marshal.TimestampType;\nimport org.apache.cassandra.db.marshal.TypeParser;\nimport org.apache.cassandra.db.marshal.UTF8Type;\nimport org.apache.cassandra.db.marshal.UUIDType;\nimport org.apache.cassandra.exceptions.ConfigurationException;\nimport org.apache.cassandra.exceptions.SyntaxException;\nimport org.apache.cassandra.locator.NetworkTopologyStrategy;\nimport org.apache.cassandra.locator.SimpleStrategy;\nimport org.apache.cassandra.serializers.*;\n\n// TODO: Auto-generated Javadoc\n/**\n * The Class CassandraValidationClassMapper holds the map of validation\n * class(e.g. wrapper for default_validation_class property) mapper.\n * \n * @author Kuldeep.kumar\n */\npublic final class CassandraValidationClassMapper\n{\n\n    /** The Constant validationClassMapper. */\n    private final static HashMap<Class<?>, Class<?>> validationClassMapper = new HashMap<Class<?>, Class<?>>();\n\n    /** The Constant validationSerializerClassMapper. */\n    private final static HashMap<Class<?>, TypeSerializer<?>> validationSerializerClassMapper = new HashMap<Class<?>, TypeSerializer<?>>();\n\n    /** The Constant replication_strategies. */\n    private final static List<String> replication_strategies = new ArrayList<String>();\n\n    /** The validators and comparators. */\n    private static List<String> validatorsAndComparators = new ArrayList<String>();\n    static\n    {\n        // adding all possible strategies classes into list.\n        replication_strategies.add(SimpleStrategy.class.getName());\n        replication_strategies.add(NetworkTopologyStrategy.class.getName());\n\n        // adding all possible validator and comparators into list.\n        validatorsAndComparators.add(BytesType.class.getSimpleName());\n        validatorsAndComparators.add(AsciiType.class.getSimpleName());\n        validatorsAndComparators.add(UTF8Type.class.getSimpleName());\n        validatorsAndComparators.add(Int32Type.class.getSimpleName());\n        validatorsAndComparators.add(IntegerType.class.getSimpleName());\n        validatorsAndComparators.add(LongType.class.getSimpleName());\n        validatorsAndComparators.add(UUIDType.class.getSimpleName());\n        validatorsAndComparators.add(DateType.class.getSimpleName());\n        validatorsAndComparators.add(BooleanType.class.getSimpleName());\n        validatorsAndComparators.add(FloatType.class.getSimpleName());\n        validatorsAndComparators.add(DoubleType.class.getSimpleName());\n        validatorsAndComparators.add(DecimalType.class.getSimpleName());\n        validatorsAndComparators.add(CounterColumnType.class.getSimpleName());\n\n        // putting possible combination into map.\n        validationClassMapper.put(java.lang.String.class, UTF8Type.class);\n        validationClassMapper.put(Character.class, UTF8Type.class);\n        validationClassMapper.put(char.class, UTF8Type.class);\n\n        validationClassMapper.put(java.sql.Time.class, DateType.class);\n        validationClassMapper.put(java.lang.Integer.class, Int32Type.class);\n        validationClassMapper.put(int.class, Int32Type.class);\n        validationClassMapper.put(java.sql.Timestamp.class, DateType.class);\n        validationClassMapper.put(Short.class, IntegerType.class);\n        validationClassMapper.put(short.class, IntegerType.class);\n        validationClassMapper.put(java.math.BigDecimal.class, DecimalType.class);\n        validationClassMapper.put(java.sql.Date.class, DateType.class);\n        validationClassMapper.put(java.util.Date.class, DateType.class);\n        validationClassMapper.put(java.math.BigInteger.class, IntegerType.class);\n\n        validationClassMapper.put(java.lang.Double.class, DoubleType.class);\n        validationClassMapper.put(double.class, DoubleType.class);\n\n        validationClassMapper.put(boolean.class, BooleanType.class);\n        validationClassMapper.put(Boolean.class, BooleanType.class);\n\n        validationClassMapper.put(java.lang.Long.class, LongType.class);\n        validationClassMapper.put(long.class, LongType.class);\n\n        validationClassMapper.put(Byte.class, BytesType.class);\n        validationClassMapper.put(byte.class, BytesType.class);\n\n        validationClassMapper.put(Float.class, FloatType.class);\n        validationClassMapper.put(float.class, FloatType.class);\n\n        validationClassMapper.put(UUID.class, UUIDType.class);\n\n        validationClassMapper.put(Calendar.class, DateType.class);\n\n        validationClassMapper.put(List.class, ListType.class);\n        validationClassMapper.put(Set.class, SetType.class);\n        validationClassMapper.put(Map.class, MapType.class);\n\n        // validation serializer class mappers\n        validationSerializerClassMapper.put(java.lang.String.class, UTF8Serializer.instance);\n        validationSerializerClassMapper.put(Character.class, UTF8Serializer.instance);\n        validationSerializerClassMapper.put(char.class, UTF8Serializer.instance);\n\n        validationSerializerClassMapper.put(java.sql.Time.class, TimestampSerializer.instance);\n        validationSerializerClassMapper.put(java.lang.Integer.class, Int32Serializer.instance);\n        validationSerializerClassMapper.put(int.class, Int32Serializer.instance);\n        validationSerializerClassMapper.put(java.sql.Timestamp.class, TimestampSerializer.instance);\n        validationSerializerClassMapper.put(Short.class, IntegerSerializer.instance);\n        validationSerializerClassMapper.put(short.class, IntegerSerializer.instance);\n        validationSerializerClassMapper.put(java.math.BigDecimal.class, DecimalSerializer.instance);\n        validationSerializerClassMapper.put(java.sql.Date.class, TimestampSerializer.instance);\n        validationSerializerClassMapper.put(java.util.Date.class, TimestampSerializer.instance);\n        validationSerializerClassMapper.put(java.math.BigInteger.class, IntegerSerializer.instance);\n\n        validationSerializerClassMapper.put(java.lang.Double.class, DoubleSerializer.instance);\n        validationSerializerClassMapper.put(double.class, DoubleSerializer.instance);\n\n        validationSerializerClassMapper.put(boolean.class, BooleanSerializer.instance);\n        validationSerializerClassMapper.put(Boolean.class, BooleanSerializer.instance);\n\n        validationSerializerClassMapper.put(java.lang.Long.class, LongSerializer.instance);\n        validationSerializerClassMapper.put(long.class, LongSerializer.instance);\n\n        validationSerializerClassMapper.put(Byte.class, BytesSerializer.instance);\n        validationSerializerClassMapper.put(byte.class, BytesSerializer.instance);\n\n        validationSerializerClassMapper.put(Float.class, FloatSerializer.instance);\n        validationSerializerClassMapper.put(float.class, FloatSerializer.instance);\n\n        validationSerializerClassMapper.put(UUID.class, UUIDSerializer.instance);\n\n        validationSerializerClassMapper.put(Calendar.class, TimestampSerializer.instance);\n\n    }\n\n    /**\n     * Gets the validation class.\n     * \n     * @param dataType\n     *            the data type\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return the validation class\n     */\n    public static String getValidationClass(Class<?> dataType, boolean isCql3Enabled)\n    {\n        return getValidationClassInstance(dataType, isCql3Enabled).getSimpleName();\n    }\n\n    /**\n     * Gets the validation class instance.\n     * \n     * @param dataType\n     *            the data type\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return the validation class instance\n     */\n    public static Class<?> getValidationClassInstance(Class<?> dataType, boolean isCql3Enabled)\n    {\n        resetMapperForCQL3(isCql3Enabled);\n        Class<?> validation_class;\n        validation_class = validationClassMapper.get(dataType);\n        if (validation_class == null)\n        {\n            if (dataType.isEnum())\n            {\n                validation_class = UTF8Type.class;\n            }\n            else\n            {\n                validation_class = BytesType.class;\n            }\n        }\n        resetMapperForThrift(isCql3Enabled);\n        return validation_class;\n    }\n\n    /**\n     * Gets the validation serializer class instance.\n     * \n     * @param dataType\n     *            the data type\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return the validation serializer class instance\n     */\n    public static TypeSerializer<?> getValidationSerializerClassInstance(Class<?> dataType, boolean isCql3Enabled)\n    {\n        resetMapperForCQL3(isCql3Enabled);\n        TypeSerializer<?> validation_class;\n        validation_class = validationSerializerClassMapper.get(dataType);\n        if (validation_class == null)\n        {\n            if (dataType.isEnum())\n            {\n                validation_class = UTF8Serializer.instance;\n            }\n            else\n            {\n                validation_class = BytesSerializer.instance;\n            }\n        }\n        resetMapperForThrift(isCql3Enabled);\n        return validation_class;\n    }\n\n    /**\n     * Gets the value type name.\n     * \n     * @param dataType\n     *            the data type\n     * @param genericClasses\n     *            the generic classes\n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     * @return the value type name\n     * @throws SyntaxException\n     *             the syntax exception\n     * @throws ConfigurationException\n     *             the configuration exception\n     * @throws IllegalArgumentException\n     *             the illegal argument exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     * @throws NoSuchFieldException\n     *             the no such field exception\n     * @throws SecurityException\n     *             the security exception\n     */\n    public static String getValueTypeName(Class<?> dataType, List<Class<?>> genericClasses, boolean isCql3Enabled)\n            throws SyntaxException, ConfigurationException, IllegalArgumentException, IllegalAccessException,\n            NoSuchFieldException, SecurityException\n    {\n        String valueType;\n\n        Class<?> validation_class = getValidationClassInstance(dataType, isCql3Enabled);\n\n        valueType = validation_class.toString();\n        if (validation_class.equals(ListType.class))\n        {\n            TypeParser parser = new TypeParser(getValidationClass(genericClasses.get(0), isCql3Enabled));\n            valueType = ListType.getInstance(parser.parse(), true).toString();\n        }\n        else if (validation_class.equals(SetType.class))\n        {\n            TypeParser parser = new TypeParser(getValidationClass(genericClasses.get(0), isCql3Enabled));\n            valueType = SetType.getInstance(parser.parse(), true).toString();\n        }\n        else if (validation_class.equals(MapType.class))\n        {\n            Class keyClass = CassandraValidationClassMapper.getValidationClassInstance(genericClasses.get(0), true);\n            Class valueClass = CassandraValidationClassMapper.getValidationClassInstance(genericClasses.get(1), true);\n\n            Object keyClassInstance = keyClass.getDeclaredField(\"instance\").get(null);\n            Object valueClassInstance = valueClass.getDeclaredField(\"instance\").get(null);\n\n            valueType = MapType.getInstance((AbstractType) keyClassInstance, (AbstractType) valueClassInstance, true)\n                    .toString();\n            // TypeParser keyParser = new\n            // TypeParser(getValidationClass(genericClasses.get(0),\n            // isCql3Enabled));\n            // TypeParser valueParser = new\n            // TypeParser(getValidationClass(genericClasses.get(1),\n            // isCql3Enabled));\n            // valueType = MapType.getInstance(keyParser,\n            // valueParser).toString();\n        }\n        return valueType;\n    }\n\n    /**\n     * Gets the replication strategies.\n     * \n     * @return the replication strategies\n     */\n    public static List<String> getReplicationStrategies()\n    {\n        return replication_strategies;\n    }\n\n    /**\n     * Gets the validators and comparators.\n     * \n     * @return the validatorsAndComparators\n     */\n    public static List<String> getValidatorsAndComparators()\n    {\n        return validatorsAndComparators;\n    }\n\n    /**\n     * Reset mapper for cq l3.\n     * \n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     */\n    private static void resetMapperForCQL3(boolean isCql3Enabled)\n    {\n        if (isCql3Enabled)\n        {\n            validationClassMapper.put(Byte.class, Int32Type.class);\n            validationClassMapper.put(byte.class, Int32Type.class);\n            validationClassMapper.put(Short.class, Int32Type.class);\n            validationClassMapper.put(short.class, Int32Type.class);\n            validationClassMapper.put(java.sql.Time.class, TimestampType.class);\n            validationClassMapper.put(java.sql.Date.class, TimestampType.class);\n            validationClassMapper.put(java.util.Date.class, TimestampType.class);\n            validationClassMapper.put(java.sql.Timestamp.class, TimestampType.class);\n\n        }\n    }\n\n    /**\n     * Reset mapper for thrift.\n     * \n     * @param isCql3Enabled\n     *            the is cql3 enabled\n     */\n    private static void resetMapperForThrift(boolean isCql3Enabled)\n    {\n        if (isCql3Enabled)\n        {\n            validationClassMapper.put(Byte.class, BytesType.class);\n            validationClassMapper.put(byte.class, BytesType.class);\n            validationClassMapper.put(Short.class, IntegerType.class);\n            validationClassMapper.put(short.class, IntegerType.class);\n            validationClassMapper.put(java.sql.Time.class, DateType.class);\n            validationClassMapper.put(java.sql.Date.class, DateType.class);\n            validationClassMapper.put(java.util.Date.class, DateType.class);\n            validationClassMapper.put(java.sql.Timestamp.class, DateType.class);\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/service/CassandraHost.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.service;\n\nimport net.dataforte.cassandra.pool.HostFailoverPolicy;\n\nimport org.apache.commons.lang.builder.HashCodeBuilder;\n\nimport com.impetus.kundera.service.Host;\n\n/**\n * Cassandra Host configuration.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class CassandraHost implements Host\n{\n\n    public static final int DEFAULT_PORT = 9160;\n\n    public static final int DEFAULT_SHOCKET_TIMEOUT = 120000;\n\n    public static final int DEFAULT_MAX_ACTIVE = 30;\n\n    // Cap on the number of \"idle\" instances in the pool.\n    public static final int DEFAULT_MAX_IDLE = 10;\n\n    // Minimum number of idle objects to maintain in each of the nodes.\n    public static final int DEFAULT_MIN_IDLE = 5;\n\n    // Cap on the total number of instances from all nodes combined.\n    public static final int DEFAULT_MAX_TOTAL = 50;\n\n    private int maxActive;\n\n    // Cap on the number of \"idle\" instances in the pool.\n    private int maxIdle;\n\n    // Minimum number of idle objects to maintain in each of the nodes.\n    private int minIdle;\n\n    // Cap on the total number of instances from all nodes combined.\n    private int maxTotal;\n\n    private String host;\n\n    private int port;\n\n    private int initialSize;\n\n    private boolean testOnBorrow;\n\n    private boolean testOnConnect;\n\n    private boolean testOnReturn;\n\n    private boolean testWhileIdle;\n\n    private int socketTimeOut;\n\n    private HostFailoverPolicy hostFailoverPolicy;\n\n    private boolean retryHost;\n\n    private String userName;\n\n    private String password;\n\n    private int maxWait;\n\n    public CassandraHost(String host)\n    {\n        this.host = host;\n        this.port = DEFAULT_PORT;\n    }\n\n    public CassandraHost(String host, int port)\n    {\n        this.host = host;\n        this.port = port;\n    }\n\n    @Override\n    public String getHost()\n    {\n        return host;\n    }\n\n    @Override\n    public int getPort()\n    {\n        return port;\n    }\n\n    @Override\n    public boolean equals(Object obj)\n    {\n        if (!(obj instanceof CassandraHost))\n        {\n            return false;\n        }\n        CassandraHost other = (CassandraHost) obj;\n        return other.host.equals(this.host) && other.port == this.port;\n    }\n\n    @Override\n    public int hashCode()\n    {\n        StringBuilder builder = new StringBuilder(host);\n        builder.append(port);\n        return HashCodeBuilder.reflectionHashCode(builder);\n    }\n\n    @Override\n    public String toString()\n    {\n        StringBuilder builder = new StringBuilder(host);\n        builder.append(\":\");\n        builder.append(port);\n        return builder.toString();\n    }\n\n    public void setInitialSize(int initialSize)\n    {\n        this.initialSize = initialSize;\n    }\n\n    public void setTestOnBorrow(boolean testOnBorrow)\n    {\n        this.testOnBorrow = testOnBorrow;\n    }\n\n    public void setTestOnConnect(boolean testOnConnect)\n    {\n        this.testOnConnect = testOnConnect;\n    }\n\n    public void setTestOnReturn(boolean testOnReturn)\n    {\n        this.testOnReturn = testOnReturn;\n    }\n\n    public void setTestWhileIdle(boolean testWhileIdle)\n    {\n        this.testWhileIdle = testWhileIdle;\n    }\n\n    public void setSocketTimeout(int socketTimeOut)\n    {\n        this.socketTimeOut = socketTimeOut;\n    }\n\n    /**\n     * @return the maxTotal\n     */\n    public int getMaxTotal()\n    {\n        return maxTotal;\n    }\n\n    /**\n     * @param maxTotal\n     *            the maxTotal to set\n     */\n    public void setMaxTotal(int maxTotal)\n    {\n        this.maxTotal = maxTotal;\n    }\n\n    /**\n     * @return the maxActive\n     */\n    public int getMaxActive()\n    {\n        return maxActive;\n    }\n\n    /**\n     * @return the maxIdle\n     */\n    public int getMaxIdle()\n    {\n        return maxIdle;\n    }\n\n    /**\n     * @return the minIdle\n     */\n    public int getMinIdle()\n    {\n        return minIdle;\n    }\n\n    /**\n     * @param maxActive\n     *            the maxActive to set\n     */\n    public void setMaxActive(int maxActive)\n    {\n        this.maxActive = maxActive;\n    }\n\n    /**\n     * @param maxIdle\n     *            the maxIdle to set\n     */\n    public void setMaxIdle(int maxIdle)\n    {\n        this.maxIdle = maxIdle;\n    }\n\n    /**\n     * @param minIdle\n     *            the minIdle to set\n     */\n    public void setMinIdle(int minIdle)\n    {\n        this.minIdle = minIdle;\n    }\n\n    /**\n     * @return the socketTimeOut\n     */\n    public int getSocketTimeOut()\n    {\n        return socketTimeOut;\n    }\n\n    /**\n     * @param socketTimeOut\n     *            the socketTimeOut to set\n     */\n    public void setSocketTimeOut(int socketTimeOut)\n    {\n        this.socketTimeOut = socketTimeOut;\n    }\n\n    /**\n     * @return the initialSize\n     */\n    public int getInitialSize()\n    {\n        return initialSize;\n    }\n\n    /**\n     * @return the testOnBorrow\n     */\n    public boolean isTestOnBorrow()\n    {\n        return testOnBorrow;\n    }\n\n    /**\n     * @return the testOnConnect\n     */\n    public boolean isTestOnConnect()\n    {\n        return testOnConnect;\n    }\n\n    /**\n     * @return the testOnReturn\n     */\n    public boolean isTestOnReturn()\n    {\n        return testOnReturn;\n    }\n\n    /**\n     * @return the testWhileIdle\n     */\n    public boolean isTestWhileIdle()\n    {\n        return testWhileIdle;\n    }\n\n    public HostFailoverPolicy getHostFailoverPolicy()\n    {\n        return this.hostFailoverPolicy;\n    }\n\n    public void setHostFailoverPolicy(HostFailoverPolicy hostFailoverPolicy)\n    {\n        this.hostFailoverPolicy = hostFailoverPolicy;\n    }\n\n    public boolean isRetryHost()\n    {\n        return retryHost;\n    }\n\n    public void setRetryHost(boolean retryHost)\n    {\n        this.retryHost = retryHost;\n    }\n\n    @Override\n    public String getUser()\n    {\n        return this.userName;\n    }\n\n    @Override\n    public String getPassword()\n    {\n        return this.password;\n    }\n\n    public void setUserName(String userName)\n    {\n        this.userName = userName;\n    }\n\n    public void setPassword(String password)\n    {\n        this.password = password;\n    }\n\n    public void setMaxWait(int maxWait)\n    {\n        this.maxWait = maxWait;\n    }\n\n    public int getMaxWait()\n    {\n        return this.maxWait;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/service/CassandraHostConfiguration.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.service;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.concurrent.CopyOnWriteArrayList;\n\nimport net.dataforte.cassandra.pool.HostFailoverPolicy;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.config.CassandraPropertyReader.CassandraSchemaMetadata;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection.Server;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.service.Host;\nimport com.impetus.kundera.service.HostConfiguration;\n\n/**\n * Holds host configuration for cassandra specific settings.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class CassandraHostConfiguration extends HostConfiguration\n{\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(CassandraHostConfiguration.class);\n\n    public CassandraHostConfiguration(Map externalProperties, CassandraSchemaMetadata csmd, String persistenceUnit,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(externalProperties, csmd != null ? csmd.getConnectionServers() : new ArrayList<Server>(),\n                persistenceUnit, kunderaMetadata);\n        connectionProperties.putAll(csmd.getConnectionProperties());\n        String property = csmd.getConnectionProperties().getProperty(Constants.RETRY_DELAY);\n        if (StringUtils.isNumeric(property))\n        {\n            retryDelay = Integer.parseInt(property);\n        }\n    }\n\n    protected void buildHosts(List<Server> servers, List<Host> hostsList)\n    {\n        List<CassandraHost> cassandraHosts = new CopyOnWriteArrayList<CassandraHost>();\n        for (Server server : servers)\n        {\n            String host = server.getHost().trim();\n            String portAsString = server.getPort().trim();\n            onValidation(host, portAsString);\n            Properties serverProperties = server.getProperties();\n            CassandraHost cassandraHost = new CassandraHost(host, Integer.parseInt(portAsString));\n            setConfig(cassandraHost, null, serverProperties);\n            cassandraHosts.add(cassandraHost);\n            hostsList.add(cassandraHost);\n        }\n    }\n\n    protected void buildHosts(String hosts, String portAsString, List<Host> hostsList)\n    {\n        String[] hostVals = hosts.split(\",\");\n        List<CassandraHost> cassandraHosts = new CopyOnWriteArrayList<CassandraHost>();\n        for (int x = 0; x < hostVals.length; x++)\n        {\n            String host = hostVals[x].trim();\n            portAsString = portAsString.trim();\n            onValidation(host, portAsString);\n            int port = Integer.parseInt(portAsString);\n            CassandraHost cassandraHost = port == CassandraHost.DEFAULT_PORT ? new CassandraHost(host)\n                    : new CassandraHost(host, port);\n            setConfig(cassandraHost, persistenceUnitMetadata.getProperties(), externalProperties);\n            cassandraHosts.add(cassandraHost);\n            hostsList.add(cassandraHost);\n        }\n    }\n\n    @Override\n    protected void setConfig(Host host, Properties props, Map externalProperties)\n    {\n        CassandraHost cassandraHost = (CassandraHost) host;\n        String maxActivePerNode = null;\n        String maxIdlePerNode = null;\n        String minIdlePerNode = null;\n        String maxTotal = null;\n        String testOnBorrow = null;\n        String testWhileIdle = null;\n        String testOnConnect = null;\n        String testOnReturn = null;\n        String socketTimeOut = null;\n        String userName = null;\n        String password = null;\n        String maxWaitInMilli = null;\n        String failOverPolicy = null;\n        boolean hostRetry = false;\n        if (externalProperties != null)\n        {\n            connectionProperties.putAll(externalProperties);\n\n            maxActivePerNode = (String) connectionProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE);\n            maxIdlePerNode = (String) connectionProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_IDLE);\n            minIdlePerNode = (String) connectionProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MIN_IDLE);\n            maxTotal = (String) connectionProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_TOTAL);\n            testOnBorrow = (String) connectionProperties.get(CassandraConstants.TEST_ON_BORROW);\n            testOnConnect = (String) connectionProperties.get(CassandraConstants.TEST_ON_CONNECT);\n            testOnReturn = (String) connectionProperties.get(CassandraConstants.TEST_ON_RETURN);\n            testWhileIdle = (String) connectionProperties.get(CassandraConstants.TEST_WHILE_IDLE);\n            socketTimeOut = (String) connectionProperties.get(CassandraConstants.SOCKET_TIMEOUT);\n            userName = (String) connectionProperties.get(PersistenceProperties.KUNDERA_USERNAME);\n            password = (String) connectionProperties.get(PersistenceProperties.KUNDERA_PASSWORD);\n            maxWaitInMilli = (String) connectionProperties.get(CassandraConstants.MAX_WAIT);\n            hostRetry = Boolean.parseBoolean((String)connectionProperties.get(Constants.RETRY));\n        }\n\n        if (props != null)\n        {\n            if (maxActivePerNode == null)\n            {\n                maxActivePerNode = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE) != null ? props\n                        .getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE).trim() : null;\n            }\n            if (maxIdlePerNode == null)\n            {\n                maxIdlePerNode = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_IDLE) != null ? props\n                        .getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_IDLE).trim() : null;\n            }\n            if (minIdlePerNode == null)\n            {\n                minIdlePerNode = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MIN_IDLE) != null ? props\n                        .getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MIN_IDLE).trim() : null;\n            }\n            if (maxTotal == null)\n            {\n                maxTotal = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_TOTAL) != null ? props\n                        .getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_TOTAL).trim() : null;\n            }\n            if (maxWaitInMilli == null)\n            {\n                maxWaitInMilli = props.getProperty(CassandraConstants.MAX_WAIT) != null ? props.getProperty(\n                        CassandraConstants.MAX_WAIT).trim() : null;\n            }\n\n            if (userName == null)\n            {\n                userName = props.getProperty(PersistenceProperties.KUNDERA_USERNAME);\n                password = props.getProperty(PersistenceProperties.KUNDERA_PASSWORD);\n            }\n        }\n        try\n        {\n            if (!StringUtils.isEmpty(maxActivePerNode))\n            {\n                cassandraHost.setInitialSize(Integer.parseInt(maxActivePerNode));\n                cassandraHost.setMaxActive(Integer.parseInt(maxActivePerNode));\n            }\n\n            if (!StringUtils.isEmpty(maxIdlePerNode))\n            {\n                cassandraHost.setMaxIdle(Integer.parseInt(maxIdlePerNode));\n            }\n\n            if (!StringUtils.isEmpty(minIdlePerNode))\n            {\n                cassandraHost.setMinIdle(Integer.parseInt(minIdlePerNode));\n            }\n\n            if (!StringUtils.isEmpty(maxTotal))\n            {\n                cassandraHost.setMaxActive(Integer.parseInt(maxTotal));\n            }\n            if (!StringUtils.isEmpty(maxWaitInMilli))\n            {\n                cassandraHost.setMaxWait(Integer.parseInt(maxWaitInMilli));\n            }\n\n            cassandraHost.setTestOnBorrow(Boolean.parseBoolean(testOnBorrow));\n            cassandraHost.setTestOnConnect(Boolean.parseBoolean(testOnConnect));\n            cassandraHost.setTestOnReturn(Boolean.parseBoolean(testOnReturn));\n            cassandraHost.setTestWhileIdle(Boolean.parseBoolean(testWhileIdle));\n            cassandraHost.setHostFailoverPolicy(getFailoverPolicy(failOverPolicy));\n            cassandraHost.setRetryHost(hostRetry);\n            cassandraHost.setUserName(userName);\n            cassandraHost.setPassword(password);\n\n            if (!StringUtils.isEmpty(socketTimeOut))\n            {\n                cassandraHost.setSocketTimeout(Integer.parseInt(socketTimeOut));\n            }\n            else\n            {\n                cassandraHost.setSocketTimeout(CassandraHost.DEFAULT_SHOCKET_TIMEOUT);\n            }\n        }\n        catch (NumberFormatException e)\n        {\n            logger.warn(\"Some Connection pool related property couldn't be parsed. Default pool policy would be used\");\n        }\n    }\n\n    /**\n     * \n     * @return Host array\n     */\n    public List<Host> getCassandraHosts()\n    {\n        return hostsList;\n    }\n\n    /**\n     * Resolve failover policy for Cassandra thrift.\n     * \n     * @param failoverOption\n     * @return\n     */\n    private HostFailoverPolicy getFailoverPolicy(String failoverOption)\n    {\n        if (failoverOption != null)\n        {\n            if (Constants.FAIL_FAST.equals(failoverOption))\n            {\n                return HostFailoverPolicy.FAIL_FAST;\n            }\n            else if (Constants.ON_FAIL_TRY_ALL_AVAILABLE.equals(failoverOption))\n            {\n                return HostFailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE;\n            }\n            else if (Constants.ON_FAIL_TRY_ONE_NEXT_AVAILABLE.equals(failoverOption))\n            {\n                return HostFailoverPolicy.ON_FAIL_TRY_ONE_NEXT_AVAILABLE;\n            }\n            else\n            {\n                logger.warn(\"Invalid failover policy {}, using default {} \", failoverOption,\n                        HostFailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE.name());\n                return HostFailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE;\n            }\n        }\n        return HostFailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE;\n    }\n\n    /**\n     * \n     * @return\n     */\n    public int getRetryDelay()\n    {\n        return retryDelay;\n    }\n\n    /**\n     * \n     * @param host\n     * @param port\n     * @return CassandraHosts\n     */\n    public CassandraHost getCassandraHost(String host, int port)\n    {\n        for (Host cassandraHost : hostsList)\n        {\n            if (((CassandraHost) cassandraHost).equals(new CassandraHost(host, port)))\n            {\n                return (CassandraHost) cassandraHost;\n            }\n        }\n        return null;\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/service/CassandraRetryService.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.service;\n\nimport java.util.Iterator;\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.concurrent.TimeUnit;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.common.CassandraClientFactory;\nimport com.impetus.client.cassandra.common.CassandraUtilities;\nimport com.impetus.kundera.loader.ClientFactory;\nimport com.impetus.kundera.service.Host;\nimport com.impetus.kundera.service.HostConfiguration;\nimport com.impetus.kundera.service.policy.RetryService;\n\n/**\n * Cassandra retry service, retries for downed cassandra server with a fix\n * delay, and add it to hostspool map when it up.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class CassandraRetryService extends RetryService\n{\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(CassandraRetryService.class);\n\n    private LinkedBlockingQueue<CassandraHost> downedHostQueue;\n\n    private ClientFactory clientFactory;\n\n    public CassandraRetryService(HostConfiguration configuration, ClientFactory clientFactory)\n    {\n        super(((CassandraHostConfiguration) configuration).getRetryDelay());\n        downedHostQueue = new LinkedBlockingQueue<CassandraHost>();\n        this.clientFactory = clientFactory;\n        sf = executor.scheduleWithFixedDelay(new RetryRunner(), this.retryDelayInSeconds, this.retryDelayInSeconds,\n                TimeUnit.SECONDS);\n    }\n\n    @Override\n    protected boolean verifyConnection(Host host)\n    {\n        return CassandraUtilities.verifyConnection(host.getHost(), host.getPort());\n    }\n\n    class RetryRunner implements Runnable\n    {\n\n        @Override\n        public void run()\n        {\n            if (!downedHostQueue.isEmpty())\n            {\n                try\n                {\n                    retryDownedHosts();\n                }\n                catch (Throwable t)\n                {\n                    logger.error(\"Error while retrying downed hosts caused by : \", t);\n                }\n            }\n        }\n\n        private void retryDownedHosts()\n        {\n            Iterator<CassandraHost> iter = downedHostQueue.iterator();\n            while (iter.hasNext())\n            {\n                CassandraHost host = iter.next();\n\n                if (host == null)\n                {\n                    continue;\n                }\n\n                boolean reconnected = verifyConnection(host);\n                if (reconnected)\n                {\n                    ((CassandraClientFactory) clientFactory).addCassandraHost(host);\n                    iter.remove();\n                }\n            }\n        }\n    }\n\n    public void add(final CassandraHost cassandraHost)\n    {\n        downedHostQueue.add(cassandraHost);\n\n        // schedule a check of this host immediately,\n        executor.submit(new Runnable()\n        {\n            @Override\n            public void run()\n            {\n                if (verifyConnection(cassandraHost))\n                {\n                    if (((CassandraClientFactory) clientFactory).addCassandraHost(cassandraHost))\n                    {\n                        downedHostQueue.remove(cassandraHost);\n                    }\n                }\n            }\n        });\n    }\n\n    @Override\n    public void shutdown()\n    {\n        downedHostQueue.clear();\n        if (sf != null)\n        {\n            sf.cancel(true);\n        }\n        if (executor != null)\n        {\n            executor.shutdownNow();\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/CQLTranslator.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift;\n\nimport java.lang.reflect.Field;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Calendar;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.ElementCollection;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.apache.cassandra.db.marshal.BooleanType;\nimport org.apache.cassandra.db.marshal.BytesType;\nimport org.apache.cassandra.db.marshal.CounterColumnType;\nimport org.apache.cassandra.db.marshal.DateType;\nimport org.apache.cassandra.db.marshal.DecimalType;\nimport org.apache.cassandra.db.marshal.DoubleType;\nimport org.apache.cassandra.db.marshal.FloatType;\nimport org.apache.cassandra.db.marshal.Int32Type;\nimport org.apache.cassandra.db.marshal.IntegerType;\nimport org.apache.cassandra.db.marshal.ListType;\nimport org.apache.cassandra.db.marshal.LongType;\nimport org.apache.cassandra.db.marshal.MapType;\nimport org.apache.cassandra.db.marshal.SetType;\nimport org.apache.cassandra.db.marshal.TimestampType;\nimport org.apache.cassandra.db.marshal.UTF8Type;\nimport org.apache.cassandra.db.marshal.UUIDType;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.apache.commons.codec.binary.Hex;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.common.CassandraUtilities;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.TableGeneratorDiscriptor;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * CQL translator interface, to translate all CRUD operations into CQL queries.\n * In case compound primary key is boolean, we need to\n * $COLUMNS,$COLUMNFAMILY,$COLUMNVALUES : They need to be comma separated.\n * $COLUMNVALUES : It has to be according to data type(add \"'\" only for\n * text/string)\n * \n * @author vivek.mishra\n */\npublic final class CQLTranslator\n{\n\n    /** The Constant CREATE_COLUMNFAMILY_QUERY. */\n    public static final String CREATE_COLUMNFAMILY_QUERY = \"CREATE COLUMNFAMILY $COLUMNFAMILY ($COLUMNS\";\n\n    /** The Constant ADD_PRIMARYKEY_CLAUSE. */\n    public static final String ADD_PRIMARYKEY_CLAUSE = \" , PRIMARY KEY($COLUMNS))\";\n\n    /** The Constant SELECTALL_QUERY. */\n    public static final String SELECTALL_QUERY = \"SELECT * FROM $COLUMNFAMILY\";\n\n    /** The Constant SELECT_COUNT_QUERY. */\n    public static final String SELECT_COUNT_QUERY = \"SELECT COUNT(*) FROM $COLUMNFAMILY\";\n\n    /** The Constant ADD_WHERE_CLAUSE. */\n    public static final String ADD_WHERE_CLAUSE = \" WHERE \";\n\n    /** The Constant SELECT_QUERY. */\n    public static final String SELECT_QUERY = \"SELECT $COLUMNS FROM $COLUMNFAMILY\";\n\n    /** The Constant INSERT_QUERY. */\n    public static final String INSERT_QUERY = \" INSERT INTO $COLUMNFAMILY($COLUMNS) VALUES($COLUMNVALUES) \";\n\n    /** The Constant DELETE_QUERY. */\n    public static final String DELETE_QUERY = \"DELETE FROM $COLUMNFAMILY\";\n\n    /** The Constant COLUMN_FAMILY. */\n    public static final String COLUMN_FAMILY = \"$COLUMNFAMILY\";\n\n    /** The Constant COLUMNS. */\n    public static final String COLUMNS = \"$COLUMNS\";\n\n    /** The Constant COLUMN_VALUES. */\n    public static final String COLUMN_VALUES = \"$COLUMNVALUES\";\n\n    /** The Constant AND_CLAUSE. */\n    public static final String AND_CLAUSE = \" AND \";\n\n    /** The Constant SORT_CLAUSE. */\n    public static final String SORT_CLAUSE = \" ORDER BY \";\n\n    /** The Constant EQ_CLAUSE. */\n    public static final String EQ_CLAUSE = \"=\";\n\n    /** The Constant WITH_CLAUSE. */\n    public static final String WITH_CLAUSE = \" WITH \";\n\n    /** The Constant QUOTE_STR. */\n    public static final String QUOTE_STR = \"'\";\n\n    /** The Constant LIMIT. */\n    public static final String LIMIT = \" LIMIT \";\n\n    /** The Constant CREATE_INDEX_QUERY. */\n    public static final String CREATE_INDEX_QUERY = \"CREATE INDEX ON $COLUMNFAMILY ($COLUMNS)\";\n\n    /** The Constant BATCH_QUERY. */\n    public static final String BATCH_QUERY = \"BEGIN BATCH $STATEMENT \";\n\n    /** The Constant STATEMENT. */\n    public static final String STATEMENT = \"$STATEMENT\";\n\n    /** The Constant APPLY_BATCH. */\n    public static final String APPLY_BATCH = \" APPLY BATCH\";\n\n    /** The Constant USING_CONSISTENCY. */\n    public static final String USING_CONSISTENCY = \"$USING CONSISTENCY\";\n\n    /** The Constant CONSISTENCY_LEVEL. */\n    public static final String CONSISTENCY_LEVEL = \"$CONSISTENCYLEVEL\";\n\n    /** The Constant DROP_TABLE. */\n    public static final String DROP_TABLE = \"drop columnfamily $COLUMN_FAMILY\";\n\n    /** The Constant UPDATE_QUERY. */\n    public static final String UPDATE_QUERY = \"UPDATE $COLUMNFAMILY \";\n\n    /** The Constant ADD_SET_CLAUSE. */\n    public static final String ADD_SET_CLAUSE = \"SET \";\n\n    /** The Constant COMMA_STR. */\n    public static final String COMMA_STR = \", \";\n\n    /** The Constant INCR_COUNTER. */\n    public static final String INCR_COUNTER = \"+\";\n\n    /** The Constant TOKEN. */\n    public static final String TOKEN = \"token(\";\n\n    /** The Constant CLOSE_BRACKET. */\n    public static final String CLOSE_BRACKET = \")\";\n\n    /** The Constant SPACE_STRING. */\n    public static final String SPACE_STRING = \" \";\n\n    /** The Constant IN_CLAUSE. */\n    public static final String IN_CLAUSE = \"IN\";\n\n    /** The Constant OPEN_BRACKET. */\n    public static final String OPEN_BRACKET = \"(\";\n\n    /** The Constant CREATE_COLUMNFAMILY_CLUSTER_ORDER. */\n    public static final String CREATE_COLUMNFAMILY_CLUSTER_ORDER = \" WITH CLUSTERING ORDER BY ($COLUMNS\";\n\n    /** The Constant DEFAULT_KEY_NAME. */\n    public static final String DEFAULT_KEY_NAME = \"key\";\n\n    /** The Constant CREATE_KEYSPACE. */\n    public static final String CREATE_KEYSPACE = \"CREATE KEYSPACE IF NOT EXISTS $KEYSPACE WITH REPLICATION = { 'class':'$CLASS',$REPLICATION} and durable_writes = '$DURABLE_WRITES'\";\n\n    /** The Constant SIMPLE_REPLICATION. */\n    public static final String SIMPLE_REPLICATION = \"'replication_factor':$REPLICATION_FACTOR\";\n\n    /** The Constant DURABLE_WRITES. */\n    public static final String DURABLE_WRITES = \"durable_writes=$DURABLE_WRITES\";\n\n    /** The Constant CREATE_TYPE. */\n    public static final String CREATE_TYPE = \"CREATE TYPE IF NOT EXISTS $TYPE ($COLUMNS\";\n\n    /** The Constant TYPE. */\n    public static final String TYPE = \"$TYPE\";\n\n    /** The Constant FROZEN. */\n    public static final String FROZEN = \"frozen\";\n\n    /** The Constant BEGIN_COUNTER_BATCH. */\n    public static final String BEGIN_COUNTER_BATCH = \"BEGIN COUNTER BATCH\";\n\n    /** The Constant BEGIN_BATCH. */\n    public static final String BEGIN_BATCH = \"BEGIN BATCH\";\n\n    /**\n     * Instantiates a new CQL translator.\n     */\n    public CQLTranslator()\n    {\n\n    }\n\n    /**\n     * The Enum TranslationType.\n     */\n    public static enum TranslationType\n    {\n\n        /** The column. */\n        COLUMN,\n        /** The value. */\n        VALUE,\n        /** The all. */\n        ALL;\n    }\n\n    /**\n     * Prepares column name or column values.\n     * \n     * @param record\n     *            entity.\n     * @param entityMetadata\n     *            entity meta data\n     * @param type\n     *            translation type.\n     * @param externalProperties\n     *            the external properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @return Map containing translation type as key and string as translated\n     *         CQL string.\n     */\n    public HashMap<TranslationType, Map<String, StringBuilder>> prepareColumnOrColumnValues(final Object record,\n            final EntityMetadata entityMetadata, TranslationType type, Map<String, Object> externalProperties,\n            final KunderaMetadata kunderaMetadata)\n    {\n        HashMap<TranslationType, Map<String, StringBuilder>> parsedColumnOrColumnValue = new HashMap<CQLTranslator.TranslationType, Map<String, StringBuilder>>();\n        if (type == null)\n        {\n            throw new TranslationException(\"Please specify TranslationType: either COLUMN or VALUE\");\n        }\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n        Class entityClazz = entityMetadata.getEntityClazz();\n        EntityType entityType = metaModel.entity(entityClazz);\n\n        Map<String, StringBuilder> builders = new HashMap<String, StringBuilder>();\n        Map<String, StringBuilder> columnBuilders = new HashMap<String, StringBuilder>();\n\n        onTranslation(record, entityMetadata, type, metaModel, entityClazz, entityType, builders, columnBuilders,\n                externalProperties, kunderaMetadata);\n\n        for (String tableName : columnBuilders.keySet())\n        {\n            StringBuilder builder = builders.get(tableName);\n            StringBuilder columnBuilder = columnBuilders.get(tableName);\n\n            if (type.equals(TranslationType.ALL) || type.equals(TranslationType.VALUE))\n            {\n                builder.deleteCharAt(builder.length() - 1);\n            }\n\n            if (type.equals(TranslationType.ALL) || type.equals(TranslationType.COLUMN))\n            {\n                columnBuilder.deleteCharAt(columnBuilder.length() - 1);\n            }\n        }\n        parsedColumnOrColumnValue.put(TranslationType.COLUMN, columnBuilders);\n\n        parsedColumnOrColumnValue.put(TranslationType.VALUE, builders);\n\n        return parsedColumnOrColumnValue;\n    }\n\n    /**\n     * Gets the CQL type.\n     * \n     * @param internalClazz\n     *            the internal clazz\n     * @return the CQL type\n     */\n    public static String getCQLType(String internalClazz)\n    {\n        return InternalToCQLMapper.getType(internalClazz);\n    }\n\n    /**\n     * Gets the keyword.\n     * \n     * @param property\n     *            the property\n     * @return the keyword\n     */\n    public static String getKeyword(String property)\n    {\n        return CQLKeywordMapper.getType(property);\n    }\n\n    /**\n     * On translation.\n     * \n     * @param record\n     *            the record\n     * @param m\n     *            the m\n     * @param type\n     *            the type\n     * @param metaModel\n     *            the meta model\n     * @param entityClazz\n     *            the entity clazz\n     * @param entityType\n     *            the entity type\n     * @param builders\n     *            the builders\n     * @param columnBuilders\n     *            the column builders\n     * @param externalProperties\n     *            the external properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    private void onTranslation(final Object record, final EntityMetadata m, TranslationType type,\n            MetamodelImpl metaModel, Class entityClazz, EntityType entityType, Map<String, StringBuilder> builders,\n            Map<String, StringBuilder> columnBuilders, Map<String, Object> externalProperties,\n            final KunderaMetadata kunderaMetadata)\n    {\n        Set<Attribute> attributes = entityType.getAttributes();\n        Iterator<Attribute> iterator = attributes.iterator();\n        while (iterator.hasNext())\n        {\n            Attribute attribute = iterator.next();\n\n            // Populating table name.\n            String tableName = ((AbstractAttribute) attribute).getTableName() != null ? ((AbstractAttribute) attribute)\n                    .getTableName() : m.getTableName();\n\n            StringBuilder columnBuilder = columnBuilders.get(tableName);\n            if (columnBuilder == null)\n            {\n                columnBuilder = new StringBuilder();\n                columnBuilders.put(tableName, columnBuilder);\n            }\n\n            StringBuilder builder = builders.get(tableName);\n            if (builder == null)\n            {\n                builder = new StringBuilder();\n                builders.put(tableName, builder);\n            }\n            Field field = (Field) attribute.getJavaMember();\n            if (!attribute.equals(m.getIdAttribute())\n                    && !((AbstractAttribute) attribute).getJPAColumnName().equals(\n                            ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName()))\n            {\n                if (metaModel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType()))\n                {\n                    // create embedded entity persisting format\n                    if (field.isAnnotationPresent(ElementCollection.class))\n                    {\n                        // handle embeddable collection\n                        // check list, map, set\n                        // build embedded value\n                        StringBuilder elementCollectionValue = buildElementCollectionValue(field, record, metaModel,\n                                attribute);\n                        columnBuilder.append(Constants.ESCAPE_QUOTE);\n                        columnBuilder.append(((AbstractAttribute) attribute).getJPAColumnName());\n                        columnBuilder.append(Constants.ESCAPE_QUOTE);\n                        columnBuilder.append(Constants.COMMA);\n                        builder.append(elementCollectionValue);\n                        builder.append(Constants.COMMA);\n                    }\n                    else\n                    {\n                        EmbeddableType embeddableKey = metaModel.embeddable(field.getType());\n                        Object embeddableKeyObj = PropertyAccessorHelper.getObject(record, field);\n                        if (embeddableKeyObj != null)\n                        {\n\n                            StringBuilder embeddedValueBuilder = new StringBuilder(Constants.OPEN_CURLY_BRACKET);\n\n                            for (Field embeddableColumn : field.getType().getDeclaredFields())\n                            {\n                                if (!ReflectUtils.isTransientOrStatic(embeddableColumn))\n                                {\n                                    AbstractAttribute subAttribute = (AbstractAttribute) embeddableKey\n                                            .getAttribute(embeddableColumn.getName());\n                                    if (metaModel.isEmbeddable(subAttribute.getBindableJavaType()))\n                                    {\n                                        // construct map; recursive\n                                        // send attribute\n                                        if (embeddableColumn.isAnnotationPresent(ElementCollection.class))\n                                        {\n                                            // build element collection value\n                                            StringBuilder elementCollectionValue = buildElementCollectionValue(\n                                                    embeddableColumn, embeddableKeyObj, metaModel,\n                                                    (Attribute) subAttribute);\n\n                                            appendColumnName(embeddedValueBuilder,\n                                                    ((AbstractAttribute) (embeddableKey.getAttribute(embeddableColumn\n                                                            .getName()))).getJPAColumnName());\n                                            embeddedValueBuilder.append(Constants.COLON);\n                                            embeddedValueBuilder.append(elementCollectionValue);\n                                        }\n                                        else\n                                        {\n                                            buildEmbeddedValue(embeddableKeyObj, metaModel, embeddedValueBuilder,\n                                                    (SingularAttribute) subAttribute);\n                                        }\n                                    }\n                                    else\n                                    {\n                                        // append key value\n                                        appendColumnName(embeddedValueBuilder,\n                                                ((AbstractAttribute) (embeddableKey.getAttribute(embeddableColumn\n                                                        .getName()))).getJPAColumnName());\n                                        embeddedValueBuilder.append(Constants.COLON);\n                                        appendColumnValue(embeddedValueBuilder, embeddableKeyObj, embeddableColumn);\n                                    }\n                                    embeddedValueBuilder.append(Constants.COMMA);\n                                }\n                            }\n                            // strip last char and append '}'\n                            embeddedValueBuilder.deleteCharAt(embeddedValueBuilder.length() - 1);\n                            embeddedValueBuilder.append(Constants.CLOSE_CURLY_BRACKET);\n                            // add to columnbuilder and builder\n                            columnBuilder.append(Constants.ESCAPE_QUOTE);\n                            columnBuilder.append(((AbstractAttribute) attribute).getJPAColumnName());\n                            columnBuilder.append(Constants.ESCAPE_QUOTE);\n                            columnBuilder.append(Constants.COMMA);\n                            builder.append(embeddedValueBuilder);\n                            builder.append(Constants.COMMA);\n                            // end if\n                        }\n                    }\n                }\n                else if (!ReflectUtils.isTransientOrStatic(field) && !attribute.isAssociation())\n                {\n                    onTranslation(type, builder, columnBuilder, ((AbstractAttribute) attribute).getJPAColumnName(),\n                            record, field);\n                }\n            }\n        }\n\n        for (String tableName : columnBuilders.keySet())\n        {\n            translateCompositeId(record, m, type, metaModel, builders, columnBuilders, externalProperties,\n                    kunderaMetadata, tableName, m.getIdAttribute());\n        }\n\n        // on inherited columns.\n        onDiscriminatorColumn(builders.get(m.getTableName()), columnBuilders.get(m.getTableName()), entityType);\n    }\n\n    /**\n     * Builds the element collection value.\n     * \n     * @param field\n     *            the field\n     * @param record\n     *            the record\n     * @param metaModel\n     *            the meta model\n     * @param attribute\n     *            the attribute\n     * @return the string builder\n     */\n    private StringBuilder buildElementCollectionValue(Field field, Object record, MetamodelImpl metaModel,\n            Attribute attribute)\n    {\n        StringBuilder elementCollectionValueBuilder = new StringBuilder();\n        EmbeddableType embeddableKey = metaModel.embeddable(((AbstractAttribute) attribute).getBindableJavaType());\n        ((AbstractAttribute) attribute).getJavaMember();\n        Object value = PropertyAccessorHelper.getObject(record, field);\n        boolean isPresent = false;\n        if (Collection.class.isAssignableFrom(field.getType()))\n        {\n\n            if (value instanceof Collection)\n            {\n                Collection collection = ((Collection) value);\n                isPresent = true;\n                if (List.class.isAssignableFrom(field.getType()))\n                {\n                    elementCollectionValueBuilder.append(Constants.OPEN_SQUARE_BRACKET);\n                }\n                if (Set.class.isAssignableFrom(field.getType()))\n                {\n                    elementCollectionValueBuilder.append(Constants.OPEN_CURLY_BRACKET);\n                }\n                for (Object o : collection)\n                {\n                    // Allowing null values.\n                    // build embedded value\n                    if (o != null)\n                    {\n\n                        StringBuilder embeddedValueBuilder = new StringBuilder(Constants.OPEN_CURLY_BRACKET);\n\n                        for (Field embeddableColumn : ((AbstractAttribute) attribute).getBindableJavaType()\n                                .getDeclaredFields())\n                        {\n                            if (!ReflectUtils.isTransientOrStatic(embeddableColumn))\n                            {\n                                AbstractAttribute subAttribute = (AbstractAttribute) embeddableKey\n                                        .getAttribute(embeddableColumn.getName());\n                                if (metaModel.isEmbeddable(subAttribute.getBindableJavaType()))\n                                {\n                                    // construct map; recursive\n                                    // send attribute\n                                    if (embeddableColumn.getType().isAnnotationPresent(ElementCollection.class))\n                                    {\n                                        // build element collection value\n                                        StringBuilder elementCollectionValue = buildElementCollectionValue(\n                                                embeddableColumn, o, metaModel, (Attribute) subAttribute);\n                                        appendColumnName(embeddedValueBuilder,\n                                                ((AbstractAttribute) (embeddableKey.getAttribute(embeddableColumn\n                                                        .getName()))).getJPAColumnName());\n                                        embeddedValueBuilder.append(Constants.COLON);\n                                        embeddedValueBuilder.append(elementCollectionValue);\n                                    }\n                                    else\n                                    {\n                                        buildEmbeddedValue(o, metaModel, embeddedValueBuilder,\n                                                (SingularAttribute) subAttribute);\n                                    }\n                                }\n                                else\n                                {\n                                    // append key value\n                                    appendColumnName(\n                                            embeddedValueBuilder,\n                                            ((AbstractAttribute) (embeddableKey.getAttribute(embeddableColumn.getName())))\n                                                    .getJPAColumnName());\n                                    embeddedValueBuilder.append(Constants.COLON);\n                                    appendColumnValue(embeddedValueBuilder, o, embeddableColumn);\n                                }\n                                embeddedValueBuilder.append(Constants.COMMA);\n                            }\n                        }\n                        // strip last char and append '}'\n                        embeddedValueBuilder.deleteCharAt(embeddedValueBuilder.length() - 1);\n                        embeddedValueBuilder.append(Constants.CLOSE_CURLY_BRACKET);\n                        // add to columnbuilder and builder\n                        elementCollectionValueBuilder.append(embeddedValueBuilder);\n                        // end if\n                    }\n\n                    elementCollectionValueBuilder.append(Constants.COMMA);\n                }\n                if (!collection.isEmpty())\n                {\n                    elementCollectionValueBuilder.deleteCharAt(elementCollectionValueBuilder.length() - 1);\n                }\n                if (List.class.isAssignableFrom(field.getType()))\n                {\n                    elementCollectionValueBuilder.append(Constants.CLOSE_SQUARE_BRACKET);\n                }\n                if (Set.class.isAssignableFrom(field.getType()))\n                {\n                    elementCollectionValueBuilder.append(Constants.CLOSE_CURLY_BRACKET);\n                }\n                return elementCollectionValueBuilder;\n            }\n            return null;\n\n        }\n\n        else if (Map.class.isAssignableFrom(field.getType()))\n        {\n            if (value instanceof Map)\n            {\n                Map map = ((Map) value);\n                isPresent = true;\n                elementCollectionValueBuilder.append(Constants.OPEN_CURLY_BRACKET);\n                for (Object mapKey : map.keySet())\n                {\n                    Object mapValue = map.get(mapKey);\n                    // Allowing null keys.\n                    // key is basic type.. no support for embeddable keys\n                    appendValue(elementCollectionValueBuilder, mapKey != null ? mapKey.getClass() : null, mapKey, false);\n                    elementCollectionValueBuilder.append(Constants.COLON);\n                    // Allowing null values.\n                    if (mapValue != null)\n                    {\n\n                        StringBuilder embeddedValueBuilder = new StringBuilder(Constants.OPEN_CURLY_BRACKET);\n\n                        for (Field embeddableColumn : ((AbstractAttribute) attribute).getBindableJavaType()\n                                .getDeclaredFields())\n                        {\n                            if (!ReflectUtils.isTransientOrStatic(embeddableColumn))\n                            {\n                                AbstractAttribute subAttribute = (AbstractAttribute) embeddableKey\n                                        .getAttribute(embeddableColumn.getName());\n                                if (metaModel.isEmbeddable(subAttribute.getBindableJavaType()))\n                                {\n                                    // construct map; recursive\n                                    // send attribute\n                                    if (embeddableColumn.getType().isAnnotationPresent(ElementCollection.class))\n                                    {\n                                        // build element collection value\n                                        StringBuilder elementCollectionValue = buildElementCollectionValue(\n                                                embeddableColumn, mapValue, metaModel, (Attribute) subAttribute);\n                                        appendColumnName(embeddedValueBuilder,\n                                                ((AbstractAttribute) (embeddableKey.getAttribute(embeddableColumn\n                                                        .getName()))).getJPAColumnName());\n                                        embeddedValueBuilder.append(Constants.COLON);\n                                        embeddedValueBuilder.append(elementCollectionValue);\n                                    }\n                                    else\n                                    {\n                                        buildEmbeddedValue(mapValue, metaModel, embeddedValueBuilder,\n                                                (SingularAttribute) subAttribute);\n                                    }\n                                }\n                                else\n                                {\n                                    // append key value\n                                    appendColumnName(\n                                            embeddedValueBuilder,\n                                            ((AbstractAttribute) (embeddableKey.getAttribute(embeddableColumn.getName())))\n                                                    .getJPAColumnName());\n                                    embeddedValueBuilder.append(Constants.COLON);\n                                    appendColumnValue(embeddedValueBuilder, mapValue, embeddableColumn);\n\n                                }\n                                embeddedValueBuilder.append(Constants.COMMA);\n                            }\n\n                        }\n                        // strip last char and append '}'\n                        embeddedValueBuilder.deleteCharAt(embeddedValueBuilder.length() - 1);\n                        embeddedValueBuilder.append(Constants.CLOSE_CURLY_BRACKET);\n                        // add to columnbuilder and builder\n                        elementCollectionValueBuilder.append(embeddedValueBuilder);\n                        // end if\n                    }\n                    elementCollectionValueBuilder.append(Constants.COMMA);\n                }\n                if (!map.isEmpty())\n                {\n                    elementCollectionValueBuilder.deleteCharAt(elementCollectionValueBuilder.length() - 1);\n                }\n\n                elementCollectionValueBuilder.append(Constants.CLOSE_CURLY_BRACKET);\n                return elementCollectionValueBuilder;\n            }\n            return null;\n        }\n        return null;\n    }\n\n    /**\n     * Builds the embedded value.\n     * \n     * @param record\n     *            the record\n     * @param metaModel\n     *            the meta model\n     * @param embeddedValueBuilder\n     *            the embedded value builder\n     * @param attribute\n     *            the attribute\n     */\n    private void buildEmbeddedValue(final Object record, MetamodelImpl metaModel, StringBuilder embeddedValueBuilder,\n            SingularAttribute attribute)\n    {\n        // TODO Auto-generated method stub\n        Field field = (Field) attribute.getJavaMember();\n\n        EmbeddableType embeddableKey = metaModel.embeddable(field.getType());\n        Object embeddableKeyObj = PropertyAccessorHelper.getObject(record, field);\n        if (embeddableKeyObj != null)\n        {\n            StringBuilder tempBuilder = new StringBuilder();\n            tempBuilder.append(Constants.OPEN_CURLY_BRACKET);\n\n            for (Field embeddableColumn : field.getType().getDeclaredFields())\n            {\n                if (!ReflectUtils.isTransientOrStatic(embeddableColumn))\n                {\n                    Attribute subAttribute = (SingularAttribute) embeddableKey.getAttribute(embeddableColumn.getName());\n                    if (metaModel.isEmbeddable(((AbstractAttribute) subAttribute).getBindableJavaType()))\n                    {\n                        // construct map; recursive\n                        // send attribute\n                        buildEmbeddedValue(embeddableKeyObj, metaModel, tempBuilder, (SingularAttribute) subAttribute);\n                    }\n                    else\n                    {\n                        // append key value\n                        appendColumnName(tempBuilder, ((AbstractAttribute) (embeddableKey.getAttribute(embeddableColumn\n                                .getName()))).getJPAColumnName());\n                        tempBuilder.append(Constants.COLON);\n                        appendColumnValue(tempBuilder, embeddableKeyObj, embeddableColumn);\n                    }\n                    tempBuilder.append(Constants.COMMA);\n                }\n\n            }\n            // strip last char and append '}'\n            tempBuilder.deleteCharAt(tempBuilder.length() - 1);\n            tempBuilder.append(Constants.CLOSE_CURLY_BRACKET);\n            appendColumnName(embeddedValueBuilder, ((AbstractAttribute) attribute).getJPAColumnName());\n            embeddedValueBuilder.append(Constants.COLON);\n            embeddedValueBuilder.append(tempBuilder);\n        }\n        else\n        {\n            embeddedValueBuilder.deleteCharAt(embeddedValueBuilder.length() - 1);\n        }\n    }\n\n    /**\n     * Translate composite id.\n     * \n     * @param record\n     *            the record\n     * @param m\n     *            the m\n     * @param type\n     *            the type\n     * @param metaModel\n     *            the meta model\n     * @param builders\n     *            the builders\n     * @param columnBuilders\n     *            the column builders\n     * @param externalProperties\n     *            the external properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param tableName\n     *            the table name\n     * @param attribute\n     *            the attribute\n     */\n    private void translateCompositeId(final Object record, final EntityMetadata m, TranslationType type,\n            MetamodelImpl metaModel, Map<String, StringBuilder> builders, Map<String, StringBuilder> columnBuilders,\n            Map<String, Object> externalProperties, final KunderaMetadata kunderaMetadata, String tableName,\n            SingularAttribute attribute)\n    {\n        StringBuilder builder = builders.get(tableName);\n        StringBuilder columnBuilder = columnBuilders.get(tableName);\n        Field field = (Field) attribute.getJavaMember();\n        if (metaModel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType()))\n        {\n            // builder.\n            // Means it is a compound key! As other\n            // iterate for it's fields to populate it's values in\n            // order!\n            EmbeddableType compoundKey = metaModel.embeddable(field.getType());\n            Object compoundKeyObj = PropertyAccessorHelper.getObject(record, field);\n            for (Field compositeColumn : field.getType().getDeclaredFields())\n            {\n                if (!ReflectUtils.isTransientOrStatic(compositeColumn))\n                {\n                    attribute = (SingularAttribute) compoundKey.getAttribute(compositeColumn.getName());\n                    if (metaModel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType()))\n                    {\n                        translateCompositeId(compoundKeyObj, m, type, metaModel, builders, columnBuilders,\n                                externalProperties, kunderaMetadata, tableName, attribute);\n                    }\n                    else\n                    {\n                        onTranslation(type, builder, columnBuilder,\n                                ((AbstractAttribute) (compoundKey.getAttribute(compositeColumn.getName())))\n                                        .getJPAColumnName(), compoundKeyObj, compositeColumn);\n                    }\n                }\n            }\n        }\n        else if (!ReflectUtils.isTransientOrStatic(field))\n        {\n            onTranslation(type, builder, columnBuilder,\n                    CassandraUtilities.getIdColumnName(kunderaMetadata, m, externalProperties, true), record, field);\n        }\n    }\n\n    /**\n     * On discriminator column.\n     * \n     * @param builder\n     *            the builder\n     * @param columnBuilder\n     *            the column builder\n     * @param entityType\n     *            the entity type\n     */\n    private void onDiscriminatorColumn(StringBuilder builder, StringBuilder columnBuilder, EntityType entityType)\n    {\n        String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n        String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();\n\n        // No need to check for empty or blank, as considering it as valid name\n        // for nosql!\n        if (discrColumn != null && discrValue != null)\n        {\n            appendValue(builder, String.class, discrValue, false);\n            builder.append(Constants.COMMA);\n            appendColumnName(columnBuilder, discrColumn);\n            columnBuilder.append(Constants.COMMA); // because only key columns\n\n        }\n    }\n\n    /**\n     * Build where clause with @ EQ_CLAUSE} clause.\n     * \n     * @param builder\n     *            the builder\n     * @param field\n     *            the field\n     * @param member\n     *            the member\n     * @param entity\n     *            the entity\n     */\n    public void buildWhereClause(StringBuilder builder, String field, Field member, Object entity)\n    {\n        // builder = ensureCase(builder, field, false);\n        // builder.append(EQ_CLAUSE);\n        // appendColumnValue(builder, entity, member);\n        // builder.append(AND_CLAUSE);\n        Object value = PropertyAccessorHelper.getObject(entity, member);\n        buildWhereClause(builder, member.getType(), field, value, EQ_CLAUSE, false);\n    }\n\n    /**\n     * Build where clause with given clause.\n     * \n     * @param builder\n     *            the builder\n     * @param fieldClazz\n     *            the field clazz\n     * @param field\n     *            the field\n     * @param value\n     *            the value\n     * @param clause\n     *            the clause\n     * @param useToken\n     *            the use token\n     */\n    public void buildWhereClause(StringBuilder builder, Class fieldClazz, String field, Object value, String clause,\n            boolean useToken)\n    {\n\n        builder = onWhereClause(builder, fieldClazz, field, value, clause, useToken);\n        builder.append(AND_CLAUSE);\n    }\n\n    /**\n     * Build where clause with given clause.\n     * \n     * @param builder\n     *            the builder\n     * @param fieldClazz\n     *            the field clazz\n     * @param field\n     *            the field\n     * @param value\n     *            the value\n     * @param clause\n     *            the clause\n     * @param useToken\n     *            the use token\n     * @return the string builder\n     */\n    public StringBuilder onWhereClause(StringBuilder builder, Class fieldClazz, String field, Object value,\n            String clause, boolean useToken)\n    {\n\n        if (clause.trim().equals(IN_CLAUSE))\n        {\n            useToken = false;\n        }\n\n        builder = ensureCase(builder, field, useToken);\n        builder.append(SPACE_STRING);\n        if (fieldClazz.isAssignableFrom(List.class) || fieldClazz.isAssignableFrom(Map.class)\n                || fieldClazz.isAssignableFrom(Set.class))\n        {\n            builder.append(\"CONTAINS\");\n        }\n        else\n        {\n            builder.append(clause);\n        }\n        builder.append(SPACE_STRING);\n\n        if (clause.trim().equals(IN_CLAUSE))\n        {\n            builder.append(OPEN_BRACKET);\n            String itemValues = String.valueOf(value);\n            itemValues = itemValues.startsWith(OPEN_BRACKET) && itemValues.endsWith(CLOSE_BRACKET) ? itemValues\n                    .substring(1, itemValues.length() - 1) : itemValues;\n            List<String> items = Arrays.asList(((String) itemValues).split(\"\\\\s*,\\\\s*\"));\n            int counter = 0;\n            for (String str : items)\n            {\n                str = str.trim();\n                str = (str.startsWith(Constants.ESCAPE_QUOTE) && str.endsWith(Constants.ESCAPE_QUOTE))\n                        || (str.startsWith(\"'\") && str.endsWith(\"'\")) ? str.substring(1, str.length() - 1) : str;\n                appendValue(builder, fieldClazz, str, false, false);\n                counter++;\n                if (counter < items.size())\n                {\n                    builder.append(COMMA_STR);\n                }\n\n            }\n            builder.append(CLOSE_BRACKET);\n        }\n        else\n        {\n            appendValue(builder, fieldClazz, value, false, useToken);\n        }\n        return builder;\n    }\n\n    /**\n     * Builds set clause for a given counter field.\n     * \n     * @param builder\n     *            the builder\n     * @param field\n     *            the field\n     * @param value\n     *            the value\n     */\n    public void buildSetClauseForCounters(StringBuilder builder, String field, Object value)\n    {\n        builder = ensureCase(builder, field, false);\n        builder.append(EQ_CLAUSE);\n        builder = ensureCase(builder, field, false);\n        builder.append(INCR_COUNTER);\n        appendValue(builder, value.getClass(), value, false, false);\n        builder.append(COMMA_STR);\n    }\n\n    /**\n     * Builds set clause for a given field.\n     * \n     * @param m\n     *            the m\n     * @param builder\n     *            the builder\n     * @param property\n     *            the property\n     * @param value\n     *            the value\n     */\n    public void buildSetClause(EntityMetadata m, StringBuilder builder, String property, Object value)\n    {\n        builder = ensureCase(builder, property, false);\n        builder.append(EQ_CLAUSE);\n\n        if (m.isCounterColumnType())\n        {\n            builder = ensureCase(builder, property, false);\n            builder.append(INCR_COUNTER);\n            builder.append(value);\n        }\n        else\n        {\n            appendValue(builder, value.getClass(), value, false, false);\n        }\n\n        builder.append(COMMA_STR);\n    }\n\n    /**\n     * Ensures case for corresponding column name.\n     * \n     * @param builder\n     *            column name builder.\n     * @param fieldName\n     *            column name.\n     * @param useToken\n     *            the use token\n     * @return builder object with appended column name.\n     */\n    public StringBuilder ensureCase(StringBuilder builder, String fieldName, boolean useToken)\n    {\n        if (useToken)\n        {\n            builder.append(TOKEN);\n        }\n        builder.append(Constants.ESCAPE_QUOTE);\n        builder.append(fieldName);\n        builder.append(Constants.ESCAPE_QUOTE);\n        if (useToken)\n        {\n            builder.append(CLOSE_BRACKET);\n        }\n        return builder;\n\n    }\n\n    /**\n     * Translates input object and corresponding field based on: a) ALL :\n     * translate both column name and column value. b) COlUMN: translates column\n     * name only. c) VALUE: translates column value only.\n     * \n     * @param type\n     *            translation type.\n     * @param builder\n     *            column value builder object.\n     * @param columnBuilder\n     *            column name builder object.\n     * @param columnName\n     *            column name.\n     * @param record\n     *            value object.\n     * @param column\n     *            value column name.\n     */\n    private void onTranslation(TranslationType type, StringBuilder builder, StringBuilder columnBuilder,\n            String columnName, Object record, Field column)\n    {\n        switch (type)\n        {\n        case ALL:\n            if (appendColumnValue(builder, record, column))\n            {\n                builder.append(Constants.COMMA);\n                appendColumnName(columnBuilder, columnName);\n                columnBuilder.append(Constants.COMMA); // because only key columns\n            }\n            break;\n\n        case COLUMN:\n\n            appendColumnName(columnBuilder, columnName);\n            columnBuilder.append(Constants.COMMA); // because only key columns\n            break;\n\n        case VALUE:\n\n            if (appendColumnValue(builder, record, column))\n            {\n                builder.append(Constants.COMMA); // because only key columns\n            }\n            break;\n        }\n    }\n\n    /**\n     * Appends column value with parametrised builder object. Returns true if\n     * value is present.\n     * \n     * @param builder\n     *            the builder\n     * @param valueObj\n     *            the value obj\n     * @param column\n     *            the column\n     * @return true if value is not null,else false.\n     */\n    private boolean appendColumnValue(StringBuilder builder, Object valueObj, Field column)\n    {\n        Object value = PropertyAccessorHelper.getObject(valueObj, column);\n        boolean isPresent = false;\n        isPresent = appendValue(builder, column.getType(), value, isPresent, false);\n        return isPresent;\n    }\n\n    /**\n     * Appends value to builder object for given class type.\n     * \n     * @param builder\n     *            string builder.\n     * @param fieldClazz\n     *            field class.\n     * @param value\n     *            value to be appended.\n     * @param isPresent\n     *            if field is present.\n     * @param useToken\n     *            the use token\n     * @return true, if value is not null else false.\n     */\n    public boolean appendValue(StringBuilder builder, Class fieldClazz, Object value, boolean isPresent,\n            boolean useToken)\n    {\n        if (List.class.isAssignableFrom(fieldClazz))\n        {\n            isPresent = appendList(builder, value != null ? value : new ArrayList());\n        }\n\n        else if (Set.class.isAssignableFrom(fieldClazz))\n        {\n            isPresent = appendSet(builder, value != null ? value : new HashSet());\n        }\n\n        else if (Map.class.isAssignableFrom(fieldClazz))\n        {\n            isPresent = appendMap(builder, value != null ? value : new HashMap());\n        }\n        else\n        {\n            isPresent = true;\n            appendValue(builder, fieldClazz, value, useToken);\n        }\n        return isPresent;\n    }\n\n    /**\n     * Appends a object of type {@link java.util.List}\n     * \n     * @param builder\n     *            the builder\n     * @param value\n     *            the value\n     * @return true, if successful\n     */\n    private boolean appendList(StringBuilder builder, Object value)\n    {\n        boolean isPresent = false;\n        if (value instanceof Collection)\n        {\n            Collection collection = ((Collection) value);\n            isPresent = true;\n            builder.append(Constants.OPEN_SQUARE_BRACKET);\n            for (Object o : collection)\n            {\n                // Allowing null values.\n                appendValue(builder, o != null ? o.getClass() : null, o, false);\n                builder.append(Constants.COMMA);\n            }\n            if (!collection.isEmpty())\n            {\n                builder.deleteCharAt(builder.length() - 1);\n            }\n            builder.append(Constants.CLOSE_SQUARE_BRACKET);\n\n        }\n        else\n        {\n            appendValue(builder, value.getClass(), value, false);\n        }\n        return isPresent;\n    }\n\n    /**\n     * Appends a object of type {@link java.util.Map}\n     * \n     * @param builder\n     *            the builder\n     * @param value\n     *            the value\n     * @return true, if successful\n     */\n    private boolean appendSet(StringBuilder builder, Object value)\n    {\n        boolean isPresent = false;\n        if (value instanceof Collection)\n        {\n            Collection collection = ((Collection) value);\n            isPresent = true;\n            builder.append(Constants.OPEN_CURLY_BRACKET);\n            for (Object o : collection)\n            {\n                // Allowing null values.\n                appendValue(builder, o != null ? o.getClass() : null, o, false);\n                builder.append(Constants.COMMA);\n            }\n            if (!collection.isEmpty())\n            {\n                builder.deleteCharAt(builder.length() - 1);\n            }\n            builder.append(Constants.CLOSE_CURLY_BRACKET);\n        }\n        else\n        {\n            appendValue(builder, value.getClass(), value, false);\n        }\n        return isPresent;\n    }\n\n    /**\n     * Appends a object of type {@link java.util.List}\n     * \n     * @param builder\n     *            the builder\n     * @param value\n     *            the value\n     * @return true, if successful\n     */\n    private boolean appendMap(StringBuilder builder, Object value)\n    {\n        boolean isPresent = false;\n        if (value instanceof Map)\n        {\n            Map map = ((Map) value);\n            isPresent = true;\n            builder.append(Constants.OPEN_CURLY_BRACKET);\n            for (Object mapKey : map.keySet())\n            {\n                Object mapValue = map.get(mapKey);\n                // Allowing null keys.\n                appendValue(builder, mapKey != null ? mapKey.getClass() : null, mapKey, false);\n                builder.append(Constants.COLON);\n                // Allowing null values.\n                appendValue(builder, mapValue != null ? mapValue.getClass() : null, mapValue, false);\n                builder.append(Constants.COMMA);\n            }\n            if (!map.isEmpty())\n            {\n                builder.deleteCharAt(builder.length() - 1);\n            }\n\n            builder.append(Constants.CLOSE_CURLY_BRACKET);\n        }\n        else\n        {\n            appendValue(builder, value.getClass(), value, false);\n        }\n        return isPresent;\n    }\n\n    /**\n     * Append value.\n     * \n     * @param builder\n     *            the builder\n     * @param fieldClazz\n     *            the field clazz\n     * @param value\n     *            the value\n     * @param useToken\n     *            the use token\n     */\n    private void appendValue(StringBuilder builder, Class fieldClazz, Object value, boolean useToken)\n    {\n        // To allow handle byte array class object by converting it to string\n\n        if (fieldClazz != null && fieldClazz.isAssignableFrom(byte[].class))\n        {\n            value = value != null ? value : ByteBufferUtil.EMPTY_BYTE_BUFFER.array();\n            StringBuilder hexstr = new StringBuilder(\"0x\");\n            builder.append(hexstr.append((Hex.encodeHex((byte[]) value))));\n        }\n        else\n        {\n            if (useToken)\n            {\n                builder.append(TOKEN);\n            }\n\n            if (fieldClazz != null\n                    && value != null\n                    && (fieldClazz.isAssignableFrom(String.class) || isDate(fieldClazz)\n                            || fieldClazz.isAssignableFrom(char.class) || fieldClazz.isAssignableFrom(Character.class) || value instanceof Enum))\n            {\n\n                if (fieldClazz.isAssignableFrom(String.class))\n                {\n                    // To allow escape character\n                    value = ((String) value).replaceAll(\"'\", \"''\");\n                }\n                builder.append(\"'\");\n\n                if (isDate(fieldClazz)) // For CQL, date has to\n                                        // be in date.getTime()\n                {\n                    builder.append(PropertyAccessorFactory.getPropertyAccessor(fieldClazz).toString(value));\n                }\n                else if (value instanceof Enum)\n                {\n                    builder.append(((Enum) value).name());\n                }\n\n                else\n                {\n                    builder.append(value);\n                }\n                builder.append(\"'\");\n            }\n            else\n            {\n                builder.append(value);\n            }\n\n        }\n        if (useToken)\n        {\n            builder.append(CLOSE_BRACKET);\n        }\n    }\n\n    /**\n     * Appends column name and ensure case sensitivity.\n     * \n     * @param builder\n     *            string builder.\n     * @param columnName\n     *            column name.\n     */\n    public void appendColumnName(StringBuilder builder, String columnName)\n    {\n        ensureCase(builder, columnName, false);\n    }\n\n    /**\n     * Appends column name and data type also ensures case sensitivity.\n     * \n     * @param builder\n     *            string builder\n     * @param columnName\n     *            column name\n     * @param dataType\n     *            data type.\n     */\n    public void appendColumnName(StringBuilder builder, String columnName, String dataType)\n    {\n        ensureCase(builder, columnName, false);\n        builder.append(\" \"); // because only key columns\n        builder.append(dataType);\n    }\n\n    /**\n     * Validates if input class is of type input.\n     * \n     * @param clazz\n     *            class\n     * \n     * @return true, if it is a date field class.\n     */\n    private boolean isDate(Class clazz)\n    {\n        return clazz.isAssignableFrom(Date.class) || clazz.isAssignableFrom(java.sql.Date.class)\n                || clazz.isAssignableFrom(Timestamp.class) || clazz.isAssignableFrom(Time.class)\n                || clazz.isAssignableFrom(Calendar.class);\n    }\n\n    /**\n     * Maps internal data type of cassandra to CQL type representation.\n     * \n     * @author vivek.mishra\n     */\n    private static class InternalToCQLMapper\n    {\n        /** The Mapper. */\n        private final static Map<String, String> mapper;\n\n        static\n        {\n            Map<String, String> validationClassMapper = new HashMap<String, String>();\n            // TODO: support for ascii is missing!\n\n            // putting possible combination into map.\n\n            validationClassMapper.put(UTF8Type.class.getSimpleName(), \"text\");\n\n            validationClassMapper.put(IntegerType.class.getSimpleName(), \"varint\");\n\n            validationClassMapper.put(Int32Type.class.getSimpleName(), \"int\");\n\n            validationClassMapper.put(DoubleType.class.getSimpleName(), \"double\");\n\n            validationClassMapper.put(BooleanType.class.getSimpleName(), \"boolean\");\n\n            validationClassMapper.put(LongType.class.getSimpleName(), \"bigint\");\n\n            validationClassMapper.put(BytesType.class.getSimpleName(), \"blob\");\n\n            validationClassMapper.put(FloatType.class.getSimpleName(), \"float\");\n\n            // missing\n            validationClassMapper.put(CounterColumnType.class.getSimpleName(), \"counter\");\n\n            validationClassMapper.put(DecimalType.class.getSimpleName(), \"decimal\");\n\n            validationClassMapper.put(UUIDType.class.getSimpleName(), \"uuid\");\n\n            validationClassMapper.put(DateType.class.getSimpleName(), \"timestamp\");\n            validationClassMapper.put(TimestampType.class.getSimpleName(), \"timestamp\");\n\n            // collection types\n            validationClassMapper.put(ListType.class.getSimpleName(), \"list\");\n            validationClassMapper.put(SetType.class.getSimpleName(), \"set\");\n            validationClassMapper.put(MapType.class.getSimpleName(), \"map\");\n\n            mapper = Collections.synchronizedMap(validationClassMapper);\n        }\n\n        /**\n         * Gets the type.\n         * \n         * @param internalClassName\n         *            the internal class name\n         * @return the type\n         */\n        private static final String getType(final String internalClassName)\n        {\n            return mapper.get(internalClassName);\n        }\n    }\n\n    /**\n     * The Class CQLKeywordMapper.\n     */\n    private static class CQLKeywordMapper\n    {\n        /** The Mapper. */\n        private final static Map<String, String> mapper = new HashMap<String, String>();\n\n        // missing: compaction_strategy_options,\n        // compression_parameters,sstable_size_in_mb\n        static\n        {\n            mapper.put(CassandraConstants.READ_REPAIR_CHANCE, \"read_repair_chance\");\n            mapper.put(CassandraConstants.DCLOCAL_READ_REPAIR_CHANCE, \"dclocal_read_repair_chance\");\n            mapper.put(CassandraConstants.BLOOM_FILTER_FP_CHANCE, \"bloom_filter_fp_chance\");\n            mapper.put(CassandraConstants.COMPACTION_STRATEGY, \"compaction_strategy_class\");\n            mapper.put(CassandraConstants.BLOOM_FILTER_FP_CHANCE, \"bloom_filter_fp_chance\");\n\n            // mapper.put(CassandraConstants.COMPARATOR_TYPE, \"comparator\");\n\n            mapper.put(CassandraConstants.REPLICATE_ON_WRITE, \"replicate_on_write\");\n            mapper.put(CassandraConstants.CACHING, \"caching\");\n            // TODO: these are not supported.\n            // mapper.put(CassandraConstants.MAX_COMPACTION_THRESHOLD,\n            // \"max_compaction_threshold\");\n            // mapper.put(CassandraConstants.MIN_COMPACTION_THRESHOLD,\n            // \"min_compaction_threshold\");\n            mapper.put(CassandraConstants.COMMENT, \"comment\");\n            mapper.put(CassandraConstants.GC_GRACE_SECONDS, \"gc_grace_seconds\");\n        }\n\n        /**\n         * Gets the type.\n         * \n         * @param propertyName\n         *            the property name\n         * @return the type\n         */\n        private static final String getType(final String propertyName)\n        {\n            return mapper.get(propertyName);\n        }\n    }\n\n    /**\n     * Builds the filtering clause.\n     * \n     * @param builder\n     *            the builder\n     */\n    public void buildFilteringClause(StringBuilder builder)\n    {\n        builder.append(\" ALLOW FILTERING\");\n    }\n\n    /**\n     * Builds the order by clause.\n     * \n     * @param builder\n     *            the builder\n     * @param field\n     *            the field\n     * @param orderType\n     *            the order type\n     * @param useToken\n     *            the use token\n     */\n    public void buildOrderByClause(StringBuilder builder, String field, Object orderType, boolean useToken)\n    {\n        builder.append(SPACE_STRING);\n        builder.append(SORT_CLAUSE);\n        builder = ensureCase(builder, field, useToken);\n        builder.append(SPACE_STRING);\n        builder.append(orderType);\n    }\n\n    /**\n     * Builds the select query.\n     * \n     * @param descriptor\n     *            the descriptor\n     * @return the string builder\n     */\n    public StringBuilder buildSelectQuery(TableGeneratorDiscriptor descriptor)\n    {\n        StringBuilder builder = new StringBuilder(\"Select \");\n        ensureCase(builder, descriptor.getValueColumnName(), false).append(\" from \");\n        ensureCase(builder, descriptor.getTable(), false).append(\" where \");\n        ensureCase(builder, descriptor.getPkColumnName(), false).append(\" = '\").append(\n                descriptor.getPkColumnValue() + \"'\");\n\n        return builder;\n    }\n\n    /**\n     * Builds the update query.\n     * \n     * @param descriptor\n     *            the descriptor\n     * @return the string builder\n     */\n    public StringBuilder buildUpdateQuery(TableGeneratorDiscriptor descriptor)\n    {\n        StringBuilder builder = new StringBuilder(\"Update \");\n        ensureCase(builder, descriptor.getTable(), false).append(\" set \");\n        ensureCase(builder, descriptor.getValueColumnName(), false).append(\" = \");\n        ensureCase(builder, descriptor.getValueColumnName(), false).append(\" + \").append(1).append(\" where \");\n        ensureCase(builder, descriptor.getPkColumnName(), false).append(\" = '\").append(\n                descriptor.getPkColumnValue() + \"'\");\n\n        return builder;\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/ThriftClient.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.thrift;\n\nimport java.io.UnsupportedEncodingException;\nimport java.lang.reflect.Field;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.EntityType;\n\nimport net.dataforte.cassandra.pool.ConnectionPool;\n\nimport org.apache.cassandra.db.marshal.UTF8Type;\nimport org.apache.cassandra.thrift.Cassandra;\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.ColumnOrSuperColumn;\nimport org.apache.cassandra.thrift.ColumnParent;\nimport org.apache.cassandra.thrift.ColumnPath;\nimport org.apache.cassandra.thrift.CounterColumn;\nimport org.apache.cassandra.thrift.CounterSuperColumn;\nimport org.apache.cassandra.thrift.IndexClause;\nimport org.apache.cassandra.thrift.IndexExpression;\nimport org.apache.cassandra.thrift.IndexOperator;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KeyRange;\nimport org.apache.cassandra.thrift.KeySlice;\nimport org.apache.cassandra.thrift.Mutation;\nimport org.apache.cassandra.thrift.SlicePredicate;\nimport org.apache.cassandra.thrift.SliceRange;\nimport org.apache.cassandra.thrift.SuperColumn;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.apache.thrift.TException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.client.cassandra.CassandraIdGenerator;\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.common.CassandraUtilities;\nimport com.impetus.client.cassandra.datahandler.CassandraDataHandler;\nimport com.impetus.client.cassandra.index.InvertedIndexHandler;\nimport com.impetus.client.cassandra.query.CassQuery;\nimport com.impetus.client.cassandra.thrift.ThriftClientFactory.Connection;\nimport com.impetus.client.cassandra.thrift.ThriftDataResultHelper.ColumnFamilyType;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.db.SearchResult;\nimport com.impetus.kundera.generator.AutoGenerator;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.generator.TableGenerator;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.TableGeneratorDiscriptor;\nimport com.impetus.kundera.metadata.model.EntityMetadata.Type;\nimport com.impetus.kundera.metadata.model.annotation.DefaultEntityAnnotationProcessor;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.EntityReaderException;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessor;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.TimestampGenerator;\n\n/**\n * Kundera Client implementation for Cassandra using Thrift library.\n * \n * @author amresh.singh\n */\npublic class ThriftClient extends CassandraClientBase implements Client<CassQuery>, Batcher\n\n{\n\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(ThriftClient.class);\n\n    /** The data handler. */\n    private final ThriftDataHandler dataHandler;\n\n    /** Handler for Inverted indexing. */\n    private final InvertedIndexHandler invertedIndexHandler;\n\n    /** The reader. */\n    private final EntityReader reader;\n\n    /** The client factory. */\n    private final ThriftClientFactory clientFactory;\n\n    /** The pool. */\n    private final ConnectionPool pool;\n\n    /**\n     * Instantiates a new thrift client.\n     * \n     * @param clientFactory\n     *            the client factory\n     * @param indexManager\n     *            the index manager\n     * @param reader\n     *            the reader\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param pool\n     *            the pool\n     * @param externalProperties\n     *            the external properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param generator\n     *            the generator\n     */\n    public ThriftClient(ThriftClientFactory clientFactory, IndexManager indexManager, EntityReader reader,\n            String persistenceUnit, ConnectionPool pool, Map<String, Object> externalProperties,\n            final KunderaMetadata kunderaMetadata, final TimestampGenerator generator)\n    {\n        super(persistenceUnit, externalProperties, kunderaMetadata, generator);\n        this.clientFactory = clientFactory;\n        this.indexManager = indexManager;\n        this.dataHandler = new ThriftDataHandler(this, kunderaMetadata, generator);\n        this.reader = reader;\n        this.clientMetadata = clientFactory.getClientMetadata();\n        this.invertedIndexHandler = new ThriftInvertedIndexHandler(this,\n                MetadataUtils.useSecondryIndex(clientMetadata), generator);\n        this.pool = pool;\n    }\n\n    /**\n     * Persists and indexes a {@link Node} to database.\n     * \n     * @param node\n     *            the node\n     */\n    @Override\n    public void persist(Node node)\n    {\n        super.persist(node);\n    }\n\n    /**\n     * Persists a {@link Node} to database.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @param id\n     *            the id\n     * @param rlHolders\n     *            the rl holders\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n        Connection conn = getConnection();\n        try\n        {\n            // if entity is embeddable...call cql translator to get cql string!\n            // use thrift client to execute cql query.\n\n            if (isCql3Enabled(entityMetadata))\n            {\n                cqlClient.persist(entityMetadata, entity, conn.getClient(), rlHolders,\n                        getTtlValues().get(entityMetadata.getTableName()));\n            }\n            else\n            {\n                Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();\n                prepareMutation(entityMetadata, entity, id, rlHolders, mutationMap);\n                // Write Mutation map to database\n                conn.getClient().batch_mutate(mutationMap, getConsistencyLevel());\n\n                mutationMap.clear();\n                mutationMap = null;\n            }\n\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(\"Error while persisting record, Caused by: .\", e);\n            throw new KunderaException(e);\n        }\n        catch (TException e)\n        {\n            log.error(\"Error while persisting record, Caused by: .\", e);\n            throw new KunderaException(e);\n        }\n        catch (UnsupportedEncodingException e)\n        {\n            log.error(\"Error while persisting record, Caused by: .\", e);\n            throw new KunderaException(e);\n        }\n        finally\n        {\n            releaseConnection(conn);\n\n            if (isTtlPerRequest())\n            {\n                getTtlValues().clear();\n            }\n        }\n    }\n\n    /**\n     * Persists a Join table record set into database.\n     * \n     * @param joinTableData\n     *            the join table data\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        String joinTableName = joinTableData.getJoinTableName();\n        String invJoinColumnName = joinTableData.getInverseJoinColumnName();\n        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                joinTableData.getEntityClass());\n\n        Connection conn = null;\n        try\n        {\n\n            conn = getConnection();\n\n            if (isCql3Enabled(entityMetadata))\n            {\n                persistJoinTableByCql(joinTableData, conn.getClient());\n            }\n            else\n            {\n                KunderaCoreUtils.printQuery(\"Persist join table:\" + joinTableName, showQuery);\n                for (Object key : joinTableRecords.keySet())\n                {\n                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor((Field) entityMetadata\n                            .getIdAttribute().getJavaMember());\n                    byte[] rowKey = accessor.toBytes(key);\n\n                    Set<Object> values = joinTableRecords.get(key);\n                    List<Column> columns = new ArrayList<Column>();\n\n                    // Create Insertion List\n                    List<Mutation> insertionList = new ArrayList<Mutation>();\n                    Class columnType = null;\n                    for (Object value : values)\n                    {\n                        Column column = new Column();\n                        column.setName(PropertyAccessorFactory.STRING.toBytes(invJoinColumnName\n                                + Constants.JOIN_COLUMN_NAME_SEPARATOR + value));\n                        column.setValue(PropertyAccessorHelper.getBytes(value));\n\n                        column.setTimestamp(generator.getTimestamp());\n                        columnType = value.getClass();\n                        columns.add(column);\n\n                        Mutation mut = new Mutation();\n                        mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setColumn(column));\n                        insertionList.add(mut);\n                    }\n                    createIndexesOnColumns(entityMetadata, joinTableName, columns, columnType);\n                    // Create Mutation Map\n                    Map<String, List<Mutation>> columnFamilyValues = new HashMap<String, List<Mutation>>();\n                    columnFamilyValues.put(joinTableName, insertionList);\n                    Map<ByteBuffer, Map<String, List<Mutation>>> mulationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();\n                    mulationMap.put(ByteBuffer.wrap(rowKey), columnFamilyValues);\n\n                    // Write Mutation map to database\n\n                    conn.getClient().set_keyspace(entityMetadata.getSchema());\n\n                    conn.getClient().batch_mutate(mulationMap, getConsistencyLevel());\n                }\n            }\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(\"Error while inserting record into join table, Caused by: .\", e);\n            throw new PersistenceException(e);\n        }\n        catch (TException e)\n        {\n            log.error(\"Error while inserting record into join table, Caused by: .\", e);\n            throw new PersistenceException(e);\n        }\n        finally\n        {\n            releaseConnection(conn);\n        }\n    }\n\n    /**\n     * Indexes a {@link Node} to database.\n     * \n     * @param node\n     *            the node\n     * @param entityMetadata\n     *            the entity metadata\n     */\n    @Override\n    protected void indexNode(Node node, EntityMetadata entityMetadata)\n    {\n        super.indexNode(node, entityMetadata);\n\n        // Write to inverted index table if applicable\n        invertedIndexHandler.write(node, entityMetadata, getPersistenceUnit(), getConsistencyLevel(), dataHandler);\n    }\n\n    /**\n     * Finds an entity from database.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param key\n     *            the key\n     * @return the object\n     */\n    @Override\n    public Object find(Class entityClass, Object key)\n    {\n        return super.find(entityClass, key);\n    }\n\n    /**\n     * Finds a {@link List} of entities from database.\n     * \n     * @param <E>\n     *            the element type\n     * @param entityClass\n     *            the entity class\n     * @param columnsToSelect\n     *            the columns to select\n     * @param keys\n     *            the keys\n     * @return the list\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)\n    {\n        return super.findAll(entityClass, columnsToSelect, keys);\n    }\n\n    /**\n     * Finds a {@link List} of entities from database.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param relationNames\n     *            the relation names\n     * @param isWrapReq\n     *            the is wrap req\n     * @param metadata\n     *            the metadata\n     * @param rowIds\n     *            the row ids\n     * @return the list\n     */\n    @Override\n    public final List find(Class entityClass, List<String> relationNames, boolean isWrapReq, EntityMetadata metadata,\n            Object... rowIds)\n    {\n        if (!isOpen())\n        {\n            throw new PersistenceException(\"ThriftClient is closed.\");\n        }\n        return findByRowKeys(entityClass, relationNames, isWrapReq, metadata, rowIds);\n    }\n\n    /**\n     * Finds a {@link List} of entities from database for given super columns.\n     * \n     * @param <E>\n     *            the element type\n     * @param entityClass\n     *            the entity class\n     * @param embeddedColumnMap\n     *            the embedded column map\n     * @return the list\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n        return super.find(entityClass, embeddedColumnMap, dataHandler);\n    }\n\n    /**\n     * Loads super columns from database.\n     * \n     * @param keyspace\n     *            the keyspace\n     * @param columnFamily\n     *            the column family\n     * @param rowId\n     *            the row id\n     * @param superColumnNames\n     *            the super column names\n     * @return the list\n     */\n    @Override\n    protected final List<SuperColumn> loadSuperColumns(String keyspace, String columnFamily, String rowId,\n            String... superColumnNames)\n    {\n        // TODO::: super column abstract entity and discriminator column\n        if (!isOpen())\n            throw new PersistenceException(\"ThriftClient is closed.\");\n\n        byte[] rowKey = rowId.getBytes();\n\n        SlicePredicate predicate = new SlicePredicate();\n        List<ByteBuffer> columnNames = new ArrayList<ByteBuffer>();\n        for (String superColumnName : superColumnNames)\n        {\n            KunderaCoreUtils.printQuery(\"Fetch superColumn:\" + superColumnName, showQuery);\n            columnNames.add(ByteBuffer.wrap(superColumnName.getBytes()));\n        }\n\n        predicate.setColumn_names(columnNames);\n\n        ColumnParent parent = new ColumnParent(columnFamily);\n        List<ColumnOrSuperColumn> coscList;\n        Connection conn = null;\n        try\n        {\n            conn = getConnection();\n\n            coscList = conn.getClient().get_slice(ByteBuffer.wrap(rowKey), parent, predicate, getConsistencyLevel());\n\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(\"Error while getting super columns for row Key {} , Caused by: .\", rowId, e);\n            throw new EntityReaderException(e);\n        }\n        catch (UnavailableException e)\n        {\n            log.error(\"Error while getting super columns for row Key {} , Caused by: .\", rowId, e);\n            throw new EntityReaderException(e);\n        }\n        catch (TimedOutException e)\n        {\n            log.error(\"Error while getting super columns for row Key {} , Caused by: .\", rowId, e);\n            throw new EntityReaderException(e);\n        }\n        catch (TException e)\n        {\n            log.error(\"Error while getting super columns for row Key {} , Caused by: .\", rowId, e);\n            throw new EntityReaderException(e);\n        }\n        finally\n        {\n\n            releaseConnection(conn);\n        }\n\n        List<SuperColumn> superColumns = ThriftDataResultHelper.transformThriftResult(coscList,\n                ColumnFamilyType.SUPER_COLUMN, null);\n        return superColumns;\n    }\n\n    /**\n     * Retrieves column for a given primary key.\n     * \n     * @param <E>\n     *            the element type\n     * @param schemaName\n     *            the schema name\n     * @param tableName\n     *            the table name\n     * @param pKeyColumnName\n     *            the key column name\n     * @param columnName\n     *            the column name\n     * @param pKeyColumnValue\n     *            the key column value\n     * @param columnJavaType\n     *            the column java type\n     * @return the columns by id\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,\n            Object pKeyColumnValue, Class columnJavaType)\n    {\n        List<Object> foreignKeys = new ArrayList<Object>();\n\n        if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0))\n        {\n            foreignKeys = getColumnsByIdUsingCql(schemaName, tableName, pKeyColumnName, columnName, pKeyColumnValue,\n                    columnJavaType);\n        }\n        else\n        {\n            byte[] rowKey = CassandraUtilities.toBytes(pKeyColumnValue);\n\n            if (rowKey != null)\n            {\n                SlicePredicate predicate = new SlicePredicate();\n                SliceRange sliceRange = new SliceRange();\n                sliceRange.setStart(new byte[0]);\n                sliceRange.setFinish(new byte[0]);\n                predicate.setSlice_range(sliceRange);\n\n                ColumnParent parent = new ColumnParent(tableName);\n                List<ColumnOrSuperColumn> results;\n                Connection conn = null;\n                try\n                {\n                    conn = getConnection();\n                    results = conn.getClient().get_slice(ByteBuffer.wrap(rowKey), parent, predicate,\n                            getConsistencyLevel());\n                }\n                catch (InvalidRequestException e)\n                {\n                    log.error(\"Error while getting columns for row Key {} , Caused by: .\", pKeyColumnValue, e);\n                    throw new EntityReaderException(e);\n                }\n                catch (UnavailableException e)\n                {\n                    log.error(\"Error while getting columns for row Key {} , Caused by: .\", pKeyColumnValue, e);\n                    throw new EntityReaderException(e);\n                }\n                catch (TimedOutException e)\n                {\n                    log.error(\"Error while getting columns for row Key {} , Caused by: .\", pKeyColumnValue, e);\n                    throw new EntityReaderException(e);\n                }\n                catch (TException e)\n                {\n                    log.error(\"Error while getting columns for row Key {} , Caused by: .\", pKeyColumnValue, e);\n                    throw new EntityReaderException(e);\n                }\n                finally\n                {\n                    releaseConnection(conn);\n                }\n\n                List<Column> columns = ThriftDataResultHelper.transformThriftResult(results, ColumnFamilyType.COLUMN,\n                        null);\n\n                foreignKeys = dataHandler.getForeignKeysFromJoinTable(columnName, columns, columnJavaType);\n            }\n        }\n        return (List<E>) foreignKeys;\n    }\n\n    /**\n     * Retrieves IDs for a given column.\n     * \n     * @param schemaName\n     *            the schema name\n     * @param tableName\n     *            the table name\n     * @param pKeyName\n     *            the key name\n     * @param columnName\n     *            the column name\n     * @param columnValue\n     *            the column value\n     * @param entityClazz\n     *            the entity clazz\n     * @return the object[]\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n        List<Object> rowKeys = new ArrayList<Object>();\n\n        if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0))\n        {\n            rowKeys = findIdsByColumnUsingCql(schemaName, tableName, pKeyName, columnName, columnValue, entityClazz);\n        }\n        else\n        {\n            EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n            SlicePredicate slicePredicate = new SlicePredicate();\n\n            slicePredicate.setSlice_range(new SliceRange(ByteBufferUtil.EMPTY_BYTE_BUFFER,\n                    ByteBufferUtil.EMPTY_BYTE_BUFFER, false, Integer.MAX_VALUE));\n\n            String childIdStr = PropertyAccessorHelper.getString(columnValue);\n            IndexExpression ie = new IndexExpression(UTF8Type.instance.decompose(columnName\n                    + Constants.JOIN_COLUMN_NAME_SEPARATOR + childIdStr), IndexOperator.EQ,\n                    UTF8Type.instance.decompose(childIdStr));\n\n            List<IndexExpression> expressions = new ArrayList<IndexExpression>();\n            expressions.add(ie);\n\n            IndexClause ix = new IndexClause();\n            ix.setStart_key(ByteBufferUtil.EMPTY_BYTE_BUFFER);\n            ix.setCount(Integer.MAX_VALUE);\n            ix.setExpressions(expressions);\n\n            ColumnParent columnParent = new ColumnParent(tableName);\n            Connection conn = null;\n            try\n            {\n                conn = getConnection();\n                List<KeySlice> keySlices = conn.getClient().get_indexed_slices(columnParent, ix, slicePredicate,\n                        getConsistencyLevel());\n\n                rowKeys = ThriftDataResultHelper.getRowKeys(keySlices, metadata);\n            }\n            catch (InvalidRequestException e)\n            {\n                log.error(\"Error while fetching key slices of column family {} for column name {} , Caused by: .\",\n                        tableName, columnName, e);\n                throw new KunderaException(e);\n            }\n            catch (UnavailableException e)\n            {\n                log.error(\"Error while fetching key slices of column family {} for column name {} , Caused by: .\",\n                        tableName, columnName, e);\n                throw new KunderaException(e);\n            }\n            catch (TimedOutException e)\n            {\n                log.error(\"Error while fetching key slices of column family {} for column name {} , Caused by: .\",\n                        tableName, columnName, e);\n                throw new KunderaException(e);\n            }\n            catch (TException e)\n            {\n                log.error(\"Error while fetching key slices of column family {} for column name {} , Caused by: .\",\n                        tableName, columnName, e);\n                throw new KunderaException(e);\n            }\n            finally\n            {\n                releaseConnection(conn);\n            }\n        }\n        if (rowKeys != null && !rowKeys.isEmpty())\n        {\n            return rowKeys.toArray(new Object[0]);\n        }\n\n        if (log.isInfoEnabled())\n        {\n            log.info(\"No record found!, returning null.\");\n        }\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n        List<Object> entities = null;\n\n        if (isCql3Enabled(m))\n        {\n            entities = new ArrayList<Object>();\n\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n\n            EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n            List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n\n            if (subManagedType.isEmpty())\n            {\n                entities.addAll(findByRelationQuery(m, colName, colValue, entityClazz, dataHandler));\n            }\n            else\n            {\n                for (AbstractManagedType subEntity : subManagedType)\n                {\n                    EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                            subEntity.getJavaType());\n\n                    entities.addAll(findByRelationQuery(subEntityMetadata, colName, colValue,\n                            subEntityMetadata.getEntityClazz(), dataHandler));\n                    // TODOO:: if(entities != null)\n                }\n            }\n\n        }\n        else\n        {\n            SlicePredicate slicePredicate = new SlicePredicate();\n            slicePredicate.setSlice_range(new SliceRange(ByteBufferUtil.EMPTY_BYTE_BUFFER,\n                    ByteBufferUtil.EMPTY_BYTE_BUFFER, false, Integer.MAX_VALUE));\n\n            IndexExpression ie = new IndexExpression(UTF8Type.instance.decompose(colName), IndexOperator.EQ,\n                    ByteBuffer.wrap(PropertyAccessorHelper.getBytes(colValue)));\n            List<IndexExpression> expressions = new ArrayList<IndexExpression>();\n            expressions.add(ie);\n\n            IndexClause ix = new IndexClause();\n            ix.setStart_key(ByteBufferUtil.EMPTY_BYTE_BUFFER);\n            ix.setCount(Integer.MAX_VALUE);\n            ix.setExpressions(expressions);\n            ColumnParent columnParent = new ColumnParent(m.getTableName());\n\n            List<KeySlice> keySlices = null;\n            Connection conn = null;\n\n            try\n            {\n                conn = getConnection();\n                if (!m.getType().equals(Type.SUPER_COLUMN_FAMILY))\n                {\n                    keySlices = conn.getClient().get_indexed_slices(columnParent, ix, slicePredicate,\n                            getConsistencyLevel());\n                }\n            }\n            catch (InvalidRequestException e)\n            {\n                if (e.why != null && e.why.contains(\"No indexed columns\"))\n                {\n                    return entities;\n                }\n                else\n                {\n                    log.error(\"Error while finding relations for column family {} , Caused by: .\", m.getTableName(), e);\n                    throw new KunderaException(e);\n                }\n            }\n            catch (UnavailableException e)\n            {\n                log.error(\"Error while finding relations for column family {} , Caused by: .\", m.getTableName(), e);\n                throw new KunderaException(e);\n            }\n            catch (TimedOutException e)\n            {\n                log.error(\"Error while finding relations for column family {} , Caused by: .\", m.getTableName(), e);\n                throw new KunderaException(e);\n            }\n            catch (TException e)\n            {\n                log.error(\"Error while finding relations for column family {} , Caused by: .\", m.getTableName(), e);\n                throw new KunderaException(e);\n            }\n            finally\n            {\n                releaseConnection(conn);\n            }\n\n            if (keySlices != null)\n            {\n                entities = new ArrayList<Object>(keySlices.size());\n\n                MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                        m.getPersistenceUnit());\n\n                EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n                List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n\n                if (subManagedType.isEmpty())\n                {\n                    entities = populateData(m, keySlices, entities, m.getRelationNames() != null, m.getRelationNames());\n                }\n                else\n                {\n                    for (AbstractManagedType subEntity : subManagedType)\n                    {\n                        EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                                subEntity.getJavaType());\n                        entities = populateData(subEntityMetadata, keySlices, entities,\n                                subEntityMetadata.getRelationNames() != null, subEntityMetadata.getRelationNames());\n                        // TODOO:: if(entities != null)\n\n                    }\n                }\n            }\n        }\n        return entities;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.cassandra.CassandraClientBase#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    public void delete(Object entity, Object pKey)\n    {\n        if (!isOpen())\n        {\n            throw new PersistenceException(\"ThriftClient is closed.\");\n        }\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        Connection conn = null;\n        try\n        {\n            conn = getConnection();\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    metadata.getPersistenceUnit());\n\n            AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(metadata.getEntityClazz());\n            // For secondary tables.\n            List<String> secondaryTables = ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation())\n                    .getSecondaryTablesName();\n            secondaryTables.add(metadata.getTableName());\n\n            for (String tableName : secondaryTables)\n            {\n                if (isCql3Enabled(metadata))\n                {\n                    String deleteQuery = onDeleteQuery(metadata, tableName, metaModel, pKey);\n                    executeCQLQuery(deleteQuery, isCql3Enabled(metadata));\n\n                }\n                else\n                {\n                    if (metadata.isCounterColumnType())\n                    {\n                        deleteRecordFromCounterColumnFamily(pKey, tableName, metadata, getConsistencyLevel());\n                    }\n                    else\n                    {\n                        ColumnPath path = new ColumnPath(tableName);\n\n                        conn.getClient().remove(\n                                CassandraUtilities.toBytes(pKey, metadata.getIdAttribute().getJavaType()), path,\n                                generator.getTimestamp(), getConsistencyLevel());\n                    }\n                }\n            }\n            getIndexManager().remove(metadata, entity, pKey);\n\n            // Delete from Inverted Index if applicable\n            invertedIndexHandler.delete(entity, metadata, getConsistencyLevel(), kunderaMetadata);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(\"Error while deleting of column family {} for row key {}, Caused by: .\", metadata.getTableName(),\n                    pKey, e);\n            throw new KunderaException(e);\n        }\n        catch (TException e)\n        {\n            log.error(\"Error while deleting of column family {} for row key {}, Caused by: .\", metadata.getTableName(),\n                    pKey, e);\n            throw new KunderaException(e);\n        }\n        finally\n        {\n            releaseConnection(conn);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    @Override\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n        if (!isOpen())\n        {\n            throw new PersistenceException(\"ThriftClient is closed.\");\n        }\n\n        Connection conn = null;\n        try\n        {\n            conn = getConnection();\n            ColumnPath path = new ColumnPath(tableName);\n            conn.getClient().remove(CassandraUtilities.toBytes(columnValue, columnValue.getClass()), path,\n                    generator.getTimestamp(), getConsistencyLevel());\n\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(\"Error while deleting of column family {} for row key {}, Caused by: .\", tableName, columnValue,\n                    e);\n            throw new KunderaException(e);\n        }\n        catch (TException e)\n        {\n            log.error(\"Error while deleting of column family {} for row key {}, Caused by: .\", tableName, columnValue,\n                    e);\n            throw new KunderaException(e);\n        }\n        finally\n        {\n            releaseConnection(conn);\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<CassQuery> getQueryImplementor()\n    {\n        return CassQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientBase#getPersistenceUnit()\n     */\n    @Override\n    public String getPersistenceUnit()\n    {\n        return super.getPersistenceUnit();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientBase#getRelationHolders(com.impetus.\n     * kundera.graph.Node)\n     */\n    @Override\n    protected List<RelationHolder> getRelationHolders(Node node)\n    {\n        return super.getRelationHolders(node);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#close()\n     */\n    @Override\n    public void close()\n    {\n        this.indexManager.flush();\n        // this.dataHandler = null;\n        // this.invertedIndexHandler = null;\n        super.close();\n    }\n\n    /**\n     * Populate data.\n     * \n     * @param m\n     *            the m\n     * @param keySlices\n     *            the key slices\n     * @param entities\n     *            the entities\n     * @param isRelational\n     *            the is relational\n     * @param relationNames\n     *            the relation names\n     * @return the list\n     */\n    private List populateData(EntityMetadata m, List<KeySlice> keySlices, List<Object> entities, boolean isRelational,\n            List<String> relationNames)\n    {\n        try\n        {\n            if (m.getType().isSuperColumnFamilyMetadata())\n            {\n                List<Object> rowKeys = ThriftDataResultHelper.getRowKeys(keySlices, m);\n\n                Object[] rowIds = rowKeys.toArray();\n                entities.addAll(findAll(m.getEntityClazz(), null, rowIds));\n            }\n            else\n            {\n                for (KeySlice keySlice : keySlices)\n                {\n                    byte[] key = keySlice.getKey();\n                    List<ColumnOrSuperColumn> coscList = keySlice.getColumns();\n\n                    List<Column> columns = ThriftDataResultHelper.transformThriftResult(coscList,\n                            ColumnFamilyType.COLUMN, null);\n                    Object e = null;\n                    Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key);\n                    e = dataHandler.populateEntity(new ThriftRow(id, m.getTableName(), columns,\n                            new ArrayList<SuperColumn>(0), new ArrayList<CounterColumn>(0),\n                            new ArrayList<CounterSuperColumn>(0)), m, KunderaCoreUtils.getEntity(e), relationNames,\n                            isRelational);\n                    entities.add(e);\n                }\n            }\n        }\n        catch (Exception e)\n        {\n\n            log.error(\"Error while populating data for relations of column family {}, Caused by: .\", m.getTableName(),\n                    e);\n            throw new KunderaException(e);\n        }\n        return entities;\n    }\n\n    /**\n     * Query related methods.\n     * \n     * @param clazz\n     *            the clazz\n     * @param relationalField\n     *            the relational field\n     * @param isNative\n     *            the is native\n     * @param cqlQuery\n     *            the cql query\n     * @return the list\n     */\n\n    @Override\n    public List executeQuery(Class clazz, List<String> relationalField, boolean isNative, String cqlQuery)\n    {\n        if (clazz == null)\n        {\n            return super.executeScalarQuery(cqlQuery);\n        }\n        return super.executeSelectQuery(clazz, relationalField, dataHandler, isNative, cqlQuery);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.cassandra.CassandraClientBase#find(java.util.List,\n     * com.impetus.kundera.metadata.model.EntityMetadata, boolean,\n     * java.util.List, int, java.util.List)\n     */\n    @Override\n    public List find(List<IndexClause> ixClause, EntityMetadata m, boolean isRelation, List<String> relations,\n            int maxResult, List<String> columns)\n    {\n        List<Object> entities = new ArrayList<Object>();\n        Connection conn = null;\n        try\n        {\n            // ixClause can be 0,1 or more!\n            SlicePredicate slicePredicate = new SlicePredicate();\n\n            if (columns != null && !columns.isEmpty())\n            {\n                List asList = new ArrayList(32);\n                for (String colName : columns)\n                {\n                    if (colName != null)\n                    {\n                        asList.add(UTF8Type.instance.decompose(colName));\n                    }\n                }\n                slicePredicate.setColumn_names(asList);\n            }\n            else\n            {\n                SliceRange sliceRange = new SliceRange();\n                sliceRange.setStart(ByteBufferUtil.EMPTY_BYTE_BUFFER);\n                sliceRange.setFinish(ByteBufferUtil.EMPTY_BYTE_BUFFER);\n                slicePredicate.setSlice_range(sliceRange);\n            }\n            conn = getConnection();\n\n            if (ixClause.isEmpty())\n            {\n                KeyRange keyRange = new KeyRange(maxResult);\n                keyRange.setStart_key(ByteBufferUtil.EMPTY_BYTE_BUFFER);\n                keyRange.setEnd_key(ByteBufferUtil.EMPTY_BYTE_BUFFER);\n\n                if (m.isCounterColumnType())\n                {\n                    List<KeySlice> ks = conn.getClient().get_range_slices(new ColumnParent(m.getTableName()),\n                            slicePredicate, keyRange, getConsistencyLevel());\n                    entities = onCounterColumn(m, isRelation, relations, ks);\n\n                }\n                else\n                {\n                    List<KeySlice> keySlices = conn.getClient().get_range_slices(new ColumnParent(m.getTableName()),\n                            slicePredicate, keyRange, getConsistencyLevel());\n\n                    if (m.getType().isSuperColumnFamilyMetadata())\n                    {\n                        Map<ByteBuffer, List<SuperColumn>> qResults = ThriftDataResultHelper.transformThriftResult(\n                                ColumnFamilyType.SUPER_COLUMN, keySlices, null);\n                        entities = new ArrayList<Object>(qResults.size());\n                        computeEntityViaSuperColumns(m, isRelation, relations, entities, qResults);\n                    }\n                    else\n                    {\n                        Map<ByteBuffer, List<Column>> qResults = ThriftDataResultHelper.transformThriftResult(\n                                ColumnFamilyType.COLUMN, keySlices, null);\n                        entities = new ArrayList<Object>(qResults.size());\n                        computeEntityViaColumns(m, isRelation, relations, entities, qResults);\n                    }\n                }\n            }\n            else\n            {\n                entities = new ArrayList<Object>();\n                for (IndexClause ix : ixClause)\n                {\n                    List<KeySlice> keySlices = conn.getClient().get_indexed_slices(new ColumnParent(m.getTableName()),\n                            ix, slicePredicate, getConsistencyLevel());\n\n                    Map<ByteBuffer, List<Column>> qResults = ThriftDataResultHelper.transformThriftResult(\n                            ColumnFamilyType.COLUMN, keySlices, null);\n                    // iterate through complete map and populate.\n                    entities = new ArrayList<Object>(qResults.size());\n\n                    computeEntityViaColumns(m, isRelation, relations, entities, qResults);\n                }\n            }\n        }\n        catch (InvalidRequestException irex)\n        {\n            log.error(\"Error during executing find of column family {}, Caused by: .\", m.getTableName(), irex);\n            throw new PersistenceException(irex);\n        }\n        catch (UnavailableException uex)\n        {\n            log.error(\"Error during executing find of column family {}, Caused by: .\", m.getTableName(), uex);\n            throw new PersistenceException(uex);\n        }\n        catch (TimedOutException tex)\n        {\n            log.error(\"Error during executing find of column family {}, Caused by: .\", m.getTableName(), tex);\n            throw new PersistenceException(tex);\n        }\n        catch (TException tex)\n        {\n            log.error(\"Error during executing find of column family {}, Caused by: .\", m.getTableName(), tex);\n            throw new PersistenceException(tex);\n        }\n        finally\n        {\n\n            releaseConnection(conn);\n        }\n        return entities;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.cassandra.CassandraClientBase#find(com.impetus.kundera\n     * .metadata.model.EntityMetadata, java.util.List, java.util.List, int,\n     * java.util.List)\n     */\n    @Override\n    public List<EnhanceEntity> find(EntityMetadata m, List<String> relationNames, List<IndexClause> conditions,\n            int maxResult, List<String> columns)\n    {\n        return (List<EnhanceEntity>) find(conditions, m, true, relationNames, maxResult, columns);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#findByRange(byte[],\n     * byte[], com.impetus.kundera.metadata.model.EntityMetadata, boolean,\n     * java.util.List, java.util.List, java.util.List, int)\n     */\n    @Override\n    public List findByRange(byte[] minVal, byte[] maxVal, EntityMetadata m, boolean isWrapReq, List<String> relations,\n            List<String> columns, List<IndexExpression> conditions, int maxResults) throws Exception\n    {\n        SlicePredicate slicePredicate = new SlicePredicate();\n\n        if (columns != null && !columns.isEmpty())\n        {\n            List asList = new ArrayList(32);\n            for (String colName : columns)\n            {\n                if (colName != null)\n                {\n                    asList.add(UTF8Type.instance.decompose(colName));\n                }\n            }\n            slicePredicate.setColumn_names(asList);\n        }\n        else\n        {\n            SliceRange sliceRange = new SliceRange();\n            sliceRange.setStart(ByteBufferUtil.EMPTY_BYTE_BUFFER);\n            sliceRange.setFinish(ByteBufferUtil.EMPTY_BYTE_BUFFER);\n            slicePredicate.setSlice_range(sliceRange);\n        }\n\n        KeyRange keyRange = new KeyRange(maxResults);\n        keyRange.setStart_key(minVal == null ? \"\".getBytes() : minVal);\n        keyRange.setEnd_key(maxVal == null ? \"\".getBytes() : maxVal);\n        ColumnParent cp = new ColumnParent(m.getTableName());\n\n        if (conditions != null && !conditions.isEmpty())\n        {\n            keyRange.setRow_filter(conditions);\n            keyRange.setRow_filterIsSet(true);\n        }\n\n        Connection conn = getConnection();\n\n        List<KeySlice> keys = conn.getClient().get_range_slices(cp, slicePredicate, keyRange, getConsistencyLevel());\n\n        releaseConnection(conn);\n\n        List results = null;\n        if (keys != null)\n        {\n            results = populateEntitiesFromKeySlices(m, isWrapReq, relations, keys, dataHandler);\n        }\n        return results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.cassandra.CassandraClientBase#searchInInvertedIndex\n     * (java.lang.String, com.impetus.kundera.metadata.model.EntityMetadata,\n     * java.util.Map)\n     */\n    @Override\n    public List<SearchResult> searchInInvertedIndex(String columnFamilyName, EntityMetadata m,\n            Map<Boolean, List<IndexClause>> indexClauseMap)\n    {\n        return invertedIndexHandler.search(m, getPersistenceUnit(), getConsistencyLevel(), indexClauseMap);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#getDataHandler()\n     */\n    @Override\n    protected CassandraDataHandler getDataHandler()\n    {\n        return dataHandler;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#getConnection()\n     */\n    protected Connection getConnection()\n    {\n        Connection connection = clientFactory.getConnection(pool);\n        return connection;\n    }\n\n    /**\n     * Return cassandra client instance.\n     * \n     * @param connection\n     *            the connection\n     * @return the connection\n     */\n    protected Cassandra.Client getConnection(Object connection)\n    {\n        if (connection != null)\n        {\n            return ((Connection) connection).getClient();\n        }\n\n        throw new KunderaException(\"Invalid configuration!, no available pooled connection found for:\"\n                + this.getClass().getSimpleName());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.cassandra.CassandraClientBase#releaseConnection(java\n     * .lang.Object)\n     */\n    protected void releaseConnection(Object conn)\n    {\n        clientFactory.releaseConnection(((Connection) conn).getPool(), ((Connection) conn).getClient());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        return (Generator) KunderaCoreUtils.createNewInstance(ThriftIdGenerator.class);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/ThriftClientFactory.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.thrift;\n\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport net.dataforte.cassandra.pool.ConnectionPool;\nimport net.dataforte.cassandra.pool.PoolConfiguration;\nimport net.dataforte.cassandra.pool.PoolProperties;\n\nimport org.apache.cassandra.thrift.Cassandra;\nimport org.apache.thrift.TException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.common.collect.Lists;\nimport com.impetus.client.cassandra.common.CassandraClientFactory;\nimport com.impetus.client.cassandra.common.CassandraUtilities;\nimport com.impetus.client.cassandra.config.CassandraPropertyReader;\nimport com.impetus.client.cassandra.query.CassandraEntityReader;\nimport com.impetus.client.cassandra.schemamanager.CassandraSchemaManager;\nimport com.impetus.client.cassandra.service.CassandraHost;\nimport com.impetus.client.cassandra.service.CassandraHostConfiguration;\nimport com.impetus.client.cassandra.service.CassandraRetryService;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.service.Host;\nimport com.impetus.kundera.service.HostConfiguration;\nimport com.impetus.kundera.service.policy.LeastActiveBalancingPolicy;\nimport com.impetus.kundera.service.policy.RoundRobinBalancingPolicy;\n\n/**\n * A factory of {@link ThriftClient} Currently it uses Pelops for Connection\n * pooling. Need to replace it with our own pooling. Most of the code is\n * borrowed from {@link PelopsClientFactory}\n * \n * @author amresh.singh\n */\npublic class ThriftClientFactory extends CassandraClientFactory\n{\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(ThriftClientFactory.class);\n\n    /** The configuration. */\n    protected HostConfiguration configuration;\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.loader.ClientFactory#getSchemaManager(java.util.Map)\n     */\n    @Override\n    public SchemaManager getSchemaManager(Map<String, Object> externalProperty)\n    {\n        if (schemaManager == null)\n        {\n            initializePropertyReader();\n            schemaManager = new CassandraSchemaManager(ThriftClientFactory.class.getName(), externalProperties,\n                    kunderaMetadata);\n        }\n        return schemaManager;\n    }\n\n    /**\n     * Initialize property reader.\n     */\n    private void initializePropertyReader()\n    {\n        if (propertyReader == null)\n        {\n            propertyReader = new CassandraPropertyReader(externalProperties, kunderaMetadata.getApplicationMetadata()\n                    .getPersistenceUnitMetadata(getPersistenceUnit()));\n            propertyReader.read(getPersistenceUnit());\n        }\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.loader.ClientLifeCycleManager#destroy()\n     */\n    @Override\n    public void destroy()\n    {\n        if (indexManager != null)\n        {\n            indexManager.close();\n        }\n        if (schemaManager != null)\n        {\n            schemaManager.dropSchema();\n        }\n        schemaManager = null;\n        externalProperties = null;\n\n        for (Object connectionPool : hostPools.values())\n        {\n            if (connectionPool != null && connectionPool.getClass().isAssignableFrom(ConnectionPool.class))\n            {\n                ((ConnectionPool) connectionPool).close(true);\n            }\n        }\n        ((CassandraRetryService) hostRetryService).shutdown();\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.loader.GenericClientFactory#initialize(java.util.Map)\n     */\n    @Override\n    public void initialize(Map<String, Object> externalProperty)\n    {\n        reader = new CassandraEntityReader(kunderaMetadata);\n        initializePropertyReader();\n        setExternalProperties(externalProperty);\n        String loadBalancingPolicyName = CassandraPropertyReader.csmd != null ? CassandraPropertyReader.csmd\n                .getConnectionProperties().getProperty(Constants.LOADBALANCING_POLICY) : null;\n        initializeLoadBalancer(loadBalancingPolicyName);\n        configuration = new CassandraHostConfiguration(externalProperties, CassandraPropertyReader.csmd,\n                getPersistenceUnit(), kunderaMetadata);\n        hostRetryService = new CassandraRetryService(configuration, this);\n\n        // initialize timestamp generator.\n        initializeTimestampGenerator(externalProperty);\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.loader.GenericClientFactory#createPoolOrConnection()\n     */\n    @Override\n    protected Object createPoolOrConnection()\n    {\n        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(getPersistenceUnit());\n\n        Properties props = persistenceUnitMetadata.getProperties();\n        String keyspace = null;\n\n        if (externalProperties != null)\n        {\n            keyspace = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);\n        }\n\n        if (keyspace == null)\n        {\n            keyspace = (String) props.get(PersistenceProperties.KUNDERA_KEYSPACE);\n        }\n\n        for (Host host : ((CassandraHostConfiguration) configuration).getCassandraHosts())\n        {\n            PoolConfiguration prop = new PoolProperties();\n            prop.setHost(host.getHost());\n            prop.setPort(host.getPort());\n            prop.setKeySpace(keyspace);\n\n            CassandraUtilities.setPoolConfigPolicy((CassandraHost) host, prop);\n            try\n            {\n                ConnectionPool pool = new ConnectionPool(prop);\n                hostPools.put(host, pool);\n            }\n            catch (TException e)\n            {\n                logger.warn(\"Node {} are down, Caused by {} .\", host.getHost(), e.getMessage());\n                if (host.isRetryHost())\n                {\n                    logger.warn(\"Scheduling node for future retry\");\n                    ((CassandraRetryService) hostRetryService).add((CassandraHost) host);\n                }\n            }\n        }\n        return null;\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.loader.GenericClientFactory#instantiateClient(java.lang.String)\n     */\n    @Override\n    protected Client instantiateClient(String persistenceUnit)\n    {\n        ConnectionPool pool = getPoolUsingPolicy();\n        return new ThriftClient(this, indexManager, reader, persistenceUnit, pool, externalProperties, kunderaMetadata, timestampGenerator);\n    }\n\n    /**\n     * Gets the pool using policy.\n     *\n     * @return pool an the basis of LoadBalancing policy.\n     */\n    private ConnectionPool getPoolUsingPolicy()\n    {\n        if (!hostPools.isEmpty())\n        {\n            return (ConnectionPool) loadBalancingPolicy.getPool(hostPools.values());\n        }\n        throw new KunderaException(\"All hosts are down. please check servers manully.\");\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.loader.GenericClientFactory#isThreadSafe()\n     */\n    @Override\n    public boolean isThreadSafe()\n    {\n        return false;\n    }\n\n    /**\n     * Gets the new pool.\n     *\n     * @param host the host\n     * @param port the port\n     * @return the new pool\n     */\n    private ConnectionPool getNewPool(String host, int port)\n    {\n        CassandraHost cassandraHost = ((CassandraHostConfiguration) configuration).getCassandraHost(host, port);\n        hostPools.remove(cassandraHost);\n\n        if (cassandraHost.isRetryHost())\n        {\n            logger.warn(\"Scheduling node for future retry\");\n            ((CassandraRetryService) hostRetryService).add((CassandraHost) cassandraHost);\n        }\n\n        return getPoolUsingPolicy();\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.kundera.loader.GenericClientFactory#initializeLoadBalancer(java.lang.String)\n     */\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n        if (loadBalancingPolicyName != null)\n        {\n            switch (LoadBalancer.getValue(loadBalancingPolicyName))\n            {\n            case ROUNDROBIN:\n                loadBalancingPolicy = new RoundRobinBalancingPolicy();\n                break;\n            case LEASTACTIVE:\n                loadBalancingPolicy = new ThriftLeastActiveBalancingPolcy();\n                break;\n            default:\n                loadBalancingPolicy = new RoundRobinBalancingPolicy();\n                break;\n            }\n        }\n        loadBalancingPolicy = new RoundRobinBalancingPolicy();\n    }\n\n    /**\n     * Gets the connection.\n     *\n     * @param pool the pool\n     * @return the connection\n     */\n    Connection getConnection(ConnectionPool pool)\n    {\n        ConnectionPool connectionPool = pool;\n        boolean success = false;\n        while (!success)\n        {\n            try\n            {\n                success = true;\n                Cassandra.Client client = connectionPool.getConnection();\n\n                if (logger.isDebugEnabled())\n                {\n                    logger.debug(\"Returning connection of {} :{} .\", pool.getPoolProperties().getHost(), pool\n                            .getPoolProperties().getPort());\n                }\n\n                return new Connection(client, connectionPool);\n            }\n            catch (TException te)\n            {\n                success = false;\n                logger.warn(\"{} :{}  host appears to be down, trying for next \", pool.getPoolProperties().getHost(),\n                        pool.getPoolProperties().getPort());\n                connectionPool = getNewPool(pool.getPoolProperties().getHost(), pool.getPoolProperties().getPort());\n            }\n        }\n\n        throw new KunderaException(\"All hosts are down. please check servers manully.\");\n    }\n\n    /**\n     * Release connection.\n     *\n     * @param pool the pool\n     * @param conn the conn\n     */\n    void releaseConnection(ConnectionPool pool, Cassandra.Client conn)\n    {\n        if (pool != null && conn != null)\n        {\n            pool.release(conn);\n        }\n    }\n\n    /**\n     * Adds a pool in hostPools map for given host.\n     *\n     * @param cassandraHost the cassandra host\n     * @return true id added successfully.\n     */\n    public boolean addCassandraHost(CassandraHost cassandraHost)\n    {\n        String keysapce = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata, getPersistenceUnit())\n                .getProperties().getProperty(PersistenceProperties.KUNDERA_KEYSPACE);\n        PoolConfiguration prop = new PoolProperties();\n        prop.setHost(cassandraHost.getHost());\n        prop.setPort(cassandraHost.getPort());\n        prop.setKeySpace(keysapce);\n\n        CassandraUtilities.setPoolConfigPolicy(cassandraHost, prop);\n        try\n        {\n            if (logger.isInfoEnabled())\n            {\n                logger.info(\"Initializing connection for keyspace {},host {},port {}\", keysapce,\n                        cassandraHost.getHost(), cassandraHost.getPort());\n            }\n            ConnectionPool pool = new ConnectionPool(prop);\n            hostPools.put(cassandraHost, pool);\n            return true;\n        }\n        catch (TException e)\n        {\n            logger.warn(\"Node \" + cassandraHost.getHost() + \" are still down\");\n            return false;\n        }\n    }\n\n    /**\n     * Extends LeastActiveBalancingPolicy class and provide own implementation\n     * in order to support least active balancing policy.\n     * \n     * @author Kuldeep.Mishra\n     * \n     */\n    private class ThriftLeastActiveBalancingPolcy extends LeastActiveBalancingPolicy\n    {\n\n        /**\n         * Gets the pool.\n         *\n         * @param pools the pools\n         * @return pool object for host which has least active connections\n         *         determined by maxActive connection.\n         */\n        @Override\n        public Object getPool(Collection<Object> pools)\n        {\n            List<Object> vals = Lists.newArrayList(pools);\n            Collections.shuffle(vals);\n            Collections.sort(vals, new ShufflingCompare());\n            Collections.reverse(vals);\n            Iterator<Object> iterator = vals.iterator();\n            Object concurrentConnectionPool = iterator.next();\n            return concurrentConnectionPool;\n        }\n\n        /**\n         * Compares two pool object on the basis of their maxActive connection.\n         * \n         * @author Kuldeep Mishra\n         * \n         */\n        private final class ShufflingCompare implements Comparator<Object>\n        {\n            \n            /* (non-Javadoc)\n             * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)\n             */\n            public int compare(Object o1, Object o2)\n            {\n                PoolConfiguration props1 = ((ConnectionPool) o1).getPoolProperties();\n                PoolConfiguration props2 = ((ConnectionPool) o2).getPoolProperties();\n\n                int activeConnections1 = ((ConnectionPool) o1).getActive();\n                int activeConnections2 = ((ConnectionPool) o2).getActive();\n\n                return (props1.getMaxActive() - activeConnections1) - (props2.getMaxActive() - activeConnections2);\n            }\n        }\n    }\n\n    /**\n     * Connection class holds client and related pool.\n     * \n     * @author Kuldeep.Mishra\n     * \n     */\n    public class Connection\n    {\n        \n        /** The client. */\n        private Cassandra.Client client;\n\n        /** The pool. */\n        private ConnectionPool pool;\n\n        /**\n         * Instantiates a new connection.\n         *\n         * @param client the client\n         * @param pool the pool\n         */\n        public Connection(org.apache.cassandra.thrift.Cassandra.Client client, ConnectionPool pool)\n        {\n            this.client = client;\n            this.pool = pool;\n        }\n\n        /**\n         * Gets the client.\n         *\n         * @return the client\n         */\n        public Cassandra.Client getClient()\n        {\n            return client;\n        }\n\n        /**\n         * Gets the pool.\n         *\n         * @return the pool\n         */\n        public ConnectionPool getPool()\n        {\n            return pool;\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/ThriftDataHandler.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.thrift;\n\nimport java.nio.ByteBuffer;\nimport java.nio.charset.CharacterCodingException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.cassandra.thrift.ColumnOrSuperColumn;\nimport org.apache.cassandra.thrift.ColumnParent;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.SlicePredicate;\nimport org.apache.cassandra.thrift.SliceRange;\nimport org.apache.cassandra.thrift.SuperColumn;\nimport org.apache.cassandra.utils.ByteBufferUtil;\n\nimport com.impetus.client.cassandra.common.CassandraUtilities;\nimport com.impetus.client.cassandra.datahandler.CassandraDataHandler;\nimport com.impetus.client.cassandra.datahandler.CassandraDataHandlerBase;\nimport com.impetus.client.cassandra.thrift.ThriftClientFactory.Connection;\nimport com.impetus.kundera.db.DataRow;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.annotation.DefaultEntityAnnotationProcessor;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.TimestampGenerator;\n\n\n/**\n * Data handler for Thrift Clients.\n *\n * @author amresh.singh\n */\n/**\n * @author vivek.mishra\n * \n */\npublic final class ThriftDataHandler extends CassandraDataHandlerBase implements CassandraDataHandler\n{\n    \n    /** The thrift client. */\n    private final ThriftClient thriftClient;\n\n    /**\n     * Instantiates a new thrift data handler.\n     *\n     * @param thriftClient the thrift client\n     * @param kunderaMetadata the kundera metadata\n     * @param generator the generator\n     */\n    public ThriftDataHandler(final ThriftClient thriftClient, final KunderaMetadata kunderaMetadata,\n            final TimestampGenerator generator)\n    {\n        super(thriftClient, kunderaMetadata, generator);\n        this.thriftClient = thriftClient;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.datahandler.CassandraDataHandlerBase#\n     * fromThriftRow(java.lang.Class,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.lang.String,\n     * java.util.List, boolean, org.apache.cassandra.thrift.ConsistencyLevel)\n     */\n    @Override\n    public Object fromThriftRow(Class<?> clazz, EntityMetadata m, Object rowKey, List<String> relationNames,\n            boolean isWrapReq, ConsistencyLevel consistencyLevel) throws Exception\n    {\n        Object e = null;\n        SlicePredicate predicate = new SlicePredicate();\n        predicate.setSlice_range(new SliceRange(ByteBufferUtil.EMPTY_BYTE_BUFFER, ByteBufferUtil.EMPTY_BYTE_BUFFER,\n                true, 10000));\n\n        ByteBuffer key = ByteBuffer.wrap(PropertyAccessorHelper.toBytes(rowKey, m.getIdAttribute().getJavaType()));\n        Connection conn = thriftClient.getConnection();\n        try\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n\n            AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(m.getEntityClazz());\n\n            // For secondary tables.\n            List<String> secondaryTables = ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation())\n                    .getSecondaryTablesName();\n            secondaryTables.add(m.getTableName());\n\n            for (String tableName : secondaryTables)\n            {\n                List<ColumnOrSuperColumn> columnOrSuperColumns = conn.getClient().get_slice(key,\n                        new ColumnParent(tableName), predicate, consistencyLevel);\n\n                Map<ByteBuffer, List<ColumnOrSuperColumn>> thriftColumnOrSuperColumns = new HashMap<ByteBuffer, List<ColumnOrSuperColumn>>();\n                thriftColumnOrSuperColumns.put(key, columnOrSuperColumns);\n                if (!columnOrSuperColumns.isEmpty())\n                {\n                    e = populateEntityFromSlice(m, relationNames, isWrapReq, KunderaCoreUtils.getEntity(e),\n                            thriftColumnOrSuperColumns);\n                }\n            }\n            return e;\n        }\n        finally\n        {\n            thriftClient.releaseConnection(conn);\n        }\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.client.cassandra.datahandler.CassandraDataHandlerBase#fromThriftRow(java.lang.Class, com.impetus.kundera.metadata.model.EntityMetadata, com.impetus.kundera.db.DataRow)\n     */\n    @Override\n    public <E> E fromThriftRow(Class<E> clazz, EntityMetadata m, DataRow<SuperColumn> tr) throws Exception\n    {\n        return super.fromThriftRow(clazz, m, tr);\n    }\n\n    /**\n     * Populate entity from slice.\n     *\n     * @param m the m\n     * @param relationNames the relation names\n     * @param isWrapReq the is wrap req\n     * @param e the e\n     * @param columnOrSuperColumnsFromRow the column or super columns from row\n     * @return the object\n     * @throws CharacterCodingException the character coding exception\n     */\n    private Object populateEntityFromSlice(EntityMetadata m, List<String> relationNames, boolean isWrapReq, Object e,\n            Map<ByteBuffer, List<ColumnOrSuperColumn>> columnOrSuperColumnsFromRow) throws CharacterCodingException\n    {\n        ThriftDataResultHelper dataGenerator = new ThriftDataResultHelper();\n        for (ByteBuffer key : columnOrSuperColumnsFromRow.keySet())\n        {\n            Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key.array());\n            ThriftRow tr = new ThriftRow();\n            tr.setColumnFamilyName(m.getTableName());\n            tr.setId(id);\n            tr = dataGenerator.translateToThriftRow(columnOrSuperColumnsFromRow, m.isCounterColumnType(), m.getType(),\n                    tr);\n            e = populateEntity(tr, m, e, relationNames, isWrapReq);\n        }\n        return e;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/ThriftDataResultHelper.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.thrift;\n\nimport java.lang.reflect.Field;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.cassandra.thrift.ColumnOrSuperColumn;\nimport org.apache.cassandra.thrift.KeySlice;\n\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata.Type;\nimport com.impetus.kundera.property.PropertyAccessor;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\n\n\n/**\n * Provides utility methods for extracting useful data from Thrift result\n * retrieved from database (usually in the form of {@link ColumnOrSuperColumn}.\n *\n * @author amresh.singh\n */\npublic class ThriftDataResultHelper\n{\n    \n    /**\n     * The Enum ColumnFamilyType.\n     */\n    public enum ColumnFamilyType\n    {\n        \n        /** The column. */\n        COLUMN, /* Column family */\n        /** The super column. */\n        SUPER_COLUMN, /* Super Column family */\n        /** The counter column. */\n        COUNTER_COLUMN, /* Counter Column family */\n        /** The counter super column. */\n        COUNTER_SUPER_COLUMN\n        /* Super Counter Column family */\n    }\n\n    /**\n     * Transforms data retrieved as result via thrift to a List whose content\n     * type is determined by {@link ColumnFamilyType}.\n     *\n     * @param <T> the generic type\n     * @param coscList the cosc list\n     * @param columnFamilyType the column family type\n     * @param row the row\n     * @return the list\n     */\n    public static <T> List<T> transformThriftResult(List<ColumnOrSuperColumn> coscList,\n            ColumnFamilyType columnFamilyType, ThriftRow row)\n    {\n        List result = new ArrayList(coscList.size());\n        for (ColumnOrSuperColumn cosc : coscList)\n        {\n            result.add(transformThriftResult(cosc, columnFamilyType, row));\n        }\n        return result;\n    }\n\n    /**\n     * Transform thrift result.\n     *\n     * @param <T> the generic type\n     * @param cosc the cosc\n     * @param columnFamilyType the column family type\n     * @param row the row\n     * @return the t\n     */\n    public static <T> T transformThriftResult(ColumnOrSuperColumn cosc, ColumnFamilyType columnFamilyType, ThriftRow row)\n    {\n        Object output = null;\n        if (cosc != null)\n        {\n            switch (columnFamilyType)\n            {\n            case COLUMN:\n                output = cosc.column;\n                if (row != null)\n                {\n                    row.addColumn(cosc.column);\n                }\n                break;\n\n            case SUPER_COLUMN:\n                output = cosc.super_column;\n                if (row != null)\n                {\n                    row.addSuperColumn(cosc.super_column);\n                }\n                break;\n\n            case COUNTER_COLUMN:\n                output = cosc.counter_column;\n                if (row != null)\n                {\n                    row.addCounterColumn(cosc.counter_column);\n                }\n                break;\n\n            case COUNTER_SUPER_COLUMN:\n                output = cosc.counter_super_column;\n                if (row != null)\n                {\n                    row.addCounterSuperColumn(cosc.counter_super_column);\n                }\n                break;\n            }\n        }\n        return (T) output;\n    }\n\n    /**\n     * Transforms data retrieved as result via thrift to a Map whose content\n     * type is determined by {@link ColumnFamilyType}.\n     *\n     * @param <T> the generic type\n     * @param coscResultMap the cosc result map\n     * @param columnFamilyType the column family type\n     * @param row the row\n     * @return the map\n     */\n    public static <T> Map<ByteBuffer, List<T>> transformThriftResult(\n            Map<ByteBuffer, List<ColumnOrSuperColumn>> coscResultMap, ColumnFamilyType columnFamilyType, ThriftRow row)\n    {\n\n        Map<ByteBuffer, List<T>> output = new HashMap<ByteBuffer, List<T>>();\n\n        for (ByteBuffer key : coscResultMap.keySet())\n        {\n            output.put(key, (List<T>) transformThriftResult(coscResultMap.get(key), columnFamilyType, row));\n        }\n\n        return output;\n    }\n\n    /**\n     * Transform thrift result.\n     *\n     * @param <T> the generic type\n     * @param columnFamilyType the column family type\n     * @param keySlices the key slices\n     * @param row the row\n     * @return the map\n     */\n    public static <T> Map<ByteBuffer, List<T>> transformThriftResult(ColumnFamilyType columnFamilyType,\n            List<KeySlice> keySlices, ThriftRow row)\n    {\n\n        Map<ByteBuffer, List<T>> output = new HashMap<ByteBuffer, List<T>>();\n\n        for (KeySlice keySlice : keySlices)\n        {\n            output.put(ByteBuffer.wrap(keySlice.getKey()),\n                    (List<T>) transformThriftResult(keySlice.getColumns(), columnFamilyType, row));\n        }\n\n        return output;\n    }\n\n    /**\n     * Transforms data retrieved as result via thrift to a List whose content\n     * type is determined by {@link ColumnFamilyType}.\n     *\n     * @param <T> the generic type\n     * @param coscResultMap the cosc result map\n     * @param columnFamilyType the column family type\n     * @param row the row\n     * @return the list\n     */\n    public <T> List<T> transformThriftResultAndAddToList(Map<ByteBuffer, List<ColumnOrSuperColumn>> coscResultMap,\n            ColumnFamilyType columnFamilyType, ThriftRow row)\n    {\n\n        List<ColumnOrSuperColumn> coscList = new ArrayList<ColumnOrSuperColumn>();\n\n        for (List<ColumnOrSuperColumn> list : coscResultMap.values())\n        {\n            coscList.addAll(list);\n        }\n\n        return transformThriftResult(coscList, columnFamilyType, row);\n    }\n\n    /**\n     * Translates into thrift row.\n     *\n     * @param coscResultMap the cosc result map\n     * @param isCounterType the is counter type\n     * @param columnFamilyType the column family type\n     * @param row the row\n     * @return the thrift row\n     */\n    public ThriftRow translateToThriftRow(Map<ByteBuffer, List<ColumnOrSuperColumn>> coscResultMap,\n            boolean isCounterType, Type columnFamilyType, ThriftRow row)\n    {\n        ColumnFamilyType columnType = ColumnFamilyType.COLUMN;\n\n        if (isCounterType)\n        {\n            if (columnFamilyType.equals(Type.SUPER_COLUMN_FAMILY))\n            {\n                columnType = ColumnFamilyType.COUNTER_SUPER_COLUMN;\n            }\n            else\n            {\n                columnType = ColumnFamilyType.COUNTER_COLUMN;\n            }\n        }\n        else if (columnFamilyType.equals(Type.SUPER_COLUMN_FAMILY))\n        {\n            columnType = ColumnFamilyType.SUPER_COLUMN;\n        }\n        transformThriftResultAndAddToList(coscResultMap, columnType, row);\n        return row;\n    }\n\n    /**\n     * Fetches Row keys from a {@link List} of {@link KeySlice}.\n     *\n     * @param keySlices the key slices\n     * @param metadata the metadata\n     * @return the row keys\n     */\n    public static List<Object> getRowKeys(List<KeySlice> keySlices, EntityMetadata metadata)\n    {\n        PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor((Field) metadata.getIdAttribute()\n                .getJavaMember());\n        List<Object> rowKeys = new ArrayList<Object>();\n        for (KeySlice keySlice : keySlices)\n        {\n            byte[] key = keySlice.getKey();\n            Object rowKey = accessor.fromBytes(metadata.getIdAttribute().getJavaType(), key);\n            rowKeys.add(rowKey);\n        }\n        return rowKeys;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/ThriftIdGenerator.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift;\n\nimport com.impetus.client.cassandra.CassandraIdGenerator;\n\n/**\n * The Class ThriftIdGenerator.\n * \n * @author: karthikp.manchala\n */\npublic class ThriftIdGenerator extends CassandraIdGenerator\n{\n    // methods available from super class\n    // override if necessary\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/ThriftInvertedIndexHandler.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.thrift;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.ColumnOrSuperColumn;\nimport org.apache.cassandra.thrift.ColumnParent;\nimport org.apache.cassandra.thrift.ColumnPath;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.IndexClause;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.Mutation;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SlicePredicate;\nimport org.apache.cassandra.thrift.SliceRange;\nimport org.apache.cassandra.thrift.SuperColumn;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.datahandler.CassandraDataHandler;\nimport com.impetus.client.cassandra.index.CassandraIndexHelper;\nimport com.impetus.client.cassandra.index.InvertedIndexHandler;\nimport com.impetus.client.cassandra.index.InvertedIndexHandlerBase;\nimport com.impetus.client.cassandra.thrift.ThriftClientFactory.Connection;\nimport com.impetus.client.cassandra.thrift.ThriftDataResultHelper.ColumnFamilyType;\nimport com.impetus.kundera.db.SearchResult;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.index.IndexingException;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.TimestampGenerator;\n\n\n/**\n * Thrift implementation of {@link InvertedIndexHandler}.\n *\n * @author amresh.singh\n */\npublic class ThriftInvertedIndexHandler extends InvertedIndexHandlerBase implements InvertedIndexHandler\n{\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(ThriftInvertedIndexHandler.class);\n\n    /** The thrift client. */\n    private final ThriftClient thriftClient;\n\n    /**\n     * Instantiates a new thrift inverted index handler.\n     *\n     * @param thriftClient the thrift client\n     * @param useSecondryIndex the use secondry index\n     * @param generator the generator\n     */\n    public ThriftInvertedIndexHandler(final ThriftClient thriftClient, final boolean useSecondryIndex, final TimestampGenerator generator)\n    {\n        super(generator);\n        this.thriftClient = thriftClient;\n        this.useSecondryIndex = useSecondryIndex;\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.client.cassandra.index.InvertedIndexHandler#write(com.impetus.kundera.graph.Node, com.impetus.kundera.metadata.model.EntityMetadata, java.lang.String, org.apache.cassandra.thrift.ConsistencyLevel, com.impetus.client.cassandra.datahandler.CassandraDataHandler)\n     */\n    @Override\n    public void write(Node node, EntityMetadata entityMetadata, String persistenceUnit,\n            ConsistencyLevel consistencyLevel, CassandraDataHandler cdHandler)\n    {\n        // Write to Inverted Index table if applicable\n        boolean invertedIndexingApplicable = CassandraIndexHelper.isInvertedIndexingApplicable(entityMetadata, useSecondryIndex);\n\n        if (invertedIndexingApplicable)\n        {\n            String indexColumnFamily = CassandraIndexHelper.getInvertedIndexTableName(entityMetadata.getTableName());\n\n            ThriftDataHandler thriftDataHandler = (ThriftDataHandler) cdHandler;\n\n            List<ThriftRow> indexThriftyRows = thriftDataHandler.toIndexThriftRow(node.getData(), entityMetadata,\n                    indexColumnFamily);\n            Connection conn = thriftClient.getConnection();\n            try\n            {\n                for (ThriftRow thriftRow : indexThriftyRows)\n                {\n                    byte[] rowKey = PropertyAccessorHelper.toBytes(thriftRow.getId(), thriftRow.getId().getClass());\n\n                    // Create Insertion List\n                    List<Mutation> insertion_list = new ArrayList<Mutation>();\n\n                    List<Column> thriftColumns = thriftRow.getColumns();\n                    List<SuperColumn> thriftSuperColumns = thriftRow.getSuperColumns();\n                    if (thriftColumns != null && !thriftColumns.isEmpty())\n                    {\n                        for (Column column : thriftColumns)\n                        {\n                            Mutation mut = new Mutation();\n                            mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setColumn(column));\n                            insertion_list.add(mut);\n                        }\n                    }\n\n                    if (thriftSuperColumns != null && !thriftSuperColumns.isEmpty())\n                    {\n                        for (SuperColumn superColumn : thriftSuperColumns)\n                        {\n                            Mutation mut = new Mutation();\n                            mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setSuper_column(superColumn));\n                            insertion_list.add(mut);\n                        }\n                    }\n\n                    // Create Mutation Map\n                    Map<String, List<Mutation>> columnFamilyValues = new HashMap<String, List<Mutation>>();\n                    columnFamilyValues.put(indexColumnFamily, insertion_list);\n                    Map<ByteBuffer, Map<String, List<Mutation>>> mulationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();\n                    mulationMap.put(ByteBuffer.wrap(rowKey), columnFamilyValues);\n\n                    // Write Mutation map to database\n                    conn.getClient().batch_mutate(mulationMap, consistencyLevel);\n                }\n            }\n            catch (IllegalStateException e)\n            {\n                log.error(\"Unable to insert records into inverted index, Caused by: .\", e);\n                throw new IndexingException(e);\n            }\n            catch (InvalidRequestException e)\n            {\n                log.error(\"Unable to insert records into inverted index, Caused by: .\", e);\n                throw new IndexingException(e);\n            }\n            catch (TException e)\n            {\n                log.error(\"Unable to insert records into inverted index, Caused by: .\", e);\n                throw new IndexingException(e);\n            }\n            finally\n            {\n                thriftClient.releaseConnection(conn);\n            }\n        }\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.client.cassandra.index.InvertedIndexHandlerBase#search(com.impetus.kundera.metadata.model.EntityMetadata, java.lang.String, org.apache.cassandra.thrift.ConsistencyLevel, java.util.Map)\n     */\n    @Override\n    public List<SearchResult> search(EntityMetadata m, String persistenceUnit, ConsistencyLevel consistencyLevel,\n            Map<Boolean, List<IndexClause>> indexClauseMap)\n    {\n\n        return super.search(m, persistenceUnit, consistencyLevel, indexClauseMap);\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.client.cassandra.index.InvertedIndexHandlerBase#searchSuperColumnsInRange(java.lang.String, org.apache.cassandra.thrift.ConsistencyLevel, java.lang.String, java.lang.String, byte[], java.util.List, byte[], byte[])\n     */\n    @Override\n    protected void searchSuperColumnsInRange(String columnFamilyName, ConsistencyLevel consistencyLevel,\n            String persistenceUnit, String rowKey, byte[] searchSuperColumnName, List<SuperColumn> thriftSuperColumns,\n            byte[] start, byte[] finish)\n    {\n        SlicePredicate colPredicate = new SlicePredicate();\n        SliceRange sliceRange = new SliceRange();\n        sliceRange.setStart(start);\n        sliceRange.setFinish(finish);\n        colPredicate.setSlice_range(sliceRange);\n        Connection conn = thriftClient.getConnection();\n\n        List<ColumnOrSuperColumn> coscList = null;\n        try\n        {\n            coscList = conn.getClient().get_slice(ByteBuffer.wrap(rowKey.getBytes()),\n                    new ColumnParent(columnFamilyName), colPredicate, consistencyLevel);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(\"Unable to search from inverted index, Caused by: .\", e);\n            throw new IndexingException(e);\n        }\n        catch (UnavailableException e)\n        {\n            log.error(\"Unable to search from inverted index, Caused by: .\", e);\n            throw new IndexingException(e);\n        }\n        catch (TimedOutException e)\n        {\n            log.error(\"Unable to search from inverted index, Caused by: .\", e);\n            throw new IndexingException(e);\n        }\n        catch (TException e)\n        {\n            log.error(\"Unable to search from inverted index, Caused by: \", e);\n            throw new IndexingException(e);\n        }\n        finally\n        {\n            thriftClient.releaseConnection(conn);\n        }\n        List<SuperColumn> allThriftSuperColumns = ThriftDataResultHelper.transformThriftResult(coscList,\n                ColumnFamilyType.SUPER_COLUMN, null);\n\n        for (SuperColumn superColumn : allThriftSuperColumns)\n        {\n            if (superColumn == null)\n                continue;\n\n            if (superColumn.getName() == searchSuperColumnName)\n            {\n                thriftSuperColumns.add(superColumn);\n            }\n        }\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.client.cassandra.index.InvertedIndexHandlerBase#getSuperColumnForRow(org.apache.cassandra.thrift.ConsistencyLevel, java.lang.String, java.lang.String, byte[], java.lang.String)\n     */\n    @Override\n    protected SuperColumn getSuperColumnForRow(ConsistencyLevel consistencyLevel, String columnFamilyName,\n            String rowKey, byte[] superColumnName, String persistenceUnit)\n    {\n        ColumnPath cp = new ColumnPath(columnFamilyName);\n        cp.setSuper_column(superColumnName);\n        ColumnOrSuperColumn cosc = null;\n        Connection conn = thriftClient.getConnection();\n\n        try\n        {\n            cosc = conn.getClient().get(ByteBuffer.wrap(rowKey.getBytes()), cp, consistencyLevel);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(\"Unable to search from inverted index, Caused by: .\", e);\n            throw new IndexingException(e);\n        }\n        catch (NotFoundException e)\n        {\n            log.warn(\"Not found any record in inverted index table.\");\n        }\n        catch (UnavailableException e)\n        {\n            log.error(\"Unable to search from inverted index, Caused by: .\", e);\n            throw new IndexingException(e);\n        }\n        catch (TimedOutException e)\n        {\n            log.error(\"Unable to search from inverted index, Caused by: .\", e);\n            throw new IndexingException(e);\n        }\n        catch (TException e)\n        {\n            log.error(\"Unable to search from inverted index, Caused by: .\", e);\n            throw new IndexingException(e);\n        }\n        finally\n        {\n            thriftClient.releaseConnection(conn);\n        }\n        SuperColumn thriftSuperColumn = ThriftDataResultHelper.transformThriftResult(cosc,\n                ColumnFamilyType.SUPER_COLUMN, null);\n        return thriftSuperColumn;\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.client.cassandra.index.InvertedIndexHandlerBase#delete(java.lang.Object, com.impetus.kundera.metadata.model.EntityMetadata, org.apache.cassandra.thrift.ConsistencyLevel, com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata)\n     */\n    @Override\n    public void delete(Object entity, EntityMetadata metadata, ConsistencyLevel consistencyLevel, final KunderaMetadata kunderaMetadata)\n    {\n\n        super.delete(entity, metadata, consistencyLevel, kunderaMetadata);\n\n    }\n\n    /* (non-Javadoc)\n     * @see com.impetus.client.cassandra.index.InvertedIndexHandlerBase#deleteColumn(java.lang.String, java.lang.String, byte[], java.lang.String, org.apache.cassandra.thrift.ConsistencyLevel, byte[])\n     */\n    @Override\n    protected void deleteColumn(String indexColumnFamily, String rowKey, byte[] superColumnName,\n            String persistenceUnit, ConsistencyLevel consistencyLevel, byte[] columnName)\n    {\n        ColumnPath cp = new ColumnPath(indexColumnFamily);\n        cp.setSuper_column(superColumnName);\n        Connection conn = thriftClient.getConnection();\n        try\n        {\n            ColumnOrSuperColumn cosc;\n            try\n            {\n                cosc = conn.getClient().get(ByteBuffer.wrap(rowKey.getBytes()), cp, consistencyLevel);\n            }\n            catch (NotFoundException e)\n            {\n                return;\n            }\n            SuperColumn thriftSuperColumn = ThriftDataResultHelper.transformThriftResult(cosc,\n                    ColumnFamilyType.SUPER_COLUMN, null);\n\n            if (thriftSuperColumn != null && thriftSuperColumn.getColumns() != null\n                    && thriftSuperColumn.getColumns().size() > 1)\n            {\n                cp.setColumn(columnName);\n            }\n            conn.getClient().remove(ByteBuffer.wrap(rowKey.getBytes()), cp, generator.getTimestamp(),\n                    consistencyLevel);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(\"Unable to delete data from inverted index, Caused by: .\", e);\n            throw new IndexingException(e);\n        }\n        catch (UnavailableException e)\n        {\n            log.error(\"Unable to delete data from inverted index, Caused by: .\", e);\n            throw new IndexingException(e);\n        }\n        catch (TimedOutException e)\n        {\n            log.error(\"Unable to delete data from inverted index, Caused by: .\", e);\n            throw new IndexingException(e);\n        }\n        catch (TException e)\n        {\n            log.error(\"Unable to delete data from inverted index, Caused by: .\", e);\n            throw new IndexingException(e);\n        }\n        finally\n        {\n            thriftClient.releaseConnection(conn);\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/ThriftRow.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.thrift;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.CounterColumn;\nimport org.apache.cassandra.thrift.CounterSuperColumn;\nimport org.apache.cassandra.thrift.SuperColumn;\n\n// TODO: Auto-generated Javadoc\n/**\n * Utility class that represents a row in Cassandra DB.\n * \n * @author amresh.singh\n */\npublic class ThriftRow\n{\n    /** Id of the row. */\n    private Object id;\n\n    /** name of the family. */\n    private String columnFamilyName;\n\n    /** list of thrift columns from the row. */\n    private List<Column> columns;\n\n    /** list of thrift super columns columns from the row. */\n    private List<SuperColumn> superColumns;\n\n    /** list of thrift counter columns from the row. */\n    private List<CounterColumn> counterColumns;\n\n    /** list of thrift counter super columns columns from the row. */\n    private List<CounterSuperColumn> counterSuperColumns;\n\n    /**\n     * default constructor.\n     */\n\n    public ThriftRow()\n    {\n        columns = new ArrayList<Column>();\n        superColumns = new ArrayList<SuperColumn>();\n        counterColumns = new ArrayList<CounterColumn>();\n        counterSuperColumns = new ArrayList<CounterSuperColumn>();\n    }\n\n    /**\n     * The Constructor.\n     *\n     * @param id            the id\n     * @param columnFamilyName            the column family name\n     * @param columns            the columns\n     * @param superColumns            the super columns\n     * @param counterColumns the counter columns\n     * @param counterSuperColumns the counter super columns\n     */\n    public ThriftRow(Object id, String columnFamilyName, List<Column> columns, List<SuperColumn> superColumns,\n            List<CounterColumn> counterColumns, List<CounterSuperColumn> counterSuperColumns)\n    {\n        this.id = id;\n        this.columnFamilyName = columnFamilyName;\n        if (columns != null)\n        {\n            this.columns = columns;\n        }\n\n        if (superColumns != null)\n        {\n            this.superColumns = superColumns;\n        }\n        if (counterColumns != null)\n        {\n            this.counterColumns = counterColumns;\n        }\n\n        if (counterSuperColumns != null)\n        {\n            this.counterSuperColumns = counterSuperColumns;\n        }\n    }\n\n    /**\n     * Adds the column.\n     * \n     * @param column\n     *            the column\n     */\n    public void addColumn(Column column)\n    {\n        columns.add(column);\n    }\n\n    /**\n     * Gets the id.\n     *\n     * @return the id\n     */\n    public Object getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     *\n     * @param id            the id to set\n     */\n    public void setId(Object id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the column family name.\n     *\n     * @return the columnFamilyName\n     */\n    public String getColumnFamilyName()\n    {\n        return columnFamilyName;\n    }\n\n    /**\n     * Sets the column family name.\n     *\n     * @param columnFamilyName            the columnFamilyName to set\n     */\n    public void setColumnFamilyName(String columnFamilyName)\n    {\n        this.columnFamilyName = columnFamilyName;\n    }\n\n    /**\n     * Gets the columns.\n     *\n     * @return the columns\n     */\n    public List<Column> getColumns()\n    {\n        return columns;\n    }\n\n    /**\n     * Sets the columns.\n     *\n     * @param columns            the columns to set\n     */\n    public void setColumns(List<Column> columns)\n    {\n        this.columns = columns;\n    }\n\n    /**\n     * Gets the super columns.\n     *\n     * @return the superColumns\n     */\n    public List<SuperColumn> getSuperColumns()\n    {\n        return superColumns;\n    }\n\n    /**\n     * Sets the super columns.\n     *\n     * @param superColumns            the superColumns to set\n     */\n    public void setSuperColumns(List<SuperColumn> superColumns)\n    {\n        this.superColumns = superColumns;\n    }\n\n    /**\n     * Adds the super column.\n     * \n     * @param superColumn\n     *            the super column\n     */\n    public void addSuperColumn(SuperColumn superColumn)\n    {\n        this.superColumns.add(superColumn);\n    }\n\n    /**\n     * Gets the counter columns.\n     *\n     * @return the counterColumns\n     */\n    public List<CounterColumn> getCounterColumns()\n    {\n        return counterColumns;\n    }\n\n    /**\n     * Sets the counter columns.\n     *\n     * @param counterColumns            the counterColumns to set\n     */\n    public void setCounterColumns(List<CounterColumn> counterColumns)\n    {\n        this.counterColumns = counterColumns;\n    }\n\n    /**\n     * Adds the counter column.\n     *\n     * @param column the column\n     */\n    public void addCounterColumn(CounterColumn column)\n    {\n        counterColumns.add(column);\n    }\n\n    /**\n     * Gets the counter super columns.\n     *\n     * @return the counterSuperColumns\n     */\n    public List<CounterSuperColumn> getCounterSuperColumns()\n    {\n        return counterSuperColumns;\n    }\n\n    /**\n     * Sets the counter super columns.\n     *\n     * @param counterSuperColumns            the counterSuperColumns to set\n     */\n    public void setCounterSuperColumns(List<CounterSuperColumn> counterSuperColumns)\n    {\n        this.counterSuperColumns = counterSuperColumns;\n    }\n\n    /**\n     * Adds the counter super column.\n     *\n     * @param superColumn the super column\n     */\n    public void addCounterSuperColumn(CounterSuperColumn superColumn)\n    {\n        this.counterSuperColumns.add(superColumn);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/TranslationException.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * Runtime exception class for CQL translation.\n * \n * @author vivek.mishra\n * \n */\npublic class TranslationException extends KunderaException\n{\n    \n    /** The Constant serialVersionUID. */\n    private static final long serialVersionUID = 2557677206649004876L;\n\n    /**\n     * Instantiates a new translation exception.\n     */\n    public TranslationException()\n    {\n    }\n\n    /**\n     * Instantiates a new translation exception.\n     *\n     * @param arg0 the arg0\n     */\n    public TranslationException(String arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * Instantiates a new translation exception.\n     *\n     * @param arg0 the arg0\n     */\n    public TranslationException(Throwable arg0)\n    {\n        super(arg0);\n\n    }\n\n    /**\n     * Instantiates a new translation exception.\n     *\n     * @param arg0 the arg0\n     * @param arg1 the arg1\n     */\n    public TranslationException(String arg0, Throwable arg1)\n    {\n        super(arg0, arg1);\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/config/CassandraDefaultSuperUser.java",
    "content": "package com.impetus.client.cassandra.config;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.client.twitter.entities.PersonalDetailCassandra;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"CassandraDefaultSuperUser\", schema = \"KunderaCassandraXmlTest@CassandraXmlPropertyTest\")\npublic class CassandraDefaultSuperUser\n{\n    @Id\n    private String name;\n\n    @Column\n    private int age;\n\n    @Column\n    private String address;\n\n    @Embedded\n    private PersonalDetailCassandra personalDetailCassandra;\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    public PersonalDetailCassandra getPersonalDetailCassandra()\n    {\n        return personalDetailCassandra;\n    }\n\n    public void setPersonalDetailCassandra(PersonalDetailCassandra personalDetailCassandra)\n    {\n        this.personalDetailCassandra = personalDetailCassandra;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/config/CassandraDefaultUser.java",
    "content": "/**\n * \n */\npackage com.impetus.client.cassandra.config;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"CassandraDefaultUser\", schema = \"KunderaCassandraXmlTest@CassandraXmlPropertyTest\")\npublic class CassandraDefaultUser\n{\n\n    @Id\n    private String name;\n\n    @Column\n    private int age;\n\n    @Column\n    private String address;\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/config/CassandraPropertySetterTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.config;\n\nimport java.lang.reflect.Field;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.service.CassandraHostConfiguration;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.service.HostConfiguration;\n\n/**\n * Junit to test Kundera-Cassandra's implementation of {@link PropertySetter}\n * \n * @author Chhavi Gangwal\n * \n */\npublic class CassandraPropertySetterTest\n{\n\n    /**\n     * \n     */\n    private static final String _PU = \"CassandraXmlPropertyTest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Map<String, Object> puProperties = new HashMap<String, Object>();\n\n    private Logger logger = LoggerFactory.getLogger(CassandraPropertySetterTest.class);\n\n    /**\n     * creates client connection and keyspace\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n\n        puProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n        puProperties.put(\"kundera.keyspace\", \"KunderaKeyspace\");\n        puProperties.put(\"kundera.client.lookup.class\", \"com.impetus.client.cassandra.thrift.ThriftClientFactory\");\n        puProperties.put(\"kundera.nodes\", \"localhost\");\n        puProperties.put(\"kundera.port\", \"9160\");\n        puProperties.put(\"kundera.client.property\", \"kunderaTest.xml\");\n\n        emf = Persistence.createEntityManagerFactory(_PU, puProperties);\n\n    }\n\n    /**\n     * Drops keyspace and closes connection\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        puProperties = null;\n        CassandraCli.dropKeySpace(\"KunderaKeyspace\");\n    }\n\n    /**\n     * Sets property of cassandra client in form of string\n     */\n    @Test\n    public void testStringPropertyValues()\n    {\n        try\n        {\n            Map<String, Object> puPropertiesString = new HashMap<String, Object>();\n            Map<String, Object> ttv = new HashMap<String, Object>();\n\n            ttv.put(\"\", \"\");\n            puPropertiesString.put(CassandraConstants.CQL_VERSION, \"\" + CassandraConstants.CQL_VERSION_2_0);\n            puPropertiesString.put(\"consistency.level\", \"\" + (ConsistencyLevel.QUORUM));\n            puPropertiesString.put(\"ttl.per.request\", \"\" + true);\n            puPropertiesString.put(\"ttl.per.session\", \"\" + false);\n            puPropertiesString.put(\"ttl.values\", ttv);\n\n            em = emf.createEntityManager(puPropertiesString);\n\n            Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n            Client client = clients.get(_PU);\n\n            Field f;\n\n            f = ((CassandraClientBase) client).getClass().getSuperclass().getDeclaredField(\"consistencyLevel\"); // NoSuchFieldException\n            f.setAccessible(true);\n            Assert.assertEquals(f.get((CassandraClientBase) client), ConsistencyLevel.QUORUM);\n\n            f = ((CassandraClientBase) client).getClass().getSuperclass().getDeclaredField(\"cqlVersion\"); // NoSuchFieldException\n            f.setAccessible(true);\n            Assert.assertEquals(f.get((CassandraClientBase) client), CassandraConstants.CQL_VERSION_2_0);\n\n            Assert.assertTrue(((CassandraClientBase) client).isTtlPerRequest());\n            Assert.assertFalse(((CassandraClientBase) client).isTtlPerSession());\n            Assert.assertEquals(((CassandraClientBase) client).getTtlValues().size(), ttv.size());\n\n        }\n        catch (NoSuchFieldException nfe)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\", nfe.getMessage());\n\n        }\n        catch (IllegalArgumentException iae)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\", iae.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\", e.getMessage());\n        }\n\n    }\n\n    /**\n     * Sets property of cassandra client in form of object map\n     */\n    @Test\n    public void testObjectPropertyValues()\n    {\n        try\n        {\n            Map<String, Object> puPropertiesObj = new HashMap<String, Object>();\n            Map<String, Object> ttv = new HashMap<String, Object>();\n\n            ttv.put(\"test\", \"1\");\n            puPropertiesObj.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_2_0);\n            puPropertiesObj.put(\"consistency.level\", ConsistencyLevel.QUORUM);\n            puPropertiesObj.put(\"ttl.per.request\", true);\n            puPropertiesObj.put(\"ttl.per.session\", false);\n            puPropertiesObj.put(\"ttl.values\", ttv);\n\n            em = emf.createEntityManager(puPropertiesObj);\n\n            Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n            Client client = clients.get(_PU);\n\n            Field f;\n\n            f = ((CassandraClientBase) client).getClass().getSuperclass().getDeclaredField(\"consistencyLevel\"); // NoSuchFieldException\n            f.setAccessible(true);\n            Assert.assertEquals(f.get((CassandraClientBase) client), ConsistencyLevel.QUORUM);\n\n            f = ((CassandraClientBase) client).getClass().getSuperclass().getDeclaredField(\"cqlVersion\"); // NoSuchFieldException\n            f.setAccessible(true);\n            Assert.assertEquals(f.get((CassandraClientBase) client), CassandraConstants.CQL_VERSION_2_0);\n\n            Assert.assertTrue(((CassandraClientBase) client).isTtlPerRequest());\n            Assert.assertFalse(((CassandraClientBase) client).isTtlPerSession());\n            Assert.assertEquals(((CassandraClientBase) client).getTtlValues().size(), ttv.size());\n\n        }\n        catch (NoSuchFieldException nfe)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\", nfe.getMessage());\n\n        }\n        catch (IllegalArgumentException iae)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\", iae.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\", e.getMessage());\n        }\n\n    }\n\n    /*\n     * tests emf properties set partially from external map and persistence.xml\n     */\n    @Test\n    public void testPartialOverridingOfPUProperties()\n    {\n\n        Map<String, Object> puMap = new HashMap<String, Object>();\n\n        puMap.put(\"kundera.keyspace\", \"KunderaKeyspace\");\n        puMap.put(\"kundera.port\", \"9160\");\n\n        puMap.put(\"kundera.client.lookup.class\", \"com.impetus.client.cassandra.thrift.ThriftClientFactory\");\n        puMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n\n        emf = Persistence.createEntityManagerFactory(\"partialPropertyOverridePU\", puMap);\n        em = emf.createEntityManager();\n\n        HostConfiguration hostConfig = new CassandraHostConfiguration(puMap, CassandraPropertyReader.csmd,\n                \"partialPropertyOverridePU\", ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        Assert.assertEquals(hostConfig.getHosts().get(0).getHost(), \"localhost\");\n        Assert.assertEquals(hostConfig.getHosts().get(0).getPort(), 9160);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/config/CassandraSchemaGenerationUsingXmlTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.cassandra.config;\n\nimport java.nio.ByteBuffer;\nimport java.nio.charset.CharacterCodingException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.db.marshal.BytesType;\nimport org.apache.cassandra.db.marshal.UTF8Type;\nimport org.apache.cassandra.locator.SimpleStrategy;\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.CqlResult;\nimport org.apache.cassandra.thrift.CqlRow;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class CassandraSchemaGenerationUsingXmlTest\n{\n    private EntityManagerFactory emf;\n\n    private String keyspaceName = \"KunderaCassandraXmlTest\";\n\n    private Logger logger = LoggerFactory.getLogger(CassandraSchemaGenerationUsingXmlTest.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(keyspaceName);\n        Map propertyMap = new HashMap();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(\"CassandraXmlPropertyTest\", propertyMap);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        CassandraCli.dropKeySpace(keyspaceName);\n    }\n\n    @Test\n    public void test()\n    {\n        try\n        {\n              CqlResult cqlResult = CassandraCli.client.execute_cql3_query(ByteBuffer\n                                    .wrap(\"Select * from system_schema.keyspaces where keyspace_name = 'KunderaCassandraXmlTest'\"\n                                            .getBytes()), Compression.NONE, ConsistencyLevel.ONE);\n\n            List<CqlRow> cqlRows = cqlResult.getRows();\n            \n            StringBuilder builder = new  StringBuilder(\"{\");\n            builder.append(\"\\\"replication_factor\\\"\");\n            builder.append(\":\");\n            builder.append(\"\\\"1\\\"\");\n            builder.append(\"}\");\n            \n            for(CqlRow cqlRow : cqlRows)\n            {\n                Assert.assertEquals(\"keyspace_name\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(0).getName())));\n                Assert.assertEquals(keyspaceName, ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(0).getValue())));\n                Assert.assertEquals(\"durable_writes\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(1).getName())));\n                Assert.assertEquals(false, Boolean.getBoolean(ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(1).getValue()))));\n                Assert.assertEquals(\"replication\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(2).getName())));\n            }\n            \n            cqlResult = CassandraCli.client.execute_cql3_query(ByteBuffer\n                                    .wrap(\"Select * from system_schema.tables where keyspace_name = 'KunderaCassandraXmlTest'\"\n                                            .getBytes()), Compression.NONE, ConsistencyLevel.ONE);\n\n            List<CqlRow> columnFamilies = cqlResult.getRows();\n\n            Assert.assertNotNull(columnFamilies);\n           \n//            Assert.assertEquals(13, columnFamilies.size());\n\n            for (CqlRow cqlRow : cqlResult.getRows())\n            {\n                Assert.assertNotNull(cqlRow);\n                if (\"CASSANDRAUSERXYZ\".equals(ByteBuffer.wrap(cqlRow.getColumns().get(1).getValue())))\n                {                    \n                    Assert.assertEquals(\"comment\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(5).getName())));\n                    Assert.assertTrue(ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(5).getValue())).isEmpty());\n                    Assert.assertEquals(\"comparator\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(8).getName())));\n                    Assert.assertEquals(UTF8Type.class.getName(), ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(8).getValue())));\n                    Assert.assertEquals(\"default_validator\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(10).getName())));\n                    Assert.assertEquals(BytesType.class.getName(), Boolean.getBoolean(ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(10).getValue()))));\n                    Assert.assertEquals(\"max_compaction_threshold\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(17).getName())));\n                    Assert.assertEquals(16, ByteBufferUtil.toInt(ByteBuffer.wrap(cqlRow.getColumns().get(17).getValue())));\n                    Assert.assertEquals(\"min_compaction_threshold\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(18).getName())));\n                    Assert.assertEquals(64, ByteBufferUtil.toInt(ByteBuffer.wrap(cqlRow.getColumns().get(18).getValue())));\n                    Assert.assertEquals(\"replicate_on_write\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(21).getName())));\n                    Assert.assertEquals(\"true\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(21).getValue())));\n                    Assert.assertEquals(\"subcomparator\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(22).getName())));\n                    Assert.assertNull(ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(22).getValue())));\n                    Assert.assertEquals(\"type\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(23).getName())));\n                    Assert.assertEquals(\"Standard\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(23).getValue())));\n                }\n                else if (\"CassandraDefaultUser\".equals(ByteBuffer.wrap(cqlRow.getColumns().get(1).getValue())))\n                {\n                    Assert.assertEquals(\"comment\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(5).getName())));\n                    Assert.assertTrue(ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(5).getValue())).isEmpty());\n                    Assert.assertEquals(\"comparator\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(8).getName())));\n                    Assert.assertEquals(UTF8Type.class.getName(), ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(8).getValue())));\n                    Assert.assertEquals(\"default_validator\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(10).getName())));\n                    Assert.assertEquals(BytesType.class.getName(), Boolean.getBoolean(ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(10).getValue()))));\n                    Assert.assertEquals(\"max_compaction_threshold\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(17).getName())));\n                    Assert.assertEquals(4, ByteBufferUtil.toInt(ByteBuffer.wrap(cqlRow.getColumns().get(17).getValue())));\n                    Assert.assertEquals(\"min_compaction_threshold\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(18).getName())));\n                    Assert.assertEquals(32, ByteBufferUtil.toInt(ByteBuffer.wrap(cqlRow.getColumns().get(18).getValue())));\n                    Assert.assertEquals(\"replicate_on_write\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(21).getName())));\n                    Assert.assertEquals(\"true\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(21).getValue())));\n                    Assert.assertEquals(\"subcomparator\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(22).getName())));\n                    Assert.assertNull(ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(22).getValue())));\n                    Assert.assertEquals(\"type\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(23).getName())));\n                    Assert.assertEquals(\"Standard\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(23).getValue())));                  \n                }\n                else if (\"CassandraDefaultSuperUser\".equals(ByteBuffer.wrap(cqlRow.getColumns().get(1).getValue())))\n                {\n                    Assert.assertEquals(\"comment\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(5).getName())));\n                    Assert.assertTrue(ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(5).getValue())).isEmpty());\n                    Assert.assertEquals(\"comparator\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(8).getName())));\n                    Assert.assertEquals(UTF8Type.class.getName(), ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(8).getValue())));\n                    Assert.assertEquals(\"default_validator\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(10).getName())));\n                    Assert.assertEquals(BytesType.class.getName(), Boolean.getBoolean(ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(10).getValue()))));\n                    Assert.assertEquals(\"max_compaction_threshold\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(17).getName())));\n                    Assert.assertEquals(16, ByteBufferUtil.toInt(ByteBuffer.wrap(cqlRow.getColumns().get(17).getValue())));\n                    Assert.assertEquals(\"min_compaction_threshold\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(18).getName())));\n                    Assert.assertEquals(64, ByteBufferUtil.toInt(ByteBuffer.wrap(cqlRow.getColumns().get(18).getValue())));\n                    Assert.assertEquals(\"replicate_on_write\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(21).getName())));\n                    Assert.assertEquals(\"true\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(21).getValue())));\n                    Assert.assertEquals(\"subcomparator\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(22).getName())));\n                    Assert.assertNull(ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(22).getValue())));\n                    Assert.assertEquals(\"type\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(23).getName())));\n                    Assert.assertEquals(\"Super\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(23).getValue())));\n                }\n                else if (\"CASSANDRASUPERUSER\".equals(ByteBuffer.wrap(cqlRow.getColumns().get(1).getValue())))\n                {\n                    Assert.assertEquals(\"comment\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(5).getName())));\n                    Assert.assertTrue(ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(5).getValue())).isEmpty());\n                    Assert.assertEquals(\"comparator\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(8).getName())));\n                    Assert.assertEquals(UTF8Type.class.getName(), ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(8).getValue())));\n                    Assert.assertEquals(\"default_validator\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(10).getName())));\n                    Assert.assertEquals(BytesType.class.getName(), Boolean.getBoolean(ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(10).getValue()))));\n                    Assert.assertEquals(\"max_compaction_threshold\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(17).getName())));\n                    Assert.assertEquals(16, ByteBufferUtil.toInt(ByteBuffer.wrap(cqlRow.getColumns().get(17).getValue())));\n                    Assert.assertEquals(\"min_compaction_threshold\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(18).getName())));\n                    Assert.assertEquals(64, ByteBufferUtil.toInt(ByteBuffer.wrap(cqlRow.getColumns().get(18).getValue())));\n                    Assert.assertEquals(\"replicate_on_write\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(21).getName())));\n                    Assert.assertEquals(\"true\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(21).getValue())));\n                    Assert.assertEquals(\"subcomparator\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(22).getName())));\n                    Assert.assertNull(ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(22).getValue())));\n                    Assert.assertEquals(\"type\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(23).getName())));\n                    Assert.assertEquals(\"Super\", ByteBufferUtil.string(ByteBuffer.wrap(cqlRow.getColumns().get(23).getValue())));\n                }\n                else\n                {\n\n                }\n            }\n\n        }        \n        catch (InvalidRequestException ire)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\", ire.getMessage());\n        }\n        catch (TException te)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, caused by: .\", te.getMessage());\n        }\n        catch (CharacterCodingException e)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, caused by: .\", e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/config/CassandraSuperUser.java",
    "content": "package com.impetus.client.cassandra.config;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.client.twitter.entities.PersonalDetailCassandra;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"CASSANDRASUPERUSER\", schema = \"KunderaCassandraXmlTest@CassandraXmlPropertyTest\")\npublic class CassandraSuperUser\n{\n    @Id\n    private String name;\n\n    @Column\n    private int age;\n\n    @Column\n    private String address;\n\n    @Embedded\n    private PersonalDetailCassandra personalDetailCassandra;\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    public PersonalDetailCassandra getPersonalDetailCassandra()\n    {\n        return personalDetailCassandra;\n    }\n\n    public void setPersonalDetailCassandra(PersonalDetailCassandra personalDetailCassandra)\n    {\n        this.personalDetailCassandra = personalDetailCassandra;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/config/CassandraTimestampGenerator.java",
    "content": "package com.impetus.client.cassandra.config;\n\nimport com.impetus.kundera.utils.TimestampGenerator;\n\npublic class CassandraTimestampGenerator implements TimestampGenerator\n{\n\n    @Override\n    public long getTimestamp()\n    {\n        return 10 * System.currentTimeMillis();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/config/CassandraUser.java",
    "content": "/**\n * \n */\npackage com.impetus.client.cassandra.config;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"CASSANDRAUSERXYZ\", schema = \"KunderaCassandraXmlTest@CassandraXmlPropertyTest\")\npublic class CassandraUser\n{\n\n    @Id\n    private String name;\n\n    @Column\n    private int age;\n\n    @Column\n    private String address;\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/config/CassandraUserTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.cassandra.config;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class CassandraUserTest\n{\n\n    /**\n     * \n     */\n    private static final String _PU = \"CassandraXmlPropertyTest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Map<String, Object> puProperties = new HashMap<String, Object>();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        puProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n        puProperties.put(\"kundera.keyspace\", \"KunderaKeyspace\");\n        puProperties.put(\"kundera.client.lookup.class\", \"com.impetus.client.cassandra.thrift.ThriftClientFactory\");\n        puProperties.put(\"kundera.nodes\", \"localhost\");\n        puProperties.put(\"kundera.port\", \"9160\");\n        puProperties.put(\"kundera.client.property\", \"kunderaTest.xml\");\n        puProperties.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_2_0);\n        puProperties.put(Constants.DEFAULT_TIMESTAMP_GENERATOR, CassandraTimestampGenerator.class.getName());\n        emf = Persistence.createEntityManagerFactory(_PU, puProperties);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        puProperties = null;\n        CassandraCli.dropKeySpace(\"KunderaKeyspace\");\n    }\n\n    @Test\n    public void test()\n    {\n        CassandraUser u = new CassandraUser();\n        u.setName(\"kuldeep\");\n        u.setAge(24);\n        u.setAddress(\"gzb\");\n        em.persist(u);\n\n        em.clear();\n\n        CassandraUser user = em.find(CassandraUser.class, \"kuldeep\");\n        Assert.assertNotNull(user);\n        Assert.assertEquals(24, user.getAge());\n        Assert.assertEquals(\"gzb\", user.getAddress());\n\n        Query q = em.createQuery(\"Select u from CassandraUser u\");\n        List<CassandraUser> users = q.getResultList();\n        Assert.assertNotNull(users);\n        Assert.assertEquals(1, users.size());\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/query/CassQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.query;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.metamodel.Metamodel;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.crud.PersonCassandra;\nimport com.impetus.client.crud.compositeType.CassandraCompoundKey;\nimport com.impetus.client.crud.compositeType.CassandraPrimeUser;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityManagerImpl;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQueryParser;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic class CassQueryTest\n{\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(CassQueryTest.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.cassandra.query.CassQuery#onQueryOverCQL3(com.impetus.kundera.metadata.model.EntityMetadata, com.impetus.kundera.client.Client, com.impetus.kundera.metadata.model.MetamodelImpl, java.util.List)}\n     * .\n     * \n     * @throws InvocationTargetException\n     * @throws IllegalAccessException\n     * @throws IllegalArgumentException\n     */\n    @Test\n    public void testOnQueryOverCQL3ForSimpleEntity() throws IllegalArgumentException, IllegalAccessException,\n            InvocationTargetException\n    {\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        String pu = \"genericCassandraTest\";\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(pu);\n        EntityManager em = emf.createEntityManager();\n\n        // Simple Query.\n        String queryString = \"Select p from PersonCassandra p WHERE p.personId = 'kk'\";\n\n        String cqlQuery = parseAndCreateCqlQuery(getQueryObject(queryString, emf), emf, em, pu, PersonCassandra.class,\n                200);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"personId\\\" = 'kk' LIMIT 200\", cqlQuery);\n\n        // In Query.\n        queryString = \"Select p from PersonCassandra p WHERE p.personId in ('kk', 'sk','pk')\";\n\n        cqlQuery = parseAndCreateCqlQuery(getQueryObject(queryString, emf), emf, em, pu, PersonCassandra.class, 400);\n\n        Assert.assertNotNull(cqlQuery);\n\n//        \"SELECT * FROM \"PERSONCASSANDRA\" WHERE \"personId\" IN ('(''kk''', 'sk', '''pk') LIMIT 400\";\n        Assert.assertEquals(\"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"personId\\\" IN ('kk', 'sk', 'pk') LIMIT 400\", cqlQuery);\n\n        // In Query set Paramater.\n        queryString = \"Select p from PersonCassandra p WHERE p.personId in :nameList\";\n\n        List<String> nameList = new ArrayList<String>();\n        nameList.add(\"kk\");\n        nameList.add(\"dk\");\n        nameList.add(\"sk\");\n\n        KunderaQuery kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"nameList\", nameList);\n\n        cqlQuery = parseAndCreateCqlQuery(kunderaQuery, emf, em, pu, PersonCassandra.class, Integer.MAX_VALUE);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"personId\\\" IN ('kk', 'dk', 'sk' ) \", cqlQuery);\n\n        // In Query set Paramater with and clause.\n        queryString = \"Select p from PersonCassandra p WHERE p.personId in :nameList and p.age = 10\";\n\n        kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"nameList\", nameList);\n\n        cqlQuery = parseAndCreateCqlQuery(kunderaQuery, emf, em, pu, PersonCassandra.class, Integer.MAX_VALUE);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\n                \"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"personId\\\" IN ('kk', 'dk', 'sk' )  AND \\\"AGE\\\" = 10  ALLOW FILTERING\",\n                cqlQuery);\n\n        // In Query set Paramater with gt clause.\n        queryString = \"Select p from PersonCassandra p WHERE p.personId in :nameList and p.age > 10\";\n\n        kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"nameList\", nameList);\n\n        cqlQuery = parseAndCreateCqlQuery(kunderaQuery, emf, em, pu, PersonCassandra.class, 5);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\n                \"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"personId\\\" IN ('kk', 'dk', 'sk' )  AND \\\"AGE\\\" > 10 LIMIT 5  ALLOW FILTERING\",\n                cqlQuery);\n\n        // In Query over non pk field set Paramater with gt clause.\n        queryString = \"Select p from PersonCassandra p WHERE p.age in :ageList and p.personName = 'vivek'\";\n\n        List<Integer> ageList = new ArrayList<Integer>();\n        ageList.add(10);\n        ageList.add(20);\n        ageList.add(30);\n\n        kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"ageList\", ageList);\n\n        cqlQuery = parseAndCreateCqlQuery(kunderaQuery, emf, em, pu, PersonCassandra.class, 100);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\n                \"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"AGE\\\" IN (10, 20, 30 )  AND \\\"PERSON_NAME\\\" = 'vivek' LIMIT 100  ALLOW FILTERING\",\n                cqlQuery);\n\n        em.close();\n        emf.close();\n\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.cassandra.query.CassQuery#onQueryOverCQL3(com.impetus.kundera.metadata.model.EntityMetadata, com.impetus.kundera.client.Client, com.impetus.kundera.metadata.model.MetamodelImpl, java.util.List)}\n     * .\n     * \n     * @throws InvocationTargetException\n     * @throws IllegalAccessException\n     * @throws IllegalArgumentException\n     */\n    @Test\n    public void testOnQueryOverCQL3ForEmbeddedEntity() throws IllegalArgumentException, IllegalAccessException,\n            InvocationTargetException\n    {\n        CassandraCli.createKeySpace(\"CompositeCassandra\");\n        String pu = \"composite_pu\";\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(pu);\n        EntityManager em = emf.createEntityManager();\n\n        // Simple Query.\n        String queryString = \"Select u from CassandraPrimeUser u WHERE u.name = 'kk'\";\n\n        String cqlQuery = parseAndCreateCqlQuery(getQueryObject(queryString, emf), emf, em, pu,\n                CassandraPrimeUser.class, 100);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"SELECT * FROM \\\"CompositeUser\\\" WHERE \\\"name\\\" = 'kk' LIMIT 100  ALLOW FILTERING\", cqlQuery);\n\n        // In Query.\n        queryString = \"Select u from CassandraPrimeUser u WHERE u.key.userId IN ('kk','dk','sk') ORDER BY u.key.tweetId ASC\";\n\n        cqlQuery = parseAndCreateCqlQuery(getQueryObject(queryString, emf), emf, em, pu, CassandraPrimeUser.class, 400);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\n                \"SELECT * FROM \\\"CompositeUser\\\" WHERE \\\"userId\\\" IN ('kk', 'dk', 'sk')  ORDER BY \\\"tweetId\\\" ASC  LIMIT 400  ALLOW FILTERING\",\n                cqlQuery);\n\n        // In Query set Paramater.\n        queryString = \"Select u from CassandraPrimeUser u WHERE u.key.userId IN :userIdList ORDER BY u.key.tweetId ASC\";\n\n        List<String> userIdList = new ArrayList<String>();\n        userIdList.add(\"kk\");\n        userIdList.add(\"dk\");\n        userIdList.add(\"sk\");\n\n        KunderaQuery kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"userIdList\", userIdList);\n\n        cqlQuery = parseAndCreateCqlQuery(kunderaQuery, emf, em, pu, CassandraPrimeUser.class, Integer.MAX_VALUE);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\n                \"SELECT * FROM \\\"CompositeUser\\\" WHERE \\\"userId\\\" IN ('kk', 'dk', 'sk' )   ORDER BY \\\"tweetId\\\" ASC   ALLOW FILTERING\",\n                cqlQuery);\n\n        // In Query set Paramater with and clause.\n        queryString = \"Select u from CassandraPrimeUser u WHERE u.key.userId IN :userIdList and p.name = 'kuldeep' ORDER BY u.key.tweetId ASC\";\n\n        kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"userIdList\", userIdList);\n\n        cqlQuery = parseAndCreateCqlQuery(kunderaQuery, emf, em, pu, CassandraPrimeUser.class, 100);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\n                \"SELECT * FROM \\\"CompositeUser\\\" WHERE \\\"userId\\\" IN ('kk', 'dk', 'sk' )  AND \\\"name\\\" = 'kuldeep'  ORDER BY \\\"tweetId\\\" ASC  LIMIT 100  ALLOW FILTERING\",\n                cqlQuery);\n\n        // In Query set Paramater with gt clause.\n        queryString = \"Select u from CassandraPrimeUser u WHERE u.key IN :keyList\";\n\n        List<CassandraCompoundKey> personIdList = new ArrayList<CassandraCompoundKey>();\n        UUID timeLineId1 = UUID.randomUUID();\n        personIdList.add(new CassandraCompoundKey(\"kk\", 1, timeLineId1));\n        personIdList.add(new CassandraCompoundKey(\"vm\", 2, timeLineId1));\n        personIdList.add(new CassandraCompoundKey(\"vs\", 3, timeLineId1));\n\n        kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"keyList\", personIdList);\n\n        cqlQuery = parseAndCreateCqlQuery(kunderaQuery, emf, em, pu, CassandraPrimeUser.class, 100);\n\n        Assert.assertNotNull(cqlQuery);\n        Assert.assertTrue(cqlQuery.contains(\"SELECT * FROM \\\"CompositeUser\\\" WHERE \"));\n        Assert.assertTrue(cqlQuery.contains(\"\\\"timeLineId\\\" IN (\" + timeLineId1 + \", \" + timeLineId1 + \", \"\n                + timeLineId1 + \" )\"));\n        Assert.assertTrue(cqlQuery.contains(\"\\\"userId\\\" IN ('kk', 'vm', 'vs' )\"));\n        Assert.assertTrue(cqlQuery.contains(\"\\\"tweetId\\\" IN (1, 2, 3 )\"));\n        Assert.assertTrue(cqlQuery.contains(\" LIMIT 100\"));\n        Assert.assertTrue(cqlQuery.contains(\" AND \"));\n        Assert.assertTrue(cqlQuery.indexOf(\" AND \") > 0);\n\n        // In Query over non pk field set Paramater with gt clause.\n        queryString = \"Select u from CassandraPrimeUser u WHERE u.key IN :keyList and u.name = 'vivek'\";\n\n        kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"keyList\", personIdList);\n\n        cqlQuery = parseAndCreateCqlQuery(kunderaQuery, emf, em, pu, CassandraPrimeUser.class, 100);\n\n        Assert.assertNotNull(cqlQuery);\n        Assert.assertTrue(cqlQuery.contains(\"SELECT * FROM \\\"CompositeUser\\\" WHERE \"));\n        Assert.assertTrue(cqlQuery.contains(\"\\\"timeLineId\\\" IN (\" + timeLineId1 + \", \" + timeLineId1 + \", \"\n                + timeLineId1 + \" )\"));\n        Assert.assertTrue(cqlQuery.contains(\"\\\"userId\\\" IN ('kk', 'vm', 'vs' )\"));\n        Assert.assertTrue(cqlQuery.contains(\"\\\"tweetId\\\" IN (1, 2, 3 )\"));\n        Assert.assertTrue(cqlQuery.contains(\" LIMIT 100\"));\n        Assert.assertTrue(cqlQuery.contains(\" AND \"));\n        Assert.assertTrue(cqlQuery.contains(\"AND \\\"name\\\" = 'vivek'\"));\n        Assert.assertTrue(cqlQuery.indexOf(\" AND \") > 0);\n\n        em.close();\n        emf.close();\n\n        CassandraCli.dropKeySpace(\"CompositeCassandra\");\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.cassandra.query.CassQuery#onQueryOverCQL3(com.impetus.kundera.metadata.model.EntityMetadata, com.impetus.kundera.client.Client, com.impetus.kundera.metadata.model.MetamodelImpl, java.util.List)}\n     * .\n     * \n     * @throws InvocationTargetException\n     * @throws IllegalAccessException\n     * @throws IllegalArgumentException\n     */\n    @Test\n    public void testUpdateDeleteQuerySimpleEntity() throws IllegalArgumentException, IllegalAccessException,\n            InvocationTargetException\n    {\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        String pu = \"genericCassandraTest\";\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(pu);\n        EntityManager em = emf.createEntityManager();\n\n        // Simple Query.\n        String queryString = \"Update PersonCassandra p SET p.personName = 'Kuldeep' WHERE p.personId = '1'\";\n\n        String cqlQuery = parseAndCreateUpdateQuery(getQueryObject(queryString, emf), emf, em, pu,\n                PersonCassandra.class, 200);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"UPDATE \\\"PERSONCASSANDRA\\\" SET \\\"PERSON_NAME\\\"='Kuldeep' WHERE \\\"personId\\\" = '1'\", cqlQuery);\n\n        // In Query.\n        queryString = \"Update PersonCassandra p SET p.personName = 'Kuldeep' WHERE p.personId IN ('1', '2', '3')\";\n\n        cqlQuery = parseAndCreateUpdateQuery(getQueryObject(queryString, emf), emf, em, pu, PersonCassandra.class, 400);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\n                \"UPDATE \\\"PERSONCASSANDRA\\\" SET \\\"PERSON_NAME\\\"='Kuldeep' WHERE \\\"personId\\\" IN ('1', '2', '3')\", cqlQuery);\n\n        // In Query set Paramater.\n        queryString = \"Update PersonCassandra p SET p.personName = 'Kuldeep' WHERE p.personId IN :idList\";\n\n        List<String> id = new ArrayList<String>();\n        id.add(\"1\");\n        id.add(\"2\");\n        id.add(\"3\");\n\n        KunderaQuery kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"idList\", id);\n\n        cqlQuery = parseAndCreateUpdateQuery(kunderaQuery, emf, em, pu, PersonCassandra.class, Integer.MAX_VALUE);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\n                \"UPDATE \\\"PERSONCASSANDRA\\\" SET \\\"PERSON_NAME\\\"='Kuldeep' WHERE \\\"personId\\\" IN ('1', '2', '3' ) \", cqlQuery);\n\n        // In Query set Paramater with and clause.\n        queryString = \"Update PersonCassandra p SET p.personName = 'Kuldeep' WHERE p.personId in :nameList and p.age = 10\";\n\n        kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"nameList\", id);\n\n        cqlQuery = parseAndCreateUpdateQuery(kunderaQuery, emf, em, pu, PersonCassandra.class, Integer.MAX_VALUE);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\n                \"UPDATE \\\"PERSONCASSANDRA\\\" SET \\\"PERSON_NAME\\\"='Kuldeep' WHERE \\\"personId\\\" IN ('1', '2', '3' )  AND \\\"AGE\\\" = 10\",\n                cqlQuery);\n\n        // In Query.\n        queryString = \"Delete from PersonCassandra p WHERE p.personId = '1'\";\n\n        cqlQuery = parseAndCreateDeleteQuery(getQueryObject(queryString, emf), emf, em, pu, PersonCassandra.class, 400);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"DELETE FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"personId\\\" = '1'\", cqlQuery);\n\n        // In Query.\n        queryString = \"Delete from PersonCassandra p WHERE p.personId IN ('1', '2', '3')\";\n\n        cqlQuery = parseAndCreateDeleteQuery(getQueryObject(queryString, emf), emf, em, pu, PersonCassandra.class, 400);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"DELETE FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"personId\\\" IN ('1', '2', '3')\", cqlQuery);\n\n        // In Query set Paramater.\n        queryString = \"Delete from PersonCassandra p WHERE p.personId IN :idList\";\n\n        kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"idList\", id);\n\n        cqlQuery = parseAndCreateDeleteQuery(kunderaQuery, emf, em, pu, PersonCassandra.class, Integer.MAX_VALUE);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"DELETE FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"personId\\\" IN ('1', '2', '3' ) \", cqlQuery);\n\n        // In Query over non pk field set Paramater with gt clause.\n        queryString = \"Delete from PersonCassandra p WHERE p.personId in :idList and p.age = 25\";\n\n        kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"idList\", id);\n\n        cqlQuery = parseAndCreateDeleteQuery(kunderaQuery, emf, em, pu, PersonCassandra.class, 100);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"DELETE FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"personId\\\" IN ('1', '2', '3' )  AND \\\"AGE\\\" = 25\",\n                cqlQuery);\n\n        em.close();\n        emf.close();\n\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.cassandra.query.CassQuery#onQueryOverCQL3(com.impetus.kundera.metadata.model.EntityMetadata, com.impetus.kundera.client.Client, com.impetus.kundera.metadata.model.MetamodelImpl, java.util.List)}\n     * .\n     * \n     * @throws InvocationTargetException\n     * @throws IllegalAccessException\n     * @throws IllegalArgumentException\n     */\n    @Test\n    public void testUpdateQueryWithTTLSimpleEntity() throws IllegalArgumentException, IllegalAccessException,\n            InvocationTargetException\n    {\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        String pu = \"genericCassandraTest\";\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(pu);\n        EntityManager em = emf.createEntityManager();\n\n        // Simple Query.\n        String queryString = \"Update PersonCassandra p SET p.personName = 'Kuldeep' WHERE p.personId = '1'\";\n\n        String cqlQuery = parseAndCreateUpdateQuery(getQueryObject(queryString, emf), emf, em, pu,\n                PersonCassandra.class, 200,100);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"UPDATE \\\"PERSONCASSANDRA\\\"  USING TTL 100 SET \\\"PERSON_NAME\\\"='Kuldeep' WHERE \\\"personId\\\" = '1'\", cqlQuery);\n\n        // In Query.\n        queryString = \"Update PersonCassandra p SET p.personName = 'Kuldeep' WHERE p.personId IN ('1', '2', '3')\";\n\n        cqlQuery = parseAndCreateUpdateQuery(getQueryObject(queryString, emf), emf, em, pu, PersonCassandra.class, 400, 200);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\n                \"UPDATE \\\"PERSONCASSANDRA\\\"  USING TTL 200 SET \\\"PERSON_NAME\\\"='Kuldeep' WHERE \\\"personId\\\" IN ('1', '2', '3')\", cqlQuery);\n\n        // In Query set Paramater.\n        queryString = \"Update PersonCassandra p SET p.personName = 'Kuldeep' WHERE p.personId IN :idList\";\n\n        List<String> id = new ArrayList<String>();\n        id.add(\"1\");\n        id.add(\"2\");\n        id.add(\"3\");\n\n        KunderaQuery kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"idList\", id);\n\n        cqlQuery = parseAndCreateUpdateQuery(kunderaQuery, emf, em, pu, PersonCassandra.class, Integer.MAX_VALUE, 1000);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\n                \"UPDATE \\\"PERSONCASSANDRA\\\"  USING TTL 1000 SET \\\"PERSON_NAME\\\"='Kuldeep' WHERE \\\"personId\\\" IN ('1', '2', '3' ) \", cqlQuery);\n\n        // In Query set Paramater with and clause.\n        queryString = \"Update PersonCassandra p SET p.personName = 'Kuldeep' WHERE p.personId in :nameList and p.age = 10\";\n\n        kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"nameList\", id);\n\n        cqlQuery = parseAndCreateUpdateQuery(kunderaQuery, emf, em, pu, PersonCassandra.class, Integer.MAX_VALUE);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\n                \"UPDATE \\\"PERSONCASSANDRA\\\" SET \\\"PERSON_NAME\\\"='Kuldeep' WHERE \\\"personId\\\" IN ('1', '2', '3' )  AND \\\"AGE\\\" = 10\",\n                cqlQuery);\n\n        em.close();\n        emf.close();\n\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.cassandra.query.CassQuery#onQueryOverCQL3(com.impetus.kundera.metadata.model.EntityMetadata, com.impetus.kundera.client.Client, com.impetus.kundera.metadata.model.MetamodelImpl, java.util.List)}\n     * .\n     * \n     * @throws InvocationTargetException\n     * @throws IllegalAccessException\n     * @throws IllegalArgumentException\n     */\n    @Test\n    public void testUpdateDeleteQueryEmbeddedEntity() throws IllegalArgumentException, IllegalAccessException,\n            InvocationTargetException\n    {\n        CassandraCli.createKeySpace(\"CompositeCassandra\");\n        String pu = \"composite_pu\";\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(pu);\n        EntityManager em = emf.createEntityManager();\n\n        // Simple Query.\n        String queryString = \"Update CassandraPrimeUser u SET u.name = 'Kuldeep' WHERE u.name = 'kk'\";\n\n        String cqlQuery = parseAndCreateUpdateQuery(getQueryObject(queryString, emf), emf, em, pu,\n                CassandraPrimeUser.class, 100);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"UPDATE \\\"CompositeUser\\\" SET \\\"name\\\"='Kuldeep' WHERE \\\"name\\\" = 'kk'\", cqlQuery);\n\n        // In Query.\n        queryString = \"Update CassandraPrimeUser u SET u.name = 'Kuldeep' WHERE u.key.userId IN ('kk','dk','sk')\";\n\n        cqlQuery = parseAndCreateUpdateQuery(getQueryObject(queryString, emf), emf, em, pu, CassandraPrimeUser.class,\n                400);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"UPDATE \\\"CompositeUser\\\" SET \\\"name\\\"='Kuldeep' WHERE \\\"userId\\\" IN ('kk', 'dk', 'sk')\",\n                cqlQuery);\n\n        // In Query set Paramater.\n        queryString = \"Update CassandraPrimeUser u SET u.name = 'Kuldeep' WHERE u.key.userId IN :userIdList\";\n\n        List<String> userIdList = new ArrayList<String>();\n        userIdList.add(\"kk\");\n        userIdList.add(\"dk\");\n        userIdList.add(\"sk\");\n\n        KunderaQuery kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"userIdList\", userIdList);\n\n        cqlQuery = parseAndCreateUpdateQuery(kunderaQuery, emf, em, pu, CassandraPrimeUser.class, Integer.MAX_VALUE);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"UPDATE \\\"CompositeUser\\\" SET \\\"name\\\"='Kuldeep' WHERE \\\"userId\\\" IN ('kk', 'dk', 'sk' ) \",\n                cqlQuery);\n\n        // Simple Query.\n        queryString = \"Delete from CassandraPrimeUser u WHERE u.name = 'kk'\";\n\n        cqlQuery = parseAndCreateDeleteQuery(getQueryObject(queryString, emf), emf, em, pu, CassandraPrimeUser.class,\n                100);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"DELETE FROM \\\"CompositeUser\\\" WHERE \\\"name\\\" = 'kk'\", cqlQuery);\n\n        // In Query.\n        queryString = \"Delete from CassandraPrimeUser u WHERE u.key.userId IN ('kk', 'dk', 'sk' )\";\n\n        cqlQuery = parseAndCreateDeleteQuery(getQueryObject(queryString, emf), emf, em, pu, CassandraPrimeUser.class,\n                400);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"DELETE FROM \\\"CompositeUser\\\" WHERE \\\"userId\\\" IN ('kk', 'dk', 'sk')\", cqlQuery);\n\n        // In Query set Paramater with and clause.\n        queryString = \"Delete from CassandraPrimeUser u WHERE u.key.userId IN :userIdList\";\n\n        kunderaQuery = getQueryObject(queryString, emf);\n        kunderaQuery.setParameter(\"userIdList\", userIdList);\n\n        cqlQuery = parseAndCreateDeleteQuery(kunderaQuery, emf, em, pu, CassandraPrimeUser.class, 100);\n\n        Assert.assertNotNull(cqlQuery);\n\n        Assert.assertEquals(\"DELETE FROM \\\"CompositeUser\\\" WHERE \\\"userId\\\" IN ('kk', 'dk', 'sk' ) \", cqlQuery);\n\n        em.close();\n        emf.close();\n\n        CassandraCli.dropKeySpace(\"CompositeCassandra\");\n    }\n\n    /**\n     * \n     * @param kunderaQuery\n     * @return\n     */\n    private String parseAndCreateCqlQuery(KunderaQuery kunderaQuery, EntityManagerFactory emf, EntityManager em,\n            String puName, Class entityClass, Integer maxResult)\n    {\n        Method getpd = null;\n        try\n        {\n            getpd = EntityManagerImpl.class.getDeclaredMethod(\"getPersistenceDelegator\");\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error during execution, Caused by : \",e.getMessage());\n        }\n        \n        getpd.setAccessible(true);\n        PersistenceDelegator pd = getPersistenceDelegator(em, getpd);\n\n        KunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n\n        CassQuery query = new CassQuery(kunderaQuery, pd, kunderaMetadata);\n        query.setMaxResults(maxResult);\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        Metamodel metaModel = KunderaMetadataManager.getMetamodel(kunderaMetadata, puName);\n\n        Client<CassQuery> client = pd.getClient(metadata);\n\n        String cqlQuery = query.onQueryOverCQL3(metadata, client, (MetamodelImpl) metaModel,\n                metadata.getRelationNames());\n        return cqlQuery;\n    }\n\n    private PersistenceDelegator getPersistenceDelegator(EntityManager em, Method getpd)\n    {\n        PersistenceDelegator pd = null;\n        try\n        {\n            pd = (PersistenceDelegator) getpd.invoke(em);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error during execution, Caused by : \",e.getMessage());\n        }\n        return pd;\n    }\n\n    /**\n     * Parse and create update query.\n     * \n     * @param kunderaQuery  kundera query.\n     * @param emf  entity manager factory.\n     * @param em   entity manager\n     * @param puName     persistence unit name.\n     * @param entityClass  entity class. \n     * @param maxResult max result.\n     * \n     * @return parsed query.\n     */\n    private String parseAndCreateUpdateQuery(KunderaQuery kunderaQuery, EntityManagerFactory emf, EntityManager em,\n            String puName, Class entityClass, Integer maxResult)\n    {\n        return parseAndCreateUpdateQuery(kunderaQuery, emf, em, puName, entityClass, maxResult, null);\n    }\n    /**\n     * \n     * @param kunderaQuery\n     * @return\n     */\n    private String parseAndCreateUpdateQuery(KunderaQuery kunderaQuery, EntityManagerFactory emf, EntityManager em,\n            String puName, Class entityClass, Integer maxResult, Integer ttl)\n    {\n        Method getpd = null;\n        try\n        {\n            getpd = EntityManagerImpl.class.getDeclaredMethod(\"getPersistenceDelegator\");\n        }\n        catch (SecurityException e)\n        {\n        \tlog.warn(e.getMessage());\n        }\n        catch (NoSuchMethodException e)\n        {\n        \tlog.warn(e.getMessage());\n        }\n        getpd.setAccessible(true);\n//        PersistenceDelegator pd = null;\n        PersistenceDelegator pd = getPersistenceDelegator(em, getpd);\n        KunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n\n        CassQuery query = new CassQuery(kunderaQuery, pd, kunderaMetadata);\n        query.setMaxResults(maxResult);\n        if(ttl != null)\n        {\n            query.applyTTL(ttl);\n        }\n        \n        String cqlQuery = query.createUpdateQuery(kunderaQuery);\n        return cqlQuery;\n    }\n\n    /**\n     * \n     * @param kunderaQuery\n     * @return\n     */\n    private String parseAndCreateDeleteQuery(KunderaQuery kunderaQuery, EntityManagerFactory emf, EntityManager em,\n            String puName, Class entityClass, Integer maxResult)\n    {\n        Method getpd = null;\n        try\n        {\n            getpd = EntityManagerImpl.class.getDeclaredMethod(\"getPersistenceDelegator\");\n        }\n        catch (SecurityException e)\n        {\n        \tlog.warn(e.getMessage());\n        }\n        catch (NoSuchMethodException e)\n        {\n        \tlog.warn(e.getMessage());\n        }\n        getpd.setAccessible(true);\n        PersistenceDelegator pd = null;\n        try\n        {\n            pd = (PersistenceDelegator) getpd.invoke(em);\n        }\n        catch (IllegalArgumentException e)\n        {\n        \tlog.warn(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n        \tlog.warn(e.getMessage());\n        }\n        catch (InvocationTargetException e)\n        {\n        \tlog.warn(e.getMessage());\n        }\n\n        KunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n\n        CassQuery query = new CassQuery(kunderaQuery, pd, kunderaMetadata);\n        query.setMaxResults(maxResult);\n\n        String cqlQuery = query.createDeleteQuery(kunderaQuery);\n        return cqlQuery;\n    }\n\n    /**\n     * \n     * @param queryString\n     * @return\n     */\n    private KunderaQuery getQueryObject(String queryString, EntityManagerFactory emf)\n    {\n        Method getpostParsingInit = null;\n        try\n        {\n            getpostParsingInit = KunderaQuery.class.getDeclaredMethod(\"postParsingInit\");\n        }\n        catch (SecurityException e)\n        {\n        \tlog.warn(e.getMessage());\n        }\n        catch (NoSuchMethodException e)\n        {\n        \tlog.warn(e.getMessage());\n        }\n        getpostParsingInit.setAccessible(true);\n\n        KunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n        KunderaQuery kunderaQuery = new KunderaQuery(queryString, kunderaMetadata);\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        try\n        {\n            getpostParsingInit.invoke(kunderaQuery);\n        }\n        catch (IllegalArgumentException e)\n        {\n        \tlog.warn(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n        \tlog.warn(e.getMessage());\n        }\n        catch (InvocationTargetException e)\n        {\n        \tlog.warn(e.getMessage());\n        }\n\n        return kunderaQuery;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/query/JpaQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.query;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.metamodel.Metamodel;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.crud.PersonCassandra;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityManagerImpl;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQueryParser;\nimport com.vividsolutions.jts.util.Assert;\n\n/*\n * @author shaheed hussain\n * testcase to test the exception which is thrown if user uses any of the interclause or intraclause value in his data\n */\npublic class JpaQueryTest {\n\n\t/** The Constant logger. */\n\tprivate static final Logger logger = LoggerFactory\n\t\t\t.getLogger(JpaQueryTest.class);\n\n\t@Before\n\tpublic void setUp() throws Exception {\n\t\tCassandraCli.cassandraSetUp();\n\t\tCassandraCli.createKeySpace(\"KunderaExamples\");\n\t}\n\n\t@After\n\tpublic void tearDown() throws Exception {\n\t\tCassandraCli.dropKeySpace(\"KunderaExamples\");\n\t\t\n\t}\n\n\t/**\n\t * @throws Exception\n\t */\n\t@Test\n\tpublic void test() throws Exception {\n\n\t\tString pu = \"genericCassandraTest\";\n\t\tEntityManagerFactory emf = Persistence.createEntityManagerFactory(pu);\n\t\tEntityManager em = emf.createEntityManager();\n\n\t\tString queryString = \" select p from PersonCassandra p where p.age in ('in vivek','in kk','AND shaheed') OR p.personName in ('vivek','kk')\";\n\t\tString cqlQuery = parseAndCreateCqlQuery(\n\t\t\t\tgetQueryObject(queryString, emf), emf, em, pu,\n\t\t\t\tPersonCassandra.class, 200);\n\t\tString expectedQuery = \"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"AGE\\\" IN (in vivek, inkk, AND shaheed) AND \\\"PERSON_NAME\\\" IN ('vivek', 'kk') LIMIT 200  ALLOW FILTERING\";\n\t\t// Assert.equals(cqlQuery,expectedQuery); //vivek is fixing for extra\n\t\t// quotes in 'in' clause\n\n\t\tqueryString = \"Select p from PersonCassandra p where p.personName='sam''s and joseph''s' and p.age=80 \";\n\t\tcqlQuery = parseAndCreateCqlQuery(getQueryObject(queryString, emf),\n\t\t\t\temf, em, pu, PersonCassandra.class, 200);\n\n\t\texpectedQuery = \"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"PERSON_NAME\\\" = 'sam''s and joseph''s' AND \\\"AGE\\\" = 80 LIMIT 200  ALLOW FILTERING\";\n\t\tAssert.equals(cqlQuery, expectedQuery);\n\n\t\tqueryString = \"Select p from PersonCassandra p where p.personName = 'ram and wwe' and p.age='10'\";\n\t\tcqlQuery = parseAndCreateCqlQuery(getQueryObject(queryString, emf),\n\t\t\t\temf, em, pu, PersonCassandra.class, 200);\n\t\texpectedQuery = \"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"PERSON_NAME\\\" = 'ram and wwe' AND \\\"AGE\\\" = 10 LIMIT 200  ALLOW FILTERING\";\n\t\tAssert.equals(cqlQuery, expectedQuery);\n\n\t\tqueryString = \"Select p from PersonCassandra p where p.personName = 'Like-==' \";\n\t\tcqlQuery = parseAndCreateCqlQuery(getQueryObject(queryString, emf),\n\t\t\t\temf, em, pu, PersonCassandra.class, 200);\n\t\texpectedQuery = \"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"PERSON_NAME\\\" = 'Like-==' LIMIT 200  ALLOW FILTERING\";\n\t\tAssert.equals(cqlQuery, expectedQuery);\n\n\t\tqueryString = \"Select p from PersonCassandra p where p.personName = '==1'\";\n\t\tcqlQuery = parseAndCreateCqlQuery(getQueryObject(queryString, emf),\n\t\t\t\temf, em, pu, PersonCassandra.class, 200);\n\t\texpectedQuery = \"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"PERSON_NAME\\\" = '==1' LIMIT 200  ALLOW FILTERING\";\n\t\tAssert.equals(cqlQuery, expectedQuery);\n\n\t\tqueryString = \"Select p from PersonCassandra p where p.personName = 'Like >= NOT IN'\";\n\t\tcqlQuery = parseAndCreateCqlQuery(getQueryObject(queryString, emf),\n\t\t\t\temf, em, pu, PersonCassandra.class, 200);\n\t\texpectedQuery = \"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"PERSON_NAME\\\" = 'Like >= NOT IN' LIMIT 200  ALLOW FILTERING\";\n\n\t\tqueryString = \"Select p from PersonCassandra p where p.personName = 'in= NOT IN >=set >< <>'\";\n\t\tcqlQuery = parseAndCreateCqlQuery(getQueryObject(queryString, emf),\n\t\t\t\temf, em, pu, PersonCassandra.class, 200);\n\t\texpectedQuery = \"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"PERSON_NAME\\\" = 'in= NOT IN >=set >< <>' LIMIT 200  ALLOW FILTERING\";\n\t\tAssert.equals(cqlQuery, expectedQuery);\n\n\t\tqueryString = \"Select p from PersonCassandra p where p.personName = 'in= between. >=set anand >< or <>'\";\n\t\tcqlQuery = parseAndCreateCqlQuery(getQueryObject(queryString, emf),\n\t\t\t\temf, em, pu, PersonCassandra.class, 200);\n\t\texpectedQuery = \"SELECT * FROM \\\"PERSONCASSANDRA\\\" WHERE \\\"PERSON_NAME\\\" = 'in= between. >=set anand >< or <>' LIMIT 200  ALLOW FILTERING\";\n\t\tAssert.equals(cqlQuery, expectedQuery);\n\n\t\tem.close();\n\t\temf.close();\n\n\t}\n\n\t/**\n\t * @param queryString\n\t * @param emf\n\t * @return\n\t */\n\tprivate KunderaQuery getQueryObject(String queryString,\n\t\t\tEntityManagerFactory emf) {\n\t\tMethod getpostParsingInit = null;\n\t\ttry {\n\t\t\tgetpostParsingInit = KunderaQuery.class\n\t\t\t\t\t.getDeclaredMethod(\"postParsingInit\");\n\t\t} catch (SecurityException e) {\n\t\t\tlogger.warn(e.getMessage());\n\t\t} catch (NoSuchMethodException e) {\n\t\t\tlogger.warn(e.getMessage());\n\t\t}\n\t\tgetpostParsingInit.setAccessible(true);\n\n\t\tKunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl) emf)\n\t\t\t\t.getKunderaMetadataInstance();\n\t\tKunderaQuery kunderaQuery = new KunderaQuery(queryString,\n\t\t\t\tkunderaMetadata);\n\t\tKunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n\t\tqueryParser.parse();\n\t\ttry {\n\t\t\tgetpostParsingInit.invoke(kunderaQuery);\n\t\t} catch (IllegalArgumentException e) {\n\t\t\tlogger.warn(e.getMessage());\n\t\t} catch (IllegalAccessException e) {\n\t\t\tlogger.warn(e.getMessage());\n\t\t} catch (InvocationTargetException e) {\n\t\t\tlogger.warn(e.getMessage());\n\t\t}\n\n\t\treturn kunderaQuery;\n\t}\n\n\t/**\n\t * @param kunderaQuery\n\t * @param emf\n\t * @param em\n\t * @param puName\n\t * @param entityClass\n\t * @param maxResult\n\t * @return\n\t */\n\tprivate String parseAndCreateCqlQuery(KunderaQuery kunderaQuery,\n\t\t\tEntityManagerFactory emf, EntityManager em, String puName,\n\t\t\tClass entityClass, Integer maxResult) {\n\t\tMethod getpd = null;\n\t\ttry {\n\t\t\tgetpd = EntityManagerImpl.class\n\t\t\t\t\t.getDeclaredMethod(\"getPersistenceDelegator\");\n\t\t} catch (SecurityException e) {\n\t\t\tlogger.warn(e.getMessage());\n\t\t} catch (NoSuchMethodException e) {\n\t\t\tlogger.warn(e.getMessage());\n\t\t}\n\t\tgetpd.setAccessible(true);\n\t\tPersistenceDelegator pd = null;\n\t\ttry {\n\t\t\tpd = (PersistenceDelegator) getpd.invoke(em);\n\t\t} catch (IllegalArgumentException e) {\n\t\t\tlogger.warn(e.getMessage());\n\t\t} catch (IllegalAccessException e) {\n\t\t\tlogger.warn(e.getMessage());\n\t\t} catch (InvocationTargetException e) {\n\t\t\tlogger.warn(e.getMessage());\n\t\t}\n\n\t\tKunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl) emf)\n\t\t\t\t.getKunderaMetadataInstance();\n\n\t\tCassQuery query = new CassQuery(kunderaQuery, pd, kunderaMetadata);\n\t\tquery.setMaxResults(maxResult);\n\n\t\tEntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n\t\t\t\tkunderaMetadata, entityClass);\n\t\tMetamodel metaModel = KunderaMetadataManager.getMetamodel(\n\t\t\t\tkunderaMetadata, puName);\n\n\t\tClient<CassQuery> client = pd.getClient(metadata);\n\n\t\tString cqlQuery = query.onQueryOverCQL3(metadata, client,\n\t\t\t\t(MetamodelImpl) metaModel, metadata.getRelationNames());\n\t\treturn cqlQuery;\n\n\t}\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/AddressHandler.java",
    "content": "package com.impetus.client.cassandra.thrift;\n\nimport javax.persistence.PostPersist;\nimport javax.persistence.PrePersist;\n\npublic class AddressHandler\n{\n\n    @PrePersist\n    public void handledPrePersist(AddressListenerDTO address)\n    {\n        address.setStreet(\"aaaa\");\n    }\n\n    @PostPersist\n    public void handledPostPersist(AddressListenerDTO address)\n    {\n        address.setStreet(\"bbbb\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/AddressListenerDTO.java",
    "content": "package com.impetus.client.cassandra.thrift;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EntityListeners;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"address\", schema = \"KunderaExamples@secIdxCassandraTest\")\n@EntityListeners({ AddressHandler.class })\npublic class AddressListenerDTO\n{\n    @Id\n    private String addressId;\n\n    @Column\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/PersonHandler.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift;\n\nimport javax.persistence.PostPersist;\nimport javax.persistence.PrePersist;\n\npublic class PersonHandler\n{\n\n    @PrePersist\n    public void handledPrePersist(PersonnelListenerDTO user)\n    {\n        user.setFirstName(\"kuldeep\");\n    }\n\n    @PostPersist\n    public void handledPostPersist(PersonnelListenerDTO user)\n    {\n        user.setFirstName(\"vivek\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/PersonIdentity.java",
    "content": "/**\n * \n */\npackage com.impetus.client.cassandra.thrift;\n\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * @author impadmin\n * \n */\n@Entity\n@Table(name = \"PERSONIDENTITY\", schema = \"CompositeCassandra@composite_pu\")\npublic class PersonIdentity\n{\n    @Id\n    private String personId;\n\n    @Column\n    private String personName;\n\n    @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)\n    @JoinColumn(name = \"personId\")\n    private List<Phone> phones;\n    \n\n  \n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n  \n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public List<Phone> getPhones()\n    {\n        return phones;\n    }\n\n    public void setPhones(List<Phone> phones)\n    {\n        this.phones = phones;\n    }\n    \n    \n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/PersonIdentityTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic class PersonIdentityTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"CompositeCassandra\");\n                \n        emf = Persistence.createEntityManagerFactory(\"composite_pu\");\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        CassandraCli.dropKeySpace(\"CompositeCassandra\");\n    }\n\n    @Test\n    public void test()\n    {\n        PhoneId phoneId1 = new PhoneId();\n        phoneId1.setPhoneId(\"A\");\n        PhoneId phoneId2 = new PhoneId();\n        phoneId2.setPhoneId(\"B\");\n\n        Phone phone1 = new Phone();\n        phone1.setPhoneId(phoneId1);\n        phone1.setPhoneNumber(99533533434l);\n\n        Phone phone2 = new Phone();\n        phone2.setPhoneId(phoneId2);\n        phone2.setPhoneNumber(9972723678l);\n\n        List<Phone> phones = new ArrayList<Phone>();\n        phones.add(phone1);\n        phones.add(phone2);\n\n        PersonIdentity identity = new PersonIdentity();\n        identity.setPersonId(\"1\");\n        identity.setPersonName(\"KK\");\n        identity.setPhones(phones);\n\n        em.persist(identity);\n\n        em.clear();\n        \n        em.close();\n        \n        em = emf.createEntityManager();\n\n        PersonIdentity foundPerson = em.find(PersonIdentity.class, \"1\");\n\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getPhones());\n        Assert.assertFalse(foundPerson.getPhones().isEmpty());\n        Assert.assertEquals(2,foundPerson.getPhones().size());\n        Assert.assertNotNull(foundPerson.getPhones().get(0));\n        Assert.assertNotNull(foundPerson.getPhones().get(1));\n        Assert.assertNotNull(foundPerson.getPhones().get(0).getPhoneId());\n        Assert.assertNotNull(foundPerson.getPhones().get(1).getPhoneId());\n\n        Assert.assertEquals(new Long(99533533434l), foundPerson.getPhones().get(0).getPhoneNumber());\n        Assert.assertEquals(new Long(9972723678l), foundPerson.getPhones().get(1).getPhoneNumber());\n\n        Assert.assertEquals(\"1\", foundPerson.getPhones().get(0).getPhoneId().getPersonId());\n        \n        List<String> phoneIds = new ArrayList<String>();\n        phoneIds.add(\"A\");\n        phoneIds.add(\"B\");\n        Assert.assertTrue(phoneIds.contains(foundPerson.getPhones().get(0).getPhoneId().getPhoneId()));\n        Assert.assertEquals(\"1\", foundPerson.getPhones().get(1).getPhoneId().getPersonId());\n        Assert.assertNotSame(foundPerson.getPhones().get(0).getPhoneId().getPhoneId(), foundPerson.getPhones().get(1).getPhoneId().getPhoneId());\n        \n        foundPerson.setPhones(null);\n        foundPerson.setPersonName(null);\n        em.merge(foundPerson);\n        \n        foundPerson = em.find(PersonIdentity.class, 1);\n\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNull(foundPerson.getPhones());\n        Assert.assertNull(foundPerson.getPersonName());\n        Assert.assertEquals(\"1\",foundPerson.getPersonId());\n       \n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/PersonnelListenerDTO.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.cassandra.thrift;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.EntityListeners;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.OneToOne;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * The Class PersonnelDTO.\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"person\", schema = \"KunderaExamples@secIdxCassandraTest\")\r\n@EntityListeners({ PersonHandler.class })\r\npublic class PersonnelListenerDTO\r\n{\r\n\r\n    /** The person id. */\r\n    @Id\r\n    private String personId;\r\n\r\n    /** The first name. */\r\n    @Column(name = \"first_name\")\r\n    private String firstName;\r\n\r\n    /** The last name. */\r\n    @Column(name = \"last_name\")\r\n    private String lastName;\r\n\r\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\r\n    @JoinColumn(name = \"addressId\")\r\n    private AddressListenerDTO address;\r\n\r\n    /**\r\n     * Instantiates a new personnel dto.\r\n     * \r\n     * @param personId\r\n     *            the person id\r\n     * @param firstName\r\n     *            the first name\r\n     * @param lastName\r\n     *            the last name\r\n     */\r\n    public PersonnelListenerDTO(String personId, String firstName, String lastName)\r\n    {\r\n        this.personId = personId;\r\n        this.firstName = firstName;\r\n        this.lastName = lastName;\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new personnel dto.\r\n     */\r\n    public PersonnelListenerDTO()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * Gets the person id.\r\n     * \r\n     * @return the personId\r\n     */\r\n    public String getPersonId()\r\n    {\r\n        return personId;\r\n    }\r\n\r\n    /**\r\n     * Sets the person id.\r\n     * \r\n     * @param personId\r\n     *            the personId to set\r\n     */\r\n    public void setPersonId(String personId)\r\n    {\r\n        this.personId = personId;\r\n    }\r\n\r\n    /**\r\n     * Gets the first name.\r\n     * \r\n     * @return the firstName\r\n     */\r\n    public String getFirstName()\r\n    {\r\n        return firstName;\r\n    }\r\n\r\n    /**\r\n     * Sets the first name.\r\n     * \r\n     * @param firstName\r\n     *            the firstName to set\r\n     */\r\n    public void setFirstName(String firstName)\r\n    {\r\n        this.firstName = firstName;\r\n    }\r\n\r\n    /**\r\n     * Gets the last name.\r\n     * \r\n     * @return the lastName\r\n     */\r\n    public String getLastName()\r\n    {\r\n        return lastName;\r\n    }\r\n\r\n    /**\r\n     * Sets the last name.\r\n     * \r\n     * @param lastName\r\n     *            the lastName to set\r\n     */\r\n    public void setLastName(String lastName)\r\n    {\r\n        this.lastName = lastName;\r\n    }\r\n\r\n    public AddressListenerDTO getAddress()\r\n    {\r\n        return address;\r\n    }\r\n\r\n    public void setAddress(AddressListenerDTO address)\r\n    {\r\n        this.address = address;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/PersonnelListenerDTOTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.cassandra.thrift;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author impadmin\n * \n */\npublic class PersonnelListenerDTOTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        Map propertyMap = new HashMap();\n     //   propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        emf = Persistence.createEntityManagerFactory(\"secIdxCassandraTest\", propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    @Test\n    public void test()\n    {\n        AddressListenerDTO address = new AddressListenerDTO();\n        address.setStreet(\"New Street\");\n        address.setAddressId(\"a1\");\n        PersonnelListenerDTO personnel = new PersonnelListenerDTO();\n        personnel.setPersonId(\"1\");\n        personnel.setFirstName(\"kk\");\n        personnel.setLastName(\"Mishra\");\n        personnel.setAddress(address);\n\n        em.persist(personnel);\n\n        em.clear();\n\n        PersonnelListenerDTO foundPersonnel = em.find(PersonnelListenerDTO.class, \"1\");\n       \n        Assert.assertNotNull(foundPersonnel);\n        Assert.assertEquals(\"kuldeep\", foundPersonnel.getFirstName());\n        Assert.assertNotNull(foundPersonnel.getAddress());\n        Assert.assertEquals(\"aaaa\", foundPersonnel.getAddress().getStreet());\n        \n        \n        List<PersonnelListenerDTO> results = em.createNativeQuery(\"select * from person\", PersonnelListenerDTO.class).getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(\"kuldeep\", results.get(0).getFirstName());\n        Assert.assertNotNull(results.get(0).getAddress());\n        Assert.assertEquals(\"aaaa\", results.get(0).getAddress().getStreet());\n    }\n    \n   \n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/Phone.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * \n * @author Kuldeep.Mishra\n *\n */\n@Entity\n@Table(name = \"PHONE\", schema = \"CompositeCassandra@composite_pu\")\npublic class Phone\n{\n    @EmbeddedId\n    private PhoneId phoneIdentifier;\n\n    @Column\n    private Long phoneNumber;\n\n    public PhoneId getPhoneId()\n    {\n        return phoneIdentifier;\n    }\n\n    public void setPhoneId(PhoneId phoneId)\n    {\n        this.phoneIdentifier = phoneId;\n    }\n\n    public Long getPhoneNumber()\n    {\n        return phoneNumber;\n    }\n\n    public void setPhoneNumber(Long phoneNumber)\n    {\n        this.phoneNumber = phoneNumber;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/PhoneId.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * \n * @author Kuldeep.Mishra\n *\n */\n@Embeddable\npublic class PhoneId\n{\n\n    @Column\n    private String personId;\n\n    @Column\n    private String phoneId;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public String getPhoneId()\n    {\n        return phoneId;\n    }\n\n    public void setPhoneId(String phoneId)\n    {\n        this.phoneId = phoneId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/CQLUser.java",
    "content": "package com.impetus.client.cassandra.thrift.cql;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"CQLUSER\", schema = \"CqlKeyspace@cassandra_cql\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class CQLUser\n{\n    @Id\n    private int id;\n\n    @Column\n    private String name;\n\n    @Column\n    private int age;\n\n    @Column\n    private transient int salary;\n\n    @Column\n    private static String address;\n\n    public int getId()\n    {\n        return id;\n    }\n\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public int getSalary()\n    {\n        return salary;\n    }\n\n    public void setSalary(int salary)\n    {\n        this.salary = salary;\n    }\n\n    public static String getAddress()\n    {\n        return address;\n    }\n\n    public static void setAddress(String address)\n    {\n        CQLUser.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/CQLUserTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift.cql;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author Kuldeep\n * \n */\npublic class CQLUserTest\n{\n\n    private EntityManagerFactory emf;\n\n    private String persistenceUnit = \"cassandra_cql\";\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        Map propertyMap = new HashMap();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(persistenceUnit, propertyMap);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        emf = null;\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        EntityManager em = emf.createEntityManager();\n        CQLUser user = new CQLUser();\n        user.setId(1);\n        user.setName(\"Kuldeep\");\n        user.setAge(24);\n\n        em.persist(user);\n\n        em.clear();\n\n        CQLUser foundUser = em.find(CQLUser.class, 1);\n        Assert.assertNotNull(foundUser);\n        Assert.assertEquals(1, foundUser.getId());\n        Assert.assertEquals(24, foundUser.getAge());\n        Assert.assertEquals(\"Kuldeep\", foundUser.getName());\n\n        foundUser.setName(null);\n\n        em.merge(foundUser);\n\n        em.clear();\n\n        CQLUser mergedUser = em.find(CQLUser.class, 1);\n        Assert.assertNotNull(mergedUser);\n        Assert.assertEquals(1, mergedUser.getId());\n        Assert.assertEquals(24, mergedUser.getAge());\n        Assert.assertEquals(null, mergedUser.getName());\n\n        em.remove(mergedUser);\n\n        CQLUser deletedUser = em.find(CQLUser.class, 1);\n        Assert.assertNull(deletedUser);\n\n        em.clear();\n\n        deletedUser = em.find(CQLUser.class, 1);\n        Assert.assertNull(deletedUser);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/CassandraBatchProcessorCQLTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.cassandra.thrift.cql;\n\nimport java.util.HashMap;\n\nimport org.junit.After;\nimport org.junit.Before;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.crud.batch.CassandraBatchProcessorTest;\nimport com.impetus.kundera.PersistenceProperties;\n\n/**\n * @author impadmin\n * \n */\npublic class CassandraBatchProcessorCQLTest extends CassandraBatchProcessorTest\n{\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.crud.batch.CassandraBatchProcessorTest#setUp()\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        propertyMap = new HashMap();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        propertyMap.put(\"kundera.batch.size\", \"5\");\n        AUTO_MANAGE_SCHEMA = false;\n        USE_CQL = false;\n        super.setUp();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.crud.batch.CassandraBatchProcessorTest#tearDown()\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/CassandraCqlSecondaryTableTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift.cql;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.cassandra.thrift.Cassandra.Client;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * \n * @author Kuldeep.Mishra\n *\n */\npublic class CassandraCqlSecondaryTableTest\n{\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        \n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        loadData();\n        Map<String, String> props = new HashMap<String, String>();\n        props.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(\"secIdxCassandraTest\", props);\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    @Test\n    public void test()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        SecondaryTableCqlEntity entity = new SecondaryTableCqlEntity();\n        entity.setAge(24);\n        entity.setObjectId(\"123\");\n        entity.setName(\"Kuldeep\");\n\n        em.persist(entity);\n\n        em.clear();\n\n        SecondaryTableCqlEntity foundEntity = em.find(SecondaryTableCqlEntity.class, \"123\");\n        Assert.assertNotNull(foundEntity);\n        Assert.assertEquals(\"Kuldeep\", foundEntity.getName());\n        Assert.assertEquals(24, foundEntity.getAge());\n\n        foundEntity.setAge(25);\n        foundEntity.setName(\"kk\");\n\n        em.merge(foundEntity);\n\n        em.clear();\n\n        foundEntity = em.find(SecondaryTableCqlEntity.class, \"123\");\n        Assert.assertNotNull(foundEntity);\n        Assert.assertEquals(\"kk\", foundEntity.getName());\n        Assert.assertEquals(25, foundEntity.getAge());\n\n        em.remove(foundEntity);\n\n        foundEntity = em.find(SecondaryTableCqlEntity.class, \"123\");\n        Assert.assertNull(foundEntity);\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n        String table1 = \"PRIMARY_TABLE\";\n        String table2 = \"SECONDARY_TABLE\";\n        String keyspace = \"KunderaExamples\";\n\n        try\n        {\n            Client client = CassandraCli.getClient();\n            KsDef ksDef = client.describe_keyspace(keyspace);\n            client.set_keyspace(keyspace);\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(table1))\n                {\n                    client.system_drop_column_family(table1);\n                }\n                if (cfDef1.getName().equalsIgnoreCase(table2))\n                {\n                    client.system_drop_column_family(table2);\n                }\n            }\n\n            client.execute_cql3_query(ByteBufferUtil.bytes(\"create table \\\"PRIMARY_TABLE\\\"(\\\"OBJECT_ID\\\" text PRIMARY KEY, \\\"NAME\\\" text)\"),\n                    org.apache.cassandra.thrift.Compression.NONE, org.apache.cassandra.thrift.ConsistencyLevel.ANY);\n\n            client.execute_cql3_query(ByteBufferUtil.bytes(\"create table \\\"SECONDARY_TABLE\\\"(\\\"OBJECT_ID\\\" text PRIMARY KEY, \\\"AGE\\\" int)\"),\n                    org.apache.cassandra.thrift.Compression.NONE, org.apache.cassandra.thrift.ConsistencyLevel.ANY);\n        }\n        catch (NotFoundException e)\n        {\n            \n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/CassandraShowQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift.cql;\n\nimport static org.junit.Assert.fail;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.FileReader;\nimport java.io.PrintStream;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * test case for checking printed queries when kundera.show.query is enabled\n * \n * @author shaheed.hussain\n * \n */\npublic class CassandraShowQueryTest\n{\n    private static final String SHOW_QUERY_ENABLED_PU = \"CassandraShowQueryEnabledPu\";\n\n    private static final String SHOW_QUERY_DISABLED_PU = \"CassandraShowQueryDisabledPu\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Map<String, Object> puProperties = new HashMap<String, Object>();\n\n    private Logger logger = LoggerFactory.getLogger(CassandraShowQueryTest.class);\n\n    @Before\n    public void setUpBeforeClass() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        puProperties.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n\n    }\n\n    @After\n    public void tearDownAfterClass() throws Exception\n    {\n        puProperties = null;\n\n    }\n\n    /*\n     * testing show.query when it is enabled in persistence unit\n     */\n    @Test\n    public void testShowQuerySetInPU()\n    {\n        emf = Persistence.createEntityManagerFactory(SHOW_QUERY_ENABLED_PU, puProperties);\n        em = emf.createEntityManager();\n        try\n        {\n            \n            String expectedQuery[] = new String[3];\n            String actualQuery = null;\n            BufferedReader br = null;\n            File file = new File(\"showQuery.log\");\n            PrintStream printStream;\n\n            printStream = new PrintStream(new FileOutputStream(file));\n            System.setOut(printStream);\n            Query findQuery = em.createQuery(\"Select s from UserInformation s\", UserInformation.class);\n            findQuery.getResultList();\n            expectedQuery[0] = \"SELECT * FROM \\\"USER\\\" LIMIT 100\";\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select s from UserInformation s where s.name = vivek\");\n            findQuery.getResultList();\n            expectedQuery[1] = \"SELECT * FROM \\\"USER\\\" WHERE \\\"name\\\" = 'vivek' LIMIT 100  ALLOW FILTERING\";\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select s.age from UserInformation s where s.name = vivek\");\n            findQuery.getResultList();\n            expectedQuery[2] = \"SELECT \\\"age\\\" FROM \\\"USER\\\" WHERE \\\"name\\\" = 'vivek' LIMIT 100  ALLOW FILTERING\";\n            System.setOut(printStream);\n\n            br = new BufferedReader(new FileReader(\"showQuery.log\"));\n            actualQuery = br.readLine();\n            if (actualQuery == null)\n                fail(\"failed as file is empty\");\n\n            while (actualQuery != null)\n            {\n                actualQuery.concat(br.readLine());\n            }\n            Assert.assertTrue(actualQuery.indexOf(expectedQuery[0]) != -1\n                    && actualQuery.indexOf(expectedQuery[1]) != -1 && actualQuery.indexOf(expectedQuery[2]) != -1);\n            em.close();\n            emf.close();\n        }\n        catch (Exception e)\n        {\n            logger.info(e.getMessage());\n        }\n    }\n\n    /*\n     * testing show.query property when it is disabled\n     */\n    @Test\n    public void testShowQueryDisabled()\n    {\n        emf = Persistence.createEntityManagerFactory(SHOW_QUERY_DISABLED_PU, puProperties);\n        em = emf.createEntityManager();\n        try\n        {\n            String expectedQuery[] = new String[3];\n            String actualQuery = null;\n            boolean isFileEmpty = false;\n            BufferedReader br = null;\n            File file = new File(\"showQuery.log\");\n            PrintStream printStream;\n\n            printStream = new PrintStream(new FileOutputStream(file));\n            \n            System.setOut(printStream);\n            Query findQuery = em.createQuery(\"Select s from UserInformation s\", UserInformation.class);\n            findQuery.getResultList();\n            expectedQuery[0] = \"SELECT * FROM \\\"USER\\\" LIMIT 100\";\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select s from UserInformation s where s.name = vivek\");\n            findQuery.getResultList();\n            expectedQuery[1] = \"SELECT * FROM \\\"USER\\\" WHERE \\\"name\\\" = 'vivek' LIMIT 100  ALLOW FILTERING\";\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select s.age from UserInformation s where s.name = vivek\");\n            findQuery.getResultList();\n            expectedQuery[2] = \"SELECT \\\"age\\\" FROM \\\"USER\\\" WHERE \\\"name\\\" = 'vivek' LIMIT 100  ALLOW FILTERING\";\n            System.setOut(printStream);\n            \n            br = new BufferedReader(new FileReader(\"showQuery.log\"));\n            isFileEmpty = br.readLine() == null;\n            \n            while (actualQuery != null)\n            {\n                actualQuery.concat(br.readLine());\n            }\n            Assert.assertTrue(actualQuery.indexOf(expectedQuery[0]) == -1\n                    && actualQuery.indexOf(expectedQuery[1]) == -1 && actualQuery.indexOf(expectedQuery[2]) == -1);\n            \n        }\n        catch (Exception e)\n        {\n            logger.info(e.getMessage());\n        }\n        em.close();\n        emf.close();\n    }\n\n    /*\n     * testing kunera.show.query property when it is enabled at external\n     * properties level\n     */\n\n    @Test\n    public void testShowQueryPropertySetInPropertyMap()\n    {\n        puProperties.put(\"kundera.show.query\", \"true\");\n        emf = Persistence.createEntityManagerFactory(SHOW_QUERY_DISABLED_PU, puProperties);\n        em = emf.createEntityManager();\n        try\n        {\n            \n            String expectedQuery[] = new String[3];\n            String actualQuery = null;\n            BufferedReader br = null;\n            File file = new File(\"showQuery.log\");\n            PrintStream printStream;\n\n            printStream = new PrintStream(new FileOutputStream(file));\n            System.setOut(printStream);\n            Query findQuery = em.createQuery(\"Select s from UserInformation s\", UserInformation.class);\n            findQuery.getResultList();\n            expectedQuery[0] = \"SELECT * FROM \\\"USER\\\" LIMIT 100\";\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select s from UserInformation s where s.name = vivek\");\n            findQuery.getResultList();\n            expectedQuery[1] = \"SELECT * FROM \\\"USER\\\" WHERE \\\"name\\\" = 'vivek' LIMIT 100  ALLOW FILTERING\";\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select s.age from UserInformation s where s.name = vivek\");\n            findQuery.getResultList();\n            expectedQuery[2] = \"SELECT \\\"age\\\" FROM \\\"USER\\\" WHERE \\\"name\\\" = 'vivek' LIMIT 100  ALLOW FILTERING\";\n            System.setOut(printStream);\n\n            br = new BufferedReader(new FileReader(\"showQuery.log\"));\n            actualQuery = br.readLine();\n            if (actualQuery == null)\n                fail(\"failed as file is empty\");\n\n            while (actualQuery != null)\n            {\n                actualQuery.concat(br.readLine());\n            }\n            Assert.assertTrue(actualQuery.indexOf(expectedQuery[0]) != -1\n                    && actualQuery.indexOf(expectedQuery[1]) != -1 && actualQuery.indexOf(expectedQuery[2]) != -1);\n            em.close();\n            emf.close();\n        }\n        catch (Exception e)\n        {\n            logger.info(e.getMessage());\n        }\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/CountersTestOnCql.java",
    "content": "package com.impetus.client.cassandra.thrift.cql;\n\nimport org.junit.After;\nimport org.junit.Before;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.crud.countercolumns.CountersTest;\nimport com.impetus.kundera.PersistenceProperties;\n\npublic class CountersTestOnCql extends CountersTest\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/LoggingConfiguration.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift.cql;\n\nimport java.sql.Timestamp;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"LoggingConfiguration\", schema = \"KunderaExamples@twissandraTest\")\n@IndexCollection(columns = { @Index(name = \"logname\") })\npublic class LoggingConfiguration\n{\n    @Id\n    private String id;\n\n    @Column\n    private String label;\n\n    @Column\n    private String logname;\n\n    @Column\n    private Timestamp nnow;\n\n    @Column\n    private String lvl;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public String getLable()\n    {\n        return label;\n    }\n\n    public void setLable(String lable)\n    {\n        this.label = lable;\n    }\n\n    public String getLongName()\n    {\n        return logname;\n    }\n\n    public void setLongName(String longName)\n    {\n        this.logname = longName;\n    }\n\n    public String getLvl()\n    {\n        return lvl;\n    }\n\n    public void setLvl(String lvl)\n    {\n        this.lvl = lvl;\n    }\n\n    public Timestamp getNnow()\n    {\n        return nnow;\n    }\n\n    public void setNnow(Timestamp nnow)\n    {\n        this.nnow = nnow;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/LoggingConfigurationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift.cql;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author impadmin\n * \n */\npublic class LoggingConfigurationTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        Map propertyMap = new HashMap();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        emf = Persistence.createEntityManagerFactory(\"twissandraTest\", propertyMap);\n        em = emf.createEntityManager();\n\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void test()\n    {\n        LoggingConfiguration lc = new LoggingConfiguration();\n        lc.setId(\"lc1\");\n        lc.setLable(\"one\");\n        lc.setLongName(\"first lc\");\n\n        LoggingConfiguration lc1 = new LoggingConfiguration();\n        lc1.setId(\"lc2\");\n        lc1.setLable(\"two\");\n        lc1.setLongName(\"second lc\");\n\n        em.persist(lc);\n        em.persist(lc1);\n\n        em.clear();\n\n        em.createNativeQuery(\n                \"insert into \\\"LoggingConfiguration\\\" (id,label,logname,nnow) values ('1','one','first lc','now')\",\n                LoggingConfiguration.class).executeUpdate();\n        em.createNativeQuery(\n                \"insert into \\\"LoggingConfiguration\\\" (id,label,logname,nnow) values ('2','two','second log','now')\",\n                LoggingConfiguration.class).executeUpdate();\n\n        Query query = em.createQuery(\"SELECT lc FROM LoggingConfiguration lc WHERE lc.logname = :logname\",\n                LoggingConfiguration.class);\n        query.setParameter(\"logname\", \"first lc\");\n        List<LoggingConfiguration> matchingConfigurations = query.getResultList();\n\n        int count = 0;\n        Assert.assertNotNull(matchingConfigurations);\n        for (LoggingConfiguration configuration : matchingConfigurations)\n        {\n            if (configuration.getId().equals(\"1\"))\n            {\n                Assert.assertNotNull(configuration.getNnow());\n                Assert.assertEquals(\"one\", configuration.getLable());\n                Assert.assertEquals(\"first lc\", configuration.getLongName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(configuration.getNnow());\n                Assert.assertEquals(\"one\", configuration.getLable());\n                Assert.assertEquals(\"lc1\", configuration.getId());\n                Assert.assertEquals(\"first lc\", configuration.getLongName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        matchingConfigurations = em.createNativeQuery(\"SELECT * FROM \\\"LoggingConfiguration\\\"\",\n                LoggingConfiguration.class).getResultList();\n        Assert.assertNotNull(matchingConfigurations);\n        for (LoggingConfiguration configuration : matchingConfigurations)\n        {\n            if (configuration.getId().equals(\"1\"))\n            {\n                Assert.assertNotNull(configuration.getNnow());\n                Assert.assertEquals(\"one\", configuration.getLable());\n                Assert.assertEquals(\"first lc\", configuration.getLongName());\n                count++;\n            }\n            else if (configuration.getId().equals(\"2\"))\n            {\n                Assert.assertNotNull(configuration.getNnow());\n                Assert.assertEquals(\"two\", configuration.getLable());\n                Assert.assertEquals(\"second log\", configuration.getLongName());\n                count++;\n            }\n            else if (configuration.getId().equals(\"lc1\"))\n            {\n                Assert.assertNull(configuration.getNnow());\n                Assert.assertEquals(\"one\", configuration.getLable());\n                Assert.assertEquals(\"lc1\", configuration.getId());\n                Assert.assertEquals(\"first lc\", configuration.getLongName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(configuration.getNnow());\n                Assert.assertEquals(\"two\", configuration.getLable());\n                Assert.assertEquals(\"lc2\", configuration.getId());\n                Assert.assertEquals(\"second lc\", configuration.getLongName());\n                count++;\n            }\n        }\n        Assert.assertEquals(6, count);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/OTMCRUDCQLTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift.cql;\n\nimport java.util.HashMap;\n\nimport org.junit.After;\nimport org.junit.Before;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.crud.OTMCRUDTest;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic class OTMCRUDCQLTest extends OTMCRUDTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        propertyMap = new HashMap();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        super.setUp();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/PersonCassandraCQLTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift.cql;\n\nimport java.util.HashMap;\n\nimport org.junit.After;\nimport org.junit.Before;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class PersonCassandraCQLTest extends com.impetus.client.crud.PersonCassandraTest\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        propertyMap = new HashMap();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        AUTO_MANAGE_SCHEMA = true;\n        USE_CQL = true;\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/SecondaryTableCqlEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift.cql;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.SecondaryTable;\nimport javax.persistence.Table;\n\n/**\n * \n * @author Kuldeep.Mishra\n *\n */\n@Table(name = \"PRIMARY_TABLE\")\n@SecondaryTable(name = \"SECONDARY_TABLE\")\n@Entity\npublic class SecondaryTableCqlEntity\n{\n    @Id\n    @Column(name = \"OBJECT_ID\")\n    private String objectId;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    @Column(name = \"AGE\", table = \"SECONDARY_TABLE\")\n    private int age;\n\n    public String getObjectId()\n    {\n        return objectId;\n    }\n\n    public void setObjectId(String objectId)\n    {\n        this.objectId = objectId;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/StudentCassandraCQLTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift.cql;\n\nimport java.util.HashMap;\n\nimport org.junit.After;\nimport org.junit.Before;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.crud.datatypes.StudentCassandraTest;\nimport com.impetus.kundera.PersistenceProperties;\n\n/**\n * \n * @author Kuldeep.Mishra\n *\n */\npublic class StudentCassandraCQLTest extends StudentCassandraTest\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        propertyMap = new HashMap();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        AUTO_MANAGE_SCHEMA = false;\n        cqlEnabled = true;\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/SuperCountersTestOnCql.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift.cql;\n\nimport org.junit.After;\nimport org.junit.Before;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.crud.countercolumns.SuperCountersTest;\nimport com.impetus.kundera.PersistenceProperties;\n\n/**\n * \n * @author Kuldeep.Mishra\n *\n */\npublic class SuperCountersTestOnCql extends SuperCountersTest\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/cql/UserInformation.java",
    "content": "package com.impetus.client.cassandra.thrift.cql;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"USER\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class UserInformation\n{\n    @Id\n    private int id;\n\n    @Column\n    private String name;\n\n    @Column\n    private int age;\n\n    public int getId()\n    {\n        return id;\n    }\n\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/entities/AddressMToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"ADDRESSM2M\", schema = \"KunderaExamples@thriftClientTest\")\npublic class AddressMToM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/thrift/entities/PersonMToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.thrift.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"PERSONM2M\", schema = \"KunderaExamples@thriftClientTest\")\npublic class PersonMToM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"PERSON_ADDRESS\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Set<AddressMToM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressMToM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressMToM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/udt/Address.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n /*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * The Class Address.\n */\n@Embeddable\npublic class Address\n{\n    \n    /** The street. */\n    @Column(name = \"street\")\n    private String street;\n\n    /** The city. */\n    @Column(name = \"city\")\n    private String city;\n\n    /** The pin. */\n    @Column(name = \"pin\")\n    private String pin;\n\n    /**\n     * Instantiates a new address.\n     */\n    public Address()\n    {\n\n    }\n\n    /**\n     * Gets the street.\n     *\n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     *\n     * @param street the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    /**\n     * Gets the city.\n     *\n     * @return the city\n     */\n    public String getCity()\n    {\n        return city;\n    }\n\n    /**\n     * Sets the city.\n     *\n     * @param city the new city\n     */\n    public void setCity(String city)\n    {\n        this.city = city;\n    }\n\n    /**\n     * Gets the pin.\n     *\n     * @return the pin\n     */\n    public String getPin()\n    {\n        return pin;\n    }\n\n    /**\n     * Sets the pin.\n     *\n     * @param pin the new pin\n     */\n    public void setPin(String pin)\n    {\n        this.pin = pin;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/udt/Fullname.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n /*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * The Class Fullname.\n */\n@Embeddable\npublic class Fullname\n{\n    \n    /** The first name. */\n    @Column\n    private String firstName;\n\n    /** The middle name. */\n    @Column\n    private String middleName;\n\n    /** The last name. */\n    @Column\n    private String lastName;\n\n    /**\n     * Instantiates a new fullname.\n     */\n    public Fullname()\n    {\n\n    }\n\n    /**\n     * Gets the first name.\n     *\n     * @return the first name\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * Sets the first name.\n     *\n     * @param firstName the new first name\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * Gets the middle name.\n     *\n     * @return the middle name\n     */\n    public String getMiddleName()\n    {\n        return middleName;\n    }\n\n    /**\n     * Sets the middle name.\n     *\n     * @param middleName the new middle name\n     */\n    public void setMiddleName(String middleName)\n    {\n        this.middleName = middleName;\n    }\n\n    /**\n     * Gets the last name.\n     *\n     * @return the last name\n     */\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    /**\n     * Sets the last name.\n     *\n     * @param lastName the new last name\n     */\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/udt/PersonUDT.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n /*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class PersonUDT.\n */\n@Entity\n@Table(name = \"person_udt\", schema = \"UdtTest@cassandra_udt\")\n@IndexCollection(columns = { @Index(name = \"nicknames\"), @Index(name = \"email\"), @Index(name = \"password\") })\npublic class PersonUDT\n{\n\n    /** The person id. */\n    @Id\n    @Column\n    private String personId;\n\n    /** The personal details. */\n    @Embedded\n    private PersonalDetailsUDT personalDetails;\n\n    /** The professional details. */\n    @Embedded\n    private ProfessionalDetailsUDT professionalDetails;\n\n    /** The email. */\n    @Column\n    private String email;\n\n    /** The password. */\n    @Column\n    private String password;\n\n    /** The nicknames. */\n    @Column\n    private List<String> nicknames;\n    \n    /** The list profs. */\n    @ElementCollection\n    private List<ProfessionalDetailsUDT> listProfs;\n    \n    /** The set profs. */\n    @ElementCollection\n    private Set<ProfessionalDetailsUDT> setProfs;\n    \n    /** The map profs key. */\n    @ElementCollection\n    private Map<String, ProfessionalDetailsUDT> mapProfsKey;\n    \n    \n    /**\n     * Gets the sets the profs.\n     *\n     * @return the sets the profs\n     */\n    public Set<ProfessionalDetailsUDT> getSetProfs()\n    {\n        return setProfs;\n    }\n\n    /**\n     * Sets the sets the profs.\n     *\n     * @param setProfs the new sets the profs\n     */\n    public void setSetProfs(Set<ProfessionalDetailsUDT> setProfs)\n    {\n        this.setProfs = setProfs;\n    }\n\n    /**\n     * Gets the map profs key.\n     *\n     * @return the map profs key\n     */\n    public Map<String, ProfessionalDetailsUDT> getMapProfsKey()\n    {\n        return mapProfsKey;\n    }\n\n    /**\n     * Sets the map profs key.\n     *\n     * @param mapProfsKey the map profs key\n     */\n    public void setMapProfsKey(Map<String, ProfessionalDetailsUDT> mapProfsKey)\n    {\n        this.mapProfsKey = mapProfsKey;\n    }\n\n//    public Map<Fullname, ProfessionalDetailsUDT> getMapProfsBoth()\n//    {\n//        return mapProfsBoth;\n//    }\n//\n//    public void setMapProfsBoth(Map<Fullname, ProfessionalDetailsUDT> mapProfsBoth)\n//    {\n//        this.mapProfsBoth = mapProfsBoth;\n//    }\n\n//    public Map<ProfessionalDetailsUDT, Integer> getMapProfsValue()\n//    {\n//        return mapProfsValue;\n//    }\n//\n//    public void setMapProfsValue(Map<ProfessionalDetailsUDT, Integer> mapProfsValue)\n//    {\n//        this.mapProfsValue = mapProfsValue;\n//    }\n//\n//    @ElementCollection\n//    private Map<ProfessionalDetailsUDT, Integer> mapProfsValue;\n\n    \n    /**\n * Gets the list profs.\n *\n * @return the list profs\n */\npublic List<ProfessionalDetailsUDT> getListProfs()\n    {\n        return listProfs;\n    }\n\n    /**\n     * Sets the list profs.\n     *\n     * @param listProfs the new list profs\n     */\n    public void setListProfs(List<ProfessionalDetailsUDT> listProfs)\n    {\n        this.listProfs = listProfs;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the personal details.\n     * \n     * @return the personal details\n     */\n    public PersonalDetailsUDT getPersonalDetails()\n    {\n        return personalDetails;\n    }\n\n    /**\n     * Sets the personal details.\n     * \n     * @param personalDetails\n     *            the new personal details\n     */\n    public void setPersonalDetails(PersonalDetailsUDT personalDetails)\n    {\n        this.personalDetails = personalDetails;\n    }\n\n    /**\n     * Gets the professional details.\n     * \n     * @return the professional details\n     */\n    public ProfessionalDetailsUDT getProfessionalDetails()\n    {\n        return professionalDetails;\n    }\n\n    /**\n     * Sets the professional details.\n     * \n     * @param professionalDetails\n     *            the new professional details\n     */\n    public void setProfessionalDetails(ProfessionalDetailsUDT professionalDetails)\n    {\n        this.professionalDetails = professionalDetails;\n    }\n\n    /**\n     * Gets the email.\n     * \n     * @return the email\n     */\n    public String getEmail()\n    {\n        return email;\n    }\n\n    /**\n     * Sets the email.\n     * \n     * @param email\n     *            the new email\n     */\n    public void setEmail(String email)\n    {\n        this.email = email;\n    }\n\n    /**\n     * Gets the password.\n     * \n     * @return the password\n     */\n    public String getPassword()\n    {\n        return password;\n    }\n\n    /**\n     * Sets the password.\n     * \n     * @param password\n     *            the new password\n     */\n    public void setPassword(String password)\n    {\n        this.password = password;\n    }\n\n    /**\n     * Gets the nicknames.\n     * \n     * @return the nicknames\n     */\n    public List<String> getNicknames()\n    {\n        return nicknames;\n    }\n\n    /**\n     * Sets the nicknames.\n     * \n     * @param nicknames\n     *            the new nicknames\n     */\n    public void setNicknames(List<String> nicknames)\n    {\n        this.nicknames = nicknames;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/udt/PersonalDetailsUDT.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n /*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Embedded;\n\n/**\n * The Class PersonalDetailsUDT.\n */\n@Embeddable\npublic class PersonalDetailsUDT\n{\n\n    /** The fullname. */\n    @Embedded\n    private Fullname fullname;\n\n    /** The addresses. */\n    @ElementCollection\n    private Map<String, Address> addresses;\n\n    /** The phones. */\n    @ElementCollection\n    private List<Phone> phones;\n    \n    /** The spouses. */\n    @ElementCollection\n    private Set<Spouse> spouses;\n\n    /**\n     * Gets the fullname.\n     *\n     * @return the fullname\n     */\n    public Fullname getFullname()\n    {\n        return fullname;\n    }\n\n    /**\n     * Sets the fullname.\n     *\n     * @param fullname the new fullname\n     */\n    public void setFullname(Fullname fullname)\n    {\n        this.fullname = fullname;\n    }\n\n    /**\n     * Gets the addresses.\n     *\n     * @return the addresses\n     */\n    public Map<String, Address> getAddresses()\n    {\n        return addresses;\n    }\n\n    /**\n     * Sets the addresses.\n     *\n     * @param addresses the addresses\n     */\n    public void setAddresses(Map<String, Address> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n    /**\n     * Gets the phones.\n     *\n     * @return the phones\n     */\n    public List<Phone> getPhones()\n    {\n        return phones;\n    }\n\n    /**\n     * Sets the phones.\n     *\n     * @param phones the new phones\n     */\n    public void setPhones(List<Phone> phones)\n    {\n        this.phones = phones;\n    }\n\n    /**\n     * Gets the spouses.\n     *\n     * @return the spouses\n     */\n    public Set<Spouse> getSpouses()\n    {\n        return spouses;\n    }\n\n    /**\n     * Sets the spouses.\n     *\n     * @param spouses the new spouses\n     */\n    public void setSpouses(Set<Spouse> spouses)\n    {\n        this.spouses = spouses;\n    }\n    \n    \n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/udt/Phone.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n /*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n// TODO: Auto-generated Javadoc\n/**\n * The Class Phone.\n */\n@Embeddable\npublic class Phone\n{\n    \n    /** The number. */\n    @Column\n    private String number;\n\n     /** The tags. */\n     @Column\n     private Set<String> tags;\n\n    /**\n     * Instantiates a new phone.\n     */\n    public Phone()\n    {\n\n    }\n\n    /**\n     * Gets the number.\n     *\n     * @return the number\n     */\n    public String getNumber()\n    {\n        return number;\n    }\n\n    /**\n     * Sets the number.\n     *\n     * @param number the new number\n     */\n    public void setNumber(String number)\n    {\n        this.number = number;\n    }\n\n     /**\n      * Gets the tags.\n      *\n      * @return the tags\n      */\n     public Set<String> getTags()\n     {\n     return tags;\n     }\n    \n     /**\n      * Sets the tags.\n      *\n      * @param tags the new tags\n      */\n     public void setTags(Set<String> tags)\n     {\n     this.tags = tags;\n     }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/udt/ProfessionalDetailsUDT.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n/*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * The Class ProfessionalDetailsUDT.\n */\n@Embeddable\npublic class ProfessionalDetailsUDT\n{\n\n    /** The company. */\n    @Column\n    private String company;\n\n    /** The project. */\n    @Column\n    private List<Integer> extentions;\n\n    /** The colleagues. */\n    @Column\n    private Set<String> colleagues;\n\n    /** The projects. */\n    @Column\n    private Map<Integer, String> projects;\n\n    /** The grade. */\n    @Column\n    private String grade;\n\n    /** The monthly salary. */\n    @Column\n    private Double monthlySalary;\n\n    /**\n     * Gets the company.\n     * \n     * @return the company\n     */\n    public String getCompany()\n    {\n        return company;\n    }\n\n    /**\n     * Sets the company.\n     * \n     * @param company\n     *            the new company\n     */\n    public void setCompany(String company)\n    {\n        this.company = company;\n    }\n\n    /**\n     * Gets the extentions.\n     * \n     * @return the extentions\n     */\n    public List<Integer> getExtentions()\n    {\n        return extentions;\n    }\n\n    /**\n     * Sets the extentions.\n     * \n     * @param extentions\n     *            the new extentions\n     */\n    public void setExtentions(List<Integer> extentions)\n    {\n        this.extentions = extentions;\n    }\n\n    /**\n     * Gets the colleagues.\n     * \n     * @return the colleagues\n     */\n    public Set<String> getColleagues()\n    {\n        return colleagues;\n    }\n\n    /**\n     * Sets the colleagues.\n     * \n     * @param colleagues\n     *            the new colleagues\n     */\n    public void setColleagues(Set<String> colleagues)\n    {\n        this.colleagues = colleagues;\n    }\n\n    /**\n     * Gets the projects.\n     * \n     * @return the projects\n     */\n    public Map<Integer, String> getProjects()\n    {\n        return projects;\n    }\n\n    /**\n     * Sets the projects.\n     * \n     * @param projects\n     *            the projects\n     */\n    public void setProjects(Map<Integer, String> projects)\n    {\n        this.projects = projects;\n    }\n\n    /**\n     * Gets the grade.\n     * \n     * @return the grade\n     */\n    public String getGrade()\n    {\n        return grade;\n    }\n\n    /**\n     * Sets the grade.\n     * \n     * @param grade\n     *            the new grade\n     */\n    public void setGrade(String grade)\n    {\n        this.grade = grade;\n    }\n\n    /**\n     * Gets the monthly salary.\n     * \n     * @return the monthly salary\n     */\n    public Double getMonthlySalary()\n    {\n        return monthlySalary;\n    }\n\n    /**\n     * Sets the monthly salary.\n     * \n     * @param monthlySalary\n     *            the new monthly salary\n     */\n    public void setMonthlySalary(Double monthlySalary)\n    {\n        this.monthlySalary = monthlySalary;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/udt/Spouse.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n /*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Embedded;\n\n/**\n * The Class Spouse.\n */\n@Embeddable\npublic class Spouse\n{\n\n    /** The fullname. */\n    @Embedded\n    private Fullname fullname;\n\n    /** The maiden name. */\n    @Column\n    private String maidenName;\n\n    /** The age. */\n    @Column\n    private int age;\n\n    /**\n     * Instantiates a new spouse.\n     */\n    public Spouse()\n    {\n\n    }\n\n    /**\n     * Gets the fullname.\n     *\n     * @return the fullname\n     */\n    public Fullname getFullname()\n    {\n        return fullname;\n    }\n\n    /**\n     * Sets the fullname.\n     *\n     * @param fullname the new fullname\n     */\n    public void setFullname(Fullname fullname)\n    {\n        this.fullname = fullname;\n    }\n\n    /**\n     * Gets the maiden name.\n     *\n     * @return the maiden name\n     */\n    public String getMaidenName()\n    {\n        return maidenName;\n    }\n\n    /**\n     * Sets the maiden name.\n     *\n     * @param maidenName the new maiden name\n     */\n    public void setMaidenName(String maidenName)\n    {\n        this.maidenName = maidenName;\n    }\n\n    /**\n     * Gets the age.\n     *\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     *\n     * @param age the new age\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/udt/UdtAsEmbeddablesCRUDTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n/*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * The Class UdtAsEmbeddablesCRUDTest.\n */\npublic class UdtAsEmbeddablesCRUDTest\n{\n\n    /** The Constant PU. */\n    private static final String PU = \"cassandra_udt\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager entityManager;\n\n    /** The property map. */\n    protected static Map propertyMap = null;\n\n    /** The auto manage schema. */\n    protected boolean AUTO_MANAGE_SCHEMA = true;\n\n    \n    \n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n\n        emf = Persistence.createEntityManagerFactory(PU, propertyMap);\n\n    }\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n       \n        entityManager = emf.createEntityManager();\n\n    }\n\n    /**\n     * On insert cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onInsert() throws Exception\n    {\n        Object p1 = prepareDataLevel1();\n        Object p2 = prepareDataLevel2();\n        Object p3 = prepareDataLevel3();\n        Object p4 = prepareDataLevel4();\n\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        entityManager.persist(p4);\n        entityManager.clear();\n\n        PersonUDT f1 = entityManager.find(PersonUDT.class, \"1\");\n        PersonUDT f2 = entityManager.find(PersonUDT.class, \"2\");\n        PersonUDT f3 = entityManager.find(PersonUDT.class, \"3\");\n        PersonUDT f4 = entityManager.find(PersonUDT.class, \"4\");\n\n        Assert.assertNotNull(f1);\n        Assert.assertNotNull(f2);\n        Assert.assertNotNull(f3);\n        Assert.assertNotNull(f4);\n\n    }\n\n\n    /**\n     * On delete.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onDelete() throws Exception\n    {\n        Object p1 = prepareDataLevel1();\n        Object p2 = prepareDataLevel2();\n        Object p3 = prepareDataLevel3();\n        Object p4 = prepareDataLevel4();\n\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        entityManager.persist(p4);\n        entityManager.clear();\n\n        PersonUDT beforeDelete1 = entityManager.find(PersonUDT.class, \"2\");\n        PersonUDT beforeDelete2 = entityManager.find(PersonUDT.class, \"4\");\n        Assert.assertNotNull(beforeDelete1);\n        Assert.assertNotNull(beforeDelete2);\n\n        entityManager.remove(beforeDelete1);\n        entityManager.remove(beforeDelete2);\n        entityManager.clear();\n\n        PersonUDT after1 = entityManager.find(PersonUDT.class, \"2\");\n        PersonUDT after2 = entityManager.find(PersonUDT.class, \"4\");\n\n        Assert.assertNull(after1);\n        Assert.assertNull(after2);\n\n    }\n\n    /**\n     * On merge.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onMerge() throws Exception\n    {\n        Object p1 = prepareDataLevel1();\n        Object p2 = prepareDataLevel2();\n        Object p3 = prepareDataLevel3();\n        Object p4 = prepareDataLevel4();\n\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        entityManager.persist(p4);\n        entityManager.clear();\n\n        PersonUDT beforeMerge = entityManager.find(PersonUDT.class, \"3\");\n\n        Assert.assertEquals(beforeMerge.getPassword(), ((PersonUDT) p3).getPassword());\n        beforeMerge.setPassword(\"qwerty\");\n        beforeMerge.getNicknames().add(\"nick added\");\n        beforeMerge.setNicknames(beforeMerge.getNicknames());\n        entityManager.merge(beforeMerge);\n        entityManager.clear();\n\n        PersonUDT afterMerge = entityManager.find(PersonUDT.class, \"3\");\n\n        Assert.assertNotNull(afterMerge);\n        Assert.assertEquals(\"qwerty\", afterMerge.getPassword());\n        Assert.assertEquals(\"nick added\", afterMerge.getNicknames().get(1));\n\n    }\n\n    /**\n     * On find.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onFind() throws Exception\n    {\n        Object p1 = prepareDataLevel1();\n        Object p2 = prepareDataLevel2();\n        Object p3 = prepareDataLevel3();\n        Object p4 = prepareDataLevel4();\n\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        entityManager.persist(p4);\n        entityManager.clear();\n\n        PersonUDT f1 = entityManager.find(PersonUDT.class, \"1\");\n        PersonUDT f2 = entityManager.find(PersonUDT.class, \"2\");\n        PersonUDT f3 = entityManager.find(PersonUDT.class, \"3\");\n        PersonUDT f4 = entityManager.find(PersonUDT.class, \"4\");\n\n        Assert.assertNotNull(f1);\n        Assert.assertNotNull(f2);\n        Assert.assertNotNull(f3);\n        Assert.assertNotNull(f4);\n\n        assertEntity((PersonUDT) p1, f1);\n        assertEntity((PersonUDT) p2, f2);\n        assertEntity((PersonUDT) p3, f3);\n        assertEntity((PersonUDT) p4, f4);\n\n    }\n\n    /**\n     * On embeddable merge.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onEmbeddableMerge() throws Exception\n    {\n        Object p1 = prepareDataLevel1();\n\n        entityManager.persist(p1);\n        entityManager.clear();\n\n        PersonUDT beforeMerge = entityManager.find(PersonUDT.class, \"1\");\n        entityManager.clear();\n        Assert.assertEquals(beforeMerge.getPassword(), ((PersonUDT) p1).getPassword());\n        beforeMerge.setPassword(\"qwerty\");\n        beforeMerge.getNicknames().add(\"nick added\");\n        beforeMerge.setNicknames(beforeMerge.getNicknames());\n        PersonalDetailsUDT personalDetails = loadPersonalDetails(\"devender\", \"yadav\");\n        beforeMerge.setPersonalDetails(personalDetails);\n        entityManager.merge(beforeMerge);\n        entityManager.clear();\n\n        PersonUDT afterMerge = entityManager.find(PersonUDT.class, \"1\");\n\n        Assert.assertNotNull(afterMerge);\n        Assert.assertEquals(\"qwerty\", afterMerge.getPassword());\n        Assert.assertEquals(\"nick added\", afterMerge.getNicknames().get(2));\n        Assert.assertEquals(\"devender\", afterMerge.getPersonalDetails().getFullname().getFirstName());\n        Assert.assertEquals(\"yadav\", afterMerge.getPersonalDetails().getFullname().getLastName());\n\n    }\n\n    /**\n     * On select all query.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onSelectAllQuery() throws Exception\n    {\n        Object p1 = prepareDataLevel1();\n        Object p2 = prepareDataLevel2();\n        Object p3 = prepareDataLevel3();\n        Object p4 = prepareDataLevel4();\n\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        entityManager.persist(p4);\n        entityManager.clear();\n\n        PersonUDT f1 = null;\n        PersonUDT f2 = null;\n        PersonUDT f3 = null;\n        PersonUDT f4 = null;\n\n        Query query = entityManager.createQuery(\"Select t from PersonUDT t\");\n\n        List<PersonUDT> results = query.getResultList();\n        Iterator<PersonUDT> i = results.iterator();\n        while (i.hasNext())\n        {\n            PersonUDT t = (PersonUDT) i.next();\n            if (t.getPersonId().equals(\"1\"))\n            {\n                f1 = t;\n            }\n            if (t.getPersonId().equals(\"2\"))\n            {\n                f2 = t;\n            }\n            if (t.getPersonId().equals(\"3\"))\n            {\n                f3 = t;\n            }\n            if (t.getPersonId().equals(\"4\"))\n            {\n                f4 = t;\n            }\n        }\n\n        Assert.assertNotNull(f1);\n        Assert.assertNotNull(f2);\n        Assert.assertNotNull(f3);\n        Assert.assertNotNull(f4);\n\n        assertEntity((PersonUDT) p1, f1);\n        assertEntity((PersonUDT) p2, f2);\n        assertEntity((PersonUDT) p3, f3);\n        assertEntity((PersonUDT) p4, f4);\n\n    }\n\n    /**\n     * On select by id query.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onSelectByIdQuery() throws Exception\n    {\n        Object p3 = prepareDataLevel3();\n\n        entityManager.persist(p3);\n        entityManager.clear();\n\n        Query query = entityManager.createQuery(\"Select t from PersonUDT t where t.personId = 3\");\n\n        List<PersonUDT> results = query.getResultList();\n\n        Assert.assertNotNull(results.get(0));\n\n        PersonUDT f3 = results.get(0);\n\n        Assert.assertNotNull(f3);\n\n        assertEntity((PersonUDT) p3, f3);\n\n    }\n\n    /**\n     * On collection indexes.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onCollectionIndexes() throws Exception\n    {\n        Object p3 = prepareDataLevel3();\n\n        entityManager.persist(p3);\n        entityManager.clear();\n\n        Query query = entityManager.createQuery(\"Select t from PersonUDT t where t.nicknames = 'dev'\");\n\n        List<PersonUDT> results = query.getResultList();\n\n        Assert.assertNotNull(results.get(0));\n\n        PersonUDT f3 = results.get(0);\n\n        Assert.assertNotNull(f3);\n\n        assertEntity((PersonUDT) p3, f3);\n\n    }\n\n    /**\n     * Assert entity.\n     * \n     * @param expected\n     *            the expected entity\n     * @param actual\n     *            the actual entity\n     */\n    private void assertEntity(PersonUDT expected, PersonUDT actual)\n    {\n        Assert.assertEquals(expected.getEmail(), actual.getEmail());\n        Assert.assertEquals(expected.getPassword(), actual.getPassword());\n        Assert.assertEquals(expected.getPersonId(), actual.getPersonId());\n        Assert.assertEquals(expected.getNicknames(), actual.getNicknames());\n        Assert.assertEquals(expected.getPersonalDetails().getFullname().getFirstName(), actual.getPersonalDetails()\n                .getFullname().getFirstName());\n        Assert.assertEquals(expected.getPersonalDetails().getFullname().getLastName(), actual.getPersonalDetails()\n                .getFullname().getLastName());\n        assertPersonalDetails(expected.getPersonalDetails(), actual.getPersonalDetails());\n        assertProfessionalDetails(expected.getProfessionalDetails(), actual.getProfessionalDetails());\n        //assert collection data\n        assertProfessionalDetails(expected.getListProfs().get(0), actual.getListProfs().get(0));\n        assertProfessionalDetails(expected.getMapProfsKey().get(\"karthik\"), actual.getMapProfsKey().get(\"karthik\"));\n        assertProfessionalDetails(expected.getMapProfsKey().get(\"pragalbh\"), actual.getMapProfsKey().get(\"pragalbh\"));\n        assertProfessionalDetails(expected.getSetProfs().iterator().next(), actual.getSetProfs().iterator().next());\n    }\n\n    /**\n     * Assert personal details.\n     *\n     * @param expected the expected\n     * @param actual the actual\n     */\n    private void assertPersonalDetails(PersonalDetailsUDT expected, PersonalDetailsUDT actual)\n    {\n        Assert.assertEquals(expected.getAddresses().get(\"Office\").getStreet(), actual.getAddresses().get(\"Office\").getStreet());\n        Assert.assertEquals(expected.getAddresses().get(\"Home\").getPin(), actual.getAddresses().get(\"Home\").getPin());\n        Assert.assertEquals(expected.getPhones().get(0).getNumber(), actual.getPhones().get(0).getNumber());\n        Assert.assertEquals(expected.getPhones().get(0).getTags(), actual.getPhones().get(0).getTags());\n        Assert.assertEquals(expected.getSpouses().iterator().next().getMaidenName(), actual.getSpouses().iterator().next().getMaidenName());\n    }\n\n    /**\n     * Assert professional details.\n     *\n     * @param expected the expected\n     * @param actual the actual\n     */\n    private void assertProfessionalDetails(ProfessionalDetailsUDT expected,\n            ProfessionalDetailsUDT actual)\n    {\n        Assert.assertEquals(expected.getCompany(), actual.getCompany());\n        Assert.assertEquals(expected.getGrade(), actual.getGrade());\n        Assert.assertEquals(expected.getMonthlySalary(), actual.getMonthlySalary());\n        // assert collection data\n        Assert.assertEquals(expected.getProjects().get(0), actual.getProjects().get(0));\n        Assert.assertEquals(expected.getProjects().get(1), actual.getProjects().get(1));\n        Assert.assertEquals(true, expected.getColleagues().containsAll(actual.getColleagues()));\n        Assert.assertEquals(expected.getExtentions().get(0), actual.getExtentions().get(0));\n        Assert.assertEquals(expected.getExtentions().get(1), actual.getExtentions().get(1));\n        \n    }\n\n    /**\n     * Prepare data level3.\n     * \n     * @return the object\n     */\n    private Object prepareDataLevel3()\n    {\n        PersonUDT personUDT = new PersonUDT();\n        personUDT.setPersonId(\"3\");\n        personUDT.setEmail(\"devender@impetus.com\");\n        List<String> nicknames = new ArrayList<String>();\n        nicknames.add(\"dev\");\n        personUDT.setNicknames(nicknames);\n        personUDT.setPassword(\"impetus\");\n        PersonalDetailsUDT personalDetails = loadPersonalDetails(\"devender\", \"yadav\");\n        personUDT.setPersonalDetails(personalDetails);\n        ProfessionalDetailsUDT professionalDetails = loadProfessionalDetails();\n        personUDT.setProfessionalDetails(professionalDetails);\n        prepareCollectionData(personUDT);\n\n        return personUDT;\n    }\n\n    /**\n     * Prepare data level4.\n     * \n     * @return the object\n     */\n    private Object prepareDataLevel4()\n    {\n        PersonUDT personUDT = new PersonUDT();\n        personUDT.setPersonId(\"4\");\n        personUDT.setEmail(\"devender@impetus.com\");\n        List<String> nicknames = new ArrayList<String>();\n        nicknames.add(\"rockstar\");\n        personUDT.setNicknames(nicknames);\n        personUDT.setPassword(\"impetus\");\n        PersonalDetailsUDT personalDetails = loadPersonalDetails(\"amit\", \"kumar\");\n        personUDT.setPersonalDetails(personalDetails);\n        ProfessionalDetailsUDT professionalDetails = loadProfessionalDetails();\n        personUDT.setProfessionalDetails(professionalDetails);\n        prepareCollectionData(personUDT);\n\n        return personUDT;\n    }\n\n    /**\n     * Prepare data level2.\n     * \n     * @return the object\n     */\n    private Object prepareDataLevel2()\n    {\n        PersonUDT personUDT = new PersonUDT();\n        personUDT.setPersonId(\"2\");\n        personUDT.setEmail(\"pragalbh@impetus.com\");\n        List<String> nicknames = new ArrayList<String>();\n        nicknames.add(\"articuno\");\n        nicknames.add(\"PG\");\n        personUDT.setNicknames(nicknames);\n        personUDT.setPassword(\"impetus\");\n        PersonalDetailsUDT personalDetails = loadPersonalDetails(\"pragalbh\", \"garg\");\n        personUDT.setPersonalDetails(personalDetails);\n        ProfessionalDetailsUDT professionalDetails = loadProfessionalDetails();\n        personUDT.setProfessionalDetails(professionalDetails);\n        List<ProfessionalDetailsUDT> listProfs = new ArrayList<ProfessionalDetailsUDT>();\n        listProfs.add(professionalDetails);\n        listProfs.add(professionalDetails);\n        personUDT.setListProfs(listProfs);\n        prepareCollectionData(personUDT);\n\n        return personUDT;\n    }\n\n    /**\n     * Prepare data level1.\n     * \n     * @return the object\n     */\n    private Object prepareDataLevel1()\n    {\n        PersonUDT personUDT = new PersonUDT();\n        personUDT.setPersonId(\"1\");\n        personUDT.setEmail(\"karthik@impetus.com\");\n        List<String> nicknames = new ArrayList<String>();\n        nicknames.add(\"tango\");\n        nicknames.add(\"kar\");\n        personUDT.setNicknames(nicknames);\n        personUDT.setPassword(\"impetus\");\n        PersonalDetailsUDT personalDetails = loadPersonalDetails(\"karthik\", \"manchala\");\n        personUDT.setPersonalDetails(personalDetails);\n        ProfessionalDetailsUDT professionalDetails = loadProfessionalDetails();\n        personUDT.setProfessionalDetails(professionalDetails);\n        // set collections\n        prepareCollectionData(personUDT);\n\n        return personUDT;\n    }\n\n    /**\n     * Prepare collection data.\n     *\n     * @param personUDT the person udt\n     */\n    private void prepareCollectionData(PersonUDT personUDT)\n    {\n        ProfessionalDetailsUDT professionalDetails = loadProfessionalDetails();\n\n        List<ProfessionalDetailsUDT> listProfs = new ArrayList<ProfessionalDetailsUDT>();\n        listProfs.add(professionalDetails);\n        personUDT.setListProfs(listProfs);\n\n        Map<String, ProfessionalDetailsUDT> mapProfsKey = new HashMap<String, ProfessionalDetailsUDT>();\n        mapProfsKey.put(\"pragalbh\", professionalDetails);\n        mapProfsKey.put(\"karthik\", professionalDetails);\n        personUDT.setMapProfsKey(mapProfsKey);\n\n        Set<ProfessionalDetailsUDT> setProfs = new HashSet<ProfessionalDetailsUDT>();\n        setProfs.add(professionalDetails);\n        setProfs.add(professionalDetails);\n        personUDT.setSetProfs(setProfs);\n    }\n\n    /**\n     * Load professional details.\n     * \n     * @return the professional details udt\n     */\n    private ProfessionalDetailsUDT loadProfessionalDetails()\n    {\n        Map<Integer, String> projects = new HashMap<Integer, String>();\n        projects.put(1111, \"iLabs\");\n        projects.put(2222, \"Kundera\");\n        List<Integer> extns = new ArrayList<Integer>();\n        extns.add(4526);\n        extns.add(2810);\n        Set<String> colleagues = new HashSet<String>();\n        colleagues.add(\"Pavan\");\n        colleagues.add(\"Gautam\");\n        ProfessionalDetailsUDT profDetails = new ProfessionalDetailsUDT();\n        profDetails.setCompany(\"impetus\");\n        profDetails.setGrade(\"g4\");\n        profDetails.setMonthlySalary((double) 12345);\n        profDetails.setProjects(projects);\n        profDetails.setColleagues(colleagues);\n        profDetails.setExtentions(extns);\n\n        return profDetails;\n    }\n\n    /**\n     * Load personal details.\n     * \n     * @param firstname\n     *            the firstname\n     * @param lastname\n     *            the lastname\n     * @return the personal details udt\n     */\n    private PersonalDetailsUDT loadPersonalDetails(String firstname, String lastname)\n    {\n        PersonalDetailsUDT personalDetails = new PersonalDetailsUDT();\n        Fullname fullname = new Fullname();\n        fullname.setFirstName(firstname);\n        fullname.setLastName(lastname);\n        personalDetails.setFullname(fullname);\n        \n        Address address = new Address();\n        address.setCity(\"indore\");\n        address.setPin(\"452001\");\n        address.setStreet(\"palasia\");\n        Map<String, Address> addresses = new HashMap<String, Address>();\n        addresses.put(\"Office\", address);\n        Address address1 = new Address();\n        address1.setCity(\"Delhi\");\n        address1.setPin(\"201301\");\n        address1.setStreet(\"NSEZ\");\n        addresses.put(\"Home\", address1);\n        personalDetails.setAddresses(addresses);\n       \n        \n        Phone phone = new Phone();\n        phone.setNumber(\"9988776655\");\n        String elements[] = { \"personal\", \"main\", \"indore\" };\n        phone.setTags(new HashSet<String>(Arrays.asList(elements)));\n        List<Phone> phoneList = new ArrayList<Phone>();\n        phoneList.add(phone);\n        personalDetails.setPhones(phoneList );\n        \n        Spouse spouse = new Spouse();\n        spouse.setAge(20);\n        Fullname spouseName = new Fullname();\n        spouseName.setFirstName(\"asdfgh\");\n        spouse.setFullname(spouseName);\n        spouse.setMaidenName(\"qrqrrte\");\n        Set<Spouse> spouses = new HashSet<Spouse>();\n        spouses.add(spouse);\n        personalDetails.setSpouses(spouses );\n\n        return personalDetails;\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        entityManager.close();\n    }\n\n    /**\n     * Tear down after class.\n     */\n    @AfterClass\n    public static void tearDownAfterClass()\n    {\n        CassandraCli.dropKeySpace(\"UdtTest\");\n        if (entityManager != null)\n        {\n            \n            entityManager = null;\n            emf.close();\n            emf = null;\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/validator/BookEntity.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Devender Yadav\n * \n */\n@Entity\n@Table(name = \"BOOK_ENTITY\", schema = \"KunderaTests@cassandra_pu\")\npublic class BookEntity\n{\n\n    @Id\n    @Column(name = \"ID\")\n    private int bookId;\n\n    @Column(name = \"TITLE\")\n    private String title;\n\n    @Column(name = \"AUTHOR\")\n    private String author;\n\n    @Column(name = \"PAGES\")\n    private int pages;\n\n    protected BookEntity()\n    {\n    }\n\n    public int getBookId()\n    {\n        return bookId;\n    }\n\n    public void setBookId(int bookId)\n    {\n        this.bookId = bookId;\n    }\n\n    public String getTitle()\n    {\n        return title;\n    }\n\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    public int getPages()\n    {\n        return pages;\n    }\n\n    public void setPages(int pages)\n    {\n        this.pages = pages;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/cassandra/validator/ConstructorValidationTest.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.validator;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\n/**\n * @author Devender Yadav\n * \n */\npublic class ConstructorValidationTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    @Test\n    public void validConstructorTest() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"cassandra_pu\");\n        em = emf.createEntityManager();\n        BookEntity book = new BookEntity();\n        book.setBookId(1);\n        book.setTitle(\"The Complete Reference\");\n        book.setAuthor(\"Herbert Schildt\");\n        book.setPages(500);\n\n        em.persist(book);\n\n        em.clear();\n\n        BookEntity book1 = em.find(BookEntity.class, 1);\n\n        Assert.assertNotNull(book1);\n        Assert.assertEquals(1, book1.getBookId());\n        Assert.assertEquals(\"The Complete Reference\", book1.getTitle());\n        Assert.assertEquals(\"Herbert Schildt\", book1.getAuthor());\n        Assert.assertEquals(500, book1.getPages());\n\n        em.remove(book1);\n\n        BookEntity book2 = em.find(BookEntity.class, 1);\n        Assert.assertNull(book2);\n\n        em.close();\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/BaseTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\nimport javax.persistence.TypedQuery;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Root;\n\nimport junit.framework.Assert;\n\nimport com.impetus.client.crud.PersonCassandra.Day;\n\n/**\n * The Class BaseTest.\n * \n * @author vivek.mishra\n */\npublic abstract class BaseTest\n{\n\n    /**\n     * Prepare data.\n     * \n     * @param rowKey\n     *            the row key\n     * @param age\n     *            the age\n     * @return the person\n     */\n    protected PersonCassandra prepareData(String rowKey, int age)\n    {\n        PersonCassandra o = new PersonCassandra();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age);\n        o.setDay(Day.thursday);\n        o.setMonth(Month.APRIL);\n        return o;\n    }\n\n    /**\n     * Find by id.\n     * \n     * @param <E>\n     *            the element type\n     * @param clazz\n     *            the clazz\n     * @param rowKey\n     *            the row key\n     * @param em\n     *            the em\n     * @return the e\n     */\n    protected <E extends Object> E findById(Class<E> clazz, Object rowKey, EntityManager em)\n    {\n        return em.find(clazz, rowKey);\n    }\n\n    /**\n     * Assert find by name.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByName(EntityManager em, Class clazz, E e, String name, String fieldName)\n    {\n\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<E> query = criteriaBuilder.createQuery(clazz);\n        Root<E> from = query.from(clazz);\n        query.select(from.alias(\"p\"));\n        query.where(criteriaBuilder.equal(from.get(fieldName), name));\n        // // find by name.\n        TypedQuery<E> q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n    }\n    \n    /**\n     * Assert find by name.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByNameWithReservedKeywords(EntityManager em, Class clazz, E e, String name, String fieldName)\n    {\n\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<E> query = criteriaBuilder.createQuery(clazz);\n        Root<E> from = query.from(clazz);\n        query.select(from.alias(\"p\"));\n        query.where(criteriaBuilder.equal(from.get(fieldName), name));\n        // // find by name.\n        TypedQuery<E> q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(1, results.size());\n    }\n\n    /**\n     * Assert find by name.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByName(EntityManager em, String clazz, E e, String name,\n            String fieldName)\n    {\n\n        String query = \"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name;\n        // // find by name.\n        Query q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n\n    }\n\n    /**\n     * Assert find by name and age.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param minVal\n     *            the min val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByNameAndAge(EntityManager em, String clazz, E e, String name,\n            String minVal, String fieldName)\n    {\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name + \" and p.age > \"\n                + minVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n    }\n\n    protected <E extends Object> void assertFindByNameAndAge(EntityManager em, Class clazz, E e, String name,\n            String minVal, String fieldName)\n    {\n\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<E> query = criteriaBuilder.createQuery(clazz);\n        Root<E> from = query.from(clazz);\n        query.select(from.alias(\"p\"));\n        query.where(criteriaBuilder.and(criteriaBuilder.equal(from.get(fieldName), name),\n                criteriaBuilder.gt((Expression) from.get(\"age\"), Integer.parseInt(minVal))));\n\n        TypedQuery<E> q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n    }\n\n    /**\n     * Assert find by name and age gt and lt.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param minVal\n     *            the min val\n     * @param maxVal\n     *            the max val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByNameAndAgeGTAndLT(EntityManager em, String clazz, E e, String name,\n            String minVal, String maxVal, String fieldName)\n    {\n        // // // find by name, age clause\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name + \" and p.age > \"\n                + minVal + \" and p.age < \" + maxVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(1, results.size());\n    }\n\n    protected <E extends Object> void assertFindByNameAndAgeGTAndLT(EntityManager em, Class clazz, E e, String name,\n            String minVal, String maxVal, String fieldName)\n    {\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<E> query = criteriaBuilder.createQuery(clazz);\n        Root<E> from = query.from(clazz);\n        query.select(from.alias(\"p\"));\n        query.where(criteriaBuilder.and(criteriaBuilder.equal(from.get(fieldName), name),\n                criteriaBuilder.gt((Expression) from.get(\"age\"), Integer.parseInt(minVal)),\n                criteriaBuilder.lt((Expression) from.get(\"age\"), Integer.parseInt(maxVal))));\n\n        // // // find by name, age clause\n        TypedQuery<E> q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(1, results.size());\n    }\n\n    /**\n     * Assert find by name and age between.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param minVal\n     *            the min val\n     * @param maxVal\n     *            the max val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByNameAndAgeBetween(EntityManager em, String clazz, E e, String name,\n            String minVal, String maxVal, String fieldName)\n    {\n        // // find by between clause\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name\n                + \" and p.age between \" + minVal + \" and \" + maxVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n\n    }\n\n    protected <E extends Object> void assertFindByNameAndAgeBetween(EntityManager em, Class clazz, E e, String name,\n            String minVal, String maxVal, String fieldName)\n    {\n        // // find by between clause\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<E> query = criteriaBuilder.createQuery(clazz);\n        Root<E> from = query.from(clazz);\n        query.select(from.alias(\"p\"));\n        query.where(criteriaBuilder.and(\n                criteriaBuilder.equal(from.get(fieldName), name),\n                criteriaBuilder.between((Expression) from.get(\"age\"), Integer.parseInt(minVal),\n                        Integer.parseInt(maxVal))));\n\n        TypedQuery<E> q = em.createQuery(query);\n        List<E> results = q.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n\n    }\n\n    /**\n     * Assert find by range.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param minVal\n     *            the min val\n     * @param maxVal\n     *            the max val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByRange(EntityManager em, String clazz, E e, String minVal,\n            String maxVal, String fieldName, boolean useCql)\n\n    {\n        // find by Range.\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" Between \" + minVal + \" and \"\n                + maxVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        if (useCql)\n        {\n            Assert.assertEquals(3, results.size());\n        }\n        else\n        {\n            Assert.assertEquals(2, results.size());\n        }\n    }\n\n    protected <E extends Object> void assertFindByRange(EntityManager em, Class clazz, E e, String minVal,\n            String maxVal, String fieldName, boolean useCql)\n\n    {\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<E> query = criteriaBuilder.createQuery(clazz);\n        Root<E> from = query.from(clazz);\n        query.select(from.alias(\"p\"));\n        query.where(criteriaBuilder.between((Expression) from.get(fieldName), Integer.parseInt(minVal),\n                Integer.parseInt(maxVal)));\n\n        TypedQuery<E> q = em.createQuery(query);\n        List<E> results = q.getResultList();\n\n        // find by Range.\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n\n        if (useCql)\n        {\n            Assert.assertEquals(3, results.size());\n        }\n        else\n        {\n            Assert.assertEquals(2, results.size());\n        }\n    }\n\n    /**\n     * Assert find without where clause.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     */\n    protected <E extends Object> void assertFindWithoutWhereClause(EntityManager em, String clazz, E e, boolean useCql)\n    {\n        // find by without where clause.\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p\");\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        if (useCql)\n        {\n            Assert.assertEquals(4, results.size());\n        }\n        else\n        {\n            Assert.assertEquals(3, results.size());\n        }\n    }\n\n    protected <E extends Object> void assertFindWithoutWhereClause(EntityManager em, Class clazz, E e, boolean useCql)\n    {\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<E> query = criteriaBuilder.createQuery(clazz);\n        Root<E> from = query.from(clazz);\n        query.select(from.alias(\"p\"));\n\n        // find by without where clause.\n        TypedQuery<E> q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        if (useCql)\n        {\n            Assert.assertEquals(4, results.size());\n        }\n        else\n        {\n            Assert.assertEquals(3, results.size());\n        }\n    }\n\n    /**\n     * Assert on merge.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param oldName\n     *            the old name\n     * @param newName\n     *            the new name\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertOnMerge(EntityManager em, String clazz, E e, String oldName,\n            String newName, String fieldName)\n    {\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + oldName);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + newName);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotSame(oldName, getPersonName(e, results.get(0)));\n        Assert.assertEquals(newName, getPersonName(e, results.get(0)));\n    }\n\n    protected <E extends Object> void assertOnMerge(EntityManager em, Class clazz, E e, String oldName, String newName,\n            String fieldName)\n    {\n        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();\n        CriteriaQuery<E> query = criteriaBuilder.createQuery(clazz);\n        Root<E> from = query.from(clazz);\n        query.select(from.alias(\"p\"));\n        query.where(criteriaBuilder.equal(from.get(fieldName), oldName));\n        // // find by name.\n        TypedQuery<E> q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        criteriaBuilder = em.getCriteriaBuilder();\n        query = criteriaBuilder.createQuery(clazz);\n        from = query.from(clazz);\n        query.select(from.alias(\"p\"));\n        query.where(criteriaBuilder.equal(from.get(fieldName), newName));\n        // // find by name.\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotSame(oldName, getPersonName(e, results.get(0)));\n        Assert.assertEquals(newName, getPersonName(e, results.get(0)));\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @param <E>\n     *            the element type\n     * @param e\n     *            the e\n     * @param result\n     *            the result\n     * @return the person name\n     */\n    private <E extends Object> String getPersonName(E e, Object result)\n    {\n\n        return ((PersonCassandra) result).getPersonName();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/CassandraBiAssociationTest.java",
    "content": "package com.impetus.client.crud;\n\n/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.client.crud.associations.AssociationsBiDirectionalBase;\n\n/**\n * @author Pragalbh Garg\n *\n */\npublic class CassandraBiAssociationTest extends AssociationsBiDirectionalBase\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        _PU = \"CassandraShowQueryDisabledPu\";\n        super.setUpInternal();\n    }\n\n    @Test\n    public void test()\n    {\n        assertBegin();\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"KunderaTests\");\n        tearDownInternal();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/CassandraIdQueryTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.crud;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class CassandraIdQueryTest extends BaseTest\n{\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    private Map<Object, Object> col;\n\n    private CassandraCli cli;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        Map propertyMap = new HashMap();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_2_0);\n        emf = Persistence.createEntityManagerFactory(\"genericCassandraTest\", propertyMap);\n        loadData();\n        em = emf.createEntityManager();\n        col = new java.util.HashMap<Object, Object>();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        for (Object val : col.values())\n        {\n            em.remove(val);\n        }\n        em.close();\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    @Test\n    public void test() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n        init();\n        em.clear();\n        findById();\n        findByWithOutWhereClause();\n        findByIdEQ();\n        findByIdLT();\n        findByIdLTE();\n        findByIdGT();\n        findByIdGTE();\n        findByIdGTEAndLT();\n        findByIdGTAndLTE();\n//        findByIdAndAgeGTAndLT();\n//        findByIdGTAndAgeGTAndLT();\n        findByIdAndAge();\n        findByIdAndAgeGT();\n        findByIdGTEAndAge();\n        findByIdLTEAndAge();\n    }\n\n    /**\n     * \n     */\n    private void findByWithOutWhereClause()\n    {\n        String qry = \"Select p.personName from PersonCassandra p\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonCassandra person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n\n    }\n\n    /**\n     * \n     */\n    private void findByIdEQ()\n    {\n        String qry = \"Select p.personName from PersonCassandra p where p.personId = 2\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        for (PersonCassandra person : persons)\n        {\n            Assert.assertNull(person.getAge());\n            Assert.assertEquals(\"2\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n        }\n    }\n\n    /**\n     * \n     */\n    private void findByIdLT()\n    {\n        String qry = \"Select p.personName from PersonCassandra p where p.personId < 3\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonCassandra person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdLTE()\n    {\n        String qry = \"Select p.personName, p.age from PersonCassandra p where p.personId <= 3\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonCassandra person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertEquals(new Integer(\"20\"), person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertEquals(new Integer(\"15\"), person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(new Integer(\"10\"), person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdGT()\n    {\n        String qry = \"Select p.personName from PersonCassandra p where p.personId > 1\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonCassandra person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTE()\n    {\n        String qry = \"Select p.personName from PersonCassandra p where p.personId >= 1 \";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonCassandra person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTEAndLT()\n    {\n        String qry = \"Select p.personName from PersonCassandra p where p.personId >= 1 and p.personId < 3\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonCassandra person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTAndLTE()\n    {\n        String qry = \"Select p.personName from PersonCassandra p where p.personId > 1 and p.personId <= 2\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(2, persons.size());\n        int count = 0;\n        for (PersonCassandra person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTAndAgeGTAndLT()\n    {\n\n        String qry = \"Select p.personName from PersonCassandra p where p.personId > 1 and p.personName = vivek and p.age >=10 and p.age <= 20\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonCassandra person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n    }\n\n    /**\n     * \n     */\n    private void findById()\n    {\n        PersonCassandra personHBase = findById(PersonCassandra.class, \"1\", em);\n        Assert.assertNotNull(personHBase);\n        Assert.assertEquals(\"vivek\", personHBase.getPersonName());\n        Assert.assertEquals(new Integer(10), personHBase.getAge());\n\n        personHBase = findById(PersonCassandra.class, \"2\", em);\n        Assert.assertNotNull(personHBase);\n        Assert.assertEquals(\"vivek\", personHBase.getPersonName());\n        Assert.assertEquals(new Integer(20), personHBase.getAge());\n\n        personHBase = findById(PersonCassandra.class, \"3\", em);\n        Assert.assertNotNull(personHBase);\n        Assert.assertEquals(\"vivek\", personHBase.getPersonName());\n        Assert.assertEquals(new Integer(15), personHBase.getAge());\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTEAndAge()\n    {\n        String qry = \"Select p.personName, p.age from PersonCassandra p where p.personId >= 1 and p.age = 10\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        for (PersonCassandra person : persons)\n        {\n            Assert.assertEquals(new Integer(10), person.getAge());\n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n        }\n    }\n\n    /**\n     * \n     */\n    private void findByIdAndAge()\n    {\n        String qry = \"Select p.personName, p.age from PersonCassandra p where p.personId = 1 and p.age = 10\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        for (PersonCassandra person : persons)\n        {\n            Assert.assertEquals(new Integer(10), person.getAge());\n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n            Assert.assertEquals(10, person.getAge().intValue());\n            Assert.assertNull(person.getA());\n        }\n    }\n\n    /**\n     * \n     */\n    private void findByIdAndAgeGT()\n    {\n        String qry = \"Select p.personName, p.age from PersonCassandra p where p.personId = 1 and p.age > 5\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        for (PersonCassandra person : persons)\n        {\n            Assert.assertEquals(new Integer(10), person.getAge());\n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n            Assert.assertEquals(10, person.getAge().intValue());\n            Assert.assertNull(person.getA());\n        }\n    }\n\n    /**\n     * \n     */\n    private void findByIdAndAgeGTAndLT()\n    {\n        String qry = \"Select p.personName from PersonCassandra p where p.personId = 1 and p.personName = vivek and p.age >=10 and p.age <= 20\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        int count = 0;\n        for (PersonCassandra person : persons)\n        {\n            if (person.getPersonId().equals(\"1\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(1, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdLTEAndAge()\n    {\n        String qry = \"Select p.personName, p.age from PersonCassandra p where p.personId <= 3 and p.age = 10\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        for (PersonCassandra person : persons)\n        {\n            Assert.assertEquals(new Integer(10), person.getAge());\n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n        }\n\n    }\n\n    private void init() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n\n        KsDef ksDef = null;\n        CfDef user_Def = new CfDef();\n        user_Def.name = \"PERSONCASSANDRA\";\n        user_Def.keyspace = \"KunderaExamples\";\n        user_Def.setComparator_type(\"UTF8Type\");\n        user_Def.setDefault_validation_class(\"UTF8Type\");\n        user_Def.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"PERSON_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef);\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"IntegerType\");\n        columnDef1.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef1);\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"ENUM\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef2);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaExamples\");\n            CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"PERSONCASSANDRA\"))\n                {\n\n                    CassandraCli.client.system_drop_column_family(\"PERSONCASSANDRA\");\n\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def);\n\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(\"KunderaExamples\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/CassandraNativeFunctionsTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.crud.PersonCassandra.Day;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * The Class CassandraNativeFunctionsTest.\n * \n * @author: karthikp.manchala\n */\npublic class CassandraNativeFunctionsTest\n{\n\n    /** The entity manager factory. */\n    private static EntityManagerFactory entityManagerFactory;\n\n    /** The entity manager. */\n    private static EntityManager entityManager;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n        HashMap propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"genericCassandraTest\", propertyMap);\n        EntityManager em = emf.createEntityManager();\n\n        Object p1 = prepareData(\"1\", 10, \"karthik\");\n        Object p2 = prepareData(\"2\", 20, \"dev\");\n        Object p3 = prepareData(\"3\", 15, \"karthik\");\n        Object p4 = prepareData(\"4\", 25, \"dev\");\n        Object p5 = prepareData(\"5\", 30, \"karthik\");\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        em.persist(p4);\n        em.persist(p5);\n\n        emf.close();\n        em.close();\n\n        entityManagerFactory = Persistence.createEntityManagerFactory(\"CassandraScalarQueriesTest\");\n        entityManager = entityManagerFactory.createEntityManager();\n    }\n\n    /**\n     * Test native aggregations.\n     */\n    @Test\n    public void testNativeAggregations()\n    {\n        String qry = \"Select min(\\\"AGE\\\") as min_age, count(*) from \\\"PERSONCASSANDRA\\\"\";\n\n        Query q = entityManager.createNativeQuery(qry);\n        List persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n        Assert.assertEquals(10, ((Map) persons.get(0)).get(\"min_age\"));\n        Assert.assertEquals(5l, ((Map) persons.get(0)).get(\"count\"));\n\n        qry = \"Select max(\\\"AGE\\\") from \\\"PERSONCASSANDRA\\\"\";\n        q = entityManager.createNativeQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n        Assert.assertEquals(30, ((Map) persons.get(0)).get(\"system.max(AGE)\"));\n\n        qry = \"Select sum(\\\"AGE\\\") from \\\"PERSONCASSANDRA\\\"\";\n        q = entityManager.createNativeQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n        Assert.assertEquals(100, ((Map) persons.get(0)).get(\"system.sum(AGE)\"));\n\n        qry = \"Select avg(\\\"AGE\\\") from \\\"PERSONCASSANDRA\\\"\";\n        q = entityManager.createNativeQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n        Assert.assertEquals(20, ((Map) persons.get(0)).get(\"system.avg(AGE)\"));\n    }\n\n    /**\n     * Test user defined functions.\n     */\n    @Test\n    public void testUserDefinedFunctions()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n        Query q = entityManager.createNativeQuery(useNativeSql);\n        q.executeUpdate();\n        // create user defined function\n        String udf = \"CREATE OR REPLACE FUNCTION fLog (input int) \" + \"CALLED ON NULL INPUT \" + \"RETURNS double \"\n                + \"LANGUAGE java AS 'return Double.valueOf(Math.log(input.intValue()));'\";\n        q = entityManager.createNativeQuery(udf);\n        q.executeUpdate();\n        // Assert values\n        String qry = \"Select fLog(\\\"AGE\\\") from \\\"PERSONCASSANDRA\\\" where \\\"personId\\\" = '1'\";\n        q = entityManager.createNativeQuery(qry);\n        List persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n        // log 10 base e\n        Assert.assertEquals(2.302585092994046, ((Map) persons.get(0)).get(\"KunderaExamples.flog(AGE)\"));\n    }\n\n    /**\n     * Test user defined aggregation functions.\n     */\n    @Test\n    public void testUserDefinedAggregationFunctions()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n        Query q = entityManager.createNativeQuery(useNativeSql);\n        q.executeUpdate();\n        // create user defined function to return state for aggregation function\n        String udaf = \"CREATE FUNCTION state_group_and_total( state map<text, int>, name text, age int )\"\n                + \"CALLED ON NULL INPUT \" + \"RETURNS map<text, int> \"\n                + \"LANGUAGE java AS 'Integer count = (Integer) state.get(name); \" + \"if (count == null) count = age; \"\n                + \"else count = count + age; \" + \"state.put(name, count); return state; ' ;\";\n        q = entityManager.createNativeQuery(udaf);\n        q.executeUpdate();\n\n        // create aggregation function\n        udaf = \"CREATE OR REPLACE AGGREGATE group_and_total(text, int) \" + \"SFUNC state_group_and_total \"\n                + \"STYPE map<text, int>\" + \"INITCOND {};\";\n        q = entityManager.createNativeQuery(udaf);\n        q.executeUpdate();\n        // Assert values\n        String qry = \"Select group_and_total(\\\"PERSON_NAME\\\", \\\"AGE\\\") from \\\"PERSONCASSANDRA\\\"\";\n        q = entityManager.createNativeQuery(qry);\n        List persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n        // log 10 base e\n        Assert.assertEquals(45,\n                ((Map) ((Map) persons.get(0)).get(\"KunderaExamples.group_and_total(PERSON_NAME, AGE)\")).get(\"dev\"));\n        Assert.assertEquals(55,\n                ((Map) ((Map) persons.get(0)).get(\"KunderaExamples.group_and_total(PERSON_NAME, AGE)\")).get(\"karthik\"));\n    }\n\n    /**\n     * Test select and insert json.\n     */\n    @Test\n    public void testSelectAndInsertJSON()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n        Query q = entityManager.createNativeQuery(useNativeSql);\n        q.executeUpdate();\n        // create user defined function\n        String insertJSON = \"Insert into \\\"PERSONCASSANDRA\\\" JSON '{\\\"\\\\\\\"PERSON_NAME\\\\\\\"\\\": \\\"kundera\\\", \\\"\\\\\\\"AGE\\\\\\\"\\\": 123, \\\"\\\\\\\"personId\\\\\\\"\\\":\\\"abc\\\" }'\";\n        q = entityManager.createNativeQuery(insertJSON);\n        q.executeUpdate();\n        // Assert values\n        String qry = \"Select JSON * from \\\"PERSONCASSANDRA\\\"\";\n        q = entityManager.createNativeQuery(qry);\n        List persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(6, persons.size());\n        q = entityManager.createNativeQuery(\"Delete from \\\"PERSONCASSANDRA\\\" where \\\"personId\\\" = 'abc'\");\n        q.executeUpdate();\n    }\n\n    /**\n     * Test to json.\n     */\n    @Test\n    public void testToJSON()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n        Query q = entityManager.createNativeQuery(useNativeSql);\n        q.executeUpdate();\n        String qry = \"Select \\\"personId\\\", toJson(\\\"PERSON_NAME\\\") as person_name from \\\"PERSONCASSANDRA\\\"\";\n        q = entityManager.createNativeQuery(qry);\n        List persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(5, persons.size());\n    }\n\n    /**\n     * Test from json.\n     */\n    @Test\n    public void testFromJSON()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n        Query q = entityManager.createNativeQuery(useNativeSql);\n        q.executeUpdate();\n        String qry = \"UPDATE \\\"PERSONCASSANDRA\\\" SET \\\"AGE\\\" = fromJson('500') WHERE \\\"personId\\\" = fromJson('\\\"3\\\"')\";\n        q = entityManager.createNativeQuery(qry);\n        q.executeUpdate();\n\n        // Assertions\n        qry = \"Select * from \\\"PERSONCASSANDRA\\\" where \\\"personId\\\" = '3'\";\n        q = entityManager.createNativeQuery(qry);\n        List persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n        Assert.assertEquals(\"3\", ((Map) persons.get(0)).get(\"personId\"));\n        Assert.assertEquals(\"karthik\", ((Map) persons.get(0)).get(\"PERSON_NAME\"));\n        Assert.assertEquals(\"MAY\", ((Map) persons.get(0)).get(\"MONTH_ENUM\"));\n        Assert.assertEquals(500, ((Map) persons.get(0)).get(\"AGE\"));\n    }\n\n    /**\n     * Test in clause on primary key.\n     */\n    @Test\n    public void testINClauseOnPrimaryKey()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n        Query q = entityManager.createNativeQuery(useNativeSql);\n        q.executeUpdate();\n\n        String qry = \"Select * from \\\"PERSONCASSANDRA\\\" where \\\"personId\\\" IN ('1', '3', '5', '7')\";\n        q = entityManager.createNativeQuery(qry);\n        List persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(3, persons.size());\n    }\n\n    /**\n     * Test in clause on composite partition and clustering keys.\n     */\n    @Test\n    public void testINClauseOnCompositePartitionAndClusteringKeys()\n    {\n        // prepare data for querying\n        prepareDataWithCompositePartitionAndClusteringKeys();\n\n        // query and assert\n        String qry = \"select * from kundera where k_part_one IN ('kar','dev', 'amit') and k_part_two IN (1, 5, 7, 9, 13, 50)\";\n        Query q = entityManager.createNativeQuery(qry);\n        List persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(2, persons.size());\n\n        qry = \"select * from kundera where k_part_one IN ('kar','dev', 'amit') and k_part_two IN (1, 5, 7, 9, 13, 50) \"\n                + \"and k_clust_one IN ('cluster11', 'cluster13', 'cluster14')\";\n        q = entityManager.createNativeQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n\n        qry = \"select * from kundera where k_part_one IN ('kar','dev', 'amit')\";\n        q = entityManager.createNativeQuery(qry);\n        try\n        {\n            persons = q.getResultList();\n            Assert.fail();\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\"javax.persistence.PersistenceException: com.impetus.kundera.KunderaException: \"\n                    + \"InvalidRequestException(why:Cannot execute this query as it might \"\n                    + \"involve data filtering and thus may have unpredictable performance. \"\n                    + \"If you want to execute this query despite the performance \"\n                    + \"unpredictability, use ALLOW FILTERING)\", e.getMessage());\n        }\n    }\n\n    /**\n     * Prepare data with composite partition and clustering keys.\n     */\n    private void prepareDataWithCompositePartitionAndClusteringKeys()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n        Query q = entityManager.createNativeQuery(useNativeSql);\n        q.executeUpdate();\n        String qry = \"create table kundera (k_part_one text, k_part_two int, \"\n                + \"k_clust_one text, k_clust_two int, k_clust_three text, data text, \"\n                + \"PRIMARY KEY((k_part_one,k_part_two), k_clust_one, k_clust_two, k_clust_three))\";\n        q = entityManager.createNativeQuery(qry);\n        q.executeUpdate();\n\n        qry = \"insert into kundera (k_part_one, k_part_two, k_clust_one, k_clust_two, k_clust_three, data)\"\n                + \"VALUES ('kar', 13, 'cluster11', 21, 'cluster31', 'some random data')\";\n        q = entityManager.createNativeQuery(qry);\n        q.executeUpdate();\n\n        qry = \"insert into kundera (k_part_one, k_part_two, k_clust_one, k_clust_two, k_clust_three, data)\"\n                + \"VALUES ('dev', 7, 'cluster12', 22, 'cluster32', 'some more random data')\";\n        q = entityManager.createNativeQuery(qry);\n        q.executeUpdate();\n\n        qry = \"insert into kundera (k_part_one, k_part_two, k_clust_one, k_clust_two, k_clust_three, data)\"\n                + \"VALUES ('pg', 9, 'cluster13', 23, 'cluster33', 'random data')\";\n        q = entityManager.createNativeQuery(qry);\n        q.executeUpdate();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n        entityManagerFactory.close();\n        entityManager.close();\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param rowKey\n     *            the row key\n     * @param age\n     *            the age\n     * @param name\n     *            the name\n     * @return the person cassandra\n     */\n    private static PersonCassandra prepareData(String rowKey, int age, String name)\n    {\n        PersonCassandra o = new PersonCassandra();\n        o.setPersonId(rowKey);\n        o.setPersonName(name);\n        o.setAge(age);\n        o.setDay(Day.friday);\n        o.setMonth(Month.MAY);\n        return o;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/CassandraScalarQueriesTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.PersonCassandra.Day;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * The Class CassandraScalarQueriesTest.\n * \n * @author: karthikp.manchala\n */\npublic class CassandraScalarQueriesTest\n{\n\n    /** The entity manager factory. */\n    private static EntityManagerFactory entityManagerFactory;\n\n    /** The entity manager. */\n    private static EntityManager entityManager;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n        HashMap propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"genericCassandraTest\", propertyMap);\n        EntityManager em = emf.createEntityManager();\n\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        emf.close();\n        em.close();\n\n        entityManagerFactory = Persistence.createEntityManagerFactory(\"CassandraScalarQueriesTest\");\n        entityManager = entityManagerFactory.createEntityManager();\n    }\n\n    /**\n     * Test scalar query.\n     */\n    @Test\n    public void testSelectQueries()\n    {\n        String qry = \"Select key, \\\"PERSON_NAME\\\" from \\\"PERSONCASSANDRA\\\" where key = '1'\";\n\n        Query q = entityManager.createNativeQuery(qry);\n        List persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n        Assert.assertEquals(\"1\", ((Map) persons.get(0)).get(\"key\"));\n        Assert.assertEquals(\"karthik\", ((Map) persons.get(0)).get(\"PERSON_NAME\"));\n\n        qry = \"Select * from \\\"PERSONCASSANDRA\\\" where key = '1'\";\n        q = entityManager.createNativeQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n        Assert.assertEquals(\"1\", ((Map) persons.get(0)).get(\"key\"));\n        Assert.assertEquals(\"karthik\", ((Map) persons.get(0)).get(\"PERSON_NAME\"));\n        Assert.assertEquals(\"MAY\", ((Map) persons.get(0)).get(\"MONTH_ENUM\"));\n        Assert.assertEquals(10, ((Map) persons.get(0)).get(\"AGE\"));\n\n        qry = \"Select * from \\\"PERSONCASSANDRA\\\"\";\n        q = entityManager.createNativeQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(3, persons.size());\n    }\n\n    /**\n     * Test on column family.\n     */\n    @Test\n    public void testCreateAndUpdateQueries()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n        Query q = entityManager.createNativeQuery(useNativeSql);\n        q.executeUpdate();\n        // create column family\n        String colFamilySql = \"CREATE COLUMNFAMILY IF NOT EXISTS users (key varchar PRIMARY KEY,full_name varchar, birth_date int,state varchar)\";\n        q = entityManager.createNativeQuery(colFamilySql);\n        q.executeUpdate();\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"users\", \"KunderaExamples\"));\n\n        // Add indexes\n        String idxSql = \"CREATE INDEX IF NOT EXISTS ON users (birth_date)\";\n        q = entityManager.createNativeQuery(idxSql);\n        q.executeUpdate();\n        idxSql = \"CREATE INDEX IF NOT EXISTS ON users (state)\";\n        q = entityManager.createNativeQuery(idxSql);\n        q.executeUpdate();\n        // insert users.\n        String insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('bsanderson', 'Brandon Sanderson', 1975, 'UT')\";\n        q = entityManager.createNativeQuery(insertSql);\n        q.executeUpdate();\n\n        // select key and state\n        String selectSql = \"SELECT key, state FROM users\";\n        q = entityManager.createNativeQuery(selectSql);\n        List results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"bsanderson\", ((Map) results.get(0)).get(\"key\"));\n        Assert.assertEquals(\"UT\", ((Map) results.get(0)).get(\"state\"));\n        Assert.assertEquals(null, ((Map) results.get(0)).get(\"full_name\"));\n\n        // insert users.\n        insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('prothfuss', 'Patrick Rothfuss', 1973, 'WI')\";\n        q = entityManager.createNativeQuery(insertSql);\n        q.getResultList();\n\n        insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('htayler', 'Howard Tayler', 1968, 'UT')\";\n        q = entityManager.createNativeQuery(insertSql);\n        q.getResultList();\n\n        // select all\n        String selectAll = \"SELECT * FROM users WHERE state='UT' AND birth_date > 1970 ALLOW FILTERING\";\n        q = entityManager.createNativeQuery(selectAll);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"bsanderson\", ((Map) results.get(0)).get(\"key\"));\n        Assert.assertEquals(\"UT\", ((Map) results.get(0)).get(\"state\"));\n        Assert.assertEquals(\"Brandon Sanderson\", ((Map) results.get(0)).get(\"full_name\"));\n        Assert.assertEquals(new Integer(1975), ((Map) results.get(0)).get(\"birth_date\"));\n\n        String updateSql = \"UPDATE users SET full_name = 'update' WHERE key = 'bsanderson'\";\n        q = entityManager.createNativeQuery(updateSql);\n        q.getResultList();\n\n        selectAll = \"SELECT * FROM users WHERE state='UT' AND birth_date > 1970 ALLOW FILTERING\";\n        q = entityManager.createNativeQuery(selectAll);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"bsanderson\", ((Map) results.get(0)).get(\"key\"));\n        Assert.assertEquals(\"UT\", ((Map) results.get(0)).get(\"state\"));\n        Assert.assertEquals(\"update\", ((Map) results.get(0)).get(\"full_name\"));\n        Assert.assertEquals(new Integer(1975), ((Map) results.get(0)).get(\"birth_date\"));\n\n    }\n\n    @Test\n    public void testMetadataQueries()\n    {\n        String useNativeSql = \"SELECT keyspace_name,table_name,column_name,kind,type FROM system_schema.columns\"\n                + \" WHERE keyspace_name = 'KunderaExamples' AND table_name = 'PERSONCASSANDRA'\";\n        Query q = entityManager.createNativeQuery(useNativeSql);\n        List results = q.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(8, results.size());\n        Assert.assertEquals(\"KunderaExamples\", ((Map) results.get(0)).get(\"keyspace_name\"));\n        Assert.assertEquals(\"PERSONCASSANDRA\", ((Map) results.get(0)).get(\"table_name\"));\n        Assert.assertEquals(\"AGE\", ((Map) results.get(0)).get(\"column_name\"));\n        Assert.assertEquals(\"static\", ((Map) results.get(0)).get(\"kind\"));\n        Assert.assertEquals(\"int\", ((Map) results.get(0)).get(\"type\"));\n\n        useNativeSql = \"SELECT * FROM system_schema.keyspaces WHERE keyspace_name = 'KunderaExamples'\";\n        q = entityManager.createNativeQuery(useNativeSql);\n        results = q.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"KunderaExamples\", ((Map) results.get(0)).get(\"keyspace_name\"));\n        Assert.assertEquals(true, ((Map) results.get(0)).get(\"durable_writes\"));\n\n        useNativeSql = \"SELECT COUNT(*) FROM system_schema.columns WHERE keyspace_name = 'KunderaExamples'AND table_name = 'PERSONCASSANDRA'\";\n        q = entityManager.createNativeQuery(useNativeSql);\n        results = q.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(8l, ((Map) results.get(0)).get(\"count\"));\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param rowKey\n     *            the row key\n     * @param age\n     *            the age\n     * @return the person cassandra\n     */\n    private static PersonCassandra prepareData(String rowKey, int age)\n    {\n        PersonCassandra o = new PersonCassandra();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"karthik\");\n        o.setAge(age);\n        o.setDay(Day.friday);\n        o.setMonth(Month.MAY);\n        return o;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/CassandraThriftSecondaryTableTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * \n * @author Kuldeep.Mishra\n *\n */\npublic class CassandraThriftSecondaryTableTest extends SecondaryTableTestBase\n{\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        loadData();\n        emf = Persistence.createEntityManagerFactory(\"secIdxCassandraTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    @Test\n    public void test()\n    {\n        testCRUD(emf);\n    }\n    \n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n        String table1 = \"PRIMARY_TABLE\";\n        String table2 = \"SECONDARY_TABLE\";\n        String keyspace = \"KunderaExamples\";\n        KsDef ksDef = null;\n        CfDef user_Def1 = new CfDef();\n        user_Def1.name = table1;\n        user_Def1.keyspace = keyspace;\n        user_Def1.column_type = \"Super\";\n\n\n        CfDef user_Def2 = new CfDef();\n        user_Def2.name = table2;\n        user_Def2.keyspace = keyspace;\n        user_Def2.column_type = \"Super\";\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def1);\n        cfDefs.add(user_Def2);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(keyspace);\n            CassandraCli.client.set_keyspace(keyspace);\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(table1))\n                {\n                    CassandraCli.client.system_drop_column_family(table1);\n                }\n                if (cfDef1.getName().equalsIgnoreCase(table2))\n                {\n                    CassandraCli.client.system_drop_column_family(table2);\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def1);\n            CassandraCli.client.system_add_column_family(user_Def2);\n\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/EmbeddedEntity.java",
    "content": "package com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n@Embeddable\npublic class EmbeddedEntity\n{\n    @Column(name = \"EMAIL_ID\", table = \"SECONDARY_TABLE\")\n    private String emailId;\n\n    @Column(name = \"PHONE_NO\")\n    private long phoneNo;\n\n    public String getEmailId()\n    {\n        return emailId;\n    }\n\n    public void setEmailId(String emailId)\n    {\n        this.emailId = emailId;\n    }\n\n    public long getPhoneNo()\n    {\n        return phoneNo;\n    }\n\n    public void setPhoneNo(long phoneNo)\n    {\n        this.phoneNo = phoneNo;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/Employee.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaExamples@secIdxCassandraTest\")\npublic class Employee\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"manager\")\n    private Set<Employee> Employees;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"MANAGER_ID\")\n    private Employee manager;\n\n    public Employee()\n    {\n    }\n\n    /**\n     * @return the personId\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * @param personId\n     *            the personId to set\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the personName\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * @param personName\n     *            the personName to set\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * @return the employees\n     */\n    public Set<Employee> getEmployees()\n    {\n        return Employees;\n    }\n\n    /**\n     * @param employees\n     *            the employees to set\n     */\n    public void setEmployees(Set<Employee> employees)\n    {\n        Employees = employees;\n    }\n\n    /**\n     * @return the manager\n     */\n    public Employee getManager()\n    {\n        return manager;\n    }\n\n    /**\n     * @param manager\n     *            the manager to set\n     */\n    public void setManager(Employee manager)\n    {\n        this.manager = manager;\n    }\n\n    // Constructors, Getters, setters here\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/EntityTransactionTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * The Class EntityTransactionTest.\n * \n * @author vivek.mishra\n */\npublic class EntityTransactionTest extends BaseTest\n{\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        // cassandraSetUp();\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        loadData();\n\n        emf = Persistence.createEntityManagerFactory(\"genericCassandraTest\");\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * On rollback.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onRollback() throws IOException, TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n\n        em.getTransaction().begin();\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        // roll back.\n        em.getTransaction().rollback();\n\n        em.getTransaction().begin();\n\n        PersonCassandra p = findById(PersonCassandra.class, \"1\", em);\n        Assert.assertNull(p);\n\n        // on commit.\n        em.getTransaction().commit();\n\n        // Still no record should be flushed as already rollback!\n        p = findById(PersonCassandra.class, \"1\", em);\n        Assert.assertNull(p);\n    }\n\n    /**\n     * On commit.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onCommit() throws IOException, TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n\n        em.getTransaction().begin();\n\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        // on commit.\n        em.getTransaction().commit();\n\n        PersonCassandra p = findById(PersonCassandra.class, \"1\", em);\n        Assert.assertNotNull(p);\n\n        em.getTransaction().begin();\n\n        ((PersonCassandra) p2).setPersonName(\"rollback\");\n        em.merge(p2);\n\n        // roll back, should roll back person name for p2!\n        em.getTransaction().rollback();\n\n        p = findById(PersonCassandra.class, \"1\", em);\n        Assert.assertNotNull(p);\n\n        p = findById(PersonCassandra.class, \"2\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertNotSame(\"rollback\", p.getPersonName());\n\n    }\n\n    /**\n     * Rollback on error.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void rollbackOnError() throws IOException, TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        PersonCassandra p = null;\n        try\n        {\n            Object p1 = prepareData(\"1\", 10);\n            Object p2 = prepareData(\"2\", 20);\n            em.persist(p1);\n            em.persist(p2);\n\n            p = findById(PersonCassandra.class, \"1\", em);\n            Assert.assertNotNull(p);\n\n            Object p3 = prepareData(\"3\", 15);\n            em.persist(p3);\n\n            // Assert on rollback on error.\n            ((PersonCassandra) p2).setPersonName(\"rollback\");\n            em.merge(p2);\n            em.merge(null);\n\n            // As this is a runtime exception so rollback should happen and\n            // delete out commited data.\n        }\n        catch (Exception ex)\n        {\n\n            p = findById(PersonCassandra.class, \"1\", em);\n            Assert.assertNull(p);\n\n            p = findById(PersonCassandra.class, \"2\", em);\n            Assert.assertNull(p);\n\n            p = findById(PersonCassandra.class, \"3\", em);\n            Assert.assertNull(p);\n        }\n        em.clear();\n        // persist with 1 em\n        EntityManager em1 = emf.createEntityManager();\n        // em1.setFlushMode(FlushModeType.COMMIT);\n        em1.getTransaction().begin();\n        Object p3 = prepareData(\"4\", 15);\n        em1.persist(p3);\n        em1.getTransaction().commit();\n\n        try\n        {\n            // remove with another em with auto flush.\n            EntityManager em2 = emf.createEntityManager();\n            PersonCassandra person = em2.find(PersonCassandra.class, \"4\");\n            em2.remove(person);\n            em2.merge(null);\n        }\n        catch (Exception ex)\n        {\n            // Deleted records cannot be rolled back in cassandra!\n            // em1.clear();\n\n            p = findById(PersonCassandra.class, \"4\", em1);\n            Assert.assertNotNull(p);\n            Assert.assertEquals(\"vivek\", p.getPersonName());\n\n        }\n    }\n\n    /**\n     * Roll back with multi transactions.\n     */\n    @Test\n    public void rollBackWithMultiTransactions()\n    {\n        EntityManager em1 = emf.createEntityManager();\n        // em1.setFlushMode(FlushModeType.COMMIT);\n\n        // Begin transaction.\n        em1.getTransaction().begin();\n        Object p1 = prepareData(\"11\", 10);\n        em1.persist(p1);\n\n        // commit p1.\n        em1.getTransaction().commit();\n\n        // another em instance\n        EntityManager em2 = emf.createEntityManager();\n        // em2.setFlushMode(FlushModeType.COMMIT);\n\n        // begin transaction.\n        em2.getTransaction().begin();\n        PersonCassandra found = em2.find(PersonCassandra.class, \"11\");\n        found.setPersonName(\"merged\");\n        em2.merge(found);\n\n        // commit p1 after modification.\n        em2.getTransaction().commit();\n\n        // open another entity manager.\n        EntityManager em3 = emf.createEntityManager();\n        found = em3.find(PersonCassandra.class, \"11\");\n        found.setPersonName(\"lastemerge\");\n        try\n        {\n            em3.merge(found);\n            em3.merge(null);\n        }\n        catch (Exception ex)\n        {\n            PersonCassandra finalFound = em2.find(PersonCassandra.class, \"11\");\n            Assert.assertNotNull(finalFound);\n            Assert.assertEquals(\"merged\", finalFound.getPersonName());\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {/*\n      * Delete is working, but as row keys are not deleted from cassandra, so\n      * resulting in issue while reading back. // Delete\n      * em.remove(em.find(Person.class, \"1\")); em.remove(em.find(Person.class,\n      * \"2\")); em.remove(em.find(Person.class, \"3\")); em.close(); emf.close();\n      * em = null; emf = null;\n      */\n    \tem.close();\n    \temf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n\n        KsDef ksDef = null;\n        CfDef user_Def = new CfDef();\n        user_Def.name = \"PERSONCASSANDRA\";\n        user_Def.keyspace = \"KunderaExamples\";\n        user_Def.setComparator_type(\"UTF8Type\");\n        user_Def.setDefault_validation_class(\"UTF8Type\");\n        user_Def.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"PERSON_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef);\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef1);\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"ENUM\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef2);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaExamples\");\n            CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"PERSON\"))\n                {\n\n                    CassandraCli.client.system_drop_column_family(\"PERSON\");\n\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def);\n\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(\"KunderaExamples\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/EntityWithClause.java",
    "content": "package com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"tests\", schema = \"KunderaTests@cassandra_pu\")\n@IndexCollection(columns = { @Index(name = \"likedBy\"), @Index(name = \"income\"), @Index(name = \"settlementDate\"),\n        @Index(name = \"dateSet\"), @Index(name = \"and\"), @Index(name = \"between\"), @Index(name = \"or\") })\npublic class EntityWithClause\n{\n    @Id\n    private String id;\n\n    @Column\n    private String likedBy;\n\n    @Column\n    private String income;\n\n    @Column\n    private String settlementDate;\n\n    @Column\n    private String dateSet;\n\n    @Column\n    private String and;\n\n    @Column\n    private String between;\n\n    @Column\n    private String or;\n\n    @Column\n    private String set;\n\n    // @ElementCollection\n    // @CollectionTable\n    // private List<CurvePoint> curvePoints;\n\n    public String getLikedBy()\n    {\n        return likedBy;\n    }\n\n    public void setLikedBy(String likedBy)\n    {\n        this.likedBy = likedBy;\n    }\n\n    public String getIncome()\n    {\n        return income;\n    }\n\n    public void setIncome(String income)\n    {\n        this.income = income;\n    }\n\n    public String getSettlementDate()\n    {\n        return settlementDate;\n    }\n\n    public void setSettlementDate(String settlementDate)\n    {\n        this.settlementDate = settlementDate;\n    }\n\n    public String getAnd()\n    {\n        return and;\n    }\n\n    public void setAnd(String and)\n    {\n        this.and = and;\n    }\n\n    public String getBetween()\n    {\n        return between;\n    }\n\n    public void setBetween(String between)\n    {\n        this.between = between;\n    }\n\n    public String getDateSet()\n    {\n        return dateSet;\n    }\n\n    public void setDateSet(String dateSet)\n    {\n        this.dateSet = dateSet;\n    }\n\n    public EntityWithClause()\n    {\n    }\n\n    // public List<CurvePoint> getCurvePoints()\n    // {\n    // return curvePoints;\n    // }\n    //\n    // public void setCurvePoints(List<CurvePoint> curvePoints)\n    // {\n    // this.curvePoints = curvePoints;\n    // }\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public EntityWithClause(String id/* , List<CurvePoint> curvePoints */)\n    {\n        this.id = id;\n        // this.curvePoints = curvePoints;\n    }\n\n    public String getOr()\n    {\n        return or;\n    }\n\n    public void setOr(String or)\n    {\n        this.or = or;\n    }\n\n    public String getSet()\n    {\n        return set;\n    }\n\n    public void setSet(String set)\n    {\n        this.set = set;\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/EntityWithClauseBatchTest.java",
    "content": "package com.impetus.client.crud;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class EntityWithClauseBatchTest\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    @Test\n    public void test()\n    {\n        Map<String, String> propertyMap = new HashMap<String, String>();\n        propertyMap.put(\"kundera.batch.size\", \"5\");\n\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"cassandra_pu\", propertyMap);\n\n        propertyMap.put(\"kundera.batch.size\", \"10\");\n\n        EntityManager em = emf.createEntityManager(propertyMap);\n\n        for (int i = 1; i <= 10; i++)\n        {\n            EntityWithClause entityWithClause1 = new EntityWithClause(\"1\" + i);\n            entityWithClause1.setIncome(\"1233\");\n            entityWithClause1.setLikedBy(\"kk\");\n            entityWithClause1.setSettlementDate(\"12/12/12\");\n            entityWithClause1.setAnd(\"and\");\n            entityWithClause1.setBetween(\"between\");\n            entityWithClause1.setDateSet(\"dateSet\");\n            entityWithClause1.setOr(\"or\");\n\n            em.persist(entityWithClause1);\n\n            if (i == 10)\n            {\n                List<EntityWithClause> entityWithClauses = em.createQuery(\"select t from EntityWithClause t\")\n                        .getResultList();\n                Assert.assertNotNull(entityWithClauses);\n                Assert.assertEquals(10, entityWithClauses.size());\n            }\n            else\n            {\n                List<EntityWithClause> entityWithClauses = em.createQuery(\"select t from EntityWithClause t\")\n                        .getResultList();\n                Assert.assertNotNull(entityWithClauses);\n                Assert.assertTrue(entityWithClauses.isEmpty());\n            }\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/EntityWithClauseTest.java",
    "content": "package com.impetus.client.crud;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class EntityWithClauseTest\n{\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    @org.junit.Test\n    public void test()\n    {\n        Map<String, String> propertyMap = new HashMap();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"cassandra_pu\", propertyMap);\n        EntityManager em = emf.createEntityManager();\n\n        EntityWithClause entityWithClause1 = new EntityWithClause(\"1\");\n        entityWithClause1.setIncome(\"1233\");\n        entityWithClause1.setLikedBy(\"kk\");\n        entityWithClause1.setSettlementDate(\"12/12/12\");\n        entityWithClause1.setAnd(\"and\");\n        entityWithClause1.setBetween(\"between\");\n        entityWithClause1.setDateSet(\"dateSet\");\n        entityWithClause1.setOr(\"or\");\n        entityWithClause1.setSet(\"set\");\n\n        EntityWithClause entityWithClause2 = new EntityWithClause(\"2\");\n        entityWithClause2.setIncome(\"2233\");\n        entityWithClause2.setLikedBy(\"kk\");\n        entityWithClause2.setSettlementDate(\"12/12/12\");\n        entityWithClause2.setAnd(\"and\");\n        entityWithClause2.setBetween(\"between\");\n        entityWithClause2.setDateSet(\"dateSet\");\n        entityWithClause2.setOr(\"or\");\n        entityWithClause2.setSet(\"set\");\n\n        EntityWithClause entityWithClause3 = new EntityWithClause(\"3\");\n        entityWithClause3.setIncome(\"3233\");\n        entityWithClause3.setLikedBy(\"kk\");\n        entityWithClause3.setSettlementDate(\"12/12/13\");\n        entityWithClause3.setAnd(\"and\");\n        entityWithClause3.setBetween(\"between\");\n        entityWithClause3.setDateSet(\"dateSet\");\n        entityWithClause3.setOr(\"or\");\n\n        em.persist(entityWithClause1);\n        em.persist(entityWithClause2);\n        em.persist(entityWithClause3);\n\n        em.clear();\n\n        // Select query.\n        List<EntityWithClause> entityWithClauses = em.createQuery(\n                \"select t from EntityWithClause t where t.income=1233\").getResultList();\n        Assert.assertNotNull(entityWithClauses);\n        Assert.assertEquals(1, entityWithClauses.size());\n\n        entityWithClauses = em.createQuery(\"select t from EntityWithClause t where t.likedBy=kk\").getResultList();\n        Assert.assertNotNull(entityWithClauses);\n        Assert.assertEquals(3, entityWithClauses.size());\n\n        entityWithClauses = em.createQuery(\"select t from EntityWithClause t where t.dateSet=dateSet\").getResultList();\n        Assert.assertNotNull(entityWithClauses);\n        Assert.assertEquals(3, entityWithClauses.size());\n\n        entityWithClauses = em.createQuery(\"select t from EntityWithClause t where t.settlementDate='12/12/12'\")\n                .getResultList();\n        Assert.assertNotNull(entityWithClauses);\n        Assert.assertEquals(2, entityWithClauses.size());\n\n        // entityWithClauses =\n        // em.createQuery(\"select t from EntityWithClause t where t.or=or\").getResultList();\n        // Assert.assertNotNull(entityWithClauses);\n        // Assert.assertEquals(3, entityWithClauses.size());\n\n        // entityWithClauses =\n        // em.createQuery(\"select t from EntityWithClause t where t.between=between\").getResultList();\n        // Assert.assertNotNull(entityWithClauses);\n        // Assert.assertEquals(3, entityWithClauses.size());\n        //\n        // entityWithClauses =\n        // em.createQuery(\"select t from EntityWithClause t where t.and=and\").getResultList();\n        // Assert.assertNotNull(entityWithClauses);\n        // Assert.assertEquals(3, entityWithClauses.size());\n\n        // try\n        // {\n        // entityWithClauses =\n        // em.createQuery(\"select set from EntityWithClause set where set.set=set\")\n        // .getResultList();\n        // Assert.fail();\n        // }\n        // catch (JPQLParseException e)\n        // {\n        // Assert.assertEquals(\n        // \"Out of order keyword set, entity alias must not be any reserved keyword.. For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\",\n        // e.getMessage());\n        // }\n        //\n        // try\n        // {\n        // entityWithClauses =\n        // em.createQuery(\"select from from EntityWithClause from where from.set=set\")\n        // .getResultList();\n        // Assert.fail();\n        // }\n        // catch (JPQLParseException e)\n        // {\n        // Assert.assertEquals(\n        // \"Out of order keyword from, entity alias must not be any reserved keyword.. For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\",\n        // e.getMessage());\n        // }\n\n        // Update query.\n        int affectedRecord = em.createQuery(\"Update EntityWithClause t SET t.or=newor where t.id = 1\").executeUpdate();\n        EntityWithClause result = em.find(EntityWithClause.class, \"1\");\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"newor\", result.getOr());\n\n        em.clear();\n\n        affectedRecord = em.createQuery(\"Update EntityWithClause t SET t.and=newand where t.id = 1\").executeUpdate();\n        result = em.find(EntityWithClause.class, \"1\");\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"newand\", result.getAnd());\n\n        em.clear();\n\n        affectedRecord = em.createQuery(\"Update EntityWithClause t SET t.set=newset where t.id = 1\").executeUpdate();\n        result = em.find(EntityWithClause.class, \"1\");\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"newset\", result.getSet());\n\n        em.clear();\n\n        affectedRecord = em.createQuery(\"Update EntityWithClause t SET t.between=newbetween where t.id = 1\")\n                .executeUpdate();\n        result = em.find(EntityWithClause.class, \"1\");\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"newbetween\", result.getBetween());\n\n        em.clear();\n\n        affectedRecord = em.createQuery(\"Update EntityWithClause t SET t.likedBy=newKK where t.id = 1\").executeUpdate();\n        result = em.find(EntityWithClause.class, \"1\");\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"newKK\", result.getLikedBy());\n\n        // try\n        // {\n        // affectedRecord =\n        // em.createQuery(\"Update EntityWithClause set SET set.likedBy=newKK where set.id = 1\")\n        // .executeUpdate();\n        // Assert.fail();\n        // }\n        // catch (JPQLParseException e)\n        // {\n        // Assert.assertEquals(\n        // \"Out of order keyword SET, entity alias must not be any reserved keyword.. For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\",\n        // e.getMessage());\n        // }\n        //\n        // try\n        // {\n        // affectedRecord =\n        // em.createQuery(\"Update EntityWithClause from SET from.likedBy=newKK where from.id = 1\")\n        // .executeUpdate();\n        // Assert.fail();\n        // }\n        // catch (JPQLParseException e)\n        // {\n        // Assert.assertEquals(\n        // \"Out of order keyword from, entity alias must not be any reserved keyword.. For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\",\n        // e.getMessage());\n        // }\n\n        // Delete query.\n\n        // affectedRecord =\n        // em.createQuery(\"Delete From EntityWithClause t where t.or=newor\").executeUpdate();\n        // result = em.find(EntityWithClause.class, \"1\");\n        // Assert.assertNull(result);\n\n        // try\n        // {\n        // affectedRecord =\n        // em.createQuery(\"Delete From EntityWithClause t where t.and=and\").executeUpdate();\n        // result = em.find(EntityWithClause.class, \"2\");\n        // Assert.assertNull(result);\n        // }\n        // catch (JPQLParseException e)\n        // {\n        // Assert.assertEquals(\n        // \"Out of order keyword from, entity alias must not be any reserver keyword.. For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\",\n        // e.getMessage());\n        // }\n\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/Group.java",
    "content": "package com.impetus.client.crud;\n\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"groups\", schema = \"KunderaExamples@secIdxCassandraTest\")\n@IndexCollection(columns = { @Index(name = \"parentId\") })\npublic class Group\n{\n\n    @Id\n    @Column(name = \"resourceId\")\n    private String resourceId;\n\n    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)\n    @JoinColumn(name = \"parentId\")\n    private Group parent;\n\n    @OneToMany(fetch = FetchType.EAGER, mappedBy = \"parent\")\n    private List<Group> children;\n\n    @Column(name = \"resourceName\")\n    private String resourceName;\n\n    public Group()\n    {\n    }\n\n    public Group getParent()\n    {\n        return parent;\n    }\n\n    public void setParent(Group parent)\n    {\n        this.parent = parent;\n    }\n\n    public List<Group> getChildren()\n    {\n        return children;\n    }\n\n    public void setChildren(List<Group> children)\n    {\n        this.children = children;\n    }\n\n    public String getResourceId()\n    {\n        return resourceId;\n    }\n\n    public void setResourceId(String resourceId)\n    {\n        this.resourceId = resourceId;\n    }\n\n    public String getResourceName()\n    {\n        return resourceName;\n    }\n\n    public void setResourceName(String resourceName)\n    {\n        this.resourceName = resourceName;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/MTOBiSelfAssociationTest.java",
    "content": "package com.impetus.client.crud;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class MTOBiSelfAssociationTest\n{\n\n    private static final String SEC_IDX_CASSANDRA_TEST = \"secIdxCassandraTest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    protected Map propertyMap = null;\n\n    protected boolean AUTO_MANAGE_SCHEMA = true;\n\n    protected boolean USE_CQL = false;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        \n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n\n        if (propertyMap == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            // loadData();\n        }\n        emf = Persistence.createEntityManagerFactory(SEC_IDX_CASSANDRA_TEST, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void test()\n    {\n        Group all = new Group();\n        all.setResourceId(\"All\"); // A\n        all.setResourceName(\"resName\");\n\n        Group ungrouped = new Group();\n        ungrouped.setResourceId(\"ungrouped\");\n        ungrouped.setParent(all); // B\n\n        Group grouped = new Group();\n        grouped.setResourceId(\"grouped\");\n        grouped.setParent(all); // C\n\n        List<Group> children = new ArrayList<Group>();\n        children.add(ungrouped);\n        children.add(grouped);\n        all.setChildren(children);\n\n        em.persist(ungrouped);\n        em.persist(grouped);\n        em.persist(all);\n\n        em.clear();\n        Group parent = em.find(Group.class, \"All\");\n\n        Assert.assertNotNull(parent);\n        Assert.assertNotNull(parent.getChildren());\n        Assert.assertNull(parent.getParent());\n        Assert.assertEquals(2, parent.getChildren().size());\n        Assert.assertSame(parent, parent.getChildren().iterator().next().getParent());\n        Assert.assertSame(parent, parent.getChildren().iterator().next().getParent());\n\n        em.clear();\n        Group child1 = em.find(Group.class, \"ungrouped\");\n        Assert.assertNotNull(child1);\n        Assert.assertEquals(child1.getParent().getResourceId(), \"All\");\n        Assert.assertNull(child1.getParent().getParent());\n        Assert.assertEquals(child1.getResourceId(), \"ungrouped\");\n        Assert.assertEquals(2, child1.getParent().getChildren().size());\n        Assert.assertSame(child1.getParent().getChildren().iterator().next().getParent(), child1.getParent()\n                .getChildren().iterator().next().getParent());\n\n        em.clear();\n        Group child2 = em.find(Group.class, \"grouped\");\n        Assert.assertNotNull(child2);\n        Assert.assertEquals(child2.getParent().getResourceId(), \"All\");\n        Assert.assertNull(child2.getParent().getParent());\n        Assert.assertEquals(child2.getResourceId(), \"grouped\");\n        Assert.assertEquals(2, child2.getParent().getChildren().size());\n        Assert.assertSame(child2.getParent().getChildren().iterator().next().getParent(), child2.getParent()\n                .getChildren().iterator().next().getParent());\n\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/Month.java",
    "content": "package com.impetus.client.crud;\n\npublic enum Month\n{\n    JAN, FEB, MARCH, APRIL, MAY, JUNE;\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/MyTestEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.io.Serializable;\nimport java.sql.Timestamp;\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"test1\", schema = \"KunderaCassandraXmlTest@CassandraXmlPropertyTest\")\n@IndexCollection(columns = { @Index(name = \"url\") })\npublic class MyTestEntity implements Serializable\n{\n\n    private static final long serialVersionUID = 1L;\n\n    @Id\n    @Column(name = \"id\")\n    private UUID key;\n\n    @Column(name = \"userid\")\n    private UUID userid;\n\n    @Column(name = \"url\")\n    private String url;\n\n    @Column(name = \"datetime\")\n    private Timestamp datetime;\n\n    @Column(name = \"linkcounts\")\n    private int linkcounts;\n\n    public MyTestEntity()\n    {\n    }\n\n    public UUID getKey()\n    {\n        return key;\n    }\n\n    public void setKey(UUID key)\n    {\n        this.key = key;\n    }\n\n    public UUID getUserid()\n    {\n        return userid;\n    }\n\n    public void setUserid(UUID userid)\n    {\n        this.userid = userid;\n    }\n\n    public String getUrl()\n    {\n        return url;\n    }\n\n    public void setUrl(String url)\n    {\n        this.url = url;\n    }\n\n    public Timestamp getDatetime()\n    {\n        return datetime;\n    }\n\n    public void setDatetime(Timestamp datetime)\n    {\n        this.datetime = datetime;\n    }\n\n    public int getLinkcounts()\n    {\n        return linkcounts;\n    }\n\n    public void setLinkcounts(int linkcounts)\n    {\n        this.linkcounts = linkcounts;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/OTMCRUDTest.java",
    "content": "package com.impetus.client.crud;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class OTMCRUDTest\n{\n\n    private static final String SEC_IDX_CASSANDRA_TEST = \"myapp_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    protected Map propertyMap = null;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n        CassandraCli.createKeySpace(\"myapp\");\n        if (propertyMap == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_2_0);\n        }\n        emf = Persistence.createEntityManagerFactory(SEC_IDX_CASSANDRA_TEST, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        String query = \"Delete from Token t\";\n        Query q = em.createQuery(query);\n        q.executeUpdate();\n\n        if (emf != null)\n        {\n            emf.close();\n            emf = null;\n        }\n        if (em != null)\n        {\n            em.close();\n            em = null;\n        }\n\n        CassandraCli.dropKeySpace(\"myapp\");\n    }\n\n    @Test\n    public void test()\n    {\n        Token token1 = new Token();\n        token1.setId(\"tokenId1\");\n        TokenClient client = new TokenClient();\n        client.setClientName(\"tokenClient1\");\n        client.setId(\"tokenClientId\");\n        token1.setClient(client);\n\n        Token token2 = new Token();\n        token2.setId(\"tokenId2\");\n        token2.setClient(client);\n        em.persist(token1);\n        em.persist(token2);\n\n        em.clear();\n        Token result = em.find(Token.class, \"tokenId1\");\n\n        Assert.assertNotNull(result);\n        Assert.assertNotNull(result.getClient());\n\n        em.clear();\n        String query = \"Select t from Token t\";\n        Query q = em.createQuery(query);\n        List<Token> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotNull(results.get(0).getClient());\n        Assert.assertNotNull(results.get(1).getClient());\n\n        em.clear();\n        query = \"Select t from TokenClient t\";\n        q = em.createQuery(query);\n        List<TokenClient> resultClient = q.getResultList();\n        Assert.assertNotNull(resultClient);\n        Assert.assertEquals(1, resultClient.size());\n        Assert.assertEquals(2, resultClient.get(0).getTokens().size());\n\n        em.clear();\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/PersonAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Test case to perform simple SelfAssociation.\n * \n * @author vivek.mishra\n * \n *         Run this script to create column family in cassandra with indexes.\n *         create column family PERSON with comparator=UTF8Type and\n *         column_metadata=[{column_name: PERSON_NAME,\n *         validation_class:UTF8Type, index_type: KEYS}, {column_name:\n *         AGE,validation_class:IntegerType, index_type: KEYS}, {column_name:\n *         MANAGER_ID,validation_class:UTF8Type, index_type: KEYS}];\n * \n */\npublic class PersonAssociationTest extends BaseTest\n{\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    private CassandraCli cassandraCli;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        cassandraCli = new CassandraCli();\n        cassandraCli.cassandraSetUp();\n        loadData();\n        \n        emf = Persistence.createEntityManagerFactory(\"secIdxCassandraTest\");\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testDemo()\n    {\n\n    }\n\n    /**\n     * On crud.\n     */\n    // @Test\n    public void onInsert()\n    {\n\n        Employee emp1 = new Employee();\n        emp1.setPersonId(\"1_e\");\n        emp1.setPersonName(\"emp\");\n\n        Employee emp2 = new Employee();\n        emp2.setPersonId(\"2_e\");\n        emp2.setPersonName(\"emp2\");\n\n        Employee manager = new Employee();\n        manager.setPersonId(\"2_m\");\n        manager.setPersonName(\"mgr\");\n        emp1.setManager(manager);\n\n        // set manager for employee2\n        emp2.setManager(manager);\n        // set manager for employee1\n        emp1.setManager(manager);\n\n        Set<Employee> ems = new java.util.HashSet<Employee>();\n        ems.add(emp2);\n        ems.add(emp1);\n\n        // set employees for manager.\n        manager.setEmployees(ems);\n\n        em.persist(emp1);\n        em.persist(emp2);\n        // em.persist(manager);\n\n        em.clear();\n        Employee emp = em.find(Employee.class, \"1_e\");\n\n        Assert.assertNotNull(emp);\n        Assert.assertEquals(\"2_m\", emp.getManager().getPersonId());\n        Assert.assertNull(emp.getEmployees());\n        Assert.assertNotNull(emp.getManager().getEmployees());\n        Assert.assertFalse(emp.getManager().getEmployees().isEmpty());\n        Assert.assertEquals(2, emp.getManager().getEmployees().size());\n        Iterator<Employee> iter = emp.getManager().getEmployees().iterator();\n        String firstEmployee = iter.next().getPersonId();\n        String secEmployee = iter.next().getPersonId();\n        Assert.assertNotSame(firstEmployee, secEmployee);\n        // Assert.assertEquals(\"2_e\",\n        // emp.getEmployees().iterator().next().getPersonId());\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     * @throws InvalidRequestException\n     * @throws UnavailableException\n     * @throws TimedOutException\n     * @throws SchemaDisagreementException\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n\n        KsDef ksDef = null;\n        CfDef user_Def = new CfDef();\n        user_Def.name = \"PERSON\";\n        user_Def.keyspace = \"KunderaExamples\";\n        user_Def.setComparator_type(\"UTF8Type\");\n        user_Def.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef personName = new ColumnDef(ByteBuffer.wrap(\"PERSON_NAME\".getBytes()), \"UTF8Type\");\n        personName.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(personName);\n        ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"IntegerType\");\n        age.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(age);\n\n        ColumnDef reference_key = new ColumnDef(ByteBuffer.wrap(\"MANAGER_ID\".getBytes()), \"UTF8Type\");\n        reference_key.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(reference_key);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaExamples\");\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"PERSON\"))\n                {\n\n                    CassandraCli.client.system_drop_column_family(\"PERSON\");\n\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def);\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(\"KunderaExamples\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        cassandraCli.dropKeySpace(\"KunderaExamples\");\n        /*\n         * Delete is working, but as row keys are not deleted from cassandra, so\n         * resulting in issue while reading back. // Delete\n         * em.remove(em.find(Person.class, \"1\"));\n         * em.remove(em.find(Person.class, \"2\"));\n         * em.remove(em.find(Person.class, \"3\")); em.close(); emf.close(); em =\n         * null; emf = null;\n         */\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/PersonCassandra.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.NamedNativeQuery;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSONCASSANDRA\", schema = \"KunderaExamples@genericCassandraTest\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\n@NamedNativeQuery(name=\"q\", query=\"select * from \\\"PERSONCASSANDRA\\\"\")\n\n\n  public class PersonCassandra\n{\n    public static final String UID = \"uid\";\n\n    public static final String EID = \"eid\";\n\n    public static final String FIRST_NAME = \"firstName\";\n\n    public static final String LAST_NAME = \"lastName\";\n\n    public static final String CITY = \"city\";\n\n    public static final String CREATED = \"created\";\n\n    public static final String LAST_MODIFIED = \"lastModified\";\n\n    /** The person id. */\n    @Id\n    // @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"AGEss\")\n    private byte[] a;\n\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    @Column(name = \"MONTH_ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Month month;\n\n    /**\n     * @return the a\n     */\n    public byte[] getA()\n    {\n        return a;\n    }\n\n    /**\n     * @param a\n     *            the a to set\n     */\n    public void setA(byte[] a)\n    {\n        this.a = a;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the day\n     */\n    public Day getDay()\n    {\n        return day;\n    }\n\n    /**\n     * @param day\n     *            the day to set\n     */\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n\n    public Month getMonth()\n    {\n        return month;\n    }\n\n    public void setMonth(Month month)\n    {\n        this.month = month;\n    }\n\n    enum Day\n    {\n        monday,tuesday,wednesday,thursday,friday, saturday,sunday;\n//        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/PersonCassandraLuceneTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.nio.ByteBuffer;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport javax.persistence.TypedQuery;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.ColumnOrSuperColumn;\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.Mutation;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.thrift.CQLTranslator;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * Test case to perform simple CRUD operation.(insert, delete, merge, and select)\n * \n * @author kuldeep.mishra\n * \n *         Run this script to create column family in cassandra with indexes. create column family PERSON with\n *         comparator=UTF8Type and column_metadata=[{column_name: PERSON_NAME, validation_class: UTF8Type, index_type:\n *         KEYS}, {column_name: AGE, validation_class: IntegerType, index_type: KEYS}];\n * \n */\npublic class PersonCassandraLuceneTest extends BaseTest {\n    private static final String LUCENE_IDX_CASSANDRA_TEST = \"luceneCassandraTest\";\n\n    protected static boolean USE_CQL = false;\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The col. */\n    private Map<Object, Object> col;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n        Map propertyMap = new HashMap();\n        // propertyMap.put(CassandraConstants.CQL_VERSION,\n        // CassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(LUCENE_IDX_CASSANDRA_TEST, propertyMap);\n        em = emf.createEntityManager();\n        col = new java.util.HashMap<Object, Object>();\n    }\n\n    /**\n     * On insert cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onInsertCassandra() throws Exception {\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n\n        em.clear();\n        PersonLuceneCassandra p = findById(PersonLuceneCassandra.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n\n        em.clear();\n        String qry = \"Select p.personId,p.personName from PersonLuceneCassandra p where p.personId >= 1\";\n        Query q = em.createQuery(qry);\n        List<PersonLuceneCassandra> persons = q.getResultList();\n\n        selectIdQuery();\n        assertFindByName(em, \"PersonLuceneCassandra\", PersonLuceneCassandra.class, \"vivek\", \"personName\");\n        assertFindByNameAndAge(em, \"PersonLuceneCassandra\", PersonLuceneCassandra.class, \"vivek\", \"10\", \"personName\");\n        assertFindByNameAndAgeGTAndLT(em, \"PersonLuceneCassandra\", PersonLuceneCassandra.class, \"vivek\", \"10\", \"20\",\n            \"personName\");\n        assertFindByNameAndAgeBetween(em, \"PersonLuceneCassandra\", PersonLuceneCassandra.class, \"vivek\", \"10\", \"15\",\n            \"personName\");\n        assertFindByRange(em, \"PersonLuceneCassandra\", PersonLuceneCassandra.class, \"1\", \"2\", \"personId\", false);\n        assertFindWithoutWhereClause(em, \"PersonLuceneCassandra\", PersonLuceneCassandra.class, false);\n\n        // OR clause test case.\n        String orClauseQuery = \"Select p from PersonLuceneCassandra p where p.personName = 'vivek1' OR p.age = 10\";\n\n        q = em.createQuery(orClauseQuery);\n\n        List<PersonLuceneCassandra> results = q.getResultList();\n\n        Assert.assertEquals(1, results.size());\n        // perform merge after query.\n        for (PersonLuceneCassandra person : persons) {\n            person.setPersonName(\"after merge\");\n            em.merge(person);\n        }\n\n        em.clear();\n\n        p = findById(PersonLuceneCassandra.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"after merge\", p.getPersonName());\n\n        List<PersonLuceneCassandra> allPersons =\n            em.createQuery(\"select p from PersonLuceneCassandra p where p.personId = :id\", PersonLuceneCassandra.class)\n                .setParameter(\"id\", 1).getResultList();\n\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(1, allPersons.size());\n\n        // Delete without WHERE clause.\n\n        String deleteQuery = \"DELETE from PersonLuceneCassandra\";\n        q = em.createQuery(deleteQuery);\n        Assert.assertEquals(3, q.executeUpdate());\n\n    }\n\n    /**\n     * On merge cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onMergeCassandra() throws Exception {\n        // CassandraCli.cassandraSetUp();\n        // loadData();\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        em.clear();\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        PersonLuceneCassandra p = findById(PersonLuceneCassandra.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        // modify record.\n        p.setPersonName(\"newvivek\");\n        em.merge(p);\n\n        assertOnMerge(em, \"PersonLuceneCassandra\", \"vivek\", \"newvivek\", \"personName\");\n    }\n\n    @Test\n    public void onDeleteThenInsertCassandra() throws Exception {\n        // CassandraCli.cassandraSetUp();\n        // CassandraCli.initClient();\n        // loadData();\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        PersonLuceneCassandra p = findById(PersonLuceneCassandra.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        em.remove(p);\n        em.clear();\n\n        TypedQuery<PersonLuceneCassandra> query =\n            em.createQuery(\"Select p from PersonLuceneCassandra p\", PersonLuceneCassandra.class);\n\n        List<PersonLuceneCassandra> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        p1 = prepare(\"1\", 10);\n        em.persist(p1);\n\n        query = em.createQuery(\"Select p from PersonLuceneCassandra p\", PersonLuceneCassandra.class);\n\n        results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n\n    }\n\n    @Test\n    public void onRefreshCassandra() throws Exception {\n        // cassandraSetUp();\n        // CassandraCli.cassandraSetUp();\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n\n        // Check for contains\n        Object pp1 = prepare(\"1\", 10);\n        Object pp2 = prepare(\"2\", 20);\n        Object pp3 = prepare(\"3\", 15);\n        Assert.assertTrue(em.contains(pp1));\n        Assert.assertTrue(em.contains(pp2));\n        Assert.assertTrue(em.contains(pp3));\n\n        // Check for detach\n        em.detach(pp1);\n        em.detach(pp2);\n        Assert.assertFalse(em.contains(pp1));\n        Assert.assertFalse(em.contains(pp2));\n        Assert.assertTrue(em.contains(pp3));\n\n        // Modify value in database directly, refresh and then check PC\n        em.clear();\n        em = emf.createEntityManager();\n        Object o1 = em.find(PersonLuceneCassandra.class, \"1\");\n\n        if (!USE_CQL) {\n            // Create Insertion List\n            List<Mutation> insertionList = new ArrayList<Mutation>();\n            List<Column> columns = new ArrayList<Column>();\n            Column column = new Column();\n            column.setName(PropertyAccessorFactory.STRING.toBytes(\"PERSON_NAME\"));\n            column.setValue(PropertyAccessorFactory.STRING.toBytes(\"Amry\"));\n            column.setTimestamp(System.currentTimeMillis());\n            columns.add(column);\n            Mutation mut = new Mutation();\n            mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setColumn(column));\n            insertionList.add(mut);\n            // Create Mutation Map\n            Map<String, List<Mutation>> columnFamilyValues = new HashMap<String, List<Mutation>>();\n            columnFamilyValues.put(\"PERSON\", insertionList);\n            Map<ByteBuffer, Map<String, List<Mutation>>> mulationMap =\n                new HashMap<ByteBuffer, Map<String, List<Mutation>>>();\n            mulationMap.put(ByteBuffer.wrap(\"1\".getBytes()), columnFamilyValues);\n            CassandraCli.client.batch_mutate(mulationMap, ConsistencyLevel.ONE);\n        } else {\n            CQLTranslator translator = new CQLTranslator();\n            String query = \"insert into \\\"PERSON\\\" (key,\\\"PERSON_NAME\\\",\\\"AGE\\\") values ('1','Amry','10' )\";\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(query.getBytes()), Compression.NONE,\n                ConsistencyLevel.ONE);\n        }\n\n        em.refresh(o1);\n        Object oo1 = em.find(PersonLuceneCassandra.class, \"1\");\n        Assert.assertTrue(em.contains(o1));\n        Assert.assertEquals(\"Amry\", ((PersonLuceneCassandra) oo1).getPersonName());\n    }\n\n    /**\n     * On typed create query\n     * \n     * @throws TException\n     * @throws InvalidRequestException\n     * @throws UnavailableException\n     * @throws TimedOutException\n     * @throws SchemaDisagreementException\n     */\n    @Test\n    public void onTypedQuery() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n        SchemaDisagreementException {\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        TypedQuery<PersonLuceneCassandra> query =\n            em.createQuery(\"Select p from PersonLuceneCassandra p\", PersonLuceneCassandra.class);\n\n        List<PersonLuceneCassandra> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n    }\n\n    /**\n     * On typed create query\n     * \n     * @throws TException\n     * @throws InvalidRequestException\n     * @throws UnavailableException\n     * @throws TimedOutException\n     * @throws SchemaDisagreementException\n     */\n    @Test\n    public void onGenericTypedQuery() throws TException, InvalidRequestException, UnavailableException,\n        TimedOutException, SchemaDisagreementException {\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        TypedQuery<Object> query = em.createQuery(\"Select p from PersonLuceneCassandra p\", Object.class);\n\n        List<Object> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(PersonLuceneCassandra.class, results.get(0).getClass());\n    }\n\n    /**\n     * on invalid typed query.\n     * \n     * @throws TException\n     * @throws InvalidRequestException\n     * @throws UnavailableException\n     * @throws TimedOutException\n     * @throws SchemaDisagreementException\n     */\n    @Test\n    public void onInvalidTypedQuery() throws TException, InvalidRequestException, UnavailableException,\n        TimedOutException, SchemaDisagreementException {\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        TypedQuery<Group> query = null;\n        try {\n            query = em.createQuery(\"Select p from PersonLuceneCassandra p\", Group.class);\n            Assert.fail(\"Should have gone to catch block, as it is an invalid scenario!\");\n        } catch (IllegalArgumentException iaex) {\n            Assert.assertNull(query);\n        }\n    }\n\n    @Test\n    public void onGhostRows() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n        SchemaDisagreementException {\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        em.clear();\n        PersonLuceneCassandra person = em.find(PersonLuceneCassandra.class, \"1\");\n        em.remove(person);\n        em.clear(); // just to make sure that not to be picked up from cache.\n        TypedQuery<PersonLuceneCassandra> query =\n            em.createQuery(\"Select p from PersonLuceneCassandra p\", PersonLuceneCassandra.class);\n\n        List<PersonLuceneCassandra> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n    }\n\n    // added, test for like queries and matchmode with '%'\n    @Test\n    public void testLikeQuery() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n        SchemaDisagreementException {\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n        Object p1 = prepare(10, \"karthik\");\n        Object p2 = prepare(20, \"viveek\");\n        Object p3 = prepare(15, \"kartheek\");\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        em.clear();\n        // test left\n        TypedQuery<PersonLuceneCassandraUUID> query =\n            em.createQuery(\"Select p from PersonLuceneCassandraUUID p where p.personName like :name\",\n                PersonLuceneCassandraUUID.class);\n        query.setParameter(\"name\", \"%eek\");\n\n        List<PersonLuceneCassandraUUID> results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotSame(\"karthik\", results.get(0).getPersonName());\n        Assert.assertNotSame(\"karthik\", results.get(1).getPersonName());\n\n        if (results.get(0).getAge().equals(\"20\")) {\n            Assert.assertEquals(\"viveek\", results.get(0).getPersonName());\n            Assert.assertEquals(\"kartheek\", results.get(1).getPersonName());\n        } else {\n            Assert.assertEquals(\"kartheek\", results.get(0).getPersonName());\n            Assert.assertEquals(\"viveek\", results.get(1).getPersonName());\n        }\n\n        // test right\n        query =\n            em.createQuery(\"Select p from PersonLuceneCassandraUUID p where p.personName like :name\",\n                PersonLuceneCassandraUUID.class);\n        query.setParameter(\"name\", \"kar%\");\n\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotSame(\"viveek\", results.get(0).getPersonName());\n        Assert.assertNotSame(\"viveek\", results.get(1).getPersonName());\n\n        if (results.get(0).getAge().equals(\"10\")) {\n            Assert.assertEquals(\"karthik\", results.get(0).getPersonName());\n            Assert.assertEquals(\"kartheek\", results.get(1).getPersonName());\n        } else {\n            Assert.assertEquals(\"kartheek\", results.get(0).getPersonName());\n            Assert.assertEquals(\"karthik\", results.get(1).getPersonName());\n        }\n\n        // test default\n        query =\n            em.createQuery(\"Select p from PersonLuceneCassandraUUID p where p.personName like :name\",\n                PersonLuceneCassandraUUID.class);\n        query.setParameter(\"name\", \"viv\");\n\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"viveek\", results.get(0).getPersonName());\n\n        // test both\n        query =\n            em.createQuery(\"Select p from PersonLuceneCassandraUUID p where p.personName like :name\",\n                PersonLuceneCassandraUUID.class);\n        query.setParameter(\"name\", \"%art%\");\n\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotSame(\"viveek\", results.get(0).getPersonName());\n        Assert.assertNotSame(\"viveek\", results.get(1).getPersonName());\n\n        if (results.get(0).getAge().equals(\"10\")) {\n            Assert.assertEquals(\"karthik\", results.get(0).getPersonName());\n            Assert.assertEquals(\"kartheek\", results.get(1).getPersonName());\n        } else {\n            Assert.assertEquals(\"kartheek\", results.get(0).getPersonName());\n            Assert.assertEquals(\"karthik\", results.get(1).getPersonName());\n        }\n\n    }\n\n    // added, test for partition keys of type UUID\n    @Test\n    public void testUUID() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n        SchemaDisagreementException {\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n\n        Object p1 = prepare(10, \"karthik\");\n        Object p2 = prepare(20, \"vivek\");\n        Object p3 = prepare(15, \"pragalbh\");\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        em.clear();\n        TypedQuery<PersonLuceneCassandraUUID> query =\n            em.createQuery(\"Select p from PersonLuceneCassandraUUID p\", PersonLuceneCassandraUUID.class);\n        List<PersonLuceneCassandraUUID> results = query.getResultList();\n        java.util.Iterator<PersonLuceneCassandraUUID> i = results.iterator();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n    }\n\n    private void selectIdQuery() {\n        String query = \"select p from PersonLuceneCassandra p\";\n        Query q = em.createQuery(query);\n        List<PersonLuceneCassandra> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertEquals(\"vivek\", results.get(0).getPersonName());\n\n        query = \"Select p.personName from PersonLuceneCassandra p where p.personName = vivek\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertEquals(\"vivek\", results.get(0).getPersonName());\n        Assert.assertNull(results.get(0).getAge());\n\n        q =\n            em.createQuery(\"Select p.personId,p.personName from PersonLuceneCassandra p where p.personName = vivek and p.age >10\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNotNull(results.get(0).getPersonName());\n        Assert.assertNull(results.get(0).getAge());\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception {/*\n                                              * Delete is working, but as row keys are not deleted from cassandra, so\n                                              * resulting in issue while reading back. // Delete\n                                              * em.remove(em.find(Person.class, \"1\")); em.remove(em.find(Person.class,\n                                              * \"2\")); em.remove(em.find(Person.class, \"3\")); em.close(); emf.close();\n                                              * em = null; emf = null;\n                                              */\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n        LuceneCleanupUtilities.cleanLuceneDirectory(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance()\n            .getApplicationMetadata().getPersistenceUnitMetadata(LUCENE_IDX_CASSANDRA_TEST));\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n        SchemaDisagreementException {\n        KsDef ksDef = null;\n        CfDef user_Def = new CfDef();\n        user_Def.name = \"PERSON\";\n        user_Def.keyspace = \"KunderaExamples\";\n        user_Def.setComparator_type(\"UTF8Type\");\n        user_Def.setDefault_validation_class(\"UTF8Type\");\n        user_Def.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"PERSON_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef);\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef1);\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"ENUM\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef2);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def);\n\n        try {\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaExamples\");\n            CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn) {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"PERSON\")) {\n\n                    CassandraCli.client.system_drop_column_family(\"PERSON\");\n\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def);\n\n        } catch (NotFoundException e) {\n\n            ksDef = new KsDef(\"KunderaExamples\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null) {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param rowKey\n     *            the row key\n     * @param age\n     *            the age\n     * @return the person\n     */\n    private PersonLuceneCassandra prepare(String rowKey, int age) {\n        PersonLuceneCassandra o = new PersonLuceneCassandra();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age + \"\");\n        o.setDay(com.impetus.client.crud.PersonLuceneCassandra.Day.MONDAY);\n        return o;\n    }\n\n    // added by me\n    private PersonLuceneCassandraUUID prepare(int age, String name) {\n        PersonLuceneCassandraUUID o = new PersonLuceneCassandraUUID();\n        UUID z = UUID.randomUUID();\n        o.setPersonId(z);\n        o.setPersonName(name);\n        if (name.equals(\"karthik\")) {\n            o.setDate(new Timestamp(9419290317914l));\n        } else if (name.equals(\"pragalbh\")) {\n            o.setDate(new Timestamp(new Date().getTime()));\n        } else {\n            o.setDate(new Timestamp(1418290317914l));\n        }\n        o.setAge(age + \"\");\n        o.setDay(PersonLuceneCassandraUUID.Day.MONDAY);\n        return o;\n    }\n\n    private void assertOnMerge(EntityManager em, String clazz, String oldName, String newName, String fieldName) {\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + oldName);\n        List<PersonLuceneCassandra> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + newName);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotSame(oldName, getPersonName(results.get(0)));\n        Assert.assertEquals(newName, getPersonName(results.get(0)));\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @param <E>\n     *            the element type\n     * @param e\n     *            the e\n     * @param result\n     *            the result\n     * @return the person name\n     */\n    private String getPersonName(Object result) {\n\n        return ((PersonLuceneCassandra) result).getPersonName();\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/PersonCassandraLuceneTestCQL3.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport org.junit.After;\nimport org.junit.Before;\n\n/**\n * \n * @author karthikp.manchala\n * \n * \n */\npublic class PersonCassandraLuceneTestCQL3 extends PersonCassandraLuceneTest\n{\n    \n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        super.USE_CQL = true;\n        super.setUp();\n    }\n\n   \n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/PersonCassandraTTLTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.nio.ByteBuffer;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.ColumnOrSuperColumn;\nimport org.apache.cassandra.thrift.ColumnParent;\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.CqlResult;\nimport org.apache.cassandra.thrift.CqlRow;\nimport org.apache.cassandra.thrift.SlicePredicate;\nimport org.apache.cassandra.thrift.SliceRange;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Test case for verifying Time to Live feature of Cassandra on single entity\n * \n * @author amresh.singh\n */\npublic class PersonCassandraTTLTest extends BaseTest\n{\n    private static final String SEC_IDX_CASSANDRA_TEST = \"genericCassandraTest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The col. */\n    private Map<Object, Object> col;\n\n    protected Map propertyMap = null;\n\n    protected boolean AUTO_MANAGE_SCHEMA = true;\n\n    protected boolean USE_CQL = false;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        if (em != null)\n            em.close();\n        if (emf != null)\n            emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    /**\n     * Tests whether TTL provided while inserting records are correctly getting\n     * applied for CQL 2.0 Common TTL value for entire row is used\n     * \n     * @throws Exception\n     */\n\n    @Test\n    public void testTTLForEntireRowOnCQL2_0() throws Exception\n    {\n        if (propertyMap == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        }\n        emf = Persistence.createEntityManagerFactory(SEC_IDX_CASSANDRA_TEST, propertyMap);\n        em = emf.createEntityManager();\n\n        Map<String, Integer> ttlValues = new HashMap<String, Integer>();\n        ttlValues.put(\"PERSONCASSANDRA\", new Integer(5));\n        em.setProperty(\"ttl.per.request\", true);\n        em.setProperty(\"ttl.values\", ttlValues);\n\n        Object p1 = prepareData(\"1\", 10);\n        em.persist(p1);\n        em.clear();\n        PersonCassandra p = findById(PersonCassandra.class, \"1\", em);\n\n        SlicePredicate predicate = new SlicePredicate();\n        predicate.setSlice_range(new SliceRange(ByteBufferUtil.EMPTY_BYTE_BUFFER, ByteBufferUtil.EMPTY_BYTE_BUFFER,\n                true, 10000));\n        ByteBuffer key = ByteBuffer.wrap(\"1\".getBytes());\n\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n        List<ColumnOrSuperColumn> columnOrSuperColumns = CassandraCli.client.get_slice(key, new ColumnParent(\n                \"PERSONCASSANDRA\"), predicate, ConsistencyLevel.ONE);\n\n        boolean personNameFound = false;\n        boolean ageFound = false;\n\n        for (ColumnOrSuperColumn cosc : columnOrSuperColumns)\n        {\n            Column column = cosc.column;\n\n            String columnName = new String(column.getName(), Constants.ENCODING);\n            if (columnName.equals(\"PERSON_NAME\"))\n            {\n                Assert.assertEquals(5, column.getTtl());\n                personNameFound = true;\n            }\n            else if (columnName.equals(\"AGE\"))\n            {\n                Assert.assertEquals(5, column.getTtl());\n                ageFound = true;\n            }\n        }\n\n        Assert.assertTrue(personNameFound && ageFound);\n        Thread.sleep(5000);\n\n        columnOrSuperColumns = CassandraCli.client.get_slice(key, new ColumnParent(\"PERSONCASSANDRA\"), predicate,\n                ConsistencyLevel.ONE);\n        for (ColumnOrSuperColumn cosc : columnOrSuperColumns)\n        {\n            Column column = cosc.column;\n\n            String columnName = new String(column.getName(), Constants.ENCODING);\n            if (columnName.equals(\"PERSON_NAME\"))\n            {\n                Assert.fail(\"PERSON_NAME column not deleted even though a TTL of 5 seconds was specified while writing to cassandra.\");\n            }\n            else if (columnName.equals(\"AGE\"))\n            {\n                Assert.fail(\"Age column not deleted even though a TTL of 5 seconds was specified while writing to cassandra.\");\n            }\n        }\n\n        String deleteQuery = \"DELETE from PersonCassandra\";\n        Query q = em.createQuery(deleteQuery);\n        Assert.assertEquals(0, q.executeUpdate());\n    }\n\n    /**\n     * Tests whether TTL provided while inserting records are correctly getting\n     * applied for CQL 2.0 Different TTL Values for Different columns are used\n     * \n     * @throws Exception\n     */\n\n    @Test\n    public void testDifferentTTLOnCQL2_0() throws Exception\n    {\n        if (propertyMap == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        }\n        emf = Persistence.createEntityManagerFactory(SEC_IDX_CASSANDRA_TEST, propertyMap);\n        em = emf.createEntityManager();\n\n        Map<String, Integer> ttlColumns = new HashMap<String, Integer>();\n        ttlColumns.put(\"PERSON_NAME\", 5000000);\n        ttlColumns.put(\"AGE\", 5);\n        Map<String, Map<String, Integer>> ttlValues = new HashMap<String, Map<String, Integer>>();\n        ttlValues.put(\"PERSONCASSANDRA\", ttlColumns);\n        em.setProperty(\"ttl.per.request\", true);\n        em.setProperty(\"ttl.values\", ttlValues);\n\n        Object p1 = prepareData(\"1\", 10);\n        em.persist(p1);\n        em.clear();\n        PersonCassandra p = findById(PersonCassandra.class, \"1\", em);\n\n        SlicePredicate predicate = new SlicePredicate();\n        predicate.setSlice_range(new SliceRange(ByteBufferUtil.EMPTY_BYTE_BUFFER, ByteBufferUtil.EMPTY_BYTE_BUFFER,\n                true, 10000));\n        ByteBuffer key = ByteBuffer.wrap(\"1\".getBytes());\n\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n        List<ColumnOrSuperColumn> columnOrSuperColumns = CassandraCli.client.get_slice(key, new ColumnParent(\n                \"PERSONCASSANDRA\"), predicate, ConsistencyLevel.ONE);\n\n        boolean personNameFound = false;\n        boolean ageFound = false;\n\n        for (ColumnOrSuperColumn cosc : columnOrSuperColumns)\n        {\n            Column column = cosc.column;\n\n            String columnName = new String(column.getName(), Constants.ENCODING);\n            if (columnName.equals(\"PERSON_NAME\"))\n            {\n                Assert.assertEquals(5000000, column.getTtl());\n                personNameFound = true;\n            }\n            else if (columnName.equals(\"AGE\"))\n            {\n                Assert.assertEquals(5, column.getTtl());\n                ageFound = true;\n            }\n        }\n\n        Assert.assertTrue(personNameFound && ageFound);\n        Thread.sleep(5000);\n\n        columnOrSuperColumns = CassandraCli.client.get_slice(key, new ColumnParent(\"PERSONCASSANDRA\"), predicate,\n                ConsistencyLevel.ONE);\n        for (ColumnOrSuperColumn cosc : columnOrSuperColumns)\n        {\n            Column column = cosc.column;\n\n            String columnName = new String(column.getName(), Constants.ENCODING);\n            if (columnName.equals(\"PERSON_NAME\"))\n            {\n                Assert.assertEquals(5000000, column.getTtl());\n                personNameFound = true;\n            }\n            else if (columnName.equals(\"AGE\"))\n            {\n                Assert.fail(\"Age column not deleted even though a TTL of 5 seconds was specified while writing to cassandra.\");\n            }\n        }\n\n        String deleteQuery = \"DELETE from PersonCassandra\";\n        Query q = em.createQuery(deleteQuery);\n        Assert.assertEquals(1, q.executeUpdate());\n    }\n\n    /**\n     * Tests whether TTL provided while inserting records are correctly getting\n     * applied using CQL 3 Common TTL value for entire row is used\n     * \n     * @throws Exception\n     */\n    @Test\n    public void testTTLonCQL3_0() throws Exception\n    {\n        propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(SEC_IDX_CASSANDRA_TEST, propertyMap);\n        em = emf.createEntityManager();\n\n        Map<String, Integer> ttlValues = new HashMap<String, Integer>();\n        ttlValues.put(\"PERSONCASSANDRA\", new Integer(5));\n        em.setProperty(\"ttl.per.request\", true);\n        em.setProperty(\"ttl.values\", ttlValues);\n\n        Object p1 = prepareData(\"1\", 10);\n        em.persist(p1);\n        em.clear();\n\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n        CqlResult cqlResult = CassandraCli.client.execute_cql3_query(ByteBuffer\n                .wrap(\"Select ttl(\\\"PERSON_NAME\\\"), ttl(\\\"AGE\\\") from \\\"PERSONCASSANDRA\\\" where \\\"personId\\\" = '1'\"\n                        .getBytes()), Compression.NONE, ConsistencyLevel.ONE);\n\n        List<CqlRow> cqlRows = cqlResult.getRows();\n        CqlRow cqlRow = cqlRows.get(0);\n\n        boolean personNameFound = false;\n        boolean ageFound = false;\n\n        for (Column column : cqlRow.getColumns())\n        {\n            String columnName = new String(column.getName(), Constants.ENCODING);\n            if (columnName.equals(\"ttl(PERSON_NAME)\"))\n            {\n                Assert.assertEquals(5, ByteBufferUtil.toInt(ByteBuffer.wrap(column.getValue())));\n                personNameFound = true;\n            }\n            else if (columnName.equals(\"ttl(AGE)\"))\n            {\n                Assert.assertEquals(5, ByteBufferUtil.toInt(ByteBuffer.wrap(column.getValue())));\n                ageFound = true;\n            }\n        }\n\n        Assert.assertTrue(personNameFound && ageFound);\n        Thread.sleep(5000);\n\n        cqlResult = CassandraCli.client.execute_cql3_query(ByteBuffer\n                .wrap(\"Select ttl(\\\"PERSON_NAME\\\"), ttl(\\\"AGE\\\") from \\\"PERSONCASSANDRA\\\" where \\\"personId\\\" = '1'\"\n                        .getBytes()), Compression.NONE, ConsistencyLevel.ONE);\n\n        cqlRows = cqlResult.getRows();\n\n        try\n        {\n            cqlRow = cqlRows.get(0);\n            Assert.fail(\"PERSON_NAME and AGE column not deleted even though a TTL of 5 seconds was specified while writing to cassandra.\");\n        }\n        catch (IndexOutOfBoundsException ioobe)\n        {\n            Assert.assertTrue(cqlRows.isEmpty());\n        }\n        // checking for update query.\n\n        Object p2 = prepareData(\"2\", 10);\n        em.persist(p2);\n        em.clear();\n\n        ttlValues = new HashMap<String, Integer>();\n        ttlValues.put(\"PERSONCASSANDRA\", new Integer(10));\n        em.setProperty(\"ttl.per.request\", true);\n        em.setProperty(\"ttl.values\", ttlValues);\n\n        Query q = em.createQuery(\"update PersonCassandra p set p.personName='''KK MISHRA''' where p.personId=2\");\n        q.executeUpdate();\n\n        cqlResult = CassandraCli.client.execute_cql3_query(ByteBuffer\n                .wrap(\"Select ttl(\\\"PERSON_NAME\\\"), ttl(\\\"AGE\\\") from \\\"PERSONCASSANDRA\\\" where \\\"personId\\\" = '2'\"\n                        .getBytes()), Compression.NONE, ConsistencyLevel.ONE);\n\n        cqlRows = cqlResult.getRows();\n        cqlRow = cqlRows.get(0);\n\n        personNameFound = false;\n        ageFound = false;\n\n        for (Column column : cqlRow.getColumns())\n        {\n            String columnName = new String(column.getName(), Constants.ENCODING);\n            if (columnName.equals(\"ttl(PERSON_NAME)\"))\n            {\n                Assert.assertEquals(10, ByteBufferUtil.toInt(ByteBuffer.wrap(column.getValue())));\n                personNameFound = true;\n            }\n            else if (columnName.equals(\"ttl(AGE)\"))\n            {\n                Assert.assertEquals(null, column.getValue());\n                ageFound = true;\n            }            \n        }\n\n        Assert.assertTrue(personNameFound && ageFound);\n        Thread.sleep(10000);\n\n        cqlResult = CassandraCli.client.execute_cql3_query(ByteBuffer\n                .wrap(\"Select ttl(\\\"PERSON_NAME\\\"), ttl(\\\"AGE\\\") from \\\"PERSONCASSANDRA\\\" where \\\"personId\\\" = '2'\"\n                        .getBytes()), Compression.NONE, ConsistencyLevel.ONE);\n\n        cqlRows = cqlResult.getRows();\n        cqlRow = cqlRows.get(0);\n        for (Column column : cqlRow.getColumns())\n        {\n            String columnName = new String(column.getName(), Constants.ENCODING);\n            if (columnName.equals(\"ttl(PERSON_NAME)\"))\n            {\n                Assert.assertEquals(null, null);\n                personNameFound = true;\n            }\n            else if (columnName.equals(\"ttl(AGE)\"))\n            {\n                Assert.assertEquals(null, column.getValue());\n                ageFound = true;\n            }\n            if (columnName.equals(\"PERSON_NAME\"))\n            {\n                Assert.fail(\"PERSON_NAME column not deleted even though a TTL of 10 seconds was specified while writing to cassandra.\");\n            }\n        }\n\n        // TTL per session.\n\n        ttlValues = new HashMap<String, Integer>();\n        ttlValues.put(\"PERSONCASSANDRA\", new Integer(10));\n        em.setProperty(\"ttl.per.session\", true);\n        em.setProperty(\"ttl.values\", ttlValues);\n\n        Object p3 = prepareData(\"3\", 10);\n        em.persist(p3);\n        em.clear();\n\n        cqlResult = CassandraCli.client.execute_cql3_query(ByteBuffer\n                .wrap(\"Select ttl(\\\"PERSON_NAME\\\"), ttl(\\\"AGE\\\") from \\\"PERSONCASSANDRA\\\" where \\\"personId\\\" = '3'\"\n                        .getBytes()), Compression.NONE, ConsistencyLevel.ONE);\n\n        cqlRows = cqlResult.getRows();\n        cqlRow = cqlRows.get(0);\n\n        personNameFound = false;\n        ageFound = false;\n\n        for (Column column : cqlRow.getColumns())\n        {\n            String columnName = new String(column.getName(), Constants.ENCODING);\n            if (columnName.equals(\"ttl(PERSON_NAME)\"))\n            {\n                Assert.assertEquals(10, ByteBufferUtil.toInt(ByteBuffer.wrap(column.getValue())));\n                personNameFound = true;\n            }\n            else if (columnName.equals(\"ttl(AGE)\"))\n            {\n                Assert.assertEquals(10, ByteBufferUtil.toInt(ByteBuffer.wrap(column.getValue())));\n                ageFound = true;\n            }\n        }\n\n        Assert.assertTrue(personNameFound && ageFound);\n        Thread.sleep(10000);\n\n        cqlResult = CassandraCli.client.execute_cql3_query(ByteBuffer\n                .wrap(\"Select ttl(\\\"PERSON_NAME\\\"), ttl(\\\"AGE\\\") from \\\"PERSONCASSANDRA\\\" where \\\"personId\\\" = '3'\"\n                        .getBytes()), Compression.NONE, ConsistencyLevel.ONE);\n\n        cqlRows = cqlResult.getRows();\n        try\n        {\n            cqlRow = cqlRows.get(0);\n            Assert.fail(\"PERSON_NAME and AGE column not deleted even though a TTL of 5 seconds was specified while writing to cassandra.\");\n        }\n        catch (IndexOutOfBoundsException ioobe)\n        {\n            Assert.assertTrue(cqlRows.isEmpty());\n        }\n\n        Object p4 = prepareData(\"4\", 10);\n        ttlValues = new HashMap<String, Integer>();\n        ttlValues.put(\"PERSONCASSANDRA\", new Integer(10));\n        em.setProperty(\"ttl.per.session\", true);\n        em.setProperty(\"ttl.values\", ttlValues);\n        em.persist(p4);\n        em.clear();\n\n        cqlResult = CassandraCli.client.execute_cql3_query(ByteBuffer\n                .wrap(\"Select ttl(\\\"PERSON_NAME\\\"), ttl(\\\"AGE\\\") from \\\"PERSONCASSANDRA\\\" where \\\"personId\\\" = '4'\"\n                        .getBytes()), Compression.NONE, ConsistencyLevel.ONE);\n\n        cqlRows = cqlResult.getRows();\n        cqlRow = cqlRows.get(0);\n        personNameFound = false;\n        ageFound = false;\n\n        for (Column column : cqlRow.getColumns())\n        {\n            String columnName = new String(column.getName(), Constants.ENCODING);\n            if (columnName.equals(\"ttl(PERSON_NAME)\"))\n            {\n                Assert.assertEquals(10, ByteBufferUtil.toInt(ByteBuffer.wrap(column.getValue())));\n                personNameFound = true;\n            }\n            else if (columnName.equals(\"ttl(AGE)\"))\n            {\n                Assert.assertEquals(10, ByteBufferUtil.toInt(ByteBuffer.wrap(column.getValue())));\n                ageFound = true;\n            }\n        }\n\n        Assert.assertTrue(personNameFound && ageFound);\n        Thread.sleep(10000);\n\n        cqlResult = CassandraCli.client.execute_cql3_query(ByteBuffer\n                .wrap(\"Select ttl(\\\"PERSON_NAME\\\"), ttl(\\\"AGE\\\") from \\\"PERSONCASSANDRA\\\" where \\\"personId\\\" = '4'\"\n                        .getBytes()), Compression.NONE, ConsistencyLevel.ONE);\n\n        cqlRows = cqlResult.getRows();\n        try\n        {\n            cqlRow = cqlRows.get(0);\n            Assert.fail(\"PERSON_NAME and AGE column not deleted even though a TTL of 5 seconds was specified while writing to cassandra.\");\n        }\n        catch (IndexOutOfBoundsException ioobe)\n        {\n            Assert.assertTrue(cqlRows.isEmpty());\n        }\n\n        String deleteQuery = \"DELETE from PersonCassandra\";\n        q = em.createQuery(deleteQuery);\n        Assert.assertEquals(1, q.executeUpdate());\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/PersonCassandraTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.NoResultException;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport javax.persistence.TypedQuery;\nimport javax.persistence.criteria.CriteriaBuilder;\nimport javax.persistence.criteria.CriteriaQuery;\nimport javax.persistence.criteria.Expression;\nimport javax.persistence.criteria.Root;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.ColumnOrSuperColumn;\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.Mutation;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.thrift.CQLTranslator;\nimport com.impetus.client.cassandra.thrift.ThriftClient;\nimport com.impetus.client.crud.PersonCassandra.Day;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\n\n/**\n * Test case to perform simple CRUD operation.(insert, delete, merge, and\n * select)\n * \n * @author kuldeep.mishra\n * \n *         Run this script to create column family in cassandra with indexes.\n *         create column family PERSON with comparator=UTF8Type and\n *         column_metadata=[{column_name: PERSON_NAME, validation_class:\n *         UTF8Type, index_type: KEYS}, {column_name: AGE, validation_class:\n *         IntegerType, index_type: KEYS}];\n * \n */\npublic class PersonCassandraTest extends BaseTest\n{\n\n    /** The Constant SEC_IDX_CASSANDRA_TEST. */\n    private static final String SEC_IDX_CASSANDRA_TEST = \"genericCassandraTest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager entityManager;\n\n    /** The col. */\n    private Map<Object, Object> col;\n\n    /** The property map. */\n    protected Map propertyMap = null;\n\n    /** The auto manage schema. */\n    protected boolean AUTO_MANAGE_SCHEMA = true;\n\n    /** The use cql. */\n    protected boolean USE_CQL = false;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n\n        if (propertyMap == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            // loadData();\n        }\n        emf = Persistence.createEntityManagerFactory(SEC_IDX_CASSANDRA_TEST, propertyMap);\n        entityManager = emf.createEntityManager();\n        col = new java.util.HashMap<Object, Object>();\n    }\n\n    /**\n     * On insert cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onInsertCassandra() throws Exception\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n\n        Query findQuery = entityManager.createQuery(\"Select p from PersonCassandra p\", PersonCassandra.class);\n        List<PersonCassandra> allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = entityManager.createQuery(\"Select p from PersonCassandra p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = entityManager.createQuery(\"Select p.age from PersonCassandra p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n\n        PersonCassandra personWithKey = new PersonCassandra();\n        personWithKey.setPersonId(\"111\");\n        entityManager.persist(personWithKey);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n\n        entityManager.clear();\n        PersonCassandra p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertEquals(Day.thursday, p.getDay());\n\n        entityManager.clear();\n        Query q;\n        List<PersonCassandra> persons = queryOverRowkey();\n\n        assertFindByName(entityManager, \"PersonCassandra\", PersonCassandra.class, \"vivek\", \"personName\");\n        assertFindByNameAndAge(entityManager, \"PersonCassandra\", PersonCassandra.class, \"vivek\", \"10\", \"personName\");\n        assertFindByNameAndAgeGTAndLT(entityManager, \"PersonCassandra\", PersonCassandra.class, \"vivek\", \"10\", \"20\",\n                \"personName\");\n        assertFindByNameAndAgeBetween(entityManager, \"PersonCassandra\", PersonCassandra.class, \"vivek\", \"10\", \"15\",\n                \"personName\");\n        assertFindByRange(entityManager, \"PersonCassandra\", PersonCassandra.class, \"1\", \"2\", \"personId\", USE_CQL);\n        assertFindWithoutWhereClause(entityManager, \"PersonCassandra\", PersonCassandra.class, USE_CQL);\n\n        // perform merge after query.\n        for (PersonCassandra person : persons)\n        {\n            person.setPersonName(\"'after merge'\");\n            person.setDay(null);\n            entityManager.merge(person);\n\n        }\n\n        entityManager.clear();\n\n        p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"'after merge'\", p.getPersonName());\n        Assert.assertEquals(new Integer(10), p.getAge());\n\n        String updateQuery = \"update PersonCassandra p set p.personName='KK MISHRA' where p.personId=1\";\n        q = entityManager.createQuery(updateQuery);\n        q.executeUpdate();\n\n        entityManager.clear();\n        p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"KK MISHRA\", p.getPersonName());\n\n        // Test single result.\n        Query query = entityManager.createQuery(\"select p from PersonCassandra p\");\n        query.setMaxResults(1);\n        PersonCassandra result = (PersonCassandra) (query.getSingleResult());\n        Assert.assertNotNull(result);\n        Assert.assertEquals(Month.APRIL, result.getMonth());\n\n        query = entityManager.createQuery(\"select p from PersonCassandra p where p.personName = vivek\");\n        try\n        {\n            result = (PersonCassandra) (query.getSingleResult());\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (NoResultException nrex)\n        {\n            Assert.assertNotNull(nrex.getMessage());\n        }\n\n        // Test count native query.\n        testCountResult();\n\n        testCriteriaCountResult();\n\n        testLightWeightTransactions();\n\n        testINClause();\n\n        // Delete without WHERE clause.\n        String deleteQuery = \"DELETE from PersonCassandra\";\n        q = entityManager.createQuery(deleteQuery);\n        if (USE_CQL)\n        {\n            Assert.assertEquals(4, q.executeUpdate());\n        }\n        else\n        {\n            Assert.assertEquals(3, q.executeUpdate());\n        }\n\n    }\n\n    /**\n     * Test light weight transactions.\n     */\n    private void testLightWeightTransactions()\n    {\n        CQLTranslator translator = new CQLTranslator();\n        if (USE_CQL)\n        {\n            Map<String, Client> clientMap = (Map<String, Client>) entityManager.getDelegate();\n            ThriftClient tc = (ThriftClient) clientMap.get(SEC_IDX_CASSANDRA_TEST);\n            tc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n        }\n        String key = USE_CQL ? \"\\\"personId\\\"\" : \"key\";\n\n        String query = \"INSERT INTO \" + translator.ensureCase(new StringBuilder(), \"PERSONCASSANDRA\", false).toString()\n                + \" (\" + key + \", \\\"PERSON_NAME\\\") VALUES ('1', 'Karthik') IF NOT EXISTS\";\n        Query q = entityManager.createNativeQuery(query, PersonCassandra.class);\n        q.executeUpdate();\n        entityManager.clear();\n        PersonCassandra p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"KK MISHRA\", p.getPersonName());\n\n        query = \"INSERT INTO \" + translator.ensureCase(new StringBuilder(), \"PERSONCASSANDRA\", false).toString() + \" (\"\n                + key + \", \\\"PERSON_NAME\\\") VALUES ('4', 'Karthik') IF NOT EXISTS\";\n\n        q = entityManager.createNativeQuery(query, PersonCassandra.class);\n        q.executeUpdate();\n        entityManager.clear();\n        p = findById(PersonCassandra.class, \"4\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"Karthik\", p.getPersonName());\n\n        query = \"UPDATE \" + translator.ensureCase(new StringBuilder(), \"PERSONCASSANDRA\", false).toString()\n                + \" SET \\\"PERSON_NAME\\\" = 'Pragalbh' WHERE \" + key + \" = '4' IF \\\"PERSON_NAME\\\" = 'Karthik'\";\n        q = entityManager.createNativeQuery(query, PersonCassandra.class);\n        q.executeUpdate();\n        entityManager.clear();\n        p = findById(PersonCassandra.class, \"4\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"Pragalbh\", p.getPersonName());\n        String deleteQuery = \"DELETE from PersonCassandra p WHERE p.personId = '4'\";\n        q = entityManager.createQuery(deleteQuery);\n        q.executeUpdate();\n\n    }\n\n    /**\n     * test IN clause in select query.\n     */\n    private void testINClause()\n    {\n        if (USE_CQL)\n        {\n            Map<String, Client> clientMap = (Map<String, Client>) entityManager.getDelegate();\n            ThriftClient tc = (ThriftClient) clientMap.get(SEC_IDX_CASSANDRA_TEST);\n            tc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n            Query findQuery;\n            List<PersonCassandra> allPersons;\n            findQuery = entityManager.createQuery(\"Select p from PersonCassandra p where p.personId IN :idList\");\n            List<String> idList = new ArrayList<String>();\n            idList.add(\"1\");\n            idList.add(\"2\");\n            idList.add(\"3\");\n\n            findQuery.setParameter(\"idList\", idList);\n            allPersons = findQuery.getResultList();\n            Assert.assertNotNull(allPersons);\n            Assert.assertEquals(3, allPersons.size());\n\n            findQuery = entityManager.createQuery(\"Select p from PersonCassandra p where p.personId IN ?1\");\n            findQuery.setParameter(1, idList);\n            allPersons = findQuery.getResultList();\n            Assert.assertNotNull(allPersons);\n            Assert.assertEquals(3, allPersons.size());\n\n            entityManager.close();\n\n            entityManager = emf.createEntityManager();\n\n            findQuery = entityManager.createQuery(\"Select p from PersonCassandra p where p.personId IN :idList\");\n            findQuery.setParameter(\"idList\", new ArrayList<String>());\n            allPersons = findQuery.getResultList();\n            Assert.assertNotNull(allPersons);\n            Assert.assertTrue(allPersons.isEmpty());\n\n            findQuery = entityManager.createQuery(\"Select p from PersonCassandra p where p.personId IN ('1', '2')\");\n            allPersons = findQuery.getResultList();\n            Assert.assertNotNull(allPersons);\n            Assert.assertEquals(2, allPersons.size());\n\n            entityManager.close();\n\n            try\n            {\n                entityManager = emf.createEntityManager();\n                findQuery = entityManager.createQuery(\"Select p from PersonCassandra p where p.age IN (10 , 20)\");\n                allPersons = findQuery.getResultList();\n                Assert.fail();\n            }\n            catch (Exception e)\n            {\n                Assert.assertEquals(\n                        \"javax.persistence.PersistenceException: com.impetus.kundera.KunderaException: InvalidRequestException(why:IN predicates on non-primary-key columns (AGE) is not yet supported)\",\n                        e.getMessage());\n            }\n\n            tc.setCqlVersion(CassandraConstants.CQL_VERSION_2_0);\n        }\n        else\n        {\n            Query findQuery;\n            List<PersonCassandra> allPersons;\n            findQuery = entityManager.createQuery(\"Select p from PersonCassandra p where p.personName IN :nameList\");\n            List<String> nameList = new ArrayList<String>();\n            nameList.add(\"vivek\");\n            nameList.add(\"kk\");\n\n            findQuery.setParameter(\"nameList\", nameList);\n            try\n            {\n                allPersons = findQuery.getResultList();\n                Assert.fail();\n            }\n            catch (Exception e)\n            {\n                Assert.assertEquals(\"IN clause is not enabled for thrift, use cql3.\", e.getMessage());\n            }\n\n        }\n\n    }\n\n    /**\n     * Query over rowkey.\n     * \n     * @return the list\n     */\n    private List<PersonCassandra> queryOverRowkey()\n    {\n        String qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId = 1\";\n        Query q = entityManager.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n\n        qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId > 1\";\n        q = entityManager.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n\n        qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId < 2\";\n        q = entityManager.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n\n        qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId <= 2\";\n        q = entityManager.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n\n        qry = \"Select p from PersonCassandra p where p.personId >= 1\";\n        q = entityManager.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n\n        return persons;\n    }\n\n    /**\n     * Test criteria count result.\n     */\n    private void testCriteriaCountResult()\n    {\n        Map<String, Client> clientMap = (Map<String, Client>) entityManager.getDelegate();\n        ThriftClient tc = (ThriftClient) clientMap.get(SEC_IDX_CASSANDRA_TEST);\n        tc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n        CQLTranslator translator = new CQLTranslator();\n\n        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();\n\n        CriteriaQuery<Object> personQuery = criteriaBuilder.createQuery(Object.class);\n        Root<PersonCassandra> from = personQuery.from(PersonCassandra.class);\n        personQuery.select(criteriaBuilder.count((Expression<?>) from.alias(\"p\")));\n\n        Query q = entityManager.createQuery(personQuery);\n        List noOfRows = q.getResultList();\n\n        if (USE_CQL)\n        {\n            Assert.assertEquals(new Long(4), ((Map) noOfRows.get(0)).get(\"count\"));\n        }\n        else\n        {\n            Assert.assertEquals(new Long(3), ((Map) noOfRows.get(0)).get(\"count\"));\n        }\n\n        entityManager.clear();\n        q = entityManager.createNamedQuery(\"q\");\n        noOfRows = q.getResultList();\n        if (USE_CQL)\n        {\n            Assert.assertEquals(4, noOfRows.size());\n        }\n        else\n        {\n            Assert.assertEquals(3, noOfRows.size());\n        }\n        tc.setCqlVersion(CassandraConstants.CQL_VERSION_2_0);\n    }\n    /**\n     * Test count result.\n     */\n    private void testCountResult()\n    {\n        Map<String, Client> clientMap = (Map<String, Client>) entityManager.getDelegate();\n        ThriftClient tc = (ThriftClient) clientMap.get(SEC_IDX_CASSANDRA_TEST);\n        tc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n        CQLTranslator translator = new CQLTranslator();\n\n        String query = \"select count(*) from \"\n                + translator.ensureCase(new StringBuilder(), \"PERSONCASSANDRA\", false).toString();\n        Query q = entityManager.createNativeQuery(query, PersonCassandra.class);\n        List noOfRows = q.getResultList();\n\n        if (USE_CQL)\n        {\n            Assert.assertEquals(new Long(4), ((Map) noOfRows.get(0)).get(\"count\"));\n        }\n        else\n        {\n            Assert.assertEquals(new Long(3), ((Map) noOfRows.get(0)).get(\"count\"));\n        }\n\n        entityManager.clear();\n        q = entityManager.createNamedQuery(\"q\");\n        noOfRows = q.getResultList();\n        if (USE_CQL)\n        {\n            Assert.assertEquals(4, noOfRows.size());\n        }\n        else\n        {\n            Assert.assertEquals(3, noOfRows.size());\n        }\n        tc.setCqlVersion(CassandraConstants.CQL_VERSION_2_0);\n    }\n\n    /**\n     * On merge cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onMergeCassandra() throws Exception\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n\n        entityManager.clear();\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        PersonCassandra p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertEquals(Month.APRIL, p.getMonth());\n        // modify record.\n        p.setPersonName(\"newvivek\");\n        entityManager.merge(p);\n\n        assertOnMerge(entityManager, \"PersonCassandra\", PersonCassandra.class, \"vivek\", \"newvivek\", \"personName\");\n    }\n\n    /**\n     * On delete then insert cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onDeleteThenInsertCassandra() throws Exception\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        PersonCassandra p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        entityManager.remove(p);\n        entityManager.clear();\n\n        TypedQuery<PersonCassandra> query = entityManager.createQuery(\"Select p from PersonCassandra p\",\n                PersonCassandra.class);\n\n        List<PersonCassandra> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(Month.APRIL, results.get(0).getMonth());\n\n        p1 = prepareData(\"1\", 10);\n        entityManager.persist(p1);\n\n        query = entityManager.createQuery(\"Select p from PersonCassandra p\", PersonCassandra.class);\n\n        results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(Month.APRIL, results.get(0).getMonth());\n\n    }\n\n    /**\n     * On refresh cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onRefreshCassandra() throws Exception\n    {\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n\n        // Check for contains\n        Object pp1 = prepareData(\"1\", 10);\n        Object pp2 = prepareData(\"2\", 20);\n        Object pp3 = prepareData(\"3\", 15);\n        Assert.assertTrue(entityManager.contains(pp1));\n        Assert.assertTrue(entityManager.contains(pp2));\n        Assert.assertTrue(entityManager.contains(pp3));\n\n        // Check for detach\n        entityManager.detach(pp1);\n        entityManager.detach(pp2);\n        Assert.assertFalse(entityManager.contains(pp1));\n        Assert.assertFalse(entityManager.contains(pp2));\n        Assert.assertTrue(entityManager.contains(pp3));\n\n        // Modify value in database directly, refresh and then check PC\n        entityManager.clear();\n        entityManager = emf.createEntityManager();\n        Object o1 = entityManager.find(PersonCassandra.class, \"1\");\n\n        if (!USE_CQL)\n        {\n            // Create Insertion List\n            List<Mutation> insertionList = new ArrayList<Mutation>();\n            List<Column> columns = new ArrayList<Column>();\n            Column column = new Column();\n            column.setName(PropertyAccessorFactory.STRING.toBytes(\"PERSON_NAME\"));\n            column.setValue(PropertyAccessorFactory.STRING.toBytes(\"Amry\"));\n            column.setTimestamp(System.currentTimeMillis());\n            columns.add(column);\n            Mutation mut = new Mutation();\n            mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setColumn(column));\n            insertionList.add(mut);\n            // Create Mutation Map\n            Map<String, List<Mutation>> columnFamilyValues = new HashMap<String, List<Mutation>>();\n            columnFamilyValues.put(\"PERSONCASSANDRA\", insertionList);\n            Map<ByteBuffer, Map<String, List<Mutation>>> mulationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();\n            mulationMap.put(ByteBuffer.wrap(\"1\".getBytes()), columnFamilyValues);\n            CassandraCli.client.batch_mutate(mulationMap, ConsistencyLevel.ONE);\n        }\n        else\n        {\n            String query = \"insert into \\\"PERSONCASSANDRA\\\" (\\\"personId\\\",\\\"PERSON_NAME\\\",\\\"AGE\\\") values ('1','Amry',10 )\";\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(query.getBytes()), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        entityManager.refresh(o1);\n        Object oo1 = entityManager.find(PersonCassandra.class, \"1\");\n        Assert.assertTrue(entityManager.contains(o1));\n        Assert.assertEquals(\"Amry\", ((PersonCassandra) oo1).getPersonName());\n    }\n\n    /**\n     * On typed create query.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onTypedQuery() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        TypedQuery<PersonCassandra> query = entityManager.createQuery(\"Select p from PersonCassandra p\",\n                PersonCassandra.class);\n\n        List<PersonCassandra> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(Month.APRIL, results.get(0).getMonth());\n    }\n\n    /**\n     * On typed create query.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onGenericTypedQuery() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        TypedQuery<Object> query = entityManager.createQuery(\"Select p from PersonCassandra p\", Object.class);\n\n        List<Object> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(PersonCassandra.class, results.get(0).getClass());\n    }\n\n    /**\n     * on invalid typed query.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onInvalidTypedQuery() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n\n        TypedQuery<Group> query = null;\n        try\n        {\n            query = entityManager.createQuery(\"Select p from PersonCassandra p\", Group.class);\n            Assert.fail(\"Should have gone to catch block, as it is an invalid scenario!\");\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertNull(query);\n        }\n    }\n\n    /**\n     * On ghost rows.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onGhostRows() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        entityManager.clear();\n        PersonCassandra person = entityManager.find(PersonCassandra.class, \"1\");\n        entityManager.remove(person);\n        entityManager.clear(); // just to make sure that not to be picked up\n                               // from cache.\n        TypedQuery<PersonCassandra> query = entityManager.createQuery(\"Select p from PersonCassandra p\",\n                PersonCassandra.class);\n\n        List<PersonCassandra> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n    }\n\n    // @Test\n    /**\n     * Test with multiple thread.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    public void testWithMultipleThread() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        ExecutorService executor = Executors.newFixedThreadPool(10);\n\n        List<Future> futureList = new ArrayList<Future>();\n\n        for (int i = 1; i <= 1000; i++)\n        {\n            HandlePersist persist = new HandlePersist(i);\n            futureList.add(executor.submit(persist));\n        }\n\n        while (!futureList.isEmpty())\n        {\n            for (int i = 0; i < futureList.size(); i++)\n            {\n                if (futureList.get(i).isDone())\n                {\n                    futureList.remove(i);\n                }\n            }\n        }\n\n        String qry = \"Select * from \\\"PERSONCASSANDRA\\\"\";\n        Query q = entityManager.createNativeQuery(qry, PersonCassandra.class);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1000, persons.size());\n    }\n\n    /**\n     * The Class HandlePersist.\n     */\n    private class HandlePersist implements Runnable\n    {\n\n        /** The i. */\n        private int i;\n\n        /**\n         * Instantiates a new handle persist.\n         * \n         * @param i\n         *            the i\n         */\n        public HandlePersist(int i)\n        {\n            this.i = i;\n        }\n\n        /*\n         * (non-Javadoc)\n         * \n         * @see java.lang.Runnable#run()\n         */\n        @Override\n        public void run()\n        {\n            for (int j = 1; j <= 100; j++)\n            {\n                PersonCassandra foundObject = entityManager.find(PersonCassandra.class, \"\" + i * 1000);\n\n                if (foundObject != null)\n                {\n                    Assert.assertNotNull(foundObject.getPersonId());\n                    Assert.assertEquals(10 + j - 1, foundObject.getAge().intValue());\n                    Assert.assertEquals(\"vivek\" + (j - 1), foundObject.getPersonName());\n\n                    foundObject.setAge(10 + j);\n                    foundObject.setPersonName(\"vivek\" + j);\n                }\n                else\n                {\n                    foundObject = prepareData(\"\" + i * 1000, 10 + j);\n                    foundObject.setPersonName(\"vivek\" + j);\n                }\n                entityManager.persist(foundObject);\n            }\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        entityManager.close();\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n        KsDef ksDef = null;\n        CfDef user_Def = new CfDef();\n        user_Def.name = \"PERSONCASSANDRA\";\n        user_Def.keyspace = \"KunderaExamples\";\n        user_Def.setComparator_type(\"UTF8Type\");\n        user_Def.setDefault_validation_class(\"UTF8Type\");\n        user_Def.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"PERSON_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef);\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef1);\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"ENUM\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef2);\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"MONTH_ENUM\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef3);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaExamples\");\n            CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"PERSONCASSANDRA\"))\n                {\n\n                    CassandraCli.client.system_drop_column_family(\"PERSONCASSANDRA\");\n\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def);\n\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(\"KunderaExamples\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/PersonLuceneCassandra.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.sql.Timestamp;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaExamples@luceneCassandraTest\")\n@IndexCollection(columns = { @com.impetus.kundera.index.Index(name = \"personName\"),\n    @com.impetus.kundera.index.Index(name = \"age\"), @com.impetus.kundera.index.Index(name = \"date\") })\npublic class PersonLuceneCassandra {\n\n    private static final long serialVersionUID = 6068131491098913126L;\n\n    public static final String UID = \"uid\";\n\n    public static final String EID = \"eid\";\n\n    public static final String FIRST_NAME = \"firstName\";\n\n    public static final String LAST_NAME = \"lastName\";\n\n    public static final String CITY = \"city\";\n\n    public static final String CREATED = \"created\";\n\n    public static final String LAST_MODIFIED = \"lastModified\";\n\n    /** The person id. */\n    @Id\n    // @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private String age;\n\n    @Column(name = \"DATE\")\n    private Timestamp date;\n\n    public Timestamp getDate() {\n        return date;\n    }\n\n    public void setDate(Timestamp date) {\n        this.date = date;\n    }\n\n    @Column(name = \"AGEss\")\n    private byte[] a;\n\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    /**\n     * @return the a\n     */\n    public byte[] getA() {\n        return a;\n    }\n\n    /**\n     * @param a\n     *            the a to set\n     */\n    public void setA(byte[] a) {\n        this.a = a;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId() {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName() {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName) {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId) {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public String getAge() {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(String age) {\n        this.age = age;\n    }\n\n    /**\n     * @return the day\n     */\n    public Day getDay() {\n        return day;\n    }\n\n    /**\n     * @param day\n     *            the day to set\n     */\n    public void setDay(Day day) {\n        this.day = day;\n    }\n\n    enum Day {\n        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/PersonLuceneCassandraUUID.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.sql.Timestamp;\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSONUUID\", schema = \"KunderaExamples@luceneCassandraTest\")\n@IndexCollection(columns = { @com.impetus.kundera.index.Index(name = \"personName\"),\n    @com.impetus.kundera.index.Index(name = \"age\"), @com.impetus.kundera.index.Index(name = \"date\") })\npublic class PersonLuceneCassandraUUID {\n\n    private static final long serialVersionUID = 6068131491098913126L;\n\n    public static final String UID = \"uid\";\n\n    public static final String EID = \"eid\";\n\n    public static final String FIRST_NAME = \"firstName\";\n\n    public static final String LAST_NAME = \"lastName\";\n\n    public static final String CITY = \"city\";\n\n    public static final String CREATED = \"created\";\n\n    public static final String LAST_MODIFIED = \"lastModified\";\n\n    /** The person id. */\n    @Id\n    // @Column(name = \"PERSON_ID\")\n    // private String personId;\n    private UUID personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private String age;\n\n    @Column(name = \"DATE\")\n    private Timestamp date;\n\n    public Timestamp getDate() {\n        return date;\n    }\n\n    public void setDate(Timestamp date) {\n        this.date = date;\n    }\n\n    @Column(name = \"AGEss\")\n    private byte[] a;\n\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    /**\n     * @return the a\n     */\n    public byte[] getA() {\n        return a;\n    }\n\n    /**\n     * @param a\n     *            the a to set\n     */\n    public void setA(byte[] a) {\n        this.a = a;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public UUID getPersonId() {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName() {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName) {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(UUID personId) {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public String getAge() {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(String age) {\n        this.age = age;\n    }\n\n    /**\n     * @return the day\n     */\n    public Day getDay() {\n        return day;\n    }\n\n    /**\n     * @param day\n     *            the day to set\n     */\n    public void setDay(Day day) {\n        this.day = day;\n    }\n\n    enum Day {\n        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/SecondaryTableEntity.java",
    "content": "package com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.SecondaryTable;\nimport javax.persistence.Table;\n\n@Table(name = \"PRIMARY_TABLE\")\n@SecondaryTable(name = \"SECONDARY_TABLE\")\n@Entity\npublic class SecondaryTableEntity\n{\n    @Id\n    @Column(name = \"OBJECT_ID\")\n    private String objectId;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    @Column(name = \"AGE\", table = \"SECONDARY_TABLE\")\n    private int age;\n\n    @Embedded\n    private EmbeddedEntity embeddedEntity;\n\n    public String getObjectId()\n    {\n        return objectId;\n    }\n\n    public void setObjectId(String objectId)\n    {\n        this.objectId = objectId;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public EmbeddedEntity getEmbeddedEntity()\n    {\n        return embeddedEntity;\n    }\n\n    public void setEmbeddedEntity(EmbeddedEntity embeddedEntity)\n    {\n        this.embeddedEntity = embeddedEntity;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/Token.java",
    "content": "package com.impetus.client.crud;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"tokens\", schema = \"myapp@myapp_pu\")\n@IndexCollection(columns={@Index(name=\"tokenName\")})\npublic class Token\n{\n    @Id\n    @Column(name = \"token_id\")\n    private String id;\n\n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"client_id\")\n    private TokenClient client;\n    \n    @Column\n    private String tokenName;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public TokenClient getClient()\n    {\n        return client;\n    }\n\n    public void setClient(TokenClient client)\n    {\n        this.client = client;\n    }\n\n    public String getTokenName()\n    {\n        return tokenName;\n    }\n\n    public void setTokenName(String tokenName)\n    {\n        this.tokenName = tokenName;\n    }\n\n    \n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/TokenClient.java",
    "content": "package com.impetus.client.crud;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"client\", schema = \"myapp@myapp_pu\")\npublic class TokenClient\n{\n\n    @Id\n    @Column(name = \"client_id\")\n    private String id;\n\n    @Column(name = \"client_name\")\n    private String clientName;\n\n    @OneToMany(mappedBy = \"client\", fetch = FetchType.LAZY)\n    private Set<Token> tokens;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public String getClientName()\n    {\n        return clientName;\n    }\n\n    public void setClientName(String clientName)\n    {\n        this.clientName = clientName;\n    }\n\n    public Set<Token> getTokens()\n    {\n        return tokens;\n    }\n\n    public void setTokens(Set<Token> tokens)\n    {\n        this.tokens = tokens;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/TransientUser.java",
    "content": "/**\n * \n */\npackage com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"TUSER\", schema = \"KunderaExamples@secIdxCassandraTest\")\npublic class TransientUser\n{\n\n    @Id\n    @Column(name = \"USER_ID\")\n    private String userId;\n\n    @Column(name = \"USER_NAME\")\n    private String userName;\n\n    @Column(name = \"U_NAME\")\n    private transient String uName;\n\n    public TransientUser()\n    {\n        // TODO Auto-generated constructor stub\n    }\n\n    /**\n     * @return the personId\n     */\n    public String getPersonId()\n    {\n        return userId;\n    }\n\n    /**\n     * @param personId\n     *            the personId to set\n     */\n    public void setPersonId(String personId)\n    {\n        this.userId = personId;\n    }\n\n    /**\n     * @return the personName\n     */\n    public String getPersonName()\n    {\n        return userName;\n    }\n\n    /**\n     * @param personName\n     *            the personName to set\n     */\n    public void setPersonName(String personName)\n    {\n        this.userName = personName;\n    }\n\n    /**\n     * @return the uName\n     */\n    public String getuName()\n    {\n        return uName;\n    }\n\n    /**\n     * @param uName\n     *            the uName to set\n     */\n    public void setuName(String uName)\n    {\n        this.uName = uName;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/TransientUserTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.crud;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class TransientUserTest\n{\n\n    private static final String SEC_IDX_CASSANDRA_TEST = \"secIdxCassandraTest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        loadData();\n        emf = Persistence.createEntityManagerFactory(SEC_IDX_CASSANDRA_TEST);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    @Test\n    public void test()\n    {\n        TransientUser user = new TransientUser();\n        user.setPersonId(\"1233\");\n        user.setuName(\"kuldeep\");\n        user.setPersonName(\"kk\");\n\n        em.persist(user);\n        em.clear();\n        TransientUser foundUser = em.find(TransientUser.class, \"1233\");\n        Assert.assertNotNull(foundUser);\n        Assert.assertNull(foundUser.getuName());\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n\n        KsDef ksDef = null;\n        CfDef user_Def = new CfDef();\n        user_Def.name = \"TUSER\";\n        user_Def.keyspace = \"KunderaExamples\";\n        user_Def.setComparator_type(\"UTF8Type\");\n        user_Def.setDefault_validation_class(\"UTF8Type\");\n        user_Def.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"USER_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef);\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"U_NAME\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef1);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaExamples\");\n            CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"TUSER\"))\n                {\n\n                    CassandraCli.client.system_drop_column_family(\"TUSER\");\n\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def);\n\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(\"KunderaExamples\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/UpdateDeleteJPQLLiteralTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Junit test case for Update/Delete via query test.\n * \n * @author vivek.mishra\n * \n */\npublic class UpdateDeleteJPQLLiteralTest\n{\n\n    private static final String SEC_IDX_CASSANDRA_TEST = \"CassandraXmlPropertyTest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * Setup\n     * \n     * @throws IOException\n     * @throws TException\n     * @throws InvalidRequestException\n     * @throws UnavailableException\n     * @throws TimedOutException\n     * @throws SchemaDisagreementException\n     */\n    @Before\n    public void setUp() throws IOException, TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n        Map propertyMap = new HashMap();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(SEC_IDX_CASSANDRA_TEST, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test case to demonstrate update via query use case.\n     * \n     */\n    @Test\n    public void test()\n    {\n        MyTestEntity entity = new MyTestEntity();\n\n        UUID key = UUID.randomUUID();\n        entity.setKey(key);\n        entity.setUrl(\"url\");\n        em.persist(entity);\n\n        // With JPA where clause and update parameter.\n        String jpql = \"update MyTestEntity c set c.url = :url where c.key =:key\";\n\n        Query query = em.createQuery(jpql);\n        query.setParameter(\"url\", \"firstUpdate\");\n        query.setParameter(\"key\", key);\n        query.executeUpdate();\n\n        em.clear();\n\n        MyTestEntity found = em.find(MyTestEntity.class, key);\n\n        Assert.assertNotNull(found);\n        Assert.assertEquals(\"firstUpdate\", found.getUrl());\n\n        // Static where clause with update parameter\n        jpql = \"update MyTestEntity c set c.url = :url where c.key ='\" + key.toString()+\"'\";\n        query = em.createQuery(jpql);\n        query.setParameter(\"url\", \"secondUpdate\");\n        query.executeUpdate();\n\n        em.clear();\n        found = em.find(MyTestEntity.class, key);\n\n        Assert.assertNotNull(found);\n        Assert.assertEquals(\"secondUpdate\", found.getUrl());\n    }\n\n    /**\n     * JPA String literal test for Select, Update and Delete.\n     */\n    @Test\n    public void jpaStringLiteralTest()\n    {\n        MyTestEntity entity = new MyTestEntity();\n\n        UUID key = UUID.randomUUID();\n        entity.setKey(key);\n        entity.setUrl(\"url\");\n        em.persist(entity);\n\n        String staticJpaQueryEnclosing = \"Select e from MyTestEntity e where e.url = 'url'\";\n        Query query = em.createQuery(staticJpaQueryEnclosing);\n\n        List<MyTestEntity> result = query.getResultList();\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(1, result.size());\n        Assert.assertEquals(\"url\", result.get(0).getUrl());\n\n        String withoutEnclosed = \"Select e from MyTestEntity e where e.url = url\";\n        query = em.createQuery(withoutEnclosed);\n\n        result = query.getResultList();\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(1, result.size());\n        Assert.assertEquals(\"url\", result.get(0).getUrl());\n\n        MyTestEntity found = em.find(MyTestEntity.class, key);\n\n        Assert.assertNotNull(found);\n        Assert.assertEquals(\"url\", result.get(0).getUrl());\n\n        found.setUrl(\"url's\");\n\n        em.merge(found);\n\n        String dynamicQuery = \"Select e from MyTestEntity e where e.url = 'url''s'\";\n\n        query = em.createQuery(dynamicQuery);\n\n        result = query.getResultList();\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(1, result.size());\n        Assert.assertEquals(\"url's\", result.get(0).getUrl());\n\n        dynamicQuery = \"Select e from MyTestEntity e where e.url = :url\";\n        query = em.createQuery(dynamicQuery);\n        query.setParameter(\"url\", \"url's\");\n\n        result = query.getResultList();\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(1, result.size());\n        Assert.assertEquals(\"url's\", result.get(0).getUrl());\n\n        // Update by query\n        // With JPA where clause and update parameter.\n        String jpql = \"update MyTestEntity c set c.url = :url where c.key ='\" + key.toString()+\"'\";\n        query = em.createQuery(jpql);\n        query.setParameter(\"url\", \"updateUrl\");\n        query.executeUpdate();\n\n        em.clear();\n\n        found = em.find(MyTestEntity.class, key);\n\n        Assert.assertNotNull(found);\n        Assert.assertEquals(\"updateUrl\", found.getUrl());\n\n        jpql = \"update MyTestEntity c set c.url = 'enclosedUrl' where c.key = :key\";\n        query = em.createQuery(jpql);\n        query.setParameter(\"key\", key);\n        query.executeUpdate();\n\n        em.clear();\n        found = em.find(MyTestEntity.class, key);\n\n        Assert.assertNotNull(found);\n        Assert.assertEquals(\"enclosedUrl\", found.getUrl());\n\n        jpql = \"update MyTestEntity c set c.url = 'enclosedUrl''s' where c.key = :key\";\n        query = em.createQuery(jpql);\n        query.setParameter(\"key\", key);\n        query.executeUpdate();\n\n        em.clear();\n        found = em.find(MyTestEntity.class, key);\n        Assert.assertEquals(\"enclosedUrl's\", found.getUrl());\n\n        // Delete by non column.\n\n        jpql = \"Delete from MyTestEntity c where c.url = :url\";\n        query = em.createQuery(jpql);\n        query.setParameter(\"url\", \"enclosedUrl's\");\n        query.executeUpdate();\n\n        found = em.find(MyTestEntity.class, key);\n        Assert.assertNull(found);\n\n    }\n\n    @After\n    public void tearDown()\n    {\n        CassandraCli.dropKeySpace(\"KunderaCassandraXmlTest\");\n        em.close();\n        emf.close();\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/UserPromoCodeTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.entity.PromoCode;\nimport com.impetus.client.entity.Users;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class UserPromoCodeTest\n{\n    private static final String SEC_IDX_CASSANDRA_TEST = \"secIdxCassandraTest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        loadData();\n        emf = Persistence.createEntityManagerFactory(SEC_IDX_CASSANDRA_TEST);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * On insert cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onInsertUsers() throws Exception\n    {\n        Users u = new Users();\n        u.setFirstName(\"firstname\");\n        u.setLastName(\"lastname\");\n        u.setUserId(\"1_u\");\n\n        PromoCode promoCode1 = new PromoCode();\n        promoCode1.setPromoCodeId(\"1_p\");\n        promoCode1.setPromoCodeName(\"promoname1\");\n\n        u.getPromoCodes().add(promoCode1);\n\n        em.persist(u);\n\n        em.clear(); // to avoid fetch from cache and get from DB.\n\n        Users found = em.find(Users.class, \"1_u\");\n\n        Assert.assertNotNull(found);\n        Assert.assertEquals(\"firstname\", found.getFirstName());\n        Assert.assertEquals(1, found.getPromoCodes().size());\n\n        // add 1 more promo code.\n\n        PromoCode promoCode = new PromoCode();\n        promoCode.setPromoCodeId(\"2_p\");\n        promoCode.setPromoCodeName(\"promoname2\");\n\n        found.getPromoCodes().add(promoCode);\n        em.merge(found);\n\n        em.clear(); // to avoid fetch from cache get from DB.\n\n        found = em.find(Users.class, \"1_u\");\n\n        Assert.assertNotNull(found);\n        Assert.assertEquals(\"firstname\", found.getFirstName());\n        Assert.assertEquals(2, found.getPromoCodes().size());\n\n        // Delete\n        em.remove(found);\n\n        found = em.find(Users.class, \"1_u\");\n\n        Assert.assertNull(found);\n\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n        KsDef ksDef = null;\n        CfDef user_Def = new CfDef();\n        user_Def.name = \"users\";\n        user_Def.keyspace = \"KunderaExamples\";\n        user_Def.setComparator_type(\"UTF8Type\");\n        user_Def.setDefault_validation_class(\"UTF8Type\");\n        user_Def.setColumn_type(\"Super\");\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaExamples\");\n            CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"users\"))\n                {\n\n                    CassandraCli.client.system_drop_column_family(\"users\");\n\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def);\n\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(\"KunderaExamples\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n    }\n\n    @After\n    \n    public void tearDown()\n    {\n    \tem.close();\n    \temf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/batch/AddressBatch.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud.batch;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Entity class for batch operation\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ADDRESS_BATCH\", schema = \"KunderaExamples@batchTestSizeTwenty\")\n@IndexCollection(columns = { @Index(name = \"STREET\") })\npublic class AddressBatch\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The person name. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * @return the addressId\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * @param addressId\n     *            the addressId to set\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * @param street\n     *            the street to set\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/batch/CQL3BatchProcessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.batch;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.thrift.cql.CQLUser;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.api.Batcher;\n\n/**\n * @author Chhavi Gangwal\n * \n */\npublic class CQL3BatchProcessorTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private String persistenceUnit = \"cassandra_cql\";\n\n    /**\n     * setup the PU\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        Map propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create-drop\");\n\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        propertyMap.put(PersistenceProperties.KUNDERA_BATCH_SIZE, \"5\");\n\n        emf = Persistence.createEntityManagerFactory(persistenceUnit, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * closes em\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        emf = null;\n    }\n\n    /**\n     * tests batch execution process for cql3\n     */\n    @Test\n    public void testBatcherForCQL3()\n    {\n\n        Map<String, Integer> ttlValues = new HashMap<String, Integer>();\n        ttlValues.put(\"CQLUSER\", new Integer(5));\n        em.setProperty(\"ttl.per.request\", true);\n        em.setProperty(\"ttl.values\", ttlValues);\n        em.setProperty(PersistenceProperties.KUNDERA_BATCH_SIZE, 5);\n        int counter = 0;\n        List<CQLUser> rows = prepareData(10);\n        for (CQLUser entity : rows)\n        {\n            em.persist(entity);\n\n            // check for implicit flush.\n            if (++counter == 5)\n            {\n                Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n\n                Batcher client = (Batcher) clients.get(persistenceUnit);\n                Assert.assertEquals(5, client.getBatchSize());\n                // em.clear();\n                for (int i = 0; i < 5; i++)\n                {\n\n                    // assert on each batch size record\n                    Assert.assertNotNull(em.find(CQLUser.class, rows.get(i).getId()));\n\n                    Assert.assertNull(em.find(CQLUser.class, rows.get(9).getId()));\n                }\n                // means implicit flush must happen\n            }\n        }\n\n        // flush all on close.\n        // explicit flush on close\n        em.clear();\n        \n        \n        String sql = \" Delete from CQLUser p\";\n        Query query = em.createQuery(sql);\n        List<PersonBatchCassandraEntity> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(0, results.size());\n        em.close();\n    }\n\n    /**\n     * prepare teh dat afor batch execution\n     */\n    private List<CQLUser> prepareData(Integer noOfRecords)\n    {\n        List<CQLUser> persons = new ArrayList<CQLUser>();\n        for (int i = 1; i <= noOfRecords; i++)\n        {\n            CQLUser user = new CQLUser();\n            user.setId(i);\n            user.setName(\"Kuldeep\");\n            user.setAge(24);\n            persons.add(user);\n        }\n\n        return persons;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/batch/CassandraBatchProcessorMixedTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud.batch;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Test case for more than one entities persisted in the same batch\n * \n * @author amresh.singh\n */\npublic class CassandraBatchProcessorMixedTest\n{\n\n    private static final String CF_ADDRESS_BATCH = \"ADDRESS_BATCH\";\n\n    private static final String CF_PERSON_BATCH = \"PERSON_BATCH\";\n\n    private static final String KEYSPACE_KUNDERA_EXAMPLES = \"KunderaExamples\";\n\n    private static final String PERSISTENCE_UNIT = \"batchTestSizeTwenty\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(KEYSPACE_KUNDERA_EXAMPLES);\n        loadData();\n\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void onBatch()\n    {\n        List<PersonBatch> persons = preparePersonData(10);\n        List<AddressBatch> addresses = prepareAddressData(10);\n\n        // Insert Persons\n        for (PersonBatch person : persons)\n        {\n            em.persist(person);\n        }\n\n        // Insert Addresses\n        for (AddressBatch address : addresses)\n        {\n            em.persist(address);\n        }\n\n        // flush all on close.\n        // explicit flush on close\n        em.clear();\n        em.close();\n\n        em = emf.createEntityManager();\n\n        // Query on Persons\n        String personsQueryStr = \" Select p from PersonBatch p\";\n        Query personsQuery = em.createQuery(personsQueryStr);\n        List<PersonBatch> allPersons = personsQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(10, allPersons.size());\n\n        // Query on Addresses\n        String addressQueryStr = \" Select a from AddressBatch a\";\n        Query addressQuery = em.createQuery(addressQueryStr);\n        List<AddressBatch> allAddresses = addressQuery.getResultList();\n        Assert.assertNotNull(allAddresses);\n        Assert.assertEquals(10, allAddresses.size());\n\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    \tem.close();\n        emf.close();\n        CassandraCli.dropKeySpace(KEYSPACE_KUNDERA_EXAMPLES);\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n\n        KsDef ksDef = null;\n\n        CfDef user_Def = new CfDef();\n        user_Def.name = CF_PERSON_BATCH;\n        user_Def.keyspace = KEYSPACE_KUNDERA_EXAMPLES;\n        user_Def.setComparator_type(\"UTF8Type\");\n        user_Def.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"PERSON_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef);\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef1);\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"AGEss\".getBytes()), \"BytesType\");\n        columnDef2.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef2);\n\n        CfDef address_Def = new CfDef();\n        address_Def.name = CF_ADDRESS_BATCH;\n        address_Def.keyspace = KEYSPACE_KUNDERA_EXAMPLES;\n        address_Def.setComparator_type(\"UTF8Type\");\n        address_Def.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDefStreet = new ColumnDef(ByteBuffer.wrap(\"STREET\".getBytes()), \"UTF8Type\");\n        columnDefStreet.index_type = IndexType.KEYS;\n        address_Def.addToColumn_metadata(columnDefStreet);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def);\n        cfDefs.add(address_Def);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(KEYSPACE_KUNDERA_EXAMPLES);\n            CassandraCli.client.set_keyspace(KEYSPACE_KUNDERA_EXAMPLES);\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(CF_PERSON_BATCH))\n                {\n                    CassandraCli.client.system_drop_column_family(CF_PERSON_BATCH);\n                }\n                else if (cfDef1.getName().equalsIgnoreCase(CF_ADDRESS_BATCH))\n                {\n                    CassandraCli.client.system_drop_column_family(CF_ADDRESS_BATCH);\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def);\n            CassandraCli.client.system_add_column_family(address_Def);\n\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(KEYSPACE_KUNDERA_EXAMPLES, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n\n        CassandraCli.client.set_keyspace(KEYSPACE_KUNDERA_EXAMPLES);\n\n    }\n\n    private List<PersonBatch> preparePersonData(Integer noOfRecords)\n    {\n        List<PersonBatch> persons = new ArrayList<PersonBatch>();\n        for (int i = 1; i <= noOfRecords; i++)\n        {\n            PersonBatch o = new PersonBatch();\n            o.setPersonId(i + \"\");\n            o.setPersonName(\"Name \" + i);\n            o.setAge(10);\n            persons.add(o);\n        }\n        return persons;\n    }\n\n    private List<AddressBatch> prepareAddressData(Integer noOfRecords)\n    {\n        List<AddressBatch> addresses = new ArrayList<AddressBatch>();\n        for (int i = 1; i <= noOfRecords; i++)\n        {\n            AddressBatch o = new AddressBatch();\n            o.setAddressId(i + \"\");\n            o.setStreet(\"My Street \" + i);\n            addresses.add(o);\n        }\n        return addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/batch/CassandraBatchProcessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.batch;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.api.Batcher;\n\n/**\n * Batch processing test case for cassandra.\n * \n * @author vivek.mishra\n * \n */\npublic class CassandraBatchProcessorTest\n{\n\n    /**\n     * \n     */\n    private static final String PERSISTENCE_UNIT = \"secIdxBatchTest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    protected boolean AUTO_MANAGE_SCHEMA = true;\n\n    protected boolean USE_CQL = false;\n\n    protected Map propertyMap = null;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        // cassandraSetUp();\n        CassandraCli.cassandraSetUp();\n        // CassandraCli.initClient();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            loadData();\n        }\n\n        if (propertyMap == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_2_0);\n            propertyMap.put(\"kundera.batch.size\", \"5\");\n        }\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void onBatch()\n    {\n        int counter = 0;\n        List<PersonBatchCassandraEntity> rows = prepareData(10);\n        for (PersonBatchCassandraEntity entity : rows)\n        {\n            em.persist(entity);\n\n            // check for implicit flush.\n            if (++counter == 5)\n            {\n                Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n\n                Batcher client = (Batcher) clients.get(PERSISTENCE_UNIT);\n                Assert.assertEquals(5, client.getBatchSize());\n                em.clear();\n                for (int i = 0; i < 5; i++)\n                {\n\n                    // assert on each batch size record\n                    Assert.assertNotNull(em.find(PersonBatchCassandraEntity.class, rows.get(i).getPersonId()));\n\n                    // as batch size is 5.\n                    Assert.assertNull(em.find(PersonBatchCassandraEntity.class, rows.get(6).getPersonId()));\n                }\n                // means implicit flush must happen\n            }\n        }\n\n        // flush all on close.\n        // explicit flush on close\n        em.clear();\n        em.close();\n\n        em = emf.createEntityManager();\n\n        String sql = \" Select p from PersonBatchCassandraEntity p\";\n        Query query = em.createQuery(sql);\n        List<PersonBatchCassandraEntity> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(10, results.size());\n        \n        sql = \" Delete from PersonBatchCassandraEntity p\";\n        query = em.createQuery(sql);\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(0, results.size());\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    \tem.close();\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n\n        KsDef ksDef = null;\n        CfDef user_Def = new CfDef();\n        user_Def.name = \"PERSON_BATCH\";\n        user_Def.keyspace = \"KunderaExamples\";\n        user_Def.setComparator_type(\"UTF8Type\");\n        user_Def.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"PERSON_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef);\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef1);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaExamples\");\n            CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"PERSON_BATCH\"))\n                {\n\n                    CassandraCli.client.system_drop_column_family(\"PERSON_BATCH\");\n\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def);\n\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(\"KunderaExamples\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n    }\n\n    private List<PersonBatchCassandraEntity> prepareData(Integer noOfRecords)\n    {\n        List<PersonBatchCassandraEntity> persons = new ArrayList<PersonBatchCassandraEntity>();\n        for (int i = 1; i <= noOfRecords; i++)\n        {\n            PersonBatchCassandraEntity o = new PersonBatchCassandraEntity();\n            o.setPersonId(i + \"\");\n            o.setPersonName(\"vivek\" + i);\n            o.setAge(10);\n            persons.add(o);\n        }\n\n        return persons;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/batch/PersonBatch.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud.batch;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Entity class for Person in Batch operation\n * \n * @author amresh.singh\n */\n@Entity\n@Table(name = \"PERSON_BATCH\", schema = \"KunderaExamples@batchTestSizeTwenty\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\npublic class PersonBatch\n{\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"AGEss\")\n    private byte[] a;\n\n    /**\n     * @return the a\n     */\n    public byte[] getA()\n    {\n        return a;\n    }\n\n    /**\n     * @param a\n     *            the a to set\n     */\n    public void setA(byte[] a)\n    {\n        this.a = a;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/batch/PersonBatchCassandraEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.batch;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON_BATCH\", schema = \"KunderaExamples@secIdxBatchTest\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\npublic class PersonBatchCassandraEntity\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"AGEss\")\n    private byte[] a;\n\n    /**\n     * @return the a\n     */\n    public byte[] getA()\n    {\n        return a;\n    }\n\n    /**\n     * @param a\n     *            the a to set\n     */\n    public void setA(byte[] a)\n    {\n        this.a = a;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/collection/BlogPost.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.collection;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.NamedNativeQuery;\nimport javax.persistence.NamedQuery;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Entity class for Blog post\n * @author amresh.singh\n */\n@Entity\n@Table(name=\"blog_posts\", schema=\"KunderaExamples@secIdxCassandraTest\")\n@NamedNativeQuery(name=\"select.post.1\", query=\"select * from blog_posts where post_id = 1\")\n@NamedQuery(name=\"select.post.2\", query=\"Select p from BlogPost p where p.postId=2\")\n@IndexCollection(columns = { @Index(name = \"body\"), @Index(name = \"tags\"), @Index(name = \"likedBy\"), @Index(name = \"comments\") })\npublic class BlogPost\n{    \n    @Id\n    @Column(name=\"post_id\")\n    private int postId;\n    \n    //Body of the post\n    @Column(name=\"body\")\n    private String body;       \n    \n    //Useful tags specified by author\n    @ElementCollection\n    @Column(name=\"tags\")\n    private Set<String> tags;  \n    \n    //List of user IDs who liked this blog post\n    @ElementCollection\n    @Column(name=\"liked_by\")\n    private List<Integer> likedBy;   \n    \n    //User IDs and their respective comments on this blog\n    @ElementCollection\n    @Column(name=\"comments\")\n    private Map<Integer, String> comments; \n\n    /**\n     * @return the postId\n     */\n    public int getPostId()\n    {\n        return postId;\n    }\n\n    /**\n     * @param postId the postId to set\n     */\n    public void setPostId(int postId)\n    {\n        this.postId = postId;\n    }\n\n    /**\n     * @return the body\n     */\n    public String getBody()\n    {\n        return body;\n    }\n\n    /**\n     * @param body the body to set\n     */\n    public void setBody(String body)\n    {\n        this.body = body;\n    }\n\n    /**\n     * @return the tags\n     */\n    public Set<String> getTags()\n    {\n        return tags;\n    }\n\n    /**\n     * @param tags the tags to set\n     */\n    public void setTags(Set<String> tags)\n    {\n        this.tags = tags;\n    }\n\n    /**\n     * @return the likedBy\n     */\n    public List<Integer> getLikedBy()\n    {\n        return likedBy;\n    }\n\n    /**\n     * @param likedBy the likedBy to set\n     */\n    public void setLikedBy(List<Integer> likedBy)\n    {\n        this.likedBy = likedBy;\n    }\n\n    /**\n     * @return the comments\n     */\n    public Map<Integer, String> getComments()\n    {\n        return comments;\n    }\n\n    /**\n     * @param comments the comments to set\n     */\n    public void setComments(Map<Integer, String> comments)\n    {\n        this.comments = comments;\n    }\n    \n    public void addTag(String tag)\n    {\n        if(tags == null)\n        {\n            tags = new HashSet<String>();\n        }\n        tags.add(tag);\n    }\n    \n    public void addLikedBy(Integer likedByUserId)\n    {\n        if(likedBy == null)\n        {\n            likedBy = new ArrayList<Integer>();\n        }\n        likedBy.add(likedByUserId);\n    }\n    \n    public void addComment(Integer userId, String comment)\n    {\n        if(comments == null)\n        {\n            comments = new HashMap<Integer, String>();\n        }\n        comments.put(userId, comment);\n    }\n    \n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/collection/BlogPostTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.collection;\n\nimport java.nio.ByteBuffer;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Test case for Storing and retrieving Blog posts. 1. Validates correct\n * functioning of Element collection for basic types 2. Checks all types of\n * collection (Set, Map, List)\n * \n * @author amresh.singh\n */\npublic class BlogPostTest\n{\n    EntityManagerFactory emf;\n\n    EntityManager em;\n\n    String persistenceUnit = \"secIdxCassandraTest\";\n\n    private boolean RUN_IN_EMBEDDED_MOODE = true;\n\n    private boolean AUTO_MANAGE_SCHEMA = true;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        if (RUN_IN_EMBEDDED_MOODE)\n        {\n            CassandraCli.cassandraSetUp();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n\n            createKeyspace();\n            createColumnFamily();\n        }\n\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        em = emf.createEntityManager();\n        em.setProperty(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        // Insert records\n        BlogPost p1 = prepareBlogPost1();\n        BlogPost p2 = prepareBlogPost2();\n\n        em.persist(p1);\n        em.persist(p2);\n\n        // Find records by ID\n        em.clear();\n        BlogPost pp1 = em.find(BlogPost.class, 1);\n        BlogPost pp2 = em.find(BlogPost.class, 2);\n\n        assertPost1(pp1);\n        assertPost2(pp2);\n\n        // Update records\n        modifyBlogPost1(pp1);\n        modifyBlogPost2(pp2);\n\n        em.merge(pp1);\n        em.merge(pp2);\n\n        em.clear();\n        pp1 = em.find(BlogPost.class, 1);\n        pp2 = em.find(BlogPost.class, 2);\n\n        assertUpdatedPost1(pp1);\n        assertUpdatedPost2(pp2);\n\n        // Remove records\n        em.remove(pp1);\n        em.remove(pp2);\n\n        em.clear();\n        pp1 = em.find(BlogPost.class, 1);\n        pp2 = em.find(BlogPost.class, 2);\n\n        Assert.assertNull(pp1);\n        Assert.assertNull(pp2);\n    }\n\n    @Test\n    public void testJPAQuery()\n    {\n        // Insert records\n        BlogPost p1 = prepareBlogPost1();\n        BlogPost p2 = prepareBlogPost2();\n\n        em.persist(p1);\n        em.persist(p2);\n\n        // Select All query\n        Query q = em.createQuery(\"Select p from BlogPost p\");\n        List<BlogPost> allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(2, allPosts.size());\n        assertPost1(allPosts.get(0));\n        assertPost2(allPosts.get(1));\n\n        // Search over Row ID\n        q = em.createQuery(\"Select p from BlogPost p where p.postId=:postId\");\n        q.setParameter(\"postId\", 1);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertPost1(allPosts.get(0));\n\n        // Search over Body column\n        q = em.createQuery(\"Select p from BlogPost p where p.body=:body\");\n        q.setParameter(\"body\", \"Kundera - Knight in the shining armor!\");\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertPost2(allPosts.get(0));\n\n        // Update Query\n        q = em.createQuery(\"update BlogPost p set p.body=:body,p.tags=:tags,p.likedBy=:likedBy,p.comments=:comments where p.postId=1\");\n        modifyBlogPost1(p1);\n        q.setParameter(\"body\", p1.getBody());\n        q.setParameter(\"tags\", p1.getTags());\n        q.setParameter(\"likedBy\", p1.getLikedBy());\n        q.setParameter(\"comments\", p1.getComments());\n        int updatedRecords = q.executeUpdate();\n\n        em.clear();\n        q = em.createQuery(\"Select p from BlogPost p where p.postId=:postId\");\n        q.setParameter(\"postId\", 1);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertUpdatedPost1(allPosts.get(0));\n\n        // Named Query\n        em.clear();\n        q = em.createNamedQuery(\"select.post.2\");\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertPost2(allPosts.get(0));\n\n        // Delete Query\n        q = em.createQuery(\"DELETE from BlogPost\");\n        int deleteCount = q.executeUpdate();\n        Assert.assertEquals(2, deleteCount);\n\n        em.clear();\n        q = em.createQuery(\"Select p from BlogPost p\");\n        allPosts = q.getResultList();\n        Assert.assertTrue(allPosts == null || allPosts.isEmpty());\n    }\n\n    @Test\n    public void testNativeQuery()\n    {\n        // Insert records\n        BlogPost p1 = prepareBlogPost1();\n        BlogPost p2 = prepareBlogPost2();\n\n        em.persist(p1);\n        em.persist(p2);\n\n        // Select All query\n        Query q = em.createNativeQuery(\"select * from blog_posts\", BlogPost.class);\n        List<BlogPost> allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(2, allPosts.size());\n        assertPost1(allPosts.get(0));\n        assertPost2(allPosts.get(1));\n\n        // Search over a column\n        q = em.createNativeQuery(\"select * from blog_posts where body='Working with MongoDB using Kundera'\",\n                BlogPost.class);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertPost1(allPosts.get(0));\n\n        // Updating set, list and map for Blog Post 1\n        q = em.createNativeQuery(\"update blog_posts set body = 'Updated body 1' where post_id = 1\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"update blog_posts set tags = tags + {'new tag 1'} where post_id = 1\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"update blog_posts set liked_by = liked_by - [111] where post_id = 1\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"update blog_posts set comments = comments + {888:'New comment 1'} where post_id = 1\",\n                BlogPost.class);\n        q.executeUpdate();\n\n        q = em.createNativeQuery(\"select * from blog_posts where post_id = 1\", BlogPost.class);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertUpdatedPost1(allPosts.get(0));\n\n        // Updating set, list and map for Blog Post 2\n        q = em.createNativeQuery(\"update blog_posts set body = 'Updated body 2' where post_id = 2\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"update blog_posts set tags = tags + {'new tag 2'} where post_id = 2\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"update blog_posts set liked_by = liked_by - [444] where post_id = 2\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"update blog_posts set comments = comments + {999:'New comment 2'} where post_id = 2\",\n                BlogPost.class);\n        q.executeUpdate();\n\n        // Native select query\n        q = em.createNativeQuery(\"select * from blog_posts where post_id = 2\", BlogPost.class);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertUpdatedPost2(allPosts.get(0));\n\n        // Named native query\n        q = em.createNativeQuery(\"select.post.1\", BlogPost.class);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertUpdatedPost1(allPosts.get(0));\n\n        // Delete all posts\n        q = em.createNativeQuery(\"delete from blog_posts where post_id = 1\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"delete from blog_posts where post_id = 2\", BlogPost.class);\n        q.executeUpdate();\n\n        q = em.createNativeQuery(\"select * from blog_posts\", BlogPost.class);\n        allPosts = q.getResultList();\n        Assert.assertTrue(allPosts == null || allPosts.isEmpty());\n    }\n\n    @Test\n    public void testCollectionWithNullValues()\n    {\n        // Insert records\n        BlogPost p1 = prepareBlogPost1();\n        BlogPost p2 = prepareBlogPost2();\n\n        try\n        {\n            // Testing map containing null as value.\n            p1.addComment(444, null);\n            em.persist(p1);\n            Assert.fail(\"Should have gone into catch block.\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\"com.impetus.kundera.KunderaException: InvalidRequestException(why:null is not supported inside collections)\", e.getMessage());\n        }\n        try\n        {\n            // Testing map containing null as key and value.\n            p2.addComment(null, null);\n            em.persist(p2);\n            Assert.fail(\"Should have gone into catch block.\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\"com.impetus.kundera.KunderaException: InvalidRequestException(why:null is not supported inside collections)\", e.getMessage());\n        }\n\n        p1 = prepareBlogPost1();\n        p2 = prepareBlogPost2();\n\n        try\n        {\n            // Testing list containing null as value.\n            p1.addLikedBy(null);\n            em.persist(p1);\n            Assert.fail(\"Should have gone into catch block.\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\"com.impetus.kundera.KunderaException: InvalidRequestException(why:null is not supported inside collections)\", e.getMessage());\n        }\n\n        try\n        {\n            // Testing set containing null as value.\n            p2.addTag(null);\n            em.persist(p2);\n            Assert.fail(\"Should have gone into catch block.\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\"com.impetus.kundera.KunderaException: InvalidRequestException(why:null is not supported inside collections)\", e.getMessage());\n        }\n\n    }\n    \n    @Test\n    public void testCollectionIndexes()\n    {\n        // Insert records\n        BlogPost p1 = prepareBlogPost1();\n        BlogPost p2 = prepareBlogPost2();\n\n        em.persist(p1);\n        em.persist(p2);\n        \n        em.clear();\n\n        // Select All query\n        Query q = em.createQuery(\"Select p from BlogPost p\");\n        List<BlogPost> allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(2, allPosts.size());\n        assertPost1(allPosts.get(0));\n        assertPost2(allPosts.get(1));\n\n        // Search over tags Set\n        q = em.createQuery(\"Select p from BlogPost p where p.tags = :tags\");\n        q.setParameter(\"tags\", \"nosql\");\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(2, allPosts.size());\n        assertPost1(allPosts.get(0));\n        assertPost2(allPosts.get(1));\n\n        // Search over likedBy List\n        q = em.createQuery(\"Select p from BlogPost p where p.likedBy = :likedBy\");\n        q.setParameter(\"likedBy\", 555);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertPost2(allPosts.get(0));\n\n     // Search over comments Map\n        q = em.createQuery(\"Select p from BlogPost p where p.comments = :comments\");\n        q.setParameter(\"comments\", \"Great work\");\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertPost2(allPosts.get(0));\n\n    }\n\n    private BlogPost prepareBlogPost1()\n    {\n        BlogPost p1 = new BlogPost();\n        p1.setPostId(1);\n        p1.setBody(\"Working with MongoDB using Kundera\");\n\n        p1.addTag(\"nosql\");\n        p1.addTag(\"kundera\");\n        p1.addTag(\"mongo\");\n\n        p1.addLikedBy(111);\n        p1.addLikedBy(222);\n\n        p1.addComment(111, \"What a post!\");\n        p1.addComment(222, \"I am getting NPE on line no. 145\");\n        p1.addComment(333, \"My hobby is to spam blogs\");\n        return p1;\n    }\n\n    private BlogPost prepareBlogPost2()\n    {\n        BlogPost p2 = new BlogPost();\n        p2.setPostId(2);\n        p2.setBody(\"Kundera - Knight in the shining armor!\");\n\n        p2.addTag(\"nosql\");\n        p2.addTag(\"cassandra\");\n        p2.addTag(\"kundera\");\n        p2.addTag(\"jpa\");\n\n        p2.addLikedBy(333);\n        p2.addLikedBy(444);\n        p2.addLikedBy(555);\n\n        p2.addComment(333, \"Great work\");\n        p2.addComment(555, \"Doesn't work on my machine\");\n        p2.addComment(777, \"Wanna buy medicines from my store?\");\n        return p2;\n    }\n\n    private void modifyBlogPost1(BlogPost p)\n    {\n        p.setBody(\"Updated body 1\");\n        p.getTags().add(\"new tag 1\");\n        p.getLikedBy().remove(0);\n        p.addComment(888, \"New comment 1\");\n    }\n\n    private void modifyBlogPost2(BlogPost p)\n    {\n        p.setBody(\"Updated body 2\");\n        p.getTags().add(\"new tag 2\");\n        p.getLikedBy().remove(1);\n        p.addComment(999, \"New comment 2\");\n    }\n\n    private void assertPost1(BlogPost p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPostId());\n        Assert.assertEquals(\"Working with MongoDB using Kundera\", p.getBody());\n\n        Assert.assertNotNull(p.getTags());\n        Assert.assertFalse(p.getTags().isEmpty());\n        Assert.assertEquals(3, p.getTags().size());\n        for (String tag : p.getTags())\n        {\n            Assert.assertTrue(tag.equals(\"nosql\") || tag.equals(\"kundera\") || tag.equals(\"mongo\"));\n        }\n\n        Assert.assertNotNull(p.getLikedBy());\n        Assert.assertFalse(p.getLikedBy().isEmpty());\n        Assert.assertEquals(2, p.getLikedBy().size());\n        for (int likedUserId : p.getLikedBy())\n        {\n            Assert.assertTrue(likedUserId == 111 || likedUserId == 222);\n        }\n\n        Assert.assertNotNull(p.getComments());\n        Assert.assertFalse(p.getComments().isEmpty());\n        Assert.assertEquals(3, p.getComments().size());\n        for (int commentedBy : p.getComments().keySet())\n        {\n            String commentText = p.getComments().get(commentedBy);\n            Assert.assertTrue(commentedBy == 111 || commentedBy == 222 || commentedBy == 333);\n            Assert.assertTrue(commentText.equals(\"What a post!\")\n                    || commentText.equals(\"I am getting NPE on line no. 145\")\n                    || commentText.equals(\"My hobby is to spam blogs\"));\n        }\n    }\n\n    private void assertPost2(BlogPost p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(2, p.getPostId());\n        Assert.assertEquals(\"Kundera - Knight in the shining armor!\", p.getBody());\n\n        Assert.assertNotNull(p.getTags());\n        Assert.assertFalse(p.getTags().isEmpty());\n        Assert.assertEquals(4, p.getTags().size());\n        for (String tag : p.getTags())\n        {\n            Assert.assertTrue(tag.equals(\"nosql\") || tag.equals(\"cassandra\") || tag.equals(\"kundera\")\n                    || tag.equals(\"jpa\"));\n        }\n\n        Assert.assertNotNull(p.getLikedBy());\n        Assert.assertFalse(p.getLikedBy().isEmpty());\n        Assert.assertEquals(3, p.getLikedBy().size());\n        for (int likedUserId : p.getLikedBy())\n        {\n            Assert.assertTrue(likedUserId == 333 || likedUserId == 444 || likedUserId == 555);\n        }\n\n        Assert.assertNotNull(p.getComments());\n        Assert.assertFalse(p.getComments().isEmpty());\n        Assert.assertEquals(3, p.getComments().size());\n        for (int commentedBy : p.getComments().keySet())\n        {\n            String commentText = p.getComments().get(commentedBy);\n            Assert.assertTrue(commentedBy == 333 || commentedBy == 555 || commentedBy == 777);\n            Assert.assertTrue(commentText.equals(\"Great work\") || commentText.equals(\"Doesn't work on my machine\")\n                    || commentText.equals(\"Wanna buy medicines from my store?\"));\n        }\n    }\n\n    private void assertUpdatedPost1(BlogPost p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPostId());\n        Assert.assertEquals(\"Updated body 1\", p.getBody());\n\n        Assert.assertNotNull(p.getTags());\n        Assert.assertFalse(p.getTags().isEmpty());\n        Assert.assertEquals(4, p.getTags().size());\n        for (String tag : p.getTags())\n        {\n            Assert.assertTrue(tag.equals(\"nosql\") || tag.equals(\"kundera\") || tag.equals(\"mongo\")\n                    || tag.equals(\"new tag 1\"));\n        }\n\n        Assert.assertNotNull(p.getLikedBy());\n        Assert.assertFalse(p.getLikedBy().isEmpty());\n        Assert.assertEquals(1, p.getLikedBy().size());\n        for (int likedUserId : p.getLikedBy())\n        {\n            Assert.assertTrue(likedUserId == 222);\n        }\n\n        Assert.assertNotNull(p.getComments());\n        Assert.assertFalse(p.getComments().isEmpty());\n        Assert.assertEquals(4, p.getComments().size());\n        for (int commentedBy : p.getComments().keySet())\n        {\n            String commentText = p.getComments().get(commentedBy);\n            Assert.assertTrue(commentedBy == 111 || commentedBy == 222 || commentedBy == 333 || commentedBy == 888);\n            Assert.assertTrue(commentText.equals(\"What a post!\")\n                    || commentText.equals(\"I am getting NPE on line no. 145\")\n                    || commentText.equals(\"My hobby is to spam blogs\") || commentText.equals(\"New comment 1\"));\n        }\n\n    }\n\n    private void assertUpdatedPost2(BlogPost p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(2, p.getPostId());\n        Assert.assertEquals(\"Updated body 2\", p.getBody());\n\n        Assert.assertNotNull(p.getTags());\n        Assert.assertFalse(p.getTags().isEmpty());\n        Assert.assertEquals(5, p.getTags().size());\n        for (String tag : p.getTags())\n        {\n            Assert.assertTrue(tag.equals(\"nosql\") || tag.equals(\"cassandra\") || tag.equals(\"kundera\")\n                    || tag.equals(\"jpa\") || tag.equals(\"new tag 2\"));\n        }\n\n        Assert.assertNotNull(p.getLikedBy());\n        Assert.assertFalse(p.getLikedBy().isEmpty());\n        Assert.assertEquals(2, p.getLikedBy().size());\n        for (int likedUserId : p.getLikedBy())\n        {\n            Assert.assertTrue(likedUserId == 333 || likedUserId == 555);\n        }\n\n        Assert.assertNotNull(p.getComments());\n        Assert.assertFalse(p.getComments().isEmpty());\n        Assert.assertEquals(4, p.getComments().size());\n        for (int commentedBy : p.getComments().keySet())\n        {\n            String commentText = p.getComments().get(commentedBy);\n            Assert.assertTrue(commentedBy == 333 || commentedBy == 555 || commentedBy == 777 || commentedBy == 999);\n            Assert.assertTrue(commentText.equals(\"Great work\") || commentText.equals(\"Doesn't work on my machine\")\n                    || commentText.equals(\"Wanna buy medicines from my store?\") || commentText.equals(\"New comment 2\"));\n        }\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        if (emf != null && emf.isOpen())\n        {\n            emf.close();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            CassandraCli.executeCqlQuery(\"TRUNCATE blog_posts\", \"KunderaExamples\");\n            CassandraCli.executeCqlQuery(\"DROP TABLE blog_posts\", \"KunderaExamples\");\n            CassandraCli.executeCqlQuery(\"DROP KEYSPACE \\\"KunderaExamples\\\"\", \"KunderaExamples\");\n        }\n\n    }\n\n    private void createColumnFamily()\n    {\n        try\n        {\n            CassandraCli.executeCqlQuery(\"USE \\\"KunderaExamples\\\"\", \"KunderaExamples\");\n            CassandraCli\n                    .executeCqlQuery(\n                            \"CREATE TABLE blog_posts (post_id int PRIMARY KEY, body text, tags set<text>, liked_by list<int>, comments map<int, text>)\",\n                            \"KunderaExamples\");\n            CassandraCli.executeCqlQuery(\"CREATE INDEX ON blog_posts(body)\", \"KunderaExamples\");\n            CassandraCli.executeCqlQuery(\"CREATE INDEX ON blog_posts(tags)\", \"KunderaExamples\");\n            CassandraCli.executeCqlQuery(\"CREATE INDEX ON blog_posts(comments)\", \"KunderaExamples\");\n            CassandraCli.executeCqlQuery(\"CREATE INDEX ON blog_posts(liked_by)\", \"KunderaExamples\");\n        }\n        catch (Exception e)\n        {\n        }\n    }\n\n    private void createKeyspace()\n    {\n        try\n        {\n            CassandraCli\n                    .getClient()\n                    .execute_cql3_query(\n                            ByteBuffer.wrap(\"CREATE KEYSPACE \\\"KunderaExamples\\\" WITH replication = {'class':'SimpleStrategy','replication_factor':3}\"\n                                    .getBytes(\"UTF-8\")), Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception e)\n        {\n\n        }\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/CQLTranslatorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.thrift.CQLTranslator;\nimport com.impetus.client.cassandra.thrift.CQLTranslator.TranslationType;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * JUnit for CQL translator test\n * \n * @author vivek.mishra\n * \n */\npublic class CQLTranslatorTest\n{\n    private EntityManagerFactory emf;\n\n    private static final Logger logger = LoggerFactory.getLogger(CassandraCompositeTypeTest.class);\n    \n    private static final String KEYSPACE = \"CompositeCassandra\";\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n    \tCassandraCli.dropKeySpace(KEYSPACE);\n        CassandraCli.cassandraSetUp();\n        emf = Persistence.createEntityManagerFactory(\"composite_pu\");\n    }\n\n    @Test\n    public void testPrepareColumns()\n    {\n        logger.info(\"On prepare columns.\");\n        CQLTranslator translator = new CQLTranslator();\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n        CassandraPrimeUser user = new CassandraPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance(), CassandraPrimeUser.class);\n        Map<String, StringBuilder> translatedSql = translator\n                .prepareColumnOrColumnValues(user, entityMetadata, TranslationType.VALUE, null, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance()).get(\n                        TranslationType.VALUE);\n        String columnAsCsv = \"'mevivs',1,\" + timeLineId /*+ \",'my first tweet','\" + currentDate.getTime() + */ /*+ \"'\"*/;\n        \n        Assert.assertTrue(StringUtils.contains(translatedSql.get(entityMetadata.getTableName()).toString(), columnAsCsv));\n//        Assert.assertEquals(columnAsCsv, translatedSql);\n    }\n    \n    @Test\n    public void testGetKeyword()\n    {\n        CQLTranslator translator = new CQLTranslator();\n        Assert.assertEquals(\"read_repair_chance\", translator.getKeyword(CassandraConstants.READ_REPAIR_CHANCE));\n        Assert.assertEquals(\"dclocal_read_repair_chance\", translator.getKeyword(CassandraConstants.DCLOCAL_READ_REPAIR_CHANCE));\n        Assert.assertEquals(\"bloom_filter_fp_chance\", translator.getKeyword(CassandraConstants.BLOOM_FILTER_FP_CHANCE));\n        Assert.assertEquals(\"compaction_strategy_class\", translator.getKeyword(CassandraConstants.COMPACTION_STRATEGY));\n        Assert.assertEquals(\"bloom_filter_fp_chance\", translator.getKeyword(CassandraConstants.BLOOM_FILTER_FP_CHANCE));\n        Assert.assertEquals(\"replicate_on_write\", translator.getKeyword(CassandraConstants.REPLICATE_ON_WRITE));\n        Assert.assertEquals(\"caching\", translator.getKeyword(CassandraConstants.CACHING));\n        Assert.assertEquals(\"comment\", translator.getKeyword(CassandraConstants.COMMENT));\n        Assert.assertEquals(\"gc_grace_seconds\", translator.getKeyword(CassandraConstants.GC_GRACE_SECONDS));    \n        \n    }\n\n    @After\n    public void tearDown()\n    {\n        CassandraCli.dropKeySpace(KEYSPACE);\n        emf.close();\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/CassandraCompositeTypeOrderByTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\n\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Junit test case for Compound/Composite key.\n * \n * @author chhavi.gangwal\n * \n */\n\npublic class CassandraCompositeTypeOrderByTest\n{\n\n    private static final String _PU = \"composite_pu\";\n\n    private EntityManagerFactory emf;\n\n    /** The Constant logger. */\n    private static final Logger logger = LoggerFactory.getLogger(CassandraCompositeTypeOrderByTest.class);\n\n\n    private Date currentDate = new Date();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        Map<String, Object> puProperties = new HashMap<String, Object>();\n        puProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n        \n\n        emf = Persistence.createEntityManagerFactory(_PU, puProperties);\n    }\n\n    @Test\n    public void onQuery() throws Exception\n    {\n\n        EntityManager em = emf.createEntityManager();\n        UUID timeLineId = UUID.randomUUID();\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(_PU);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        CassandraPrimeUser user = new CassandraPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        CassandraCompoundKey key1 = new CassandraCompoundKey(\"mevivs1\", 12, timeLineId);\n        user = new CassandraPrimeUser(key1);\n        user.setTweetBody(\"my second tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.flush(); // optional,just to clear persistence cache.\n\n        em.clear();\n\n        final String noClause = \"Select u from CassandraPrimeUser u\";\n\n        // query with no clause.\n        Query q = em.createQuery(noClause);\n        List<CassandraPrimeUser> results = q.getResultList();\n        Assert.assertEquals(2, results.size());\n        \n        em.close();\n\n    }\n\n    /**\n     * CompositeUserDataType\n     * \n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        CassandraCli.dropKeySpace(\"CompositeCassandra\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/CassandraCompositeTypeTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.crud.compositeType.CassandraPrimeUser.NickName;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.query.QueryHandlerException;\n\n/**\n * Junit test case for Compound/Composite key.\n * \n * @author vivek.mishra\n * \n */\n\npublic class CassandraCompositeTypeTest\n{\n\n    /** The Constant PERSISTENCE_UNIT. */\n    private static final String PERSISTENCE_UNIT = \"composite_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The Constant logger. */\n    private static final Logger logger = LoggerFactory.getLogger(CassandraCompositeTypeTest.class);\n\n    /** The current date. */\n    private Date currentDate = new Date();\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n\n    }\n\n    /**\n     * On add column.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onAddColumn() throws Exception\n    {\n        // cql script is not adding \"tweetBody\", kundera.ddl.auto.update will\n        // add it.\n        String cql_Query = \"create columnfamily \\\"CompositeUser\\\" (\\\"userId\\\" text, \\\"tweetId\\\" int, \\\"timeLineId\\\" uuid, \"\n                + \" \\\"tweetDate\\\" timestamp, PRIMARY KEY(\\\"userId\\\",\\\"tweetId\\\",\\\"timeLineId\\\"))\";\n\n        executeScript(cql_Query);\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n        onCRUD(em, key);\n        em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n        CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertNull(result.getKey().getFullName());\n        Assert.assertEquals(\"After merge\", result.getTweetBody()); // assertion\n                                                                   // of newly\n                                                                   // added\n                                                                   // tweet body\n        em.remove(result);\n\n        em.flush();\n        em.close();\n        em = emf.createEntityManager();\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n        result = em.find(CassandraPrimeUser.class, key);\n        Assert.assertNull(result);\n\n        em.close();\n    }\n\n    // @Test\n    /**\n     * On alter column type.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    public void onAlterColumnType() throws Exception\n    {\n        // Here tweetDate is of type \"int\". On update will be changed to\n        // timestamp.\n\n        String cql_Query = \"create columnfamily \\\"CompositeUser\\\" (\\\"userId\\\" text, \\\"tweetId\\\" int, \\\"timeLineId\\\" uuid, \"\n                + \" \\\"tweetDate\\\" int, PRIMARY KEY(\\\"userId\\\",\\\"tweetId\\\",\\\"timeLineId\\\"))\";\n        executeScript(cql_Query);\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        EntityManager em = emf.createEntityManager();\n        UUID timeLineId = UUID.randomUUID();\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n        onCRUD(em, key);\n        em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n        CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertNull(result.getKey().getFullName());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime()); // assertion\n                                                                                     // of\n                                                                                     // changed\n                                                                                     // tweetDate.\n        em.remove(result);\n        em.flush();\n        em.close();\n        em = emf.createEntityManager();\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n        result = em.find(CassandraPrimeUser.class, key);\n        Assert.assertNull(result);\n\n        em.close();\n    }\n\n    /**\n     * On query.\n     */\n    @Test\n    public void onQuery()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        CassandraPrimeUser user = new CassandraPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.flush(); // optional,just to clear persistence cache.\n\n        em.clear();\n\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n        final String noClause = \"Select u from CassandraPrimeUser u\";\n\n        final String withFirstCompositeColClause = \"Select u from CassandraPrimeUser u where u.key.userId = :userId\";\n\n        final String withSecondCompositeColClause = \"Select u from CassandraPrimeUser u where u.key.tweetId = :tweetId\";\n        final String withBothCompositeColClause = \"Select u from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId\";\n        final String withAllCompositeColClause = \"Select u from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        final String withLastCompositeColGTClause = \"Select u from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId >= :timeLineId\";\n\n        final String withSelectiveCompositeColClause = \"Select u.key from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n\n        final String withSelectCompositeKeyColumnClause = \"Select u.key.userId,u.key.timeLineId, u.tweetDate from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n\n        // query over 1 composite and 1 non-column\n\n        // query with no clause.\n        Query q = em.createQuery(noClause);\n        List<CassandraPrimeUser> results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withFirstCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        // Query with composite key clause.\n        q = em.createQuery(withSecondCompositeColClause);\n        q.setParameter(\"tweetId\", 1);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        // Query with composite key clause.\n        q = em.createQuery(withBothCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        // Query with composite key clause.\n        q = em.createQuery(withAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        // Query with composite key clause.\n        q = em.createQuery(withLastCompositeColGTClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertNull(results.get(0).getKey().getFullName());\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key with selective clause.\n        q = em.createQuery(withSelectiveCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertNull(results.get(0).getTweetBody());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        // Query for selecting a column of composite key.\n        q = em.createQuery(withSelectCompositeKeyColumnClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotNull(results.get(0));\n        Assert.assertNotNull(results.get(0).getKey());\n        Assert.assertNotNull(results.get(0).getKey().getUserId());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n        Assert.assertNotNull(results.get(0).getKey().getTimeLineId());\n        Assert.assertEquals(0, results.get(0).getKey().getTweetId());\n        Assert.assertEquals(currentDate, results.get(0).getTweetDate());\n        Assert.assertNull(results.get(0).getTweetBody());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        final String selectiveColumnTweetBodyWithAllCompositeColClause = \"Select u.tweetBody from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        // Query for selective column tweetBody with composite key clause.\n        q = em.createQuery(selectiveColumnTweetBodyWithAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"my first tweet\", results.get(0).getTweetBody());\n        Assert.assertNull(results.get(0).getTweetDate());\n\n        final String selectiveColumnTweetDateWithAllCompositeColClause = \"Select u.tweetDate from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        // Query for selective column tweetDate with composite key clause.\n        q = em.createQuery(selectiveColumnTweetDateWithAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(currentDate.getTime(), results.get(0).getTweetDate().getTime());\n        Assert.assertNull(results.get(0).getTweetBody());\n\n        final String withCompositeKeyClause = \"Select u from CassandraPrimeUser u where u.key = :key\";\n        // Query with composite key clause.\n        q = em.createQuery(withCompositeKeyClause);\n        q.setParameter(\"key\", key);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        final String withSemiColonAtEnd = \"Select u from CassandraPrimeUser u where u.key.userId = :userId;\";\n        // Query with semi colon at end.\n        try\n        {\n            q = em.createQuery(withSemiColonAtEnd);\n            q.setParameter(\"userId\", \"mevivs\");\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertEquals(\n                    \"unexpected char: ';' in query [ Select u from CassandraPrimeUser u where u.key.userId = :userId; ]\",\n                    qhe.getMessage().trim());\n        }\n\n        em.remove(user);\n\n        em.clear();// optional,just to clear persistence cache.\n    }\n\n    /**\n     * On named query test.\n     */\n    @Test\n    public void onNamedQueryTest()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        updateNamed();\n        deleteNamed();\n    }\n\n    /**\n     * On named query batch test.\n     */\n    @Test\n    public void onNamedQueryBatchTest()\n    {\n        Map propertyMap = new HashMap();\n        propertyMap.put(\"kundera.batch.size\", \"5\");\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, propertyMap);\n        insertUpdateBatch();\n        deleteBatch();\n    }\n\n    /**\n     * On limit.\n     */\n    @Test\n    public void onLimit()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        CassandraPrimeUser user1 = new CassandraPrimeUser(key);\n        user1.setTweetBody(\"my first tweet\");\n        user1.setTweetDate(currentDate);\n        em.persist(user1);\n\n        key = new CassandraCompoundKey(\"mevivs\", 2, timeLineId);\n        CassandraPrimeUser user2 = new CassandraPrimeUser(key);\n        user2.setTweetBody(\"my first tweet\");\n        user2.setTweetDate(currentDate);\n        em.persist(user2);\n\n        key = new CassandraCompoundKey(\"mevivs\", 3, timeLineId);\n        CassandraPrimeUser user3 = new CassandraPrimeUser(key);\n        user3.setTweetBody(\"my first tweet\");\n        user3.setTweetDate(currentDate);\n        em.persist(user3);\n\n        em.flush();\n\n        // em.clear(); // optional,just to clear persistence cache.\n\n        // em = emf.createEntityManager();\n        em.clear();\n\n        final String noClause = \"Select u from CassandraPrimeUser u\";\n        Query q = em.createQuery(noClause);\n        List<CassandraPrimeUser> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        // With limit\n        q = em.createQuery(noClause);\n        q.setMaxResults(2);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n    }\n\n    /**\n     * On order by clause.\n     */\n    @Test\n    public void onOrderBYClause()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        CassandraPrimeUser user1 = new CassandraPrimeUser(key);\n        user1.setTweetBody(\"my first tweet\");\n        user1.setTweetDate(currentDate);\n        em.persist(user1);\n\n        key = new CassandraCompoundKey(\"mevivs\", 2, timeLineId);\n        CassandraPrimeUser user2 = new CassandraPrimeUser(key);\n        user2.setTweetBody(\"my second tweet\");\n        user2.setTweetDate(currentDate);\n        em.persist(user2);\n\n        key = new CassandraCompoundKey(\"mevivs\", 3, timeLineId);\n        CassandraPrimeUser user3 = new CassandraPrimeUser(key);\n        user3.setTweetBody(\"my third tweet\");\n        user3.setTweetDate(currentDate);\n        em.persist(user3);\n\n        em.flush();\n\n        // em.clear(); // optional,just to clear persistence cache.\n\n        // em = emf.createEntityManager();\n        em.clear();\n\n        String orderClause = \"Select u from CassandraPrimeUser u where u.key.userId = :userId ORDER BY u.key.tweetId ASC\";\n        Query q = em.createQuery(orderClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        List<CassandraPrimeUser> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(\"my first tweet\", results.get(0).getTweetBody());\n        Assert.assertEquals(\"my second tweet\", results.get(1).getTweetBody());\n        Assert.assertEquals(\"my third tweet\", results.get(2).getTweetBody());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        orderClause = \"Select u from CassandraPrimeUser u where u.key.userId = :userId ORDER BY u.key.tweetId DESC\";\n        q = em.createQuery(orderClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(\"my first tweet\", results.get(2).getTweetBody());\n        Assert.assertEquals(\"my second tweet\", results.get(1).getTweetBody());\n        Assert.assertEquals(\"my third tweet\", results.get(0).getTweetBody());\n        Assert.assertEquals(3, results.size());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        // With limit\n        q = em.createQuery(orderClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setMaxResults(2);\n        results = q.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        try\n        {\n            orderClause = \"Select u from CassandraPrimeUser u where u.key.userId = :userId ORDER BY u.key.userId DESC\";\n            q = em.createQuery(orderClause);\n            q.setParameter(\"userId\", \"mevivs\");\n            results = q.getResultList();\n\n            Assert.fail();\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\n                    \"javax.persistence.PersistenceException: com.impetus.kundera.KunderaException: InvalidRequestException(why:Order by is currently only supported on the clustered columns of the PRIMARY KEY, got userId)\",\n                    e.getMessage());\n        }\n    }\n\n    /**\n     * On in clause.\n     */\n    @Test\n    public void onInClause()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        CassandraPrimeUser user1 = new CassandraPrimeUser(key);\n        user1.setTweetBody(\"my first tweet\");\n        user1.setTweetDate(currentDate);\n        em.persist(user1);\n\n        key = new CassandraCompoundKey(\"cgangwals\", 2, timeLineId);\n        CassandraPrimeUser user2 = new CassandraPrimeUser(key);\n        user2.setTweetBody(\"my second tweet\");\n        user2.setTweetDate(currentDate);\n        em.persist(user2);\n\n        key = new CassandraCompoundKey(\"kmishra\", 3, timeLineId);\n        CassandraPrimeUser user3 = new CassandraPrimeUser(key);\n        user3.setTweetBody(\"my third tweet\");\n        user3.setTweetDate(currentDate);\n        em.persist(user3);\n\n        em.flush();\n\n        em.clear();\n\n        String inClause = \"Select u from CassandraPrimeUser u where u.key.userId IN ('mevivs','kmishra') ORDER BY u.key.tweetId ASC\";\n        Query q = em.createQuery(inClause);\n\n        List<CassandraPrimeUser> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotNull(results.get(0));\n        Assert.assertNotNull(results.get(1));\n        Assert.assertEquals(\"my first tweet\", results.get(0).getTweetBody());\n        Assert.assertEquals(\"my third tweet\", results.get(1).getTweetBody());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        inClause = \"Select u from CassandraPrimeUser u where u.key.userId IN ('\\\"mevivs\\\"','\\\"kmishra\\\"') ORDER BY u.key.tweetId ASC\";\n        q = em.createQuery(inClause);\n\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertTrue(results.isEmpty());\n\n        inClause = \"Select u from CassandraPrimeUser u where u.key.userId IN ('mevivs') ORDER BY u.key.tweetId ASC\";\n        q = em.createQuery(inClause);\n        em.clear();\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(\"my first tweet\", results.get(0).getTweetBody());\n        Assert.assertEquals(1, results.size());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        inClause = \"Select u from CassandraPrimeUser u where u.key.userId IN ('mevivs', 'cgangwals', 'karthik') and u.key.tweetId IN (1,2,3) ORDER BY u.key.tweetId DESC\";\n        q = em.createQuery(inClause);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(\"cgangwals\", results.get(0).getKey().getUserId());\n        Assert.assertEquals(2, results.get(0).getKey().getTweetId());\n        Assert.assertEquals(\"mevivs\", results.get(1).getKey().getUserId());\n        Assert.assertEquals(1, results.get(1).getKey().getTweetId());\n\n        // In Query.\n        inClause = \"Select u from CassandraPrimeUser u where u.key.userId IN ('mevivs','kmishra') ORDER BY u.key.tweetId ASC\";\n        q = em.createQuery(inClause);\n\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertTrue(!results.isEmpty());\n        Assert.assertEquals(2, results.size());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        // In Query set Paramater.\n        inClause = \"Select u from CassandraPrimeUser u where u.key.userId IN :userIdList ORDER BY u.key.tweetId ASC\";\n        q = em.createQuery(inClause);\n\n        List<String> userIdList = new ArrayList<String>();\n        userIdList.add(\"mevivs\");\n        userIdList.add(\"kmishra\");\n        userIdList.add(\"cgangwals\");\n        q = em.createQuery(inClause);\n        q.setParameter(\"userIdList\", userIdList);\n\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertTrue(!results.isEmpty());\n        Assert.assertEquals(3, results.size());\n        Assert.assertNull(results.get(0).getKey().getFullName());\n\n        // In Query set Paramater with and clause.\n        inClause = \"Select u from CassandraPrimeUser u where u.key.userId IN :userIdList and u.name = 'kuldeep' ORDER BY u.key.tweetId ASC\";\n        q = em.createQuery(inClause);\n\n        q.setParameter(\"userIdList\", userIdList);\n\n        try\n        {\n            results = q.getResultList();\n            Assert.fail();\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\n                    \"javax.persistence.PersistenceException: com.impetus.kundera.KunderaException: InvalidRequestException(why:Select on indexed columns and with IN clause for the PRIMARY KEY are not supported)\",\n                    e.getMessage());\n        }\n\n        // In Query set Paramater with gt clause.\n        inClause = \"Select u from CassandraPrimeUser u where u.key IN :keyList\";\n        q = em.createQuery(inClause);\n\n        List<CassandraCompoundKey> keyList = new ArrayList<CassandraCompoundKey>();\n        UUID timeLineId1 = UUID.randomUUID();\n        keyList.add(new CassandraCompoundKey(\"mevivs\", 1, timeLineId1));\n        keyList.add(new CassandraCompoundKey(\"kmishra\", 3, timeLineId1));\n        keyList.add(new CassandraCompoundKey(\"cgangwals\", 2, timeLineId1));\n\n        q.setParameter(\"keyList\", keyList);\n\n        results = q.getResultList();\n\n    }\n\n    /**\n     * On batch insert.\n     */\n    @Test\n    public void onBatchInsert()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        for (int i = 0; i < 500; i++)\n        {\n            CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", i, timeLineId);\n            Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n            Client client = clients.get(PERSISTENCE_UNIT);\n            ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n            CassandraPrimeUser user = new CassandraPrimeUser(key);\n            user.setTweetBody(\"my first tweet\");\n            user.setTweetDate(currentDate);\n            em.persist(user);\n        }\n\n        em.clear();\n\n        CassandraPrimeUser u = em.find(CassandraPrimeUser.class, new CassandraCompoundKey(\"mevivs\", 499, timeLineId));\n        Assert.assertNotNull(u);\n    }\n\n    /**\n     * CompositeUserDataType.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"use \\\"CompositeCassandra\\\"\".getBytes()),\n                Compression.NONE, ConsistencyLevel.ONE);\n        CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"truncate \\\"CompositeUser\\\"\".getBytes()),\n                Compression.NONE, ConsistencyLevel.ONE);\n        CassandraCli.dropKeySpace(\"CompositeCassandra\");\n    }\n\n    // DO NOT DELETE IT!! though it is automated with schema creation option.\n    /**\n     * create column family script for compound key.\n     * \n     * @param cql\n     *            the cql\n     */\n    private void executeScript(final String cql)\n    {\n        CassandraCli.createKeySpace(\"CompositeCassandra\");\n        CassandraCli.executeCqlQuery(cql, \"CompositeCassandra\");\n    }\n\n    /**\n     * CRUD over Compound primary Key.\n     * \n     * @param em\n     *            the em\n     * @param key\n     *            the key\n     */\n\n    private void onCRUD(final EntityManager em, CassandraCompoundKey key)\n    {\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n        CassandraPrimeUser user = new CassandraPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        user.setNickName(NickName.KK);\n        em.persist(user);\n        em.flush();\n\n        // em.clear(); // optional,just to clear persistence cache.\n\n        // em = emf.createEntityManager();\n        em.clear();\n\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"my first tweet\", result.getTweetBody());\n        // Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n        Assert.assertEquals(NickName.KK, result.getNickName());\n        Assert.assertEquals(NickName.KK.name(), result.getNickName().name());\n\n        em.clear();// optional,just to clear persistence cache.\n\n        user.setTweetBody(\"After merge\");\n        em.merge(user);\n        em.close();// optional,just to clear persistence cache.\n\n        EntityManager em1 = emf.createEntityManager();\n        // em = emf.createEntityManager();\n        clients = (Map<String, Client>) em1.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        result = em1.find(CassandraPrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"After merge\", result.getTweetBody());\n        // Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n\n        // deleting composite\n        em1.clear(); // optional,just to clear persistence cache.\n        // em.close();// optional,just to clear persistence cache.\n\n    }\n\n    /**\n     * Update by Named Query.\n     */\n    private void updateNamed()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        UUID timeLineId = UUID.randomUUID();\n\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n        CassandraPrimeUser user = new CassandraPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.close();\n        em = emf.createEntityManager();\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        String updateQuery = \"Update CassandraPrimeUser u SET u.tweetBody='after merge' where u.key= :beforeUpdate\";\n        Query q = em.createQuery(updateQuery);\n        q.setParameter(\"beforeUpdate\", key);\n        q.executeUpdate();\n\n        em.close(); // optional,just to clear persistence cache.\n\n        em = emf.createEntityManager();\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"after merge\", result.getTweetBody());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n        em.close();\n    }\n\n    /**\n     * delete by Named Query.\n     */\n    private void deleteNamed()\n    {\n        UUID timeLineId = UUID.randomUUID();\n\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n\n        String deleteQuery = \"Delete From CassandraPrimeUser u where u.key= :key\";\n        EntityManager em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        Query q = em.createQuery(deleteQuery);\n        q.setParameter(\"key\", key);\n        q.executeUpdate();\n\n        CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key);\n        Assert.assertNull(result);\n        em.close();\n    }\n\n    /**\n     * Insert update batch.\n     */\n    private void insertUpdateBatch()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        UUID timeLineId = UUID.randomUUID();\n\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n        CassandraPrimeUser user = new CassandraPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n        CassandraCompoundKey key1 = new CassandraCompoundKey(\"mevivs\", 2, timeLineId);\n        CassandraPrimeUser user1 = new CassandraPrimeUser(key1);\n        user1.setTweetBody(\"my first tweet\");\n        user1.setTweetDate(currentDate);\n        em.persist(user1);\n        CassandraCompoundKey key2 = new CassandraCompoundKey(\"mevivs\", 3, timeLineId);\n        CassandraPrimeUser user2 = new CassandraPrimeUser(key2);\n        user2.setTweetBody(\"my first tweet\");\n        user2.setTweetDate(currentDate);\n        em.persist(user2);\n\n        em.close();\n        em = emf.createEntityManager();\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        String updateQuery = \"Update CassandraPrimeUser u SET u.tweetBody='after merge' where u.key= :beforeUpdate\";\n        Query q = em.createQuery(updateQuery);\n        q.setParameter(\"beforeUpdate\", key);\n        q.executeUpdate();\n\n        em.close(); // optional,just to clear persistence cache.\n\n        em = emf.createEntityManager();\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"after merge\", result.getTweetBody());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n        em.close();\n    }\n\n    /**\n     * Delete batch.\n     */\n    private void deleteBatch()\n    {\n        UUID timeLineId = UUID.randomUUID();\n\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n\n        String deleteQuery = \"Delete From CassandraPrimeUser u where u.key.userId= :userId\";\n        EntityManager em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        Query q = em.createQuery(deleteQuery);\n        q.setParameter(\"userId\", \"mevivs\");\n\n        q.executeUpdate();\n\n        CassandraPrimeUser result = em.find(CassandraPrimeUser.class, key);\n        Assert.assertNull(result);\n        em.close();\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/CassandraCompoundKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.io.Serializable;\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * @author vivek.mishra\n */\n@Embeddable\npublic class CassandraCompoundKey implements Serializable\n{\n    private static final long serialVersionUID = -8055485531216607863L;\n            \n    @Column\n    private String userId;\n\n    @Column\n    private int tweetId;\n\n    @Column\n    private UUID timeLineId;\n\n    @Column\n    private transient String fullName;\n\n    /**\n     * \n     */\n    public CassandraCompoundKey()\n    {\n    }\n\n    /**\n     * @param userId\n     * @param tweetId\n     * @param timeLineId\n     */\n    public CassandraCompoundKey(String userId, int tweetId, UUID timeLineId)\n    {\n        this.userId = userId;\n        this.tweetId = tweetId;\n        this.timeLineId = timeLineId;\n        this.fullName = \"kuldeep\";\n    }\n\n    /**\n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * @return the tweetId\n     */\n    public int getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * @return the timeLineId\n     */\n    public UUID getTimeLineId()\n    {\n        return timeLineId;\n    }\n\n    public String getFullName()\n    {\n        return this.fullName;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/CassandraEmbeddedAssociation.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.util.Date;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.client.crud.compositeType.association.UserInfo;\n\n/**\n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"CompositeUserAssociation\", schema = \"CompositeCassandra@composite_pu\")\n// @Index(index = true,columns = { \"tweetBody\",\"tweetDate\" })\npublic class CassandraEmbeddedAssociation\n{\n\n    @EmbeddedId\n    private CassandraCompoundKey key;\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private Date tweetDate;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"userInfo_id\")\n    private UserInfo userInfo;\n\n    public CassandraEmbeddedAssociation()\n    {\n    }\n\n    public CassandraEmbeddedAssociation(CassandraCompoundKey key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the key\n     */\n    public CassandraCompoundKey getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n    public UserInfo getUserInfo()\n    {\n        return userInfo;\n    }\n\n    public void setUserInfo(UserInfo userInfo)\n    {\n        this.userInfo = userInfo;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/CassandraPrimeUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.OrderBy;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"CompositeUser\")\n@IndexCollection(columns = { @Index(name = \"name\") })\npublic class CassandraPrimeUser\n{\n\n    @EmbeddedId\n    @OrderBy(\"key.tweetId ASC, key.timeLineId DESC\")\n    private CassandraCompoundKey key;\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private Date tweetDate;\n\n    @Column\n    private String name;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private NickName nickName;\n\n    public CassandraPrimeUser()\n    {\n    }\n\n    public CassandraPrimeUser(CassandraCompoundKey key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the key\n     */\n    public CassandraCompoundKey getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public NickName getNickName()\n    {\n        return nickName;\n    }\n\n    public void setNickName(NickName nickName)\n    {\n        this.nickName = nickName;\n    }\n\n    enum NickName\n    {\n        KK, VM, AS;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/CompositeDataTypeTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Junit test case for Compound/Composite key.\n * \n * @author vivek.mishra\n * \n */\npublic class CompositeDataTypeTest\n{\n\n    /**\n     * \n     */\n    private static final String PERSISTENCE_UNIT = \"compositedatatype\";\n\n    private EntityManagerFactory emf;\n\n    /** The enrolment date. */\n    protected Date enrolmentDate = new Date(Long.parseLong(\"1344079065781\"));\n\n    /** The joining date and time. */\n    protected Date joiningDateAndTime = new Date();\n\n    /** The date. */\n    protected long date = new Date().getTime();\n\n    /** The new sql date. */\n    protected java.sql.Date newSqlDate = new java.sql.Date(date);\n\n    /** The enrolment time. */\n    protected Date enrolmentTime = new Date();\n\n    /** The sql time. */\n    protected java.sql.Time sqlTime = new java.sql.Time(date);\n\n    /** The sql timestamp. */\n    protected java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(date);\n\n    /** The big decimal. */\n    protected BigDecimal bigDecimal = new BigDecimal(123456789);\n\n    /** The big integer. */\n    protected BigInteger bigInteger = new BigInteger(\"123456789\");\n\n    /** The number of students. */\n    protected int numberOfStudents = 1000;\n\n    /** The calendar. */\n    protected Calendar calendar = Calendar.getInstance();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n        loadData();\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n    }\n\n    /**\n     * CRUD over Compound primary Key.\n     * \n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     */\n    @Test\n    public void onCRUD() throws InstantiationException, IllegalAccessException\n    {\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        CompoundKeyDataType key = prepareData(new Long(12345677), 78575785897L, \"Amresh\", false, 10, 'A', (byte) 5,\n                (short) 8, (float) 69.3, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime,\n                new Integer(3), new Long(978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal,\n                bigInteger, calendar, CompoundKeyDataType.class.newInstance());\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n        PrimeUserDataType user = new PrimeUserDataType(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        user.setIsActive(true);\n        em.persist(user);\n\n        em.clear(); // optional,just to clear persistence cache.\n\n        PrimeUserDataType result = em.find(PrimeUserDataType.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"my first tweet\", result.getTweetBody());\n        // Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n        Assert.assertTrue(result.getIsActive());\n\n        em.clear();// optional,just to clear persistence cache.\n\n        user.setTweetBody(\"After merge\");\n        em.merge(user);\n\n        em.clear();// optional,just to clear persistence cache.\n\n        result = em.find(PrimeUserDataType.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"After merge\", result.getTweetBody());\n        // Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n\n        // deleting composite\n        em.remove(result);\n\n        em.clear();// optional,just to clear persistence cache.\n\n        result = em.find(PrimeUserDataType.class, key);\n        Assert.assertNull(result);\n    }\n\n    @Test\n    public void onQuery() throws InstantiationException, IllegalAccessException\n    {\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        CompoundKeyDataType key = prepareData(new Long(12345677), 78575785897L, \"Amresh\", false, 10, 'A', (byte) 5,\n                (short) 8, (float) 69.3, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime,\n                new Integer(3), new Long(978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal,\n                bigInteger, calendar, CompoundKeyDataType.class.newInstance());\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        PrimeUserDataType user = new PrimeUserDataType(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.clear(); // optional,just to clear persistence cache.\n        final String noClause = \"Select u from PrimeUserDataType u\";\n\n        // secondary index support over compound key is not enabled in cassandra\n        // composite keys yet. DO NOT DELETE/UNCOMMENT.\n\n        // final String withClauseOnNoncomposite =\n        // \"Select u from PrimeUserDataType u where u.tweetDate = ?1\";\n\n        final String withFirstCompositeColClause = \"Select u from PrimeUserDataType u where u.key.studentId = :studentId\";\n        final String withSecondCompositeColClause = \"Select u from PrimeUserDataType u where u.key.uniqueId >= :uniqueId1 and u.key.uniqueId <= :uniqueId2\";\n        final String withBothCompositeColClause = \"Select u from PrimeUserDataType u where u.key.studentId = :studentId and u.key.uniqueId = :uniqueId\";\n        final String withSelectiveCompositeColClause = \"Select u.key from PrimeUserDataType u where u.key = :key\";\n\n        final String withAllCompositeColClause = \"Select u from PrimeUserDataType u where u.key.studentId = :studentId and u.key.uniqueId = :uniqueId and u.key.studentName = :studentName and u.key.isExceptional = :isExceptional and u.key.age = :age and u.key.semester = :semester and u.key.digitalSignature = :digitalSignature and u.key.cgpa = :cgpa and u.key.percentage = :percentage and u.key.height = :height and u.key.enrolmentDate = :enrolmentDate and u.key.enrolmentTime = :enrolmentTime and u.key.joiningDateAndTime = :joiningDateAndTime and u.key.yearsSpent = :yearsSpent and u.key.rollNumber = :rollNumber and u.key.monthlyFee = :monthlyFee and u.key.sqlDate = :sqlDate and u.key.sqlTimestamp = :sqlTimestamp and u.key.sqlTime = :sqlTime and u.key.bigInteger = :bigInteger and u.key.calendar = :calendar\";\n        final String selectiveColumnTweetBodyWithAllCompositeColClause = \"Select u.tweetBody from PrimeUserDataType u where u.key.studentId = :studentId and u.key.uniqueId = :uniqueId and u.key.studentName = :studentName and u.key.isExceptional = :isExceptional and u.key.age = :age and u.key.semester = :semester and u.key.digitalSignature = :digitalSignature and u.key.cgpa = :cgpa and u.key.percentage = :percentage and u.key.height = :height and u.key.enrolmentDate = :enrolmentDate and u.key.enrolmentTime = :enrolmentTime and u.key.joiningDateAndTime = :joiningDateAndTime and u.key.yearsSpent = :yearsSpent and u.key.rollNumber = :rollNumber and u.key.monthlyFee = :monthlyFee and u.key.sqlDate = :sqlDate and u.key.sqlTimestamp = :sqlTimestamp and u.key.sqlTime = :sqlTime and u.key.bigInteger = :bigInteger and u.key.calendar = :calendar\";\n\n        // query over 1 composite and 1 non-column\n\n        // query with no clause.\n        Query q = em.createQuery(noClause);\n        List<PrimeUserDataType> results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withFirstCompositeColClause);\n        q.setParameter(\"studentId\", new Long(12345677));\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // secondary index support over compound key is not enabled in cassandra\n        // composite keys yet. DO NOT DELETE/UNCOMMENT.\n\n        // Query with composite key clause.\n        // q = em.createQuery(withClauseOnNoncomposite);\n        // q.setParameter(1, currentDate);\n        // results = q.getResultList();\n        // Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withSecondCompositeColClause);\n        q.setParameter(\"uniqueId1\", 78575785897L);\n        q.setParameter(\"uniqueId2\", 78575785897L);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withBothCompositeColClause);\n        q.setParameter(\"studentId\", new Long(12345677));\n        q.setParameter(\"uniqueId\", 78575785897L);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withAllCompositeColClause);\n        q.setParameter(\"studentId\", new Long(12345677));\n        q.setParameter(\"uniqueId\", 78575785897L);\n        q.setParameter(\"studentName\", \"Amresh\");\n        q.setParameter(\"isExceptional\", false);\n        q.setParameter(\"age\", 10);\n        q.setParameter(\"semester\", 'A');\n        q.setParameter(\"digitalSignature\", new Byte((byte) 5));\n        q.setParameter(\"cgpa\", (short) 8);\n        q.setParameter(\"percentage\", (float) 69.3);\n        q.setParameter(\"height\", 163.76765654);\n        q.setParameter(\"enrolmentDate\", enrolmentDate);\n        q.setParameter(\"enrolmentTime\", enrolmentTime);\n        q.setParameter(\"joiningDateAndTime\", joiningDateAndTime);\n        q.setParameter(\"yearsSpent\", new Integer(3));\n        q.setParameter(\"rollNumber\", new Long(978423946455l));\n        q.setParameter(\"monthlyFee\", 135434.89);\n        q.setParameter(\"sqlDate\", newSqlDate);\n        q.setParameter(\"sqlTimestamp\", sqlTimestamp);\n        q.setParameter(\"sqlTime\", sqlTime);\n        q.setParameter(\"bigInteger\", bigInteger);\n        q.setParameter(\"calendar\", calendar);\n\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key with selective clause.\n        q = em.createQuery(withSelectiveCompositeColClause);\n        q.setParameter(\"key\", key);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertNull(results.get(0).getTweetBody());\n\n        // // Query for selective column tweetBody with composite key clause.\n        q = em.createQuery(selectiveColumnTweetBodyWithAllCompositeColClause);\n        q.setParameter(\"studentId\", new Long(12345677));\n        q.setParameter(\"uniqueId\", 78575785897L);\n        q.setParameter(\"studentName\", \"Amresh\");\n        q.setParameter(\"isExceptional\", false);\n        q.setParameter(\"age\", 10);\n        q.setParameter(\"semester\", 'A');\n        q.setParameter(\"digitalSignature\", (byte) 5);\n        q.setParameter(\"cgpa\", (short) 8);\n        q.setParameter(\"percentage\", (float) 69.3);\n        q.setParameter(\"height\", 163.76765654);\n        q.setParameter(\"enrolmentDate\", enrolmentDate);\n        q.setParameter(\"enrolmentTime\", enrolmentTime);\n        q.setParameter(\"joiningDateAndTime\", joiningDateAndTime);\n        q.setParameter(\"yearsSpent\", new Integer(3));\n        q.setParameter(\"rollNumber\", new Long(978423946455l));\n        q.setParameter(\"monthlyFee\", 135434.89);\n        q.setParameter(\"sqlDate\", newSqlDate);\n        q.setParameter(\"sqlTimestamp\", sqlTimestamp);\n        q.setParameter(\"sqlTime\", sqlTime);\n        q.setParameter(\"bigInteger\", bigInteger);\n        q.setParameter(\"calendar\", calendar);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"my first tweet\", results.get(0).getTweetBody());\n        Assert.assertNull(results.get(0).getTweetDate());\n\n        final String selectiveColumnTweetDateWithAllCompositeColClause = \"Select u.tweetDate from PrimeUserDataType u where u.key = :key\";\n        // Query for selective column tweetDate with composite key clause.\n        q = em.createQuery(selectiveColumnTweetDateWithAllCompositeColClause);\n        q.setParameter(\"key\", key);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(currentDate.getTime(), results.get(0).getTweetDate().getTime());\n        Assert.assertNull(results.get(0).getTweetBody());\n\n        final String withCompositeKeyClause = \"Select u from PrimeUserDataType u where u.key = :key\";\n        // Query with composite key clause.\n        q = em.createQuery(withCompositeKeyClause);\n        q.setParameter(\"key\", key);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        em.remove(user);\n\n        em.clear();// optional,just to clear persistence cache.\n    }\n\n    @Test\n    public void onNamedQueryTest() throws InstantiationException, IllegalAccessException\n    {\n        updateNamed();\n        deleteNamed();\n\n    }\n\n    /**\n     * Update by Named Query.\n     * \n     * @return\n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     */\n    private void updateNamed() throws InstantiationException, IllegalAccessException\n    {\n        EntityManager em = emf.createEntityManager();\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        CompoundKeyDataType key = prepareData(new Long(12345677), 78575785897L, \"Amresh\", false, 10, 'A', (byte) 5,\n                (short) 8, (float) 69.3, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime,\n                new Integer(3), new Long(978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal,\n                bigInteger, calendar, CompoundKeyDataType.class.newInstance());\n        PrimeUserDataType user = new PrimeUserDataType(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em = emf.createEntityManager();\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        String updateQuery = \"Update PrimeUserDataType u SET u.tweetBody='after merge' where u.key= :beforeUpdate\";\n        Query q = em.createQuery(updateQuery);\n        q.setParameter(\"beforeUpdate\", key);\n        q.executeUpdate();\n\n        em.clear();\n        PrimeUserDataType result = em.find(PrimeUserDataType.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"after merge\", result.getTweetBody());\n        // Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n        em.close();\n    }\n\n    /**\n     * delete by Named Query.\n     * \n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     */\n    private void deleteNamed() throws InstantiationException, IllegalAccessException\n    {\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        CompoundKeyDataType key = prepareData(new Long(12345677), 78575785897L, \"Amresh\", false, 10, 'A', (byte) 5,\n                (short) 8, (float) 69.3, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime,\n                new Integer(3), new Long(978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal,\n                bigInteger, calendar, CompoundKeyDataType.class.newInstance());\n\n        String deleteQuery = \"Delete From PrimeUserDataType u where u.key= :key\";\n        EntityManager em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        Query q = em.createQuery(deleteQuery);\n        q.setParameter(\"key\", key);\n        q.executeUpdate();\n\n        PrimeUserDataType result = em.find(PrimeUserDataType.class, key);\n        Assert.assertNull(result);\n        em.close();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n//        CassandraCli.dropKeySpace(\"CompositeCassandra\");\n        emf.close();\n    }\n\n    // DO NOT DELETE IT!! though it is automated with schema creation option.\n    /**\n     * create column family script for compound key.\n     */\n    private void loadData()\n    {/*\n      * CassandraCli.createKeySpace(\"CompositeCassandra\"); String cql_Query =\n      * \"create columnfamily \\\"CompositeUserDataType\\\" (\\\"userId\\\" text, \\\"tweetId\\\" int, \\\"timeLineId\\\" uuid, \\\"tweetBody\\\" text,\"\n      * +\n      * \" \\\"tweetDate\\\" timestamp, PRIMARY KEY(\\\"userId\\\",\\\"tweetId\\\",\\\"timeLineId\\\"))\"\n      * ; try { CassandraCli.getClient().set_keyspace(\"CompositeCassandra\"); }\n      * catch (InvalidRequestException e) { logger.error(e.getMessage()); }\n      * catch (TException e) { logger.error(e.getMessage()); }\n      * CassandraCli.executeCqlQuery(cql_Query);\n      */\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param studentId\n     *            the student id\n     * @param uniqueId\n     *            the unique id\n     * @param studentName\n     *            the student name\n     * @param isExceptional\n     *            the is exceptional\n     * @param age\n     *            the age\n     * @param semester\n     *            the semester\n     * @param digitalSignature\n     *            the digital signature\n     * @param cgpa\n     *            the cgpa\n     * @param percentage\n     *            the percentage\n     * @param height\n     *            the height\n     * @param enrolmentDate\n     *            the enrolment date\n     * @param enrolmentTime\n     *            the enrolment time\n     * @param joiningDateAndTime\n     *            the joining date and time\n     * @param yearsSpent\n     *            the years spent\n     * @param rollNumber\n     *            the roll number\n     * @param monthlyFee\n     *            the monthly fee\n     * @param newSqlDate\n     *            the new sql date\n     * @param sqlTime\n     *            the sql time\n     * @param sqlTimestamp\n     *            the sql timestamp\n     * @param bigDecimal\n     *            the big decimal\n     * @param bigInteger\n     *            the big integer\n     * @param calendar\n     *            the calendar\n     * @param o\n     *            the o\n     * @return the person\n     */\n    private CompoundKeyDataType prepareData(long studentId, long uniqueId, String studentName, boolean isExceptional,\n            int age, char semester, byte digitalSignature, short cgpa, float percentage, double height,\n            java.util.Date enrolmentDate, java.util.Date enrolmentTime, java.util.Date joiningDateAndTime,\n            Integer yearsSpent, Long rollNumber, Double monthlyFee, java.sql.Date newSqlDate, java.sql.Time sqlTime,\n            java.sql.Timestamp sqlTimestamp, BigDecimal bigDecimal, BigInteger bigInteger, Calendar calendar,\n            CompoundKeyDataType o)\n    {\n        o.setStudentId((Long) studentId);\n        o.setUniqueId(uniqueId);\n        o.setStudentName(studentName);\n        o.setExceptional(isExceptional);\n        o.setAge(age);\n        o.setSemester(semester);\n        o.setDigitalSignature(digitalSignature);\n        o.setCgpa(cgpa);\n        o.setPercentage(percentage);\n        o.setHeight(height);\n\n        o.setEnrolmentDate(enrolmentDate);\n        o.setEnrolmentTime(enrolmentTime);\n        o.setJoiningDateAndTime(joiningDateAndTime);\n\n        o.setYearsSpent(yearsSpent);\n        o.setRollNumber(rollNumber);\n        o.setMonthlyFee(monthlyFee);\n        o.setSqlDate(newSqlDate);\n        o.setSqlTime(sqlTime);\n        o.setSqlTimestamp(sqlTimestamp);\n        // o.setBigDecimal(bigDecimal);\n        o.setBigInteger(bigInteger);\n        o.setCalendar(calendar);\n        return o;\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/CompoundKeyDataType.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.math.BigInteger;\nimport java.util.Calendar;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\n/**\n * @author vivek.mishra\n */\n@Embeddable\npublic class CompoundKeyDataType\n{\n\n    // Primitive Types\n    // @Id\n    @Column(name = \"STUDENT_ID\")\n    private long studentId;\n\n    @Column(name = \"UNIQUE_ID\")\n    private long uniqueId;\n\n    @Column(name = \"STUDENT_NAME\")\n    private String studentName;\n\n    @Column(name = \"IS_EXCEPTIONAL\")\n    private boolean isExceptional;\n\n    @Column(name = \"AGE\")\n    private int age;\n\n    @Column(name = \"SEMESTER\")\n    private char semester; // A,B,C,D,E,F for i to vi\n\n    @Column(name = \"DIGITAL_SIGNATURE\")\n    private byte digitalSignature;\n\n    @Column(name = \"CGPA\")\n    private short cgpa; // 1-10\n\n    @Column(name = \"PERCENTAGE\")\n    private float percentage;\n\n    @Column(name = \"HEIGHT\")\n    private double height;\n\n    // Date-time types\n    @Column(name = \"ENROLMENT_DATE\")\n    @Temporal(TemporalType.DATE)\n    private java.util.Date enrolmentDate;\n\n    @Column(name = \"ENROLMENT_TIME\")\n    @Temporal(TemporalType.TIME)\n    private java.util.Date enrolmentTime;\n\n    @Column(name = \"JOINING_DATE_TIME\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private java.util.Date joiningDateAndTime;\n\n    // Wrapper types\n\n    @Column(name = \"YEARS_SPENT\")\n    private Integer yearsSpent;\n\n    @Column(name = \"ROLL_NUMBER\")\n    private Long rollNumber;\n\n    @Column(name = \"MONTHLY_FEE\")\n    private Double monthlyFee;\n\n    @Column(name = \"SQL_DATE\")\n    private java.sql.Date sqlDate;\n\n    @Column(name = \"SQL_TIMESTAMP\")\n    private java.sql.Timestamp sqlTimestamp;\n\n    @Column(name = \"SQL_TIME\")\n    private java.sql.Time sqlTime;\n\n    @Column(name = \"BIG_INT\")\n    private BigInteger bigInteger;\n\n    // @Column(name = \"BIG_DECIMAL\")\n    // private BigDecimal bigDecimal;\n\n    @Column(name = \"CALENDAR\")\n    private Calendar calendar;\n\n    /**\n     * \n     */\n    public CompoundKeyDataType()\n    {\n    }\n\n    /**\n     * @return the studentId\n     */\n    public long getStudentId()\n    {\n        return studentId;\n    }\n\n    /**\n     * @param studentId\n     *            the studentId to set\n     */\n    public void setStudentId(long studentId)\n    {\n        this.studentId = studentId;\n    }\n\n    /**\n     * @return the uniqueId\n     */\n    public long getUniqueId()\n    {\n        return uniqueId;\n    }\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    public void setUniqueId(long uniqueId)\n    {\n        this.uniqueId = uniqueId;\n    }\n\n    /**\n     * @return the studentName\n     */\n    public String getStudentName()\n    {\n        return studentName;\n    }\n\n    /**\n     * @param studentName\n     *            the studentName to set\n     */\n    public void setStudentName(String studentName)\n    {\n        this.studentName = studentName;\n    }\n\n    /**\n     * @return the isExceptional\n     */\n    public boolean isExceptional()\n    {\n        return isExceptional;\n    }\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    public void setExceptional(boolean isExceptional)\n    {\n        this.isExceptional = isExceptional;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the semester\n     */\n    public char getSemester()\n    {\n        return semester;\n    }\n\n    /**\n     * @param semester\n     *            the semester to set\n     */\n    public void setSemester(char semester)\n    {\n        this.semester = semester;\n    }\n\n    /**\n     * @return the digitalSignature\n     */\n    public byte getDigitalSignature()\n    {\n        return digitalSignature;\n    }\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    public void setDigitalSignature(byte digitalSignature)\n    {\n        this.digitalSignature = digitalSignature;\n    }\n\n    /**\n     * @return the cgpa\n     */\n    public short getCgpa()\n    {\n        return cgpa;\n    }\n\n    /**\n     * @param cgpa\n     *            the cgpa to set\n     */\n    public void setCgpa(short cgpa)\n    {\n        this.cgpa = cgpa;\n    }\n\n    /**\n     * @return the percentage\n     */\n    public float getPercentage()\n    {\n        return percentage;\n    }\n\n    /**\n     * @param percentage\n     *            the percentage to set\n     */\n    public void setPercentage(float percentage)\n    {\n        this.percentage = percentage;\n    }\n\n    /**\n     * @return the height\n     */\n    public double getHeight()\n    {\n        return height;\n    }\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    public void setHeight(double height)\n    {\n        this.height = height;\n    }\n\n    /**\n     * @return the enrolmentDate\n     */\n    public java.util.Date getEnrolmentDate()\n    {\n        return enrolmentDate;\n    }\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    public void setEnrolmentDate(java.util.Date enrolmentDate)\n    {\n        this.enrolmentDate = enrolmentDate;\n    }\n\n    /**\n     * @return the enrolmentTime\n     */\n    public java.util.Date getEnrolmentTime()\n    {\n        return enrolmentTime;\n    }\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    public void setEnrolmentTime(java.util.Date enrolmentTime)\n    {\n        this.enrolmentTime = enrolmentTime;\n    }\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    public java.util.Date getJoiningDateAndTime()\n    {\n        return joiningDateAndTime;\n    }\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    public void setJoiningDateAndTime(java.util.Date joiningDateAndTime)\n    {\n        this.joiningDateAndTime = joiningDateAndTime;\n    }\n\n    /**\n     * @return the yearsSpent\n     */\n    public Integer getYearsSpent()\n    {\n        return yearsSpent;\n    }\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    public void setYearsSpent(Integer yearsSpent)\n    {\n        this.yearsSpent = yearsSpent;\n    }\n\n    /**\n     * @return the rollNumber\n     */\n    public Long getRollNumber()\n    {\n        return rollNumber;\n    }\n\n    /**\n     * @param rollNumber\n     *            the rollNumber to set\n     */\n    public void setRollNumber(Long rollNumber)\n    {\n        this.rollNumber = rollNumber;\n    }\n\n    /**\n     * @return the monthlyFee\n     */\n    public Double getMonthlyFee()\n    {\n        return monthlyFee;\n    }\n\n    /**\n     * @param monthlyFee\n     *            the monthlyFee to set\n     */\n    public void setMonthlyFee(Double monthlyFee)\n    {\n        this.monthlyFee = monthlyFee;\n    }\n\n    public java.sql.Date getSqlDate()\n    {\n        return sqlDate;\n    }\n\n    public void setSqlDate(java.sql.Date sqlDate)\n    {\n        this.sqlDate = sqlDate;\n    }\n\n    /**\n     * @return the sqlTimestamp\n     */\n    public java.sql.Timestamp getSqlTimestamp()\n    {\n        return sqlTimestamp;\n    }\n\n    /**\n     * @param sqlTimestamp\n     *            the sqlTimestamp to set\n     */\n    public void setSqlTimestamp(java.sql.Timestamp sqlTimestamp)\n    {\n        this.sqlTimestamp = sqlTimestamp;\n    }\n\n    /**\n     * @return the sqlTime\n     */\n    public java.sql.Time getSqlTime()\n    {\n        return sqlTime;\n    }\n\n    /**\n     * @param sqlTime\n     *            the sqlTime to set\n     */\n    public void setSqlTime(java.sql.Time sqlTime)\n    {\n        this.sqlTime = sqlTime;\n    }\n\n    /**\n     * @return the bigInteger\n     */\n    public BigInteger getBigInteger()\n    {\n        return bigInteger;\n    }\n\n    /**\n     * @param bigInteger\n     *            the bigInteger to set\n     */\n    public void setBigInteger(BigInteger bigInteger)\n    {\n        this.bigInteger = bigInteger;\n    }\n\n    // /**\n    // * @return the bigDecimal\n    // */\n    // public BigDecimal getBigDecimal()\n    // {\n    // return bigDecimal;\n    // }\n    //\n    // /**\n    // * @param bigDecimal\n    // * the bigDecimal to set\n    // */\n    // public void setBigDecimal(BigDecimal bigDecimal)\n    // {\n    // this.bigDecimal = bigDecimal;\n    // }\n\n    /**\n     * @return the calendar\n     */\n    public Calendar getCalendar()\n    {\n        return calendar;\n    }\n\n    /**\n     * @param calendar\n     *            the calendar to set\n     */\n    public void setCalendar(Calendar calendar)\n    {\n        this.calendar = calendar;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/EntityWithMultiplePartitionKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\n@Entity\n@Table(name = \"EntityWithMultiplePartitionKey\")\npublic class EntityWithMultiplePartitionKey\n{\n    @EmbeddedId\n    private IdWithMultiplePartitionKey id;\n\n    @Column\n    private String entityDiscription;\n\n    @Column\n    private String action;\n\n    /**\n     * @return the id\n     */\n    public IdWithMultiplePartitionKey getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(IdWithMultiplePartitionKey id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the entityDiscription\n     */\n    public String getEntityDiscription()\n    {\n        return entityDiscription;\n    }\n\n    /**\n     * @param entityDiscription\n     *            the entityDiscription to set\n     */\n    public void setEntityDiscription(String entityDiscription)\n    {\n        this.entityDiscription = entityDiscription;\n    }\n\n    /**\n     * @return the action\n     */\n    public String getAction()\n    {\n        return action;\n    }\n\n    /**\n     * @param action\n     *            the action to set\n     */\n    public void setAction(String action)\n    {\n        this.action = action;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/EntityWithMultiplePartitionKeyAutoGenTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.Persistence;\n\nimport org.junit.Before;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\n\n/**\n * The Class EntityWithMultiplePartitionKeyAutoGenTest.\n *\n * @author karthikp.manchala\n */\npublic class EntityWithMultiplePartitionKeyAutoGenTest extends EntityWithMultiplePartitionKeyTest\n{\n    \n    /* (non-Javadoc)\n     * @see com.impetus.client.crud.compositeType.EntityWithMultiplePartitionKeyTest#setUp()\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        Map<String, String> propertymap = new HashMap<String, String>();\n        propertymap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        propertymap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        emf = Persistence.createEntityManagerFactory(_PU, propertymap);\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/EntityWithMultiplePartitionKeyTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.query.Query;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic class EntityWithMultiplePartitionKeyTest\n{\n\n    protected static String _PU = \"compositedatatype\";\n\n    protected EntityManagerFactory emf;\n\n    private static final String _keyspace = \"CompositeCassandra\";\n\n    /** The Constant logger. */\n    private static final Logger log = LoggerFactory.getLogger(EntityWithMultiplePartitionKeyTest.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n        CassandraCli.createKeySpace(_keyspace);\n        try\n        {\n            CassandraCli\n                    .executeCqlQuery(\n                            \"create table \\\"EntityWithMultiplePartitionKey\\\"(\\\"partitionKey1\\\" text, \\\"partitionKey2\\\" int, \\\"clusterkey1\\\" text, \\\"clusterkey2\\\" int, \\\"entityDiscription\\\" text, action text, PRIMARY KEY((\\\"partitionKey1\\\", \\\"partitionKey2\\\"), \\\"clusterkey1\\\", \\\"clusterkey2\\\"))\",\n                            _keyspace);\n        }\n        catch (Exception e)\n        {\n            log.warn(e.getMessage());\n        }\n        Map<String, String> propertymap = new HashMap<String, String>();\n        propertymap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"\");\n        emf = Persistence.createEntityManagerFactory(_PU, propertymap);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        CassandraCli.dropKeySpace(_keyspace);\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        PartitionKey partitionKey = new PartitionKey();\n        partitionKey.setPartitionKey1(\"partitionKey1\");\n        partitionKey.setPartitionKey2(1);\n\n        IdWithMultiplePartitionKey id = new IdWithMultiplePartitionKey();\n        id.setClusterkey1(\"clusterkey1\");\n        id.setClusterkey2(11);\n        id.setPartitionKey(partitionKey);\n\n        EntityWithMultiplePartitionKey entity = new EntityWithMultiplePartitionKey();\n        entity.setEntityDiscription(\"Entity to test composite key with multiple partition key.\");\n        entity.setAction(\"Persisting\");\n        entity.setId(id);\n\n        // Insert.\n        em.persist(entity);\n\n        em.clear();\n\n        // Retrieve.\n        EntityWithMultiplePartitionKey foundEntity = em.find(EntityWithMultiplePartitionKey.class, id);\n        Assert.assertNotNull(foundEntity);\n        Assert.assertNotNull(foundEntity.getId());\n        Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n        Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n        Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                foundEntity.getEntityDiscription());\n        Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n        Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n        Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n        Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n\n        foundEntity.setAction(\"updating\");\n        // Update.\n        em.merge(foundEntity);\n\n        em.clear();\n\n        foundEntity = em.find(EntityWithMultiplePartitionKey.class, id);\n        Assert.assertNotNull(foundEntity);\n        Assert.assertNotNull(foundEntity.getId());\n        Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n        Assert.assertEquals(\"updating\", foundEntity.getAction());\n        Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                foundEntity.getEntityDiscription());\n        Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n        Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n        Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n        Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n\n        // Delete.\n        em.remove(foundEntity);\n        em.clear();\n\n        foundEntity = em.find(EntityWithMultiplePartitionKey.class, id);\n        Assert.assertNull(foundEntity);\n\n    }\n\n    @Test\n    public void testQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        PartitionKey partitionKey1 = new PartitionKey();\n        partitionKey1.setPartitionKey1(\"partitionKey1\");\n        partitionKey1.setPartitionKey2(1);\n\n        IdWithMultiplePartitionKey id1 = new IdWithMultiplePartitionKey();\n        id1.setClusterkey1(\"clusterkey1\");\n        id1.setClusterkey2(11);\n        id1.setPartitionKey(partitionKey1);\n\n        EntityWithMultiplePartitionKey entity1 = new EntityWithMultiplePartitionKey();\n        entity1.setEntityDiscription(\"Entity to test composite key with multiple partition key.\");\n        entity1.setAction(\"Persisting\");\n        entity1.setId(id1);\n\n        PartitionKey partitionKey2 = new PartitionKey();\n        partitionKey2.setPartitionKey1(\"partitionKey2\");\n        partitionKey2.setPartitionKey2(2);\n\n        IdWithMultiplePartitionKey id2 = new IdWithMultiplePartitionKey();\n        id2.setClusterkey1(\"clusterkey2\");\n        id2.setClusterkey2(111);\n        id2.setPartitionKey(partitionKey2);\n\n        EntityWithMultiplePartitionKey entity2 = new EntityWithMultiplePartitionKey();\n        entity2.setEntityDiscription(\"Entity to test composite key with multiple partition key.\");\n        entity2.setAction(\"Persisting\");\n        entity2.setId(id2);\n\n        PartitionKey partitionKey3 = new PartitionKey();\n        partitionKey3.setPartitionKey1(\"partitionKey3\");\n        partitionKey3.setPartitionKey2(3);\n\n        IdWithMultiplePartitionKey id3 = new IdWithMultiplePartitionKey();\n        id3.setClusterkey1(\"clusterkey3\");\n        id3.setClusterkey2(1111);\n        id3.setPartitionKey(partitionKey3);\n\n        EntityWithMultiplePartitionKey entity3 = new EntityWithMultiplePartitionKey();\n        entity3.setEntityDiscription(\"Entity to test composite key with multiple partition key.\");\n        entity3.setAction(\"Persisting\");\n        entity3.setId(id3);\n\n        // Insert.\n        em.persist(entity1);\n        em.persist(entity2);\n        em.persist(entity3);\n\n        em.clear();\n\n        // Select All query.\n        List<EntityWithMultiplePartitionKey> foundEntitys = em.createQuery(\n                \"select e from EntityWithMultiplePartitionKey e\").getResultList();\n\n        Assert.assertNotNull(foundEntitys);\n        Assert.assertFalse(foundEntitys.isEmpty());\n        Assert.assertEquals(3, foundEntitys.size());\n\n        int count = 0;\n        for (EntityWithMultiplePartitionKey foundEntity : foundEntitys)\n        {\n            Assert.assertNotNull(foundEntity);\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n\n            if (foundEntity.getId().getClusterkey1().equals(\"clusterkey1\"))\n            {\n                Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n                Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n            else if (foundEntity.getId().getClusterkey1().equals(\"clusterkey2\"))\n            {\n                Assert.assertEquals(111, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey2\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(2, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(\"clusterkey3\", foundEntity.getId().getClusterkey1());\n                Assert.assertEquals(1111, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey3\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(3, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.clear();\n\n        // Select by both partition key query.\n        foundEntitys = em\n                .createQuery(\n                        \"select e from EntityWithMultiplePartitionKey e where e.id.partitionKey.partitionKey1=partitionKey1 and e.id.partitionKey.partitionKey2=1\")\n                .getResultList();\n\n        Assert.assertNotNull(foundEntitys);\n        Assert.assertFalse(foundEntitys.isEmpty());\n        Assert.assertEquals(1, foundEntitys.size());\n\n        count = 0;\n        for (EntityWithMultiplePartitionKey foundEntity : foundEntitys)\n        {\n            Assert.assertNotNull(foundEntity);\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n            Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n            Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n            Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n            Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n\n        // Select by both partition key query and one cluster key.\n        foundEntitys = em\n                .createQuery(\n                        \"select e from EntityWithMultiplePartitionKey e where e.id.partitionKey.partitionKey1=partitionKey1 and e.id.partitionKey.partitionKey2=1 and e.id.clusterkey1=clusterkey1\")\n                .getResultList();\n\n        Assert.assertNotNull(foundEntitys);\n        Assert.assertFalse(foundEntitys.isEmpty());\n        Assert.assertEquals(1, foundEntitys.size());\n\n        count = 0;\n        for (EntityWithMultiplePartitionKey foundEntity : foundEntitys)\n        {\n            Assert.assertNotNull(foundEntity);\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n            Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n            Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n            Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n            Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n\n        // Select by both partition key query.\n        foundEntitys = em\n                .createQuery(\"select e from EntityWithMultiplePartitionKey e where e.id.partitionKey = :partitionKey\")\n                .setParameter(\"partitionKey\", partitionKey1).getResultList();\n\n        Assert.assertNotNull(foundEntitys);\n        Assert.assertFalse(foundEntitys.isEmpty());\n        Assert.assertEquals(1, foundEntitys.size());\n\n        count = 0;\n        for (EntityWithMultiplePartitionKey foundEntity : foundEntitys)\n        {\n            Assert.assertNotNull(foundEntity);\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n            Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n            Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n            Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n            Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n\n        // Select by first partition key with equal clause and second partition\n        // key with IN clause.\n        try\n        {\n            foundEntitys = em\n                    .createQuery(\n                            \"select e from EntityWithMultiplePartitionKey e where e.id.partitionKey.partitionKey1=partitionKey1 and e.id.partitionKey.partitionKey2 IN (1, 2, 3)\")\n                    .getResultList();\n\n            Assert.assertNotNull(foundEntitys);\n            Assert.assertFalse(foundEntitys.isEmpty());\n            Assert.assertEquals(1, foundEntitys.size());\n\n            count = 0;\n            for (EntityWithMultiplePartitionKey foundEntity : foundEntitys)\n            {\n                Assert.assertNotNull(foundEntity);\n                Assert.assertNotNull(foundEntity.getId());\n                Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n                Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n                Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                        foundEntity.getEntityDiscription());\n                Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n                Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n        }\n        catch (Exception e)\n        {\n            log.warn(e.getMessage());\n        }\n\n        // Select by composite id object query.\n        try\n        {\n            foundEntitys = em.createQuery(\"select e from EntityWithMultiplePartitionKey e where e.id = :id\")\n                    .setParameter(\"id\", id1).getResultList();\n\n            Assert.assertNotNull(foundEntitys);\n            Assert.assertFalse(foundEntitys.isEmpty());\n            Assert.assertEquals(1, foundEntitys.size());\n\n            count = 0;\n            for (EntityWithMultiplePartitionKey foundEntity : foundEntitys)\n            {\n                Assert.assertNotNull(foundEntity);\n                Assert.assertNotNull(foundEntity.getId());\n                Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n                Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n                Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                        foundEntity.getEntityDiscription());\n                Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n                Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n        }\n        catch (Exception e)\n        {\n            Assert.fail();\n        }\n        \n     // Select by cluster key only.\n        try\n        {\n            foundEntitys = em.createQuery(\"select e from EntityWithMultiplePartitionKey e where e.id.clusterkey1=clusterkey1\").getResultList();\n\n            Assert.assertNotNull(foundEntitys);\n            Assert.assertFalse(foundEntitys.isEmpty());\n            Assert.assertEquals(1, foundEntitys.size());\n\n            count = 0;\n            for (EntityWithMultiplePartitionKey foundEntity : foundEntitys)\n            {\n                Assert.assertNotNull(foundEntity);\n                Assert.assertNotNull(foundEntity.getId());\n                Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n                Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n                Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                        foundEntity.getEntityDiscription());\n                Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n                Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n        }\n        catch (Exception e)\n        {\n            Assert.fail();\n        }\n\n        // Select by first partition key query.\n        try\n        {\n            foundEntitys = em\n                    .createQuery(\n                            \"select e from EntityWithMultiplePartitionKey e where e.id.partitionKey.partitionKey1=partitionKey1\")\n                    .getResultList();\n            EntityWithMultiplePartitionKey foundEntity = foundEntitys.get(0);\n\t\t\tAssert.assertNotNull(foundEntity );\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n            Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n            Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n            Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n            Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n\n        }\n        catch (Exception e)\n        {\n        \tAssert.fail();\n        }\n\n        //test iteration of result.\n        Query query = (com.impetus.kundera.query.Query) em\n                .createQuery(\"SELECT e FROM EntityWithMultiplePartitionKey e\");\n\n        query.setFetchSize(1);\n\n        Iterator<EntityWithMultiplePartitionKey> iterator = query.iterate();\n        count = 0;\n        while (iterator.hasNext())\n        {\n            EntityWithMultiplePartitionKey entity = iterator.next();\n            Assert.assertNotNull(entity);\n            Assert.assertNotNull(entity.getId());\n            Assert.assertNotNull(entity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", entity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    entity.getEntityDiscription());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/IdWithMultiplePartitionKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Embedded;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\n@Embeddable\npublic class IdWithMultiplePartitionKey implements Serializable\n{\n    private static final long serialVersionUID = 10000000L;\n\n    @Embedded\n    private PartitionKey partitionKey;\n\n    @Column\n    private String clusterkey1;\n\n    @Column\n    private int clusterkey2;\n\n    /**\n     * @return the partitionKey\n     */\n    public PartitionKey getPartitionKey()\n    {\n        return partitionKey;\n    }\n\n    /**\n     * @param partitionKey\n     *            the partitionKey to set\n     */\n    public void setPartitionKey(PartitionKey partitionKey)\n    {\n        this.partitionKey = partitionKey;\n    }\n\n    /**\n     * @return the clusterkey1\n     */\n    public String getClusterkey1()\n    {\n        return clusterkey1;\n    }\n\n    /**\n     * @param clusterkey1\n     *            the clusterkey1 to set\n     */\n    public void setClusterkey1(String clusterkey1)\n    {\n        this.clusterkey1 = clusterkey1;\n    }\n\n    /**\n     * @return the clusterkey2\n     */\n    public int getClusterkey2()\n    {\n        return clusterkey2;\n    }\n\n    /**\n     * @param clusterkey2\n     *            the clusterkey2 to set\n     */\n    public void setClusterkey2(int clusterkey2)\n    {\n        this.clusterkey2 = clusterkey2;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/LuceneCompositeKeyTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * test case for lucenecompositekey\n * \n * @author shaheed.hussain\n * \n */\npublic class LuceneCompositeKeyTest\n{\n    private static final String PERSISTENCE_UNIT = \"cassandra_cql\";\n\n    private static final String _keyspace = \"CqlKeyspace\";\n\n    private static final String LUCENE_DIR_PATH = \"./lucene\";\n\n    private static final Logger log = LoggerFactory.getLogger(LuceneCompositeKeyTest.class);\n\n    private EntityManager em;\n\n    private EntityManagerFactory emf;\n\n    private Date currentDate = new Date();\n\n    private Map<String, Object> puProperties = new HashMap<String, Object>();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        puProperties.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        puProperties.put(\"index.home.dir\", \"lucene\");\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n        CassandraCli.createKeySpace(_keyspace);\n        \n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        CassandraCli.dropKeySpace(_keyspace);\n        LuceneCleanupUtilities.cleanDir(LUCENE_DIR_PATH);\n    }\n\n    @Test\n    public void compositeKeyQuerytest()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, puProperties);\n        em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n        CassandraPrimeUser user = new CassandraPrimeUser(key);\n        user.setName(\"ankit\");\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        CassandraCompoundKey key2 = new CassandraCompoundKey(\"shahid\", 1, timeLineId);\n        CassandraPrimeUser user2 = new CassandraPrimeUser(key2);\n        user2.setTweetBody(\"my second tweet\");\n        user2.setTweetDate(currentDate);\n        em.persist(user2);\n\n        em.flush(); // optional,just to clear persistence cache.\n\n        em.clear();\n\n        CassandraPrimeUser u = em.find(CassandraPrimeUser.class, key);\n        Assert.assertEquals(\"my first tweet\", u.getTweetBody());\n\n        em.clear();\n\n        final String s = \"Select u.name from CassandraPrimeUser u where u.name=ankit\";\n        Query qu = em.createQuery(s);\n        List<CassandraPrimeUser> result = qu.getResultList();\n        Assert.assertNotNull(result.get(0).getName());\n        Assert.assertNull(result.get(0).getTweetBody());\n        Assert.assertNull(result.get(0).getTweetDate());\n\n        final String selectiveColumnTweetBodyWithAllCompositeColClause = \"Select u from CassandraPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n\n        // Query for selective column tweetBody with composite key clause.\n        Query q = em.createQuery(selectiveColumnTweetBodyWithAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        List<CassandraPrimeUser> results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"my first tweet\", results.get(0).getTweetBody());\n\n        final String selectiveColumnTweetDateWithAllCompositeColClause = \"Select u from CassandraPrimeUser u where u.key.userId = :userId and u.key.timeLineId = :timeLineId\";\n        // Query for selective column tweetDate with composite key clause.\n        q = em.createQuery(selectiveColumnTweetDateWithAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(currentDate.getTime(), results.get(0).getTweetDate().getTime());\n\n        final String querySearcingAllRecords = \"Select u from CassandraPrimeUser u\";\n        // Query with composite key clause.\n        q = em.createQuery(querySearcingAllRecords);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        final String withCompositeKeyClause = \"Select u from CassandraPrimeUser u where u.key = :key\";\n        // Query with composite key clause.\n        q = em.createQuery(withCompositeKeyClause);\n        q.setParameter(\"key\", key);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        em.flush(); // just to clear persistence cache.\n        em.clear();\n\n        em.remove(user);\n\n        em.flush(); // optional,just to clear persistence cache.\n        em.clear();\n\n        final String querySearcingAfterDeletion = \"Select u from CassandraPrimeUser u\";\n        // Query with composite key clause.\n        q = em.createQuery(querySearcingAfterDeletion);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n    }\n\n    @Test\n    public void compositeKeytest()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, puProperties);\n        em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n\n        CassandraCompoundKey key = new CassandraCompoundKey(\"shahid\", 1, timeLineId);\n        CassandraPrimeUser user = new CassandraPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        CassandraPrimeUser user2 = new CassandraPrimeUser(key);\n        user2.setTweetBody(\"my second tweet\");\n        user2.setTweetDate(currentDate);\n\n        em.flush(); // optional,just to clear persistence cache.\n\n        em.clear();\n\n        CassandraPrimeUser u = em.find(CassandraPrimeUser.class, key);\n        Assert.assertEquals(\"my first tweet\", u.getTweetBody());\n\n        em.merge(user2);\n        u = em.find(CassandraPrimeUser.class, key);\n        Assert.assertEquals(\"my second tweet\", u.getTweetBody());\n        em.remove(user2);\n    }\n\n    @Test\n    public void lucenePartitionKeyTest()\n    {\n        createMultiplePatitionKeyTable();\n        puProperties.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"\");\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, puProperties);\n        em = emf.createEntityManager();\n\n        PartitionKey partitionKey1 = new PartitionKey();\n        partitionKey1.setPartitionKey1(\"partitionKey1\");\n        partitionKey1.setPartitionKey2(1);\n\n        IdWithMultiplePartitionKey id1 = new IdWithMultiplePartitionKey();\n        id1.setClusterkey1(\"clusterkey1\");\n        id1.setClusterkey2(11);\n        id1.setPartitionKey(partitionKey1);\n\n        EntityWithMultiplePartitionKey entity1 = new EntityWithMultiplePartitionKey();\n        entity1.setEntityDiscription(\"Entity to test composite key with multiple partition key.\");\n        entity1.setAction(\"Persisting\");\n        entity1.setId(id1);\n\n        PartitionKey partitionKey2 = new PartitionKey();\n        partitionKey2.setPartitionKey1(\"partitionKey2\");\n        partitionKey2.setPartitionKey2(2);\n\n        IdWithMultiplePartitionKey id2 = new IdWithMultiplePartitionKey();\n        id2.setClusterkey1(\"clusterkey2\");\n        id2.setClusterkey2(111);\n        id2.setPartitionKey(partitionKey2);\n\n        EntityWithMultiplePartitionKey entity2 = new EntityWithMultiplePartitionKey();\n        entity2.setEntityDiscription(\"Entity to test composite key with multiple partition key.\");\n        entity2.setAction(\"Persisting\");\n        entity2.setId(id2);\n\n        PartitionKey partitionKey3 = new PartitionKey();\n        partitionKey3.setPartitionKey1(\"partitionKey3\");\n        partitionKey3.setPartitionKey2(3);\n\n        IdWithMultiplePartitionKey id3 = new IdWithMultiplePartitionKey();\n        id3.setClusterkey1(\"clusterkey3\");\n        id3.setClusterkey2(1111);\n        id3.setPartitionKey(partitionKey3);\n\n        EntityWithMultiplePartitionKey entity3 = new EntityWithMultiplePartitionKey();\n        entity3.setEntityDiscription(\"Entity to test composite key with multiple partition key.\");\n        entity3.setAction(\"Persisting\");\n        entity3.setId(id3);\n\n        // Insert.\n        em.persist(entity1);\n        em.persist(entity2);\n        em.persist(entity3);\n\n        em.clear();\n\n        // Select All query.\n        List<EntityWithMultiplePartitionKey> foundEntitys = em.createQuery(\n                \"select e from EntityWithMultiplePartitionKey e\").getResultList();\n\n        Assert.assertNotNull(foundEntitys);\n        Assert.assertFalse(foundEntitys.isEmpty());\n        Assert.assertEquals(3, foundEntitys.size());\n\n        int count = 0;\n        for (EntityWithMultiplePartitionKey foundEntity : foundEntitys)\n        {\n            Assert.assertNotNull(foundEntity);\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n\n            if (foundEntity.getId().getClusterkey1().equals(\"clusterkey1\"))\n            {\n                Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n                Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n            else if (foundEntity.getId().getClusterkey1().equals(\"clusterkey2\"))\n            {\n                Assert.assertEquals(111, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey2\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(2, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(\"clusterkey3\", foundEntity.getId().getClusterkey1());\n                Assert.assertEquals(1111, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey3\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(3, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.clear();\n\n        // Select by both partition key query.\n        foundEntitys = em\n                .createQuery(\n                        \"select e from EntityWithMultiplePartitionKey e where e.id.partitionKey.partitionKey1=partitionKey1 and e.id.partitionKey.partitionKey2=1\")\n                .getResultList();\n\n        Assert.assertNotNull(foundEntitys);\n        Assert.assertFalse(foundEntitys.isEmpty());\n        Assert.assertEquals(1, foundEntitys.size());\n\n        count = 0;\n        for (EntityWithMultiplePartitionKey foundEntity : foundEntitys)\n        {\n            Assert.assertNotNull(foundEntity);\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n            Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n            Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n            Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n            Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n\n        // Select by both partition key query and one cluster key.\n        foundEntitys = em\n                .createQuery(\n                        \"select e from EntityWithMultiplePartitionKey e where e.id.partitionKey.partitionKey1=partitionKey1 and e.id.partitionKey.partitionKey2=1 and e.id.clusterkey1=clusterkey1\")\n                .getResultList();\n\n        Assert.assertNotNull(foundEntitys);\n        Assert.assertFalse(foundEntitys.isEmpty());\n        Assert.assertEquals(1, foundEntitys.size());\n\n        count = 0;\n        for (EntityWithMultiplePartitionKey foundEntity : foundEntitys)\n        {\n            Assert.assertNotNull(foundEntity);\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n            Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n            Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n            Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n            Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n\n        // Select by both partition key query.\n        foundEntitys = em\n                .createQuery(\"select e from EntityWithMultiplePartitionKey e where e.id.partitionKey = :partitionKey\")\n                .setParameter(\"partitionKey\", partitionKey1).getResultList();\n\n        Assert.assertNotNull(foundEntitys);\n        Assert.assertFalse(foundEntitys.isEmpty());\n        Assert.assertEquals(1, foundEntitys.size());\n\n        count = 0;\n        for (EntityWithMultiplePartitionKey foundEntity : foundEntitys)\n        {\n            Assert.assertNotNull(foundEntity);\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n            Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n            Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n            Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n            Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n\n        try\n        {\n            foundEntitys = em.createQuery(\"select e from EntityWithMultiplePartitionKey e where e.id = :id\")\n                    .setParameter(\"id\", id1).getResultList();\n\n            Assert.assertNotNull(foundEntitys);\n            Assert.assertFalse(foundEntitys.isEmpty());\n            Assert.assertEquals(1, foundEntitys.size());\n\n            count = 0;\n            for (EntityWithMultiplePartitionKey foundEntity : foundEntitys)\n            {\n                Assert.assertNotNull(foundEntity);\n                Assert.assertNotNull(foundEntity.getId());\n                Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n                Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n                Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                        foundEntity.getEntityDiscription());\n                Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n                Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n        }\n        catch (Exception e)\n        {\n            Assert.fail();\n        }\n\n        // Select by first partition key query.\n        try\n        {\n            foundEntitys = em\n                    .createQuery(\n                            \"select e from EntityWithMultiplePartitionKey e where e.id.partitionKey.partitionKey1=partitionKey1\")\n                    .getResultList();\n\n            Assert.fail();\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\"Incomplete partition key fields in query\", e.getMessage());\n        }\n\n    }\n    \n    private void createMultiplePatitionKeyTable() {\n        try\n        {\n            CassandraCli\n                    .executeCqlQuery(\n                            \"create table \\\"EntityWithMultiplePartitionKey\\\"(\\\"partitionKey1\\\" text, \\\"partitionKey2\\\" int, \\\"clusterkey1\\\" text, \\\"clusterkey2\\\" int, \\\"entityDiscription\\\" text, action text, PRIMARY KEY((\\\"partitionKey1\\\", \\\"partitionKey2\\\"), \\\"clusterkey1\\\", \\\"clusterkey2\\\"))\",\n                            _keyspace);\n        }\n        catch (Exception e)\n        {\n            log.warn(e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/PartitionKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\n@Embeddable\npublic class PartitionKey implements Serializable\n{\n\n    private static final long serialVersionUID = 100000L;\n\n    @Column\n    private String partitionKey1;\n\n    @Column\n    private int partitionKey2;\n\n    /**\n     * @return the partitionKey1\n     */\n    public String getPartitionKey1()\n    {\n        return partitionKey1;\n    }\n\n    /**\n     * @param partitionKey1\n     *            the partitionKey1 to set\n     */\n    public void setPartitionKey1(String partitionKey1)\n    {\n        this.partitionKey1 = partitionKey1;\n    }\n\n    /**\n     * @return the partitionKey2\n     */\n    public int getPartitionKey2()\n    {\n        return partitionKey2;\n    }\n\n    /**\n     * @param partitionKey2\n     *            the partitionKey2 to set\n     */\n    public void setPartitionKey2(int partitionKey2)\n    {\n        this.partitionKey2 = partitionKey2;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/PrimeUserDataType.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"CompositeUserDataType\", schema = \"CompositeCassandra@compositedatatype\")\n// @Index(index = true,columns = { \"tweetBody\",\"tweetDate\" })\npublic class PrimeUserDataType\n{\n\n    @EmbeddedId\n    private CompoundKeyDataType key;\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private Date tweetDate;\n\n    @Column\n    private Boolean isActive;\n\n    public PrimeUserDataType()\n    {\n    }\n\n    public PrimeUserDataType(CompoundKeyDataType key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the key\n     */\n    public CompoundKeyDataType getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n    public Boolean getIsActive()\n    {\n        return isActive;\n    }\n\n    public void setIsActive(Boolean isActive)\n    {\n        this.isActive = isActive;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/association/AddressOTOPK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType.association;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"AddressOTOPK\", schema = \"KunderaExamples@thriftClientTest\")\npublic class AddressOTOPK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @OneToOne(mappedBy = \"address\", fetch = FetchType.LAZY)\n    private UserOTOPK user;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public UserOTOPK getUser()\n    {\n        return user;\n    }\n\n    public void setUser(UserOTOPK user)\n    {\n        this.user = user;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/association/CassandraAddressUniOTM.java",
    "content": "package com.impetus.client.crud.compositeType.association;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"CassandraAddressUniOTM\", schema = \"KunderaExamples@secIdxCassandraTest\")\npublic class CassandraAddressUniOTM\n{\n\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/association/CassandraUserOTMTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.crud.compositeType.association;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author impadmin\n * \n */\npublic class CassandraUserOTMTest\n{\n\n    private static final String _KEYSPACE = \"KunderaExamples\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(_KEYSPACE);\n        loadData();\n        // HashMap propertyMap = new HashMap();\n        // propertyMap.put(CassandraConstants.CQL_VERSION,\n        // CassandraConstants.CQL_VERSION_3_0);\n        // propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE,\n        // \"create\");\n        emf = Persistence.createEntityManagerFactory(\"secIdxCassandraTest\");\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(_KEYSPACE);\n        emf.close();\n    }\n\n    @Test\n    public void test()\n    {\n        em = emf.createEntityManager();\n\n        Set<CassandraAddressUniOTM> addresses = new HashSet<CassandraAddressUniOTM>();\n\n        CassandraAddressUniOTM address1 = new CassandraAddressUniOTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"my street\");\n        CassandraAddressUniOTM address2 = new CassandraAddressUniOTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"my new street\");\n\n        addresses.add(address1);\n        addresses.add(address2);\n\n        CassandraUserUniOTM userUniOTM = new CassandraUserUniOTM();\n        userUniOTM.setPersonId(\"1\");\n        userUniOTM.setPersonName(\"kuldeep\");\n        userUniOTM.setAddresses(addresses);\n\n        em.persist(userUniOTM);\n\n        em.clear();\n\n        CassandraUserUniOTM foundObject = em.find(CassandraUserUniOTM.class, \"1\");\n        Assert.assertNotNull(foundObject);\n        Assert.assertEquals(2, foundObject.getAddresses().size());\n\n        Query q = em.createQuery(\"Select u from CassandraUserUniOTM u\");\n        List<CassandraUserUniOTM> users = q.getResultList();\n        Assert.assertNotNull(users);\n        Assert.assertEquals(1, users.size());\n        Assert.assertNotNull(users.get(0));\n        Assert.assertEquals(\"kuldeep\", users.get(0).getPersonName());\n        Assert.assertEquals(\"1\", users.get(0).getPersonId());\n        Assert.assertNotNull(users.get(0).getAddresses());\n        Assert.assertEquals(2, users.get(0).getAddresses().size());\n\n        em.remove(foundObject);\n\n        foundObject = em.find(CassandraUserUniOTM.class, \"1\");\n        Assert.assertNull(foundObject);\n    }\n\n    /**\n     * Loads data.\n     * \n     * @throws InvalidRequestException\n     * @throws SchemaDisagreementException\n     * @throws TException\n     */\n    private void loadData() throws InvalidRequestException, SchemaDisagreementException, TException\n    {\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n\n        CfDef user = new CfDef(_KEYSPACE, \"CassandraUserUniOTM\");\n        user.setKey_validation_class(\"UTF8Type\");\n        user.setDefault_validation_class(\"UTF8Type\");\n        user.setComparator_type(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"PERSON_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        user.addToColumn_metadata(columnDef);\n\n        CfDef address = new CfDef(_KEYSPACE, \"CassandraAddressUniOTM\");\n        address.setKey_validation_class(\"UTF8Type\");\n        address.setDefault_validation_class(\"UTF8Type\");\n        address.setComparator_type(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PERSON_ID\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"STREET\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n\n        address.addToColumn_metadata(columnDef1);\n        address.addToColumn_metadata(columnDef2);\n\n        cfDefs.add(user);\n        cfDefs.add(address);\n        KsDef ksDef = null;\n        try\n        {\n            CassandraCli.initClient();\n            ksDef = CassandraCli.client.describe_keyspace(_KEYSPACE);\n            CassandraCli.client.set_keyspace(_KEYSPACE);\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n                if (cfDef1.getName().equals(\"CassandraUserUniOTM\"))\n                {\n                    CassandraCli.client.system_drop_column_family(\"CassandraUserUniOTM\");\n                }\n                if (cfDef1.getName().equals(\"CassandraAddressUniOTM\"))\n                {\n                    CassandraCli.client.system_drop_column_family(\"CassandraAddressUniOTM\");\n                }\n            }\n            CassandraCli.client.system_add_column_family(user);\n            CassandraCli.client.system_add_column_family(address);\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new org.apache.cassandra.thrift.KsDef(_KEYSPACE, \"org.apache.cassandra.locator.SimpleStrategy\",\n                    cfDefs);\n\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n            CassandraCli.client.system_add_keyspace(ksDef);\n\n            CassandraCli.client.set_keyspace(_KEYSPACE);\n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/association/CassandraUserUniOTM.java",
    "content": "package com.impetus.client.crud.compositeType.association;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"CassandraUserUniOTM\", schema = \"KunderaExamples@secIdxCassandraTest\")\npublic class CassandraUserUniOTM\n{\n\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<CassandraAddressUniOTM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<CassandraAddressUniOTM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<CassandraAddressUniOTM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/association/UserInfo.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType.association;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"UserInfo\", schema = \"CompositeCassandra@composite_pu\")\npublic class UserInfo\n{\n\n    @Id\n    @Column(name = \"userInfo_id\")\n    private String userInfoId;\n\n    @Column(name = \"first_name\")\n    private String firstName;\n\n    @Column(name = \"last_name\")\n    private String lastName;\n\n    @Column(name = \"age\")\n    private int age;\n\n    // Height in cm.\n    @Column(name = \"height\")\n    private transient int height;\n\n    /**\n     * \n     */\n    public UserInfo()\n    {\n    }\n\n    /**\n     * @param userInfoId\n     * @param firstName\n     * @param lastName\n     * @param age\n     * @param timeLine\n     */\n    public UserInfo(String userInfoId, String firstName, String lastName, int age, int height)\n    {\n        super();\n        this.userInfoId = userInfoId;\n        this.firstName = firstName;\n        this.lastName = lastName;\n        this.age = age;\n        this.height = height;\n    }\n\n    /**\n     * @return the userInfoId\n     */\n    public String getUserInfoId()\n    {\n        return userInfoId;\n    }\n\n    /**\n     * @return the firstName\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * @return the lastName\n     */\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param firstName\n     *            the firstName to set\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the height\n     */\n    public int getHeight()\n    {\n        return height;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/association/UserInfoTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType.association;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.compositeType.CassandraCompoundKey;\nimport com.impetus.client.crud.compositeType.CassandraEmbeddedAssociation;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class UserInfoTest\n{\n    private static final String _CQL_VERSION = \"2.0.0\";\n\n    private EntityManagerFactory emf;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n        CassandraCli.dropKeySpace(\"CompositeCassandra\");\n        loadData();\n        Map<String, String> props = new HashMap<String, String>(1);\n        props.put(\"kundera.ddl.auto.prepare\", \"\");\n        emf = Persistence.createEntityManagerFactory(\"composite_pu\", props);\n    }\n\n    @Test\n    public void onCRUD()\n    {\n        EntityManager em = createEM(_CQL_VERSION);\n\n        // persist userinfo object only.\n        UserInfo userInfo = new UserInfo(\"mevivs_info\", \"Vivek\", \"Mishra\", 31, 168);\n        em.persist(userInfo);\n\n        em.clear();\n        em.close();\n        em = createEM(_CQL_VERSION);\n\n        UserInfo foundUser = em.find(UserInfo.class, userInfo.getUserInfoId());\n        Assert.assertNotNull(foundUser);\n        Assert.assertEquals(\"Mishra\", foundUser.getLastName());\n        Assert.assertEquals(\"Vivek\", foundUser.getFirstName());\n        Assert.assertEquals(31, foundUser.getAge());\n        Assert.assertEquals(0, foundUser.getHeight());\n\n        em.remove(foundUser);\n\n        em.clear();\n        em.close();\n        em = createEM(_CQL_VERSION);\n\n        UserInfo deletedUser = em.find(UserInfo.class, userInfo.getUserInfoId());\n        Assert.assertNull(deletedUser);\n\n        em.clear();\n        em.close();\n        em = createEM(_CQL_VERSION);\n\n        // Persist\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n        CassandraEmbeddedAssociation timeLine = new CassandraEmbeddedAssociation(key);\n        timeLine.setTweetBody(\"my first tweet\");\n        timeLine.setTweetDate(currentDate);\n\n        timeLine.setUserInfo(userInfo);\n        em.persist(timeLine);\n        em.clear();\n        em.close();\n\n        em = createEM(_CQL_VERSION);\n\n        // Find\n        CassandraEmbeddedAssociation result = em.find(CassandraEmbeddedAssociation.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(currentDate, result.getTweetDate());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(\"Vivek\", result.getUserInfo().getFirstName());\n        Assert.assertEquals(31, result.getUserInfo().getAge());\n        Assert.assertEquals(0, result.getUserInfo().getHeight());\n\n        result.getUserInfo().setFirstName(\"Kuldeep\");\n        result.getUserInfo().setAge(23);\n\n        em.merge(result);\n\n        em.clear();\n        em.close();\n        em = createEM(_CQL_VERSION);\n        // Find\n        result = null;\n        result = em.find(CassandraEmbeddedAssociation.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(currentDate, result.getTweetDate());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(\"Kuldeep\", result.getUserInfo().getFirstName());\n        Assert.assertEquals(23, result.getUserInfo().getAge());\n        Assert.assertEquals(0, result.getUserInfo().getHeight());\n\n        em.remove(result);\n\n        em.clear();\n        em.close();\n        em = createEM(_CQL_VERSION);\n\n        result = em.find(CassandraEmbeddedAssociation.class, key);\n        Assert.assertNull(result);\n\n    }\n\n    private EntityManager createEM(String cqlVersion)\n    {\n        EntityManager em = emf.createEntityManager();\n        // Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        // Client client = clients.get(\"composite_pu\");\n        // ((CassandraClientBase) client).setCqlVersion(cqlVersion);\n        return em;\n    }\n\n    @Test\n    public void onQuery()\n    {\n        EntityManager em = createEM(_CQL_VERSION);\n\n        // Persist\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n        CassandraEmbeddedAssociation timeLine = new CassandraEmbeddedAssociation(key);\n        timeLine.setTweetBody(\"my first tweet\");\n        timeLine.setTweetDate(currentDate);\n\n        UserInfo userInfo = new UserInfo(\"mevivs_info\", \"Vivek\", \"Mishra\", 31, 170);\n        timeLine.setUserInfo(userInfo);\n        em.persist(timeLine);\n\n        em.clear(); // optional,just to clear persistence cache.\n        em.flush();\n\n        final String noClause = \"Select t from CassandraEmbeddedAssociation t\";\n\n        Query query = em.createQuery(noClause);\n        List<CassandraEmbeddedAssociation> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"Vivek\", results.get(0).getUserInfo().getFirstName());\n        Assert.assertEquals(31, results.get(0).getUserInfo().getAge());\n        Assert.assertEquals(0, results.get(0).getUserInfo().getHeight());\n\n        em.remove(timeLine);\n\n        em.clear();// optional,just to clear persistence cache.\n        em.close();\n\n        em = createEM(_CQL_VERSION);\n        UserInfo user_Info = em.find(UserInfo.class, \"mevivs_info\");\n        Assert.assertNull(user_Info);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        CassandraCli.dropKeySpace(\"CompositeCassandra\");\n    }\n\n    /**\n     * Loads data.\n     * \n     * @throws InvalidRequestException\n     * @throws SchemaDisagreementException\n     * @throws TException\n     */\n    private void loadData() throws InvalidRequestException, SchemaDisagreementException, TException\n    {\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        CfDef cfDef = new CfDef(\"CompositeCassandra\", \"UserInfo\");\n        cfDef.setKey_validation_class(\"UTF8Type\");\n        cfDef.setDefault_validation_class(\"UTF8Type\");\n        cfDef.setComparator_type(\"UTF8Type\");\n        cfDef.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"first_name\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef);\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"last_name\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef1);\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"age\".getBytes()), \"Int32Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef2);\n        // ColumnDef columnDef3 = new\n        // ColumnDef(ByteBuffer.wrap(\"height\".getBytes()), \"Int32Type\");\n        // columnDef3.index_type = IndexType.KEYS;\n        // cfDef.addToColumn_metadata(columnDef3);\n        cfDefs.add(cfDef);\n        KsDef ksDef = new KsDef(\"CompositeCassandra\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n\n        if (ksDef.strategy_options == null)\n        {\n            ksDef.strategy_options = new LinkedHashMap<String, String>();\n        }\n        ksDef.strategy_options.put(\"replication_factor\", \"1\");\n\n        CassandraCli.getClient().system_add_keyspace(ksDef);\n\n        CassandraCli.executeCqlQuery(\"USE \\\"CompositeCassandra\\\"\", ksDef.getName());\n\n        // \\\"first_name\\\" varchar,\\\"last_name\\\" varchar, \\\"age\\\" int,\n        CassandraCli\n                .executeCqlQuery(\n                        \"CREATE TABLE \\\"CompositeUserAssociation\\\" (\\\"userId\\\" varchar,\\\"tweetId\\\" int,\\\"timeLineId\\\" uuid, \\\"tweetBody\\\" varchar, \\\"tweetDate\\\" timestamp, \\\"userInfo_id\\\" varchar, PRIMARY KEY (\\\"userId\\\", \\\"tweetId\\\",\\\"timeLineId\\\"))\",\n                        ksDef.getName());\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/association/UserOTOPK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType.association;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"UserOTOPK\", schema = \"KunderaExamples@thriftClientTest\")\npublic class UserOTOPK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, optional = false)\n    @PrimaryKeyJoinColumn\n    private AddressOTOPK address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressOTOPK getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressOTOPK address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/compositeType/association/UserOTOPKTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType.association;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author impadmin\n * \n */\npublic class UserOTOPKTest\n{\n    private String keyspace = \"KunderaExamples\";\n\n    private EntityManagerFactory emf;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n        loadData();\n        emf = Persistence.createEntityManagerFactory(\"thriftClientTest\");\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(keyspace);\n        emf.close();\n    }\n\n    @Test\n    public void testOTOPk()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        AddressOTOPK addressOTOPK = new AddressOTOPK();\n        addressOTOPK.setAddressId(\"xyz\");\n        addressOTOPK.setStreet(\"STTRRREEEETTTTT\");\n\n        UserOTOPK userOTOPK = new UserOTOPK();\n        userOTOPK.setPersonId(\"1234\");\n        userOTOPK.setPersonName(\"Kuldeep\");\n        userOTOPK.setAddress(addressOTOPK);\n\n        em.persist(userOTOPK);\n\n        em.clear();\n\n        UserOTOPK otopk = em.find(UserOTOPK.class, \"1234\");\n        Assert.assertNotNull(otopk);\n        Assert.assertNotNull(otopk.getAddress());\n        Assert.assertEquals(\"Kuldeep\", otopk.getPersonName());\n        Assert.assertEquals(\"1234\", otopk.getAddress().getPersonId());\n        Assert.assertEquals(\"xyz\", otopk.getAddress().getAddressId());\n        Assert.assertEquals(\"STTRRREEEETTTTT\", otopk.getAddress().getStreet());\n\n        em.clear();\n\n        Query q = em.createQuery(\"Select u from UserOTOPK u\");\n        List<UserOTOPK> users = q.getResultList();\n        Assert.assertNotNull(users);\n        Assert.assertEquals(1, users.size());\n        Assert.assertNotNull(users.get(0));\n        Assert.assertNotNull(users.get(0).getAddress());\n        Assert.assertEquals(\"STTRRREEEETTTTT\", users.get(0).getAddress().getStreet());\n        em.close();\n\n    }\n\n    /**\n     * Loads data.\n     * \n     * @throws InvalidRequestException\n     * @throws SchemaDisagreementException\n     * @throws TException\n     */\n    private void loadData() throws InvalidRequestException, SchemaDisagreementException, TException\n    {\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n\n        CfDef user = new CfDef(keyspace, \"UserOTOPK\");\n        user.setKey_validation_class(\"UTF8Type\");\n        user.setDefault_validation_class(\"UTF8Type\");\n        user.setComparator_type(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"PERSON_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        user.addToColumn_metadata(columnDef);\n\n        CfDef address = new CfDef(keyspace, \"AddressOTOPK\");\n        address.setKey_validation_class(\"UTF8Type\");\n        address.setDefault_validation_class(\"UTF8Type\");\n        address.setComparator_type(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"ADDRESS_ID\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"STREET\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n\n        address.addToColumn_metadata(columnDef1);\n        address.addToColumn_metadata(columnDef2);\n\n        cfDefs.add(user);\n        cfDefs.add(address);\n        KsDef ksDef = null;\n        try\n        {\n            CassandraCli.initClient();\n            ksDef = CassandraCli.client.describe_keyspace(keyspace);\n            CassandraCli.client.set_keyspace(keyspace);\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n                if (cfDef1.getName().equalsIgnoreCase(\"UserOTOPK\"))\n                {\n                    CassandraCli.client.system_drop_column_family(\"UserOTOPK\");\n                }\n                if (cfDef1.getName().equalsIgnoreCase(\"AddressOTOPK\"))\n                {\n                    CassandraCli.client.system_drop_column_family(\"AddressOTOPK\");\n                }\n            }\n            CassandraCli.client.system_add_column_family(user);\n            CassandraCli.client.system_add_column_family(address);\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new org.apache.cassandra.thrift.KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\",\n                    cfDefs);\n\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n            CassandraCli.client.system_add_keyspace(ksDef);\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/countercolumns/CounterWithStringId.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud.countercolumns;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * Counter column family with id as string.\n *\n */\n@Entity\n@Table(name = \"CountersWithString\",schema = \"KunderaCounterColumn@CassandraCounterTest\")\npublic class CounterWithStringId\n{\n\n    @Id\n    @Column(name=\"counterkey\")\n    private String id;\n    \n    @Column\n    private int counter;\n\n\n    public CounterWithStringId()\n    {\n        \n    }\n    \n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public int getCounter()\n    {\n        return counter;\n    }\n\n    public void setCounter(int counter)\n    {\n        this.counter = counter;\n    }\n\n\n    \n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/countercolumns/CounterWithStringIdTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud.countercolumns;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author vivek.mishra\n * Added junit for counter column test\n *\n */\npublic class CounterWithStringIdTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        Map<String, String> propertyMap = new HashMap<String, String>();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(\"CassandraCounterTest\", propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void test()\n    {\n        CounterWithStringId entity = new CounterWithStringId();\n        entity.setCounter(1);\n        entity.setId(\"cnt1\");\n        em.persist(entity);\n        \n        em.clear();\n        CounterWithStringId result = em.find(CounterWithStringId.class, \"cnt1\");\n        \n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"cnt1\",result.getId());\n\n        // increment counter\n        result.setCounter(result.getCounter()+1);\n        em.merge(result);\n        \n        em.clear();\n        result = em.find(CounterWithStringId.class, \"cnt1\");\n        \n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"cnt1\",result.getId());\n        Assert.assertEquals(3,result.getCounter());\n\n\n        \n    }\n\n    @After\n    public void tearDown()\n    {\n        CassandraCli.dropKeySpace(\"KunderaCounterColumn\");\n        if (em != null)\n        {\n            em.close();\n        }\n\n        if (emf != null)\n        {\n            emf.close();\n        }\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/countercolumns/Counters.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.countercolumns;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"counters\", schema = \"KunderaCounterColumn@CassandraCounterTest\")\npublic class Counters\n{\n    @Id\n    private String id;\n\n    @Column\n    private int counter;\n\n    @Column\n    private transient int count;\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the counter1\n     */\n    public int getCounter()\n    {\n        return counter;\n    }\n\n    /**\n     * @param counter1\n     *            the counter1 to set\n     */\n    public void setCounter(int counter)\n    {\n        this.counter = counter;\n    }\n\n    public int getCount()\n    {\n        return count;\n    }\n\n    public void setCount(int count)\n    {\n        this.count = count;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/countercolumns/CountersCQL3BatchTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.countercolumns;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Cassandra.Client;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.api.Batcher;\n\n/**\n * The Class CountersBatchTest.\n * \n * @author: karthikp.manchala\n */\npublic class CountersCQL3BatchTest\n{\n\n    /** The Constant COUNTERS_PU. */\n    private static final String COUNTERS_PU = \"CassandraCounterTest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The Constant RUN_IN_EMBEDDED_MODE. */\n    private static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    /** The keyspace. */\n    private String keyspace = \"KunderaCounterColumn\";\n\n    /** The property map. */\n    protected Map propertyMap = new HashMap();\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startServer();\n        }\n\n        if (propertyMap.isEmpty())\n        {\n            propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n            propertyMap.put(PersistenceProperties.KUNDERA_BATCH_SIZE, \"5\");\n        }\n        emf = Persistence.createEntityManagerFactory(COUNTERS_PU, propertyMap);\n    }\n\n    /**\n     * Counters batch test.\n     */\n    @Test\n    public void countersBatchTest()\n    {\n        EntityManager em = emf.createEntityManager();\n        int count = 1;\n        List<Counters> rows = prepareData(10);\n        for (Counters entity : rows)\n        {\n            em.persist(entity);\n\n            int BATCH_SIZE = 5;\n            if (count < BATCH_SIZE)\n            {\n                Assert.assertNull(em.find(Counters.class, entity.getId()));\n            }\n            else if (count == BATCH_SIZE)\n            {\n                Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n\n                Batcher client = (Batcher) clients.get(COUNTERS_PU);\n                Assert.assertEquals(5, client.getBatchSize());\n                em.clear();\n                for (int i = 0; i < BATCH_SIZE; i++)\n                {\n                    // assert on each batch size record\n                    Assert.assertNotNull(em.find(Counters.class, rows.get(i).getId()));\n                }\n                count = 0;\n            }\n            count++;\n        }\n        em.close();\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param n\n     *            the n\n     * @return the list\n     */\n    private List<Counters> prepareData(int n)\n    {\n        List<Counters> rows = new ArrayList<Counters>();\n        for (int i = 0; i < n; i++)\n        {\n            Counters counter = new Counters();\n            counter.setCounter(1);\n            counter.setId(i + \"\");\n            rows.add(counter);\n        }\n        return rows;\n    }\n\n    /**\n     * Start server.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void startServer() throws IOException, TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        CassandraCli.cassandraSetUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (CassandraCli.client != null)\n        {\n            CassandraCli.dropKeySpace(keyspace);\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/countercolumns/CountersTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.countercolumns;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Cassandra.Client;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Counter column test case for Counter column family in cassandra.\n * \n * @author kuldeep.mishra\n * \n */\npublic class CountersTest\n{\n    private static final String id1 = \"12\";\n\n    private static final String id2 = \"15\";\n\n    private static final String id3 = \"18\";\n\n    private EntityManagerFactory emf;\n\n    private static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    private static final boolean AUTO_MANAGE_SCHEMA = true;\n\n    private String keyspace = \"KunderaCounterColumn\";\n\n    protected Map propertyMap = new HashMap();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startServer();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            // createSchema();\n        }\n        if (propertyMap.isEmpty())\n        {\n            propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_2_0);\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        }\n        emf = Persistence.createEntityManagerFactory(\"CassandraCounterTest\", propertyMap);\n    }\n\n    private void createSchema() throws InvalidRequestException, TException, SchemaDisagreementException\n    {\n        Client client = CassandraCli.getClient();\n        CassandraCli.createKeySpace(keyspace);\n        client.set_keyspace(keyspace);\n\n        CfDef cfDef = new CfDef();\n        cfDef.keyspace = keyspace;\n        cfDef.name = \"counters\";\n        cfDef.default_validation_class = \"CounterColumnType\";\n        cfDef.key_validation_class = \"UTF8Type\";\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"counter\".getBytes()), \"CounterColumnType\");\n        columnDef.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef);\n        cfDef.comparator_type = \"UTF8Type\";\n\n        client.system_add_column_family(cfDef);\n    }\n\n    private void startServer() throws IOException, TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        CassandraCli.cassandraSetUp();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (/* AUTO_MANAGE_SCHEMA && CassandraCli.keyspaceExist(keyspace) */CassandraCli.client != null)\n        {\n            CassandraCli.dropKeySpace(keyspace);\n        }\n    }\n\n    @Test\n    public void testCRUDOnCounter()\n    {\n        incrCounter();\n        decrCounter();\n        findCounter();\n        selectAllQuery();\n        queryGTEQOnId();\n        queryLTEQOnId();\n        rangeQuery();\n        mergeCounter();\n        updateNamedQueryOnCounter();\n        deleteNamedQueryOnCounter();\n        deleteCounter();\n        CassandraCli.truncateColumnFamily(keyspace, \"counters\");\n    }\n\n    public void incrCounter()\n    {\n        EntityManager em = emf.createEntityManager();\n        Counters counter = new Counters();\n        counter.setCounter(12);\n        counter.setId(id1);\n        em.persist(counter);\n\n        Counters counter1 = new Counters();\n        counter1.setCounter(15);\n        counter1.setId(id2);\n        em.persist(counter1);\n\n        Counters counter2 = new Counters();\n        counter2.setCounter(18);\n        counter2.setId(id3);\n        em.persist(counter2);\n\n        em.close();\n    }\n\n    private void decrCounter()\n    {\n        EntityManager em = emf.createEntityManager();\n        Counters counter1 = new Counters();\n        counter1.setCounter(-10);\n        counter1.setId(id1);\n        em.persist(counter1);\n\n        Counters counter2 = new Counters();\n        counter2.setCounter(-10);\n        counter2.setId(id2);\n        em.persist(counter2);\n\n        Counters counter3 = new Counters();\n        counter3.setCounter(-10);\n        counter3.setId(id3);\n        em.persist(counter3);\n\n        em.close();\n    }\n\n    public void findCounter()\n    {\n        EntityManager em = emf.createEntityManager();\n        Counters counter1 = new Counters();\n        counter1 = em.find(Counters.class, id1);\n        Assert.assertNotNull(counter1);\n        Assert.assertNotNull(counter1.getCounter());\n        Assert.assertEquals(2, counter1.getCounter());\n\n        Counters counter2 = new Counters();\n        counter2 = em.find(Counters.class, id2);\n        Assert.assertNotNull(counter2);\n        Assert.assertNotNull(counter2.getCounter());\n        Assert.assertEquals(5, counter2.getCounter());\n\n        Counters counter3 = new Counters();\n        counter3 = em.find(Counters.class, id3);\n        Assert.assertNotNull(counter3);\n        Assert.assertNotNull(counter3.getCounter());\n        Assert.assertEquals(8, counter3.getCounter());\n\n        em.close();\n    }\n\n    public void deleteCounter()\n    {\n        EntityManager em = emf.createEntityManager();\n        Counters counters = new Counters();\n        counters = em.find(Counters.class, id3);\n        Assert.assertNotNull(counters);\n        Assert.assertNotNull(counters.getCounter());\n        em.remove(counters);\n\n        EntityManager em1 = emf.createEntityManager();\n        counters = em1.find(Counters.class, id3);\n        Assert.assertNull(counters);\n\n        em.close();\n    }\n\n    public void mergeCounter()\n    {\n        EntityManager em = emf.createEntityManager();\n        Counters counters = new Counters();\n        counters = em.find(Counters.class, id1);\n        Assert.assertNotNull(counters);\n        Assert.assertNotNull(counters.getCounter());\n        try\n        {\n            em.merge(counters);\n        }\n        catch (KunderaException ke)\n        {\n            Assert.assertEquals(\"java.lang.UnsupportedOperationException:  Merge is not permitted on counter column! \",\n                    ke.getMessage());\n        }\n        finally\n        {\n            em.close();\n        }\n    }\n\n    public void selectAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(\"select c from Counters c\");\n        List<Counters> r = q.getResultList();\n        Assert.assertNotNull(r);\n        Assert.assertEquals(3, r.size());\n        int counter = 0;\n        for (Counters counters : r)\n        {\n            if (counters.getId().equals(id1))\n            {\n                counter++;\n                Assert.assertNotNull(counters);\n                Assert.assertNotNull(counters.getCounter());\n                Assert.assertEquals(2, counters.getCounter());\n            }\n            else if (counters.getId().equals(id2))\n            {\n                counter++;\n                Assert.assertNotNull(counters);\n                Assert.assertNotNull(counters.getCounter());\n                Assert.assertEquals(5, counters.getCounter());\n            }\n            else\n            {\n                counter++;\n                Assert.assertNotNull(counters);\n                Assert.assertNotNull(counters.getCounter());\n                Assert.assertEquals(id3, counters.getId());\n                Assert.assertEquals(8, counters.getCounter());\n            }\n\n        }\n        Assert.assertEquals(3, counter);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void rangeQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(\"select c from Counters c where c.id between 12 and 15\");\n        List<Counters> r = q.getResultList();\n        Assert.assertNotNull(r);\n        Assert.assertEquals(2, r.size());\n        int counter = 0;\n        for (Counters counters : r)\n        {\n            if (counters.getId().equals(id1))\n            {\n                counter++;\n                Assert.assertNotNull(counters);\n                Assert.assertNotNull(counters.getCounter());\n                Assert.assertEquals(2, counters.getCounter());\n            }\n            else\n            {\n                counter++;\n                Assert.assertNotNull(counters);\n                Assert.assertNotNull(counters.getCounter());\n                Assert.assertEquals(id2, counters.getId());\n                Assert.assertEquals(5, counters.getCounter());\n            }\n        }\n        Assert.assertEquals(2, counter);\n        em.close();\n    }\n\n    private void queryGTEQOnId()\n    {\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(\"select c from Counters c where c.id >= 15\");\n        List<Counters> r = q.getResultList();\n        Assert.assertNotNull(r);\n        Assert.assertEquals(2, r.size());\n        int counter = 0;\n        for (Counters counters : r)\n        {\n            if (counters.getId().equals(id2))\n            {\n                counter++;\n                Assert.assertNotNull(counters);\n                Assert.assertNotNull(counters.getCounter());\n                Assert.assertEquals(5, counters.getCounter());\n            }\n            else\n            {\n                counter++;\n                Assert.assertNotNull(counters);\n                Assert.assertNotNull(counters.getCounter());\n                Assert.assertEquals(id3, counters.getId());\n                Assert.assertEquals(8, counters.getCounter());\n            }\n\n        }\n        Assert.assertEquals(2, counter);\n        em.close();\n    }\n\n    private void queryLTEQOnId()\n    {\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(\"select c from Counters c where c.id <= 15\");\n        List<Counters> r = q.getResultList();\n        Assert.assertNotNull(r);\n        Assert.assertEquals(2, r.size());\n        int counter = 0;\n        for (Counters counters : r)\n        {\n            if (counters.getId().equals(id1))\n            {\n                counter++;\n                Assert.assertNotNull(counters);\n                Assert.assertNotNull(counters.getCounter());\n                Assert.assertEquals(2, counters.getCounter());\n            }\n            else\n            {\n                counter++;\n                Assert.assertNotNull(counters);\n                Assert.assertNotNull(counters.getCounter());\n                Assert.assertEquals(id2, counters.getId());\n                Assert.assertEquals(5, counters.getCounter());\n            }\n\n        }\n        Assert.assertEquals(2, counter);\n        em.close();\n    }\n\n    private void updateNamedQueryOnCounter()\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update Counters c SET c.counter=23 where c.id=12\";\n        Query q = em.createQuery(updateQuery);\n\n        try\n        {\n            q.executeUpdate();\n        }\n        catch (UnsupportedOperationException uoe)\n        {\n            Assert.assertEquals(\"Invalid operation! Merge is not possible over counter column.\", uoe.getMessage());\n        }\n        finally\n        {\n            em.close();\n        }\n    }\n\n    private void deleteNamedQueryOnCounter()\n    {\n        EntityManager em = emf.createEntityManager();\n        String deleteQuery = \"Delete From Counters c where c.id <= \" + id2;\n\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n\n        Counters counter2 = new Counters();        \n        counter2 = em.find(Counters.class, id1);\n        Assert.assertNull(counter2);\n\n        Counters counter3 = new Counters();\n        counter3 = em.find(Counters.class, id2);\n        Assert.assertNull(counter3);\n\n        em.close();\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/countercolumns/SubCounter.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.countercolumns;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n@Embeddable\npublic class SubCounter\n{\n\n    @Column(name = \"SUB_COUNTER\")\n    private long subCounter;\n\n    @Column(name = \"SUB_COUNTER_NAME\")\n    private transient String subCounter_name;\n\n    /**\n     * @return the subCounter\n     */\n    public long getSubCounter()\n    {\n        return subCounter;\n    }\n\n    /**\n     * @param subCounter\n     *            the subCounter to set\n     */\n    public void setSubCounter(long subCounter)\n    {\n        this.subCounter = subCounter;\n    }\n\n    /**\n     * @return the subCounter_name\n     */\n    public String getSubCounter_name()\n    {\n        return subCounter_name;\n    }\n\n    /**\n     * @param subCounter_name\n     *            the subCounter_name to set\n     */\n    public void setSubCounter_name(String subCounter_name)\n    {\n        this.subCounter_name = subCounter_name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/countercolumns/SuperCounters.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.countercolumns;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"SuperCounters\", schema = \"KunderaCounterColumn@CassandraCounterTest\")\npublic class SuperCounters\n{\n    @Id\n    @Column(name = \"ID\")\n    private String id;\n\n    @Column(name = \"COUNTER\")\n    private int counter;\n\n    @Column(name = \"Long_COUNTER\")\n    private long lCounter;\n\n    @Embedded\n    private SubCounter subCounter;\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the counter\n     */\n    public int getCounter()\n    {\n        return counter;\n    }\n\n    /**\n     * @param counter\n     *            the counter to set\n     */\n    public void setCounter(int counter)\n    {\n        this.counter = counter;\n    }\n\n    /**\n     * @return the subCounter\n     */\n    public SubCounter getSubCounter()\n    {\n        return subCounter;\n    }\n\n    /**\n     * @param subCounter\n     *            the subCounter to set\n     */\n    public void setSubCounter(SubCounter subCounter)\n    {\n        this.subCounter = subCounter;\n    }\n\n    /**\n     * @return the lCounter\n     */\n    public long getlCounter()\n    {\n        return lCounter;\n    }\n\n    /**\n     * @param lCounter\n     *            the lCounter to set\n     */\n    public void setlCounter(long lCounter)\n    {\n        this.lCounter = lCounter;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/countercolumns/SuperCountersTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.countercolumns;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.apache.cassandra.thrift.Cassandra.Client;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author impadmin\n * \n */\npublic class SuperCountersTest\n{\n    private static final String id1 = \"12\";\n\n    private static final String id2 = \"15\";\n\n    private static final String id3 = \"18\";\n\n    private EntityManagerFactory emf;\n\n    private static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    private static final boolean AUTO_MANAGE_SCHEMA = true;\n\n    private String keyspace = \"KunderaCounterColumn\";\n\n    protected Map propertyMap = new HashMap();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startServer();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        if (propertyMap.isEmpty())\n        {\n            propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_2_0);\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        }\n        emf = Persistence.createEntityManagerFactory(\"CassandraCounterTest\");\n    }\n\n    private void createSchema() throws InvalidRequestException, TException, SchemaDisagreementException\n    {\n        Client client = CassandraCli.getClient();\n        CassandraCli.createKeySpace(keyspace);\n        client.set_keyspace(keyspace);\n\n        CfDef cfDef = new CfDef();\n        cfDef.keyspace = keyspace;\n        cfDef.name = \"SuperCounters\";\n        cfDef.column_type = \"Super\";\n        cfDef.default_validation_class = \"CounterColumnType\";\n        cfDef.comparator_type = \"UTF8Type\";\n        cfDef.subcomparator_type = \"UTF8Type\";\n        client.system_add_column_family(cfDef);\n    }\n\n    private void startServer() throws IOException, TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        CassandraCli.cassandraSetUp();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (/* AUTO_MANAGE_SCHEMA && CassandraCli.keyspaceExist(keyspace) */CassandraCli.client != null)\n        {\n            CassandraCli.dropKeySpace(keyspace);\n        }\n    }\n\n    @Test\n    public void testCRUDOnSuperCounter()\n    {\n        incrSuperCounter();\n        findSuperCounter();\n        decrSuperCounter();\n        selectAllQuery();\n        queryGTEQOnId();\n        queryLTEQOnId();\n        rangeQuery();\n        mergeCounter();\n        updateNamedQueryOnCounter();\n        deleteNamedQueryOnCounter();\n        deleteSuperCounter();\n    }\n\n    private void deleteNamedQueryOnCounter()\n    {\n        EntityManager em = emf.createEntityManager();\n        String deleteQuery = \"Delete From SuperCounters c where c.id <= \" + id2;\n\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n\n        em.clear();\n        SuperCounters counter2 = new SuperCounters();\n        counter2 = em.find(SuperCounters.class, id1);\n        Assert.assertNull(counter2);\n\n        SuperCounters counter3 = new SuperCounters();\n        counter3 = em.find(SuperCounters.class, id2);\n        Assert.assertNull(counter3);\n\n        em.close();\n\n    }\n\n    private void updateNamedQueryOnCounter()\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update SuperCounters c SET c.counter=23 where c.id=12\";\n        Query q = em.createQuery(updateQuery);\n\n        try\n        {\n            q.executeUpdate();\n        }\n        catch (UnsupportedOperationException uoe)\n        {\n            Assert.assertEquals(\"Invalid operation! Merge is not possible over counter column.\", uoe.getMessage());\n        }\n        finally\n        {\n            em.close();\n        }\n\n    }\n\n    private void mergeCounter()\n    {\n        EntityManager em = emf.createEntityManager();\n        SuperCounters counter = new SuperCounters();\n        counter = em.find(SuperCounters.class, id1);\n        Assert.assertNotNull(counter);\n        Assert.assertNotNull(counter.getCounter());\n        try\n        {\n            em.merge(counter);\n        }\n        catch (KunderaException ke)\n        {\n            Assert.assertEquals(\"java.lang.UnsupportedOperationException:  Merge is not permitted on counter column! \",\n                    ke.getMessage());\n        }\n        finally\n        {\n            em.close();\n        }\n\n    }\n\n    private void rangeQuery()\n    {\n\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(\"select c from SuperCounters c where c.id between 12 and 15\");\n        List<SuperCounters> r = q.getResultList();\n        Assert.assertNotNull(r);\n        Assert.assertEquals(2, r.size());\n        int count = 0;\n        for (SuperCounters counter : r)\n        {\n            if (id1.equalsIgnoreCase(counter.getId()))\n            {\n                count++;\n                Assert.assertNotNull(counter);\n                Assert.assertNotNull(counter.getCounter());\n                Assert.assertEquals(2, counter.getCounter());\n                Assert.assertEquals(2223, counter.getlCounter());\n                Assert.assertNotNull(counter.getSubCounter());\n                Assert.assertEquals(3, counter.getSubCounter().getSubCounter());\n            }\n            else\n            {\n                count++;\n                Assert.assertNotNull(counter);\n                Assert.assertEquals(id2, counter.getId());\n                Assert.assertNotNull(counter.getCounter());\n                Assert.assertEquals(5, counter.getCounter());\n                Assert.assertEquals(2224, counter.getlCounter());\n                Assert.assertNotNull(counter.getSubCounter());\n                Assert.assertEquals(3, counter.getSubCounter().getSubCounter());\n            }\n        }\n        Assert.assertEquals(2, count);\n    }\n\n    private void queryLTEQOnId()\n    {\n\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(\"select c from SuperCounters c where c.id <= 15\");\n        List<SuperCounters> r = q.getResultList();\n        Assert.assertNotNull(r);\n        Assert.assertEquals(2, r.size());\n        int count = 0;\n        for (SuperCounters counter : r)\n        {\n            if (id1.equalsIgnoreCase(counter.getId()))\n            {\n                count++;\n                Assert.assertNotNull(counter);\n                Assert.assertNotNull(counter.getCounter());\n                Assert.assertEquals(2, counter.getCounter());\n                Assert.assertEquals(2223, counter.getlCounter());\n                Assert.assertNotNull(counter.getSubCounter());\n                Assert.assertEquals(3, counter.getSubCounter().getSubCounter());\n            }\n            else\n            {\n                count++;\n                Assert.assertNotNull(counter);\n                Assert.assertEquals(id2, counter.getId());\n                Assert.assertNotNull(counter.getCounter());\n                Assert.assertEquals(5, counter.getCounter());\n                Assert.assertEquals(2224, counter.getlCounter());\n                Assert.assertNotNull(counter.getSubCounter());\n                Assert.assertEquals(3, counter.getSubCounter().getSubCounter());\n            }\n        }\n        Assert.assertEquals(2, count);\n    }\n\n    private void queryGTEQOnId()\n    {\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(\"select c from SuperCounters c where c.id >= 15\");\n        List<SuperCounters> r = q.getResultList();\n        Assert.assertNotNull(r);\n        Assert.assertEquals(2, r.size());\n        int count = 0;\n        for (SuperCounters counter : r)\n        {\n            if (id2.equalsIgnoreCase(counter.getId()))\n            {\n                count++;\n                Assert.assertNotNull(counter);\n                Assert.assertNotNull(counter.getCounter());\n                Assert.assertEquals(5, counter.getCounter());\n                Assert.assertEquals(2224, counter.getlCounter());\n                Assert.assertNotNull(counter.getSubCounter());\n                Assert.assertEquals(3, counter.getSubCounter().getSubCounter());\n            }\n            else\n            {\n                count++;\n                Assert.assertNotNull(counter);\n                Assert.assertEquals(id3, counter.getId());\n                Assert.assertNotNull(counter.getCounter());\n                Assert.assertEquals(8, counter.getCounter());\n                Assert.assertEquals(2225, counter.getlCounter());\n                Assert.assertNotNull(counter.getSubCounter());\n                Assert.assertEquals(3, counter.getSubCounter().getSubCounter());\n            }\n        }\n        Assert.assertEquals(2, count);\n    }\n\n    private void deleteSuperCounter()\n    {\n        EntityManager em = emf.createEntityManager();\n        SuperCounters counter = new SuperCounters();\n        counter = em.find(SuperCounters.class, id3);\n        Assert.assertNotNull(counter);\n        Assert.assertNotNull(counter.getCounter());\n        Assert.assertNotNull(counter.getSubCounter());\n        Assert.assertEquals(8, counter.getCounter());\n        Assert.assertEquals(2225, counter.getlCounter());\n        Assert.assertEquals(3, counter.getSubCounter().getSubCounter());\n        em.remove(counter);\n\n        EntityManager em1 = emf.createEntityManager();\n        counter = em1.find(SuperCounters.class, id3);\n        Assert.assertNull(counter);\n\n        em.close();\n\n    }\n\n    private void findSuperCounter()\n    {\n\n        EntityManager em = emf.createEntityManager();\n        SuperCounters superCounter = new SuperCounters();\n        superCounter = em.find(SuperCounters.class, id1);\n        Assert.assertNotNull(superCounter);\n        Assert.assertNotNull(superCounter.getCounter());\n        Assert.assertNotNull(superCounter.getSubCounter());\n        Assert.assertEquals(12, superCounter.getCounter());\n        Assert.assertEquals(12223, superCounter.getlCounter());\n        Assert.assertEquals(23, superCounter.getSubCounter().getSubCounter());\n        Assert.assertNull(superCounter.getSubCounter().getSubCounter_name());\n\n        SuperCounters superCounter1 = new SuperCounters();\n        superCounter1 = em.find(SuperCounters.class, id2);\n        Assert.assertNotNull(superCounter1);\n        Assert.assertNotNull(superCounter1.getCounter());\n        Assert.assertNotNull(superCounter1.getSubCounter());\n        Assert.assertEquals(15, superCounter1.getCounter());\n        Assert.assertEquals(12224, superCounter1.getlCounter());\n        Assert.assertEquals(23, superCounter1.getSubCounter().getSubCounter());\n        Assert.assertNull(superCounter1.getSubCounter().getSubCounter_name());\n\n        SuperCounters superCounter2 = new SuperCounters();\n        superCounter2 = em.find(SuperCounters.class, id3);\n        Assert.assertNotNull(superCounter2);\n        Assert.assertNotNull(superCounter2.getCounter());\n        Assert.assertNotNull(superCounter2.getSubCounter());\n        Assert.assertEquals(18, superCounter2.getCounter());\n        Assert.assertEquals(12225, superCounter2.getlCounter());\n        Assert.assertEquals(23, superCounter2.getSubCounter().getSubCounter());\n        Assert.assertNull(superCounter2.getSubCounter().getSubCounter_name());\n\n        em.close();\n    }\n\n    private void incrSuperCounter()\n    {\n\n        EntityManager em = emf.createEntityManager();\n        SuperCounters superCounter = new SuperCounters();\n        superCounter.setCounter(12);\n        superCounter.setId(id1);\n        superCounter.setlCounter(12223);\n        SubCounter subCounter = new SubCounter();\n        subCounter.setSubCounter(23);\n        subCounter.setSubCounter_name(\"First Sub Counter\");\n        superCounter.setSubCounter(subCounter);\n        em.persist(superCounter);\n\n        SuperCounters superCounter1 = new SuperCounters();\n        superCounter1.setCounter(15);\n        superCounter1.setId(id2);\n        superCounter1.setlCounter(12224);\n        SubCounter subCounter1 = new SubCounter();\n        subCounter1.setSubCounter(23);\n        subCounter1.setSubCounter_name(\"Second Sub Counter\");\n        superCounter1.setSubCounter(subCounter1);\n        em.persist(superCounter1);\n\n        SuperCounters superCounter2 = new SuperCounters();\n        superCounter2.setCounter(18);\n        superCounter2.setId(id3);\n        superCounter2.setlCounter(12225);\n        SubCounter subCounter2 = new SubCounter();\n        subCounter2.setSubCounter(23);\n        subCounter2.setSubCounter_name(\"Third Sub Counter\");\n        superCounter2.setSubCounter(subCounter2);\n        em.persist(superCounter2);\n\n        em.close();\n\n    }\n\n    private void decrSuperCounter()\n    {\n        EntityManager em = emf.createEntityManager();\n        SuperCounters superCounter = new SuperCounters();\n        superCounter.setCounter(-10);\n        superCounter.setId(id1);\n        superCounter.setlCounter(-10000);\n        SubCounter subCounter = new SubCounter();\n        subCounter.setSubCounter(-20);\n        superCounter.setSubCounter(subCounter);\n        em.persist(superCounter);\n\n        SuperCounters superCounter1 = new SuperCounters();\n        superCounter1.setCounter(-10);\n        superCounter1.setId(id2);\n        superCounter1.setlCounter(-10000);\n        SubCounter subCounter1 = new SubCounter();\n        subCounter1.setSubCounter(-20);\n        superCounter1.setSubCounter(subCounter1);\n        em.persist(superCounter1);\n\n        SuperCounters superCounter2 = new SuperCounters();\n        superCounter2.setCounter(-10);\n        superCounter2.setId(id3);\n        superCounter2.setlCounter(-10000);\n        SubCounter subCounter2 = new SubCounter();\n        subCounter2.setSubCounter(-20);\n        superCounter2.setSubCounter(subCounter2);\n        em.persist(superCounter2);\n\n        em.close();\n\n    }\n\n    public void selectAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(\"select c from SuperCounters c\");\n        List<SuperCounters> r = q.getResultList();\n        Assert.assertNotNull(r);\n        Assert.assertEquals(3, r.size());\n        int count = 0;\n        for (SuperCounters counter : r)\n        {\n            if (id1.equalsIgnoreCase(counter.getId()))\n            {\n                count++;\n                Assert.assertNotNull(counter);\n                Assert.assertNotNull(counter.getCounter());\n                Assert.assertEquals(2, counter.getCounter());\n                Assert.assertEquals(2223, counter.getlCounter());\n                Assert.assertNotNull(counter.getSubCounter());\n                Assert.assertEquals(3, counter.getSubCounter().getSubCounter());\n            }\n            else if (id2.equalsIgnoreCase(counter.getId()))\n            {\n                count++;\n                Assert.assertNotNull(counter);\n                Assert.assertNotNull(counter.getCounter());\n                Assert.assertEquals(5, counter.getCounter());\n                Assert.assertEquals(2224, counter.getlCounter());\n                Assert.assertNotNull(counter.getSubCounter());\n                Assert.assertEquals(3, counter.getSubCounter().getSubCounter());\n            }\n            else\n            {\n                count++;\n                Assert.assertNotNull(counter);\n                Assert.assertEquals(id3, counter.getId());\n                Assert.assertNotNull(counter.getCounter());\n                Assert.assertEquals(8, counter.getCounter());\n                Assert.assertEquals(2225, counter.getlCounter());\n                Assert.assertNotNull(counter.getSubCounter());\n                Assert.assertEquals(3, counter.getSubCounter().getSubCounter());\n            }\n        }\n        Assert.assertEquals(3, count);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/ByteDataTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes;\n\nimport java.awt.image.BufferedImage;\nimport java.io.BufferedInputStream;\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.imageio.ImageIO;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.commons.codec.binary.Hex;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.crud.BaseTest;\nimport com.impetus.client.crud.PersonCassandra;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Test case to perform simple CRUD operation.(insert, delete, merge, and\n * select)\n * \n * @author chhavi.gangwal\n * \n *         Run this script to create column family in cassandra with indexes.\n *         create column family PERSON with comparator=UTF8Type and\n *         column_metadata=[{column_name: PERSON_NAME, validation_class:\n *         UTF8Type, index_type: KEYS}, {column_name: AGE, validation_class:\n *         IntegerType, index_type: KEYS}];\n * \n */\npublic class ByteDataTest extends BaseTest\n{\n    private static final String SEC_IDX_CASSANDRA_TEST = \"genericCassandraTest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The col. */\n    private Map<Object, Object> col;\n\n    protected Map propertyMap = null;\n\n    protected boolean AUTO_MANAGE_SCHEMA = true;\n\n    protected boolean USE_CQL = false;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n\n        if (propertyMap == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        }\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n\n        emf = Persistence.createEntityManagerFactory(SEC_IDX_CASSANDRA_TEST, propertyMap);\n        em = emf.createEntityManager();\n        col = new java.util.HashMap<Object, Object>();\n    }\n\n    /**\n     * On insert image in cassandra blob object\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onInsertBlobImageCassandra() throws Exception\n    {\n\n        PersonCassandra personWithKey = new PersonCassandra();\n        personWithKey.setPersonId(\"111\");\n\n        BufferedImage originalImage = ImageIO.read(new File(\"src/test/resources/nature.jpg\"));\n        ByteArrayOutputStream baos = new ByteArrayOutputStream();\n        ImageIO.write(originalImage, \"jpg\", baos);\n        baos.flush();\n        byte[] imageInByte = baos.toByteArray();\n\n        baos.close();\n\n        personWithKey.setA(imageInByte);\n        em.persist(personWithKey);\n\n        em.clear();\n\n        String qry = \"Select p from PersonCassandra p where p.personId = 111\";\n        Query q = em.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        PersonCassandra person = persons.get(0);\n\n        InputStream in = new ByteArrayInputStream(person.getA());\n        BufferedImage bImageFromConvert = ImageIO.read(in);\n\n        ImageIO.write(bImageFromConvert, \"jpg\", new File(\"src/test/resources/nature-test.jpg\"));\n\n        Assert.assertNotNull(person.getA());\n        Assert.assertEquals(new File(\"src/test/resources/nature.jpg\").getTotalSpace(), new File(\n                \"src/test/resources/nature-test.jpg\").getTotalSpace());\n        Assert.assertEquals(String.valueOf(Hex.encodeHex((byte[]) imageInByte)),\n                String.valueOf(Hex.encodeHex((byte[]) person.getA())));\n\n    }\n\n    /**\n     * On insert pdf in cassandra blob object\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onInsertBlobPdfCassandra() throws Exception\n    {\n\n        try\n        {\n\n            FileInputStream fileInputStream = null;\n\n            File file = new File(\"src/test/resources/persistence.pdf\");\n\n            byte[] bFile = new byte[(int) file.length()];\n\n            PersonCassandra personWithKey = new PersonCassandra();\n            personWithKey.setPersonId(\"111\");\n            // convert file into array of bytes\n            fileInputStream = new FileInputStream(file);\n            fileInputStream.read(bFile);\n            fileInputStream.close();\n\n            personWithKey.setA(bFile);\n            em.persist(personWithKey);\n            em.clear();\n\n            String qry = \"Select p from PersonCassandra p where p.personId = 111\";\n            Query q = em.createQuery(qry);\n            List<PersonCassandra> persons = q.getResultList();\n            PersonCassandra person = persons.get(0);\n\n            // convert array of bytes into file\n            FileOutputStream fileOuputStream = new FileOutputStream(\"src/test/resources/persistence-test.pdf\");\n            fileOuputStream.write(person.getA());\n            fileOuputStream.close();\n\n            Assert.assertNotNull(person.getA());\n            Assert.assertEquals(new File(\"src/test/resources/persistence.pdf\").getTotalSpace(), new File(\n                    \"src/test/resources/persistence-test.pdf\").getTotalSpace());\n            Assert.assertTrue(isFileBinaryEqual(new File(\"src/test/resources/persistence.pdf\"), new File(\n                    \"src/test/resources/persistence-test.pdf\")));\n            Assert.assertEquals(String.valueOf(Hex.encodeHex((byte[]) bFile)),\n                    String.valueOf(Hex.encodeHex((byte[]) person.getA())));\n\n        }\n        catch (Exception e)\n        {\n\n        }\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {/*\n      * Delete is working, but as row keys are not deleted from cassandra, so\n      * resulting in issue while reading back. // Delete\n      * em.remove(em.find(Person.class, \"1\")); em.remove(em.find(Person.class,\n      * \"2\")); em.remove(em.find(Person.class, \"3\")); em.close(); emf.close();\n      * em = null; emf = null;\n      */\n        em.close();\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    /**\n     * Compare binary files. Both files must be files (not directories) and\n     * exist.\n     * \n     * @param first\n     *            - first file\n     * @param second\n     *            - second file\n     * @return boolean - true if files are binary equal\n     * @throws IOException\n     *             - error in function\n     */\n    private boolean isFileBinaryEqual(File first, File second) throws IOException\n    {\n\n        boolean retval = false;\n\n        if ((first.exists()) && (second.exists()) && (first.isFile()) && (second.isFile()))\n        {\n            if (first.getCanonicalPath().equals(second.getCanonicalPath()))\n            {\n                retval = true;\n            }\n            else\n            {\n                FileInputStream firstInput = new FileInputStream(first);\n                FileInputStream secondInput = new FileInputStream(second);\n                BufferedInputStream bufFirstInput = new BufferedInputStream(firstInput);\n                BufferedInputStream bufSecondInput = new BufferedInputStream(secondInput);\n\n                try\n                {\n\n                    int firstByte;\n                    int secondByte;\n\n                    while (true)\n                    {\n                        firstByte = bufFirstInput.read();\n                        secondByte = bufSecondInput.read();\n                        if (firstByte != secondByte)\n                        {\n                            break;\n                        }\n                        if ((firstByte < 0) && (secondByte < 0))\n                        {\n                            retval = true;\n                            break;\n                        }\n                    }\n                }\n                finally\n                {\n                    try\n                    {\n                        if (bufFirstInput != null)\n                        {\n                            bufFirstInput.close();\n                        }\n                    }\n                    finally\n                    {\n                        if (bufSecondInput != null)\n                        {\n                            bufSecondInput.close();\n                        }\n                    }\n                }\n            }\n        }\n\n        return retval;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/CassandraBase.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.thrift.TException;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.datatypes.datagenerator.DataGenerator;\nimport com.impetus.kundera.datatypes.datagenerator.DataGeneratorFactory;\n\npublic abstract class CassandraBase\n{\n    private static final String _PU = \"CassandraDataTypeTest\";\n\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    public static final boolean AUTO_MANAGE_SCHEMA = false;\n\n    protected EntityManagerFactory emf;\n\n    protected Map propertyMap;\n\n    protected void setUp() throws Exception\n    {\n\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n\n        // just to create schema ones.\n\n        propertyMap = new HashMap();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n\n        if (propertyMap != null && !CassandraCli.isArchived(_PU))\n        {\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        }\n\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n\n        CassandraCli.archivePu(_PU);\n    }\n\n    protected void tearDown() throws Exception\n    {\n        emf.close();\n        dropSchema();\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    DataGenerator<?> dataGenerator;\n\n    DataGeneratorFactory factory = new DataGeneratorFactory();\n\n    protected Object getMaxValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.maxValue();\n    }\n\n    protected Object getMinValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.minValue();\n    }\n\n    protected Object getRandomValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.randomValue();\n    }\n\n    protected Object getPartialValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.partialValue();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n\n        }\n        catch (TException e)\n        {\n\n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    // protected abstract void startCluster();\n    //\n    // protected abstract void stopCluster();\n\n    protected abstract void createSchema();\n\n    protected abstract void dropSchema();\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/CollectionTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud.datatypes;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.crud.datatypes.entities.EntityWithCollection;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.property.accessor.ObjectAccessor;\nimport com.impetus.kundera.property.accessor.UUIDAccessor;\n\n/**\n * @author vivek.mishra\n * junit to test blob type over collection data type(e.g. Map,List and Set)  \n *\n */\npublic class CollectionTest\n{\n\n    private EntityManagerFactory emf;\n    private EntityManager em;\n    \n    \n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        Map<String, String> propertyMap = new HashMap<String, String>();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(\"cassandra_pu\", propertyMap);\n        em = emf.createEntityManager();\n\n    }\n    \n    @Test\n    public void test()\n    {\n        Map<String, byte[]> byteCollection = new HashMap<String, byte[]>();\n        \n        ObjectAccessor accessor = new ObjectAccessor();\n        accessor.toBytes(10);\n        accessor.toBytes(100);\n        \n        byteCollection.put(\"key1\", accessor.toBytes(10));\n        byteCollection.put(\"key2\", accessor.toBytes(11));\n        EntityWithCollection entity = new EntityWithCollection();\n        entity.setId(\"entityId1\");\n        entity.setDataMap(byteCollection);\n        entity.setByteData(accessor.toBytes(100));\n        em.persist(entity); // persist entity.\n        \n        em.clear();\n        EntityWithCollection result = em.find(EntityWithCollection.class, \"entityId1\");\n        Assert.assertNotNull(result);\n        \n        byte[] bytes = result.getDataMap().get(\"key1\");\n        byte[] newdata = result.getByteData();\n        Object value = PropertyAccessorHelper.getObject(Object.class, bytes);\n\n        Assert.assertEquals(10, value);\n        \n        // set list\n        \n        List<byte[]> listAsBytes= new ArrayList<byte[]>();\n        \n        UUID randomId = UUID.randomUUID();\n        listAsBytes.add(\"Vivek\".getBytes());\n        listAsBytes.add(new UUIDAccessor().toBytes(randomId));\n        \n        result.setListAsBytes(listAsBytes);\n        em.merge(result); // merge with list as bytes.\n        \n        em.clear();  // clear from cache.\n        \n        result = em.find(EntityWithCollection.class, \"entityId1\");\n        Assert.assertNotNull(result);\n        assertOnList(result, randomId);        \n        \n        Set<byte[]> setAsBytes = new HashSet<byte[]>();\n        setAsBytes.add(\"Vivek\".getBytes());\n        setAsBytes.add(new UUIDAccessor().toBytes(randomId));\n        result.setSetAsBytes(setAsBytes);\n        em.merge(result); // merge with list as bytes.\n        \n        em.clear();\n        result = em.find(EntityWithCollection.class, \"entityId1\");\n        Assert.assertNotNull(result);\n        assertOnList(result, randomId);\n        \n        Set<byte[]> resultAsBytes = result.getSetAsBytes();\n        \n     // on set type.\n        for(byte[] recInBytes : resultAsBytes)\n        {\n            assertBytes(randomId, recInBytes);\n        }\n        // on set type.\n    }\n\n    @After\n    public void tearDown()\n    {\n        CassandraCli.dropKeySpace(\"KunderaTests\");\n        if(em != null)\n        {\n            em.close();\n        }\n        \n        if(emf != null)\n        {\n            emf.close();\n        }\n        \n        \n    }\n    private void assertOnList(EntityWithCollection result, UUID randomId)\n    {\n        List<byte[]> lst = result.getListAsBytes();\n        Assert.assertFalse(lst.isEmpty());\n        Assert.assertEquals(2, lst.size());\n\n        for (byte[] recInBytes : lst)\n        {\n            assertBytes(randomId, recInBytes);\n        }\n    }\n\n    private void assertBytes(UUID randomId, byte[] recInBytes)\n    {\n        try\n        {\n            String str = (String) PropertyAccessorHelper.getObject(String.class, recInBytes);\n            \n            if(!str.equals(\"Vivek\")) // string record is already compared\n            {\n                UUIDAccessor uuidAccessor = new UUIDAccessor();\n                UUID recAsUUID = uuidAccessor.fromBytes(UUID.class, recInBytes);\n                Assert.assertEquals(randomId, recAsUUID);\n                \n            } \n        }\n        catch (Exception e)\n        {\n            Assert.fail();\n        }\n    }\n    \n    \n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/EntityWithUnicode.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */package com.impetus.client.crud.datatypes;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n/**\n * @author vivek.mishra\n * Entity with unicode characters\n */\n@Entity\npublic class EntityWithUnicode\n{\n\n    @Id\n    private UUID id;\n    \n    @Column\n    private String desc;\n\n    public EntityWithUnicode()\n    {\n        \n    }\n    \n    public UUID getId()\n    {\n        return id;\n    }\n\n    public void setId(UUID id)\n    {\n        this.id = id;\n    }\n\n    public String getDesc()\n    {\n        return desc;\n    }\n\n    public void setDesc(String desc)\n    {\n        this.desc = desc;\n    }\n    \n    \n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/EntityWithUnicodeTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud.datatypes;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author vivek.mishra\n * junit for unicode character test. \n */\npublic class EntityWithUnicodeTest\n{\n\n    private EntityManagerFactory emf;\n    private EntityManager em;\n\n    \n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        Map<String, String> propertyMap = new HashMap<String, String>();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(\"cassandra_pu\", propertyMap);\n        em = emf.createEntityManager();\n\n    }\n\n    @Test\n    public void test()\n    {\n        String uniCode = \"中文\";\n        UUID id = UUID.randomUUID();\n        EntityWithUnicode entity = new EntityWithUnicode();\n        entity.setDesc(uniCode);\n        entity.setId(id);\n        em.persist(entity);\n\n        em.clear(); // clear persistence cache.\n        EntityWithUnicode result = em.find(EntityWithUnicode.class, id);\n        Assert.assertEquals(uniCode,result.getDesc());\n        \n    }\n\n    @After\n    public void tearDown()\n    {\n        CassandraCli.dropKeySpace(\"KunderaTests\");\n        if(em != null)\n        {\n            em.close();\n        }\n        \n        if(emf != null)\n        {\n            emf.close();\n        }\n        \n        \n    }\n\n    \n    \n    \n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandra.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"STUDENT\", schema = \"KunderaExamples@secIdxCassandraTest\")\n@IndexCollection(columns = { @Index(name = \"uniqueId\"), @Index(name = \"studentName\"), @Index(name = \"isExceptional\"),\n        @Index(name = \"age\"), @Index(name = \"semester\"), @Index(name = \"digitalSignature\"), @Index(name = \"cgpa\"),\n        @Index(name = \"percentage\"), @Index(name = \"height\"), @Index(name = \"enrolmentDate\"),\n        @Index(name = \"enrolmentTime\"), @Index(name = \"joiningDateAndTime\"), @Index(name = \"yearsSpent\"),\n        @Index(name = \"rollNumber\"), @Index(name = \"monthlyFee\"), @Index(name = \"sqlDate\"),\n        @Index(name = \"sqlTimestamp\"), @Index(name = \"sqlTime\"), @Index(name = \"bigInteger\"),\n        @Index(name = \"bigDecimal\"), @Index(name = \"calendar\") })\npublic class StudentCassandra implements StudentEntityDef\n{\n    // Primitive Types\n    @Id\n    @Column(name = \"STUDENT_ID\")\n    private long studentId;\n\n    @Column(name = \"UNIQUE_ID\")\n    private long uniqueId;\n\n    @Column(name = \"STUDENT_NAME\")\n    private String studentName;\n\n    @Column(name = \"IS_EXCEPTIONAL\")\n    private boolean isExceptional;\n\n    @Column(name = \"AGE\")\n    private int age;\n\n    @Column(name = \"SEMESTER\")\n    private char semester; // A,B,C,D,E,F for i to vi\n\n    @Column(name = \"DIGITAL_SIGNATURE\")\n    private byte digitalSignature;\n\n    @Column(name = \"CGPA\")\n    private short cgpa; // 1-10\n\n    @Column(name = \"PERCENTAGE\")\n    private float percentage;\n\n    @Column(name = \"HEIGHT\")\n    private double height;\n\n    // Date-time types\n    @Column(name = \"ENROLMENT_DATE\")\n    @Temporal(TemporalType.DATE)\n    private java.util.Date enrolmentDate;\n\n    @Column(name = \"ENROLMENT_TIME\")\n    @Temporal(TemporalType.TIME)\n    private java.util.Date enrolmentTime;\n\n    @Column(name = \"JOINING_DATE_TIME\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private java.util.Date joiningDateAndTime;\n\n    // Wrapper types\n\n    @Column(name = \"YEARS_SPENT\")\n    private Integer yearsSpent;\n\n    @Column(name = \"ROLL_NUMBER\")\n    private Long rollNumber;\n\n    @Column(name = \"MONTHLY_FEE\")\n    private Double monthlyFee;\n\n    @Column(name = \"SQL_DATE\")\n    private java.sql.Date sqlDate;\n\n    @Column(name = \"SQL_TIMESTAMP\")\n    private java.sql.Timestamp sqlTimestamp;\n\n    @Column(name = \"SQL_TIME\")\n    private java.sql.Time sqlTime;\n\n    @Column(name = \"BIG_INT\")\n    private BigInteger bigInteger;\n\n    @Column(name = \"BIG_DECIMAL\")\n    private BigDecimal bigDecimal;\n\n    @Column(name = \"CALENDAR\")\n    private Calendar calendar;\n\n    /**\n     * @return the studentId\n     */\n    public long getStudentId()\n    {\n        return studentId;\n    }\n\n    /**\n     * @param studentId\n     *            the studentId to set\n     */\n    public void setStudentId(long studentId)\n    {\n        this.studentId = studentId;\n    }\n\n    /**\n     * @return the uniqueId\n     */\n    public long getUniqueId()\n    {\n        return uniqueId;\n    }\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    public void setUniqueId(long uniqueId)\n    {\n        this.uniqueId = uniqueId;\n    }\n\n    /**\n     * @return the studentName\n     */\n    public String getStudentName()\n    {\n        return studentName;\n    }\n\n    /**\n     * @param studentName\n     *            the studentName to set\n     */\n    public void setStudentName(String studentName)\n    {\n        this.studentName = studentName;\n    }\n\n    /**\n     * @return the isExceptional\n     */\n    public boolean isExceptional()\n    {\n        return isExceptional;\n    }\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    public void setExceptional(boolean isExceptional)\n    {\n        this.isExceptional = isExceptional;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the semester\n     */\n    public char getSemester()\n    {\n        return semester;\n    }\n\n    /**\n     * @param semester\n     *            the semester to set\n     */\n    public void setSemester(char semester)\n    {\n        this.semester = semester;\n    }\n\n    /**\n     * @return the digitalSignature\n     */\n    public byte getDigitalSignature()\n    {\n        return digitalSignature;\n    }\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    public void setDigitalSignature(byte digitalSignature)\n    {\n        this.digitalSignature = digitalSignature;\n    }\n\n    /**\n     * @return the cgpa\n     */\n    public short getCgpa()\n    {\n        return cgpa;\n    }\n\n    /**\n     * @param cgpa\n     *            the cgpa to set\n     */\n    public void setCgpa(short cgpa)\n    {\n        this.cgpa = cgpa;\n    }\n\n    /**\n     * @return the percentage\n     */\n    public float getPercentage()\n    {\n        return percentage;\n    }\n\n    /**\n     * @param percentage\n     *            the percentage to set\n     */\n    public void setPercentage(float percentage)\n    {\n        this.percentage = percentage;\n    }\n\n    /**\n     * @return the height\n     */\n    public double getHeight()\n    {\n        return height;\n    }\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    public void setHeight(double height)\n    {\n        this.height = height;\n    }\n\n    /**\n     * @return the enrolmentDate\n     */\n    public java.util.Date getEnrolmentDate()\n    {\n        return enrolmentDate;\n    }\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    public void setEnrolmentDate(java.util.Date enrolmentDate)\n    {\n        this.enrolmentDate = enrolmentDate;\n    }\n\n    /**\n     * @return the enrolmentTime\n     */\n    public java.util.Date getEnrolmentTime()\n    {\n        return enrolmentTime;\n    }\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    public void setEnrolmentTime(java.util.Date enrolmentTime)\n    {\n        this.enrolmentTime = enrolmentTime;\n    }\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    public java.util.Date getJoiningDateAndTime()\n    {\n        return joiningDateAndTime;\n    }\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    public void setJoiningDateAndTime(java.util.Date joiningDateAndTime)\n    {\n        this.joiningDateAndTime = joiningDateAndTime;\n    }\n\n    /**\n     * @return the yearsSpent\n     */\n    public Integer getYearsSpent()\n    {\n        return yearsSpent;\n    }\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    public void setYearsSpent(Integer yearsSpent)\n    {\n        this.yearsSpent = yearsSpent;\n    }\n\n    /**\n     * @return the rollNumber\n     */\n    public Long getRollNumber()\n    {\n        return rollNumber;\n    }\n\n    /**\n     * @param rollNumber\n     *            the rollNumber to set\n     */\n    public void setRollNumber(Long rollNumber)\n    {\n        this.rollNumber = rollNumber;\n    }\n\n    /**\n     * @return the monthlyFee\n     */\n    public Double getMonthlyFee()\n    {\n        return monthlyFee;\n    }\n\n    /**\n     * @param monthlyFee\n     *            the monthlyFee to set\n     */\n    public void setMonthlyFee(Double monthlyFee)\n    {\n        this.monthlyFee = monthlyFee;\n    }\n\n    public java.sql.Date getSqlDate()\n    {\n        return sqlDate;\n    }\n\n    public void setSqlDate(java.sql.Date sqlDate)\n    {\n        this.sqlDate = sqlDate;\n    }\n\n    /**\n     * @return the sqlTimestamp\n     */\n    public java.sql.Timestamp getSqlTimestamp()\n    {\n        return sqlTimestamp;\n    }\n\n    /**\n     * @param sqlTimestamp\n     *            the sqlTimestamp to set\n     */\n    public void setSqlTimestamp(java.sql.Timestamp sqlTimestamp)\n    {\n        this.sqlTimestamp = sqlTimestamp;\n    }\n\n    /**\n     * @return the sqlTime\n     */\n    public java.sql.Time getSqlTime()\n    {\n        return sqlTime;\n    }\n\n    /**\n     * @param sqlTime\n     *            the sqlTime to set\n     */\n    public void setSqlTime(java.sql.Time sqlTime)\n    {\n        this.sqlTime = sqlTime;\n    }\n\n    /**\n     * @return the bigInteger\n     */\n    public BigInteger getBigInteger()\n    {\n        return bigInteger;\n    }\n\n    /**\n     * @param bigInteger\n     *            the bigInteger to set\n     */\n    public void setBigInteger(BigInteger bigInteger)\n    {\n        this.bigInteger = bigInteger;\n    }\n\n    /**\n     * @return the bigDecimal\n     */\n    public BigDecimal getBigDecimal()\n    {\n        return bigDecimal;\n    }\n\n    /**\n     * @param bigDecimal\n     *            the bigDecimal to set\n     */\n    public void setBigDecimal(BigDecimal bigDecimal)\n    {\n        this.bigDecimal = bigDecimal;\n    }\n\n    /**\n     * @return the calendar\n     */\n    public Calendar getCalendar()\n    {\n        return calendar;\n    }\n\n    /**\n     * @param calendar\n     *            the calendar to set\n     */\n    public void setCalendar(Calendar calendar)\n    {\n        this.calendar = calendar;\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport com.impetus.client.crud.BaseTest;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * The Class StudentBase.\n * \n * @param <E>\n *            the element type\n */\npublic abstract class StudentCassandraBase<E extends StudentEntityDef> extends BaseTest\n{\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    public boolean AUTO_MANAGE_SCHEMA = false;\n\n    /** The emf. */\n    protected EntityManagerFactory emf;\n\n    /** The em. */\n    protected EntityManager em;\n\n    // protected String persistenceUnit =\n    // /*\"twissandra,twibase,twingo,picmysql\"*/null;\n\n    /** The student id1. */\n    protected long studentId1;\n\n    /** The student id2. */\n    protected long studentId2;\n\n    /** The student id3. */\n    protected long studentId3;\n\n    /** The enrolment date. */\n    protected Date enrolmentDate = new Date(Long.parseLong(\"1344079065781\"));\n\n    /** The joining date and time. */\n    protected Date joiningDateAndTime = new Date();\n\n    /** The date. */\n    protected long date = new Date().getTime();\n\n    /** The new sql date. */\n    protected java.sql.Date newSqlDate = new java.sql.Date(date);\n\n    /** The enrolment time. */\n    protected Date enrolmentTime = new Date();\n\n    /** The sql time. */\n    protected java.sql.Time sqlTime = new java.sql.Time(date);\n\n    /** The sql timestamp. */\n    protected java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(date);\n\n    /** The big decimal. */\n    protected BigDecimal bigDecimal = new BigDecimal(123456789.2345678);\n\n    /** The big integer. */\n    protected BigInteger bigInteger = new BigInteger(\"123456789\");\n\n    /** The number of students. */\n    protected int numberOfStudents = 1000;\n\n    /** The calendar. */\n    protected Calendar calendar = Calendar.getInstance();\n\n    /** The dao. */\n    // StudentDao dao;\n\n    /**\n     * Sets the up internal.\n     * \n     * @param persisntenceUnit\n     *            the new up internal\n     * @param CLQ_ENABLED\n     */\n    protected void setupInternal(String persisntenceUnit, Map propertyMap, boolean CLQ_ENABLED)\n    {\n        // dao = new StudentDao(persistenceUnit);\n\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startServer();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema(CLQ_ENABLED);\n        }\n        else\n        {\n            CassandraCli.createKeySpace(\"KunderaExamples\");\n        }\n\n        studentId1 = new Long(12345677);\n        studentId2 = new Long(12345678);\n        studentId3 = new Long(12345679);\n\n        emf = Persistence.createEntityManagerFactory(persisntenceUnit, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Sets the up internal.\n     * \n     * @param persistenceUnit\n     *            the new up internal\n     */\n    protected void teardownInternal(String persistenceUnit)\n    {\n\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopServer();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n        }\n        deleteSchema();\n\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n    /**\n     * on insert.\n     * \n     * @param instance\n     *            the instance\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    protected void onInsert(E instance) throws InstantiationException, IllegalAccessException\n    {\n\n        em.persist(prepareData((Long) studentId1, 78575785897L, \"Amresh\", false, 10, 'A', (byte) 5, (short) 8,\n                (float) 69.3, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar,\n                ((E) instance.getClass().newInstance())));\n\n        em.persist(prepareData((Long) studentId2, 78575785898L, \"Amresh\", true, 20, 'B', (byte) 50, (short) 8,\n                (float) 69.2, 163.86765654, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, new BigInteger(\n                        \"123456788\"), calendar, ((E) instance.getClass().newInstance())));\n\n        em.persist(prepareData((Long) studentId3, 78575785899L, \"Amresh\", true, 15, 'C', (byte) 50, (short) 8,\n                (float) 61.6, 163.96765654, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, new BigInteger(\n                        \"123456787\"), calendar, ((E) instance.getClass().newInstance())));\n\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param studentId\n     *            the student id\n     * @param uniqueId\n     *            the unique id\n     * @param studentName\n     *            the student name\n     * @param isExceptional\n     *            the is exceptional\n     * @param age\n     *            the age\n     * @param semester\n     *            the semester\n     * @param digitalSignature\n     *            the digital signature\n     * @param cgpa\n     *            the cgpa\n     * @param percentage\n     *            the percentage\n     * @param height\n     *            the height\n     * @param enrolmentDate\n     *            the enrolment date\n     * @param enrolmentTime\n     *            the enrolment time\n     * @param joiningDateAndTime\n     *            the joining date and time\n     * @param yearsSpent\n     *            the years spent\n     * @param rollNumber\n     *            the roll number\n     * @param monthlyFee\n     *            the monthly fee\n     * @param newSqlDate\n     *            the new sql date\n     * @param sqlTime\n     *            the sql time\n     * @param sqlTimestamp\n     *            the sql timestamp\n     * @param bigDecimal\n     *            the big decimal\n     * @param bigInteger\n     *            the big integer\n     * @param calendar\n     *            the calendar\n     * @param o\n     *            the o\n     * @return the person\n     */\n    protected E prepareData(long studentId, long uniqueId, String studentName, boolean isExceptional, int age,\n            char semester, byte digitalSignature, short cgpa, float percentage, double height,\n            java.util.Date enrolmentDate, java.util.Date enrolmentTime, java.util.Date joiningDateAndTime,\n            Integer yearsSpent, Long rollNumber, Double monthlyFee, java.sql.Date newSqlDate, java.sql.Time sqlTime,\n            java.sql.Timestamp sqlTimestamp, BigDecimal bigDecimal, BigInteger bigInteger, Calendar calendar, E o)\n    {\n        o.setStudentId((Long) studentId);\n        o.setUniqueId(uniqueId);\n        o.setStudentName(studentName);\n        o.setExceptional(isExceptional);\n        o.setAge(age);\n        o.setSemester(semester);\n        o.setDigitalSignature(digitalSignature);\n        o.setCgpa(cgpa);\n        o.setPercentage(percentage);\n        o.setHeight(height);\n\n        o.setEnrolmentDate(enrolmentDate);\n        o.setEnrolmentTime(enrolmentTime);\n        o.setJoiningDateAndTime(joiningDateAndTime);\n\n        o.setYearsSpent(yearsSpent);\n        o.setRollNumber(rollNumber);\n        o.setMonthlyFee(monthlyFee);\n        o.setSqlDate(newSqlDate);\n        o.setSqlTime(sqlTime);\n        o.setSqlTimestamp(sqlTimestamp);\n        o.setBigDecimal(bigDecimal);\n        o.setBigInteger(bigInteger);\n        o.setCalendar(calendar);\n        return (E) o;\n    }\n\n    /**\n     * Assert on data types.\n     * \n     * @param s\n     *            the s\n     */\n    protected void assertOnDataTypes(E s)\n    {\n\n        Assert.assertNotNull(s);\n        Assert.assertEquals(((Long) studentId1).longValue(), s.getStudentId());\n        Assert.assertEquals(78575785897L, s.getUniqueId());\n        Assert.assertEquals(\"Amresh\", s.getStudentName());\n        Assert.assertEquals(false, s.isExceptional());\n        Assert.assertEquals(10, s.getAge());\n        Assert.assertEquals('A', s.getSemester());\n        Assert.assertEquals((byte) 5, s.getDigitalSignature());\n        Assert.assertEquals((short) 8, s.getCgpa());\n        Assert.assertEquals((float) 69.3, s.getPercentage());\n        Assert.assertEquals(163.76765654, s.getHeight());\n\n        Assert.assertEquals(enrolmentDate.getDate(), s.getEnrolmentDate().getDate());\n        Assert.assertEquals(enrolmentDate.getMonth(), s.getEnrolmentDate().getMonth());\n        Assert.assertEquals(enrolmentDate.getYear(), s.getEnrolmentDate().getYear());\n\n        Assert.assertEquals(enrolmentTime.getHours(), s.getEnrolmentTime().getHours());\n        Assert.assertEquals(enrolmentTime.getMinutes(), s.getEnrolmentTime().getMinutes());\n        Assert.assertEquals(enrolmentTime.getSeconds(), s.getEnrolmentTime().getSeconds());\n\n        Assert.assertEquals(joiningDateAndTime.getDate(), s.getJoiningDateAndTime().getDate());\n        Assert.assertEquals(joiningDateAndTime.getMonth(), s.getJoiningDateAndTime().getMonth());\n        Assert.assertEquals(joiningDateAndTime.getYear(), s.getJoiningDateAndTime().getYear());\n        Assert.assertEquals(joiningDateAndTime.getHours(), s.getJoiningDateAndTime().getHours());\n        Assert.assertEquals(joiningDateAndTime.getMinutes(), s.getJoiningDateAndTime().getMinutes());\n        Assert.assertEquals(joiningDateAndTime.getSeconds(), s.getJoiningDateAndTime().getSeconds());\n\n        Assert.assertEquals(newSqlDate.getDate(), s.getSqlDate().getDate());\n        Assert.assertEquals(newSqlDate.getMonth(), s.getSqlDate().getMonth());\n        Assert.assertEquals(newSqlDate.getYear(), s.getSqlDate().getYear());\n\n        Assert.assertEquals(sqlTime.getMinutes(), s.getSqlTime().getMinutes());\n        Assert.assertEquals(sqlTime.getSeconds(), s.getSqlTime().getSeconds());\n        Assert.assertEquals(sqlTime.getHours(), s.getSqlTime().getHours());\n\n        Assert.assertEquals(sqlTimestamp.getDate(), s.getSqlTimestamp().getDate());\n        Assert.assertEquals(sqlTimestamp.getMonth(), s.getSqlTimestamp().getMonth());\n        Assert.assertEquals(sqlTimestamp.getYear(), s.getSqlTimestamp().getYear());\n        Assert.assertEquals(sqlTimestamp.getHours(), s.getSqlTimestamp().getHours());\n        Assert.assertEquals(sqlTimestamp.getMinutes(), s.getSqlTimestamp().getMinutes());\n        Assert.assertEquals(sqlTimestamp.getSeconds(), s.getSqlTimestamp().getSeconds());\n\n        Assert.assertEquals(bigDecimal,s.getBigDecimal());\n        Assert.assertEquals(bigInteger, s.getBigInteger());\n\n        Assert.assertEquals(calendar.get(Calendar.YEAR), s.getCalendar().get(Calendar.YEAR));\n        Assert.assertEquals(calendar.get(Calendar.MONTH), s.getCalendar().get(Calendar.MONTH));\n        Assert.assertEquals(calendar.get(Calendar.WEEK_OF_YEAR), s.getCalendar().get(Calendar.WEEK_OF_YEAR));\n        Assert.assertEquals(calendar.get(Calendar.WEEK_OF_MONTH), s.getCalendar().get(Calendar.WEEK_OF_MONTH));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_MONTH), s.getCalendar().get(Calendar.DAY_OF_MONTH));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_WEEK), s.getCalendar().get(Calendar.DAY_OF_WEEK));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH),\n                s.getCalendar().get(Calendar.DAY_OF_WEEK_IN_MONTH));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_YEAR), s.getCalendar().get(Calendar.DAY_OF_YEAR));\n        Assert.assertEquals(calendar.get(Calendar.HOUR), s.getCalendar().get(Calendar.HOUR));\n        Assert.assertEquals(calendar.get(Calendar.HOUR_OF_DAY), s.getCalendar().get(Calendar.HOUR_OF_DAY));\n        Assert.assertEquals(calendar.get(Calendar.AM), s.getCalendar().get(Calendar.AM));\n        Assert.assertEquals(calendar.get(Calendar.PM), s.getCalendar().get(Calendar.PM));\n        Assert.assertEquals(calendar.get(Calendar.AM_PM), s.getCalendar().get(Calendar.AM_PM));\n\n        Assert.assertEquals(new Integer(3), s.getYearsSpent());\n        Assert.assertEquals(new Long(978423946455l), s.getRollNumber());\n        Assert.assertEquals(new Double(135434.89), s.getMonthlyFee());\n\n    }\n\n    abstract void startServer();\n\n    abstract void stopServer();\n\n    abstract void createSchema(boolean cLQ_ENABLED2);\n\n    abstract void deleteSchema();\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraBigDecimalTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.crud.datatypes.entities.StudentBigDecimal;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraBigDecimalTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        propertyMap = new HashMap();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_2_0);\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of BigDecimal\n        StudentBigDecimal studentMax = new StudentBigDecimal();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setStudentId((BigDecimal) getMaxValue(BigDecimal.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of BigDecimal\n        StudentBigDecimal studentMin = new StudentBigDecimal();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setStudentId((BigDecimal) getMinValue(BigDecimal.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of BigDecimal\n        StudentBigDecimal student = new StudentBigDecimal();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setStudentId((BigDecimal) getRandomValue(BigDecimal.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBigDecimal studentMax = em\n                .find(StudentBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigDecimal studentMin = em\n                .find(StudentBigDecimal.class, getMinValue(BigDecimal.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigDecimal student = em\n                .find(StudentBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentBigDecimal student = em.find(StudentBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigDecimal newStudent = em\n                .find(StudentBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            Assert.assertEquals(getMinValue(BigDecimal.class), student.getStudentId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(BigDecimal.class));\n        q.setParameter(2, getMaxValue(BigDecimal.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            if (student.getStudentId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getStudentId().equals(getMinValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigDecimal.class), student.getStudentId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigDecimal.class), student.getStudentId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBigDecimal studentMax = em\n                .find(StudentBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentBigDecimal s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigDecimal newStudent = em.find(StudentBigDecimal.class,\n                getRandomValue(BigDecimal.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentBigDecimal s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigDecimal newStudent = em.find(StudentBigDecimal.class,\n                getRandomValue(BigDecimal.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getStudentId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getStudentId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            if (student.getStudentId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigDecimal.class), student.getStudentId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getStudentId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            if (student.getStudentId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigDecimal.class), student.getStudentId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentBigDecimal s \";\n        Query q = em.createQuery(query);\n        List<StudentBigDecimal> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            if (student.getStudentId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getStudentId().equals(getMinValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(BigDecimal.class), student.getStudentId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentBigDecimal\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"DecimalType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"IntegerType\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentBigDecimal\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentBigDecimal\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentBigDecimal\\\"\", keyspace);\n//        CassandraCli.dropKeySpace(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraBigIntegerTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentBigInteger;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraBigIntegerTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of BigInteger\n        StudentBigInteger studentMax = new StudentBigInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((BigInteger) getMaxValue(BigInteger.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of BigInteger\n        StudentBigInteger studentMin = new StudentBigInteger();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((BigInteger) getMinValue(BigInteger.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of BigInteger\n        StudentBigInteger student = new StudentBigInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((BigInteger) getRandomValue(BigInteger.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBigInteger studentMax = em\n                .find(StudentBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigInteger studentMin = em\n                .find(StudentBigInteger.class, getMinValue(BigInteger.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigInteger student = em\n                .find(StudentBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentBigInteger student = em.find(StudentBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigInteger newStudent = em\n                .find(StudentBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(BigInteger.class));\n        q.setParameter(2, getMaxValue(BigInteger.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBigInteger studentMax = em\n                .find(StudentBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentBigInteger s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigInteger newStudent = em.find(StudentBigInteger.class,\n                getRandomValue(BigInteger.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentBigInteger s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigInteger newStudent = em.find(StudentBigInteger.class,\n                getRandomValue(BigInteger.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentBigInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentBigInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentBigInteger\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"IntegerType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentBigInteger\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentBigInteger\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an BigInteger\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentBigInteger\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraBooleanPrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentBooleanPrimitive;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class StudentCassandraBooleanPrimitiveTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of boolean\n        StudentBooleanPrimitive studentMax = new StudentBooleanPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Boolean) getMaxValue(boolean.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of boolean\n        StudentBooleanPrimitive studentMin = new StudentBooleanPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Boolean) getMinValue(boolean.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBooleanPrimitive studentMax = em.find(StudentBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanPrimitive studentMin = em.find(StudentBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentBooleanPrimitive student = em.find(StudentBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanPrimitive newStudent = em.find(StudentBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(boolean.class));\n        q.setParameter(2, getMaxValue(boolean.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.name = Kuldeep or s.age > \" + getMinValue(short.class);\n        try\n        {\n            q = em.createQuery(query);\n            students = q.getResultList();\n            Assert.assertNotNull(students);\n            Assert.assertEquals(1, students.size());\n            count = 0;\n            for (StudentBooleanPrimitive student : students)\n            {\n                Assert.assertEquals(getMaxValue(boolean.class), student.getId());\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n            em.close();\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertEquals(\"unsupported clause OR for cassandra\", qhe.getMessage());\n        }\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(boolean.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBooleanPrimitive studentMax = em.find(StudentBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMinValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentBooleanPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanPrimitive newStudent = em.find(StudentBooleanPrimitive.class, getRandomValue(boolean.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentBooleanPrimitive s SET s.name=Vivek where s.id=true\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanPrimitive newStudent = em.find(StudentBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.name = Kuldeep and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.age = \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentBooleanPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentBooleanPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentBooleanPrimitive\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"BooleanType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentBooleanPrimitive\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentBooleanPrimitive\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentBooleanPrimitive\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraBooleanWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentBooleanWrapper;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class StudentCassandraBooleanWrapperTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Boolean\n        StudentBooleanWrapper studentMax = new StudentBooleanWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Boolean) getMaxValue(Boolean.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Boolean\n        StudentBooleanWrapper studentMin = new StudentBooleanWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Boolean) getMinValue(Boolean.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBooleanWrapper studentMax = em.find(StudentBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanWrapper studentMin = em.find(StudentBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        em.close();\n    }\n\n    public void testMerge(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentBooleanWrapper student = em.find(StudentBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanWrapper newStudent = em.find(StudentBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(Boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Boolean.class));\n        q.setParameter(2, getMaxValue(Boolean.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.name = Kuldeep or s.age > \" + getMinValue(short.class);\n        try\n        {\n            q = em.createQuery(query);\n            students = q.getResultList();\n            Assert.assertNotNull(students);\n            Assert.assertEquals(1, students.size());\n            count = 0;\n            for (StudentBooleanWrapper student : students)\n            {\n                Assert.assertEquals(getMaxValue(Boolean.class), student.getId());\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n            em.close();\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertEquals(\"unsupported clause OR for cassandra\", qhe.getMessage());\n        }\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(Boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(Boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBooleanWrapper studentMax = em.find(StudentBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMinValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(Boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentBooleanWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanWrapper newStudent = em.find(StudentBooleanWrapper.class, getRandomValue(Boolean.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentBooleanWrapper s SET s.name=Vivek where s.id=true\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanWrapper newStudent = em.find(StudentBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.name = Kuldeep and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(Boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(Boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.age = \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentBooleanWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentBooleanWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentBooleanWrapper\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"BooleanType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentBooleanWrapper\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentBooleanWrapper\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentBooleanWrapper\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraBytePrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentBytePrimitive;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraBytePrimitiveTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of byte\n        StudentBytePrimitive studentMax = new StudentBytePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of byte\n        StudentBytePrimitive studentMin = new StudentBytePrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Byte) getMinValue(byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of byte\n        StudentBytePrimitive student = new StudentBytePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBytePrimitive studentMax = em.find(StudentBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBytePrimitive studentMin = em.find(StudentBytePrimitive.class, getMinValue(byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBytePrimitive student = em.find(StudentBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentBytePrimitive student = em.find(StudentBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBytePrimitive newStudent = em.find(StudentBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(byte.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(byte.class));\n        q.setParameter(2, getMaxValue(byte.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Byte) getMinValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBytePrimitive studentMax = em.find(StudentBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentBytePrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBytePrimitive newStudent = em.find(StudentBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentBytePrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBytePrimitive newStudent = em.find(StudentBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentBytePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentBytePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Byte) getMinValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentBytePrimitive\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"Int32Type\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentBytePrimitive\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentBytePrimitive\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentBytePrimitive\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraByteWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentByteWrapper;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraByteWrapperTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Byte\n        StudentByteWrapper studentMax = new StudentByteWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(Byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Byte\n        StudentByteWrapper studentMin = new StudentByteWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Byte) getMinValue(Byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Byte\n        StudentByteWrapper student = new StudentByteWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(Byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentByteWrapper studentMax = em.find(StudentByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentByteWrapper studentMin = em.find(StudentByteWrapper.class, getMinValue(Byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentByteWrapper student = em.find(StudentByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentByteWrapper student = em.find(StudentByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentByteWrapper newStudent = em.find(StudentByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Byte.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.id between \" + getMinValue(Byte.class) + \" and \"\n                + getMaxValue(Byte.class);\n        // query =\n        // \"Select s From StudentByteWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        // q.setParameter(1, getMinValue(Byte.class));\n        // q.setParameter(2, getMaxValue(Byte.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Byte.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentByteWrapper studentMax = em.find(StudentByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentByteWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentByteWrapper newStudent = em.find(StudentByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentByteWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentByteWrapper newStudent = em.find(StudentByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentByteWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentByteWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Byte.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentByteWrapper\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"BytesType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentByteWrapper\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentByteWrapper\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentByteWrapper\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraCharTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentChar;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraCharTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of char\n        StudentChar studentMax = new StudentChar();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Character) getMaxValue(char.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of char\n        StudentChar studentMin = new StudentChar();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Character) getMinValue(char.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of char\n        StudentChar student = new StudentChar();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(char.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentChar studentMax = em.find(StudentChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentChar studentMin = em.find(StudentChar.class, getMinValue(char.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentChar student = em.find(StudentChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentChar student = em.find(StudentChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentChar newStudent = em.find(StudentChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            Assert.assertEquals(getMinValue(char.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(char.class));\n        q.setParameter(2, getMaxValue(char.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Character) getMinValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(char.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentChar studentMax = em.find(StudentChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentChar.class, getMaxValue(char.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentChar s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentChar newStudent = em.find(StudentChar.class, getRandomValue(char.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentChar s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentChar newStudent = em.find(StudentChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentChar s \";\n        Query q = em.createQuery(query);\n        List<StudentChar> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Character) getMinValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(char.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentChar\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"UTF8Type\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentChar\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentChar\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentChar\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraCharacterTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentCharacter;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraCharacterTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Character\n        StudentCharacter studentMax = new StudentCharacter();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Character) getMaxValue(Character.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Character\n        StudentCharacter studentMin = new StudentCharacter();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Character) getMinValue(Character.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Character\n        StudentCharacter student = new StudentCharacter();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(Character.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCharacter studentMax = em.find(StudentCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCharacter studentMin = em.find(StudentCharacter.class, getMinValue(Character.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCharacter student = em.find(StudentCharacter.class, getRandomValue(Character.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCharacter student = em.find(StudentCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCharacter newStudent = em.find(StudentCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            Assert.assertEquals(getMinValue(Character.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Character.class));\n        q.setParameter(2, getMaxValue(Character.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Character.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            Assert.assertEquals(getMaxValue(Character.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            Assert.assertEquals(getMaxValue(Character.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCharacter studentMax = em.find(StudentCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCharacter.class, getMaxValue(Character.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentCharacter s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCharacter newStudent = em\n                .find(StudentCharacter.class, getRandomValue(Character.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentCharacter s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCharacter newStudent = em\n                .find(StudentCharacter.class, getRandomValue(Character.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentCharacter s \";\n        Query q = em.createQuery(query);\n        List<StudentCharacter> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Character.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentCharacter\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"UTF8Type\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentCharacter\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentCharacter\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentCharacter\\\"\",keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraDateTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentDate;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraDateTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentDate student = new StudentDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue(Date.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Date\n        StudentDate studentMax = new StudentDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue(Date.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Date\n        StudentDate studentMin = new StudentDate();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Date) getMinValue(Date.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentDate studentMax = em.find(StudentDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDate studentMin = em.find(StudentDate.class, getMinValue(Date.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDate student = em.find(StudentDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentDate student = em.find(StudentDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDate newStudent = em.find(StudentDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            Assert.assertEquals(getMinValue(Date.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.id between ?1  and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Date.class));\n        q.setParameter(2, getMaxValue(Date.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Date.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentDate studentMax = em.find(StudentDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentDate.class, getMaxValue(Date.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentDate s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDate newStudent = em.find(StudentDate.class, getRandomValue(Date.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentDate s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDate newStudent = em.find(StudentDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentDate s \";\n        Query q = em.createQuery(query);\n        List<StudentDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue(Date.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n   }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentDate\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"DateType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentDate\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentDate\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentDate\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraDoublePrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentDoublePrimitive;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraDoublePrimitiveTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Double\n        StudentDoublePrimitive studentMax = new StudentDoublePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) getMaxValue(Double.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Double\n        StudentDoublePrimitive studentMin = new StudentDoublePrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Double) getMinValue(Double.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Double\n        StudentDoublePrimitive student = new StudentDoublePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentDoublePrimitive studentMax = em.find(StudentDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoublePrimitive studentMin = em.find(StudentDoublePrimitive.class, getMinValue(Double.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoublePrimitive student = em.find(StudentDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentDoublePrimitive student = em.find(StudentDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoublePrimitive newStudent = em.find(StudentDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(Double.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(double.class));\n        q.setParameter(2, getMaxValue(double.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Double) getMinValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentDoublePrimitive studentMax = em.find(StudentDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentDoublePrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoublePrimitive newStudent = em.find(StudentDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentDoublePrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoublePrimitive newStudent = em.find(StudentDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentDoublePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentDoublePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Double) getMinValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentDoublePrimitive\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"DoubleType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentDoublePrimitive\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentDoublePrimitive\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an Double\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentDoublePrimitive\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraDoubleWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentDoubleWrapper;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraDoubleWrapperTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Double\n        StudentDoubleWrapper studentMax = new StudentDoubleWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) getMaxValue(Double.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Double\n        StudentDoubleWrapper studentMin = new StudentDoubleWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Double) getMinValue(Double.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Double\n        StudentDoubleWrapper student = new StudentDoubleWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentDoubleWrapper studentMax = em.find(StudentDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoubleWrapper studentMin = em.find(StudentDoubleWrapper.class, getMinValue(Double.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoubleWrapper student = em.find(StudentDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentDoubleWrapper student = em.find(StudentDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoubleWrapper newStudent = em.find(StudentDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Double.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Double.class));\n        q.setParameter(2, getMaxValue(Double.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Double.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentDoubleWrapper studentMax = em.find(StudentDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentDoubleWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoubleWrapper newStudent = em.find(StudentDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentDoubleWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoubleWrapper newStudent = em.find(StudentDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentDoubleWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentDoubleWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Double.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentDoubleWrapper\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"DoubleType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentDoubleWrapper\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentDoubleWrapper\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an Double\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentDoubleWrapper\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraFloatPrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentFloatPrimitive;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraFloatPrimitiveTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of float\n        StudentFloatPrimitive studentMax = new StudentFloatPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Float) getMaxValue(float.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of float\n        StudentFloatPrimitive studentMin = new StudentFloatPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Float) getMinValue(float.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of float\n        StudentFloatPrimitive student = new StudentFloatPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Float) getRandomValue(float.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentFloatPrimitive studentMax = em.find(StudentFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentFloatPrimitive studentMin = em.find(StudentFloatPrimitive.class, getMinValue(float.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentFloatPrimitive student = em.find(StudentFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentFloatPrimitive student = em.find(StudentFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentFloatPrimitive newStudent = em.find(StudentFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(float.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatPrimitive s where s.id between \" + getMinValue(float.class) + \" and \"\n                + getMaxValue(float.class);\n        // query =\n        // \"Select s From StudentFloatPrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        // q.setParameter(1, getMinValue(float.class));\n        // q.setParameter(2, getMaxValue(float.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Float) getMinValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentFloatPrimitive studentMax = em.find(StudentFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentFloatPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentFloatPrimitive newStudent = em.find(StudentFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentFloatPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentFloatPrimitive newStudent = em.find(StudentFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatPrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatPrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatPrimitive s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentFloatPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentFloatPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Float) getMinValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentFloatPrimitive\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"FloatType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentFloatPrimitive\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentFloatPrimitive\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentFloatPrimitive\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraFloatWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentFloatWrapper;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraFloatWrapperTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Float\n        StudentFloatWrapper studentMax = new StudentFloatWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Float) getMaxValue(Float.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Float\n        StudentFloatWrapper studentMin = new StudentFloatWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Float) getMinValue(Float.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Float\n        StudentFloatWrapper student = new StudentFloatWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Float) getRandomValue(Float.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentFloatWrapper studentMax = em.find(StudentFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentFloatWrapper studentMin = em.find(StudentFloatWrapper.class, getMinValue(Float.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentFloatWrapper student = em.find(StudentFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentFloatWrapper student = em.find(StudentFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentFloatWrapper newStudent = em.find(StudentFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Float.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Float.class));\n        q.setParameter(2, getMaxValue(Float.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Float.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentFloatWrapper studentMax = em.find(StudentFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentFloatWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentFloatWrapper newStudent = em.find(StudentFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentFloatWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentFloatWrapper newStudent = em.find(StudentFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatWrapper s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentFloatWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentFloatWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentFloatWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Float.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n}\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentFloatWrapper\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"FloatType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentFloatWrapper\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentFloatWrapper\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentFloatWrapper\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraIntTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentInt;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraIntTest extends CassandraBase\n{\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of int\n        StudentInt studentMax = new StudentInt();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(int.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of int\n        StudentInt studentMin = new StudentInt();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Integer) getMinValue(int.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of int\n        StudentInt student = new StudentInt();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(int.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentInt studentMax = em.find(StudentInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInt studentMin = em.find(StudentInt.class, getMinValue(int.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInt student = em.find(StudentInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentInt student = em.find(StudentInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInt newStudent = em.find(StudentInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            Assert.assertEquals(getMinValue(int.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.id between \" + getMinValue(int.class) + \" and \"\n                + getMaxValue(int.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Integer) getMinValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentInt studentMax = em.find(StudentInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentInt.class, getMaxValue(int.class));\n        Assert.assertNull(studentMax);\n        testPersist(useSameEm);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentInt s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInt newStudent = em.find(StudentInt.class, getRandomValue(int.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentInt s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInt newStudent = em.find(StudentInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentInt s \";\n        Query q = em.createQuery(query);\n        List<StudentInt> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Integer) getMinValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentInt\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"Int32Type\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentInt\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentInt\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentInt\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraIntegerTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentInteger;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraIntegerTest extends CassandraBase\n{\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of integer\n        StudentInteger studentMax = new StudentInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(Integer.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of integer\n        StudentInteger studentMin = new StudentInteger();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Integer) getMinValue(Integer.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of integer\n        StudentInteger student = new StudentInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(Integer.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentInteger studentMax = em.find(StudentInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInteger studentMin = em.find(StudentInteger.class, getMinValue(Integer.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInteger student = em.find(StudentInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentInteger student = em.find(StudentInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInteger newStudent = em.find(StudentInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(Integer.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Integer.class));\n        q.setParameter(2, getMaxValue(Integer.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Integer.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentInteger studentMax = em.find(StudentInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentInteger.class, getMaxValue(Integer.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentInteger s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInteger newStudent = em.find(StudentInteger.class, getRandomValue(Integer.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentInteger s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInteger newStudent = em.find(StudentInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Integer.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentInteger\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"Int32Type\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentInteger\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentInteger\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an integer\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n       \n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentInteger\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraLongPrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentLongPrimitive;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraLongPrimitiveTest extends CassandraBase\n{\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of long\n        StudentLongPrimitive studentMax = new StudentLongPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of long\n        StudentLongPrimitive studentMin = new StudentLongPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Long) getMinValue(long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of long\n        StudentLongPrimitive student = new StudentLongPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentLongPrimitive studentMax = em.find(StudentLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongPrimitive studentMin = em.find(StudentLongPrimitive.class, getMinValue(long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongPrimitive student = em.find(StudentLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentLongPrimitive student = em.find(StudentLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongPrimitive newStudent = em.find(StudentLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(long.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.id between \" + getMinValue(long.class) + \" and \"\n                + getMaxValue(long.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Long) getMinValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentLongPrimitive studentMax = em.find(StudentLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentLongPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongPrimitive newStudent = em.find(StudentLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentLongPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongPrimitive newStudent = em.find(StudentLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentLongPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentLongPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Long) getMinValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentLongPrimitive\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"LongType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentLongPrimitive\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentLongPrimitive\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an long\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentLongPrimitive\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraLongWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentLongWrapper;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraLongWrapperTest extends CassandraBase\n{\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert min value of Long\n        StudentLongWrapper studentMin = new StudentLongWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Long) getMinValue(Long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Long\n        StudentLongWrapper student = new StudentLongWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(Long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Long\n        StudentLongWrapper studentMax = new StudentLongWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(Long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentLongWrapper studentMax = em.find(StudentLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongWrapper studentMin = em.find(StudentLongWrapper.class, getMinValue(Long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongWrapper student = em.find(StudentLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentLongWrapper student = em.find(StudentLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongWrapper newStudent = em.find(StudentLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Long.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Long.class));\n        q.setParameter(2, getMaxValue(Long.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Long.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentLongWrapper studentMax = em.find(StudentLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentLongWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongWrapper newStudent = em.find(StudentLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentLongWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongWrapper newStudent = em.find(StudentLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentLongWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentLongWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Long.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentLongWrapper\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"LongType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentLongWrapper\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentLongWrapper\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an Long\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentLongWrapper\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraShortPrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentShortPrimitive;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraShortPrimitiveTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentShortPrimitive studentMax = new StudentShortPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentShortPrimitive studentMin = new StudentShortPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Short) getMinValue(Short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentShortPrimitive student = new StudentShortPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentShortPrimitive studentMax = em.find(StudentShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortPrimitive studentMin = em.find(StudentShortPrimitive.class, getMinValue(Short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortPrimitive student = em.find(StudentShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentShortPrimitive student = em.find(StudentShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortPrimitive newStudent = em.find(StudentShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(Short.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.id between \" + getMinValue(Short.class) + \" and \"\n                + getMaxValue(Short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Short) getMinValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentShortPrimitive studentMax = em.find(StudentShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentShortPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortPrimitive newStudent = em.find(StudentShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentShortPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortPrimitive newStudent = em.find(StudentShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentShortPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentShortPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Short) getMinValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentShortPrimitive\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"Int32Type\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                // CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentShortPrimitive\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentShortPrimitive\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an Short\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n        }\n        catch (TException e)\n        {\n            \n        }\n\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentShortPrimitive\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraShortWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentShortWrapper;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraShortWrapperTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentShortWrapper studentMax = new StudentShortWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentShortWrapper studentMin = new StudentShortWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Short) getMinValue(Short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentShortWrapper student = new StudentShortWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentShortWrapper studentMax = em.find(StudentShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortWrapper studentMin = em.find(StudentShortWrapper.class, getMinValue(Short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortWrapper student = em.find(StudentShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentShortWrapper student = em.find(StudentShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortWrapper newStudent = em.find(StudentShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Short.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.id between \" + getMinValue(Short.class) + \" and \"\n                + getMaxValue(Short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Short.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentShortWrapper studentMax = em.find(StudentShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentShortWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortWrapper newStudent = em.find(StudentShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentShortWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortWrapper newStudent = em.find(StudentShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentShortWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentShortWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Short.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentShortWrapper\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"Int32Type\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentShortWrapper\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentShortWrapper\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an Short\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentShortWrapper\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraSqlDateTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.sql.Date;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentSqlDate;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraSqlDateTest extends CassandraBase\n{\n    private static final Date DATE = new Date(System.currentTimeMillis());\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentSqlDate student = new StudentSqlDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue());\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Date\n        StudentSqlDate studentMax = new StudentSqlDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue());\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Date\n        StudentSqlDate studentMin = new StudentSqlDate();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Date) getMinValue());\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    private Object getMinValue()\n    {\n        return new Date(1970, 1, 1);\n    }\n\n    private Object getRandomValue()\n    {\n        return DATE;\n    }\n\n    private Object getMaxValue()\n    {\n        return new Date(2100, 1, 1);\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentSqlDate studentMax = em.find(StudentSqlDate.class, getMaxValue());\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentSqlDate studentMin = em.find(StudentSqlDate.class, getMinValue());\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentSqlDate student = em.find(StudentSqlDate.class, getRandomValue());\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentSqlDate student = em.find(StudentSqlDate.class, getMaxValue());\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentSqlDate newStudent = em.find(StudentSqlDate.class, getMaxValue());\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            Assert.assertEquals(getMinValue().toString(), student.getId().toString());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.id between \" + getMinValue() + \" and \" + getMaxValue();\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentSqlDate student : students)\n        {\n            if (student.getId().toString().equals(getMaxValue().toString()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().toString().equals(getMinValue().toString()))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue().toString(), student.getId().toString());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            Assert.assertEquals(getMaxValue().toString(), student.getId().toString());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            Assert.assertEquals(getMaxValue().toString(), student.getId().toString());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentSqlDate studentMax = em.find(StudentSqlDate.class, getMaxValue());\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentSqlDate.class, getMaxValue());\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentSqlDate s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentSqlDate newStudent = em.find(StudentSqlDate.class, getRandomValue());\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentSqlDate s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentSqlDate newStudent = em.find(StudentSqlDate.class, getRandomValue());\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue().toString(), student.getId().toString());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue().toString(), student.getId().toString());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            if (student.getId().toString().equals(getMaxValue().toString()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue().toString(), student.getId().toString());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue().toString(), student.getId().toString());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            if (student.getId().toString().equals(getMaxValue().toString()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue().toString(), student.getId().toString());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentSqlDate s \";\n        Query q = em.createQuery(query);\n        List<StudentSqlDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentSqlDate student : students)\n        {\n            if (student.getId().toString().equals(getMaxValue().toString()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().toString().equals(getMinValue().toString()))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue()).toString(), student.getId().toString());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n\n        }\n        catch (TException e)\n        {\n\n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentSqlDate\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"DateType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentSqlDate\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentSqlDate\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n\n        }\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentSqlDate\\\"\", keyspace);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraStringTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentString;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraStringTest extends CassandraBase\n{\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of String\n        StudentString studentMax = new StudentString();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((String) getMaxValue(String.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of String\n        StudentString studentMin = new StudentString();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((String) getMinValue(String.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of String\n        StudentString student = new StudentString();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((String) getRandomValue(String.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentString studentMax = em.find(StudentString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentString studentMin = em.find(StudentString.class, getMinValue(String.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentString student = em.find(StudentString.class, getRandomValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentString student = em.find(StudentString.class, getMaxValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentString newStudent = em.find(StudentString.class, getMaxValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            Assert.assertEquals(getMinValue(String.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.id between \" + getMinValue(String.class) + \" and \"\n                + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentString studentMax = em.find(StudentString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentString.class, getMaxValue(String.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentString s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentString newStudent = em.find(StudentString.class, getRandomValue(String.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentString s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentString newStudent = em.find(StudentString.class, getRandomValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentString s \";\n        Query q = em.createQuery(query);\n        List<StudentString> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(String.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(String.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentString\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"UTF8Type\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentString\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentString\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an String\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentString\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.databene.contiperf.PerfTest;\nimport org.databene.contiperf.junit.ContiPerfRule;\nimport org.databene.contiperf.report.CSVSummaryReportModule;\nimport org.databene.contiperf.report.HtmlReportModule;\nimport org.databene.contiperf.report.ReportModule;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * The Class StudentDaoTest. script to create Cassandra column family for this\n * test case:\n * \n * @see create column family STUDENT with comparator=AsciiType and\n *      key_validation_class=LongType and column_metadata=[{column_name:\n *      STUDENT_NAME, validation_class:UTF8Type, index_type: KEYS},\n *      {column_name: AGE, validation_class:IntegerType, index_type: KEYS},\n *      {column_name: UNIQUE_ID, validation_class:IntegerType, index_type:\n *      KEYS}, {column_name: IS_EXCEPTIONAL, validation_class:IntegerType,\n *      index_type: KEYS}, {column_name: SEMESTER, validation_class:IntegerType,\n *      index_type: KEYS}, {column_name: DIGITAL_SIGNATURE,\n *      validation_class:IntegerType, index_type: KEYS}, {column_name: CGPA,\n *      validation_class:IntegerType, index_type: KEYS}, {column_name:\n *      PERCENTAGE, validation_class:IntegerType, index_type: KEYS},\n *      {column_name: HEIGHT, validation_class:IntegerType, index_type: KEYS},\n *      {column_name: ENROLMENT_DATE, validation_class:IntegerType, index_type:\n *      KEYS}, {column_name: ENROLMENT_TIME, validation_class:IntegerType,\n *      index_type: KEYS}, {column_name: JOINING_DATE_TIME,\n *      validation_class:IntegerType, index_type: KEYS}, {column_name:\n *      YEARS_SPENT, validation_class:IntegerType, index_type: KEYS},\n *      {column_name: ROLL_NUMBER, validation_class:IntegerType, index_type:\n *      KEYS}, {column_name: MONTHLY_FEE, validation_class:IntegerType,\n *      index_type: KEYS}, {column_name: SQL_DATE, validation_class:IntegerType,\n *      index_type: KEYS}, {column_name: SQL_TIMESTAMP,\n *      validation_class:IntegerType, index_type: KEYS}, {column_name: SQL_TIME,\n *      validation_class:IntegerType, index_type: KEYS}, {column_name: BIG_INT,\n *      validation_class:IntegerType, index_type: KEYS}, {column_name:\n *      BIG_DECIMAL, validation_class:IntegerType, index_type: KEYS},\n *      {column_name: CALENDAR, validation_class:UTF8Type, index_type: KEYS}];\n * @author Vivek Mishra\n */\npublic class StudentCassandraTest extends StudentCassandraBase<StudentCassandra>\n{\n    String persistenceUnit = \"secIdxCassandraTest\";\n\n    @Rule\n    public ContiPerfRule i = new ContiPerfRule(new ReportModule[] { new CSVSummaryReportModule(),\n            new HtmlReportModule() });\n\n    protected Map propertyMap = null;\n\n    protected boolean cqlEnabled = false;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        if (propertyMap == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n            // propertyMap.put(CassandraConstants.CQL_VERSION,\n            // CassandraConstants.CQL_VERSION_2_0);\n        }\n        setupInternal(persistenceUnit, propertyMap, cqlEnabled);\n        propertyMap = null;\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        teardownInternal(persistenceUnit);\n    }\n\n    @Test\n    @PerfTest(invocations = 2)\n    public void executeTests()\n    {\n        onInsert();\n        onMerge();\n    }\n\n    /**\n     * Test method for.\n     * \n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     *             {@link com.impetus.kundera.examples.student.StudentDao#saveStudent(com.impetus.kundera.examples.crud.datatype.entities.StudentCassandra)}\n     *             .\n     */\n\n    public void onInsert()\n    {\n        try\n        {\n            onInsert(new StudentCassandra());\n            em.clear();\n            // // find by id.\n            StudentEntityDef s = em.find(StudentCassandra.class, studentId1);\n            assertOnDataTypes((StudentCassandra) s);\n            em.clear();\n            //\n            // // // find by name.\n            assertFindByName(em, \"StudentCassandra\", StudentCassandra.class, \"Amresh\", \"studentName\");\n            em.clear();\n            //\n            // // find by Id\n            // // assertFindByGTId(em, \"StudentCassandra\",\n            // StudentCassandra.class,\n            // // \"12345677\", \"studentId\");\n            //\n            // // find by name and age.\n            assertFindByNameAndAge(em, \"StudentCassandra\", StudentCassandra.class, \"Amresh\", \"10\", \"studentName\");\n            em.clear();\n            //\n            // // find by name, age clause\n            assertFindByNameAndAgeGTAndLT(em, \"StudentCassandra\", StudentCassandra.class, \"Amresh\", \"10\", \"20\",\n                    \"studentName\");\n            em.clear();\n            // //\n            // // // find by between clause\n            assertFindByNameAndAgeBetween(em, \"StudentCassandra\", StudentCassandra.class, \"Amresh\", \"10\", \"15\",\n                    \"studentName\");\n            em.clear();\n            //\n            // // find by Range.\n            // assertFindByRange(em, \"StudentCassandra\", StudentCassandra.class,\n            // \"12345677\", \"12345678\", \"studentId\");\n            //\n            // // find by without where clause.\n            assertFindWithoutWhereClause(em, \"StudentCassandra\", StudentCassandra.class, false);\n            em.clear();\n            //\n\n            // Query on Date.\n            String query = \"Select s from StudentCassandra s where s.enrolmentDate =:enrolmentDate\";\n            Query q = em.createQuery(query);\n            q.setParameter(\"enrolmentDate\", enrolmentDate);\n            List<StudentCassandra> results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(3, results.size());\n\n            // Query on long.\n            /* String */query = \"Select s from StudentCassandra s where s.uniqueId =?1\";\n            /* Query */q = em.createQuery(query);\n            q.setParameter(1, 78575785897L);\n\n            /* List<StudentCassandra> */results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(1, results.size());\n            Assert.assertEquals(78575785897L, results.get(0).getUniqueId());\n            em.clear();\n            // Assert on boolean.\n            query = \"Select s from StudentCassandra s where s.isExceptional =?1\";\n            q = em.createQuery(query);\n            q.setParameter(1, true);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(2, results.size());\n            Assert.assertEquals(true, results.get(0).isExceptional());\n            Assert.assertEquals(true, results.get(1).isExceptional());\n\n            em.clear();\n            // with false.\n            query = \"Select s from StudentCassandra s where s.isExceptional =?1\";\n            q = em.createQuery(query);\n            q.setParameter(1, false);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(1, results.size());\n            Assert.assertEquals(false, results.get(0).isExceptional());\n            em.clear();\n            // query on int.\n\n            query = \"Select s from StudentCassandra s where s.age =?1\";\n            q = em.createQuery(query);\n            q.setParameter(1, 10);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(1, results.size());\n            Assert.assertEquals(false, results.get(0).isExceptional());\n            Assert.assertEquals(10, results.get(0).getAge());\n            em.clear();\n            // query on char (semester)\n\n            query = \"Select s from StudentCassandra s where s.semester =?1\";\n            q = em.createQuery(query);\n            q.setParameter(1, 'A');\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(1, results.size());\n            Assert.assertEquals(false, results.get(0).isExceptional());\n            Assert.assertEquals(10, results.get(0).getAge());\n            Assert.assertEquals('A', results.get(0).getSemester());\n            em.clear();\n            // query on float (percentage)\n            query = \"Select s from StudentCassandra s where s.percentage =?1\";\n            q = em.createQuery(query);\n            q.setParameter(1, 61.6);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(1, results.size());\n            Assert.assertEquals(true, results.get(0).isExceptional());\n            Assert.assertEquals(61.6f, results.get(0).getPercentage());\n            em.clear();\n            // query on double (height)\n\n            query = \"Select s from StudentCassandra s where s.height =?1\";\n            q = em.createQuery(query);\n            q.setParameter(1, 163.76765654);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(1, results.size());\n            Assert.assertEquals(false, results.get(0).isExceptional());\n            Assert.assertEquals(163.76765654, results.get(0).getHeight());\n            em.clear();\n            // query on cgpa.\n            query = \"Select s from StudentCassandra s where s.cgpa =?1\";\n            q = em.createQuery(query);\n            q.setParameter(1, (short) 8);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(3, results.size());\n            for (StudentCassandra studentCassandra : results)\n            {\n                if (studentCassandra.getStudentId() == studentId1)\n                {\n                    Assert.assertEquals(false, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                }\n                else if (studentCassandra.getStudentId() == studentId2)\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                }\n                else\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                }\n            }\n\n            em.clear();\n            // query on yearsSpent.\n            Integer i = new Integer(3);\n            query = \"Select s from StudentCassandra s where s.yearsSpent = 3\";\n            q = em.createQuery(query);\n            // q.setParameter(1, new Integer(3));\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(3, results.size());\n            for (StudentCassandra studentCassandra : results)\n            {\n                if (studentCassandra.getStudentId() == studentId1)\n                {\n                    Assert.assertEquals(false, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                }\n                else if (studentCassandra.getStudentId() == studentId2)\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                }\n                else\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                }\n            }\n\n            em.clear();\n            // query on yearsSpent.\n            query = \"Select s from StudentCassandra s where s.yearsSpent =?1\";\n            q = em.createQuery(query);\n            q.setParameter(1, new Integer(3));\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(3, results.size());\n            for (StudentCassandra studentCassandra : results)\n            {\n                if (studentCassandra.getStudentId() == studentId1)\n                {\n                    Assert.assertEquals(false, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                }\n                else if (studentCassandra.getStudentId() == studentId2)\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                }\n                else\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                }\n            }\n            em.clear();\n            // query on digitalSignature.\n            query = \"Select s from StudentCassandra s where s.digitalSignature =?1\";\n            q = em.createQuery(query);\n            q.setParameter(1, (byte) 50);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(2, results.size());\n            for (StudentCassandra studentCassandra : results)\n            {\n                if (studentCassandra.getStudentId() == studentId2)\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                }\n                else\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                }\n            }\n            em.clear();\n            // query on cpga and digitalSignature.\n            query = \"Select s from StudentCassandra s where s.cgpa =?1 and s.digitalSignature >= ?2 and s.digitalSignature <= ?3\";\n            q = em.createQuery(query);\n            q.setParameter(1, (short) 8);\n            q.setParameter(2, (byte) 5);\n            q.setParameter(3, (byte) 50);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(3, results.size());\n            for (StudentCassandra studentCassandra : results)\n            {\n                if (studentCassandra.getStudentId() == studentId1)\n                {\n                    Assert.assertEquals(false, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 5, studentCassandra.getDigitalSignature());\n                }\n                else if (studentCassandra.getStudentId() == studentId2)\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 50, studentCassandra.getDigitalSignature());\n                }\n                else\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 50, studentCassandra.getDigitalSignature());\n                }\n            }\n\n            em.clear();\n            // query on cpga and digitalSignature.\n            query = \"Select s from StudentCassandra s where s.digitalSignature = ?2 and s.cgpa >= ?3 and s.cgpa <=?1\";\n            q = em.createQuery(query);\n            q.setParameter(1, (short) 8);\n            q.setParameter(2, (byte) 5);\n            q.setParameter(3, (short) 4);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(1, results.size());\n            Assert.assertEquals(false, results.get(0).isExceptional());\n            Assert.assertEquals((short) 8, results.get(0).getCgpa());\n            Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n            em.clear();\n\n            // query on percentage and height.\n            query = \"Select s from StudentCassandra s where s.percentage >= ?2 and s.percentage <= ?3 and s.height =?1\";\n            q = em.createQuery(query);\n            q.setParameter(1, 163.76765654);\n            q.setParameter(2, 61.6);\n            q.setParameter(3, 69.3);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(1, results.size());\n            Assert.assertEquals(false, results.get(0).isExceptional());\n            Assert.assertEquals((short) 8, results.get(0).getCgpa());\n            Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n            Assert.assertEquals(69.3f, results.get(0).getPercentage());\n            Assert.assertEquals(163.76765654, results.get(0).getHeight());\n            em.clear();\n            // query on percentage and height parameter appended in string.\n            query = \"Select s from StudentCassandra s where s.percentage >= 61.6 and s.percentage <= 69.3 and s.height = 163.76765654\";\n            q = em.createQuery(query);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(1, results.size());\n            Assert.assertEquals(false, results.get(0).isExceptional());\n            Assert.assertEquals((short) 8, results.get(0).getCgpa());\n            Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n            Assert.assertEquals(69.3f, results.get(0).getPercentage());\n            Assert.assertEquals(163.76765654, results.get(0).getHeight());\n            em.clear();\n            // query on cpga and digitalSignature parameter appended with String\n            // .\n            query = \"Select s from StudentCassandra s where s.cgpa = 8 and s.digitalSignature >= 5 and s.digitalSignature <= 50\";\n            q = em.createQuery(query);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(3, results.size());\n            for (StudentCassandra studentCassandra : results)\n            {\n                if (studentCassandra.getStudentId() == studentId1)\n                {\n                    Assert.assertEquals(false, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 5, studentCassandra.getDigitalSignature());\n                }\n                else if (studentCassandra.getStudentId() == studentId2)\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 50, studentCassandra.getDigitalSignature());\n                }\n                else\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 50, studentCassandra.getDigitalSignature());\n                }\n            }\n            em.clear();\n            // query on cpga and uniqueId.\n            query = \"Select s from StudentCassandra s where s.cgpa =?1 and s.uniqueId >= ?2 and s.uniqueId <= ?3\";\n            q = em.createQuery(query);\n            q.setParameter(1, (short) 8);\n            q.setParameter(2, 78575785897L);\n            q.setParameter(3, 78575785899L);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(3, results.size());\n            for (StudentCassandra studentCassandra : results)\n            {\n                if (studentCassandra.getStudentId() == studentId1)\n                {\n                    Assert.assertEquals(false, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 5, studentCassandra.getDigitalSignature());\n                    Assert.assertEquals(78575785897L, studentCassandra.getUniqueId());\n                }\n                else if (studentCassandra.getStudentId() == studentId2)\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 50, studentCassandra.getDigitalSignature());\n                    Assert.assertEquals(78575785898L, studentCassandra.getUniqueId());\n                }\n                else\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 50, studentCassandra.getDigitalSignature());\n                    Assert.assertEquals(78575785899L, studentCassandra.getUniqueId());\n                }\n            }\n\n            // query on cpga and semester.\n            query = \"Select s from StudentCassandra s where s.cgpa =?1 and s.semester >= ?2 and s.semester < ?3\";\n            q = em.createQuery(query);\n            q.setParameter(1, (short) 8);\n            q.setParameter(2, 'A');\n            q.setParameter(3, 'C');\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(2, results.size());\n            for (StudentCassandra studentCassandra : results)\n            {\n                if (studentCassandra.getStudentId() == studentId1)\n                {\n                    Assert.assertEquals(false, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 5, studentCassandra.getDigitalSignature());\n                    Assert.assertEquals(78575785897L, studentCassandra.getUniqueId());\n                    Assert.assertEquals(10, studentCassandra.getAge());\n                }\n                else if (studentCassandra.getStudentId() == studentId2)\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 50, studentCassandra.getDigitalSignature());\n                    Assert.assertEquals(78575785898L, studentCassandra.getUniqueId());\n                    Assert.assertEquals(20, studentCassandra.getAge());\n                }\n                else\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 50, studentCassandra.getDigitalSignature());\n                    Assert.assertEquals(78575785899L, studentCassandra.getUniqueId());\n                    Assert.assertEquals(15, studentCassandra.getAge());\n                }\n            }\n\n            // query on cpga and semester with appending in string.\n            query = \"Select s from StudentCassandra s where s.cgpa = 8 and s.semester >= A and s.semester < C\";\n            q = em.createQuery(query);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(2, results.size());\n            for (StudentCassandra studentCassandra : results)\n            {\n                if (studentCassandra.getStudentId() == studentId1)\n                {\n                    Assert.assertEquals(false, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 5, studentCassandra.getDigitalSignature());\n                    Assert.assertEquals(78575785897L, studentCassandra.getUniqueId());\n                    Assert.assertEquals(10, studentCassandra.getAge());\n                }\n                else if (studentCassandra.getStudentId() == studentId2)\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 50, studentCassandra.getDigitalSignature());\n                    Assert.assertEquals(78575785898L, studentCassandra.getUniqueId());\n                    Assert.assertEquals(20, studentCassandra.getAge());\n                }\n                else\n                {\n                    Assert.assertEquals(true, studentCassandra.isExceptional());\n                    Assert.assertEquals(8, studentCassandra.getCgpa());\n                    Assert.assertEquals(i, studentCassandra.getYearsSpent());\n                    Assert.assertEquals((byte) 50, studentCassandra.getDigitalSignature());\n                    Assert.assertEquals(78575785899L, studentCassandra.getUniqueId());\n                    Assert.assertEquals(15, studentCassandra.getAge());\n                }\n            }\n\n            em.clear();\n            // query on invalid cpga and uniqueId.\n            query = \"Select s from StudentCassandra s where s.cgpa =?1 and s.uniqueId >= ?2 and s.uniqueId <= ?3\";\n            q = em.createQuery(query);\n            q.setParameter(1, (short) 2);\n            q.setParameter(2, 78575785897L);\n            q.setParameter(3, 78575785899L);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertTrue(results.isEmpty());\n            em.clear();\n            // query on big integer.\n            query = \"Select s from StudentCassandra s where s.bigInteger =?1\";\n            q = em.createQuery(query);\n            q.setParameter(1, bigInteger);\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(1, results.size());\n            Assert.assertEquals(false, results.get(0).isExceptional());\n            Assert.assertEquals(163.76765654, results.get(0).getHeight());\n\n            // invalid.\n            q.setParameter(1, new BigInteger(\"1234567823\"));\n            results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertTrue(results.isEmpty());\n\n            updateQueryTest();\n        }\n        catch (Exception e)\n        {\n\n            Assert.fail(\"Failure onInsert test, caused by :\" + e);\n        }\n    }\n\n    private void updateQueryTest()\n    {\n        Query q = em\n                .createQuery(\"update StudentCassandra s set s.studentName = :newName where s.studentName = :oldName\");\n        q.setParameter(\"newName\", \"NewAmresh\");\n        q.setParameter(\"oldName\", \"Amresh\");\n        q.executeUpdate();\n\n        em.clear();\n        // // find by id.\n        StudentEntityDef s = em.find(StudentCassandra.class, studentId1);\n        Assert.assertEquals(\"NewAmresh\", s.getStudentName());\n\n        q = em.createQuery(\"update StudentCassandra s set s.studentName = :newName where s.studentName = :oldName\");\n        q.setParameter(\"newName\", \"Amresh\");\n        q.setParameter(\"oldName\", \"NewAmresh\");\n        q.executeUpdate();\n\n        em.clear();\n        // // find by id.\n        s = em.find(StudentCassandra.class, studentId1);\n        Assert.assertEquals(\"Amresh\", s.getStudentName());\n    }\n\n    /**\n     * On merge.\n     */\n    public void onMerge()\n    {\n        try\n        {\n            em.persist(prepareData((Long) studentId1, 78575785897L, \"Amresh\", true, 10, 'C', (byte) 5, (short) 8,\n                    (float) 69.6, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3),\n                    new Long(978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger,\n                    calendar, new StudentCassandra()));\n            StudentCassandra s = em.find(StudentCassandra.class, studentId1);\n            Assert.assertNotNull(s);\n            Assert.assertEquals(\"Amresh\", s.getStudentName());\n            // modify record.\n            s.setStudentName(\"NewAmresh\");\n            em.merge(s);\n            // emf.close();\n            // assertOnMerge(em, \"StudentCassandra\", StudentCassandra.class,\n            // \"Amresh\", \"NewAmresh\", \"STUDENT_NAME\");\n            Query q = em.createQuery(\"Select p from StudentCassandra p where p.studentName = NewAmresh\");\n            List<StudentCassandra> results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(1, results.size());\n        }\n        catch (Exception e)\n        {\n            Assert.fail(\"Failure onMerge test\");\n        }\n\n    }\n\n    /**\n     * Loads cassandra specific data.\n     * \n     * @param cql_enabled\n     * \n     * @throws TException\n     * @throws InvalidRequestException\n     * @throws UnavailableException\n     * @throws TimedOutException\n     * @throws SchemaDisagreementException\n     */\n    private void loadData(boolean cql_enabled) throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n\n        KsDef ksDef = null;\n\n        CfDef cfDef = new CfDef();\n        cfDef.name = \"STUDENT\";\n        cfDef.keyspace = \"KunderaExamples\";\n        cfDef.setKey_validation_class(\"LongType\");\n        cfDef.setComparator_type(\"UTF8Type\");\n\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"UNIQUE_ID\".getBytes()), \"LongType\");\n        columnDef2.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef2);\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"STUDENT_NAME\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef3);\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"IS_EXCEPTIONAL\".getBytes()), \"BooleanType\");\n        columnDef4.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef4);\n        ColumnDef columnDef5;\n        ColumnDef columnDef8;\n        ColumnDef columnDef11;\n        ColumnDef columnDef16;\n        ColumnDef columnDef7;\n        if (cql_enabled)\n        {\n            columnDef5 = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            columnDef8 = new ColumnDef(ByteBuffer.wrap(\"CGPA\".getBytes()), \"Int32Type\");\n            columnDef11 = new ColumnDef(ByteBuffer.wrap(\"YEARS_SPENT\".getBytes()), \"Int32Type\");\n            columnDef16 = new ColumnDef(ByteBuffer.wrap(\"BIG_INT\".getBytes()), \"Int32Type\");\n            columnDef7 = new ColumnDef(ByteBuffer.wrap(\"DIGITAL_SIGNATURE\".getBytes()), \"Int32Type\");\n        }\n        else\n        {\n            columnDef5 = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"IntegerType\");\n            columnDef8 = new ColumnDef(ByteBuffer.wrap(\"CGPA\".getBytes()), \"Int32Type\");\n            columnDef11 = new ColumnDef(ByteBuffer.wrap(\"YEARS_SPENT\".getBytes()), \"IntegerType\");\n            columnDef16 = new ColumnDef(ByteBuffer.wrap(\"BIG_INT\".getBytes()), \"IntegerType\");\n            columnDef7 = new ColumnDef(ByteBuffer.wrap(\"DIGITAL_SIGNATURE\".getBytes()), \"BytesType\");\n        }\n\n        columnDef5.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef5);\n\n        columnDef8.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef8);\n\n        columnDef11.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef11);\n\n        columnDef16.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef16);\n\n        ColumnDef columnDef6 = new ColumnDef(ByteBuffer.wrap(\"SEMESTER\".getBytes()), \"UTF8Type\");\n        columnDef6.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef6);\n\n        columnDef7.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef7);\n\n        ColumnDef columnDef9 = new ColumnDef(ByteBuffer.wrap(\"PERCENTAGE\".getBytes()), \"FloatType\");\n        columnDef9.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef9);\n\n        ColumnDef columnDef10 = new ColumnDef(ByteBuffer.wrap(\"HEIGHT\".getBytes()), \"DoubleType\");\n        columnDef10.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef10);\n\n        ColumnDef columnDef12 = new ColumnDef(ByteBuffer.wrap(\"ROLL_NUMBER\".getBytes()), \"LongType\");\n        columnDef12.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef12);\n\n        ColumnDef columnDef13 = new ColumnDef(ByteBuffer.wrap(\"SQL_DATE\".getBytes()), \"DateType\");\n        columnDef13.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef13);\n\n        ColumnDef columnDef14 = new ColumnDef(ByteBuffer.wrap(\"SQL_TIMESTAMP\".getBytes()), \"DateType\");\n        columnDef14.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef14);\n\n        ColumnDef columnDef15 = new ColumnDef(ByteBuffer.wrap(\"SQL_TIME\".getBytes()), \"DateType\");\n        columnDef15.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef15);\n\n        ColumnDef columnDef17 = new ColumnDef(ByteBuffer.wrap(\"BIG_DECIMAL\".getBytes()), \"DecimalType\");\n        columnDef17.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef17);\n\n        ColumnDef columnDef18 = new ColumnDef(ByteBuffer.wrap(\"CALENDAR\".getBytes()), \"DateType\");\n        columnDef18.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef18);\n\n        ColumnDef columnDef19 = new ColumnDef(ByteBuffer.wrap(\"MONTHLY_FEE\".getBytes()), \"DoubleType\");\n        columnDef19.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef19);\n\n        ColumnDef columnDef20 = new ColumnDef(ByteBuffer.wrap(\"ENROLMENT_DATE\".getBytes()), \"DateType\");\n        columnDef20.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef20);\n\n        ColumnDef columnDef21 = new ColumnDef(ByteBuffer.wrap(\"ENROLMENT_TIME\".getBytes()), \"DateType\");\n        columnDef21.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef21);\n\n        ColumnDef columnDef22 = new ColumnDef(ByteBuffer.wrap(\"JOINING_DATE_TIME\".getBytes()), \"DateType\");\n        columnDef22.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef22);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(cfDef);\n        try\n        {\n            CassandraCli.initClient();\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaExamples\");\n            CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"PERSONNEL\"))\n                {\n\n                    CassandraCli.client.system_drop_column_family(\"PERSONNEL\");\n\n                }\n            }\n            CassandraCli.client.system_add_column_family(cfDef);\n\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(\"KunderaExamples\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n    }\n\n    @Override\n    void startServer()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n\n        }\n        catch (TException e)\n        {\n\n        }\n    }\n\n    @Override\n    void stopServer()\n    {\n    }\n\n    @Override\n    void createSchema(boolean cql_enabled)\n    {\n        try\n        {\n            loadData(cql_enabled);\n        }\n        catch (TException e)\n        {\n\n        }\n    }\n\n    @Override\n    void deleteSchema()\n    {\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    public void setPersistenceUnit(String persistenceUnit)\n    {\n        this.persistenceUnit = persistenceUnit;\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraTimeTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.sql.Time;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentTime;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraTimeTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Time\n        StudentTime student = new StudentTime();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Time) getRandomValue(Time.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Time\n        StudentTime studentMax = new StudentTime();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Time) getMaxValue(Time.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Time\n        StudentTime studentMin = new StudentTime();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Time) getMinValue(Time.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentTime studentMax = em.find(StudentTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTime studentMin = em.find(StudentTime.class, getMinValue(Time.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTime student = em.find(StudentTime.class, getRandomValue(Time.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentTime student = em.find(StudentTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTime newStudent = em.find(StudentTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            Assert.assertEquals(getMinValue(Time.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.id between \" + getMinValue(Time.class) + \" and \"\n                + getMaxValue(Time.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Time.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Time.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            Assert.assertEquals(getMaxValue(Time.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            Assert.assertEquals(getMaxValue(Time.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentTime studentMax = em.find(StudentTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentTime.class, getMaxValue(Time.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentTime s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTime newStudent = em.find(StudentTime.class, getRandomValue(Time.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String upTimeQuery = \"Update StudentTime s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(upTimeQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTime newStudent = em.find(StudentTime.class, getRandomValue(Time.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Time.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Time.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentTime s \";\n        Query q = em.createQuery(query);\n        List<StudentTime> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Time.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Time) getRandomValue(Time.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentTime\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"DateType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentTime\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentTime\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentTime\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraTimestampTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentTimestamp;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraTimestampTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Time\n        StudentTimestamp student = new StudentTimestamp();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Timestamp) getRandomValue(Timestamp.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Time\n        StudentTimestamp studentMax = new StudentTimestamp();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Timestamp) getMaxValue(Timestamp.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Timestamp\n        StudentTimestamp studentMin = new StudentTimestamp();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Timestamp) getMinValue(Timestamp.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentTimestamp studentMax = em.find(StudentTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTimestamp studentMin = em.find(StudentTimestamp.class, getMinValue(Timestamp.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTimestamp student = em.find(StudentTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentTimestamp student = em.find(StudentTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTimestamp newStudent = em.find(StudentTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.id between \" + getMinValue(Timestamp.class)\n                + \" and \" + getMaxValue(Timestamp.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            Assert.assertEquals(getMaxValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            Assert.assertEquals(getMaxValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentTimestamp studentMax = em.find(StudentTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentTimestamp s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTimestamp newStudent = em\n                .find(StudentTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String upTimeQuery = \"Update StudentTimestamp s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(upTimeQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTimestamp newStudent = em\n                .find(StudentTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentTimestamp s \";\n        Query q = em.createQuery(query);\n        List<StudentTimestamp> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Timestamp) getRandomValue(Timestamp.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            \n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentTimestamp\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"LongType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentTimestamp\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentTimestamp\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n            \n        }\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentTimestamp\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentCassandraUUIDTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentUUID;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class StudentCassandraUUIDTest extends CassandraBase\n{\n\n    private static final String keyspace = \"KunderaCassandraDataType\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNativeQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * @param b\n     */\n    private void testNativeQuery(boolean b)\n    {\n        String s = \"Select * From \" + \"\\\"StudentUUID\\\"\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createNativeQuery(s, StudentUUID.class);\n        List<StudentUUID> results = q.getResultList();\n        Assert.assertNotNull(results);\n\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of UUID\n        StudentUUID studentMax = new StudentUUID();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((UUID) getMaxValue(UUID.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of UUID\n        StudentUUID studentMin = new StudentUUID();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((UUID) getMinValue(UUID.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of UUID\n        StudentUUID student = new StudentUUID();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((UUID) getRandomValue(UUID.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentUUID studentMax = em.find(StudentUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentUUID studentMin = em.find(StudentUUID.class, getMinValue(UUID.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentUUID student = em.find(StudentUUID.class, getRandomValue(UUID.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentUUID student = em.find(StudentUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentUUID newStudent = em.find(StudentUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentUUID s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentUUID student : students)\n        {\n            Assert.assertEquals(getMinValue(UUID.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentUUID> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentUUID s where s.id between \" + getMinValue(UUID.class) + \" and \"\n                + getMaxValue(UUID.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(UUID.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentUUID s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentUUID student : students)\n        {\n            Assert.assertEquals(getMaxValue(UUID.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentUUID s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentUUID student : students)\n        {\n            Assert.assertEquals(getMaxValue(UUID.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentUUID studentMax = em.find(StudentUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentUUID.class, getMaxValue(UUID.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentUUID s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentUUID newStudent = em.find(StudentUUID.class, getRandomValue(UUID.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentUUID s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentUUID newStudent = em.find(StudentUUID.class, getRandomValue(UUID.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentUUID s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentUUID s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentUUID s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(UUID.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentUUID s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentUUID s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(UUID.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentUUID s \";\n        Query q = em.createQuery(query);\n        List<StudentUUID> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(UUID.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n\n        }\n        catch (TException e)\n        {\n\n        }\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n        try\n        {\n            KsDef ksDef = null;\n\n            CfDef cfDef = new CfDef();\n            cfDef.name = \"StudentUUID\";\n            cfDef.keyspace = keyspace;\n            cfDef.setKey_validation_class(\"UUIDType\");\n            cfDef.setComparator_type(\"UTF8Type\");\n            ColumnDef name = new ColumnDef(ByteBuffer.wrap(\"NAME\".getBytes()), \"UTF8Type\");\n            name.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(name);\n            ColumnDef age = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"Int32Type\");\n            age.index_type = IndexType.KEYS;\n            cfDef.addToColumn_metadata(age);\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\n            cfDefs.add(cfDef);\n            try\n            {\n                CassandraCli.initClient();\n                ksDef = CassandraCli.client.describe_keyspace(keyspace);\n                CassandraCli.client.set_keyspace(keyspace);\n\n                List<CfDef> cfDefn = ksDef.getCf_defs();\n\n                for (CfDef cfDef1 : cfDefn)\n                {\n\n                    if (cfDef1.getName().equalsIgnoreCase(\"StudentUUID\"))\n                    {\n\n                        CassandraCli.client.system_drop_column_family(\"StudentUUID\");\n\n                    }\n                }\n                CassandraCli.client.system_add_column_family(cfDef);\n\n            }\n            catch (NotFoundException e)\n            {\n\n                ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                // Set replication factor\n                if (ksDef.strategy_options == null)\n                {\n                    ksDef.strategy_options = new LinkedHashMap<String, String>();\n                }\n                // Set replication factor, the value MUST be an int\n                ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                CassandraCli.client.system_add_keyspace(ksDef);\n            }\n\n            CassandraCli.client.set_keyspace(keyspace);\n        }\n        catch (TException e)\n        {\n\n        }\n\n    }\n\n    public void dropSchema()\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"StudentUUID\\\"\", keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/StudentEntityDef.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\n\n/**\n * @author vivek.mishra\n * \n */\npublic interface StudentEntityDef\n{\n\n    /**\n     * @return the studentId\n     */\n    long getStudentId();\n\n    /**\n     * @param studentId\n     *            the studentId to set\n     */\n    void setStudentId(long studentId);\n\n    /**\n     * @return the uniqueId\n     */\n    long getUniqueId();\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    void setUniqueId(long uniqueId);\n\n    /**\n     * @return the studentName\n     */\n    String getStudentName();\n\n    /**\n     * @param studentName\n     *            the studentName to set\n     */\n    void setStudentName(String studentName);\n\n    /**\n     * @return the isExceptional\n     */\n    boolean isExceptional();\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    void setExceptional(boolean isExceptional);\n\n    /**\n     * @return the age\n     */\n    int getAge();\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    void setAge(int age);\n\n    /**\n     * @return the semester\n     */\n    char getSemester();\n\n    /**\n     * @param semester\n     *            the semester to set\n     */\n    void setSemester(char semester);\n\n    /**\n     * @return the digitalSignature\n     */\n    byte getDigitalSignature();\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    void setDigitalSignature(byte digitalSignature);\n\n    /**\n     * @return the cgpa\n     */\n    short getCgpa();\n\n    /**\n     * @param cgpa\n     *            the cgpa to set\n     */\n    void setCgpa(short cgpa);\n\n    /**\n     * @return the percentage\n     */\n    float getPercentage();\n\n    /**\n     * @param percentage\n     *            the percentage to set\n     */\n    void setPercentage(float percentage);\n\n    /**\n     * @return the height\n     */\n    double getHeight();\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    void setHeight(double height);\n\n    /**\n     * @return the enrolmentDate\n     */\n    java.util.Date getEnrolmentDate();\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    void setEnrolmentDate(java.util.Date enrolmentDate);\n\n    /**\n     * @return the enrolmentTime\n     */\n    java.util.Date getEnrolmentTime();\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    void setEnrolmentTime(java.util.Date enrolmentTime);\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    java.util.Date getJoiningDateAndTime();\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    void setJoiningDateAndTime(java.util.Date joiningDateAndTime);\n\n    /**\n     * @return the yearsSpent\n     */\n    Integer getYearsSpent();\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    void setYearsSpent(Integer yearsSpent);\n\n    /**\n     * @return the rollNumber\n     */\n    Long getRollNumber();\n\n    /**\n     * @param rollNumber\n     *            the rollNumber to set\n     */\n    void setRollNumber(Long rollNumber);\n\n    /**\n     * @return the monthlyFee\n     */\n    Double getMonthlyFee();\n\n    /**\n     * @param monthlyFee\n     *            the monthlyFee to set\n     */\n    void setMonthlyFee(Double monthlyFee);\n\n    java.sql.Date getSqlDate();\n\n    void setSqlDate(java.sql.Date sqlDate);\n\n    /**\n     * @return the sqlTimestamp\n     */\n    java.sql.Timestamp getSqlTimestamp();\n\n    /**\n     * @param sqlTimestamp\n     *            the sqlTimestamp to set\n     */\n    void setSqlTimestamp(java.sql.Timestamp sqlTimestamp);\n\n    /**\n     * @return the sqlTime\n     */\n    java.sql.Time getSqlTime();\n\n    /**\n     * @param sqlTime\n     *            the sqlTime to set\n     */\n    void setSqlTime(java.sql.Time sqlTime);\n\n    /**\n     * @return the bigInteger\n     */\n    BigInteger getBigInteger();\n\n    /**\n     * @param bigInteger\n     *            the bigInteger to set\n     */\n    void setBigInteger(BigInteger bigInteger);\n\n    /**\n     * @return the bigDecimal\n     */\n    BigDecimal getBigDecimal();\n\n    /**\n     * @param bigDecimal\n     *            the bigDecimal to set\n     */\n    void setBigDecimal(BigDecimal bigDecimal);\n\n    /**\n     * @return the calendar\n     */\n    Calendar getCalendar();\n\n    /**\n     * @param calendar\n     *            the calendar to set\n     */\n    void setCalendar(Calendar calendar);\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/EntityWithCollection.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud.datatypes.entities;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * Entity with collection attribute.\n *\n */\n@Entity\n@Table(name = \"foo_table\")\npublic class EntityWithCollection\n{\n    @Id\n    private String id;\n\n    @Column\n    private Map<String, byte[]> dataMap;\n\n    @Column\n    private Set<byte[]> setAsBytes;\n\n    @Column\n    private List<byte[]> listAsBytes;\n    \n    @Column\n    private byte[] byteData;\n\n    public byte[] getByteData()\n    {\n        return byteData;\n    }\n\n    public void setByteData(byte[] byteData)\n    {\n        this.byteData = byteData;\n    }\n\n    public EntityWithCollection()\n    {\n    }\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public Map<String, byte[]> getDataMap()\n    {\n        return dataMap;\n    }\n\n    public void setDataMap(Map<String, byte[]> dataMap)\n    {\n        this.dataMap = dataMap;\n    }\n\n    public Set<byte[]> getSetAsBytes()\n    {\n        return setAsBytes;\n    }\n\n    public void setSetAsBytes(Set<byte[]> setAsBytes)\n    {\n        this.setAsBytes = setAsBytes;\n    }\n\n    public List<byte[]> getListAsBytes()\n    {\n        return listAsBytes;\n    }\n\n    public void setListAsBytes(List<byte[]> listAsBytes)\n    {\n        this.listAsBytes = listAsBytes;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentBigDecimal.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.math.BigDecimal;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentBigDecimal\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentBigDecimal\n{\n\n    @Id\n    @Column(name = \"STUDENT_ID\")\n    private BigDecimal studentId;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public BigDecimal getStudentId()\n    {\n        return studentId;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setStudentId(BigDecimal studentId)\n    {\n        this.studentId = studentId;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentBigInteger.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.math.BigInteger;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentBigInteger\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentBigInteger {\n\n\t@Id\n\tprivate BigInteger id;\n\n\t@Column(name = \"AGE\")\n\tprivate short age;\n\n\t@Column(name = \"NAME\")\n\tprivate String name;\n\n\t/**\n\t * @return the id\n\t */\n\tpublic BigInteger getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * @param id\n\t *            the id to set\n\t */\n\tpublic void setId(BigInteger id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * @return the age\n\t */\n\tpublic short getAge() {\n\t\treturn age;\n\t}\n\n\t/**\n\t * @param age\n\t *            the age to set\n\t */\n\tpublic void setAge(short age) {\n\t\tthis.age = age;\n\t}\n\n\t/**\n\t * @return the name\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * @param name\n\t *            the name to set\n\t */\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentBooleanPrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentBooleanPrimitive\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentBooleanPrimitive\n{\n    @Id\n    private boolean id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public boolean getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(boolean id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentBooleanWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentBooleanWrapper\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentBooleanWrapper\n{\n    @Id\n    private Boolean id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Boolean getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Boolean id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentBytePrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentBytePrimitive\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentBytePrimitive\n{\n\n    @Id\n    private byte id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentByteWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentByteWrapper\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentByteWrapper\n{\n\n    @Id\n    private Byte id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentCalendar.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.util.Calendar;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentCalendar\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentCalendar\n{\n\n    @Id\n    private Calendar id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Calendar getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Calendar id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentChar.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentChar\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentChar\n{\n\n    @Id\n    private char id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public char getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(char id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentCharacter.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentCharacter\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentCharacter\n{\n    @Id\n    private Character id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Character getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Character id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentDate.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentDate\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentDate\n{\n\n    @Id\n//    @Temporal(TemporalType.DATE)\n    private Date id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentDoublePrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentDoublePrimitive\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentDoublePrimitive\n{\n\n    @Id\n    private double id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public double getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentDoubleWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentDoubleWrapper\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentDoubleWrapper\n{\n\n    @Id\n    private Double id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Double getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentFloatPrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentFloatPrimitive\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentFloatPrimitive\n{\n    @Id\n    private float id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public float getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentFloatWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentFloatWrapper\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentFloatWrapper\n{\n\n    @Id\n    private Float id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Float getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentInt.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentInt\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentInt\n{\n\n    @Id\n    private int id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentInteger.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentInteger\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentInteger\n{\n    @Id\n    private Integer id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Integer getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Integer id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentLongPrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentLongPrimitive\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentLongPrimitive\n{\n\n    @Id\n    private long id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public long getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentLongWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentLongWrapper\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentLongWrapper\n{\n\n    @Id\n    private Long id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Long getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentShortPrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentShortPrimitive\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentShortPrimitive\n{\n\n    @Id\n    private short id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public short getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentShortWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentShortWrapper\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentShortWrapper\n{\n\n    @Id\n    private Short id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Short getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentSqlDate.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.sql.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentSqlDate\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentSqlDate\n{\n\n    @Id\n    private Date id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentString.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentString\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentString\n{\n\n    @Id\n    @Column(name = \"STUDENT_ID\")\n    private String id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentTime.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.sql.Time;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentTime\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentTime\n{\n\n    @Id\n    private Time id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Time getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Time id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentTimestamp.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.sql.Timestamp;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentTimestamp\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentTimestamp\n{\n\n    @Id\n    private Timestamp id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Timestamp getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Timestamp id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/datatypes/entities/StudentUUID.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentUUID\", schema = \"KunderaCassandraDataType@CassandraDataTypeTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentUUID\n{\n\n    @Id\n    private UUID id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public UUID getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(UUID id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/mappedsuperclass/inheritence/CassandraEntityWithoutFieldsTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.mappedsuperclass.inheritence;\n\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.metadata.mappedsuperclass.EntityWithoutFieldsBase;\n\n/**\n * @author amitkumar\n *\n *\tClass to verify that at least one field in entity class is not mandatory if the \n *\tsuperclass contains all the mandatory fields\n */\npublic class CassandraEntityWithoutFieldsTest extends EntityWithoutFieldsBase {\n\n\tprivate static Logger logger = LoggerFactory.getLogger(CassandraEntityWithoutFieldsTest.class);\t\n\n\t@Before\n\tpublic void setup()\n\t{\n\t\tpersistenceUnit = \"CassandraShowQueryDisabledPu\";\n\t\tsetupInternal();\n\t}\n\t\n\t@Test\n\tpublic void testEntityWithNoFields()\n\t{\n\t\ttestEntityWithNoFieldsBase();\n\t}\n\t\n\t@Test\n\tpublic void testEntityWithNoFields2LevelInheritance()\n\t{\n\t\ttestEntityWithNoFields2LevelInheritanceBase();\n\t}\n\n\t@After\n\tpublic void tearDown()\n\t{\n\t\ttearDownInternal();\n\t}\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/mappedsuperclass/inheritence/CassandraMappedSuperClassTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.mappedsuperclass.inheritence;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.MappedSuperclass;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.client.crud.mappedsuperclass.MappedSuperClassBase;\n\n/**\n * @author vivek.mishra\n * junit for {@link MappedSuperclass}, {@link AttributeOverride}, {@link AttributeOverrides}.\n */\npublic class CassandraMappedSuperClassTest extends MappedSuperClassBase\n{\n    \n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        _PU = \"cassandra_pu\";\n        super.setUpInternal();\n    }\n\n    @Test\n    public void test()\n    {\n        assertInternal();\n    }\n\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"KunderaTests\");\n        tearDownInternal();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/crud/mappedsuperclass/inheritence/CassandraMappedSuperClassTestCQL3.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.mappedsuperclass.inheritence;\n\nimport java.util.HashMap;\n\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.client.crud.mappedsuperclass.MappedSuperClassBase;\n\n/**\n * @author Pragalbh Garg\n * \n */\npublic class CassandraMappedSuperClassTestCQL3 extends MappedSuperClassBase\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        _PU = \"cassandra_pu\";\n        CassandraCli.cassandraSetUp();\n        HashMap propertyMap = new HashMap();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void test()\n    {\n        assertInternal();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"KunderaTests\");\n        tearDownInternal();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/entity/PromoCode.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.entity;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\n@Embeddable\r\npublic class PromoCode\r\n{\r\n\r\n    @Column(name = \"promoCode_id\")\r\n    private String promoCodeId;\r\n\r\n    @Column(name = \"promoCode_name\")\r\n    private String promoCodeName;\r\n\r\n    public String getPromoCodeId()\r\n    {\r\n        return promoCodeId;\r\n    }\r\n\r\n    public void setPromoCodeId(String promoCodeId)\r\n    {\r\n        this.promoCodeId = promoCodeId;\r\n    }\r\n\r\n    public String getPromoCodeName()\r\n    {\r\n        return promoCodeName;\r\n    }\r\n\r\n    public void setPromoCodeName(String promoCodeName)\r\n    {\r\n        this.promoCodeName = promoCodeName;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/entity/Users.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.entity;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.ElementCollection;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n@Entity\r\n@Table(name = \"users\", schema = \"KunderaExamples@secIdxCassandraTest\")\r\npublic class Users\r\n{\r\n\r\n    @Id\r\n    protected String userId;\r\n\r\n    @Column\r\n    protected String firstName = \"\";\r\n\r\n    @Column\r\n    protected String lastName = \"\";\r\n\r\n    @ElementCollection\r\n    private List<PromoCode> promoCodes = new ArrayList<PromoCode>();\r\n\r\n    public Users()\r\n    {\r\n    }\r\n\r\n    public String getUserId()\r\n    {\r\n        return userId;\r\n    }\r\n\r\n    public void setUserId(String userId)\r\n    {\r\n        this.userId = userId;\r\n    }\r\n\r\n    public String getFirstName()\r\n    {\r\n        return firstName;\r\n    }\r\n\r\n    public void setFirstName(String firstName)\r\n    {\r\n        this.firstName = firstName;\r\n    }\r\n\r\n    public String getLastName()\r\n    {\r\n        return lastName;\r\n    }\r\n\r\n    public void setLastName(String lastName)\r\n    {\r\n        this.lastName = lastName;\r\n    }\r\n\r\n    public List<PromoCode> getPromoCodes()\r\n    {\r\n        return promoCodes;\r\n    }\r\n\r\n    public void setPromoCodes(List<PromoCode> promoCodes)\r\n    {\r\n        this.promoCodes = promoCodes;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/esindexer/CassandraESAggregationTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n/*\n * author: karthikp.manchala\n */\npackage com.impetus.client.esindexer;\n\nimport javax.persistence.Persistence;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.query.AggregationsBaseTest;\nimport com.impetus.kundera.query.Person;\n\n/**\n * The Class CassandraESAggregationTest.\n * \n * @author karthikp.manchala\n */\npublic class CassandraESAggregationTest extends AggregationsBaseTest\n{\n\n    /** The node. */\n    private static Node node = null;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n    }\n\n    /**\n     * Setup.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    @Before\n    public void setup() throws InterruptedException\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"esIndexerTest\");\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        testAggregation();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (node != null)\n            node.close();\n    }\n\n    /**\n     * Tear down.\n     */\n    @After\n    public void tearDown()\n    {\n        em.remove(em.find(Person.class, \"1\"));\n        em.remove(em.find(Person.class, \"2\"));\n        em.remove(em.find(Person.class, \"3\"));\n        em.remove(em.find(Person.class, \"4\"));\n        em.close();\n        emf.close();\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/esindexer/CassandraESGroupByTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.esindexer;\n\nimport javax.persistence.Persistence;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.query.GroupByBaseTest;\n\n/**\n * The Class CassandraESGroupByTest.\n * \n * @author karthikp.manchala\n * \n */\npublic class CassandraESGroupByTest extends GroupByBaseTest\n{\n\n    /** The node. */\n    private static Node node = null;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n\n        emf = Persistence.createEntityManagerFactory(\"esIndexerTest\");\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Test aggregation.\n     */\n    @Test\n    public void test()\n    {\n        testAggregation();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        em.createQuery(\"Delete from Person p\").executeUpdate();\n        waitThread();\n\n        em.close();\n        emf.close();\n\n        if (node != null)\n            node.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/esindexer/CassandraESOrderByTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.esindexer;\n\nimport javax.persistence.Persistence;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.query.OrderByBaseTest;\n\n/**\n * The Class CassandraESOrderByTest.\n * \n * @author Amit Kumar\n */\npublic class CassandraESOrderByTest extends OrderByBaseTest\n{\n\n    /** The node. */\n    private static Node node = null;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n\n        emf = Persistence.createEntityManagerFactory(\"esIndexerTest\");\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Test Order By.\n     */\n    @Test\n    public void test()\n    {\n        testQuery();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        em.createQuery(\"Delete from Person p\").executeUpdate();\n        waitThread();\n\n        em.close();\n        emf.close();\n\n        if (node != null)\n            node.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/esindexer/PersonCassandraESIndexerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.esindexer;\n\nimport java.nio.ByteBuffer;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport javax.persistence.TypedQuery;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.ColumnOrSuperColumn;\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.Mutation;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.thrift.CQLTranslator;\nimport com.impetus.client.crud.BaseTest;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\n\n/**\n * Test case to perform simple CRUD operation.(insert, delete, merge, and select)\n * \n * @author kuldeep.mishra\n * \n *         Run this script to create column family in cassandra with indexes. create column family PERSON_ESINDEXER with\n *         comparator=UTF8Type and column_metadata=[{column_name: PERSON_NAME, validation_class: UTF8Type, index_type:\n *         KEYS}, {column_name: AGE, validation_class: IntegerType, index_type: KEYS}];\n * \n */\npublic class PersonCassandraESIndexerTest extends BaseTest {\n\n    /** The Constant _PU. */\n    private static final String _PU = \"esIndexerTest\";\n\n    /** The Constant USE_CQL. */\n    protected static boolean USE_CQL = false;\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The col. */\n    private Map<Object, Object> col;\n\n    /** The node. */\n    private static Node node = null;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception {\n        Builder builder = Settings.settingsBuilder();\n        builder.put(\"path.home\", \"target/data\");\n        node = new NodeBuilder().settings(builder).node();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception {\n        node.close();\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception {\n\n        Map propertyMap = new HashMap();\n        if (USE_CQL) {\n            propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        }\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n        em = emf.createEntityManager();\n        col = new java.util.HashMap<Object, Object>();\n    }\n    \n    @Test\n    public void indexDeletionTest() throws Exception\n    {\n        em.createQuery(\"DELETE FROM PersonESIndexerCassandra p\").executeUpdate();\n        Thread.sleep(1000);\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 30);\n        Object p4 = prepare(\"4\", 40);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        em.persist(p4);\n        Thread.sleep(1000);\n        String query = \"Select min(p.age) from PersonESIndexerCassandra p\";\n        List resultList = em.createQuery(query).getResultList();\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(10.0, resultList.get(0));\n        \n        em.remove(p1);\n        Thread.sleep(1000);\n        query = \"Select min(p.age) from PersonESIndexerCassandra p\";\n        resultList = em.createQuery(query).getResultList();\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(20.0, resultList.get(0));;\n        \n        em.remove(p2);\n        Thread.sleep(1000);\n        query = \"Select min(p.age) from PersonESIndexerCassandra p\";\n        resultList = em.createQuery(query).getResultList();\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(30.0, resultList.get(0));\n        \n        em.createQuery(\"DELETE FROM PersonESIndexerCassandra p\").executeUpdate();\n    }\n\n    /**\n     * On insert cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onInsertCassandra() throws Exception {\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        waitThread();\n        em.clear();\n        PersonESIndexerCassandra p = findById(PersonESIndexerCassandra.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n\n        em.clear();\n        String qry = \"Select p.personId,p.personName from PersonESIndexerCassandra p where p.personId >= 1\";\n        Query q = em.createQuery(qry);\n        List<PersonESIndexerCassandra> persons = q.getResultList();\n\n        assertFindByName(em, \"PersonESIndexerCassandra\", PersonESIndexerCassandra.class, \"vivek\", \"personName\");\n        assertFindByNameAndAge(em, \"PersonESIndexerCassandra\", PersonESIndexerCassandra.class, \"vivek\", \"10\",\n            \"personName\");\n        assertFindByNameAndAgeGTAndLT(em, \"PersonESIndexerCassandra\", PersonESIndexerCassandra.class, \"vivek\", \"10\",\n            \"20\", \"personName\");\n        assertFindByNameAndAgeBetween(em, \"PersonESIndexerCassandra\", PersonESIndexerCassandra.class, \"vivek\", \"10\",\n            \"15\", \"personName\");\n        assertFindByRange(em, \"PersonESIndexerCassandra\", PersonESIndexerCassandra.class, \"1\", \"2\", \"personId\", false);\n        assertFindWithoutWhereClause(em, \"PersonESIndexerCassandra\", PersonESIndexerCassandra.class, false);\n\n        // OR clause test case.\n        String orClauseQuery = \"Select p from PersonESIndexerCassandra p where p.personName = 'vivek1' OR p.age = 10\";\n\n        q = em.createQuery(orClauseQuery);\n\n        List<PersonESIndexerCassandra> results = q.getResultList();\n\n        Assert.assertEquals(1, results.size());\n        // perform merge after query.\n        for (PersonESIndexerCassandra person : persons) {\n            person.setPersonName(\"after merge\");\n            em.merge(person);\n        }\n        em.clear();\n\n        p = findById(PersonESIndexerCassandra.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"after merge\", p.getPersonName());\n\n        // Delete without WHERE clause.\n\n        String deleteQuery = \"DELETE from PersonESIndexerCassandra\";\n        q = em.createQuery(deleteQuery);\n        Assert.assertEquals(3, q.executeUpdate());\n    }\n\n    /**\n     * On merge cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onMergeCassandra() throws Exception {\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        waitThread();\n        em.clear();\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        PersonESIndexerCassandra p = findById(PersonESIndexerCassandra.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        // modify record.\n        p.setPersonName(\"newvivek\");\n        em.merge(p);\n        waitThread();\n        assertOnMerge(em, \"PersonESIndexerCassandra\", \"vivek\", \"newvivek\", \"personName\");\n    }\n\n    /**\n     * On delete then insert cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onDeleteThenInsertCassandra() throws Exception {\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        waitThread();\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        PersonESIndexerCassandra p = findById(PersonESIndexerCassandra.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        em.remove(p);\n        em.clear();\n        waitThread();\n        TypedQuery<PersonESIndexerCassandra> query =\n            em.createQuery(\"Select p from PersonESIndexerCassandra p\", PersonESIndexerCassandra.class);\n\n        List<PersonESIndexerCassandra> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        p1 = prepare(\"1\", 10);\n        em.persist(p1);\n\n        waitThread();\n\n        query = em.createQuery(\"Select p from PersonESIndexerCassandra p\", PersonESIndexerCassandra.class);\n\n        results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n\n    }\n\n    /**\n     * On refresh cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onRefreshCassandra() throws Exception {\n        CassandraCli.cassandraSetUp();\n        // loadData();\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        waitThread();\n        // Check for contains\n        Object pp1 = prepare(\"1\", 10);\n        Object pp2 = prepare(\"2\", 20);\n        Object pp3 = prepare(\"3\", 15);\n        Assert.assertTrue(em.contains(pp1));\n        Assert.assertTrue(em.contains(pp2));\n        Assert.assertTrue(em.contains(pp3));\n\n        // Check for detach\n        em.detach(pp1);\n        em.detach(pp2);\n        Assert.assertFalse(em.contains(pp1));\n        Assert.assertFalse(em.contains(pp2));\n        Assert.assertTrue(em.contains(pp3));\n\n        // Modify value in database directly, refresh and then check PC\n        em.clear();\n        em = emf.createEntityManager();\n        Object o1 = em.find(PersonESIndexerCassandra.class, \"1\");\n\n        if (!USE_CQL) {\n            // Create Insertion List\n            List<Mutation> insertionList = new ArrayList<Mutation>();\n            List<Column> columns = new ArrayList<Column>();\n            Column column = new Column();\n            column.setName(PropertyAccessorFactory.STRING.toBytes(\"PERSON_NAME\"));\n            column.setValue(PropertyAccessorFactory.STRING.toBytes(\"Amry\"));\n            column.setTimestamp(System.currentTimeMillis());\n            columns.add(column);\n            Mutation mut = new Mutation();\n            mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setColumn(column));\n            insertionList.add(mut);\n            // Create Mutation Map\n            Map<String, List<Mutation>> columnFamilyValues = new HashMap<String, List<Mutation>>();\n            columnFamilyValues.put(\"PERSON_ESINDEXER\", insertionList);\n            Map<ByteBuffer, Map<String, List<Mutation>>> mulationMap =\n                new HashMap<ByteBuffer, Map<String, List<Mutation>>>();\n            mulationMap.put(ByteBuffer.wrap(\"1\".getBytes()), columnFamilyValues);\n            CassandraCli.client.batch_mutate(mulationMap, ConsistencyLevel.ONE);\n        } else {\n            CQLTranslator translator = new CQLTranslator();\n            String query =\n                \"insert into \\\"PERSON_ESINDEXER\\\" (\\\"personId\\\",\\\"PERSON_NAME\\\",\\\"AGE\\\") values ('1','Amry','10')\";\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(query.getBytes()), Compression.NONE,\n                ConsistencyLevel.ONE);\n        }\n\n        em.refresh(o1);\n        Object oo1 = em.find(PersonESIndexerCassandra.class, \"1\");\n        Assert.assertTrue(em.contains(o1));\n        Assert.assertEquals(\"Amry\", ((PersonESIndexerCassandra) oo1).getPersonName());\n    }\n\n    /**\n     * On typed create query.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onTypedQuery() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n        SchemaDisagreementException {\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        waitThread();\n        TypedQuery<PersonESIndexerCassandra> query =\n            em.createQuery(\"Select p from PersonESIndexerCassandra p\", PersonESIndexerCassandra.class);\n\n        List<PersonESIndexerCassandra> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n    }\n\n    /**\n     * On typed create query.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onGenericTypedQuery() throws TException, InvalidRequestException, UnavailableException,\n        TimedOutException, SchemaDisagreementException {\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        waitThread();\n        TypedQuery<Object> query = em.createQuery(\"Select p from PersonESIndexerCassandra p\", Object.class);\n\n        List<Object> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(PersonESIndexerCassandra.class, results.get(0).getClass());\n    }\n\n    /**\n     * On ghost rows.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onGhostRows() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n        SchemaDisagreementException {\n        Object p1 = prepare(\"1\", 10);\n        Object p2 = prepare(\"2\", 20);\n        Object p3 = prepare(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        em.clear();\n        waitThread();\n        PersonESIndexerCassandra person = em.find(PersonESIndexerCassandra.class, \"1\");\n        em.remove(person);\n        em.clear(); // just to make sure that not to be picked up from cache.\n        waitThread();\n        TypedQuery<PersonESIndexerCassandra> query =\n            em.createQuery(\"Select p from PersonESIndexerCassandra p\", PersonESIndexerCassandra.class);\n\n        List<PersonESIndexerCassandra> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n    }\n\n    // added, test for like queries and matchmode with '%'\n    /**\n     * Test like query.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void testLikeQuery() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n        SchemaDisagreementException {\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n        Object p1 = prepare(10, \"karthik\");\n        Object p2 = prepare(20, \"viveek\");\n        Object p3 = prepare(15, \"kartheek\");\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        em.clear();\n        waitThread();\n        // test left\n        TypedQuery<PersonESIndexerCassandraUUID> query =\n            em.createQuery(\"Select p from PersonESIndexerCassandraUUID p where p.personName like :name\",\n                PersonESIndexerCassandraUUID.class);\n        query.setParameter(\"name\", \"%eek\");\n\n        List<PersonESIndexerCassandraUUID> results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotSame(\"karthik\", results.get(0).getPersonName());\n        Assert.assertNotSame(\"karthik\", results.get(1).getPersonName());\n\n        if (results.get(0).getAge().equals(\"20\")) {\n            Assert.assertEquals(\"viveek\", results.get(0).getPersonName());\n            Assert.assertEquals(\"kartheek\", results.get(1).getPersonName());\n        } else {\n            Assert.assertEquals(\"kartheek\", results.get(0).getPersonName());\n            Assert.assertEquals(\"viveek\", results.get(1).getPersonName());\n        }\n\n        // test right\n        query =\n            em.createQuery(\"Select p from PersonESIndexerCassandraUUID p where p.personName like :name\",\n                PersonESIndexerCassandraUUID.class);\n        query.setParameter(\"name\", \"kar%\");\n\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotSame(\"viveek\", results.get(0).getPersonName());\n        Assert.assertNotSame(\"viveek\", results.get(1).getPersonName());\n\n        if (results.get(0).getAge().equals(\"10\")) {\n            Assert.assertEquals(\"karthik\", results.get(0).getPersonName());\n            Assert.assertEquals(\"kartheek\", results.get(1).getPersonName());\n        } else {\n            Assert.assertEquals(\"kartheek\", results.get(0).getPersonName());\n            Assert.assertEquals(\"karthik\", results.get(1).getPersonName());\n        }\n\n        // test default\n        query =\n            em.createQuery(\"Select p from PersonESIndexerCassandraUUID p where p.personName like :name\",\n                PersonESIndexerCassandraUUID.class);\n        query.setParameter(\"name\", \"viv\");\n\n        results = query.getResultList();\n        Assert.assertEquals(\"viveek\", results.get(0).getPersonName());\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // test both\n        query =\n            em.createQuery(\"Select p from PersonESIndexerCassandraUUID p where p.personName like :name\",\n                PersonESIndexerCassandraUUID.class);\n        query.setParameter(\"name\", \"%art%\");\n\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotSame(\"viveek\", results.get(0).getPersonName());\n        Assert.assertNotSame(\"viveek\", results.get(1).getPersonName());\n\n        if (results.get(0).getAge().equals(\"10\")) {\n            Assert.assertEquals(\"karthik\", results.get(0).getPersonName());\n            Assert.assertEquals(\"kartheek\", results.get(1).getPersonName());\n        } else {\n            Assert.assertEquals(\"kartheek\", results.get(0).getPersonName());\n            Assert.assertEquals(\"karthik\", results.get(1).getPersonName());\n        }\n\n    }\n\n    // added, test for '>' on datatype Timestamp\n    /**\n     * Test operators.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void testOperators() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n        SchemaDisagreementException {\n\n        Object p1 = prepare(10, \"karthik\", new Timestamp(9419290317914l));\n        Object p2 = prepare(20, \"vivek\", new Timestamp(new Date().getTime()));\n        Object p3 = prepare(15, \"pragalbh\", new Timestamp(1418290317914l));\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        em.clear();\n        waitThread();\n        TypedQuery<PersonESIndexerCassandraUUID> query =\n            em.createQuery(\"Select p from PersonESIndexerCassandraUUID p where p.date > :date\",\n                PersonESIndexerCassandraUUID.class).setParameter(\"date\", new Timestamp(new Date().getTime()).getTime());\n        List<PersonESIndexerCassandraUUID> results = query.getResultList();\n        java.util.Iterator<PersonESIndexerCassandraUUID> i = results.iterator();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n    }\n\n    // added, test for partition keys of type UUID\n    /**\n     * Test uuid.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void testUUID() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n        SchemaDisagreementException {\n\n        Object p1 = prepare(10, \"karthik\");\n        Object p2 = prepare(20, \"vivek\");\n        Object p3 = prepare(15, \"pragalbh\");\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        em.clear();\n        waitThread();\n        TypedQuery<PersonESIndexerCassandraUUID> query =\n            em.createQuery(\"Select p from PersonESIndexerCassandraUUID p\", PersonESIndexerCassandraUUID.class);\n        List<PersonESIndexerCassandraUUID> results = query.getResultList();\n        java.util.Iterator<PersonESIndexerCassandraUUID> i = results.iterator();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception {\n\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param rowKey\n     *            the row key\n     * @param age\n     *            the age\n     * @return the person\n     */\n    private PersonESIndexerCassandra prepare(String rowKey, int age) {\n        PersonESIndexerCassandra o = new PersonESIndexerCassandra();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age);\n        o.setDay(PersonESIndexerCassandra.Day.MONDAY);\n        return o;\n    }\n\n    /**\n     * Prepare.\n     * \n     * @param age\n     *            the age\n     * @param name\n     *            the name\n     * @return the person es indexer cassandra uuid\n     */\n    private PersonESIndexerCassandraUUID prepare(int age, String name) {\n        PersonESIndexerCassandraUUID o = new PersonESIndexerCassandraUUID();\n        UUID z = UUID.randomUUID();\n        o.setPersonId(z);\n        o.setPersonName(name);\n        o.setAge(age + \"\");\n        o.setDay(PersonESIndexerCassandraUUID.Day.MONDAY);\n        return o;\n    }\n\n    /**\n     * Prepare.\n     * \n     * @param age\n     *            the age\n     * @param name\n     *            the name\n     * @return the person es indexer cassandra uuid\n     */\n    private PersonESIndexerCassandraUUID prepare(int age, String name, Timestamp time) {\n        PersonESIndexerCassandraUUID o = new PersonESIndexerCassandraUUID();\n        UUID z = UUID.randomUUID();\n        o.setPersonId(z);\n        o.setPersonName(name);\n        o.setDate(time);\n        o.setAge(age + \"\");\n        return o;\n    }\n\n    /**\n     * Assert on merge.\n     * \n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param oldName\n     *            the old name\n     * @param newName\n     *            the new name\n     * @param fieldName\n     *            the field name\n     */\n    private void assertOnMerge(EntityManager em, String clazz, String oldName, String newName, String fieldName) {\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + oldName);\n        List<PersonESIndexerCassandra> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + newName);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotSame(oldName, getPersonName(results.get(0)));\n        Assert.assertEquals(newName, getPersonName(results.get(0)));\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @param result\n     *            the result\n     * @return the person name\n     */\n    private String getPersonName(Object result) {\n\n        return ((PersonESIndexerCassandra) result).getPersonName();\n    }\n\n    /**\n     * Wait thread.\n     */\n    private void waitThread() {\n        try {\n            Thread.sleep(2000);\n        } catch (InterruptedException e) {\n\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/esindexer/PersonCassandraESIndexerTestCQL3.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.esindexer;\n\nimport org.junit.After;\nimport org.junit.Before;\n\n/**\n * The Class PersonCassandraESIndexerTestCQL3.\n * \n * @author karthikp.manchala\n */\npublic class PersonCassandraESIndexerTestCQL3 extends PersonCassandraESIndexerTest {\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n\n    @Before\n    public void setUp() throws Exception {\n        super.USE_CQL = true;\n        super.setUp();\n    }\n\n    /**\n     * tears down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n\n    @After\n    public void tearDown() throws Exception {\n        super.tearDown();\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/esindexer/PersonESIndexerCassandra.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.esindexer;\n\nimport java.sql.Timestamp;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON_ESINDEXER\", schema = \"KunderaExamples@esIndexerTest\")\n@IndexCollection(columns = { @com.impetus.kundera.index.Index(name = \"personName\"),\n        @com.impetus.kundera.index.Index(name = \"age\"), @com.impetus.kundera.index.Index(name = \"date\"),@com.impetus.kundera.index.Index(name = \"salary\") })\npublic class PersonESIndexerCassandra\n{\n\n    private static final long serialVersionUID = 6068131491098913126L;\n\n    public static final String UID = \"uid\";\n\n    public static final String EID = \"eid\";\n\n    public static final String FIRST_NAME = \"firstName\";\n\n    public static final String LAST_NAME = \"lastName\";\n\n    public static final String CITY = \"city\";\n\n    public static final String CREATED = \"created\";\n\n    public static final String LAST_MODIFIED = \"lastModified\";\n\n    /** The person id. */\n    @Id\n    // @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n    \n    @Column\n    private Double salary;\n\n    public Double getSalary()\n    {\n        return salary;\n    }\n\n    public void setSalary(Double salary)\n    {\n        this.salary = salary;\n    }\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n    \n    @Column(name = \"DATE\")\n    private Timestamp date;\n\n    public Timestamp getDate() {\n\t\treturn date;\n\t}\n\n\tpublic void setDate(Timestamp date) {\n\t\tthis.date = date;\n\t}\n\n//\t@Column(name = \"AGEss\")\n//    private byte[] a;\n\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    /**\n     * @return the a\n     */\n//    public byte[] getA()\n//    {\n//        return a;\n//    }\n//\n//    /**\n//     * @param a\n//     *            the a to set\n//     */\n//    public void setA(byte[] a)\n//    {\n//        this.a = a;\n//    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(Integer age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the day\n     */\n    public Day getDay()\n    {\n        return day;\n    }\n\n    /**\n     * @param day\n     *            the day to set\n     */\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n\n    enum Day\n    {\n        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/esindexer/PersonESIndexerCassandraUUID.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.esindexer;\n\nimport java.sql.Timestamp;\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSON_ESINDEXERUUID\", schema = \"KunderaExamples@esIndexerTest\")\n@IndexCollection(columns = { @com.impetus.kundera.index.Index(name = \"personName\"),\n    @com.impetus.kundera.index.Index(name = \"age\"), @com.impetus.kundera.index.Index(name = \"date\") })\npublic class PersonESIndexerCassandraUUID {\n\n    private static final long serialVersionUID = 6068131491098913126L;\n\n    public static final String UID = \"uid\";\n\n    public static final String EID = \"eid\";\n\n    public static final String FIRST_NAME = \"firstName\";\n\n    public static final String LAST_NAME = \"lastName\";\n\n    public static final String CITY = \"city\";\n\n    public static final String CREATED = \"created\";\n\n    public static final String LAST_MODIFIED = \"lastModified\";\n\n    /** The person id. */\n    @Id\n    // @Column(name = \"PERSON_ID\")\n    private UUID personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private String age;\n\n    @Column(name = \"DATE\")\n    private Timestamp date;\n\n    public Timestamp getDate() {\n        return date;\n    }\n\n    public void setDate(Timestamp date) {\n        this.date = date;\n    }\n\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public UUID getPersonId() {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName() {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName) {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(UUID personId) {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public String getAge() {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(String age) {\n        this.age = age;\n    }\n\n    /**\n     * @return the day\n     */\n    public Day getDay() {\n        return day;\n    }\n\n    /**\n     * @param day\n     *            the day to set\n     */\n    public void setDay(Day day) {\n        this.day = day;\n    }\n\n    enum Day {\n        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/CassandraGeneratedIdCqlTest.java",
    "content": "package com.impetus.client.generatedId;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\n\npublic class CassandraGeneratedIdCqlTest extends CassandraGeneratedIdTest\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        properties.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        super.setUp();\n    }\n\n    @Test\n    public void testPersist(){\n    \tsuper.testPersist();\n    }\n    \n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/CassandraGeneratedIdTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.generatedId;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.thrift.ThriftClient;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdDefault;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdStrategyAuto;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdStrategyIdentity;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdStrategySequence;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdStrategyTable;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdWithOutSequenceGenerator;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdWithOutTableGenerator;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdWithSequenceGenerator;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdWithTableGenerator;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class CassandraGeneratedIdTest\n{\n    private EntityManagerFactory emf;\n\n    protected Map<String, String> properties = new HashMap<String, String>();\n\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        if (properties.isEmpty())\n        {\n            emf = Persistence.createEntityManagerFactory(\"cassandra_generated_id\");\n        }\n        else\n        {\n            emf = Persistence.createEntityManagerFactory(\"cassandra_generated_id\", properties);\n        }\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n//    @Test\n    //TODO: TimedOutException (acknowledged_by:0), to be resolved\n    public void testPersist()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        try\n        {\n            CassandraGeneratedIdDefault idDefault = new CassandraGeneratedIdDefault();\n            idDefault.setName(\"kuldeep\");\n            em.persist(idDefault);\n            List<CassandraGeneratedIdDefault> list = em.createQuery(\"Select c from CassandraGeneratedIdDefault c\")\n                    .getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"kuldeep\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            idDefault = em.find(CassandraGeneratedIdDefault.class, id);\n            Assert.assertNotNull(idDefault);\n            Assert.assertEquals(\"kuldeep\", idDefault.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n\n        try\n        {\n            CassandraGeneratedIdStrategyAuto strategyAuto = new CassandraGeneratedIdStrategyAuto();\n            strategyAuto.setName(\"kuldeep\");\n            em.persist(strategyAuto);\n            List<CassandraGeneratedIdStrategyAuto> list = em.createQuery(\n                    \"Select c from CassandraGeneratedIdStrategyAuto c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"kuldeep\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            strategyAuto = em.find(CassandraGeneratedIdStrategyAuto.class, id);\n            Assert.assertNotNull(strategyAuto);\n            Assert.assertEquals(\"kuldeep\", strategyAuto.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n\n        try\n        {\n            CassandraGeneratedIdStrategyIdentity strategyIdentity = new CassandraGeneratedIdStrategyIdentity();\n            strategyIdentity.setName(\"kuldeep\");\n            em.persist(strategyIdentity);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.UnsupportedOperationException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.IDENTITY + \" Strategy not supported by this client :\"\n                            + ThriftClient.class.getName(), e.getMessage());\n        }\n\n        try\n        {\n            CassandraGeneratedIdStrategySequence strategySequence = new CassandraGeneratedIdStrategySequence();\n            strategySequence.setName(\"Kuldeep\");\n            em.persist(strategySequence);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + ThriftClient.class.getName(), e.getMessage());\n        }\n\n        try\n        {\n            CassandraGeneratedIdStrategyTable strategyTable = new CassandraGeneratedIdStrategyTable();\n            strategyTable.setName(\"KK\");\n            em.persist(strategyTable);\n            List<CassandraGeneratedIdStrategyTable> list = em.createQuery(\n                    \"Select c from CassandraGeneratedIdStrategyTable c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"KK\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            strategyTable = em.find(CassandraGeneratedIdStrategyTable.class, id);\n            Assert.assertNotNull(strategyTable);\n            Assert.assertEquals(\"KK\", strategyTable.getName());\n\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n\n        try\n        {\n            CassandraGeneratedIdWithOutSequenceGenerator withOutSequenceGenerator = new CassandraGeneratedIdWithOutSequenceGenerator();\n            withOutSequenceGenerator.setName(\"Kuldeep Kumar\");\n            em.persist(withOutSequenceGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + ThriftClient.class.getName(), e.getMessage());\n        }\n\n        try\n        {\n            CassandraGeneratedIdWithOutTableGenerator withOutTableGenerator = new CassandraGeneratedIdWithOutTableGenerator();\n            withOutTableGenerator.setName(\"Kuldeep Mishra\");\n            em.persist(withOutTableGenerator);\n            List<CassandraGeneratedIdWithOutTableGenerator> list = em.createQuery(\n                    \"Select c from CassandraGeneratedIdWithOutTableGenerator c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"Kuldeep Mishra\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            withOutTableGenerator = em.find(CassandraGeneratedIdWithOutTableGenerator.class, id);\n            Assert.assertNotNull(withOutTableGenerator);\n            Assert.assertEquals(\"Kuldeep Mishra\", withOutTableGenerator.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n        try\n        {\n            CassandraGeneratedIdWithSequenceGenerator withSequenceGenerator = new CassandraGeneratedIdWithSequenceGenerator();\n            withSequenceGenerator.setName(\"Kuldeep Kumar Mishra\");\n            em.persist(withSequenceGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + ThriftClient.class.getName(), e.getMessage());\n        }\n        try\n        {\n            CassandraGeneratedIdWithTableGenerator withTableGenerator = new CassandraGeneratedIdWithTableGenerator();\n            withTableGenerator.setName(\"Kumar Mishra\");\n            em.persist(withTableGenerator);\n            List<CassandraGeneratedIdWithTableGenerator> list = em.createQuery(\n                    \"Select c from CassandraGeneratedIdWithTableGenerator c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"Kumar Mishra\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            withTableGenerator = em.find(CassandraGeneratedIdWithTableGenerator.class, id);\n            Assert.assertNotNull(withTableGenerator);\n            Assert.assertEquals(\"Kumar Mishra\", withTableGenerator.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/CustomGeneratedIdTest.java",
    "content": "package com.impetus.client.generatedId;\n\n/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.thrift.ThriftClient;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdDefault;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdStrategyAuto;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdStrategyIdentity;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdStrategySequence;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdStrategyTable;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdWithOutSequenceGenerator;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdWithOutTableGenerator;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdWithSequenceGenerator;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdWithTableGenerator;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class CustomGeneratedIdTest\n{\n\n    private EntityManagerFactory emf;\n\n    protected Map<String, String> properties = new HashMap<String, String>();\n\n    @Before\n    public void setUp() throws Exception\n    {\n        properties.put(PersistenceProperties.KUNDERA_AUTO_GENERATOR_CLASS, \"com.impetus.client.generatedId.CustomIdGenerator\");\n        CassandraCli.cassandraSetUp();\n        if (properties.isEmpty())\n        {\n            emf = Persistence.createEntityManagerFactory(\"cassandra_generated_id\");\n        }\n        else\n        {\n            emf = Persistence.createEntityManagerFactory(\"cassandra_generated_id\", properties);\n        }\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testPersist()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        try\n        {\n            CassandraGeneratedIdDefault idDefault = new CassandraGeneratedIdDefault();\n            idDefault.setName(\"kuldeep\");\n            em.persist(idDefault);\n            List<CassandraGeneratedIdDefault> list = em.createQuery(\"Select c from CassandraGeneratedIdDefault c\")\n                    .getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"kuldeep\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            \n            idDefault = em.find(CassandraGeneratedIdDefault.class, id);\n            Assert.assertNotNull(idDefault);\n            Assert.assertEquals(\"kuldeep\", idDefault.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n\n        try\n        {\n            CassandraGeneratedIdStrategyAuto strategyAuto = new CassandraGeneratedIdStrategyAuto();\n            strategyAuto.setName(\"kuldeep\");\n            em.persist(strategyAuto);\n            List<CassandraGeneratedIdStrategyAuto> list = em.createQuery(\n                    \"Select c from CassandraGeneratedIdStrategyAuto c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"kuldeep\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            strategyAuto = em.find(CassandraGeneratedIdStrategyAuto.class, id);\n            Assert.assertNotNull(strategyAuto);\n            Assert.assertEquals(\"kuldeep\", strategyAuto.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n\n        try\n        {\n            CassandraGeneratedIdStrategyIdentity strategyIdentity = new CassandraGeneratedIdStrategyIdentity();\n            strategyIdentity.setName(\"kuldeep\");\n            em.persist(strategyIdentity);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.UnsupportedOperationException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.IDENTITY + \" Strategy not supported by this client :\"\n                            + ThriftClient.class.getName(), e.getMessage());\n        }\n\n        try\n        {\n            CassandraGeneratedIdStrategySequence strategySequence = new CassandraGeneratedIdStrategySequence();\n            strategySequence.setName(\"Kuldeep\");\n            em.persist(strategySequence);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + ThriftClient.class.getName(), e.getMessage());\n        }\n\n        try\n        {\n            CassandraGeneratedIdStrategyTable strategyTable = new CassandraGeneratedIdStrategyTable();\n            strategyTable.setName(\"KK\");\n            em.persist(strategyTable);\n            List<CassandraGeneratedIdStrategyTable> list = em.createQuery(\n                    \"Select c from CassandraGeneratedIdStrategyTable c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"KK\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            strategyTable = em.find(CassandraGeneratedIdStrategyTable.class, id);\n            Assert.assertNotNull(strategyTable);\n            Assert.assertEquals(\"KK\", strategyTable.getName());\n\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n\n        try\n        {\n            CassandraGeneratedIdWithOutSequenceGenerator withOutSequenceGenerator = new CassandraGeneratedIdWithOutSequenceGenerator();\n            withOutSequenceGenerator.setName(\"Kuldeep Kumar\");\n            em.persist(withOutSequenceGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + ThriftClient.class.getName(), e.getMessage());\n        }\n\n        try\n        {\n            CassandraGeneratedIdWithOutTableGenerator withOutTableGenerator = new CassandraGeneratedIdWithOutTableGenerator();\n            withOutTableGenerator.setName(\"Kuldeep Mishra\");\n            em.persist(withOutTableGenerator);\n            List<CassandraGeneratedIdWithOutTableGenerator> list = em.createQuery(\n                    \"Select c from CassandraGeneratedIdWithOutTableGenerator c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"Kuldeep Mishra\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            withOutTableGenerator = em.find(CassandraGeneratedIdWithOutTableGenerator.class, id);\n            Assert.assertNotNull(withOutTableGenerator);\n            Assert.assertEquals(\"Kuldeep Mishra\", withOutTableGenerator.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n        try\n        {\n            CassandraGeneratedIdWithSequenceGenerator withSequenceGenerator = new CassandraGeneratedIdWithSequenceGenerator();\n            withSequenceGenerator.setName(\"Kuldeep Kumar Mishra\");\n            em.persist(withSequenceGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + ThriftClient.class.getName(), e.getMessage());\n        }\n        try\n        {\n            CassandraGeneratedIdWithTableGenerator withTableGenerator = new CassandraGeneratedIdWithTableGenerator();\n            withTableGenerator.setName(\"Kumar Mishra\");\n            em.persist(withTableGenerator);\n            List<CassandraGeneratedIdWithTableGenerator> list = em.createQuery(\n                    \"Select c from CassandraGeneratedIdWithTableGenerator c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"Kumar Mishra\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            withTableGenerator = em.find(CassandraGeneratedIdWithTableGenerator.class, id);\n            Assert.assertNotNull(withTableGenerator);\n            Assert.assertEquals(\"Kumar Mishra\", withTableGenerator.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/CustomIdGenerator.java",
    "content": "package com.impetus.client.generatedId;\n\nimport java.util.Random;\n\nimport org.apache.cassandra.thrift.Cassandra;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.generator.AutoGenerator;\nimport com.impetus.kundera.generator.TableGenerator;\nimport com.impetus.kundera.metadata.model.TableGeneratorDiscriptor;\n\npublic class CustomIdGenerator implements AutoGenerator, TableGenerator\n{\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(CustomIdGenerator.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.AutoGenerator#generate(com.impetus.kundera\n     * .client.Client, java.lang.Object)\n     */\n    @Override\n    public Object generate(Client<?> client, String dataType)\n    {\n               \n            return java.util.UUID.randomUUID();\n\n        \n    }\n\n    @Override\n    public Object generate(TableGeneratorDiscriptor discriptor, ClientBase client, String dataType)\n    {\n        Cassandra.Client conn = ((CassandraClientBase) client).getRawClient(discriptor.getSchema());\n        long latestCount = 0l;\n        Random random = new Random();\n        if (latestCount == 0)\n        {\n            return (long) discriptor.getInitialValue();\n        }\n        else\n        {\n            latestCount = random.nextLong();\n            return (latestCount + 1) * discriptor.getAllocationSize();\n        }\n    }\n\n   \n\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/entites/CassandraGeneratedIdDefault.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"CassandraGeneratedIdDefault\", schema = \"kunderaGeneratedId@cassandra_generated_id\")\npublic class CassandraGeneratedIdDefault\n{\n    @Id\n    @GeneratedValue\n    private UUID id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public UUID getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(UUID id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/entites/CassandraGeneratedIdStrategyAuto.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"CassandraGeneratedIdStrategyAuto\", schema = \"kunderaGeneratedId@cassandra_generated_id\")\n@TableGenerator(name = \"id_gen\")\npublic class CassandraGeneratedIdStrategyAuto\n{\n    @Id\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.AUTO)\n    private UUID id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public UUID getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(UUID id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/entites/CassandraGeneratedIdStrategyIdentity.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"CassandraGeneratedIdStrategyIdentity\", schema = \"kunderaGeneratedId@cassandra_generated_id\")\npublic class CassandraGeneratedIdStrategyIdentity\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/entites/CassandraGeneratedIdStrategySequence.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"CassandraGeneratedIdStrategySequence\", schema = \"kunderaGeneratedId@cassandra_generated_id\")\npublic class CassandraGeneratedIdStrategySequence\n{\n    @Id\n    @SequenceGenerator(name = \"seq_gen\")\n    @GeneratedValue(generator = \"seq_gen\", strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/entites/CassandraGeneratedIdStrategyTable.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"CassandraGeneratedIdStrategyTable\", schema = \"kunderaGeneratedId@cassandra_generated_id\")\n@TableGenerator(name = \"table_gen\")\npublic class CassandraGeneratedIdStrategyTable\n{\n\n    @Id\n    @TableGenerator(name = \"table_gen_1\")\n    @GeneratedValue(generator = \"table_gen\", strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/entites/CassandraGeneratedIdWithOutSequenceGenerator.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"CassandraGeneratedIdWithOutSequenceGenerator\", schema = \"kunderaGeneratedId@cassandra_generated_id\")\npublic class CassandraGeneratedIdWithOutSequenceGenerator\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/entites/CassandraGeneratedIdWithOutTableGenerator.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"CassandraGeneratedIdWithOutTableGenerator\", schema = \"kunderaGeneratedId@cassandra_generated_id\")\npublic class CassandraGeneratedIdWithOutTableGenerator\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/entites/CassandraGeneratedIdWithSequenceGenerator.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"CassandraGeneratedIdWithSequenceGenerator\", schema = \"kunderaGeneratedId@cassandra_generated_id\")\npublic class CassandraGeneratedIdWithSequenceGenerator\n{\n    @Id\n    @SequenceGenerator(name = \"id_gen\", allocationSize = 20, initialValue = 80, schema = \"kunderaGeneratedId\", sequenceName = \"newSequence\")\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/entites/CassandraGeneratedIdWithTableGenerator.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"CassandraGeneratedIdWithTableGenerator\", schema = \"kunderaGeneratedId@cassandra_generated_id\")\npublic class CassandraGeneratedIdWithTableGenerator\n{\n\n    @Id\n    @TableGenerator(name = \"id_gen\", allocationSize = 30, initialValue = 100, schema = \"kunderaGeneratedId\", table = \"kundera\", pkColumnName = \"sequence\", valueColumnName = \"sequenceValue\", pkColumnValue = \"kk\")\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/entites/EmployeeAddress.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"EmployeeAddress\", schema = \"kunderaGeneratedId@cassandra_generated_id\")\npublic class EmployeeAddress\n{\n\n    @Id\n    @Column(name = \"RegionID\")\n    @TableGenerator(name = \"id_gen\", allocationSize = 1, initialValue = 1)\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.TABLE)\n    private Long address;\n    \n    @Column(name=\"street\")\n    private String street;\n\n    public EmployeeAddress()\n    {\n        \n    }\n    public Long getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(Long address)\n    {\n        this.address = address;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n    \n    \n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/entites/EmployeeInfo.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.generatedId.entites;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"EmployeeInfo\", schema = \"kunderaGeneratedId@cassandra_generated_id\")\npublic class EmployeeInfo\n{\n    @Id\n    @Column(name = \"UserID\")\n    @TableGenerator(name = \"id_gen\", allocationSize = 1, initialValue = 1)\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.TABLE)\n    private Long userid;\n    \n//    @Column(name=\"name\")\n//    \n//    private String employeeName;\n    \n    public EmployeeInfo()\n    {\n        \n    }\n    \n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"address_id\")\n    private EmployeeAddress address;\n\n    public Long getUserid()\n    {\n        return userid;\n    }\n\n    public void setUserid(Long userid)\n    {\n        this.userid = userid;\n    }\n\n    public EmployeeAddress getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(EmployeeAddress address)\n    {\n        this.address = address;\n    }\n\n//    public String getEmployeeName()\n//    {\n//        return employeeName;\n//    }\n//\n//    public void setEmployeeName(String employeeName)\n//    {\n//        this.employeeName = employeeName;\n//    }\n//    \n    \n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/generatedId/entites/EmployeeInfoTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.generatedId.entites;\n\nimport java.util.HashMap;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class EmployeeInfoTest\n{\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        HashMap propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        propertyMap.put(CassandraConstants.CQL_VERSION,\tCassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(\"cassandra_generated_id\", propertyMap);\n    }\n\n    //@Test\n    //TODO: not working on CQL3 (issue with updating kundera_sequences, expected id:1 found:2)\n    public void test()\n    {\n        EntityManager em = emf.createEntityManager();\n        EmployeeInfo emp_info = new EmployeeInfo();\n        EmployeeAddress address_info = new EmployeeAddress();\n        address_info.setStreet(\"street\");\n        emp_info.setAddress(address_info);\n//        emp_info.setEmployeeName(\"vivek\");\n        em.persist(emp_info);\n\n        em.clear();\n\n        EmployeeInfo result = em.find(EmployeeInfo.class, 1l);\n\n        Assert.assertNotNull(result);\n        Assert.assertNotNull(result.getAddress());\n        Assert.assertNotNull(result.getAddress().getStreet());\n        Assert.assertNotNull(result.getAddress().getAddress());\n        Assert.assertEquals(\"street\", result.getAddress().getStreet());\n        \n        result.getAddress().setStreet(\"newStreet\");\n        em.merge(result);\n        \n        em.clear();\n        \n        result = em.find(EmployeeInfo.class, 1l);\n        Assert.assertNotNull(result);\n        Assert.assertNotNull(result.getAddress());\n        Assert.assertNotNull(result.getAddress().getStreet());\n        Assert.assertNotNull(result.getAddress().getAddress());\n        Assert.assertEquals(\"newStreet\", result.getAddress().getStreet());\n        \n        em.remove(result);\n        em.clear();\n        result = em.find(EmployeeInfo.class, 1l);\n        Assert.assertNull(result);\n        \n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"kunderaGeneratedId\");\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/persistence/CassandraBatchEntity.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.persistence;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class\n * \n * @author amresh.singh\n */\n@Entity\n@Table(name = \"CassandraBatchEntity\", schema = \"KunderaExamples@cassandra\")\npublic class CassandraBatchEntity\n{\n    @Id\n    @Column(name = \"user_name\")\n    private String user_name;\n\n    @Column(name = \"password\")\n    private String password;\n\n    @Column(name = \"name\")\n    private String name;\n\n    public CassandraBatchEntity()\n    {\n\n    }\n\n    /**\n     * @return the user_name\n     */\n    public String getUser_name()\n    {\n        return user_name;\n    }\n\n    /**\n     * @param user_name\n     *            the user_name to set\n     */\n    public void setUser_name(String user_name)\n    {\n        this.user_name = user_name;\n    }\n\n    /**\n     * @return the password\n     */\n    public String getPassword()\n    {\n        return password;\n    }\n\n    /**\n     * @param password\n     *            the password to set\n     */\n    public void setPassword(String password)\n    {\n        this.password = password;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/persistence/CassandraEntity.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.persistence;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class\n * \n * @author amresh.singh\n */\n@Entity\n@Table(name = \"users\", schema = \"KunderaExamples@cassandra\")\npublic class CassandraEntity\n{\n    @Id\n    @Column(name = \"key\")\n    private String key;\n\n    @Column(name = \"full_name\")\n    private String full_name;\n\n    @Column(name = \"birth_date\")\n    private Integer birth_date;\n\n    @Column(name = \"state\")\n    private String state;\n\n    /**\n     * @return the key\n     */\n    public String getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @param key\n     *            the key to set\n     */\n    public void setKey(String key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the full_name\n     */\n    public String getFull_name()\n    {\n        return full_name;\n    }\n\n    /**\n     * @param full_name\n     *            the full_name to set\n     */\n    public void setFull_name(String full_name)\n    {\n        this.full_name = full_name;\n    }\n\n    /**\n     * @return the birth_date\n     */\n    public Integer getBirth_date()\n    {\n        return birth_date;\n    }\n\n    /**\n     * @param birth_date\n     *            the birth_date to set\n     */\n    public void setBirth_date(int birth_date)\n    {\n        this.birth_date = birth_date;\n    }\n\n    /**\n     * @return the state\n     */\n    public String getState()\n    {\n        return state;\n    }\n\n    /**\n     * @param state\n     *            the state to set\n     */\n    public void setState(String state)\n    {\n        this.state = state;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/persistence/CassandraEntitySample.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.persistence;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Test Entity\n * \n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"users\", schema = \"KunderaExamples@cassandra\")\npublic class CassandraEntitySample\n{\n\n    @Id\n    @Column(name = \"key\")\n    private String key;\n\n    @Column(name = \"full_name\")\n    private String full_name;\n\n    @Column(name = \"birth_date\")\n    private Integer birth_date;\n\n    @Column(name = \"state\")\n    private String state;\n\n    /**\n     * @return the key\n     */\n    public String getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @param key\n     *            the key to set\n     */\n    public void setKey(String key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the full_name\n     */\n    public String getFull_name()\n    {\n        return full_name;\n    }\n\n    /**\n     * @param full_name\n     *            the full_name to set\n     */\n    public void setFull_name(String full_name)\n    {\n        this.full_name = full_name;\n    }\n\n    /**\n     * @return the birth_date\n     */\n    public Integer getBirth_date()\n    {\n        return birth_date;\n    }\n\n    /**\n     * @param birth_date\n     *            the birth_date to set\n     */\n    public void setBirth_date(int birth_date)\n    {\n        this.birth_date = birth_date;\n    }\n\n    /**\n     * @return the state\n     */\n    public String getState()\n    {\n        return state;\n    }\n\n    /**\n     * @param state\n     *            the state to set\n     */\n    public void setState(String state)\n    {\n        this.state = state;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/persistence/NativeQueryCQLV3Test.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.persistence;\n\nimport java.nio.ByteBuffer;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.thrift.ThriftClient;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * <Prove description of functionality provided by this Type>\n * \n * @author amresh.singh\n */\npublic class NativeQueryCQLV3Test\n{\n\n    private final String schema = \"KunderaExamples\";\n\n    private EntityManagerFactoryImpl emf;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.dropKeySpace(schema);\n        String nativeSql = \"CREATE KEYSPACE \\\"\" + schema\n                + \"\\\" with replication = {'class':'SimpleStrategy', 'replication_factor':1}\";\n        CassandraCli.getClient().execute_cql3_query(ByteBuffer.wrap(nativeSql.getBytes(\"UTF-8\")), Compression.NONE,\n                ConsistencyLevel.ONE);\n        emf = getEntityManagerFactory();\n    }\n\n    /**\n     * Test create insert column family query.\n     */\n    @Test\n    public void testCreateInsertColumnFamilyQueryVersion3()\n    {\n\n        String useNativeSql = \"USE \\\"\" + schema + \"\\\"\";\n        EntityManager em = emf.createEntityManager();\n\n        Map<String, Client> clientMap = (Map<String, Client>) em.getDelegate();\n        ThriftClient pc = (ThriftClient) clientMap.get(\"cassandra\");\n        pc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        Query q = em.createNativeQuery(useNativeSql, CassandraEntity.class);\n        q.executeUpdate();\n        // create column family\n        String colFamilySql = \"CREATE COLUMNFAMILY users (key varchar PRIMARY KEY,full_name varchar, birth_date int,state varchar)\";\n        q = em.createNativeQuery(colFamilySql, CassandraEntity.class);\n        q.executeUpdate();\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"users\", schema));\n\n        // Add indexes\n        String idxSql = \"CREATE INDEX ON users (birth_date)\";\n        q = em.createNativeQuery(idxSql, CassandraEntity.class);\n        q.executeUpdate();\n        idxSql = \"CREATE INDEX ON users (state)\";\n        q = em.createNativeQuery(idxSql, CassandraEntity.class);\n        q.executeUpdate();\n        // insert users.\n        String insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('bsanderson', 'Brandon Sanderson', 1975, 'UT')\";\n        q = em.createNativeQuery(insertSql, CassandraEntity.class);\n        q.executeUpdate();\n        // select key and state\n        String selectSql = \"SELECT key, state FROM users\";\n\n        q = em.createNativeQuery(selectSql, CassandraEntity.class);\n        List<CassandraEntity> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"bsanderson\", results.get(0).getKey());\n        Assert.assertEquals(\"UT\", results.get(0).getState());\n        Assert.assertNull(results.get(0).getFull_name());\n\n        // insert users.\n        insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('prothfuss', 'Patrick Rothfuss', 1973, 'WI')\";\n        q = em.createNativeQuery(insertSql, CassandraEntity.class);\n        q.getResultList();\n\n        insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('htayler', 'Howard Tayler', 1968, 'UT')\";\n        q = em.createNativeQuery(insertSql, CassandraEntity.class);\n        q.getResultList();\n\n        // select all\n        String selectAll = \"SELECT * FROM users WHERE state='UT' AND birth_date > 1970 Allow Filtering\";\n        q = em.createNativeQuery(selectAll, CassandraEntity.class);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"bsanderson\", results.get(0).getKey());\n        Assert.assertEquals(\"UT\", results.get(0).getState());\n        Assert.assertEquals(\"Brandon Sanderson\", results.get(0).getFull_name());\n        Assert.assertEquals(new Integer(1975), results.get(0).getBirth_date());\n        emf.close();\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory()\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(\"cassandra\");\n    }\n\n    @Test\n    public void testCQLBatch()\n    {\n        String useNativeSql = \"USE \\\"\" + schema + \"\\\"\";\n        String createColumnFamily = \"CREATE TABLE CassandraBatchEntity ( user_name varchar PRIMARY KEY, password varchar, name varchar)\";\n        String batchOps = \"BEGIN BATCH INSERT INTO CassandraBatchEntity (user_name, password, name) VALUES ('user2', 'ch@ngem3b', 'second user') UPDATE CassandraBatchEntity SET password = 'ps22dhds' WHERE user_name = 'user2' INSERT INTO CassandraBatchEntity (user_name, password) VALUES ('user3', 'ch@ngem3c') DELETE name FROM CassandraBatchEntity WHERE user_name = 'user2' INSERT INTO CassandraBatchEntity (user_name, password, name) VALUES ('user4', 'ch@ngem3c', 'Andrew') APPLY BATCH\";\n\n        EntityManager em = emf.createEntityManager();\n\n        Map<String, Client> clientMap = (Map<String, Client>) em.getDelegate();\n        ThriftClient pc = (ThriftClient) clientMap.get(\"cassandra\");\n        pc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        Query q = em.createNativeQuery(useNativeSql);\n        // q.getResultList();\n        q.executeUpdate();\n\n        pc.setConsistencyLevel(ConsistencyLevel.QUORUM);\n        q = em.createNativeQuery(createColumnFamily, CassandraBatchEntity.class);\n        // q.getResultList();\n        q.executeUpdate();\n\n        pc.setConsistencyLevel(ConsistencyLevel.QUORUM);\n        q = em.createNativeQuery(batchOps, CassandraBatchEntity.class);\n        // q.getResultList();\n        q.executeUpdate();\n\n        q = em.createNativeQuery(\"select * from CassandraBatchEntity\", CassandraBatchEntity.class);\n        List<CassandraBatchEntity> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n\n        // Multiple table batch processing.\n\n        createColumnFamily = \"create table test1 (id timeuuid primary key, url text, userid uuid, datetime timestamp, linkcounts int)\";\n        em.createNativeQuery(createColumnFamily, CassandraBatchEntity.class).executeUpdate();\n        createColumnFamily = \"create table test2 (key text primary key, count int)\";\n        em.createNativeQuery(createColumnFamily, CassandraBatchEntity.class).executeUpdate();\n        batchOps = \"BEGIN BATCH INSERT INTO test1(id, url) VALUES (64907b40-29a1-11e2-93fa-90b11c71b811,'w') INSERT INTO test2(key, count) VALUES ('key1',12) APPLY BATCH\";\n        em.createNativeQuery(batchOps, CassandraBatchEntity.class).executeUpdate();\n        emf.close();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(schema);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/persistence/NativeQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.persistence;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.query.QueryImpl;\n\n/**\n * Junit test case for NativeQuery support.\n * \n * @author vivek.mishra\n * \n */\npublic class NativeQueryTest\n{\n    // /** The schema. */\n    private final String schema = \"KunderaExamples\";\n\n    private EntityManagerFactoryImpl emf;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(schema);\n        emf = getEntityManagerFactory();\n    }\n\n    /**\n     * Test create native query.\n     */\n    @Test\n    public void testCreateNativeQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        String nativeSql = \"Select * from Cassandra c\";\n\n        QueryImpl q = (QueryImpl) em.createNativeQuery(nativeSql, CassandraEntitySample.class);\n        Assert.assertEquals(nativeSql, q.getJPAQuery());\n    }\n\n    /**\n     * Test execute native create keyspace query.\n     */\n    @Test\n    public void testExecutNativeQuery()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createNativeQuery(useNativeSql, CassandraEntitySample.class);\n        q.executeUpdate();\n        Assert.assertTrue(CassandraCli.keyspaceExist(schema));\n        Assert.assertFalse(CassandraCli.keyspaceExist(\"invalidSchema\"));\n    }\n\n    /**\n     * Native queries should not leak connections. Pelops pool fails providing a\n     * connection if we don't call {@link IPooledConnection#release()}\n     */\n    @Test\n    public void testReleasesNativeQueryConnection()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n\n        EntityManager em = emf.createEntityManager();\n\n        // won't be able to loop if connections are leaked\n        for (int i = 0; i < 30; i++)\n        {\n            Query q = em.createNativeQuery(useNativeSql, CassandraEntitySample.class);\n            q.executeUpdate();\n        }\n    }\n\n    /**\n     * Test create insert column family query.\n     */\n    @Test\n    public void testCreateInsertColumnFamilyQuery()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createNativeQuery(useNativeSql, CassandraEntitySample.class);\n        // q.getResultList();\n        q.executeUpdate();\n        // create column family\n        String colFamilySql = \"CREATE COLUMNFAMILY users (key varchar PRIMARY KEY,full_name varchar, birth_date int,state varchar)\";\n        q = em.createNativeQuery(colFamilySql, CassandraEntitySample.class);\n        // q.getResultList();\n        q.executeUpdate();\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"users\", \"KunderaExamples\"));\n\n        // Add indexes\n        String idxSql = \"CREATE INDEX ON users (birth_date)\";\n        q = em.createNativeQuery(idxSql, CassandraEntitySample.class);\n        // q.getResultList();\n        q.executeUpdate();\n        idxSql = \"CREATE INDEX ON users (state)\";\n        q = em.createNativeQuery(idxSql, CassandraEntitySample.class);\n        // q.getResultList();\n        q.executeUpdate();\n        // insert users.\n        String insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('bsanderson', 'Brandon Sanderson', 1975, 'UT')\";\n        q = em.createNativeQuery(insertSql, CassandraEntitySample.class);\n        // q.getResultList();\n        q.executeUpdate();\n        // select key and state\n        String selectSql = \"SELECT key, state FROM users\";\n\n        q = em.createNativeQuery(selectSql, CassandraEntitySample.class);\n        List<CassandraEntitySample> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"bsanderson\", results.get(0).getKey());\n        Assert.assertEquals(\"UT\", results.get(0).getState());\n        Assert.assertNull(results.get(0).getFull_name());\n\n        // insert users.\n        insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('prothfuss', 'Patrick Rothfuss', 1973, 'WI')\";\n        q = em.createNativeQuery(insertSql, CassandraEntitySample.class);\n        q.getResultList();\n\n        insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('htayler', 'Howard Tayler', 1968, 'UT')\";\n        q = em.createNativeQuery(insertSql, CassandraEntitySample.class);\n        q.getResultList();\n\n        // select all\n        String selectAll = \"SELECT * FROM users WHERE state='UT' AND birth_date > 1970 ALLOW FILTERING\";\n        q = em.createNativeQuery(selectAll, CassandraEntitySample.class);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"bsanderson\", results.get(0).getKey());\n        Assert.assertEquals(\"UT\", results.get(0).getState());\n        Assert.assertEquals(\"Brandon Sanderson\", results.get(0).getFull_name());\n        Assert.assertEquals(new Integer(1975), results.get(0).getBirth_date());\n\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory()\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(\"cassandra\");\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(schema);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/persistence/NullableFieldAccessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.persistence;\n\nimport java.nio.ByteBuffer;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Cassandra;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * @author kuldeep.mishra\n * \n *         The Class PersistWithNullField.\n */\npublic class NullableFieldAccessorTest\n{\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        Cassandra.Client client = CassandraCli.getClient();\n        client.set_keyspace(\"KunderaExamples\");\n        CfDef cf_def = new CfDef();\n        cf_def.keyspace = \"KunderaExamples\";\n        cf_def.name = \"users\";\n        cf_def.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"full_name\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        cf_def.addToColumn_metadata(columnDef2);\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"birth_date\".getBytes()), \"Int32Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        cf_def.addToColumn_metadata(columnDef3);\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"state\".getBytes()), \"UTF8Type\");\n        columnDef4.index_type = IndexType.KEYS;\n        cf_def.addToColumn_metadata(columnDef4);\n        client.system_add_column_family(cf_def);\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        EntityManagerFactoryImpl emf = getEntityManagerFactory();\n        EntityManager em = emf.createEntityManager();\n        CassandraEntitySample entity = new CassandraEntitySample();\n        entity.setKey(\"123\");\n        entity.setFull_name(\"kuldeep mishra\");\n        entity.setState(\"delhi\");\n        // birth_date is null\n\n        em.persist(entity);\n\n        CassandraEntitySample findEntity = em.find(CassandraEntitySample.class, 123);\n        Assert.assertNotNull(findEntity);\n        Assert.assertEquals(\"123\", findEntity.getKey());\n        Assert.assertEquals(\"kuldeep mishra\", findEntity.getFull_name());\n        Assert.assertEquals(\"delhi\", findEntity.getState());\n        Assert.assertNull(findEntity.getBirth_date());\n\n        emf.close();\n\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory()\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(\"cassandra\");\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/persistence/UpdateDeleteNamedQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.persistence;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * Test case for update/delete via JPQL.\n * \n * @author vivek.mishra\n * \n */\npublic class UpdateDeleteNamedQueryTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n\n        loadData();\n    }\n\n    /**\n     * @throws TException\n     * @throws InvalidRequestException\n     * @throws SchemaDisagreementException\n     * \n     */\n    private void loadData() throws InvalidRequestException, TException, SchemaDisagreementException\n    {\n        KsDef ksDef = null;\n        CfDef user_Def = new CfDef();\n        user_Def.name = \"users\";\n        user_Def.keyspace = \"KunderaExamples\";\n        user_Def.setComparator_type(\"UTF8Type\");\n        user_Def.setDefault_validation_class(\"UTF8Type\");\n        user_Def.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"birth_date\".getBytes()), \"Int32Type\");\n        columnDef.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef);\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"state\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef1);\n\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"full_name\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef2);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def);\n\n        ksDef = new KsDef(\"KunderaExamples\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n        // Set replication factor\n        if (ksDef.strategy_options == null)\n        {\n            ksDef.strategy_options = new LinkedHashMap<String, String>();\n        }\n        // Set replication factor, the value MUST be an integer\n        ksDef.strategy_options.put(\"replication_factor\", \"1\");\n        CassandraCli.client.system_add_keyspace(ksDef);\n    }\n\n    @Test\n    public void testUpdate()\n    {\n        EntityManagerFactory emf = getEntityManagerFactory();\n        EntityManager em = emf.createEntityManager();\n\n        CassandraEntitySample entity = new CassandraEntitySample();\n        entity.setBirth_date(new Integer(100112));\n        entity.setFull_name(\"impetus_emp\");\n        entity.setKey(\"k\");\n        entity.setState(\"UP\");\n        em.persist(entity);\n\n        String updateQuery = \"Update CassandraEntitySample c SET c.state = DELHI where c.state = UP\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        CassandraEntitySample result = em.find(CassandraEntitySample.class, \"k\");\n        Assert.assertNotNull(result);\n\n        updateQuery = \"Update CassandraEntitySample c SET c.state = Bengalore where c.key = k\";\n        q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        \n        em.clear();\n        \n        result = em.find(CassandraEntitySample.class, \"k\");\n        Assert.assertNotNull(result);\n\n        Assert.assertEquals(\"Bengalore\", result.getState()); // This should be\n        // uncommented later. as merge got some issue.\n        String deleteQuery = \"Delete From CassandraEntitySample c where c.state=Bengalore\";\n\n        q = em.createQuery(deleteQuery);\n        // q = em.createNamedQuery(\"delete.query\");\n        q.executeUpdate();\n        \n        em.clear();\n        \n        result = em.find(CassandraEntitySample.class, \"k\");\n//        Assert.assertNull(result); // This should be uncommented later. as\n        // merge got some issue.\n        emf.close();\n    }\n\n    @Test\n    public void testUpdateUsingIdColumnClause()\n    {\n        EntityManagerFactory emf = getEntityManagerFactory();\n        EntityManager em = emf.createEntityManager();\n\n        CassandraEntitySample entity = new CassandraEntitySample();\n        entity.setBirth_date(new Integer(100112));\n        entity.setFull_name(\"impetus_emp\");\n        entity.setKey(\"k\");\n        entity.setState(\"UP\");\n        em.persist(entity);\n\n        String updateQuery = \"Update CassandraEntitySample c SET c.state = DELHI where c.key = k\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        \n        em.clear();\n        \n        CassandraEntitySample result = em.find(CassandraEntitySample.class, \"k\");\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"DELHI\", result.getState()); // This should be\n        // uncommented later. as merge got some issue.\n        String deleteQuery = \"Delete From CassandraEntitySample c where c.key=k\";\n\n        q = em.createQuery(deleteQuery);\n        // q = em.createNamedQuery(\"delete.query\");\n        q.executeUpdate();\n        \n        em.clear();\n        \n        result = em.find(CassandraEntitySample.class, \"k\");\n        Assert.assertNull(result); // This should be uncommented later. as\n        // merge got some issue.\n        emf.close();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory()\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(\"cassandra\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/CassandraSchemaManagerMTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.metadata.validator.InvalidEntityDefinitionException;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * @author Kuldeep.Kumar\n * \n */\npublic class CassandraSchemaManagerMTM\n{\n    private static final String keyspace = \"KunderaCassandraExamples\";\n\n    private static final String pu = \"cassandra\";\n\n    private final boolean useLucene = false;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(keyspace);\n    }\n\n    @Test\n    public void test()\n    {\n        try\n        {\n            getEntityManagerFactory(\"create\");\n\n            Assert.assertTrue(CassandraCli.keyspaceExist(keyspace));\n            Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityPersonnelUniMToM\", keyspace));\n            Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityHabitatUniMToM\", keyspace));\n            Assert.assertTrue(CassandraCli.columnFamilyExist(\"PERSONNEL_ADDRESS\", keyspace));\n        }\n        catch (InvalidEntityDefinitionException iedex)\n        {\n            Assert.assertEquals(\"It's manadatory to use @JoinTable with parent side of ManyToMany relationship.\",\n                    iedex.getMessage());\n        }\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory(String property)\n    {\n        Map propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_KEYSPACE, \"KunderaCassandraMTMExamples\");\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"cassandra\", propertyMap);\n        return (EntityManagerFactoryImpl) emf;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/CassandraSchemaManagerMTMTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.metadata.validator.InvalidEntityDefinitionException;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * @author Kuldeep.Kumar\n * \n */\npublic class CassandraSchemaManagerMTMTest\n{\n    private static final String _keyspace = \"KunderaExamples\";\n\n    private static final String _persistenceUnit = \"cassandra\";\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(_keyspace);\n    }\n\n    @Test\n    public void test()\n    {\n        try\n        {\n            getEntityManagerFactory(\"create\");\n            Assert.assertTrue(CassandraCli.keyspaceExist(_keyspace));\n            Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityPersonnelUniMToM\", _keyspace));\n            Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityHabitatUniMToM\", _keyspace));\n            Assert.assertTrue(CassandraCli.columnFamilyExist(\"PERSONNEL_ADDRESS\", _keyspace));\n        }\n        catch (InvalidEntityDefinitionException iedex)\n        {\n            Assert.assertEquals(\"It's manadatory to use @JoinTable with parent side of ManyToMany relationship.\",\n                    iedex.getMessage());\n        }\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory(String property)\n    {\n        Map propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, property);\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(_persistenceUnit, propertyMap);\n        return (EntityManagerFactoryImpl) emf;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/CassandraSchemaManagerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.schemamanager;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * CassandraSchemaManagerTest class test the auto creation schema property in\n * cassandra data store.\n * \n * @author Kuldeep.Kumar\n * \n */\npublic class CassandraSchemaManagerTest\n{\n    private static final String _PU = \"CassandraSchemaManager\";\n\n    private static final String _KEYSPACE = \"CassandraSchemaManagerTest\";\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(_KEYSPACE);\n    }\n\n    /**\n     * Test schema operation.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void schemaOperation() throws IOException, TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        EntityManagerFactory emf = getEntityManagerFactory(null, _PU);\n        Assert.assertTrue(CassandraCli.keyspaceExist(_KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntitySuper\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityAddressUni1To1\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityAddressUniMTo1\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityAddressUni1ToM\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityPersonUniMto1\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityPersonUni1ToM\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityPersonUni1To1\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityPersonUni1To1PK\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityAddressUni1To1PK\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityPersonBi1To1FK\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityPersonBi1To1PK\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityPersonBi1ToM\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityPersonBiMTo1\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityAddressBi1To1FK\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityAddressBi1To1PK\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityAddressBi1ToM\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntityAddressBiMTo1\", _KEYSPACE));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEmbeddedPersonUniMto1\", _KEYSPACE));\n\n        emf.close();\n\n    }\n\n\n    @Test\n    public void schemaOperationViaCQL3() throws IOException, TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        final String pu = \"CassandraSchemaOperationTest\";\n        Map propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        EntityManagerFactory emf = getEntityManagerFactory(propertyMap, pu);\n\n        String keyspaceName = \"KunderaCoreExmples\";\n        Assert.assertTrue(CassandraCli.keyspaceExist(keyspaceName));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntitySimple\", keyspaceName));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"Actor\", keyspaceName));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"TwitterUser\", keyspaceName));\n        emf.close();\n        CassandraCli.dropKeySpace(keyspaceName);\n\n\n    }\n\n    @Test\n    public void testValidate()\n    {\n        try\n        {\n            final String pu = \"CassandraSchemaOperationTest\";\n            Map propertyMap = new HashMap();\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n            propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n            EntityManagerFactory emf = getEntityManagerFactory(propertyMap, pu);\n\n            String keyspaceName = \"KunderaCoreExmples\";\n            CassandraCli.dropColumnFamily(\"CassandraEntitySimple\", keyspaceName);\n            String colFamilySql = \"CREATE table \\\"CassandraEntitySimple\\\" (\\\"PERSON_ID\\\" varchar PRIMARY KEY,\\\"PERSON_NAME\\\" varchar, \\\"AGE\\\" int)\";\n            \n            CassandraCli.executeCqlQuery(colFamilySql, keyspaceName);\n            \n//            colFamilySql = \"CREATE TABLE \\\"TwitterUser\\\" (user_id text,\\\"tweetDate\\\" timestamp,\\\"firstName\\\" text,body text,followers set<text>,PRIMARY KEY (user_id, \\\"tweetDate\\\", \\\"firstName\\\"))\";\n//            CassandraCli.executeCqlQuery(colFamilySql, keyspaceName);\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"validate\");\n            propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n            EntityManagerFactory emf1 = getEntityManagerFactory(propertyMap, pu);\n            emf1.close();\n            CassandraCli.dropKeySpace(keyspaceName);\n        }\n        catch (SchemaGenerationException sgex)\n        {\n            Assert.fail(sgex.getMessage());\n        }\n\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory(Map propertyMap, final String persistenceUnit)\n    {\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, propertyMap);\n        return (EntityManagerFactoryImpl) emf;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/CassandraSchemaManagerValidateEntityTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager;\n\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.config.CassandraPropertyReader;\nimport com.impetus.client.cassandra.schemamanager.CassandraSchemaManager;\nimport com.impetus.client.cassandra.thrift.ThriftClientFactory;\nimport com.impetus.client.schemamanager.entites.InvalidCounterColumnEntity;\nimport com.impetus.client.schemamanager.entites.ValidCounterColumnFamily;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * @author impadmin\n * \n */\npublic class CassandraSchemaManagerValidateEntityTest\n{\n\n    private String persistenceUnit = \"cassandraProperties\";\n\n    // private String[] persistenceUnits = new String[] {persistenceUnit};\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.cassandra.schemamanager.CassandraSchemaManager#validateEntity(java.lang.Class)}\n     * .\n     */\n    @Test\n    public void testValidateEntity()\n    {\n        EntityManagerFactoryImpl emf = getEntityManagerFactory();\n        CassandraPropertyReader reader = new CassandraPropertyReader(null, emf.getKunderaMetadataInstance()\n                .getApplicationMetadata().getPersistenceUnitMetadata(\"cassandraProperties\"));\n        reader.read(persistenceUnit);\n        CassandraSchemaManager manager = new CassandraSchemaManager(ThriftClientFactory.class.getName(), null,\n                emf.getKunderaMetadataInstance());\n        boolean valid = manager.validateEntity(ValidCounterColumnFamily.class);\n        Assert.assertTrue(valid);\n        valid = manager.validateEntity(InvalidCounterColumnEntity.class);\n        Assert.assertFalse(valid);\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory()\n    {\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(\"cassandraProperties\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/CassandraSchemaOperationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager;\n\nimport java.io.UnsupportedEncodingException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.db.marshal.IntegerType;\nimport org.apache.cassandra.db.marshal.UTF8Type;\nimport org.apache.cassandra.thrift.Cassandra;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.thrift.ThriftClientFactory;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.ClientResolver;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * @author Kuldeep.Kumar\n * \n */\n//TODO: Check for TTransportException\npublic class CassandraSchemaOperationTest\n{\n    private Cassandra.Client client;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    //@Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        client = CassandraCli.getClient();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    //@After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"KunderaCoreExmples\");\n    }\n\n    //@Test\n    public void testCreate() throws NotFoundException, InvalidRequestException, TException,\n            UnsupportedEncodingException\n    {\n        getEntityManagerFactory(\"create\");\n        Assert.assertTrue(CassandraCli.keyspaceExist(\"KunderaCoreExmples\"));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntitySimple\", \"KunderaCoreExmples\"));\n        org.apache.cassandra.thrift.KsDef ksDef = new KsDef();\n        ksDef = client.describe_keyspace(\"KunderaCoreExmples\");\n        Assert.assertEquals(1, ksDef.getCf_defs().size());\n        for (org.apache.cassandra.thrift.CfDef cfDef : ksDef.getCf_defs())\n        {\n            if (\"CassandraEntitySimple\".equals(cfDef.getName()))\n            {\n                Assert.assertEquals(\"CassandraEntitySimple\", cfDef.getName());\n\n                Assert.assertEquals(\"Standard\", cfDef.column_type);\n                Assert.assertEquals(2, cfDef.getColumn_metadata().size());\n                List<String> columns = new ArrayList<String>();\n                columns.add(\"AGE\");\n                columns.add(\"PERSON_NAME\");\n                for (ColumnDef columnDef : cfDef.getColumn_metadata())\n                {\n                    if (new String(columnDef.getName(), Constants.ENCODING).equals(\"AGE\"))\n                    {\n                        Assert.assertTrue(columnDef.isSetIndex_type());\n                        Assert.assertTrue(columns.contains(new String(columnDef.getName(), Constants.ENCODING)));\n                        Assert.assertEquals(IndexType.KEYS, columnDef.index_type);\n                        // Assert.assertEquals(\"age_index\",\n                        // columnDef.index_name);\n                    }\n                    else\n                    {\n\n                        Assert.assertTrue(columnDef.isSetIndex_type());\n                        Assert.assertTrue(columns.contains(new String(columnDef.getName(), Constants.ENCODING)));\n                        Assert.assertEquals(IndexType.KEYS, columnDef.index_type);\n                        // Assert.assertEquals(\"name_index\",\n                        // columnDef.index_name);\n                    }\n                }\n            }\n        }\n    }\n\n    //@Test\n    public void testCreatedrop() throws NotFoundException, InvalidRequestException, TException,\n            UnsupportedEncodingException\n    {\n        getEntityManagerFactory(\"create-drop\");\n        Assert.assertTrue(CassandraCli.keyspaceExist(\"KunderaCoreExmples\"));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntitySimple\", \"KunderaCoreExmples\"));\n        org.apache.cassandra.thrift.KsDef ksDef = new KsDef();\n        ksDef = client.describe_keyspace(\"KunderaCoreExmples\");\n        for (org.apache.cassandra.thrift.CfDef cfDef : ksDef.getCf_defs())\n        {\n            if (\"CassandraEntitySimple\".equals(cfDef.getName()))\n            {\n                Assert.assertEquals(\"CassandraEntitySimple\", cfDef.getName());\n\n                Assert.assertEquals(\"Standard\", cfDef.column_type);\n                Assert.assertEquals(2, cfDef.getColumn_metadata().size());\n\n                List<String> columns = new ArrayList<String>();\n                columns.add(\"AGE\");\n                columns.add(\"PERSON_NAME\");\n\n                for (ColumnDef columnDef : cfDef.getColumn_metadata())\n                {\n                    if (new String(columnDef.getName(), Constants.ENCODING).equals(\"AGE\"))\n                    {\n                        Assert.assertTrue(columnDef.isSetIndex_type());\n                        Assert.assertTrue(columns.contains(new String(columnDef.getName(), Constants.ENCODING)));\n                        Assert.assertEquals(IndexType.KEYS, columnDef.index_type);\n                        // Assert.assertEquals(\"age_index\",\n                        // columnDef.index_name);\n                    }\n                    else\n                    {\n                        Assert.assertTrue(columnDef.isSetIndex_type());\n                        Assert.assertTrue(columns.contains(new String(columnDef.getName(), Constants.ENCODING)));\n                        Assert.assertEquals(IndexType.KEYS, columnDef.index_type);\n                        // Assert.assertEquals(\"name_index\",\n                        // columnDef.index_name);\n                    }\n                }\n            }\n        }\n        ThriftClientFactory clientFactory = (ThriftClientFactory) ClientResolver\n                .getClientFactory(\"CassandraSchemaOperationTest\");\n        clientFactory.getSchemaManager(null).dropSchema();\n        Assert.assertFalse(CassandraCli.keyspaceExist(\"KunderaCoreExmples\"));\n    }\n\n    //@Test\n    public void testUpdate() throws NotFoundException, InvalidRequestException, TException,\n            SchemaDisagreementException, UnsupportedEncodingException\n    {\n        CassandraCli.createKeySpace(\"KunderaCoreExmples\");\n        client.set_keyspace(\"KunderaCoreExmples\");\n        org.apache.cassandra.thrift.CfDef cf_def = new org.apache.cassandra.thrift.CfDef(\"KunderaCoreExmples\",\n                \"CassandraEntitySimple\");\n        cf_def.column_type = \"Standard\";\n        client.system_add_column_family(cf_def);\n\n        Assert.assertTrue(CassandraCli.keyspaceExist(\"KunderaCoreExmples\"));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntitySimple\", \"KunderaCoreExmples\"));\n        org.apache.cassandra.thrift.KsDef ksDef = new KsDef();\n        ksDef = client.describe_keyspace(\"KunderaCoreExmples\");\n        Assert.assertEquals(0, ksDef.getCf_defs().get(0).getColumn_metadata().size());\n\n        getEntityManagerFactory(\"update\");\n        Assert.assertTrue(CassandraCli.keyspaceExist(\"KunderaCoreExmples\"));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntitySimple\", \"KunderaCoreExmples\"));\n        ksDef = client.describe_keyspace(\"KunderaCoreExmples\");\n        for (org.apache.cassandra.thrift.CfDef cfDef : ksDef.getCf_defs())\n        {\n            if (\"CassandraEntitySimple\".equals(cfDef.getName()))\n            {\n                Assert.assertEquals(\"CassandraEntitySimple\", cfDef.getName());\n\n                Assert.assertEquals(\"Standard\", cfDef.getColumn_type());\n\n                int counter = 0;\n                for (ColumnDef columnDef : cfDef.getColumn_metadata())\n                {\n                    if (new String(columnDef.getName(), Constants.ENCODING).equals(\"AGE\"))\n                    {\n                        Assert.assertTrue(columnDef.isSetIndex_type());\n                        Assert.assertNotNull(columnDef.index_name);\n                        Assert.assertEquals(IntegerType.class.getName(), columnDef.getValidation_class());\n                        // Assert.assertEquals(\"age_index\",\n                        // columnDef.index_name);\n                        counter++;\n                    }\n                    else\n                    {\n                        Assert.assertTrue(columnDef.isSetIndex_type());\n                        Assert.assertEquals(\"PERSON_NAME\", new String(columnDef.getName(), Constants.ENCODING));\n                        Assert.assertNotNull(columnDef.index_name);\n                        Assert.assertEquals(UTF8Type.class.getName(), columnDef.getValidation_class());\n                        // Assert.assertEquals(\"name_index\",\n                        // columnDef.index_name);\n                        counter++;\n                    }\n                }\n                Assert.assertEquals(2, counter);\n            }\n        }\n    }\n\n    //@Test\n    public void testUpdateInValid() throws NotFoundException, InvalidRequestException, TException,\n            SchemaDisagreementException, UnsupportedEncodingException\n    {\n        CassandraCli.createKeySpace(\"KunderaCoreExmples\");\n        client.set_keyspace(\"KunderaCoreExmples\");\n        org.apache.cassandra.thrift.CfDef cf_def = new org.apache.cassandra.thrift.CfDef(\"KunderaCoreExmples\",\n                \"CassandraEntitySimple\");\n        cf_def.column_type = \"Standard\";\n        List<ColumnDef> column_metadata = new ArrayList<ColumnDef>();\n        ColumnDef def = new ColumnDef();\n        def.setName(\"AGE\".getBytes());\n        def.setValidation_class(\"Int32Type\");\n        def.setIndex_type(IndexType.KEYS);\n\n        ColumnDef def1 = new ColumnDef();\n        def1.setName(\"PERSON_NAME\".getBytes());\n        def1.setValidation_class(\"UTF8Type\");\n        def1.setIndex_type(IndexType.KEYS);\n\n        column_metadata.add(def1);\n        column_metadata.add(def);\n\n        cf_def.setColumn_metadata(column_metadata);\n        client.system_add_column_family(cf_def);\n\n        Assert.assertTrue(CassandraCli.keyspaceExist(\"KunderaCoreExmples\"));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntitySimple\", \"KunderaCoreExmples\"));\n        org.apache.cassandra.thrift.KsDef ksDef = client.describe_keyspace(\"KunderaCoreExmples\");\n        Assert.assertEquals(1, ksDef.getCf_defs().size());\n        Assert.assertEquals(2, ksDef.getCf_defs().get(0).getColumn_metadata().size());\n\n        getEntityManagerFactory(\"update\");\n\n        // TODO: Do not delete it.\n        Assert.assertTrue(CassandraCli.keyspaceExist(\"KunderaCoreExmples\"));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntitySimple\", \"KunderaCoreExmples\"));\n        ksDef = client.describe_keyspace(\"KunderaCoreExmples\");\n        for (org.apache.cassandra.thrift.CfDef cfDef : ksDef.getCf_defs())\n        {\n            if (\"CassandraEntitySimple\".equals(cfDef.getName()))\n            {\n                Assert.assertEquals(\"CassandraEntitySimple\", cfDef.getName());\n\n                Assert.assertEquals(\"Standard\", cfDef.getColumn_type());\n\n                int counter = 0;\n                for (ColumnDef columnDef : cfDef.getColumn_metadata())\n                {\n                    if (new String(columnDef.getName(), Constants.ENCODING).equals(\"AGE\"))\n                    {\n                        Assert.assertTrue(columnDef.isSetIndex_type());\n                        Assert.assertNotNull(columnDef.index_name);\n                        Assert.assertEquals(IntegerType.class.getName(), columnDef.getValidation_class());\n                        // Assert.assertEquals(\"age_index\",\n                        // columnDef.index_name);\n                        counter++;\n                    }\n                    else\n                    {\n                        Assert.assertTrue(columnDef.isSetIndex_type());\n                        Assert.assertEquals(\"PERSON_NAME\", new String(columnDef.getName(), Constants.ENCODING));\n                        Assert.assertNotNull(columnDef.index_name);\n                        Assert.assertEquals(UTF8Type.class.getName(), columnDef.getValidation_class());\n                        // Assert.assertEquals(\"name_index\",\n                        // columnDef.index_name);\n                        counter++;\n                    }\n                }\n                Assert.assertEquals(2, counter);\n            }\n        }\n    }\n\n    //@Test\n    public void testValidate()\n    {\n        try\n        {\n            CassandraCli.createKeySpace(\"KunderaCoreExmples\");\n\n            client.set_keyspace(\"KunderaCoreExmples\");\n\n            org.apache.cassandra.thrift.CfDef cf_def = new org.apache.cassandra.thrift.CfDef(\"KunderaCoreExmples\",\n                    \"CassandraEntitySimple\");\n            cf_def.column_type = \"Standard\";\n            client.system_add_column_family(cf_def);\n\n            org.apache.cassandra.thrift.CfDef actor = new org.apache.cassandra.thrift.CfDef(\"KunderaCoreExmples\",\n                    \"Actor\");\n            actor.column_type = \"Super\";\n\n            client.system_add_column_family(actor);\n\n            getEntityManagerFactory(\"validate\");\n            Assert.assertTrue(CassandraCli.keyspaceExist(\"KunderaCoreExmples\"));\n            Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntitySimple\", \"KunderaCoreExmples\"));\n            org.apache.cassandra.thrift.KsDef ksDef = client.describe_keyspace(\"KunderaCoreExmples\");\n            for (org.apache.cassandra.thrift.CfDef cfDef : ksDef.getCf_defs())\n            {\n                if (\"CassandraEntitySimple\".equals(cfDef.getName()))\n                {\n                    Assert.assertEquals(\"CassandraEntitySimple\", cfDef.getName());\n\n                    Assert.assertEquals(\"Standard\", cfDef.column_type);\n                    List<String> columns = new ArrayList<String>();\n                    columns.add(\"AGE\");\n                    columns.add(\"PERSON_NAME\");\n\n                    for (ColumnDef columnDef : cfDef.getColumn_metadata())\n                    {\n                        Assert.assertFalse(columnDef.isSetIndex_type());\n                        Assert.assertTrue(columns.contains(new String(columnDef.getName(), Constants.ENCODING)));\n                        Assert.assertNull(columnDef.index_name);\n                    }\n                }\n            }\n        }\n        catch (SchemaGenerationException e)\n        {\n            List<String> errors = new ArrayList<String>();\n            errors.add(\"com.impetus.kundera.configure.schema.SchemaGenerationException: Column AGE does not exist in column family CassandraEntitySimple\");\n            errors.add(\"com.impetus.kundera.configure.schema.SchemaGenerationException: Column PERSON_NAME does not exist in column family CassandraEntitySimple\");\n            Assert.assertTrue(errors.contains(e.getMessage()));\n\n        }\n        catch (InvalidRequestException e1)\n        {\n            Assert.fail(\"failed caused by:\" + e1.getMessage());\n        }\n        catch (TException e1)\n        {\n            Assert.fail(\"failed caused by:\" + e1.getMessage());\n        }\n        catch (UnsupportedEncodingException e)\n        {\n            Assert.fail(\"failed caused by:\" + e.getMessage());\n        }\n    }\n\n    //@Test\n    public void validateInvalidSchema() throws NotFoundException, InvalidRequestException, TException,\n            SchemaDisagreementException, UnsupportedEncodingException\n    {\n        try\n        {\n            CassandraCli.createKeySpace(\"KunderaCoreExmples\");\n            client.set_keyspace(\"KunderaCoreExmples\");\n            org.apache.cassandra.thrift.CfDef cf_def = new org.apache.cassandra.thrift.CfDef(\"KunderaCoreExmples\",\n                    \"CassandraEntitySimple\");\n            cf_def.column_type = \"Standard\";\n            List<ColumnDef> column_metadata = new ArrayList<ColumnDef>();\n            ColumnDef def = new ColumnDef();\n            def.setName(\"AGE\".getBytes());\n            def.setValidation_class(\"UTF8Type\");\n            def.setIndex_type(IndexType.KEYS);\n\n            ColumnDef def1 = new ColumnDef();\n            def1.setName(\"PERSON_NAME\".getBytes());\n            def1.setValidation_class(\"BytesType\");\n            def1.setIndex_type(IndexType.KEYS);\n\n            column_metadata.add(def1);\n            column_metadata.add(def);\n\n            cf_def.setColumn_metadata(column_metadata);\n            client.system_add_column_family(cf_def);\n\n            org.apache.cassandra.thrift.CfDef actor = new org.apache.cassandra.thrift.CfDef(\"KunderaCoreExmples\",\n                    \"Actor\");\n            actor.column_type = \"Super\";\n\n            client.system_add_column_family(actor);\n\n            Assert.assertTrue(CassandraCli.keyspaceExist(\"KunderaCoreExmples\"));\n            Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntitySimple\", \"KunderaCoreExmples\"));\n            org.apache.cassandra.thrift.KsDef ksDef = client.describe_keyspace(\"KunderaCoreExmples\");\n            Assert.assertEquals(2, ksDef.getCf_defs().size());\n            Assert.assertTrue(2 == ksDef.getCf_defs().get(0).getColumn_metadata().size()\n                    || 0 == ksDef.getCf_defs().get(0).getColumn_metadata().size());\n            Assert.assertTrue(1 == ksDef.getCf_defs().get(1).getColumn_metadata().size()\n                    || 1 == ksDef.getCf_defs().get(1).getColumn_metadata().size());\n\n            getEntityManagerFactory(\"validate\");\n            Assert.assertTrue(CassandraCli.keyspaceExist(\"KunderaCassandraExamples\"));\n            Assert.assertTrue(CassandraCli.columnFamilyExist(\"CassandraEntitySimple\", \"KunderaCassandraExamples\"));\n            ksDef = client.describe_keyspace(\"KunderaCassandraExamples\");\n            for (org.apache.cassandra.thrift.CfDef cfDef : ksDef.getCf_defs())\n            {\n                if (\"CassandraEntitySimple\".equals(cfDef.getName()))\n                {\n                    Assert.assertEquals(\"CassandraEntitySimple\", cfDef.getName());\n\n                    Assert.assertEquals(\"Standard\", cfDef.getColumn_type());\n\n                    List<String> columns = new ArrayList<String>();\n                    columns.add(\"AGE\");\n                    columns.add(\"PERSON_NAME\");\n                    for (ColumnDef columnDef : cfDef.getColumn_metadata())\n                    {\n                        Assert.assertTrue(columnDef.isSetIndex_type());\n                        Assert.assertTrue(columns.contains(new String(columnDef.getName(), Constants.ENCODING)));\n                        Assert.assertNotNull(columnDef.index_name);\n                    }\n                }\n            }\n        }\n        catch (SchemaGenerationException sgex)\n        {\n            List<String> errors = new ArrayList<String>();\n            errors.add(\"com.impetus.kundera.configure.schema.SchemaGenerationException: Column AGE does not exist in column family CassandraEntitySimple\");\n            errors.add(\"com.impetus.kundera.configure.schema.SchemaGenerationException: Column PERSON_NAME does not exist in column family CassandraEntitySimple\");\n            errors.add(\"com.impetus.kundera.configure.schema.SchemaGenerationException: column family CassandraEntitySimple does not exist in keyspace KunderaCoreExmples\");\n            Assert.assertTrue(errors.contains(sgex.getMessage().trim()));\n        }\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory(String property)\n    {\n        Map<String, String> propertyMap = new HashMap<String, String>();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, property);\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(\"CassandraSchemaOperationTest\",\n                propertyMap);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/CassanrdaGeneratedIdSchemaTest.java",
    "content": "package com.impetus.client.schemamanager;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.cassandra.db.marshal.CounterColumnType;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdDefault;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdStrategyAuto;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdStrategyIdentity;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdStrategySequence;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdStrategyTable;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdWithOutSequenceGenerator;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdWithOutTableGenerator;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdWithSequenceGenerator;\nimport com.impetus.client.generatedId.entites.CassandraGeneratedIdWithTableGenerator;\nimport com.impetus.client.generatedId.entites.EmployeeAddress;\nimport com.impetus.client.generatedId.entites.EmployeeInfo;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class CassanrdaGeneratedIdSchemaTest\n{\n    private Logger logger = LoggerFactory.getLogger(CassanrdaGeneratedIdSchemaTest.class);\n    \n    private EntityManagerFactory emf;\n    \n    private List<String> columnFamilies = new ArrayList<String>();\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        \n    }\n\n    @Before\n    public void setUp() throws Exception\n    {\n        columnFamilies.add(CassandraGeneratedIdDefault.class.getSimpleName());\n        columnFamilies.add(CassandraGeneratedIdStrategyAuto.class.getSimpleName());\n        columnFamilies.add(CassandraGeneratedIdStrategyIdentity.class.getSimpleName());\n        columnFamilies.add(CassandraGeneratedIdStrategySequence.class.getSimpleName());\n        columnFamilies.add(CassandraGeneratedIdStrategyTable.class.getSimpleName());\n        columnFamilies.add(CassandraGeneratedIdWithOutSequenceGenerator.class.getSimpleName());\n        columnFamilies.add(CassandraGeneratedIdWithOutTableGenerator.class.getSimpleName());\n        columnFamilies.add(CassandraGeneratedIdWithSequenceGenerator.class.getSimpleName());\n        columnFamilies.add(CassandraGeneratedIdWithTableGenerator.class.getSimpleName());\n        columnFamilies.add(EmployeeAddress.class.getSimpleName());\n        columnFamilies.add(EmployeeInfo.class.getSimpleName());\n        \n        CassandraCli.cassandraSetUp();\n        emf = Persistence.createEntityManagerFactory(\"cassandra_generated_id\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void test()\n    {\n        try\n        {\n            KsDef ksDef = CassandraCli.client.describe_keyspace(\"kunderaGeneratedId\");\n            Assert.assertNotNull(ksDef);\n            int count = 0;\n            for (CfDef cfDef : ksDef.cf_defs)\n            {\n                if (cfDef.getName().equals(\"kundera_sequences\"))\n                {\n                    Assert.assertTrue(cfDef.getColumn_type().equals(\"Standard\"));\n                    Assert.assertTrue(cfDef.getDefault_validation_class().equals(CounterColumnType.class.getName()));\n                    count++;\n                    continue;\n                }\n                if (cfDef.getName().equals(\"kundera\"))\n                {\n                    Assert.assertTrue(cfDef.getColumn_type().equals(\"Standard\"));\n                    Assert.assertTrue(cfDef.getDefault_validation_class().equals(CounterColumnType.class.getName()));\n                    count++;\n                }\n                else if (columnFamilies.contains(cfDef.getName()))\n                {\n                    Assert.assertTrue(cfDef.getColumn_type().equals(\"Standard\"));\n                    List<ColumnDef> columnDefs = cfDef.getColumn_metadata();\n                    Assert.assertEquals(1, columnDefs.size());\n                    count++;\n                }\n\n            }\n            Assert.assertEquals(13, count);\n        }\n        catch (NotFoundException e)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\", e.getMessage());\n\n        }\n        catch (InvalidRequestException e)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\", e.getMessage());\n\n        }\n        catch (TException e)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\", e.getMessage());\n\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/Actor.java",
    "content": "/**\n * \n */\npackage com.impetus.client.schemamanager.entites;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.CollectionTable;\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"Actor\", schema = \"KunderaCoreExmples@CassandraSchemaOperationTest\")\npublic class Actor\n{\n    @Id\n    @Column(name = \"actor_id\")\n    private String actorId;\n\n    // Element collection, will persist co-located\n    @ElementCollection\n    @CollectionTable(name = \"movie\")\n    private List<Movie> movies;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"FRIEND_ID\")\n    private List<Actor> friends; // List of users whom I follow\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"FOLLOWER_ID\")\n    private List<Actor> followers; // List of users who are following me\n\n    /**\n     * @return the actorId\n     */\n    public String getActorId()\n    {\n        return actorId;\n    }\n\n    /**\n     * @param actorId\n     *            the actorId to set\n     */\n    public void setActorId(String actorId)\n    {\n        this.actorId = actorId;\n    }\n\n    /**\n     * @return the tweets\n     */\n    public List<Movie> getTweets()\n    {\n        return movies;\n    }\n\n    /**\n     * @param movies\n     *            the tweets to set\n     */\n    public void addTweet(Movie tweet)\n    {\n        if (this.movies == null || this.movies.isEmpty())\n        {\n            this.movies = new ArrayList<Movie>();\n        }\n        this.movies.add(tweet);\n    }\n\n    /**\n     * @return the friends\n     */\n    public List<Actor> getFriends()\n    {\n        return friends;\n    }\n\n    /**\n     * @param friends\n     *            the friends to set\n     */\n    public void addFriend(Actor friend)\n    {\n        if (this.friends == null || this.friends.isEmpty())\n        {\n            this.friends = new ArrayList<Actor>();\n        }\n        this.friends.add(friend);\n    }\n\n    /**\n     * @return the followers\n     */\n    public List<Actor> getFollowers()\n    {\n        return followers;\n    }\n\n    /**\n     * @param followers\n     *            the followers to set\n     */\n    public void addFollower(Actor follower)\n    {\n        if (this.followers == null || this.followers.isEmpty())\n        {\n            this.followers = new ArrayList<Actor>();\n        }\n\n        this.followers.add(follower);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/ActorTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.schemamanager.entites;\n\nimport java.io.UnsupportedEncodingException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Cassandra;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class ActorTest\n{\n    private Cassandra.Client client;\n\n    private final boolean useLucene = false;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli cli = new CassandraCli();\n        client = cli.getClient();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"KunderaCoreExmples\");\n\n    }\n\n    @Test\n    public void test() throws NotFoundException, InvalidRequestException, TException, UnsupportedEncodingException\n    {\n        getEntityManagerFactory(\"create\");\n\n        Assert.assertTrue(CassandraCli.keyspaceExist(\"KunderaCoreExmples\"));\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"Actor\", \"KunderaCoreExmples\"));\n        org.apache.cassandra.thrift.KsDef ksDef = new KsDef();\n        ksDef = client.describe_keyspace(\"KunderaCoreExmples\");\n        Assert.assertEquals(2, ksDef.getCf_defs().size());\n        for (org.apache.cassandra.thrift.CfDef cfDef : ksDef.getCf_defs())\n        {\n            if (\"Actor\".equals(cfDef.getName()))\n            {\n                Assert.assertEquals(\"Standard\", cfDef.column_type);\n            }\n        }\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @param useLucene\n     * @param property\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory(String property)\n    {\n        Map propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, property);\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(\"CassandraSchemaOperationTest\",\n                propertyMap);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEmbeddedPersonUniMto1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityPersonUniMto1.\n */\n@Entity\n@Table(name = \"CassandraEmbeddedPersonUniMto1\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEmbeddedPersonUniMto1\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The personal data. */\n    @Embedded\n    private CassandraPersonalData personalData;\n\n    /** The address. */\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private CassandraEntityAddressUniMTo1 address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public CassandraPersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(CassandraPersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public CassandraEntityAddressUniMTo1 getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the address to set\n     */\n    public void setAddress(CassandraEntityAddressUniMTo1 address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityAddressBi1To1FK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityAddressBi1To1FK.\n */\n@Entity\n@Table(name = \"CassandraEntityAddressBi1To1FK\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityAddressBi1To1FK\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /** The person. */\n    @OneToOne(mappedBy = \"address\")\n    private CassandraEntityPersonBi1To1FK person;\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    /**\n     * Gets the person.\n     * \n     * @return the person\n     */\n    public CassandraEntityPersonBi1To1FK getPerson()\n    {\n        return person;\n    }\n\n    /**\n     * Sets the person.\n     * \n     * @param person\n     *            the new person\n     */\n    public void setPerson(CassandraEntityPersonBi1To1FK person)\n    {\n        this.person = person;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityAddressBi1To1PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityAddressBi1To1PK.\n */\n@Entity\n@Table(name = \"CassandraEntityAddressBi1To1PK\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityAddressBi1To1PK\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The address id. */\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /** The person. */\n    @OneToOne(mappedBy = \"address\", fetch = FetchType.LAZY)\n    private CassandraEntityPersonBi1To1PK person;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    /**\n     * Gets the person.\n     * \n     * @return the person\n     */\n    public CassandraEntityPersonBi1To1PK getPerson()\n    {\n        return person;\n    }\n\n    /**\n     * Sets the person.\n     * \n     * @param person\n     *            the new person\n     */\n    public void setPerson(CassandraEntityPersonBi1To1PK person)\n    {\n        this.person = person;\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityAddressBi1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityAddressBi1ToM.\n */\n@Entity\n@Table(name = \"CassandraEntityAddressBi1ToM\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityAddressBi1ToM\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /** The person. */\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private CassandraEntityPersonBi1ToM person;\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    /**\n     * Gets the person.\n     * \n     * @return the person\n     */\n    public CassandraEntityPersonBi1ToM getPerson()\n    {\n        return person;\n    }\n\n    /**\n     * Sets the person.\n     * \n     * @param person\n     *            the new person\n     */\n    public void setPerson(CassandraEntityPersonBi1ToM person)\n    {\n        this.person = person;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityAddressBiMTo1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityAddressBiMTo1.\n */\n@Entity\n@Table(name = \"CassandraEntityAddressBiMTo1\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityAddressBiMTo1\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /** The people. */\n    @OneToMany(mappedBy = \"address\", fetch = FetchType.LAZY)\n    private Set<CassandraEntityPersonBiMTo1> people;\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    /**\n     * Gets the people.\n     * \n     * @return the people\n     */\n    public Set<CassandraEntityPersonBiMTo1> getPeople()\n    {\n        return people;\n    }\n\n    /**\n     * Sets the people.\n     * \n     * @param people\n     *            the new people\n     */\n    public void setPeople(Set<CassandraEntityPersonBiMTo1> people)\n    {\n        this.people = people;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityAddressUni1To1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityAddressUni1To1.\n */\n@Entity\n@Table(name = \"CassandraEntityAddressUni1To1\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityAddressUni1To1\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityAddressUni1To1PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityAddressUni1To1PK.\n */\n@Entity\n@Table(name = \"CassandraEntityAddressUni1To1PK\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityAddressUni1To1PK\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The address id. */\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityAddressUni1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityAddressUni1ToM.\n */\n@Entity\n@Table(name = \"CassandraEntityAddressUni1ToM\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityAddressUni1ToM\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityAddressUniMTo1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityAddressUniMTo1.\n */\n@Entity\n@Table(name = \"CassandraEntityAddressUniMTo1\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityAddressUniMTo1\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityHabitatUniMToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"CassandraEntityHabitatUniMToM\", schema = \"KunderaExamples@cassandra\")\npublic class CassandraEntityHabitatUniMToM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityPersonBi1To1FK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityPersonBi1To1FK.\n */\n@Entity\n@Table(name = \"CassandraEntityPersonBi1To1FK\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityPersonBi1To1FK\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The personal data. */\n    @Embedded\n    private CassandraPersonalData personalData;\n\n    /** The address. */\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private CassandraEntityAddressBi1To1FK address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public CassandraPersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(CassandraPersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public CassandraEntityAddressBi1To1FK getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the new address\n     */\n    public void setAddress(CassandraEntityAddressBi1To1FK address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityPersonBi1To1PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityPersonBi1To1PK.\n */\n@Entity\n@Table(name = \"CassandraEntityPersonBi1To1PK\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityPersonBi1To1PK\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The personal data. */\n    @Embedded\n    private CassandraPersonalData personalData;\n\n    /** The address. */\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)\n    @PrimaryKeyJoinColumn\n    private CassandraEntityAddressBi1To1PK address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public CassandraPersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(CassandraPersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public CassandraEntityAddressBi1To1PK getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the new address\n     */\n    public void setAddress(CassandraEntityAddressBi1To1PK address)\n    {\n        this.address = address;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityPersonBi1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityPersonBi1ToM.\n */\n@Entity\n@Table(name = \"CassandraEntityPersonBi1ToM\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityPersonBi1ToM\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The personal data. */\n    @Embedded\n    private CassandraPersonalData personalData;\n\n    /** The addresses. */\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"person\")\n    private Set<CassandraEntityAddressBi1ToM> addresses;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(CassandraPersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public CassandraPersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Gets the addresses.\n     * \n     * @return the addresses\n     */\n    public Set<CassandraEntityAddressBi1ToM> getAddresses()\n    {\n        return addresses;\n    }\n\n    /**\n     * Sets the addresses.\n     * \n     * @param addresses\n     *            the new addresses\n     */\n    public void setAddresses(Set<CassandraEntityAddressBi1ToM> addresses)\n    {\n        this.addresses = addresses;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityPersonBiMTo1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n\n\n/**\n * The Class CassandraEntityPersonBiMTo1.\n */\n@Entity\n@Table(name = \"CassandraEntityPersonBiMTo1\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityPersonBiMTo1\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The personal data. */\n    @Embedded\n    private CassandraPersonalData personalData;\n\n    /** The address. */\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")    \n    private CassandraEntityAddressBiMTo1 address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public CassandraPersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(CassandraPersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public CassandraEntityAddressBiMTo1 getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the new address\n     */\n    public void setAddress(CassandraEntityAddressBiMTo1 address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityPersonUni1To1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityPersonUni1To1.\n */\n@Entity\n@Table(name = \"CassandraEntityPersonUni1To1\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityPersonUni1To1\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The personal data. */\n    @Embedded\n    private CassandraPersonalData personalData;\n\n    /** The address. */\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private CassandraEntityAddressUni1To1 address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public CassandraPersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(CassandraPersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public CassandraEntityAddressUni1To1 getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the address to set\n     */\n    public void setAddress(CassandraEntityAddressUni1To1 address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityPersonUni1To1PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityPersonUni1To1PK.\n */\n@Entity\n@Table(name = \"CassandraEntityPersonUni1To1PK\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityPersonUni1To1PK\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The personal data. */\n    @Embedded\n    CassandraPersonalData personalData;\n\n    /** The address. */\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)\n    @PrimaryKeyJoinColumn\n    private CassandraEntityAddressUni1To1PK address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public CassandraPersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(CassandraPersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public CassandraEntityAddressUni1To1PK getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the address to set\n     */\n    public void setAddress(CassandraEntityAddressUni1To1PK address)\n    {\n        this.address = address;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityPersonUni1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntityPersonUni1ToM.\n */\n@Entity\n@Table(name = \"CassandraEntityPersonUni1ToM\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntityPersonUni1ToM\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The personal data. */\n    @Embedded\n    private CassandraPersonalData personalData;\n\n    /** The addresses. */\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<CassandraEntityAddressUni1ToM> addresses;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public CassandraPersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(CassandraPersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the addresses.\n     * \n     * @return the addresses\n     */\n    public Set<CassandraEntityAddressUni1ToM> getAddresses()\n    {\n        return addresses;\n    }\n\n    /**\n     * Sets the addresses.\n     * \n     * @param addresses\n     *            the addresses to set\n     */\n    public void setAddresses(Set<CassandraEntityAddressUni1ToM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityPersonUniMto1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class CassandraEntityPersonUniMto1.\n */\n@Entity\n@Table(name = \"CassandraEntityPersonUniMto1\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\npublic class CassandraEntityPersonUniMto1\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The address. */\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private CassandraEntityAddressUniMTo1 address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public CassandraEntityAddressUniMTo1 getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the address to set\n     */\n    public void setAddress(CassandraEntityAddressUniMTo1 address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntityPersonnelUniMToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"CassandraEntityPersonnelUniMToM\", schema = \"KunderaExamples@cassandra\")\npublic class CassandraEntityPersonnelUniMToM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @Embedded\n    CassandraPersonalData personalData;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"PERSONNEL_ADDRESS\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Set<CassandraEntityHabitatUniMToM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<CassandraEntityHabitatUniMToM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<CassandraEntityHabitatUniMToM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n    /**\n     * @return the personalData\n     */\n    public CassandraPersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(CassandraPersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntitySimple.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class CassandraEntitySimple.\n */\n@Entity\n@Table(name = \"CassandraEntitySimple\", schema = \"KunderaCoreExmples@CassandraSchemaOperationTest\")\n@IndexCollection(columns = { @Index(name = \"personName\", type = \"KEYS\"), @Index(name = \"age\", type = \"KEYS\") })\npublic class CassandraEntitySimple\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraEntitySuper.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class CassandraEntitySuper.\n */\n@Entity\n@Table(name = \"CassandraEntitySuper\", schema = \"CassandraSchemaManagerTest@CassandraSchemaManager\")\npublic class CassandraEntitySuper\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The personal data. */\n    @Embedded\n    private CassandraPersonalData personalData;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public CassandraPersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(CassandraPersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CassandraPersonalData.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.schemamanager.entites;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\n/**\r\n * The Class CassandraPersonalData.\r\n */\r\n@Embeddable\r\npublic class CassandraPersonalData\r\n{\r\n\r\n    /** The website. */\r\n    @Column(name = \"p_website\")\r\n    private String website;\r\n\r\n    /** The email. */\r\n    @Column(name = \"p_email\")\r\n    private String email;\r\n\r\n    /** The yahoo id. */\r\n    @Column(name = \"p_yahoo_id\")\r\n    private String yahooId;\r\n\r\n    /**\r\n     * Instantiates a new cassandra personal data.\r\n     */\r\n    public CassandraPersonalData()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new cassandra personal data.\r\n     * \r\n     * @param website\r\n     *            the website\r\n     * @param email\r\n     *            the email\r\n     * @param yahooId\r\n     *            the yahoo id\r\n     */\r\n    public CassandraPersonalData(String website, String email, String yahooId)\r\n    {\r\n        this.website = website;\r\n        this.email = email;\r\n        this.yahooId = yahooId;\r\n    }\r\n\r\n    /**\r\n     * Gets the website.\r\n     * \r\n     * @return the website\r\n     */\r\n    public String getWebsite()\r\n    {\r\n        return website;\r\n    }\r\n\r\n    /**\r\n     * Sets the website.\r\n     * \r\n     * @param website\r\n     *            the new website\r\n     */\r\n    public void setWebsite(String website)\r\n    {\r\n        this.website = website;\r\n    }\r\n\r\n    /**\r\n     * Gets the email.\r\n     * \r\n     * @return the email\r\n     */\r\n    public String getEmail()\r\n    {\r\n        return email;\r\n    }\r\n\r\n    /**\r\n     * Sets the email.\r\n     * \r\n     * @param email\r\n     *            the email to set\r\n     */\r\n    public void setEmail(String email)\r\n    {\r\n        this.email = email;\r\n    }\r\n\r\n    /**\r\n     * Gets the yahoo id.\r\n     * \r\n     * @return the yahoo id\r\n     */\r\n    public String getYahooId()\r\n    {\r\n        return yahooId;\r\n    }\r\n\r\n    /**\r\n     * Sets the yahoo id.\r\n     * \r\n     * @param yahooId\r\n     *            the new yahoo id\r\n     */\r\n    public void setYahooId(String yahooId)\r\n    {\r\n        this.yahooId = yahooId;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/CompositeUser.java",
    "content": "/*******************************************************************************\n *  * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Embeddable\n@IndexCollection(columns = { @Index(name = \"tweetDate\"), @Index(name = \"firstName\") })\npublic class CompositeUser\n{\n\n    @Column\n    private String user_id;\n\n    @Column\n    private Date tweetDate;\n\n    @Column\n    private String firstName;\n\n    public CompositeUser()\n    {\n        \n    }\n    \n    public String getUser_id()\n    {\n        return user_id;\n    }\n\n    public void setUser_id(String user_id)\n    {\n        this.user_id = user_id;\n    }\n\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/Doctor.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author Kuldeep Mishra\n * @version 1.0\n * \n */\n@Entity\n@Table(name = \"DOCTOR\", schema = \"KunderaExamples@secIdxCassandraTest\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"key\") })\npublic class Doctor\n{\n    @Id\n    private String id;\n\n    @Column\n    private String name;\n\n    @Column\n    private long age;\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public long getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(long age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/InvalidCounterColumnEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"InvalidCounterColumnEntity\", schema = \"KunderaCounterColumn@cassandraProperties\")\npublic class InvalidCounterColumnEntity\n{\n\n    @Id\n    private int id;\n\n    @Column\n    private long counter;\n\n    @Column\n    private String lCounter;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the counter\n     */\n    public long getCounter()\n    {\n        return counter;\n    }\n\n    /**\n     * @param counter\n     *            the counter to set\n     */\n    public void setCounter(long counter)\n    {\n        this.counter = counter;\n    }\n\n    /**\n     * @return the lCounter\n     */\n    public String getlCounter()\n    {\n        return lCounter;\n    }\n\n    /**\n     * @param lCounter\n     *            the lCounter to set\n     */\n    public void setlCounter(String lCounter)\n    {\n        this.lCounter = lCounter;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/Movie.java",
    "content": "/**\n * \n */\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Embeddable\n@IndexCollection(columns = { @Index(name = \"title\"), @Index(name = \"released_year\") })\npublic class Movie\n{\n    @Column(name = \"movie_id\")\n    private String movieId;\n\n    @Column(name = \"title\")\n    private String title;\n\n    @Column(name = \"released_year\")\n    private String releasedYear;\n\n    /**\n     * @return the movieId\n     */\n    public String getMovieId()\n    {\n        return movieId;\n    }\n\n    /**\n     * @param movieId\n     *            the movieId to set\n     */\n    public void setMovieId(String movieId)\n    {\n        this.movieId = movieId;\n    }\n\n    /**\n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * @param title\n     *            the title to set\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * @return the releasedYear\n     */\n    public String getReleasedYear()\n    {\n        return releasedYear;\n    }\n\n    /**\n     * @param releasedYear\n     *            the releasedYear to set\n     */\n    public void setReleasedYear(String releasedYear)\n    {\n        this.releasedYear = releasedYear;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/TwitterUser.java",
    "content": "/*******************************************************************************\n *  * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n *         Composite user entity\n */\n@Entity\n@Table(name = \"TwitterUser\", schema = \"KunderaCoreExmples@CassandraSchemaOperationTest\")\npublic class TwitterUser\n{\n\n    @EmbeddedId\n    private CompositeUser compositeKey;\n\n    @Column\n    private String body;\n\n    @ElementCollection\n    private Set<String> followers;\n\n    public TwitterUser()\n    {\n\n    }\n\n    public CompositeUser getCompositeKey()\n    {\n        return compositeKey;\n    }\n\n    public void setCompositeKey(CompositeUser compositeKey)\n    {\n        this.compositeKey = compositeKey;\n    }\n\n    public String getBody()\n    {\n        return body;\n    }\n\n    public void setBody(String body)\n    {\n        this.body = body;\n    }\n\n    public Set<String> getFollowers()\n    {\n        return followers;\n    }\n\n    public void setFollowers(Set<String> followers)\n    {\n        this.followers = followers;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/schemamanager/entites/ValidCounterColumnFamily.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.schemamanager.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"ValidCounterColumnFamily\", schema = \"KunderaCounterColumn@cassandraProperties\")\npublic class ValidCounterColumnFamily\n{\n\n    @Id\n    private int id;\n\n    @Column\n    private long counter;\n\n    @Column\n    private Long lCounter;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the counter\n     */\n    public long getCounter()\n    {\n        return counter;\n    }\n\n    /**\n     * @param counter\n     *            the counter to set\n     */\n    public void setCounter(long counter)\n    {\n        this.counter = counter;\n    }\n\n    /**\n     * @return the lCounter\n     */\n    public Long getlCounter()\n    {\n        return lCounter;\n    }\n\n    /**\n     * @param lCounter\n     *            the lCounter to set\n     */\n    public void setlCounter(Long lCounter)\n    {\n        this.lCounter = lCounter;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/twitter/TwissandraSuperColumnDatatypeTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.twitter;\n\nimport java.io.IOException;\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport org.apache.cassandra.locator.SimpleStrategy;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.twitter.entities.ProfessionalDetailCassandra;\nimport com.impetus.client.twitter.entities.UserCassandra;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Test case for data type compatibility testing for Twissandra\n * \n * @author amresh.singh\n */\npublic class TwissandraSuperColumnDatatypeTest extends TwitterTestBaseCassandra\n{\n    /** The Constant LOG. */\n    private static final Logger log = LoggerFactory.getLogger(TwissandraSuperColumnDatatypeTest.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal(persistenceUnit);\n    }\n\n    @Test\n    public void onExecute() throws Exception\n    {\n        // Insert, Find and Update\n        addAllUserInfo();\n        getUserById();\n        updateUser();\n\n        // Queries for all data types\n        getUserByProfessionId();\n        getUserByDepartmentName();\n        getExceptionalUsers();\n        getUserByAge();\n        getUserByGrade();\n        getUserByDigitalSignature();\n        getUserByRating();\n        getUserByCompliance();\n        getUserByHeight();\n        getUserByEnrolmentDate();\n        getUserByEnrolmentTime();\n        getUserByJoiningDateAndTime();\n\n        getUserByYearsSpent();\n        getUserByUniqueId();\n        getUserByMonthlySalary();\n        getUserByBirthday();\n        getUserByBirthtime();\n        getUserByAnniversary();\n        getUserByJobAttempts();\n        getUserByAccumulatedWealth();\n        getUserByGraduationDay();\n\n        // Remove Users\n        removeUsers();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        tearDownInternal();\n    }\n\n    @Override\n    void startServer()\n    {\n        try\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        catch (IOException e)\n        {\n            log.error(e.getMessage(),e);\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage(),e);\n        }\n    }\n\n    /************** Queries on Professional Data ****************/\n    void getUserByProfessionId()\n    {\n        // User 1\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByProfessionId(1234567);\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(1234567, pd.getProfessionId());\n        twitter.closeEntityManager();\n\n        // User2\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByProfessionId(1234568);\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(1234568, pd2.getProfessionId());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByDepartmentName()\n    {\n        // User 1\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByDepartment(\"Labs\");\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(\"Labs\", pd.getDepartmentName());\n        twitter.closeEntityManager();\n\n        // User2\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByDepartment(\"ODC\");\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(\"ODC\", pd2.getDepartmentName());\n        twitter.closeEntityManager();\n    }\n\n    void getExceptionalUsers()\n    {\n        // User 1\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findExceptionalUsers();\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId2, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(true, pd.isExceptional());\n        twitter.closeEntityManager();\n\n    }\n\n    void getUserByAge()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByAge(31);\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(31, pd.getAge());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByAge(32);\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(32, pd2.getAge());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByGrade()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByGrade('C');\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals('C', pd.getGrade());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByGrade('A');\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals('A', pd2.getGrade());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByDigitalSignature()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByDigitalSignature((byte) 8);\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals((byte) 8, pd.getDigitalSignature());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByDigitalSignature((byte) 10);\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals((byte) 10, pd2.getDigitalSignature());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByRating()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByRating((short) 5);\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals((short) 5, pd.getRating());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByRating((short) 8);\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals((short) 8, pd2.getRating());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByCompliance()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByCompliance((float) 10.0);\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals((float) 10.0, pd.getCompliance(), 0.0);\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByCompliance((float) 9.80);\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals((float) 9.80, pd2.getCompliance(), 0.0);\n        twitter.closeEntityManager();\n    }\n\n    void getUserByHeight()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByHeight(163.12);\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(163.12, pd.getHeight(), 0.0);\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByHeight(323.3);\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(323.3, pd2.getHeight(), 0.0);\n        twitter.closeEntityManager();\n\n    }\n\n    void getUserByEnrolmentDate()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByEnrolmentDate(new Date(Long.parseLong(\"1344079065781\")));\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(new Date(Long.parseLong(\"1344079065781\")), pd.getEnrolmentDate());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByEnrolmentDate(new Date(Long.parseLong(\"1344079063412\")));\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(new Date(Long.parseLong(\"1344079063412\")), pd2.getEnrolmentDate());\n        twitter.closeEntityManager();\n\n    }\n\n    void getUserByEnrolmentTime()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByEnrolmentTime(new Date(Long.parseLong(\"1344079067623\")));\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(new Date(Long.parseLong(\"1344079067623\")), pd.getEnrolmentTime());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByEnrolmentTime(new Date(Long.parseLong(\"1344079068266\")));\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(new Date(Long.parseLong(\"1344079068266\")), pd2.getEnrolmentTime());\n        twitter.closeEntityManager();\n\n    }\n\n    void getUserByJoiningDateAndTime()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByJoiningDateAndTime(new Date(Long.parseLong(\"1344079069105\")));\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(new Date(Long.parseLong(\"1344079069105\")), pd.getJoiningDateAndTime());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByJoiningDateAndTime(new Date(Long.parseLong(\"1344079061078\")));\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(new Date(Long.parseLong(\"1344079061078\")), pd2.getJoiningDateAndTime());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByYearsSpent()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByYearsSpent(new Integer(2));\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(new Integer(2), pd.getYearsSpent());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByYearsSpent(new Integer(5));\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(new Integer(5), pd2.getYearsSpent());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByUniqueId()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByUniqueId(new Long(3634521523423L));\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(new Long(3634521523423L), pd.getUniqueId());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByUniqueId(new Long(25423452343L));\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(new Long(25423452343L), pd2.getUniqueId());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByMonthlySalary()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByMonthlySalary(new Double(0.23452342343));\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(new Double(0.23452342343), pd.getMonthlySalary());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByMonthlySalary(new Double(0.76452343));\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(new Double(0.76452343), pd2.getMonthlySalary());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByBirthday()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByBirthday(new java.sql.Date(new Date(Long\n                .parseLong(\"1344079061111\")).getTime()));\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(new java.sql.Date(new Date(Long.parseLong(\"1344079061111\")).getTime()), pd.getBirthday());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByBirthday(new java.sql.Date(new Date(Long\n                .parseLong(\"1344079064444\")).getTime()));\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(new java.sql.Date(new Date(Long.parseLong(\"1344079064444\")).getTime()), pd2.getBirthday());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByBirthtime()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByBirthtime(new java.sql.Time(new Date(Long\n                .parseLong(\"1344079062222\")).getTime()));\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(new java.sql.Time(new Date(Long.parseLong(\"1344079062222\")).getTime()), pd.getBirthtime());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByBirthtime(new java.sql.Time(new Date(Long\n                .parseLong(\"1344079065555\")).getTime()));\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(new java.sql.Time(new Date(Long.parseLong(\"1344079065555\")).getTime()), pd2.getBirthtime());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByAnniversary()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByAnniversary(new java.sql.Timestamp(new Date(Long\n                .parseLong(\"13440790653333\")).getTime()));\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(new java.sql.Timestamp(new Date(Long.parseLong(\"13440790653333\")).getTime()),\n                pd.getAnniversary());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByAnniversary(new java.sql.Timestamp(new Date(Long\n                .parseLong(\"1344079066666\")).getTime()));\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(new java.sql.Timestamp(new Date(Long.parseLong(\"1344079066666\")).getTime()),\n                pd2.getAnniversary());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByJobAttempts()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByJobAttempts(new BigInteger(\"123456789\"));\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(new BigInteger(\"123456789\"), pd.getJobAttempts());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByJobAttempts(new BigInteger(\"123456790\"));\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(new BigInteger(\"123456790\"), pd2.getJobAttempts());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByAccumulatedWealth()\n    {\n        twitter.createEntityManager();\n        List<UserCassandra> users = twitter.findUserByAccumulatedWealth(new BigDecimal(123456789));\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(new BigDecimal(123456789), pd.getAccumulatedWealth());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n        List<UserCassandra> users2 = twitter.findUserByAccumulatedWealth(new BigDecimal(123456790));\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(new BigDecimal(123456790), pd2.getAccumulatedWealth());\n        twitter.closeEntityManager();\n    }\n\n    void getUserByGraduationDay()\n    {\n        twitter.createEntityManager();\n\n        Calendar cal = Calendar.getInstance();\n        cal.setTime(new Date(1344079067777l));\n        List<UserCassandra> users = twitter.findUserByGraduationDay(cal);\n        Assert.assertNotNull(users);\n        Assert.assertFalse(users.isEmpty());\n        Assert.assertTrue(users.size() == 1);\n        UserCassandra user = users.get(0);\n        Assert.assertNotNull(user);\n        Assert.assertEquals(userId1, user.getUserId());\n        ProfessionalDetailCassandra pd = user.getProfessionalDetail();\n        Assert.assertNotNull(pd);\n        Assert.assertEquals(cal, pd.getGraduationDay());\n        twitter.closeEntityManager();\n\n        twitter.createEntityManager();\n\n        Calendar cal2 = Calendar.getInstance();\n        cal2.setTime(new Date(1344079068888l));\n        List<UserCassandra> users2 = twitter.findUserByGraduationDay(cal2);\n        Assert.assertNotNull(users2);\n        Assert.assertFalse(users2.isEmpty());\n        Assert.assertTrue(users2.size() == 1);\n        UserCassandra user2 = users2.get(0);\n        Assert.assertNotNull(user2);\n        Assert.assertEquals(userId2, user2.getUserId());\n        ProfessionalDetailCassandra pd2 = user2.getProfessionalDetail();\n        Assert.assertNotNull(pd2);\n        Assert.assertEquals(cal2, pd2.getGraduationDay());\n        twitter.closeEntityManager();\n    }\n\n    @Override\n    void stopServer()\n    {\n    }\n\n    @Override\n    void createSchema() throws InvalidRequestException, SchemaDisagreementException, TException\n    {\n        KsDef ksDef = null;\n        CfDef userCfDef = new CfDef();\n        userCfDef.name = \"USER\";\n        userCfDef.keyspace = keyspace;\n        userCfDef.column_type = \"Super\";\n        userCfDef.setComparator_type(\"UTF8Type\");\n        userCfDef.setSubcomparator_type(\"AsciiType\");\n        userCfDef.setKey_validation_class(\"UTF8Type\");\n\n        CfDef userIndexCfDef = new CfDef();\n        userIndexCfDef.name = \"USER\" + Constants.INDEX_TABLE_SUFFIX;\n        userIndexCfDef.column_type = \"Super\";\n        userIndexCfDef.keyspace = keyspace;\n        userCfDef.setKey_validation_class(\"AsciiType\");\n\n        CfDef prefrenceCfDef = new CfDef();\n        prefrenceCfDef.name = \"PREFERENCE\";\n        prefrenceCfDef.keyspace = keyspace;\n        prefrenceCfDef.setComparator_type(\"UTF8Type\");\n        prefrenceCfDef.setDefault_validation_class(\"UTF8Type\");\n        prefrenceCfDef.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"WEBSITE_THEME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"PRIVACY_LEVEL\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        prefrenceCfDef.addToColumn_metadata(columnDef);\n        prefrenceCfDef.addToColumn_metadata(columnDef3);\n\n        CfDef externalLinkCfDef = new CfDef();\n        externalLinkCfDef.name = \"EXTERNAL_LINK\";\n        externalLinkCfDef.keyspace = keyspace;\n        externalLinkCfDef.setComparator_type(\"UTF8Type\");\n        externalLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        externalLinkCfDef.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"LINK_TYPE\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"LINK_ADDRESS\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"USER_ID\".getBytes()), \"UTF8Type\");\n        columnDef4.index_type = IndexType.KEYS;\n        externalLinkCfDef.addToColumn_metadata(columnDef1);\n        externalLinkCfDef.addToColumn_metadata(columnDef2);\n        externalLinkCfDef.addToColumn_metadata(columnDef4);\n\n        /*\n         * CfDef userCfDef = new CfDef(); userCfDef.name = \"USER\";\n         * userCfDef.keyspace = keyspace; userCfDef.column_type = \"Super\";\n         * userCfDef.setComparator_type(\"UTF8Type\");\n         * userCfDef.setSubcomparator_type(\"AsciiType\");\n         * userCfDef.setKey_validation_class(\"UTF8Type\");\n         * \n         * CfDef userIndexCfDef = new CfDef(); userIndexCfDef.name = \"USER\" +\n         * Constants.INDEX_TABLE_SUFFIX; userIndexCfDef.column_type = \"Super\";\n         * userIndexCfDef.keyspace = keyspace;\n         * userIndexCfDef.setKey_validation_class(\"UTF8Type\");\n         * \n         * CfDef prefrenceCfDef = new CfDef(); prefrenceCfDef.name =\n         * \"PREFERENCE\"; prefrenceCfDef.keyspace = keyspace;\n         * prefrenceCfDef.setComparator_type(\"UTF8Type\");\n         * prefrenceCfDef.setDefault_validation_class(\"UTF8Type\"); ColumnDef\n         * columnDef = new\n         * ColumnDef(ByteBuffer.wrap(\"WEBSITE_THEME\".getBytes()), \"UTF8Type\");\n         * columnDef.index_type = IndexType.KEYS; ColumnDef columnDef3 = new\n         * ColumnDef(ByteBuffer.wrap(\"PRIVACY_LEVEL\".getBytes()), \"UTF8Type\");\n         * columnDef3.index_type = IndexType.KEYS;\n         * prefrenceCfDef.addToColumn_metadata(columnDef);\n         * prefrenceCfDef.addToColumn_metadata(columnDef3);\n         * \n         * CfDef externalLinkCfDef = new CfDef(); externalLinkCfDef.name =\n         * \"EXTERNAL_LINK\"; externalLinkCfDef.keyspace = keyspace;\n         * externalLinkCfDef.setComparator_type(\"UTF8Type\");\n         * externalLinkCfDef.setDefault_validation_class(\"UTF8Type\"); ColumnDef\n         * columnDef1 = new ColumnDef(ByteBuffer.wrap(\"LINK_TYPE\".getBytes()),\n         * \"UTF8Type\"); columnDef1.index_type = IndexType.KEYS; ColumnDef\n         * columnDef2 = new\n         * ColumnDef(ByteBuffer.wrap(\"LINK_ADDRESS\".getBytes()), \"UTF8Type\");\n         * columnDef2.index_type = IndexType.KEYS; ColumnDef columnDef4 = new\n         * ColumnDef(ByteBuffer.wrap(\"USER_ID\".getBytes()), \"UTF8Type\");\n         * columnDef4.index_type = IndexType.KEYS;\n         * externalLinkCfDef.addToColumn_metadata(columnDef1);\n         * externalLinkCfDef.addToColumn_metadata(columnDef2);\n         * externalLinkCfDef.addToColumn_metadata(columnDef4);\n         */\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(userCfDef);\n        cfDefs.add(userIndexCfDef);\n        cfDefs.add(prefrenceCfDef);\n        cfDefs.add(externalLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(keyspace);\n            CassandraCli.client.set_keyspace(keyspace);\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"USER\"))\n                {\n                    CassandraCli.client.system_drop_column_family(\"USER\");\n                }\n                if (cfDef1.getName().equalsIgnoreCase(\"USER\" + Constants.INDEX_TABLE_SUFFIX))\n                {\n                    CassandraCli.client.system_drop_column_family(\"USER\" + Constants.INDEX_TABLE_SUFFIX);\n                }\n                if (cfDef1.getName().equalsIgnoreCase(\"PREFERENCE\"))\n                {\n                    CassandraCli.client.system_drop_column_family(\"PREFERENCE\");\n                }\n                if (cfDef1.getName().equalsIgnoreCase(\"EXTERNAL_LINK\"))\n                {\n                    CassandraCli.client.system_drop_column_family(\"EXTERNAL_LINK\");\n                }\n            }\n            CassandraCli.client.system_add_column_family(userCfDef);\n            CassandraCli.client.system_add_column_family(userIndexCfDef);\n            CassandraCli.client.system_add_column_family(externalLinkCfDef);\n            CassandraCli.client.system_add_column_family(prefrenceCfDef);\n        }\n        catch (NotFoundException e)\n        {\n            ksDef = new KsDef(keyspace, SimpleStrategy.class.getSimpleName(), cfDefs);\n\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage(),e);\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage(),e);\n        }\n    }\n\n    @Override\n    void deleteSchema()\n    {\n        CassandraCli.dropKeySpace(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/twitter/TwissandraTest.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter;\r\n\r\nimport java.io.IOException;\r\nimport java.nio.ByteBuffer;\r\nimport java.util.ArrayList;\r\nimport java.util.LinkedHashMap;\r\nimport java.util.List;\r\n\r\nimport org.apache.cassandra.locator.SimpleStrategy;\r\nimport org.apache.cassandra.thrift.CfDef;\r\nimport org.apache.cassandra.thrift.ColumnDef;\r\nimport org.apache.cassandra.thrift.IndexType;\r\nimport org.apache.cassandra.thrift.InvalidRequestException;\r\nimport org.apache.cassandra.thrift.KsDef;\r\nimport org.apache.cassandra.thrift.NotFoundException;\r\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\r\nimport org.apache.thrift.TException;\r\nimport org.databene.contiperf.PerfTest;\r\nimport org.databene.contiperf.junit.ContiPerfRule;\r\nimport org.databene.contiperf.report.CSVSummaryReportModule;\r\nimport org.databene.contiperf.report.HtmlReportModule;\r\nimport org.databene.contiperf.report.ReportModule;\r\nimport org.junit.After;\r\nimport org.junit.Before;\r\nimport org.junit.Rule;\r\nimport org.junit.Test;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.Constants;\r\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\r\n\r\n/**\r\n * Test case for Cassandra.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class TwissandraTest extends TwitterTestBaseCassandra\r\n{\r\n\r\n    /** The Constant LOG. */\r\n    private static final Logger log = LoggerFactory.getLogger(TwissandraTest.class);\r\n\r\n    @Rule\r\n    public ContiPerfRule i = new ContiPerfRule(new ReportModule[] { new CSVSummaryReportModule(),\r\n            new HtmlReportModule() });\r\n\r\n    @Before\r\n    public void setUp() throws Exception\r\n    {\r\n        setUpInternal(persistenceUnit);\r\n    }\r\n\r\n    @Test\r\n    @PerfTest(invocations = 10)\r\n    public void onExecute() throws Exception\r\n    {\r\n        executeTwissandraTest();\r\n    }\r\n\r\n    @After\r\n    public void tearDown() throws Exception\r\n    {\r\n        tearDownInternal();\r\n    }\r\n\r\n    @Override\r\n    void startServer()\r\n    {\r\n        try\r\n        {\r\n            CassandraCli.cassandraSetUp();\r\n        }\r\n        catch (IOException e)\r\n        {\r\n            \r\n        }\r\n        catch (TException e)\r\n        {\r\n            \r\n        }\r\n    }\r\n\r\n    @Override\r\n    void stopServer()\r\n    {\r\n    }\r\n\r\n    @Override\r\n    void createSchema() throws InvalidRequestException, SchemaDisagreementException, TException\r\n    {\r\n        KsDef ksDef = null;\r\n\r\n        CfDef userCfDef = new CfDef();\r\n        userCfDef.name = \"USER\";\r\n        userCfDef.keyspace = keyspace;\r\n        userCfDef.column_type = \"Super\";\r\n        userCfDef.setComparator_type(\"UTF8Type\");\r\n        userCfDef.setSubcomparator_type(\"AsciiType\");\r\n        userCfDef.setKey_validation_class(\"UTF8Type\");\r\n\r\n        CfDef userIndexCfDef = new CfDef();\r\n        userIndexCfDef.name = \"USER\" + Constants.INDEX_TABLE_SUFFIX;\r\n        userIndexCfDef.column_type = \"Super\";\r\n        userIndexCfDef.keyspace = keyspace;\r\n        userCfDef.setKey_validation_class(\"AsciiType\");\r\n\r\n        CfDef prefrenceCfDef = new CfDef();\r\n        prefrenceCfDef.name = \"PREFERENCE\";\r\n        prefrenceCfDef.keyspace = keyspace;\r\n        prefrenceCfDef.setComparator_type(\"UTF8Type\");\r\n        prefrenceCfDef.setDefault_validation_class(\"UTF8Type\");\r\n        prefrenceCfDef.setKey_validation_class(\"UTF8Type\");\r\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"WEBSITE_THEME\".getBytes()), \"UTF8Type\");\r\n        columnDef.index_type = IndexType.KEYS;\r\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"PRIVACY_LEVEL\".getBytes()), \"UTF8Type\");\r\n        columnDef3.index_type = IndexType.KEYS;\r\n        prefrenceCfDef.addToColumn_metadata(columnDef);\r\n        prefrenceCfDef.addToColumn_metadata(columnDef3);\r\n\r\n        CfDef externalLinkCfDef = new CfDef();\r\n        externalLinkCfDef.name = \"EXTERNAL_LINK\";\r\n        externalLinkCfDef.keyspace = keyspace;\r\n        externalLinkCfDef.setComparator_type(\"UTF8Type\");\r\n        externalLinkCfDef.setDefault_validation_class(\"UTF8Type\");\r\n        externalLinkCfDef.setKey_validation_class(\"UTF8Type\");\r\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"LINK_TYPE\".getBytes()), \"UTF8Type\");\r\n        columnDef1.index_type = IndexType.KEYS;\r\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"LINK_ADDRESS\".getBytes()), \"UTF8Type\");\r\n        columnDef2.index_type = IndexType.KEYS;\r\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"USER_ID\".getBytes()), \"UTF8Type\");\r\n        columnDef4.index_type = IndexType.KEYS;\r\n        externalLinkCfDef.addToColumn_metadata(columnDef1);\r\n        externalLinkCfDef.addToColumn_metadata(columnDef2);\r\n        externalLinkCfDef.addToColumn_metadata(columnDef4);\r\n\r\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\r\n        cfDefs.add(userCfDef);\r\n        cfDefs.add(userIndexCfDef);\r\n        cfDefs.add(prefrenceCfDef);\r\n        cfDefs.add(externalLinkCfDef);\r\n        try\r\n        {\r\n            ksDef = CassandraCli.client.describe_keyspace(keyspace);\r\n            CassandraCli.client.set_keyspace(keyspace);\r\n            List<CfDef> cfDefn = ksDef.getCf_defs();\r\n\r\n            for (CfDef cfDef1 : cfDefn)\r\n            {\r\n\r\n                if (cfDef1.getName().equalsIgnoreCase(\"USER\"))\r\n                {\r\n                    CassandraCli.client.system_drop_column_family(\"USER\");\r\n                }\r\n                if (cfDef1.getName().equalsIgnoreCase(\"USER\" + Constants.INDEX_TABLE_SUFFIX))\r\n                {\r\n                    CassandraCli.client.system_drop_column_family(\"USER\" + Constants.INDEX_TABLE_SUFFIX);\r\n                }\r\n                if (cfDef1.getName().equalsIgnoreCase(\"PREFERENCE\"))\r\n                {\r\n                    CassandraCli.client.system_drop_column_family(\"PREFERENCE\");\r\n                }\r\n                if (cfDef1.getName().equalsIgnoreCase(\"EXTERNAL_LINK\"))\r\n                {\r\n                    CassandraCli.client.system_drop_column_family(\"EXTERNAL_LINK\");\r\n                }\r\n            }\r\n            CassandraCli.client.system_add_column_family(userCfDef);\r\n            CassandraCli.client.system_add_column_family(userIndexCfDef);\r\n            CassandraCli.client.system_add_column_family(externalLinkCfDef);\r\n            CassandraCli.client.system_add_column_family(prefrenceCfDef);\r\n        }\r\n        catch (NotFoundException e)\r\n        {\r\n            ksDef = new KsDef(keyspace, SimpleStrategy.class.getSimpleName(), cfDefs);\r\n\r\n            // Set replication factor\r\n            if (ksDef.strategy_options == null)\r\n            {\r\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\r\n            }\r\n            // Set replication factor, the value MUST be an integer\r\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\r\n\r\n            CassandraCli.client.system_add_keyspace(ksDef);\r\n        }\r\n        catch (InvalidRequestException e)\r\n        {\r\n            log.error(e.getMessage());\r\n        }\r\n        catch (TException e)\r\n        {\r\n            log.error(e.getMessage());\r\n        }\r\n    }\r\n\r\n    @Override\r\n    void deleteSchema()\r\n    {\r\n        /*\r\n         * LOG.warn(\r\n         * \"Truncating Column families and finally dropping Keyspace KunderaExamples in Cassandra....\"\r\n         * ); CassandraCli.dropColumnFamily(\"USER\", keyspace);\r\n         * CassandraCli.dropColumnFamily(\"PREFERENCE\", keyspace);\r\n         * CassandraCli.dropColumnFamily(\"EXTERNAL_LINKS\", keyspace);\r\n         * CassandraCli.dropKeySpace(keyspace);\r\n         */\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/twitter/TwitterTestBaseCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter;\r\n\r\nimport java.math.BigDecimal;\r\nimport java.math.BigInteger;\r\nimport java.util.Calendar;\r\nimport java.util.Date;\r\nimport java.util.List;\r\n\r\nimport org.apache.cassandra.thrift.InvalidRequestException;\r\nimport org.apache.cassandra.thrift.NotFoundException;\r\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\r\nimport org.apache.thrift.TException;\r\nimport org.junit.Assert;\r\n\r\nimport com.impetus.client.twitter.dao.TwitterCassandra;\r\nimport com.impetus.client.twitter.dao.TwitterServiceCassandra;\r\nimport com.impetus.client.twitter.entities.ExternalLinkCassandra;\r\nimport com.impetus.client.twitter.entities.PersonalDetailCassandra;\r\nimport com.impetus.client.twitter.entities.PreferenceCassandra;\r\nimport com.impetus.client.twitter.entities.ProfessionalDetailCassandra;\r\nimport com.impetus.client.twitter.entities.TweetCassandra;\r\nimport com.impetus.client.twitter.entities.UserCassandra;\r\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\r\n\r\n/**\r\n * Test case for Cassandra Cassandra-cli commands for running with standalone\r\n * cassandra server: ********** Cassandra-cli commands ************* drop\r\n * keyspace KunderaExamples; create keyspace KunderaExamples; use\r\n * KunderaExamples; create column family USER with column_type=Super and\r\n * comparator=UTF8Type and subcomparator = AsciiType and\r\n * key_validation_class=UTF8Type; create column family USER_INVRTD_IDX with\r\n * column_type=Super and key_validation_class=UTF8Type; create column family\r\n * PREFERENCE; create column family EXTERNAL_LINK with comparator=UTF8Type and\r\n * default_validation_class=UTF8Type and key_validation_class=UTF8Type and\r\n * column_metadata=[{column_name: USER_ID, validation_class:UTF8Type,\r\n * index_type: KEYS}]; describe KunderaExamples;\r\n * \r\n * @author amresh.singh\r\n */\r\npublic abstract class TwitterTestBaseCassandra\r\n{\r\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\r\n\r\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\r\n\r\n    public static final String persistenceUnit = \"twissandraTest\";\r\n\r\n    public static final String keyspace = \"KunderaExamples\";\r\n\r\n    /** The user id1. */\r\n    String userId1;\r\n\r\n    /** The user id2. */\r\n    String userId2;\r\n\r\n    /** The twitter. */\r\n    protected TwitterCassandra twitter;\r\n\r\n    /**\r\n     * Sets the up internal.\r\n     * \r\n     * @param persistenceUnitName\r\n     *            the new up internal\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    protected void setUpInternal(String persistenceUnitName) throws Exception\r\n    {\r\n        userId1 = \"0001\";\r\n        userId2 = \"0002\";\r\n\r\n        // Start Cassandra Server\r\n        if (RUN_IN_EMBEDDED_MODE)\r\n        {\r\n            startServer();\r\n        }\r\n\r\n        // Create Schema\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            CassandraCli.initClient();\r\n            createSchema();\r\n        }\r\n        \r\n        twitter = new TwitterServiceCassandra(persistenceUnitName);\r\n\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see junit.framework.TestCase#tearDown()\r\n     */\r\n    /**\r\n     * Tear down internal.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    protected void tearDownInternal() throws Exception\r\n    {\r\n        if (twitter != null)\r\n        {\r\n            twitter.close();\r\n        }\r\n\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            deleteSchema();\r\n        }\r\n\r\n        // Stop Server\r\n        if (RUN_IN_EMBEDDED_MODE)\r\n        {\r\n            stopServer();\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Execute suite.\r\n     */\r\n    protected void executeTwissandraTest()\r\n    {\r\n        // Insert, Find and Update\r\n        addAllUserInfo();\r\n        getUserById();\r\n        updateUser();\r\n\r\n        // Queries\r\n        getPersonalDetailByName();\r\n        getAllUsers();\r\n        getTweetsByDevice();\r\n        getTweetsByRelationshipAndDevice();\r\n        getTweetsByUserIdAndDevice();\r\n\r\n        // Remove Users\r\n        removeUsers();\r\n    }\r\n\r\n    protected void addAllUserInfo()\r\n    {\r\n        UserCassandra user1 = buildUser1();\r\n        UserCassandra user2 = buildUser2();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addUser(user1);\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addUser(user2);\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    protected void getUserById()\r\n    {\r\n        twitter.createEntityManager();\r\n        UserCassandra user1 = twitter.findUserById(userId1);\r\n        assertUser1(user1);\r\n\r\n        UserCassandra user2 = twitter.findUserById(userId2);\r\n        assertUser2(user2);\r\n    }\r\n\r\n    protected void updateUser()\r\n    {\r\n        twitter.createEntityManager();\r\n        UserCassandra user1 = twitter.findUserById(userId1);\r\n        assertUser1(user1);\r\n\r\n        user1.setPersonalDetail(new PersonalDetailCassandra(\"Vivek\", \"unknown\", \"Married\", 24));\r\n        user1.addTweet(new TweetCassandra(\"My Third Tweet\", \"iPhone\"));\r\n        twitter.mergeUser(user1);\r\n\r\n        UserCassandra user1AfterMerge = twitter.findUserById(userId1);\r\n\r\n        assertUpdatedUser1(user1AfterMerge);\r\n\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    protected void removeUsers()\r\n    {\r\n        twitter.createEntityManager();\r\n        UserCassandra user1 = twitter.findUserById(userId1);\r\n        assertUpdatedUser1(user1);\r\n\r\n        twitter.removeUser(user1);\r\n        \r\n        UserCassandra user1AfterRemoval = twitter.findUserById(userId1);\r\n        Assert.assertNull(user1AfterRemoval);\r\n\r\n        UserCassandra user2 = twitter.findUserById(userId2);\r\n        assertUser2(user2);\r\n\r\n        twitter.removeUser(user2);\r\n\r\n        UserCassandra user2AfterRemoval = twitter.findUserById(userId2);\r\n        Assert.assertNull(user2AfterRemoval);\r\n\r\n        twitter.closeEntityManager();\r\n\r\n    }\r\n\r\n    protected void getAllUsers()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<UserCassandra> users = twitter.getAllUsers();\r\n        Assert.assertNotNull(users);\r\n        Assert.assertFalse(users.isEmpty());\r\n        Assert.assertEquals(2, users.size());\r\n\r\n        for (UserCassandra u : users)\r\n        {\r\n            Assert.assertNotNull(u);\r\n            if (u.getUserId().equals(userId1))\r\n            {\r\n                assertUpdatedUser1(u);\r\n            }\r\n            else if (u.getUserId().equals(userId2))\r\n            {\r\n                assertUser2(u);\r\n            }\r\n        }\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Adds the users.\r\n     */\r\n    protected void addUsers()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addUser(userId1, \"Amresh\", \"password1\", \"married\", 25);\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addUser(userId2, \"Saurabh\", \"password2\", \"single\", 25);\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Save preference.\r\n     */\r\n    protected void savePreference()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.savePreference(userId1, new PreferenceCassandra(\"P1\", \"Motif\", \"2\"));\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.savePreference(userId2, new PreferenceCassandra(\"P2\", \"High Contrast\", \"3\"));\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Adds the external links.\r\n     */\r\n    protected void addExternalLinks()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId1, \"L1\", \"Facebook\", \"http://facebook.com/coolnerd\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId1, \"L2\", \"LinkedIn\", \"http://linkedin.com/in/devilmate\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId2, \"L3\", \"GooglePlus\", \"http://plus.google.com/inviteme\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId2, \"L4\", \"Yahoo\", \"http://yahoo.com/profiles/itsmeamry\");\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Adds the tweets.\r\n     */\r\n    protected void addTweets()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId1, \"Here is my first tweet\", \"Web\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId1, \"Second Tweet from me\", \"Mobile\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId2, \"Saurabh tweets for the first time\", \"Phone\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId2, \"Another tweet from Saurabh\", \"text\");\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * User1 follows user2.\r\n     */\r\n    protected void user1FollowsUser2()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.startFollowing(userId1, userId2);\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * User1 adds user2 as follower.\r\n     */\r\n    protected void user1AddsUser2AsFollower()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addFollower(userId1, userId2);\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Gets the all tweets.\r\n     * \r\n     * @return the all tweets\r\n     */\r\n    protected void getAllTweets()\r\n    {\r\n        twitter.createEntityManager();\r\n\r\n        List<TweetCassandra> tweetsUser1 = twitter.getAllTweets(userId1);\r\n        List<TweetCassandra> tweetsUser2 = twitter.getAllTweets(userId2);\r\n\r\n        twitter.closeEntityManager();\r\n\r\n        Assert.assertNotNull(tweetsUser1);\r\n        Assert.assertNotNull(tweetsUser2);\r\n\r\n        Assert.assertFalse(tweetsUser1.isEmpty());\r\n        Assert.assertFalse(tweetsUser2.isEmpty());\r\n\r\n        Assert.assertEquals(3, tweetsUser1.size());\r\n        Assert.assertEquals(2, tweetsUser2.size());\r\n    }\r\n\r\n    public void getPersonalDetailByName()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<UserCassandra> users = twitter.findPersonalDetailByName(\"Saurabh\");\r\n        Assert.assertNotNull(users);\r\n        Assert.assertFalse(users.isEmpty());\r\n        Assert.assertTrue(users.size() == 1);\r\n\r\n        UserCassandra user = users.get(0);\r\n        Assert.assertNotNull(user);\r\n        PersonalDetailCassandra pd = user.getPersonalDetail();\r\n        Assert.assertNotNull(pd);\r\n        Assert.assertTrue(pd.getPersonalDetailId() != null && !pd.getPersonalDetailId().trim().equals(\"\"));\r\n        Assert.assertTrue(\"Saurabh\", pd.getName() != null);\r\n        Assert.assertEquals(\"password2\", pd.getPassword());\r\n        Assert.assertEquals(\"single\", pd.getRelationshipStatus());\r\n\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Gets the tweets by body.\r\n     * \r\n     * @return the tweets by body\r\n     */\r\n    public void getTweetsByBody()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<TweetCassandra> user1Tweet = twitter.findTweetByBody(\"Here\");\r\n        List<TweetCassandra> user2Tweet = twitter.findTweetByBody(\"Saurabh\");\r\n\r\n        twitter.closeEntityManager();\r\n\r\n        Assert.assertNotNull(user1Tweet);\r\n        Assert.assertNotNull(user2Tweet);\r\n        Assert.assertEquals(1, user1Tweet.size());\r\n        Assert.assertEquals(1, user2Tweet.size());\r\n    }\r\n\r\n    /**\r\n     * Gets the tweet by device.\r\n     * \r\n     * @return the tweet by device\r\n     */\r\n    public void getTweetsByDevice()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<TweetCassandra> webTweets = twitter.findTweetByDevice(\"Web\");\r\n        List<TweetCassandra> mobileTweets = twitter.findTweetByDevice(\"Mobile\");\r\n\r\n        twitter.closeEntityManager();\r\n\r\n        Assert.assertNotNull(webTweets);\r\n        Assert.assertNotNull(mobileTweets);\r\n        Assert.assertEquals(1, webTweets.size());\r\n        Assert.assertEquals(1, mobileTweets.size());\r\n    }\r\n\r\n    public void getTweetsByRelationshipAndDevice()\r\n    {\r\n        // Positive scenario, record exists for user who is married and tweeted\r\n        // from Web\r\n        twitter.createEntityManager();\r\n        List<UserCassandra> users = twitter.findByRelationshipAndDevice(\"married\", \"Web\");\r\n        twitter.closeEntityManager();\r\n\r\n        Assert.assertNotNull(users);\r\n        Assert.assertFalse(users.isEmpty());\r\n        Assert.assertTrue(users.size() == 1);\r\n        UserCassandra user = users.get(0);\r\n\r\n        Assert.assertFalse(user == null);\r\n        Assert.assertEquals(\"0001\", user.getUserId());\r\n        List<TweetCassandra> tweets = user.getTweets();\r\n        Assert.assertFalse(tweets == null);\r\n        Assert.assertTrue(tweets.size() == 1);\r\n        TweetCassandra tweet = tweets.get(0);\r\n        Assert.assertNotNull(tweet);\r\n        Assert.assertEquals(\"Web\", tweet.getDevice());\r\n\r\n        // Negative scenario, record doesn't exist for user who is single and\r\n        // tweeted from mobile\r\n        twitter.createEntityManager();\r\n        List<UserCassandra> users2 = twitter.findByRelationshipAndDevice(\"single\", \"Mobile\");\r\n        twitter.closeEntityManager();\r\n        Assert.assertTrue(users2 == null || users2.isEmpty());\r\n    }\r\n\r\n    public void getTweetsByUserIdAndDevice()\r\n    {\r\n        // Positive scenario, record exists for user1 who tweeted from Web\r\n        twitter.createEntityManager();\r\n        UserCassandra user = twitter.findByUserIdAndTweetDevice(userId1, \"Web\");\r\n        twitter.closeEntityManager();\r\n        Assert.assertNotNull(user);\r\n        Assert.assertEquals(userId1, user.getUserId());\r\n        List<TweetCassandra> tweets = user.getTweets();\r\n        Assert.assertNotNull(tweets);\r\n        Assert.assertFalse(tweets.isEmpty());\r\n        Assert.assertTrue(tweets.size() == 1);\r\n        Assert.assertEquals(\"Web\", tweets.get(0).getDevice());\r\n\r\n        // Negative scenario, User 2 never tweeted from Mobile\r\n        twitter.createEntityManager();\r\n        UserCassandra user2 = twitter.findByUserIdAndTweetDevice(userId2, \"Mobile\");\r\n        twitter.closeEntityManager();\r\n        Assert.assertNull(user2);\r\n    }\r\n\r\n    /**\r\n     * Gets the all followers.\r\n     * \r\n     * @return the all followers\r\n     */\r\n    protected void getAllFollowers()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<UserCassandra> follower1 = twitter.getFollowers(userId1);\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        List<UserCassandra> follower2 = twitter.getFollowers(userId2);\r\n        twitter.closeEntityManager();\r\n\r\n        Assert.assertNull(follower1);\r\n        Assert.assertNotNull(follower2);\r\n    }\r\n\r\n    /**\r\n     * @return\r\n     */\r\n    private UserCassandra buildUser1()\r\n    {\r\n        UserCassandra user1 = new UserCassandra(userId1, \"Amresh\", \"password1\", \"married\", 25);\r\n\r\n        Calendar cal = Calendar.getInstance();\r\n        cal.setTime(new Date(1344079067777l));\r\n        user1.setProfessionalDetail(new ProfessionalDetailCassandra(1234567, \"Labs\", false, 31, 'C', (byte) 8,\r\n                (short) 5, (float) 10.0, 163.12, new Date(Long.parseLong(\"1344079065781\")), new Date(Long\r\n                        .parseLong(\"1344079067623\")), new Date(Long.parseLong(\"1344079069105\")), 2, new Long(\r\n                        3634521523423L), new Double(0.23452342343), new java.sql.Date(new Date(Long\r\n                        .parseLong(\"1344079061111\")).getTime()), new java.sql.Time(new Date(Long\r\n                        .parseLong(\"1344079062222\")).getTime()), new java.sql.Timestamp(new Date(Long\r\n                        .parseLong(\"13440790653333\")).getTime()), new BigInteger(\"123456789\"),\r\n                new BigDecimal(123456789), cal));\r\n\r\n        user1.setPreference(new PreferenceCassandra(\"P1\", \"Motif\", \"2\"));\r\n\r\n        user1.addExternalLink(new ExternalLinkCassandra(\"L1\", \"Facebook\", \"http://facebook.com/coolnerd\"));\r\n        user1.addExternalLink(new ExternalLinkCassandra(\"L2\", \"LinkedIn\", \"http://linkedin.com/in/devilmate\"));\r\n\r\n        user1.addTweet(new TweetCassandra(\"Here is my first tweet\", \"Web\"));\r\n        user1.addTweet(new TweetCassandra(\"Second Tweet from me\", \"Mobile\"));\r\n        return user1;\r\n    }\r\n\r\n    /**\r\n     * @return\r\n     */\r\n    private UserCassandra buildUser2()\r\n    {\r\n        UserCassandra user2 = new UserCassandra(userId2, \"Saurabh\", \"password2\", \"single\", 25);\r\n\r\n        Calendar cal = Calendar.getInstance();\r\n        cal.setTime(new Date(1344079068888l));\r\n        user2.setProfessionalDetail(new ProfessionalDetailCassandra(1234568, \"ODC\", true, 32, 'A', (byte) 10,\r\n                (short) 8, (float) 9.80, 323.3, new Date(Long.parseLong(\"1344079063412\")), new Date(Long\r\n                        .parseLong(\"1344079068266\")), new Date(Long.parseLong(\"1344079061078\")), 5, new Long(\r\n                        25423452343L), new Double(0.76452343), new java.sql.Date(new Date(Long\r\n                        .parseLong(\"1344079064444\")).getTime()), new java.sql.Time(new Date(Long\r\n                        .parseLong(\"1344079065555\")).getTime()), new java.sql.Timestamp(new Date(Long\r\n                        .parseLong(\"1344079066666\")).getTime()), new BigInteger(\"123456790\"),\r\n                new BigDecimal(123456790), cal));\r\n\r\n        user2.setPreference(new PreferenceCassandra(\"P2\", \"High Contrast\", \"3\"));\r\n\r\n        user2.addExternalLink(new ExternalLinkCassandra(\"L3\", \"GooglePlus\", \"http://plus.google.com/inviteme\"));\r\n        user2.addExternalLink(new ExternalLinkCassandra(\"L4\", \"Yahoo\", \"http://yahoo.com/profiles/itsmeamry\"));\r\n\r\n        user2.addTweet(new TweetCassandra(\"Saurabh tweets for the first time\", \"Phone\"));\r\n        user2.addTweet(new TweetCassandra(\"Another tweet from Saurabh\", \"text\"));\r\n        return user2;\r\n    }\r\n\r\n    private void assertUser1(UserCassandra user1)\r\n    {\r\n        Assert.assertNotNull(user1);\r\n        Assert.assertEquals(userId1, user1.getUserId());\r\n        Assert.assertNotNull(user1.getPersonalDetail());\r\n        Assert.assertEquals(\"Amresh\", user1.getPersonalDetail().getName());\r\n        Assert.assertNotNull(user1.getPreference());\r\n        Assert.assertEquals(\"2\", user1.getPreference().getPrivacyLevel());\r\n        Assert.assertNotNull(user1.getTweets());\r\n        Assert.assertFalse(user1.getTweets().isEmpty());\r\n        Assert.assertEquals(2, user1.getTweets().size());\r\n        Assert.assertNotNull(user1.getExternalLinks());\r\n        Assert.assertFalse(user1.getExternalLinks().isEmpty());        \r\n        Assert.assertEquals(2, user1.getExternalLinks().size());\r\n        Assert.assertEquals(0, user1.getPersonalDetail().getAge());\r\n    }\r\n\r\n    private void assertUser2(UserCassandra user2)\r\n    {\r\n        Assert.assertNotNull(user2);\r\n        Assert.assertEquals(userId2, user2.getUserId());\r\n        Assert.assertNotNull(user2.getPersonalDetail());\r\n        Assert.assertEquals(\"Saurabh\", user2.getPersonalDetail().getName());\r\n        Assert.assertNotNull(user2.getPreference());\r\n        Assert.assertEquals(\"3\", user2.getPreference().getPrivacyLevel());\r\n        Assert.assertNotNull(user2.getTweets());\r\n        Assert.assertFalse(user2.getTweets().isEmpty());\r\n        Assert.assertEquals(2, user2.getTweets().size());\r\n        Assert.assertNotNull(user2.getExternalLinks());\r\n        Assert.assertFalse(user2.getExternalLinks().isEmpty());\r\n        Assert.assertEquals(2, user2.getExternalLinks().size());    \r\n        Assert.assertEquals(0, user2.getPersonalDetail().getAge());\r\n    }\r\n\r\n    private void assertUpdatedUser1(UserCassandra user1)\r\n    {\r\n        Assert.assertNotNull(user1);\r\n        Assert.assertEquals(userId1, user1.getUserId());\r\n        Assert.assertNotNull(user1.getPersonalDetail());\r\n        Assert.assertEquals(\"Vivek\", user1.getPersonalDetail().getName());\r\n        Assert.assertEquals(\"unknown\", user1.getPersonalDetail().getPassword());\r\n        Assert.assertNotNull(user1.getPreference());\r\n        Assert.assertEquals(\"2\", user1.getPreference().getPrivacyLevel());\r\n        Assert.assertNotNull(user1.getTweets());\r\n        Assert.assertFalse(user1.getTweets().isEmpty());\r\n        Assert.assertEquals(3, user1.getTweets().size());\r\n        Assert.assertNotNull(user1.getExternalLinks());\r\n        Assert.assertFalse(user1.getExternalLinks().isEmpty());\r\n        Assert.assertEquals(2, user1.getExternalLinks().size());\r\n        Assert.assertEquals(0, user1.getPersonalDetail().getAge());\r\n    }\r\n\r\n    abstract void startServer();\r\n\r\n    abstract void stopServer();\r\n\r\n    abstract void deleteSchema();\r\n\r\n    abstract void createSchema() throws NotFoundException, InvalidRequestException, TException,\r\n            SchemaDisagreementException;\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/twitter/dao/SuperDaoCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.dao;\r\n\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Persistence;\r\n\r\n/**\r\n * The Class SuperDao.\r\n * \r\n * @author impetus\r\n */\r\npublic class SuperDaoCassandra\r\n{\r\n\r\n    /**\r\n     * Inits the.\r\n     * \r\n     * @param persistenceUnitName\r\n     *            the persistence unit name\r\n     * @return the entity manager\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    protected EntityManagerFactory createEntityManagerFactory(String persistenceUnitName)\r\n    {\r\n        return Persistence.createEntityManagerFactory(persistenceUnitName);\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/twitter/dao/TwitterCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.dao;\r\n\r\nimport java.math.BigDecimal;\r\nimport java.math.BigInteger;\r\nimport java.util.Calendar;\r\nimport java.util.Date;\r\nimport java.util.List;\r\n\r\nimport com.impetus.client.twitter.entities.PreferenceCassandra;\r\nimport com.impetus.client.twitter.entities.TweetCassandra;\r\nimport com.impetus.client.twitter.entities.UserCassandra;\r\n\r\n/**\r\n * Single window application for Twitter application. Contains methods for\r\n * performing CRUD operations on users and their tweets.\r\n */\r\npublic interface TwitterCassandra\r\n{\r\n\r\n    void addUser(UserCassandra user);\r\n\r\n    /**\r\n     * Registers a new user with Twitter application\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param name\r\n     *            the name\r\n     * @param password\r\n     *            the password\r\n     * @param relationshipStatus\r\n     *            the relationship status\r\n     */\r\n    void addUser(String userId, String name, String password, String relationshipStatus, int age);\r\n\r\n    /**\r\n     * Save preference for a given user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param preference\r\n     *            the preference\r\n     */\r\n    void savePreference(String userId, PreferenceCassandra preference);\r\n\r\n    /**\r\n     * Adds an external link for the given user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param linkType\r\n     *            the link type\r\n     * @param linkAddress\r\n     *            the link address\r\n     */\r\n    void addExternalLink(String userId, String linkId, String linkType, String linkAddress);\r\n\r\n    /**\r\n     * Adds a new tweet for a user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param tweetBody\r\n     *            the tweet body\r\n     * @param device\r\n     *            the device\r\n     */\r\n    void addTweet(String userId, String tweetBody, String device);\r\n\r\n    /**\r\n     * Makes User whose row key is <code>userId</code> follow a user whose row\r\n     * key is <code>friendUserId</code>\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param friendUserId\r\n     *            the friend user id\r\n     */\r\n    void startFollowing(String userId, String friendUserId);\r\n\r\n    /**\r\n     * Adds the follower whose row key is <code>followerUserId</code> to User\r\n     * whose row key is <code>userId</code>\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param followerUserId\r\n     *            the follower user id\r\n     */\r\n    void addFollower(String userId, String followerUserId);\r\n\r\n    UserCassandra findUserById(String userId);\r\n\r\n    void removeUser(UserCassandra user);\r\n\r\n    void mergeUser(UserCassandra user);\r\n\r\n    /**\r\n     * Retrieves all tweets for a given user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @return the all tweets\r\n     */\r\n    List<UserCassandra> getAllUsers();\r\n\r\n    List<TweetCassandra> getAllTweets(String userId);\r\n\r\n    /**\r\n     * Returns a list of followers for a given user.\r\n     * \r\n     * @param userId\r\n     *            user id\r\n     * @return list of all followers.\r\n     */\r\n    List<UserCassandra> getFollowers(String userId);\r\n\r\n    /************** Queries ***********************/\r\n\r\n    List<UserCassandra> findPersonalDetailByName(String name);\r\n\r\n    /**\r\n     * Find tweets tweeted by individual with certain marital status and using a\r\n     * certain device.\r\n     * \r\n     * @param relationship\r\n     * @param device\r\n     * @return\r\n     */\r\n    List<UserCassandra> findByRelationshipAndDevice(String relationship, String device);\r\n\r\n    /**\r\n     * Get me all tweets that I tweeted from a particular device\r\n     * \r\n     * @param userId\r\n     * @param device\r\n     * @return\r\n     */\r\n    UserCassandra findByUserIdAndTweetDevice(String userId, String device);\r\n\r\n    /**\r\n     * Find tweet by tweet body.\r\n     * \r\n     * @param tweetBody\r\n     *            the tweet body\r\n     * @return the list\r\n     */\r\n    List<TweetCassandra> findTweetByBody(String tweetBody);\r\n\r\n    /**\r\n     * Find tweet by device.\r\n     * \r\n     * @param deviceName\r\n     *            the device name\r\n     * @return the list\r\n     */\r\n    List<TweetCassandra> findTweetByDevice(String deviceName);\r\n\r\n    /**\r\n     * Close.\r\n     */\r\n    void close();\r\n\r\n    void createEntityManager();\r\n\r\n    void closeEntityManager();\r\n\r\n    /************** Queries on Professional Data ****************/\r\n    List<UserCassandra> findUserByProfessionId(long professionId);\r\n\r\n    List<UserCassandra> findUserByDepartment(String departmentName);\r\n\r\n    List<UserCassandra> findExceptionalUsers();\r\n\r\n    List<UserCassandra> findUserByAge(int age);\r\n\r\n    List<UserCassandra> findUserByGrade(char grade);\r\n\r\n    List<UserCassandra> findUserByDigitalSignature(byte digitalSignature);\r\n\r\n    List<UserCassandra> findUserByRating(short rating);\r\n\r\n    List<UserCassandra> findUserByCompliance(float compliance);\r\n\r\n    List<UserCassandra> findUserByHeight(double age);\r\n\r\n    List<UserCassandra> findUserByEnrolmentDate(Date enrolmentDate);\r\n\r\n    List<UserCassandra> findUserByEnrolmentTime(Date enrolmentTime);\r\n\r\n    List<UserCassandra> findUserByJoiningDateAndTime(Date joiningDateAndTime);\r\n\r\n    List<UserCassandra> findUserByYearsSpent(Integer yearsSpent);\r\n\r\n    List<UserCassandra> findUserByUniqueId(Long uniqueId);\r\n\r\n    List<UserCassandra> findUserByMonthlySalary(Double monthlySalary);\r\n\r\n    List<UserCassandra> findUserByBirthday(java.sql.Date birthday);\r\n\r\n    List<UserCassandra> findUserByBirthtime(java.sql.Time birthtime);\r\n\r\n    List<UserCassandra> findUserByAnniversary(java.sql.Timestamp anniversary);\r\n\r\n    List<UserCassandra> findUserByJobAttempts(BigInteger jobAttempts);\r\n\r\n    List<UserCassandra> findUserByAccumulatedWealth(BigDecimal accumulatedWealth);\r\n\r\n    List<UserCassandra> findUserByGraduationDay(Calendar graduationDay);\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/twitter/dao/TwitterServiceCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.dao;\r\n\r\nimport java.math.BigDecimal;\r\nimport java.math.BigInteger;\r\nimport java.sql.Time;\r\nimport java.sql.Timestamp;\r\nimport java.util.Calendar;\r\nimport java.util.Date;\r\nimport java.util.List;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Query;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.client.twitter.entities.ExternalLinkCassandra;\r\nimport com.impetus.client.twitter.entities.PreferenceCassandra;\r\nimport com.impetus.client.twitter.entities.TweetCassandra;\r\nimport com.impetus.client.twitter.entities.UserCassandra;\r\nimport com.impetus.kundera.KunderaException;\r\n\r\n/**\r\n * Data access object class for implementation of twitter.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class TwitterServiceCassandra extends SuperDaoCassandra implements TwitterCassandra\r\n{\r\n    private static final Logger log = LoggerFactory.getLogger(TwitterServiceCassandra.class);\r\n\r\n    private EntityManager em;\r\n\r\n    private EntityManagerFactory emf;\r\n\r\n    public TwitterServiceCassandra(String persistenceUnitName)\r\n    {\r\n        if (emf == null)\r\n        {\r\n            try\r\n            {\r\n                emf = createEntityManagerFactory(persistenceUnitName);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                log.error(e.getMessage(),e);\r\n                throw new KunderaException(e);\r\n            }\r\n        }\r\n\r\n    }\r\n\r\n    @Override\r\n    public void createEntityManager()\r\n    {\r\n        if (em == null)\r\n        {\r\n            em = emf.createEntityManager();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void closeEntityManager()\r\n    {\r\n        if (em != null)\r\n        {\r\n            em.close();\r\n            em = null;\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void close()\r\n    {\r\n        if (emf != null)\r\n        {\r\n            emf.close();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void addUser(UserCassandra user)\r\n    {\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void addUser(String userId, String name, String password, String relationshipStatus, int age)\r\n    {\r\n        UserCassandra user = new UserCassandra(userId, name, password, relationshipStatus, age);\r\n        em.persist(user);\r\n\r\n    }\r\n\r\n    @Override\r\n    public void savePreference(String userId, PreferenceCassandra preference)\r\n    {\r\n\r\n        UserCassandra user = em.find(UserCassandra.class, userId);\r\n        user.setPreference(preference);\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void addExternalLink(String userId, String linkId, String linkType, String linkAddress)\r\n    {\r\n        UserCassandra user = em.find(UserCassandra.class, userId);\r\n        user.addExternalLink(new ExternalLinkCassandra(linkId, linkType, linkAddress));\r\n\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void addTweet(String userId, String tweetBody, String device)\r\n    {\r\n        UserCassandra user = em.find(UserCassandra.class, userId);\r\n        user.addTweet(new TweetCassandra(tweetBody, device));\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void startFollowing(String userId, String friendUserId)\r\n    {\r\n        UserCassandra user = em.find(UserCassandra.class, userId);\r\n        UserCassandra friend = em.find(UserCassandra.class, friendUserId);\r\n\r\n        user.addFriend(friend);\r\n        em.persist(user);\r\n\r\n        friend.addFollower(user);\r\n        em.persist(friend);\r\n    }\r\n\r\n    @Override\r\n    public void addFollower(String userId, String followerUserId)\r\n    {\r\n        UserCassandra user = em.find(UserCassandra.class, userId);\r\n        UserCassandra follower = em.find(UserCassandra.class, followerUserId);\r\n\r\n        user.addFollower(follower);\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public UserCassandra findUserById(String userId)\r\n    {\r\n        em.clear();\r\n        UserCassandra user = em.find(UserCassandra.class, userId);\r\n        return user;\r\n    }\r\n\r\n    @Override\r\n    public void removeUser(UserCassandra user)\r\n    {\r\n        em.remove(user);\r\n    }\r\n\r\n    @Override\r\n    public void mergeUser(UserCassandra user)\r\n    {\r\n        em.merge(user);\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> getAllUsers()\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u\");\r\n\r\n        List<UserCassandra> users = q.getResultList();\r\n\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<TweetCassandra> getAllTweets(String userId)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.userId =:userId\");\r\n        q.setParameter(\"userId\", userId);\r\n        List<UserCassandra> users = q.getResultList();\r\n        if (users == null || users.isEmpty())\r\n        {\r\n            return null;\r\n        }\r\n        else\r\n        {\r\n            return users.get(0).getTweets();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> getFollowers(String userId)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.userId =:userId\");\r\n        q.setParameter(\"userId\", userId);\r\n        List<UserCassandra> users = q.getResultList();\r\n        if (users == null || users.isEmpty())\r\n        {\r\n            return null;\r\n        }\r\n        //return users.get(0).getFollowers();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findPersonalDetailByName(String name)\r\n    {\r\n        em.clear();\r\n        Query q = em\r\n                .createQuery(\"select u.personalDetail.name from UserCassandra u where u.personalDetail.name =:name\");\r\n        q.setParameter(\"name\", name);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<TweetCassandra> findTweetByBody(String tweetBody)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u.tweets.body from UserCassandra u where u.tweets.body like :body\");\r\n        q.setParameter(\"body\", tweetBody);\r\n        List<TweetCassandra> tweets = q.getResultList();\r\n        return tweets;\r\n    }\r\n\r\n    @Override\r\n    public List<TweetCassandra> findTweetByDevice(String deviceName)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u.tweets.device from UserCassandra u where u.tweets.device =:device\");\r\n        q.setParameter(\"device\", deviceName);\r\n        List<TweetCassandra> tweets = q.getResultList();\r\n        return tweets;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findByRelationshipAndDevice(String relationship, String device)\r\n    {\r\n        em.clear();\r\n        Query q = em\r\n                .createQuery(\"select u.tweets.device from UserCassandra u where u.tweets.device=:device and u.personalDetail.relationshipStatus=:relation\");\r\n        q.setParameter(\"device\", device);\r\n        q.setParameter(\"relation\", relationship);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public UserCassandra findByUserIdAndTweetDevice(String userId, String device)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.tweets.device=:device and u.userId=:userId\");\r\n        q.setParameter(\"device\", device);\r\n        q.setParameter(\"userId\", userId);\r\n        List<UserCassandra> users = q.getResultList();\r\n        if (users != null && !users.isEmpty())\r\n        {\r\n            return users.get(0);\r\n        }\r\n        return null;\r\n    }\r\n\r\n    /************* Queries on Professional Details for all data types *************/\r\n    @Override\r\n    public List<UserCassandra> findUserByProfessionId(long professionId)\r\n    {\r\n        em.clear();\r\n        Query q = em\r\n                .createQuery(\"select u from UserCassandra u where u.professionalDetail.professionId =:professionId\");\r\n        q.setParameter(\"professionId\", professionId);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByDepartment(String departmentName)\r\n    {\r\n        em.clear();\r\n        Query q = em\r\n                .createQuery(\"select u from UserCassandra u where u.professionalDetail.departmentName =:departmentName\");\r\n        q.setParameter(\"departmentName\", departmentName);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findExceptionalUsers()\r\n    {\r\n        em.clear();\r\n        Query q = em\r\n                .createQuery(\"select u from UserCassandra u where u.professionalDetail.isExceptional =:isExceptional\");\r\n        q.setParameter(\"isExceptional\", true);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByAge(int age)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.professionalDetail.age =:age\");\r\n        q.setParameter(\"age\", age);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByGrade(char grade)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.professionalDetail.grade =:grade\");\r\n        q.setParameter(\"grade\", grade);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByDigitalSignature(byte digitalSignature)\r\n    {\r\n        em.clear();\r\n        Query q = em\r\n                .createQuery(\"select u from UserCassandra u where u.professionalDetail.digitalSignature =:digitalSignature\");\r\n        q.setParameter(\"digitalSignature\", digitalSignature);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByRating(short rating)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.professionalDetail.rating =:rating\");\r\n        q.setParameter(\"rating\", rating);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByCompliance(float compliance)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.professionalDetail.compliance =:compliance\");\r\n        q.setParameter(\"compliance\", compliance);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByHeight(double height)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.professionalDetail.height =:height\");\r\n        q.setParameter(\"height\", height);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByEnrolmentDate(Date enrolmentDate)\r\n    {\r\n        em.clear();\r\n        Query q = em\r\n                .createQuery(\"select u from UserCassandra u where u.professionalDetail.enrolmentDate =:enrolmentDate\");\r\n        q.setParameter(\"enrolmentDate\", enrolmentDate);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByEnrolmentTime(Date enrolmentTime)\r\n    {\r\n        em.clear();\r\n        Query q = em\r\n                .createQuery(\"select u from UserCassandra u where u.professionalDetail.enrolmentTime =:enrolmentTime\");\r\n        q.setParameter(\"enrolmentTime\", enrolmentTime);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByJoiningDateAndTime(Date joiningDateAndTime)\r\n    {\r\n        em.clear();\r\n        Query q = em\r\n                .createQuery(\"select u from UserCassandra u where u.professionalDetail.joiningDateAndTime =:joiningDateAndTime\");\r\n        q.setParameter(\"joiningDateAndTime\", joiningDateAndTime);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByYearsSpent(Integer yearsSpent)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.professionalDetail.yearsSpent =:yearsSpent\");\r\n        q.setParameter(\"yearsSpent\", yearsSpent);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByUniqueId(Long uniqueId)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.professionalDetail.uniqueId =:uniqueId\");\r\n        q.setParameter(\"uniqueId\", uniqueId);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByMonthlySalary(Double monthlySalary)\r\n    {\r\n        em.clear();\r\n        Query q = em\r\n                .createQuery(\"select u from UserCassandra u where u.professionalDetail.monthlySalary =:monthlySalary\");\r\n        q.setParameter(\"monthlySalary\", monthlySalary);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByBirthday(java.sql.Date birthday)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.professionalDetail.birthday =:birthday\");\r\n        q.setParameter(\"birthday\", birthday);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByBirthtime(Time birthtime)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.professionalDetail.birthtime =:birthtime\");\r\n        q.setParameter(\"birthtime\", birthtime);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByAnniversary(Timestamp anniversary)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.professionalDetail.anniversary =:anniversary\");\r\n        q.setParameter(\"anniversary\", anniversary);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByJobAttempts(BigInteger jobAttempts)\r\n    {\r\n        em.clear();\r\n        Query q = em.createQuery(\"select u from UserCassandra u where u.professionalDetail.jobAttempts =:jobAttempts\");\r\n        q.setParameter(\"jobAttempts\", jobAttempts);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByAccumulatedWealth(BigDecimal accumulatedWealth)\r\n    {\r\n        em.clear();\r\n        Query q = em\r\n                .createQuery(\"select u from UserCassandra u where u.professionalDetail.accumulatedWealth =:accumulatedWealth\");\r\n        q.setParameter(\"accumulatedWealth\", accumulatedWealth);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<UserCassandra> findUserByGraduationDay(Calendar graduationDay)\r\n    {\r\n        em.clear();\r\n        Query q = em\r\n                .createQuery(\"select u from UserCassandra u where u.professionalDetail.graduationDay =:graduationDay\");\r\n        q.setParameter(\"graduationDay\", graduationDay);\r\n        List<UserCassandra> users = q.getResultList();\r\n        return users;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/twitter/entities/ExternalLinkCassandra.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.twitter.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class for user's External link details\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"EXTERNAL_LINK\", schema = \"KunderaExamples@twissandraTest\")\npublic class ExternalLinkCassandra\n{\n\n    @Id\n    @Column(name = \"EXT_LINK_ID\")\n    private String extLinkId;\n\n    @Column(name = \"LINK_TYPE\")\n    private String linkType;\n\n    @Column(name = \"LINK_ADDRESS\")\n    private String linkAddress;\n\n    public ExternalLinkCassandra()\n    {\n    }\n\n    public ExternalLinkCassandra(String extLinkId, String type, String address)\n    {\n        this.extLinkId = extLinkId;\n        this.linkType = type;\n        this.linkAddress = address;\n    }\n\n    /**\n     * @return the extLinkId\n     */\n    public String getExtLinkId()\n    {\n        return extLinkId;\n    }\n\n    /**\n     * @param extLinkId\n     *            the extLinkId to set\n     */\n    public void setExtLinkId(String extLinkId)\n    {\n        this.extLinkId = extLinkId;\n    }\n\n    /**\n     * @return the linkType\n     */\n    public String getLinkType()\n    {\n        return linkType;\n    }\n\n    /**\n     * @param linkType\n     *            the linkType to set\n     */\n    public void setLinkType(String linkType)\n    {\n        this.linkType = linkType;\n    }\n\n    /**\n     * @return the linkAddress\n     */\n    public String getLinkAddress()\n    {\n        return linkAddress;\n    }\n\n    /**\n     * @param linkAddress\n     *            the linkAddress to set\n     */\n    public void setLinkAddress(String linkAddress)\n    {\n        this.linkAddress = linkAddress;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/twitter/entities/PersonalDetailCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\nimport com.impetus.client.twitter.utils.ExampleUtilsCassandra;\r\nimport com.impetus.kundera.index.Index;\r\nimport com.impetus.kundera.index.IndexCollection;\r\n\r\n/**\r\n * Entity class for user's personal details\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"relationshipStatus\") })\r\npublic class PersonalDetailCassandra\r\n{\r\n    @Column(name = \"personal_detail_id\")\r\n    private String personalDetailId;\r\n\r\n    @Column(name = \"person_name\")\r\n    private String name;\r\n\r\n    @Column(name = \"person_password\")\r\n    private String password;\r\n\r\n    @Column(name = \"rel_status\")\r\n    private String relationshipStatus;\r\n\r\n    @Column(name = \"age\")\r\n    private transient int age;\r\n\r\n    public PersonalDetailCassandra()\r\n    {\r\n\r\n    }\r\n\r\n    public PersonalDetailCassandra(String name, String password, String relationshipStatus, int age)\r\n    {\r\n        setPersonalDetailId(ExampleUtilsCassandra.getUniqueId());\r\n        setName(name);\r\n        setPassword(password);\r\n        setRelationshipStatus(relationshipStatus);\r\n        setAge(age);\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetailId\r\n     */\r\n    public String getPersonalDetailId()\r\n    {\r\n        return personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetailId\r\n     *            the personalDetailId to set\r\n     */\r\n    public void setPersonalDetailId(String personalDetailId)\r\n    {\r\n        this.personalDetailId = personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @return the name\r\n     */\r\n    public String getName()\r\n    {\r\n        return name;\r\n    }\r\n\r\n    /**\r\n     * @param name\r\n     *            the name to set\r\n     */\r\n    public void setName(String name)\r\n    {\r\n        this.name = name;\r\n    }\r\n\r\n    /**\r\n     * @return the password\r\n     */\r\n    public String getPassword()\r\n    {\r\n        return password;\r\n    }\r\n\r\n    /**\r\n     * @param password\r\n     *            the password to set\r\n     */\r\n    public void setPassword(String password)\r\n    {\r\n        this.password = password;\r\n    }\r\n\r\n    /**\r\n     * @return the relationshipStatus\r\n     */\r\n    public String getRelationshipStatus()\r\n    {\r\n        return relationshipStatus;\r\n    }\r\n\r\n    /**\r\n     * @param relationshipStatus\r\n     *            the relationshipStatus to set\r\n     */\r\n    public void setRelationshipStatus(String relationshipStatus)\r\n    {\r\n        this.relationshipStatus = relationshipStatus;\r\n    }\r\n\r\n    /**\r\n     * @return the age\r\n     */\r\n    public int getAge()\r\n    {\r\n        return age;\r\n    }\r\n\r\n    /**\r\n     * @param age\r\n     *            the age to set\r\n     */\r\n    public void setAge(int age)\r\n    {\r\n        this.age = age;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/twitter/entities/PreferenceCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * Entity class for User Preferences\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"PREFERENCE\", schema = \"KunderaExamples@twissandraTest\")\r\npublic class PreferenceCassandra\r\n{\r\n    @Id\r\n    @Column(name = \"PREFERENCE_ID\")\r\n    String preferenceId;\r\n\r\n    @Column(name = \"WEBSITE_THEME\")\r\n    String websiteTheme;\r\n\r\n    @Column(name = \"PRIVACY_LEVEL\")\r\n    String privacyLevel; // 1, 2, 3\r\n\r\n    public PreferenceCassandra()\r\n    {\r\n\r\n    }\r\n\r\n    public PreferenceCassandra(String preferenceId, String theme, String privacyLevel)\r\n    {\r\n        this.preferenceId = preferenceId;\r\n        this.websiteTheme = theme;\r\n        this.privacyLevel = privacyLevel;\r\n    }\r\n\r\n    /**\r\n     * @return the preferenceId\r\n     */\r\n    public String getPreferenceId()\r\n    {\r\n        return preferenceId;\r\n    }\r\n\r\n    /**\r\n     * @param preferenceId\r\n     *            the preferenceId to set\r\n     */\r\n    public void setPreferenceId(String preferenceId)\r\n    {\r\n        this.preferenceId = preferenceId;\r\n    }\r\n\r\n    /**\r\n     * @return the websiteTheme\r\n     */\r\n    public String getWebsiteTheme()\r\n    {\r\n        return websiteTheme;\r\n    }\r\n\r\n    /**\r\n     * @param websiteTheme\r\n     *            the websiteTheme to set\r\n     */\r\n    public void setWebsiteTheme(String websiteTheme)\r\n    {\r\n        this.websiteTheme = websiteTheme;\r\n    }\r\n\r\n    /**\r\n     * @return the privacyLevel\r\n     */\r\n    public String getPrivacyLevel()\r\n    {\r\n        return privacyLevel;\r\n    }\r\n\r\n    /**\r\n     * @param privacyLevel\r\n     *            the privacyLevel to set\r\n     */\r\n    public void setPrivacyLevel(String privacyLevel)\r\n    {\r\n        this.privacyLevel = privacyLevel;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/twitter/entities/ProfessionalDetailCassandra.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.twitter.entities;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Holds professional details of any user\n * \n * @author amresh.singh\n */\n\n@Embeddable\n@IndexCollection(columns = { @Index(name = \"professionId\"), @Index(name = \"departmentName\"),\n        @Index(name = \"isExceptional\"), @Index(name = \"age\"), @Index(name = \"grade\"),\n        @Index(name = \"digitalSignature\"), @Index(name = \"rating\"), @Index(name = \"compliance\"),\n        @Index(name = \"height\"), @Index(name = \"enrolmentDate\"), @Index(name = \"enrolmentTime\"),\n        @Index(name = \"joiningDateAndTime\"), @Index(name = \"yearsSpent\"), @Index(name = \"uniqueId\"),\n        @Index(name = \"monthlySalary\"), @Index(name = \"birthday\"), @Index(name = \"birthtime\"),\n        @Index(name = \"anniversary\"), @Index(name = \"jobAttempts\"), @Index(name = \"accumulatedWealth\"),\n        @Index(name = \"graduationDay\") })\npublic class ProfessionalDetailCassandra\n{\n    // Primitive Types\n    @Column(name = \"PROFESSION_ID\")\n    private long professionId;\n\n    @Column(name = \"DEPARTMENT_NAME\")\n    private String departmentName;\n\n    @Column(name = \"IS_EXCEPTIONAL\")\n    private boolean isExceptional;\n\n    @Column(name = \"AGE\")\n    private int age;\n\n    @Column(name = \"GRADE\")\n    private char grade; // A,B,C,D,E,F for i to vi\n\n    @Column(name = \"DIGITAL_SIGNATURE\")\n    private byte digitalSignature;\n\n    @Column(name = \"RATING\")\n    private short rating; // 1-10\n\n    @Column(name = \"COMPLIANCE\")\n    private float compliance;\n\n    @Column(name = \"HEIGHT\")\n    private double height;\n\n    // Date-time types\n    @Column(name = \"ENROLMENT_DATE\")\n    @Temporal(TemporalType.DATE)\n    private java.util.Date enrolmentDate;\n\n    @Column(name = \"ENROLMENT_TIME\")\n    @Temporal(TemporalType.TIME)\n    private java.util.Date enrolmentTime;\n\n    @Column(name = \"JOINING_DATE_TIME\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private java.util.Date joiningDateAndTime;\n\n    // Wrapper types\n    @Column(name = \"YEARS_SPENT\")\n    private Integer yearsSpent;\n\n    @Column(name = \"UNIQUE_ID\")\n    private Long uniqueId;\n\n    @Column(name = \"MONTHLY_SALARY\")\n    private Double monthlySalary;\n\n    @Column(name = \"BIRTH_DAY\")\n    private java.sql.Date birthday;\n\n    @Column(name = \"BIRTH_TIME\")\n    private java.sql.Time birthtime;\n\n    @Column(name = \"ANNIVERSARY\")\n    private java.sql.Timestamp anniversary;\n\n    @Column(name = \"JOB_ATTEMPTS\")\n    private BigInteger jobAttempts;\n\n    @Column(name = \"ACCUMULATED_WEALTH\")\n    private BigDecimal accumulatedWealth;\n\n    @Column(name = \"GRADUATION_DAY\")\n    private Calendar graduationDay;\n\n    public ProfessionalDetailCassandra(long professionId, String departmentName, boolean isExceptional, int age,\n            char grade, byte digitalSignature, short rating, float compliance, double height, Date enrolmentDate,\n            Date enrolmentTime, Date joiningDateAndTime, Integer yearsSpent, Long uniqueId, Double monthlySalary,\n            java.sql.Date birthday, Time birthtime, Timestamp anniversary, BigInteger jobAttempts,\n            BigDecimal accumulatedWealth, Calendar graduationDay)\n    {\n        super();\n        this.professionId = professionId;\n        this.departmentName = departmentName;\n        this.isExceptional = isExceptional;\n        this.age = age;\n        this.grade = grade;\n        this.digitalSignature = digitalSignature;\n        this.rating = rating;\n        this.compliance = compliance;\n        this.height = height;\n        this.enrolmentDate = enrolmentDate;\n        this.enrolmentTime = enrolmentTime;\n        this.joiningDateAndTime = joiningDateAndTime;\n        this.yearsSpent = yearsSpent;\n        this.uniqueId = uniqueId;\n        this.monthlySalary = monthlySalary;\n        this.birthday = birthday;\n        this.birthtime = birthtime;\n        this.anniversary = anniversary;\n        this.jobAttempts = jobAttempts;\n        this.accumulatedWealth = accumulatedWealth;\n        this.graduationDay = graduationDay;\n    }\n\n    public ProfessionalDetailCassandra()\n    {\n\n    }\n\n    /**\n     * @return the professionId\n     */\n    public long getProfessionId()\n    {\n        return professionId;\n    }\n\n    /**\n     * @param professionId\n     *            the professionId to set\n     */\n    public void setProfessionId(long professionId)\n    {\n        this.professionId = professionId;\n    }\n\n    /**\n     * @return the departmentName\n     */\n    public String getDepartmentName()\n    {\n        return departmentName;\n    }\n\n    /**\n     * @param departmentName\n     *            the departmentName to set\n     */\n    public void setDepartmentName(String departmentName)\n    {\n        this.departmentName = departmentName;\n    }\n\n    /**\n     * @return the isExceptional\n     */\n    public boolean isExceptional()\n    {\n        return isExceptional;\n    }\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    public void setExceptional(boolean isExceptional)\n    {\n        this.isExceptional = isExceptional;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the grade\n     */\n    public char getGrade()\n    {\n        return grade;\n    }\n\n    /**\n     * @param grade\n     *            the grade to set\n     */\n    public void setGrade(char grade)\n    {\n        this.grade = grade;\n    }\n\n    /**\n     * @return the digitalSignature\n     */\n    public byte getDigitalSignature()\n    {\n        return digitalSignature;\n    }\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    public void setDigitalSignature(byte digitalSignature)\n    {\n        this.digitalSignature = digitalSignature;\n    }\n\n    /**\n     * @return the rating\n     */\n    public short getRating()\n    {\n        return rating;\n    }\n\n    /**\n     * @param rating\n     *            the rating to set\n     */\n    public void setRating(short rating)\n    {\n        this.rating = rating;\n    }\n\n    /**\n     * @return the compliance\n     */\n    public float getCompliance()\n    {\n        return compliance;\n    }\n\n    /**\n     * @param compliance\n     *            the compliance to set\n     */\n    public void setCompliance(float compliance)\n    {\n        this.compliance = compliance;\n    }\n\n    /**\n     * @return the height\n     */\n    public double getHeight()\n    {\n        return height;\n    }\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    public void setHeight(double height)\n    {\n        this.height = height;\n    }\n\n    /**\n     * @return the enrolmentDate\n     */\n    public java.util.Date getEnrolmentDate()\n    {\n        return enrolmentDate;\n    }\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    public void setEnrolmentDate(java.util.Date enrolmentDate)\n    {\n        this.enrolmentDate = enrolmentDate;\n    }\n\n    /**\n     * @return the enrolmentTime\n     */\n    public java.util.Date getEnrolmentTime()\n    {\n        return enrolmentTime;\n    }\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    public void setEnrolmentTime(java.util.Date enrolmentTime)\n    {\n        this.enrolmentTime = enrolmentTime;\n    }\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    public java.util.Date getJoiningDateAndTime()\n    {\n        return joiningDateAndTime;\n    }\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    public void setJoiningDateAndTime(java.util.Date joiningDateAndTime)\n    {\n        this.joiningDateAndTime = joiningDateAndTime;\n    }\n\n    /**\n     * @return the yearsSpent\n     */\n    public Integer getYearsSpent()\n    {\n        return yearsSpent;\n    }\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    public void setYearsSpent(Integer yearsSpent)\n    {\n        this.yearsSpent = yearsSpent;\n    }\n\n    /**\n     * @return the uniqueId\n     */\n    public Long getUniqueId()\n    {\n        return uniqueId;\n    }\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    public void setUniqueId(Long uniqueId)\n    {\n        this.uniqueId = uniqueId;\n    }\n\n    /**\n     * @return the monthlySalary\n     */\n    public Double getMonthlySalary()\n    {\n        return monthlySalary;\n    }\n\n    /**\n     * @param monthlySalary\n     *            the monthlySalary to set\n     */\n    public void setMonthlySalary(Double monthlySalary)\n    {\n        this.monthlySalary = monthlySalary;\n    }\n\n    /**\n     * @return the birthday\n     */\n    public java.sql.Date getBirthday()\n    {\n        return birthday;\n    }\n\n    /**\n     * @param birthday\n     *            the birthday to set\n     */\n    public void setBirthday(java.sql.Date birthday)\n    {\n        this.birthday = birthday;\n    }\n\n    /**\n     * @return the birthtime\n     */\n    public java.sql.Time getBirthtime()\n    {\n        return birthtime;\n    }\n\n    /**\n     * @param birthtime\n     *            the birthtime to set\n     */\n    public void setBirthtime(java.sql.Time birthtime)\n    {\n        this.birthtime = birthtime;\n    }\n\n    /**\n     * @return the anniversary\n     */\n    public java.sql.Timestamp getAnniversary()\n    {\n        return anniversary;\n    }\n\n    /**\n     * @param anniversary\n     *            the anniversary to set\n     */\n    public void setAnniversary(java.sql.Timestamp anniversary)\n    {\n        this.anniversary = anniversary;\n    }\n\n    /**\n     * @return the jobAttempts\n     */\n    public BigInteger getJobAttempts()\n    {\n        return jobAttempts;\n    }\n\n    /**\n     * @param jobAttempts\n     *            the jobAttempts to set\n     */\n    public void setJobAttempts(BigInteger jobAttempts)\n    {\n        this.jobAttempts = jobAttempts;\n    }\n\n    /**\n     * @return the accumulatedWealth\n     */\n    public BigDecimal getAccumulatedWealth()\n    {\n        return accumulatedWealth;\n    }\n\n    /**\n     * @param accumulatedWealth\n     *            the accumulatedWealth to set\n     */\n    public void setAccumulatedWealth(BigDecimal accumulatedWealth)\n    {\n        this.accumulatedWealth = accumulatedWealth;\n    }\n\n    /**\n     * @return the graduationDay\n     */\n    public Calendar getGraduationDay()\n    {\n        return graduationDay;\n    }\n\n    /**\n     * @param graduationDay\n     *            the graduationDay to set\n     */\n    public void setGraduationDay(Calendar graduationDay)\n    {\n        this.graduationDay = graduationDay;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/twitter/entities/TweetCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\nimport com.impetus.client.twitter.utils.ExampleUtilsCassandra;\r\nimport com.impetus.kundera.index.Index;\r\nimport com.impetus.kundera.index.IndexCollection;\r\n\r\n/**\r\n * Class for Tweets\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\n@IndexCollection(columns = { @Index(name = \"body\"), @Index(name = \"device\") })\r\npublic class TweetCassandra\r\n{\r\n\r\n    @Column(name = \"tweet_id\")\r\n    private String tweetId;\r\n\r\n    @Column(name = \"tweet_body\")\r\n    private String body;\r\n\r\n    @Column(name = \"tweeted_from\")\r\n    private String device;\r\n\r\n    // private long timestamp;\r\n\r\n    public TweetCassandra(String body, String device)\r\n    {\r\n        this.tweetId = ExampleUtilsCassandra.getUniqueId();\r\n        this.body = body;\r\n        this.device = device;\r\n        // this.timestamp = ExampleUtils.getCurrentTimestamp();\r\n    }\r\n\r\n    public TweetCassandra()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * @return the tweetId\r\n     */\r\n    public String getTweetId()\r\n    {\r\n        return tweetId;\r\n    }\r\n\r\n    /**\r\n     * @param tweetId\r\n     *            the tweetId to set\r\n     */\r\n    public void setTweetId(String tweetId)\r\n    {\r\n        this.tweetId = tweetId;\r\n    }\r\n\r\n    /**\r\n     * @return the body\r\n     */\r\n    public String getBody()\r\n    {\r\n        return body;\r\n    }\r\n\r\n    /**\r\n     * @param body\r\n     *            the body to set\r\n     */\r\n    public void setBody(String body)\r\n    {\r\n        this.body = body;\r\n    }\r\n\r\n    /**\r\n     * @return the device\r\n     */\r\n    public String getDevice()\r\n    {\r\n        return device;\r\n    }\r\n\r\n    /**\r\n     * @param device\r\n     *            the device to set\r\n     */\r\n    public void setDevice(String device)\r\n    {\r\n        this.device = device;\r\n    }\r\n\r\n    /*    *//**\r\n     * @return the timestamp\r\n     */\r\n    /*\r\n     * public long getTimestamp() { return timestamp; }\r\n     *//**\r\n     * @param timestamp\r\n     *            the timestamp to set\r\n     */\r\n    /*\r\n     * public void setTimestamp(long timestamp) { this.timestamp = timestamp; }\r\n     */\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/twitter/entities/UserCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.CollectionTable;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.ElementCollection;\r\nimport javax.persistence.Embedded;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.OneToOne;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * @author impetus\r\n * \r\n */\r\n@Entity\r\n@Table(name = \"USER\", schema = \"KunderaExamples@twissandraTest\")\r\npublic class UserCassandra\r\n{\r\n\r\n    @Id\r\n    @Column(name = \"USER_ID\")\r\n    private String userId;\r\n\r\n    // Embedded object, will persist co-located\r\n    @Embedded\r\n    private PersonalDetailCassandra personalDetail;\r\n\r\n    // Embedded object, will persist co-located\r\n    @Embedded\r\n    private ProfessionalDetailCassandra professionalDetail;\r\n\r\n    // Element collection, will persist co-located\r\n    @ElementCollection\r\n    @CollectionTable(name = \"tweeted\")\r\n    private List<TweetCassandra> tweets;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"FRIEND_ID\")\r\n    private List<UserCassandra> friends; // List of users whom I follow\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"FOLLOWER_ID\")\r\n    private List<UserCassandra> followers; // List of users who are following me\r\n\r\n    // One-to-one, will be persisted separately\r\n    @OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)\r\n    @JoinColumn(name = \"PREFERENCE_ID\")\r\n    private PreferenceCassandra preference;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)\r\n    @JoinColumn(name = \"USER_ID\")\r\n    private Set<ExternalLinkCassandra> externalLinks;\r\n\r\n    public UserCassandra()\r\n    {\r\n\r\n    }\r\n\r\n    public UserCassandra(String userId, String name, String password, String relationshipStatus, int age)\r\n    {\r\n        PersonalDetailCassandra pd = new PersonalDetailCassandra(name, password, relationshipStatus, age);\r\n        setUserId(userId);\r\n        setPersonalDetail(pd);\r\n    }\r\n\r\n    /**\r\n     * @return the userId\r\n     */\r\n    public String getUserId()\r\n    {\r\n        return userId;\r\n    }\r\n\r\n    /**\r\n     * @param userId\r\n     *            the userId to set\r\n     */\r\n    public void setUserId(String userId)\r\n    {\r\n        this.userId = userId;\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetail\r\n     */\r\n    public PersonalDetailCassandra getPersonalDetail()\r\n    {\r\n        return personalDetail;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetail\r\n     *            the personalDetail to set\r\n     */\r\n    public void setPersonalDetail(PersonalDetailCassandra personalDetail)\r\n    {\r\n        this.personalDetail = personalDetail;\r\n    }\r\n\r\n    /**\r\n     * @return the professionalDetail\r\n     */\r\n    public ProfessionalDetailCassandra getProfessionalDetail()\r\n    {\r\n        return professionalDetail;\r\n    }\r\n\r\n    /**\r\n     * @param professionalDetail\r\n     *            the professionalDetail to set\r\n     */\r\n    public void setProfessionalDetail(ProfessionalDetailCassandra professionalDetail)\r\n    {\r\n        this.professionalDetail = professionalDetail;\r\n    }\r\n\r\n    /**\r\n     * @return the tweets\r\n     */\r\n    public List<TweetCassandra> getTweets()\r\n    {\r\n        return tweets;\r\n    }\r\n\r\n    /**\r\n     * @param tweets\r\n     *            the tweets to set\r\n     */\r\n    public void addTweet(TweetCassandra tweet)\r\n    {\r\n        if (this.tweets == null || this.tweets.isEmpty())\r\n        {\r\n            this.tweets = new ArrayList<TweetCassandra>();\r\n        }\r\n        this.tweets.add(tweet);\r\n    }\r\n\r\n    /**\r\n     * @return the preference\r\n     */\r\n    public PreferenceCassandra getPreference()\r\n    {\r\n        return preference;\r\n    }\r\n\r\n    /**\r\n     * @param preference\r\n     *            the preference to set\r\n     */\r\n    public void setPreference(PreferenceCassandra preference)\r\n    {\r\n        this.preference = preference;\r\n    }\r\n\r\n    /**\r\n     * @return the externalLinks\r\n     */\r\n    public Set<ExternalLinkCassandra> getExternalLinks()\r\n    {\r\n        return externalLinks;\r\n    }\r\n\r\n    /**\r\n     * @param imDetails\r\n     *            the imDetails to set\r\n     */\r\n    public void addExternalLink(ExternalLinkCassandra externalLink)\r\n    {\r\n        if (this.externalLinks == null || this.externalLinks.isEmpty())\r\n        {\r\n            this.externalLinks = new HashSet<ExternalLinkCassandra>();\r\n        }\r\n\r\n        this.externalLinks.add(externalLink);\r\n    }\r\n    //To do : Need to add support for self referential structures\r\n//\r\n   /**\r\n     * @return the friends\r\n     */\r\n    public List<UserCassandra> getFriends()\r\n    {\r\n        return friends;\r\n    }\r\n\r\n    /**\r\n     * @param friends\r\n     *            the friends to set\r\n     */\r\n    public void addFriend(UserCassandra friend)\r\n    {\r\n        if (this.friends == null || this.friends.isEmpty())\r\n        {\r\n            this.friends = new ArrayList<UserCassandra>();\r\n        }\r\n        this.friends.add(friend);\r\n    }\r\n\r\n    /**\r\n     * @return the followers\r\n     */\r\n    public List<UserCassandra> getFollowers()\r\n    {\r\n        return followers;\r\n    }\r\n\r\n    /**\r\n     * @param followers\r\n     *            the followers to set\r\n     */\r\n    public void addFollower(UserCassandra follower)\r\n    {\r\n        if (this.followers == null || this.followers.isEmpty())\r\n        {\r\n            this.followers = new ArrayList<UserCassandra>();\r\n        }\r\n\r\n        this.followers.add(follower);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/client/twitter/utils/ExampleUtilsCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.utils;\r\n\r\nimport java.util.Date;\r\nimport java.util.UUID;\r\n\r\n/**\r\n * Class for utility methods\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class ExampleUtilsCassandra\r\n{\r\n    public static String getUniqueId()\r\n    {\r\n        return UUID.randomUUID().toString();\r\n    }\r\n\r\n    public static long getCurrentTimestamp()\r\n    {\r\n        return new Date().getTime();\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/cassandra/persistence/CassandraCli.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.client.cassandra.persistence;\r\n\r\nimport java.io.File;\r\nimport java.io.IOException;\r\nimport java.io.UnsupportedEncodingException;\r\nimport java.net.Socket;\r\nimport java.net.UnknownHostException;\r\nimport java.nio.ByteBuffer;\r\nimport java.util.ArrayList;\r\nimport java.util.LinkedHashMap;\r\nimport java.util.List;\r\n\r\nimport org.apache.cassandra.locator.SimpleStrategy;\r\nimport org.apache.cassandra.service.EmbeddedCassandraService;\r\nimport org.apache.cassandra.thrift.Cassandra;\r\nimport org.apache.cassandra.thrift.CfDef;\r\nimport org.apache.cassandra.thrift.Compression;\r\nimport org.apache.cassandra.thrift.ConsistencyLevel;\r\nimport org.apache.cassandra.thrift.InvalidRequestException;\r\nimport org.apache.cassandra.thrift.KsDef;\r\nimport org.apache.cassandra.thrift.NotFoundException;\r\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\r\nimport org.apache.cassandra.thrift.TimedOutException;\r\nimport org.apache.cassandra.thrift.UnavailableException;\r\nimport org.apache.thrift.TException;\r\nimport org.apache.thrift.protocol.TBinaryProtocol;\r\nimport org.apache.thrift.protocol.TProtocol;\r\nimport org.apache.thrift.transport.TFramedTransport;\r\nimport org.apache.thrift.transport.TSocket;\r\nimport org.apache.thrift.transport.TTransport;\r\nimport org.apache.thrift.transport.TTransportException;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.KunderaException;\r\n\r\n/**\r\n * The Class CassandraCli.\r\n * \r\n * @author vivek.mishra\r\n */\r\npublic final class CassandraCli\r\n{\r\n\r\n    /** The cassandra. */\r\n    private static EmbeddedCassandraService cassandra;\r\n\r\n    /** The client. */\r\n    public static Cassandra.Client client;\r\n\r\n    /** the log used by this class. */\r\n    private static Logger log = LoggerFactory.getLogger(CassandraCli.class);\r\n\r\n    private static List<String> puWithSchemaGeneration = new ArrayList<String>();\r\n\r\n    /**\r\n     * Cassandra set up.\r\n     * \r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     * @throws TException\r\n     *             the t exception\r\n     * @throws InvalidRequestException\r\n     *             the invalid request exception\r\n     * @throws UnavailableException\r\n     *             the unavailable exception\r\n     * @throws TimedOutException\r\n     *             the timed out exception\r\n     * @throws SchemaDisagreementException\r\n     *             the schema disagreement exception\r\n     */\r\n    public static void cassandraSetUp() throws IOException, TException, InvalidRequestException, UnavailableException,\r\n            TimedOutException, SchemaDisagreementException\r\n    {\r\n        if (!checkIfServerRunning())\r\n        {\r\n            cassandra = new EmbeddedCassandraService();\r\n            cassandra.start();\r\n        }\r\n        initClient();\r\n    }\r\n\r\n    public static void archivePu(final String peristenceunit)\r\n    {\r\n        puWithSchemaGeneration.add(peristenceunit);\r\n    }\r\n\r\n    public static boolean isArchived(final String persistenceUnit)\r\n    {\r\n        return puWithSchemaGeneration.contains(persistenceUnit);\r\n    }\r\n\r\n    /**\r\n     * Create keyspace.\r\n     * \r\n     * @param keyspaceName\r\n     *            keyspace name.\r\n     */\r\n    public static void createKeySpace(String keyspaceName)\r\n    {\r\n        try\r\n        {\r\n            client.describe_keyspace(keyspaceName);\r\n        }\r\n        catch (NotFoundException e)\r\n        {\r\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\r\n            KsDef ks_Def = new KsDef(keyspaceName, SimpleStrategy.class.getName(), cfDefs);\r\n\r\n            // Set replication factor\r\n            if (ks_Def.strategy_options == null)\r\n            {\r\n                ks_Def.strategy_options = new LinkedHashMap<String, String>();\r\n            }\r\n            // Set replication factor, the value MUST be an integer\r\n            ks_Def.strategy_options.put(\"replication_factor\", \"1\");\r\n\r\n            try\r\n            {\r\n                client.system_add_keyspace(ks_Def);\r\n            }\r\n            catch (TException e1)\r\n            {\r\n                log.error(\"Error while adding keyspace, Caused by: .\", e1);\r\n            }\r\n\r\n        }\r\n\r\n        catch (InvalidRequestException e)\r\n        {\r\n            log.error(\"Error while adding keyspace, Caused by: .\", e);\r\n        }\r\n        catch (TException e)\r\n        {\r\n            log.error(\"Error while adding keyspace, Caused by: .\", e);\r\n        }\r\n\r\n    }\r\n\r\n    public static void truncateColumnFamily(String keyspace, String... columns)\r\n    {\r\n        try\r\n        {\r\n            if (client != null)\r\n            {\r\n                client.set_keyspace(keyspace);\r\n                for (String column : columns)\r\n                {\r\n                    if (columnFamilyExist(column, keyspace))\r\n                    {\r\n                        client.truncate(column);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        catch (IllegalArgumentException iex)\r\n        {\r\n            // do nothing.\r\n        }\r\n        catch (InvalidRequestException e)\r\n        {\r\n            // do nothing.\r\n        }\r\n        catch (UnavailableException e)\r\n        {\r\n            // do nothing.\r\n        }\r\n        catch (TimedOutException e)\r\n        {\r\n            // do nothing.\r\n        }\r\n        catch (TException e)\r\n        {\r\n            // do nothing.\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Drop out key space.\r\n     * \r\n     * @param keyspaceName\r\n     *            keyspace name\r\n     */\r\n    public static void dropKeySpace(String keyspaceName)\r\n    {\r\n        try\r\n        {\r\n            if (client != null)\r\n            {\r\n                client.system_drop_keyspace(keyspaceName);\r\n            }\r\n            // deleteCassandraFolders(\"/var/lib/cassandra/data/\");\r\n            // deleteCassandraFolders(\"/var/lib/cassandra/data/system/\");\r\n            // deleteCassandraFolders(\"/var/lib/cassandra/commitlog/\");\r\n            // deleteCassandraFolders(\"/var/lib/cassandra/saved_caches/\");\r\n            // deleteCassandraFolders(\"/var/log/cassandra/\");\r\n        }\r\n        catch (InvalidRequestException e)\r\n        {\r\n            return;\r\n        }\r\n        catch (SchemaDisagreementException e)\r\n        {\r\n            log.error(\"Error while dropping keyspace, Caused by: .\", e);\r\n        }\r\n        catch (TException e)\r\n        {\r\n            log.error(\"Error while dropping keyspace, Caused by: .\", e);\r\n        }\r\n    }\r\n\r\n    private static void deleteCassandraFolders(String dir)\r\n    {\r\n        File directory = new File(dir);\r\n        // Get all files in directory\r\n        File[] files = directory.listFiles();\r\n        for (File file : files)\r\n        {\r\n            // Delete each file\r\n            if (!file.delete())\r\n            {\r\n                // Failed to delete file\r\n            }\r\n        }\r\n    }\r\n\r\n    public static boolean keyspaceExist(String keySpaceName)\r\n    {\r\n        try\r\n        {\r\n            return client.describe_keyspace(keySpaceName) != null;\r\n        }\r\n        catch (NotFoundException e)\r\n        {\r\n            return false;\r\n        }\r\n        catch (InvalidRequestException e)\r\n        {\r\n            log.error(\"Error while keyspace check, Caused by: .\", e);\r\n        }\r\n        catch (TException e)\r\n        {\r\n            log.error(\"Error while keyspace check, Caused by: .\", e);\r\n        }\r\n        return false;\r\n    }\r\n\r\n    public static boolean columnFamilyExist(String columnfamilyName, String keyspaceName)\r\n    {\r\n        try\r\n        {\r\n            client.set_keyspace(keyspaceName);\r\n            client.system_add_column_family(new CfDef(keyspaceName, columnfamilyName));\r\n        }\r\n        catch (InvalidRequestException irex)\r\n        {\r\n\r\n            StringBuilder builder = new StringBuilder(\"^Cannot add already existing (?:column family|table) .*$\");\r\n\r\n            if (irex.getWhy() != null && irex.getWhy().matches(builder.toString()))\r\n            {\r\n                return true;\r\n            }\r\n            return false;\r\n        }\r\n        catch (SchemaDisagreementException e)\r\n        {\r\n            return false;\r\n        }\r\n        catch (TException e)\r\n        {\r\n            return false;\r\n        }\r\n        return true;\r\n    }\r\n\r\n    /**\r\n     * Check if server running.\r\n     * \r\n     * @return true, if successful\r\n     */\r\n    private static boolean checkIfServerRunning()\r\n    {\r\n        try\r\n        {\r\n            Socket socket = new Socket(\"127.0.0.1\", 9160);\r\n            return socket.getInetAddress() != null;\r\n        }\r\n        catch (UnknownHostException e)\r\n        {\r\n            return false;\r\n        }\r\n        catch (IOException e)\r\n        {\r\n            return false;\r\n        }\r\n\r\n    }\r\n\r\n    /**\r\n     * Inits the client.\r\n     * \r\n     * @throws TTransportException\r\n     *             the t transport exception\r\n     */\r\n    public static void initClient() throws TTransportException\r\n    {\r\n        TSocket socket = new TSocket(\"127.0.0.1\", 9160);\r\n        TTransport transport = new TFramedTransport(socket);\r\n        TProtocol protocol = new TBinaryProtocol(transport, true, true);\r\n        client = new Cassandra.Client(protocol);\r\n        socket.open();\r\n    }\r\n\r\n    /**\r\n     * @return the client\r\n     */\r\n    public static Cassandra.Client getClient()\r\n    {\r\n        return client;\r\n    }\r\n\r\n    public static void executeCqlQuery(String cqlQuery, String keyspaceName)\r\n    {\r\n        try\r\n        {\r\n            getClient().set_cql_version(\"3.0.0\");\r\n            getClient().set_keyspace(keyspaceName);\r\n            getClient().execute_cql3_query(ByteBuffer.wrap(cqlQuery.getBytes(\"UTF-8\")), Compression.NONE,\r\n                    ConsistencyLevel.ONE);\r\n        }\r\n        catch (InvalidRequestException e)\r\n        {\r\n            log.error(\"Error while executing cql query {}, Caused by: .\", cqlQuery, e);\r\n            throw new KunderaException(e);\r\n        }\r\n        catch (UnavailableException e)\r\n        {\r\n            log.error(\"Error while executing cql query {}, Caused by: .\", cqlQuery, e);\r\n            throw new KunderaException(e);\r\n        }\r\n        catch (TimedOutException e)\r\n        {\r\n            log.error(\"Error while executing cql query {}, Caused by: .\", cqlQuery, e);\r\n            throw new KunderaException(e);\r\n        }\r\n        catch (SchemaDisagreementException e)\r\n        {\r\n            log.error(\"Error while executing cql query {}, Caused by: .\", cqlQuery, e);\r\n            throw new KunderaException(e);\r\n        }\r\n        catch (TException e)\r\n        {\r\n            log.error(\"Error while executing cql query {}, Caused by: .\", cqlQuery, e);\r\n            throw new KunderaException(e);\r\n        }\r\n        catch (UnsupportedEncodingException e)\r\n        {\r\n            log.error(\"Error while executing cql query {}, Caused by: .\", cqlQuery, e);\r\n            throw new KunderaException(e);\r\n        }\r\n    }\r\n\r\n    public static boolean dropColumnFamily(String columnFamilyName, String keyspaceName)\r\n    {\r\n        try\r\n        {\r\n            if (columnFamilyExist(columnFamilyName, keyspaceName))\r\n            {\r\n                client.system_drop_column_family(columnFamilyName);\r\n            }\r\n        }\r\n        catch (InvalidRequestException e)\r\n        {\r\n            return true;\r\n        }\r\n        catch (SchemaDisagreementException e)\r\n        {\r\n            return false;\r\n        }\r\n        catch (TException e)\r\n        {\r\n            return false;\r\n        }\r\n        return false;\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/cassandra/thrift/ThriftClientFactoryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.thrift;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.concurrent.ConcurrentMap;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.thrift.ThriftClientFactory;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.service.Host;\n\n/**\n * The Class ThriftClientFactoryTest.\n * \n * @author: karthikp.manchala\n */\npublic class ThriftClientFactoryTest\n{\n\n    /** The Constant PU. */\n    private static final String PU = \"cassandra_pool\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(PU);\n        emf.createEntityManager();\n\n    }\n\n    /**\n     * Test.\n     * \n     * @throws SecurityException\n     *             the security exception\n     * @throws NoSuchMethodException\n     *             the no such method exception\n     * @throws IllegalArgumentException\n     *             the illegal argument exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     * @throws InvocationTargetException\n     *             the invocation target exception\n     * @throws NoSuchFieldException\n     *             the no such field exception\n     */\n    @Test\n    public void test() throws SecurityException, NoSuchMethodException, IllegalArgumentException,\n            IllegalAccessException, InvocationTargetException, NoSuchFieldException\n    {\n        ThriftClientFactory thriftFactory = new ThriftClientFactory();\n\n        Field f = thriftFactory.getClass().getSuperclass().getSuperclass().getDeclaredField(\"persistenceUnit\");\n\n        f.setAccessible(true);\n        f.set(thriftFactory, PU);\n\n        Method m = GenericClientFactory.class.getDeclaredMethod(\"setKunderaMetadata\", KunderaMetadata.class);\n        m.setAccessible(true);\n\n        m.invoke(thriftFactory, ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        thriftFactory.load(PU, null);\n\n        Field hostPools = (thriftFactory.getClass().getSuperclass().getSuperclass()).getDeclaredField(\"hostPools\");\n        hostPools.setAccessible(true);\n        ConcurrentMap<Host, Object> hosts = (ConcurrentMap<Host, Object>) hostPools.get(thriftFactory);\n\n        // for each host check if pooling properties are applied\n        for (Host host : hosts.keySet())\n        {\n            Assert.assertEquals(host.getMaxActive(), 200);\n            Assert.assertEquals(host.getMaxIdle(), 200);\n            Assert.assertEquals(host.getMinIdle(), 20);\n        }\n        thriftFactory.destroy();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/cassandra/thrift/ThriftClientTest.java",
    "content": "package com.impetus.kundera.client.cassandra.thrift;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.thrift.ThriftClient;\nimport com.impetus.client.cassandra.thrift.entities.PersonMToM;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData.OPERATION;\n\npublic class ThriftClientTest\n{\n    private String persistenceUnit = \"thriftClientTest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private ThriftClient client;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        createSchema();\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        client = (ThriftClient) clients.get(persistenceUnit);\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        if (em != null)\n        {\n            em.close();\n        }\n        if (emf != null)\n        {\n            emf.close();\n        }\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    @Test\n    public void executeTests()\n    {\n        persistJoinTable();\n        getColumnsById();\n//        findIdsByColumn();\n        //TODO: debug TimedOutException\n    }\n\n    private void persistJoinTable()\n    {\n        JoinTableData joinTableData = new JoinTableData(OPERATION.INSERT, \"KunderaExamples\", \"PERSON_ADDRESS\",\n                \"PERSON_ID\", \"ADDRESS_ID\", PersonMToM.class);\n\n        Set<Object> values1 = new HashSet<Object>();\n        values1.add(\"A\");\n        values1.add(\"B\");\n        Set<Object> values2 = new HashSet<Object>();\n        values2.add(\"C\");\n        values2.add(\"D\");\n\n        joinTableData.addJoinTableRecord(\"1\", values1);\n        joinTableData.addJoinTableRecord(\"2\", values2);\n\n        client.persistJoinTable(joinTableData);\n\n    }\n\n    private void getColumnsById()\n    {\n        List columns1 = client.getColumnsById(\"KunderaExamples\", \"PERSON_ADDRESS\", \"PERSON_ID\", \"ADDRESS_ID\", \"1\",\n                String.class);\n        Assert.assertNotNull(columns1);\n        Assert.assertFalse(columns1.isEmpty());\n        Assert.assertEquals(2, columns1.size());\n        Assert.assertTrue(columns1.contains(\"A\"));\n        Assert.assertTrue(columns1.contains(\"B\"));\n\n        List columns2 = client.getColumnsById(\"KunderaExamples\", \"PERSON_ADDRESS\", \"PERSON_ID\", \"ADDRESS_ID\", \"2\",\n                String.class);\n        Assert.assertNotNull(columns2);\n        Assert.assertFalse(columns2.isEmpty());\n        Assert.assertEquals(2, columns2.size());\n        Assert.assertTrue(columns2.contains(\"C\"));\n        Assert.assertTrue(columns2.contains(\"D\"));\n\n    }\n\n    private void findIdsByColumn()\n    {\n        Object[] ids1 = client.findIdsByColumn(\"KunderaExamples\", \"PERSON_ADDRESS\", \"PERSON_ID\", \"ADDRESS_ID\", \"A\",\n                PersonMToM.class);\n        Assert.assertNotNull(ids1);\n        Assert.assertTrue(ids1.length == 1);\n        Assert.assertEquals(\"1\", ids1[0]);\n\n        Object[] ids2 = client.findIdsByColumn(\"KunderaExamples\", \"PERSON_ADDRESS\", \"PERSON_ID\", \"ADDRESS_ID\", \"B\",\n                PersonMToM.class);\n        Assert.assertNotNull(ids2);\n        Assert.assertTrue(ids2.length == 1);\n        Assert.assertEquals(\"1\", ids2[0]);\n\n        Object[] ids3 = client.findIdsByColumn(\"KunderaExamples\", \"PERSON_ADDRESS\", \"PERSON_ID\", \"ADDRESS_ID\", \"C\",\n                PersonMToM.class);\n        Assert.assertNotNull(ids3);\n        Assert.assertTrue(ids3.length == 1);\n        Assert.assertEquals(\"2\", ids3[0]);\n\n        Object[] ids4 = client.findIdsByColumn(\"KunderaExamples\", \"PERSON_ADDRESS\", \"PERSON_ID\", \"ADDRESS_ID\", \"D\",\n                PersonMToM.class);\n        Assert.assertNotNull(ids4);\n        Assert.assertTrue(ids4.length == 1);\n        Assert.assertEquals(\"2\", ids4[0]);\n    }\n\n    private void createSchema() throws InvalidRequestException, SchemaDisagreementException, TException\n    {\n        KsDef ksDef = null;\n        CfDef user_Def = new CfDef();\n        user_Def.name = \"PERSON_ADDRESS\";\n        user_Def.keyspace = \"KunderaExamples\";\n        user_Def.setComparator_type(\"UTF8Type\");\n        user_Def.setDefault_validation_class(\"UTF8Type\");\n        user_Def.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"PERSON_ID\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef);\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"ADDRESS_ID\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef1);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaExamples\");\n            CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"PERSON\"))\n                {\n\n                    CassandraCli.client.system_drop_column_family(\"PERSON\");\n\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def);\n\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(\"KunderaExamples\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/entitylisteners/AbstractSuperClass.java",
    "content": "/*******************************************************************************\n* * Copyright 2017 Impetus Infotech.\n* *\n* * Licensed under the Apache License, Version 2.0 (the \"License\");\n* * you may not use this file except in compliance with the License.\n* * You may obtain a copy of the License at\n* *\n* * http://www.apache.org/licenses/LICENSE-2.0\n* *\n* * Unless required by applicable law or agreed to in writing, software\n* * distributed under the License is distributed on an \"AS IS\" BASIS,\n* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* * See the License for the specific language governing permissions and\n* * limitations under the License.\n******************************************************************************/\npackage com.impetus.kundera.client.crud.entitylisteners;\n\nimport javax.persistence.EntityListeners;\nimport javax.persistence.MappedSuperclass;\n\n/**\n * The Class AbstractSuperClass.\n */\n@MappedSuperclass\n@EntityListeners(Listener.class)\npublic abstract class AbstractSuperClass\n{\n\n    /** The extern id. */\n    private String externId;\n\n    /**\n     * Instantiates a new abstract super class.\n     */\n    public AbstractSuperClass()\n    {\n    }\n\n    /**\n     * Gets the extern id.\n     * \n     * @return the extern id\n     */\n    public String getExternId()\n    {\n        return this.externId;\n    }\n\n    /**\n     * Sets the extern id.\n     * \n     * @param externId\n     *            the new extern id\n     */\n    public void setExternId(String externId)\n    {\n        this.externId = externId;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/entitylisteners/EntityListenersTest.java",
    "content": "/*******************************************************************************\n* * Copyright 2017 Impetus Infotech.\n* *\n* * Licensed under the Apache License, Version 2.0 (the \"License\");\n* * you may not use this file except in compliance with the License.\n* * You may obtain a copy of the License at\n* *\n* * http://www.apache.org/licenses/LICENSE-2.0\n* *\n* * Unless required by applicable law or agreed to in writing, software\n* * distributed under the License is distributed on an \"AS IS\" BASIS,\n* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* * See the License for the specific language governing permissions and\n* * limitations under the License.\n******************************************************************************/\npackage com.impetus.kundera.client.crud.entitylisteners;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * The Class EntityListenersTest.\n */\npublic class EntityListenersTest\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        Map<String, String> props = new HashMap<>();\n        props.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(\"entitylisteners_pu\", props);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test operations.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testOperations() throws Exception\n    {\n        Person p = new Person();\n        p.setId(101);\n        p.setExternId(\"abc\");\n        em.persist(p);\n\n        Person p1 = em.find(Person.class, 101);\n        Assert.assertEquals(\"id_set_from_pre_persist\", p1.getExternId());\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"EntityListenersTest\");\n        emf.close();\n        emf = null;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/entitylisteners/Listener.java",
    "content": "/*******************************************************************************\n* * Copyright 2017 Impetus Infotech.\n* *\n* * Licensed under the Apache License, Version 2.0 (the \"License\");\n* * you may not use this file except in compliance with the License.\n* * You may obtain a copy of the License at\n* *\n* * http://www.apache.org/licenses/LICENSE-2.0\n* *\n* * Unless required by applicable law or agreed to in writing, software\n* * distributed under the License is distributed on an \"AS IS\" BASIS,\n* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* * See the License for the specific language governing permissions and\n* * limitations under the License.\n******************************************************************************/\npackage com.impetus.kundera.client.crud.entitylisteners;\n\nimport javax.persistence.PrePersist;\n\n/**\n * The Class Listener.\n */\npublic class Listener\n{\n\n    /**\n     * On pre persist.\n     * \n     * @param entity\n     *            the entity\n     */\n    @PrePersist\n    void onPrePersist(final Object entity)\n    {\n\n        String id = \"id_set_from_pre_persist\";\n\n        ((AbstractSuperClass) entity).setExternId(id);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/entitylisteners/Person.java",
    "content": "/*******************************************************************************\n* * Copyright 2017 Impetus Infotech.\n* *\n* * Licensed under the Apache License, Version 2.0 (the \"License\");\n* * you may not use this file except in compliance with the License.\n* * You may obtain a copy of the License at\n* *\n* * http://www.apache.org/licenses/LICENSE-2.0\n* *\n* * Unless required by applicable law or agreed to in writing, software\n* * distributed under the License is distributed on an \"AS IS\" BASIS,\n* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* * See the License for the specific language governing permissions and\n* * limitations under the License.\n******************************************************************************/\npackage com.impetus.kundera.client.crud.entitylisteners;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n/**\n * The Class Person.\n */\n@Entity\npublic class Person extends AbstractSuperClass\n{\n\n    /** The id. */\n    @Id\n    private int id;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the new id\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/inheritence/FacebookProfile.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.DiscriminatorValue;\r\nimport javax.persistence.Entity;\r\n\r\n/**\r\n * Facebook profile entity\r\n * \r\n * @author vivek.mishra\r\n * \r\n */\r\n@Entity\r\n@DiscriminatorValue(\"fb\")\r\npublic class FacebookProfile extends SocialProfile\r\n{\r\n    // protected static final String TYPE = \"twitter\";\r\n\r\n    // @Id\r\n    // // @GeneratedValue\r\n    // @Column(name = \"guid\", updatable = false, nullable = false)\r\n    // private String id;\r\n\r\n    @Column(name = \"facebook_id\", updatable = false)\r\n    private String facebookId;\r\n\r\n    @Column(name = \"facebook_user\", length = 128)\r\n    private String facebookUser;\r\n\r\n    public String getFacebookId()\r\n    {\r\n        return facebookId;\r\n    }\r\n\r\n    public void setFacebookId(String facebookId)\r\n    {\r\n        this.facebookId = facebookId;\r\n    }\r\n\r\n    public String getFacebookUser()\r\n    {\r\n        return facebookUser;\r\n    }\r\n\r\n    public void setFacebookUser(String facebookUser)\r\n    {\r\n        this.facebookUser = facebookUser;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/inheritence/GuidDomainObject.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\nimport javax.persistence.Id;\r\nimport javax.persistence.MappedSuperclass;\r\n\r\n\r\n\r\n/**\r\n * Abstract mapped super class.\r\n * @author vivek.mishra\r\n *\r\n */\r\n@MappedSuperclass\r\nabstract public class GuidDomainObject \r\n{\r\n    @Id\r\n    private Long id;\r\n\r\n    public Long getId()\r\n    {\r\n        return id;\r\n    }\r\n\r\n    public void setId(Long id)\r\n    {\r\n        this.id = id;\r\n    }\r\n\r\n    \r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/inheritence/InheritenceDomainTest.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Persistence;\r\nimport javax.persistence.Query;\r\n\r\nimport junit.framework.Assert;\r\n\r\nimport org.junit.After;\r\nimport org.junit.AfterClass;\r\nimport org.junit.BeforeClass;\r\nimport org.junit.Test;\r\n\r\nimport com.impetus.client.cassandra.common.CassandraConstants;\r\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\r\n\r\n/**\r\n * Junit for abstract entity class's operation.\r\n * \r\n * @author vivek.mishra\r\n * \r\n */\r\npublic class InheritenceDomainTest\r\n{\r\n\r\n    protected static String _PU = \"twissandraTest\";\r\n\r\n    /** The emf. */\r\n    private static EntityManagerFactory emfThrift;\r\n\r\n    /** The em. */\r\n    private static EntityManager emThrift;\r\n\r\n    @BeforeClass\r\n    public static void setUpBeforeClass() throws Exception\r\n    {\r\n        CassandraCli.cassandraSetUp();\r\n        CassandraCli.createKeySpace(\"KunderaExamples\");\r\n    }\r\n\r\n    /**\r\n     * Test abstract entity relations via thrift.\r\n     */\r\n    @Test\r\n    public void testRelationViaThrift()\r\n    {\r\n        createEmf(null);\r\n        assertRelation(emThrift);\r\n    }\r\n\r\n    /**\r\n     * Test abstract entity operations via thrift.\r\n     */\r\n    @Test\r\n    public void testAbstractEntityViaThrift()\r\n    {\r\n        createEmf(null);\r\n        assertAbstractEntity(emThrift);\r\n    }\r\n\r\n    /**\r\n     * Test abstract entity relations via thrift.\r\n     */\r\n    @Test\r\n    public void testRelationViaCQL()\r\n    {\r\n        // Map<String, Client> clientMap = (Map<String, Client>)\r\n        // emThrift.getDelegate();\r\n        // ThriftClient tc = (ThriftClient) clientMap.get(_PU);\r\n        // tc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\r\n        createEmf(CassandraConstants.CQL_VERSION_3_0);\r\n        assertRelation(emThrift);\r\n        // tc.setCqlVersion(CassandraConstants.CQL_VERSION_2_0); // reset CQL\r\n        // version to 2.0\r\n    }\r\n\r\n    /**\r\n     * Test abstract entity operations via thrift.\r\n     */\r\n    @Test\r\n    public void testAbstractEntityViaCQL()\r\n    {\r\n        // Map<String, Client> clientMap = (Map<String, Client>)\r\n        // emThrift.getDelegate();\r\n        // ThriftClient tc = (ThriftClient) clientMap.get(_PU);\r\n        // tc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\r\n        createEmf(CassandraConstants.CQL_VERSION_3_0);\r\n        assertAbstractEntity(emThrift);\r\n        // tc.setCqlVersion(CassandraConstants.CQL_VERSION_2_0); // reset CQL\r\n        // version to 2.0\r\n    }\r\n\r\n    /**\r\n     * Tear down.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    @After\r\n    public void tearDown() throws Exception\r\n    {\r\n        CassandraCli.dropColumnFamily(\"user_account\", \"KunderaExamples\");\r\n        CassandraCli.dropColumnFamily(\"social_profile\", \"KunderaExamples\");\r\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\r\n    }\r\n\r\n    @AfterClass\r\n    public static void tearDownAfterClass()\r\n    {\r\n        if (emThrift != null)\r\n        {\r\n            emThrift.close();\r\n            emThrift = null;\r\n        }\r\n      \r\n    }\r\n\r\n    private void createEmf(String auto_ddl_proeprty)\r\n    {\r\n        if (auto_ddl_proeprty != null)\r\n        {\r\n            Map<String, String> propertyMap = new HashMap<String, String>();\r\n            propertyMap.put(CassandraConstants.CQL_VERSION, auto_ddl_proeprty);\r\n\r\n            emfThrift = Persistence.createEntityManagerFactory(_PU, propertyMap);\r\n        }\r\n        else\r\n        {\r\n            emfThrift = Persistence.createEntityManagerFactory(_PU);\r\n        }\r\n        emThrift = emfThrift.createEntityManager();\r\n    }\r\n\r\n    private void assertRelation(EntityManager em)\r\n    {\r\n        List<SocialProfile> profiles = new ArrayList<SocialProfile>();\r\n\r\n        FacebookProfile fbprofile = new FacebookProfile();\r\n        fbprofile.setId(103l);\r\n        fbprofile.setFacebookId(\"fb1\");\r\n        fbprofile.setFacebookUser(\"facebook\");\r\n        fbprofile.setuserType(\"dumbo\");\r\n\r\n        profiles.add(fbprofile);\r\n\r\n        TwitterProfile twprofile1 = new TwitterProfile();\r\n        twprofile1.setTwitterId(\"2\");\r\n        twprofile1.setTwitterName(\"test2\");\r\n        twprofile1.setId(102l);\r\n        profiles.add(twprofile1);\r\n        twprofile1.setuserType(\"dumbo\");\r\n\r\n        UserAccount uacc = new UserAccount();\r\n\r\n        uacc.setId(101l);\r\n        uacc.setDispName(\"Test\");\r\n        uacc.setSocialProfiles(profiles);\r\n\r\n        twprofile1.setuserAccount(uacc);\r\n        fbprofile.setuserAccount(uacc);\r\n\r\n        em.getTransaction().begin();\r\n        em.persist(uacc);\r\n        em.getTransaction().commit();\r\n\r\n        // TODO: Stack over flow error.\r\n\r\n        // Uncomment this to test\r\n        // https://github.com/impetus-opensource/Kundera/issues/460\r\n        uacc.setDispName(\"UpdatedTest\");\r\n        em.persist(fbprofile);\r\n\r\n        em.persist(twprofile1);\r\n        em.clear();\r\n\r\n        String uaQuery = \"Select ua from UserAccount ua\";\r\n\r\n        Query q = em.createQuery(uaQuery);\r\n        List<UserAccount> results = q.getResultList();\r\n\r\n        Assert.assertEquals(1, results.size());\r\n        Assert.assertEquals(\"UpdatedTest\", results.get(0).getDispName());\r\n        Assert.assertEquals(2, results.get(0).getSocialProfiles().size());\r\n        Assert.assertFalse(results.get(0).getSocialProfiles().get(0).getId().equals(results.get(0).getId()));\r\n\r\n        em.clear();\r\n    }\r\n\r\n    private void assertAbstractEntity(EntityManager em)\r\n    {\r\n        FacebookProfile fbprofile = new FacebookProfile();\r\n        fbprofile.setId(Long.MIN_VALUE);\r\n        fbprofile.setFacebookId(\"fb1\");\r\n        fbprofile.setFacebookUser(\"facebook\");\r\n        fbprofile.setuserType(\"dumbo\");\r\n\r\n        em.persist(fbprofile);\r\n\r\n        TwitterProfile twprofile = new TwitterProfile();\r\n        twprofile.setTwitterId(\"2\");\r\n        twprofile.setTwitterName(\"test2\");\r\n        twprofile.setId(Long.MAX_VALUE);\r\n        twprofile.setuserType(\"dumbo\");\r\n\r\n        em.persist(twprofile);\r\n\r\n        SocialProfile facebookProfile = em.find(SocialProfile.class, Long.MIN_VALUE);\r\n        Assert.assertNotNull(facebookProfile);\r\n        Assert.assertTrue(facebookProfile.getClass().isAssignableFrom(FacebookProfile.class));\r\n\r\n        SocialProfile twitterProfile = em.find(SocialProfile.class, Long.MAX_VALUE);\r\n        Assert.assertNotNull(twitterProfile);\r\n        Assert.assertTrue(twitterProfile.getClass().isAssignableFrom(TwitterProfile.class));\r\n\r\n        String queryStr = \"Select s from SocialProfile s\";\r\n\r\n        Query query = em.createQuery(queryStr);\r\n\r\n        List<SocialProfile> socialProfiles = query.getResultList();\r\n\r\n        Assert.assertFalse(socialProfiles.isEmpty());\r\n        Assert.assertEquals(2, socialProfiles.size());\r\n        Assert.assertFalse(socialProfiles.get(0).getClass().getSimpleName()\r\n                .equals(socialProfiles.get(1).getClass().getSimpleName()));\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/inheritence/SocialProfile.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.crud.inheritence;\n\nimport java.io.Serializable;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorColumn;\nimport javax.persistence.DiscriminatorType;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * Abstract entity class.\n * @author vivek.mishra\n *\n */\n@Entity\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@Table(name = \"social_profile\")\n@DiscriminatorColumn(name = \"profile_type\", length = 64, discriminatorType = DiscriminatorType.STRING)\npublic abstract class SocialProfile extends GuidDomainObject implements Serializable\n{\n    @Column(name = \"userType\")\n    private String userType;\n\n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"user_account_id\")\n    private UserAccount account;\n    \n    public String getuserType()\n    {\n        return userType;\n    }\n\n    public void setuserType(String userType)\n    {\n        this.userType = userType;\n    }\n    \n    public UserAccount getuserAccount()\n    {\n        return account;\n    }\n\n    public void setuserAccount(UserAccount account)\n    {\n        this.account = account;\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/inheritence/TwitterProfile.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.DiscriminatorValue;\r\nimport javax.persistence.Entity;\r\n\r\n/**\r\n * Twitter profile entity.\r\n * @author vivek.mishra\r\n *\r\n */\r\n@Entity\r\n@DiscriminatorValue(\"twitter\")\r\npublic class TwitterProfile extends SocialProfile\r\n{\r\n\r\n    @Column(name = \"twitter_id\", updatable = false)\r\n    private String twitterId;\r\n\r\n    @Column(name = \"twitter_user\", length = 128)\r\n    private String twitterUser;\r\n    \r\n    public String getTwitterId()\r\n    {\r\n        return twitterId;\r\n    }\r\n\r\n    public void setTwitterId(String twitterId)\r\n    {\r\n        this.twitterId = twitterId;\r\n    }\r\n    \r\n    public String getTwitterName()\r\n    {\r\n        return twitterUser;\r\n    }\r\n\r\n    public void setTwitterName(String twitterUser)\r\n    {\r\n        this.twitterUser = twitterUser;\r\n    }\r\n\r\n\r\n}  \r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/inheritence/UserAccount.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\n\r\nimport java.util.List;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.Table;\r\n\r\n\r\n/**\r\n * User account entity.\r\n * @author vivek.mishra\r\n *\r\n */\r\n@Entity\r\n@Table(name = \"user_account\")\r\npublic class UserAccount extends GuidDomainObject\r\n{\r\n   \r\n    @Column(name = \"display_name\", length = 128)\r\n    private String displayName = null;\r\n\r\n    @Column(name = \"email\", length = 128, unique = true)\r\n    private String email = null;\r\n\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER,mappedBy = \"account\")\r\n    private List<SocialProfile> profiles;\r\n    \r\n    public String getDispName()\r\n    {\r\n        return displayName;\r\n    }\r\n\r\n    public void setDispName(String displayName)\r\n    {\r\n        this.displayName = displayName;\r\n    }\r\n    \r\n    public String getEmail()\r\n    {\r\n        return email;\r\n    }\r\n\r\n    public void setEmail(String email)\r\n    {\r\n        this.email = email;\r\n    }\r\n    \r\n    public List<SocialProfile> getSocialProfiles()\r\n    {\r\n        return profiles;\r\n    }\r\n\r\n    public void setSocialProfiles(List<SocialProfile> profiles)\r\n    {\r\n        this.profiles = profiles;\r\n    }\r\n} \r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/CreditTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n * Credit transaction extends {@link Transaction}\n *\n */\n\n@Entity\n@Table(name = \"TRNX_CREDIT\")\n@DiscriminatorValue(value = \"CREDIT\")\n@AttributeOverride(name=\"bankIdentifier\",column= @Column(name=\"CREDIT_BANK_IDENT\"))\n@IndexCollection(columns={@Index(name=\"bankIdentifier\")})\npublic class CreditTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public CreditTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/DebitTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n * Debit transaction extends {@link Transaction}\n *\n */\n@Entity\n@DiscriminatorValue(value=\"DEBIT\")\n\n@AttributeOverrides(value = { @AttributeOverride(name = \"txId\", column = @Column(name = \"DEBIT_ID\")),\n        @AttributeOverride(name = \"bankIdentifier\", column = @Column(name = \"DEBIT_BANK_IDENT\")),\n        @AttributeOverride(name = \"transactionDt\", column = @Column(name = \"TX_DT\")) })\n\n@IndexCollection(columns={@Index(name=\"bankIdentifier\")})\npublic class DebitTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public DebitTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/query/ResultIteratorEmbeddableTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.query;\n\n\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.crud.compositeType.CassandraCompoundKey;\nimport com.impetus.client.crud.compositeType.CassandraPrimeUser;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author chhavi.gangwal\n * junit for {@link IResultIteratorEmbeddableTest}.\n */\npublic class ResultIteratorEmbeddableTest \n{\n  \n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n    \n   \n    private static final String PERSISTENCE_UNIT = \"composite_pu\";\n\n  \n\n    /** The Constant logger. */\n    private static final Logger logger = LoggerFactory.getLogger(ResultIteratorEmbeddableTest.class);\n\n    \n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n        \n        \n        \n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        em = emf.createEntityManager();\n    }\n\n\n    \n    @Test\n    public void testScrollViaCQL3() throws Exception\n    {\n        onScroll();\n    }\n\n  \n    private void onScroll()\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 15);\n        Object p3 = prepareData(\"3\", 20);\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        em.flush();\n        em.clear();\n        final String queryWithoutClause = \"Select p from CassandraPrimeUser p \";\n\n        assertOnScroll(queryWithoutClause,3);\n\n        final String queryWithClause = \"Select p from CassandraPrimeUser p where p.name = vivek\";\n        \n        assertOnScroll(queryWithClause,3);\n        \n        final String queryWithAndClause = \"Select p from CassandraPrimeUser p where p.name = vivek and p.key.userId = 'mevivs2' and p.key.tweetId = 15\";\n        \n        assertOnScroll(queryWithAndClause,1);\n\n        final String queryWithLTClause = \"Select p from CassandraPrimeUser p where p.name = vivek and p.key.userId = 'mevivs1' and p.key.tweetId < 15\";\n        \n        assertOnScroll(queryWithLTClause,1);\n\n        final String queryWithLTGTClause = \"Select p from CassandraPrimeUser p where p.name = vivek and p.key.userId = 'mevivs2' and p.key.tweetId > 10 and p.key.tweetId < 20\";\n        \n        assertOnScroll(queryWithLTGTClause,1);\n\n              \n        String queryWithIdClause = \"Select p from CassandraPrimeUser p where p.key.userId = 'mevivs2' \";\n        assertOnScroll(queryWithIdClause,1);\n        \n        String queryWithIdEmbeddableKeyClause = \"Select p from CassandraPrimeUser p where p.key.userId = 'mevivs2' and p.key.tweetId = 15\";\n        assertOnScroll(queryWithIdEmbeddableKeyClause,1);\n    }\n\n    \n\n    private void assertOnScroll(final String queryWithoutClause, int expectedCount)\n    {\n        Query query = (Query) em.createQuery(queryWithoutClause,\n                CassandraPrimeUser.class);\n        \n        assertOnFetch(query, 3, expectedCount);\n        assertOnFetch(query,2,expectedCount);  // less records\n\n        assertOnFetch(query,4,expectedCount); // more fetch size than available in db.\n        assertOnFetch(query,3,expectedCount); // more fetch size than available in db.\n      \n        assertOnFetch(query,null,expectedCount); //set to null; \n        \n    }\n\n    private void assertOnFetch(Query query, Integer fetchSize, int available)\n    {\n        query.setFetchSize(fetchSize);\n        int counter=0;\n        Iterator<CassandraPrimeUser> iter = query.iterate();\n\n        while (iter.hasNext())\n        {\n            Assert.assertNotNull(iter.next());\n            counter++;\n        }\n\n        Assert.assertEquals(counter, fetchSize == null || available < fetchSize?available:fetchSize);\n        try\n        {\n            iter.next();\n            Assert.fail();\n        }\n        catch (NoSuchElementException nsex)\n        {\n            Assert.assertNotNull(nsex.getMessage());\n        }\n    }\n\n    /**\n     * CompositeUserDataType\n     * \n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n\n        CassandraCli.truncateColumnFamily(\"CompositeCassandra\", \"CompositeUser\");\n    }\n    \n    private Object prepareData(String rowkey, int tweetId)\n    {\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();   \n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\"+rowkey, tweetId, timeLineId);\n        CassandraPrimeUser user = new CassandraPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        user.setName(\"vivek\");\n        return user;\n    }\n    \n   \n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/com/impetus/kundera/query/ResultIteratorTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.query;\n\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport java.util.UUID;\nimport org.junit.Assert;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.crud.BaseTest;\nimport com.impetus.client.crud.PersonCassandra;\nimport com.impetus.client.crud.Token;\nimport com.impetus.client.crud.TokenClient;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author vivek.mishra\n * junit for {@link IResultIterator}.\n */\npublic class ResultIteratorTest extends BaseTest\n{\n    private static final String SEC_IDX_CASSANDRA_TEST = \"genericCassandraTest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    public void setUp(final String persistenceUnit,final String keyspace, final String cqlVersion) throws Exception\n    {\n        \n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(keyspace);\n        Map propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        propertyMap.put(CassandraConstants.CQL_VERSION, cqlVersion);\n\n        emf = Persistence.createEntityManagerFactory(persistenceUnit, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testScrollViaCQL3() throws Exception\n    {\n        setUp(SEC_IDX_CASSANDRA_TEST,\"KunderaExamples\",CassandraConstants.CQL_VERSION_3_0);\n        onScroll();\n        tearDown(\"KunderaExamples\");\n    }\n\n    @Test\n    public void testScrollViaCQL3ForNativeQuery() throws Exception\n    {\n        setUp(SEC_IDX_CASSANDRA_TEST,\"KunderaExamples\",CassandraConstants.CQL_VERSION_3_0);\n        OnScrollForNativeQuery();\n        tearDown(\"KunderaExamples\");\n    }\n    \n    \n   @Test\n    public void testScrollViaCQL2ForNativeQuery() throws Exception\n    {\n        setUp(SEC_IDX_CASSANDRA_TEST,\"KunderaExamples\",CassandraConstants.CQL_VERSION_2_0);\n        OnScrollForNativeQuery();\n        tearDown(\"KunderaExamples\");\n    }\n   \n   @Test\n   public void testScrollViaCQL2() throws Exception\n   {\n       setUp(SEC_IDX_CASSANDRA_TEST,\"KunderaExamples\",CassandraConstants.CQL_VERSION_2_0);\n       onScroll();\n       tearDown(\"KunderaExamples\");\n   }\n   \n   \n   \n\n    @Test\n    public void testCQL3ScrollAssociation() throws Exception \n    {\n        setUp(\"myapp_pu\", \"myapp\", CassandraConstants.CQL_VERSION_3_0);\n        assertOnTokenScroll();\n        tearDown(\"myapp\");\n    }\n    \n    @Test\n    public void testCQL2ScrollAssociation() throws Exception \n    {\n        setUp(\"myapp_pu\", \"myapp\", CassandraConstants.CQL_VERSION_2_0);\n        assertOnTokenScroll();\n        tearDown(\"myapp\");\n    }\n\n    private void assertOnTokenScroll()\n    {\n        Token token1 = new Token();\n        token1.setId(\"tokenId1\");\n        token1.setTokenName(\"tokenName1\");\n        TokenClient client = new TokenClient();\n        client.setClientName(\"tokenClient1\");\n        client.setId(\"tokenClientId\");\n        token1.setClient(client);\n\n        Token token2 = new Token();\n        token2.setId(\"tokenId2\");\n        token2.setTokenName(\"tokenName2\");\n        token2.setClient(client);\n        em.persist(token1);\n        em.persist(token2);\n\n        String queryWithoutClause = \"Select t from Token t\";\n        assertOnTokenScroll(queryWithoutClause,2);\n\n    \n        String queryWithClause = \"Select t from Token t where t.tokenName='tokenName1'\";\n        \n        assertOnTokenScroll(queryWithClause,1);\n\n        //TODO:: Need to discuss with KK, this should be working with token support. Special scenario. \n        String queryWithIdClause = \"Select t from Token t where t.id = 'tokenId1'\";\n//        \n        assertOnTokenScroll(queryWithIdClause,1);\n        \n\n    }\n\n    private void assertOnTokenScroll(String queryClause, int expected)\n    {\n        Query query = (Query) em.createQuery(queryClause,\n                Token.class);\n        \n        int count=0;\n        Iterator<Token> tokens = query.iterate();\n        while(tokens.hasNext())\n        {\n            Token token = tokens.next();\n            Assert.assertNotNull(token);\n            Assert.assertNotNull(token.getClient());\n            Assert.assertEquals(2, token.getClient().getTokens().size());\n            count++;\n        }\n        \n        Assert.assertTrue(count > 0);\n        Assert.assertTrue(count == expected);\n    }\n    \n    public void OnScrollForNativeQuery()\n    {\n    \tObject p = prepareData(UUID.randomUUID().toString(), 99);\n    \t\n        em.persist(p);\n    \tem.flush();\n        em.clear();\n       \n       assertOnScrollForNativeQuery(null,1);\n     }\n    \n    \n    private void onScroll()\n    {\n        \n        Object p1= prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n       \n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        em.flush();\n        em.clear();\n\n\n        final String queryWithClause = \"Select p from PersonCassandra p where p.personName = vivek\";\n        \n        assertOnScroll(queryWithClause,3);\n        \n        final String queryWithAndClause = \"Select p from PersonCassandra p where p.personName = vivek and p.age = 15\";\n        \n        assertOnScroll(queryWithAndClause,1);\n\n        final String queryWithLTClause = \"Select p from PersonCassandra p where p.personName = vivek and p.age < 15\";\n        \n        assertOnScroll(queryWithLTClause,1);\n\n        final String queryWithGTClause = \"Select p from PersonCassandra p where p.personName = vivek and p.age >= 15\";\n        \n        assertOnScroll(queryWithGTClause,2);\n\n        final String queryWithLTGTClause = \"Select p from PersonCassandra p where p.personName = vivek and p.age > 10 and p.age < 20\";\n        \n        assertOnScroll(queryWithLTGTClause,1);\n\n        final String queryWithLTGTEClause = \"Select p from PersonCassandra p where p.personName = vivek and p.age >= 10 and p.age < 20\";\n        \n        assertOnScroll(queryWithLTGTEClause,2);\n        \n        String queryWithIdClause = \"Select p from PersonCassandra p where p.personId = '2' \";\n        assertOnScroll(queryWithIdClause,1);\n    }\n\n   \n    private void assertOnScrollForNativeQuery(final String queryWithoutClause, int expectedCount)\n    {\n        Query query = (Query) em.createNamedQuery(\"q\",\n                PersonCassandra.class);\n        \n       assertOnFetch(query,10,expectedCount);  \n        }\n    \n    \n    \n    \n    private void assertOnScroll(final String queryWithoutClause, int expectedCount)\n    {\n        Query query = (Query) em.createNamedQuery(queryWithoutClause,\n                PersonCassandra.class);\n        \n        assertOnFetch(query, 0, expectedCount);\n        assertOnFetch(query,2,expectedCount);  // less records\n\n        assertOnFetch(query,5,expectedCount); // more fetch size than available in db.\n        assertOnFetch(query,3,expectedCount); // more fetch size than available in db.\n        \n        assertOnFetch(query,null,expectedCount); //set to null; \n        \n    }\n\n    \n   private void assertOnFetch(Query query, Integer fetchSize, int available)\n    {\n        query.setFetchSize(fetchSize);\n        int counter=0;\n        try\n        {\n        Iterator<PersonCassandra> iter = query.iterate();\n\n        while (iter.hasNext())\n        {\n            Assert.assertNotNull(iter.next());\n            counter++;\n        }\n\n        Assert.assertEquals(counter, fetchSize == null || available < fetchSize?available:fetchSize);\n        try\n        {\n            iter.next();\n            Assert.fail();\n        }\n        catch (NoSuchElementException nsex)\n        {\n            Assert.assertNotNull(nsex.getMessage());\n        }\n        }catch(UnsupportedOperationException e)\n        { \n        \tAssert.assertEquals(\"Iteration not supported over native queries\",e.getMessage());\n        }\n        \n    }\n\n    public void tearDown(final String keyspace)\n    {\n//        em.close();\n//        emf.close();\n        CassandraCli.dropKeySpace(keyspace);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/org/apache/cassandra/auth/SimpleAuthenticator.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage org.apache.cassandra.auth;\n\n/*\n * \n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n * \n *   http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n * \n */\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.InetAddress;\nimport java.security.MessageDigest;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.apache.cassandra.exceptions.AuthenticationException;\nimport org.apache.cassandra.exceptions.ConfigurationException;\nimport org.apache.cassandra.io.util.FileUtils;\nimport org.apache.cassandra.utils.FBUtilities;\nimport org.apache.cassandra.utils.Hex;\n\npublic class SimpleAuthenticator implements IAuthenticator\n{\n    public final static String PASSWD_FILENAME_PROPERTY = \"passwd.properties\";\n\n    public final static String PMODE_PROPERTY = \"passwd.mode\";\n\n    public static final String USERNAME_KEY = \"username\";\n\n    public static final String PASSWORD_KEY = \"password\";\n\n    public enum PasswordMode\n    {\n        PLAIN, MD5,\n    };\n\n    public AuthenticatedUser defaultUser()\n    {\n        // users must log in\n        return null;\n    }\n\n    public AuthenticatedUser authenticate(Map<String, String> credentials) throws AuthenticationException\n    {\n        String pmode_plain = System.getProperty(PMODE_PROPERTY);\n        PasswordMode mode = PasswordMode.PLAIN;\n\n        if (null != pmode_plain)\n        {\n            try\n            {\n                mode = PasswordMode.valueOf(pmode_plain);\n            }\n            catch (Exception e)\n            {\n                // this is not worth a StringBuffer\n                String mode_values = \"\";\n                for (PasswordMode pm : PasswordMode.values())\n                    mode_values += \"'\" + pm + \"', \";\n\n                mode_values += \"or leave it unspecified.\";\n                throw new AuthenticationException(\"The requested password check mode '\" + pmode_plain\n                        + \"' is not a valid mode.  Possible values are \" + mode_values);\n            }\n        }\n\n        String pfilename = System.getProperty(PASSWD_FILENAME_PROPERTY);\n\n        String username = null;\n        CharSequence user = credentials.get(USERNAME_KEY);\n        if (null == user)\n            throw new AuthenticationException(\"Authentication request was missing the required key '\" + USERNAME_KEY\n                    + \"'\");\n        else\n            username = user.toString();\n\n        String password = null;\n        CharSequence pass = credentials.get(PASSWORD_KEY);\n        if (null == pass)\n            throw new AuthenticationException(\"Authentication request was missing the required key '\" + PASSWORD_KEY\n                    + \"'\");\n        else\n            password = pass.toString();\n\n        boolean authenticated = false;\n\n        InputStream in = null;\n        try\n        {\n            in = Thread.currentThread().getContextClassLoader().getResourceAsStream(\"passwd.properties\");\n            // in = new BufferedInputStream(new FileInputStream(pfilename));\n            Properties props = new Properties();\n            props.load(in);\n\n            // note we keep the message here and for the wrong password exactly\n            // the same to prevent attackers from guessing what users are valid\n            if (null == props.getProperty(username))\n                throw new AuthenticationException(authenticationErrorMessage(mode, username));\n            switch (mode)\n            {\n            case PLAIN:\n                authenticated = password.equals(props.getProperty(username));\n                break;\n            case MD5:\n                authenticated = MessageDigest.isEqual(FBUtilities.threadLocalMD5Digest().digest(password.getBytes()),\n                        Hex.hexToBytes(props.getProperty(username)));\n                break;\n            default:\n                throw new RuntimeException(\"Unknown PasswordMode \" + mode);\n            }\n        }\n        catch (IOException e)\n        {\n            throw new RuntimeException(\"Authentication table file given by property \" + PASSWD_FILENAME_PROPERTY\n                    + \" could not be opened: \" + e.getMessage());\n        }\n        catch (Exception e)\n        {\n            throw new RuntimeException(\"Unexpected authentication problem\", e);\n        }\n        finally\n        {\n            FileUtils.closeQuietly(in);\n        }\n\n        if (!authenticated)\n            throw new AuthenticationException(authenticationErrorMessage(mode, username));\n\n        return new AuthenticatedUser(username);\n    }\n\n    public void validateConfiguration() throws ConfigurationException\n    {\n        String pfilename = System.getProperty(SimpleAuthenticator.PASSWD_FILENAME_PROPERTY);\n        if (pfilename == null)\n        {\n            throw new ConfigurationException(\"When using \" + this.getClass().getCanonicalName() + \" \"\n                    + SimpleAuthenticator.PASSWD_FILENAME_PROPERTY + \" properties must be defined.\");\n        }\n    }\n\n    static String authenticationErrorMessage(PasswordMode mode, String username)\n    {\n        return String.format(\"Given password in password mode %s could not be validated for user %s\", mode, username);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see org.apache.cassandra.auth.IAuthenticator#protectedResources()\n     */\n    @Override\n    public Set<? extends IResource> protectedResources()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see org.apache.cassandra.auth.IAuthenticator#requireAuthentication()\n     */\n    @Override\n    public boolean requireAuthentication()\n    {\n        // TODO Auto-generated method stub\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see org.apache.cassandra.auth.IAuthenticator#setup()\n     */\n    @Override\n    public void setup()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    @Override\n    public AuthenticatedUser legacyAuthenticate(Map<String, String> arg0) throws AuthenticationException {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    public SaslNegotiator newSaslNegotiator() {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n\t@Override\n\tpublic SaslNegotiator newSaslNegotiator(InetAddress arg0) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/java/org/apache/cassandra/auth/SimpleAuthority.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage org.apache.cassandra.auth;\n\n/*\n * \n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n * \n *   http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n * \n */\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.apache.cassandra.exceptions.ConfigurationException;\nimport org.apache.cassandra.exceptions.RequestExecutionException;\nimport org.apache.cassandra.exceptions.RequestValidationException;\nimport org.apache.cassandra.io.util.FileUtils;\n\n// TODO: Auto-generated Javadoc\n/**\n * The Class SimpleAuthority.\n */\npublic class SimpleAuthority implements IAuthorizer {\n\n    /** The Constant ACCESS_FILENAME_PROPERTY. */\n    public final static String ACCESS_FILENAME_PROPERTY = \"access.properties\";\n\n    // magical property for WRITE permissions to the keyspaces list\n    /** The Constant KEYSPACES_WRITE_PROPERTY. */\n    public final static String KEYSPACES_WRITE_PROPERTY = \"<modify-keyspaces>\";\n\n    /**\n     * Authorize.\n     * \n     * @param user\n     *            the user\n     * @param resource\n     *            the resource\n     * @return the enum set\n     */\n    public EnumSet<Permission> authorize(AuthenticatedUser user, List<Object> resource) {\n        if (resource.size() < 2 || !Resources.ROOT.equals(resource.get(0))\n            || !Resources.KEYSPACES.equals(resource.get(1)))\n            return (EnumSet<Permission>) Permission.NONE;\n\n        String keyspace, columnFamily = null;\n        EnumSet<Permission> authorized = (EnumSet<Permission>) Permission.NONE;\n\n        // /cassandra/keyspaces\n        if (resource.size() == 2) {\n            keyspace = KEYSPACES_WRITE_PROPERTY;\n            authorized = EnumSet.of(Permission.READ);\n        }\n        // /cassandra/keyspaces/<keyspace name>\n        else if (resource.size() == 3) {\n            keyspace = (String) resource.get(2);\n        }\n        // /cassandra/keyspaces/<keyspace name>/<cf name>\n        else if (resource.size() == 4) {\n            keyspace = (String) resource.get(2);\n            columnFamily = (String) resource.get(3);\n        } else {\n            // We don't currently descend any lower in the hierarchy.\n            throw new UnsupportedOperationException();\n        }\n\n        String accessFilename = System.getProperty(ACCESS_FILENAME_PROPERTY);\n        InputStream in = null;\n        try {\n            in = Thread.currentThread().getContextClassLoader().getResourceAsStream(\"access.properties\");\n            // in = new BufferedInputStream(new\n            // FileInputStream(accessFilename));\n            Properties accessProperties = new Properties();\n            accessProperties.load(in);\n\n            // Special case access to the keyspace list\n            if (keyspace == KEYSPACES_WRITE_PROPERTY) {\n                String kspAdmins = accessProperties.getProperty(KEYSPACES_WRITE_PROPERTY);\n                for (String admin : kspAdmins.split(\",\"))\n                    if (admin.equals(user.getName()))\n                        return (EnumSet<Permission>) Permission.ALL;\n            }\n\n            boolean canRead = false, canWrite = false;\n            String readers = null, writers = null;\n\n            if (columnFamily == null) {\n                readers = accessProperties.getProperty(keyspace + \".<ro>\");\n                writers = accessProperties.getProperty(keyspace + \".<rw>\");\n            } else {\n                readers = accessProperties.getProperty(keyspace + \".\" + columnFamily + \".<ro>\");\n                writers = accessProperties.getProperty(keyspace + \".\" + columnFamily + \".<rw>\");\n            }\n\n            if (readers != null) {\n                for (String reader : readers.split(\",\")) {\n                    if (reader.equals(user.getName())) {\n                        canRead = true;\n                        break;\n                    }\n                }\n            }\n\n            if (writers != null) {\n                for (String writer : writers.split(\",\")) {\n                    if (writer.equals(user.getName())) {\n                        canWrite = true;\n                        break;\n                    }\n                }\n            }\n\n            if (canWrite)\n                authorized = (EnumSet<Permission>) Permission.ALL;\n            else if (canRead)\n                authorized = EnumSet.of(Permission.READ);\n\n        } catch (IOException e) {\n            throw new RuntimeException(String.format(\"Authorization table file '%s' could not be opened: %s\",\n                accessFilename, e.getMessage()));\n        } finally {\n            FileUtils.closeQuietly(in);\n        }\n\n        return authorized;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see org.apache.cassandra.auth.IAuthorizer#validateConfiguration()\n     */\n    public void validateConfiguration() throws ConfigurationException {\n        String afilename = System.getProperty(ACCESS_FILENAME_PROPERTY);\n        if (afilename == null) {\n            throw new ConfigurationException(String.format(\"When using %s, '%s' property must be defined.\", this\n                .getClass().getCanonicalName(), ACCESS_FILENAME_PROPERTY));\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see org.apache.cassandra.auth.IAuthorizer#authorize(org.apache.cassandra. auth.AuthenticatedUser,\n     * org.apache.cassandra.auth.IResource)\n     */\n    @Override\n    public Set<Permission> authorize(AuthenticatedUser arg0, IResource arg1) {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see org.apache.cassandra.auth.IAuthorizer#protectedResources()\n     */\n    @Override\n    public Set<? extends IResource> protectedResources() {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see org.apache.cassandra.auth.IAuthorizer#setup()\n     */\n    @Override\n    public void setup() {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see org.apache.cassandra.auth.IAuthorizer#grant(org.apache.cassandra.auth.AuthenticatedUser, java.util.Set,\n     * org.apache.cassandra.auth.IResource, org.apache.cassandra.auth.RoleResource)\n     */\n    @Override\n    public void grant(AuthenticatedUser arg0, Set<Permission> arg1, IResource arg2, RoleResource arg3)\n        throws RequestValidationException, RequestExecutionException {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see org.apache.cassandra.auth.IAuthorizer#list(org.apache.cassandra.auth.AuthenticatedUser, java.util.Set,\n     * org.apache.cassandra.auth.IResource, org.apache.cassandra.auth.RoleResource)\n     */\n    @Override\n    public Set<PermissionDetails> list(AuthenticatedUser arg0, Set<Permission> arg1, IResource arg2, RoleResource arg3)\n        throws RequestValidationException, RequestExecutionException {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see org.apache.cassandra.auth.IAuthorizer#revoke(org.apache.cassandra.auth.AuthenticatedUser, java.util.Set,\n     * org.apache.cassandra.auth.IResource, org.apache.cassandra.auth.RoleResource)\n     */\n    @Override\n    public void revoke(AuthenticatedUser arg0, Set<Permission> arg1, IResource arg2, RoleResource arg3)\n        throws RequestValidationException, RequestExecutionException {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see org.apache.cassandra.auth.IAuthorizer#revokeAllFrom(org.apache.cassandra.auth.RoleResource)\n     */\n    @Override\n    public void revokeAllFrom(RoleResource arg0) {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see org.apache.cassandra.auth.IAuthorizer#revokeAllOn(org.apache.cassandra.auth.IResource)\n     */\n    @Override\n    public void revokeAllOn(IResource arg0) {\n        // TODO Auto-generated method stub\n\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/resources/META-INF/persistence.xml",
    "content": "\n<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\t\n\t<persistence-unit name=\"entitylisteners_pu\">\n        <provider>com.impetus.kundera.KunderaPersistence</provider>\n        <class>com.impetus.kundera.client.crud.entitylisteners.Person</class>\n        <exclude-unlisted-classes>true</exclude-unlisted-classes>     \n        <properties>            \n            <property name=\"kundera.nodes\" value=\"localhost\"/>\n            <property name=\"kundera.port\" value=\"9160\"/>\n            <property name=\"kundera.keyspace\" value=\"EntityListenersTest\"/>\n            <property name=\"kundera.dialect\" value=\"cassandra\"/>\n            <property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n            <property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />         \n        </properties>       \n    </persistence-unit>\n\n\t<persistence-unit name=\"secIdxCassandraTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<!-- <property name=\"kundera.ddl.auto.prepare\" value=\"create\" /> -->\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"genericCassandraTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.crud.PersonCassandra</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<!-- <property name=\"kundera.ddl.auto.prepare\" value=\"create\" /> -->\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"CassandraScalarQueriesTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<!-- test without entity definition -->\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"cassandra_udt\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.cassandra.udt.Address</class>\n\t\t<class>com.impetus.client.cassandra.udt.Fullname</class>\n\t\t<class>com.impetus.client.cassandra.udt.PersonalDetailsUDT</class>\n\t\t<class>com.impetus.client.cassandra.udt.PersonUDT</class>\n\t\t<class>com.impetus.client.cassandra.udt.ProfessionalDetailsUDT</class>\n\t\t<class>com.impetus.client.cassandra.udt.Spouse</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"UdtTest\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"luceneCassandraTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.crud.PersonLuceneCassandra</class>\n\t\t<class>com.impetus.client.crud.PersonLuceneCassandraUUID</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<property name=\"index.home.dir\" value=\"lucene\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaLoadbalancingTest.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\n\t<persistence-unit name=\"twissandraTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<jar-file></jar-file>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"CassandraCounterTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaCounterColumn\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\n\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"authenticationTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaAuthentication\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<!-- <property name=\"kundera.ddl.auto.prepare\" value=\"create\" /> -->\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<property name=\"kundera.username\" value=\"kunderauser\" />\n\t\t\t<property name=\"kundera.password\" value=\"kunderapassword\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"invalidauthenticationTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaAuthentication\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<!-- <property name=\"kundera.ddl.auto.prepare\" value=\"create\" /> -->\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<property name=\"kundera.username\" value=\"kunderauser\" />\n\t\t\t<property name=\"kundera.password\" value=\"kunderapassword\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"thriftClientTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<!-- <property name=\"kundera.ddl.auto.prepare\" value=\"create\" /> -->\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"CassandraDataTypeTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaCassandraDataType\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\n\t<persistence-unit name=\"secIdxBatchTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<!-- <property name=\"kundera.ddl.auto.prepare\" value=\"create\"/> -->\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<property name=\"kundera.batch.size\" value=\"5\" />\n\t\t</properties>\n\n\t</persistence-unit>\n\n\t<persistence-unit name=\"batchTestSizeTwenty\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<!-- <property name=\"kundera.ddl.auto.prepare\" value=\"create\"/> -->\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<property name=\"kundera.batch.size\" value=\"20\" />\n\t\t</properties>\n\n\t</persistence-unit>\n\n\t<persistence-unit name=\"CassandraXmlPropertyTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaCassandraXmlTest\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"composite_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.crud.compositeType.CassandraPrimeUser</class>\n\t\t<class>com.impetus.client.cassandra.thrift.Phone</class>\n\t\t<class>com.impetus.client.cassandra.thrift.PersonIdentity</class>\n\t\t<class>com.impetus.client.crud.compositeType.association.UserInfo</class>\n\t\t<class>com.impetus.client.crud.compositeType.CassandraEmbeddedAssociation</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"CompositeCassandra\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client\" value=\"pelops\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"/home/impadmin/lucene\" /> -->\n\t\t\t<!-- <property name=\"kundera.batch.size\" value=\"500\" /> -->\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaConnectionTest.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"compositedatatype\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"CompositeCassandra\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client\" value=\"pelops\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTestDataType.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"cassandra_generated_id\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"kunderaGeneratedId\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client\" value=\"pelops\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTestDataType.xml\" />\n<!-- \t\t\t<property name=\"kundera.auto.generator.class\" value=\"com.impetus.client.generatedId.CustomIdGenerator\" /> -->\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"myapp_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.crud.PersonCassandra</class>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"myapp\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"cassandra_cql\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"CqlKeyspace\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t\t<!-- <property name=\"kundera.show.query\" value=\"true\" /> -->\n\t\t\t<property name=\"kundera.client\" value=\"thrift\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"load-balancing-test\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"Cassandra\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client\" value=\"thrift\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaLoadbalancingTest.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"esIndexerTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.esindexer.PersonESIndexerCassandra</class>\n\t\t<class>com.impetus.client.esindexer.PersonESIndexerCassandraUUID</class>\n\t\t<class>com.impetus.kundera.query.Person</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<property name=\"kundera.indexer.class\" value=\"com.impetus.client.es.index.ESIndexer\" />\n\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"cassandra_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.client\" value=\"thrift\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"cassandra_pool\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.pool.size.max.active\" value=\"200\" />\n\t\t\t<property name=\"kundera.pool.size.max.idle\" value=\"200\" />\n\t\t\t<property name=\"kundera.pool.size.min.idle\" value=\"20\" />\n\t\t\t<property name=\"kundera.nodes\" value=\"127.0.0.1\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"cassandra\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.schemamanager.entites.CassandraEntityPersonnelUniMToM</class>\n\t\t<class>com.impetus.client.schemamanager.entites.CassandraEntityHabitatUniMToM</class>\n\t\t<class>com.impetus.client.persistence.CassandraEntity</class>\n\t\t<class>com.impetus.client.persistence.CassandraEntitySample</class>\n\t\t<class>com.impetus.client.persistence.CassandraBatchEntity</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.client\" value=\"pelops\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"CassandraSchemaManager\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.schemamanager.entites.Actor</class>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"CassandraSchemaManagerTest\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.client\" value=\"thrift\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"cassandraProperties\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaCounterColumn\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.client\" value=\"thrift\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"CassandraSchemaOperationTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.schemamanager.entites.CassandraEntitySimple</class>\n<!-- \t\t<class>com.impetus.client.schemamanager.entites.Actor</class> -->\n\t\t<class>com.impetus.client.schemamanager.entites.TwitterUser</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaCoreExmples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.client\" value=\"thrift\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"CassandraShowQueryEnabledPu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.cassandra.thrift.cql.UserInformation</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"showQueryKeyspace\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.show.query\" value=\"true\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"CassandraShowQueryDisabledPu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.cassandra.thrift.cql.UserInformation</class>\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileHandset</class>\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileManufacturer</class>\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileOperatingSystem</class>\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.Person</class>\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.PersonChild</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"showQueryKeyspace\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"partialPropertyOverridePU\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.cassandra.thrift.cql.UserInformation</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\n\n</persistence>"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/resources/META-INF/persistence_2_0.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!-- persistence.xml schema -->\r\n<xsd:schema targetNamespace=\"http://java.sun.com/xml/ns/persistence\" \r\n  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\r\n  xmlns:persistence=\"http://java.sun.com/xml/ns/persistence\"\r\n  elementFormDefault=\"qualified\" \r\n  attributeFormDefault=\"unqualified\" \r\n  version=\"2.0\">\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n      @(#)persistence_2_0.xsd  1.0  October 1 2009\r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n\r\n  Copyright (c) 2008, 2009 Sun Microsystems. All rights reserved. \r\n  \r\n  This program and the accompanying materials are made available under the \r\n  terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 \r\n  which accompanies this distribution. \r\n  The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html\r\n  and the Eclipse Distribution License is available at \r\n  http://www.eclipse.org/org/documents/edl-v10.php.\r\n  \r\n  Contributors:\r\n      Linda DeMichiel - Java Persistence 2.0, Version 2.0 (October 1, 2009)\r\n      Specification available from http://jcp.org/en/jsr/detail?id=317\r\n \r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n   <xsd:annotation>\r\n     <xsd:documentation><![CDATA[\r\n\r\n     This is the XML Schema for the persistence configuration file.\r\n     The file must be named \"META-INF/persistence.xml\" in the \r\n     persistence archive.\r\n\r\n     Persistence configuration files must indicate\r\n     the persistence schema by using the persistence namespace:\r\n\r\n     http://java.sun.com/xml/ns/persistence\r\n\r\n     and indicate the version of the schema by\r\n     using the version element as shown below:\r\n\r\n      <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n        xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n          http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\"\r\n        version=\"2.0\">\r\n          ...\r\n      </persistence>\r\n\r\n    ]]></xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:simpleType name=\"versionType\">\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:pattern value=\"[0-9]+(\\.[0-9]+)*\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:element name=\"persistence\">\r\n    <xsd:complexType>\r\n      <xsd:sequence>\r\n\r\n        <!-- **************************************************** -->\r\n\r\n        <xsd:element name=\"persistence-unit\" \r\n                     minOccurs=\"1\" maxOccurs=\"unbounded\">\r\n          <xsd:complexType>\r\n            <xsd:annotation>\r\n              <xsd:documentation>\r\n\r\n                Configuration of a persistence unit.\r\n\r\n              </xsd:documentation>\r\n            </xsd:annotation>\r\n            <xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"description\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Description of this persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"provider\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Provider class that supplies EntityManagers for this \r\n                    persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of the JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"non-jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of a non-JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"mapping-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    File containing mapping information. Loaded as a resource \r\n                    by the persistence provider.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jar-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Jar file that is to be scanned for managed classes. \r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"class\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Managed class to be included in the persistence unit and\r\n                    to scan for annotations.  It should be annotated \r\n                    with either @Entity, @Embeddable or @MappedSuperclass.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"exclude-unlisted-classes\" type=\"xsd:boolean\" \r\n                           default=\"true\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    When set to true then only listed classes and jars will \r\n                    be scanned for persistent classes, otherwise the \r\n                    enclosing jar or directory will also be scanned. \r\n                    Not applicable to Java SE persistence units.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"shared-cache-mode\" \r\n                           type=\"persistence:persistence-unit-caching-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Defines whether caching is enabled for the \r\n                    persistence unit if caching is supported by the\r\n                    persistence provider. When set to ALL, all entities \r\n                    will be cached. When set to NONE, no entities will\r\n                    be cached. When set to ENABLE_SELECTIVE, only entities\r\n                    specified as cacheable will be cached. When set to\r\n                    DISABLE_SELECTIVE, entities specified as not cacheable\r\n                    will not be cached. When not specified or when set to\r\n                    UNSPECIFIED, provider defaults may apply.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"validation-mode\" \r\n                           type=\"persistence:persistence-unit-validation-mode-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The validation mode to be used for the persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"properties\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    A list of standard and vendor-specific properties \r\n                    and hints.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n                <xsd:complexType>\r\n                  <xsd:sequence>\r\n                    <xsd:element name=\"property\" \r\n                                 minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                      <xsd:annotation>\r\n                        <xsd:documentation>\r\n                          A name-value pair.\r\n                        </xsd:documentation>\r\n                      </xsd:annotation>\r\n                      <xsd:complexType>\r\n                        <xsd:attribute name=\"name\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                        <xsd:attribute name=\"value\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                      </xsd:complexType>\r\n                    </xsd:element>\r\n                  </xsd:sequence>\r\n                </xsd:complexType>\r\n              </xsd:element>\r\n\r\n            </xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Name used in code to reference this persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"transaction-type\" \r\n                           type=\"persistence:persistence-unit-transaction-type\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Type of transactions used by EntityManagers from this \r\n                  persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n          </xsd:complexType>\r\n        </xsd:element>\r\n      </xsd:sequence>\r\n      <xsd:attribute name=\"version\" type=\"persistence:versionType\" \r\n                     fixed=\"2.0\" use=\"required\"/>\r\n    </xsd:complexType>\r\n  </xsd:element>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-transaction-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum PersistenceUnitTransactionType {JTA, RESOURCE_LOCAL};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"JTA\"/>\r\n      <xsd:enumeration value=\"RESOURCE_LOCAL\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-caching-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum SharedCacheMode { ALL, NONE, ENABLE_SELECTIVE, DISABLE_SELECTIVE, UNSPECIFIED};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"ALL\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n      <xsd:enumeration value=\"ENABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"DISABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"UNSPECIFIED\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-validation-mode-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum ValidationMode { AUTO, CALLBACK, NONE};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"AUTO\"/>\r\n      <xsd:enumeration value=\"CALLBACK\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n</xsd:schema>\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/resources/access.properties",
    "content": "<modify-keyspaces>=kunderauser\nKunderaAuthentication.<rw>=kunderauser\nKunderaAuthentication.PERSON.<rw>=kunderauser\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/resources/cassandra.yaml",
    "content": "# Cassandra storage config YAML \n\n# NOTE:\n#   See http://wiki.apache.org/cassandra/StorageConfiguration for\n#   full explanations of configuration directives\n# /NOTE\n\n# The name of the cluster. This is mainly used to prevent machines in\n# one logical cluster from joining another.\ncluster_name: 'Test Cluster'\n\n# This defines the number of tokens randomly assigned to this node on the ring\n# The more tokens, relative to other nodes, the larger the proportion of data\n# that this node will store. You probably want all nodes to have the same number\n# of tokens assuming they have equal hardware capability.\n#\n# If you leave this unspecified, Cassandra will use the default of 1 token for legacy compatibility,\n# and will use the initial_token as described below.\n#\n# Specifying initial_token will override this setting on the node's initial start,\n# on subsequent starts, this setting will apply even if initial token is set.\n#\n# If you already have a cluster with 1 token per node, and wish to migrate to \n# multiple tokens per node, see http://wiki.apache.org/cassandra/Operations\nnum_tokens: 256\n\n# initial_token allows you to specify tokens manually.  While you can use # it with\n# vnodes (num_tokens > 1, above) -- in which case you should provide a \n# comma-separated list -- it's primarily used when adding nodes # to legacy clusters \n# that do not have vnodes enabled.\n# initial_token:\n\n# See http://wiki.apache.org/cassandra/HintedHandoff\n# May either be \"true\" or \"false\" to enable globally, or contain a list\n# of data centers to enable per-datacenter.\n# hinted_handoff_enabled: DC1,DC2\nhinted_handoff_enabled: true\n# this defines the maximum amount of time a dead host will have hints\n# generated.  After it has been dead this long, new hints for it will not be\n# created until it has been seen alive and gone down again.\nmax_hint_window_in_ms: 10800000 # 3 hours\n# Maximum throttle in KBs per second, per delivery thread.  This will be\n# reduced proportionally to the number of nodes in the cluster.  (If there\n# are two nodes in the cluster, each delivery thread will use the maximum\n# rate; if there are three, each will throttle to half of the maximum,\n# since we expect two nodes to be delivering hints simultaneously.)\nhinted_handoff_throttle_in_kb: 1024\n# Number of threads with which to deliver hints;\n# Consider increasing this number when you have multi-dc deployments, since\n# cross-dc handoff tends to be slower\nmax_hints_delivery_threads: 2\n\n# Maximum throttle in KBs per second, total. This will be\n# reduced proportionally to the number of nodes in the cluster.\nbatchlog_replay_throttle_in_kb: 1024\n\n# Authentication backend, implementing IAuthenticator; used to identify users\n# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthenticator,\n# PasswordAuthenticator}.\n#\n# - AllowAllAuthenticator performs no checks - set it to disable authentication.\n# - PasswordAuthenticator relies on username/password pairs to authenticate\n#   users. It keeps usernames and hashed passwords in system_auth.credentials table.\n#   Please increase system_auth keyspace replication factor if you use this authenticator.\nauthenticator: AllowAllAuthenticator\n\n# Authorization backend, implementing IAuthorizer; used to limit access/provide permissions\n# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthorizer,\n# CassandraAuthorizer}.\n#\n# - AllowAllAuthorizer allows any action to any user - set it to disable authorization.\n# - CassandraAuthorizer stores permissions in system_auth.permissions table. Please\n#   increase system_auth keyspace replication factor if you use this authorizer.\nauthorizer: AllowAllAuthorizer\n\n# Validity period for permissions cache (fetching permissions can be an\n# expensive operation depending on the authorizer, CassandraAuthorizer is\n# one example). Defaults to 2000, set to 0 to disable.\n# Will be disabled automatically for AllowAllAuthorizer.\npermissions_validity_in_ms: 2000\n\n# The partitioner is responsible for distributing groups of rows (by\n# partition key) across nodes in the cluster.  You should leave this\n# alone for new clusters.  The partitioner can NOT be changed without\n# reloading all data, so when upgrading you should set this to the\n# same partitioner you were already using.\n#\n# Besides Murmur3Partitioner, partitioners included for backwards\n# compatibility include RandomPartitioner, ByteOrderedPartitioner, and\n# OrderPreservingPartitioner.\n#\npartitioner: org.apache.cassandra.dht.ByteOrderedPartitioner\n\n# Directories where Cassandra should store data on disk.  Cassandra\n# will spread data evenly across them, subject to the granularity of\n# the configured compaction strategy.\n# If not set, the default directory is $CASSANDRA_HOME/data/data.\n# data_file_directories:\n#     - /var/lib/cassandra/data\n\n# commit log.  when running on magnetic HDD, this should be a\n# separate spindle than the data directories.\n# If not set, the default directory is $CASSANDRA_HOME/data/commitlog.\n# commitlog_directory: /var/lib/cassandra/commitlog\n\n# policy for data disk failures:\n# die: shut down gossip and Thrift and kill the JVM for any fs errors or\n#      single-sstable errors, so the node can be replaced.\n# stop_paranoid: shut down gossip and Thrift even for single-sstable errors.\n# stop: shut down gossip and Thrift, leaving the node effectively dead, but\n#       can still be inspected via JMX.\n# best_effort: stop using the failed disk and respond to requests based on\n#              remaining available sstables.  This means you WILL see obsolete\n#              data at CL.ONE!\n# ignore: ignore fatal errors and let requests fail, as in pre-1.2 Cassandra\ndisk_failure_policy: stop\n\n# policy for commit disk failures:\n# die: shut down gossip and Thrift and kill the JVM, so the node can be replaced.\n# stop: shut down gossip and Thrift, leaving the node effectively dead, but\n#       can still be inspected via JMX.\n# stop_commit: shutdown the commit log, letting writes collect but\n#              continuing to service reads, as in pre-2.0.5 Cassandra\n# ignore: ignore fatal errors and let the batches fail\ncommit_failure_policy: stop\n\n# Maximum size of the key cache in memory.\n#\n# Each key cache hit saves 1 seek and each row cache hit saves 2 seeks at the\n# minimum, sometimes more. The key cache is fairly tiny for the amount of\n# time it saves, so it's worthwhile to use it at large numbers.\n# The row cache saves even more time, but must contain the entire row,\n# so it is extremely space-intensive. It's best to only use the\n# row cache if you have hot rows or static rows.\n#\n# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.\n#\n# Default value is empty to make it \"auto\" (min(5% of Heap (in MB), 100MB)). Set to 0 to disable key cache.\nkey_cache_size_in_mb:\n\n# Duration in seconds after which Cassandra should\n# save the key cache. Caches are saved to saved_caches_directory as\n# specified in this configuration file.\n#\n# Saved caches greatly improve cold-start speeds, and is relatively cheap in\n# terms of I/O for the key cache. Row cache saving is much more expensive and\n# has limited use.\n#\n# Default is 14400 or 4 hours.\nkey_cache_save_period: 14400\n\n# Number of keys from the key cache to save\n# Disabled by default, meaning all keys are going to be saved\n# key_cache_keys_to_save: 100\n\n# Maximum size of the row cache in memory.\n# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.\n#\n# Default value is 0, to disable row caching.\nrow_cache_size_in_mb: 0\n\n# Duration in seconds after which Cassandra should\n# save the row cache. Caches are saved to saved_caches_directory as specified\n# in this configuration file.\n#\n# Saved caches greatly improve cold-start speeds, and is relatively cheap in\n# terms of I/O for the key cache. Row cache saving is much more expensive and\n# has limited use.\n#\n# Default is 0 to disable saving the row cache.\nrow_cache_save_period: 0\n\n# Number of keys from the row cache to save\n# Disabled by default, meaning all keys are going to be saved\n# row_cache_keys_to_save: 100\n\n# Maximum size of the counter cache in memory.\n#\n# Counter cache helps to reduce counter locks' contention for hot counter cells.\n# In case of RF = 1 a counter cache hit will cause Cassandra to skip the read before\n# write entirely. With RF > 1 a counter cache hit will still help to reduce the duration\n# of the lock hold, helping with hot counter cell updates, but will not allow skipping\n# the read entirely. Only the local (clock, count) tuple of a counter cell is kept\n# in memory, not the whole counter, so it's relatively cheap.\n#\n# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.\n#\n# Default value is empty to make it \"auto\" (min(2.5% of Heap (in MB), 50MB)). Set to 0 to disable counter cache.\n# NOTE: if you perform counter deletes and rely on low gcgs, you should disable the counter cache.\ncounter_cache_size_in_mb:\n\n# Duration in seconds after which Cassandra should\n# save the counter cache (keys only). Caches are saved to saved_caches_directory as\n# specified in this configuration file.\n#\n# Default is 7200 or 2 hours.\ncounter_cache_save_period: 7200\n\n# Number of keys from the counter cache to save\n# Disabled by default, meaning all keys are going to be saved\n# counter_cache_keys_to_save: 100\n\n# The off-heap memory allocator.  Affects storage engine metadata as\n# well as caches.  Experiments show that JEMAlloc saves some memory\n# than the native GCC allocator (i.e., JEMalloc is more\n# fragmentation-resistant).\n# \n# Supported values are: NativeAllocator, JEMallocAllocator\n#\n# If you intend to use JEMallocAllocator you have to install JEMalloc as library and\n# modify cassandra-env.sh as directed in the file.\n#\n# Defaults to NativeAllocator\n# memory_allocator: NativeAllocator\n\n# saved caches\n# If not set, the default directory is $CASSANDRA_HOME/data/saved_caches.\n# saved_caches_directory: /var/lib/cassandra/saved_caches\n\n# commitlog_sync may be either \"periodic\" or \"batch.\" \n# When in batch mode, Cassandra won't ack writes until the commit log\n# has been fsynced to disk.  It will wait up to\n# commitlog_sync_batch_window_in_ms milliseconds for other writes, before\n# performing the sync.\n#\n# commitlog_sync: batch\n# commitlog_sync_batch_window_in_ms: 50\n#\n# the other option is \"periodic\" where writes may be acked immediately\n# and the CommitLog is simply synced every commitlog_sync_period_in_ms\n# milliseconds.  commitlog_periodic_queue_size allows 1024*(CPU cores) pending\n# entries on the commitlog queue by default.  If you are writing very large\n# blobs, you should reduce that; 16*cores works reasonably well for 1MB blobs.\n# It should be at least as large as the concurrent_writes setting.\ncommitlog_sync: periodic\ncommitlog_sync_period_in_ms: 10000\n# commitlog_periodic_queue_size:\n\n# The size of the individual commitlog file segments.  A commitlog\n# segment may be archived, deleted, or recycled once all the data\n# in it (potentially from each columnfamily in the system) has been\n# flushed to sstables.  \n#\n# The default size is 32, which is almost always fine, but if you are\n# archiving commitlog segments (see commitlog_archiving.properties),\n# then you probably want a finer granularity of archiving; 8 or 16 MB\n# is reasonable.\ncommitlog_segment_size_in_mb: 32\n\n# any class that implements the SeedProvider interface and has a\n# constructor that takes a Map<String, String> of parameters will do.\nseed_provider:\n    # Addresses of hosts that are deemed contact points. \n    # Cassandra nodes use this list of hosts to find each other and learn\n    # the topology of the ring.  You must change this if you are running\n    # multiple nodes!\n    - class_name: org.apache.cassandra.locator.SimpleSeedProvider\n      parameters:\n          # seeds is actually a comma-delimited list of addresses.\n          # Ex: \"<ip1>,<ip2>,<ip3>\"\n          - seeds: \"127.0.0.1\"\n\n# For workloads with more data than can fit in memory, Cassandra's\n# bottleneck will be reads that need to fetch data from\n# disk. \"concurrent_reads\" should be set to (16 * number_of_drives) in\n# order to allow the operations to enqueue low enough in the stack\n# that the OS and drives can reorder them. Same applies to\n# \"concurrent_counter_writes\", since counter writes read the current\n# values before incrementing and writing them back.\n#\n# On the other hand, since writes are almost never IO bound, the ideal\n# number of \"concurrent_writes\" is dependent on the number of cores in\n# your system; (8 * number_of_cores) is a good rule of thumb.\nconcurrent_reads: 32\nconcurrent_writes: 32\nconcurrent_counter_writes: 32\n\n# Total memory to use for sstable-reading buffers.  Defaults to\n# the smaller of 1/4 of heap or 512MB.\n# file_cache_size_in_mb: 512\n\n# Total permitted memory to use for memtables. Cassandra will stop \n# accepting writes when the limit is exceeded until a flush completes,\n# and will trigger a flush based on memtable_cleanup_threshold\n# If omitted, Cassandra will set both to 1/4 the size of the heap.\n# memtable_heap_space_in_mb: 2048\n# memtable_offheap_space_in_mb: 2048\n\n# Ratio of occupied non-flushing memtable size to total permitted size\n# that will trigger a flush of the largest memtable.  Lager mct will\n# mean larger flushes and hence less compaction, but also less concurrent\n# flush activity which can make it difficult to keep your disks fed\n# under heavy write load.\n#\n# memtable_cleanup_threshold defaults to 1 / (memtable_flush_writers + 1)\n# memtable_cleanup_threshold: 0.11\n\n# Specify the way Cassandra allocates and manages memtable memory.\n# Options are:\n#   heap_buffers:    on heap nio buffers\n#   offheap_buffers: off heap (direct) nio buffers\n#   offheap_objects: native memory, eliminating nio buffer heap overhead\nmemtable_allocation_type: heap_buffers\n\n# Total space to use for commitlogs.  Since commitlog segments are\n# mmapped, and hence use up address space, the default size is 32\n# on 32-bit JVMs, and 8192 on 64-bit JVMs.\n#\n# If space gets above this value (it will round up to the next nearest\n# segment multiple), Cassandra will flush every dirty CF in the oldest\n# segment and remove it.  So a small total commitlog space will tend\n# to cause more flush activity on less-active columnfamilies.\n# commitlog_total_space_in_mb: 8192\n\n# This sets the amount of memtable flush writer threads.  These will\n# be blocked by disk io, and each one will hold a memtable in memory\n# while blocked. \n#\n# memtable_flush_writers defaults to the smaller of (number of disks,\n# number of cores), with a minimum of 2 and a maximum of 8.\n# \n# If your data directories are backed by SSD, you should increase this\n# to the number of cores.\n#memtable_flush_writers: 8\n\n# A fixed memory pool size in MB for for SSTable index summaries. If left\n# empty, this will default to 5% of the heap size. If the memory usage of\n# all index summaries exceeds this limit, SSTables with low read rates will\n# shrink their index summaries in order to meet this limit.  However, this\n# is a best-effort process. In extreme conditions Cassandra may need to use\n# more than this amount of memory.\nindex_summary_capacity_in_mb:\n\n# How frequently index summaries should be resampled.  This is done\n# periodically to redistribute memory from the fixed-size pool to sstables\n# proportional their recent read rates.  Setting to -1 will disable this\n# process, leaving existing index summaries at their current sampling level.\nindex_summary_resize_interval_in_minutes: 60\n\n# Whether to, when doing sequential writing, fsync() at intervals in\n# order to force the operating system to flush the dirty\n# buffers. Enable this to avoid sudden dirty buffer flushing from\n# impacting read latencies. Almost always a good idea on SSDs; not\n# necessarily on platters.\ntrickle_fsync: false\ntrickle_fsync_interval_in_kb: 10240\n\n# TCP port, for commands and data\nstorage_port: 7000\n\n# SSL port, for encrypted communication.  Unused unless enabled in\n# encryption_options\nssl_storage_port: 7001\n\n# Address or interface to bind to and tell other Cassandra nodes to connect to.\n# You _must_ change this if you want multiple nodes to be able to communicate!\n#\n# Set listen_address OR listen_interface, not both. Interfaces must correspond\n# to a single address, IP aliasing is not supported.\n#\n# Leaving it blank leaves it up to InetAddress.getLocalHost(). This\n# will always do the Right Thing _if_ the node is properly configured\n# (hostname, name resolution, etc), and the Right Thing is to use the\n# address associated with the hostname (it might not be).\n#\n# Setting listen_address to 0.0.0.0 is always wrong.\nlisten_address: localhost\n# listen_interface: eth0\n\n# Address to broadcast to other Cassandra nodes\n# Leaving this blank will set it to the same value as listen_address\n# broadcast_address: 1.2.3.4\n\n# Internode authentication backend, implementing IInternodeAuthenticator;\n# used to allow/disallow connections from peer nodes.\n# internode_authenticator: org.apache.cassandra.auth.AllowAllInternodeAuthenticator\n\n# Whether to start the native transport server.\n# Please note that the address on which the native transport is bound is the\n# same as the rpc_address. The port however is different and specified below.\nstart_native_transport: true\n# port for the CQL native transport to listen for clients on\nnative_transport_port: 9042\n# The maximum threads for handling requests when the native transport is used.\n# This is similar to rpc_max_threads though the default differs slightly (and\n# there is no native_transport_min_threads, idle threads will always be stopped\n# after 30 seconds).\n# native_transport_max_threads: 128\n#\n# The maximum size of allowed frame. Frame (requests) larger than this will\n# be rejected as invalid. The default is 256MB.\n# native_transport_max_frame_size_in_mb: 256\n\n# Whether to start the thrift rpc server.\nstart_rpc: true\n\n# The address or interface to bind the Thrift RPC service and native transport\n# server to.\n#\n# Set rpc_address OR rpc_interface, not both. Interfaces must correspond\n# to a single address, IP aliasing is not supported.\n#\n# Leaving rpc_address blank has the same effect as on listen_address\n# (i.e. it will be based on the configured hostname of the node).\n#\n# Note that unlike listen_address, you can specify 0.0.0.0, but you must also\n# set broadcast_rpc_address to a value other than 0.0.0.0.\nrpc_address: localhost\n# rpc_interface: eth1\n\n# port for Thrift to listen for clients on\nrpc_port: 9160\n\n# RPC address to broadcast to drivers and other Cassandra nodes. This cannot\n# be set to 0.0.0.0. If left blank, this will be set to the value of\n# rpc_address. If rpc_address is set to 0.0.0.0, broadcast_rpc_address must\n# be set.\n# broadcast_rpc_address: 1.2.3.4\n\n# enable or disable keepalive on rpc/native connections\nrpc_keepalive: true\n\n# Cassandra provides two out-of-the-box options for the RPC Server:\n#\n# sync  -> One thread per thrift connection. For a very large number of clients, memory\n#          will be your limiting factor. On a 64 bit JVM, 180KB is the minimum stack size\n#          per thread, and that will correspond to your use of virtual memory (but physical memory\n#          may be limited depending on use of stack space).\n#\n# hsha  -> Stands for \"half synchronous, half asynchronous.\" All thrift clients are handled\n#          asynchronously using a small number of threads that does not vary with the amount\n#          of thrift clients (and thus scales well to many clients). The rpc requests are still\n#          synchronous (one thread per active request). If hsha is selected then it is essential\n#          that rpc_max_threads is changed from the default value of unlimited.\n#\n# The default is sync because on Windows hsha is about 30% slower.  On Linux,\n# sync/hsha performance is about the same, with hsha of course using less memory.\n#\n# Alternatively,  can provide your own RPC server by providing the fully-qualified class name\n# of an o.a.c.t.TServerFactory that can create an instance of it.\nrpc_server_type: sync\n\n# Uncomment rpc_min|max_thread to set request pool size limits.\n#\n# Regardless of your choice of RPC server (see above), the number of maximum requests in the\n# RPC thread pool dictates how many concurrent requests are possible (but if you are using the sync\n# RPC server, it also dictates the number of clients that can be connected at all).\n#\n# The default is unlimited and thus provides no protection against clients overwhelming the server. You are\n# encouraged to set a maximum that makes sense for you in production, but do keep in mind that\n# rpc_max_threads represents the maximum number of client requests this server may execute concurrently.\n#\n# rpc_min_threads: 16\n# rpc_max_threads: 2048\n\n# uncomment to set socket buffer sizes on rpc connections\n# rpc_send_buff_size_in_bytes:\n# rpc_recv_buff_size_in_bytes:\n\n# Uncomment to set socket buffer size for internode communication\n# Note that when setting this, the buffer size is limited by net.core.wmem_max\n# and when not setting it it is defined by net.ipv4.tcp_wmem\n# See:\n# /proc/sys/net/core/wmem_max\n# /proc/sys/net/core/rmem_max\n# /proc/sys/net/ipv4/tcp_wmem\n# /proc/sys/net/ipv4/tcp_wmem\n# and: man tcp\n# internode_send_buff_size_in_bytes:\n# internode_recv_buff_size_in_bytes:\n\n# Frame size for thrift (maximum message length).\nthrift_framed_transport_size_in_mb: 15\n\n# Set to true to have Cassandra create a hard link to each sstable\n# flushed or streamed locally in a backups/ subdirectory of the\n# keyspace data.  Removing these links is the operator's\n# responsibility.\nincremental_backups: false\n\n# Whether or not to take a snapshot before each compaction.  Be\n# careful using this option, since Cassandra won't clean up the\n# snapshots for you.  Mostly useful if you're paranoid when there\n# is a data format change.\nsnapshot_before_compaction: false\n\n# Whether or not a snapshot is taken of the data before keyspace truncation\n# or dropping of column families. The STRONGLY advised default of true \n# should be used to provide data safety. If you set this flag to false, you will\n# lose data on truncation or drop.\nauto_snapshot: true\n\n# When executing a scan, within or across a partition, we need to keep the\n# tombstones seen in memory so we can return them to the coordinator, which\n# will use them to make sure other replicas also know about the deleted rows.\n# With workloads that generate a lot of tombstones, this can cause performance\n# problems and even exaust the server heap.\n# (http://www.datastax.com/dev/blog/cassandra-anti-patterns-queues-and-queue-like-datasets)\n# Adjust the thresholds here if you understand the dangers and want to\n# scan more tombstones anyway.  These thresholds may also be adjusted at runtime\n# using the StorageService mbean.\ntombstone_warn_threshold: 1000\ntombstone_failure_threshold: 100000\n\n# Granularity of the collation index of rows within a partition.\n# Increase if your rows are large, or if you have a very large\n# number of rows per partition.  The competing goals are these:\n#   1) a smaller granularity means more index entries are generated\n#      and looking up rows withing the partition by collation column\n#      is faster\n#   2) but, Cassandra will keep the collation index in memory for hot\n#      rows (as part of the key cache), so a larger granularity means\n#      you can cache more hot rows\ncolumn_index_size_in_kb: 64\n\n\n# Log WARN on any batch size exceeding this value. 5kb per batch by default.\n# Caution should be taken on increasing the size of this threshold as it can lead to node instability.\nbatch_size_warn_threshold_in_kb: 5\n\n# Number of simultaneous compactions to allow, NOT including\n# validation \"compactions\" for anti-entropy repair.  Simultaneous\n# compactions can help preserve read performance in a mixed read/write\n# workload, by mitigating the tendency of small sstables to accumulate\n# during a single long running compactions. The default is usually\n# fine and if you experience problems with compaction running too\n# slowly or too fast, you should look at\n# compaction_throughput_mb_per_sec first.\n#\n# concurrent_compactors defaults to the smaller of (number of disks,\n# number of cores), with a minimum of 2 and a maximum of 8.\n# \n# If your data directories are backed by SSD, you should increase this\n# to the number of cores.\n#concurrent_compactors: 1\n\n# Throttles compaction to the given total throughput across the entire\n# system. The faster you insert data, the faster you need to compact in\n# order to keep the sstable count down, but in general, setting this to\n# 16 to 32 times the rate you are inserting data is more than sufficient.\n# Setting this to 0 disables throttling. Note that this account for all types\n# of compaction, including validation compaction.\ncompaction_throughput_mb_per_sec: 16\n\n# When compacting, the replacement sstable(s) can be opened before they\n# are completely written, and used in place of the prior sstables for\n# any range that has been written. This helps to smoothly transfer reads \n# between the sstables, reducing page cache churn and keeping hot rows hot\nsstable_preemptive_open_interval_in_mb: 50\n\n# Throttles all outbound streaming file transfers on this node to the\n# given total throughput in Mbps. This is necessary because Cassandra does\n# mostly sequential IO when streaming data during bootstrap or repair, which\n# can lead to saturating the network connection and degrading rpc performance.\n# When unset, the default is 200 Mbps or 25 MB/s.\n# stream_throughput_outbound_megabits_per_sec: 200\n\n# Throttles all streaming file transfer between the datacenters,\n# this setting allows users to throttle inter dc stream throughput in addition\n# to throttling all network stream traffic as configured with\n# stream_throughput_outbound_megabits_per_sec\n# inter_dc_stream_throughput_outbound_megabits_per_sec:\n\n# How long the coordinator should wait for read operations to complete\nread_request_timeout_in_ms: 5000\n# How long the coordinator should wait for seq or index scans to complete\nrange_request_timeout_in_ms: 10000\n# How long the coordinator should wait for writes to complete\nwrite_request_timeout_in_ms: 2000\n# How long the coordinator should wait for counter writes to complete\ncounter_write_request_timeout_in_ms: 5000\n# How long a coordinator should continue to retry a CAS operation\n# that contends with other proposals for the same row\ncas_contention_timeout_in_ms: 1000\n# How long the coordinator should wait for truncates to complete\n# (This can be much longer, because unless auto_snapshot is disabled\n# we need to flush first so we can snapshot before removing the data.)\ntruncate_request_timeout_in_ms: 60000\n# The default timeout for other, miscellaneous operations\nrequest_timeout_in_ms: 10000\n\n# Enable operation timeout information exchange between nodes to accurately\n# measure request timeouts.  If disabled, replicas will assume that requests\n# were forwarded to them instantly by the coordinator, which means that\n# under overload conditions we will waste that much extra time processing \n# already-timed-out requests.\n#\n# Warning: before enabling this property make sure to ntp is installed\n# and the times are synchronized between the nodes.\ncross_node_timeout: false\n\n# Enable socket timeout for streaming operation.\n# When a timeout occurs during streaming, streaming is retried from the start\n# of the current file. This _can_ involve re-streaming an important amount of\n# data, so you should avoid setting the value too low.\n# Default value is 0, which never timeout streams.\n# streaming_socket_timeout_in_ms: 0\n\n# phi value that must be reached for a host to be marked down.\n# most users should never need to adjust this.\n# phi_convict_threshold: 8\n\n# endpoint_snitch -- Set this to a class that implements\n# IEndpointSnitch.  The snitch has two functions:\n# - it teaches Cassandra enough about your network topology to route\n#   requests efficiently\n# - it allows Cassandra to spread replicas around your cluster to avoid\n#   correlated failures. It does this by grouping machines into\n#   \"datacenters\" and \"racks.\"  Cassandra will do its best not to have\n#   more than one replica on the same \"rack\" (which may not actually\n#   be a physical location)\n#\n# IF YOU CHANGE THE SNITCH AFTER DATA IS INSERTED INTO THE CLUSTER,\n# YOU MUST RUN A FULL REPAIR, SINCE THE SNITCH AFFECTS WHERE REPLICAS\n# ARE PLACED.\n#\n# Out of the box, Cassandra provides\n#  - SimpleSnitch:\n#    Treats Strategy order as proximity. This can improve cache\n#    locality when disabling read repair.  Only appropriate for\n#    single-datacenter deployments.\n#  - GossipingPropertyFileSnitch\n#    This should be your go-to snitch for production use.  The rack\n#    and datacenter for the local node are defined in\n#    cassandra-rackdc.properties and propagated to other nodes via\n#    gossip.  If cassandra-topology.properties exists, it is used as a\n#    fallback, allowing migration from the PropertyFileSnitch.\n#  - PropertyFileSnitch:\n#    Proximity is determined by rack and data center, which are\n#    explicitly configured in cassandra-topology.properties.\n#  - Ec2Snitch:\n#    Appropriate for EC2 deployments in a single Region. Loads Region\n#    and Availability Zone information from the EC2 API. The Region is\n#    treated as the datacenter, and the Availability Zone as the rack.\n#    Only private IPs are used, so this will not work across multiple\n#    Regions.\n#  - Ec2MultiRegionSnitch:\n#    Uses public IPs as broadcast_address to allow cross-region\n#    connectivity.  (Thus, you should set seed addresses to the public\n#    IP as well.) You will need to open the storage_port or\n#    ssl_storage_port on the public IP firewall.  (For intra-Region\n#    traffic, Cassandra will switch to the private IP after\n#    establishing a connection.)\n#  - RackInferringSnitch:\n#    Proximity is determined by rack and data center, which are\n#    assumed to correspond to the 3rd and 2nd octet of each node's IP\n#    address, respectively.  Unless this happens to match your\n#    deployment conventions, this is best used as an example of\n#    writing a custom Snitch class and is provided in that spirit.\n#\n# You can use a custom Snitch by setting this to the full class name\n# of the snitch, which will be assumed to be on your classpath.\nendpoint_snitch: SimpleSnitch\n\n# controls how often to perform the more expensive part of host score\n# calculation\ndynamic_snitch_update_interval_in_ms: 100 \n# controls how often to reset all host scores, allowing a bad host to\n# possibly recover\ndynamic_snitch_reset_interval_in_ms: 600000\n# if set greater than zero and read_repair_chance is < 1.0, this will allow\n# 'pinning' of replicas to hosts in order to increase cache capacity.\n# The badness threshold will control how much worse the pinned host has to be\n# before the dynamic snitch will prefer other replicas over it.  This is\n# expressed as a double which represents a percentage.  Thus, a value of\n# 0.2 means Cassandra would continue to prefer the static snitch values\n# until the pinned host was 20% worse than the fastest.\ndynamic_snitch_badness_threshold: 0.1\n\n# request_scheduler -- Set this to a class that implements\n# RequestScheduler, which will schedule incoming client requests\n# according to the specific policy. This is useful for multi-tenancy\n# with a single Cassandra cluster.\n# NOTE: This is specifically for requests from the client and does\n# not affect inter node communication.\n# org.apache.cassandra.scheduler.NoScheduler - No scheduling takes place\n# org.apache.cassandra.scheduler.RoundRobinScheduler - Round robin of\n# client requests to a node with a separate queue for each\n# request_scheduler_id. The scheduler is further customized by\n# request_scheduler_options as described below.\nrequest_scheduler: org.apache.cassandra.scheduler.NoScheduler\n\n# Scheduler Options vary based on the type of scheduler\n# NoScheduler - Has no options\n# RoundRobin\n#  - throttle_limit -- The throttle_limit is the number of in-flight\n#                      requests per client.  Requests beyond \n#                      that limit are queued up until\n#                      running requests can complete.\n#                      The value of 80 here is twice the number of\n#                      concurrent_reads + concurrent_writes.\n#  - default_weight -- default_weight is optional and allows for\n#                      overriding the default which is 1.\n#  - weights -- Weights are optional and will default to 1 or the\n#               overridden default_weight. The weight translates into how\n#               many requests are handled during each turn of the\n#               RoundRobin, based on the scheduler id.\n#\n# request_scheduler_options:\n#    throttle_limit: 80\n#    default_weight: 5\n#    weights:\n#      Keyspace1: 1\n#      Keyspace2: 5\n\n# request_scheduler_id -- An identifier based on which to perform\n# the request scheduling. Currently the only valid option is keyspace.\n# request_scheduler_id: keyspace\n\n# Enable or disable inter-node encryption\n# Default settings are TLS v1, RSA 1024-bit keys (it is imperative that\n# users generate their own keys) TLS_RSA_WITH_AES_128_CBC_SHA as the cipher\n# suite for authentication, key exchange and encryption of the actual data transfers.\n# Use the DHE/ECDHE ciphers if running in FIPS 140 compliant mode.\n# NOTE: No custom encryption options are enabled at the moment\n# The available internode options are : all, none, dc, rack\n#\n# If set to dc cassandra will encrypt the traffic between the DCs\n# If set to rack cassandra will encrypt the traffic between the racks\n#\n# The passwords used in these options must match the passwords used when generating\n# the keystore and truststore.  For instructions on generating these files, see:\n# http://download.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore\n#\nserver_encryption_options:\n    internode_encryption: none\n    keystore: conf/.keystore\n    keystore_password: cassandra\n    truststore: conf/.truststore\n    truststore_password: cassandra\n    # More advanced defaults below:\n    # protocol: TLS\n    # algorithm: SunX509\n    # store_type: JKS\n    # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]\n    # require_client_auth: false\n\n# enable or disable client/server encryption.\nclient_encryption_options:\n    enabled: false\n    keystore: conf/.keystore\n    keystore_password: cassandra\n    # require_client_auth: false\n    # Set trustore and truststore_password if require_client_auth is true\n    # truststore: conf/.truststore\n    # truststore_password: cassandra\n    # More advanced defaults below:\n    # protocol: TLS\n    # algorithm: SunX509\n    # store_type: JKS\n    # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]\n\n# internode_compression controls whether traffic between nodes is\n# compressed.\n# can be:  all  - all traffic is compressed\n#          dc   - traffic between different datacenters is compressed\n#          none - nothing is compressed.\ninternode_compression: all\n\n# Enable or disable tcp_nodelay for inter-dc communication.\n# Disabling it will result in larger (but fewer) network packets being sent,\n# reducing overhead from the TCP protocol itself, at the cost of increasing\n# latency if you block for cross-datacenter responses.\ninter_dc_tcp_nodelay: false\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/resources/ehcache-test.xml",
    "content": "<ehcache xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"ehcache.xsd\">\r\n\r\n\t<diskStore path=\"java.io.tmpdir\"/>\r\n\r\n\r\n\t<defaultCache maxElementsInMemory=\"10000\" eternal=\"false\" timeToIdleSeconds=\"120\"\r\n\t\ttimeToLiveSeconds=\"300\" overflowToDisk=\"true\" diskSpoolBufferSizeMB=\"30\"\r\n\t\tmaxElementsOnDisk=\"100000\" diskPersistent=\"false\" diskExpiryThreadIntervalSeconds=\"120\"\r\n\t\tmemoryStoreEvictionPolicy=\"LRU\" />\r\n\r\n\t<cache name=\"com.impetus.kundera.entity.Person\" maxElementsInMemory=\"10000\"\r\n\t\tmaxElementsOnDisk=\"1000\" eternal=\"false\" overflowToDisk=\"true\" diskSpoolBufferSizeMB=\"20\"\r\n\t\ttimeToIdleSeconds=\"300\" timeToLiveSeconds=\"600\" />\r\n\r\n\t<cache name=\"com.impetus.kundera.entity.Employee\" maxElementsInMemory=\"10000\"\r\n\t\tmaxElementsOnDisk=\"1000\" eternal=\"false\" overflowToDisk=\"true\" diskSpoolBufferSizeMB=\"20\"\r\n\t\ttimeToIdleSeconds=\"300\" timeToLiveSeconds=\"600\" />\r\n\r\n\t<cache name=\"com.impetus.kundera.entity.Department\" maxElementsInMemory=\"10000\"\r\n\t\tmaxElementsOnDisk=\"1000\" eternal=\"false\" overflowToDisk=\"true\" diskSpoolBufferSizeMB=\"20\"\r\n\t\ttimeToIdleSeconds=\"300\" timeToLiveSeconds=\"600\" />\r\n\r\n</ehcache>\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/resources/kundera-cassandra.properties",
    "content": "replication.factor=1\nstrategy.class=org.apache.cassandra.locator.SimpleStrategy\ncf.defs=counters|CounterColumnType|UTF8Type,SuperCounters|CounterColumnType|UTF8Type,InvalidCounterColumnEntity|CounterColumnType,ValidCounterColumnFamily|CounterColumnType\ninverted.indexing.enabled=true\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/resources/kunderaConnectionTest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>cassandra</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"testonborrow\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"testwhileidle\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"testonconnect\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"testonreturn\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"socket.timeout\" value=\"120000\"></property>\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/resources/kunderaLoadbalancingTest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>cassandra</name>\n\t\t\t<connection>\n<!-- \t\t\t\t<properties>\n\t\t\t\t\t<property name=\"cql.version\" value=\"3.0.0\" />\n\t\t\t\t\tLoad balancing specific configuration\n\t\t\t\t\t<property name=\"loadbalancing.policy\" value=\"roundrobin\" />\n\t\t\t\t\t<property name=\"retry\" value=\"true\" />\n\t\t\t\t\t<property name=\"retry.delay\" value=\"1\" />\n\t\t\t\t\t<property name=\"max.wait\" value=\"3000\" />\n\t\t\t\t</properties> -->\n\t\t\t\t<servers>\n\t\t\t\t\t<server>\n\t\t\t\t\t\t<host>\n\t\t\t\t\t\t\tlocalhost\n\t\t\t\t\t\t</host>\n\t\t\t\t\t\t<port>\n\t\t\t\t\t\t\t9160\n\t\t\t\t\t\t</port>\n\t\t\t\t\t</server>\n\t\t\t\t</servers>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/resources/log4j.properties",
    "content": "#log4j.rootLogger=INFO, DRFA, CONSOLE\r\nlog4j.logger.com.impetus=FATAL, CONSOLE, DRFA\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration>\n\n\t<!-- Send debug messages to System.out -->\n\t<appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n\t\t<!-- By default, encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder -->\n\t\t<encoder>\n\t\t\t<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n</pattern>\n\t\t</encoder>\n\t</appender>\n\n\t<!-- Send error messages to a file at \"${user.home}/kundera.log\" -->\n\t<appender name=\"FILE\" class=\"ch.qos.logback.core.rolling.RollingFileAppender\">\n\t\t<file>${user.home}/kundera.log</file>\n\t\t<encoder class=\"ch.qos.logback.classic.encoder.PatternLayoutEncoder\">\n\t\t\t<Pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern>\n\t\t</encoder>\n \n\t\t<rollingPolicy class=\"ch.qos.logback.core.rolling.FixedWindowRollingPolicy\">\n\t\t\t<FileNamePattern>${user.home}/kundera.%i.log.zip</FileNamePattern>\n\t\t\t<MinIndex>1</MinIndex>\n\t\t\t<MaxIndex>10</MaxIndex>\n\t\t</rollingPolicy>\n \n\t\t<triggeringPolicy class=\"ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy\">\n\t\t\t<MaxFileSize>2MB</MaxFileSize>\n\t\t</triggeringPolicy>\n\t</appender>\n\n\t<logger name=\"log4j.logger.com.impetus\" level=\"ERROR\" additivity=\"false\">\n            <appender-ref ref=\"STDOUT\" />\n            <appender-ref ref=\"FILE\" />\n\t</logger>\n\n\t<!-- By default, the level of the root level is set to DEBUG -->\n\t<root level=\"ERROR\">\n\t\t<appender-ref ref=\"STDOUT\" />\n\t</root>\n</configuration>"
  },
  {
    "path": "src/kundera-cassandra/cassandra-core/src/test/resources/passwd.properties",
    "content": "kunderauser=kunderapassword"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t<artifactId>kundera-cassandra-parent</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-cassandra-ds-driver</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-cassandra-ds-driver</name>\n\t<url>http://maven.apache.org</url>\n\n\t<!-- Dependencies -->\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.datastax.cassandra</groupId>\n\t\t\t<artifactId>cassandra-driver-core</artifactId>\n\t\t\t<version>3.3.0</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<!-- https://mvnrepository.com/artifact/cglib/cglib -->\n\t\t<dependency>\n\t\t\t<groupId>cglib</groupId>\n\t\t\t<artifactId>cglib</artifactId>\n\t\t\t<version>3.1</version>\n\t\t</dependency>\n\n\n\t</dependencies>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-clean-plugin</artifactId>\n\t\t\t\t<version>2.4.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<filesets>\n\t\t\t\t\t\t<fileset>\n\t\t\t\t\t\t\t<directory>${basedir}</directory>\n\t\t\t\t\t\t\t<excludes>\n\t\t\t\t\t\t\t\t<exclude>.git/**</exclude>\n\t\t\t\t\t\t\t\t<exclude>.gitignore</exclude>\n\t\t\t\t\t\t\t</excludes>\n\t\t\t\t\t\t\t<includes>\n\t\t\t\t\t\t\t\t<include>lucene/**</include>\n\t\t\t\t\t\t\t</includes>\n\t\t\t\t\t\t</fileset>\n\t\t\t\t\t</filesets>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n\n</project>\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/main/java/com/impetus/kundera/client/cassandra/dsdriver/DSCassQuery.java",
    "content": "package com.impetus.kundera.client.cassandra.dsdriver;\n\nimport java.util.Iterator;\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.client.cassandra.query.CassQuery;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * The Class DSCassQuery.\n * \n * @author karthikp.manchala\n */\npublic class DSCassQuery extends CassQuery\n{\n\n    /**\n     * Instantiates a new DS cass query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param persistenceDelegator\n     *            the persistence delegator\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public DSCassQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.query.CassQuery#iterate()\n     */\n    @Override\n    public Iterator iterate()\n    {\n        if (kunderaQuery.isNative())\n        {\n            throw new UnsupportedOperationException(\"Iteration not supported over native queries\");\n        }\n        EntityMetadata m = getEntityMetadata();\n        Client client = persistenceDelegeator.getClient(m);\n        externalProperties = ((CassandraClientBase) client).getExternalProperties();\n\n        if (!MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))\n        {\n            throw new UnsupportedOperationException(\"Scrolling over cassandra is unsupported for lucene queries\");\n        }\n\n        return new DSResultIterator(this, m, persistenceDelegeator.getClient(m), this.getReader(),\n                getFetchSize() != null ? getFetchSize() : this.maxResult, kunderaMetadata);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/main/java/com/impetus/kundera/client/cassandra/dsdriver/DSClient.java",
    "content": "/**\n\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.cassandra.dsdriver;\n\nimport java.io.UnsupportedEncodingException;\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.cassandra.thrift.IndexClause;\nimport org.apache.cassandra.thrift.IndexExpression;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SuperColumn;\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.thrift.TException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.datastax.driver.core.ColumnDefinitions;\nimport com.datastax.driver.core.ColumnDefinitions.Definition;\nimport com.datastax.driver.core.ColumnMetadata;\nimport com.datastax.driver.core.ConsistencyLevel;\nimport com.datastax.driver.core.DataType;\nimport com.datastax.driver.core.ResultSet;\nimport com.datastax.driver.core.Row;\nimport com.datastax.driver.core.Session;\nimport com.datastax.driver.core.SimpleStatement;\nimport com.datastax.driver.core.Statement;\nimport com.datastax.driver.core.BoundStatement;\nimport com.datastax.driver.core.PreparedStatement;\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.datahandler.CassandraDataHandler;\nimport com.impetus.client.cassandra.thrift.CQLTranslator;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.db.SearchResult;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.annotation.DefaultEntityAnnotationProcessor;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessor;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.TimestampGenerator;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * Kundera powered datastax java driver based client.\n * \n * @author vivek.mishra\n * \n */\npublic class DSClient extends CassandraClientBase implements Client<DSCassQuery>, Batcher {\n\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(DSClient.class);\n\n    /** The factory. */\n    private DSClientFactory factory;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /**\n     * Instantiates a new DS client.\n     * \n     * @param factory\n     *            the factory\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param externalProperties\n     *            the external properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param reader\n     *            the reader\n     * @param generator\n     *            the generator\n     */\n    public DSClient(DSClientFactory factory, String persistenceUnit, Map<String, Object> externalProperties,\n        KunderaMetadata kunderaMetadata, EntityReader reader, final TimestampGenerator generator) {\n        super(persistenceUnit, externalProperties, kunderaMetadata, generator);\n        this.factory = factory;\n        this.reader = reader;\n        this.clientMetadata = factory.getClientMetadata();\n        this.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.metadata .model.EntityMetadata,\n     * java.lang.Object, java.lang.Object, java.util.List)\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders) {\n        // Insert, update is fine\n        try {\n            cqlClient.persist(entityMetadata, entity, null, rlHolders,\n                getTtlValues().get(entityMetadata.getTableName()));\n        } catch (InvalidRequestException e) {\n            log.error(\"Error while persisting record, Caused by: .\", e);\n            throw new KunderaException(e);\n        } catch (TException e) {\n            log.error(\"Error while persisting record, Caused by: .\", e);\n            throw new KunderaException(e);\n        } catch (UnsupportedEncodingException e) {\n            log.error(\"Error while persisting record, Caused by: .\", e);\n            throw new KunderaException(e);\n        }\n\n    }\n\n    /**\n     * Finds an entity from database.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param rowId\n     *            the row id\n     * @return the object\n     */\n    @Override\n    public Object find(Class entityClass, Object rowId) {\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        StringBuilder builder = createSelectQuery(rowId, metadata, metadata.getTableName());\n        ResultSet rSet = this.execute(builder.toString(), null);\n        List results = iterateAndReturn(rSet, metadata);\n        return results.isEmpty() ? null : results.get(0);\n    }\n\n    /**\n     * Creates the select query.\n     * \n     * @param rowId\n     *            the row id\n     * @param metadata\n     *            the metadata\n     * @param tableName\n     *            the table name\n     * @return the string builder\n     */\n    private StringBuilder createSelectQuery(Object rowId, EntityMetadata metadata, String tableName) {\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());\n\n        CQLTranslator translator = new CQLTranslator();\n\n        String select_Query = translator.SELECTALL_QUERY;\n        select_Query = StringUtils.replace(select_Query, CQLTranslator.COLUMN_FAMILY,\n            translator.ensureCase(new StringBuilder(), tableName, false).toString());\n        StringBuilder builder = new StringBuilder(select_Query);\n\n        builder.append(CQLTranslator.ADD_WHERE_CLAUSE);\n        onWhereClause(metadata, rowId, translator, builder, metaModel, metadata.getIdAttribute());\n        builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length());\n\n        return builder;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#findAll(java.lang.Class, java.lang.String[],\n     * java.lang.Object[])\n     */\n    @Override\n    public final <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... rowIds) {\n        // TODO: need to think about selected column case.\n        // Bring in IN Clause in place of each read.\n\n        List results = new ArrayList<E>();\n        if (rowIds != null) {\n            for (Object rowId : rowIds) {\n                Object result = find(entityClass, rowId);\n                if (result != null) {\n                    results.add(result);\n                }\n            }\n        }\n        return results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class, java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap) {\n        throw new UnsupportedOperationException(\n            \"Support for super columns is not available with DS java driver. Either use Thrift or pelops for the same\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera\n     * .persistence.context.jointable.JoinTableData)\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData) {\n        // TODO:: Add support for Many-to-Many join tables.\n        String joinTableName = joinTableData.getJoinTableName();\n        String invJoinColumnName = joinTableData.getInverseJoinColumnName();\n        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();\n\n        EntityMetadata entityMetadata =\n            KunderaMetadataManager.getEntityMetadata(kunderaMetadata, joinTableData.getEntityClass());\n\n        // need to bring in an insert query for this\n        // add columns & execute query\n\n        CQLTranslator translator = new CQLTranslator();\n\n        String batch_Query = CQLTranslator.BATCH_QUERY;\n\n        String insert_Query = translator.INSERT_QUERY;\n\n        StringBuilder builder = new StringBuilder();\n        builder.append(CQLTranslator.DEFAULT_KEY_NAME);\n        builder.append(CQLTranslator.COMMA_STR);\n        builder.append(translator.ensureCase(new StringBuilder(), joinTableData.getJoinColumnName(), false));\n        builder.append(CQLTranslator.COMMA_STR);\n        builder.append(translator.ensureCase(new StringBuilder(), joinTableData.getInverseJoinColumnName(), false));\n\n        insert_Query = StringUtils.replace(insert_Query, CQLTranslator.COLUMN_FAMILY,\n            translator.ensureCase(new StringBuilder(), joinTableName, false).toString());\n\n        insert_Query = StringUtils.replace(insert_Query, CQLTranslator.COLUMNS, builder.toString());\n\n        StringBuilder columnValueBuilder = new StringBuilder();\n\n        StringBuilder statements = new StringBuilder();\n\n        // insert query for each row key and\n        for (Object key : joinTableRecords.keySet()) {\n            PropertyAccessor accessor =\n                PropertyAccessorFactory.getPropertyAccessor((Field) entityMetadata.getIdAttribute().getJavaMember());\n\n            Set<Object> values = joinTableRecords.get(key); // join column value\n\n            for (Object value : values) {\n                if (value != null) {\n                    String insertQuery = insert_Query;\n                    columnValueBuilder.append(CQLTranslator.QUOTE_STR);\n                    columnValueBuilder.append(\n                        PropertyAccessorHelper.getString(key) + \"\\001\" + PropertyAccessorHelper.getString(value));\n                    columnValueBuilder.append(CQLTranslator.QUOTE_STR);\n                    columnValueBuilder.append(CQLTranslator.COMMA_STR);\n                    translator.appendValue(columnValueBuilder, key.getClass(), key, true, false);\n                    columnValueBuilder.append(CQLTranslator.COMMA_STR);\n                    translator.appendValue(columnValueBuilder, value.getClass(), value, true, false);\n\n                    insertQuery =\n                        StringUtils.replace(insertQuery, CQLTranslator.COLUMN_VALUES, columnValueBuilder.toString());\n                    statements.append(insertQuery);\n                    statements.append(\" \");\n                }\n            }\n        }\n\n        if (!StringUtils.isBlank(statements.toString())) {\n            batch_Query = StringUtils.replace(batch_Query, CQLTranslator.STATEMENT, statements.toString());\n            StringBuilder batchBuilder = new StringBuilder();\n            batchBuilder.append(batch_Query);\n            batchBuilder.append(CQLTranslator.APPLY_BATCH);\n            execute(batchBuilder.toString(), null);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String, java.lang.String, java.lang.String,\n     * java.lang.String, java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,\n        Object pKeyColumnValue, Class columnJavaType) {\n        // select columnName from tableName where pKeyColumnName =\n        // pKeyColumnValue\n        List results = new ArrayList();\n        CQLTranslator translator = new CQLTranslator();\n        String selectQuery = translator.SELECT_QUERY;\n        selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMN_FAMILY,\n            translator.ensureCase(new StringBuilder(), tableName, false).toString());\n        selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMNS,\n            translator.ensureCase(new StringBuilder(), columnName, false).toString());\n\n        StringBuilder selectQueryBuilder = new StringBuilder(selectQuery);\n\n        selectQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE);\n\n        translator.buildWhereClause(selectQueryBuilder, columnJavaType, pKeyColumnName, pKeyColumnValue,\n            CQLTranslator.EQ_CLAUSE, false);\n        selectQueryBuilder.delete(selectQueryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE),\n            selectQueryBuilder.length());\n\n        ResultSet rSet = execute(selectQueryBuilder.toString(), null);\n\n        Iterator<Row> rowIter = rSet.iterator();\n        while (rowIter.hasNext()) {\n            Row row = rowIter.next();\n            DataType dataType = row.getColumnDefinitions().getType(columnName);\n            Object columnValue =\n                DSClientUtilities.assign(row, null, null, dataType.getName(), null, columnName, null, null);\n            results.add(columnValue);\n        }\n        return results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String, java.lang.String, java.lang.String,\n     * java.lang.String, java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n        Object columnValue, Class entityClazz) {\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n\n        return getColumnsById(schemaName, tableName, columnName,\n            ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName(), columnValue,\n            metadata.getIdAttribute().getBindableJavaType()).toArray();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String, java.lang.String, java.lang.String,\n     * java.lang.Object)\n     */\n    @Override\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue) {\n        Session session = factory.getConnection();\n        String rowKeyName = null;\n        CQLTranslator translator = new CQLTranslator();\n        try {\n            List<ColumnMetadata> primaryKeys = session.getCluster().getMetadata().getKeyspace(\"\\\"\" + schemaName + \"\\\"\")\n                .getTable(\"\\\"\" + tableName + \"\\\"\").getPrimaryKey();\n            rowKeyName = primaryKeys.get(0).getName();\n        } finally {\n            // factory.releaseConnection(session);\n        }\n\n        List rowKeys =\n            getColumnsById(schemaName, tableName, columnName, rowKeyName, columnValue, columnValue.getClass());\n        for (Object rowKey : rowKeys) {\n            if (rowKey != null) {\n                String deleteQuery = CQLTranslator.DELETE_QUERY;\n\n                deleteQuery = StringUtils.replace(deleteQuery, CQLTranslator.COLUMN_FAMILY,\n                    translator.ensureCase(new StringBuilder(), tableName, false).toString());\n                StringBuilder deleteQueryBuilder = new StringBuilder(deleteQuery);\n                deleteQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE);\n                deleteQueryBuilder = translator.ensureCase(deleteQueryBuilder, rowKeyName, false);\n                deleteQueryBuilder.append(CQLTranslator.EQ_CLAUSE);\n                translator.appendValue(deleteQueryBuilder, rowKey.getClass(), rowKey, false, false);\n                this.execute(deleteQueryBuilder.toString(), null);\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String, java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz) {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n        CQLTranslator translator = new CQLTranslator();\n        String selectQuery = translator.SELECTALL_QUERY;\n        selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMN_FAMILY,\n            translator.ensureCase(new StringBuilder(), m.getTableName(), false).toString());\n\n        StringBuilder selectQueryBuilder = new StringBuilder(selectQuery);\n        selectQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE);\n\n        translator.buildWhereClause(selectQueryBuilder, colValue.getClass(), colName, colValue, CQLTranslator.EQ_CLAUSE,\n            false);\n        selectQueryBuilder.delete(selectQueryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE),\n            selectQueryBuilder.length());\n\n        ResultSet rSet = (ResultSet) this.execute(selectQueryBuilder.toString(), null);\n\n        return iterateAndReturn(rSet, m);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader() {\n        return this.reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<DSCassQuery> getQueryImplementor() {\n        return DSCassQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#find(java.lang.Class, java.util.List, boolean,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.lang.Object[])\n     */\n    @Override\n    public List find(Class entityClass, List<String> relationNames, boolean isWrapReq, EntityMetadata metadata,\n        Object... rowIds) {\n        return findAll(entityClass, null, rowIds);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#loadSuperColumns(java .lang.String, java.lang.String,\n     * java.lang.String, java.lang.String[])\n     */\n    @Override\n    protected List<SuperColumn> loadSuperColumns(String keyspace, String columnFamily, String rowId,\n        String... superColumnNames) {\n        throw new UnsupportedOperationException(\n            \"Support for super columns is not available with DS java driver. Either use Thrift or pelops for the same\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#executeQuery(java.lang .Class, java.util.List, boolean,\n     * java.lang.String)\n     */\n    @Override\n    public List executeQuery(Class clazz, List<String> relationalField, boolean isNative, String cqlQuery) {\n        ResultSet rSet = (ResultSet) this.execute(cqlQuery, null);\n        if (clazz == null) {\n\t\t// XXX\n            if (isNative)\n                return iterateAndReturnNative(rSet);\n            return iterateAndReturn(rSet);\n        }\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n        return iterateAndReturn(rSet, metadata);\n    }\n\n    // XXX\n    @Override\n    public List executeQuery(final Class clazz, final List<String> relationalField, final boolean isNative,\n        final String cqlQuery, final List<KunderaQuery.BindParameter> parameters) {\n        ResultSet rSet = (ResultSet) this.execute(cqlQuery, null, parameters);\n\n        if (clazz == null) {\n            if (isNative)\n                return iterateAndReturnNative(rSet);\n            return iterateAndReturn(rSet);\n        }\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n        return iterateAndReturn(rSet, metadata);\n    }\n\n    public ResultSet executeStatement(Statement st) {\n\n        Session session = factory.getConnection();\n        return session.execute(st);\n    }\n\n    /**\n     * XXX\n     *\n     * Iterate and return for native queries. Returns a List&lt;Object&gt; or a List&lt;Object[]&gt;\n     * \n     * @param rSet\n     *            the r set\n     * @return the list\n     */\n    private List iterateAndReturnNative(final ResultSet rSet) {\n        final Iterator<Row> rowIter = rSet.iterator();\n        final List results = new ArrayList();\n        final List item = new ArrayList<>();\n\n        final boolean isSingle = (rSet.getColumnDefinitions().size() == 1);\n\n        while (rowIter.hasNext()) {\n            final Row row = rowIter.next();\n\n            final ColumnDefinitions columnDefs = row.getColumnDefinitions();\n\n            final Iterator<Definition> columnDefIter = columnDefs.iterator();\n\n            item.clear();\n\n            while (columnDefIter.hasNext()) {\n                final Definition columnDef = columnDefIter.next();\n\n                item.add(DSClientUtilities.assign(row, null, null, columnDef.getType().getName(), null,\n                    columnDef.getName(), null, null));\n            }\n\n            if (isSingle) {\n                if (!item.isEmpty())\n                    results.add(item.get(0));\n                else\n                    results.add(null);\n            } else\n                results.add(item.toArray(new Object[item.size()]));\n        }\n\n        return results;\n    }\n\n    /**\n     * Iterate and return.\n     * \n     * @param rSet\n     *            the r set\n     * @return the list\n     */\n    private List iterateAndReturn(ResultSet rSet) {\n        Iterator<Row> rowIter = rSet.iterator();\n        List results = new ArrayList();\n\n        while (rowIter.hasNext()) {\n            Row row = rowIter.next();\n            ColumnDefinitions columnDefs = row.getColumnDefinitions();\n            Iterator<Definition> columnDefIter = columnDefs.iterator();\n            Map rowData = new HashMap();\n            while (columnDefIter.hasNext()) {\n                Definition columnDef = columnDefIter.next();\n                rowData.put(columnDef.getName(), DSClientUtilities.assign(row, null, null,\n                    columnDef.getType().getName(), null, columnDef.getName(), null, null));\n            }\n            results.add(rowData);\n        }\n        return results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#find(java.util.List,\n     * com.impetus.kundera.metadata.model.EntityMetadata, boolean, java.util.List, int, java.util.List)\n     */\n    @Override\n    public List find(List<IndexClause> ixClause, EntityMetadata m, boolean isRelation, List<String> relations,\n        int maxResult, List<String> columns) {\n        throw new UnsupportedOperationException(\"Support available only for thrift/pelops.\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#findByRange(byte[], byte[],\n     * com.impetus.kundera.metadata.model.EntityMetadata, boolean, java.util.List, java.util.List, java.util.List, int)\n     */\n    @Override\n    public List findByRange(byte[] muinVal, byte[] maxVal, EntityMetadata m, boolean isWrapReq, List<String> relations,\n        List<String> columns, List<IndexExpression> conditions, int maxResults) throws Exception {\n        throw new UnsupportedOperationException(\"Support available only for thrift/pelops.\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#searchInInvertedIndex (java.lang.String,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.util.Map)\n     */\n    @Override\n    public List<SearchResult> searchInInvertedIndex(String columnFamilyName, EntityMetadata m,\n        Map<Boolean, List<IndexClause>> indexClauseMap) {\n        throw new UnsupportedOperationException(\"Support available only for thrift/pelops.\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#find(com.impetus.kundera .metadata.model.EntityMetadata,\n     * java.util.List, java.util.List, int, java.util.List)\n     */\n    @Override\n    public List<EnhanceEntity> find(EntityMetadata m, List<String> relationNames, List<IndexClause> conditions,\n        int maxResult, List<String> columns) {\n        throw new UnsupportedOperationException(\"Support available only for thrift/pelops.\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#getDataHandler()\n     */\n    @Override\n    protected CassandraDataHandler getDataHandler() {\n        throw new UnsupportedOperationException(\"Support available only for thrift/pelops.\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#delete(java.lang.Object, java.lang.Object)\n     */\n    @Override\n    public void delete(Object entity, Object pKey) {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());\n\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(m.getEntityClazz());\n\n        // For secondary tables.\n        List<String> secondaryTables =\n            ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation()).getSecondaryTablesName();\n        secondaryTables.add(m.getTableName());\n\n        for (String tableName : secondaryTables) {\n            this.execute(onDeleteQuery(m, tableName, metaModel, pKey), null);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#getConnection()\n     */\n    @Override\n    protected Object getConnection() {\n        // do nothing returning null.\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#getConnection(java.lang .Object)\n     */\n    @Override\n    protected Object getConnection(Object connection) {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#releaseConnection(java .lang.Object)\n     */\n    @Override\n    protected void releaseConnection(Object conn) {\n        // do nothing\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#execute(java.lang.String , java.lang.Object)\n     */\n    @Override\n    public <T> T execute(final String query, Object connection) {\n\n        Session session = factory.getConnection();\n        try {\n            Statement queryStmt = new SimpleStatement(query);\n            KunderaCoreUtils.printQuery(query, showQuery);\n            queryStmt.setConsistencyLevel(ConsistencyLevel.valueOf(this.consistencyLevel.name()));\n            return (T) session.execute(queryStmt);\n        } catch (Exception e) {\n            log.error(\"Error while executing query {}.\", query);\n            throw new KunderaException(e);\n        } finally {\n            // factory.releaseConnection(session);\n        }\n    }\n\n    @Override\n    public <T> T execute(final String query, Object connection, final List<KunderaQuery.BindParameter> parameters) {\n\n        Session session = factory.getConnection();\n\n        try {\n            final PreparedStatement preparedStatement = session.prepare(query);\n            final BoundStatement boundStatement = preparedStatement.bind();\n\n            for (KunderaQuery.BindParameter value : parameters) {\n\n                log.info(\"binding [\" + value.getIndex() + \":\" + value.getName() + \"] to [\" + value.getValue() + \"]\");\n\n                if (value.getValue() != null) {\n\n                    if (value.getValue() instanceof String) {\n                        if (value.isNamed())\n                            boundStatement.setString(value.getName(), (String) value.getValue());\n                        else\n                            boundStatement.setString(value.getIndex() - 1, (String) value.getValue());\n                    } else if (value.getValue() instanceof Integer) {\n                        if (value.isNamed())\n                            boundStatement.setInt(value.getName(), (Integer) value.getValue());\n                        else\n                            boundStatement.setInt(value.getIndex() - 1, (Integer) value.getValue());\n                    } else if (value.getValue() instanceof Long) {\n                        if (value.isNamed())\n                            boundStatement.setLong(value.getName(), (Long) value.getValue());\n                        else\n                            boundStatement.setLong(value.getIndex() - 1, (Long) value.getValue());\n                    } else if (value.getValue() instanceof java.util.UUID) {\n                        if (value.isNamed())\n                            boundStatement.setUUID(value.getName(), (java.util.UUID) value.getValue());\n                        else\n                            boundStatement.setUUID(value.getIndex() - 1, (java.util.UUID) value.getValue());\n                    } else if (value.getValue() instanceof List) {\n                        if (value.isNamed())\n                            boundStatement.setList(value.getName(), (List) value.getValue());\n                        else\n                            boundStatement.setList(value.getIndex() - 1, (List) value.getValue());\n                    } else {\n                        throw new IllegalArgumentException(\"bind parameter type [\" + value.getValue().getClass()\n                            + \"] is not supported, \" + value.getIndex() + \":\" + value.getName());\n                    }\n                } else {\n                    throw new IllegalArgumentException(\"setting null bind parameters is not supported\");\n                }\n            }\n\n            KunderaCoreUtils.printQuery(query, showQuery);\n\n            boundStatement.setConsistencyLevel(ConsistencyLevel.valueOf(this.consistencyLevel.name()));\n\n            return (T) session.execute(boundStatement);\n        } catch (Exception e) {\n            log.error(\"Error while executing query {}.\", query);\n            throw new KunderaException(e);\n        } finally {\n            // factory.releaseConnection(session);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#executeUpdateDeleteQuery (java.lang.String)\n     */\n    public int executeUpdateDeleteQuery(String cqlQuery) {\n        Session session = null;\n        try {\n            if (log.isInfoEnabled()) {\n                log.info(\"Executing cql query {}.\", cqlQuery);\n            }\n            session = factory.getConnection();\n            KunderaCoreUtils.printQuery(cqlQuery, showQuery);\n            session.execute(cqlQuery);\n        } finally {\n            // factory.releaseConnection(session);\n        }\n        // TODO: can't find a way to return number of updated records.\n        return 0;\n\n    }\n\n    /**\n     * Iterate and return.\n     * \n     * @param rSet\n     *            the r set\n     * @param entityClazz\n     *            the entity clazz\n     * @param metadata\n     *            the metadata\n     * @return the list\n     */\n    private List iterateAndReturn(ResultSet rSet, EntityMetadata metadata) {\n        MetamodelImpl metaModel =\n            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(metadata.getEntityClazz());\n\n        Iterator<Row> rowIter = rSet.iterator();\n        List results = new ArrayList();\n\n        Map<String, Object> relationalValues = new HashMap<String, Object>();\n\n        while (rowIter.hasNext()) {\n            Object entity = null;\n            Row row = rowIter.next();\n            populateObjectFromRow(metadata, metaModel, entityType, results, relationalValues, entity, row);\n        }\n        return results;\n    }\n\n    void populateObjectFromRow(EntityMetadata metadata, MetamodelImpl metaModel, EntityType entityType, List results,\n        Map<String, Object> relationalValues, Object entity, Row row) {\n        ColumnDefinitions columnDefs = row.getColumnDefinitions();\n        Iterator<Definition> columnDefIter = columnDefs.iterator();\n\n        entity = iteratorColumns(metadata, metaModel, entityType, relationalValues, entity, row, columnDefIter);\n\n        if (entity != null && entity.getClass().isAssignableFrom(metadata.getEntityClazz())) {\n            Object rowKey = PropertyAccessorHelper.getId(entity, metadata);\n\n            // populate secondary tables data if there is any.\n            populateSecondaryTableData(rowKey, entity, metaModel, metadata);\n\n            if (!relationalValues.isEmpty()) {\n                results.add(new EnhanceEntity(entity, rowKey, relationalValues));\n            } else {\n                results.add(entity);\n            }\n        } else if (entity != null) {\n            results.add(entity);\n        }\n    }\n\n    /**\n     * Populates data form secondary tables of entity for given row key.\n     * \n     * @param rowId\n     *            the row id\n     * @param entity\n     *            the entity\n     * @param metaModel\n     *            the meta model\n     * @param metadata\n     *            the metadata\n     */\n    private void populateSecondaryTableData(Object rowId, Object entity, MetamodelImpl metaModel,\n        EntityMetadata metadata) {\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(metadata.getEntityClazz());\n        List<String> secondaryTables =\n            ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation()).getSecondaryTablesName();\n\n        for (String tableName : secondaryTables) {\n            StringBuilder builder = createSelectQuery(rowId, metadata, tableName);\n            ResultSet rSet = this.execute(builder.toString(), null);\n\n            Iterator<Row> rowIter = rSet.iterator();\n\n            Row row = rowIter.next();\n            ColumnDefinitions columnDefs = row.getColumnDefinitions();\n            Iterator<Definition> columnDefIter = columnDefs.iterator();\n\n            entity = iteratorColumns(metadata, metaModel, metaModel.entity(metadata.getEntityClazz()),\n                new HashMap<String, Object>(), entity, row, columnDefIter);\n        }\n    }\n\n    /**\n     * Iterator columns.\n     * \n     * @param metadata\n     *            the metadata\n     * @param metamodel\n     *            the metamodel\n     * @param entityType\n     *            the entity type\n     * @param relationalValues\n     *            the relational values\n     * @param entity\n     *            the entity\n     * @param row\n     *            the row\n     * @param columnDefIter\n     *            the column def iter\n     * @return the object\n     */\n    private Object iteratorColumns(EntityMetadata metadata, MetamodelImpl metamodel, EntityType entityType,\n        Map<String, Object> relationalValues, Object entity, Row row, Iterator<Definition> columnDefIter) {\n        while (columnDefIter.hasNext()) {\n            Definition columnDef = columnDefIter.next();\n            final String columnName = columnDef.getName(); // column name\n\n            DataType dataType = columnDef.getType(); // data type\n\n            if (metadata.getRelationNames() != null && metadata.getRelationNames().contains(columnName)\n                && !columnName.equals(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName())) {\n                Object relationalValue = DSClientUtilities.assign(row, null, metadata, dataType.getName(), entityType,\n                    columnName, null, metamodel);\n                relationalValues.put(columnName, relationalValue);\n            } else {\n                String fieldName = columnName.equals(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName())\n                    ? metadata.getIdAttribute().getName() : metadata.getFieldName(columnName);\n                Attribute attribute = fieldName != null ? entityType.getAttribute(fieldName) : null;\n\n                if (attribute != null) {\n                    if (!attribute.isAssociation()) {\n                        entity = DSClientUtilities.assign(row, entity, metadata, dataType.getName(), entityType,\n                            columnName, null, metamodel);\n                    }\n                } else if (metamodel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {\n                    entity = populateCompositeId(metadata, entity, columnName, row, metamodel,\n                        metadata.getIdAttribute(), metadata.getEntityClazz(), dataType);\n                } else {\n                    entity = DSClientUtilities.assign(row, entity, metadata, dataType.getName(), entityType, columnName,\n                        null, metamodel);\n                }\n            }\n        }\n        return entity;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#close()\n     */\n    @Override\n    public void close() {\n        super.close();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientBase#getPersistenceUnit()\n     */\n    @Override\n    public String getPersistenceUnit() {\n        return super.getPersistenceUnit();\n    }\n\n    /**\n     * Populate composite id.\n     * \n     * @param metadata\n     *            the metadata\n     * @param entity\n     *            the entity\n     * @param columnName\n     *            the column name\n     * @param row\n     *            the row\n     * @param metaModel\n     *            the meta model\n     * @param attribute\n     *            the attribute\n     * @param entityClazz\n     *            the entity clazz\n     * @param dataType\n     *            the data type\n     * @return the object\n     */\n    private Object populateCompositeId(EntityMetadata metadata, Object entity, String columnName, Row row,\n        MetamodelImpl metaModel, Attribute attribute, Class<?> entityClazz, DataType dataType) {\n        Class javaType = ((AbstractAttribute) attribute).getBindableJavaType();\n\n        if (metaModel.isEmbeddable(javaType)) {\n            EmbeddableType compoundKey = metaModel.embeddable(javaType);\n            Object compoundKeyObject = null;\n            try {\n                Set<Attribute> attributes = compoundKey.getAttributes();\n                entity = KunderaCoreUtils.initialize(entityClazz, entity);\n\n                for (Attribute compoundAttribute : attributes) {\n                    compoundKeyObject =\n                        compoundKeyObject == null ? getCompoundKey(attribute, entity) : compoundKeyObject;\n\n                    if (metaModel.isEmbeddable(((AbstractAttribute) compoundAttribute).getBindableJavaType())) {\n                        Object compoundObject = populateCompositeId(metadata, compoundKeyObject, columnName, row,\n                            metaModel, compoundAttribute, javaType, dataType);\n                        PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), compoundObject);\n                    } else if (((AbstractAttribute) compoundAttribute).getJPAColumnName().equals(columnName)) {\n                        DSClientUtilities.assign(row, compoundKeyObject, null, dataType.getName(), null, columnName,\n                            (Field) compoundAttribute.getJavaMember(), metaModel);\n                        PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), compoundKeyObject);\n                        break;\n                    }\n                }\n            } catch (IllegalArgumentException iaex) {\n                // ignore as it might not represented within entity.\n                // No need for any logger message\n            } catch (Exception e) {\n                log.error(\"Error while retrieving data, Caused by: .\", e);\n                throw new PersistenceException(e);\n            }\n        }\n        return entity;\n    }\n\n    /**\n     * Gets the compound key.\n     * \n     * @param attribute\n     *            the attribute\n     * @param entity\n     *            the entity\n     * @return the compound key\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    private Object getCompoundKey(Attribute attribute, Object entity)\n        throws InstantiationException, IllegalAccessException {\n        Object compoundKeyObject = null;\n        if (entity != null) {\n            compoundKeyObject = PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());\n            if (compoundKeyObject == null) {\n                compoundKeyObject = ((AbstractAttribute) attribute).getBindableJavaType().newInstance();\n            }\n        }\n\n        return compoundKeyObject;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator() {\n        return (Generator) KunderaCoreUtils.createNewInstance(DSIdGenerator.class);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/main/java/com/impetus/kundera/client/cassandra/dsdriver/DSClientFactory.java",
    "content": "/**\n * Copyright 2014 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.cassandra.dsdriver;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.net.InetSocketAddress;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.datastax.driver.core.Cluster;\nimport com.datastax.driver.core.Cluster.Builder;\nimport com.datastax.driver.core.HostDistance;\nimport com.datastax.driver.core.PoolingOptions;\nimport com.datastax.driver.core.ProtocolOptions.Compression;\nimport com.datastax.driver.core.Session;\nimport com.datastax.driver.core.SocketOptions;\nimport com.datastax.driver.core.policies.ConstantReconnectionPolicy;\nimport com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;\nimport com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;\nimport com.datastax.driver.core.policies.ExponentialReconnectionPolicy;\nimport com.datastax.driver.core.policies.FallthroughRetryPolicy;\nimport com.datastax.driver.core.policies.HostFilterPolicy;\nimport com.datastax.driver.core.policies.LatencyAwarePolicy;\nimport com.datastax.driver.core.policies.LoadBalancingPolicy;\nimport com.datastax.driver.core.policies.LoggingRetryPolicy;\nimport com.datastax.driver.core.policies.RoundRobinPolicy;\nimport com.datastax.driver.core.policies.TokenAwarePolicy;\nimport com.datastax.driver.core.policies.WhiteListPolicy;\nimport com.google.common.base.Predicate;\nimport com.impetus.client.cassandra.common.CassandraClientFactory;\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.config.CassandraPropertyReader;\nimport com.impetus.client.cassandra.query.CassandraEntityReader;\nimport com.impetus.client.cassandra.schemamanager.CassandraSchemaManager;\nimport com.impetus.client.cassandra.service.CassandraHost;\nimport com.impetus.client.cassandra.service.CassandraHostConfiguration;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.service.Host;\nimport com.impetus.kundera.utils.InvalidConfigurationException;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * Data stax java driver client factory.\n * \n * @author vivek.mishra\n * \n */\npublic class DSClientFactory extends CassandraClientFactory\n{\n\n    /** The Constant GET_INSTANCE. */\n    private static final String GET_INSTANCE = \"getInstance\";\n\n    /** The Constant CUSTOM_RETRY_POLICY. */\n    private static final String CUSTOM_RETRY_POLICY = \"customRetryPolicy\";\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(DSClientFactory.class);\n\n    /** The configuration. */\n    private CassandraHostConfiguration configuration;\n\n    /** The keyspace. */\n    private String keyspace;\n\n    /** The session. */\n    private Session session;\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.ClientFactory#getSchemaManager(java.util.Map)\n     */\n    @Override\n    public SchemaManager getSchemaManager(Map<String, Object> puProperties)\n    {\n        if (schemaManager == null)\n        {\n            initializePropertyReader();\n            externalProperties.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n            externalProperties.put(\n                    CassandraConstants.THRIFT_PORT,\n                    externalProperties.get(CassandraConstants.THRIFT_PORT) != null ? externalProperties\n                            .get(CassandraConstants.THRIFT_PORT) : \"9160\");\n            schemaManager = new CassandraSchemaManager(this.getClass().getName(), externalProperties, kunderaMetadata);\n        }\n        return schemaManager;\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.ClientLifeCycleManager#destroy()\n     */\n    @Override\n    public void destroy()\n    {\n        if (indexManager != null)\n        {\n            indexManager.close();\n        }\n        if (schemaManager != null)\n        {\n            schemaManager.dropSchema();\n        }\n        schemaManager = null;\n        externalProperties = null;\n        releaseConnection(this.session);\n        ((Cluster) getConnectionPoolOrConnection()).closeAsync();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.cassandra.common.CassandraClientFactory#addCassandraHost\n     * (com.impetus.client.cassandra.service.CassandraHost)\n     */\n    @Override\n    public boolean addCassandraHost(CassandraHost host)\n    {\n        // No need to setup this, as it is part of Kundera powered retry\n        // service.\n\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initialize(java.util.Map)\n     */\n    @Override\n    public void initialize(Map<String, Object> externalProperty)\n    {\n        reader = new CassandraEntityReader(kunderaMetadata);\n        initializePropertyReader();\n        setExternalProperties(externalProperty);\n\n        configuration = new CassandraHostConfiguration(externalProperties, CassandraPropertyReader.csmd,\n                getPersistenceUnit(), kunderaMetadata);\n\n        // initialize timestamp generator.\n        initializeTimestampGenerator(externalProperty);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#createPoolOrConnection()\n     */\n    @Override\n    protected Object createPoolOrConnection()\n    {\n        // AuthInfoProvider,LoadBalancingPolicy, ReconnectionPolicy,\n        // RetryPolicy,ProtocolOptions.Compression, SSLOptions,\n        // PoolingOptions,SocketOptions\n\n        if (logger.isDebugEnabled())\n        {\n            logger.debug(\"Intiatilzing connection\");\n        }\n\n        Properties connectionProperties = CassandraPropertyReader.csmd.getConnectionProperties();\n        Builder connectionBuilder = Cluster.builder();\n\n        // add host/port and AuthInfoProvider\n        for (Host host : configuration.getCassandraHosts())\n        {\n            connectionBuilder.addContactPoint(host.getHost()).withPort(host.getPort());\n            if (host.getUser() != null)\n            {\n                connectionBuilder.withCredentials(host.getUser(), host.getPassword());\n            }\n        }\n\n        // add policy configuration\n        String loadBalancingPolicy = connectionProperties.getProperty(Constants.LOADBALANCING_POLICY);\n        if (!StringUtils.isBlank(loadBalancingPolicy))\n        {\n            LoadBalancingPolicy policy = getPolicyInstance(BalancingPolicy.getPolicy(loadBalancingPolicy),\n                    connectionProperties);\n            if (policy != null)\n            {\n                connectionBuilder.withLoadBalancingPolicy(policy);\n            }\n        }\n\n        // compression\n        String compression = connectionProperties.getProperty(\"compression\");\n\n        if (!StringUtils.isBlank(compression))\n        {\n            connectionBuilder.withCompression(Compression.valueOf(compression));\n        }\n\n        // ReconnectionPolicy\n\n        String reconnectionPolicy = connectionProperties.getProperty(\"reconnection.policy\");\n        if (!StringUtils.isBlank(reconnectionPolicy))\n        {\n            com.datastax.driver.core.policies.ReconnectionPolicy policy = getPolicy(\n                    ReconnectionPolicy.getPolicy(reconnectionPolicy), connectionProperties);\n\n            if (policy != null)\n            {\n                connectionBuilder.withReconnectionPolicy(policy);\n            }\n\n        }\n\n        // , RetryPolicy\n        String retryPolicy = connectionProperties.getProperty(\"retry.policy\");\n\n        if (!StringUtils.isBlank(retryPolicy))\n        {\n            com.datastax.driver.core.policies.RetryPolicy policy = getPolicy(RetryPolicy.getPolicy(retryPolicy),\n                    connectionProperties);\n\n            if (policy != null)\n            {\n                connectionBuilder.withRetryPolicy(policy);\n            }\n\n        }\n\n        // TODO::: SSLOptions? Not sure how to add it.\n\n        // SocketOptions\n        connectionBuilder.withSocketOptions(getSocketOptions(connectionProperties));\n\n        // PoolingOptions,\n        connectionBuilder.withPoolingOptions(getPoolingOptions(connectionProperties));\n\n        // finally build cluster.\n        Cluster cluster = connectionBuilder.build();\n\n        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(getPersistenceUnit());\n        Properties props = persistenceUnitMetadata.getProperties();\n\n        if (externalProperties != null)\n        {\n            keyspace = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);\n        }\n\n        if (keyspace == null)\n        {\n            keyspace = (String) props.get(PersistenceProperties.KUNDERA_KEYSPACE);\n        }\n        setSessionObject(cluster); // TODO custom session\n        return cluster; // TODO custom cluster\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#instantiateClient(java\n     * .lang.String)\n     */\n    @Override\n    protected Client<?> instantiateClient(String persistenceUnit)\n    {\n        return new DSClient(this, persistenceUnit, externalProperties, kunderaMetadata, reader, timestampGenerator);\n    }\n\n    /**\n     * Sets the session object.\n     * \n     * @param cluster\n     *            the new session object\n     */\n    void setSessionObject(Cluster cluster)\n    {\n        this.session = cluster.connect(\"\\\"\" + keyspace + \"\\\"\");\n    }\n\n    /**\n     * Gets the connection.\n     * \n     * @return the connection\n     */\n    Session getConnection()\n    {\n        return this.session != null ? this.session : ((Cluster) this.getConnectionPoolOrConnection()).connect(\"\\\"\"\n                + keyspace + \"\\\"\");\n    }\n\n    /**\n     * Release connection.\n     * \n     * @param session\n     *            the session\n     */\n    void releaseConnection(Session session)\n    {\n        if (session != null)\n        {\n            session.closeAsync();\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.GenericClientFactory#isThreadSafe()\n     */\n    @Override\n    public boolean isThreadSafe()\n    {\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initializeLoadBalancer\n     * (java.lang.String)\n     */\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n        throw new UnsupportedOperationException(\"Method not supported for datastax java driver\");\n    }\n\n    /**\n     * Initialize property reader.\n     */\n    private void initializePropertyReader()\n    {\n        if (propertyReader == null)\n        {\n            propertyReader = new CassandraPropertyReader(externalProperties, kunderaMetadata.getApplicationMetadata()\n                    .getPersistenceUnitMetadata(getPersistenceUnit()));\n            propertyReader.read(getPersistenceUnit());\n        }\n    }\n\n    /**\n     * The Enum ReconnectionPolicy.\n     */\n    enum ReconnectionPolicy\n    {\n\n        /** The Constant reconnection policy. */\n        ConstantReconnectionPolicy,\n        /** The Exponential reconnection policy. */\n        ExponentialReconnectionPolicy;\n\n        /**\n         * Gets the policy.\n         * \n         * @param name\n         *            the name\n         * @return the policy\n         */\n        static ReconnectionPolicy getPolicy(String name)\n        {\n            for (ReconnectionPolicy p : ReconnectionPolicy.values())\n            {\n                if (p.name().equalsIgnoreCase(name))\n                {\n                    return p;\n                }\n            }\n\n            logger.error(\"Invalid policy name {} provided, supported policies are {}\", name,\n                    ReconnectionPolicy.values());\n\n            throw new InvalidConfigurationException(\"Invalid policy name \" + name + \" provided!\");\n        }\n    }\n\n    /**\n     * The Enum BalancingPolicy.\n     */\n    enum BalancingPolicy\n    {\n\n        /** The DC aware round robin policy. */\n        DCAwareRoundRobinPolicy,\n        /** The Round robin policy. */\n        RoundRobinPolicy;\n\n        /**\n         * Gets the policy.\n         * \n         * @param name\n         *            the name\n         * @return the policy\n         */\n        static BalancingPolicy getPolicy(String name)\n        {\n            for (BalancingPolicy p : BalancingPolicy.values())\n            {\n                if (p.name().equalsIgnoreCase(name))\n                {\n                    return p;\n                }\n            }\n\n            logger.error(\"Invalid policy name {} provided, supported policies are {}\", name, BalancingPolicy.values());\n\n            throw new InvalidConfigurationException(\"Invalid policy name \" + name + \" provided!\");\n        }\n\n    }\n\n    /**\n     * The Enum RetryPolicy.\n     */\n    enum RetryPolicy\n    {\n\n        /** The Downgrading consistency retry policy. */\n        DowngradingConsistencyRetryPolicy,\n        /** The Fallthrough retry policy. */\n        FallthroughRetryPolicy,\n        /** The Custom. */\n        Custom;\n\n        /**\n         * Gets the policy.\n         * \n         * @param name\n         *            the name\n         * @return the policy\n         */\n        static RetryPolicy getPolicy(String name)\n        {\n            for (RetryPolicy p : RetryPolicy.values())\n            {\n                if (p.name().equalsIgnoreCase(name))\n                {\n                    return p;\n                }\n            }\n\n            logger.error(\"Invalid policy name {} provided, supported policies are {}\", name, RetryPolicy.values());\n\n            throw new InvalidConfigurationException(\"Invalid policy name \" + name + \" provided!\");\n        }\n    }\n\n    /**\n     * Gets the policy instance.\n     * \n     * @param policy\n     *            the policy\n     * @param conProperties\n     *            the con properties\n     * @return the policy instance\n     */\n    private LoadBalancingPolicy getPolicyInstance(BalancingPolicy policy, Properties conProperties)\n    {\n\n        LoadBalancingPolicy loadBalancingPolicy = null;\n        String isTokenAware = (String) conProperties.get(\"isTokenAware\");\n        String isLatencyAware = (String) conProperties.get(\"isLatencyAware\");\n        String whiteList = (String) conProperties.get(\"whiteList\");\n        String hostFilterPolicy = (String) conProperties.get(\"hostFilterPolicy\");\n        // Policy.v\n        switch (policy)\n        {\n\n        case DCAwareRoundRobinPolicy:\n\n            String usedHostsPerRemoteDc = (String) conProperties.get(\"usedHostsPerRemoteDc\");\n            String localdc = (String) conProperties.get(\"localdc\");\n            String allowRemoteDCsForLocalConsistencyLevel = (String) conProperties\n                    .get(\"allowRemoteDCsForLocalConsistencyLevel\");\n            DCAwareRoundRobinPolicy.Builder policyBuilder = DCAwareRoundRobinPolicy.builder();\n            policyBuilder.withLocalDc(localdc == null ? \"DC1\" : localdc);\n            policyBuilder.withUsedHostsPerRemoteDc(usedHostsPerRemoteDc != null ? Integer\n                    .parseInt(usedHostsPerRemoteDc) : 0);\n            if (allowRemoteDCsForLocalConsistencyLevel != null\n                    && \"true\".equalsIgnoreCase(allowRemoteDCsForLocalConsistencyLevel))\n            {\n                policyBuilder.allowRemoteDCsForLocalConsistencyLevel();\n            }\n            loadBalancingPolicy = policyBuilder.build();\n            break;\n\n        // case RoundRobinPolicy:\n        // loadBalancingPolicy = new RoundRobinPolicy();\n        // break;\n\n        default:\n            // default is RoundRobinPolicy\n            loadBalancingPolicy = new RoundRobinPolicy();\n            break;\n        }\n\n        if (loadBalancingPolicy != null && Boolean.valueOf(isTokenAware))\n        {\n            loadBalancingPolicy = new TokenAwarePolicy(loadBalancingPolicy);\n        }\n        else if (loadBalancingPolicy != null && Boolean.valueOf(isLatencyAware))\n        {\n            loadBalancingPolicy = LatencyAwarePolicy.builder(loadBalancingPolicy).build();\n        }\n\n        if (loadBalancingPolicy != null && whiteList != null)\n        {\n            Collection<InetSocketAddress> whiteListCollection = buildWhiteListCollection(whiteList);\n\n            loadBalancingPolicy = new WhiteListPolicy(loadBalancingPolicy, whiteListCollection);\n        }\n\n        if (loadBalancingPolicy != null && hostFilterPolicy != null)\n        {\n            Predicate<com.datastax.driver.core.Host> predicate = getHostFilterPredicate(hostFilterPolicy);\n\n            loadBalancingPolicy = new HostFilterPolicy(loadBalancingPolicy, predicate);\n        }\n\n        return loadBalancingPolicy;\n    }\n\n    /**\n     * Gets the host filter predicate.\n     * \n     * @param hostFilterPolicy\n     *            the host filter policy\n     * @return the host filter predicate\n     */\n    private Predicate<com.datastax.driver.core.Host> getHostFilterPredicate(String hostFilterPolicy)\n    {\n        Predicate<com.datastax.driver.core.Host> predicate = null;\n        Method getter = null;\n        Class<?> hostFilterClazz = null;\n        try\n        {\n\n            hostFilterClazz = Class.forName(hostFilterPolicy);\n            getter = hostFilterClazz.getDeclaredMethod(GET_INSTANCE);\n\n            predicate = (Predicate<com.datastax.driver.core.Host>) getter.invoke(KunderaCoreUtils\n                    .createNewInstance(hostFilterClazz));\n        }\n        catch (ClassNotFoundException e)\n        {\n            logger.error(e.getMessage());\n            throw new KunderaException(\"Please make sure class \" + hostFilterPolicy\n                    + \" set in property file exists in classpath \" + e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            logger.error(e.getMessage());\n            throw new KunderaException(\"Method \" + getter.getName() + \" must be declared public \" + e.getMessage());\n        }\n        catch (NoSuchMethodException e)\n        {\n            logger.error(e.getMessage());\n            throw new KunderaException(\"Please make sure getter method of \" + hostFilterClazz.getSimpleName()\n                    + \" is named \\\"getInstance()\\\"\");\n        }\n        catch (InvocationTargetException e)\n        {\n            logger.error(e.getMessage());\n            throw new KunderaException(\"Error while executing \\\"getInstance()\\\" method of Class \"\n                    + hostFilterClazz.getSimpleName() + \": \" + e.getMessage());\n        }\n        catch (SecurityException e)\n        {\n            logger.error(e.getMessage());\n            throw new KunderaException(\"Encountered security exception while accessing the method: \"\n                    + \"\\\"getInstance()\\\"\" + e.getMessage());\n        }\n        return predicate;\n    }\n\n    /**\n     * Builds the white list collection.\n     * \n     * @param whiteList\n     *            the white list\n     * @return the collection\n     */\n    private Collection<InetSocketAddress> buildWhiteListCollection(String whiteList)\n    {\n        String[] list = whiteList.split(Constants.COMMA);\n        Collection<InetSocketAddress> whiteListCollection = new ArrayList<InetSocketAddress>();\n\n        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(getPersistenceUnit());\n        Properties props = persistenceUnitMetadata.getProperties();\n        int defaultPort = 9042;\n\n        if (externalProperties != null && externalProperties.get(PersistenceProperties.KUNDERA_PORT) != null)\n        {\n            try\n            {\n                defaultPort = Integer.parseInt((String) externalProperties.get(PersistenceProperties.KUNDERA_PORT));\n            }\n            catch (NumberFormatException e)\n            {\n                logger.error(\"Port in persistence.xml should be integer\");\n            }\n        }\n\n        else\n        {\n            try\n            {\n                defaultPort = Integer.parseInt((String) props.get(PersistenceProperties.KUNDERA_PORT));\n            }\n            catch (NumberFormatException e)\n            {\n                logger.error(\"Port in persistence.xml should be integer\");\n            }\n        }\n\n        for (String node : list)\n        {\n            if (node.indexOf(Constants.COLON) > 0)\n            {\n                String[] parts = node.split(Constants.COLON);\n                whiteListCollection.add(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));\n            }\n            else\n            {\n                whiteListCollection.add(new InetSocketAddress(node, defaultPort));\n            }\n        }\n        return whiteListCollection;\n    }\n\n    /**\n     * Gets the policy.\n     * \n     * @param policy\n     *            the policy\n     * @param props\n     *            the props\n     * @return the policy\n     */\n    private com.datastax.driver.core.policies.ReconnectionPolicy getPolicy(ReconnectionPolicy policy, Properties props)\n    {\n        com.datastax.driver.core.policies.ReconnectionPolicy reconnectionPolicy = null;\n        switch (policy)\n        {\n        case ConstantReconnectionPolicy:\n            String property = props.getProperty(\"constantDelayMs\");\n            long constantDelayMs = property != null ? new Long(property) : 0l;\n            reconnectionPolicy = new ConstantReconnectionPolicy(constantDelayMs);\n            break;\n\n        case ExponentialReconnectionPolicy:\n            String baseDelayMsAsStr = props.getProperty(\"baseDelayMs\");\n            String maxDelayMsAsStr = props.getProperty(\"maxDelayMs\");\n            if (!StringUtils.isBlank(baseDelayMsAsStr) && !StringUtils.isBlank(maxDelayMsAsStr))\n            {\n                long baseDelayMs = new Long(baseDelayMsAsStr);\n                long maxDelayMs = new Long(maxDelayMsAsStr);\n                reconnectionPolicy = new ExponentialReconnectionPolicy(baseDelayMs, maxDelayMs);\n            }\n            break;\n\n        default:\n            break;\n        }\n\n        return reconnectionPolicy;\n    }\n\n    /**\n     * Gets the policy.\n     * \n     * @param policy\n     *            the policy\n     * @param props\n     *            the props\n     * @return the policy\n     * @throws Exception\n     *             the exception\n     */\n    private com.datastax.driver.core.policies.RetryPolicy getPolicy(RetryPolicy policy, Properties props)\n    {\n        com.datastax.driver.core.policies.RetryPolicy retryPolicy = null;\n\n        String isLoggingRetry = (String) props.get(\"isLoggingRetry\");\n\n        switch (policy)\n        {\n        case DowngradingConsistencyRetryPolicy:\n            retryPolicy = DowngradingConsistencyRetryPolicy.INSTANCE;\n            break;\n\n        case FallthroughRetryPolicy:\n            retryPolicy = FallthroughRetryPolicy.INSTANCE;\n            break;\n\n        case Custom:\n            retryPolicy = getCustomRetryPolicy(props);\n            break;\n\n        default:\n            break;\n        }\n\n        if (retryPolicy != null && Boolean.valueOf(isLoggingRetry))\n        {\n            retryPolicy = new LoggingRetryPolicy(retryPolicy);\n        }\n\n        return retryPolicy;\n\n    }\n\n    /**\n     * Gets the custom retry policy.\n     * \n     * @param props\n     *            the props\n     * @return the custom retry policy\n     * @throws ClassNotFoundException\n     * @throws IllegalAccessException\n     * @throws NoSuchMethodException\n     * @throws InvocationTargetException\n     * @throws Exception\n     *             the exception\n     */\n    private com.datastax.driver.core.policies.RetryPolicy getCustomRetryPolicy(Properties props)\n\n    {\n        String customRetryPolicy = (String) props.get(CUSTOM_RETRY_POLICY);\n        Class<?> clazz = null;\n        Method getter = null;\n        try\n        {\n            clazz = Class.forName(customRetryPolicy);\n            com.datastax.driver.core.policies.RetryPolicy retryPolicy = (com.datastax.driver.core.policies.RetryPolicy) KunderaCoreUtils\n                    .createNewInstance(clazz);\n            if (retryPolicy != null)\n            {\n                return retryPolicy;\n            }\n            getter = clazz.getDeclaredMethod(GET_INSTANCE);\n            return (com.datastax.driver.core.policies.RetryPolicy) getter.invoke(null, (Object[]) null);\n        }\n        catch (ClassNotFoundException e)\n        {\n            logger.error(e.getMessage());\n            throw new KunderaException(\"Please make sure class \" + customRetryPolicy\n                    + \" set in property file exists in classpath \" + e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            logger.error(e.getMessage());\n            throw new KunderaException(\"Method \" + getter.getName() + \" must be declared public \" + e.getMessage());\n        }\n        catch (NoSuchMethodException e)\n        {\n            logger.error(e.getMessage());\n            throw new KunderaException(\"Please make sure getter method of \" + clazz.getSimpleName()\n                    + \" is named \\\"getInstance()\\\"\");\n        }\n        catch (InvocationTargetException e)\n        {\n            logger.error(e.getMessage());\n            throw new KunderaException(\"Error while executing \\\"getInstance()\\\" method of Class \"\n                    + clazz.getSimpleName() + \": \" + e.getMessage());\n        }\n    }\n\n    /**\n     * Gets the socket options.\n     * \n     * @param connectionProperties\n     *            the connection properties\n     * @return the socket options\n     */\n    private SocketOptions getSocketOptions(Properties connectionProperties)\n    {\n        // SocketOptions\n        SocketOptions socketConfig = new SocketOptions();\n\n        String connectTimeoutMillis = connectionProperties.getProperty(CassandraConstants.SOCKET_TIMEOUT);\n        String readTimeoutMillis = connectionProperties.getProperty(\"readTimeoutMillis\");\n        String keepAlive = connectionProperties.getProperty(\"keepAlive\");\n        String reuseAddress = connectionProperties.getProperty(\"reuseAddress\");\n        String soLinger = connectionProperties.getProperty(\"soLinger\");\n        String tcpNoDelay = connectionProperties.getProperty(\"tcpNoDelay\");\n        String receiveBufferSize = connectionProperties.getProperty(\"receiveBufferSize\");\n        String sendBufferSize = connectionProperties.getProperty(\"sendBufferSize\");\n\n        if (!StringUtils.isBlank(connectTimeoutMillis))\n        {\n            socketConfig.setConnectTimeoutMillis(new Integer(connectTimeoutMillis));\n        }\n\n        if (!StringUtils.isBlank(readTimeoutMillis))\n        {\n            socketConfig.setReadTimeoutMillis(new Integer(readTimeoutMillis));\n        }\n\n        if (!StringUtils.isBlank(keepAlive))\n        {\n            socketConfig.setKeepAlive(new Boolean(keepAlive));\n        }\n\n        if (!StringUtils.isBlank(reuseAddress))\n        {\n            socketConfig.setReuseAddress(new Boolean(reuseAddress));\n        }\n\n        if (!StringUtils.isBlank(soLinger))\n        {\n            socketConfig.setSoLinger(new Integer(soLinger));\n        }\n\n        if (!StringUtils.isBlank(tcpNoDelay))\n        {\n            socketConfig.setTcpNoDelay(new Boolean(tcpNoDelay));\n        }\n\n        if (!StringUtils.isBlank(receiveBufferSize))\n        {\n            socketConfig.setReceiveBufferSize(new Integer(receiveBufferSize));\n        }\n\n        if (!StringUtils.isBlank(sendBufferSize))\n        {\n            socketConfig.setSendBufferSize(new Integer(sendBufferSize));\n        }\n\n        return socketConfig;\n    }\n\n    /**\n     * Gets the pooling options.\n     * \n     * @param connectionProperties\n     *            the connection properties\n     * @return the pooling options\n     */\n    private PoolingOptions getPoolingOptions(Properties connectionProperties)\n    {\n        // minSimultaneousRequests, maxSimultaneousRequests, coreConnections,\n        // maxConnections\n\n        PoolingOptions options = new PoolingOptions();\n\n        String hostDistance = connectionProperties.getProperty(\"hostDistance\");\n        String maxConnectionsPerHost = connectionProperties.getProperty(\"maxConnectionsPerHost\");\n        String maxRequestsPerConnection = connectionProperties.getProperty(\"maxRequestsPerConnection\");\n        String coreConnections = connectionProperties.getProperty(\"coreConnections\");\n\n        if (!StringUtils.isBlank(hostDistance))\n        {\n            HostDistance hostDist = HostDistance.valueOf(hostDistance.toUpperCase());\n            if (!StringUtils.isBlank(coreConnections))\n            {\n                options.setCoreConnectionsPerHost(HostDistance.LOCAL, new Integer(coreConnections));\n            }\n\n            if (!StringUtils.isBlank(maxConnectionsPerHost))\n            {\n                options.setMaxConnectionsPerHost(hostDist, new Integer(maxConnectionsPerHost));\n            }\n\n            if (!StringUtils.isBlank(maxRequestsPerConnection))\n            {\n                options.setMaxRequestsPerConnection(hostDist, new Integer(maxRequestsPerConnection));\n            }\n        }\n        return options;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/main/java/com/impetus/kundera/client/cassandra/dsdriver/DSClientUtilities.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.cassandra.dsdriver;\n\nimport java.lang.reflect.Field;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Embeddable;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.cassandra.db.marshal.BytesType;\nimport org.apache.cassandra.utils.ByteBufferUtil;\n\nimport com.datastax.driver.core.DataType.Name;\nimport com.datastax.driver.core.Row;\nimport com.datastax.driver.core.UDTValue;\nimport com.impetus.client.cassandra.schemamanager.CassandraDataTranslator;\nimport com.impetus.client.cassandra.schemamanager.CassandraDataTranslator.CassandraType;\nimport com.impetus.client.cassandra.schemamanager.CassandraValidationClassMapper;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.property.accessor.CharAccessor;\nimport com.impetus.kundera.property.accessor.EnumAccessor;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * Utility class.\n * \n * @author vivek.mishra\n * \n */\npublic final class DSClientUtilities\n{\n\n    /**\n     * assign value to provided entity instance else return value of mapped java\n     * type.\n     * \n     * @param row\n     *            DS row\n     * @param entity\n     *            JPA entity\n     * @param metadata\n     *            entity's metadata\n     * @param dataType\n     *            data type\n     * @param entityType\n     *            entity type from metamodel\n     * @param columnName\n     *            jpa column name\n     * @param member\n     *            the member\n     * @param metamodel\n     *            the metamodel\n     * @return modified entity instance with data type value. If entity is null\n     *         then returns value of mapped java class.\n     */\n    @SuppressWarnings(\"unchecked\")\n    static Object assign(Row row, Object entity, EntityMetadata metadata, Name dataType, EntityType entityType,\n            String columnName, Field member, MetamodelImpl metamodel)\n    {\n        String fieldName = null;\n\n        // if metadata is null or it is relational attribute do not set\n        // fieldName and member.\n\n        if (metadata != null)\n        {\n            if (columnName.equals(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName()))\n            {\n                entity = KunderaCoreUtils.initialize(metadata, entity, null);\n                fieldName = metadata.getIdAttribute().getName();\n                member = (Field) metadata.getIdAttribute().getJavaMember();\n            }\n            else if (metadata.getRelationNames() == null || !metadata.getRelationNames().contains(columnName))\n            {\n                fieldName = metadata.getFieldName(columnName);\n                if (fieldName != null && entityType != null)\n                {\n                    entity = KunderaCoreUtils.initialize(metadata, entity, null);\n                    member = (Field) entityType.getAttribute(fieldName).getJavaMember();\n                }\n            }\n        }\n\n        // Field member=null;\n        /*\n         * if (metadata != null && (metadata.getRelationNames() == null ||\n         * !metadata.getRelationNames().contains(columnName))) { if\n         * (!columnName.equals(((AbstractAttribute)\n         * metadata.getIdAttribute()).getJPAColumnName())) { fieldName =\n         * metadata.getFieldName(columnName); if (fieldName != null &&\n         * entityType != null) { entity =\n         * CassandraUtilities.initialize(metadata, entity, null); member =\n         * (Field) entityType.getAttribute(fieldName).getJavaMember(); } } else\n         * { entity = CassandraUtilities.initialize(metadata, entity, null);\n         * fieldName = metadata.getIdAttribute().getName(); member = (Field)\n         * metadata.getIdAttribute().getJavaMember(); }\n         * \n         * }\n         */\n        Object retVal = null;\n        \n        if(row.isNull(columnName)){\n        \treturn entity;\n        }\n        \n        switch (dataType)\n        {\n        case BLOB:\n        case CUSTOM:\n            retVal = row.getBytes(columnName);\n            if (member != null && retVal != null && entity != null)\n            {\n                PropertyAccessorHelper.set(entity, member, ((ByteBuffer) retVal).array());\n            }\n            break;\n\n        case BOOLEAN:\n            retVal = row.getBool(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case BIGINT:\n        case COUNTER:\n            retVal = row.getLong(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case DECIMAL:\n            retVal = row.getDecimal(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case DOUBLE:\n            retVal = row.getDouble(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case FLOAT:\n            retVal = row.getFloat(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case INET:\n            retVal = row.getInet(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case INT:\n            retVal = row.getInt(columnName);\n            retVal = setIntValue(member, retVal);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case ASCII:\n        case TEXT:\n        case VARCHAR:\n            retVal = row.getString(columnName);\n            retVal = setTextValue(entity, member, retVal);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case TIMESTAMP:\n            retVal = row.getTimestamp(columnName);\n            if (retVal != null && member != null)\n                retVal = CassandraDataTranslator.decompose(member.getType(),\n                        ByteBufferUtil.bytes(((Date) retVal).getTime()).array(), true);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case VARINT:\n            retVal = row.getVarint(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case UUID:\n        case TIMEUUID:\n            retVal = row.getUUID(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case LIST:\n            Class listAttributeTypeClass = PropertyAccessorHelper.getGenericClass(member);\n            Class listClazz = null;\n            boolean isElementCollectionList = false;\n            if (listAttributeTypeClass.isAssignableFrom(byte[].class))\n            {\n\n                listClazz = ByteBuffer.class;\n            }\n            else if (listAttributeTypeClass.isAnnotationPresent(Embeddable.class))\n            {\n                isElementCollectionList = true;\n                listClazz = UDTValue.class;\n            }\n            else\n            {\n                listClazz = listAttributeTypeClass;\n            }\n            retVal = row.getList(columnName, listClazz);\n            Collection resultList = new ArrayList();\n            if (isElementCollectionList)\n            {\n                Iterator collectionItems = ((Collection) retVal).iterator();\n                while (collectionItems.hasNext())\n                {\n                    resultList.add(setUDTValue(entity, listAttributeTypeClass, (UDTValue) collectionItems.next(),\n                            metamodel));\n                }\n            }\n\n            if (retVal != null && !((List) retVal).isEmpty() && !isElementCollectionList)\n            {\n                if (listAttributeTypeClass.isAssignableFrom(byte[].class))\n                {\n                    setFieldValue(entity, member, CassandraDataTranslator.marshalCollection(BytesType.class,\n                            (Collection) retVal, listAttributeTypeClass, ArrayList.class));\n                }\n                else\n                {\n                    Iterator collectionItems = ((Collection) retVal).iterator();\n                    while (collectionItems.hasNext())\n                    {\n                        resultList.add(collectionItems.next());\n                    }\n                    setFieldValue(entity, member, resultList);\n                }\n\n            }\n            else if (retVal != null && !((Collection) retVal).isEmpty())\n            {\n                setFieldValue(entity, member, resultList);\n            }\n            break;\n\n        case SET:\n            Class setAttributeTypeClass = PropertyAccessorHelper.getGenericClass(member);\n            Class setClazz = null;\n            boolean isElementCollectionSet = false;\n            if (setAttributeTypeClass.isAssignableFrom(byte[].class))\n            {\n\n                setClazz = ByteBuffer.class;\n            }\n            else if (setAttributeTypeClass.isAnnotationPresent(Embeddable.class))\n            {\n                isElementCollectionSet = true;\n                setClazz = UDTValue.class;\n            }\n            else\n            {\n                setClazz = setAttributeTypeClass;\n            }\n            retVal = row.getSet(columnName, setClazz);\n            Collection resultSet = new HashSet();\n            if (isElementCollectionSet)\n            {\n                Iterator collectionItems = ((Collection) retVal).iterator();\n                while (collectionItems.hasNext())\n                {\n                    resultSet.add(setUDTValue(entity, setAttributeTypeClass, (UDTValue) collectionItems.next(),\n                            metamodel));\n                }\n            }\n\n            if (retVal != null && !((Set) retVal).isEmpty() && !isElementCollectionSet)\n            {\n                if (setAttributeTypeClass.isAssignableFrom(byte[].class))\n                {\n                    setFieldValue(entity, member, CassandraDataTranslator.marshalCollection(BytesType.class,\n                            (Collection) retVal, setAttributeTypeClass, HashSet.class));\n                }\n                else\n                {\n                    Iterator collectionItems = ((Collection) retVal).iterator();\n                    while (collectionItems.hasNext())\n                    {\n                        resultSet.add(collectionItems.next());\n                    }\n                    setFieldValue(entity, member, resultSet);\n                }\n            }\n            else if (retVal != null && !((Collection) retVal).isEmpty())\n            {\n                setFieldValue(entity, member, resultSet);\n            }\n            break;\n        /*\n         * ASCII, BIGINT, BLOB, BOOLEAN, COUNTER, DECIMAL, DOUBLE, FLOAT, INET,\n         * INT, TEXT, TIMESTAMP, UUID, VARCHAR, VARINT, TIMEUUID, LIST, SET,\n         * MAP, CUSTOM;\n         */\n        case MAP:\n            List<Class<?>> mapGenericClasses = PropertyAccessorHelper.getGenericClasses(member);\n            \n            if(mapGenericClasses.isEmpty()){\n            \t//TODO: get map types from column metadata where member is null (Scalar queries)\n            \tbreak;\n            }\n\n            Class keyClass = CassandraValidationClassMapper.getValidationClassInstance(mapGenericClasses.get(0), true);\n            Class valueClass = CassandraValidationClassMapper\n                    .getValidationClassInstance(mapGenericClasses.get(1), true);\n            Class mapValueClazz = null;\n            boolean isElementCollectionMap = false;\n            if (mapGenericClasses.get(1).isAssignableFrom(byte[].class))\n            {\n\n                mapValueClazz = ByteBuffer.class;\n            }\n            else if (mapGenericClasses.get(1).isAnnotationPresent(Embeddable.class))\n            {\n                isElementCollectionMap = true;\n                mapValueClazz = UDTValue.class;\n            }\n            else\n            {\n                mapValueClazz = mapGenericClasses.get(1);\n            }\n            retVal = row.getMap(columnName, mapGenericClasses.get(0).isAssignableFrom(byte[].class) ? ByteBuffer.class\n                    : mapGenericClasses.get(0), mapValueClazz);\n\n            Map resultMap = new HashMap();\n\n            if (isElementCollectionMap)\n            {\n                Iterator keys = ((Map) retVal).keySet().iterator();\n                while (keys.hasNext())\n                {\n                    Object keyValue = keys.next();\n                    resultMap.put(\n                            keyValue,\n                            setUDTValue(entity, mapGenericClasses.get(1), (UDTValue) ((Map) retVal).get(keyValue),\n                                    metamodel));\n                }\n            }\n\n            boolean isByteBuffer = mapGenericClasses.get(0).isAssignableFrom(byte[].class)\n                    || mapGenericClasses.get(1).isAssignableFrom(byte[].class);\n\n            // set the values.\n            if (retVal != null && !((Map) retVal).isEmpty() && !isElementCollectionMap)\n            {\n                if (isByteBuffer)\n                {\n                    setFieldValue(entity, member,\n                            CassandraDataTranslator.marshalMap(mapGenericClasses, keyClass, valueClass, (Map) retVal));\n                }\n                else\n                {\n                    Iterator keys = ((Map) retVal).keySet().iterator();\n                    while (keys.hasNext())\n                    {\n                        Object keyValue = keys.next();\n                        resultMap.put(keyValue, ((Map) retVal).get(keyValue));\n                    }\n                    setFieldValue(entity, member, resultMap);\n                }\n            }\n            else if (retVal != null && !((Map) retVal).isEmpty())\n            {\n                setFieldValue(entity, member, resultMap);\n            }\n            break;\n        case UDT:\n            retVal = row.getUDTValue(columnName);\n            setFieldValue(entity, member,\n                    retVal != null ? setUDTValue(entity, member.getType(), (UDTValue) retVal, metamodel) : null);\n            break;\n        }\n\n        return entity != null ? entity : retVal;\n    }\n\n    /**\n     * Sets the udt value.\n     * \n     * @param entity\n     *            the entity\n     * @param embeddedClass\n     *            the embedded class\n     * @param udt\n     *            the udt\n     * @param metaModel\n     *            the meta model\n     * @return the object\n     */\n    private static Object setUDTValue(Object entity, Class embeddedClass, UDTValue udt, MetamodelImpl metaModel)\n    {\n        Object embeddedObject = KunderaCoreUtils.createNewInstance(embeddedClass);\n        EmbeddableType embeddable = metaModel.embeddable(embeddedClass);\n\n        for (Object subAttribute : embeddable.getAttributes())\n        {\n            Field embeddableColumn = (Field) ((AbstractAttribute) subAttribute).getJavaMember();\n            if (metaModel.isEmbeddable(embeddableColumn.getType()))\n            {\n                UDTValue subUDT = udt.getUDTValue(((AbstractAttribute) subAttribute).getJPAColumnName());\n\n                setFieldValue(embeddedObject, embeddableColumn,\n                        setUDTValue(embeddedObject, embeddableColumn.getType(), subUDT, metaModel));\n            }\n            else\n            {\n                setBasicValue(embeddedObject, embeddableColumn, ((AbstractAttribute) subAttribute).getJPAColumnName(),\n                        udt, CassandraDataTranslator.getCassandraDataTypeClass(embeddableColumn.getType()), metaModel);\n            }\n\n        }\n        return embeddedObject;\n\n    }\n\n    /**\n     * Sets the basic value.\n     * \n     * @param entity\n     *            the entity\n     * @param member\n     *            the member\n     * @param columnName\n     *            the column name\n     * @param row\n     *            the row\n     * @param dataType\n     *            the data type\n     * @param metamodel\n     *            the metamodel\n     */\n    private static void setBasicValue(Object entity, Field member, String columnName, UDTValue row,\n            CassandraType dataType, MetamodelImpl metamodel)\n    {\n    \tif(row.isNull(columnName)){\n        \treturn;\n        }\n        Object retVal = null;\n        switch (dataType)\n        {\n        case BYTES:\n            // case CUSTOM:\n            retVal = row.getBytes(columnName);\n            if (retVal != null)\n            {\n                setFieldValue(entity, member, ((ByteBuffer) retVal).array());\n            }\n            break;\n\n        case BOOLEAN:\n            retVal = row.getBool(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case BIGINT:\n            // bigints in embeddables and element collections are mapped/defined\n            // by Long\n        case LONG:\n        case COUNTER:\n            retVal = row.getLong(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case DECIMAL:\n            retVal = row.getDecimal(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case DOUBLE:\n            retVal = row.getDouble(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case FLOAT:\n            retVal = row.getFloat(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case INET:\n            retVal = row.getInet(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case INT:\n            retVal = row.getInt(columnName);\n            retVal = setIntValue(member, retVal);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case ASCII:\n        case STRING:\n        case CHARACTER:\n            try\n            {\n                row.getBytes(columnName);\n            }\n            catch (Exception e)\n            {\n                // do nothing\n            }\n            retVal = row.getString(columnName);\n            retVal = setTextValue(entity, member, retVal);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case TIMESTAMP:\n            retVal = row.getTimestamp(columnName);\n            if (retVal != null && member != null)\n                retVal = CassandraDataTranslator.decompose(member.getType(),\n                        ByteBufferUtil.bytes(((Date) retVal).getTime()).array(), true);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case UUID:\n            // case TIMEUUID:\n            retVal = row.getUUID(columnName);\n            setFieldValue(entity, member, retVal);\n            break;\n\n        case LIST:\n            Class listAttributeTypeClass = PropertyAccessorHelper.getGenericClass(member);\n            Class listClazz = null;\n            boolean isElementCollectionList = false;\n            if (listAttributeTypeClass.isAssignableFrom(byte[].class))\n            {\n\n                listClazz = ByteBuffer.class;\n            }\n            else if (listAttributeTypeClass.isAnnotationPresent(Embeddable.class))\n            {\n                isElementCollectionList = true;\n                listClazz = UDTValue.class;\n            }\n            else\n            {\n                listClazz = listAttributeTypeClass;\n            }\n            retVal = row.getList(columnName, listClazz);\n            Collection resultList = new ArrayList();\n            if (isElementCollectionList)\n            {\n                Iterator collectionItems = ((Collection) retVal).iterator();\n                while (collectionItems.hasNext())\n                {\n                    resultList.add(setUDTValue(entity, listAttributeTypeClass, (UDTValue) collectionItems.next(),\n                            metamodel));\n                }\n            }\n\n            if (retVal != null && !((List) retVal).isEmpty() && !isElementCollectionList)\n            {\n                if (listAttributeTypeClass.isAssignableFrom(byte[].class))\n                {\n                    setFieldValue(entity, member, CassandraDataTranslator.marshalCollection(BytesType.class,\n                            (Collection) retVal, listAttributeTypeClass, ArrayList.class));\n                }\n                else\n                {\n                    Iterator collectionItems = ((Collection) retVal).iterator();\n                    while (collectionItems.hasNext())\n                    {\n                        resultList.add(collectionItems.next());\n                    }\n                    setFieldValue(entity, member, resultList);\n                }\n\n            }\n            else if (retVal != null && !((Collection) retVal).isEmpty())\n            {\n                setFieldValue(entity, member, resultList);\n            }\n            break;\n\n        case SET:\n            Class setAttributeTypeClass = PropertyAccessorHelper.getGenericClass(member);\n            Class setClazz = null;\n            boolean isElementCollectionSet = false;\n            if (setAttributeTypeClass.isAssignableFrom(byte[].class))\n            {\n\n                setClazz = ByteBuffer.class;\n            }\n            else if (setAttributeTypeClass.isAnnotationPresent(Embeddable.class))\n            {\n                isElementCollectionSet = true;\n                setClazz = UDTValue.class;\n            }\n            else\n            {\n                setClazz = setAttributeTypeClass;\n            }\n            retVal = row.getSet(columnName, setClazz);\n            Collection resultSet = new HashSet();\n            if (isElementCollectionSet)\n            {\n                Iterator collectionItems = ((Collection) retVal).iterator();\n                while (collectionItems.hasNext())\n                {\n                    resultSet.add(setUDTValue(entity, setAttributeTypeClass, (UDTValue) collectionItems.next(),\n                            metamodel));\n                }\n            }\n\n            if (retVal != null && !((Set) retVal).isEmpty() && !isElementCollectionSet)\n            {\n                if (setAttributeTypeClass.isAssignableFrom(byte[].class))\n                {\n                    setFieldValue(entity, member, CassandraDataTranslator.marshalCollection(BytesType.class,\n                            (Collection) retVal, setAttributeTypeClass, HashSet.class));\n                }\n                else\n                {\n                    Iterator collectionItems = ((Collection) retVal).iterator();\n                    while (collectionItems.hasNext())\n                    {\n                        resultSet.add(collectionItems.next());\n                    }\n                    setFieldValue(entity, member, resultSet);\n                }\n            }\n            else if (retVal != null && !((Collection) retVal).isEmpty())\n            {\n                setFieldValue(entity, member, resultSet);\n            }\n            break;\n        /*\n         * ASCII, BIGINT, BLOB, BOOLEAN, COUNTER, DECIMAL, DOUBLE, FLOAT, INET,\n         * INT, TEXT, TIMESTAMP, UUID, VARCHAR, VARINT, TIMEUUID, LIST, SET,\n         * MAP, CUSTOM;\n         */\n        case MAP:\n            List<Class<?>> mapGenericClasses = PropertyAccessorHelper.getGenericClasses(member);\n\n            Class keyClass = CassandraValidationClassMapper.getValidationClassInstance(mapGenericClasses.get(0), true);\n            Class valueClass = CassandraValidationClassMapper\n                    .getValidationClassInstance(mapGenericClasses.get(1), true);\n            Class mapValueClazz = null;\n            boolean isElementCollectionMap = false;\n            if (mapGenericClasses.get(1).isAssignableFrom(byte[].class))\n            {\n\n                mapValueClazz = ByteBuffer.class;\n            }\n            else if (mapGenericClasses.get(1).isAnnotationPresent(Embeddable.class))\n            {\n                isElementCollectionMap = true;\n                mapValueClazz = UDTValue.class;\n            }\n            else\n            {\n                mapValueClazz = mapGenericClasses.get(1);\n            }\n            retVal = row.getMap(columnName, mapGenericClasses.get(0).isAssignableFrom(byte[].class) ? ByteBuffer.class\n                    : mapGenericClasses.get(0), mapValueClazz);\n\n            Map resultMap = new HashMap();\n\n            if (isElementCollectionMap)\n            {\n                Iterator keys = ((Map) retVal).keySet().iterator();\n                while (keys.hasNext())\n                {\n                    Object keyValue = keys.next();\n                    resultMap.put(\n                            keyValue,\n                            setUDTValue(entity, mapGenericClasses.get(1), (UDTValue) ((Map) retVal).get(keyValue),\n                                    metamodel));\n                }\n            }\n\n            boolean isByteBuffer = mapGenericClasses.get(0).isAssignableFrom(byte[].class)\n                    || mapGenericClasses.get(1).isAssignableFrom(byte[].class);\n\n            // set the values.\n            if (retVal != null && !((Map) retVal).isEmpty() && !isElementCollectionMap)\n            {\n                if (isByteBuffer)\n                {\n                    setFieldValue(entity, member,\n                            CassandraDataTranslator.marshalMap(mapGenericClasses, keyClass, valueClass, (Map) retVal));\n                }\n                else\n                {\n                    Iterator keys = ((Map) retVal).keySet().iterator();\n                    while (keys.hasNext())\n                    {\n                        Object keyValue = keys.next();\n                        resultMap.put(keyValue, ((Map) retVal).get(keyValue));\n                    }\n                    setFieldValue(entity, member, resultMap);\n                }\n            }\n            else if (retVal != null && !((Map) retVal).isEmpty())\n            {\n                setFieldValue(entity, member, resultMap);\n            }\n            break;\n        }\n\n    }\n\n    /**\n     * Sets the int value.\n     * \n     * @param member\n     *            the member\n     * @param retVal\n     *            the ret val\n     * @return the object\n     */\n    private static Object setIntValue(Field member, Object retVal)\n    {\n        if (member != null)\n        {\n            if (member.getType().isAssignableFrom(byte.class))\n            {\n                retVal = ((Integer) retVal).byteValue();\n            }\n            else if (member.getType().isAssignableFrom(short.class))\n            {\n                retVal = ((Integer) retVal).shortValue();\n            }\n        }\n        return retVal;\n    }\n\n    /**\n     * Sets the text value.\n     * \n     * @param entity\n     *            the entity\n     * @param member\n     *            the member\n     * @param retVal\n     *            the ret val\n     * @return the object\n     */\n    private static Object setTextValue(Object entity, Field member, Object retVal)\n    {\n        if (member != null && member.getType().isEnum())\n        {\n            EnumAccessor accessor = new EnumAccessor();\n            if (member != null)\n            {\n                retVal = accessor.fromString(member.getType(), (String) retVal);\n            }\n        }\n        else if (member != null\n                && (member.getType().isAssignableFrom(char.class) || member.getType().isAssignableFrom(Character.class)))\n        {\n            retVal = new CharAccessor().fromString(member.getType(), (String) retVal);\n        }\n        return retVal;\n    }\n\n    /**\n     * Sets the field value.\n     * \n     * @param entity\n     *            the entity\n     * @param member\n     *            the member\n     * @param retVal\n     *            the ret val\n     */\n    private static void setFieldValue(Object entity, Field member, Object retVal)\n    {\n        if (member != null && retVal != null && entity != null)\n        {\n            PropertyAccessorHelper.set(entity, member, retVal);\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/main/java/com/impetus/kundera/client/cassandra/dsdriver/DSIdGenerator.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.dsdriver;\n\nimport java.util.UUID;\n\nimport com.datastax.driver.core.ResultSet;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.generator.AutoGenerator;\n\n/**\n * The Class DSIdGenerator.\n * \n * @author: karthikp.manchala\n */\npublic class DSIdGenerator implements AutoGenerator\n{\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.AutoGenerator#generate(com.impetus.kundera\n     * .client.Client, java.lang.Object)\n     */\n    @Override\n    public Object generate(Client<?> client, String dataType)\n    {\n\n        final String generatedId = \"Select now() from system_schema.columns\";\n        ResultSet rSet = ((DSClient) client).execute(generatedId, null);\n\n        UUID uuid = rSet.iterator().next().getUUID(0);\n        return uuid;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/main/java/com/impetus/kundera/client/cassandra/dsdriver/DSResultIterator.java",
    "content": "package com.impetus.kundera.client.cassandra.dsdriver;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.EntityType;\n\nimport com.datastax.driver.core.ResultSet;\nimport com.datastax.driver.core.Row;\nimport com.datastax.driver.core.SimpleStatement;\nimport com.datastax.driver.core.Statement;\nimport com.impetus.client.cassandra.query.ResultIterator;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.query.Query;\n\n/**\n * The Class DSResultIterator.\n * \n * @author karthikp.manchala\n * \n * @param <E>\n *            the element type\n */\npublic class DSResultIterator<E> extends ResultIterator<E>\n{\n\n    /** The r set. */\n    private ResultSet rSet;\n\n    /** The row iter. */\n    private Iterator<Row> rowIter;\n\n    /**\n     * Constructor with parameters.\n     * \n     * @param query\n     *            the query\n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @param reader\n     *            the reader\n     * @param fetchSize\n     *            the fetch size\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    DSResultIterator(final Query query, final EntityMetadata m, final Client client, final EntityReader reader,\n            final int fetchSize, final KunderaMetadata kunderaMetadata)\n    {\n        super((javax.persistence.Query) query, m, client, reader, fetchSize, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.query.ResultIterator#hasNext()\n     */\n    @Override\n    public boolean hasNext()\n    {\n        if (fetchSize != 0 && (count % fetchSize) == 0)\n        {\n            try\n            {\n                results = populateEntities(entityMetadata, client);\n                count = 0;\n            }\n            catch (Exception e)\n            {\n                throw new PersistenceException(\"Error while scrolling over results, Caused by :.\", e);\n            }\n        }\n        if (results != null && !results.isEmpty() && count < results.size())\n        {\n            return true;\n        }\n\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.query.ResultIterator#next()\n     */\n    @Override\n    public E next()\n    {\n        if (results != null && !results.isEmpty() && count < results.size())\n        {\n            current = results.get(count++);\n            return current;\n        }\n        else\n        {\n            throw new NoSuchElementException(\n                    \"No object found in the iterator... Use hasNext() to check for valid next()\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.cassandra.query.ResultIterator#populateEntities(com\n     * .impetus.kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List<E> populateEntities(EntityMetadata m, Client client) throws Exception\n    {\n        int count = 0;\n        List results = new ArrayList();\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n        Map<String, Object> relationalValues = new HashMap<String, Object>();\n        if (rSet == null)\n        {\n            String parsedQuery = query.onQueryOverCQL3(m, client, metaModel, null);\n            Statement statement = new SimpleStatement(parsedQuery);\n            statement.setFetchSize(fetchSize);\n            rSet = ((DSClient) client).executeStatement(statement);\n            rowIter = rSet.iterator();\n        }\n        while (rowIter.hasNext() && count++ < fetchSize)\n        {\n            Object entity = null;\n            Row row = rowIter.next();\n            ((DSClient) client).populateObjectFromRow(entityMetadata, metaModel, entityType, results, relationalValues,\n                    entity, row);\n        }\n        return results;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/crud/compositeType/association/AddressOTOPK.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.crud.compositeType.association;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * Address One-To-One entity\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"AddressOTOPK\")\npublic class AddressOTOPK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @OneToOne(mappedBy = \"address\", fetch = FetchType.LAZY)\n    private UserOTOPK user;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public UserOTOPK getUser()\n    {\n        return user;\n    }\n\n    public void setUser(UserOTOPK user)\n    {\n        this.user = user;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/crud/compositeType/association/CassandraAddressUniOTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.crud.compositeType.association;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Address uni directional One-To-Many entity\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"CassandraAddressUniOTM\")\npublic class CassandraAddressUniOTM\n{\n\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/crud/compositeType/association/CassandraCompoundKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.crud.compositeType.association;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * Embeddable entity\n * @author vivek.mishra\n */\n@Embeddable\npublic class CassandraCompoundKey\n{\n    @Column\n    private String userId;\n\n    @Column\n    private int tweetId;\n\n    @Column\n    private UUID timeLineId;\n\n    @Column\n    private transient String fullName;\n\n    /**\n     * \n     */\n    public CassandraCompoundKey()\n    {\n    }\n\n    /**\n     * @param userId\n     * @param tweetId\n     * @param timeLineId\n     */\n    public CassandraCompoundKey(String userId, int tweetId, UUID timeLineId)\n    {\n        this.userId = userId;\n        this.tweetId = tweetId;\n        this.timeLineId = timeLineId;\n        this.fullName = \"kuldeep\";\n    }\n\n    /**\n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * @return the tweetId\n     */\n    public int getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * @return the timeLineId\n     */\n    public UUID getTimeLineId()\n    {\n        return timeLineId;\n    }\n\n    public String getFullName()\n    {\n        return this.fullName;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/crud/compositeType/association/CassandraEmbeddedAssociation.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.crud.compositeType.association;\n\nimport java.util.Date;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n\n\n/**\n * Embedded association enttiy\n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"CompositeUserAssociation\")\n// @Index(index = true,columns = { \"tweetBody\",\"tweetDate\" })\npublic class CassandraEmbeddedAssociation\n{\n\n    @EmbeddedId\n    private CassandraCompoundKey key;\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private Date tweetDate;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"userInfo_id\")\n    private UserInfo userInfo;\n\n    public CassandraEmbeddedAssociation()\n    {\n    }\n\n    public CassandraEmbeddedAssociation(CassandraCompoundKey key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the key\n     */\n    public CassandraCompoundKey getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n    public UserInfo getUserInfo()\n    {\n        return userInfo;\n    }\n\n    public void setUserInfo(UserInfo userInfo)\n    {\n        this.userInfo = userInfo;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/crud/compositeType/association/CassandraUserOTMTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.crud.compositeType.association;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * User One-To-Many junit.\n * @author vivek.mishra\n * \n */\npublic class CassandraUserOTMTest\n{\n\n    private static final String _KEYSPACE = \"KunderaExamples\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(_KEYSPACE);\n        Map<String, Object> puPropertiesObj = new HashMap<String, Object>();\n   \n       puPropertiesObj.put(CassandraConstants.THRIFT_PORT, \"9160\");\n       \n       \n        emf = Persistence.createEntityManagerFactory(\"ds_pu\",puPropertiesObj);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(_KEYSPACE);\n        emf.close();\n    }\n\n    @Test\n    public void test()\n    {\n        em = emf.createEntityManager();\n\n        Set<CassandraAddressUniOTM> addresses = new HashSet<CassandraAddressUniOTM>();\n\n        CassandraAddressUniOTM address1 = new CassandraAddressUniOTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"my street\");\n        CassandraAddressUniOTM address2 = new CassandraAddressUniOTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"my new street\");\n\n        addresses.add(address1);\n        addresses.add(address2);\n\n        CassandraUserUniOTM userUniOTM = new CassandraUserUniOTM();\n        userUniOTM.setPersonId(\"1\");\n        userUniOTM.setPersonName(\"kuldeep\");\n        userUniOTM.setAddresses(addresses);\n\n        em.persist(userUniOTM);\n\n        em.clear();\n\n        CassandraUserUniOTM foundObject = em.find(CassandraUserUniOTM.class, \"1\");\n        Assert.assertNotNull(foundObject);\n        Assert.assertEquals(2, foundObject.getAddresses().size());\n\n        Query q = em.createQuery(\"Select u from CassandraUserUniOTM u\");\n        List<CassandraUserUniOTM> users = q.getResultList();\n        Assert.assertNotNull(users);\n        Assert.assertEquals(1, users.size());\n        Assert.assertNotNull(users.get(0));\n        Assert.assertEquals(\"kuldeep\", users.get(0).getPersonName());\n        Assert.assertEquals(\"1\", users.get(0).getPersonId());\n        Assert.assertNotNull(users.get(0).getAddresses());\n        Assert.assertEquals(2, users.get(0).getAddresses().size());\n\n        em.remove(foundObject);\n\n        foundObject = em.find(CassandraUserUniOTM.class, \"1\");\n        Assert.assertNull(foundObject);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/crud/compositeType/association/CassandraUserUniOTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.crud.compositeType.association;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * One-To-Many entity\n \n * @author vivek.mishra\n */\n@Entity\n@Table(name = \"CassandraUserUniOTM\")\npublic class CassandraUserUniOTM\n{\n\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<CassandraAddressUniOTM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<CassandraAddressUniOTM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<CassandraAddressUniOTM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/crud/compositeType/association/UserInfo.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.crud.compositeType.association;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * User info entity\n * \n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"UserInfo\")\npublic class UserInfo\n{\n\n    @Id\n    @Column(name = \"userInfo_id\")\n    private String userInfoId;\n\n    @Column(name = \"first_name\")\n    private String firstName;\n\n    @Column(name = \"last_name\")\n    private String lastName;\n\n    @Column(name = \"age\")\n    private int age;\n\n    // height in inches.\n    @Column(name = \"height\")\n    private transient int height;\n\n    /**\n     * \n     */\n    public UserInfo()\n    {\n    }\n\n    /**\n     * @param userInfoId\n     * @param firstName\n     * @param lastName\n     * @param age\n     * @param timeLine\n     */\n    public UserInfo(String userInfoId, String firstName, String lastName, int age, int height)\n    {\n        super();\n        this.userInfoId = userInfoId;\n        this.firstName = firstName;\n        this.lastName = lastName;\n        this.age = age;\n        this.height = height;\n    }\n\n    /**\n     * @return the userInfoId\n     */\n    public String getUserInfoId()\n    {\n        return userInfoId;\n    }\n\n    /**\n     * @return the firstName\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * @return the lastName\n     */\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param firstName\n     *            the firstName to set\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the height\n     */\n    public int getHeight()\n    {\n        return height;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/crud/compositeType/association/UserInfoTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.crud.compositeType.association;\n\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * User info test.\n * \n * @author vivek.mishra\n * \n */\npublic class UserInfoTest\n{\n    private EntityManagerFactory emf;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n        Map<String, String> props = new HashMap<String, String>(1);\n        emf = Persistence.createEntityManagerFactory(\"ds_composite_pu\", props);\n    }\n\n    @Test\n    public void onCRUD()\n    {\n        EntityManager em = createEM();\n\n        // persist userinfo object only.\n        UserInfo userInfo = new UserInfo(\"mevivs_info\", \"Vivek\", \"Mishra\", 31, 68);\n        em.persist(userInfo);\n\n        em.clear();\n        em.close();\n        em = createEM();\n\n        UserInfo foundUser = em.find(UserInfo.class, userInfo.getUserInfoId());\n        Assert.assertNotNull(foundUser);\n        Assert.assertEquals(\"Mishra\", foundUser.getLastName());\n        Assert.assertEquals(\"Vivek\", foundUser.getFirstName());\n        Assert.assertEquals(31, foundUser.getAge());\n        Assert.assertEquals(0, foundUser.getHeight());\n\n        em.remove(foundUser);\n        UserInfo deletedUser = em.find(UserInfo.class, userInfo.getUserInfoId());\n        Assert.assertNull(deletedUser);\n\n        em.clear();\n        em.close();\n        em = createEM();\n\n        // Persist\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n        CassandraEmbeddedAssociation timeLine = new CassandraEmbeddedAssociation(key);\n        timeLine.setTweetBody(\"my first tweet\");\n        timeLine.setTweetDate(currentDate);\n\n        timeLine.setUserInfo(userInfo);\n        em.persist(timeLine);\n\n        em.clear();\n        em.close();\n        em = createEM();\n\n        // Find\n        CassandraEmbeddedAssociation result = em.find(CassandraEmbeddedAssociation.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(currentDate, result.getTweetDate());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(\"Vivek\", result.getUserInfo().getFirstName());\n        Assert.assertEquals(31, result.getUserInfo().getAge());\n        Assert.assertEquals(0, result.getUserInfo().getHeight());\n\n        result.getUserInfo().setFirstName(\"Kuldeep\");\n        result.getUserInfo().setAge(23);\n\n        em.merge(result);\n\n        em.clear();\n        em.close();\n        em = createEM();\n        // Find\n        result = null;\n        result = em.find(CassandraEmbeddedAssociation.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(currentDate, result.getTweetDate());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(\"Kuldeep\", result.getUserInfo().getFirstName());\n        Assert.assertEquals(23, result.getUserInfo().getAge());\n        Assert.assertEquals(0, result.getUserInfo().getHeight());\n\n        em.remove(result);\n\n        em.clear();\n        em.close();\n\n        em = createEM();\n        result = em.find(CassandraEmbeddedAssociation.class, key);\n        Assert.assertNull(result);\n\n    }\n\n    private EntityManager createEM()\n    {\n        EntityManager em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(\"ds_composite_pu\");\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n        return em;\n    }\n\n    @Test\n    public void onQuery()\n    {\n        EntityManager em = createEM();\n\n        // Persist\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        CassandraCompoundKey key = new CassandraCompoundKey(\"mevivs\", 1, timeLineId);\n        CassandraEmbeddedAssociation timeLine = new CassandraEmbeddedAssociation(key);\n        timeLine.setTweetBody(\"my first tweet\");\n        timeLine.setTweetDate(currentDate);\n\n        UserInfo userInfo = new UserInfo(\"mevivs_info\", \"Vivek\", \"Mishra\", 31, 72);\n        timeLine.setUserInfo(userInfo);\n        em.persist(timeLine);\n\n        em.clear(); // optional,just to clear persistence cache.\n        em.flush();\n\n        final String noClause = \"Select t from CassandraEmbeddedAssociation t\";\n\n        Query query = em.createQuery(noClause);\n        List<CassandraEmbeddedAssociation> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"Vivek\", results.get(0).getUserInfo().getFirstName());\n        Assert.assertEquals(31, results.get(0).getUserInfo().getAge());\n        Assert.assertEquals(0, results.get(0).getUserInfo().getHeight());\n\n        em.remove(timeLine);\n\n        em.clear();// optional,just to clear persistence cache.\n        em.close();\n\n        em = createEM();\n        UserInfo user_Info = em.find(UserInfo.class, \"mevivs_info\");\n        Assert.assertNull(user_Info);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/crud/compositeType/association/UserOTOPK.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.crud.compositeType.association;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\nimport javax.persistence.Table;\n\n/**\n * User One-To-One entity\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"UserOTOPK\")\npublic class UserOTOPK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, optional = false)\n    @PrimaryKeyJoinColumn\n    private AddressOTOPK address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressOTOPK getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressOTOPK address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/crud/compositeType/association/UserOTOPKTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.crud.compositeType.association;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * One-To-One by primary key test.\n * \n * @author vivek.mishra\n * \n */\npublic class UserOTOPKTest\n{\n    private String keyspace = \"KunderaExamples\";\n\n    private EntityManagerFactory emf;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n        emf = Persistence.createEntityManagerFactory(\"ds_pu\");\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(keyspace);\n        emf.close();\n    }\n\n    @Test\n    public void testOTOPk()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        AddressOTOPK addressOTOPK = new AddressOTOPK();\n        addressOTOPK.setAddressId(\"xyz\");\n        addressOTOPK.setStreet(\"STTRRREEEETTTTT\");\n\n        UserOTOPK userOTOPK = new UserOTOPK();\n        userOTOPK.setPersonId(\"1234\");\n        userOTOPK.setPersonName(\"Kuldeep\");\n        userOTOPK.setAddress(addressOTOPK);\n\n        em.persist(userOTOPK);\n\n        em.clear();\n\n        UserOTOPK otopk = em.find(UserOTOPK.class, \"1234\");\n        Assert.assertNotNull(otopk);\n        Assert.assertNotNull(otopk.getAddress());\n        Assert.assertEquals(\"Kuldeep\", otopk.getPersonName());\n        Assert.assertEquals(\"1234\", otopk.getAddress().getPersonId());\n        Assert.assertEquals(\"xyz\", otopk.getAddress().getAddressId());\n        Assert.assertEquals(\"STTRRREEEETTTTT\", otopk.getAddress().getStreet());\n\n        em.clear();\n\n        Query q = em.createQuery(\"Select u from UserOTOPK u\");\n        List<UserOTOPK> users = q.getResultList();\n        Assert.assertNotNull(users);\n        Assert.assertEquals(1, users.size());\n        Assert.assertNotNull(users.get(0));\n        Assert.assertNotNull(users.get(0).getAddress());\n        Assert.assertEquals(\"STTRRREEEETTTTT\", users.get(0).getAddress().getStreet());\n        em.close();\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/generatedId/CassandraGeneratedIdTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.generatedId;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.generatedId.entites.CassandraGeneratedIdDefault;\nimport com.impetus.client.cassandra.generatedId.entites.CassandraGeneratedIdStrategyAuto;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Cassandra generated id junit.\n * \n * @author vivek.mishra\n *\n */\npublic class CassandraGeneratedIdTest\n{\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        emf = Persistence.createEntityManagerFactory(\"ds_pu\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n        emf.close();\n    }\n\n    @Test\n    public void testPersist()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        CassandraGeneratedIdDefault idDefault = new CassandraGeneratedIdDefault();\n        idDefault.setName(\"kuldeep\");\n        em.persist(idDefault);\n        CassandraGeneratedIdStrategyAuto strategyAuto = new CassandraGeneratedIdStrategyAuto();\n        strategyAuto.setName(\"kuldeep\");\n        em.persist(strategyAuto);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/generatedId/entites/CassandraGeneratedIdDefault.java",
    "content": "package com.impetus.client.cassandra.generatedId.entites;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"CassandraGeneratedIdDefault\")\npublic class CassandraGeneratedIdDefault\n{\n    @Id\n    @GeneratedValue\n    private UUID id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public UUID getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(UUID id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/generatedId/entites/CassandraGeneratedIdStrategyAuto.java",
    "content": "package com.impetus.client.cassandra.generatedId.entites;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"CassandraGeneratedIdStrategyAuto\")\n@TableGenerator(name = \"id_gen\")\npublic class CassandraGeneratedIdStrategyAuto\n{\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    private UUID id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public UUID getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(UUID id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/generatedId/entites/EmployeeAddress.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.generatedId.entites;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"EmployeeAddress\")\npublic class EmployeeAddress\n{\n\n    @Id\n    @Column(name = \"RegionID\")\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.AUTO)\n    private UUID address;\n    \n    @Column(name=\"street\")\n    private String street;\n\n    public EmployeeAddress()\n    {\n        \n    }\n    public UUID getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(UUID address)\n    {\n        this.address = address;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n    \n    \n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/generatedId/entites/EmployeeInfo.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.generatedId.entites;\n\nimport java.util.UUID;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * Employee info entity.\n * \n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"EmployeeInfo\")\npublic class EmployeeInfo\n{\n    @Id\n    @Column(name = \"UserID\")\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    private UUID userid;\n    \n    \n    public EmployeeInfo()\n    {\n        \n    }\n    \n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"address_id\")\n    private EmployeeAddress address;\n\n    public UUID getUserid()\n    {\n        return userid;\n    }\n\n    public void setUserid(UUID userid)\n    {\n        this.userid = userid;\n    }\n\n    public EmployeeAddress getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(EmployeeAddress address)\n    {\n        this.address = address;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/generatedId/entites/EmployeeInfoTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.generatedId.entites;\n\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Employee info jun\n * @author vivek.mishra\n *\n */\npublic class EmployeeInfoTest\n{\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        emf = Persistence.createEntityManagerFactory(\"ds_pu\");\n    }\n\n    @Test\n    public void test()\n    {\n        EntityManager em = emf.createEntityManager();\n        EmployeeInfo emp_info = new EmployeeInfo();\n        EmployeeAddress address_info = new EmployeeAddress();\n        address_info.setStreet(\"street\");\n        emp_info.setAddress(address_info);\n        em.persist(emp_info);\n        \n        UUID key = emp_info.getUserid();\n        \n        em.clear();\n\n        EmployeeInfo result = em.find(EmployeeInfo.class, key);\n\n        Assert.assertNotNull(result);\n        Assert.assertNotNull(result.getAddress());\n        Assert.assertNotNull(result.getAddress().getStreet());\n        Assert.assertNotNull(result.getAddress().getAddress());\n        Assert.assertEquals(\"street\", result.getAddress().getStreet());\n        \n        result.getAddress().setStreet(\"newStreet\");\n        em.merge(result);\n        \n        em.clear();\n        \n        result = em.find(EmployeeInfo.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertNotNull(result.getAddress());\n        Assert.assertNotNull(result.getAddress().getStreet());\n        Assert.assertNotNull(result.getAddress().getAddress());\n        Assert.assertEquals(\"newStreet\", result.getAddress().getStreet());\n        \n        em.remove(result);\n        em.clear();\n        result = em.find(EmployeeInfo.class, key);\n        Assert.assertNull(result);\n        \n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/udt/Address.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n /*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * The Class Address.\n */\n@Embeddable\npublic class Address\n{\n    \n    /** The street. */\n    @Column(name = \"street\")\n    private String street;\n\n    /** The city. */\n    @Column(name = \"city\")\n    private String city;\n\n    /** The pin. */\n    @Column(name = \"pin\")\n    private String pin;\n\n    /**\n     * Instantiates a new address.\n     */\n    public Address()\n    {\n\n    }\n\n    /**\n     * Gets the street.\n     *\n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     *\n     * @param street the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    /**\n     * Gets the city.\n     *\n     * @return the city\n     */\n    public String getCity()\n    {\n        return city;\n    }\n\n    /**\n     * Sets the city.\n     *\n     * @param city the new city\n     */\n    public void setCity(String city)\n    {\n        this.city = city;\n    }\n\n    /**\n     * Gets the pin.\n     *\n     * @return the pin\n     */\n    public String getPin()\n    {\n        return pin;\n    }\n\n    /**\n     * Sets the pin.\n     *\n     * @param pin the new pin\n     */\n    public void setPin(String pin)\n    {\n        this.pin = pin;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/udt/Fullname.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n /*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * The Class Fullname.\n */\n@Embeddable\npublic class Fullname\n{\n    \n    /** The first name. */\n    @Column\n    private String firstname;\n\n    /** The middle name. */\n    @Column\n    private String middlename;\n\n    /** The last name. */\n    @Column\n    private String lastname;\n\n    /**\n     * Instantiates a new fullname.\n     */\n    public Fullname()\n    {\n\n    }\n\n    /**\n     * Gets the first name.\n     *\n     * @return the first name\n     */\n    public String getFirstName()\n    {\n        return firstname;\n    }\n\n    /**\n     * Sets the first name.\n     *\n     * @param firstName the new first name\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstname = firstName;\n    }\n\n    /**\n     * Gets the middle name.\n     *\n     * @return the middle name\n     */\n    public String getMiddleName()\n    {\n        return middlename;\n    }\n\n    /**\n     * Sets the middle name.\n     *\n     * @param middleName the new middle name\n     */\n    public void setMiddleName(String middleName)\n    {\n        this.middlename = middleName;\n    }\n\n    /**\n     * Gets the last name.\n     *\n     * @return the last name\n     */\n    public String getLastName()\n    {\n        return lastname;\n    }\n\n    /**\n     * Sets the last name.\n     *\n     * @param lastName the new last name\n     */\n    public void setLastName(String lastName)\n    {\n        this.lastname = lastName;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/udt/PersonUDT.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n /*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class PersonUDT.\n */\n@Entity\n@Table(name = \"person_udt\", schema = \"KunderaExamples@ds_collection_pu\")\n@IndexCollection(columns = { @Index(name = \"nicknames\"), @Index(name = \"email\"), @Index(name = \"password\") })\npublic class PersonUDT\n{\n\n    /** The person id. */\n    @Id\n    @Column\n    private String personId;\n\n    /** The personal details. */\n    @Embedded\n    private PersonalDetailsUDT personalDetails;\n\n    /** The professional details. */\n    @Embedded\n    private ProfessionalDetailsUDT professionalDetails;\n\n    /** The email. */\n    @Column\n    private String email;\n\n    /** The password. */\n    @Column\n    private String password;\n\n    /** The nicknames. */\n    @Column\n    private List<String> nicknames;\n    \n    /** The list profs. */\n    @ElementCollection\n    private List<ProfessionalDetailsUDT> listProfs;\n    \n    /** The set profs. */\n    @ElementCollection\n    private Set<ProfessionalDetailsUDT> setProfs;\n    \n    /** The map profs key. */\n    @ElementCollection\n    private Map<String, ProfessionalDetailsUDT> mapProfsKey;\n    \n    \n    /**\n     * Gets the sets the profs.\n     *\n     * @return the sets the profs\n     */\n    public Set<ProfessionalDetailsUDT> getSetProfs()\n    {\n        return setProfs;\n    }\n\n    /**\n     * Sets the sets the profs.\n     *\n     * @param setProfs the new sets the profs\n     */\n    public void setSetProfs(Set<ProfessionalDetailsUDT> setProfs)\n    {\n        this.setProfs = setProfs;\n    }\n\n    /**\n     * Gets the map profs key.\n     *\n     * @return the map profs key\n     */\n    public Map<String, ProfessionalDetailsUDT> getMapProfsKey()\n    {\n        return mapProfsKey;\n    }\n\n    /**\n     * Sets the map profs key.\n     *\n     * @param mapProfsKey the map profs key\n     */\n    public void setMapProfsKey(Map<String, ProfessionalDetailsUDT> mapProfsKey)\n    {\n        this.mapProfsKey = mapProfsKey;\n    }\n\n//    public Map<Fullname, ProfessionalDetailsUDT> getMapProfsBoth()\n//    {\n//        return mapProfsBoth;\n//    }\n//\n//    public void setMapProfsBoth(Map<Fullname, ProfessionalDetailsUDT> mapProfsBoth)\n//    {\n//        this.mapProfsBoth = mapProfsBoth;\n//    }\n\n//    public Map<ProfessionalDetailsUDT, Integer> getMapProfsValue()\n//    {\n//        return mapProfsValue;\n//    }\n//\n//    public void setMapProfsValue(Map<ProfessionalDetailsUDT, Integer> mapProfsValue)\n//    {\n//        this.mapProfsValue = mapProfsValue;\n//    }\n//\n//    @ElementCollection\n//    private Map<ProfessionalDetailsUDT, Integer> mapProfsValue;\n\n    \n    /**\n * Gets the list profs.\n *\n * @return the list profs\n */\npublic List<ProfessionalDetailsUDT> getListProfs()\n    {\n        return listProfs;\n    }\n\n    /**\n     * Sets the list profs.\n     *\n     * @param listProfs the new list profs\n     */\n    public void setListProfs(List<ProfessionalDetailsUDT> listProfs)\n    {\n        this.listProfs = listProfs;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the personal details.\n     * \n     * @return the personal details\n     */\n    public PersonalDetailsUDT getPersonalDetails()\n    {\n        return personalDetails;\n    }\n\n    /**\n     * Sets the personal details.\n     * \n     * @param personalDetails\n     *            the new personal details\n     */\n    public void setPersonalDetails(PersonalDetailsUDT personalDetails)\n    {\n        this.personalDetails = personalDetails;\n    }\n\n    /**\n     * Gets the professional details.\n     * \n     * @return the professional details\n     */\n    public ProfessionalDetailsUDT getProfessionalDetails()\n    {\n        return professionalDetails;\n    }\n\n    /**\n     * Sets the professional details.\n     * \n     * @param professionalDetails\n     *            the new professional details\n     */\n    public void setProfessionalDetails(ProfessionalDetailsUDT professionalDetails)\n    {\n        this.professionalDetails = professionalDetails;\n    }\n\n    /**\n     * Gets the email.\n     * \n     * @return the email\n     */\n    public String getEmail()\n    {\n        return email;\n    }\n\n    /**\n     * Sets the email.\n     * \n     * @param email\n     *            the new email\n     */\n    public void setEmail(String email)\n    {\n        this.email = email;\n    }\n\n    /**\n     * Gets the password.\n     * \n     * @return the password\n     */\n    public String getPassword()\n    {\n        return password;\n    }\n\n    /**\n     * Sets the password.\n     * \n     * @param password\n     *            the new password\n     */\n    public void setPassword(String password)\n    {\n        this.password = password;\n    }\n\n    /**\n     * Gets the nicknames.\n     * \n     * @return the nicknames\n     */\n    public List<String> getNicknames()\n    {\n        return nicknames;\n    }\n\n    /**\n     * Sets the nicknames.\n     * \n     * @param nicknames\n     *            the new nicknames\n     */\n    public void setNicknames(List<String> nicknames)\n    {\n        this.nicknames = nicknames;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/udt/PersonalDetailsUDT.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n /*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Embedded;\n\n/**\n * The Class PersonalDetailsUDT.\n */\n@Embeddable\npublic class PersonalDetailsUDT\n{\n\n    /** The fullname. */\n    @Embedded\n    private Fullname fullname;\n\n    /** The addresses. */\n    @ElementCollection\n    private Map<String, Address> addresses;\n\n    /** The phones. */\n    @ElementCollection\n    private List<Phone> phones;\n    \n    /** The spouses. */\n    @ElementCollection\n    private Set<Spouse> spouses;\n\n    /**\n     * Gets the fullname.\n     *\n     * @return the fullname\n     */\n    public Fullname getFullname()\n    {\n        return fullname;\n    }\n\n    /**\n     * Sets the fullname.\n     *\n     * @param fullname the new fullname\n     */\n    public void setFullname(Fullname fullname)\n    {\n        this.fullname = fullname;\n    }\n\n    /**\n     * Gets the addresses.\n     *\n     * @return the addresses\n     */\n    public Map<String, Address> getAddresses()\n    {\n        return addresses;\n    }\n\n    /**\n     * Sets the addresses.\n     *\n     * @param addresses the addresses\n     */\n    public void setAddresses(Map<String, Address> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n    /**\n     * Gets the phones.\n     *\n     * @return the phones\n     */\n    public List<Phone> getPhones()\n    {\n        return phones;\n    }\n\n    /**\n     * Sets the phones.\n     *\n     * @param phones the new phones\n     */\n    public void setPhones(List<Phone> phones)\n    {\n        this.phones = phones;\n    }\n\n    /**\n     * Gets the spouses.\n     *\n     * @return the spouses\n     */\n    public Set<Spouse> getSpouses()\n    {\n        return spouses;\n    }\n\n    /**\n     * Sets the spouses.\n     *\n     * @param spouses the new spouses\n     */\n    public void setSpouses(Set<Spouse> spouses)\n    {\n        this.spouses = spouses;\n    }\n    \n    \n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/udt/Phone.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n /*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n// TODO: Auto-generated Javadoc\n/**\n * The Class Phone.\n */\n@Embeddable\npublic class Phone\n{\n    \n    /** The number. */\n    @Column\n    private Long number;\n\n     /** The tags. */\n     @Column\n     private Set<String> tags;\n\n    /**\n     * Instantiates a new phone.\n     */\n    public Phone()\n    {\n\n    }\n\n    /**\n     * Gets the number.\n     *\n     * @return the number\n     */\n    public Long getNumber()\n    {\n        return number;\n    }\n\n    /**\n     * Sets the number.\n     *\n     * @param number the new number\n     */\n    public void setNumber(Long number)\n    {\n        this.number = number;\n    }\n\n     /**\n      * Gets the tags.\n      *\n      * @return the tags\n      */\n     public Set<String> getTags()\n     {\n     return tags;\n     }\n    \n     /**\n      * Sets the tags.\n      *\n      * @param tags the new tags\n      */\n     public void setTags(Set<String> tags)\n     {\n     this.tags = tags;\n     }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/udt/ProfessionalDetailsUDT.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n/*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * The Class ProfessionalDetailsUDT.\n */\n@Embeddable\npublic class ProfessionalDetailsUDT\n{\n\n    /** The company. */\n    @Column\n    private String company;\n\n    /** The project. */\n    @Column\n    private List<Integer> extentions;\n\n    /** The colleagues. */\n    @Column\n    private Set<String> colleagues;\n\n    /** The projects. */\n    @Column\n    private Map<Integer, String> projects;\n\n    /** The grade. */\n    @Column\n    private String grade;\n\n    /** The monthly salary. */\n    @Column(name = \"monthly_salary\")\n    private Double monthlySalary;\n\n    /**\n     * Gets the company.\n     * \n     * @return the company\n     */\n    public String getCompany()\n    {\n        return company;\n    }\n\n    /**\n     * Sets the company.\n     * \n     * @param company\n     *            the new company\n     */\n    public void setCompany(String company)\n    {\n        this.company = company;\n    }\n\n    /**\n     * Gets the extentions.\n     * \n     * @return the extentions\n     */\n    public List<Integer> getExtentions()\n    {\n        return extentions;\n    }\n\n    /**\n     * Sets the extentions.\n     * \n     * @param extentions\n     *            the new extentions\n     */\n    public void setExtentions(List<Integer> extentions)\n    {\n        this.extentions = extentions;\n    }\n\n    /**\n     * Gets the colleagues.\n     * \n     * @return the colleagues\n     */\n    public Set<String> getColleagues()\n    {\n        return colleagues;\n    }\n\n    /**\n     * Sets the colleagues.\n     * \n     * @param colleagues\n     *            the new colleagues\n     */\n    public void setColleagues(Set<String> colleagues)\n    {\n        this.colleagues = colleagues;\n    }\n\n    /**\n     * Gets the projects.\n     * \n     * @return the projects\n     */\n    public Map<Integer, String> getProjects()\n    {\n        return projects;\n    }\n\n    /**\n     * Sets the projects.\n     * \n     * @param projects\n     *            the projects\n     */\n    public void setProjects(Map<Integer, String> projects)\n    {\n        this.projects = projects;\n    }\n\n    /**\n     * Gets the grade.\n     * \n     * @return the grade\n     */\n    public String getGrade()\n    {\n        return grade;\n    }\n\n    /**\n     * Sets the grade.\n     * \n     * @param grade\n     *            the new grade\n     */\n    public void setGrade(String grade)\n    {\n        this.grade = grade;\n    }\n\n    /**\n     * Gets the monthly salary.\n     * \n     * @return the monthly salary\n     */\n    public Double getMonthlySalary()\n    {\n        return monthlySalary;\n    }\n\n    /**\n     * Sets the monthly salary.\n     * \n     * @param monthlySalary\n     *            the new monthly salary\n     */\n    public void setMonthlySalary(Double monthlySalary)\n    {\n        this.monthlySalary = monthlySalary;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/udt/Spouse.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n /*\n * author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Embedded;\n\n/**\n * The Class Spouse.\n */\n@Embeddable\npublic class Spouse\n{\n\n    /** The fullname. */\n    @Embedded\n    private Fullname fullname;\n\n    /** The maiden name. */\n    @Column(name = \"maiden_name\")\n    private String maidenName;\n\n    /** The age. */\n    @Column\n    private int age;\n\n    /**\n     * Instantiates a new spouse.\n     */\n    public Spouse()\n    {\n\n    }\n\n    /**\n     * Gets the fullname.\n     *\n     * @return the fullname\n     */\n    public Fullname getFullname()\n    {\n        return fullname;\n    }\n\n    /**\n     * Sets the fullname.\n     *\n     * @param fullname the new fullname\n     */\n    public void setFullname(Fullname fullname)\n    {\n        this.fullname = fullname;\n    }\n\n    /**\n     * Gets the maiden name.\n     *\n     * @return the maiden name\n     */\n    public String getMaidenName()\n    {\n        return maidenName;\n    }\n\n    /**\n     * Sets the maiden name.\n     *\n     * @param maidenName the new maiden name\n     */\n    public void setMaidenName(String maidenName)\n    {\n        this.maidenName = maidenName;\n    }\n\n    /**\n     * Gets the age.\n     *\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     *\n     * @param age the new age\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/cassandra/udt/UdtAsEmbeddablesCRUDTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n/*\n * @author: karthikp.manchala\n */\npackage com.impetus.client.cassandra.udt;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * The Class UdtAsEmbeddablesCRUDTest.\n */\npublic class UdtAsEmbeddablesCRUDTest\n{\n\n    /** The Constant PU. */\n    private static final String PU = \"ds_collection_pu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager entityManager;\n\n    /** The property map. */\n    protected static Map propertyMap = null;\n\n    /** The auto manage schema. */\n    protected boolean AUTO_MANAGE_SCHEMA = true;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n\n        emf = Persistence.createEntityManagerFactory(PU, propertyMap);\n\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        entityManager = emf.createEntityManager();\n\n    }\n\n    /**\n     * On insert cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onInsert() throws Exception\n    {\n        Object p1 = prepareDataLevel1();\n        Object p2 = prepareDataLevel2();\n        Object p3 = prepareDataLevel3();\n        Object p4 = prepareDataLevel4();\n\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        entityManager.persist(p4);\n        entityManager.clear();\n\n        PersonUDT f1 = entityManager.find(PersonUDT.class, \"1\");\n        PersonUDT f2 = entityManager.find(PersonUDT.class, \"2\");\n        PersonUDT f3 = entityManager.find(PersonUDT.class, \"3\");\n        PersonUDT f4 = entityManager.find(PersonUDT.class, \"4\");\n\n        Assert.assertNotNull(f1);\n        Assert.assertNotNull(f2);\n        Assert.assertNotNull(f3);\n        Assert.assertNotNull(f4);\n\n    }\n\n    /**\n     * On delete.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onDelete() throws Exception\n    {\n        Object p1 = prepareDataLevel1();\n        Object p2 = prepareDataLevel2();\n        Object p3 = prepareDataLevel3();\n        Object p4 = prepareDataLevel4();\n\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        entityManager.persist(p4);\n        entityManager.clear();\n\n        PersonUDT beforeDelete1 = entityManager.find(PersonUDT.class, \"2\");\n        PersonUDT beforeDelete2 = entityManager.find(PersonUDT.class, \"4\");\n        Assert.assertNotNull(beforeDelete1);\n        Assert.assertNotNull(beforeDelete2);\n\n        entityManager.remove(beforeDelete1);\n        entityManager.remove(beforeDelete2);\n        entityManager.clear();\n\n        PersonUDT after1 = entityManager.find(PersonUDT.class, \"2\");\n        PersonUDT after2 = entityManager.find(PersonUDT.class, \"4\");\n\n        Assert.assertNull(after1);\n        Assert.assertNull(after2);\n\n    }\n\n    /**\n     * On merge.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onMerge() throws Exception\n    {\n        Object p1 = prepareDataLevel1();\n        Object p2 = prepareDataLevel2();\n        Object p3 = prepareDataLevel3();\n        Object p4 = prepareDataLevel4();\n\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        entityManager.persist(p4);\n        entityManager.clear();\n\n        PersonUDT beforeMerge = entityManager.find(PersonUDT.class, \"3\");\n\n        Assert.assertEquals(beforeMerge.getPassword(), ((PersonUDT) p3).getPassword());\n        beforeMerge.setPassword(\"qwerty\");\n        beforeMerge.getNicknames().add(\"nick added\");\n        beforeMerge.setNicknames(beforeMerge.getNicknames());\n        entityManager.merge(beforeMerge);\n        entityManager.clear();\n\n        PersonUDT afterMerge = entityManager.find(PersonUDT.class, \"3\");\n\n        Assert.assertNotNull(afterMerge);\n        Assert.assertEquals(\"qwerty\", afterMerge.getPassword());\n        Assert.assertEquals(\"nick added\", afterMerge.getNicknames().get(1));\n\n    }\n\n    /**\n     * On find.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onFind() throws Exception\n    {\n        Object p1 = prepareDataLevel1();\n        Object p2 = prepareDataLevel2();\n        Object p3 = prepareDataLevel3();\n        Object p4 = prepareDataLevel4();\n\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        entityManager.persist(p4);\n        entityManager.clear();\n\n        PersonUDT f1 = entityManager.find(PersonUDT.class, \"1\");\n        PersonUDT f2 = entityManager.find(PersonUDT.class, \"2\");\n        PersonUDT f3 = entityManager.find(PersonUDT.class, \"3\");\n        PersonUDT f4 = entityManager.find(PersonUDT.class, \"4\");\n\n        Assert.assertNotNull(f1);\n        Assert.assertNotNull(f2);\n        Assert.assertNotNull(f3);\n        Assert.assertNotNull(f4);\n\n        assertEntity((PersonUDT) p1, f1);\n        assertEntity((PersonUDT) p2, f2);\n        assertEntity((PersonUDT) p3, f3);\n        assertEntity((PersonUDT) p4, f4);\n\n    }\n\n    /**\n     * On embeddable merge.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onEmbeddableMerge() throws Exception\n    {\n        Object p1 = prepareDataLevel1();\n\n        entityManager.persist(p1);\n        entityManager.clear();\n\n        PersonUDT beforeMerge = entityManager.find(PersonUDT.class, \"1\");\n        entityManager.clear();\n        Assert.assertEquals(beforeMerge.getPassword(), ((PersonUDT) p1).getPassword());\n        beforeMerge.setPassword(\"qwerty\");\n        beforeMerge.getNicknames().add(\"nick added\");\n        beforeMerge.setNicknames(beforeMerge.getNicknames());\n        PersonalDetailsUDT personalDetails = loadPersonalDetails(\"devender\", \"yadav\");\n        beforeMerge.setPersonalDetails(personalDetails);\n        entityManager.merge(beforeMerge);\n        entityManager.clear();\n\n        PersonUDT afterMerge = entityManager.find(PersonUDT.class, \"1\");\n\n        Assert.assertNotNull(afterMerge);\n        Assert.assertEquals(\"qwerty\", afterMerge.getPassword());\n        Assert.assertEquals(\"nick added\", afterMerge.getNicknames().get(2));\n        Assert.assertEquals(\"devender\", afterMerge.getPersonalDetails().getFullname().getFirstName());\n        Assert.assertEquals(\"yadav\", afterMerge.getPersonalDetails().getFullname().getLastName());\n\n    }\n\n    /**\n     * On select all query.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onSelectAllQuery() throws Exception\n    {\n        Object p1 = prepareDataLevel1();\n        Object p2 = prepareDataLevel2();\n        Object p3 = prepareDataLevel3();\n        Object p4 = prepareDataLevel4();\n\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        entityManager.persist(p4);\n        entityManager.clear();\n\n        PersonUDT f1 = null;\n        PersonUDT f2 = null;\n        PersonUDT f3 = null;\n        PersonUDT f4 = null;\n\n        Query query = entityManager.createQuery(\"Select t from PersonUDT t\");\n\n        List<PersonUDT> results = query.getResultList();\n        Iterator<PersonUDT> i = results.iterator();\n        while (i.hasNext())\n        {\n            PersonUDT t = (PersonUDT) i.next();\n            if (t.getPersonId().equals(\"1\"))\n            {\n                f1 = t;\n            }\n            if (t.getPersonId().equals(\"2\"))\n            {\n                f2 = t;\n            }\n            if (t.getPersonId().equals(\"3\"))\n            {\n                f3 = t;\n            }\n            if (t.getPersonId().equals(\"4\"))\n            {\n                f4 = t;\n            }\n        }\n\n        Assert.assertNotNull(f1);\n        Assert.assertNotNull(f2);\n        Assert.assertNotNull(f3);\n        Assert.assertNotNull(f4);\n\n        assertEntity((PersonUDT) p1, f1);\n        assertEntity((PersonUDT) p2, f2);\n        assertEntity((PersonUDT) p3, f3);\n        assertEntity((PersonUDT) p4, f4);\n\n    }\n\n    /**\n     * On select by id query.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onSelectByIdQuery() throws Exception\n    {\n        Object p3 = prepareDataLevel3();\n\n        entityManager.persist(p3);\n        entityManager.clear();\n\n        Query query = entityManager.createQuery(\"Select t from PersonUDT t where t.personId = 3\");\n\n        List<PersonUDT> results = query.getResultList();\n\n        Assert.assertNotNull(results.get(0));\n\n        PersonUDT f3 = results.get(0);\n\n        Assert.assertNotNull(f3);\n\n        assertEntity((PersonUDT) p3, f3);\n\n    }\n\n    /**\n     * On collection indexes.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onCollectionIndexes() throws Exception\n    {\n        Object p3 = prepareDataLevel3();\n\n        entityManager.persist(p3);\n        entityManager.clear();\n\n        Query query = entityManager.createQuery(\"Select t from PersonUDT t where t.nicknames = 'dev'\");\n\n        List<PersonUDT> results = query.getResultList();\n\n        Assert.assertNotNull(results.get(0));\n\n        PersonUDT f3 = results.get(0);\n\n        Assert.assertNotNull(f3);\n\n        assertEntity((PersonUDT) p3, f3);\n\n    }\n    \n    /**\n     * Test null embeddable.\n     */\n    @Test\n    public void testNullEmbeddable()\n    {\n        PersonUDT personUDT = new PersonUDT();\n        personUDT.setPersonId(\"10\");\n        personUDT.setEmail(\"user@impetus.com\");\n        List<String> nicknames = new ArrayList<String>();\n        nicknames.add(\"Charlie\");\n        nicknames.add(\"kar\");\n        personUDT.setNicknames(nicknames);\n        personUDT.setPassword(\"impetus\");\n        personUDT.setPersonalDetails(null);\n        \n        entityManager.persist(personUDT);\n        entityManager.clear();\n\n        PersonUDT f1 = entityManager.find(PersonUDT.class, \"10\");\n        \n        Assert.assertNotNull(f1);\n    }\n\n    /**\n     * Assert entity.\n     * \n     * @param expected\n     *            the expected entity\n     * @param actual\n     *            the actual entity\n     */\n    private void assertEntity(PersonUDT expected, PersonUDT actual)\n    {\n        Assert.assertEquals(expected.getEmail(), actual.getEmail());\n        Assert.assertEquals(expected.getPassword(), actual.getPassword());\n        Assert.assertEquals(expected.getPersonId(), actual.getPersonId());\n        Assert.assertEquals(expected.getNicknames(), actual.getNicknames());\n        Assert.assertEquals(expected.getPersonalDetails().getFullname().getFirstName(), actual.getPersonalDetails()\n                .getFullname().getFirstName());\n        Assert.assertEquals(expected.getPersonalDetails().getFullname().getLastName(), actual.getPersonalDetails()\n                .getFullname().getLastName());\n        assertPersonalDetails(expected.getPersonalDetails(), actual.getPersonalDetails());\n        assertProfessionalDetails(expected.getProfessionalDetails(), actual.getProfessionalDetails());\n        // assert collection data\n        assertProfessionalDetails(expected.getListProfs().get(0), actual.getListProfs().get(0));\n        assertProfessionalDetails(expected.getMapProfsKey().get(\"karthik\"), actual.getMapProfsKey().get(\"karthik\"));\n        assertProfessionalDetails(expected.getMapProfsKey().get(\"pragalbh\"), actual.getMapProfsKey().get(\"pragalbh\"));\n        assertProfessionalDetails(expected.getSetProfs().iterator().next(), actual.getSetProfs().iterator().next());\n    }\n\n    /**\n     * Assert personal details.\n     * \n     * @param expected\n     *            the expected\n     * @param actual\n     *            the actual\n     */\n    private void assertPersonalDetails(PersonalDetailsUDT expected, PersonalDetailsUDT actual)\n    {\n        Assert.assertEquals(expected.getAddresses().get(\"Office\").getStreet(), actual.getAddresses().get(\"Office\")\n                .getStreet());\n        Assert.assertEquals(expected.getAddresses().get(\"Home\").getPin(), actual.getAddresses().get(\"Home\").getPin());\n        Assert.assertEquals(expected.getPhones().get(0).getNumber(), actual.getPhones().get(0).getNumber());\n        Assert.assertEquals(expected.getPhones().get(0).getTags(), actual.getPhones().get(0).getTags());\n        Assert.assertEquals(expected.getSpouses().iterator().next().getMaidenName(), actual.getSpouses().iterator()\n                .next().getMaidenName());\n    }\n\n    /**\n     * Assert professional details.\n     * \n     * @param expected\n     *            the expected\n     * @param actual\n     *            the actual\n     */\n    private void assertProfessionalDetails(ProfessionalDetailsUDT expected, ProfessionalDetailsUDT actual)\n    {\n        Assert.assertEquals(expected.getCompany(), actual.getCompany());\n        Assert.assertEquals(expected.getGrade(), actual.getGrade());\n        Assert.assertEquals(expected.getMonthlySalary(), actual.getMonthlySalary());\n        // assert collection data\n        Assert.assertEquals(expected.getProjects().get(0), actual.getProjects().get(0));\n        Assert.assertEquals(expected.getProjects().get(1), actual.getProjects().get(1));\n        Assert.assertEquals(true, expected.getColleagues().containsAll(actual.getColleagues()));\n        Assert.assertEquals(expected.getExtentions().get(0), actual.getExtentions().get(0));\n        Assert.assertEquals(expected.getExtentions().get(1), actual.getExtentions().get(1));\n\n    }\n\n    /**\n     * Prepare data level3.\n     * \n     * @return the object\n     */\n    private Object prepareDataLevel3()\n    {\n        PersonUDT personUDT = new PersonUDT();\n        personUDT.setPersonId(\"3\");\n        personUDT.setEmail(\"devender@impetus.com\");\n        List<String> nicknames = new ArrayList<String>();\n        nicknames.add(\"dev\");\n        personUDT.setNicknames(nicknames);\n        personUDT.setPassword(\"impetus\");\n        PersonalDetailsUDT personalDetails = loadPersonalDetails(\"devender\", \"yadav\");\n        personUDT.setPersonalDetails(personalDetails);\n        ProfessionalDetailsUDT professionalDetails = loadProfessionalDetails();\n        personUDT.setProfessionalDetails(professionalDetails);\n        prepareCollectionData(personUDT);\n\n        return personUDT;\n    }\n\n    /**\n     * Prepare data level4.\n     * \n     * @return the object\n     */\n    private Object prepareDataLevel4()\n    {\n        PersonUDT personUDT = new PersonUDT();\n        personUDT.setPersonId(\"4\");\n        personUDT.setEmail(\"devender@impetus.com\");\n        List<String> nicknames = new ArrayList<String>();\n        nicknames.add(\"rockstar\");\n        personUDT.setNicknames(nicknames);\n        personUDT.setPassword(\"impetus\");\n        PersonalDetailsUDT personalDetails = loadPersonalDetails(\"amit\", \"kumar\");\n        personUDT.setPersonalDetails(personalDetails);\n        ProfessionalDetailsUDT professionalDetails = loadProfessionalDetails();\n        personUDT.setProfessionalDetails(professionalDetails);\n        prepareCollectionData(personUDT);\n\n        return personUDT;\n    }\n\n    /**\n     * Prepare data level2.\n     * \n     * @return the object\n     */\n    private Object prepareDataLevel2()\n    {\n        PersonUDT personUDT = new PersonUDT();\n        personUDT.setPersonId(\"2\");\n        personUDT.setEmail(\"pragalbh@impetus.com\");\n        List<String> nicknames = new ArrayList<String>();\n        nicknames.add(\"articuno\");\n        nicknames.add(\"PG\");\n        personUDT.setNicknames(nicknames);\n        personUDT.setPassword(\"impetus\");\n        PersonalDetailsUDT personalDetails = loadPersonalDetails(\"pragalbh\", \"garg\");\n        personUDT.setPersonalDetails(personalDetails);\n        ProfessionalDetailsUDT professionalDetails = loadProfessionalDetails();\n        personUDT.setProfessionalDetails(professionalDetails);\n        List<ProfessionalDetailsUDT> listProfs = new ArrayList<ProfessionalDetailsUDT>();\n        listProfs.add(professionalDetails);\n        listProfs.add(professionalDetails);\n        personUDT.setListProfs(listProfs);\n        prepareCollectionData(personUDT);\n\n        return personUDT;\n    }\n\n    /**\n     * Prepare data level1.\n     * \n     * @return the object\n     */\n    private Object prepareDataLevel1()\n    {\n        PersonUDT personUDT = new PersonUDT();\n        personUDT.setPersonId(\"1\");\n        personUDT.setEmail(\"karthik@impetus.com\");\n        List<String> nicknames = new ArrayList<String>();\n        nicknames.add(\"tango\");\n        nicknames.add(\"kar\");\n        personUDT.setNicknames(nicknames);\n        personUDT.setPassword(\"impetus\");\n        PersonalDetailsUDT personalDetails = loadPersonalDetails(\"karthik\", \"manchala\");\n        personUDT.setPersonalDetails(personalDetails);\n        ProfessionalDetailsUDT professionalDetails = loadProfessionalDetails();\n        personUDT.setProfessionalDetails(professionalDetails);\n        // set collections\n        prepareCollectionData(personUDT);\n\n        return personUDT;\n    }\n\n    /**\n     * Prepare collection data.\n     * \n     * @param personUDT\n     *            the person udt\n     */\n    private void prepareCollectionData(PersonUDT personUDT)\n    {\n        ProfessionalDetailsUDT professionalDetails = loadProfessionalDetails();\n\n        List<ProfessionalDetailsUDT> listProfs = new ArrayList<ProfessionalDetailsUDT>();\n        listProfs.add(professionalDetails);\n        personUDT.setListProfs(listProfs);\n\n        Map<String, ProfessionalDetailsUDT> mapProfsKey = new HashMap<String, ProfessionalDetailsUDT>();\n        mapProfsKey.put(\"pragalbh\", professionalDetails);\n        mapProfsKey.put(\"karthik\", professionalDetails);\n        personUDT.setMapProfsKey(mapProfsKey);\n\n        Set<ProfessionalDetailsUDT> setProfs = new HashSet<ProfessionalDetailsUDT>();\n        setProfs.add(professionalDetails);\n        setProfs.add(professionalDetails);\n        personUDT.setSetProfs(setProfs);\n    }\n\n    /**\n     * Load professional details.\n     * \n     * @return the professional details udt\n     */\n    private ProfessionalDetailsUDT loadProfessionalDetails()\n    {\n        Map<Integer, String> projects = new HashMap<Integer, String>();\n        projects.put(1111, \"iLabs\");\n        projects.put(2222, \"Kundera\");\n        List<Integer> extns = new ArrayList<Integer>();\n        extns.add(4526);\n        extns.add(2810);\n        Set<String> colleagues = new HashSet<String>();\n        colleagues.add(\"Pavan\");\n        colleagues.add(\"Gautam\");\n        ProfessionalDetailsUDT profDetails = new ProfessionalDetailsUDT();\n        profDetails.setCompany(\"impetus\");\n        profDetails.setGrade(\"g4\");\n        profDetails.setMonthlySalary((double) 12345);\n        profDetails.setProjects(projects);\n        profDetails.setColleagues(colleagues);\n        profDetails.setExtentions(extns);\n\n        return profDetails;\n    }\n\n    /**\n     * Load personal details.\n     * \n     * @param firstname\n     *            the firstname\n     * @param lastname\n     *            the lastname\n     * @return the personal details udt\n     */\n    private PersonalDetailsUDT loadPersonalDetails(String firstname, String lastname)\n    {\n        PersonalDetailsUDT personalDetails = new PersonalDetailsUDT();\n        Fullname fullname = new Fullname();\n        fullname.setFirstName(firstname);\n        fullname.setLastName(lastname);\n        personalDetails.setFullname(fullname);\n\n        Address address = new Address();\n        address.setCity(\"indore\");\n        address.setPin(\"452001\");\n        address.setStreet(\"palasia\");\n        Map<String, Address> addresses = new HashMap<String, Address>();\n        addresses.put(\"Office\", address);\n        Address address1 = new Address();\n        address1.setCity(\"Delhi\");\n        address1.setPin(\"201301\");\n        address1.setStreet(\"NSEZ\");\n        addresses.put(\"Home\", address1);\n        personalDetails.setAddresses(addresses);\n\n        Phone phone = new Phone();\n        phone.setNumber(9988776655l);\n        String elements[] = { \"personal\", \"main\", \"indore\" };\n        phone.setTags(new HashSet<String>(Arrays.asList(elements)));\n        List<Phone> phoneList = new ArrayList<Phone>();\n        phoneList.add(phone);\n        personalDetails.setPhones(phoneList);\n\n        Spouse spouse = new Spouse();\n        spouse.setAge(20);\n        Fullname spouseName = new Fullname();\n        spouseName.setFirstName(\"asdfgh\");\n        spouse.setFullname(spouseName);\n        spouse.setMaidenName(\"qrqrrte\");\n        Set<Spouse> spouses = new HashSet<Spouse>();\n        spouses.add(spouse);\n        personalDetails.setSpouses(spouses);\n\n        return personalDetails;\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        entityManager.close();\n    }\n\n    /**\n     * Tear down after class.\n     */\n    @AfterClass\n    public static void tearDownAfterClass()\n    {\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n        emf.close();\n        emf = null;\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/crud/CassandraScalarQueriesTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.PersonCassandra.Day;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * The Class CassandraScalarQueriesTest.\n * \n * @author: karthikp.manchala\n */\npublic class CassandraScalarQueriesTest\n{\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n        HashMap propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"dsscalar_entity\", propertyMap);\n        EntityManager em = emf.createEntityManager();\n\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n    }\n\n    /**\n     * Test scalar query.\n     */\n    @Test\n    public void testSelectQueries()\n    {\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"dsscalar\");\n        EntityManager entityManager = emf.createEntityManager();\n        String qry = \"Select \\\"personId\\\", \\\"PERSON_NAME\\\" from \\\"PERSON\\\" where \\\"personId\\\" = '1'\";\n\n        Query q = entityManager.createNativeQuery(qry);\n        List<Object[]> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n\n        Assert.assertEquals(\"1\", persons.get(0)[0]);\n        Assert.assertEquals(\"karthik\", persons.get(0)[1]);\n\n        qry = \"Select \\\"personId\\\", \\\"PERSON_NAME\\\", \\\"MONTH_ENUM\\\", \\\"AGE\\\" from \\\"PERSON\\\" where \\\"personId\\\" = '1'\";\n        q = entityManager.createNativeQuery(qry);\n\n        persons = q.getResultList();\n\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n\n        Assert.assertEquals(\"1\", persons.get(0)[0]);\n        Assert.assertEquals(\"karthik\", persons.get(0)[1]);\n        Assert.assertEquals(\"MAY\", persons.get(0)[2]);\n        Assert.assertEquals(10, persons.get(0)[3]);\n\n        qry = \"Select \\\"personId\\\", \\\"PERSON_NAME\\\", \\\"MONTH_ENUM\\\", \\\"AGE\\\" from \\\"PERSON\\\"\";\n        q = entityManager.createNativeQuery(qry);\n\n        persons = q.getResultList();\n\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(3, persons.size());\n\n        Assert.assertEquals(\"1\", persons.get(0)[0]);\n        Assert.assertEquals(\"karthik\", persons.get(0)[1]);\n        Assert.assertEquals(\"MAY\", persons.get(0)[2]);\n        Assert.assertEquals(10, persons.get(0)[3]);\n\n        entityManager.close();\n        emf.close();\n    }\n\n    /**\n     * Test on column family.\n     */\n    @Test\n    public void testCreateAndUpdateQueries()\n    {\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"dsscalar\");\n        EntityManager entityManager = emf.createEntityManager();\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n        Query q = entityManager.createNativeQuery(useNativeSql);\n        q.executeUpdate();\n        // create column family\n        String colFamilySql = \"CREATE COLUMNFAMILY IF NOT EXISTS users (key varchar PRIMARY KEY,full_name varchar, birth_date int,state varchar)\";\n        q = entityManager.createNativeQuery(colFamilySql);\n        q.executeUpdate();\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"users\", \"KunderaExamples\"));\n\n        // Add indexes\n        String idxSql = \"CREATE INDEX IF NOT EXISTS ON users (birth_date)\";\n        q = entityManager.createNativeQuery(idxSql);\n        q.executeUpdate();\n        idxSql = \"CREATE INDEX IF NOT EXISTS ON users (state)\";\n        q = entityManager.createNativeQuery(idxSql);\n        q.executeUpdate();\n        // insert users.\n        String insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('bsanderson', 'Brandon Sanderson', 1975, 'UT')\";\n        q = entityManager.createNativeQuery(insertSql);\n        q.executeUpdate();\n\n        // select key and state\n        String selectSql = \"SELECT key, state FROM users\";\n        q = entityManager.createNativeQuery(selectSql);\n\n        List<Object[]> results = q.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        Assert.assertEquals(\"bsanderson\", results.get(0)[0]);\n        Assert.assertEquals(\"UT\", results.get(0)[1]);\n      //  Assert.assertEquals(null, ((Map) results.get(0)).get(\"full_name\"));\n\n        // insert users.\n        insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('prothfuss', 'Patrick Rothfuss', 1973, 'WI')\";\n        q = entityManager.createNativeQuery(insertSql);\n        q.getResultList();\n\n        insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('htayler', 'Howard Tayler', 1968, 'UT')\";\n        q = entityManager.createNativeQuery(insertSql);\n        q.getResultList();\n\n        // select all\n        String selectAll = \"SELECT * FROM users WHERE state='UT' AND birth_date > 1970 ALLOW FILTERING\";\n        q = entityManager.createNativeQuery(selectAll);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        Assert.assertEquals(\"bsanderson\", results.get(0)[0]);\n        Assert.assertEquals(\"UT\", results.get(0)[1]);\n        Assert.assertEquals(\"Brandon Sanderson\", results.get(0)[2]);\n        Assert.assertEquals(new Integer(1975), results.get(0)[3]);\n\n        String updateSql = \"UPDATE users SET full_name = 'update' WHERE key = 'bsanderson'\";\n        q = entityManager.createNativeQuery(updateSql);\n        q.getResultList();\n\n        selectAll = \"SELECT * FROM users WHERE state='UT' AND birth_date > 1970 ALLOW FILTERING\";\n        q = entityManager.createNativeQuery(selectAll);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        Assert.assertEquals(\"bsanderson\", results.get(0)[0]);\n        Assert.assertEquals(\"UT\", results.get(0)[1]);\n        Assert.assertEquals(\"update\", results.get(0)[2]);\n        Assert.assertEquals(new Integer(1975), results.get(0)[3]);\n\n        entityManager.close();\n        emf.close();\n    }\n\n    @Test\n    public void testMetadataQueries()\n    {\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"dsscalar\");\n        EntityManager entityManager = emf.createEntityManager();\n        String useNativeSql = \"SELECT keyspace_name,table_name,column_name,kind,type FROM system_schema.columns\"\n                + \" WHERE keyspace_name = 'KunderaExamples' AND table_name = 'PERSON'\";\n        Query q = entityManager.createNativeQuery(useNativeSql);\n        List<Object[]> results = q.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(6, results.size());\n\n        Assert.assertEquals(\"KunderaExamples\", results.get(0)[0]);\n        Assert.assertEquals(\"PERSON\", results.get(0)[1]);\n        Assert.assertEquals(\"AGE\", results.get(0)[2]);\n        Assert.assertEquals(\"regular\", results.get(0)[3]);\n        Assert.assertEquals(\"int\", results.get(0)[4]);\n\n        useNativeSql = \"SELECT keyspace_name, durable_writes FROM system_schema.keyspaces WHERE keyspace_name = 'KunderaExamples'\";\n        q = entityManager.createNativeQuery(useNativeSql);\n        results = q.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        Assert.assertEquals(\"KunderaExamples\", results.get(0)[0]);\n        Assert.assertEquals(true, results.get(0)[1]);\n\n        useNativeSql = \"SELECT COUNT(*) FROM system_schema.columns WHERE keyspace_name = 'KunderaExamples'AND table_name = 'PERSON'\";\n        q = entityManager.createNativeQuery(useNativeSql);\n\n        final List<Object> resultsSingle = q.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, resultsSingle.size());\n        Assert.assertEquals(6l, resultsSingle.get(0));\n\n        entityManager.close();\n        emf.close();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param rowKey\n     *            the row key\n     * @param age\n     *            the age\n     * @return the person cassandra\n     */\n    private static PersonCassandra prepareData(String rowKey, int age)\n    {\n        PersonCassandra o = new PersonCassandra();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"karthik\");\n        o.setAge(age);\n        o.setDay(Day.friday);\n        o.setMonth(Month.MAY);\n        return o;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/crud/ClassMTM.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\n/**\n * Class entity with many to many association.\n * \n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name=\"ClassMTM\")\npublic class ClassMTM\n{\n\n    @Id\n    @Column(name = \"CLASS_ID\")\n    private long classId;\n\n    @Column(name = \"topic\")\n    private String topic;\n\n    @Column(name = \"classNo\")\n    private int classNumber;\n\n    @ManyToMany(mappedBy = \"classes\", fetch = FetchType.LAZY, cascade=CascadeType.ALL)\n    private Set<StudentMTM> students= new HashSet<StudentMTM>();\n\n    public ClassMTM()\n    {\n    }\n    \n    public ClassMTM(long classId)\n    {\n        this.classId = classId;\n    }\n\n    public String getTopic()\n    {\n        return topic;\n    }\n\n    public void setTopic(String topic)\n    {\n        this.topic = topic;\n    }\n\n    public int getClassNumber()\n    {\n        return classNumber;\n    }\n\n    public void setClassNumber(int classNumber)\n    {\n        this.classNumber = classNumber;\n    }\n\n    public long getClassId()\n    {\n        return classId;\n    }\n\n    public Set<StudentMTM> getStudents()\n    {\n        return students;\n    }\n\n    public void assignStudent(StudentMTM student)\n    {\n        this.students.add(student);\n    }\n\n    \n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/crud/DSClientSecondaryTableTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.cassandra.thrift.Cassandra.Client;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class DSClientSecondaryTableTest\n{\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        loadData();\n        Map<String, String> props = new HashMap<String, String>();\n        props.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(\"ds_pu\", props);\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    @Test\n    public void test()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        SecondaryTableEntity entity = new SecondaryTableEntity();\n        entity.setAge(24);\n        entity.setObjectId(\"123\");\n        entity.setName(\"Kuldeep\");\n\n        em.persist(entity);\n\n        em.clear();\n\n        SecondaryTableEntity foundEntity = em.find(SecondaryTableEntity.class, \"123\");\n        Assert.assertNotNull(foundEntity);\n        Assert.assertEquals(\"Kuldeep\", foundEntity.getName());\n        // Assert.assertEquals(24, foundEntity.getAge());\n\n        foundEntity.setAge(25);\n        foundEntity.setName(\"kk\");\n\n        em.merge(foundEntity);\n\n        em.clear();\n\n        foundEntity = em.find(SecondaryTableEntity.class, \"123\");\n        Assert.assertNotNull(foundEntity);\n        Assert.assertEquals(\"kk\", foundEntity.getName());\n        // Assert.assertEquals(25, foundEntity.getAge());\n\n        em.remove(foundEntity);\n\n        foundEntity = em.find(SecondaryTableEntity.class, \"123\");\n        Assert.assertNull(foundEntity);\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n        String table2 = \"SECONDARY_TABLE\";\n        String keyspace = \"KunderaExamples\";\n\n        try\n        {\n            Client client = CassandraCli.getClient();\n            KsDef ksDef = client.describe_keyspace(keyspace);\n            client.set_keyspace(keyspace);\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n                if (cfDef1.getName().equalsIgnoreCase(table2))\n                {\n                    client.system_drop_column_family(table2);\n                }\n            }\n            client.execute_cql3_query(ByteBufferUtil\n                    .bytes(\"create table \\\"SECONDARY_TABLE\\\"(\\\"OBJECT_ID\\\" text PRIMARY KEY, \\\"AGE\\\" int)\"),\n                    org.apache.cassandra.thrift.Compression.NONE, org.apache.cassandra.thrift.ConsistencyLevel.ANY);\n        }\n        catch (NotFoundException e)\n        {\n\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/crud/ManyToManyAssociationTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud;\n\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Many to many association test.\n * \n * @author vivek.mishra\n */\npublic class ManyToManyAssociationTest\n{\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    private static final String _PU = \"ds_pu\";\n\n    @Before\n    public void setup() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        Map propertyMap = new HashMap();\n//        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"\");\n\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n        em = emf.createEntityManager();\n//        createSchema();\n    }\n\n    @Test\n    public void testManyToMany()\n    {\n        StudentMTM student1 = new StudentMTM(100l);\n        student1.setFirstName(\"vivek\");\n        student1.setLastName(\"mishra\");\n\n        StudentMTM student2 = new StudentMTM(101l);\n        student2.setFirstName(\"kuldeep\");\n        student2.setLastName(\"mishra\");\n\n        StudentMTM student3 = new StudentMTM(102l);\n        student3.setFirstName(\"chhavi\");\n        student3.setLastName(\"gangwal\");\n\n        StudentMTM student4 = new StudentMTM(103l);\n        student4.setFirstName(\"shaheed\");\n        student4.setLastName(\"hussain\");\n\n        ClassMTM mathClass = new ClassMTM(200l);\n        mathClass.setTopic(\"maths\");\n\n        ClassMTM scienceClass = new ClassMTM(201l);\n        scienceClass.setTopic(\"science\");\n\n        ClassMTM electricalClass = new ClassMTM(202l);\n        electricalClass.setTopic(\"electrical\");\n\n        student1.assignClass(mathClass);\n        // mathClass.assignStudent(student1);\n\n        student2.assignClass(mathClass);\n        student2.assignClass(scienceClass);\n        // mathClass.assignStudent(student2);\n        // scienceClass.assignStudent(student2);\n\n        student3.assignClass(mathClass);\n        student3.assignClass(scienceClass);\n        // mathClass.assignStudent(student3);\n        // scienceClass.assignStudent(student3);\n\n        student4.assignClass(mathClass);\n        student4.assignClass(scienceClass);\n        student4.assignClass(electricalClass);\n        // mathClass.assignStudent(student4);\n        // scienceClass.assignStudent(student4);\n\n        em.persist(student1); // with cascading effect all of these should get\n                              // persisted.\n\n        em.persist(student2);\n        em.persist(student3);\n        em.persist(student4);\n\n        em.clear();\n        StudentMTM result = em.find(StudentMTM.class, 103l);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(result.getFirstName(), \"shaheed\");\n\n        Assert.assertEquals(3, result.getClasses().size());\n\n        Iterator<ClassMTM> classIter = result.getClasses().iterator();\n        while (classIter.hasNext())\n        {\n            ClassMTM topicClass = classIter.next();\n            if (topicClass.getTopic().equals(\"electrical\"))\n            {\n                Assert.assertEquals(1, topicClass.getStudents().size());\n            }\n            else if (topicClass.getTopic().equals(\"maths\"))\n            {\n                Assert.assertEquals(4, topicClass.getStudents().size());\n            }\n            else if (topicClass.getTopic().equals(\"science\"))\n            {\n                Assert.assertEquals(3, topicClass.getStudents().size());\n            }\n            else\n            {\n                Assert.fail();\n            }\n        }\n\n        em.remove(student1); // with cascading effect all of these should get\n        // persisted.\n\n        em.remove(student2);\n        em.remove(student3);\n        em.remove(student4);\n        \n        em.clear();\n        \n        result = em.find(StudentMTM.class, 103l);\n        Assert.assertNull(result);\n        em.clear();\n        result = em.find(StudentMTM.class, 102l);\n        Assert.assertNull(result);\n        em.clear();\n        result = em.find(StudentMTM.class, 101l);\n        Assert.assertNull(result);\n        em.clear();\n        result = em.find(StudentMTM.class, 100l);\n        Assert.assertNull(result);\n    }\n\n    @After\n    public void tearDown()\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n        if (em != null)\n        {\n            em.close();\n        }\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    /**\n     * Create schema.\n     */\n    private void createSchema()\n    {\n        String createStudentTableQuery = \"create table \\\"Student\\\"(\\\"key\\\" bigint PRIMARY KEY,fname text, lname text)\";\n        String createClassTableQuery = \"create table \\\"ClassMTM\\\"(\\\"key\\\" bigint PRIMARY KEY,topic text, \\\"classNo\\\" int)\";\n        String createMappingTableQuery = \"create table \\\"STUDENT_CLASS\\\"(key text PRIMARY KEY,\\\"STUDENT_ID\\\" bigint , \\\"CLASS_ID\\\" bigint)\";\n        String classIndexQuery = \"create index on \\\"STUDENT_CLASS\\\"(\\\"CLASS_ID\\\")\";\n        String studentIndexQuery = \"create index on \\\"STUDENT_CLASS\\\"(\\\"STUDENT_ID\\\")\";\n        CassandraCli.executeCqlQuery(createStudentTableQuery, \"KunderaExamples\");\n        CassandraCli.executeCqlQuery(createClassTableQuery, \"KunderaExamples\");\n        CassandraCli.executeCqlQuery(createMappingTableQuery, \"KunderaExamples\");\n\n        CassandraCli.executeCqlQuery(classIndexQuery, \"KunderaExamples\");\n        CassandraCli.executeCqlQuery(studentIndexQuery, \"KunderaExamples\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/crud/PersonCassandra.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.NamedNativeQuery;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n\n/**\n * Sample JPA entity\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"PERSON\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\n@NamedNativeQuery(name=\"q\", query=\"select * from \\\"PERSON\\\"\")\npublic class PersonCassandra\n{\n    public static final String UID = \"uid\";\n\n    public static final String EID = \"eid\";\n\n    public static final String FIRST_NAME = \"firstName\";\n\n    public static final String LAST_NAME = \"lastName\";\n\n    public static final String CITY = \"city\";\n\n    public static final String CREATED = \"created\";\n\n    public static final String LAST_MODIFIED = \"lastModified\";\n\n    /** The person id. */\n    @Id\n    // @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"AGEss\")\n    private byte[] a;\n\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    @Column(name = \"MONTH_ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Month month;\n\n    /**\n     * @return the a\n     */\n    public byte[] getA()\n    {\n        return a;\n    }\n\n    /**\n     * @param a\n     *            the a to set\n     */\n    public void setA(byte[] a)\n    {\n        this.a = a;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the day\n     */\n    public Day getDay()\n    {\n        return day;\n    }\n\n    /**\n     * @param day\n     *            the day to set\n     */\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n\n    public Month getMonth()\n    {\n        return month;\n    }\n\n    public void setMonth(Month month)\n    {\n        this.month = month;\n    }\n\n    public enum Day\n    {\n        monday,tuesday,wednesday,thursday,friday, saturday,sunday;\n//        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/crud/SecondaryTableEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.SecondaryTable;\nimport javax.persistence.Table;\n\n/**\n * \n * @author Kuldeep.Mishra\n *\n */\n@Table(name = \"PRIMARY_TABLE\")\n@SecondaryTable(name = \"SECONDARY_TABLE\")\n@Entity\npublic class SecondaryTableEntity\n{\n    @Id\n    @Column(name = \"OBJECT_ID\")\n    private String objectId;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    @Column(name = \"AGE\", table = \"SECONDARY_TABLE\")\n    private int age;\n\n    public String getObjectId()\n    {\n        return objectId;\n    }\n\n    public void setObjectId(String objectId)\n    {\n        this.objectId = objectId;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/crud/StudentMTM.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\n/**\n * Student entity with many to many association\n * \n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"Student\")\npublic class StudentMTM\n{\n\n    @Id\n    @Column(name = \"STUDENT_ID\")\n    private long studenId;\n\n    @Column(name = \"fname\")\n    private String firstName;\n\n    @Column(name = \"lname\")\n    private String lastName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"STUDENT_CLASS\", schema = \"KunderaExamples\", joinColumns = { @JoinColumn(name = \"STUDENT_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"CLASS_ID\") })\n    private Set<ClassMTM> classes = new HashSet<ClassMTM>();\n    \n    public StudentMTM()\n    {\n    }\n\n    public StudentMTM(long studenId)\n    {\n        this.studenId = studenId;\n    }\n\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n    public long getStudenId()\n    {\n        return studenId;\n    }\n\n    public Set<ClassMTM> getClasses()\n    {\n        return classes;\n    }\n\n\n    public void assignClass(ClassMTM studentClass)\n    {\n        this.classes.add(studentClass);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/crud/collection/BlogPost.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.collection;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.NamedNativeQuery;\nimport javax.persistence.NamedQuery;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Entity class for Blog post\n * @author amresh.singh\n */\n@Entity\n@Table(name=\"blog_posts\", schema=\"KunderaExamples@ds_collection_pu\")\n@NamedNativeQuery(name=\"select.post.1\", query=\"select * from blog_posts where post_id = 1\")\n@NamedQuery(name=\"select.post.2\", query=\"Select p from BlogPost p where p.postId=2\")\n@IndexCollection(columns = { @Index(name = \"body\"), @Index(name = \"tags\"), @Index(name = \"likedBy\"), @Index(name = \"comments\") })\npublic class BlogPost\n{    \n    @Id\n    @Column(name=\"post_id\")\n    private int postId;\n    \n    //Body of the post\n    @Column(name=\"body\")\n    private String body;       \n    \n    //Useful tags specified by author\n    @ElementCollection\n    @Column(name=\"tags\")\n    private Set<String> tags;  \n    \n    //List of user IDs who liked this blog post\n    @ElementCollection\n    @Column(name=\"liked_by\")\n    private List<Integer> likedBy;   \n    \n    //User IDs and their respective comments on this blog\n    @ElementCollection\n    @Column(name=\"comments\")\n    private Map<Integer, String> comments; \n\n    /**\n     * @return the postId\n     */\n    public int getPostId()\n    {\n        return postId;\n    }\n\n    /**\n     * @param postId the postId to set\n     */\n    public void setPostId(int postId)\n    {\n        this.postId = postId;\n    }\n\n    /**\n     * @return the body\n     */\n    public String getBody()\n    {\n        return body;\n    }\n\n    /**\n     * @param body the body to set\n     */\n    public void setBody(String body)\n    {\n        this.body = body;\n    }\n\n    /**\n     * @return the tags\n     */\n    public Set<String> getTags()\n    {\n        return tags;\n    }\n\n    /**\n     * @param tags the tags to set\n     */\n    public void setTags(Set<String> tags)\n    {\n        this.tags = tags;\n    }\n\n    /**\n     * @return the likedBy\n     */\n    public List<Integer> getLikedBy()\n    {\n        return likedBy;\n    }\n\n    /**\n     * @param likedBy the likedBy to set\n     */\n    public void setLikedBy(List<Integer> likedBy)\n    {\n        this.likedBy = likedBy;\n    }\n\n    /**\n     * @return the comments\n     */\n    public Map<Integer, String> getComments()\n    {\n        return comments;\n    }\n\n    /**\n     * @param comments the comments to set\n     */\n    public void setComments(Map<Integer, String> comments)\n    {\n        this.comments = comments;\n    }\n    \n    public void addTag(String tag)\n    {\n        if(tags == null)\n        {\n            tags = new HashSet<String>();\n        }\n        tags.add(tag);\n    }\n    \n    public void addLikedBy(Integer likedByUserId)\n    {\n        if(likedBy == null)\n        {\n            likedBy = new ArrayList<Integer>();\n        }\n        likedBy.add(likedByUserId);\n    }\n    \n    public void addComment(Integer userId, String comment)\n    {\n        if(comments == null)\n        {\n            comments = new HashMap<Integer, String>();\n        }\n        comments.put(userId, comment);\n    }\n    \n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/client/crud/collection/BlogPostTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.collection;\n\nimport java.nio.ByteBuffer;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Test case for Storing and retrieving Blog posts. 1. Validates correct\n * functioning of Element collection for basic types 2. Checks all types of\n * collection (Set, Map, List)\n * \n * @author amresh.singh\n */\npublic class BlogPostTest\n{\n    EntityManagerFactory emf;\n\n    EntityManager em;\n\n    String persistenceUnit = \"ds_collection_pu\";\n\n    private boolean RUN_IN_EMBEDDED_MOODE = true;\n\n    private boolean AUTO_MANAGE_SCHEMA = true;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        if (RUN_IN_EMBEDDED_MOODE)\n        {\n            CassandraCli.cassandraSetUp();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n\n            createKeyspace();\n            createColumnFamily();\n        }\n\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        em = emf.createEntityManager();\n        em.setProperty(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        // Insert records\n        BlogPost p1 = prepareBlogPost1();\n        BlogPost p2 = prepareBlogPost2();\n\n        em.persist(p1);\n        em.persist(p2);\n\n        // Find records by ID\n        em.clear();\n        BlogPost pp1 = em.find(BlogPost.class, 1);\n        BlogPost pp2 = em.find(BlogPost.class, 2);\n\n        assertPost1(pp1);\n        assertPost2(pp2);\n\n        // Update records\n        modifyBlogPost1(pp1);\n        modifyBlogPost2(pp2);\n\n        em.merge(pp1);\n        em.merge(pp2);\n\n        em.clear();\n        pp1 = em.find(BlogPost.class, 1);\n        pp2 = em.find(BlogPost.class, 2);\n\n        assertUpdatedPost1(pp1);\n        assertUpdatedPost2(pp2);\n\n        // Remove records\n        em.remove(pp1);\n        em.remove(pp2);\n\n        em.clear();\n        pp1 = em.find(BlogPost.class, 1);\n        pp2 = em.find(BlogPost.class, 2);\n\n        Assert.assertNull(pp1);\n        Assert.assertNull(pp2);\n    }\n\n    @Test\n    public void testJPAQuery()\n    {\n        // Insert records\n        BlogPost p1 = prepareBlogPost1();\n        BlogPost p2 = prepareBlogPost2();\n\n        em.persist(p1);\n        em.persist(p2);\n\n        // Select All query\n        Query q = em.createQuery(\"Select p from BlogPost p\");\n        List<BlogPost> allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(2, allPosts.size());\n        assertPost1(allPosts.get(0));\n        assertPost2(allPosts.get(1));\n\n        // Search over Row ID\n        q = em.createQuery(\"Select p from BlogPost p where p.postId=:postId\");\n        q.setParameter(\"postId\", 1);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertPost1(allPosts.get(0));\n\n        // Search over Body column\n        q = em.createQuery(\"Select p from BlogPost p where p.body=:body\");\n        q.setParameter(\"body\", \"Kundera - Knight in the shining armor!\");\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertPost2(allPosts.get(0));\n\n        // Update Query\n        q = em.createQuery(\"update BlogPost p set p.body=:body,p.tags=:tags,p.likedBy=:likedBy,p.comments=:comments where p.postId=1\");\n        modifyBlogPost1(p1);\n        q.setParameter(\"body\", p1.getBody());\n        q.setParameter(\"tags\", p1.getTags());\n        q.setParameter(\"likedBy\", p1.getLikedBy());\n        q.setParameter(\"comments\", p1.getComments());\n        int updatedRecords = q.executeUpdate();\n\n        em.clear();\n        q = em.createQuery(\"Select p from BlogPost p where p.postId=:postId\");\n        q.setParameter(\"postId\", 1);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertUpdatedPost1(allPosts.get(0));\n\n        // Named Query\n        em.clear();\n        q = em.createNamedQuery(\"select.post.2\");\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertPost2(allPosts.get(0));\n\n        // Delete Query\n        q = em.createQuery(\"DELETE from BlogPost\");\n        int deleteCount = q.executeUpdate();\n        Assert.assertEquals(2, deleteCount);\n\n        em.clear();\n        q = em.createQuery(\"Select p from BlogPost p\");\n        allPosts = q.getResultList();\n        Assert.assertTrue(allPosts == null || allPosts.isEmpty());\n    }\n\n    @Test\n    public void testNativeQuery()\n    {\n        // Insert records\n        BlogPost p1 = prepareBlogPost1();\n        BlogPost p2 = prepareBlogPost2();\n\n        em.persist(p1);\n        em.persist(p2);\n\n        // Select All query\n        Query q = em.createNativeQuery(\"select * from blog_posts\", BlogPost.class);\n        List<BlogPost> allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(2, allPosts.size());\n        assertPost1(allPosts.get(0));\n        assertPost2(allPosts.get(1));\n\n        // Search over a column\n        q = em.createNativeQuery(\"select * from blog_posts where body='Working with MongoDB using Kundera'\",\n                BlogPost.class);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertPost1(allPosts.get(0));\n\n        // Updating set, list and map for Blog Post 1\n        q = em.createNativeQuery(\"update blog_posts set body = 'Updated body 1' where post_id = 1\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"update blog_posts set tags = tags + {'new tag 1'} where post_id = 1\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"update blog_posts set liked_by = liked_by - [111] where post_id = 1\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"update blog_posts set comments = comments + {888:'New comment 1'} where post_id = 1\",\n                BlogPost.class);\n        q.executeUpdate();\n\n        q = em.createNativeQuery(\"select * from blog_posts where post_id = 1\", BlogPost.class);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertUpdatedPost1(allPosts.get(0));\n\n        // Updating set, list and map for Blog Post 2\n        q = em.createNativeQuery(\"update blog_posts set body = 'Updated body 2' where post_id = 2\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"update blog_posts set tags = tags + {'new tag 2'} where post_id = 2\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"update blog_posts set liked_by = liked_by - [444] where post_id = 2\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"update blog_posts set comments = comments + {999:'New comment 2'} where post_id = 2\",\n                BlogPost.class);\n        q.executeUpdate();\n\n        // Native select query\n        q = em.createNativeQuery(\"select * from blog_posts where post_id = 2\", BlogPost.class);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertUpdatedPost2(allPosts.get(0));\n\n        // Named native query\n        q = em.createNativeQuery(\"select.post.1\", BlogPost.class);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertUpdatedPost1(allPosts.get(0));\n\n        // Delete all posts\n        q = em.createNativeQuery(\"delete from blog_posts where post_id = 1\", BlogPost.class);\n        q.executeUpdate();\n        q = em.createNativeQuery(\"delete from blog_posts where post_id = 2\", BlogPost.class);\n        q.executeUpdate();\n\n        q = em.createNativeQuery(\"select * from blog_posts\", BlogPost.class);\n        allPosts = q.getResultList();\n        Assert.assertTrue(allPosts == null || allPosts.isEmpty());\n    }\n\n    @Test\n    public void testCollectionWithNullValues()\n    {\n        // Insert records\n        BlogPost p1 = prepareBlogPost1();\n        BlogPost p2 = prepareBlogPost2();\n\n        try\n        {\n            // Testing map containing null as value.\n            p1.addComment(444, null);\n            em.persist(p1);\n            Assert.fail(\"Should have gone into catch block.\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\"com.impetus.kundera.KunderaException: com.datastax.driver.core.exceptions.InvalidQueryException: null is not supported inside collections\", e.getMessage());\n        }\n        try\n        {\n            // Testing map containing null as key and value.\n            p2.addComment(null, null);\n            em.persist(p2);\n            Assert.fail(\"Should have gone into catch block.\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\"com.impetus.kundera.KunderaException: com.datastax.driver.core.exceptions.InvalidQueryException: null is not supported inside collections\", e.getMessage());\n        }\n\n        p1 = prepareBlogPost1();\n        p2 = prepareBlogPost2();\n\n        try\n        {\n            // Testing list containing null as value.\n            p1.addLikedBy(null);\n            em.persist(p1);\n            Assert.fail(\"Should have gone into catch block.\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\"com.impetus.kundera.KunderaException: com.datastax.driver.core.exceptions.InvalidQueryException: null is not supported inside collections\", e.getMessage());\n        }\n\n        try\n        {\n            // Testing set containing null as value.\n            p2.addTag(null);\n            em.persist(p2);\n            Assert.fail(\"Should have gone into catch block.\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\"com.impetus.kundera.KunderaException: com.datastax.driver.core.exceptions.InvalidQueryException: null is not supported inside collections\", e.getMessage());\n        }\n\n    }\n    \n    @Test\n    public void testCollectionIndexes()\n    {\n        // Insert records\n        BlogPost p1 = prepareBlogPost1();\n        BlogPost p2 = prepareBlogPost2();\n\n        em.persist(p1);\n        em.persist(p2);\n        \n        em.clear();\n\n        // Select All query\n        Query q = em.createQuery(\"Select p from BlogPost p\");\n        List<BlogPost> allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(2, allPosts.size());\n        assertPost1(allPosts.get(0));\n        assertPost2(allPosts.get(1));\n\n        // Search over tags Set\n        q = em.createQuery(\"Select p from BlogPost p where p.tags = :tags\");\n        q.setParameter(\"tags\", \"nosql\");\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(2, allPosts.size());\n        assertPost1(allPosts.get(0));\n        assertPost2(allPosts.get(1));\n\n        // Search over likedBy List\n        q = em.createQuery(\"Select p from BlogPost p where p.likedBy = :likedBy\");\n        q.setParameter(\"likedBy\", 555);\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertPost2(allPosts.get(0));\n\n     // Search over comments Map\n        q = em.createQuery(\"Select p from BlogPost p where p.comments = :comments\");\n        q.setParameter(\"comments\", \"Great work\");\n        allPosts = q.getResultList();\n        Assert.assertNotNull(allPosts);\n        Assert.assertFalse(allPosts.isEmpty());\n        Assert.assertEquals(1, allPosts.size());\n        assertPost2(allPosts.get(0));\n\n    }\n\n    private BlogPost prepareBlogPost1()\n    {\n        BlogPost p1 = new BlogPost();\n        p1.setPostId(1);\n        p1.setBody(\"Working with MongoDB using Kundera\");\n\n        p1.addTag(\"nosql\");\n        p1.addTag(\"kundera\");\n        p1.addTag(\"mongo\");\n\n        p1.addLikedBy(111);\n        p1.addLikedBy(222);\n\n        p1.addComment(111, \"What a post!\");\n        p1.addComment(222, \"I am getting NPE on line no. 145\");\n        p1.addComment(333, \"My hobby is to spam blogs\");\n        return p1;\n    }\n\n    private BlogPost prepareBlogPost2()\n    {\n        BlogPost p2 = new BlogPost();\n        p2.setPostId(2);\n        p2.setBody(\"Kundera - Knight in the shining armor!\");\n\n        p2.addTag(\"nosql\");\n        p2.addTag(\"cassandra\");\n        p2.addTag(\"kundera\");\n        p2.addTag(\"jpa\");\n\n        p2.addLikedBy(333);\n        p2.addLikedBy(444);\n        p2.addLikedBy(555);\n\n        p2.addComment(333, \"Great work\");\n        p2.addComment(555, \"Doesn't work on my machine\");\n        p2.addComment(777, \"Wanna buy medicines from my store?\");\n        return p2;\n    }\n\n    private void modifyBlogPost1(BlogPost p)\n    {\n        p.setBody(\"Updated body 1\");\n        p.getTags().add(\"new tag 1\");\n        p.getLikedBy().remove(0);\n        p.addComment(888, \"New comment 1\");\n    }\n\n    private void modifyBlogPost2(BlogPost p)\n    {\n        p.setBody(\"Updated body 2\");\n        p.getTags().add(\"new tag 2\");\n        p.getLikedBy().remove(1);\n        p.addComment(999, \"New comment 2\");\n    }\n\n    private void assertPost1(BlogPost p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPostId());\n        Assert.assertEquals(\"Working with MongoDB using Kundera\", p.getBody());\n\n        Assert.assertNotNull(p.getTags());\n        Assert.assertFalse(p.getTags().isEmpty());\n        Assert.assertEquals(3, p.getTags().size());\n        for (String tag : p.getTags())\n        {\n            Assert.assertTrue(tag.equals(\"nosql\") || tag.equals(\"kundera\") || tag.equals(\"mongo\"));\n        }\n\n        Assert.assertNotNull(p.getLikedBy());\n        Assert.assertFalse(p.getLikedBy().isEmpty());\n        Assert.assertEquals(2, p.getLikedBy().size());\n        for (int likedUserId : p.getLikedBy())\n        {\n            Assert.assertTrue(likedUserId == 111 || likedUserId == 222);\n        }\n\n        Assert.assertNotNull(p.getComments());\n        Assert.assertFalse(p.getComments().isEmpty());\n        Assert.assertEquals(3, p.getComments().size());\n        for (int commentedBy : p.getComments().keySet())\n        {\n            String commentText = p.getComments().get(commentedBy);\n            Assert.assertTrue(commentedBy == 111 || commentedBy == 222 || commentedBy == 333);\n            Assert.assertTrue(commentText.equals(\"What a post!\")\n                    || commentText.equals(\"I am getting NPE on line no. 145\")\n                    || commentText.equals(\"My hobby is to spam blogs\"));\n        }\n    }\n\n    private void assertPost2(BlogPost p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(2, p.getPostId());\n        Assert.assertEquals(\"Kundera - Knight in the shining armor!\", p.getBody());\n\n        Assert.assertNotNull(p.getTags());\n        Assert.assertFalse(p.getTags().isEmpty());\n        Assert.assertEquals(4, p.getTags().size());\n        for (String tag : p.getTags())\n        {\n            Assert.assertTrue(tag.equals(\"nosql\") || tag.equals(\"cassandra\") || tag.equals(\"kundera\")\n                    || tag.equals(\"jpa\"));\n        }\n\n        Assert.assertNotNull(p.getLikedBy());\n        Assert.assertFalse(p.getLikedBy().isEmpty());\n        Assert.assertEquals(3, p.getLikedBy().size());\n        for (int likedUserId : p.getLikedBy())\n        {\n            Assert.assertTrue(likedUserId == 333 || likedUserId == 444 || likedUserId == 555);\n        }\n\n        Assert.assertNotNull(p.getComments());\n        Assert.assertFalse(p.getComments().isEmpty());\n        Assert.assertEquals(3, p.getComments().size());\n        for (int commentedBy : p.getComments().keySet())\n        {\n            String commentText = p.getComments().get(commentedBy);\n            Assert.assertTrue(commentedBy == 333 || commentedBy == 555 || commentedBy == 777);\n            Assert.assertTrue(commentText.equals(\"Great work\") || commentText.equals(\"Doesn't work on my machine\")\n                    || commentText.equals(\"Wanna buy medicines from my store?\"));\n        }\n    }\n\n    private void assertUpdatedPost1(BlogPost p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPostId());\n        Assert.assertEquals(\"Updated body 1\", p.getBody());\n\n        Assert.assertNotNull(p.getTags());\n        Assert.assertFalse(p.getTags().isEmpty());\n        Assert.assertEquals(4, p.getTags().size());\n        for (String tag : p.getTags())\n        {\n            Assert.assertTrue(tag.equals(\"nosql\") || tag.equals(\"kundera\") || tag.equals(\"mongo\")\n                    || tag.equals(\"new tag 1\"));\n        }\n\n        Assert.assertNotNull(p.getLikedBy());\n        Assert.assertFalse(p.getLikedBy().isEmpty());\n        Assert.assertEquals(1, p.getLikedBy().size());\n        for (int likedUserId : p.getLikedBy())\n        {\n            Assert.assertTrue(likedUserId == 222);\n        }\n\n        Assert.assertNotNull(p.getComments());\n        Assert.assertFalse(p.getComments().isEmpty());\n        Assert.assertEquals(4, p.getComments().size());\n        for (int commentedBy : p.getComments().keySet())\n        {\n            String commentText = p.getComments().get(commentedBy);\n            Assert.assertTrue(commentedBy == 111 || commentedBy == 222 || commentedBy == 333 || commentedBy == 888);\n            Assert.assertTrue(commentText.equals(\"What a post!\")\n                    || commentText.equals(\"I am getting NPE on line no. 145\")\n                    || commentText.equals(\"My hobby is to spam blogs\") || commentText.equals(\"New comment 1\"));\n        }\n\n    }\n\n    private void assertUpdatedPost2(BlogPost p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(2, p.getPostId());\n        Assert.assertEquals(\"Updated body 2\", p.getBody());\n\n        Assert.assertNotNull(p.getTags());\n        Assert.assertFalse(p.getTags().isEmpty());\n        Assert.assertEquals(5, p.getTags().size());\n        for (String tag : p.getTags())\n        {\n            Assert.assertTrue(tag.equals(\"nosql\") || tag.equals(\"cassandra\") || tag.equals(\"kundera\")\n                    || tag.equals(\"jpa\") || tag.equals(\"new tag 2\"));\n        }\n\n        Assert.assertNotNull(p.getLikedBy());\n        Assert.assertFalse(p.getLikedBy().isEmpty());\n        Assert.assertEquals(2, p.getLikedBy().size());\n        for (int likedUserId : p.getLikedBy())\n        {\n            Assert.assertTrue(likedUserId == 333 || likedUserId == 555);\n        }\n\n        Assert.assertNotNull(p.getComments());\n        Assert.assertFalse(p.getComments().isEmpty());\n        Assert.assertEquals(4, p.getComments().size());\n        for (int commentedBy : p.getComments().keySet())\n        {\n            String commentText = p.getComments().get(commentedBy);\n            Assert.assertTrue(commentedBy == 333 || commentedBy == 555 || commentedBy == 777 || commentedBy == 999);\n            Assert.assertTrue(commentText.equals(\"Great work\") || commentText.equals(\"Doesn't work on my machine\")\n                    || commentText.equals(\"Wanna buy medicines from my store?\") || commentText.equals(\"New comment 2\"));\n        }\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        if (emf != null && emf.isOpen())\n        {\n            emf.close();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            CassandraCli.executeCqlQuery(\"TRUNCATE blog_posts\", \"KunderaExamples\");\n            CassandraCli.executeCqlQuery(\"DROP TABLE blog_posts\", \"KunderaExamples\");\n            CassandraCli.executeCqlQuery(\"DROP KEYSPACE \\\"KunderaExamples\\\"\", \"KunderaExamples\");\n        }\n\n    }\n\n    private void createColumnFamily()\n    {\n        try\n        {\n            CassandraCli.executeCqlQuery(\"USE \\\"KunderaExamples\\\"\", \"KunderaExamples\");\n            CassandraCli\n                    .executeCqlQuery(\n                            \"CREATE TABLE blog_posts (post_id int PRIMARY KEY, body text, tags set<text>, liked_by list<int>, comments map<int, text>)\",\n                            \"KunderaExamples\");\n            CassandraCli.executeCqlQuery(\"CREATE INDEX ON blog_posts(body)\", \"KunderaExamples\");\n            CassandraCli.executeCqlQuery(\"CREATE INDEX ON blog_posts(tags)\", \"KunderaExamples\");\n            CassandraCli.executeCqlQuery(\"CREATE INDEX ON blog_posts(comments)\", \"KunderaExamples\");\n            CassandraCli.executeCqlQuery(\"CREATE INDEX ON blog_posts(liked_by)\", \"KunderaExamples\");\n        }\n        catch (Exception e)\n        {\n        }\n    }\n\n    private void createKeyspace()\n    {\n        try\n        {\n            CassandraCli\n                    .getClient()\n                    .execute_cql3_query(\n                            ByteBuffer.wrap(\"CREATE KEYSPACE \\\"KunderaExamples\\\" WITH replication = {'class':'SimpleStrategy','replication_factor':3}\"\n                                    .getBytes(\"UTF-8\")), Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception e)\n        {\n\n        }\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/composite/CompoundKeyDataType.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.composite;\n\nimport java.math.BigInteger;\nimport java.util.Calendar;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\n/**\n * Composite key entity containing all data types.\n * \n * @author vivek.mishra\n */\n@Embeddable\npublic class CompoundKeyDataType\n{\n\n    // Primitive Types\n    // @Id\n    @Column(name = \"STUDENT_ID\")\n    private long studentId;\n\n    @Column(name = \"UNIQUE_ID\")\n    private long uniqueId;\n\n    @Column(name = \"STUDENT_NAME\")\n    private String studentName;\n\n    @Column(name = \"IS_EXCEPTIONAL\")\n    private boolean isExceptional;\n\n    @Column(name = \"AGE\")\n    private int age;\n\n    @Column(name = \"SEMESTER\")\n    private char semester; // A,B,C,D,E,F for i to vi\n\n    @Column(name = \"DIGITAL_SIGNATURE\")\n    private byte digitalSignature;\n\n    @Column(name = \"CGPA\")\n    private short cgpa; // 1-10\n\n    @Column(name = \"PERCENTAGE\")\n    private float percentage;\n\n    @Column(name = \"HEIGHT\")\n    private double height;\n\n    // Date-time types\n    @Column(name = \"ENROLMENT_DATE\")\n    @Temporal(TemporalType.DATE)\n    private java.util.Date enrolmentDate;\n\n    @Column(name = \"ENROLMENT_TIME\")\n    @Temporal(TemporalType.TIME)\n    private java.util.Date enrolmentTime;\n\n    @Column(name = \"JOINING_DATE_TIME\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private java.util.Date joiningDateAndTime;\n\n    // Wrapper types\n\n    @Column(name = \"YEARS_SPENT\")\n    private Integer yearsSpent;\n\n    @Column(name = \"ROLL_NUMBER\")\n    private Long rollNumber;\n\n    @Column(name = \"MONTHLY_FEE\")\n    private Double monthlyFee;\n\n    @Column(name = \"SQL_DATE\")\n    private java.sql.Date sqlDate;\n\n    @Column(name = \"SQL_TIMESTAMP\")\n    private java.sql.Timestamp sqlTimestamp;\n\n    @Column(name = \"SQL_TIME\")\n    private java.sql.Time sqlTime;\n\n    @Column(name = \"BIG_INT\")\n    private BigInteger bigInteger;\n\n    // @Column(name = \"BIG_DECIMAL\")\n    // private BigDecimal bigDecimal;\n\n    @Column(name = \"CALENDAR\")\n    private Calendar calendar;\n\n    /**\n     * \n     */\n    public CompoundKeyDataType()\n    {\n    }\n\n    /**\n     * @return the studentId\n     */\n    public long getStudentId()\n    {\n        return studentId;\n    }\n\n    /**\n     * @param studentId\n     *            the studentId to set\n     */\n    public void setStudentId(long studentId)\n    {\n        this.studentId = studentId;\n    }\n\n    /**\n     * @return the uniqueId\n     */\n    public long getUniqueId()\n    {\n        return uniqueId;\n    }\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    public void setUniqueId(long uniqueId)\n    {\n        this.uniqueId = uniqueId;\n    }\n\n    /**\n     * @return the studentName\n     */\n    public String getStudentName()\n    {\n        return studentName;\n    }\n\n    /**\n     * @param studentName\n     *            the studentName to set\n     */\n    public void setStudentName(String studentName)\n    {\n        this.studentName = studentName;\n    }\n\n    /**\n     * @return the isExceptional\n     */\n    public boolean isExceptional()\n    {\n        return isExceptional;\n    }\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    public void setExceptional(boolean isExceptional)\n    {\n        this.isExceptional = isExceptional;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the semester\n     */\n    public char getSemester()\n    {\n        return semester;\n    }\n\n    /**\n     * @param semester\n     *            the semester to set\n     */\n    public void setSemester(char semester)\n    {\n        this.semester = semester;\n    }\n\n    /**\n     * @return the digitalSignature\n     */\n    public byte getDigitalSignature()\n    {\n        return digitalSignature;\n    }\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    public void setDigitalSignature(byte digitalSignature)\n    {\n        this.digitalSignature = digitalSignature;\n    }\n\n    /**\n     * @return the cgpa\n     */\n    public short getCgpa()\n    {\n        return cgpa;\n    }\n\n    /**\n     * @param cgpa\n     *            the cgpa to set\n     */\n    public void setCgpa(short cgpa)\n    {\n        this.cgpa = cgpa;\n    }\n\n    /**\n     * @return the percentage\n     */\n    public float getPercentage()\n    {\n        return percentage;\n    }\n\n    /**\n     * @param percentage\n     *            the percentage to set\n     */\n    public void setPercentage(float percentage)\n    {\n        this.percentage = percentage;\n    }\n\n    /**\n     * @return the height\n     */\n    public double getHeight()\n    {\n        return height;\n    }\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    public void setHeight(double height)\n    {\n        this.height = height;\n    }\n\n    /**\n     * @return the enrolmentDate\n     */\n    public java.util.Date getEnrolmentDate()\n    {\n        return enrolmentDate;\n    }\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    public void setEnrolmentDate(java.util.Date enrolmentDate)\n    {\n        this.enrolmentDate = enrolmentDate;\n    }\n\n    /**\n     * @return the enrolmentTime\n     */\n    public java.util.Date getEnrolmentTime()\n    {\n        return enrolmentTime;\n    }\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    public void setEnrolmentTime(java.util.Date enrolmentTime)\n    {\n        this.enrolmentTime = enrolmentTime;\n    }\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    public java.util.Date getJoiningDateAndTime()\n    {\n        return joiningDateAndTime;\n    }\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    public void setJoiningDateAndTime(java.util.Date joiningDateAndTime)\n    {\n        this.joiningDateAndTime = joiningDateAndTime;\n    }\n\n    /**\n     * @return the yearsSpent\n     */\n    public Integer getYearsSpent()\n    {\n        return yearsSpent;\n    }\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    public void setYearsSpent(Integer yearsSpent)\n    {\n        this.yearsSpent = yearsSpent;\n    }\n\n    /**\n     * @return the rollNumber\n     */\n    public Long getRollNumber()\n    {\n        return rollNumber;\n    }\n\n    /**\n     * @param rollNumber\n     *            the rollNumber to set\n     */\n    public void setRollNumber(Long rollNumber)\n    {\n        this.rollNumber = rollNumber;\n    }\n\n    /**\n     * @return the monthlyFee\n     */\n    public Double getMonthlyFee()\n    {\n        return monthlyFee;\n    }\n\n    /**\n     * @param monthlyFee\n     *            the monthlyFee to set\n     */\n    public void setMonthlyFee(Double monthlyFee)\n    {\n        this.monthlyFee = monthlyFee;\n    }\n\n    public java.sql.Date getSqlDate()\n    {\n        return sqlDate;\n    }\n\n    public void setSqlDate(java.sql.Date sqlDate)\n    {\n        this.sqlDate = sqlDate;\n    }\n\n    /**\n     * @return the sqlTimestamp\n     */\n    public java.sql.Timestamp getSqlTimestamp()\n    {\n        return sqlTimestamp;\n    }\n\n    /**\n     * @param sqlTimestamp\n     *            the sqlTimestamp to set\n     */\n    public void setSqlTimestamp(java.sql.Timestamp sqlTimestamp)\n    {\n        this.sqlTimestamp = sqlTimestamp;\n    }\n\n    /**\n     * @return the sqlTime\n     */\n    public java.sql.Time getSqlTime()\n    {\n        return sqlTime;\n    }\n\n    /**\n     * @param sqlTime\n     *            the sqlTime to set\n     */\n    public void setSqlTime(java.sql.Time sqlTime)\n    {\n        this.sqlTime = sqlTime;\n    }\n\n    /**\n     * @return the bigInteger\n     */\n    public BigInteger getBigInteger()\n    {\n        return bigInteger;\n    }\n\n    /**\n     * @param bigInteger\n     *            the bigInteger to set\n     */\n    public void setBigInteger(BigInteger bigInteger)\n    {\n        this.bigInteger = bigInteger;\n    }\n\n    // /**\n    // * @return the bigDecimal\n    // */\n    // public BigDecimal getBigDecimal()\n    // {\n    // return bigDecimal;\n    // }\n    //\n    // /**\n    // * @param bigDecimal\n    // * the bigDecimal to set\n    // */\n    // public void setBigDecimal(BigDecimal bigDecimal)\n    // {\n    // this.bigDecimal = bigDecimal;\n    // }\n\n    /**\n     * @return the calendar\n     */\n    public Calendar getCalendar()\n    {\n        return calendar;\n    }\n\n    /**\n     * @param calendar\n     *            the calendar to set\n     */\n    public void setCalendar(Calendar calendar)\n    {\n        this.calendar = calendar;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/composite/DSCQLTranslatorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.composite;\n\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.thrift.CQLTranslator;\nimport com.impetus.client.cassandra.thrift.CQLTranslator.TranslationType;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * JUnit for CQL translator test\n * \n * @author vivek.mishra\n * \n */\npublic class DSCQLTranslatorTest\n{\n    private EntityManagerFactory emf;\n\n    private static final Logger logger = LoggerFactory.getLogger(DSCompositeTypeTest.class);\n    \n    private static final String KEYSPACE = \"KunderaExamples\";\n\n    private static final String _PU=\"ds_composite_pu\";\n    \n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n    \tCassandraCli.dropKeySpace(KEYSPACE);\n        CassandraCli.cassandraSetUp();\n        emf = Persistence.createEntityManagerFactory(_PU);\n    }\n\n    @Test\n    public void testPrepareColumns()\n    {\n        logger.info(\"On prepare columns.\");\n        CQLTranslator translator = new CQLTranslator();\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        UserTimeLine key = new UserTimeLine(\"mevivs\", 1, timeLineId);\n        PrimeUser user = new PrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance(), PrimeUser.class);\n        Map<String, StringBuilder> translatedSql = translator\n                .prepareColumnOrColumnValues(user, entityMetadata, TranslationType.VALUE, null, ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance()).get(\n                        TranslationType.VALUE);\n        String columnAsCsv = \"'mevivs',1,\" + timeLineId /*+ \",'my first tweet','\" + currentDate.getTime() + */ /*+ \"'\"*/;\n        \n        Assert.assertTrue(StringUtils.contains(translatedSql.get(entityMetadata.getTableName()).toString(), columnAsCsv));\n//        Assert.assertEquals(columnAsCsv, translatedSql);\n    }\n    \n    @Test\n    public void testGetKeyword()\n    {\n        CQLTranslator translator = new CQLTranslator();\n        Assert.assertEquals(\"read_repair_chance\", translator.getKeyword(CassandraConstants.READ_REPAIR_CHANCE));\n        Assert.assertEquals(\"dclocal_read_repair_chance\", translator.getKeyword(CassandraConstants.DCLOCAL_READ_REPAIR_CHANCE));\n        Assert.assertEquals(\"bloom_filter_fp_chance\", translator.getKeyword(CassandraConstants.BLOOM_FILTER_FP_CHANCE));\n        Assert.assertEquals(\"compaction_strategy_class\", translator.getKeyword(CassandraConstants.COMPACTION_STRATEGY));\n        Assert.assertEquals(\"bloom_filter_fp_chance\", translator.getKeyword(CassandraConstants.BLOOM_FILTER_FP_CHANCE));\n        Assert.assertEquals(\"replicate_on_write\", translator.getKeyword(CassandraConstants.REPLICATE_ON_WRITE));\n        Assert.assertEquals(\"caching\", translator.getKeyword(CassandraConstants.CACHING));\n        Assert.assertEquals(\"comment\", translator.getKeyword(CassandraConstants.COMMENT));\n        Assert.assertEquals(\"gc_grace_seconds\", translator.getKeyword(CassandraConstants.GC_GRACE_SECONDS));    \n        \n    }\n\n    @After\n    public void tearDown()\n    {\n        CassandraCli.dropKeySpace(KEYSPACE);\n        emf.close();\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/composite/DSCompositeDataTypeTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.composite;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Junit test case for Compound/Composite key.\n * \n * @author vivek.mishra\n * \n */\npublic class DSCompositeDataTypeTest\n{\n\n    /**\n     * \n     */\n    private static final String PERSISTENCE_UNIT = \"ds_composite_pu\";\n\n    private EntityManagerFactory emf;\n\n    /** The enrolment date. */\n    protected Date enrolmentDate = new Date(Long.parseLong(\"1344079065781\"));\n\n    /** The joining date and time. */\n    protected Date joiningDateAndTime = new Date();\n\n    /** The date. */\n    protected long date = new Date().getTime();\n\n    /** The new sql date. */\n    protected java.sql.Date newSqlDate = new java.sql.Date(date);\n\n    /** The enrolment time. */\n    protected Date enrolmentTime = new Date();\n\n    /** The sql time. */\n    protected java.sql.Time sqlTime = new java.sql.Time(date);\n\n    /** The sql timestamp. */\n    protected java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(date);\n\n    /** The big decimal. */\n    protected BigDecimal bigDecimal = new BigDecimal(123456789);\n\n    /** The big integer. */\n    protected BigInteger bigInteger = new BigInteger(\"123456789\");\n\n    /** The number of students. */\n    protected int numberOfStudents = 1000;\n\n    /** The calendar. */\n    protected Calendar calendar = Calendar.getInstance();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n//        CassandraCli.initClient();\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n    }\n\n    /**\n     * CRUD over Compound primary Key.\n     * \n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     */\n    @Test\n    public void onCRUD() throws InstantiationException, IllegalAccessException\n    {\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        CompoundKeyDataType key = prepareData(new Long(12345677), 78575785897L, \"Amresh\", false, 10, 'A', (byte) 5,\n                (short) 8, (float) 69.3, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime,\n                new Integer(3), new Long(978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal,\n                bigInteger, calendar, CompoundKeyDataType.class.newInstance());\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n        PrimeUserDataType user = new PrimeUserDataType(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        user.setIsActive(true);\n        em.persist(user);\n\n        em.clear(); // optional,just to clear persistence cache.\n\n        PrimeUserDataType result = em.find(PrimeUserDataType.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"my first tweet\", result.getTweetBody());\n        // Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n        Assert.assertTrue(result.getIsActive());\n\n        em.clear();// optional,just to clear persistence cache.\n\n        user.setTweetBody(\"After merge\");\n        em.merge(user);\n\n        em.clear();// optional,just to clear persistence cache.\n\n        result = em.find(PrimeUserDataType.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"After merge\", result.getTweetBody());\n        // Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n\n        // deleting composite\n        em.remove(result);\n\n        em.clear();// optional,just to clear persistence cache.\n\n        result = em.find(PrimeUserDataType.class, key);\n        Assert.assertNull(result);\n    }\n\n    @Test\n    public void onQuery() throws InstantiationException, IllegalAccessException\n    {\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        CompoundKeyDataType key = prepareData(new Long(12345677), 78575785897L, \"Amresh\", false, 10, 'A', (byte) 5,\n                (short) 8, (float) 69.3, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime,\n                new Integer(3), new Long(978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal,\n                bigInteger, calendar, CompoundKeyDataType.class.newInstance());\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        PrimeUserDataType user = new PrimeUserDataType(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.clear(); // optional,just to clear persistence cache.\n        final String noClause = \"Select u from PrimeUserDataType u\";\n\n        // secondary index support over compound key is not enabled in cassandra\n        // composite keys yet. DO NOT DELETE/UNCOMMENT.\n\n        // final String withClauseOnNoncomposite =\n        // \"Select u from PrimeUserDataType u where u.tweetDate = ?1\";\n\n        final String withFirstCompositeColClause = \"Select u from PrimeUserDataType u where u.key.studentId = :studentId\";\n        final String withSecondCompositeColClause = \"Select u from PrimeUserDataType u where u.key.uniqueId >= :uniqueId1 and u.key.uniqueId <= :uniqueId2\";\n        final String withBothCompositeColClause = \"Select u from PrimeUserDataType u where u.key.studentId = :studentId and u.key.uniqueId = :uniqueId\";\n        final String withSelectiveCompositeColClause = \"Select u.key from PrimeUserDataType u where u.key = :key\";\n\n        final String withAllCompositeColClause = \"Select u from PrimeUserDataType u where u.key.studentId = :studentId and u.key.uniqueId = :uniqueId and u.key.studentName = :studentName and u.key.isExceptional = :isExceptional and u.key.age = :age and u.key.semester = :semester and u.key.digitalSignature = :digitalSignature and u.key.cgpa = :cgpa and u.key.percentage = :percentage and u.key.height = :height and u.key.enrolmentDate = :enrolmentDate and u.key.enrolmentTime = :enrolmentTime and u.key.joiningDateAndTime = :joiningDateAndTime and u.key.yearsSpent = :yearsSpent and u.key.rollNumber = :rollNumber and u.key.monthlyFee = :monthlyFee and u.key.sqlDate = :sqlDate and u.key.sqlTimestamp = :sqlTimestamp and u.key.sqlTime = :sqlTime and u.key.bigInteger = :bigInteger and u.key.calendar = :calendar\";\n        final String selectiveColumnTweetBodyWithAllCompositeColClause = \"Select u.tweetBody from PrimeUserDataType u where u.key.studentId = :studentId and u.key.uniqueId = :uniqueId and u.key.studentName = :studentName and u.key.isExceptional = :isExceptional and u.key.age = :age and u.key.semester = :semester and u.key.digitalSignature = :digitalSignature and u.key.cgpa = :cgpa and u.key.percentage = :percentage and u.key.height = :height and u.key.enrolmentDate = :enrolmentDate and u.key.enrolmentTime = :enrolmentTime and u.key.joiningDateAndTime = :joiningDateAndTime and u.key.yearsSpent = :yearsSpent and u.key.rollNumber = :rollNumber and u.key.monthlyFee = :monthlyFee and u.key.sqlDate = :sqlDate and u.key.sqlTimestamp = :sqlTimestamp and u.key.sqlTime = :sqlTime and u.key.bigInteger = :bigInteger and u.key.calendar = :calendar\";\n\n        // query over 1 composite and 1 non-column\n\n        // query with no clause.\n        Query q = em.createQuery(noClause);\n        List<PrimeUserDataType> results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withFirstCompositeColClause);\n        q.setParameter(\"studentId\", new Long(12345677));\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // secondary index support over compound key is not enabled in cassandra\n        // composite keys yet. DO NOT DELETE/UNCOMMENT.\n\n        // Query with composite key clause.\n        // q = em.createQuery(withClauseOnNoncomposite);\n        // q.setParameter(1, currentDate);\n        // results = q.getResultList();\n        // Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withSecondCompositeColClause);\n        q.setParameter(\"uniqueId1\", 78575785897L);\n        q.setParameter(\"uniqueId2\", 78575785897L);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withBothCompositeColClause);\n        q.setParameter(\"studentId\", new Long(12345677));\n        q.setParameter(\"uniqueId\", 78575785897L);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withAllCompositeColClause);\n        q.setParameter(\"studentId\", new Long(12345677));\n        q.setParameter(\"uniqueId\", 78575785897L);\n        q.setParameter(\"studentName\", \"Amresh\");\n        q.setParameter(\"isExceptional\", false);\n        q.setParameter(\"age\", 10);\n        q.setParameter(\"semester\", 'A');\n        q.setParameter(\"digitalSignature\", new Byte((byte) 5));\n        q.setParameter(\"cgpa\", (short) 8);\n        q.setParameter(\"percentage\", (float) 69.3);\n        q.setParameter(\"height\", 163.76765654);\n        q.setParameter(\"enrolmentDate\", enrolmentDate);\n        q.setParameter(\"enrolmentTime\", enrolmentTime);\n        q.setParameter(\"joiningDateAndTime\", joiningDateAndTime);\n        q.setParameter(\"yearsSpent\", new Integer(3));\n        q.setParameter(\"rollNumber\", new Long(978423946455l));\n        q.setParameter(\"monthlyFee\", 135434.89);\n        q.setParameter(\"sqlDate\", newSqlDate);\n        q.setParameter(\"sqlTimestamp\", sqlTimestamp);\n        q.setParameter(\"sqlTime\", sqlTime);\n        q.setParameter(\"bigInteger\", bigInteger);\n        q.setParameter(\"calendar\", calendar);\n\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key with selective clause.\n        q = em.createQuery(withSelectiveCompositeColClause);\n        q.setParameter(\"key\", key);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertNull(results.get(0).getTweetBody());\n\n        // // Query for selective column tweetBody with composite key clause.\n        q = em.createQuery(selectiveColumnTweetBodyWithAllCompositeColClause);\n        q.setParameter(\"studentId\", new Long(12345677));\n        q.setParameter(\"uniqueId\", 78575785897L);\n        q.setParameter(\"studentName\", \"Amresh\");\n        q.setParameter(\"isExceptional\", false);\n        q.setParameter(\"age\", 10);\n        q.setParameter(\"semester\", 'A');\n        q.setParameter(\"digitalSignature\", (byte) 5);\n        q.setParameter(\"cgpa\", (short) 8);\n        q.setParameter(\"percentage\", (float) 69.3);\n        q.setParameter(\"height\", 163.76765654);\n        q.setParameter(\"enrolmentDate\", enrolmentDate);\n        q.setParameter(\"enrolmentTime\", enrolmentTime);\n        q.setParameter(\"joiningDateAndTime\", joiningDateAndTime);\n        q.setParameter(\"yearsSpent\", new Integer(3));\n        q.setParameter(\"rollNumber\", new Long(978423946455l));\n        q.setParameter(\"monthlyFee\", 135434.89);\n        q.setParameter(\"sqlDate\", newSqlDate);\n        q.setParameter(\"sqlTimestamp\", sqlTimestamp);\n        q.setParameter(\"sqlTime\", sqlTime);\n        q.setParameter(\"bigInteger\", bigInteger);\n        q.setParameter(\"calendar\", calendar);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"my first tweet\", results.get(0).getTweetBody());\n        Assert.assertNull(results.get(0).getTweetDate());\n\n        final String selectiveColumnTweetDateWithAllCompositeColClause = \"Select u.tweetDate from PrimeUserDataType u where u.key = :key\";\n        // Query for selective column tweetDate with composite key clause.\n        q = em.createQuery(selectiveColumnTweetDateWithAllCompositeColClause);\n        q.setParameter(\"key\", key);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(currentDate.getTime(), results.get(0).getTweetDate().getTime());\n        Assert.assertNull(results.get(0).getTweetBody());\n\n        final String withCompositeKeyClause = \"Select u from PrimeUserDataType u where u.key = :key\";\n        // Query with composite key clause.\n        q = em.createQuery(withCompositeKeyClause);\n        q.setParameter(\"key\", key);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        em.remove(user);\n\n        em.clear();// optional,just to clear persistence cache.\n    }\n\n    @Test\n    public void onNamedQueryTest() throws InstantiationException, IllegalAccessException\n    {\n        updateNamed();\n        deleteNamed();\n\n    }\n\n    /**\n     * Update by Named Query.\n     * \n     * @return\n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     */\n    private void updateNamed() throws InstantiationException, IllegalAccessException\n    {\n        EntityManager em = emf.createEntityManager();\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        CompoundKeyDataType key = prepareData(new Long(12345677), 78575785897L, \"Amresh\", false, 10, 'A', (byte) 5,\n                (short) 8, (float) 69.3, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime,\n                new Integer(3), new Long(978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal,\n                bigInteger, calendar, CompoundKeyDataType.class.newInstance());\n        PrimeUserDataType user = new PrimeUserDataType(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em = emf.createEntityManager();\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        String updateQuery = \"Update PrimeUserDataType u SET u.tweetBody='after merge' where u.key= :beforeUpdate\";\n        Query q = em.createQuery(updateQuery);\n        q.setParameter(\"beforeUpdate\", key);\n        q.executeUpdate();\n\n        em.clear();\n        PrimeUserDataType result = em.find(PrimeUserDataType.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"after merge\", result.getTweetBody());\n        // Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n        em.close();\n    }\n\n    /**\n     * delete by Named Query.\n     * \n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     */\n    private void deleteNamed() throws InstantiationException, IllegalAccessException\n    {\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        CompoundKeyDataType key = prepareData(new Long(12345677), 78575785897L, \"Amresh\", false, 10, 'A', (byte) 5,\n                (short) 8, (float) 69.3, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime,\n                new Integer(3), new Long(978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal,\n                bigInteger, calendar, CompoundKeyDataType.class.newInstance());\n\n        String deleteQuery = \"Delete From PrimeUserDataType u where u.key= :key\";\n        EntityManager em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        Query q = em.createQuery(deleteQuery);\n        q.setParameter(\"key\", key);\n        q.executeUpdate();\n\n        PrimeUserDataType result = em.find(PrimeUserDataType.class, key);\n        Assert.assertNull(result);\n        em.close();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(\"CompositeCassandra\");\n        emf.close();\n    }\n\n\n    /**\n     * Prepare data.\n     * \n     * @param studentId\n     *            the student id\n     * @param uniqueId\n     *            the unique id\n     * @param studentName\n     *            the student name\n     * @param isExceptional\n     *            the is exceptional\n     * @param age\n     *            the age\n     * @param semester\n     *            the semester\n     * @param digitalSignature\n     *            the digital signature\n     * @param cgpa\n     *            the cgpa\n     * @param percentage\n     *            the percentage\n     * @param height\n     *            the height\n     * @param enrolmentDate\n     *            the enrolment date\n     * @param enrolmentTime\n     *            the enrolment time\n     * @param joiningDateAndTime\n     *            the joining date and time\n     * @param yearsSpent\n     *            the years spent\n     * @param rollNumber\n     *            the roll number\n     * @param monthlyFee\n     *            the monthly fee\n     * @param newSqlDate\n     *            the new sql date\n     * @param sqlTime\n     *            the sql time\n     * @param sqlTimestamp\n     *            the sql timestamp\n     * @param bigDecimal\n     *            the big decimal\n     * @param bigInteger\n     *            the big integer\n     * @param calendar\n     *            the calendar\n     * @param o\n     *            the o\n     * @return the person\n     */\n    private CompoundKeyDataType prepareData(long studentId, long uniqueId, String studentName, boolean isExceptional,\n            int age, char semester, byte digitalSignature, short cgpa, float percentage, double height,\n            java.util.Date enrolmentDate, java.util.Date enrolmentTime, java.util.Date joiningDateAndTime,\n            Integer yearsSpent, Long rollNumber, Double monthlyFee, java.sql.Date newSqlDate, java.sql.Time sqlTime,\n            java.sql.Timestamp sqlTimestamp, BigDecimal bigDecimal, BigInteger bigInteger, Calendar calendar,\n            CompoundKeyDataType o)\n    {\n        o.setStudentId((Long) studentId);\n        o.setUniqueId(uniqueId);\n        o.setStudentName(studentName);\n        o.setExceptional(isExceptional);\n        o.setAge(age);\n        o.setSemester(semester);\n        o.setDigitalSignature(digitalSignature);\n        o.setCgpa(cgpa);\n        o.setPercentage(percentage);\n        o.setHeight(height);\n\n        o.setEnrolmentDate(enrolmentDate);\n        o.setEnrolmentTime(enrolmentTime);\n        o.setJoiningDateAndTime(joiningDateAndTime);\n\n        o.setYearsSpent(yearsSpent);\n        o.setRollNumber(rollNumber);\n        o.setMonthlyFee(monthlyFee);\n        o.setSqlDate(newSqlDate);\n        o.setSqlTime(sqlTime);\n        o.setSqlTimestamp(sqlTimestamp);\n        // o.setBigDecimal(bigDecimal);\n        o.setBigInteger(bigInteger);\n        o.setCalendar(calendar);\n        return o;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/composite/DSCompositeTypeOrderByTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.composite;\n\n\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Junit test case for Compound/Composite key.\n * \n * @author chhavi.gangwal\n * \n */\n\npublic class DSCompositeTypeOrderByTest\n{\n    private static final String _PU = \"ds_composite_pu\";\n\n    private EntityManagerFactory emf;\n\n    private Date currentDate = new Date();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        Map<String, Object> puProperties = new HashMap<String, Object>();\n        puProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n        \n\n        emf = Persistence.createEntityManagerFactory(_PU, puProperties);\n    }\n\n    @Test\n    public void onQuery() throws Exception\n    {\n\n        EntityManager em = emf.createEntityManager();\n        UUID timeLineId = UUID.randomUUID();\n        UserTimeLine key = new UserTimeLine(\"mevivs\", 1, timeLineId);\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(_PU);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        PrimeUser user = new PrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        UserTimeLine key1 = new UserTimeLine(\"mevivs1\", 12, timeLineId);\n        user = new PrimeUser(key1);\n        user.setTweetBody(\"my second tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.flush(); // optional,just to clear persistence cache.\n\n        em.clear();\n\n        final String noClause = \"Select u from PrimeUser u\";\n\n        // query with no clause.\n        Query q = em.createQuery(noClause);\n        List<PrimeUser> results = q.getResultList();\n        Assert.assertEquals(2, results.size());\n        \n        em.close();\n\n    }\n\n    /**\n     * CompositeUserDataType\n     * \n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/composite/DSCompositeTypeTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.composite;\n\nimport java.nio.ByteBuffer;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.composite.PrimeUser.NickName;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Junit test case for Compound/Composite key.\n * \n * @author vivek.mishra\n * \n */\n\npublic class DSCompositeTypeTest\n{\n\n    /**\n     * \n     */\n    private static final String PERSISTENCE_UNIT = \"ds_composite_pu\";\n\n    private EntityManagerFactory emf;\n\n    private Date currentDate = new Date();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n\n    }\n\n    @Test\n    public void onMultipleRecords()\n    {\n        String cql_Query = \"create columnfamily \\\"CompositeUser\\\" (\\\"userId\\\" text, \\\"tweetId\\\" int, \\\"timeLineId\\\" uuid, \"\n                + \" \\\"tweetDate\\\" timestamp, PRIMARY KEY(\\\"userId\\\",\\\"tweetId\\\",\\\"timeLineId\\\"))\";\n        executeScript(cql_Query);\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        UserTimeLine key1 = new UserTimeLine(\"mevivs\", 1, timeLineId);\n        PrimeUser user1 = new PrimeUser(key1);\n        user1.setTweetBody(\"my first tweet\");\n        user1.setTweetDate(currentDate);\n        user1.setNickName(NickName.KK);\n\n        timeLineId = UUID.randomUUID();\n        UserTimeLine key2 = new UserTimeLine(\"mevivs\", 1, timeLineId);\n        PrimeUser user2 = new PrimeUser(key2);\n        user2.setTweetBody(\"my first tweet\");\n        user2.setTweetDate(currentDate);\n        user2.setNickName(NickName.KK);\n\n        em.persist(user1);\n        em.persist(user2);\n\n        em.clear();\n\n        final String noClause = \"Select u from PrimeUser u\";\n        Query query = em.createQuery(noClause);\n\n        List<PrimeUser> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotSame(results.get(0).getKey(), results.get(1).getKey());\n        Assert.assertEquals(results.get(0).getKey().getUserId(), results.get(1).getKey().getUserId());\n        Assert.assertNotSame(results.get(0).getKey().getTimeLineId(), results.get(1).getKey().getTimeLineId());\n        Assert.assertEquals(results.get(0).getTweetBody(), results.get(1).getTweetBody());\n\n        final String deleteQuery = \"Delete from PrimeUser p\";\n        em.createQuery(deleteQuery).executeUpdate();\n        query = em.createQuery(noClause);\n        results = query.getResultList();\n\n        Assert.assertTrue(results.isEmpty());\n\n        em.close();\n        // emf.close();\n    }\n\n    @Test\n    public void onAddColumn() throws Exception\n    {\n        // cql script is not adding \"tweetBody\", kundera.ddl.auto.update will\n        // add it.\n        String cql_Query = \"create columnfamily \\\"CompositeUser\\\" (\\\"userId\\\" text, \\\"tweetId\\\" int, \\\"timeLineId\\\" uuid, \"\n                + \" \\\"tweetDate\\\" timestamp, PRIMARY KEY(\\\"userId\\\",\\\"tweetId\\\",\\\"timeLineId\\\"))\";\n\n        executeScript(cql_Query);\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        UserTimeLine key = new UserTimeLine(\"mevivs\", 1, timeLineId);\n        onCRUD(em, key);\n        em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n        PrimeUser result = em.find(PrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"After merge\", result.getTweetBody()); // assertion\n                                                                   // of newly\n                                                                   // added\n                                                                   // tweet body\n        em.remove(result);\n\n        em.flush();\n        em.close();\n        em = emf.createEntityManager();\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        result = em.find(PrimeUser.class, key);\n        Assert.assertNull(result);\n\n        em.close();\n    }\n\n    // @Test\n    public void onAlterColumnType() throws Exception\n    {\n        // Here tweetDate is of type \"int\". On update will be changed to\n        // timestamp.\n\n        String cql_Query = \"create columnfamily \\\"CompositeUser\\\" (\\\"userId\\\" text, \\\"tweetId\\\" int, \\\"timeLineId\\\" uuid, \"\n                + \" \\\"tweetDate\\\" int, PRIMARY KEY(\\\"userId\\\",\\\"tweetId\\\",\\\"timeLineId\\\"))\";\n        executeScript(cql_Query);\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        EntityManager em = emf.createEntityManager();\n        UUID timeLineId = UUID.randomUUID();\n        UserTimeLine key = new UserTimeLine(\"mevivs\", 1, timeLineId);\n        onCRUD(em, key);\n        em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        PrimeUser result = em.find(PrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime()); // assertion\n                                                                                     // of\n                                                                                     // changed\n                                                                                     // tweetDate.\n        em.remove(result);\n        em.flush();\n        em.close();\n        em = emf.createEntityManager();\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n        result = em.find(PrimeUser.class, key);\n        Assert.assertNull(result);\n\n        em.close();\n    }\n\n    @Test\n    public void onQuery()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n\n        UserTimeLine key = new UserTimeLine(\"mevivs\", 1, timeLineId);\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        PrimeUser user = new PrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.flush(); // optional,just to clear persistence cache.\n\n        em.clear();\n\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n        final String noClause = \"Select u from PrimeUser u\";\n\n        final String withFirstCompositeColClause = \"Select u from PrimeUser u where u.key.userId = :userId\";\n\n        // secondary index support over compound key is not enabled in cassandra\n        // composite keys yet. DO NOT DELETE/UNCOMMENT.\n\n        // final String withClauseOnNoncomposite =\n        // \"Select u from CassandraPrimeUser u where u.tweetDate = ?1\";\n        //\n\n        final String withSecondCompositeColClause = \"Select u from PrimeUser u where u.key.tweetId = :tweetId\";\n        final String withBothCompositeColClause = \"Select u from PrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId\";\n        final String withAllCompositeColClause = \"Select u from PrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        final String withLastCompositeColGTClause = \"Select u from PrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId >= :timeLineId\";\n\n        final String withSelectiveCompositeColClause = \"Select u.key from PrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n\n        // query over 1 composite and 1 non-column\n\n        // query with no clause.\n        Query q = em.createQuery(noClause);\n        List<PrimeUser> results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withFirstCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withSecondCompositeColClause);\n        q.setParameter(\"tweetId\", 1);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withBothCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withLastCompositeColGTClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key with selective clause.\n        q = em.createQuery(withSelectiveCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertNull(results.get(0).getTweetBody());\n\n        final String selectiveColumnTweetBodyWithAllCompositeColClause = \"Select u.tweetBody from PrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        // Query for selective column tweetBody with composite key clause.\n        q = em.createQuery(selectiveColumnTweetBodyWithAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"my first tweet\", results.get(0).getTweetBody());\n        Assert.assertNull(results.get(0).getTweetDate());\n\n        final String selectiveColumnTweetDateWithAllCompositeColClause = \"Select u.tweetDate from PrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        // Query for selective column tweetDate with composite key clause.\n        q = em.createQuery(selectiveColumnTweetDateWithAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(currentDate.getTime(), results.get(0).getTweetDate().getTime());\n        Assert.assertNull(results.get(0).getTweetBody());\n\n        final String withCompositeKeyClause = \"Select u from PrimeUser u where u.key = :key\";\n        // Query with composite key clause.\n        q = em.createQuery(withCompositeKeyClause);\n        q.setParameter(\"key\", key);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        em.remove(user);\n\n        em.clear();// optional,just to clear persistence cache.\n    }\n\n    @Test\n    public void onNamedQueryTest()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        updateNamed();\n        deleteNamed();\n    }\n\n    @Test\n    public void onLimit()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        UserTimeLine key = new UserTimeLine(\"mevivs\", 1, timeLineId);\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        PrimeUser user1 = new PrimeUser(key);\n        user1.setTweetBody(\"my first tweet\");\n        user1.setTweetDate(currentDate);\n        em.persist(user1);\n\n        key = new UserTimeLine(\"mevivs\", 2, timeLineId);\n        PrimeUser user2 = new PrimeUser(key);\n        user2.setTweetBody(\"my first tweet\");\n        user2.setTweetDate(currentDate);\n        em.persist(user2);\n\n        key = new UserTimeLine(\"mevivs\", 3, timeLineId);\n        PrimeUser user3 = new PrimeUser(key);\n        user3.setTweetBody(\"my first tweet\");\n        user3.setTweetDate(currentDate);\n        em.persist(user3);\n\n        em.flush();\n\n        // em.clear(); // optional,just to clear persistence cache.\n\n        // em = emf.createEntityManager();\n        em.clear();\n\n        final String noClause = \"Select u from PrimeUser u\";\n        Query q = em.createQuery(noClause);\n        List<PrimeUser> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n\n        // With limit\n        q = em.createQuery(noClause);\n        q.setMaxResults(2);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n    }\n\n    @Test\n    public void onOrderBYClause()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        UserTimeLine key = new UserTimeLine(\"mevivs\", 1, timeLineId);\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        PrimeUser user1 = new PrimeUser(key);\n        user1.setTweetBody(\"my first tweet\");\n        user1.setTweetDate(currentDate);\n        em.persist(user1);\n\n        key = new UserTimeLine(\"mevivs\", 2, timeLineId);\n        PrimeUser user2 = new PrimeUser(key);\n        user2.setTweetBody(\"my second tweet\");\n        user2.setTweetDate(currentDate);\n        em.persist(user2);\n\n        key = new UserTimeLine(\"mevivs\", 3, timeLineId);\n        PrimeUser user3 = new PrimeUser(key);\n        user3.setTweetBody(\"my third tweet\");\n        user3.setTweetDate(currentDate);\n        em.persist(user3);\n\n        em.flush();\n\n        // em.clear(); // optional,just to clear persistence cache.\n\n        // em = emf.createEntityManager();\n        em.clear();\n\n        String orderClause = \"Select u from PrimeUser u where u.key.userId = :userId ORDER BY u.key.tweetId ASC\";\n        Query q = em.createQuery(orderClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        List<PrimeUser> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(\"my first tweet\", results.get(0).getTweetBody());\n        Assert.assertEquals(\"my second tweet\", results.get(1).getTweetBody());\n        Assert.assertEquals(\"my third tweet\", results.get(2).getTweetBody());\n        Assert.assertEquals(3, results.size());\n\n        orderClause = \"Select u from PrimeUser u where u.key.userId = :userId ORDER BY u.key.tweetId DESC\";\n        q = em.createQuery(orderClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(\"my first tweet\", results.get(2).getTweetBody());\n        Assert.assertEquals(\"my second tweet\", results.get(1).getTweetBody());\n        Assert.assertEquals(\"my third tweet\", results.get(0).getTweetBody());\n        Assert.assertEquals(3, results.size());\n\n        // With limit\n        q = em.createQuery(orderClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setMaxResults(2);\n        results = q.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        try\n        {\n            orderClause = \"Select u from PrimeUser u where u.key.userId = :userId ORDER BY u.key.userId DESC\";\n            q = em.createQuery(orderClause);\n            q.setParameter(\"userId\", \"mevivs\");\n            results = q.getResultList();\n\n            Assert.fail();\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\n                    \"com.datastax.driver.core.exceptions.InvalidQueryException: Order by is currently only supported on the clustered columns of the PRIMARY KEY, got userId\",\n                    e.getMessage());\n        }\n\n    }\n\n    @Test\n    public void onInClause()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        UserTimeLine key = new UserTimeLine(\"mevivs\", 1, timeLineId);\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        PrimeUser user1 = new PrimeUser(key);\n        user1.setTweetBody(\"my first tweet\");\n        user1.setTweetDate(currentDate);\n        em.persist(user1);\n\n        key = new UserTimeLine(\"cgangwal's\", 2, timeLineId);\n        PrimeUser user2 = new PrimeUser(key);\n        user2.setTweetBody(\"my second tweet\");\n        user2.setTweetDate(currentDate);\n        em.persist(user2);\n\n        key = new UserTimeLine(\"kmishra\", 3, timeLineId);\n        PrimeUser user3 = new PrimeUser(key);\n        user3.setTweetBody(\"my third tweet\");\n        user3.setTweetDate(currentDate);\n        em.persist(user3);\n\n        em.flush();\n\n        em.clear();\n\n        // Single quote within single quote not supported by eclipselink, need\n        // to look into this\n        // String inClause =\n        // \"Select u from PrimeUser u where u.key.userId IN ('mevivs','cgangwal\\''s','kmishra') ORDER BY u.key.tweetId ASC\";\n        // Query q = em.createQuery(inClause);\n        //\n        // List<PrimeUser> results = q.getResultList();\n        // Assert.assertNotNull(results);\n        // Assert.assertEquals(3, results.size());\n        // Assert.assertEquals(\"my first tweet\", results.get(0).getTweetBody());\n        // Assert.assertEquals(\"my second tweet\",\n        // results.get(1).getTweetBody());\n        // Assert.assertEquals(\"my third tweet\", results.get(2).getTweetBody());\n        //\n        //\n        String inClause = \"Select u from PrimeUser u where u.key.userId IN (\\\"mevivs\\\",\\\"cgangwal's\\\",\\\"kmishra\\\")\";\n        Query q = em.createQuery(inClause);\n\n        List<PrimeUser> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n\n        inClause = \"Select u from PrimeUser u where u.key.userId IN (\\\"mevivs\\\",\\\"cgangwal's\\\")\";\n        q = em.createQuery(inClause);\n\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        try\n        {\n            inClause = \"Select u from PrimeUser u where u.key.tweetId IN (1,2,3) ORDER BY u.key.tweetId DESC\";\n            q = em.createQuery(inClause);\n            results = q.getResultList();\n            Assert.fail();\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\n                    \"com.datastax.driver.core.exceptions.InvalidQueryException: ORDER BY is only supported when the partition key is restricted by an EQ or an IN.\",\n                    e.getMessage());\n        }\n\n    }\n\n    @Test\n    public void onBatchInsert()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n\n        for (int i = 0; i < 500; i++)\n        {\n            UserTimeLine key = new UserTimeLine(\"mevivs\", i, timeLineId);\n            Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n            Client client = clients.get(PERSISTENCE_UNIT);\n            ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n            PrimeUser user = new PrimeUser(key);\n            user.setTweetBody(\"my first tweet\");\n            user.setTweetDate(currentDate);\n            em.persist(user);\n        }\n\n        em.clear();\n\n        PrimeUser u = em.find(PrimeUser.class, new UserTimeLine(\"mevivs\", 499, timeLineId));\n        Assert.assertNotNull(u);\n    }\n\n    /**\n     * CompositeUserDataType\n     * \n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        try\n        {\n            emf.close();\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"use \\\"KunderaExamples\\\"\".getBytes()),\n                    Compression.NONE, ConsistencyLevel.ONE);\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"truncate \\\"CompositeUser\\\"\".getBytes()),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        finally\n        {\n            CassandraCli.dropKeySpace(\"KunderaExamples\");\n        }\n    }\n\n    // DO NOT DELETE IT!! though it is automated with schema creation option.\n    /**\n     * create column family script for compound key.\n     */\n    private void executeScript(final String cql)\n    {\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n        CassandraCli.executeCqlQuery(cql, \"KunderaExamples\");\n    }\n\n    /**\n     * CRUD over Compound primary Key.\n     */\n\n    private void onCRUD(final EntityManager em, UserTimeLine key)\n    {\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n        PrimeUser user = new PrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        user.setNickName(NickName.KK);\n        em.persist(user);\n        em.flush();\n\n        // em.clear(); // optional,just to clear persistence cache.\n\n        // em = emf.createEntityManager();\n        em.clear();\n\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        PrimeUser result = em.find(PrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"my first tweet\", result.getTweetBody());\n        // Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n        Assert.assertEquals(NickName.KK, result.getNickName());\n        Assert.assertEquals(NickName.KK.name(), result.getNickName().name());\n\n        em.clear();// optional,just to clear persistence cache.\n\n        user.setTweetBody(\"After merge\");\n        em.merge(user);\n        em.close();// optional,just to clear persistence cache.\n\n        EntityManager em1 = emf.createEntityManager();\n        // em = emf.createEntityManager();\n        clients = (Map<String, Client>) em1.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        result = em1.find(PrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"After merge\", result.getTweetBody());\n        // Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n\n        // deleting composite\n        em1.clear(); // optional,just to clear persistence cache.\n        // em.close();// optional,just to clear persistence cache.\n\n    }\n\n    /**\n     * Update by Named Query.\n     * \n     * @return\n     */\n    private void updateNamed()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        UUID timeLineId = UUID.randomUUID();\n\n        UserTimeLine key = new UserTimeLine(\"mevivs\", 1, timeLineId);\n        PrimeUser user = new PrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.close();\n        em = emf.createEntityManager();\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        String updateQuery = \"Update PrimeUser u SET u.tweetBody='after merge' where u.key= :beforeUpdate\";\n        Query q = em.createQuery(updateQuery);\n        q.setParameter(\"beforeUpdate\", key);\n        q.executeUpdate();\n\n        em.close(); // optional,just to clear persistence cache.\n\n        em = emf.createEntityManager();\n        clients = (Map<String, Client>) em.getDelegate();\n        client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        PrimeUser result = em.find(PrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"after merge\", result.getTweetBody());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n        em.close();\n    }\n\n    /**\n     * delete by Named Query.\n     */\n    private void deleteNamed()\n    {\n        UUID timeLineId = UUID.randomUUID();\n\n        UserTimeLine key = new UserTimeLine(\"mevivs\", 1, timeLineId);\n\n        String deleteQuery = \"Delete From PrimeUser u where u.key= :key\";\n        EntityManager em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(PERSISTENCE_UNIT);\n        ((CassandraClientBase) client).setCqlVersion(\"3.0.0\");\n\n        Query q = em.createQuery(deleteQuery);\n        q.setParameter(\"key\", key);\n        q.executeUpdate();\n\n        PrimeUser result = em.find(PrimeUser.class, key);\n        Assert.assertNull(result);\n        em.close();\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/composite/DSEmbeddedAssociation.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.composite;\n\nimport java.util.Date;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.client.cassandra.crud.compositeType.association.UserInfo;\n\n/**\n * Composite key entity with association columns\n * \n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"CompositeUserAssociation\")\n// @Index(index = true,columns = { \"tweetBody\",\"tweetDate\" })\npublic class DSEmbeddedAssociation\n{\n\n    @EmbeddedId\n    private UserTimeLine key;\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private Date tweetDate;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"userInfo_id\")\n    private UserInfo userInfo;\n\n    public DSEmbeddedAssociation()\n    {\n    }\n\n    public DSEmbeddedAssociation(UserTimeLine key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the key\n     */\n    public UserTimeLine getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n    public UserInfo getUserInfo()\n    {\n        return userInfo;\n    }\n\n    public void setUserInfo(UserInfo userInfo)\n    {\n        this.userInfo = userInfo;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/composite/DSEntityWithMultiplePartitionKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.composite;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\n@Entity\n@Table(name = \"DSEntityWithMultiplePartitionKey\", schema = \"KunderaExamples@ds_pu\")\npublic class DSEntityWithMultiplePartitionKey\n{\n    @EmbeddedId\n    private DSIdWithMultiplePartitionKey id;\n\n    @Column\n    private String entityDiscription;\n\n    @Column\n    private String action;\n\n    /**\n     * @return the id\n     */\n    public DSIdWithMultiplePartitionKey getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(DSIdWithMultiplePartitionKey id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the entityDiscription\n     */\n    public String getEntityDiscription()\n    {\n        return entityDiscription;\n    }\n\n    /**\n     * @param entityDiscription\n     *            the entityDiscription to set\n     */\n    public void setEntityDiscription(String entityDiscription)\n    {\n        this.entityDiscription = entityDiscription;\n    }\n\n    /**\n     * @return the action\n     */\n    public String getAction()\n    {\n        return action;\n    }\n\n    /**\n     * @param action\n     *            the action to set\n     */\n    public void setAction(String action)\n    {\n        this.action = action;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/composite/DSEntityWithMultiplePartitionKeyTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.composite;\n\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.query.Query;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic class DSEntityWithMultiplePartitionKeyTest\n{\n\n    protected static String _PU = \"ds_pu\";\n\n    private EntityManagerFactory emf;\n\n    private static final String _keyspace = \"KunderaExamples\";\n\n    /** The Constant logger. */\n    private static final Logger log = LoggerFactory.getLogger(DSEntityWithMultiplePartitionKeyTest.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n        CassandraCli.dropKeySpace(_keyspace);\n        CassandraCli.createKeySpace(_keyspace);\n        try\n        {\n            CassandraCli\n                    .executeCqlQuery(\n                            \"create table \\\"DSEntityWithMultiplePartitionKey\\\"(\\\"partitionKey1\\\" text, \\\"partitionKey2\\\" int, \\\"clusterkey1\\\" text, \\\"clusterkey2\\\" int, \\\"entityDiscription\\\" text, action text, PRIMARY KEY((\\\"partitionKey1\\\", \\\"partitionKey2\\\"), \\\"clusterkey1\\\", \\\"clusterkey2\\\"))\",\n                            _keyspace);\n        }\n        catch (Exception e)\n        {\n            log.warn(e.getMessage());\n        }\n        Map<String, String> propertymap = new HashMap<String, String>();\n        propertymap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"\");\n        emf = Persistence.createEntityManagerFactory(_PU, propertymap);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        CassandraCli.dropKeySpace(_keyspace);\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        DSPartitionKey partitionKey = new DSPartitionKey();\n        partitionKey.setPartitionKey1(\"partitionKey1\");\n        partitionKey.setPartitionKey2(1);\n\n        DSIdWithMultiplePartitionKey id = new DSIdWithMultiplePartitionKey();\n        id.setClusterkey1(\"clusterkey1\");\n        id.setClusterkey2(11);\n        id.setPartitionKey(partitionKey);\n\n        DSEntityWithMultiplePartitionKey entity = new DSEntityWithMultiplePartitionKey();\n        entity.setEntityDiscription(\"Entity to test composite key with multiple partition key.\");\n        entity.setAction(\"Persisting\");\n        entity.setId(id);\n\n        // Insert.\n        em.persist(entity);\n\n        em.clear();\n\n        // Retrieve.\n        DSEntityWithMultiplePartitionKey foundEntity = em.find(DSEntityWithMultiplePartitionKey.class, id);\n        Assert.assertNotNull(foundEntity);\n        Assert.assertNotNull(foundEntity.getId());\n        Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n        Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n        Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                foundEntity.getEntityDiscription());\n        Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n        Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n        Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n        Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n\n        // Update.\n        foundEntity.setAction(\"updating\");\n        em.merge(foundEntity);\n\n        em.clear();\n\n        foundEntity = em.find(DSEntityWithMultiplePartitionKey.class, id);\n        Assert.assertNotNull(foundEntity);\n        Assert.assertNotNull(foundEntity.getId());\n        Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n        Assert.assertEquals(\"updating\", foundEntity.getAction());\n        Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                foundEntity.getEntityDiscription());\n        Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n        Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n        Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n        Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n\n        // Delete.\n        em.remove(foundEntity);\n        em.clear();\n\n        foundEntity = em.find(DSEntityWithMultiplePartitionKey.class, id);\n        Assert.assertNull(foundEntity);\n\n    }\n\n    @Test\n    public void testQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        DSPartitionKey partitionKey1 = new DSPartitionKey();\n        partitionKey1.setPartitionKey1(\"partitionKey1\");\n        partitionKey1.setPartitionKey2(1);\n\n        DSIdWithMultiplePartitionKey id1 = new DSIdWithMultiplePartitionKey();\n        id1.setClusterkey1(\"clusterkey1\");\n        id1.setClusterkey2(11);\n        id1.setPartitionKey(partitionKey1);\n\n        DSEntityWithMultiplePartitionKey entity1 = new DSEntityWithMultiplePartitionKey();\n        entity1.setEntityDiscription(\"Entity to test composite key with multiple partition key.\");\n        entity1.setAction(\"Persisting\");\n        entity1.setId(id1);\n\n        DSPartitionKey partitionKey2 = new DSPartitionKey();\n        partitionKey2.setPartitionKey1(\"partitionKey2\");\n        partitionKey2.setPartitionKey2(2);\n\n        DSIdWithMultiplePartitionKey id2 = new DSIdWithMultiplePartitionKey();\n        id2.setClusterkey1(\"clusterkey2\");\n        id2.setClusterkey2(111);\n        id2.setPartitionKey(partitionKey2);\n\n        DSEntityWithMultiplePartitionKey entity2 = new DSEntityWithMultiplePartitionKey();\n        entity2.setEntityDiscription(\"Entity to test composite key with multiple partition key.\");\n        entity2.setAction(\"Persisting\");\n        entity2.setId(id2);\n\n        DSPartitionKey partitionKey3 = new DSPartitionKey();\n        partitionKey3.setPartitionKey1(\"partitionKey3\");\n        partitionKey3.setPartitionKey2(3);\n\n        DSIdWithMultiplePartitionKey id3 = new DSIdWithMultiplePartitionKey();\n        id3.setClusterkey1(\"clusterkey3\");\n        id3.setClusterkey2(1111);\n        id3.setPartitionKey(partitionKey3);\n\n        DSEntityWithMultiplePartitionKey entity3 = new DSEntityWithMultiplePartitionKey();\n        entity3.setEntityDiscription(\"Entity to test composite key with multiple partition key.\");\n        entity3.setAction(\"Persisting\");\n        entity3.setId(id3);\n\n        // Insert.\n        em.persist(entity1);\n        em.persist(entity2);\n        em.persist(entity3);\n\n        em.clear();\n\n        // Select All query.\n        List<DSEntityWithMultiplePartitionKey> foundEntitys = em.createQuery(\n                \"select e from DSEntityWithMultiplePartitionKey e\").getResultList();\n\n        Assert.assertNotNull(foundEntitys);\n        Assert.assertFalse(foundEntitys.isEmpty());\n        Assert.assertEquals(3, foundEntitys.size());\n\n        int count = 0;\n        for (DSEntityWithMultiplePartitionKey foundEntity : foundEntitys)\n        {\n            Assert.assertNotNull(foundEntity);\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n\n            if (foundEntity.getId().getClusterkey1().equals(\"clusterkey1\"))\n            {\n                Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n                Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n            else if (foundEntity.getId().getClusterkey1().equals(\"clusterkey2\"))\n            {\n                Assert.assertEquals(111, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey2\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(2, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(\"clusterkey3\", foundEntity.getId().getClusterkey1());\n                Assert.assertEquals(1111, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey3\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(3, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.clear();\n\n        // Select by both partition key query.\n        foundEntitys = em\n                .createQuery(\n                        \"select e from DSEntityWithMultiplePartitionKey e where e.id.partitionKey.partitionKey1=partitionKey1 and e.id.partitionKey.partitionKey2=1\")\n                .getResultList();\n\n        Assert.assertNotNull(foundEntitys);\n        Assert.assertFalse(foundEntitys.isEmpty());\n        Assert.assertEquals(1, foundEntitys.size());\n\n        count = 0;\n        for (DSEntityWithMultiplePartitionKey foundEntity : foundEntitys)\n        {\n            Assert.assertNotNull(foundEntity);\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n            Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n            Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n            Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n            Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n\n        // Select by both partition key query and one cluster key.\n        foundEntitys = em\n                .createQuery(\n                        \"select e from DSEntityWithMultiplePartitionKey e where e.id.partitionKey.partitionKey1=partitionKey1 and e.id.partitionKey.partitionKey2=1 and e.id.clusterkey1=clusterkey1\")\n                .getResultList();\n\n        Assert.assertNotNull(foundEntitys);\n        Assert.assertFalse(foundEntitys.isEmpty());\n        Assert.assertEquals(1, foundEntitys.size());\n\n        count = 0;\n        for (DSEntityWithMultiplePartitionKey foundEntity : foundEntitys)\n        {\n            Assert.assertNotNull(foundEntity);\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n            Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n            Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n            Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n            Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n\n        // Select by both partition key query.\n        foundEntitys = em\n                .createQuery(\"select e from DSEntityWithMultiplePartitionKey e where e.id.partitionKey = :partitionKey\")\n                .setParameter(\"partitionKey\", partitionKey1).getResultList();\n\n        Assert.assertNotNull(foundEntitys);\n        Assert.assertFalse(foundEntitys.isEmpty());\n        Assert.assertEquals(1, foundEntitys.size());\n\n        count = 0;\n        for (DSEntityWithMultiplePartitionKey foundEntity : foundEntitys)\n        {\n            Assert.assertNotNull(foundEntity);\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n            Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n            Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n            Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n            Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n\n        // Select by first partition key with equal clause and second partition\n        // key with IN clause.\n        try\n        {\n            foundEntitys = em\n                    .createQuery(\n                            \"select e from DSEntityWithMultiplePartitionKey e where e.id.partitionKey.partitionKey1=partitionKey1 and e.id.partitionKey.partitionKey2 IN (1, 2, 3)\")\n                    .getResultList();\n\n            Assert.assertNotNull(foundEntitys);\n            Assert.assertFalse(foundEntitys.isEmpty());\n            Assert.assertEquals(1, foundEntitys.size());\n\n            count = 0;\n            for (DSEntityWithMultiplePartitionKey foundEntity : foundEntitys)\n            {\n                Assert.assertNotNull(foundEntity);\n                Assert.assertNotNull(foundEntity.getId());\n                Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n                Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n                Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                        foundEntity.getEntityDiscription());\n                Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n                Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n        }\n        catch (Exception e)\n        {\n            log.warn(e.getMessage());\n        }\n\n        // Select by composite id object query.\n        try\n        {\n            foundEntitys = em.createQuery(\"select e from DSEntityWithMultiplePartitionKey e where e.id = :id\")\n                    .setParameter(\"id\", id1).getResultList();\n\n            Assert.assertNotNull(foundEntitys);\n            Assert.assertFalse(foundEntitys.isEmpty());\n            Assert.assertEquals(1, foundEntitys.size());\n\n            count = 0;\n            for (DSEntityWithMultiplePartitionKey foundEntity : foundEntitys)\n            {\n                Assert.assertNotNull(foundEntity);\n                Assert.assertNotNull(foundEntity.getId());\n                Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n                Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n                Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                        foundEntity.getEntityDiscription());\n                Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n                Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n        }\n        catch (Exception e)\n        {\n            Assert.fail();\n        }\n        \n        // Select by cluster key only.\n        try\n        {\n            foundEntitys = em.createQuery(\"select e from DSEntityWithMultiplePartitionKey e where e.id.clusterkey1=clusterkey1\").getResultList();\n\n            Assert.assertNotNull(foundEntitys);\n            Assert.assertFalse(foundEntitys.isEmpty());\n            Assert.assertEquals(1, foundEntitys.size());\n\n            count = 0;\n            for (DSEntityWithMultiplePartitionKey foundEntity : foundEntitys)\n            {\n                Assert.assertNotNull(foundEntity);\n                Assert.assertNotNull(foundEntity.getId());\n                Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n                Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n                Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                        foundEntity.getEntityDiscription());\n                Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n                Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n                Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n                Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n        }\n        catch (Exception e)\n        {\n            Assert.fail();\n        }\n\n        // Select by first partition key query.\n        try\n        {\n            foundEntitys = em\n                    .createQuery(\n                            \"select e from DSEntityWithMultiplePartitionKey e where e.id.partitionKey.partitionKey1=partitionKey1\")\n                    .getResultList();\n\n            DSEntityWithMultiplePartitionKey foundEntity = foundEntitys.get(0);\n\t\t\tAssert.assertNotNull(foundEntity );\n            Assert.assertNotNull(foundEntity.getId());\n            Assert.assertNotNull(foundEntity.getId().getPartitionKey());\n            Assert.assertEquals(\"Persisting\", foundEntity.getAction());\n            Assert.assertEquals(\"Entity to test composite key with multiple partition key.\",\n                    foundEntity.getEntityDiscription());\n            Assert.assertEquals(\"clusterkey1\", foundEntity.getId().getClusterkey1());\n            Assert.assertEquals(11, foundEntity.getId().getClusterkey2());\n            Assert.assertEquals(\"partitionKey1\", foundEntity.getId().getPartitionKey().getPartitionKey1());\n            Assert.assertEquals(1, foundEntity.getId().getPartitionKey().getPartitionKey2());\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\n                    \"All part of partition key must be in where clause, but provided only first part. \",\n                    \"com.datastax.driver.core.exceptions.InvalidQueryException: Partition key parts: partitionKey2 must be restricted as other parts are\",\n                    e.getMessage());\n        }\n\n        // test iteration of result.\n        Query query = (com.impetus.kundera.query.Query) em\n                .createQuery(\"SELECT e FROM DSEntityWithMultiplePartitionKey e\");\n\n        query.setFetchSize(2);\n\n        Iterator<DSEntityWithMultiplePartitionKey> iterator = query.iterate();\n        count = 0;\n        while (iterator.hasNext())\n        {\n            DSEntityWithMultiplePartitionKey entity = iterator.next();\n            Assert.assertNotNull(entity);\n            Assert.assertNotNull(entity.getId());\n            Assert.assertNotNull(entity.getId().getPartitionKey());\n            count++;\n        }\n        Assert.assertEquals(3, count);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/composite/DSIdWithMultiplePartitionKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.composite;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Embedded;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\n@Embeddable\npublic class DSIdWithMultiplePartitionKey implements Serializable\n{\n    private static final long serialVersionUID = 10000000L;\n\n    @Embedded\n    private DSPartitionKey partitionKey;\n\n    @Column\n    private String clusterkey1;\n\n    @Column\n    private int clusterkey2;\n\n    /**\n     * @return the partitionKey\n     */\n    public DSPartitionKey getPartitionKey()\n    {\n        return partitionKey;\n    }\n\n    /**\n     * @param partitionKey\n     *            the partitionKey to set\n     */\n    public void setPartitionKey(DSPartitionKey partitionKey)\n    {\n        this.partitionKey = partitionKey;\n    }\n\n    /**\n     * @return the clusterkey1\n     */\n    public String getClusterkey1()\n    {\n        return clusterkey1;\n    }\n\n    /**\n     * @param clusterkey1\n     *            the clusterkey1 to set\n     */\n    public void setClusterkey1(String clusterkey1)\n    {\n        this.clusterkey1 = clusterkey1;\n    }\n\n    /**\n     * @return the clusterkey2\n     */\n    public int getClusterkey2()\n    {\n        return clusterkey2;\n    }\n\n    /**\n     * @param clusterkey2\n     *            the clusterkey2 to set\n     */\n    public void setClusterkey2(int clusterkey2)\n    {\n        this.clusterkey2 = clusterkey2;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/composite/DSPartitionKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.composite;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\n@Embeddable\npublic class DSPartitionKey implements Serializable\n{\n\n    private static final long serialVersionUID = 100000L;\n\n    @Column\n    private String partitionKey1;\n\n    @Column\n    private int partitionKey2;\n\n    /**\n     * @return the partitionKey1\n     */\n    public String getPartitionKey1()\n    {\n        return partitionKey1;\n    }\n\n    /**\n     * @param partitionKey1\n     *            the partitionKey1 to set\n     */\n    public void setPartitionKey1(String partitionKey1)\n    {\n        this.partitionKey1 = partitionKey1;\n    }\n\n    /**\n     * @return the partitionKey2\n     */\n    public int getPartitionKey2()\n    {\n        return partitionKey2;\n    }\n\n    /**\n     * @param partitionKey2\n     *            the partitionKey2 to set\n     */\n    public void setPartitionKey2(int partitionKey2)\n    {\n        this.partitionKey2 = partitionKey2;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/composite/PrimeUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.composite;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.OrderBy;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * JPA entity with composite key\n * \n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"CompositeUser\")\n@IndexCollection(columns = { @Index(name = \"name\") })\npublic class PrimeUser\n{\n\n    @EmbeddedId\n    @OrderBy(\"key.tweetId ASC, key.timeLineId DESC\")\n    private UserTimeLine key;\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private Date tweetDate;\n\n    @Column\n    private String name;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private NickName nickName;\n\n    public PrimeUser()\n    {\n    }\n\n    public PrimeUser(UserTimeLine key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the key\n     */\n    public UserTimeLine getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public NickName getNickName()\n    {\n        return nickName;\n    }\n\n    public void setNickName(NickName nickName)\n    {\n        this.nickName = nickName;\n    }\n\n    enum NickName\n    {\n        KK, VM, AS;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/composite/PrimeUserDataType.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.composite;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n\n/**\n * JPA entity with composite key consisting all supported data types\n * \n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"CompositeUserDataType\")\npublic class PrimeUserDataType\n{\n\n    @EmbeddedId\n    private CompoundKeyDataType key;\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private Date tweetDate;\n\n    @Column\n    private Boolean isActive;\n\n    public PrimeUserDataType()\n    {\n    }\n\n    public PrimeUserDataType(CompoundKeyDataType key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the key\n     */\n    public CompoundKeyDataType getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n    public Boolean getIsActive()\n    {\n        return isActive;\n    }\n\n    public void setIsActive(Boolean isActive)\n    {\n        this.isActive = isActive;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/composite/UserTimeLine.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.composite;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * User time line composite key.\n * \n * @author vivek.mishra\n */\n@Embeddable\npublic class UserTimeLine\n{\n    private static final long serialVersionUID = -8055485531216607863L;\n    \n    @Column\n    private String userId;\n\n    @Column\n    private int tweetId;\n\n    @Column\n    private UUID timeLineId;\n\n    @Column\n    private transient String fullName;\n\n    /**\n     * \n     */\n    public UserTimeLine()\n    {\n    }\n\n    /**\n     * @param userId\n     * @param tweetId\n     * @param timeLineId\n     */\n    public UserTimeLine(String userId, int tweetId, UUID timeLineId)\n    {\n        this.userId = userId;\n        this.tweetId = tweetId;\n        this.timeLineId = timeLineId;\n        this.fullName = \"kuldeep\";\n    }\n\n    /**\n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * @return the tweetId\n     */\n    public int getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * @return the timeLineId\n     */\n    public UUID getTimeLineId()\n    {\n        return timeLineId;\n    }\n\n    public String getFullName()\n    {\n        return this.fullName;\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/crud/CassandraBatchEntity.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.cassandra.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class\n * \n * @author vivek.mishra\n */\n@Entity\n@Table(name = \"CassandraBatchEntity\")\npublic class CassandraBatchEntity\n{\n    @Id\n    @Column(name = \"user_name\")\n    private String user_name;\n\n    @Column(name = \"password\")\n    private String password;\n\n    @Column(name = \"name\")\n    private String name;\n\n    public CassandraBatchEntity()\n    {\n\n    }\n\n    /**\n     * @return the user_name\n     */\n    public String getUser_name()\n    {\n        return user_name;\n    }\n\n    /**\n     * @param user_name\n     *            the user_name to set\n     */\n    public void setUser_name(String user_name)\n    {\n        this.user_name = user_name;\n    }\n\n    /**\n     * @return the password\n     */\n    public String getPassword()\n    {\n        return password;\n    }\n\n    /**\n     * @param password\n     *            the password to set\n     */\n    public void setPassword(String password)\n    {\n        this.password = password;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/crud/CassandraBatchProcessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.crud;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.PersonCassandra;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.api.Batcher;\n\n/**\n * Batch processing test case for cassandra.\n * \n * @author vivek.mishra\n * \n */\npublic class CassandraBatchProcessorTest\n{\n\n    /**\n     * \n     */\n    private static final String PERSISTENCE_UNIT = \"cassandra_ds_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    protected Map propertyMap = null;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        // cassandraSetUp();\n        CassandraCli.cassandraSetUp();\n        // CassandraCli.initClient();\n        CassandraCli.createKeySpace(\"KunderaExamples\");\n\n        if (propertyMap == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(\"kundera.batch.size\", \"5\");\n        }\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void onBatch()\n    {\n        int counter = 0;\n        List<PersonCassandra> rows = prepareData(10);\n        for (PersonCassandra entity : rows)\n        {\n            em.persist(entity);\n\n            // check for implicit flush.\n            if (++counter == 5)\n            {\n                Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n\n                Batcher client = (Batcher) clients.get(PERSISTENCE_UNIT);\n                Assert.assertEquals(5, client.getBatchSize());\n                em.clear();\n                for (int i = 0; i < 5; i++)\n                {\n\n                    // assert on each batch size record\n                    Assert.assertNotNull(em.find(PersonCassandra.class, rows.get(i).getPersonId()));\n\n                    // as batch size is 5.\n                    Assert.assertNull(em.find(PersonCassandra.class, rows.get(6).getPersonId()));\n                }\n                // means implicit flush must happen\n            }\n        }\n\n        // flush all on close.\n        // explicit flush on close\n        em.clear();\n        em.close();\n\n        em = emf.createEntityManager();\n\n        String sql = \" Select p from PersonCassandra p\";\n        Query query = em.createQuery(sql);\n        List<PersonCassandra> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(10, results.size());\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    \tem.close();\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n\n    private List<PersonCassandra> prepareData(Integer noOfRecords)\n    {\n        List<PersonCassandra> persons = new ArrayList<PersonCassandra>();\n        for (int i = 1; i <= noOfRecords; i++)\n        {\n            PersonCassandra o = new PersonCassandra();\n            o.setPersonId(i + \"\");\n            o.setPersonName(\"vivek\" + i);\n            o.setAge(10);\n            persons.add(o);\n        }\n\n        return persons;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/crud/CassandraEntity.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.cassandra.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class\n * \n * @author vivek.mishra\n */\n@Entity\n@Table(name = \"users\")\npublic class CassandraEntity\n{\n    @Id\n    @Column(name = \"key\")\n    private String key;\n\n    @Column(name = \"full_name\")\n    private String full_name;\n\n    @Column(name = \"birth_date\")\n    private Integer birth_date;\n\n    @Column(name = \"state\")\n    private String state;\n\n    /**\n     * @return the key\n     */\n    public String getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @param key\n     *            the key to set\n     */\n    public void setKey(String key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the full_name\n     */\n    public String getFull_name()\n    {\n        return full_name;\n    }\n\n    /**\n     * @param full_name\n     *            the full_name to set\n     */\n    public void setFull_name(String full_name)\n    {\n        this.full_name = full_name;\n    }\n\n    /**\n     * @return the birth_date\n     */\n    public Integer getBirth_date()\n    {\n        return birth_date;\n    }\n\n    /**\n     * @param birth_date\n     *            the birth_date to set\n     */\n    public void setBirth_date(int birth_date)\n    {\n        this.birth_date = birth_date;\n    }\n\n    /**\n     * @return the state\n     */\n    public String getState()\n    {\n        return state;\n    }\n\n    /**\n     * @param state\n     *            the state to set\n     */\n    public void setState(String state)\n    {\n        this.state = state;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/crud/CassandraEntitySample.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Test Entity\n * \n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"users\", schema = \"KunderaExamples@ds_pu\")\npublic class CassandraEntitySample\n{\n\n    @Id\n    @Column(name = \"key\")\n    private String key;\n\n    @Column(name = \"full_name\")\n    private String full_name;\n\n    @Column(name = \"birth_date\")\n    private Integer birth_date;\n\n    @Column(name = \"state\")\n    private String state;\n\n    /**\n     * @return the key\n     */\n    public String getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @param key\n     *            the key to set\n     */\n    public void setKey(String key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the full_name\n     */\n    public String getFull_name()\n    {\n        return full_name;\n    }\n\n    /**\n     * @param full_name\n     *            the full_name to set\n     */\n    public void setFull_name(String full_name)\n    {\n        this.full_name = full_name;\n    }\n\n    /**\n     * @return the birth_date\n     */\n    public Integer getBirth_date()\n    {\n        return birth_date;\n    }\n\n    /**\n     * @param birth_date\n     *            the birth_date to set\n     */\n    public void setBirth_date(int birth_date)\n    {\n        this.birth_date = birth_date;\n    }\n\n    /**\n     * @return the state\n     */\n    public String getState()\n    {\n        return state;\n    }\n\n    /**\n     * @param state\n     *            the state to set\n     */\n    public void setState(String state)\n    {\n        this.state = state;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/crud/CollectionEntity.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.cassandra.crud;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * Entity with collection attribute.\n *\n */\n@Entity\n@Table(name = \"collection_entity\")\npublic class CollectionEntity\n{\n    @Id\n    private String id;\n\n    @Column\n    private Map<String, byte[]> dataMap;\n\n    @Column\n    private Set<byte[]> setAsBytes;\n\n    @Column\n    private List<byte[]> listAsBytes;\n\n    public CollectionEntity()\n    {\n    }\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public Map<String, byte[]> getDataMap()\n    {\n        return dataMap;\n    }\n\n    public void setDataMap(Map<String, byte[]> dataMap)\n    {\n        this.dataMap = dataMap;\n    }\n\n    public Set<byte[]> getSetAsBytes()\n    {\n        return setAsBytes;\n    }\n\n    public void setSetAsBytes(Set<byte[]> setAsBytes)\n    {\n        this.setAsBytes = setAsBytes;\n    }\n\n    public List<byte[]> getListAsBytes()\n    {\n        return listAsBytes;\n    }\n\n    public void setListAsBytes(List<byte[]> listAsBytes)\n    {\n        this.listAsBytes = listAsBytes;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/crud/CollectionTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.cassandra.crud;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.property.accessor.ObjectAccessor;\nimport com.impetus.kundera.property.accessor.UUIDAccessor;\n\n/**\n * @author vivek.mishra\n * junit to test blob type over collection data type(e.g. Map,List and Set)  \n *\n */\npublic class CollectionTest\n{\n\n    private EntityManagerFactory emf;\n    private EntityManager em;\n    \n    \n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        Map<String, String> propertyMap = new HashMap<String, String>();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n        emf = Persistence.createEntityManagerFactory(\"ds_pu\", propertyMap);\n        em = emf.createEntityManager();\n\n    }\n    \n    @Test\n    public void test()\n    {\n        Map<String, byte[]> byteCollection = new HashMap<String, byte[]>();\n        \n        ObjectAccessor accessor = new ObjectAccessor();\n        accessor.toBytes(10);\n        \n        byteCollection.put(\"key1\", accessor.toBytes(10));\n        byteCollection.put(\"key2\", accessor.toBytes(11));\n        CollectionEntity entity = new CollectionEntity();\n        entity.setId(\"entityId1\");\n        entity.setDataMap(byteCollection);\n        em.persist(entity); // persist entity.\n        \n        em.clear();\n        CollectionEntity result = em.find(CollectionEntity.class, \"entityId1\");\n        Assert.assertNotNull(result);\n        \n        byte[] bytes = result.getDataMap().get(\"key1\");\n        Object value = PropertyAccessorHelper.getObject(Object.class, bytes);\n\n        Assert.assertEquals(10, value);\n        \n        // set list\n        \n        List<byte[]> listAsBytes= new ArrayList<byte[]>();\n        \n        UUID randomId = UUID.randomUUID();\n        listAsBytes.add(\"Vivek\".getBytes());\n        listAsBytes.add(new UUIDAccessor().toBytes(randomId));\n        \n        result.setListAsBytes(listAsBytes);\n        em.merge(result); // merge with list as bytes.\n        \n        em.clear();  // clear from cache.\n        \n        result = em.find(CollectionEntity.class, \"entityId1\");\n        Assert.assertNotNull(result);\n        assertOnList(result, randomId);        \n        \n        Set<byte[]> setAsBytes = new HashSet<byte[]>();\n        setAsBytes.add(\"Vivek\".getBytes());\n        setAsBytes.add(new UUIDAccessor().toBytes(randomId));\n        result.setSetAsBytes(setAsBytes);\n        em.merge(result); // merge with list as bytes.\n        \n        em.clear();\n        result = em.find(CollectionEntity.class, \"entityId1\");\n        Assert.assertNotNull(result);\n        assertOnList(result, randomId);\n        \n        Set<byte[]> resultAsBytes = result.getSetAsBytes();\n        \n     // on set type.\n        for(byte[] recInBytes : resultAsBytes)\n        {\n            assertBytes(randomId, recInBytes);\n        }\n        // on set type.\n    }\n\n    @After\n    public void tearDown()\n    {\n        CassandraCli.dropKeySpace(\"KunderaTests\");\n        if(em != null)\n        {\n            em.close();\n        }\n        \n        if(emf != null)\n        {\n            emf.close();\n        }\n        \n        \n    }\n    private void assertOnList(CollectionEntity result, UUID randomId)\n    {\n        List<byte[]> lst = result.getListAsBytes();\n        Assert.assertFalse(lst.isEmpty());\n        Assert.assertEquals(2, lst.size());\n\n        for (byte[] recInBytes : lst)\n        {\n            assertBytes(randomId, recInBytes);\n        }\n    }\n\n    private void assertBytes(UUID randomId, byte[] recInBytes)\n    {\n        try\n        {\n            String str = (String) PropertyAccessorHelper.getObject(String.class, recInBytes);\n            \n            if(!str.equals(\"Vivek\")) // string record is already compared\n            {\n                UUIDAccessor uuidAccessor = new UUIDAccessor();\n                UUID recAsUUID = uuidAccessor.fromBytes(UUID.class, recInBytes);\n                Assert.assertEquals(randomId, recAsUUID);\n                \n            } \n        }\n        catch (Exception e)\n        {\n            Assert.fail();\n        }\n    }\n    \n    \n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/crud/CriteriaQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.crud;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.BaseTest;\nimport com.impetus.client.crud.Month;\nimport com.impetus.client.crud.PersonCassandra;\nimport com.impetus.client.crud.PersonCassandra.Day;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Test case to perform simple CRUD operation.(select using CriteriaBuilder \n * @author vivek.mishra\n */\npublic class CriteriaQueryTest extends BaseTest\n{\n    private static final String _PU = \"cassandra_ds_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager entityManager;\n\n    /** The col. */\n    private Map<Object, Object> col;\n\n    protected Map propertyMap = null;\n\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        \n        CassandraCli.cassandraSetUp();\n        System.setProperty(\"cassandra.start_native_transport\", \"true\");\n\n        if (propertyMap == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        }\n\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n        entityManager = emf.createEntityManager();\n        col = new java.util.HashMap<Object, Object>();\n    }\n\n    /**\n     * On insert cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onInsertCassandra() throws Exception\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n\n        Query findQuery = entityManager.createQuery(\"Select p from PersonCassandra p\", PersonCassandra.class);\n        List<PersonCassandra> allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = entityManager.createQuery(\"Select p from PersonCassandra p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = entityManager.createQuery(\"Select p.age from PersonCassandra p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n\n        PersonCassandra personWithKey = new PersonCassandra();\n        personWithKey.setPersonId(\"111\");\n        entityManager.persist(personWithKey);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n\n        entityManager.clear();\n        PersonCassandra p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertEquals(Day.thursday, p.getDay());\n\n        entityManager.clear();\n        Query q;\n        List<PersonCassandra> persons = queryOverRowkey();\n\n        assertFindByName(entityManager, PersonCassandra.class, PersonCassandra.class, \"vivek\", \"personName\");\n        assertFindByNameAndAge(entityManager, PersonCassandra.class, PersonCassandra.class, \"vivek\", \"10\", \"personName\");\n        assertFindByNameAndAgeGTAndLT(entityManager, PersonCassandra.class, PersonCassandra.class, \"vivek\", \"10\", \"20\",\n                \"personName\");\n        assertFindByNameAndAgeBetween(entityManager, PersonCassandra.class, PersonCassandra.class, \"vivek\", \"10\", \"15\",\n                \"personName\");\n        assertFindByRange(entityManager, PersonCassandra.class, PersonCassandra.class, \"1\", \"2\", \"personId\", true);\n        assertFindWithoutWhereClause(entityManager, PersonCassandra.class, PersonCassandra.class, true);\n\n        // perform merge after query.\n        for (PersonCassandra person : persons)\n        {\n            person.setPersonName(\"'after merge'\");\n            entityManager.merge(person);\n        }\n\n        entityManager.clear();\n\n        p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"'after merge'\", p.getPersonName());\n\n        String updateQuery = \"update PersonCassandra p set p.personName='KK MISHRA' where p.personId=1\";\n        q = entityManager.createQuery(updateQuery);\n        q.executeUpdate();\n\n        entityManager.clear();\n        p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"KK MISHRA\", p.getPersonName());\n\n        updateQuery = \"update PersonCassandra p set p.personName='Screenshot from 2013-10-30 17:43:51.png' where p.personId=1\";\n        q = entityManager.createQuery(updateQuery);\n        q.executeUpdate();\n\n        entityManager.clear();\n        assertFindByNameWithReservedKeywords(entityManager, PersonCassandra.class, PersonCassandra.class, \"Screenshot from 2013-10-30 17:43:51.png\", \"personName\");\n        \n        entityManager.clear();\n        updateQuery = \"update PersonCassandra p set p.personName='john.dever@impetus.co.in' where p.personId=1\";\n        q = entityManager.createQuery(updateQuery);\n        q.executeUpdate();\n\n        entityManager.clear();\n        assertFindByNameWithReservedKeywords(entityManager, PersonCassandra.class, PersonCassandra.class, \"john.dever@impetus.co.in\", \"personName\");\n        \n        \n        // Delete without WHERE clause.\n\n        String deleteQuery = \"DELETE from PersonCassandra\";\n        q = entityManager.createQuery(deleteQuery);\n        Assert.assertEquals(4, q.executeUpdate());\n\n    }\n\n    private List<PersonCassandra> queryOverRowkey()\n    {\n        String qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId = 1\";\n        Query q = entityManager.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n\n        qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId > 1\";\n        q = entityManager.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n\n        qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId < 2\";\n        q = entityManager.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n\n        qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId <= 2\";\n        q = entityManager.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n\n        qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId >= 1\";\n        q = entityManager.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n\n        return persons;\n    }\n\n\n    /**\n     * On merge cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onMergeCassandra() throws Exception\n    {\n        // CassandraCli.cassandraSetUp();\n        // loadData();\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n\n        entityManager.clear();\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        PersonCassandra p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertEquals(Month.APRIL, p.getMonth());\n        // modify record.\n        p.setPersonName(\"newvivek\");\n        entityManager.merge(p);\n\n        assertOnMerge(entityManager, PersonCassandra.class, PersonCassandra.class, \"vivek\", \"newvivek\", \"personName\");\n    }\n\n\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        entityManager.close();\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    private class HandlePersist implements Runnable\n    {\n        private int i;\n\n        public HandlePersist(int i)\n        {\n            this.i = i;\n        }\n\n        @Override\n        public void run()\n        {\n            for (int j = i * 1000; j < (i + 1) * 1000; j++)\n            {\n                entityManager.persist(prepareData(\"\" + j, j + 10));\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/crud/NativeQueryBindParametersTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.crud;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.BaseTest;\nimport com.impetus.client.crud.Month;\nimport com.impetus.client.crud.PersonCassandra;\nimport com.impetus.client.crud.PersonCassandra.Day;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Test case to perform native queries with bind parameters\n * \n * @author dev@antonyudin.com\n */\npublic class NativeQueryBindParametersTest extends BaseTest {\n    private static final String _PU = \"cassandra_ds_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager entityManager;\n\n    protected Map propertyMap = null;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception {\n\n        CassandraCli.cassandraSetUp();\n        System.setProperty(\"cassandra.start_native_transport\", \"true\");\n\n        if (propertyMap == null) {\n            propertyMap = new HashMap();\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        }\n\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n        entityManager = emf.createEntityManager();\n\n        final List<PersonCassandra> entities = new ArrayList<>();\n\n        for (int i = 0; i < 10; i++) {\n\n            final PersonCassandra entity = new PersonCassandra();\n            entity.setPersonId(Integer.toString(i));\n            entity.setPersonName(\"name\" + i);\n            entity.setAge(10 + i);\n            entity.setDay(Day.thursday);\n            entity.setMonth(Month.APRIL);\n\n            entities.add(entity);\n        }\n\n        for (PersonCassandra entity : entities) {\n            entityManager.persist(entity);\n        }\n\n        entityManager.flush();\n        entityManager.clear();\n\n    }\n\n    /**\n     * test native queries with named bind parameters\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onTestNativeQueriesNamedParametersInteger() throws Exception {\n\n        final List<Object[]> result = entityManager\n            .createNativeQuery(\"SELECT \" + \"\\\"personId\\\", \\\"PERSON_NAME\\\", \\\"AGE\\\" \" + \"FROM \" + \"\\\"PERSON\\\" \"\n                + \"WHERE \" + \"\\\"AGE\\\" = :age \" + \"ALLOW FILTERING\")\n            .setParameter(\"age\", 10 + 3).getResultList();\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(result.size(), 1);\n        Assert.assertEquals(result.get(0)[0], \"3\");\n        Assert.assertEquals(result.get(0)[1], \"name\" + 3);\n        Assert.assertEquals(result.get(0)[2], 10 + 3);\n\n        entityManager.clear();\n    }\n\n    /**\n     * test native queries with named bind parameters\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onTestNativeQueriesNamedParametersString() throws Exception {\n\n        final List<Object[]> result =\n            entityManager.createNativeQuery(\"SELECT \" + \"\\\"personId\\\", \\\"PERSON_NAME\\\" \" + \"FROM \" + \"\\\"PERSON\\\" \"\n                + \"WHERE \" + \"\\\"personId\\\" = :personId\").setParameter(\"personId\", \"3\").getResultList();\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(result.size(), 1);\n        Assert.assertEquals(result.get(0)[0], \"3\");\n        Assert.assertEquals(result.get(0)[1], \"name\" + 3);\n\n        entityManager.clear();\n    }\n\n    /**\n     * test native queries with indexed bind parameters\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onTestNativeQueriesIndexedParametersString() throws Exception {\n\n        final List<Object[]> result = entityManager\n            .createNativeQuery(\n                \"SELECT \" + \"\\\"personId\\\", \\\"PERSON_NAME\\\" \" + \"FROM \" + \"\\\"PERSON\\\" \" + \"WHERE \" + \"\\\"personId\\\" = ?\")\n            .setParameter(1, \"2\").getResultList();\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(result.size(), 1);\n        Assert.assertEquals(result.get(0)[0], \"2\");\n        Assert.assertEquals(result.get(0)[1], \"name\" + 2);\n\n        entityManager.clear();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception {\n        entityManager.close();\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/crud/NativeQueryCQLV3Test.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.cassandra.crud;\n\nimport java.nio.ByteBuffer;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.dsdriver.DSClient;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * <Prove description of functionality provided by this Type>\n * \n * @author vivek.mishra\n */\npublic class NativeQueryCQLV3Test\n{\n\n    private final String schema = \"KunderaExamples\";\n\n    private EntityManagerFactoryImpl emf;\n\n    private static final String _PU = \"ds_pu\";\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.dropKeySpace(schema);\n        String nativeSql = \"CREATE KEYSPACE \\\"\" + schema\n                + \"\\\" with replication = {'class':'SimpleStrategy', 'replication_factor':1}\";\n        CassandraCli.getClient().execute_cql3_query(ByteBuffer.wrap(nativeSql.getBytes(\"UTF-8\")), Compression.NONE,\n                ConsistencyLevel.ONE);\n        emf = getEntityManagerFactory();\n    }\n\n    /**\n     * Test create insert column family query.\n     */\n    @Test\n    public void testCreateInsertColumnFamilyQueryVersion3()\n    {\n\n        String useNativeSql = \"USE \\\"\" + schema + \"\\\"\";\n        EntityManager em = emf.createEntityManager();\n\n        Map<String, Client> clientMap = (Map<String, Client>) em.getDelegate();\n        DSClient pc = (DSClient) clientMap.get(_PU);\n        pc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        Query q = em.createNativeQuery(useNativeSql);\n        q.executeUpdate();\n        // create column family\n        String colFamilySql = \"CREATE COLUMNFAMILY users (key varchar PRIMARY KEY,full_name varchar, birth_date int,state varchar)\";\n        q = em.createNativeQuery(colFamilySql);\n        q.executeUpdate();\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"users\", schema));\n\n        // Add indexes\n        String idxSql = \"CREATE INDEX ON users (birth_date)\";\n        q = em.createNativeQuery(idxSql);\n        q.executeUpdate();\n        idxSql = \"CREATE INDEX ON users (state)\";\n        q = em.createNativeQuery(idxSql);\n        q.executeUpdate();\n        // insert users.\n        String insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('bsanderson', 'Brandon Sanderson', 1975, 'UT')\";\n        q = em.createNativeQuery(insertSql);\n        q.executeUpdate();\n        // select key and state\n        String selectSql = \"SELECT key, state FROM users\";\n\n        q = em.createNativeQuery(selectSql, CassandraEntity.class);\n        List<CassandraEntity> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"bsanderson\", results.get(0).getKey());\n        Assert.assertEquals(\"UT\", results.get(0).getState());\n        Assert.assertNull(results.get(0).getFull_name());\n\n        // insert users.\n        insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('prothfuss', 'Patrick Rothfuss', 1973, 'WI')\";\n        q = em.createNativeQuery(insertSql);\n        q.getResultList();\n\n        insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('htayler', 'Howard Tayler', 1968, 'UT')\";\n        q = em.createNativeQuery(insertSql);\n        q.getResultList();\n\n        // select all\n        String selectAll = \"SELECT * FROM users WHERE state='UT' AND birth_date > 1970 Allow Filtering\";\n        q = em.createNativeQuery(selectAll, CassandraEntity.class);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"bsanderson\", results.get(0).getKey());\n        Assert.assertEquals(\"UT\", results.get(0).getState());\n        Assert.assertEquals(\"Brandon Sanderson\", results.get(0).getFull_name());\n        Assert.assertEquals(new Integer(1975), results.get(0).getBirth_date());\n        emf.close();\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory()\n    {\n        Map propertyMap = null;\n        if (propertyMap  == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"\");\n        }\n\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(_PU,propertyMap);\n    }\n\n    @Test\n    public void testCQLBatch()\n    {\n        String useNativeSql = \"USE \\\"\" + schema + \"\\\"\";\n        String createColumnFamily = \"CREATE TABLE CassandraBatchEntity ( user_name varchar PRIMARY KEY, password varchar, name varchar)\";\n        String batchOps = \"BEGIN BATCH INSERT INTO CassandraBatchEntity (user_name, password, name) VALUES ('user2', 'ch@ngem3b', 'second user') UPDATE CassandraBatchEntity SET password = 'ps22dhds' WHERE user_name = 'user2' INSERT INTO CassandraBatchEntity (user_name, password) VALUES ('user3', 'ch@ngem3c') DELETE name FROM CassandraBatchEntity WHERE user_name = 'user2' INSERT INTO CassandraBatchEntity (user_name, password, name) VALUES ('user4', 'ch@ngem3c', 'Andrew') APPLY BATCH\";\n\n        EntityManager em = emf.createEntityManager();\n\n        Map<String, Client> clientMap = (Map<String, Client>) em.getDelegate();\n        DSClient pc = (DSClient) clientMap.get(_PU);\n        pc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n\n        Query q = em.createNativeQuery(useNativeSql);\n        // q.getResultList();\n        q.executeUpdate();\n\n        pc.setConsistencyLevel(ConsistencyLevel.QUORUM);\n        q = em.createNativeQuery(createColumnFamily);\n        // q.getResultList();\n        q.executeUpdate();\n\n        pc.setConsistencyLevel(ConsistencyLevel.QUORUM);\n        q = em.createNativeQuery(batchOps);\n        // q.getResultList();\n        q.executeUpdate();\n\n        q = em.createNativeQuery(\"select * from CassandraBatchEntity\", CassandraBatchEntity.class);\n        List<CassandraBatchEntity> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n\n        // Multiple table batch processing.\n\n        createColumnFamily = \"create table test1 (id timeuuid primary key, url text, userid uuid, datetime timestamp, linkcounts int)\";\n        em.createNativeQuery(createColumnFamily).executeUpdate();\n        createColumnFamily = \"create table test2 (key text primary key, count int)\";\n        em.createNativeQuery(createColumnFamily).executeUpdate();\n        batchOps = \"BEGIN BATCH INSERT INTO test1(id, url) VALUES (64907b40-29a1-11e2-93fa-90b11c71b811,'w') INSERT INTO test2(key, count) VALUES ('key1',12) APPLY BATCH\";\n        em.createNativeQuery(batchOps).executeUpdate();\n        emf.close();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(schema);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/crud/NativeQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.crud;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.query.QueryImpl;\n\n/**\n * Junit test case for NativeQuery support.\n * \n * @author vivek.mishra\n * \n */\npublic class NativeQueryTest\n{\n    // /** The schema. */\n    private final String schema = \"KunderaExamples\";\n\n    private EntityManagerFactoryImpl emf;\n\n    private static final String _PU = \"ds_pu\";\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.dropKeySpace(schema);\n        CassandraCli.createKeySpace(schema);\n        emf = getEntityManagerFactory();\n    }\n\n    /**\n     * Test create native query.\n     */\n    @Test\n    public void testCreateNativeQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        String nativeSql = \"Select * from Cassandra c\";\n\n        QueryImpl q = (QueryImpl) em.createNativeQuery(nativeSql, CassandraEntitySample.class);\n        Assert.assertEquals(nativeSql, q.getJPAQuery());\n    }\n\n    /**\n     * Test execute native create keyspace query.\n     */\n    @Test\n    public void testExecutNativeQuery()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createNativeQuery(useNativeSql);\n        q.executeUpdate();\n        Assert.assertTrue(CassandraCli.keyspaceExist(schema));\n        Assert.assertFalse(CassandraCli.keyspaceExist(\"invalidSchema\"));\n    }\n\n    /**\n     * Native queries should not leak connections. Pelops pool fails providing a\n     * connection if we don't call {@link IPooledConnection#release()}\n     */\n    @Test\n    public void testReleasesNativeQueryConnection()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n\n        EntityManager em = emf.createEntityManager();\n\n        // won't be able to loop if connections are leaked\n        for (int i = 0; i < 30; i++)\n        {\n            Query q = em.createNativeQuery(useNativeSql);\n            q.executeUpdate();\n        }\n    }\n\n    /**\n     * Test create insert column family query.\n     */\n    @Test\n    public void testCreateInsertColumnFamilyQuery()\n    {\n        String useNativeSql = \"USE \" + \"\\\"KunderaExamples\\\"\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createNativeQuery(useNativeSql);\n        // q.getResultList();\n        q.executeUpdate();\n        // create column family\n        String colFamilySql = \"CREATE COLUMNFAMILY users (key varchar PRIMARY KEY,full_name varchar, birth_date int,state varchar)\";\n        q = em.createNativeQuery(colFamilySql);\n        // q.getResultList();\n        q.executeUpdate();\n        Assert.assertTrue(CassandraCli.columnFamilyExist(\"users\", \"KunderaExamples\"));\n\n        // Add indexes\n        String idxSql = \"CREATE INDEX ON users (birth_date)\";\n        q = em.createNativeQuery(idxSql);\n        // q.getResultList();\n        q.executeUpdate();\n        idxSql = \"CREATE INDEX ON users (state)\";\n        q = em.createNativeQuery(idxSql);\n        // q.getResultList();\n        q.executeUpdate();\n        // insert users.\n        String insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('bsanderson', 'Brandon Sanderson', 1975, 'UT')\";\n        q = em.createNativeQuery(insertSql);\n        // q.getResultList();\n        q.executeUpdate();\n        // select key and state\n        String selectSql = \"SELECT key, state FROM users\";\n\n        q = em.createNativeQuery(selectSql,CassandraEntitySample.class);\n        List<CassandraEntitySample> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"bsanderson\", results.get(0).getKey());\n        Assert.assertEquals(\"UT\", results.get(0).getState());\n        Assert.assertNull(results.get(0).getFull_name());\n\n        // insert users.\n        insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('prothfuss', 'Patrick Rothfuss', 1973, 'WI')\";\n        q = em.createNativeQuery(insertSql);\n        q.getResultList();\n\n        insertSql = \"INSERT INTO users (key, full_name, birth_date, state) VALUES ('htayler', 'Howard Tayler', 1968, 'UT')\";\n        q = em.createNativeQuery(insertSql);\n        q.getResultList();\n\n        // select all\n        String selectAll = \"SELECT * FROM users WHERE state='UT' AND birth_date > 1970 ALLOW FILTERING\";\n        q = em.createNativeQuery(selectAll,CassandraEntitySample.class);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"bsanderson\", results.get(0).getKey());\n        Assert.assertEquals(\"UT\", results.get(0).getState());\n        Assert.assertEquals(\"Brandon Sanderson\", results.get(0).getFull_name());\n        Assert.assertEquals(new Integer(1975), results.get(0).getBirth_date());\n\n    }\n\n    /**\n     * Gets the entity manager factory.\n     * \n     * @return the entity manager factory\n     */\n    private EntityManagerFactoryImpl getEntityManagerFactory()\n    {\n        Map propertyMap = null;\n        if (propertyMap  == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"\");\n        }\n\n        return (EntityManagerFactoryImpl) Persistence.createEntityManagerFactory(_PU, propertyMap);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(schema);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/crud/PersonEntityTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.crud;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport javax.persistence.TypedQuery;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.thrift.CQLTranslator;\nimport com.impetus.client.crud.BaseTest;\nimport com.impetus.client.crud.Group;\nimport com.impetus.client.crud.Month;\nimport com.impetus.client.crud.PersonCassandra;\nimport com.impetus.client.crud.PersonCassandra.Day;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.dsdriver.DSClient;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Test case to perform simple CRUD operation.(insert, delete, merge, and\n * select)\n * \n * @author vivek.mishra\n */\npublic class PersonEntityTest extends BaseTest\n{\n    private static final String _PU = \"cassandra_ds_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager entityManager;\n\n    /** The col. */\n    private Map<Object, Object> col;\n\n    protected Map propertyMap = null;\n\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        \n        CassandraCli.cassandraSetUp();\n        System.setProperty(\"cassandra.start_native_transport\", \"true\");\n\n        if (propertyMap == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        }\n\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n        entityManager = emf.createEntityManager();\n        col = new java.util.HashMap<Object, Object>();\n    }\n\n    /**\n     * On insert cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onInsertCassandra() throws Exception\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n\n        Query findQuery = entityManager.createQuery(\"Select p from PersonCassandra p\", PersonCassandra.class);\n        List<PersonCassandra> allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = entityManager.createQuery(\"Select p from PersonCassandra p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = entityManager.createQuery(\"Select p.age from PersonCassandra p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n\n        PersonCassandra personWithKey = new PersonCassandra();\n        personWithKey.setPersonId(\"111\");\n        entityManager.persist(personWithKey);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n\n        entityManager.clear();\n        PersonCassandra p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertEquals(Day.thursday, p.getDay());\n\n        entityManager.clear();\n        Query q;\n        List<PersonCassandra> persons = queryOverRowkey();\n\n        assertFindByName(entityManager, \"PersonCassandra\", PersonCassandra.class, \"vivek\", \"personName\");\n        assertFindByNameAndAge(entityManager, \"PersonCassandra\", PersonCassandra.class, \"vivek\", \"10\", \"personName\");\n        assertFindByNameAndAgeGTAndLT(entityManager, \"PersonCassandra\", PersonCassandra.class, \"vivek\", \"10\", \"20\",\n                \"personName\");\n        assertFindByNameAndAgeBetween(entityManager, \"PersonCassandra\", PersonCassandra.class, \"vivek\", \"10\", \"15\",\n                \"personName\");\n        assertFindByRange(entityManager, \"PersonCassandra\", PersonCassandra.class, \"1\", \"2\", \"personId\", true);\n        assertFindWithoutWhereClause(entityManager, \"PersonCassandra\", PersonCassandra.class, true);\n\n        // perform merge after query.\n        for (PersonCassandra person : persons)\n        {\n            person.setPersonName(\"'after merge'\");\n            entityManager.merge(person);\n        }\n\n        entityManager.clear();\n\n        p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"'after merge'\", p.getPersonName());\n\n        String updateQuery = \"update PersonCassandra p set p.personName='KK MISHRA' where p.personId=1\";\n        q = entityManager.createQuery(updateQuery);\n        q.executeUpdate();\n\n        entityManager.clear();\n        p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"KK MISHRA\", p.getPersonName());\n\n        testCountResult();\n        // Delete without WHERE clause.\n\n        String deleteQuery = \"DELETE from PersonCassandra\";\n        q = entityManager.createQuery(deleteQuery);\n        Assert.assertEquals(4, q.executeUpdate());\n\n    }\n\n    private List<PersonCassandra> queryOverRowkey()\n    {\n        String qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId = 1\";\n        Query q = entityManager.createQuery(qry);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n\n        qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId > 1\";\n        q = entityManager.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n\n        qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId < 2\";\n        q = entityManager.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n\n        qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId <= 2\";\n        q = entityManager.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n\n        qry = \"Select p.personId,p.personName from PersonCassandra p where p.personId >= 1\";\n        q = entityManager.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n\n        return persons;\n    }\n\n    private void testCountResult()\n    {\n        Map<String, Client> clientMap = (Map<String, Client>) entityManager.getDelegate();\n        DSClient tc = (DSClient) clientMap.get(_PU);\n        tc.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);\n        CQLTranslator translator = new CQLTranslator();\n\n        String query = \"select count(*) from \"\n                + translator.ensureCase(new StringBuilder(), \"PERSON\", false).toString();\n        Query q = entityManager.createNativeQuery(query, PersonCassandra.class);\n        List noOfRows = q.getResultList();\n        Assert.assertEquals(new Long(4),noOfRows.get(0));\n\n        entityManager.clear();\n        q = entityManager.createNamedQuery(\"q\");\n        noOfRows = q.getResultList();\n        Assert.assertEquals(4, noOfRows.size());\n    }\n\n    /**\n     * On merge cassandra.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onMergeCassandra() throws Exception\n    {\n        // CassandraCli.cassandraSetUp();\n        // loadData();\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n\n        entityManager.clear();\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        PersonCassandra p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertEquals(Month.APRIL, p.getMonth());\n        // modify record.\n        p.setPersonName(\"newvivek\");\n        entityManager.merge(p);\n\n        assertOnMerge(entityManager, \"PersonCassandra\", PersonCassandra.class, \"vivek\", \"newvivek\", \"personName\");\n    }\n\n    @Test\n    public void onDeleteThenInsertCassandra() throws Exception\n    {\n        // CassandraCli.cassandraSetUp();\n        // CassandraCli.initClient();\n        // loadData();\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        PersonCassandra p = findById(PersonCassandra.class, \"1\", entityManager);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        entityManager.remove(p);\n        entityManager.clear();\n\n        TypedQuery<PersonCassandra> query = entityManager.createQuery(\"Select p from PersonCassandra p\",\n                PersonCassandra.class);\n\n        List<PersonCassandra> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(Month.APRIL, results.get(0).getMonth());\n\n        p1 = prepareData(\"1\", 10);\n        entityManager.persist(p1);\n\n        query = entityManager.createQuery(\"Select p from PersonCassandra p\", PersonCassandra.class);\n\n        results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(Month.APRIL, results.get(0).getMonth());\n\n    }\n\n    @Test\n    public void onRefreshCassandra() throws Exception\n    {\n        // cassandraSetUp();\n        // CassandraCli.cassandraSetUp();\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n        CassandraCli.client.set_keyspace(\"KunderaExamples\");\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n\n        // Check for contains\n        Object pp1 = prepareData(\"1\", 10);\n        Object pp2 = prepareData(\"2\", 20);\n        Object pp3 = prepareData(\"3\", 15);\n        Assert.assertTrue(entityManager.contains(pp1));\n        Assert.assertTrue(entityManager.contains(pp2));\n        Assert.assertTrue(entityManager.contains(pp3));\n\n        // Check for detach\n        entityManager.detach(pp1);\n        entityManager.detach(pp2);\n        Assert.assertFalse(entityManager.contains(pp1));\n        Assert.assertFalse(entityManager.contains(pp2));\n        Assert.assertTrue(entityManager.contains(pp3));\n\n        // Modify value in database directly, refresh and then check PC\n        entityManager.clear();\n        entityManager = emf.createEntityManager();\n        Object o1 = entityManager.find(PersonCassandra.class, \"1\");\n        CQLTranslator translator = new CQLTranslator();\n        String query = \"insert into \\\"PERSON\\\" (\\\"personId\\\",\\\"PERSON_NAME\\\",\\\"AGE\\\") values ('1','Amry',10 )\";\n        CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(query.getBytes()), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        entityManager.refresh(o1);\n        Object oo1 = entityManager.find(PersonCassandra.class, \"1\");\n        Assert.assertTrue(entityManager.contains(o1));\n        Assert.assertEquals(\"Amry\", ((PersonCassandra) oo1).getPersonName());\n    }\n\n    /**\n     * On typed create query\n     * \n     * @throws TException\n     * @throws InvalidRequestException\n     * @throws UnavailableException\n     * @throws TimedOutException\n     * @throws SchemaDisagreementException\n     */\n    @Test\n    public void onTypedQuery() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        TypedQuery<PersonCassandra> query = entityManager.createQuery(\"Select p from PersonCassandra p\",\n                PersonCassandra.class);\n\n        List<PersonCassandra> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(Month.APRIL, results.get(0).getMonth());\n    }\n\n    /**\n     * On typed create query\n     * \n     * @throws TException\n     * @throws InvalidRequestException\n     * @throws UnavailableException\n     * @throws TimedOutException\n     * @throws SchemaDisagreementException\n     */\n    @Test\n    public void onGenericTypedQuery() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        TypedQuery<Object> query = entityManager.createQuery(\"Select p from PersonCassandra p\", Object.class);\n\n        List<Object> results = query.getResultList();\n        Assert.assertNotNull(query);\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(PersonCassandra.class, results.get(0).getClass());\n    }\n\n    /**\n     * on invalid typed query.\n     * \n     * @throws TException\n     * @throws InvalidRequestException\n     * @throws UnavailableException\n     * @throws TimedOutException\n     * @throws SchemaDisagreementException\n     */\n    @Test\n    public void onInvalidTypedQuery() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n\n        TypedQuery<Group> query = null;\n        try\n        {\n            query = entityManager.createQuery(\"Select p from PersonCassandra p\", Group.class);\n            Assert.fail(\"Should have gone to catch block, as it is an invalid scenario!\");\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertNull(query);\n        }\n    }\n\n    @Test\n    public void onGhostRows() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        entityManager.persist(p1);\n        entityManager.persist(p2);\n        entityManager.persist(p3);\n        entityManager.clear();\n        PersonCassandra person = entityManager.find(PersonCassandra.class, \"1\");\n        entityManager.remove(person);\n        entityManager.clear(); // just to make sure that not to be picked up\n                               // from cache.\n        TypedQuery<PersonCassandra> query = entityManager.createQuery(\"Select p from PersonCassandra p\",\n                PersonCassandra.class);\n\n        List<PersonCassandra> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n    }\n\n    @Test\n    public void testWithMultipleThread() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        // CassandraCli.createKeySpace(\"KunderaExamples\");\n        // loadData();\n\n        // EM\n        ExecutorService executor = Executors.newFixedThreadPool(10);\n\n        List<Future> futureList = new ArrayList<Future>();\n\n        for (int i = 0; i < 10; i++)\n        {\n            HandlePersist persist = new HandlePersist(i);\n            futureList.add(executor.submit(persist));\n        }\n\n        while (!futureList.isEmpty())\n        {\n            for (int i = 0; i < futureList.size(); i++)\n            {\n                if (futureList.get(i).isDone())\n                {\n                    futureList.remove(i);\n                }\n            }\n        }\n\n        String qry = \"Select * from \\\"PERSON\\\"\";\n        Query q = entityManager.createNativeQuery(qry, PersonCassandra.class);\n        List<PersonCassandra> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(100, persons.size());\n    }\n\n    // }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        entityManager.close();\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaExamples\");\n    }\n\n    private class HandlePersist implements Runnable\n    {\n        private int i;\n\n        public HandlePersist(int i)\n        {\n            this.i = i;\n        }\n\n        @Override\n        public void run()\n        {\n            for (int j = i * 10; j < (i + 1) * 10; j++)\n            {\n                entityManager.persist(prepareData(\"\" + j, j + 10));\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/crud/ResultIteratorEmbeddableTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.cassandra.crud;\n\n\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.composite.PrimeUser;\nimport com.impetus.kundera.client.cassandra.composite.UserTimeLine;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.query.Query;\n\n/**\n * @author chhavi.gangwal\n * junit for {@link IResultIteratorEmbeddableTest}.\n */\npublic class ResultIteratorEmbeddableTest \n{\n  \n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n    \n   \n    private static final String PERSISTENCE_UNIT = \"ds_pu\";\n    \n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.initClient();\n        \n        \n        \n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        em = emf.createEntityManager();\n    }\n\n\n    \n    @Test\n    public void testScrollViaCQL3() throws Exception\n    {\n        onScroll();\n    }\n\n  \n    private void onScroll()\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 15);\n        Object p3 = prepareData(\"3\", 20);\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        em.flush();\n        em.clear();\n        final String queryWithoutClause = \"Select p from PrimeUser p \";\n\n        assertOnScroll(queryWithoutClause,3);\n\n        final String queryWithClause = \"Select p from PrimeUser p where p.name = vivek\";\n        \n        assertOnScroll(queryWithClause,3);\n        \n        final String queryWithAndClause = \"Select p from PrimeUser p where p.name = vivek and p.key.userId = 'mevivs2' and p.key.tweetId = 15\";\n        \n        assertOnScroll(queryWithAndClause,1);\n\n        final String queryWithLTClause = \"Select p from PrimeUser p where p.name = vivek and p.key.userId = 'mevivs1' and p.key.tweetId < 15\";\n        \n        assertOnScroll(queryWithLTClause,1);\n\n        final String queryWithLTGTClause = \"Select p from PrimeUser p where p.name = vivek and p.key.userId = 'mevivs2' and p.key.tweetId > 10 and p.key.tweetId < 20\";\n        \n        assertOnScroll(queryWithLTGTClause,1);\n\n              \n        String queryWithIdClause = \"Select p from PrimeUser p where p.key.userId = 'mevivs2' \";\n        assertOnScroll(queryWithIdClause,1);\n        \n        String queryWithIdEmbeddableKeyClause = \"Select p from PrimeUser p where p.key.userId = 'mevivs2' and p.key.tweetId = 15\";\n        assertOnScroll(queryWithIdEmbeddableKeyClause,1);\n    }\n\n    \n\n    private void assertOnScroll(final String queryWithoutClause, int expectedCount)\n    {\n        Query query = (Query) em.createQuery(queryWithoutClause,\n                PrimeUser.class);\n        \n        assertOnFetch(query, 3, expectedCount);\n        assertOnFetch(query,2,expectedCount);  // less records\n\n        assertOnFetch(query,4,expectedCount); // more fetch size than available in db.\n        assertOnFetch(query,3,expectedCount); // more fetch size than available in db.\n      \n        assertOnFetch(query,null,expectedCount); //set to null; \n        \n    }\n\n    private void assertOnFetch(Query query, Integer fetchSize, int available)\n    {\n        query.setFetchSize(fetchSize);\n        int counter=0;\n        Iterator<PrimeUser> iter = query.iterate();\n\n        while (iter.hasNext())\n        {\n            Assert.assertNotNull(iter.next());\n            counter++;\n        }\n\n        Assert.assertEquals(counter, fetchSize != null && fetchSize == 0 ? 0:available);\n        try\n        {\n            iter.next();\n            Assert.fail();\n        }\n        catch (NoSuchElementException nsex)\n        {\n            Assert.assertNotNull(nsex.getMessage());\n        }\n    }\n\n    /**\n     * CompositeUserDataType\n     * \n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        CassandraCli.executeCqlQuery(\"TRUNCATE \\\"CompositeUser\\\"\", \"KunderaExamples\");\n    }\n    \n    private Object prepareData(String rowkey, int tweetId)\n    {\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();   \n        UserTimeLine key = new UserTimeLine(\"mevivs\"+rowkey, tweetId, timeLineId);\n        PrimeUser user = new PrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        user.setName(\"vivek\");\n        return user;\n    }\n    \n   \n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/crud/ResultIteratorTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.cassandra.crud;\n\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport java.util.UUID;\nimport org.junit.Assert;\nimport org.junit.Test;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.crud.BaseTest;\nimport com.impetus.client.crud.PersonCassandra;\nimport com.impetus.client.crud.Token;\nimport com.impetus.client.crud.TokenClient;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.query.IResultIterator;\nimport com.impetus.kundera.query.Query;\n\n/**\n * @author vivek.mishra\n * junit for {@link IResultIterator}.\n */\npublic class ResultIteratorTest extends BaseTest\n{\n    private static final String SEC_IDX_CASSANDRA_TEST = \"cassandra_ds_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    public void setUp(final String persistenceUnit,final String keyspace, final String cqlVersion) throws Exception\n    {\n        \n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(keyspace);\n        Map propertyMap = new HashMap();\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        propertyMap.put(CassandraConstants.CQL_VERSION, cqlVersion);\n\n        emf = Persistence.createEntityManagerFactory(persistenceUnit, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testScrollViaCQL3() throws Exception\n    {\n        setUp(SEC_IDX_CASSANDRA_TEST,\"KunderaExamples\",CassandraConstants.CQL_VERSION_3_0);\n        onScroll();\n        tearDown(\"KunderaExamples\");\n    }\n\n    @Test\n    public void testScrollViaCQL3ForNativeQuery() throws Exception\n    {\n        setUp(SEC_IDX_CASSANDRA_TEST,\"KunderaExamples\",CassandraConstants.CQL_VERSION_3_0);\n        OnScrollForNativeQuery();\n        tearDown(\"KunderaExamples\");\n    }\n    \n   \n    @Test\n    public void testCQL3ScrollAssociation() throws Exception \n    {\n        setUp(\"myapp_pu\", \"myapp\", CassandraConstants.CQL_VERSION_3_0);\n        assertOnTokenScroll();\n        tearDown(\"myapp\");\n    }\n    \n    private void assertOnTokenScroll()\n    {\n        Token token1 = new Token();\n        token1.setId(\"tokenId1\");\n        token1.setTokenName(\"tokenName1\");\n        TokenClient client = new TokenClient();\n        client.setClientName(\"tokenClient1\");\n        client.setId(\"tokenClientId\");\n        token1.setClient(client);\n\n        Token token2 = new Token();\n        token2.setId(\"tokenId2\");\n        token2.setTokenName(\"tokenName2\");\n        token2.setClient(client);\n        em.persist(token1);\n        em.persist(token2);\n\n        String queryWithoutClause = \"Select t from Token t\";\n        assertOnTokenScroll(queryWithoutClause,2);\n\n    \n        String queryWithClause = \"Select t from Token t where t.tokenName='tokenName1'\";\n        \n        assertOnTokenScroll(queryWithClause,1);\n\n        //TODO:: Need to discuss with KK, this should be working with token support. Special scenario. \n        String queryWithIdClause = \"Select t from Token t where t.id = 'tokenId1'\";\n//        \n        assertOnTokenScroll(queryWithIdClause,1);\n        \n\n    }\n\n    private void assertOnTokenScroll(String queryClause, int expected)\n    {\n        com.impetus.kundera.query.Query query = (com.impetus.kundera.query.Query) em.createQuery(queryClause,\n                Token.class);\n        \n        int count=0;\n        Iterator<Token> tokens = query.iterate();\n        while(tokens.hasNext())\n        {\n            Token token = tokens.next();\n            Assert.assertNotNull(token);\n            Assert.assertNotNull(token.getClient());\n            Assert.assertEquals(2, token.getClient().getTokens().size());\n            count++;\n        }\n        \n        Assert.assertTrue(count > 0);\n        Assert.assertTrue(count == expected);\n    }\n    \n    public void OnScrollForNativeQuery()\n    {\n    \tObject p = prepareData(UUID.randomUUID().toString(), 99);\n    \t\n        em.persist(p);\n    \tem.flush();\n        em.clear();\n       \n       assertOnScrollForNativeQuery(null,1);\n     }\n    \n    \n    private void onScroll()\n    {\n        \n        Object p1= prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n       \n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        em.flush();\n        em.clear();\n\n\n        final String queryWithClause = \"Select p from PersonCassandra p where p.personName = vivek\";\n        \n        assertOnScroll(queryWithClause,3);\n        \n        final String queryWithAndClause = \"Select p from PersonCassandra p where p.personName = vivek and p.age = 15\";\n        \n        assertOnScroll(queryWithAndClause,1);\n\n        final String queryWithLTClause = \"Select p from PersonCassandra p where p.personName = vivek and p.age < 15\";\n        \n        assertOnScroll(queryWithLTClause,1);\n\n        final String queryWithGTClause = \"Select p from PersonCassandra p where p.personName = vivek and p.age >= 15\";\n        \n        assertOnScroll(queryWithGTClause,2);\n\n        final String queryWithLTGTClause = \"Select p from PersonCassandra p where p.personName = vivek and p.age > 10 and p.age < 20\";\n        \n        assertOnScroll(queryWithLTGTClause,1);\n\n        final String queryWithLTGTEClause = \"Select p from PersonCassandra p where p.personName = vivek and p.age >= 10 and p.age < 20\";\n        \n        assertOnScroll(queryWithLTGTEClause,2);\n        \n        String queryWithIdClause = \"Select p from PersonCassandra p where p.personId = '2' \";\n        assertOnScroll(queryWithIdClause,1);\n    }\n\n   \n    private void assertOnScrollForNativeQuery(final String queryWithoutClause, int expectedCount)\n    {\n        Query query = (Query) em.createNamedQuery(\"q\",\n                PersonCassandra.class);\n        \n       assertOnFetch(query,10,expectedCount);  \n        }\n    \n    \n    \n    \n    private void assertOnScroll(final String queryWithoutClause, int expectedCount)\n    {\n        Query query = (Query) em.createNamedQuery(queryWithoutClause,\n                PersonCassandra.class);\n        \n        assertOnFetch(query, 0, expectedCount);\n        assertOnFetch(query,2,expectedCount);  // less records\n\n        assertOnFetch(query,5,expectedCount); // more fetch size than available in db.\n        assertOnFetch(query,3,expectedCount); // more fetch size than available in db.\n        \n        assertOnFetch(query,null,expectedCount); //set to null; \n        \n    }\n\n    \n   private void assertOnFetch(Query query, Integer fetchSize, int available)\n    {\n        query.setFetchSize(fetchSize);\n        int counter=0;\n        try\n        {\n        Iterator<PersonCassandra> iter = query.iterate();\n\n        while (iter.hasNext())\n        {\n            Assert.assertNotNull(iter.next());\n            counter++;\n        }\n\n        Assert.assertEquals(counter, fetchSize != null && fetchSize == 0 ? 0:available);\n        try\n        {\n            iter.next();\n            Assert.fail();\n        }\n        catch (NoSuchElementException nsex)\n        {\n            Assert.assertNotNull(nsex.getMessage());\n        }\n        }catch(UnsupportedOperationException e)\n        { \n        \tAssert.assertEquals(\"Iteration not supported over native queries\",e.getMessage());\n        }\n        \n    }\n\n    public void tearDown(final String keyspace)\n    {\n//        em.close();\n//        emf.close();\n        CassandraCli.dropKeySpace(keyspace);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/dsdriver/CustomRetry.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n/*\n * author: karthikp.manchala\n */\npackage com.impetus.kundera.client.cassandra.dsdriver;\n\nimport com.datastax.driver.core.Cluster;\nimport com.datastax.driver.core.ConsistencyLevel;\nimport com.datastax.driver.core.Statement;\nimport com.datastax.driver.core.WriteType;\nimport com.datastax.driver.core.exceptions.DriverException;\nimport com.datastax.driver.core.policies.RetryPolicy;\n\n/**\n * The Class CustomRetry.\n */\npublic class CustomRetry implements RetryPolicy\n{\n\n    /** The Constant INSTANCE. */\n    public static final CustomRetry INSTANCE = new CustomRetry();\n\n    /**\n     * Gets the single instance of CustomRetry.\n     * \n     * @return single instance of CustomRetry\n     */\n    public static CustomRetry getInstance()\n    {\n        return INSTANCE;\n    }\n\n    /**\n     * Instantiates a new custom retry.\n     */\n    private CustomRetry()\n    {\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.datastax.driver.core.policies.RetryPolicy#onReadTimeout(com.datastax\n     * .driver.core.Statement, com.datastax.driver.core.ConsistencyLevel, int,\n     * int, boolean, int)\n     */\n    @Override\n    public RetryDecision onReadTimeout(Statement arg0, ConsistencyLevel arg1, int arg2, int arg3, boolean arg4, int arg5)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.datastax.driver.core.policies.RetryPolicy#onUnavailable(com.datastax\n     * .driver.core.Statement, com.datastax.driver.core.ConsistencyLevel, int,\n     * int, int)\n     */\n    @Override\n    public RetryDecision onUnavailable(Statement arg0, ConsistencyLevel arg1, int arg2, int arg3, int arg4)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.datastax.driver.core.policies.RetryPolicy#onWriteTimeout(com.datastax\n     * .driver.core.Statement, com.datastax.driver.core.ConsistencyLevel,\n     * com.datastax.driver.core.WriteType, int, int, int)\n     */\n    @Override\n    public RetryDecision onWriteTimeout(Statement arg0, ConsistencyLevel arg1, WriteType arg2, int arg3, int arg4,\n            int arg5)\n    {\n        return null;\n    }\n\n\t@Override\n\tpublic void close() {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\t@Override\n\tpublic void init(Cluster arg0) {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\t@Override\n\tpublic RetryDecision onRequestError(Statement arg0, ConsistencyLevel arg1,\n\t\t\tDriverException arg2, int arg3) {\n\t\t// TODO Auto-generated method stub\n\t\treturn null;\n\t}\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/dsdriver/DSClientExternalPropertyTest.java",
    "content": "/**\n * Copyright 2014 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.cassandra.dsdriver;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.datastax.driver.core.Cluster;\nimport com.datastax.driver.core.Configuration;\nimport com.datastax.driver.core.HostDistance;\nimport com.datastax.driver.core.policies.ConstantReconnectionPolicy;\nimport com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;\nimport com.datastax.driver.core.policies.DowngradingConsistencyRetryPolicy;\nimport com.datastax.driver.core.policies.ExponentialReconnectionPolicy;\nimport com.datastax.driver.core.policies.FallthroughRetryPolicy;\nimport com.datastax.driver.core.policies.HostFilterPolicy;\nimport com.datastax.driver.core.policies.LatencyAwarePolicy;\nimport com.datastax.driver.core.policies.LoggingRetryPolicy;\nimport com.datastax.driver.core.policies.RoundRobinPolicy;\nimport com.datastax.driver.core.policies.TokenAwarePolicy;\nimport com.datastax.driver.core.policies.WhiteListPolicy;\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.config.CassandraPropertyReader;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * \n * @author shaheed.hussain Test case to check the ds client properties set via a\n *         xml file.\n * \n *         {@link DSClientFactory}\n */\n\npublic class DSClientExternalPropertyTest\n{\n\n    private EntityManagerFactory emf;\n\n    private final String keyspaceName = \"KunderaExamples\";\n\n    private final String _PU = \"external_pu\";\n\n    private Map<String, Object> propertyMap = new HashMap<String, Object>();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(keyspaceName);\n    }\n\n    /**\n     * Test to check external xml properties in case of\n     * RoundRobinPolicy,ExponentialReconnectionPolicy,FallthroughRetryPolicy\n     * with baseDelayMs,maxDelayMs available in the external xml file\n     * \n     * @throws Exception\n     */\n    @Test\n    public void withAllPropertyTest() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n        DSClientFactory ds = new DSClientFactory();\n        final String RRP = RoundRobinPolicy.class.getName();\n        final String ERP = ExponentialReconnectionPolicy.class.getName();\n        final String DCRP = CustomRetry.class.getName();\n        Properties connectionProperties = initialize(ds);\n\n        ds.initialize(propertyMap);\n        Object conn = ds.createPoolOrConnection();\n        Cluster cluster = (Cluster) conn;\n\n        HostDistance distance = HostDistance.LOCAL;\n\n        Configuration configuration = cluster.getConfiguration();\n\n        Assert.assertEquals(configuration.getSocketOptions().getReadTimeoutMillis(), 110000);\n        Assert.assertEquals(configuration.getSocketOptions().getKeepAlive().booleanValue(), false);\n        Assert.assertEquals(configuration.getSocketOptions().getReceiveBufferSize().intValue(), 12);\n        Assert.assertEquals(configuration.getSocketOptions().getReuseAddress().booleanValue(), true);\n        Assert.assertEquals(configuration.getSocketOptions().getSendBufferSize().intValue(), 11);\n        Assert.assertEquals(configuration.getSocketOptions().getSoLinger().intValue(), 10);\n        Assert.assertEquals(configuration.getSocketOptions().getTcpNoDelay().booleanValue(), true);\n\n        Assert.assertEquals(configuration.getPoolingOptions().getCoreConnectionsPerHost(distance), 5);\n        Assert.assertEquals(configuration.getPoolingOptions().getMaxConnectionsPerHost(distance), 12);\n        Assert.assertEquals(configuration.getPoolingOptions()\n                .getMaxRequestsPerConnection(distance), 128);\n\n        Assert.assertEquals(configuration.getPolicies().getLoadBalancingPolicy().getClass().getName(), RRP);\n        Assert.assertEquals(configuration.getPolicies().getReconnectionPolicy().getClass().getName(), ERP);\n        Assert.assertEquals(configuration.getPolicies().getRetryPolicy().getClass().getName(), DCRP);\n\n        Assert.assertEquals(connectionProperties.getProperty(\"baseDelayMs\"), \"11000\");\n        Assert.assertEquals(connectionProperties.getProperty(\"maxDelayMs\"), \"13000\");\n\n        emf.close();\n\n    }\n\n    private Properties initialize(DSClientFactory ds) throws NoSuchMethodException, IllegalAccessException,\n            InvocationTargetException\n    {\n        Properties connectionProperties = CassandraPropertyReader.csmd.getConnectionProperties();\n\n        Method m = GenericClientFactory.class.getDeclaredMethod(\"setKunderaMetadata\", KunderaMetadata.class);\n        if (!m.isAccessible())\n        {\n            m.setAccessible(true);\n        }\n\n        KunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n        m.invoke(ds, kunderaMetadata);\n\n        m = GenericClientFactory.class.getDeclaredMethod(\"setPersistenceUnit\", String.class);\n        if (!m.isAccessible())\n        {\n            m.setAccessible(true);\n        }\n\n        m.invoke(ds, _PU);\n\n        m = GenericClientFactory.class.getDeclaredMethod(\"setExternalProperties\", Map.class);\n        if (!m.isAccessible())\n        {\n            m.setAccessible(true);\n        }\n\n        m.invoke(ds, propertyMap);\n        return connectionProperties;\n    }\n\n    /**\n     * Test to check external xml properties in case of\n     * DCAwareRoundRobinPolicy,ConstantReonnectionPolicy\n     * ,DowngradingConsistencyRetryPolicy with\n     * localdc,usedHostsPerRemoteDc,constantDelayMs available in the external\n     * xml file\n     * \n     * @throws Exception\n     */\n\n    @Test\n    public void withPropertyTest2() throws Exception\n    {\n        propertyMap.put(\"kundera.client.property\", \"dsclienttest2.xml\");\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n\n        DSClientFactory ds = new DSClientFactory();\n        final String CRP = ConstantReconnectionPolicy.class.getName();\n        final String LRTP = LoggingRetryPolicy.class.getName();\n        final String TAP = TokenAwarePolicy.class.getName();\n        Properties connectionProperties = initialize(ds);\n\n        ds.initialize(propertyMap);\n        Object conn = ds.createPoolOrConnection();\n        Cluster cluster = (Cluster) conn;\n\n        HostDistance distance = HostDistance.LOCAL;\n\n        Configuration configuration = cluster.getConfiguration();\n\n        Assert.assertEquals(configuration.getSocketOptions().getReadTimeoutMillis(), 110000);\n        Assert.assertEquals(configuration.getSocketOptions().getKeepAlive().booleanValue(), false);\n        Assert.assertEquals(configuration.getSocketOptions().getReceiveBufferSize().intValue(), 12);\n        Assert.assertEquals(configuration.getSocketOptions().getReuseAddress().booleanValue(), true);\n        Assert.assertEquals(configuration.getSocketOptions().getSendBufferSize().intValue(), 11);\n        Assert.assertEquals(configuration.getSocketOptions().getSoLinger().intValue(), 10);\n        Assert.assertEquals(configuration.getSocketOptions().getTcpNoDelay().booleanValue(), true);\n\n        Assert.assertEquals(configuration.getPoolingOptions().getCoreConnectionsPerHost(distance), 5);\n        Assert.assertEquals(configuration.getPoolingOptions().getMaxConnectionsPerHost(distance), 12);\n        Assert.assertEquals(configuration.getPoolingOptions()\n                .getMaxRequestsPerConnection(distance), 128);\n        Assert.assertEquals(configuration.getPolicies().getLoadBalancingPolicy().getClass().getName(), TAP);\n        Assert.assertEquals(configuration.getPolicies().getReconnectionPolicy().getClass().getName(), CRP);\n        Assert.assertEquals(configuration.getPolicies().getRetryPolicy().getClass().getName(), LRTP);\n\n        Assert.assertEquals(connectionProperties.getProperty(\"constantDelayMs\"), \"110000\");\n        Assert.assertEquals(connectionProperties.getProperty(\"localdc\"), \"datacenter1\");\n        Assert.assertEquals(connectionProperties.getProperty(\"usedHostsPerRemoteDc\"), \"2\");\n        Assert.assertEquals(connectionProperties.getProperty(\"isTokenAware\"), \"true\");\n        Assert.assertEquals(connectionProperties.getProperty(\"isLoggingRetry\"), \"true\");\n\n        emf.close();\n\n    }\n\n    /**\n     * Test to check external xml properties in case of\n     * DCAwareRoundRobinPolicy,ConstantReonnectionPolicy\n     * ,DowngradingConsistencyRetryPolicy with\n     * localdc,usedHostsPerRemoteDc,constantDelayMs available in the external\n     * xml file\n     * \n     * @throws Exception\n     */\n\n    @Test\n    public void testLoadBalancingPolicyShouldBeLatencyAware() throws Exception\n    {\n        propertyMap.put(\"kundera.client.property\", \"dsclienttest3.xml\");\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n\n        DSClientFactory ds = new DSClientFactory();\n        final String CRP = ConstantReconnectionPolicy.class.getName();\n        final String LRTP = LoggingRetryPolicy.class.getName();\n\n        Properties connectionProperties = initialize(ds);\n\n        ds.initialize(propertyMap);\n        Object conn = ds.createPoolOrConnection();\n        Cluster cluster = (Cluster) conn;\n\n        HostDistance distance = HostDistance.LOCAL;\n\n        Configuration configuration = cluster.getConfiguration();\n\n        Assert.assertEquals(configuration.getSocketOptions().getReadTimeoutMillis(), 110000);\n        Assert.assertEquals(configuration.getSocketOptions().getKeepAlive().booleanValue(), false);\n        Assert.assertEquals(configuration.getSocketOptions().getReceiveBufferSize().intValue(), 12);\n        Assert.assertEquals(configuration.getSocketOptions().getReuseAddress().booleanValue(), true);\n        Assert.assertEquals(configuration.getSocketOptions().getSendBufferSize().intValue(), 11);\n        Assert.assertEquals(configuration.getSocketOptions().getSoLinger().intValue(), 10);\n        Assert.assertEquals(configuration.getSocketOptions().getTcpNoDelay().booleanValue(), true);\n\n        Assert.assertEquals(configuration.getPoolingOptions().getCoreConnectionsPerHost(distance), 5);\n        Assert.assertEquals(configuration.getPoolingOptions().getMaxConnectionsPerHost(distance), 12);\n        Assert.assertEquals(configuration.getPoolingOptions()\n                .getMaxRequestsPerConnection(distance), 128);\n        Assert.assertEquals(configuration.getPolicies().getLoadBalancingPolicy().getClass().getName(),\n                LatencyAwarePolicy.class.getName());\n        Assert.assertEquals(configuration.getPolicies().getReconnectionPolicy().getClass().getName(), CRP);\n        Assert.assertEquals(configuration.getPolicies().getRetryPolicy().getClass().getName(), LRTP);\n\n        Assert.assertEquals(connectionProperties.getProperty(\"constantDelayMs\"), \"110000\");\n        Assert.assertEquals(connectionProperties.getProperty(\"localdc\"), \"datacenter1\");\n        Assert.assertEquals(connectionProperties.getProperty(\"usedHostsPerRemoteDc\"), \"2\");\n        Assert.assertEquals(connectionProperties.getProperty(\"isLatencyAware\"), \"true\");\n        Assert.assertEquals(connectionProperties.getProperty(\"isLoggingRetry\"), \"true\");\n\n        emf.close();\n\n    }\n\n    /**\n     * Test to check external xml properties in case of\n     * RoundRobinPolicy,ExponentialReconnectionPolicy,FallthroughRetryPolicy\n     * with baseDelayMs,maxDelayMs missing from external xml file\n     * \n     * @throws Exception\n     */\n\n    @Test\n    public void missingPropertytest() throws Exception\n    {\n\n        propertyMap.put(\"kundera.client.property\", \"DSClientTestWithMissingProperties.xml\");\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n\n        DSClientFactory ds = new DSClientFactory();\n        final String RRP = WhiteListPolicy.class.getName();\n        final String ERP = ExponentialReconnectionPolicy.class.getName();\n        final String DCRP = FallthroughRetryPolicy.class.getName();\n        Properties connectionProperties = initialize(ds);\n\n        ds.initialize(propertyMap);\n        Object conn = ds.createPoolOrConnection();\n        Cluster cluster = (Cluster) conn;\n\n        HostDistance distance = HostDistance.LOCAL;\n\n        Configuration configuration = cluster.getConfiguration();\n\n        Assert.assertEquals(configuration.getSocketOptions().getReadTimeoutMillis(), 110000);\n        Assert.assertEquals(configuration.getSocketOptions().getKeepAlive().booleanValue(), false);\n        Assert.assertEquals(configuration.getSocketOptions().getReceiveBufferSize().intValue(), 12);\n        Assert.assertEquals(configuration.getSocketOptions().getReuseAddress().booleanValue(), true);\n        Assert.assertEquals(configuration.getSocketOptions().getSendBufferSize().intValue(), 11);\n        Assert.assertEquals(configuration.getSocketOptions().getSoLinger().intValue(), 10);\n        Assert.assertEquals(configuration.getSocketOptions().getTcpNoDelay().booleanValue(), true);\n\n        Assert.assertEquals(configuration.getPoolingOptions().getCoreConnectionsPerHost(distance), 5);\n        Assert.assertEquals(configuration.getPoolingOptions().getMaxConnectionsPerHost(distance), 12);\n        Assert.assertEquals(configuration.getPoolingOptions()\n                .getMaxRequestsPerConnection(distance), 128);\n\n        Assert.assertEquals(configuration.getPolicies().getLoadBalancingPolicy().getClass().getName(), RRP);\n        Assert.assertEquals(configuration.getPolicies().getReconnectionPolicy().getClass().getName(), ERP);\n        Assert.assertEquals(configuration.getPolicies().getRetryPolicy().getClass().getName(), DCRP);\n\n        Assert.assertEquals(connectionProperties.getProperty(\"baseDelayMs\"), null);\n        Assert.assertEquals(connectionProperties.getProperty(\"maxDelayMs\"), null);\n        emf.close();\n\n    }\n\n    /**\n     * Test to check external xml properties in case of\n     * DCAwareRoundRobinPolicy,ConstantReonnectionPolicy\n     * ,DowngradingConsistencyRetryPolicy with\n     * localdc,usedHostsPerRemoteDc,constantDelayMs missing from the external\n     * xml file\n     * \n     * @throws Exception\n     */\n\n    @Test\n    public void missingPropertyTest2() throws Exception\n    {\n\n        propertyMap.put(\"kundera.client.property\", \"DSClientTestWithMissingProperties2.xml\");\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n\n        DSClientFactory ds = new DSClientFactory();\n        final String DRRP = HostFilterPolicy.class.getName();\n        final String CRP = ConstantReconnectionPolicy.class.getName();\n        final String DCRP = DowngradingConsistencyRetryPolicy.class.getName();\n        Properties connectionProperties = initialize(ds);\n\n        ds.initialize(propertyMap);\n        Object conn = ds.createPoolOrConnection();\n        Cluster cluster = (Cluster) conn;\n\n        HostDistance distance = HostDistance.LOCAL;\n\n        Configuration configuration = cluster.getConfiguration();\n\n        Assert.assertEquals(configuration.getSocketOptions().getReadTimeoutMillis(), 110000);\n        Assert.assertEquals(configuration.getSocketOptions().getKeepAlive().booleanValue(), false);\n        Assert.assertEquals(configuration.getSocketOptions().getReceiveBufferSize().intValue(), 12);\n        Assert.assertEquals(configuration.getSocketOptions().getReuseAddress().booleanValue(), true);\n        Assert.assertEquals(configuration.getSocketOptions().getSendBufferSize().intValue(), 11);\n        Assert.assertEquals(configuration.getSocketOptions().getSoLinger().intValue(), 10);\n        Assert.assertEquals(configuration.getSocketOptions().getTcpNoDelay().booleanValue(), true);\n\n        Assert.assertEquals(configuration.getPoolingOptions().getCoreConnectionsPerHost(distance), 5);\n        Assert.assertEquals(configuration.getPoolingOptions().getMaxConnectionsPerHost(distance), 12);\n        Assert.assertEquals(configuration.getPoolingOptions()\n                .getMaxRequestsPerConnection(distance), 128);\n\n        Assert.assertEquals(configuration.getPolicies().getLoadBalancingPolicy().getClass().getName(), DRRP);\n        Assert.assertEquals(configuration.getPolicies().getReconnectionPolicy().getClass().getName(), CRP);\n        Assert.assertEquals(configuration.getPolicies().getRetryPolicy().getClass().getName(), DCRP);\n\n        Assert.assertEquals(connectionProperties.getProperty(\"constantDelayMs\"), null);\n\n        emf.close();\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/java/com/impetus/kundera/client/cassandra/dsdriver/HostFilterPredicate.java",
    "content": "package com.impetus.kundera.client.cassandra.dsdriver;\n\nimport com.google.common.base.Predicate;\nimport com.datastax.driver.core.Host;\n\npublic class HostFilterPredicate {\n\n\tprivate static Predicate<Host> INSTANCE = new Predicate<Host>() {\n\n\t\t@Override\n\t\tpublic boolean apply(com.datastax.driver.core.Host arg0) {\n\t\t\t// Dummy predicate\n\t\t\treturn true;\n\t\t}\n\t};\n\n\tpublic Predicate<Host> getInstance() {\n\t\treturn INSTANCE;\n\t}\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/resources/DSClientTestWithMissingProperties.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>cassandra</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"loadbalancing.policy\" value=\"RoundRobinPolicy\"></property>\n\t\t\t\t\t<property name=\"compression\" value=\"NONE\"></property>\n\t\t\t\t\t<property name=\"reconnection.policy\" value=\"ExponentialReconnectionPolicy\"></property>\n\t\t\t\t\t<property name=\"retry.policy\" value=\"FallthroughRetryPolicy\"></property>\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t<property name=\"socket.timeout\" value=\"110000\"></property>\n\t\t\t\t\t<property name=\"readTimeoutMillis\" value=\"110000\"></property>\n\t\t\t\t\t<property name=\"keepAlive\" value=\"false\"></property>\n\t\t\t\t\t<property name=\"reuseAddress\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"soLinger\" value=\"10\"></property>\n\t\t\t\t\t<property name=\"tcpNoDelay\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"receiveBufferSize\" value=\"12\"></property>\n\t\t\t\t\t<property name=\"sendBufferSize\" value=\"11\"></property>\n\t\t\t\t\t\n\t\t\t\t\t<property name=\"whiteList\" value=\"localhost\"></property>\n\t\t\t\t\t<property name=\"hostDistance\" value=\"LOCAL\"></property>\n\t\t\t\t\t<property name=\"maxConnectionsPerHost\" value=\"12\"></property>\n\t\t\t\t\t<property name=\"maxRequestsPerConnection\" value=\"128\"></property>\n\t\t\t\t\t<property name=\"coreConnections\" value=\"5\"></property>\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/resources/DSClientTestWithMissingProperties2.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>cassandra</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"loadbalancing.policy\" value=\"DCAwareRoundRobinPolicy\"></property>\n\t\t\t\t\t<property name=\"compression\" value=\"NONE\"></property>\n\t\t\t\t\t<property name=\"reconnection.policy\" value=\"ConstantReconnectionPolicy\"></property>\n\t\t\t\t\t<property name=\"retry.policy\" value=\"DowngradingConsistencyRetryPolicy\"></property>\n\t\t\t\t\t\n\t\t\t\t\t<property name=\"localdc\" value=\"datacenter1\"></property>\n\t\t\t\t\t<property name=\"usedHostsPerRemoteDc\" value=\"2\"></property>\n\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t<property name=\"socket.timeout\" value=\"110000\"></property>\n\t\t\t\t\t<property name=\"readTimeoutMillis\" value=\"110000\"></property>\n\t\t\t\t\t<property name=\"keepAlive\" value=\"false\"></property>\n\t\t\t\t\t<property name=\"reuseAddress\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"soLinger\" value=\"10\"></property>\n\t\t\t\t\t<property name=\"tcpNoDelay\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"receiveBufferSize\" value=\"12\"></property>\n\t\t\t\t\t<property name=\"sendBufferSize\" value=\"11\"></property>\n\t\t\t\t\t\n\t\t\t\t\t<property name=\"hostFilterPolicy\" value=\"com.impetus.kundera.client.cassandra.dsdriver.HostFilterPredicate\"></property>\n\t\t\t\t\t<property name=\"hostDistance\" value=\"LOCAL\"></property>\n\t\t\t\t\t<property name=\"maxConnectionsPerHost\" value=\"12\"></property>\n\t\t\t\t\t<property name=\"maxRequestsPerConnection\" value=\"128\"></property>\n\t\t\t\t\t<property name=\"coreConnections\" value=\"5\"></property>\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\nhttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\n\t<persistence-unit name=\"ds_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9042\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.kundera.client.cassandra.dsdriver.DSClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"external_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9042\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.kundera.client.cassandra.dsdriver.DSClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"dsclient.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"ds_collection_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.crud.collection.BlogPost</class>\n\t\t<class>com.impetus.client.cassandra.udt.PersonUDT</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9042\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.kundera.client.cassandra.dsdriver.DSClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"ds_composite_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.cassandra.crud.compositeType.association.CassandraEmbeddedAssociation\n\t\t</class>\n\t\t<class>com.impetus.client.cassandra.crud.compositeType.association.UserInfo\n\t\t</class>\n\t\t<class>com.impetus.kundera.client.cassandra.composite.PrimeUserDataType\n\t\t</class>\n\t\t<class>com.impetus.kundera.client.cassandra.composite.PrimeUser\n\t\t</class>\n\t\t<class>com.impetus.kundera.client.cassandra.composite.DSEmbeddedAssociation\n\t\t</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9042\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.kundera.client.cassandra.dsdriver.DSClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"cassandra_ds_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.crud.PersonCassandra</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9042\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.kundera.client.cassandra.dsdriver.DSClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"dsscalar_entity\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.crud.PersonCassandra</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9042\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.kundera.client.cassandra.dsdriver.DSClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"dsscalar\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9042\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.kundera.client.cassandra.dsdriver.DSClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n</persistence>\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/resources/META-INF/persistence_2_0.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!-- persistence.xml schema -->\r\n<xsd:schema targetNamespace=\"http://java.sun.com/xml/ns/persistence\" \r\n  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\r\n  xmlns:persistence=\"http://java.sun.com/xml/ns/persistence\"\r\n  elementFormDefault=\"qualified\" \r\n  attributeFormDefault=\"unqualified\" \r\n  version=\"2.0\">\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n      @(#)persistence_2_0.xsd  1.0  October 1 2009\r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n\r\n  Copyright (c) 2008, 2009 Sun Microsystems. All rights reserved. \r\n  \r\n  This program and the accompanying materials are made available under the \r\n  terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 \r\n  which accompanies this distribution. \r\n  The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html\r\n  and the Eclipse Distribution License is available at \r\n  http://www.eclipse.org/org/documents/edl-v10.php.\r\n  \r\n  Contributors:\r\n      Linda DeMichiel - Java Persistence 2.0, Version 2.0 (October 1, 2009)\r\n      Specification available from http://jcp.org/en/jsr/detail?id=317\r\n \r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n   <xsd:annotation>\r\n     <xsd:documentation><![CDATA[\r\n\r\n     This is the XML Schema for the persistence configuration file.\r\n     The file must be named \"META-INF/persistence.xml\" in the \r\n     persistence archive.\r\n\r\n     Persistence configuration files must indicate\r\n     the persistence schema by using the persistence namespace:\r\n\r\n     http://java.sun.com/xml/ns/persistence\r\n\r\n     and indicate the version of the schema by\r\n     using the version element as shown below:\r\n\r\n      <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n        xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n          http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\"\r\n        version=\"2.0\">\r\n          ...\r\n      </persistence>\r\n\r\n    ]]></xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:simpleType name=\"versionType\">\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:pattern value=\"[0-9]+(\\.[0-9]+)*\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:element name=\"persistence\">\r\n    <xsd:complexType>\r\n      <xsd:sequence>\r\n\r\n        <!-- **************************************************** -->\r\n\r\n        <xsd:element name=\"persistence-unit\" \r\n                     minOccurs=\"1\" maxOccurs=\"unbounded\">\r\n          <xsd:complexType>\r\n            <xsd:annotation>\r\n              <xsd:documentation>\r\n\r\n                Configuration of a persistence unit.\r\n\r\n              </xsd:documentation>\r\n            </xsd:annotation>\r\n            <xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"description\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Description of this persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"provider\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Provider class that supplies EntityManagers for this \r\n                    persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of the JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"non-jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of a non-JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"mapping-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    File containing mapping information. Loaded as a resource \r\n                    by the persistence provider.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jar-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Jar file that is to be scanned for managed classes. \r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"class\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Managed class to be included in the persistence unit and\r\n                    to scan for annotations.  It should be annotated \r\n                    with either @Entity, @Embeddable or @MappedSuperclass.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"exclude-unlisted-classes\" type=\"xsd:boolean\" \r\n                           default=\"true\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    When set to true then only listed classes and jars will \r\n                    be scanned for persistent classes, otherwise the \r\n                    enclosing jar or directory will also be scanned. \r\n                    Not applicable to Java SE persistence units.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"shared-cache-mode\" \r\n                           type=\"persistence:persistence-unit-caching-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Defines whether caching is enabled for the \r\n                    persistence unit if caching is supported by the\r\n                    persistence provider. When set to ALL, all entities \r\n                    will be cached. When set to NONE, no entities will\r\n                    be cached. When set to ENABLE_SELECTIVE, only entities\r\n                    specified as cacheable will be cached. When set to\r\n                    DISABLE_SELECTIVE, entities specified as not cacheable\r\n                    will not be cached. When not specified or when set to\r\n                    UNSPECIFIED, provider defaults may apply.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"validation-mode\" \r\n                           type=\"persistence:persistence-unit-validation-mode-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The validation mode to be used for the persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"properties\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    A list of standard and vendor-specific properties \r\n                    and hints.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n                <xsd:complexType>\r\n                  <xsd:sequence>\r\n                    <xsd:element name=\"property\" \r\n                                 minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                      <xsd:annotation>\r\n                        <xsd:documentation>\r\n                          A name-value pair.\r\n                        </xsd:documentation>\r\n                      </xsd:annotation>\r\n                      <xsd:complexType>\r\n                        <xsd:attribute name=\"name\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                        <xsd:attribute name=\"value\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                      </xsd:complexType>\r\n                    </xsd:element>\r\n                  </xsd:sequence>\r\n                </xsd:complexType>\r\n              </xsd:element>\r\n\r\n            </xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Name used in code to reference this persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"transaction-type\" \r\n                           type=\"persistence:persistence-unit-transaction-type\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Type of transactions used by EntityManagers from this \r\n                  persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n          </xsd:complexType>\r\n        </xsd:element>\r\n      </xsd:sequence>\r\n      <xsd:attribute name=\"version\" type=\"persistence:versionType\" \r\n                     fixed=\"2.0\" use=\"required\"/>\r\n    </xsd:complexType>\r\n  </xsd:element>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-transaction-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum PersistenceUnitTransactionType {JTA, RESOURCE_LOCAL};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"JTA\"/>\r\n      <xsd:enumeration value=\"RESOURCE_LOCAL\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-caching-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum SharedCacheMode { ALL, NONE, ENABLE_SELECTIVE, DISABLE_SELECTIVE, UNSPECIFIED};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"ALL\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n      <xsd:enumeration value=\"ENABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"DISABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"UNSPECIFIED\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-validation-mode-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum ValidationMode { AUTO, CALLBACK, NONE};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"AUTO\"/>\r\n      <xsd:enumeration value=\"CALLBACK\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n</xsd:schema>\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/resources/dsclient.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>cassandra</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"loadbalancing.policy\" value=\"RoundRobinPolicy\"></property>\n\t\t\t\t\t<!-- <property name=\"compression\" value=\"true\"></property> -->\n\t\t\t\t\t<property name=\"reconnection.policy\" value=\"ExponentialReconnectionPolicy\"></property>\n\t\t\t\t\t<property name=\"retry.policy\" value=\"Custom\"></property>\n\t\t\t\t\t<property name=\"customRetryPolicy\"\n\t\t\t\t\t\tvalue=\"com.impetus.kundera.client.cassandra.dsdriver.CustomRetry\"></property>\n\n\n\t\t\t\t\t<property name=\"socket.timeout\" value=\"110000\"></property>\n\t\t\t\t\t<property name=\"readTimeoutMillis\" value=\"110000\"></property>\n\t\t\t\t\t<property name=\"keepAlive\" value=\"false\"></property>\n\t\t\t\t\t<property name=\"reuseAddress\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"soLinger\" value=\"10\"></property>\n\t\t\t\t\t<property name=\"tcpNoDelay\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"receiveBufferSize\" value=\"12\"></property>\n\t\t\t\t\t<property name=\"sendBufferSize\" value=\"11\"></property>\n\n\n\t\t\t\t\t<property name=\"hostDistance\" value=\"LOCAL\"></property>\n\t\t\t\t\t<property name=\"maxConnectionsPerHost\" value=\"12\"></property>\n\t\t\t\t\t<property name=\"maxRequestsPerConnection\" value=\"128\"></property>\n\t\t\t\t\t<property name=\"coreConnections\" value=\"5\"></property>\n\t\t\t\t\t<property name=\"baseDelayMs\" value=\"11000\"></property>\n\t\t\t\t\t<property name=\"maxDelayMs\" value=\"13000\"></property>\n\n\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/resources/dsclienttest2.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>cassandra</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"loadbalancing.policy\" value=\"DCAwareRoundRobinPolicy\"></property>\n\t\t\t\t\t<property name=\"compression\" value=\"NONE\"></property>\n\t\t\t\t\t<property name=\"reconnection.policy\" value=\"ConstantReconnectionPolicy\"></property>\n\t\t\t\t\t<property name=\"retry.policy\" value=\"DowngradingConsistencyRetryPolicy\"></property>\n\n\t\t\t\t\t<property name=\"localdc\" value=\"datacenter1\"></property>\n\t\t\t\t\t<property name=\"usedHostsPerRemoteDc\" value=\"2\"></property>\n\t\t\t\t\t<property name=\"constantDelayMs\" value=\"110000\"></property>\n\n\t\t\t\t\t<property name=\"isTokenAware\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"isLoggingRetry\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"socket.timeout\" value=\"110000\"></property>\n\t\t\t\t\t<property name=\"readTimeoutMillis\" value=\"110000\"></property>\n\t\t\t\t\t<property name=\"keepAlive\" value=\"false\"></property>\n\t\t\t\t\t<property name=\"reuseAddress\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"soLinger\" value=\"10\"></property>\n\t\t\t\t\t<property name=\"tcpNoDelay\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"receiveBufferSize\" value=\"12\"></property>\n\t\t\t\t\t<property name=\"sendBufferSize\" value=\"11\"></property>\n\n\n\t\t\t\t\t<property name=\"hostDistance\" value=\"LOCAL\"></property>\n\t\t\t\t\t<property name=\"maxConnectionsPerHost\" value=\"12\"></property>\n\t\t\t\t\t<property name=\"maxRequestsPerConnection\" value=\"128\"></property>\n\t\t\t\t\t<property name=\"coreConnections\" value=\"5\"></property>\n\n\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "src/kundera-cassandra/cassandra-ds-driver/src/test/resources/dsclienttest3.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>cassandra</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"loadbalancing.policy\" value=\"DCAwareRoundRobinPolicy\"></property>\n\t\t\t\t\t<property name=\"compression\" value=\"NONE\"></property>\n\t\t\t\t\t<property name=\"reconnection.policy\" value=\"ConstantReconnectionPolicy\"></property>\n\t\t\t\t\t<property name=\"retry.policy\" value=\"DowngradingConsistencyRetryPolicy\"></property>\n\t\t\t\t\t\n\t\t\t\t\t<property name=\"localdc\" value=\"datacenter1\"></property>\n\t\t\t\t\t<property name=\"usedHostsPerRemoteDc\" value=\"2\"></property>\n\t\t\t\t\t<property name=\"constantDelayMs\" value=\"110000\"></property>\n\t\t\t\t\t\n\t\t\t\t\t<property name=\"isLatencyAware\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"isLoggingRetry\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"socket.timeout\" value=\"110000\"></property>\n\t\t\t\t\t<property name=\"readTimeoutMillis\" value=\"110000\"></property>\n\t\t\t\t\t<property name=\"keepAlive\" value=\"false\"></property>\n\t\t\t\t\t<property name=\"reuseAddress\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"soLinger\" value=\"10\"></property>\n\t\t\t\t\t<property name=\"tcpNoDelay\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"receiveBufferSize\" value=\"12\"></property>\n\t\t\t\t\t<property name=\"sendBufferSize\" value=\"11\"></property>\n\n\n\t\t\t\t\t<property name=\"hostDistance\" value=\"LOCAL\"></property>\n\t\t\t\t\t<property name=\"maxConnectionsPerHost\" value=\"12\"></property>\n\t\t\t\t\t<property name=\"maxRequestsPerConnection\" value=\"128\"></property>\n\t\t\t\t\t<property name=\"coreConnections\" value=\"5\"></property>\n\n\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t<artifactId>kundera-cassandra-parent</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-cassandra-pelops</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-cassandra-pelops</name>\n\t<url>http://maven.apache.org</url>\n\n\t<repositories>\n\t\t<repository>\n\t\t\t<id>maven.scale7.org</id>\n\t\t\t<name>Scale7 Maven Repo</name>\n\t\t\t<url>https://github.com/s7/mvnrepo/raw/master</url>\n\t\t\t<snapshots>\n\t\t\t\t<enabled>true</enabled>\n\t\t\t</snapshots>\n\t\t</repository>\n\t</repositories>\n\n\t<!-- Dependencies -->\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.scale7</groupId>\n\t\t\t<artifactId>scale7-pelops</artifactId>\n\t\t\t<version>1.3-1.1.x</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.apache.cassandra</groupId>\n\t\t\t\t\t<artifactId>cassandra-thrift</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t</dependencies>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-clean-plugin</artifactId>\n\t\t\t\t<version>2.4.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<filesets>\n\t\t\t\t\t\t<fileset>\n\t\t\t\t\t\t\t<directory>${basedir}</directory>\n\t\t\t\t\t\t\t<excludes>\n\t\t\t\t\t\t\t\t<exclude>.git/**</exclude>\n\t\t\t\t\t\t\t\t<exclude>.gitignore</exclude>\n\t\t\t\t\t\t\t</excludes>\n\t\t\t\t\t\t\t<includes>\n\t\t\t\t\t\t\t\t<include>lucene/**</include>\n\t\t\t\t\t\t\t</includes>\n\t\t\t\t\t\t</fileset>\n\t\t\t\t\t</filesets>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\n\t\t</plugins>\n\n\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/main/java/com/impetus/client/cassandra/pelops/PelopsClient.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.cassandra.pelops;\n\nimport java.io.UnsupportedEncodingException;\nimport java.lang.reflect.Field;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.cassandra.thrift.Cassandra;\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.ColumnParent;\nimport org.apache.cassandra.thrift.CounterColumn;\nimport org.apache.cassandra.thrift.CounterSuperColumn;\nimport org.apache.cassandra.thrift.IndexClause;\nimport org.apache.cassandra.thrift.IndexExpression;\nimport org.apache.cassandra.thrift.IndexOperator;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KeyRange;\nimport org.apache.cassandra.thrift.KeySlice;\nimport org.apache.cassandra.thrift.SlicePredicate;\nimport org.apache.cassandra.thrift.SuperColumn;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.scale7.cassandra.pelops.Bytes;\nimport org.scale7.cassandra.pelops.Mutator;\nimport org.scale7.cassandra.pelops.RowDeletor;\nimport org.scale7.cassandra.pelops.Selector;\nimport org.scale7.cassandra.pelops.exceptions.PelopsException;\nimport org.scale7.cassandra.pelops.pool.IThriftPool;\nimport org.scale7.cassandra.pelops.pool.IThriftPool.IPooledConnection;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.CassandraClientBase;\nimport com.impetus.client.cassandra.CassandraIdGenerator;\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.client.cassandra.common.CassandraUtilities;\nimport com.impetus.client.cassandra.datahandler.CassandraDataHandler;\nimport com.impetus.client.cassandra.index.InvertedIndexHandler;\nimport com.impetus.client.cassandra.query.CassQuery;\nimport com.impetus.client.cassandra.thrift.ThriftRow;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.db.SearchResult;\nimport com.impetus.kundera.generator.AutoGenerator;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.generator.TableGenerator;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.TableGeneratorDiscriptor;\nimport com.impetus.kundera.metadata.model.annotation.DefaultEntityAnnotationProcessor;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessor;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.TimestampGenerator;\n\n/**\n * Client implementation using Pelops. http://code.google.com/p/pelops/\n * \n * @author animesh.kumar\n * @since 0.1\n */\npublic class PelopsClient extends CassandraClientBase implements Client<CassQuery>, Batcher\n{\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(PelopsClient.class);\n\n    /** The data handler. */\n    private PelopsDataHandler dataHandler;\n\n    /** Handler for Inverted indexing. */\n    private InvertedIndexHandler invertedIndexHandler;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /** The client factory. */\n    private PelopsClientFactory clientFactory;\n\n    /** The pool. */\n    private IThriftPool pool;\n\n    /**\n     * default constructor.\n     * \n     * @param indexManager\n     *            the index manager\n     * @param reader\n     *            the reader\n     * @param clientFactory\n     *            the client factory\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param externalProperties\n     *            the external properties\n     * @param pool\n     *            the pool\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param generator\n     *            the generator\n     */\n    public PelopsClient(IndexManager indexManager, EntityReader reader, PelopsClientFactory clientFactory,\n            String persistenceUnit, Map<String, Object> externalProperties, IThriftPool pool,\n            final KunderaMetadata kunderaMetadata, final TimestampGenerator generator)\n    {\n        super(persistenceUnit, externalProperties, kunderaMetadata, generator);\n        this.indexManager = indexManager;\n        this.dataHandler = new PelopsDataHandler(this, kunderaMetadata, generator);\n        this.reader = reader;\n        this.clientFactory = clientFactory;\n        this.clientMetadata = clientFactory.getClientMetadata();\n        this.invertedIndexHandler = new PelopsInvertedIndexHandler(this,\n                MetadataUtils.useSecondryIndex(this.clientMetadata), generator);\n        this.pool = pool;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.cassandra.CassandraClientBase#find(java.lang.Class,\n     * java.lang.Object)\n     */\n    @Override\n    public final Object find(Class entityClass, Object rowId)\n    {\n        return super.find(entityClass, rowId);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.cassandra.CassandraClientBase#findAll(java.lang.Class,\n     * java.lang.String[], java.lang.Object[])\n     */\n    @Override\n    public final <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... rowIds)\n    {\n        return super.findAll(entityClass, columnsToSelect, rowIds);\n    }\n\n    /**\n     * Method to return list of entities for given below attributes:.\n     * \n     * @param entityClass\n     *            entity class\n     * @param relationNames\n     *            relation names\n     * @param isWrapReq\n     *            true, in case it needs to populate enhance entity.\n     * @param metadata\n     *            entity metadata.\n     * @param rowIds\n     *            array of row key s\n     * @return list of wrapped entities.\n     */\n    @Override\n    public final List find(Class entityClass, List<String> relationNames, boolean isWrapReq, EntityMetadata metadata,\n            Object... rowIds)\n    {\n        if (!isOpen())\n        {\n            throw new PersistenceException(\"PelopsClient is closed.\");\n        }\n\n        return findByRowKeys(entityClass, relationNames, isWrapReq, metadata, rowIds);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.cassandra.CassandraClientBase#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    public void delete(Object entity, Object pKey)\n    {\n        if (!isOpen())\n        {\n            throw new PersistenceException(\"PelopsClient is closed.\");\n        }\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                metadata.getPersistenceUnit());\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(metadata.getEntityClazz());\n        // For secondary tables.\n        List<String> secondaryTables = ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation())\n                .getSecondaryTablesName();\n        secondaryTables.add(metadata.getTableName());\n\n        for (String tableName : secondaryTables)\n        {\n            if (isCql3Enabled(metadata))\n            {\n                String deleteQuery = onDeleteQuery(metadata, tableName, metaModel, pKey);\n                executeCQLQuery(deleteQuery, isCql3Enabled(metadata));\n            }\n            else\n            {\n                if (metadata.isCounterColumnType())\n                {\n                    deleteRecordFromCounterColumnFamily(pKey, tableName, metadata, getConsistencyLevel());\n                }\n                else\n                {\n                    RowDeletor rowDeletor = clientFactory.getRowDeletor(pool);\n                    rowDeletor.deleteRow(tableName, Bytes.fromByteBuffer(CassandraUtilities.toBytes(pKey, metadata\n                            .getIdAttribute().getJavaType())), getConsistencyLevel());\n\n                }\n            }\n        }\n        getIndexManager().remove(metadata, entity, pKey);\n\n        // Delete from Inverted Index if applicable\n        Object conn = getConnection();\n        try\n        {\n            invertedIndexHandler.delete(entity, metadata, getConsistencyLevel(), kunderaMetadata);\n        }\n        finally\n        {\n            if (conn != null)\n            {\n                releaseConnection(conn);\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#close()\n     */\n    @Override\n    public final void close()\n    {\n        this.indexManager.flush();\n        this.dataHandler = null;\n        this.invertedIndexHandler = null;\n    }\n\n    /**\n     * Persists records into Join Table.\n     * \n     * @param joinTableData\n     *            the join table data\n     */\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        Mutator mutator = clientFactory.getMutator(pool);\n\n        String joinTableName = joinTableData.getJoinTableName();\n        String invJoinColumnName = joinTableData.getInverseJoinColumnName();\n        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                joinTableData.getEntityClass());\n\n        if (isCql3Enabled(entityMetadata))\n        {\n            Cassandra.Client conn = null;\n            Object pooledConnection = null;\n            pooledConnection = getConnection();\n            conn = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);\n            persistJoinTableByCql(joinTableData, conn);\n        }\n        else\n        {\n            for (Object key : joinTableRecords.keySet())\n            {\n                Set<Object> values = joinTableRecords.get(key);\n\n                List<Column> columns = new ArrayList<Column>();\n\n                Class columnType = null;\n                for (Object value : values)\n                {\n                    Column column = new Column();\n                    column.setName(PropertyAccessorFactory.STRING.toBytes(invJoinColumnName\n                            + Constants.JOIN_COLUMN_NAME_SEPARATOR + value.toString()));\n                    column.setValue(PropertyAccessorHelper.getBytes(value));\n                    column.setTimestamp(generator.getTimestamp());\n                    columnType = value.getClass();\n                    columns.add(column);\n                }\n\n                createIndexesOnColumns(entityMetadata, joinTableName, columns, columnType);\n\n                mutator.writeColumns(joinTableName, Bytes.fromByteArray(PropertyAccessorHelper.getBytes(key)),\n                        Arrays.asList(columns.toArray(new Column[0])));\n            }\n        }\n        if (log.isInfoEnabled())\n        {\n            log.info(\" Persisted data with join table column family {}\", joinTableData.getJoinTableName());\n        }\n        mutator.execute(getConsistencyLevel());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String joinTableName, String joinColumnName,\n            String inverseJoinColumnName, Object parentId, Class columnJavaType)\n    {\n        List<Object> foreignKeys = new ArrayList<Object>();\n\n        if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0))\n        {\n            foreignKeys = getColumnsByIdUsingCql(schemaName, joinTableName, joinColumnName, inverseJoinColumnName,\n                    parentId, columnJavaType);\n        }\n        else\n        {\n            Selector selector = clientFactory.getSelector(pool);\n\n            List<Column> columns = selector.getColumnsFromRow(joinTableName,\n                    Bytes.fromByteArray(PropertyAccessorHelper.getBytes(parentId)),\n                    Selector.newColumnsPredicateAll(true, 10), getConsistencyLevel());\n\n            foreignKeys = dataHandler.getForeignKeysFromJoinTable(inverseJoinColumnName, columns, columnJavaType);\n\n            if (log.isInfoEnabled())\n            {\n                log.info(\"Returning number of keys from join table\", foreignKeys != null ? foreignKeys.size() : null);\n            }\n        }\n        return (List<E>) foreignKeys;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n        List<Object> rowKeys = new ArrayList<Object>();\n\n        if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0))\n        {\n            rowKeys = findIdsByColumnUsingCql(schemaName, tableName, pKeyName, columnName, columnValue, entityClazz);\n        }\n        else\n        {\n            Selector selector = clientFactory.getSelector(pool);\n            SlicePredicate slicePredicate = Selector.newColumnsPredicateAll(false, 10000);\n            EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n\n            IndexClause ix = Selector.newIndexClause(Bytes.EMPTY, 10000, Selector.newIndexExpression(columnName\n                    + Constants.JOIN_COLUMN_NAME_SEPARATOR + columnValue, IndexOperator.EQ,\n                    Bytes.fromByteArray(PropertyAccessorHelper.getBytes(columnValue))));\n\n            Map<Bytes, List<Column>> qResults = selector.getIndexedColumns(tableName, ix, slicePredicate,\n                    getConsistencyLevel());\n\n            // iterate through complete map and\n            Iterator<Bytes> rowIter = qResults.keySet().iterator();\n            while (rowIter.hasNext())\n            {\n                Bytes rowKey = rowIter.next();\n\n                PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor((Field) metadata\n                        .getIdAttribute().getJavaMember());\n                Object value = accessor.fromBytes(metadata.getIdAttribute().getJavaType(), rowKey.toByteArray());\n\n                rowKeys.add(value);\n            }\n        }\n        if (rowKeys != null && !rowKeys.isEmpty())\n        {\n            return rowKeys.toArray(new Object[0]);\n        }\n\n        if (log.isInfoEnabled())\n        {\n            log.info(\"No row keys found, returning null.\");\n        }\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    @Override\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n\n        if (!isOpen())\n        {\n            throw new PersistenceException(\"PelopsClient is closed.\");\n        }\n\n        RowDeletor rowDeletor = clientFactory.getRowDeletor(pool);\n        rowDeletor.deleteRow(tableName,\n                Bytes.fromByteBuffer(CassandraUtilities.toBytes(columnValue, columnValue.getClass())),\n                getConsistencyLevel());\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n        return super.find(entityClass, embeddedColumnMap, dataHandler);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.String,\n     * java.lang.String, com.impetus.kundera.metadata.model.EntityMetadata)\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class clazz)\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n        List<Object> entities = null;\n        if (isCql3Enabled(m))\n        {\n            entities = findByRelationQuery(m, colName, colValue, clazz, dataHandler);\n        }\n        else\n        {\n            Selector selector = clientFactory.getSelector(pool);\n            SlicePredicate slicePredicate = Selector.newColumnsPredicateAll(false, 10000);\n            IndexClause ix = Selector.newIndexClause(\n                    Bytes.EMPTY,\n                    10000,\n                    Selector.newIndexExpression(colName, IndexOperator.EQ,\n                            Bytes.fromByteArray(PropertyAccessorHelper.getBytes(colValue))));\n            Map<Bytes, List<Column>> qResults;\n            try\n            {\n                qResults = selector.getIndexedColumns(m.getTableName(), ix, slicePredicate, getConsistencyLevel());\n            }\n            catch (PelopsException e)\n            {\n                log.warn(\"Error while retrieving entities for given column {} for class {}.\", colName, clazz);\n                return entities;\n            }\n            entities = new ArrayList<Object>(qResults.size());\n            // iterate through complete map and populateData\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n\n            EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n            List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n\n            if (subManagedType.isEmpty())\n            {\n                entities = populateData(m, qResults, entities, false, m.getRelationNames(), dataHandler);\n            }\n            else\n            {\n                for (AbstractManagedType subEntity : subManagedType)\n                {\n                    EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                            subEntity.getJavaType());\n                    entities = populateData(subEntityMetadata, qResults, entities, false,\n                            subEntityMetadata.getRelationNames(), dataHandler);\n                }\n            }\n\n        }\n        return entities;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<CassQuery> getQueryImplementor()\n    {\n        return CassQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.metadata\n     * .model.EntityMetadata, java.lang.Object, java.lang.Object,\n     * java.util.List)\n     */\n    @Override\n    protected void onPersist(EntityMetadata metadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n\n        if (!isOpen())\n        {\n            throw new PersistenceException(\"PelopsClient is closed.\");\n        }\n\n        // check for counter column\n        if (isUpdate && metadata.isCounterColumnType())\n        {\n            throw new UnsupportedOperationException(\"Invalid operation! Merge is not possible over counter column.\");\n        }\n\n        String insert_Query = null;\n        if (isCql3Enabled(metadata))\n        {\n            Cassandra.Client client = getRawClient(metadata.getSchema());\n            try\n            {\n                cqlClient.persist(metadata, entity, client, rlHolders, getTtlValues().get(metadata.getTableName()));\n            }\n            catch (InvalidRequestException e)\n            {\n                log.error(\"Error during persist while executing query {}, Caused by: .\", insert_Query, e);\n                throw new KunderaException(e);\n            }\n            catch (TException e)\n            {\n                log.error(\"Error during persist while executing query {}, Caused by: .\", insert_Query, e);\n                throw new KunderaException(e);\n            }\n            catch (UnsupportedEncodingException e)\n            {\n                log.error(\"Error during persist while executing query {}, Caused by: .\", insert_Query, e);\n                throw new KunderaException(e);\n            }\n        }\n        else\n        {\n            Collection<ThriftRow> tfRows = null;\n            try\n            {\n                String columnFamily = metadata.getTableName();\n                tfRows = dataHandler.toThriftRow(entity, id, metadata, columnFamily, getTtlValues().get(columnFamily));\n            }\n            catch (Exception e)\n            {\n                log.error(\"Error during persist, Caused by: .\", e);\n                throw new KunderaException(e);\n            }\n            for (ThriftRow tf : tfRows)\n            {\n\n                if (tf.getColumnFamilyName().equals(metadata.getTableName()))\n                {\n                    addRelationsToThriftRow(metadata, tf, rlHolders);\n                }\n                Mutator mutator = clientFactory.getMutator(pool);\n                if (metadata.isCounterColumnType())\n                {\n                    if (log.isInfoEnabled())\n                    {\n                        log.info(\"Persisting counter column family record for row key {}\", tf.getId());\n                    }\n                    List<CounterColumn> thriftCounterColumns = tf.getCounterColumns();\n                    List<CounterSuperColumn> thriftCounterSuperColumns = tf.getCounterSuperColumns();\n                    if (thriftCounterColumns != null && !thriftCounterColumns.isEmpty())\n                    {\n                        mutator.writeCounterColumns(tf.getColumnFamilyName(),\n                                Bytes.fromByteBuffer(CassandraUtilities.toBytes(tf.getId(), tf.getId().getClass())),\n                                Arrays.asList(tf.getCounterColumns().toArray(new CounterColumn[0])));\n                    }\n\n                    if (thriftCounterSuperColumns != null && !thriftCounterSuperColumns.isEmpty())\n                    {\n                        for (CounterSuperColumn sc : thriftCounterSuperColumns)\n                        {\n                            mutator.writeSubCounterColumns(\n                                    tf.getColumnFamilyName(),\n                                    Bytes.fromByteBuffer(CassandraUtilities.toBytes(tf.getId(), tf.getId().getClass())),\n                                    Bytes.fromByteArray(sc.getName()), sc.getColumns());\n                        }\n                    }\n                }\n                else\n                {\n                    List<Column> thriftColumns = tf.getColumns();\n                    List<SuperColumn> thriftSuperColumns = tf.getSuperColumns();\n                    if (thriftColumns != null && !thriftColumns.isEmpty())\n                    {\n                        // Bytes.from\n                        mutator.writeColumns(tf.getColumnFamilyName(),\n                                Bytes.fromByteBuffer(CassandraUtilities.toBytes(tf.getId(), tf.getId().getClass())),\n                                tf.getColumns());\n                    }\n\n                    if (thriftSuperColumns != null && !thriftSuperColumns.isEmpty())\n                    {\n                        for (SuperColumn sc : thriftSuperColumns)\n                        {\n                            if (log.isInfoEnabled())\n                            {\n                                log.info(\"Persisting super column family record for row key {}\", tf.getId());\n                            }\n\n                            mutator.writeSubColumns(\n                                    tf.getColumnFamilyName(),\n                                    Bytes.fromByteBuffer(CassandraUtilities.toBytes(tf.getId(), tf.getId().getClass())),\n                                    Bytes.fromByteArray(sc.getName()), sc.getColumns());\n                        }\n                    }\n                }\n                mutator.execute(getConsistencyLevel());\n            }\n            tfRows = null;\n            if (isTtlPerRequest())\n            {\n                getTtlValues().clear();\n            }\n        }\n    }\n\n    /**\n     * Indexes @Embedded and @ElementCollection objects of this entity to a\n     * separate column family.\n     * \n     * @param node\n     *            the node\n     * @param entityMetadata\n     *            the entity metadata\n     */\n    @Override\n    protected void indexNode(Node node, EntityMetadata entityMetadata)\n    {\n        // Index to lucene if applicable\n        super.indexNode(node, entityMetadata);\n\n        // Write to inverted index table if applicable\n        // Delete from Inverted Index if applicable\n        invertedIndexHandler.write(node, entityMetadata, getPersistenceUnit(), getConsistencyLevel(), dataHandler);\n    }\n\n    /**\n     * Load super columns.\n     * \n     * @param keyspace\n     *            the keyspace\n     * @param columnFamily\n     *            the column family\n     * @param rowId\n     *            the row id\n     * @param superColumnNames\n     *            the super column names\n     * @return the list\n     */\n\n    @Override\n    public final List<SuperColumn> loadSuperColumns(String keyspace, String columnFamily, String rowId,\n            String... superColumnNames)\n    {\n        if (!isOpen())\n            throw new PersistenceException(\"PelopsClient is closed.\");\n        Selector selector = clientFactory.getSelector(pool);\n        List<ByteBuffer> rowKeys = new ArrayList<ByteBuffer>();\n        rowKeys.add(ByteBuffer.wrap(rowId.getBytes()));\n\n        if (log.isInfoEnabled())\n        {\n            log.info(\"Retrieving record of super column family {} for row key {}\", columnFamily, rowId);\n        }\n\n        return selector.getSuperColumnsFromRow(columnFamily, rowId, Selector.newColumnsPredicate(superColumnNames),\n                getConsistencyLevel());\n    }\n\n    /**\n     * Query related methods.\n     * \n     * @param clazz\n     *            the clazz\n     * @param relationalField\n     *            the relational field\n     * @param isNative\n     *            the is native\n     * @param cqlQuery\n     *            the cql query\n     * @return the list\n     */\n\n    /**\n     * Method to execute cql query and return back entity/enhance entities.\n     * \n     * @param cqlQuery\n     *            cql query to be executed.\n     * @param clazz\n     *            entity class.\n     * @param relationalField\n     *            collection for relational fields.\n     * @return list of objects.\n     * \n     */\n    @Override\n    public List executeQuery(Class clazz, List<String> relationalField, boolean isNative, String cqlQuery)\n    {\n        return super.executeSelectQuery(clazz, relationalField, dataHandler, isNative, cqlQuery);\n    }\n\n    /**\n     * Find.\n     * \n     * @param ixClause\n     *            the ix clause\n     * @param m\n     *            the m\n     * @param isRelation\n     *            the is relation\n     * @param relations\n     *            the relations\n     * @param maxResult\n     *            the max result\n     * @param columns\n     *            the columns\n     * @return the list\n     */\n    @Override\n    public List find(List<IndexClause> ixClause, EntityMetadata m, boolean isRelation, List<String> relations,\n            int maxResult, List<String> columns)\n    {\n        Selector selector = clientFactory.getSelector(pool);\n\n        SlicePredicate slicePredicate = Selector.newColumnsPredicateAll(false, Integer.MAX_VALUE);\n        if (columns != null && !columns.isEmpty())\n        {\n            slicePredicate = Selector.newColumnsPredicate(columns.toArray(new String[] {}));\n        }\n\n        List<Object> entities = new ArrayList<Object>();\n        if (ixClause.isEmpty())\n        {\n            if (m.isCounterColumnType())\n            {\n                try\n                {\n                    IPooledConnection connection = getConnection();\n                    org.apache.cassandra.thrift.Cassandra.Client thriftClient = connection.getAPI();\n                    List<KeySlice> ks = thriftClient.get_range_slices(new ColumnParent(m.getTableName()),\n                            slicePredicate, Selector.newKeyRange(\"\", \"\", maxResult), getConsistencyLevel());\n                    connection.release();\n                    entities = onCounterColumn(m, isRelation, relations, ks);\n                }\n                catch (InvalidRequestException irex)\n                {\n                    log.error(\"Error during executing find, Caused by: .\", irex);\n                    throw new PersistenceException(irex);\n                }\n                catch (UnavailableException uex)\n                {\n                    log.error(\"Error during executing find, Caused by: .\", uex);\n                    throw new PersistenceException(uex);\n                }\n                catch (TimedOutException tex)\n                {\n                    log.error(\"Error during executing find, Caused by: .\", tex);\n                    throw new PersistenceException(tex);\n                }\n                catch (TException tex)\n                {\n                    log.error(\"Error during executing find, Caused by: .\", tex);\n                    throw new PersistenceException(tex);\n                }\n            }\n            else\n            {\n                if (m.getType().isSuperColumnFamilyMetadata())\n                {\n                    Map<Bytes, List<SuperColumn>> qResults = selector.getSuperColumnsFromRows(m.getTableName(),\n                            selector.newKeyRange(\"\", \"\", maxResult), slicePredicate, getConsistencyLevel());\n                    entities = new ArrayList<Object>(qResults.size());\n\n                    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                            m.getPersistenceUnit());\n\n                    EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n                    List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n\n                    for (Bytes key : qResults.keySet())\n                    {\n                        onSuperColumn(m, isRelation, relations, entities, qResults.get(key), key.getBytes());\n                    }\n                }\n                else\n                {\n                    Map<Bytes, List<Column>> qResults = selector.getColumnsFromRows(m.getTableName(),\n                            selector.newKeyRange(\"\", \"\", maxResult), slicePredicate, getConsistencyLevel());\n                    entities = new ArrayList<Object>(qResults.size());\n                    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                            m.getPersistenceUnit());\n\n                    EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n                    List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n                    for (Bytes key : qResults.keySet())\n                    {\n                        onColumn(m, isRelation, relations, entities, qResults.get(key), subManagedType, key.getBytes());\n                    }\n                }\n\n            }\n        }\n        else\n        {\n            entities = new ArrayList<Object>();\n            for (IndexClause ix : ixClause)\n            {\n                Map<Bytes, List<Column>> qResults = selector.getIndexedColumns(m.getTableName(), ix, slicePredicate,\n                        getConsistencyLevel());\n\n                MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                        m.getPersistenceUnit());\n\n                EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n                List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n\n                for (Bytes key : qResults.keySet())\n                {\n                    onColumn(m, isRelation, relations, entities, qResults.get(key), subManagedType, key.getBytes());\n                }\n            }\n        }\n        return entities;\n    }\n\n    /**\n     * Find.\n     * \n     * @param m\n     *            the m\n     * @param relationNames\n     *            the relation names\n     * @param conditions\n     *            the conditions\n     * @param maxResult\n     *            the max result\n     * @param columns\n     *            the columns\n     * @return the list\n     */\n    public List<EnhanceEntity> find(EntityMetadata m, List<String> relationNames, List<IndexClause> conditions,\n            int maxResult, List<String> columns)\n    {\n        return (List<EnhanceEntity>) find(conditions, m, true, relationNames, maxResult, columns);\n    }\n\n    /**\n     * Find by range.\n     * \n     * @param minVal\n     *            the min val\n     * @param maxVal\n     *            the max val\n     * @param m\n     *            the m\n     * @param isWrapReq\n     *            the is wrap req\n     * @param relations\n     *            the relations\n     * @param columns\n     *            the columns\n     * @param conditions\n     *            the conditions\n     * @param maxResults\n     *            the max results\n     * @return the list\n     * @throws Exception\n     *             the exception\n     */\n    @Override\n    public List findByRange(byte[] minVal, byte[] maxVal, EntityMetadata m, boolean isWrapReq, List<String> relations,\n            List<String> columns, List<IndexExpression> conditions, int maxResults) throws Exception\n    {\n        Selector selector = clientFactory.getSelector(pool);\n\n        SlicePredicate slicePredicate = Selector.newColumnsPredicateAll(false, Integer.MAX_VALUE);\n        if (columns != null && !columns.isEmpty())\n        {\n            slicePredicate = Selector.newColumnsPredicate(columns.toArray(new String[] {}));\n        }\n\n        KeyRange keyRange = selector.newKeyRange(minVal != null ? Bytes.fromByteArray(minVal) : Bytes.fromUTF8(\"\"),\n                maxVal != null ? Bytes.fromByteArray(maxVal) : Bytes.fromUTF8(\"\"), maxResults);\n        if (conditions != null)\n        {\n            keyRange.setRow_filter(conditions);\n            keyRange.setRow_filterIsSet(true);\n        }\n        List<KeySlice> keys = selector.getKeySlices(new ColumnParent(m.getTableName()), keyRange, slicePredicate,\n                getConsistencyLevel());\n\n        List results = null;\n        if (keys != null)\n        {\n            results = populateEntitiesFromKeySlices(m, isWrapReq, relations, keys, dataHandler);\n        }\n\n        if (log.isInfoEnabled())\n        {\n            log.info(\"Returning entities for find by range for\", results != null ? results.size() : null);\n        }\n\n        return results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.cassandra.CassandraClientBase#searchInInvertedIndex\n     * (java.lang.String, com.impetus.kundera.metadata.model.EntityMetadata,\n     * java.util.Map)\n     */\n    public List<SearchResult> searchInInvertedIndex(String columnFamilyName, EntityMetadata m,\n            Map<Boolean, List<IndexClause>> indexClauseMap)\n    {\n        // Delete from Inverted Index if applicable\n        Object conn = getConnection();\n        try\n        {\n            return invertedIndexHandler.search(m, getPersistenceUnit(), getConsistencyLevel(), indexClauseMap);\n        }\n        finally\n        {\n            releaseConnection(conn);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#getDataHandler()\n     */\n    @Override\n    protected CassandraDataHandler getDataHandler()\n    {\n        return dataHandler;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.cassandra.CassandraClientBase#getConnection()\n     */\n    protected IPooledConnection getConnection()\n    {\n        return clientFactory.getConnection(pool);\n    }\n\n    /**\n     * Return cassandra client instance.\n     * \n     * @param connection\n     *            the connection\n     * @return the connection\n     */\n    protected Cassandra.Client getConnection(Object connection)\n    {\n        if (connection != null)\n        {\n            return ((IPooledConnection) connection).getAPI();\n        }\n\n        throw new KunderaException(\"Invalid configuration!, no available pooled connection found for:\"\n                + this.getClass().getSimpleName());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.cassandra.CassandraClientBase#releaseConnection(java\n     * .lang.Object)\n     */\n    protected void releaseConnection(Object conn)\n    {\n        clientFactory.releaseConnection((IPooledConnection) conn);\n    }\n\n    /**\n     * Gets the mutator.\n     * \n     * @return the mutator\n     */\n    Mutator getMutator()\n    {\n        return clientFactory.getMutator(pool);\n    }\n\n    /**\n     * Gets the selector.\n     * \n     * @return the selector\n     */\n    Selector getSelector()\n    {\n        return clientFactory.getSelector(pool);\n    }\n\n    /**\n     * Gets the row deletor.\n     * \n     * @return the row deletor\n     */\n    RowDeletor getRowDeletor()\n    {\n        return clientFactory.getRowDeletor(pool);\n    }\n\n    /**\n     * Populate data.\n     * \n     * @param m\n     *            the m\n     * @param qResults\n     *            the q results\n     * @param entities\n     *            the entities\n     * @param isRelational\n     *            the is relational\n     * @param relationNames\n     *            the relation names\n     * @param dataHandler\n     *            the data handler\n     * @return the list\n     */\n    private List populateData(EntityMetadata m, Map<Bytes, List<Column>> qResults, List<Object> entities,\n            boolean isRelational, List<String> relationNames, CassandraDataHandler dataHandler)\n    {\n        if (m.getType().isSuperColumnFamilyMetadata())\n        {\n            Set<Bytes> primaryKeys = qResults.keySet();\n\n            if (primaryKeys != null && !primaryKeys.isEmpty())\n            {\n                Object[] rowIds = new Object[primaryKeys.size()];\n                int i = 0;\n                for (Bytes b : primaryKeys)\n                {\n                    rowIds[i] = PropertyAccessorHelper.getObject(b, (Field) m.getIdAttribute().getJavaMember());\n                    i++;\n                }\n                entities.addAll(findAll(m.getEntityClazz(), null, rowIds));\n            }\n\n        }\n        else\n        {\n            Iterator<Bytes> rowIter = qResults.keySet().iterator();\n            while (rowIter.hasNext())\n            {\n                Bytes rowKey = rowIter.next();\n                List<Column> columns = qResults.get(rowKey);\n                try\n                {\n                    Object id = PropertyAccessorHelper\n                            .getObject(m.getIdAttribute().getJavaType(), rowKey.toByteArray());\n                    Object e = null;\n                    e = dataHandler.populateEntity(new ThriftRow(id, m.getTableName(), columns,\n                            new ArrayList<SuperColumn>(0), new ArrayList<CounterColumn>(0),\n                            new ArrayList<CounterSuperColumn>(0)), m, KunderaCoreUtils.getEntity(e), relationNames,\n                            isRelational);\n                    if (e != null)\n                    {\n                        entities.add(e);\n                    }\n                }\n                catch (IllegalStateException e)\n                {\n                    log.error(\"Error while returning entities for {}, Caused by: .\", m.getEntityClazz(), e);\n                    throw new KunderaException(e);\n                }\n                catch (Exception e)\n                {\n                    log.error(\"Error while returning entities for {}, Caused by: .\", m.getEntityClazz(), e);\n                    throw new KunderaException(e);\n                }\n            }\n        }\n        return entities;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        return (Generator) KunderaCoreUtils.createNewInstance(PelopsIdGenerator.class);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/main/java/com/impetus/client/cassandra/pelops/PelopsClientFactory.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.cassandra.pelops;\r\n\r\nimport java.util.Collection;\r\nimport java.util.Collections;\r\nimport java.util.Comparator;\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Properties;\r\n\r\nimport org.scale7.cassandra.pelops.Cluster;\r\nimport org.scale7.cassandra.pelops.Cluster.Node;\r\nimport org.scale7.cassandra.pelops.IConnection;\r\nimport org.scale7.cassandra.pelops.Mutator;\r\nimport org.scale7.cassandra.pelops.Pelops;\r\nimport org.scale7.cassandra.pelops.RowDeletor;\r\nimport org.scale7.cassandra.pelops.Selector;\r\nimport org.scale7.cassandra.pelops.exceptions.TransportException;\r\nimport org.scale7.cassandra.pelops.pool.CommonsBackedPool;\r\nimport org.scale7.cassandra.pelops.pool.CommonsBackedPool.Policy;\r\nimport org.scale7.cassandra.pelops.pool.IThriftPool;\r\nimport org.scale7.cassandra.pelops.pool.IThriftPool.IPooledConnection;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.google.common.collect.Lists;\r\nimport com.impetus.client.cassandra.common.CassandraClientFactory;\r\nimport com.impetus.client.cassandra.common.CassandraUtilities;\r\nimport com.impetus.client.cassandra.config.CassandraPropertyReader;\r\nimport com.impetus.client.cassandra.query.CassandraEntityReader;\r\nimport com.impetus.client.cassandra.schemamanager.CassandraSchemaManager;\r\nimport com.impetus.client.cassandra.service.CassandraHost;\r\nimport com.impetus.client.cassandra.service.CassandraHostConfiguration;\r\nimport com.impetus.client.cassandra.service.CassandraRetryService;\r\nimport com.impetus.kundera.Constants;\r\nimport com.impetus.kundera.KunderaException;\r\nimport com.impetus.kundera.PersistenceProperties;\r\nimport com.impetus.kundera.client.Client;\r\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\r\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\r\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\r\nimport com.impetus.kundera.service.Host;\r\nimport com.impetus.kundera.service.HostConfiguration;\r\nimport com.impetus.kundera.service.policy.LeastActiveBalancingPolicy;\r\nimport com.impetus.kundera.service.policy.RoundRobinBalancingPolicy;\r\n\r\n/**\r\n * A factory for creating PelopsCliobjects.\r\n */\r\npublic class PelopsClientFactory extends CassandraClientFactory\r\n{\r\n    /** The logger. */\r\n    private static Logger logger = LoggerFactory.getLogger(PelopsClientFactory.class);\r\n\r\n    private HostConfiguration configuration;\r\n\r\n    @Override\r\n    public void initialize(Map<String, Object> externalProperty)\r\n    {\r\n        reader = new CassandraEntityReader(kunderaMetadata);\r\n        initializePropertyReader();\r\n        // setExternalProperties(externalProperty);\r\n        String loadBalancingPolicyName = CassandraPropertyReader.csmd != null ? CassandraPropertyReader.csmd\r\n                .getConnectionProperties().getProperty(Constants.LOADBALANCING_POLICY) : null;\r\n        initializeLoadBalancer(loadBalancingPolicyName);\r\n        configuration = new CassandraHostConfiguration(externalProperties, CassandraPropertyReader.csmd,\r\n                getPersistenceUnit(), kunderaMetadata);\r\n        hostRetryService = new CassandraRetryService(configuration, this);\r\n\r\n        // initialize timestamp generator.\r\n        initializeTimestampGenerator(externalProperty);\r\n    }\r\n\r\n    @Override\r\n    protected Object createPoolOrConnection()\r\n    {\r\n        logger.info(\"Creating pool\");\r\n        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()\r\n                .getPersistenceUnitMetadata(getPersistenceUnit());\r\n\r\n        Properties props = persistenceUnitMetadata.getProperties();\r\n        String keyspace = null;\r\n        if (externalProperties != null)\r\n        {\r\n            keyspace = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);\r\n        }\r\n        if (keyspace == null)\r\n        {\r\n            keyspace = (String) props.get(PersistenceProperties.KUNDERA_KEYSPACE);\r\n        }\r\n\r\n        for (Host host : ((CassandraHostConfiguration) configuration).getCassandraHosts())\r\n        {\r\n            CassandraHost cassandraHost = (CassandraHost) host;\r\n            String poolName = PelopsUtils.generatePoolName(cassandraHost.getHost(), cassandraHost.getPort(), keyspace);\r\n            if (CassandraUtilities.verifyConnection(cassandraHost.getHost(), cassandraHost.getPort()))\r\n            {\r\n                Cluster cluster = new Cluster(cassandraHost.getHost(), new IConnection.Config(cassandraHost.getPort(),\r\n                        true, -1, PelopsUtils.getAuthenticationRequest(cassandraHost.getUser(),\r\n                                cassandraHost.getPassword())), false);\r\n\r\n                if (logger.isInfoEnabled())\r\n                {\r\n                    logger.info(\"Initializing connection pool for keyspace {}, host {},port {}.\", keyspace,\r\n                            cassandraHost.getHost(), cassandraHost.getPort());\r\n                }\r\n\r\n                Policy policy = PelopsUtils.getPoolConfigPolicy(cassandraHost);\r\n\r\n                // Add pool with specified policy. null means default operand\r\n                // policy.\r\n                Pelops.addPool(poolName, cluster, keyspace, policy, null);\r\n                hostPools.put(cassandraHost, Pelops.getDbConnPool(poolName));\r\n            }\r\n            else\r\n            {\r\n                logger.warn(\"Node \" + host.getHost() + \" are down\");\r\n                if (host.isRetryHost())\r\n                {\r\n                    logger.info(\"Scheduling node for future retry\");\r\n                    ((CassandraRetryService) hostRetryService).add((CassandraHost) host);\r\n                }\r\n            }\r\n        }\r\n        // TODO return a thrift pool\r\n        return null;\r\n    }\r\n\r\n    @Override\r\n    protected Client instantiateClient(String persistenceUnit)\r\n    {\r\n        if (logger.isInfoEnabled())\r\n        {\r\n            // logger.info(\"Initializing pelops client for persistence unit {}\",\r\n            // persistenceUnit);\r\n        }\r\n        IThriftPool pool = getPoolUsingPolicy();\r\n        return new PelopsClient(indexManager, reader, this, persistenceUnit, externalProperties, pool, kunderaMetadata,\r\n                timestampGenerator);\r\n    }\r\n\r\n    @Override\r\n    public boolean isThreadSafe()\r\n    {\r\n        return false;\r\n    }\r\n\r\n    @Override\r\n    public void destroy()\r\n    {\r\n        if (indexManager != null)\r\n        {\r\n            indexManager.close();\r\n        }\r\n        if (schemaManager != null)\r\n        {\r\n            schemaManager.dropSchema();\r\n        }\r\n        schemaManager = null;\r\n        // Pelops.shutdown();\r\n        // Pelops.removePool(PelopsUtils.generatePoolName(getPersistenceUnit(),\r\n        // externalProperties));\r\n        externalProperties = null;\r\n    }\r\n\r\n    @Override\r\n    public SchemaManager getSchemaManager(Map<String, Object> externalProperty)\r\n    {\r\n        if (schemaManager == null)\r\n        {\r\n            initializePropertyReader();\r\n            setExternalProperties(externalProperty);\r\n            schemaManager = new CassandraSchemaManager(PelopsClientFactory.class.getName(), externalProperty,\r\n                    kunderaMetadata);\r\n        }\r\n\r\n        return schemaManager;\r\n    }\r\n\r\n    /**\r\n     * \r\n     */\r\n    private void initializePropertyReader()\r\n    {\r\n        if (propertyReader == null)\r\n        {\r\n            propertyReader = new CassandraPropertyReader(externalProperties, kunderaMetadata.getApplicationMetadata()\r\n                    .getPersistenceUnitMetadata(getPersistenceUnit()));\r\n            propertyReader.read(getPersistenceUnit());\r\n        }\r\n    }\r\n\r\n    @Override\r\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\r\n    {\r\n        switch (LoadBalancer.getValue(loadBalancingPolicyName))\r\n        {\r\n        case ROUNDROBIN:\r\n            loadBalancingPolicy = new RoundRobinBalancingPolicy();\r\n            break;\r\n        case LEASTACTIVE:\r\n            loadBalancingPolicy = new PelopsLeastActiveBalancingPolcy();\r\n            break;\r\n        default:\r\n            loadBalancingPolicy = new RoundRobinBalancingPolicy();\r\n            break;\r\n        }\r\n    }\r\n\r\n    /**\r\n     * \r\n     * @return pool an the basis of LoadBalancing policy.\r\n     */\r\n    private IThriftPool getPoolUsingPolicy()\r\n    {\r\n        if (!hostPools.isEmpty())\r\n        {\r\n            logger.info(\"Returning pool using {} .\", loadBalancingPolicy.getClass().getSimpleName());\r\n            return (IThriftPool) loadBalancingPolicy.getPool(hostPools.values());\r\n        }\r\n        throw new KunderaException(\"All hosts are down. please check servers manully.\");\r\n    }\r\n\r\n    IPooledConnection getConnection(IThriftPool pool)\r\n    {\r\n        IThriftPool iThriftPool = pool;\r\n        boolean success = false;\r\n        while (!success)\r\n        {\r\n            success = true;\r\n            if (iThriftPool != null)\r\n            {\r\n                Node[] nodes = ((CommonsBackedPool) iThriftPool).getCluster().getNodes();\r\n                String host = nodes[0].getAddress();\r\n                int thriftPort = ((CommonsBackedPool) iThriftPool).getCluster().getConnectionConfig().getThriftPort();\r\n                CassandraHost cassandraHost = ((CassandraHostConfiguration) configuration).getCassandraHost(\r\n                        nodes[0].getAddress(), ((CommonsBackedPool) pool).getCluster().getConnectionConfig()\r\n                                .getThriftPort());\r\n                if (cassandraHost.isTestOnBorrow())\r\n                {\r\n                    if (cassandraHost.isTestOnBorrow() && CassandraUtilities.verifyConnection(host, thriftPort))\r\n                    {\r\n                        // logger.info(\"Returning connection of {} :{} .\",\r\n                        // nodes[0].getAddress(), thriftPort);\r\n                        return iThriftPool.getConnection();\r\n                    }\r\n                    removePool(iThriftPool);\r\n                }\r\n                else\r\n                {\r\n                    // logger.info(\"Returning connection of {} :{} .\",\r\n                    // nodes[0].getAddress(), thriftPort);\r\n                    return iThriftPool.getConnection();\r\n                }\r\n                removePool(iThriftPool);\r\n            }\r\n            success = false;\r\n            iThriftPool = getPoolUsingPolicy();\r\n        }\r\n        throw new KunderaException(\"All hosts are down. please check servers manully.\");\r\n    }\r\n\r\n    Mutator getMutator(IThriftPool pool)\r\n    {\r\n        IThriftPool iThriftPool = pool;\r\n        boolean success = false;\r\n        while (!success)\r\n        {\r\n            success = true;\r\n            if (iThriftPool != null)\r\n            {\r\n                Node[] nodes = ((CommonsBackedPool) iThriftPool).getCluster().getNodes();\r\n                String host = nodes[0].getAddress();\r\n                int thriftPort = ((CommonsBackedPool) iThriftPool).getCluster().getConnectionConfig().getThriftPort();\r\n                CassandraHost cassandraHost = ((CassandraHostConfiguration) configuration).getCassandraHost(\r\n                        nodes[0].getAddress(), ((CommonsBackedPool) pool).getCluster().getConnectionConfig()\r\n                                .getThriftPort());\r\n                if (cassandraHost.isTestOnBorrow())\r\n                {\r\n                    if (cassandraHost.isTestOnBorrow() && CassandraUtilities.verifyConnection(host, thriftPort))\r\n                    {\r\n                        // logger.info(\"Returning mutator of {} :{} .\",\r\n                        // nodes[0].getAddress(), thriftPort);\r\n                        return Pelops.createMutator(PelopsUtils.getPoolName(iThriftPool));\r\n                    }\r\n                    removePool(iThriftPool);\r\n                }\r\n                else\r\n                {\r\n                    return iThriftPool.createMutator();\r\n                }\r\n            }\r\n            success = false;\r\n            iThriftPool = getPoolUsingPolicy();\r\n        }\r\n        throw new KunderaException(\"All hosts are down. please check servers manully.\");\r\n    }\r\n\r\n    Selector getSelector(IThriftPool pool)\r\n    {\r\n        IThriftPool iThriftPool = pool;\r\n        boolean success = false;\r\n        while (!success)\r\n        {\r\n            if (iThriftPool != null)\r\n            {\r\n                Node[] nodes = ((CommonsBackedPool) iThriftPool).getCluster().getNodes();\r\n                String host = nodes[0].getAddress();\r\n                int thriftPort = ((CommonsBackedPool) iThriftPool).getCluster().getConnectionConfig().getThriftPort();\r\n                CassandraHost cassandraHost = ((CassandraHostConfiguration) configuration).getCassandraHost(\r\n                        nodes[0].getAddress(), ((CommonsBackedPool) pool).getCluster().getConnectionConfig()\r\n                                .getThriftPort());\r\n                if (cassandraHost.isTestOnBorrow())\r\n                {\r\n                    if (cassandraHost.isTestOnBorrow() && CassandraUtilities.verifyConnection(host, thriftPort))\r\n                    {\r\n                        // logger.info(\"Returning selector of {} :{} .\",\r\n                        // nodes[0].getAddress(), thriftPort);\r\n                        return Pelops.createSelector(PelopsUtils.getPoolName(iThriftPool));\r\n                    }\r\n                    removePool(iThriftPool);\r\n                }\r\n                else\r\n                {\r\n                    // logger.info(\"Returning selector of {} :{} .\",\r\n                    // nodes[0].getAddress(), thriftPort);\r\n                    return Pelops.createSelector(PelopsUtils.getPoolName(iThriftPool));\r\n                }\r\n            }\r\n            success = false;\r\n            iThriftPool = getPoolUsingPolicy();\r\n        }\r\n        throw new KunderaException(\"All hosts are down. please check servers manully.\");\r\n    }\r\n\r\n    RowDeletor getRowDeletor(IThriftPool pool)\r\n    {\r\n        IThriftPool iThriftPool = pool;\r\n        boolean success = false;\r\n        while (!success)\r\n        {\r\n            if (iThriftPool != null)\r\n            {\r\n                Node[] nodes = ((CommonsBackedPool) iThriftPool).getCluster().getNodes();\r\n                String host = nodes[0].getAddress();\r\n                int thriftPort = ((CommonsBackedPool) iThriftPool).getCluster().getConnectionConfig().getThriftPort();\r\n                CassandraHost cassandraHost = ((CassandraHostConfiguration) configuration).getCassandraHost(\r\n                        nodes[0].getAddress(), ((CommonsBackedPool) pool).getCluster().getConnectionConfig()\r\n                                .getThriftPort());\r\n                if (cassandraHost.isTestOnBorrow())\r\n                {\r\n                    if (cassandraHost.isTestOnBorrow() && CassandraUtilities.verifyConnection(host, thriftPort))\r\n                    {\r\n                        logger.info(\"Returning row deletor of {} :{} .\", nodes[0].getAddress(), thriftPort);\r\n                        return Pelops.createRowDeletor(PelopsUtils.getPoolName(iThriftPool));\r\n                    }\r\n                    removePool(iThriftPool);\r\n                }\r\n                else\r\n                {\r\n                    logger.info(\"Returning row deletor of {} :{} .\", nodes[0].getAddress(), thriftPort);\r\n                    return Pelops.createRowDeletor(PelopsUtils.getPoolName(iThriftPool));\r\n                }\r\n            }\r\n            success = false;\r\n            iThriftPool = getPoolUsingPolicy();\r\n        }\r\n        throw new KunderaException(\"All hosts are down. please check servers manully.\");\r\n\r\n    }\r\n\r\n    void releaseConnection(IPooledConnection conn)\r\n    {\r\n        if (conn != null)\r\n        {\r\n            conn.release();\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Adds a pool in hostPools map for given host.\r\n     * \r\n     * @param cassandraHost\r\n     * @return true id added successfully.\r\n     */\r\n    public boolean addCassandraHost(CassandraHost cassandraHost)\r\n    {\r\n        Properties props = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata, getPersistenceUnit())\r\n                .getProperties();\r\n        String keyspace = null;\r\n        if (externalProperties != null)\r\n        {\r\n            keyspace = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);\r\n        }\r\n        if (keyspace == null)\r\n        {\r\n            keyspace = (String) props.get(PersistenceProperties.KUNDERA_KEYSPACE);\r\n        }\r\n        String poolName = PelopsUtils.generatePoolName(cassandraHost.getHost(), cassandraHost.getPort(), keyspace);\r\n        Cluster cluster = new Cluster(cassandraHost.getHost(), new IConnection.Config(cassandraHost.getPort(), true,\r\n                -1, PelopsUtils.getAuthenticationRequest(cassandraHost.getUser(), cassandraHost.getPassword())), false);\r\n        Policy policy = PelopsUtils.getPoolConfigPolicy(cassandraHost);\r\n        try\r\n        {\r\n            Pelops.addPool(poolName, cluster, keyspace, policy, null);\r\n            hostPools.put(cassandraHost, Pelops.getDbConnPool(poolName));\r\n            return true;\r\n        }\r\n        catch (TransportException e)\r\n        {\r\n            logger.warn(\"Node {} are still down \", cassandraHost.getHost());\r\n            return false;\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Removes downed host pool from pool map.\r\n     * \r\n     * @param pool\r\n     */\r\n    private void removePool(IThriftPool pool)\r\n    {\r\n        Pelops.removePool(PelopsUtils.getPoolName(pool));\r\n        Node[] nodes = ((CommonsBackedPool) pool).getCluster().getNodes();\r\n        logger.warn(\"{} :{}  host appears to be down, trying for next \", nodes, ((CommonsBackedPool) pool).getCluster()\r\n                .getConnectionConfig().getThriftPort());\r\n        CassandraHost cassandraHost = ((CassandraHostConfiguration) configuration).getCassandraHost(\r\n                nodes[0].getAddress(), ((CommonsBackedPool) pool).getCluster().getConnectionConfig().getThriftPort());\r\n        hostPools.remove(cassandraHost);\r\n    }\r\n\r\n    /**\r\n     * Extends LeastActiveBalancingPolicy class and provide own implementation\r\n     * in order to support least active balancing policy.\r\n     * \r\n     * @author Kuldeep.Mishra\r\n     * \r\n     */\r\n    private class PelopsLeastActiveBalancingPolcy extends LeastActiveBalancingPolicy\r\n    {\r\n\r\n        /**\r\n         * \r\n         * @return pool object for host which has least active connections\r\n         *         determined by maxActive connection.\r\n         * \r\n         */\r\n        public Object getPool(Collection<Object> pools)\r\n        {\r\n            List<Object> vals = Lists.newArrayList(pools);\r\n            Collections.shuffle(vals);\r\n            Collections.sort(vals, new ShufflingCompare());\r\n            Collections.reverse(vals);\r\n            Iterator<Object> iterator = vals.iterator();\r\n            Object concurrentConnectionPool = iterator.next();\r\n            return concurrentConnectionPool;\r\n        }\r\n\r\n        /**\r\n         * Compares two pool object on the basis of their maxActive connection\r\n         * per node.\r\n         * \r\n         * @author Kuldeep Mishra\r\n         * \r\n         */\r\n        private final class ShufflingCompare implements Comparator<Object>\r\n        {\r\n            public int compare(Object o1, Object o2)\r\n            {\r\n                Policy policy1 = ((CommonsBackedPool) ((IThriftPool) o1)).getPolicy();\r\n                Policy policy2 = ((CommonsBackedPool) ((IThriftPool) o2)).getPolicy();\r\n\r\n                int activeConnections1 = ((CommonsBackedPool) ((IThriftPool) o1)).getConnectionsActive();\r\n                int activeConnections2 = ((CommonsBackedPool) ((IThriftPool) o2)).getConnectionsActive();\r\n\r\n                return (policy1.getMaxActivePerNode() - activeConnections1)\r\n                        - (policy2.getMaxActivePerNode() - activeConnections2);\r\n            }\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/main/java/com/impetus/client/cassandra/pelops/PelopsDataHandler.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.pelops;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.cassandra.thrift.ColumnOrSuperColumn;\nimport org.apache.cassandra.thrift.ColumnParent;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.SuperColumn;\nimport org.scale7.cassandra.pelops.Selector;\n\nimport com.impetus.client.cassandra.datahandler.CassandraDataHandler;\nimport com.impetus.client.cassandra.datahandler.CassandraDataHandlerBase;\nimport com.impetus.client.cassandra.thrift.ThriftRow;\nimport com.impetus.kundera.db.DataRow;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.annotation.DefaultEntityAnnotationProcessor;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.TimestampGenerator;\n\n/**\n * Provides Pelops utility methods for data held in Column family based stores.\n * \n * @author amresh.singh\n */\nfinal class PelopsDataHandler extends CassandraDataHandlerBase implements CassandraDataHandler\n{\n\n    private final PelopsClient pelopsClient;\n\n    /**\n     * @param externalProperties\n     */\n    public PelopsDataHandler(final PelopsClient pelopsClient, final KunderaMetadata kunderaMetadata,\n            final TimestampGenerator generator)\n    {\n        super(pelopsClient, kunderaMetadata, generator);\n        this.pelopsClient = pelopsClient;\n    }\n\n    @Override\n    public Object fromThriftRow(Class<?> clazz, EntityMetadata m, Object rowKey, List<String> relationNames,\n            boolean isWrapReq, ConsistencyLevel consistencyLevel) throws Exception\n    {\n        Selector selector = pelopsClient.getSelector();\n\n        List<ByteBuffer> rowKeys = new ArrayList<ByteBuffer>(1);\n        rowKeys.add(ByteBuffer.wrap(PropertyAccessorHelper.toBytes(rowKey, m.getIdAttribute().getJavaType())));\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(m.getEntityClazz());\n\n        // For secondary tables.\n        List<String> secondaryTables = ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation())\n                .getSecondaryTablesName();\n        secondaryTables.add(m.getTableName());\n        Object e = null;\n\n        for (String tableName : secondaryTables)\n        {\n            Map<ByteBuffer, List<ColumnOrSuperColumn>> thriftColumnOrSuperColumns = selector\n                    .getColumnOrSuperColumnsFromRows(new ColumnParent(tableName), rowKeys,\n                            Selector.newColumnsPredicateAll(true, 10000), consistencyLevel);\n\n            for (ByteBuffer key : thriftColumnOrSuperColumns.keySet())\n            {\n                if (!thriftColumnOrSuperColumns.get(key).isEmpty())\n                {\n                    ThriftRow tr = new ThriftRow();\n                    tr.setId(rowKey);\n                    tr.setColumnFamilyName(tableName);\n\n                    tr = thriftTranslator.translateToThriftRow(thriftColumnOrSuperColumns, m.isCounterColumnType(),\n                            m.getType(), tr);\n\n                    e = populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relationNames, isWrapReq);\n                }\n            }\n        }\n\n        return e;\n    }\n\n    /** Translation Methods */\n\n    @Override\n    public List<Object> fromThriftRow(Class<?> clazz, EntityMetadata m, List<String> relationNames, boolean isWrapReq,\n            ConsistencyLevel consistencyLevel, Object... rowIds) throws Exception\n    {\n        return super.fromThriftRow(clazz, m, relationNames, isWrapReq, consistencyLevel, rowIds);\n    }\n\n    @Override\n    public <E> E fromThriftRow(Class<E> clazz, EntityMetadata m, DataRow<SuperColumn> tr) throws Exception\n    {\n        return super.fromThriftRow(clazz, m, tr);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/main/java/com/impetus/client/cassandra/pelops/PelopsIdGenerator.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.cassandra.pelops;\n\nimport javax.persistence.GenerationType;\n\nimport com.impetus.client.cassandra.CassandraIdGenerator;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.metadata.model.TableGeneratorDiscriptor;\n\n/**\n * The Class PelopsIdGenerator.\n * \n * @author: karthikp.manchala\n */\npublic class PelopsIdGenerator extends CassandraIdGenerator\n{\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.cassandra.CassandraIdGenerator#generate(com.impetus\n     * .kundera.metadata.model.TableGeneratorDiscriptor,\n     * com.impetus.kundera.client.ClientBase, java.lang.Object)\n     */\n    @Override\n    public Object generate(TableGeneratorDiscriptor discriptor, ClientBase client, String dataType)\n    {\n        throw new UnsupportedOperationException(GenerationType.class.getSimpleName()\n                + \".TABLE Strategy not supported by this client :\" + client.getClass().getName());\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/main/java/com/impetus/client/cassandra/pelops/PelopsInvertedIndexHandler.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.cassandra.pelops;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.IndexClause;\nimport org.apache.cassandra.thrift.SlicePredicate;\nimport org.apache.cassandra.thrift.SliceRange;\nimport org.apache.cassandra.thrift.SuperColumn;\nimport org.scale7.cassandra.pelops.Bytes;\nimport org.scale7.cassandra.pelops.Mutator;\nimport org.scale7.cassandra.pelops.Selector;\nimport org.scale7.cassandra.pelops.exceptions.NotFoundException;\nimport org.scale7.cassandra.pelops.exceptions.PelopsException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.cassandra.common.CassandraUtilities;\nimport com.impetus.client.cassandra.datahandler.CassandraDataHandler;\nimport com.impetus.client.cassandra.index.CassandraIndexHelper;\nimport com.impetus.client.cassandra.index.InvertedIndexHandler;\nimport com.impetus.client.cassandra.index.InvertedIndexHandlerBase;\nimport com.impetus.client.cassandra.thrift.ThriftRow;\nimport com.impetus.kundera.db.SearchResult;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.utils.TimestampGenerator;\n\n/**\n * Pelops implementation of {@link InvertedIndexHandler}\n * \n * @author amresh.singh\n */\npublic class PelopsInvertedIndexHandler extends InvertedIndexHandlerBase implements InvertedIndexHandler\n{\n    private static final Logger log = LoggerFactory.getLogger(PelopsInvertedIndexHandler.class);\n\n    private final PelopsClient pelopsClient;\n\n    /**\n     * @param externalProperties\n     */\n    public PelopsInvertedIndexHandler(final PelopsClient pelopsClient, final boolean useSecondryIndex, final TimestampGenerator generator)\n    {\n        super(generator);\n        this.pelopsClient = pelopsClient;\n        this.useSecondryIndex = useSecondryIndex;\n    }\n\n    @Override\n    public void write(Node node, EntityMetadata entityMetadata, String persistenceUnit,\n            ConsistencyLevel consistencyLevel, CassandraDataHandler cdHandler)\n    {\n        // Index in Inverted Index table if applicable\n        boolean invertedIndexingApplicable = CassandraIndexHelper.isInvertedIndexingApplicable(entityMetadata,\n                useSecondryIndex);\n\n        if (invertedIndexingApplicable)\n        {\n            String indexColumnFamily = CassandraIndexHelper.getInvertedIndexTableName(entityMetadata.getTableName());\n\n            Mutator mutator = pelopsClient.getMutator();\n\n            List<ThriftRow> indexThriftyRows = ((PelopsDataHandler) cdHandler).toIndexThriftRow(node.getData(),\n                    entityMetadata, indexColumnFamily);\n\n            for (ThriftRow thriftRow : indexThriftyRows)\n            {\n\n                List<Column> thriftColumns = thriftRow.getColumns();\n                List<SuperColumn> thriftSuperColumns = thriftRow.getSuperColumns();\n                if (thriftColumns != null && !thriftColumns.isEmpty())\n                {\n                    // Bytes.fromL\n                    mutator.writeColumns(thriftRow.getColumnFamilyName(), Bytes.fromByteBuffer(CassandraUtilities\n                            .toBytes(thriftRow.getId(), thriftRow.getId().getClass())), Arrays.asList(thriftRow\n                            .getColumns().toArray(new Column[0])));\n                }\n\n                if (thriftSuperColumns != null && !thriftSuperColumns.isEmpty())\n                {\n                    for (SuperColumn sc : thriftSuperColumns)\n                    {\n                        mutator.writeSubColumns(thriftRow.getColumnFamilyName(), Bytes\n                                .fromByteBuffer(CassandraUtilities.toBytes(thriftRow.getId(), thriftRow.getId()\n                                        .getClass())), Bytes.fromByteArray(sc.getName()), sc.getColumns());\n                    }\n                }\n            }\n            mutator.execute(consistencyLevel);\n            indexThriftyRows = null;\n        }\n    }\n\n    /**\n     * @param columnFamilyName\n     * @param m\n     * @param filterClauseQueue\n     * @return\n     */\n    @Override\n    public List<SearchResult> search(EntityMetadata m, String persistenceUnit, ConsistencyLevel consistencyLevel,\n            Map<Boolean, List<IndexClause>> indexClauseMap)\n    {\n        return super.search(m, persistenceUnit, consistencyLevel, indexClauseMap);\n    }\n\n    /**\n     * Searches <code>searchString</code> into <code>columnFamilyName</code>\n     * (usually a wide row column family) for a given <code>rowKey</code> from\n     * start to finish columns. Adds matching thrift columns into\n     * <code>thriftColumns</code>\n     * \n     * @param columnFamilyName\n     * @param consistencyLevel\n     * @param selector\n     * @param rowKey\n     * @param searchString\n     * @param thriftSuperColumns\n     */\n    @Override\n    public void searchSuperColumnsInRange(String columnFamilyName, ConsistencyLevel consistencyLevel,\n            String persistenceUnit, String rowKey, byte[] searchSuperColumnName, List<SuperColumn> thriftSuperColumns,\n            byte[] start, byte[] finish)\n    {\n        SlicePredicate colPredicate = new SlicePredicate();\n        SliceRange sliceRange = new SliceRange();\n        sliceRange.setStart(start);\n        sliceRange.setFinish(finish);\n        colPredicate.setSlice_range(sliceRange);\n\n        Selector selector = pelopsClient.getSelector();\n        List<SuperColumn> allThriftSuperColumns = selector.getSuperColumnsFromRow(columnFamilyName, rowKey,\n                colPredicate, consistencyLevel);\n\n        for (SuperColumn superColumn : allThriftSuperColumns)\n        {\n            if (superColumn == null)\n                continue;\n            if (superColumn.getName() == searchSuperColumnName)\n            {\n                thriftSuperColumns.add(superColumn);\n            }\n        }\n    }\n\n    /**\n     * Deletes records from inverted index table\n     * \n     * @param entity\n     * @param metadata\n     */\n\n    @Override\n    public void delete(Object entity, EntityMetadata metadata, ConsistencyLevel consistencyLevel,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super.delete(entity, metadata, consistencyLevel, kunderaMetadata);\n    }\n\n    @Override\n    public SuperColumn getSuperColumnForRow(ConsistencyLevel consistencyLevel, String columnFamilyName, String rowKey,\n            byte[] superColumnName, String persistenceUnit)\n    {\n        Selector selector = pelopsClient.getSelector();\n        SuperColumn thriftSuperColumn = null;\n        try\n        {\n            thriftSuperColumn = selector.getSuperColumnFromRow(columnFamilyName, rowKey,\n                    Bytes.fromByteArray(superColumnName), consistencyLevel);\n\n        }\n        catch (NotFoundException e)\n        {\n            log.warn(\"Error while fetching super column for Row {} , Caused by: .\", rowKey, e);\n            return null;\n        }\n        catch (PelopsException e)\n        {\n            log.warn(\"Error while fetching super column for Row {} , Caused by: .\", rowKey, e);\n            return null;\n        }\n        return thriftSuperColumn;\n    }\n\n    /**\n     * @param indexColumnFamily\n     * @param rowKey\n     * @param superColumnName\n     * @param mutator\n     */\n    public void deleteColumn(String indexColumnFamily, String rowKey, byte[] superColumnName, String persistenceUnit,\n            ConsistencyLevel consistencyLevel, byte[] columnName)\n    {\n        Mutator mutator = pelopsClient.getMutator();\n        mutator.deleteColumn(indexColumnFamily, rowKey, Bytes.fromByteArray(superColumnName));\n        mutator.execute(consistencyLevel);\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/main/java/com/impetus/client/cassandra/pelops/PelopsUtils.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.cassandra.pelops;\r\n\r\nimport org.scale7.cassandra.pelops.SimpleConnectionAuthenticator;\r\nimport org.scale7.cassandra.pelops.pool.CommonsBackedPool;\r\nimport org.scale7.cassandra.pelops.pool.CommonsBackedPool.Policy;\r\nimport org.scale7.cassandra.pelops.pool.IThriftPool;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\n/**\r\n * The Class PelopsUtils.\r\n */\r\npublic class PelopsUtils\r\n{\r\n\r\n    /** The logger. */\r\n    private static Logger logger = LoggerFactory.getLogger(PelopsUtils.class);\r\n\r\n    /**\r\n     * Generate pool name.\r\n     * \r\n     * @param persistenceUnit\r\n     *            the persistence unit\r\n     * @param puProperties\r\n     * @return the string\r\n     */\r\n    public static String generatePoolName(String node, int port, String keyspace)\r\n    {\r\n        return node + \":\" + port + \":\" + keyspace;\r\n    }\r\n\r\n/*    *//**\r\n     * Gets the pool config policy.\r\n     * \r\n     * @param persistenceUnitMetadata\r\n     *            the persistence unit metadata\r\n     * @param puProperties\r\n     * @return the pool config policy\r\n     */\r\n    public static Policy getPoolConfigPolicy(com.impetus.client.cassandra.service.CassandraHost cassandraHost)\r\n    {\r\n        Policy policy = new Policy();\r\n        if (cassandraHost.getMaxActive() > 0)\r\n        {\r\n            policy.setMaxActivePerNode(cassandraHost.getMaxActive());\r\n        }\r\n        if (cassandraHost.getMaxIdle() > 0)\r\n        {\r\n            policy.setMaxIdlePerNode(cassandraHost.getMaxIdle());\r\n        }\r\n        if (cassandraHost.getMinIdle() > 0)\r\n        {\r\n            policy.setMinIdlePerNode(cassandraHost.getMinIdle());\r\n        }\r\n        if (cassandraHost.getMaxTotal() > 0)\r\n        {\r\n            policy.setMaxTotal(cassandraHost.getMaxTotal());\r\n        }\r\n        return policy;\r\n    }\r\n\r\n\r\n    /**\r\n     * If userName and password provided, Method prepares for\r\n     * AuthenticationRequest.\r\n     * \r\n     * @param props\r\n     *            properties\r\n     * \r\n     * @return simple authenticator request. returns null if userName/password\r\n     *         are not provided.\r\n     * \r\n     */\r\n    public static SimpleConnectionAuthenticator getAuthenticationRequest(String userName, String password)\r\n    {\r\n        SimpleConnectionAuthenticator authenticator = null;\r\n        if (userName != null || password != null)\r\n        {\r\n            authenticator = new SimpleConnectionAuthenticator(userName, password);\r\n        }\r\n        return authenticator;\r\n    }\r\n\r\n\r\n    /**\r\n     * \r\n     * @param pool\r\n     * @return\r\n     */\r\n    public static String getPoolName(IThriftPool pool)\r\n    {\r\n        org.scale7.cassandra.pelops.Cluster.Node[] nodes = ((CommonsBackedPool) pool).getCluster().getNodes();\r\n        String poolName = PelopsUtils.generatePoolName(nodes[0].getAddress(), ((CommonsBackedPool) pool).getCluster()\r\n                .getConnectionConfig().getThriftPort(), ((CommonsBackedPool) pool).getKeyspace());\r\n        return poolName;\r\n    }\r\n\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/client/crud/EmbeddedEntity.java",
    "content": "package com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n@Embeddable\npublic class EmbeddedEntity\n{\n    @Column(name = \"EMAIL_ID\", table = \"SECONDARY_TABLE\")\n    private String emailId;\n\n    @Column(name = \"PHONE_NO\")\n    private long phoneNo;\n\n    public String getEmailId()\n    {\n        return emailId;\n    }\n\n    public void setEmailId(String emailId)\n    {\n        this.emailId = emailId;\n    }\n\n    public long getPhoneNo()\n    {\n        return phoneNo;\n    }\n\n    public void setPhoneNo(long phoneNo)\n    {\n        this.phoneNo = phoneNo;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/client/crud/SecondaryTableEntity.java",
    "content": "package com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.SecondaryTable;\nimport javax.persistence.Table;\n\n@Table(name = \"PRIMARY_TABLE\")\n@SecondaryTable(name = \"SECONDARY_TABLE\")\n@Entity\npublic class SecondaryTableEntity\n{\n    @Id\n    @Column(name = \"OBJECT_ID\")\n    private String objectId;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    @Column(name = \"AGE\", table = \"SECONDARY_TABLE\")\n    private int age;\n\n    @Embedded\n    private EmbeddedEntity embeddedEntity;\n\n    public String getObjectId()\n    {\n        return objectId;\n    }\n\n    public void setObjectId(String objectId)\n    {\n        this.objectId = objectId;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public EmbeddedEntity getEmbeddedEntity()\n    {\n        return embeddedEntity;\n    }\n\n    public void setEmbeddedEntity(EmbeddedEntity embeddedEntity)\n    {\n        this.embeddedEntity = embeddedEntity;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/kundera/client/cassandra/pelops/crud/CassandraAuthenticationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.pelops.crud;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.auth.PasswordAuthenticator;\nimport org.apache.cassandra.thrift.AuthenticationException;\nimport org.apache.cassandra.thrift.AuthenticationRequest;\nimport org.apache.cassandra.thrift.AuthorizationException;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n/**\n * Cassandra authentication test.\n * \n * @author vivek.mishra\n */\npublic class CassandraAuthenticationTest /*extends BaseTest*/\n{\n\n    private String userName;\n\n    private String password;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        // userName = \"kunderauser\";\n        // password = \"kunderapassword\";\n        // System.setProperty(\"passwd.properties\",\n        // \"../resources/passwd.properties\");\n        // System.setProperty(\"access.properties\",\n        // \"../resources/access.properties\");\n        //\n        // CassandraCli.cassandraSetUp();\n    }\n\n    @Test\n    public void testDummy()\n    {\n        // do nothing.\n        // please do not modify this test at all!\n    }\n\n    /**\n     * Authenticate with valid credentials.\n     */\n    // @Test\n    public void authenticateWithValidCredentials()\n    {\n        try\n        {\n            EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"authenticationTest\");\n            Assert.assertNotNull(emf);\n            loadData();\n            EntityManager em = emf.createEntityManager();\n            Assert.assertNotNull(em);\n            PersonAuth o = new PersonAuth();\n            o.setPersonId(\"1\");\n            o.setPersonName(\"vivek\");\n            o.setAge(10);\n            em.persist(o);\n\n            PersonAuth p = em.find(PersonAuth.class, \"1\");\n            Assert.assertNotNull(p);\n\n        }\n        catch (Exception e)\n        {\n            Assert.fail(e.getMessage());\n        }\n\n    }\n\n    /**\n     * Authenticate with invalid credentials.\n     * \n     * @throws SchemaDisagreementException\n     * @throws TimedOutException\n     * @throws UnavailableException\n     * @throws InvalidRequestException\n     * @throws TException\n     * @throws IOException\n     */\n    // @Test\n    public void authenticateWithInValidCredentials() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        EntityManagerFactory emf = null;\n        EntityManager em = null;\n        try\n        {\n            userName = \"kunderauser\";\n            password = \"invalid\";\n            loadData();\n            emf = Persistence.createEntityManagerFactory(\"invalidauthenticationTest\");\n            em = emf.createEntityManager();\n            Assert.fail(\"Shouldn't be called\");\n        }\n        catch (AuthenticationException e)\n        {\n            Assert.assertNull(emf);\n            Assert.assertNull(em);\n            userName = \"kunderauser\";\n            password = \"kunderapassword\";\n        }\n        catch (AuthorizationException e)\n        {\n            Assert.assertNull(emf);\n            Assert.assertNull(em);\n            userName = \"kunderauser\";\n            password = \"kunderapassword\";\n        }\n\n    }\n\n    /**\n     * No authentication test.\n     * \n     */\n    // @Test\n    public void noAuthenticationTest()\n    {\n        try\n        {\n            EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"cass_pu\");\n            Assert.assertNotNull(emf);\n            EntityManager em = emf.createEntityManager();\n            Assert.assertNotNull(em);\n        }\n        catch (Exception e)\n        {\n            Assert.fail(e.getMessage());\n        }\n\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     * @throws AuthorizationException\n     * @throws AuthenticationException\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException, AuthenticationException, AuthorizationException\n    {\n\n        KsDef ksDef = null;\n        CfDef user_Def = new CfDef();\n        user_Def.name = \"PERSON\";\n        user_Def.keyspace = \"KunderaAuthentication\";\n        user_Def.setComparator_type(\"UTF8Type\");\n        user_Def.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"PERSON_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef);\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"AGE\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef1);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def);\n\n        try\n        {\n            PasswordAuthenticator idAuth = new PasswordAuthenticator();\n            Map<String, String> credentials = new HashMap<String, String>();\n            credentials.put(idAuth.USERNAME_KEY, userName);\n            credentials.put(idAuth.PASSWORD_KEY, password);\n            CassandraCli.client.login(new AuthenticationRequest(credentials));\n\n            CassandraCli.createKeySpace(\"KunderaAuthentication\");\n\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaAuthentication\");\n            CassandraCli.client.set_keyspace(\"KunderaAuthentication\");\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"PERSON\"))\n                {\n\n                    CassandraCli.client.system_drop_column_family(\"PERSON\");\n\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def);\n\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(\"KunderaAuthentication\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            ksDef.setReplication_factor(1);\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n\n        CassandraCli.client.set_keyspace(\"KunderaAuthentication\");\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws TException\n     * @throws AuthorizationException\n     * @throws AuthenticationException\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws AuthenticationException, AuthorizationException, TException\n    {\n        // Map<String, String> credentials = new HashMap<String, String>();\n        // credentials.put(IAuthenticator.USERNAME_KEY, userName);\n        // credentials.put(IAuthenticator.PASSWORD_KEY, password);\n        // CassandraCli.client.login(new AuthenticationRequest(credentials));\n        //\n        // CassandraCli.dropKeySpace(\"KunderaAuthentication\");\n    }\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/kundera/client/cassandra/pelops/crud/CassandraPelopsSecondaryTableTest.java",
    "content": "package com.impetus.kundera.client.cassandra.pelops.crud;\n\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.SecondaryTableTestBase;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\npublic class CassandraPelopsSecondaryTableTest extends SecondaryTableTestBase\n{\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"UUIDCassandra\");\n        loadData();\n        emf = Persistence.createEntityManagerFactory(\"cass_pu\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        CassandraCli.dropKeySpace(\"UUIDCassandra\");\n    }\n\n    @Test\n    public void test()\n    {\n        testCRUD(emf);\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n        String table1 = \"PRIMARY_TABLE\";\n        String table2 = \"SECONDARY_TABLE\";\n        String keyspace = \"UUIDCassandra\";\n        KsDef ksDef = null;\n        CfDef user_Def1 = new CfDef();\n        user_Def1.name = table1;\n        user_Def1.keyspace = keyspace;\n        user_Def1.column_type = \"Super\";\n        \n        CfDef user_Def2 = new CfDef();\n        user_Def2.name = table2;\n        user_Def2.keyspace = keyspace;\n        user_Def2.column_type = \"Super\";\n \n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def1);\n        cfDefs.add(user_Def2);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(keyspace);\n            CassandraCli.client.set_keyspace(keyspace);\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(table1))\n                {\n                    CassandraCli.client.system_drop_column_family(table1);\n                }\n                if (cfDef1.getName().equalsIgnoreCase(table2))\n                {\n                    CassandraCli.client.system_drop_column_family(table2);\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def1);\n            CassandraCli.client.system_add_column_family(user_Def2);\n\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/kundera/client/cassandra/pelops/crud/CassandraUUIDEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.pelops.crud;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"uuidsample\", schema = \"UUIDCassandra@cass_pu\")\npublic class CassandraUUIDEntity\n{\n    @Id\n    @Column(name = \"uuidKey\")\n    private UUID uuidKey;\n\n    @Column(name = \"name\")\n    private String name;\n\n    @Column(name = \"age\")\n    private Integer age;\n\n    /**\n     * Default constructor.\n     */\n    public CassandraUUIDEntity()\n    {\n\n    }\n\n    /**\n     * @return the uuidKey\n     */\n    public UUID getUuidKey()\n    {\n        return uuidKey;\n    }\n\n    /**\n     * @param uuidKey\n     *            the uuidKey to set\n     */\n    public void setUuidKey(UUID uuidKey)\n    {\n        this.uuidKey = uuidKey;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(Integer age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/kundera/client/cassandra/pelops/crud/EntityManagerFactoryImplTest.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.client.cassandra.pelops.crud;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class EntityManagerFactoryImplTest\n{\n\n    /**\n     * \n     */\n    private static final String _KEYSPACE2 = \"KunderaExamples\";\n\n    /**\n     * \n     */\n    private static final String _KEYSPACE1 = \"UUIDCassandra\";\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        \n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(_KEYSPACE1);\n        CassandraCli.createKeySpace(_KEYSPACE2);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        CassandraCli.dropKeySpace(_KEYSPACE1);\n        CassandraCli.dropKeySpace(_KEYSPACE2);\n    }\n\n    @Test\n    public void test()\n    {\n        String _PU1 = \"cass_pu\";\n        String _PU2 = \"secIdxCassandraTest\";\n        EntityManagerFactory emf1 = Persistence.createEntityManagerFactory(_PU1);\n        checkEMFPropertiesAfterCreating(_PU1, emf1);\n        emf1.close();\n        checkEMFPropertyAfterClosing(_PU1, emf1);\n\n        EntityManagerFactory emf2 = Persistence.createEntityManagerFactory(_PU2);\n        checkEMFPropertiesAfterCreating(_PU2, emf2);\n        emf2.close();\n        checkEMFPropertyAfterClosing(_PU2, emf2);\n\n        emf1 = Persistence.createEntityManagerFactory(_PU1);\n        checkEMFPropertiesAfterCreating(_PU1, emf1);\n\n        emf2 = Persistence.createEntityManagerFactory(_PU2);\n        checkEMFPropertiesAfterCreating(_PU2, emf2);\n\n        emf1.close();\n        checkEMFPropertyAfterClosing(_PU1, emf1);\n\n        checkEMFPropertiesAfterCreating(_PU2, emf2);\n\n        emf2.close();\n        checkEMFPropertyAfterClosing(_PU2, emf2);\n\n        // On concurrent testing\n\n        // create first emf\n        OnConcurrentEMF c1 = new OnConcurrentEMF(_PU1, \"emf1\");\n        try\n        {\n            c1.t.join();\n        }\n        catch (InterruptedException e)\n        {\n            \n        }\n        Assert.assertEquals(\"emf1\", c1.t.getName());\n        checkEMFPropertiesAfterCreating(_PU1, c1.emf);\n\n        // create second emf\n        OnConcurrentEMF c2 = new OnConcurrentEMF(_PU2, \"emf2\");\n        try\n        {\n            c2.t.join();\n        }\n        catch (InterruptedException e)\n        {\n            \n        }\n        Assert.assertEquals(\"emf2\", c2.t.getName());\n        checkEMFPropertiesAfterCreating(_PU2, c2.emf);\n\n        // close first emf\n        c1.close();\n        checkEMFPropertyAfterClosing(_PU1, c1.emf);\n\n        // close second emf\n        c2.close();\n        checkEMFPropertyAfterClosing(_PU2, c2.emf);\n\n    }\n\n    /**\n     * @param _PU1\n     */\n    private void checkEMFPropertyAfterClosing(String _PU1, EntityManagerFactory emf)\n    {\n        Assert.assertFalse(emf.isOpen());\n        KunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance();\n        Assert.assertNotNull(kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(_PU1));\n        Assert.assertNotNull(kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadataMap().get(_PU1));\n//        Assert.assertNull(kunderaMetadata.getClientMetadata(_PU1));\n        Assert.assertNotNull(kunderaMetadata.getApplicationMetadata().getMetamodelMap().get(_PU1));\n        Assert.assertNotNull(kunderaMetadata.getApplicationMetadata().getMetamodel(_PU1));\n        Assert.assertNotNull(kunderaMetadata.getApplicationMetadata().getMetaModelBuilder(_PU1));\n//        Assert.assertNotNull(kunderaMetadata.getApplicationMetadata().getSchemaMetadata().getPuToSchemaMetadata()\n//                .get(_PU1));\n    }\n\n    /**\n     * @param pu\n     */\n    private void checkEMFPropertiesAfterCreating(String pu, EntityManagerFactory emf)\n    {\n        Assert.assertTrue(emf.isOpen());\n        EntityManager em = emf.createEntityManager();\n        Assert.assertNotNull(em);\n        KunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance();\n        Assert.assertNotNull(kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(pu));\n        Assert.assertFalse(kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadataMap().isEmpty());\n        Assert.assertNotNull(kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadataMap().get(pu));\n//        Assert.assertNotNull(kunderaMetadata.getClientMetadata(pu));\n        Assert.assertFalse(kunderaMetadata.getApplicationMetadata().getMetamodelMap().isEmpty());\n        Assert.assertNotNull(kunderaMetadata.getApplicationMetadata().getMetamodelMap().get(pu));\n        Assert.assertNotNull(kunderaMetadata.getApplicationMetadata().getMetamodel(pu));\n        Assert.assertNotNull(kunderaMetadata.getApplicationMetadata().getMetaModelBuilder(pu));\n        // TODO: Devise better way.\n//        Assert.assertNotNull(kunderaMetadata.getApplicationMetadata().getSchemaMetadata()\n//                .getPuToSchemaMetadata().get(pu));\n//        Assert.assertNull(kunderaMetadata.getClientMetadata(pu).getLuceneIndexDir());\n    }\n\n    private class OnConcurrentEMF implements Runnable\n    {\n        public Thread t;\n\n        private String _PU;\n\n        public EntityManagerFactory emf;\n\n        /**\n         * @param pu\n         * @param name\n         * \n         */\n\n        public OnConcurrentEMF(String pu, String name)\n        {\n            this._PU = pu;\n            t = new Thread(this);\n            t.setName(name);\n            t.start();\n        }\n\n        @Override\n        public void run()\n        {\n            emf = Persistence.createEntityManagerFactory(_PU);\n            checkEMFPropertiesAfterCreating(_PU, emf);\n\n        }\n\n        public void close()\n        {\n            emf.close();\n            checkEMFPropertyAfterClosing(_PU, emf);\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/kundera/client/cassandra/pelops/crud/FacebookProfile.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.cassandra.pelops.crud;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.DiscriminatorValue;\r\nimport javax.persistence.Entity;\r\n\r\n/**\r\n * Facebook profile entity\r\n * @author vivek.mishra\r\n *\r\n */\r\n@Entity\r\n@DiscriminatorValue(\"fb\")\r\npublic class FacebookProfile extends SocialProfile\r\n{\r\n    // protected static final String TYPE = \"twitter\";\r\n\r\n    // @Id\r\n    // // @GeneratedValue\r\n    // @Column(name = \"guid\", updatable = false, nullable = false)\r\n    // private String id;\r\n\r\n    @Column(name = \"facebook_id\", updatable = false)\r\n    private String facebookId;\r\n\r\n    @Column(name = \"facebook_user\", length = 128)\r\n    private String facebookUser;\r\n\r\n    public String getFacebookId()\r\n    {\r\n        return facebookId;\r\n    }\r\n\r\n    public void setFacebookId(String facebookId)\r\n    {\r\n        this.facebookId = facebookId;\r\n    }\r\n\r\n    public String getFacebookUser()\r\n    {\r\n        return facebookUser;\r\n    }\r\n\r\n    public void setFacebookUser(String facebookUser)\r\n    {\r\n        this.facebookUser = facebookUser;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/kundera/client/cassandra/pelops/crud/GuidDomainObject.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.cassandra.pelops.crud;\r\n\r\nimport javax.persistence.Id;\r\nimport javax.persistence.MappedSuperclass;\r\n\r\n\r\n\r\n/**\r\n * Abstract mapped super class.\r\n * @author vivek.mishra\r\n *\r\n */\r\n@MappedSuperclass\r\nabstract public class GuidDomainObject \r\n{\r\n    @Id\r\n    private Long id;\r\n\r\n    public Long getId()\r\n    {\r\n        return id;\r\n    }\r\n\r\n    public void setId(Long id)\r\n    {\r\n        this.id = id;\r\n    }\r\n\r\n    \r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/kundera/client/cassandra/pelops/crud/InheritenceDomainTest.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.cassandra.pelops.crud;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Persistence;\r\nimport javax.persistence.Query;\r\n\r\nimport junit.framework.Assert;\r\n\r\nimport org.junit.After;\r\nimport org.junit.BeforeClass;\r\nimport org.junit.Test;\r\n\r\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\r\n\r\n/**\r\n * Junit for abstract entity class's operation.\r\n * \r\n * @author vivek.mishra\r\n * \r\n */\r\npublic class InheritenceDomainTest\r\n{\r\n\r\n    protected static String _PU = \"twissandraTest\";\r\n\r\n    @BeforeClass\r\n    public static void setUpBeforeClass() throws Exception\r\n    {\r\n\r\n        CassandraCli.cassandraSetUp();\r\n        CassandraCli.createKeySpace(\"UUIDCassandra\");\r\n    }\r\n\r\n//    @Test\r\n    public void testRelationViaPelops() throws Exception\r\n    {\r\n        try\r\n        {\r\n            EntityManagerFactory emfPelops = Persistence.createEntityManagerFactory(\"cass_pu\");\r\n            EntityManager emPelops = emfPelops.createEntityManager();\r\n\r\n            assertRelation(emPelops);\r\n            emPelops.clear();\r\n            emPelops.close();\r\n            emfPelops.close();\r\n        }\r\n        catch (Exception e)\r\n        {\r\n            Assert.fail(e.getMessage());\r\n        }\r\n\r\n    }\r\n\r\n    @Test\r\n    public void testAbstractEntityViaPelops()\r\n    {\r\n\r\n        try\r\n        {\r\n            EntityManagerFactory emfPelops = Persistence.createEntityManagerFactory(\"cass_pu\");\r\n            EntityManager emPelops = emfPelops.createEntityManager();\r\n\r\n            assertAbstractEntity(emPelops);\r\n            emPelops.clear();\r\n            emPelops.close();\r\n            emfPelops.close();\r\n        }\r\n        catch (Exception e)\r\n        {\r\n            Assert.fail(e.getMessage());\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Tear down.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    @After\r\n    public void tearDown() throws Exception\r\n    {\r\n        CassandraCli.truncateColumnFamily(\"UUIDCassandra\", \"user_account\", \"social_profile\");\r\n    }\r\n\r\n    private void assertRelation(EntityManager em)\r\n    {\r\n        List<SocialProfile> profiles = new ArrayList<SocialProfile>();\r\n\r\n        FacebookProfile fbprofile = new FacebookProfile();\r\n        fbprofile.setId(103l);\r\n        fbprofile.setFacebookId(\"fb1\");\r\n        fbprofile.setFacebookUser(\"facebook\");\r\n        fbprofile.setuserType(\"dumbo\");\r\n\r\n        profiles.add(fbprofile);\r\n\r\n        TwitterProfile twprofile1 = new TwitterProfile();\r\n        twprofile1.setTwitterId(\"2\");\r\n        twprofile1.setTwitterName(\"test2\");\r\n        twprofile1.setId(102l);\r\n        profiles.add(twprofile1);\r\n        twprofile1.setuserType(\"dumbo\");\r\n\r\n        UserAccount uacc = new UserAccount();\r\n\r\n        uacc.setId(101l);\r\n        uacc.setDispName(\"Test\");\r\n        uacc.setSocialProfiles(profiles);\r\n\r\n        twprofile1.setuserAccount(uacc);\r\n        fbprofile.setuserAccount(uacc);\r\n\r\n        em.getTransaction().begin();\r\n        em.persist(uacc);\r\n        em.getTransaction().commit();\r\n\r\n        // TODO: Stack over flow error.\r\n\r\n        // Uncomment this to test\r\n        // https://github.com/impetus-opensource/Kundera/issues/460\r\n        uacc.setDispName(\"UpdatedTest\");\r\n        em.persist(fbprofile);\r\n\r\n        em.persist(twprofile1);\r\n        em.clear();\r\n\r\n        String uaQuery = \"Select ua from UserAccount ua\";\r\n\r\n        Query q = em.createQuery(uaQuery);\r\n        List<UserAccount> results = q.getResultList();\r\n\r\n        Assert.assertEquals(1, results.size());\r\n        Assert.assertEquals(\"UpdatedTest\", results.get(0).getDispName());\r\n        Assert.assertEquals(2, results.get(0).getSocialProfiles().size());\r\n        Assert.assertFalse(results.get(0).getSocialProfiles().get(0).getId().equals(results.get(0).getId()));\r\n\r\n        em.clear();\r\n    }\r\n\r\n    private void assertAbstractEntity(EntityManager em)\r\n    {\r\n        FacebookProfile fbprofile = new FacebookProfile();\r\n        fbprofile.setId(Long.MIN_VALUE);\r\n        fbprofile.setFacebookId(\"fb1\");\r\n        fbprofile.setFacebookUser(\"facebook\");\r\n        fbprofile.setuserType(\"dumbo\");\r\n\r\n        em.persist(fbprofile);\r\n\r\n        TwitterProfile twprofile = new TwitterProfile();\r\n        twprofile.setTwitterId(\"2\");\r\n        twprofile.setTwitterName(\"test2\");\r\n        twprofile.setId(Long.MAX_VALUE);\r\n        twprofile.setuserType(\"dumbo\");\r\n\r\n        em.persist(twprofile);\r\n\r\n        SocialProfile facebookProfile = em.find(SocialProfile.class, Long.MIN_VALUE);\r\n        Assert.assertNotNull(facebookProfile);\r\n        Assert.assertTrue(facebookProfile.getClass().isAssignableFrom(FacebookProfile.class));\r\n\r\n        SocialProfile twitterProfile = em.find(SocialProfile.class, Long.MAX_VALUE);\r\n        Assert.assertNotNull(twitterProfile);\r\n        Assert.assertTrue(twitterProfile.getClass().isAssignableFrom(TwitterProfile.class));\r\n\r\n        String queryStr = \"Select s from SocialProfile s\";\r\n\r\n        Query query = em.createQuery(queryStr);\r\n\r\n        List<SocialProfile> socialProfiles = query.getResultList();\r\n\r\n        Assert.assertFalse(socialProfiles.isEmpty());\r\n        Assert.assertEquals(2, socialProfiles.size());\r\n        Assert.assertFalse(socialProfiles.get(0).getClass().getSimpleName()\r\n                .equals(socialProfiles.get(1).getClass().getSimpleName()));\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/kundera/client/cassandra/pelops/crud/PersonAuth.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.cassandra.pelops.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaAuthentication@authenticationTest\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\npublic class PersonAuth\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"AGEss\")\n    private byte[] a;\n\n    /**\n     * @return the a\n     */\n    public byte[] getA()\n    {\n        return a;\n    }\n\n    /**\n     * @param a\n     *            the a to set\n     */\n    public void setA(byte[] a)\n    {\n        this.a = a;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/kundera/client/cassandra/pelops/crud/SocialProfile.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.cassandra.pelops.crud;\n\nimport java.io.Serializable;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorColumn;\nimport javax.persistence.DiscriminatorType;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * Abstract entity class.\n * @author vivek.mishra\n *\n */\n@Entity\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@Table(name = \"social_profile\")\n@DiscriminatorColumn(name = \"type\", length = 64, discriminatorType = DiscriminatorType.STRING)\npublic abstract class SocialProfile extends GuidDomainObject implements Serializable\n{\n    @Column(name = \"userType\")\n    private String userType;\n\n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"user_account_id\")\n    private UserAccount account;\n    \n    public String getuserType()\n    {\n        return userType;\n    }\n\n    public void setuserType(String userType)\n    {\n        this.userType = userType;\n    }\n    \n    public UserAccount getuserAccount()\n    {\n        return account;\n    }\n\n    public void setuserAccount(UserAccount account)\n    {\n        this.account = account;\n    }\n\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/kundera/client/cassandra/pelops/crud/TestCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.client.cassandra.pelops.crud;\r\n\r\nimport java.nio.ByteBuffer;\r\nimport java.util.UUID;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Persistence;\r\n\r\nimport junit.framework.Assert;\r\n\r\nimport org.apache.cassandra.thrift.Cassandra;\r\nimport org.apache.cassandra.thrift.CfDef;\r\nimport org.apache.cassandra.thrift.ColumnDef;\r\nimport org.apache.cassandra.thrift.IndexType;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\nimport org.junit.After;\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\n\r\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\r\n\r\n/**\r\n * Test case for CRUD operations on Cassandra database using Kundera.\r\n */\r\npublic class TestCassandra\r\n{\r\n    /** The logger. */\r\n    private static Logger logger = LoggerFactory.getLogger(TestCassandra.class);\r\n\r\n    /**\r\n     * Sets the up.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    @Before\r\n    public void setUp() throws Exception\r\n    {\r\n        logger.info(\"starting server\");\r\n        CassandraCli.cassandraSetUp();\r\n        CassandraCli.createKeySpace(\"UUIDCassandra\");\r\n        Cassandra.Client client = CassandraCli.getClient();\r\n        client.set_keyspace(\"UUIDCassandra\");\r\n        CfDef cf_def = new CfDef();\r\n        cf_def.keyspace = \"UUIDCassandra\";\r\n        cf_def.name = \"uuidsample\";\r\n        cf_def.setKey_validation_class(\"UUIDType\");\r\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"name\".getBytes()), \"UTF8Type\");\r\n        columnDef2.index_type = IndexType.KEYS;\r\n        cf_def.addToColumn_metadata(columnDef2);\r\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"age\".getBytes()), \"Int32Type\");\r\n        columnDef3.index_type = IndexType.KEYS;\r\n        cf_def.addToColumn_metadata(columnDef3);\r\n        try\r\n        {\r\n            client.system_add_column_family(cf_def);\r\n        }\r\n        catch (Exception e)\r\n        {\r\n            // Do noyhing\r\n        }\r\n    }\r\n\r\n    @Test\r\n    public void testUUID()\r\n    {\r\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"cass_pu\");\r\n        UUID key = UUID.randomUUID();\r\n        CassandraUUIDEntity entity = new CassandraUUIDEntity();\r\n        entity.setAge(10);\r\n        entity.setName(\"vivek\");\r\n        entity.setUuidKey(key);\r\n\r\n        EntityManager em = emf.createEntityManager();\r\n        em.persist(entity);\r\n        CassandraUUIDEntity result = em.find(CassandraUUIDEntity.class, key);\r\n        Assert.assertNotNull(result);\r\n        Assert.assertEquals(key, result.getUuidKey());\r\n        Assert.assertEquals(\"vivek\", result.getName());\r\n        Assert.assertEquals(new Integer(10), result.getAge());\r\n    }\r\n\r\n    /**\r\n     * Tear down.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    @After\r\n    public void tearDown() throws Exception\r\n    {\r\n        logger.info(\"destroying\");\r\n        CassandraCli.dropKeySpace(\"UUIDCassandra\");\r\n    }\r\n}"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/kundera/client/cassandra/pelops/crud/TwitterProfile.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.cassandra.pelops.crud;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.DiscriminatorValue;\r\nimport javax.persistence.Entity;\r\n\r\n/**\r\n * Twitter profile entity.\r\n * @author vivek.mishra\r\n *\r\n */\r\n@Entity\r\n@DiscriminatorValue(\"twitter\")\r\npublic class TwitterProfile extends SocialProfile\r\n{\r\n\r\n    @Column(name = \"twitter_id\", updatable = false)\r\n    private String twitterId;\r\n\r\n    @Column(name = \"twitter_user\", length = 128)\r\n    private String twitterUser;\r\n    \r\n    public String getTwitterId()\r\n    {\r\n        return twitterId;\r\n    }\r\n\r\n    public void setTwitterId(String twitterId)\r\n    {\r\n        this.twitterId = twitterId;\r\n    }\r\n    \r\n    public String getTwitterName()\r\n    {\r\n        return twitterUser;\r\n    }\r\n\r\n    public void setTwitterName(String twitterUser)\r\n    {\r\n        this.twitterUser = twitterUser;\r\n    }\r\n\r\n\r\n}  \r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/kundera/client/cassandra/pelops/crud/UserAccount.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.cassandra.pelops.crud;\r\n\r\n\r\nimport java.util.List;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.Table;\r\n\r\n\r\n/**\r\n * User account entity.\r\n * @author vivek.mishra\r\n *\r\n */\r\n@Entity\r\n@Table(name = \"user_account\")\r\npublic class UserAccount extends GuidDomainObject\r\n{\r\n   \r\n    @Column(name = \"display_name\", length = 128)\r\n    private String displayName = null;\r\n\r\n    @Column(name = \"email\", length = 128, unique = true)\r\n    private String email = null;\r\n\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER,mappedBy = \"account\")\r\n    private List<SocialProfile> profiles;\r\n    \r\n    public String getDispName()\r\n    {\r\n        return displayName;\r\n    }\r\n\r\n    public void setDispName(String displayName)\r\n    {\r\n        this.displayName = displayName;\r\n    }\r\n    \r\n    public String getEmail()\r\n    {\r\n        return email;\r\n    }\r\n\r\n    public void setEmail(String email)\r\n    {\r\n        this.email = email;\r\n    }\r\n    \r\n    public List<SocialProfile> getSocialProfiles()\r\n    {\r\n        return profiles;\r\n    }\r\n\r\n    public void setSocialProfiles(List<SocialProfile> profiles)\r\n    {\r\n        this.profiles = profiles;\r\n    }\r\n} \r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/java/com/impetus/kundera/query/KunderaQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.query;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Parameter;\nimport javax.persistence.Persistence;\nimport javax.persistence.PersistenceException;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.pelops.crud.CassandraUUIDEntity;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * @author kuldeep.mishra\n * \n */\npublic class KunderaQueryTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"UUIDCassandra\");\n        emf = Persistence.createEntityManagerFactory(\"cass_pu\");\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void test()\n    {\n        String query = \"Select p from CassandraUUIDEntity p\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query,\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        Assert.assertNotNull(kunderaQuery.getEntityClass());\n        Assert.assertEquals(CassandraUUIDEntity.class, kunderaQuery.getEntityClass());\n        Assert.assertNotNull(kunderaQuery.getEntityMetadata());\n        Assert.assertTrue(KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), CassandraUUIDEntity.class).equals(\n                kunderaQuery.getEntityMetadata()));\n        Assert.assertNull(kunderaQuery.getFilter());\n        Assert.assertTrue(kunderaQuery.getFilterClauseQueue().isEmpty());\n        Assert.assertNotNull(kunderaQuery.getFrom());\n        Assert.assertTrue(kunderaQuery.getUpdateClauseQueue().isEmpty());\n        Assert.assertNotNull(kunderaQuery.getResult());\n        Assert.assertEquals(\"cass_pu\", kunderaQuery.getPersistenceUnit());\n        Assert.assertNull(kunderaQuery.getOrdering());\n        try\n        {\n            query = \"Select p from p\";\n            kunderaQuery = new KunderaQuery(query, ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n            Assert.fail();\n        }\n        catch (JPQLParseException e)\n        {\n            Assert.assertEquals(\n                    \"Bad query format: p. Identification variable is mandatory in FROM clause for SELECT queries. For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\",\n                    e.getMessage());\n        }\n        try\n        {\n            query = \"Select p form CassandraUUIDEntity p\";\n            kunderaQuery = new KunderaQuery(query, ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n            Assert.fail();\n        }\n        catch (JPQLParseException e)\n        {\n            Assert.assertEquals(\n                    \"Bad query format FROM clause is mandatory for SELECT queries. For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\",\n                    e.getMessage());\n        }\n        try\n        {\n            query = \"Selct p from CassandraUUIDEntity p\";\n            kunderaQuery = new KunderaQuery(query, ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n            Assert.assertNotNull(kunderaQuery.getEntityClass());\n            Assert.assertEquals(CassandraUUIDEntity.class, kunderaQuery.getEntityClass());\n            Assert.assertNotNull(kunderaQuery.getEntityMetadata());\n            Assert.assertTrue(KunderaMetadataManager.getEntityMetadata(\n                    ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), CassandraUUIDEntity.class).equals(\n                    kunderaQuery.getEntityMetadata()));\n            Assert.assertNull(kunderaQuery.getFilter());\n            Assert.assertTrue(kunderaQuery.getFilterClauseQueue().isEmpty());\n            Assert.assertNotNull(kunderaQuery.getFrom());\n            Assert.assertTrue(kunderaQuery.getUpdateClauseQueue().isEmpty());\n            Assert.assertNotNull(kunderaQuery.getResult());\n            Assert.assertEquals(\"cass_pu\", kunderaQuery.getPersistenceUnit());\n            Assert.assertNull(kunderaQuery.getOrdering());\n        }\n        catch (JPQLParseException e)\n        {\n            Assert.assertEquals(\n                \"Bad query format FROM clause is mandatory for SELECT queries. For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\",\n                e.getMessage());\n        }\n        try\n        {\n            query = \"Select p from CassandraUUIDEntity p where\";\n            kunderaQuery = new KunderaQuery(query, ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n            Assert.fail();\n        }\n        catch (JPQLParseException e)\n        {\n            Assert.assertEquals(\n                    \"keyword without value[WHERE]. For details, see: http://openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/docs/manual/jpa_langref.html#jpa_langref_bnf\",\n                    e.getMessage());\n        }\n        try\n        {\n            query = \"Select p from CassandraUUIDEntity p where p\";\n            kunderaQuery = new KunderaQuery(query, ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n            queryParser = new KunderaQueryParser(kunderaQuery);\n            queryParser.parse();\n            kunderaQuery.postParsingInit();\n            //Assert.fail();\n        }\n        catch (PersistenceException e)\n        {\n            Assert.assertEquals(\"bad jpa query: p\", e.getMessage());\n        }\n    }\n\n    @Test\n    public void testOnIndexParameter()\n    {\n        String query = \"Select p from CassandraUUIDEntity p where p.uuidKey = ?1 and p.name= ?2\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query,\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(1, \"uuid1\");\n        kunderaQuery.setParameter(2, \"uuidname\");\n\n        List<String> uuidList = new ArrayList<String>();\n        uuidList.add(\"uuid1\");\n        List<String> nameList = new ArrayList<String>();\n        nameList.add(\"uuidname\");\n\n        Object value = kunderaQuery.getClauseValue(\"?1\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(uuidList, value);\n        value = kunderaQuery.getClauseValue(\"?2\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(nameList, value);\n        Assert.assertEquals(2, kunderaQuery.getParameters().size());\n\n        Iterator<Parameter<?>> parameters = kunderaQuery.getParameters().iterator();\n\n        while (parameters.hasNext())\n        {\n            Assert.assertTrue(kunderaQuery.isBound(parameters.next()));\n        }\n    }\n\n    @Test\n    public void testOnNameParameter()\n    {\n        String query = \"Select p from CassandraUUIDEntity p where p.uuidKey = :uuid and p.name= :name\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query,\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(\"uuid\", \"uuid1\");\n        kunderaQuery.setParameter(\"name\", \"uuidname\");\n\n        Assert.assertEquals(2, kunderaQuery.getParameters().size());\n\n        Iterator<Parameter<?>> parameters = kunderaQuery.getParameters().iterator();\n\n        while (parameters.hasNext())\n        {\n            Assert.assertTrue(kunderaQuery.isBound(parameters.next()));\n        }\n\n        List<String> uuidList = new ArrayList<String>();\n        uuidList.add(\"uuid1\");\n        List<String> nameList = new ArrayList<String>();\n        nameList.add(\"uuidname\");\n\n        Object value = kunderaQuery.getClauseValue(\":uuid\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(uuidList, value);\n        value = kunderaQuery.getClauseValue(\":name\");\n        Assert.assertNotNull(value);\n        Assert.assertEquals(nameList, value);\n        Assert.assertEquals(2, kunderaQuery.getParameters().size());\n\n    }\n\n    @Test\n    public void testInvalidIndexParameter()\n    {\n        String query = \"Select p from CassandraUUIDEntity p where p.uuidKey = ?1 and p.name= ?2\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query,\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(1, \"uuid1\");\n        kunderaQuery.setParameter(2, \"uuidname\");\n\n        try\n        {\n            kunderaQuery.getClauseValue(\"?3\");\n            Assert.fail(\"Should be catch block\");\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertEquals(\"parameter is not a parameter of the query\", iaex.getMessage());\n        }\n    }\n\n    @Test\n    public void testInvalidNameParameter()\n    {\n        String query = \"Select p from CassandraUUIDEntity p where p.uuidKey = :uuid and p.name= :name\";\n        KunderaQuery kunderaQuery = new KunderaQuery(query,\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        KunderaQueryParser queryParser = new KunderaQueryParser(kunderaQuery);\n        queryParser.parse();\n        kunderaQuery.postParsingInit();\n        kunderaQuery.setParameter(\"uuid\", \"uuid1\");\n        kunderaQuery.setParameter(\"name\", \"uuidname\");\n\n        try\n        {\n            kunderaQuery.getClauseValue(\":naame\");\n            Assert.fail(\"Should be catch block\");\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertEquals(\"parameter is not a parameter of the query\", iaex.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/resources/META-INF/persistence.xml",
    "content": "\r\n<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"cass_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n<!-- \t\t<jar-file>../target/classes/kundera-cassandra-2.11-SNAPSHOT-tests.jar</jar-file>\r\n -->\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"UUIDCassandra\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"pelops\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.cassandra.pelops.PelopsClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n</persistence>\r\n"
  },
  {
    "path": "src/kundera-cassandra/cassandra-pelops/src/test/resources/META-INF/persistence_2_0.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!-- persistence.xml schema -->\r\n<xsd:schema targetNamespace=\"http://java.sun.com/xml/ns/persistence\" \r\n  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\r\n  xmlns:persistence=\"http://java.sun.com/xml/ns/persistence\"\r\n  elementFormDefault=\"qualified\" \r\n  attributeFormDefault=\"unqualified\" \r\n  version=\"2.0\">\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n      @(#)persistence_2_0.xsd  1.0  October 1 2009\r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n\r\n  Copyright (c) 2008, 2009 Sun Microsystems. All rights reserved. \r\n  \r\n  This program and the accompanying materials are made available under the \r\n  terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 \r\n  which accompanies this distribution. \r\n  The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html\r\n  and the Eclipse Distribution License is available at \r\n  http://www.eclipse.org/org/documents/edl-v10.php.\r\n  \r\n  Contributors:\r\n      Linda DeMichiel - Java Persistence 2.0, Version 2.0 (October 1, 2009)\r\n      Specification available from http://jcp.org/en/jsr/detail?id=317\r\n \r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n   <xsd:annotation>\r\n     <xsd:documentation><![CDATA[\r\n\r\n     This is the XML Schema for the persistence configuration file.\r\n     The file must be named \"META-INF/persistence.xml\" in the \r\n     persistence archive.\r\n\r\n     Persistence configuration files must indicate\r\n     the persistence schema by using the persistence namespace:\r\n\r\n     http://java.sun.com/xml/ns/persistence\r\n\r\n     and indicate the version of the schema by\r\n     using the version element as shown below:\r\n\r\n      <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n        xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n          http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\"\r\n        version=\"2.0\">\r\n          ...\r\n      </persistence>\r\n\r\n    ]]></xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:simpleType name=\"versionType\">\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:pattern value=\"[0-9]+(\\.[0-9]+)*\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:element name=\"persistence\">\r\n    <xsd:complexType>\r\n      <xsd:sequence>\r\n\r\n        <!-- **************************************************** -->\r\n\r\n        <xsd:element name=\"persistence-unit\" \r\n                     minOccurs=\"1\" maxOccurs=\"unbounded\">\r\n          <xsd:complexType>\r\n            <xsd:annotation>\r\n              <xsd:documentation>\r\n\r\n                Configuration of a persistence unit.\r\n\r\n              </xsd:documentation>\r\n            </xsd:annotation>\r\n            <xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"description\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Description of this persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"provider\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Provider class that supplies EntityManagers for this \r\n                    persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of the JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"non-jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of a non-JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"mapping-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    File containing mapping information. Loaded as a resource \r\n                    by the persistence provider.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jar-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Jar file that is to be scanned for managed classes. \r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"class\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Managed class to be included in the persistence unit and\r\n                    to scan for annotations.  It should be annotated \r\n                    with either @Entity, @Embeddable or @MappedSuperclass.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"exclude-unlisted-classes\" type=\"xsd:boolean\" \r\n                           default=\"true\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    When set to true then only listed classes and jars will \r\n                    be scanned for persistent classes, otherwise the \r\n                    enclosing jar or directory will also be scanned. \r\n                    Not applicable to Java SE persistence units.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"shared-cache-mode\" \r\n                           type=\"persistence:persistence-unit-caching-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Defines whether caching is enabled for the \r\n                    persistence unit if caching is supported by the\r\n                    persistence provider. When set to ALL, all entities \r\n                    will be cached. When set to NONE, no entities will\r\n                    be cached. When set to ENABLE_SELECTIVE, only entities\r\n                    specified as cacheable will be cached. When set to\r\n                    DISABLE_SELECTIVE, entities specified as not cacheable\r\n                    will not be cached. When not specified or when set to\r\n                    UNSPECIFIED, provider defaults may apply.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"validation-mode\" \r\n                           type=\"persistence:persistence-unit-validation-mode-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The validation mode to be used for the persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"properties\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    A list of standard and vendor-specific properties \r\n                    and hints.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n                <xsd:complexType>\r\n                  <xsd:sequence>\r\n                    <xsd:element name=\"property\" \r\n                                 minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                      <xsd:annotation>\r\n                        <xsd:documentation>\r\n                          A name-value pair.\r\n                        </xsd:documentation>\r\n                      </xsd:annotation>\r\n                      <xsd:complexType>\r\n                        <xsd:attribute name=\"name\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                        <xsd:attribute name=\"value\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                      </xsd:complexType>\r\n                    </xsd:element>\r\n                  </xsd:sequence>\r\n                </xsd:complexType>\r\n              </xsd:element>\r\n\r\n            </xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Name used in code to reference this persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"transaction-type\" \r\n                           type=\"persistence:persistence-unit-transaction-type\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Type of transactions used by EntityManagers from this \r\n                  persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n          </xsd:complexType>\r\n        </xsd:element>\r\n      </xsd:sequence>\r\n      <xsd:attribute name=\"version\" type=\"persistence:versionType\" \r\n                     fixed=\"2.0\" use=\"required\"/>\r\n    </xsd:complexType>\r\n  </xsd:element>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-transaction-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum PersistenceUnitTransactionType {JTA, RESOURCE_LOCAL};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"JTA\"/>\r\n      <xsd:enumeration value=\"RESOURCE_LOCAL\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-caching-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum SharedCacheMode { ALL, NONE, ENABLE_SELECTIVE, DISABLE_SELECTIVE, UNSPECIFIED};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"ALL\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n      <xsd:enumeration value=\"ENABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"DISABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"UNSPECIFIED\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-validation-mode-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum ValidationMode { AUTO, CALLBACK, NONE};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"AUTO\"/>\r\n      <xsd:enumeration value=\"CALLBACK\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n</xsd:schema>\r\n"
  },
  {
    "path": "src/kundera-cassandra/pom.xml",
    "content": "\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus</groupId>\n\t\t<artifactId>kundera</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-cassandra-parent</artifactId>\n\t<packaging>pom</packaging>\n\t<name>kundera-cassandra-parent</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<cassandra.version>3.11.0</cassandra.version>\n\t</properties>\n\n\t<!-- Dependencies -->\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t        \t<groupId>com.impetus.kundera.core</groupId>\n                \t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t        \t<groupId>com.impetus.kundera.core</groupId>\n                \t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-elastic-search</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-elastic-search</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.apache.lucene</groupId>\n\t\t\t\t\t<artifactId>lucene-core</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t\n\t\t<dependency>\n\t\t\t<groupId>org.slf4j</groupId>\n\t\t\t<artifactId>slf4j-api</artifactId>\n\t\t\t<version>1.7.2</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>commons-codec</groupId>\n\t\t\t<artifactId>commons-codec</artifactId>\n\t\t\t<version>1.8</version>\n\t\t\t<scope>provided</scope>\n\t\t</dependency>\n\t\t<!-- contiperf dependency should not be here -->\n\n\t\t<dependency>\n\t\t\t<groupId>org.databene</groupId>\n\t\t\t<artifactId>contiperf</artifactId>\n\t\t\t<version>2.2.0</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>net.dataforte.cassandra</groupId>\n\t\t\t<version>0.7.1</version>\n\t\t\t<artifactId>cassandra-connection-pool</artifactId>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.apache.cassandra</groupId>\n\t\t\t\t\t<artifactId>cassandra-all</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t</dependencies>\n\n  <profiles>\n\n    <profile>\n      <id>all</id>\n      <activation>\n        <activeByDefault>true</activeByDefault>\n      </activation>\n      <modules>\n        <module>cassandra-core</module>\n        <module>cassandra-pelops</module>\n        <module>cassandra-ds-driver</module>\n      </modules>\n    </profile>\n\n    <profile>\n      <id>pelops</id>\n      <activation>\n        <activeByDefault>false</activeByDefault>\n      </activation>\n      <modules>\n        <module>cassandra-core</module>\n        <module>cassandra-pelops</module>\n      </modules>\n    </profile>\n\n\n    <profile>\n      <id>ds-driver</id>\n      <activation>\n        <activeByDefault>false</activeByDefault>\n      </activation>\n      <modules>\n        <module>cassandra-core</module>\n        <module>cassandra-ds-driver</module>\n      </modules>\n    </profile>\n    <profile>\n      <id>thrift</id>\n      <activation>\n        <activeByDefault>false</activeByDefault>\n      </activation>\n      <modules>\n        <module>cassandra-core</module>\n        <module>cassandra-thrift</module>\n      </modules>\n    </profile>\n\n</profiles>\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-clean-plugin</artifactId>\n\t\t\t\t<version>2.4.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<filesets>\n\t\t\t\t\t\t<fileset>\n\t\t\t\t\t\t\t<directory>${basedir}</directory>\n\t\t\t\t\t\t\t<excludes>\n\t\t\t\t\t\t\t\t<exclude>.git/**</exclude>\n\t\t\t\t\t\t\t\t<exclude>.gitignore</exclude>\n\t\t\t\t\t\t\t</excludes>\n\t\t\t\t\t\t\t<includes>\n\t\t\t\t\t\t\t\t<include>lucene/**</include>\n\t\t\t\t\t\t\t</includes>\n\t\t\t\t\t\t</fileset>\n\t\t\t\t\t</filesets>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n</project>\n"
  },
  {
    "path": "src/kundera-couchbase/pom.xml",
    "content": "<?xml version=\"1.0\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<artifactId>kundera</artifactId>\n\t\t<groupId>com.impetus</groupId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-couchbase</artifactId>\n\t<name>kundera-couchbase</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<couchbase.version>2.5.0</couchbase.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<!-- Kundera dependencies -->\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>commons-beanutils</groupId>\n\t\t\t<artifactId>commons-beanutils-core</artifactId>\n\t\t\t<version>1.8.3</version>\n\t\t</dependency>\n\n\t\t<!-- couchbase dependency -->\n\n\t\t<dependency>\n\t\t\t<groupId>com.couchbase.client</groupId>\n\t\t\t<artifactId>java-client</artifactId>\n\t\t\t<version>${couchbase.version}</version>\n\t\t</dependency>\n\n\t</dependencies>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n"
  },
  {
    "path": "src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/CouchbaseBucketUtils.java",
    "content": "package com.impetus.client.couchbase;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.couchbase.client.core.CouchbaseException;\nimport com.couchbase.client.java.Bucket;\nimport com.couchbase.client.java.CouchbaseCluster;\nimport com.impetus.kundera.KunderaException;\n\n/**\n * The Class CouchbaseBucketUtils.\n * \n * @author devender.yadav\n * \n */\npublic class CouchbaseBucketUtils\n{\n\n    /** The Constant LOGGER. */\n    private static final Logger LOGGER = LoggerFactory.getLogger(CouchbaseBucketUtils.class);\n\n    /**\n     * Instantiates a new couchbase bucket utils.\n     */\n    private CouchbaseBucketUtils()\n    {\n    }\n\n    /**\n     * Open bucket.\n     *\n     * @param cluster\n     *            the cluster\n     * @param name\n     *            the name\n     * @param password\n     *            the password\n     * @return the bucket\n     */\n    public static Bucket openBucket(CouchbaseCluster cluster, String name, String password)\n    {\n        if (cluster == null)\n        {\n            throw new KunderaException(\"CouchbaseCluster object can't be null\");\n        }\n        try\n        {\n            Bucket bucket;\n            if (password != null && !password.trim().isEmpty())\n            {\n                bucket = cluster.openBucket(name, password);\n            }\n            else\n            {\n                bucket = cluster.openBucket(name);\n            }\n            LOGGER.debug(\"Bucket [\" + name + \"] is opened!\");\n            return bucket;\n        }\n        catch (CouchbaseException ex)\n        {\n            LOGGER.error(\"Not able to open bucket [\" + name + \"].\", ex);\n            throw new KunderaException(\"Not able to open bucket [\" + name + \"].\", ex);\n        }\n\n    }\n\n    /**\n     * Close bucket.\n     *\n     * @param bucket\n     *            the bucket\n     */\n    public static void closeBucket(Bucket bucket)\n    {\n        if (bucket != null)\n        {\n            if (!bucket.close())\n            {\n                LOGGER.error(\"Not able to close bucket [\" + bucket.name() + \"].\");\n                throw new KunderaException(\"Not able to close bucket [\" + bucket.name() + \"].\");\n            }\n            else\n            {\n                LOGGER.debug(\"Bucket [\" + bucket.name() + \"] is closed!\");\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/CouchbaseClient.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchbase;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.metamodel.EntityType;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.couchbase.client.java.Bucket;\nimport com.couchbase.client.java.document.JsonDocument;\nimport com.couchbase.client.java.document.json.JsonObject;\nimport com.couchbase.client.java.query.N1qlParams;\nimport com.couchbase.client.java.query.N1qlQuery;\nimport com.couchbase.client.java.query.N1qlQueryResult;\nimport com.couchbase.client.java.query.N1qlQueryRow;\nimport com.couchbase.client.java.query.Statement;\nimport com.couchbase.client.java.query.consistency.ScanConsistency;\nimport com.impetus.client.couchbase.query.CouchbaseQuery;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\n\n/**\n * The Class CouchbaseClient.\n * \n * @author devender.yadav\n */\npublic class CouchbaseClient extends ClientBase implements Client<CouchbaseQuery>\n{\n\n    /** The Constant LOGGER. */\n    private static final Logger LOGGER = LoggerFactory.getLogger(CouchbaseClient.class);\n\n    /** The bucket. */\n    private Bucket bucket;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /** The handler. */\n    private DefaultCouchbaseDataHandler handler;\n\n    /**\n     * Instantiates a new couchbase client.\n     *\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param indexManager\n     *            the index manager\n     * @param reader\n     *            the reader\n     * @param properties\n     *            the properties\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param bucket\n     *            the bucket\n     * @param clientMetadata\n     *            the client metadata\n     */\n    protected CouchbaseClient(KunderaMetadata kunderaMetadata, IndexManager indexManager, EntityReader reader,\n            Map<String, Object> properties, String persistenceUnit, Bucket bucket, ClientMetadata clientMetadata)\n    {\n        super(kunderaMetadata, properties, persistenceUnit);\n        this.reader = reader;\n        this.bucket = bucket;\n        this.indexManager = indexManager;\n        this.clientMetadata = clientMetadata;\n        handler = new DefaultCouchbaseDataHandler();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.Object)\n     */\n    @Override\n    public Object find(Class entityClass, Object key)\n    {\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        JsonDocument doc;\n        String id = generateJsonDocId(entityMetadata.getTableName(), key.toString());\n        doc = bucket.get(id);\n        LOGGER.debug(\"Found result for ID : \" + key.toString() + \" in the \" + bucket.name() + \" Bucket\");\n\n        if (doc == null)\n        {\n            return null;\n        }\n        else\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                    .getMetamodel(entityMetadata.getPersistenceUnit());\n            EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n            return handler.getEntityFromDocument(entityClass, doc.content(), entityType);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.String[], java.lang.Object[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    @Override\n    public void close()\n    {\n        externalProperties = null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera.\n     * persistence.context.jointable.JoinTableData )\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,\n            Object pKeyColumnValue, Class columnJavaType)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    @Override\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<CouchbaseQuery> getQueryImplementor()\n    {\n        return CouchbaseQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.\n     * metadata.model.EntityMetadata, java.lang.Object, java.lang.Object,\n     * java.util.List)\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n        JsonDocument doc = handler.getDocumentFromEntity(entityMetadata, entity, kunderaMetadata);\n\n        if (!isUpdate)\n        {\n            bucket.insert(doc);\n            LOGGER.debug(\"Inserted document with ID : \" + doc.id() + \" in the \" + bucket.name() + \" Bucket\");\n        }\n        else\n        {\n            bucket.upsert(doc);\n            LOGGER.debug(\"Updated document with ID : \" + doc.id() + \" in the \" + bucket.name() + \" Bucket\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientBase#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    protected void delete(Object entity, Object pKey)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        String id = generateJsonDocId(entityMetadata.getTableName(), pKey.toString());\n        bucket.remove(id);\n        LOGGER.debug(\"Deleted document with ID : \" + id + \" from the \" + bucket.name() + \" Bucket\");\n    }\n\n    /**\n     * Generate json doc id.\n     *\n     * @param tableName\n     *            the table name\n     * @param pKey\n     *            the key\n     * @return the string\n     */\n    private String generateJsonDocId(String tableName, String pKey)\n    {\n        return tableName + \"_\" + pKey;\n    }\n\n    /**\n     * Execute query.\n     *\n     * @param stmt\n     *            the statement\n     * @param em\n     *            the entity manager\n     * @return the list\n     */\n    public List executeQuery(Statement stmt, EntityMetadata em)\n    {\n        N1qlQuery query = N1qlQuery.simple(stmt, N1qlParams.build().consistency(ScanConsistency.REQUEST_PLUS));\n        N1qlQueryResult list = bucket.query(query);\n        LOGGER.debug(\"Executed query : \" + query.toString() + \" on the \" + bucket.name() + \" Bucket\");\n        validateQueryResults(stmt.toString(), list);\n\n        List records = new ArrayList<>();\n        for (N1qlQueryRow row : list)\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                    .getMetamodel(em.getPersistenceUnit());\n            EntityType entityType = metaModel.entity(em.getEntityClazz());\n\n            JsonObject jsonObj = row.value().containsKey(em.getSchema()) ? row.value().getObject(em.getSchema())\n                    : row.value();\n\n            records.add(handler.getEntityFromDocument(em.getEntityClazz(), jsonObj, entityType));\n        }\n\n        return records;\n\n    }\n\n    /**\n     * Execute native query.\n     *\n     * @param n1qlQuery\n     *            the n1ql query\n     * @param em\n     *            the entity manager\n     * @return the list\n     */\n    public List executeNativeQuery(String n1qlQuery, EntityMetadata em)\n    {\n        N1qlQueryResult result = bucket\n                .query(N1qlQuery.simple(n1qlQuery, N1qlParams.build().consistency(ScanConsistency.REQUEST_PLUS)));\n        LOGGER.debug(\"Executed query : \" + n1qlQuery + \" on the \" + bucket.name() + \" Bucket\");\n\n        validateQueryResults(n1qlQuery, result);\n        return result.allRows();\n\n    }\n\n    /**\n     * Validate query results.\n     *\n     * @param query\n     *            the query\n     * @param result\n     *            the result\n     */\n    private void validateQueryResults(String query, N1qlQueryResult result)\n    {\n        LOGGER.debug(\"Query output status: \" + result.finalSuccess());\n\n        if (!result.finalSuccess())\n        {\n            StringBuilder errorBuilder = new StringBuilder();\n            for (JsonObject obj : result.errors())\n            {\n                errorBuilder.append(obj.toString());\n                errorBuilder.append(\"\\n\");\n            }\n            errorBuilder.deleteCharAt(errorBuilder.length() - 1);\n            String errors = errorBuilder.toString();\n            LOGGER.error(errors);\n            throw new KunderaException(\"Not able to execute query/statement:\" + query + \". More details : \" + errors);\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/CouchbaseClientFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchbase;\n\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.couchbase.client.java.Bucket;\nimport com.couchbase.client.java.CouchbaseCluster;\nimport com.impetus.client.couchbase.query.CouchbaseEntityReader;\nimport com.impetus.client.couchbase.schemamanager.CouchbaseSchemaManager;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * A factory for creating CouchbaseClientFactory objects.\n * \n * @author devender.yadav\n */\npublic class CouchbaseClientFactory extends GenericClientFactory\n{\n\n    /** The LOGGER. */\n    private static final Logger LOGGER = LoggerFactory.getLogger(CouchbaseClientFactory.class);\n\n    /** The cluster. */\n    private CouchbaseCluster cluster;\n\n    /** The bucket. */\n    private Bucket bucket;\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.ClientFactory#getSchemaManager(java.util.Map)\n     */\n    @Override\n    public SchemaManager getSchemaManager(Map<String, Object> puProperties)\n    {\n        if (schemaManager == null)\n        {\n            initializePropertyReader();\n            setExternalProperties(puProperties);\n            schemaManager = new CouchbaseSchemaManager(CouchbaseClientFactory.class.getName(), puProperties,\n                    kunderaMetadata);\n        }\n        return schemaManager;\n    }\n\n    /**\n     * Initialize property reader.\n     */\n    private void initializePropertyReader()\n    {\n        if (propertyReader == null)\n        {\n            propertyReader = new CouchbasePropertyReader(externalProperties,\n                    kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(getPersistenceUnit()));\n            propertyReader.read(getPersistenceUnit());\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.ClientLifeCycleManager#destroy()\n     */\n    @Override\n    public void destroy()\n    {\n        indexManager.close();\n        if (schemaManager != null)\n        {\n            schemaManager.dropSchema();\n        }\n        if (bucket != null)\n        {\n            LOGGER.info(\"Closing bucket \" + bucket.name() + \".\");\n            CouchbaseBucketUtils.closeBucket(bucket);\n            LOGGER.info(\"Closed bucket \" + bucket.name() + \".\");\n        }\n        if (cluster != null)\n        {\n            LOGGER.info(\"Closing connection to couchbase.\");\n            cluster.disconnect();\n            LOGGER.info(\"Closed connection to couchbase.\");\n        }\n        else\n        {\n            LOGGER.warn(\"Can't close connection to Couchbase, it was already disconnected\");\n        }\n        externalProperties = null;\n        schemaManager = null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initialize(java.util.Map)\n     */\n    @Override\n    public void initialize(Map<String, Object> puProperties)\n    {\n        reader = new CouchbaseEntityReader(kunderaMetadata);\n        setExternalProperties(puProperties);\n        initializePropertyReader();\n        PersistenceUnitMetadata pum = kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(getPersistenceUnit());\n\n        Properties pumProps = pum.getProperties();\n\n        if (puProperties != null)\n        {\n            pumProps.putAll(puProperties);\n        }\n\n        String host = pumProps.getProperty(\"kundera.nodes\");\n        String keyspace = pumProps.getProperty(\"kundera.keyspace\");\n\n        if (host == null)\n        {\n            throw new KunderaException(\"Hostname/IP is null.\");\n        }\n\n        if (keyspace == null)\n        {\n            throw new KunderaException(\"kundera.keyspace is null.\");\n        }\n        cluster = CouchbaseCluster.create(splitHostNames(host));\n        String password = ((CouchbasePropertyReader) propertyReader).csmd.getBucketProperty(\"bucket.password\");\n        bucket = CouchbaseBucketUtils.openBucket(cluster, keyspace, password);\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#createPoolOrConnection()\n     */\n    @Override\n    protected Object createPoolOrConnection()\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#instantiateClient(java.\n     * lang.String)\n     */\n    @Override\n    protected Client instantiateClient(String persistenceUnit)\n    {\n        return new CouchbaseClient(kunderaMetadata, indexManager, reader, externalProperties, persistenceUnit,\n                this.bucket, this.clientMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.GenericClientFactory#isThreadSafe()\n     */\n    @Override\n    public boolean isThreadSafe()\n    {\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initializeLoadBalancer(\n     * java.lang.String)\n     */\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n\n    }\n\n    /**\n     * Split host names.\n     *\n     * @param hostNames\n     *            the host names\n     * @return the string[]\n     */\n    private String[] splitHostNames(String hostNames)\n    {\n        String[] hostArray = hostNames.split(Constants.COMMA);\n        String[] hosts = new String[hostArray.length];\n        for (int i = 0; i < hostArray.length; i++)\n        {\n            hosts[i] = hostArray[i].trim();\n        }\n        return hosts;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/CouchbaseConstants.java",
    "content": "package com.impetus.client.couchbase;\n\n/**\n * The Class CouchbaseConstants.\n */\npublic class CouchbaseConstants\n{\n\n    /** The Constant COUCHBASE. */\n    public static final String COUCHBASE = \"couchbase\";\n\n    /** The Constant KUNDERA_ENTITY. */\n    public static final String KUNDERA_ENTITY = \"kundera_enity\";\n\n    /** The Constant ID_SEPARATOR. */\n    public static final String ID_SEPARATOR = \"_\";\n\n    /** The Constant DOT_REGEX. */\n    public static final String DOT_REGEX = \"[.]\";\n\n    /** The Constant PARAMETERIZED_PREFIX. */\n    public static final String PARAMETERIZED_PREFIX = \":\";\n\n    /** The Constant POSITIONAL_PREFIX. */\n    public static final String POSITIONAL_PREFIX = \"?\";\n\n    /** The Constant STAR. */\n    public static final String STAR = \"*\";\n    \n    /** The Constant INDEX_SUFFIX. */\n    public static final String INDEX_SUFFIX = \"_primary\";\n    \n\n    /**\n     * Instantiates a new couchbase constants.\n     */\n    CouchbaseConstants()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/CouchbaseDataHandler.java",
    "content": "package com.impetus.client.couchbase;\n\nimport javax.persistence.metamodel.EntityType;\n\nimport com.couchbase.client.java.document.JsonDocument;\nimport com.couchbase.client.java.document.json.JsonObject;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * The Interface CouchbaseDataHandler.\n * \n * @author devender.yadav\n */\npublic interface CouchbaseDataHandler\n{\n\n    /**\n     * Gets the entity from document.\n     *\n     * @param entityClass\n     *            the entity class\n     * @param obj\n     *            the obj\n     * @param entityType\n     *            the entity type\n     * @return the entity from document\n     */\n    Object getEntityFromDocument(Class<?> entityClass, JsonObject obj, EntityType entityType);\n\n    /**\n     * Gets the document from entity.\n     *\n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @return the document from entity\n     */\n    JsonDocument getDocumentFromEntity(EntityMetadata entityMetadata, Object entity,\n            final KunderaMetadata kunderaMetadata);\n\n}\n"
  },
  {
    "path": "src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/CouchbasePropertyReader.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchbase;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Schema;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * The Class CouchbasePropertyReader.\n * \n * @author karthikp.manchala\n */\npublic class CouchbasePropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n\n    /** The csmd. */\n    public static CouchbaseSchemaMetadata csmd;\n\n    /**\n     * Instantiates a new rethink db property reader.\n     * \n     * @param externalProperties\n     *            the external properties\n     * @param puMetadata\n     *            the pu metadata\n     */\n    public CouchbasePropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        csmd = new CouchbaseSchemaMetadata();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.AbstractPropertyReader#onXml(com.impetus.\n     * kundera.configure.ClientProperties)\n     */\n    @Override\n    public void onXml(ClientProperties cp)\n    {\n        if (cp != null)\n        {\n            csmd.setClientProperties(cp);\n        }\n    }\n\n    /**\n     * The Class CouchbaseSchemaMetadata.\n     */\n    public class CouchbaseSchemaMetadata\n    {\n\n        /** The client properties. */\n        private ClientProperties clientProperties;\n\n        /**\n         * Gets the client properties.\n         * \n         * @return the client properties\n         */\n        public ClientProperties getClientProperties()\n        {\n            return clientProperties;\n        }\n\n        /**\n         * Sets the client properties.\n         * \n         * @param clientProperties\n         *            the new client properties\n         */\n        private void setClientProperties(ClientProperties clientProperties)\n        {\n            this.clientProperties = clientProperties;\n        }\n\n        /**\n         * Gets the data store.\n         * \n         * @param datastore\n         *            the datastore\n         * @return the data store\n         */\n        public DataStore getDataStore(String datastore)\n        {\n            if (getClientProperties() != null && getClientProperties().getDatastores() != null)\n            {\n                for (DataStore dataStore : getClientProperties().getDatastores())\n                {\n                    if (dataStore.getName() != null && dataStore.getName().trim().equalsIgnoreCase(datastore))\n                    {\n                        return dataStore;\n                    }\n                }\n            }\n            return null;\n        }\n\n        /**\n         * Gets the bucket property.\n         *\n         * @param property\n         *            the property\n         * @return the bucket property\n         */\n        public String getBucketProperty(String property)\n        {\n            List<Schema> list = csmd.getDataStore(CouchbaseConstants.COUCHBASE).getSchemas();\n\n            if (!list.isEmpty())\n            {\n                Schema schema = list.get(0);\n                Properties prop = schema.getSchemaProperties();\n                return (String) prop.get(property);\n            }\n            return null;\n        }\n\n    }\n}"
  },
  {
    "path": "src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/DefaultCouchbaseDataHandler.java",
    "content": "package com.impetus.client.couchbase;\n\nimport java.lang.reflect.Field;\nimport java.util.Iterator;\nimport java.util.Set;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.commons.beanutils.ConvertUtils;\n\nimport com.couchbase.client.java.document.JsonDocument;\nimport com.couchbase.client.java.document.json.JsonObject;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class DefaultCouchbaseDataHandler.\n * \n * @author devender.yadav\n * \n */\npublic class DefaultCouchbaseDataHandler implements CouchbaseDataHandler\n{\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.couchbase.CouchbaseDataHandler#getEntityFromDocument(\n     * java.lang.Class, com.couchbase.client.java.document.json.JsonObject,\n     * javax.persistence.metamodel.EntityType)\n     */\n    @Override\n    public Object getEntityFromDocument(Class<?> entityClass, JsonObject obj, EntityType entityType)\n    {\n        Object entity = KunderaCoreUtils.createNewInstance(entityClass);\n        Set<Attribute> attributes = entityType.getAttributes();\n        Iterator<Attribute> iterator = attributes.iterator();\n        iterateAndPopulateEntity(entity, obj, iterator);\n        return entity;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.couchbase.CouchbaseDataHandler#getDocumentFromEntity(\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.lang.Object,\n     * com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata)\n     */\n    @Override\n    public JsonDocument getDocumentFromEntity(EntityMetadata entityMetadata, Object entity,\n            KunderaMetadata kunderaMetadata)\n    {\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(entityMetadata.getPersistenceUnit());\n        Class entityClazz = entityMetadata.getEntityClazz();\n        EntityType entityType = metaModel.entity(entityClazz);\n        Set<Attribute> attributes = entityType.getAttributes();\n        Iterator<Attribute> iterator = attributes.iterator();\n        JsonObject obj = iterateAndPopulateJsonObject(entity, iterator, entityMetadata.getTableName());\n        Object id = PropertyAccessorHelper.getId(entity, entityMetadata);\n        return JsonDocument.create(entityMetadata.getTableName() + CouchbaseConstants.ID_SEPARATOR + id.toString(),\n                obj);\n    }\n\n    /**\n     * Iterate and populate entity.\n     *\n     * @param entity\n     *            the entity\n     * @param obj\n     *            the obj\n     * @param iterator\n     *            the iterator\n     */\n    private void iterateAndPopulateEntity(Object entity, JsonObject obj, Iterator<Attribute> iterator)\n    {\n        while (iterator.hasNext())\n        {\n            Attribute attribute = iterator.next();\n            Field field = (Field) attribute.getJavaMember();\n            String colName = ((AbstractAttribute) attribute).getJPAColumnName();\n\n            if (!colName.equalsIgnoreCase(CouchbaseConstants.KUNDERA_ENTITY) && obj.get(colName) != null)\n            {\n                Object value = ConvertUtils.convert(obj.get(colName), field.getType());\n                PropertyAccessorHelper.set(entity, field, value);\n            }\n\n        }\n    }\n\n    /**\n     * Iterate and populate json object.\n     *\n     * @param entity\n     *            the entity\n     * @param iterator\n     *            the iterator\n     * @return the json object\n     */\n    private JsonObject iterateAndPopulateJsonObject(Object entity, Iterator<Attribute> iterator, String tableName)\n    {\n        JsonObject obj = JsonObject.create();\n        while (iterator.hasNext())\n        {\n            Attribute attribute = iterator.next();\n            Field field = (Field) attribute.getJavaMember();\n            Object value = PropertyAccessorHelper.getObject(entity, field);\n\n            obj.put(((AbstractAttribute) attribute).getJPAColumnName(), value);\n        }\n        obj.put(CouchbaseConstants.KUNDERA_ENTITY, tableName);\n        return obj;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/query/CouchbaseEntityReader.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchbase.query;\n\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\n\n/**\n * The Class CouchbaseEntityReader.\n * \n * @author karthikp.manchala\n */\npublic class CouchbaseEntityReader extends AbstractEntityReader implements EntityReader\n{\n\n    /**\n     * Instantiates a new couchbase entity reader.\n     * \n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public CouchbaseEntityReader(KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.AbstractEntityReader#findById(java.lang.\n     * Object, com.impetus.kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        return super.findById(primaryKey, m, client);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#populateRelation(com.impetus\n     * .kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client, int)\n     */\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/query/CouchbaseQuery.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchbase.query;\n\nimport static com.couchbase.client.java.query.Select.select;\nimport static com.couchbase.client.java.query.dsl.Expression.i;\nimport static com.couchbase.client.java.query.dsl.Expression.x;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.eclipse.persistence.jpa.jpql.parser.ComparisonExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.JPQLExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.WhereClause;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.couchbase.client.java.query.Statement;\nimport com.couchbase.client.java.query.dsl.path.AsPath;\nimport com.impetus.client.couchbase.CouchbaseClient;\nimport com.impetus.client.couchbase.CouchbaseConstants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQueryUtils;\nimport com.impetus.kundera.query.Query;\nimport com.impetus.kundera.query.QueryImpl;\n\n/**\n * The Class CouchbaseQuery.\n * \n * @author devender.yadav\n */\npublic class CouchbaseQuery extends QueryImpl implements Query\n{\n\n    /** The LOGGER. */\n    private static final Logger LOGGER = LoggerFactory.getLogger(CouchbaseQuery.class);\n\n    /**\n     * Instantiates a new couchbase query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param persistenceDelegator\n     *            the persistence delegator\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public CouchbaseQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera.\n     * metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List populateEntities(EntityMetadata m, Client client)\n    {\n        if (kunderaQuery.isNative())\n        {\n            return ((CouchbaseClient) client).executeNativeQuery(getJPAQuery(), m);\n        }\n        else\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                    .getMetamodel(m.getPersistenceUnit());\n            EntityType entityType = metaModel.entity(m.getEntityClazz());\n            JPQLExpression jpqlExp = kunderaQuery.getJpqlExpression();\n            List<String> selectColumns = KunderaQueryUtils.getSelectColumns(jpqlExp);\n            AsPath asPath;\n            if (selectColumns.isEmpty())\n            {\n                asPath = select(CouchbaseConstants.STAR).from(i(m.getSchema()));\n            }\n            else\n            {\n                asPath = select(selectColumns.toArray(new String[selectColumns.size()])).from(i(m.getSchema()));\n            }\n            Statement statement;\n\n            if (KunderaQueryUtils.hasWhereClause(jpqlExp))\n            {\n                WhereClause whereClause = KunderaQueryUtils.getWhereClause(jpqlExp);\n                Expression whereExp = whereClause.getConditionalExpression();\n\n                if (whereExp instanceof ComparisonExpression)\n                {\n                    String left = ((ComparisonExpression) whereExp).getLeftExpression().toActualText();\n                    String right = ((ComparisonExpression) whereExp).getRightExpression().toActualText();\n                    if (right.startsWith(CouchbaseConstants.POSITIONAL_PREFIX)\n                            || right.startsWith(CouchbaseConstants.PARAMETERIZED_PREFIX))\n                    {\n                        right = kunderaQuery.getParametersMap().get(right) + \"\";\n                    }\n                    Attribute attribute = entityType.getAttribute(left.split(CouchbaseConstants.DOT_REGEX)[1]);\n\n                    statement = addWhereCondition(asPath, ((ComparisonExpression) whereExp).getActualIdentifier(),\n                            ((AbstractAttribute) attribute).getJPAColumnName(), right, m.getTableName());\n                }\n\n            }\n            else\n            {\n                asPath.where(x(CouchbaseConstants.KUNDERA_ENTITY).eq(x(\"'\" + m.getTableName() + \"'\")));\n            }\n\n            statement = asPath;\n            return ((CouchbaseClient) client).executeQuery(statement, m);\n        }\n    }\n\n    /**\n     * Adds the where condition.\n     *\n     * @param asPath\n     *            the as path\n     * @param identifier\n     *            the identifier\n     * @param colName\n     *            the col name\n     * @param val\n     *            the val\n     * @param tableName\n     *            the table name\n     * @return the statement\n     */\n    public Statement addWhereCondition(AsPath asPath, String identifier, String colName, String val, String tableName)\n    {\n        com.couchbase.client.java.query.dsl.Expression exp;\n        switch (identifier)\n        {\n\n        case \"<\":\n            exp = x(colName).lt(x(val));\n            break;\n        case \"<=\":\n            exp = x(colName).lte(x(val));\n            break;\n        case \">\":\n            exp = x(colName).gt(x(val));\n            break;\n        case \">=\":\n            exp = x(colName).gte(x(val));\n            break;\n        case \"=\":\n            exp = x(colName).eq(x(val));\n            break;\n        default:\n            LOGGER.error(\"Operator \" + identifier + \"  is not supported in the JPA query for Couchbase.\");\n            throw new KunderaException(\"Operator \" + identifier + \"  is not supported in the JPA query for Couchbase.\");\n        }\n\n        return asPath.where(exp.and(x(CouchbaseConstants.KUNDERA_ENTITY).eq(x(\"'\" + tableName) + \"'\")));\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#findUsingLucene(com.impetus.kundera.\n     * metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#recursivelyPopulateEntities(com.\n     * impetus.kundera.metadata.model.EntityMetadata ,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#getReader()\n     */\n    @Override\n    protected EntityReader getReader()\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()\n     */\n    @Override\n    protected int onExecuteUpdate()\n    {\n        return 0;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#close()\n     */\n    @Override\n    public void close()\n    {\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#iterate()\n     */\n    @Override\n    public Iterator iterate()\n    {\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchbase/src/main/java/com/impetus/client/couchbase/schemamanager/CouchbaseSchemaManager.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchbase.schemamanager;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.couchbase.client.core.CouchbaseException;\nimport com.couchbase.client.java.Bucket;\nimport com.couchbase.client.java.CouchbaseCluster;\nimport com.couchbase.client.java.bucket.BucketType;\nimport com.couchbase.client.java.cluster.BucketSettings;\nimport com.couchbase.client.java.cluster.ClusterManager;\nimport com.couchbase.client.java.cluster.DefaultBucketSettings;\nimport com.impetus.client.couchbase.CouchbaseBucketUtils;\nimport com.impetus.client.couchbase.CouchbaseConstants;\nimport com.impetus.client.couchbase.CouchbasePropertyReader;\nimport com.impetus.client.couchbase.CouchbasePropertyReader.CouchbaseSchemaMetadata;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.configure.schema.TableInfo;\nimport com.impetus.kundera.configure.schema.api.AbstractSchemaManager;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * The Class CouchbaseSchemaManager.\n * \n * @author devender.yadav\n */\npublic class CouchbaseSchemaManager extends AbstractSchemaManager implements SchemaManager\n{\n\n    /** The Constant LOGGER. */\n    private static final Logger LOGGER = LoggerFactory.getLogger(CouchbaseSchemaManager.class);\n\n    /**\n     * The Constant DEFAULT_RAM_SIZE_IN_MB.\n     * \n     * Using 100 MB (minimum RAM Quota) be default\n     */\n    private static final int DEFAULT_RAM_SIZE_IN_MB = 100;\n\n    /** The cluster. */\n    private CouchbaseCluster cluster;\n\n    /** The csmd. */\n    private CouchbaseSchemaMetadata csmd = CouchbasePropertyReader.csmd;\n\n    /** The cluster manager. */\n    private ClusterManager clusterManager;\n\n    /**\n     * Instantiates a new couchbase schema manager.\n     * \n     * @param clientFactory\n     *            the client factory\n     * @param externalProperties\n     *            the external properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public CouchbaseSchemaManager(String clientFactory, Map<String, Object> externalProperties,\n            KunderaMetadata kunderaMetadata)\n    {\n        super(clientFactory, externalProperties, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.SchemaManager#dropSchema()\n     */\n    @Override\n    public void dropSchema()\n    {\n        if (operation != null && (\"create-drop\").equalsIgnoreCase(operation))\n        {\n            for (TableInfo tableInfo : tableInfos)\n            {\n                removeBucket(tableInfo.getTableName());\n            }\n        }\n        cluster.disconnect();\n        cluster = null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.SchemaManager#validateEntity\n     * (java.lang.Class)\n     */\n    @Override\n    public boolean validateEntity(Class clazz)\n    {\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.AbstractSchemaManager#\n     * initiateClient ()\n     */\n    @Override\n    protected boolean initiateClient()\n    {\n        for (String host : hosts)\n        {\n            if (host == null)\n            {\n                LOGGER.error(\"Host Name should not be null.\");\n                throw new IllegalArgumentException(\"Host Name should not be null.\");\n            }\n        }\n        cluster = CouchbaseCluster.create(hosts);\n\n        if (userName != null && password != null)\n        {\n            clusterManager = cluster.clusterManager(userName, password);\n        }\n        else\n        {\n            clusterManager = cluster.clusterManager();\n        }\n        return true;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#validate\n     * (java.util.List)\n     */\n    @Override\n    protected void validate(List<TableInfo> tableInfos)\n    {\n\n        if (!clusterManager.hasBucket(databaseName))\n        {\n            throw new SchemaGenerationException(\"Bucket [\" + databaseName + \"] does not exist.\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#update\n     * (java.util.List)\n     */\n    @Override\n    protected void update(List<TableInfo> tableInfos)\n    {\n        if (!clusterManager.hasBucket(databaseName))\n        {\n            addBucket(databaseName);\n            createIdIndex(databaseName);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#create\n     * (java.util.List)\n     */\n    @Override\n    protected void create(List<TableInfo> tableInfos)\n    {\n\n        if (clusterManager.hasBucket(databaseName))\n        {\n            /*\n             * Removing bucket will drop indexes too\n             * \n             */\n            removeBucket(databaseName);\n        }\n        addBucket(databaseName);\n        createIdIndex(databaseName);\n    }\n\n    /**\n     * Creates the id index.\n     *\n     * @param bucketName\n     *            the bucket name\n     */\n    private void createIdIndex(String bucketName)\n    {\n        Bucket bucket = null;\n        try\n        {\n            bucket = CouchbaseBucketUtils.openBucket(cluster, bucketName, csmd.getBucketProperty(\"bucket.password\"));\n\n            /*\n             * Ignoring if indexes pre-exist\n             */\n\n            bucket.bucketManager().createN1qlPrimaryIndex(buildIndexName(bucketName), true, false);\n\n            LOGGER.debug(\"Niql primary Index are created for bucket [\" + bucketName + \"].\");\n        }\n        catch (CouchbaseException cex)\n        {\n            LOGGER.error(\"Not able to create Niql primary index for bucket [\" + bucketName + \"].\", cex);\n            throw new KunderaException(\"Not able to create Niql primary index for bucket [\" + bucketName + \"].\", cex);\n        }\n\n        finally\n        {\n            CouchbaseBucketUtils.closeBucket(bucket);\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.AbstractSchemaManager#\n     * create_drop (java.util.List)\n     */\n    @Override\n    protected void create_drop(List<TableInfo> tableInfos)\n    {\n        create(tableInfos);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.AbstractSchemaManager#\n     * exportSchema(java.lang.String, java.util.List)\n     */\n    @Override\n    public void exportSchema(final String persistenceUnit, List<TableInfo> schemas)\n    {\n        super.exportSchema(persistenceUnit, schemas);\n    }\n\n    /**\n     * Removes the bucket.\n     *\n     * @param name\n     *            the name\n     */\n    private void removeBucket(String name)\n    {\n        try\n        {\n            if (clusterManager.removeBucket(name))\n            {\n                LOGGER.info(\"Bucket [\" + name + \"] is removed!\");\n            }\n            else\n            {\n                LOGGER.error(\"Not able to remove bucket [\" + name + \"].\");\n                throw new KunderaException(\"Not able to remove bucket [\" + name + \"].\");\n            }\n        }\n        catch (CouchbaseException ex)\n        {\n            LOGGER.error(\"Not able to remove bucket [\" + name + \"].\", ex);\n            throw new KunderaException(\"Not able to remove bucket [\" + name + \"].\", ex);\n        }\n    }\n\n    /**\n     * Adds the bucket.\n     *\n     * @param name\n     *            the name\n     */\n    private void addBucket(String name)\n    {\n        String qouta = csmd.getBucketProperty(\"bucket.quota\");\n        int bucketQuota = qouta != null ? Integer.parseInt(qouta) : DEFAULT_RAM_SIZE_IN_MB;\n        BucketSettings bucketSettings = new DefaultBucketSettings.Builder().type(BucketType.COUCHBASE).name(name)\n                .quota(bucketQuota).build();\n\n        try\n        {\n            clusterManager.insertBucket(bucketSettings);\n            LOGGER.info(\"Bucket [\" + name + \"] is added!\");\n        }\n        catch (CouchbaseException ex)\n        {\n            LOGGER.error(\"Not able to add bucket [\" + name + \"].\", ex);\n            throw new KunderaException(\"Not able to add bucket [\" + name + \"].\", ex);\n        }\n    }\n\n    /**\n     * Builds the index name.\n     *\n     * @param bucketName\n     *            the bucket name\n     * @return the string\n     */\n    private String buildIndexName(String bucketName)\n    {\n        if (bucketName == null)\n        {\n            throw new KunderaException(\"Bucket Name can't be null!\");\n        }\n        return (bucketName + CouchbaseConstants.INDEX_SUFFIX).toLowerCase();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchbase/src/test/java/com/impetus/client/couchbase/crud/CouchbaseCRUDTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchbase.crud;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.couchbase.entities.Person;\n\n/**\n * The Class CouchbaseCRUDTest.\n * \n * @author: devender.yadav\n */\npublic class CouchbaseCRUDTest\n{\n\n    /** The Constant COUCHBASE_PU. */\n    private static final String COUCHBASE_PU = \"couchbase_pu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(COUCHBASE_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test CRUD.\n     */\n    @Test\n    public void testCRUD()\n    {\n        testInsert();\n        testMerge();\n        testDelete();\n    }\n\n    /**\n     * Test insert.\n     */\n    private void testInsert()\n    {\n        Person person = new Person(\"101\", \"dev\", 22, 30000.5);\n        em.persist(person);\n        em.clear();\n        Person p = em.find(Person.class, \"101\");\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"101\", p.getPersonId());\n        Assert.assertEquals(\"dev\", p.getPersonName());\n        Assert.assertEquals(22, p.getAge());\n        Assert.assertEquals(30000.5, p.getSalary());\n    }\n\n    /**\n     * Test merge.\n     */\n    private void testMerge()\n    {\n        Person p = em.find(Person.class, \"101\");\n        p.setPersonName(\"karthik\");\n        em.merge(p);\n        em.clear();\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertNotNull(p1);\n        Assert.assertEquals(\"karthik\", p1.getPersonName());\n    }\n\n    /**\n     * Test delete.\n     */\n    private void testDelete()\n    {\n        Person p = em.find(Person.class, \"101\");\n        Assert.assertNotNull(p);\n        em.remove(p);\n        em.clear();\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertNull(p1);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchbase/src/test/java/com/impetus/client/couchbase/entities/Person.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchbase.entities;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Person.\n * \n * @author: devender.yadav\n */\n@Entity\n@Table(name = \"PERSON\")\npublic class Person\n{\n\n    /** The person id. */\n    @Id\n    private String personId;\n\n    /** The person name. */\n    private String personName;\n\n    /** The age. */\n    private int age;\n\n    /** The salary. */\n    private Double salary;\n\n    /**\n     * Instantiates a new person.\n     */\n    public Person()\n    {\n    }\n\n    /**\n     * Instantiates a new person.\n     * \n     * @param personId\n     *            the person id\n     * @param personName\n     *            the person name\n     * @param age\n     *            the age\n     * @param salary\n     *            the salary\n     */\n    public Person(String personId, String personName, int age, Double salary)\n    {\n        super();\n        this.personId = personId;\n        this.personName = personName;\n        this.age = age;\n        this.salary = salary;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the new age\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the salary.\n     * \n     * @return the salary\n     */\n    public Double getSalary()\n    {\n        return salary;\n    }\n\n    /**\n     * Sets the salary.\n     * \n     * @param salary\n     *            the new salary\n     */\n    public void setSalary(Double salary)\n    {\n        this.salary = salary;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchbase/src/test/java/com/impetus/client/couchbase/query/CouchbaseQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchbase.query;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.couchbase.entities.Person;\n\nimport junit.framework.Assert;\n\n/**\n * The Class CouchbaseQueryTest.\n * \n * @author devender.yadav\n * \n */\npublic class CouchbaseQueryTest\n{\n    /** The Constant COUCHBASE_PU. */\n    private static final String COUCHBASE_PU = \"couchbase_pu\";\n\n    /** The Constant T. */\n    private static final boolean T = true;\n\n    /** The Constant F. */\n    private static final boolean F = false;\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(COUCHBASE_PU);\n        em = emf.createEntityManager();\n        createPersons();\n    }\n\n    /**\n     * Test native select.\n     */\n    @Test\n    public void testNativeSelect()\n    {\n        List list = em.createNativeQuery(\"select * from couchbase_db where kundera_enity = 'PERSON'\").getResultList();\n        Assert.assertEquals(5, list.size());\n\n        list = em.createNativeQuery(\"select * from couchbase_db where kundera_enity = 'PERSON' AND age > 20\")\n                .getResultList();\n        Assert.assertEquals(3, list.size());\n    }\n\n    /**\n     * Test select.\n     */\n    @Test\n    public void testSelect()\n    {\n        Query query = em.createQuery(\"Select p from Person p\");\n        List<Person> results = query.getResultList();\n        Assert.assertEquals(5, results.size());\n        assertResults(results, T, T, T, T, T);\n\n        query = em.createQuery(\"Select p.personName from Person p where p.personId = '103'\");\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Person p = results.get(0);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"pg\", p.getPersonName());\n        Assert.assertEquals(0, p.getAge());\n        Assert.assertNull(p.getPersonId());\n        Assert.assertNull(p.getSalary());\n\n        query = em.createQuery(\"Select p from Person p where p.personId = '103'\");\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        assertResults(results, F, F, T, F, F);\n\n        query = em.createQuery(\"Select p from Person p where p.age > ?1\");\n        query.setParameter(1, 20);\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        assertResults(results, F, F, T, T, T);\n\n        query = em.createQuery(\"Select p from Person p where p.age >= :age\");\n        query.setParameter(\"age\", 20);\n        results = query.getResultList();\n        Assert.assertEquals(4, results.size());\n        assertResults(results, F, T, T, T, T);\n\n        query = em.createQuery(\"Select p from Person p where p.age < 40\");\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        assertResults(results, T, T, T, F, F);\n\n        query = em.createQuery(\"Select p from Person p where p.age <= 40\");\n        results = query.getResultList();\n        Assert.assertEquals(4, results.size());\n        assertResults(results, T, T, T, T, F);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (em != null)\n        {\n            deletePersons();\n            em.close();\n        }\n\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n    /**\n     * Creates the persons.\n     */\n    private static void createPersons()\n    {\n        Person person1 = new Person(\"101\", \"dev\", 10, 10000.1);\n        em.persist(person1);\n        Person person2 = new Person(\"102\", \"karthik\", 20, 20000.2);\n        em.persist(person2);\n        Person person3 = new Person(\"103\", \"pg\", 30, 30000.3);\n        em.persist(person3);\n        Person person4 = new Person(\"104\", \"amit\", 40, 40000.4);\n        em.persist(person4);\n        Person person5 = new Person(\"105\", \"vivek\", 50, 50000.5);\n        em.persist(person5);\n    }\n\n    /**\n     * Delete persons.\n     */\n    private static void deletePersons()\n    {\n        Query query = em.createQuery(\"Select p from Person p\");\n        List<Person> results = query.getResultList();\n        for (Person p : results)\n        {\n            em.remove(p);\n        }\n    }\n\n    /**\n     * Validate person1.\n     *\n     * @param p\n     *            the person\n     */\n    protected void validatePerson1(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"101\", p.getPersonId());\n        Assert.assertEquals(\"dev\", p.getPersonName());\n        Assert.assertEquals(10, p.getAge());\n        Assert.assertEquals(10000.1, p.getSalary());\n    }\n\n    /**\n     * Validate person2.\n     *\n     * @param p\n     *            the person\n     */\n    protected void validatePerson2(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"102\", p.getPersonId());\n        Assert.assertEquals(\"karthik\", p.getPersonName());\n        Assert.assertEquals(20, p.getAge());\n        Assert.assertEquals(20000.2, p.getSalary());\n    }\n\n    /**\n     * Validate person3.\n     *\n     * @param p\n     *            the person\n     */\n    protected void validatePerson3(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"103\", p.getPersonId());\n        Assert.assertEquals(\"pg\", p.getPersonName());\n        Assert.assertEquals(30, p.getAge());\n        Assert.assertEquals(30000.3, p.getSalary());\n    }\n\n    /**\n     * Validate person4.\n     *\n     * @param p\n     *            the person\n     */\n    protected void validatePerson4(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"104\", p.getPersonId());\n        Assert.assertEquals(\"amit\", p.getPersonName());\n        Assert.assertEquals(40, p.getAge());\n        Assert.assertEquals(40000.4, p.getSalary());\n    }\n\n    /**\n     * Validate person5.\n     *\n     * @param p\n     *            the person\n     */\n    protected void validatePerson5(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"105\", p.getPersonId());\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertEquals(50, p.getAge());\n        Assert.assertEquals(50000.5, p.getSalary());\n    }\n\n    /**\n     * Assert results.\n     *\n     * @param results\n     *            the results\n     * @param foundPerson1\n     *            the found person1\n     * @param foundPerson2\n     *            the found person2\n     * @param foundPerson3\n     *            the found person3\n     * @param foundPerson4\n     *            the found person4\n     * @param foundPerson5\n     *            the found person5\n     */\n    protected void assertResults(List<Person> results, boolean foundPerson1, boolean foundPerson2, boolean foundPerson3,\n            boolean foundPerson4, boolean foundPerson5)\n    {\n        for (Person person : results)\n        {\n            switch (person.getPersonId())\n            {\n            case \"101\":\n                if (foundPerson1)\n                    validatePerson1(person);\n                else\n                    Assert.fail();\n                break;\n            case \"102\":\n                if (foundPerson2)\n                    validatePerson2(person);\n                else\n                    Assert.fail();\n                break;\n            case \"103\":\n                if (foundPerson3)\n                    validatePerson3(person);\n                else\n                    Assert.fail();\n                break;\n            case \"104\":\n                if (foundPerson4)\n                    validatePerson4(person);\n                else\n                    Assert.fail();\n                break;\n            case \"105\":\n                if (foundPerson5)\n                    validatePerson5(person);\n                else\n                    Assert.fail();\n                break;\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchbase/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\n\t<persistence-unit name=\"couchbase_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.couchbase.entities.Person</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.client\" value=\"couchbase\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"couchbase_db\" />\n\t\t\t<property name=\"kundera.username\" value=\"root\" />\n\t\t\t<property name=\"kundera.password\" value=\"root\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.couchbase.CouchbaseClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaCouchbaseTest.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\n</persistence>\t"
  },
  {
    "path": "src/kundera-couchbase/src/test/resources/kunderaCouchbaseTest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>couchbase</name>\n\t\t\t<schemas>\n\t\t\t\t<schema>\n\t\t\t\t\t<name>couchbase_db</name>\n\t\t\t\t\t<properties>\n\t\t\t\t\t\t<property name=\"bucket.password\" value=\"\"></property>\n\t\t\t\t\t\t<property name=\"bucket.quota\" value=\"120\"></property>\n\t\t\t\t\t</properties>\n\t\t\t\t</schema>\n\t\t\t</schemas>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>\n\n"
  },
  {
    "path": "src/kundera-couchdb/pom.xml",
    "content": "<?xml version=\"1.0\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<artifactId>kundera</artifactId>\n\t\t<groupId>com.impetus</groupId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-couchdb</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-couchdb</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-elastic-search</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<!-- Apache HttpComponents -->\n\t\t<dependency>\n\t\t\t<groupId>org.apache.httpcomponents</groupId>\n\t\t\t<artifactId>httpclient</artifactId>\n\t\t\t<version>4.2.6</version>\n\t\t</dependency>\n\t\t<!-- Gson -->\n\t\t<dependency>\n\t\t\t<groupId>com.google.code.gson</groupId>\n\t\t\t<artifactId>gson</artifactId>\n\t\t\t<version>2.2.4</version>\n\t\t</dependency>\n\n\n\t\t<dependency>\n\t\t\t<groupId>directory-naming</groupId>\n\t\t\t<artifactId>naming-java</artifactId>\n\t\t\t<version>0.8</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<!-- contiperf dependency should not be here -->\n\n\t\t<dependency>\n\t\t\t<groupId>org.databene</groupId>\n\t\t\t<artifactId>contiperf</artifactId>\n\t\t\t<version>2.2.0</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t</dependencies>\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBClient.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.Reader;\nimport java.io.UnsupportedEncodingException;\nimport java.lang.reflect.Field;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.naming.OperationNotSupportedException;\nimport javax.persistence.metamodel.EmbeddableType;\n\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.HttpStatus;\nimport org.apache.http.client.ClientProtocolException;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpDelete;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.client.methods.HttpPut;\nimport org.apache.http.entity.StringEntity;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.gson.Gson;\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonObject;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.lifecycle.states.RemovedState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.QueryHandlerException;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * CouchDB client.\n * \n * @author Kuldeep Mishra\n * \n */\npublic class CouchDBClient extends ClientBase implements Client<CouchDBQuery>, Batcher, ClientPropertiesSetter\n{\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(CouchDBClient.class);\n\n    /** The gson. */\n    private Gson gson = new Gson();\n\n    /** The http client. */\n    private HttpClient httpClient;\n\n    /** The http host. */\n    private HttpHost httpHost;\n\n    /** The nodes. */\n    private List<Node> nodes = new ArrayList<Node>();\n\n    /** The batch size. */\n    private int batchSize;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /**\n     * Instantiates a new couch db client.\n     * \n     * @param factory\n     *            the factory\n     * @param client\n     *            the client\n     * @param httpHost\n     *            the http host\n     * @param reader\n     *            the reader\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param externalProperties\n     *            the external properties\n     * @param clientMetadata\n     *            the client metadata\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public CouchDBClient(CouchDBClientFactory factory, HttpClient client, HttpHost httpHost, EntityReader reader,\n            String persistenceUnit, Map<String, Object> externalProperties, ClientMetadata clientMetadata,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata, externalProperties, persistenceUnit);\n        this.httpClient = client;\n        this.httpHost = httpHost;\n        this.reader = reader;\n        this.indexManager = factory.getIndexManager();\n        this.clientMetadata = clientMetadata;\n        this.setBatchSize(persistenceUnit, externalProperties);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.Object)\n     */\n    @Override\n    public Object find(Class entityClass, Object key)\n    {\n        HttpResponse response = null;\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n        try\n        {\n            if (key instanceof JsonElement)\n            {\n                key = ((JsonElement) key).getAsString();\n            }\n            String _id = null;\n            if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n            {\n                Field field = (Field) entityMetadata.getIdAttribute().getJavaMember();\n                EmbeddableType embeddableType = metaModel.embeddable(entityMetadata.getIdAttribute()\n                        .getBindableJavaType());\n                _id = CouchDBObjectMapper.get_Id(field, key, embeddableType, entityMetadata.getTableName());\n            }\n            else\n            {\n                _id = entityMetadata.getTableName() + PropertyAccessorHelper.getString(key);\n            }\n\n            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + entityMetadata.getSchema().toLowerCase()\n                            + CouchDBConstants.URL_SEPARATOR + _id, null, null);\n            HttpGet get = new HttpGet(uri);\n            get.addHeader(\"Accept\", \"application/json\");\n            response = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));\n\n            InputStream content = response.getEntity().getContent();\n            Reader reader = new InputStreamReader(content);\n\n            JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);\n\n            // Check for deleted object. if object is deleted then return null.\n            if (jsonObject.get(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()) == null)\n            {\n                return null;\n            }\n\n            return CouchDBObjectMapper.getEntityFromJson(entityClass, entityMetadata, jsonObject,\n                    entityMetadata.getRelationNames(), kunderaMetadata);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while finding object by key {}, Caused by {}.\", key, e);\n            throw new KunderaException(e);\n        }\n        finally\n        {\n            closeContent(response);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.String[], java.lang.Object[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)\n    {\n        List results = new ArrayList();\n        for (Object key : keys)\n        {\n            Object object = find(entityClass, key);\n            if (object != null)\n            {\n                results.add(object);\n            }\n        }\n        return results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    @Override\n    public void close()\n    {\n        externalProperties = null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    public void delete(Object entity, Object pKey)\n    {\n        HttpResponse response = null;\n        try\n        {\n            EntityMetadata entityMetadata = KunderaMetadataManager\n                    .getEntityMetadata(kunderaMetadata, entity.getClass());\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    entityMetadata.getPersistenceUnit());\n            String _id = null;\n            if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n            {\n                Field field = (Field) entityMetadata.getIdAttribute().getJavaMember();\n                EmbeddableType embeddableType = metaModel.embeddable(entityMetadata.getIdAttribute()\n                        .getBindableJavaType());\n                _id = CouchDBObjectMapper.get_Id(field, pKey, embeddableType, entityMetadata.getTableName());\n            }\n            else\n            {\n                _id = entityMetadata.getTableName() + PropertyAccessorHelper.getString(pKey);\n            }\n            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + entityMetadata.getSchema().toLowerCase()\n                            + CouchDBConstants.URL_SEPARATOR + _id, null, null);\n            HttpGet get = new HttpGet(uri);\n            get.addHeader(\"Accept\", \"application/json\");\n            response = httpClient.execute(get);\n\n            Reader reader = new InputStreamReader(response.getEntity().getContent());\n            JsonObject json = gson.fromJson(reader, JsonObject.class);\n            closeContent(response);\n            if (!(response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND))\n            {\n                onDelete(entityMetadata.getSchema(), _id, response, json);\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while deleting object, Caused by {}.\", e);\n            throw new KunderaException(e);\n        }\n        finally\n        {\n            closeContent(response);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera\n     * .persistence.context.jointable.JoinTableData)\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        String joinTableName = joinTableData.getJoinTableName();\n        String joinColumnName = joinTableData.getJoinColumnName();\n        String invJoinColumnName = joinTableData.getInverseJoinColumnName();\n        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();\n\n        for (Object key : joinTableRecords.keySet())\n        {\n            Set<Object> values = joinTableRecords.get(key);\n            Object joinColumnValue = key;\n\n            for (Object childId : values)\n            {\n                Map<String, Object> obj = new HashMap<String, Object>();\n                String id = joinTableName + \"#\" + joinColumnValue.toString() + \"#\" + childId;\n                obj.put(\"_id\", id);\n                obj.put(joinColumnName, joinColumnValue);\n                obj.put(invJoinColumnName, childId);\n                JsonObject object = gson.toJsonTree(obj).getAsJsonObject();\n                HttpResponse response = null;\n                try\n                {\n                    URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                            CouchDBConstants.URL_SEPARATOR + joinTableData.getSchemaName().toLowerCase()\n                                    + CouchDBConstants.URL_SEPARATOR + id, null, null);\n\n                    HttpPut put = new HttpPut(uri);\n                    StringEntity stringEntity = null;\n                    stringEntity = new StringEntity(object.toString(), Constants.CHARSET_UTF8);\n                    stringEntity.setContentType(\"application/json\");\n                    put.setEntity(stringEntity);\n\n                    response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));\n                }\n                catch (Exception e)\n                {\n                    log.error(\"Error while persisting joinTable data, coused by {}.\", e);\n                    throw new KunderaException(e);\n                }\n                finally\n                {\n                    closeContent(response);\n                }\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName,\n            String inverseJoinColumnName, Object pKeyColumnValue, Class columnJavaType)\n    {\n        List<E> foreignKeys = new ArrayList<E>();\n\n        URI uri = null;\n        HttpResponse response = null;\n        try\n        {\n            String q = \"key=\" + CouchDBUtils.appendQuotes(pKeyColumnValue);\n            uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR\n                            + CouchDBConstants.DESIGN + tableName + CouchDBConstants.VIEW + pKeyColumnName, q, null);\n            HttpGet get = new HttpGet(uri);\n            get.addHeader(\"Accept\", \"application/json\");\n            response = httpClient.execute(get);\n\n            InputStream content = response.getEntity().getContent();\n            Reader reader = new InputStreamReader(content);\n            JsonObject json = gson.fromJson(reader, JsonObject.class);\n\n            JsonElement jsonElement = json.get(\"rows\");\n\n            if (jsonElement == null)\n            {\n                return foreignKeys;\n            }\n\n            JsonArray array = jsonElement.getAsJsonArray();\n            for (JsonElement element : array)\n            {\n                JsonElement value = element.getAsJsonObject().get(\"value\").getAsJsonObject().get(inverseJoinColumnName);\n                if (value != null)\n                {\n                    foreignKeys.add((E) PropertyAccessorHelper.fromSourceToTargetClass(columnJavaType, String.class,\n                            value.getAsString()));\n                }\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while fetching column by id {}, Caused by {}.\", pKeyColumnValue, e);\n            throw new KunderaException(e);\n        }\n        finally\n        {\n            closeContent(response);\n        }\n        return foreignKeys;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n        List foreignKeys = new ArrayList();\n        HttpResponse response = null;\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n        try\n        {\n            String q = \"key=\" + CouchDBUtils.appendQuotes(columnValue);\n            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR\n                            + CouchDBConstants.DESIGN + tableName + CouchDBConstants.VIEW + columnName, q, null);\n            HttpGet get = new HttpGet(uri);\n            get.addHeader(\"Accept\", \"application/json\");\n            response = httpClient.execute(get);\n\n            InputStream content = response.getEntity().getContent();\n            Reader reader = new InputStreamReader(content);\n            JsonObject json = gson.fromJson(reader, JsonObject.class);\n\n            JsonElement jsonElement = json.get(\"rows\");\n            if (jsonElement == null)\n            {\n                return foreignKeys.toArray();\n            }\n            JsonArray array = jsonElement.getAsJsonArray();\n            for (JsonElement element : array)\n            {\n                JsonElement value = element.getAsJsonObject().get(\"value\").getAsJsonObject().get(pKeyName);\n                if (value != null)\n                {\n                    foreignKeys.add(PropertyAccessorHelper.fromSourceToTargetClass(m.getIdAttribute()\n                            .getBindableJavaType(), String.class, value.getAsString()));\n                }\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while fetching ids for column where column name is\" + columnName\n                    + \" and column value is {} , Caused by {}.\", columnValue, e);\n            throw new KunderaException(e);\n        }\n        finally\n        {\n            closeContent(response);\n        }\n        return foreignKeys.toArray();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    @Override\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n        URI uri = null;\n        HttpResponse response = null;\n        try\n        {\n            String q = \"key=\" + CouchDBUtils.appendQuotes(columnValue);\n            uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR\n                            + CouchDBConstants.DESIGN + tableName + CouchDBConstants.VIEW + columnName, q, null);\n            HttpGet get = new HttpGet(uri);\n            get.addHeader(\"Accept\", \"application/json\");\n            response = httpClient.execute(get);\n\n            InputStream content = response.getEntity().getContent();\n            Reader reader = new InputStreamReader(content);\n\n            JsonObject json = gson.fromJson(reader, JsonObject.class);\n\n            JsonElement jsonElement = json.get(\"rows\");\n\n            closeContent(response);\n\n            JsonArray array = jsonElement.getAsJsonArray();\n            for (JsonElement element : array)\n            {\n                JsonObject jsonObject = element.getAsJsonObject().get(\"value\").getAsJsonObject();\n\n                JsonElement pkey = jsonObject.get(\"_id\");\n\n                onDelete(schemaName, pkey.getAsString(), response, jsonObject);\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while deleting row by column where column name is \" + columnName\n                    + \" and column value is {}, Caused by {}.\", columnValue, e);\n            throw new KunderaException(e);\n        }\n        finally\n        {\n            closeContent(response);\n        }\n    }\n\n    /**\n     * On delete.\n     * \n     * @param schemaName\n     *            the schema name\n     * @param pKey\n     *            the key\n     * @param response\n     *            the response\n     * @param jsonObject\n     *            the json object\n     * @throws URISyntaxException\n     *             the URI syntax exception\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws ClientProtocolException\n     *             the client protocol exception\n     */\n    private void onDelete(String schemaName, Object pKey, HttpResponse response, JsonObject jsonObject)\n            throws URISyntaxException, IOException, ClientProtocolException\n    {\n        URI uri;\n        String q;\n        JsonElement rev = jsonObject.get(\"_rev\");\n\n        StringBuilder builder = new StringBuilder();\n        builder.append(\"rev=\");\n        builder.append(rev.getAsString());\n        q = builder.toString();\n\n        uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR + pKey, q,\n                null);\n\n        HttpDelete delete = new HttpDelete(uri);\n\n        response = httpClient.execute(delete);\n        closeContent(response);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n        Object[] ids = findIdsByColumn(m.getSchema(), m.getTableName(),\n                ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName(), colName, colValue, m.getEntityClazz());\n        List<Object> resultSet = new ArrayList<Object>();\n        if (ids != null)\n        {\n            for (Object id : new HashSet(Arrays.asList(ids)))\n            {\n                Object object = find(entityClazz, id);\n                if (object != null)\n                {\n                    resultSet.add(object);\n                }\n            }\n        }\n        return resultSet;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<CouchDBQuery> getQueryImplementor()\n    {\n        return CouchDBQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.metadata\n     * .model.EntityMetadata, java.lang.Object, java.lang.Object,\n     * java.util.List)\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n        HttpResponse response = null;\n        try\n        {\n            JsonObject object = CouchDBObjectMapper.getJsonOfEntity(entityMetadata, entity, id, rlHolders,\n                    kunderaMetadata);\n\n            String _id = object.get(\"_id\").getAsString();\n\n            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + entityMetadata.getSchema().toLowerCase()\n                            + CouchDBConstants.URL_SEPARATOR + _id, null, null);\n\n            HttpPut put = new HttpPut(uri);\n\n            StringEntity stringEntity = null;\n\n            if (isUpdate)\n            {\n                HttpGet get = new HttpGet(uri);\n                get.addHeader(\"Accept\", \"application/json\");\n                response = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));\n\n                try\n                {\n                    InputStream content = response.getEntity().getContent();\n                    Reader reader = new InputStreamReader(content);\n                    JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);\n                    JsonElement rev = jsonObject.get(\"_rev\");\n                    object.add(\"_rev\", rev);\n                }\n                finally\n                {\n                    closeContent(response);\n                }\n            }\n            object.addProperty(\"_id\", entityMetadata.getTableName() + id);\n            stringEntity = new StringEntity(object.toString(), Constants.CHARSET_UTF8);\n            stringEntity.setContentType(\"application/json\");\n            put.setEntity(stringEntity);\n\n            response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));\n\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while persisting entity with id {}, caused by {}. \", id, e);\n            throw new KunderaException(e);\n        }\n        finally\n        {\n            closeContent(response);\n        }\n    }\n\n    /**\n     * Close content.\n     * \n     * @param response\n     *            the response\n     */\n    private void closeContent(HttpResponse response)\n    {\n        CouchDBUtils.closeContent(response);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientPropertiesSetter#populateClientProperties\n     * (com.impetus.kundera.client.Client, java.util.Map)\n     */\n    @Override\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        new CouchDbDBClientProperties().populateClientProperties(client, properties);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.api.Batcher#addBatch(com.impetus.kundera\n     * .graph.Node)\n     */\n    @Override\n    public void addBatch(Node node)\n    {\n        if (node != null)\n        {\n            nodes.add(node);\n        }\n        onBatchLimit();\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#executeBatch()\n     */\n    @Override\n    public int executeBatch()\n    {\n        List<JsonObject> objectsToPersist = new ArrayList<JsonObject>();\n        HttpResponse response = null;\n        String databaseName = null;\n        boolean isbulk = false;\n        try\n        {\n            for (Node node : nodes)\n            {\n                if (node.isDirty())\n                {\n                    node.handlePreEvent();\n                    // delete can not be executed in batch\n                    if (node.isInState(RemovedState.class))\n                    {\n                        delete(node.getData(), node.getEntityId());\n                    }\n                    else\n                    {\n                        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                                node.getDataClass());\n                        databaseName = metadata.getSchema();\n                        JsonObject asJsonObject = CouchDBObjectMapper.getJsonOfEntity(metadata, node.getData(),\n                                node.getEntityId(), getRelationHolders(node), kunderaMetadata);\n                        objectsToPersist.add(asJsonObject);\n                        isbulk = true;\n                    }\n                    node.handlePostEvent();\n                }\n            }\n\n            if (isbulk)\n            {\n                try\n                {\n                    URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                            CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase()\n                                    + CouchDBConstants.URL_SEPARATOR + \"_bulk_docs\", null, null);\n\n                    HttpPost post = new HttpPost(uri);\n                    String object = String.format(\"{%s%s}\", \"\\\"all_or_nothing\\\": true,\",\n                            \"\\\"docs\\\": \" + gson.toJson(objectsToPersist));\n                    StringEntity entity = new StringEntity(object, \"UTF-8\");\n                    entity.setContentType(\"application/json\");\n                    post.setEntity(entity);\n                    response = httpClient.execute(httpHost, post, CouchDBUtils.getContext(httpHost));\n                }\n                catch (Exception e)\n                {\n                    log.error(\"Error while executing batch, caused by {}. \", e);\n                    throw new KunderaException(\"Error while executing batch. caused by :\" + e);\n                }\n            }\n        }\n        catch (OperationNotSupportedException e)\n        {\n            throw new KunderaException(e.getMessage());\n        }\n        finally\n        {\n            CouchDBUtils.closeContent(response);\n        }\n\n        return nodes.size();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#getBatchSize()\n     */\n    @Override\n    public int getBatchSize()\n    {\n        return batchSize;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#clear()\n     */\n    @Override\n    public void clear()\n    {\n        if (nodes != null)\n        {\n            nodes.clear();\n            nodes = new ArrayList<Node>();\n        }\n\n    }\n\n    /**\n     * Check on batch limit.\n     */\n    private void onBatchLimit()\n    {\n        if (batchSize > 0 && batchSize == nodes.size())\n        {\n            executeBatch();\n            nodes.clear();\n        }\n    }\n\n    /**\n     * Creates the and execute query.\n     * \n     * @param interpreter\n     *            the interpreter\n     * @return the list\n     */\n    List createAndExecuteQuery(CouchDBQueryInterpreter interpreter)\n    {\n        EntityMetadata m = interpreter.getMetadata();\n        List results = new ArrayList();\n        try\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n            StringBuilder q = new StringBuilder();\n            String _id = CouchDBConstants.URL_SEPARATOR + m.getSchema().toLowerCase() + CouchDBConstants.URL_SEPARATOR\n                    + CouchDBConstants.DESIGN + m.getTableName() + CouchDBConstants.VIEW;\n            if ((interpreter.isIdQuery() && !interpreter.isRangeQuery() && interpreter.getOperator() == null)\n                    || interpreter.isQueryOnCompositeKey())\n            {\n                Object object = null;\n                if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n                {\n                    EmbeddableType embeddableType = metaModel.embeddable(m.getIdAttribute().getBindableJavaType());\n                    if (KunderaCoreUtils.countNonSyntheticFields(m.getIdAttribute().getBindableJavaType()) == interpreter\n                            .getKeyValues().size())\n                    {\n                        Object key = CouchDBObjectMapper.getObjectFromJson(gson.toJsonTree(interpreter.getKeyValues())\n                                .getAsJsonObject(), m.getIdAttribute().getBindableJavaType(), embeddableType\n                                .getAttributes());\n                        object = find(m.getEntityClazz(), key);\n                        if (object != null)\n                        {\n                            results.add(object);\n                        }\n                        return results;\n                    }\n                    else if (m.getIdAttribute().getName().equals(interpreter.getKeyName())\n                            && interpreter.getKeyValues().size() == 1)\n                    {\n                        object = find(m.getEntityClazz(), interpreter.getKeyValue());\n                        if (object != null)\n                        {\n                            results.add(object);\n                        }\n                        return results;\n                    }\n                    else\n                    {\n                        log.error(\"There should be each and every field of composite key.\");\n                        throw new QueryHandlerException(\"There should be each and every field of composite key.\");\n                    }\n                }\n                object = find(m.getEntityClazz(), interpreter.getKeyValue());\n                if (object != null)\n                {\n                    results.add(object);\n                }\n                return results;\n            }\n\n            // creating query.\n            _id = createQuery(interpreter, m, q, _id);\n\n            if (interpreter.getLimit() > 0)\n            {\n                q.append(\"&limit=\" + interpreter.getLimit());\n            }\n            if (interpreter.isDescending())\n            {\n                q.append(\"&descending=\" + false);\n            }\n\n            // execute query.\n            executeQueryAndGetResults(q, _id, m, results, interpreter);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while executing query, Caused by {}.\", e);\n            throw new KunderaException(e);\n        }\n        return results;\n    }\n\n    /**\n     * Execute query and get results.\n     * \n     * @param q\n     *            the q\n     * @param _id\n     *            the _id\n     * @param m\n     *            the m\n     * @param results\n     *            the results\n     * @param interpreter\n     *            the interpreter\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws URISyntaxException\n     *             the URI syntax exception\n     * @throws ClientProtocolException\n     *             the client protocol exception\n     */\n    void executeQueryAndGetResults(StringBuilder q, String _id, EntityMetadata m, List results,\n            CouchDBQueryInterpreter interpreter) throws IOException, URISyntaxException, ClientProtocolException\n    {\n        HttpResponse response = null;\n        try\n        {\n            response = getResponse(q, _id);\n            JsonArray array = getJsonFromResponse(response);\n            if (interpreter != null && interpreter.isAggregation())\n            {\n                setAggregatedValuesInResult(results, interpreter, array);\n            }\n            else if (interpreter != null && interpreter.getColumns() != null && interpreter.getColumns().length != 0)\n            {\n                setSpecificFieldsInResult(interpreter.getColumnsToOutput(), m, results, array);\n            }\n            else\n            {\n                setEntitiesInResult(m, results, array);\n            }\n        }\n        finally\n        {\n            CouchDBUtils.closeContent(response);\n        }\n    }\n\n    /**\n     * Sets the aggregated values in result.\n     * \n     * @param results\n     *            the results\n     * @param interpreter\n     *            the interpreter\n     * @param array\n     *            the array\n     */\n    private void setAggregatedValuesInResult(List results, CouchDBQueryInterpreter interpreter, JsonArray array)\n    {\n        for (JsonElement json : array)\n        {\n            JsonElement value = json.getAsJsonObject().get(\"value\");\n            if (interpreter.getAggregationType().equals(CouchDBConstants.COUNT))\n                results.add(value.getAsInt());\n            else\n                results.add(value.getAsDouble());\n        }\n    }\n\n    /**\n     * Sets the specific fields in result.\n     * \n     * @param columnsToOutput\n     *            the columns to output\n     * @param m\n     *            the m\n     * @param results\n     *            the results\n     * @param array\n     *            the array\n     */\n    private void setSpecificFieldsInResult(List<Map<String, Object>> columnsToOutput, EntityMetadata m, List results,\n            JsonArray array)\n    {\n        Map<String, Class> colNameToJavaType = new HashMap<String, Class>();\n        for (Map<String, Object> map : columnsToOutput)\n        {\n            colNameToJavaType.put((String) map.get(Constants.COL_NAME), (Class) map.get(Constants.FIELD_CLAZZ));\n        }\n        Map<String, List<Object>> outputResults = new HashMap<String, List<Object>>();\n        for (JsonElement element : array)\n        {\n            String column = element.getAsJsonObject().get(\"key\").getAsString();\n            String value = element.getAsJsonObject().get(\"value\").getAsString();\n            String id = element.getAsJsonObject().get(\"id\").getAsString();\n            Object obj = PropertyAccessorHelper.fromSourceToTargetClass(colNameToJavaType.get(column), String.class,\n                    value);\n            if (colNameToJavaType.size() > 1)\n            {\n                if (!outputResults.containsKey(id))\n                {\n                    outputResults.put(id, new ArrayList<Object>());\n                }\n                outputResults.get(id).add(obj);\n            }\n            else\n            {\n                results.add(obj);\n            }\n        }\n        if (colNameToJavaType.size() > 1)\n        {\n            results.addAll(outputResults.values());\n        }\n    }\n\n    /**\n     * Sets the entities in result.\n     * \n     * @param m\n     *            the m\n     * @param results\n     *            the results\n     * @param array\n     *            the array\n     */\n    private void setEntitiesInResult(EntityMetadata m, List results, JsonArray array)\n    {\n        for (JsonElement element : array)\n        {\n\n            String id = element.getAsJsonObject().get(\"value\").getAsJsonObject()\n                    .get(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName()).getAsString();\n            Object entityFromJson = CouchDBObjectMapper.getEntityFromJson(m.getEntityClazz(), m, element\n                    .getAsJsonObject().get(\"value\").getAsJsonObject(), m.getRelationNames(), kunderaMetadata);\n            if (entityFromJson != null\n                    && (m.getTableName().concat(id)).equals(element.getAsJsonObject().get(\"id\").getAsString()))\n            {\n                results.add(entityFromJson);\n            }\n\n        }\n    }\n\n    /**\n     * Gets the json from response.\n     * \n     * @param response\n     *            the response\n     * @return the json from response\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    private JsonArray getJsonFromResponse(HttpResponse response) throws IOException\n    {\n        InputStream content = response.getEntity().getContent();\n        Reader reader = new InputStreamReader(content);\n        JsonObject json = gson.fromJson(reader, JsonObject.class);\n        JsonElement jsonElement = json.get(\"rows\");\n        return jsonElement == null ? null : jsonElement.getAsJsonArray();\n    }\n\n    /**\n     * Gets the response.\n     * \n     * @param q\n     *            the q\n     * @param _id\n     *            the _id\n     * @return the response\n     * @throws URISyntaxException\n     *             the URI syntax exception\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws ClientProtocolException\n     *             the client protocol exception\n     */\n    private HttpResponse getResponse(StringBuilder q, String _id) throws URISyntaxException, IOException,\n            ClientProtocolException\n    {\n        URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(), _id,\n                q.toString(), null);\n        HttpGet get = new HttpGet(uri);\n        get.addHeader(\"Accept\", \"application/json\");\n        return httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));\n    }\n\n    /**\n     * Creates the query.\n     * \n     * @param interpreter\n     *            the interpreter\n     * @param m\n     *            the m\n     * @param q\n     *            the q\n     * @param _id\n     *            the _id\n     * @return the string\n     * @throws URISyntaxException\n     *             the URI syntax exception\n     * @throws UnsupportedEncodingException\n     *             the unsupported encoding exception\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws ClientProtocolException\n     *             the client protocol exception\n     */\n    String createQuery(CouchDBQueryInterpreter interpreter, EntityMetadata m, StringBuilder q, String _id)\n            throws URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException\n    {\n        if (interpreter.isAggregation())\n        {\n            _id = CouchDBConstants.URL_SEPARATOR + m.getSchema().toLowerCase() + CouchDBConstants.URL_SEPARATOR\n                    + CouchDBConstants.DESIGN + CouchDBConstants.AGGREGATIONS + CouchDBConstants.VIEW\n                    + interpreter.getAggregationType();\n            if (interpreter.getAggregationColumn() != null)\n            {\n                q.append(\"key=\");\n                q.append(\"\\\"\" + interpreter.getAggregationColumn() + \"_\" + m.getTableName() + \"\\\"\");\n\n            }\n            else\n            {\n                q.append(\"key=\" + \"\\\"\" + CouchDBConstants.ALL + \"_\" + m.getTableName() + \"\\\"\");\n            }\n            q.append(\"&group=true\");\n        }\n        else if (!interpreter.isRangeQuery() && interpreter.getOperator() != null\n                && interpreter.getOperator().equalsIgnoreCase(\"AND\"))\n        {\n            StringBuilder viewName = new StringBuilder();\n            List<String> columns = new ArrayList<String>();\n            q.append(\"key=[\");\n            for (String columnName : interpreter.getKeyValues().keySet())\n            {\n                viewName.append(columnName + \"AND\");\n                q.append(CouchDBUtils.appendQuotes(interpreter.getKeyValues().get(columnName)));\n                q.append(\",\");\n                columns.add(columnName);\n            }\n            q.deleteCharAt(q.toString().lastIndexOf(\",\"));\n            q.append(\"]\");\n            viewName.delete(viewName.toString().lastIndexOf(\"AND\"), viewName.toString().lastIndexOf(\"AND\") + 3);\n            _id = _id + viewName.toString();\n            CouchDBUtils.createDesignDocumentIfNotExist(httpClient, httpHost, gson, m.getTableName(), m.getSchema(),\n                    viewName.toString(), columns);\n        }\n        else if (interpreter.getKeyValues() != null)\n        {\n            if (interpreter.getStartKeyValue() != null || interpreter.getEndKeyValue() != null)\n            {\n                String queryString = null;\n                if (interpreter.getStartKeyValue() != null)\n                {\n                    queryString = \"startkey=\" + CouchDBUtils.appendQuotes(interpreter.getStartKeyValue());\n                    q.append(queryString);\n                }\n                if (interpreter.getEndKeyValue() != null)\n                {\n                    if (interpreter.getStartKeyValue() != null)\n                    {\n                        q.append(\"&\");\n                    }\n                    queryString = \"endkey=\" + CouchDBUtils.appendQuotes(interpreter.getEndKeyValue());\n                    q.append(queryString);\n                    if (interpreter.isIncludeLastKey())\n                    {\n                        q.append(\"&inclusive_end=\");\n                        q.append(true);\n                    }\n                }\n            }\n            else if (interpreter.getKeyValue() != null)\n            {\n                q.append(\"key=\" + CouchDBUtils.appendQuotes(interpreter.getKeyValue()));\n            }\n            _id = _id + interpreter.getKeyName();\n        }\n        else if (interpreter.getColumns() != null && interpreter.getColumns().length != 0)\n        {\n            _id += CouchDBConstants.FIELDS;\n            q.append(\"keys=[\");\n            for (String column : interpreter.getColumns())\n            {\n                q.append(\"\\\"\" + column + \"\\\",\");\n            }\n            q.setCharAt(q.length() - 1, ']');\n        }\n        else\n        {\n            _id = _id + \"all\";\n        }\n\n        return _id;\n    }\n\n    /**\n     * Sets the batch size.\n     * \n     * @param persistenceUnit\n     *            the persistence unit\n     * @param puProperties\n     *            the pu properties\n     */\n    private void setBatchSize(String persistenceUnit, Map<String, Object> puProperties)\n    {\n        String batch_Size = puProperties != null ? (String) puProperties.get(PersistenceProperties.KUNDERA_BATCH_SIZE)\n                : null;\n        if (batch_Size != null)\n        {\n            setBatchSize(Integer.valueOf(batch_Size));\n        }\n        else\n        {\n            PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\n                    persistenceUnit);\n            setBatchSize(puMetadata.getBatchSize());\n        }\n    }\n\n    /**\n     * Sets the batch size.\n     * \n     * @param batch_Size\n     *            the new batch size\n     */\n    void setBatchSize(int batch_Size)\n    {\n        this.batchSize = batch_Size;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        return (Generator) KunderaCoreUtils.createNewInstance(CouchDBIdGenerator.class);\n    }\n}"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBClientFactory.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpRequest;\nimport org.apache.http.HttpRequestInterceptor;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.HttpResponseInterceptor;\nimport org.apache.http.RequestLine;\nimport org.apache.http.auth.AuthScope;\nimport org.apache.http.auth.UsernamePasswordCredentials;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.conn.scheme.PlainSocketFactory;\nimport org.apache.http.conn.scheme.Scheme;\nimport org.apache.http.conn.scheme.SchemeRegistry;\nimport org.apache.http.conn.scheme.SchemeSocketFactory;\nimport org.apache.http.impl.client.AbstractHttpClient;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport org.apache.http.impl.conn.PoolingClientConnectionManager;\nimport org.apache.http.params.CoreProtocolPNames;\nimport org.apache.http.protocol.HttpContext;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * CouchDB client factory.\n * \n * @author Kuldeep Mishra\n * \n */\npublic class CouchDBClientFactory extends GenericClientFactory\n{\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(CouchDBClientFactory.class);\n\n    /** The http client. */\n    private HttpClient httpClient;\n\n    /** The http host. */\n    private HttpHost httpHost;\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.ClientFactory#getSchemaManager(java.util.Map)\n     */\n    @Override\n    public SchemaManager getSchemaManager(Map<String, Object> puProperties)\n    {\n        setExternalProperties(puProperties);\n        if (schemaManager == null)\n        {\n            initializePropertyReader();\n            schemaManager = new CouchDBSchemaManager(this.getClass().getName(), puProperties, this.kunderaMetadata);\n        }\n        return schemaManager;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.ClientLifeCycleManager#destroy()\n     */\n    @Override\n    public void destroy()\n    {\n        if (indexManager != null)\n        {\n            indexManager.close();\n        }\n        if (schemaManager != null)\n        {\n            schemaManager.dropSchema();\n        }\n        schemaManager = null;\n        externalProperties = null;\n        httpClient.getConnectionManager().shutdown();\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initialize(java.util.Map)\n     */\n    @Override\n    public void initialize(Map<String, Object> externalProperty)\n    {\n        reader = new CouchDBEntityReader(kunderaMetadata);\n        initializePropertyReader();\n        setExternalProperties(externalProperty);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#createPoolOrConnection()\n     */\n    @Override\n    protected Object createPoolOrConnection()\n    {\n        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(\n                getPersistenceUnit());\n\n        Properties props = puMetadata.getProperties();\n        String contactNode = null;\n        String defaultPort = null;\n        String keyspace = null;\n        String poolSize = null;\n        String userName = null;\n        String password = null;\n        String maxConnections = null;\n        if (externalProperties != null)\n        {\n            contactNode = (String) externalProperties.get(PersistenceProperties.KUNDERA_NODES);\n            defaultPort = (String) externalProperties.get(PersistenceProperties.KUNDERA_PORT);\n            keyspace = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);\n            poolSize = (String) externalProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE);\n            userName = (String) externalProperties.get(PersistenceProperties.KUNDERA_USERNAME);\n            password = (String) externalProperties.get(PersistenceProperties.KUNDERA_PASSWORD);\n            maxConnections = (String) externalProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_TOTAL);\n        }\n        if (contactNode == null)\n        {\n            contactNode = (String) props.get(PersistenceProperties.KUNDERA_NODES);\n        }\n        if (defaultPort == null)\n        {\n            defaultPort = (String) props.get(PersistenceProperties.KUNDERA_PORT);\n        }\n        if (keyspace == null)\n        {\n            keyspace = (String) props.get(PersistenceProperties.KUNDERA_KEYSPACE);\n        }\n        if (poolSize == null)\n        {\n            poolSize = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE);\n        }\n        if (userName == null)\n        {\n            userName = props.getProperty(PersistenceProperties.KUNDERA_USERNAME);\n            password = props.getProperty(PersistenceProperties.KUNDERA_PASSWORD);\n        }\n\n        onValidation(contactNode, defaultPort);\n        try\n        {\n            SchemeSocketFactory ssf = null;\n            ssf = PlainSocketFactory.getSocketFactory();\n            SchemeRegistry schemeRegistry = new SchemeRegistry();\n            schemeRegistry.register(new Scheme(CouchDBConstants.PROTOCOL, Integer.parseInt(defaultPort), ssf));\n            PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);\n            httpClient = new DefaultHttpClient(ccm);\n            httpHost = new HttpHost(contactNode, Integer.parseInt(defaultPort), CouchDBConstants.PROTOCOL);\n            httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, \"UTF-8\");\n            // httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,\n            // props.getSocketTimeout());\n\n            // httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,\n            // props.getConnectionTimeout());\n            if (!StringUtils.isBlank(maxConnections))\n            {\n                ccm.setMaxTotal(Integer.parseInt(maxConnections));\n                ccm.setDefaultMaxPerRoute(Integer.parseInt(maxConnections));\n            }\n            // basic authentication\n            if (userName != null && password != null)\n            {\n                ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(\n                        new AuthScope(contactNode, Integer.parseInt(defaultPort)),\n                        new UsernamePasswordCredentials(userName, password));\n            }\n            // request interceptor\n            ((DefaultHttpClient) httpClient).addRequestInterceptor(new HttpRequestInterceptor()\n            {\n                public void process(final HttpRequest request, final HttpContext context) throws IOException\n                {\n                    if (logger.isInfoEnabled())\n                    {\n                        RequestLine requestLine = request.getRequestLine();\n                        logger.info(\">> \" + requestLine.getMethod() + \" \" + URI.create(requestLine.getUri()).getPath());\n                    }\n                }\n            });\n            // response interceptor\n            ((DefaultHttpClient) httpClient).addResponseInterceptor(new HttpResponseInterceptor()\n            {\n                public void process(final HttpResponse response, final HttpContext context) throws IOException\n                {\n                    if (logger.isInfoEnabled())\n                        logger.info(\"<< Status: \" + response.getStatusLine().getStatusCode());\n                }\n            });\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Error Creating HTTP client, caoused by {}. \", e);\n            throw new IllegalStateException(e);\n        }\n        return httpClient;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#instantiateClient(java\n     * .lang.String)\n     */\n    @Override\n    protected Client instantiateClient(String persistenceUnit)\n    {\n        return new CouchDBClient(this, httpClient, httpHost, reader, persistenceUnit, externalProperties,\n                clientMetadata, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.GenericClientFactory#isThreadSafe()\n     */\n    @Override\n    public boolean isThreadSafe()\n    {\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initializeLoadBalancer\n     * (java.lang.String)\n     */\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n        throw new UnsupportedOperationException(\"Load balancing feature is not supported in \"\n                + this.getClass().getSimpleName());\n    }\n\n    /**\n     * Initialize property reader.\n     */\n    private void initializePropertyReader()\n    {\n        if (propertyReader == null)\n        {\n            propertyReader = new CouchDBPropertyReader(externalProperties, kunderaMetadata.getApplicationMetadata()\n                    .getPersistenceUnitMetadata(getPersistenceUnit()));\n            propertyReader.read(getPersistenceUnit());\n        }\n    }\n\n    /**\n     * Gets the index manager.\n     * \n     * @return the index manager\n     */\n    public IndexManager getIndexManager()\n    {\n        return indexManager;\n    }\n}"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBConstants.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb;\n\n/**\n * Constant Class for CouchDB.\n * \n * @author Kuldeep Mishra\n * \n */\npublic interface CouchDBConstants\n{\n\n    /** The Constant PROTOCOL. */\n    public static final String PROTOCOL = \"http\";\n\n    /** The Constant URL_SEPARATOR. */\n    public static final String URL_SEPARATOR = \"/\";\n\n    /** The Constant DESIGN. */\n    public static final String DESIGN = \"_design\" + URL_SEPARATOR;\n\n    /** The Constant VIEW. */\n    public static final String VIEW = URL_SEPARATOR + \"_view\" + URL_SEPARATOR;\n\n    /** The Constant LANGUAGE. */\n    public static final String LANGUAGE = \"javascript\";\n\n    /** The Constant LINE_SEP. */\n    public static final String LINE_SEP = System.getProperty(\"line.separator\");\n\n    /** The Constant FIELDS. */\n    public static final String FIELDS = \"fields\";\n\n    /** The Constant COUNT. */\n    public static final String COUNT = \"count\";\n\n    /** The Constant ALL. */\n    public static final String ALL = \"ALL\";\n\n    /** The Constant SUM. */\n    public static final String SUM = \"sum\";\n\n    /** The Constant MAX. */\n    public static final String MAX = \"max\";\n\n    /** The Constant MIN. */\n    public static final String MIN = \"min\";\n\n    /** The Constant AVG. */\n    public static final String AVG = \"avg\";\n\n    /** The Constant ENTITYNAME. */\n    public static final String ENTITYNAME = \"ENTITYNAME\";\n\n    /** The Constant AGGREGATIONS. */\n    public static final String AGGREGATIONS = \"aggregations\";\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBDesignDocument.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb;\n\nimport java.util.Map;\n\n/**\n * Design document.\n * \n * \n * @author Kuldeep Mishra\n */\npublic class CouchDBDesignDocument\n{\n\n    /** The _rev. */\n    private String _rev;\n\n    /** The language. */\n    private String language;\n\n    /** The views. */\n    private Map<String, MapReduce> views;\n\n    /**\n     * Gets the language.\n     * \n     * @return the language\n     */\n    public String getLanguage()\n    {\n        return language;\n    }\n\n    /**\n     * Gets the views.\n     * \n     * @return the views\n     */\n    public Map<String, MapReduce> getViews()\n    {\n        return views;\n    }\n\n    /**\n     * Sets the language.\n     * \n     * @param language\n     *            the new language\n     */\n    public void setLanguage(String language)\n    {\n        this.language = language;\n    }\n\n    /**\n     * Sets the views.\n     * \n     * @param views\n     *            the views\n     */\n    public void setViews(Map<String, MapReduce> views)\n    {\n        this.views = views;\n    }\n\n    /**\n     * Gets the _rev.\n     * \n     * @return the _rev\n     */\n    public String get_rev()\n    {\n        return _rev;\n    }\n\n    /**\n     * Sets the _rev.\n     * \n     * @param _rev\n     *            the new _rev\n     */\n    public void set_rev(String _rev)\n    {\n        this._rev = _rev;\n    }\n\n    /**\n     * Holds Map Reduce functions.\n     * \n     * @author Kuldeep Mishra\n     */\n    public static class MapReduce\n    {\n\n        /** The map. */\n        private String map;\n\n        /** The reduce. */\n        private String reduce;\n\n        /**\n         * Gets the map.\n         * \n         * @return the map\n         */\n        public String getMap()\n        {\n            return map;\n        }\n\n        /**\n         * Gets the reduce.\n         * \n         * @return the reduce\n         */\n        public String getReduce()\n        {\n            return reduce;\n        }\n\n        /**\n         * Sets the map.\n         * \n         * @param map\n         *            the new map\n         */\n        public void setMap(String map)\n        {\n            this.map = map;\n        }\n\n        /**\n         * Sets the reduce.\n         * \n         * @param reduce\n         *            the new reduce\n         */\n        public void setReduce(String reduce)\n        {\n            this.reduce = reduce;\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBEntityReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb;\n\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * CouchDBEntity Reader.\n * \n * @author Kuldeep Mishra\n * \n */\npublic class CouchDBEntityReader extends AbstractEntityReader implements EntityReader\n{\n\n    /**\n     * Instantiates a new couch db entity reader.\n     * \n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public CouchDBEntityReader(final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    /**\n     * Instantiates a new couch db entity reader.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public CouchDBEntityReader(KunderaQuery kunderaQuery, final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n        this.kunderaQuery = kunderaQuery;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#populateRelation(com.impetus\n     * .kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        // TODO Auto-generated method stub\n        throw new UnsupportedOperationException(\"Method supported not required for Redis\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#findById(java.lang.String,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.util.List,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        return super.findById(primaryKey, m, client);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBIdGenerator.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb;\n\nimport java.util.UUID;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.generator.AutoGenerator;\n\n/**\n * The Class CouchDBIdGenerator.\n * \n * @author: karthikp.manchala\n */\npublic class CouchDBIdGenerator implements AutoGenerator\n{\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.AutoGenerator#generate(com.impetus.kundera\n     * .client.Client, java.lang.Object)\n     */\n    @Override\n    public Object generate(Client<?> client, String dataType)\n    {\n        // Need to generate using couchdb.\n        return UUID.randomUUID().toString();\n    }\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBObjectMapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb;\n\nimport java.lang.reflect.Field;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.naming.OperationNotSupportedException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonNull;\nimport com.google.gson.JsonObject;\nimport com.google.gson.JsonPrimitive;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * Object mapper for json.\n * \n * @author Kuldeep Mishra\n */\npublic class CouchDBObjectMapper\n{\n\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(CouchDBObjectMapper.class);\n\n    /**\n     * Gets the json of entity.\n     * \n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param id\n     *            the id\n     * @param relations\n     *            the relations\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @return the json of entity\n     * @throws OperationNotSupportedException\n     *             the operation not supported exception\n     */\n    static JsonObject getJsonOfEntity(EntityMetadata m, Object entity, Object id, List<RelationHolder> relations,\n            final KunderaMetadata kunderaMetadata) throws OperationNotSupportedException\n    {\n        JsonObject jsonObject = new JsonObject();\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n        // Add discriminator column and value.\n        String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n        String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();\n\n        if (discrValue != null)\n        {\n            jsonObject.add(discrColumn, getJsonPrimitive(discrValue, discrValue.getClass()));\n        }\n\n        // Populate id attribute.\n        SingularAttribute idAttribute = m.getIdAttribute();\n        if (metaModel.isEmbeddable(idAttribute.getBindableJavaType()))\n        {\n            Field field = (Field) idAttribute.getJavaMember();\n            EmbeddableType embeddableType = metaModel.embeddable(idAttribute.getBindableJavaType());\n            String _id = get_Id(field, PropertyAccessorHelper.getObject(entity, field), embeddableType,\n                    m.getTableName());\n            jsonObject.addProperty(\"_id\", _id);\n            Object embeddedObject = PropertyAccessorHelper.getObject(entity, (Field) idAttribute.getJavaMember());\n            Set<Attribute> embeddableAttributes = embeddableType.getAttributes();\n\n            jsonObject.add(((AbstractAttribute) idAttribute).getJPAColumnName(),\n                    getJsonObject(field.getType().getDeclaredFields(), embeddableType, embeddedObject));\n        }\n        else\n        {\n            jsonObject.addProperty(\"_id\", m.getTableName() + PropertyAccessorHelper.getString(id));\n            jsonObject.add(((AbstractAttribute) idAttribute).getJPAColumnName(),\n                    getJsonPrimitive(id, idAttribute.getJavaType()));\n        }\n        // Populate columns\n        Set<Attribute> columns = entityType.getAttributes();\n        for (Attribute column : columns)\n        {\n            if (!column.equals(idAttribute))\n            {\n                try\n                {\n                    Class javaType = ((AbstractAttribute) column).getBindableJavaType();\n                    if (metaModel.isEmbeddable(javaType))\n                    {\n                        onEmbeddable(entityType, column, entity, metaModel.embeddable(javaType), jsonObject);\n                    }\n                    else if (!column.isAssociation())\n                    {\n                        Object valueObject = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());\n                        jsonObject.add(((AbstractAttribute) column).getJPAColumnName(),\n                                getJsonPrimitive(valueObject, column.getJavaType()));\n                    }\n                }\n                catch (PropertyAccessException paex)\n                {\n                    log.error(\"Can't access property {}.\", column.getName());\n                    throw new PropertyAccessException(paex);\n                }\n            }\n        }\n        if (relations != null)\n        {\n            for (RelationHolder rh : relations)\n            {\n                jsonObject.add(rh.getRelationName(),\n                        getJsonPrimitive(rh.getRelationValue(), rh.getRelationValue().getClass()));\n            }\n        }\n        jsonObject.add(CouchDBConstants.ENTITYNAME, new JsonPrimitive(m.getTableName()));\n        return jsonObject;\n    }\n\n    /**\n     * On embeddable.\n     * \n     * @param entityType\n     *            the entity type\n     * @param column\n     *            the column\n     * @param entity\n     *            the entity\n     * @param embeddableType\n     *            the embeddable type\n     * @param jsonObject\n     *            the json object\n     */\n    private static void onEmbeddable(EntityType entityType, Attribute column, Object entity,\n            EmbeddableType embeddableType, JsonObject jsonObject)\n    {\n        Object embeddedObject = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());\n        String embeddedColumnName = ((AbstractAttribute) column).getJPAColumnName();\n        Set<Attribute> embeddableAttributes = embeddableType.getAttributes();\n        jsonObject.add(embeddedColumnName, getJsonObject(embeddableAttributes, embeddedObject));\n    }\n\n    /**\n     * Gets the json object.\n     * \n     * @param columns\n     *            the columns\n     * @param object\n     *            the object\n     * @return the json object\n     */\n    private static JsonObject getJsonObject(Set<Attribute> columns, Object object)\n    {\n        JsonObject jsonObject = new JsonObject();\n        for (Attribute column : columns)\n        {\n            if (!column.isAssociation())\n            {\n                Object valueObject = PropertyAccessorHelper.getObject(object, (Field) column.getJavaMember());\n                jsonObject.add(((AbstractAttribute) column).getJPAColumnName(),\n                        getJsonPrimitive(valueObject, column.getJavaType()));\n            }\n        }\n        return jsonObject;\n    }\n\n    /**\n     * Gets the json object.\n     * \n     * @param declaredFields\n     *            the declared fields\n     * @param embeddableType\n     *            the embeddable type\n     * @param embeddedObject\n     *            the embedded object\n     * @return the json object\n     */\n    private static JsonElement getJsonObject(Field[] declaredFields, EmbeddableType embeddableType,\n            Object embeddedObject)\n    {\n        JsonObject jsonObject = new JsonObject();\n        for (Field field : declaredFields)\n        {\n\n            if (!ReflectUtils.isTransientOrStatic(field)\n                    && !embeddableType.getAttribute(field.getName()).isAssociation())\n            {\n                Object valueObject = PropertyAccessorHelper.getObject(embeddedObject, field);\n                jsonObject.add(((AbstractAttribute) (embeddableType.getAttribute(field.getName()))).getJPAColumnName(),\n                        getJsonPrimitive(valueObject, embeddableType.getAttribute(field.getName()).getJavaType()));\n            }\n        }\n        return jsonObject;\n    }\n\n    /**\n     * Gets the entity from json.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param m\n     *            the m\n     * @param jsonObj\n     *            the json obj\n     * @param relations\n     *            the relations\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @return the entity from json\n     */\n    static Object getEntityFromJson(Class<?> entityClass, EntityMetadata m, JsonObject jsonObj, List<String> relations,\n            final KunderaMetadata kunderaMetadata)\n    {// Entity object\n        Object entity = null;\n\n        // Map to hold property-name=>foreign-entity relations\n        try\n        {\n            entity = KunderaCoreUtils.createNewInstance(entityClass);\n\n            // Populate primary key column\n            JsonElement rowKey = jsonObj.get(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName());\n            if (rowKey == null)\n            {\n                return null;\n            }\n            Class<?> idClass = null;\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n            Map<String, Object> relationValue = null;\n            idClass = m.getIdAttribute().getJavaType();\n            if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n            {\n                Class javaType = m.getIdAttribute().getBindableJavaType();\n                PropertyAccessorHelper.setId(\n                        entity,\n                        m,\n                        getObjectFromJson(rowKey.getAsJsonObject(), javaType, metaModel.embeddable(javaType)\n                                .getAttributes()));\n            }\n            else\n            {\n                PropertyAccessorHelper.setId(entity, m,\n                        PropertyAccessorHelper.fromSourceToTargetClass(idClass, String.class, rowKey.getAsString()));\n            }\n\n            EntityType entityType = metaModel.entity(entityClass);\n\n            String discriminatorColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n\n            Set<Attribute> columns = entityType.getAttributes();\n\n            for (Attribute column : columns)\n            {\n                JsonElement value = jsonObj.get(((AbstractAttribute) column).getJPAColumnName());\n                if (!column.equals(m.getIdAttribute())\n                        && !((AbstractAttribute) column).getJPAColumnName().equals(discriminatorColumn)\n                        && value != null && !value.equals(JsonNull.INSTANCE))\n                {\n                    String fieldName = ((AbstractAttribute) column).getJPAColumnName();\n\n                    Class javaType = ((AbstractAttribute) column).getBindableJavaType();\n                    if (metaModel.isEmbeddable(javaType))\n                    {\n                        onViaEmbeddable(entityType, column, m, entity, metaModel.embeddable(javaType), jsonObj);\n                    }\n                    else if (!column.isAssociation())\n                    {\n                        setFieldValue(entity, column, value);\n                    }\n                    else if (relations != null)\n                    {\n                        if (relationValue == null)\n                        {\n                            relationValue = new HashMap<String, Object>();\n                        }\n\n                        if (relations.contains(fieldName)\n                                && !fieldName.equals(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName()))\n                        {\n                            JsonElement colValue = jsonObj.get(((AbstractAttribute) column).getJPAColumnName());\n                            if (colValue != null)\n                            {\n                                String colFieldName = m.getFieldName(fieldName);\n                                Attribute attribute = entityType.getAttribute(colFieldName);\n                                EntityMetadata relationMetadata = KunderaMetadataManager.getEntityMetadata(\n                                        kunderaMetadata, attribute.getJavaType());\n                                Object colVal = PropertyAccessorHelper.fromSourceToTargetClass(relationMetadata\n                                        .getIdAttribute().getJavaType(), String.class, colValue.getAsString());\n                                relationValue.put(fieldName, colVal);\n                            }\n                        }\n                    }\n                }\n            }\n            if (relationValue != null && !relationValue.isEmpty())\n            {\n                EnhanceEntity e = new EnhanceEntity(entity, PropertyAccessorHelper.getId(entity, m), relationValue);\n                return e;\n            }\n            else\n            {\n                return entity;\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while extracting entity object from json, caused by {}.\", e);\n            throw new KunderaException(e);\n        }\n    }\n\n    /**\n     * Sets the field value.\n     * \n     * @param entity\n     *            the entity\n     * @param column\n     *            the column\n     * @param value\n     *            the value\n     */\n    private static void setFieldValue(Object entity, Attribute column, JsonElement value)\n    {\n        if (column.getJavaType().isAssignableFrom(byte[].class))\n        {\n            PropertyAccessorHelper.set(entity, (Field) column.getJavaMember(),\n                    PropertyAccessorFactory.STRING.toBytes(value.getAsString()));\n        }\n        else\n        {\n            PropertyAccessorHelper.set(\n                    entity,\n                    (Field) column.getJavaMember(),\n                    PropertyAccessorHelper.fromSourceToTargetClass(column.getJavaType(), String.class,\n                            value.getAsString()));\n        }\n    }\n\n    /**\n     * On via embeddable.\n     * \n     * @param entityType\n     *            the entity type\n     * @param column\n     *            the column\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param embeddable\n     *            the embeddable\n     * @param jsonObj\n     *            the json obj\n     */\n    private static void onViaEmbeddable(EntityType entityType, Attribute column, EntityMetadata m, Object entity,\n            EmbeddableType embeddable, JsonObject jsonObj)\n    {\n        Field embeddedField = (Field) column.getJavaMember();\n        JsonElement embeddedDocumentObject = jsonObj.get(((AbstractAttribute) column).getJPAColumnName());\n        if (!column.isCollection())\n        {\n            PropertyAccessorHelper.set(\n                    entity,\n                    embeddedField,\n                    getObjectFromJson(embeddedDocumentObject.getAsJsonObject(),\n                            ((AbstractAttribute) column).getBindableJavaType(), embeddable.getAttributes()));\n        }\n    }\n\n    /**\n     * Gets the object from json.\n     * \n     * @param jsonObj\n     *            the json obj\n     * @param clazz\n     *            the clazz\n     * @param columns\n     *            the columns\n     * @return the object from json\n     */\n    static Object getObjectFromJson(JsonObject jsonObj, Class clazz, Set<Attribute> columns)\n    {\n        Object obj = KunderaCoreUtils.createNewInstance(clazz);\n        for (Attribute column : columns)\n        {\n            JsonElement value = jsonObj.get(((AbstractAttribute) column).getJPAColumnName());\n            setFieldValue(obj, column, value);\n        }\n        return obj;\n    }\n\n    /**\n     * Gets the json primitive.\n     * \n     * @param value\n     *            the value\n     * @param clazz\n     *            the clazz\n     * @return the json primitive\n     */\n    private static JsonElement getJsonPrimitive(Object value, Class clazz)\n    {\n        if (value != null)\n        {\n            if (clazz.isAssignableFrom(Number.class) || value instanceof Number)\n            {\n                return new JsonPrimitive((Number) value);\n            }\n            else if (clazz.isAssignableFrom(Boolean.class) || value instanceof Boolean)\n            {\n                return new JsonPrimitive((Boolean) value);\n            }\n            else if (clazz.isAssignableFrom(Character.class) || value instanceof Character)\n            {\n                return new JsonPrimitive((Character) value);\n            }\n            else if (clazz.isAssignableFrom(byte[].class) || value instanceof byte[])\n            {\n                return new JsonPrimitive(PropertyAccessorFactory.STRING.fromBytes(String.class, (byte[]) value));\n            }\n            else\n            {\n                return new JsonPrimitive(PropertyAccessorHelper.getString(value));\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Gets the _ id.\n     * \n     * @param field\n     *            the field\n     * @param embeddedObject\n     *            the embedded object\n     * @param embeddableType\n     *            the embeddable type\n     * @param _id\n     *            the _id\n     * @return the _ id\n     */\n    static String get_Id(Field field, Object embeddedObject, EmbeddableType embeddableType, String _id)\n    {\n        Field[] fields = field.getType().getDeclaredFields();\n        for (Field columnField : fields)\n        {\n            if (!ReflectUtils.isTransientOrStatic(columnField)\n                    && !embeddableType.getAttribute(columnField.getName()).isAssociation())\n            {\n                Object valueObject = PropertyAccessorHelper.getObject(embeddedObject, columnField);\n                _id = _id + PropertyAccessorHelper.getString(valueObject);\n            }\n        }\n        return _id;\n    }\n}"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBPropertyReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb;\n\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * CouchDB Property Reader.\n * \n * @author Kuldeep Mishra\n * \n */\npublic class CouchDBPropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n\n    /** log instance. */\n    private static Logger log = LoggerFactory.getLogger(CouchDBPropertyReader.class);\n\n    /** MongoDB schema metadata instance. */\n    public static CouchDBSchemaMetadata csmd;\n\n    /**\n     * Instantiates a new couch db property reader.\n     * \n     * @param externalProperties\n     *            the external properties\n     * @param puMetadata\n     *            the pu metadata\n     */\n    public CouchDBPropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        csmd = new CouchDBSchemaMetadata();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.AbstractPropertyReader#onXml(com.impetus\n     * .kundera.configure.ClientProperties)\n     */\n    @Override\n    protected void onXml(ClientProperties cp)\n    {\n        if (cp != null)\n        {\n            csmd.setClientProperties(cp);\n        }\n    }\n\n    /**\n     * The Class CouchDBSchemaMetadata.\n     * \n     * @author Kuldeep Mishra\n     */\n    public class CouchDBSchemaMetadata\n    {\n\n        /** The client properties. */\n        private ClientProperties clientProperties;\n\n        /**\n         * Gets the client properties.\n         * \n         * @return the client properties\n         */\n        public ClientProperties getClientProperties()\n        {\n            return clientProperties;\n        }\n\n        /**\n         * Sets the client properties.\n         * \n         * @param clientProperties\n         *            the new client properties\n         */\n        public void setClientProperties(ClientProperties clientProperties)\n        {\n            this.clientProperties = clientProperties;\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBQuery.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Queue;\n\nimport javax.persistence.Query;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.eclipse.persistence.jpa.jpql.parser.AvgFunction;\nimport org.eclipse.persistence.jpa.jpql.parser.CountFunction;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.MaxFunction;\nimport org.eclipse.persistence.jpa.jpql.parser.MinFunction;\nimport org.eclipse.persistence.jpa.jpql.parser.NullExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectClause;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectStatement;\nimport org.eclipse.persistence.jpa.jpql.parser.StateFieldPathExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.SumFunction;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.query.KunderaQueryUtils;\nimport com.impetus.kundera.query.QueryHandlerException;\nimport com.impetus.kundera.query.QueryImpl;\n\n/**\n * Extends QueryImpl for CouchDB query.\n * \n * @author Kuldeep Mishra\n * \n */\npublic class CouchDBQuery extends QueryImpl\n{\n\n    /** The use lucene or es. */\n    private boolean useLuceneOrES;\n\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(CouchDBQuery.class);\n\n    /**\n     * Instantiates a new couch db query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param persistenceDelegator\n     *            the persistence delegator\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public CouchDBQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n    }\n\n    /**\n     * Populate results.\n     * \n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @return the list\n     */\n    @Override\n    protected List populateEntities(EntityMetadata m, Client client)\n    {\n        ClientMetadata clientMetadata = ((ClientBase) client).getClientMetadata();\n        this.useLuceneOrES = !MetadataUtils.useSecondryIndex(clientMetadata);\n        if (useLuceneOrES)\n        {\n            return populateUsingLucene(m, client, null, kunderaQuery.getResult());\n        }\n        else\n        {\n            CouchDBQueryInterpreter interpreter = onTranslation(getKunderaQuery().getFilterClauseQueue(), m);\n            return ((CouchDBClient) client).createAndExecuteQuery(interpreter);\n        }\n    }\n\n    /**\n     * Recursively populate entity.\n     * \n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @return the list\n     */\n    @Override\n    protected List recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n        List<EnhanceEntity> ls = populateEntities(m, client);\n        return setRelationEntities(ls, client, m);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#executeUpdate()\n     */\n    @Override\n    public int executeUpdate()\n    {\n        return super.executeUpdate();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#getReader()\n     */\n    @Override\n    protected EntityReader getReader()\n    {\n        return new CouchDBEntityReader(kunderaQuery, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()\n     */\n    @Override\n    protected int onExecuteUpdate()\n    {\n        return onUpdateDeleteEvent();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#close()\n     */\n    @Override\n    public void close()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#setMaxResults(int)\n     */\n    @Override\n    public Query setMaxResults(int maxResult)\n    {\n        return super.setMaxResults(maxResult);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#iterate()\n     */\n    @Override\n    public Iterator iterate()\n    {\n        return new ResultIterator((CouchDBClient) persistenceDelegeator.getClient(getEntityMetadata()),\n                getEntityMetadata(), persistenceDelegeator, onTranslation(getKunderaQuery().getFilterClauseQueue(),\n                        getEntityMetadata()), getFetchSize() != null ? getFetchSize() : this.maxResult);\n    }\n\n    /**\n     * On translation.\n     * \n     * @param clauseQueue\n     *            the clause queue\n     * @param m\n     *            the m\n     * @return the couch db query interpreter\n     */\n    private CouchDBQueryInterpreter onTranslation(Queue clauseQueue, EntityMetadata m)\n    {\n\n        CouchDBQueryInterpreter interpreter = new CouchDBQueryInterpreter(getColumns(getKunderaQuery().getResult(), m),\n                getMaxResults(), m);\n        interpreter.setColumnsToOutput(getColumnsToOutput(m, kunderaQuery));\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n\n        EntityType entity = metaModel.entity(m.getEntityClazz());\n        if (getKunderaQuery().isAggregated() && !useLuceneOrES)\n        {\n            return onAggregatedQuery(m, interpreter, getKunderaQuery());\n        }\n        // If there is no clause present, means we might need to scan complete\n        // table.\n        /**\n         * TODOOOO: Create a sorted set with table name. and add row key as\n         * score and value on persist. delete it out as well on delete call.\n         */\n        for (Object clause : clauseQueue)\n        {\n            if (clause.getClass().isAssignableFrom(FilterClause.class))\n            {\n                Object value = ((FilterClause) clause).getValue().get(0);\n                String condition = ((FilterClause) clause).getCondition();\n                String columnName = ((FilterClause) clause).getProperty();\n\n                int indexOfDot = columnName.indexOf(\".\");\n                if (indexOfDot >= 0)\n                {\n                    EmbeddableType embeddableType = metaModel.embeddable(m.getIdAttribute().getBindableJavaType());\n                    String embeddedeFieldName = columnName.substring(0, indexOfDot);\n                    if (embeddedeFieldName.equals(((AbstractAttribute) m.getIdAttribute()).getName()))\n                    {\n                        interpreter.setQueryOnCompositeKey(true);\n                        interpreter.setKeyName(embeddedeFieldName);\n                        String colName = columnName.substring(indexOfDot + 1);\n                        Attribute attribute = embeddableType.getAttribute(colName);\n                        interpreter.setIdQuery(true);\n                        interpreter.setKeyValues(\n                                colName,\n                                PropertyAccessorHelper.fromSourceToTargetClass(attribute.getJavaType(),\n                                        value.getClass(), value));\n                    }\n                    else\n                    {\n                        log.error(\"Query on embedded column/any field of embedded column, is not supported in CouchDB\");\n                        throw new QueryHandlerException(\n                                \"Query on embedded column/any field of embedded column, is not supported in CouchDB\");\n                    }\n                }\n                else\n                {\n                    Attribute col = entity.getAttribute(m.getFieldName(columnName));\n                    interpreter.setKeyValues(columnName,\n                            PropertyAccessorHelper.fromSourceToTargetClass(col.getJavaType(), value.getClass(), value));\n                    interpreter.setKeyName(columnName);\n                    if (columnName.equals(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName()))\n                    {\n                        interpreter.setIdQuery(true);\n                    }\n\n                    if (condition.equals(\"=\"))\n                    {\n                        interpreter.setKeyValue(PropertyAccessorHelper.fromSourceToTargetClass(col.getJavaType(),\n                                value.getClass(), value));\n                    }\n                    else if (condition.equals(\">=\") || condition.equals(\">\"))\n                    {\n                        interpreter.setStartKeyValue(PropertyAccessorHelper.fromSourceToTargetClass(col.getJavaType(),\n                                value.getClass(), value));\n                    }\n                    else if (condition.equals(\"<=\"))\n                    {\n                        interpreter.setEndKeyValue(PropertyAccessorHelper.fromSourceToTargetClass(col.getJavaType(),\n                                value.getClass(), value));\n                    }\n                    else if (condition.equals(\"<\"))\n                    {\n                        interpreter.setEndKeyValue(PropertyAccessorHelper.fromSourceToTargetClass(col.getJavaType(),\n                                value.getClass(), value));\n                        interpreter.setIncludeLastKey(false);\n                    }\n                    else\n                    {\n                        log.error(\"Condition:\" + condition + \" not supported for CouchDB\");\n                        throw new QueryHandlerException(\"Condition:\" + condition + \" not supported for CouchDB\");\n                    }\n                }\n            }\n            else\n            {\n                String opr = clause.toString().trim();\n\n                if (interpreter.getOperator() == null)\n                {\n                    if (opr.equalsIgnoreCase(\"AND\"))\n                    {\n                        interpreter.setOperator(\"AND\");\n                    }\n                    else if (opr.equalsIgnoreCase(\"OR\"))\n                    {\n                        log.error(\"Condition: OR not supported in CouchDB\");\n                        throw new QueryHandlerException(\"Invalid intra clause OR is not supported in CouchDB\");\n                    }\n                    else\n                    {\n                        log.error(\"Invalid intra clause:\" + opr + \" is not supported in CouchDB\");\n                        throw new QueryHandlerException(\"Invalid intra clause:\" + opr + \" not supported for CouchDB\");\n                    }\n                }\n                else if (interpreter.getOperator() != null && !interpreter.getOperator().equalsIgnoreCase(opr))\n                {\n                    log.error(\"Multiple combination of AND/OR clause not supported in CouchDB\");\n                    throw new QueryHandlerException(\"Multiple combination of AND/OR clause not supported in CouchDB\");\n                }\n                // it is a case of \"AND\", \"OR\" clause\n            }\n        }\n        return interpreter;\n    }\n\n    /**\n     * On aggregated query.\n     * \n     * @param m\n     *            the m\n     * @param interpreter\n     *            the interpreter\n     * @param kunderaQuery\n     *            the kundera query\n     * @return the couch db query interpreter\n     */\n    private CouchDBQueryInterpreter onAggregatedQuery(EntityMetadata m, CouchDBQueryInterpreter interpreter,\n            KunderaQuery kunderaQuery)\n    {\n        interpreter.setAggregation(true);\n        SelectStatement selectStatement = kunderaQuery.getSelectStatement();\n        Expression whereClause = selectStatement.getWhereClause();\n        if (!NullExpression.class.isAssignableFrom(whereClause.getClass()))\n        {\n            throw new KunderaException(\"Aggregations with where clause are yet not supported in CouchDB\");\n        }\n        SelectClause selectClause = (SelectClause) selectStatement.getSelectClause();\n        Expression expression = selectClause.getSelectExpression();\n        if (CountFunction.class.isAssignableFrom(expression.getClass()))\n        {\n            interpreter.setAggregationType(CouchDBConstants.COUNT);\n            Expression exp = ((CountFunction) expression).getExpression();\n            setAggregationColInInterpreter(m, interpreter, exp);\n        }\n        else if (MinFunction.class.isAssignableFrom(expression.getClass()))\n        {\n            interpreter.setAggregationType(CouchDBConstants.MIN);\n            Expression exp = ((MinFunction) expression).getExpression();\n            setAggregationColInInterpreter(m, interpreter, exp);\n        }\n        else if (MaxFunction.class.isAssignableFrom(expression.getClass()))\n        {\n            interpreter.setAggregationType(CouchDBConstants.MAX);\n            Expression exp = ((MaxFunction) expression).getExpression();\n            setAggregationColInInterpreter(m, interpreter, exp);\n        }\n        else if (AvgFunction.class.isAssignableFrom(expression.getClass()))\n        {\n            interpreter.setAggregationType(CouchDBConstants.AVG);\n            Expression exp = ((AvgFunction) expression).getExpression();\n            setAggregationColInInterpreter(m, interpreter, exp);\n        }\n        else if (SumFunction.class.isAssignableFrom(expression.getClass()))\n        {\n            interpreter.setAggregationType(CouchDBConstants.SUM);\n            Expression exp = ((SumFunction) expression).getExpression();\n            setAggregationColInInterpreter(m, interpreter, exp);\n        }\n        else\n        {\n            throw new KunderaException(\"This query is currently not supported in CouchDB\");\n        }\n        return interpreter;\n    }\n\n    /**\n     * Sets the aggregation col in interpreter.\n     * \n     * @param m\n     *            the m\n     * @param interpreter\n     *            the interpreter\n     * @param exp\n     *            the exp\n     */\n    private void setAggregationColInInterpreter(EntityMetadata m, CouchDBQueryInterpreter interpreter, Expression exp)\n    {\n        if (StateFieldPathExpression.class.isAssignableFrom(exp.getClass()))\n        {\n            Map<String, Object> map = KunderaQueryUtils.setFieldClazzAndColumnFamily(exp, m, kunderaMetadata);\n            interpreter.setAggregationColumn((String) map.get(Constants.COL_NAME));\n        }\n    }\n\n    /**\n     * Gets the columns to output.\n     * \n     * @param m\n     *            the m\n     * @param kunderaQuery\n     *            the kundera query\n     * @return the columns to output\n     */\n    private List<Map<String, Object>> getColumnsToOutput(EntityMetadata m, KunderaQuery kunderaQuery)\n    {\n        if (kunderaQuery.isSelectStatement())\n        {\n            SelectStatement selectStatement = kunderaQuery.getSelectStatement();\n            SelectClause selectClause = (SelectClause) selectStatement.getSelectClause();\n            return KunderaQueryUtils.readSelectClause(selectClause.getSelectExpression(), m, false, kunderaMetadata);\n        }\n        return new ArrayList();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#findUsingLucene(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n        CouchDBQueryInterpreter interpreter = onTranslation(getKunderaQuery().getFilterClauseQueue(), m);\n        return ((CouchDBClient) client).createAndExecuteQuery(interpreter);\n    }\n\n}"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBQueryInterpreter.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport com.impetus.kundera.metadata.model.EntityMetadata;\n\n/**\n * Query interpreter for CouchDB.\n * \n * @author Kuldeep Mishra\n * \n */\npublic class CouchDBQueryInterpreter\n{\n\n    /** The m. */\n    private EntityMetadata m;\n\n    /** The is id query. */\n    private boolean isIdQuery;\n\n    /** The limit. */\n    private int limit;\n\n    /** The key value. */\n    private Object keyValue;\n\n    /** The key name. */\n    private String keyName;\n\n    /** The key values. */\n    private Map<String, Object> keyValues;\n\n    /** The start key value. */\n    private Object startKeyValue;\n\n    /** The end key value. */\n    private Object endKeyValue;\n\n    /** The include docs. */\n    private boolean includeDocs = true;\n\n    /** The descending. */\n    private boolean descending = false;\n\n    /** The columns. */\n    private String[] columns;\n\n    /** The include last key. */\n    private boolean includeLastKey = true;\n\n    /** The operator. */\n    private String operator;\n\n    /** The is query on composite key. */\n    private boolean isQueryOnCompositeKey = false;\n\n    /** The columns to output. */\n    private List<Map<String, Object>> columnsToOutput;\n\n    /** The is aggregation. */\n    private boolean isAggregation = false;\n\n    /** The aggregation type. */\n    private String aggregationType;\n\n    /** The aggregation column. */\n    private String aggregationColumn = null;\n\n    /**\n     * Instantiates a new couch db query interpreter.\n     * \n     * @param columns\n     *            the columns\n     * @param limit\n     *            the limit\n     * @param m\n     *            the m\n     */\n    public CouchDBQueryInterpreter(String[] columns, int limit, EntityMetadata m)\n    {\n        this.m = m;\n        this.columns = columns;\n        this.limit = limit;\n    }\n\n    /**\n     * Gets the limit.\n     * \n     * @return the limit\n     */\n    public int getLimit()\n    {\n        return limit;\n    }\n\n    /**\n     * Sets the limit.\n     * \n     * @param limit\n     *            the new limit\n     */\n    public void setLimit(int limit)\n    {\n        this.limit = limit;\n    }\n\n    /**\n     * Gets the key value.\n     * \n     * @return the key value\n     */\n    public Object getKeyValue()\n    {\n        return keyValue;\n    }\n\n    /**\n     * Sets the key value.\n     * \n     * @param keyValue\n     *            the new key value\n     */\n    public void setKeyValue(Object keyValue)\n    {\n        this.keyValue = keyValue;\n    }\n\n    /**\n     * Gets the start key value.\n     * \n     * @return the start key value\n     */\n    public Object getStartKeyValue()\n    {\n        return startKeyValue;\n    }\n\n    /**\n     * Sets the start key value.\n     * \n     * @param startKeyValue\n     *            the new start key value\n     */\n    public void setStartKeyValue(Object startKeyValue)\n    {\n        this.startKeyValue = startKeyValue;\n    }\n\n    /**\n     * Gets the end key value.\n     * \n     * @return the end key value\n     */\n    public Object getEndKeyValue()\n    {\n        return endKeyValue;\n    }\n\n    /**\n     * Sets the end key value.\n     * \n     * @param endKeyValue\n     *            the new end key value\n     */\n    public void setEndKeyValue(Object endKeyValue)\n    {\n        this.endKeyValue = endKeyValue;\n    }\n\n    /**\n     * Checks if is include docs.\n     * \n     * @return true, if is include docs\n     */\n    public boolean isIncludeDocs()\n    {\n        return includeDocs;\n    }\n\n    /**\n     * Sets the include docs.\n     * \n     * @param includeDocs\n     *            the new include docs\n     */\n    public void setIncludeDocs(boolean includeDocs)\n    {\n        this.includeDocs = includeDocs;\n    }\n\n    /**\n     * Checks if is descending.\n     * \n     * @return true, if is descending\n     */\n    public boolean isDescending()\n    {\n        return descending;\n    }\n\n    /**\n     * Sets the descending.\n     * \n     * @param descending\n     *            the new descending\n     */\n    public void setDescending(boolean descending)\n    {\n        this.descending = descending;\n    }\n\n    /**\n     * Checks if is id query.\n     * \n     * @return true, if is id query\n     */\n    public boolean isIdQuery()\n    {\n        return isIdQuery;\n    }\n\n    /**\n     * Sets the id query.\n     * \n     * @param isIdQuery\n     *            the new id query\n     */\n    public void setIdQuery(boolean isIdQuery)\n    {\n        this.isIdQuery = isIdQuery;\n    }\n\n    /**\n     * Gets the columns.\n     * \n     * @return the columns\n     */\n    public String[] getColumns()\n    {\n        return columns;\n    }\n\n    /**\n     * Sets the columns.\n     * \n     * @param columns\n     *            the new columns\n     */\n    public void setColumns(String[] columns)\n    {\n        this.columns = columns;\n    }\n\n    /**\n     * Gets the key values.\n     * \n     * @return the key values\n     */\n    public Map<String, Object> getKeyValues()\n    {\n        return this.keyValues;\n    }\n\n    /**\n     * Sets the key values.\n     * \n     * @param keyName\n     *            the key name\n     * @param obj\n     *            the obj\n     */\n    public void setKeyValues(String keyName, Object obj)\n    {\n        if (this.keyValues == null)\n        {\n            this.keyValues = new HashMap<String, Object>();\n        }\n        this.keyValues.put(keyName, obj);\n    }\n\n    /**\n     * Checks if is include last key.\n     * \n     * @return true, if is include last key\n     */\n    public boolean isIncludeLastKey()\n    {\n        return includeLastKey;\n    }\n\n    /**\n     * Sets the include last key.\n     * \n     * @param includeLastKey\n     *            the new include last key\n     */\n    public void setIncludeLastKey(boolean includeLastKey)\n    {\n        this.includeLastKey = includeLastKey;\n    }\n\n    /**\n     * Gets the metadata.\n     * \n     * @return the metadata\n     */\n    public EntityMetadata getMetadata()\n    {\n        return m;\n    }\n\n    /**\n     * Checks if is range query.\n     * \n     * @return true, if is range query\n     */\n    public boolean isRangeQuery()\n    {\n        return getStartKeyValue() != null && getEndKeyValue() != null;\n    }\n\n    /**\n     * Gets the operator.\n     * \n     * @return the operator\n     */\n    public String getOperator()\n    {\n        return this.operator;\n    }\n\n    /**\n     * Sets the operator.\n     * \n     * @param operator\n     *            the new operator\n     */\n    public void setOperator(String operator)\n    {\n        this.operator = operator;\n    }\n\n    /**\n     * Gets the key name.\n     * \n     * @return the key name\n     */\n    public String getKeyName()\n    {\n        return keyName;\n    }\n\n    /**\n     * Sets the key name.\n     * \n     * @param keyName\n     *            the new key name\n     */\n    public void setKeyName(String keyName)\n    {\n        this.keyName = keyName;\n    }\n\n    /**\n     * Checks if is query on composite key.\n     * \n     * @return true, if is query on composite key\n     */\n    public boolean isQueryOnCompositeKey()\n    {\n        return isQueryOnCompositeKey;\n    }\n\n    /**\n     * Sets the query on composite key.\n     * \n     * @param isQueryOnCompositeKey\n     *            the new query on composite key\n     */\n    public void setQueryOnCompositeKey(boolean isQueryOnCompositeKey)\n    {\n        this.isQueryOnCompositeKey = isQueryOnCompositeKey;\n    }\n\n    /**\n     * Gets the columns to output.\n     * \n     * @return the columns to output\n     */\n    public List<Map<String, Object>> getColumnsToOutput()\n    {\n        return columnsToOutput;\n    }\n\n    /**\n     * Sets the columns to output.\n     * \n     * @param columnsToOutput\n     *            the columns to output\n     */\n    public void setColumnsToOutput(List<Map<String, Object>> columnsToOutput)\n    {\n        this.columnsToOutput = columnsToOutput;\n    }\n\n    /**\n     * Checks if is aggregation.\n     * \n     * @return true, if is aggregation\n     */\n    public boolean isAggregation()\n    {\n        return isAggregation;\n    }\n\n    /**\n     * Sets the aggregation.\n     * \n     * @param isAggregation\n     *            the new aggregation\n     */\n    public void setAggregation(boolean isAggregation)\n    {\n        this.isAggregation = isAggregation;\n    }\n\n    /**\n     * Gets the aggregation type.\n     * \n     * @return the aggregation type\n     */\n    public String getAggregationType()\n    {\n        return aggregationType;\n    }\n\n    /**\n     * Sets the aggregation type.\n     * \n     * @param type\n     *            the new aggregation type\n     */\n    public void setAggregationType(String type)\n    {\n        this.aggregationType = type;\n    }\n\n    /**\n     * Gets the aggregation column.\n     * \n     * @return the aggregation column\n     */\n    public String getAggregationColumn()\n    {\n        return aggregationColumn;\n    }\n\n    /**\n     * Sets the aggregation column.\n     * \n     * @param aggregationColumn\n     *            the new aggregation column\n     */\n    public void setAggregationColumn(String aggregationColumn)\n    {\n        this.aggregationColumn = aggregationColumn;\n    }\n}"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBSchemaManager.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.Reader;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpRequest;\nimport org.apache.http.HttpRequestInterceptor;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.HttpResponseInterceptor;\nimport org.apache.http.HttpStatus;\nimport org.apache.http.RequestLine;\nimport org.apache.http.auth.AuthScope;\nimport org.apache.http.auth.UsernamePasswordCredentials;\nimport org.apache.http.client.ClientProtocolException;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpDelete;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.client.methods.HttpPut;\nimport org.apache.http.conn.scheme.PlainSocketFactory;\nimport org.apache.http.conn.scheme.Scheme;\nimport org.apache.http.conn.scheme.SchemeRegistry;\nimport org.apache.http.conn.scheme.SchemeSocketFactory;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.AbstractHttpClient;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport org.apache.http.impl.conn.PoolingClientConnectionManager;\nimport org.apache.http.params.CoreProtocolPNames;\nimport org.apache.http.protocol.HttpContext;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.gson.Gson;\nimport com.google.gson.JsonObject;\nimport com.impetus.client.couchdb.CouchDBDesignDocument.MapReduce;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.configure.schema.IndexInfo;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.configure.schema.TableInfo;\nimport com.impetus.kundera.configure.schema.api.AbstractSchemaManager;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * Schema Manager for couchdb.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class CouchDBSchemaManager extends AbstractSchemaManager implements SchemaManager\n{\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(CouchDBSchemaManager.class);\n\n    /** The http client. */\n    private HttpClient httpClient;\n\n    /** The http host. */\n    private HttpHost httpHost;\n\n    /** The gson. */\n    private Gson gson = new Gson();\n\n    /**\n     * Instantiates a new couch db schema manager.\n     * \n     * @param clientFactory\n     *            the client factory\n     * @param externalProperties\n     *            the external properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public CouchDBSchemaManager(String clientFactory, Map<String, Object> externalProperties,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(clientFactory, externalProperties, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#exportSchema\n     * (java.lang.String, java.util.List)\n     */\n    @Override\n    /**\n     * Export schema handles the handleOperation method.\n     */\n    public void exportSchema(final String persistenceUnit, List<TableInfo> schemas)\n    {\n        super.exportSchema(persistenceUnit, schemas);\n    }\n\n    /**\n     * drop design document from db.\n     */\n    @Override\n    public void dropSchema()\n    {\n        try\n        {\n            for (TableInfo tableInfo : tableInfos)\n            {\n                HttpResponse deleteResponse = null;\n                Map<String, MapReduce> views = new HashMap<String, MapReduce>();\n                String id = CouchDBConstants.DESIGN + tableInfo.getTableName();\n                CouchDBDesignDocument designDocument = getDesignDocument(id);\n                designDocument.setLanguage(CouchDBConstants.LANGUAGE);\n                views = designDocument.getViews();\n                if (views != null)\n                {\n                    StringBuilder builder = new StringBuilder(\"rev=\");\n                    builder.append(designDocument.get_rev());\n                    URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                            CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase()\n                                    + CouchDBConstants.URL_SEPARATOR + id, builder.toString(), null);\n                    HttpDelete delete = new HttpDelete(uri);\n                    try\n                    {\n                        deleteResponse = httpClient.execute(httpHost, delete, CouchDBUtils.getContext(httpHost));\n                    }\n                    finally\n                    {\n                        CouchDBUtils.closeContent(deleteResponse);\n                    }\n                }\n            }\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Error while creating database, caused by {}.\", e);\n            throw new SchemaGenerationException(\"Error while creating database\", e, \"couchDB\");\n        }\n    }\n\n    /**\n     * To validate entity.\n     * \n     * @param clazz\n     *            the clazz\n     * @return true, if successful\n     */\n    @Override\n    public boolean validateEntity(Class clazz)\n    {\n        return true;\n    }\n\n    /**\n     * Instantiate http client.\n     * \n     * @return true, if successful\n     */\n    @Override\n    protected boolean initiateClient()\n    {\n        try\n        {\n            SchemeSocketFactory ssf = null;\n            ssf = PlainSocketFactory.getSocketFactory();\n            SchemeRegistry schemeRegistry = new SchemeRegistry();\n            schemeRegistry.register(new Scheme(\"http\", Integer.parseInt(port), ssf));\n            PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);\n            httpClient = new DefaultHttpClient(ccm);\n            httpHost = new HttpHost(hosts[0], Integer.parseInt(port), \"http\");\n            // Http params\n            httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, \"UTF-8\");\n\n            // basic authentication\n            if (userName != null && password != null)\n            {\n                ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(\n                        new AuthScope(hosts[0], Integer.parseInt(port)),\n                        new UsernamePasswordCredentials(userName, password));\n            }\n            // request interceptor\n            ((DefaultHttpClient) httpClient).addRequestInterceptor(new HttpRequestInterceptor()\n            {\n                public void process(final HttpRequest request, final HttpContext context) throws IOException\n                {\n                    if (logger.isInfoEnabled())\n                    {\n                        RequestLine requestLine = request.getRequestLine();\n                        logger.info(\">> \" + requestLine.getMethod() + \" \" + URI.create(requestLine.getUri()).getPath());\n                    }\n                }\n            });\n            // response interceptor\n            ((DefaultHttpClient) httpClient).addResponseInterceptor(new HttpResponseInterceptor()\n            {\n                public void process(final HttpResponse response, final HttpContext context) throws IOException\n                {\n                    if (logger.isInfoEnabled())\n                        logger.info(\"<< Status: \" + response.getStatusLine().getStatusCode());\n                }\n            });\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Error Creating HTTP client {}. \", e);\n            throw new IllegalStateException(e);\n        }\n        return true;\n\n    }\n\n    /**\n     * Validate design document.\n     * \n     * @param tableInfos\n     *            the table infos\n     */\n    @Override\n    protected void validate(List<TableInfo> tableInfos)\n    {\n        try\n        {\n            if (!checkForDBExistence())\n            {\n                throw new SchemaGenerationException(\"Database \" + databaseName + \" not exist\");\n            }\n\n            for (TableInfo tableInfo : tableInfos)\n            {\n                Map<String, MapReduce> views = new HashMap<String, MapReduce>();\n                String id = CouchDBConstants.DESIGN + tableInfo.getTableName();\n                CouchDBDesignDocument designDocument = getDesignDocument(id);\n                designDocument.setLanguage(CouchDBConstants.LANGUAGE);\n                views = designDocument.getViews();\n                if (views == null)\n                {\n                    logger.warn(\"No view exist for table \" + tableInfo.getTableName()\n                            + \"so any query will not produce any result\");\n                    return;\n                }\n                for (IndexInfo indexInfo : tableInfo.getColumnsToBeIndexed())\n                {\n                    if (views.get(indexInfo.getColumnName()) == null)\n                    {\n                        logger.warn(\"No view exist for column \" + indexInfo.getColumnName() + \" of table \"\n                                + tableInfo.getTableName() + \"so any query on column \" + indexInfo.getColumnName()\n                                + \"will not produce any result\");\n                    }\n                }\n\n                // for id column.\n                if (views.get(tableInfo.getIdColumnName()) == null)\n                {\n                    logger.warn(\"No view exist for id column \" + tableInfo.getIdColumnName() + \" of table \"\n                            + tableInfo.getTableName() + \"so any query on id column \" + tableInfo.getIdColumnName()\n                            + \"will not produce any result\");\n                }\n\n                // for select all.\n                if (views.get(\"all\") == null)\n                {\n                    logger.warn(\"No view exist for select all for table \" + tableInfo.getTableName()\n                            + \"so select all query will not produce any result\");\n                }\n            }\n        }\n        catch (Exception e)\n        {\n            throw new SchemaGenerationException(\"Database \" + databaseName + \" not exist\");\n        }\n    }\n\n    /**\n     * Update design document.\n     * \n     * @param tableInfos\n     *            the table infos\n     */\n    @Override\n    protected void update(List<TableInfo> tableInfos)\n    {\n        try\n        {\n            HttpResponse response = null;\n\n            createDatabaseIfNotExist(false);\n\n            for (TableInfo tableInfo : tableInfos)\n            {\n                String id = CouchDBConstants.DESIGN + tableInfo.getTableName();\n                CouchDBDesignDocument designDocument = getDesignDocument(id);\n                designDocument.setLanguage(CouchDBConstants.LANGUAGE);\n                Map<String, MapReduce> views = designDocument.getViews();\n                if (views == null)\n                {\n                    views = new HashMap<String, MapReduce>();\n                }\n                for (IndexInfo indexInfo : tableInfo.getColumnsToBeIndexed())\n                {\n                    createViewIfNotExist(views, indexInfo.getColumnName());\n                }\n\n                // for id column.\n                createViewIfNotExist(views, tableInfo.getIdColumnName());\n\n                // for select all.\n                createViewForSelectAllIfNotExist(tableInfo, views);\n\n                // for selecting specific field\n                createViewForSelectSpecificFields(views);\n\n                designDocument.setViews(views);\n\n                URI uri = null;\n                if (designDocument.get_rev() == null)\n                {\n                    uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                            CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase()\n                                    + CouchDBConstants.URL_SEPARATOR + id, null, null);\n                }\n                else\n                {\n                    StringBuilder builder = new StringBuilder(\"rev=\");\n                    builder.append(designDocument.get_rev());\n                    uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                            CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase()\n                                    + CouchDBConstants.URL_SEPARATOR + id, builder.toString(), null);\n                }\n                HttpPut put = new HttpPut(uri);\n\n                String jsonObject = gson.toJson(designDocument);\n                StringEntity entity = new StringEntity(jsonObject);\n                put.setEntity(entity);\n                try\n                {\n                    response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));\n                }\n                finally\n                {\n                    CouchDBUtils.closeContent(response);\n                }\n            }\n            // creating views for various aggregations in the following\n            // order:\n            // -- COUNT SUM MAX MIN AVG\n            // IMPORTANT: The aggregations does not support WHERE clause\n            createDesignDocForAggregations();\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Error while creating database, caused by {}.\", e);\n            throw new SchemaGenerationException(\"Error while creating database\", e, \"couchDB\");\n        }\n    }\n\n    /**\n     * Create database and design document.\n     * \n     * @param tableInfos\n     *            the table infos\n     */\n    @Override\n    protected void create(List<TableInfo> tableInfos)\n    {\n        try\n        {\n            HttpResponse response = null;\n            createDatabaseIfNotExist(true);\n            for (TableInfo tableInfo : tableInfos)\n            {\n                CouchDBDesignDocument designDocument = new CouchDBDesignDocument();\n                Map<String, MapReduce> views = new HashMap<String, CouchDBDesignDocument.MapReduce>();\n                designDocument.setLanguage(CouchDBConstants.LANGUAGE);\n                String id = CouchDBConstants.DESIGN + tableInfo.getTableName();\n                for (IndexInfo indexInfo : tableInfo.getColumnsToBeIndexed())\n                {\n                    createView(views, indexInfo.getColumnName());\n                }\n\n                // for id column.\n                createView(views, tableInfo.getIdColumnName());\n\n                // for select all.\n                createViewForSelectAll(tableInfo, views);\n\n                // for selecting specific field\n                createViewForSelectSpecificFields(views);\n\n                designDocument.setViews(views);\n                URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                        CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase() + CouchDBConstants.URL_SEPARATOR\n                                + id, null, null);\n                HttpPut put = new HttpPut(uri);\n\n                String jsonObject = gson.toJson(designDocument);\n                StringEntity entity = new StringEntity(jsonObject);\n                put.setEntity(entity);\n                try\n                {\n                    response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));\n                }\n                finally\n                {\n                    CouchDBUtils.closeContent(response);\n                }\n            }\n            // creating views for various aggregations in the following\n            // order:\n            // -- COUNT SUM MAX MIN AVG\n            // IMPORTANT: The aggregations does not support WHERE clause\n            createDesignDocForAggregations();\n\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Error while creating database {} , caused by {}.\", databaseName, e);\n            throw new SchemaGenerationException(\"Error while creating database\", e, \"couchDB\");\n        }\n    }\n\n    /**\n     * Creates the design doc for aggregations.\n     * \n     * @throws URISyntaxException\n     *             the URI syntax exception\n     * @throws UnsupportedEncodingException\n     *             the unsupported encoding exception\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws ClientProtocolException\n     *             the client protocol exception\n     */\n    private void createDesignDocForAggregations() throws URISyntaxException, UnsupportedEncodingException, IOException,\n            ClientProtocolException\n    {\n        HttpResponse response = null;\n        URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase() + CouchDBConstants.URL_SEPARATOR\n                        + \"_design/\" + CouchDBConstants.AGGREGATIONS, null, null);\n        HttpPut put = new HttpPut(uri);\n\n        CouchDBDesignDocument designDocument = new CouchDBDesignDocument();\n        Map<String, MapReduce> views = new HashMap<String, CouchDBDesignDocument.MapReduce>();\n        designDocument.setLanguage(CouchDBConstants.LANGUAGE);\n        createViewForCount(views);\n        createViewForSum(views);\n        createViewForMax(views);\n        createViewForMin(views);\n        createViewForAvg(views);\n        designDocument.setViews(views);\n        String jsonObject = gson.toJson(designDocument);\n        StringEntity entity = new StringEntity(jsonObject);\n        put.setEntity(entity);\n        try\n        {\n            response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));\n        }\n        finally\n        {\n            CouchDBUtils.closeContent(response);\n        }\n    }\n\n    /**\n     * Creates the view for select specific fields.\n     * \n     * @param views\n     *            the views\n     */\n    private void createViewForSelectSpecificFields(Map<String, MapReduce> views)\n    {\n        if (views.get(CouchDBConstants.FIELDS) == null)\n        {\n            MapReduce mapr = new MapReduce();\n            mapr.setMap(\"function(doc){for(field in doc){emit(field, doc[field]);}}\");\n            views.put(CouchDBConstants.FIELDS, mapr);\n        }\n    }\n\n    /**\n     * Creates the view for count.\n     * \n     * @param views\n     *            the views\n     */\n    private void createViewForCount(Map<String, MapReduce> views)\n    {\n        if (views.get(CouchDBConstants.COUNT) == null)\n        {\n            MapReduce mapr = new MapReduce();\n            mapr.setMap(\"function(doc){\" + \"for(field in doc){if(field!=\\\"\" + CouchDBConstants.ENTITYNAME\n                    + \"\\\"){var o = doc[field];emit(field+\\\"_\\\"+doc.\" + CouchDBConstants.ENTITYNAME + \", o);\" + \"}}\"\n                    + \"emit(\\\"\" + CouchDBConstants.ALL + \"_\\\"+doc.\" + CouchDBConstants.ENTITYNAME + \", null);}\");\n            mapr.setReduce(\"function(keys, values){return values.length;}\");\n            views.put(CouchDBConstants.COUNT, mapr);\n        }\n    }\n\n    /**\n     * Creates the view for sum.\n     * \n     * @param views\n     *            the views\n     */\n    private void createViewForSum(Map<String, MapReduce> views)\n    {\n        if (views.get(CouchDBConstants.SUM) == null)\n        {\n            MapReduce mapr = new MapReduce();\n            mapr.setMap(\"function(doc){for(field in doc){var o = doc[field];if(typeof(o)==\\\"number\\\")emit(field+\\\"_\\\"+doc.\"\n                    + CouchDBConstants.ENTITYNAME + \", o);}}\");\n            mapr.setReduce(\"function(keys, values){return sum(values);}\");\n            views.put(CouchDBConstants.SUM, mapr);\n        }\n    }\n\n    /**\n     * Creates the view for max.\n     * \n     * @param views\n     *            the views\n     */\n    private void createViewForMax(Map<String, MapReduce> views)\n    {\n        if (views.get(CouchDBConstants.MAX) == null)\n        {\n            MapReduce mapr = new MapReduce();\n            mapr.setMap(\"function(doc){for(field in doc){var o = doc[field];if(typeof(o)==\\\"number\\\")emit(field+\\\"_\\\"+doc.\"\n                    + CouchDBConstants.ENTITYNAME + \", o);}}\");\n            mapr.setReduce(\"function(keys, values){return Math.max.apply(Math, values);}\");\n            views.put(CouchDBConstants.MAX, mapr);\n        }\n    }\n\n    /**\n     * Creates the view for min.\n     * \n     * @param views\n     *            the views\n     */\n    private void createViewForMin(Map<String, MapReduce> views)\n    {\n        if (views.get(CouchDBConstants.MIN) == null)\n        {\n            MapReduce mapr = new MapReduce();\n            mapr.setMap(\"function(doc){for(field in doc){var o = doc[field];if(typeof(o)==\\\"number\\\")emit(field+\\\"_\\\"+doc.\"\n                    + CouchDBConstants.ENTITYNAME + \", o);}}\");\n            mapr.setReduce(\"function(keys, values){return Math.min.apply(Math, values);}\");\n            views.put(CouchDBConstants.MIN, mapr);\n        }\n    }\n\n    /**\n     * Creates the view for avg.\n     * \n     * @param views\n     *            the views\n     */\n    private void createViewForAvg(Map<String, MapReduce> views)\n    {\n        if (views.get(CouchDBConstants.AVG) == null)\n        {\n            MapReduce mapr = new MapReduce();\n            mapr.setMap(\"function(doc){for(field in doc){var o = doc[field];if(typeof(o)==\\\"number\\\")emit(field+\\\"_\\\"+doc.\"\n                    + CouchDBConstants.ENTITYNAME + \", o);}}\");\n            mapr.setReduce(\"function(keys, values){return sum(values)/values.length;}\");\n            views.put(CouchDBConstants.AVG, mapr);\n        }\n    }\n\n    /**\n     * Create database and design document.\n     * \n     * @param tableInfos\n     *            the table infos\n     */\n    @Override\n    protected void create_drop(List<TableInfo> tableInfos)\n    {\n        create(tableInfos);\n    }\n\n    /**\n     * Creates the view if not exist.\n     * \n     * @param views\n     *            the views\n     * @param columnName\n     *            the column name\n     */\n    private void createViewIfNotExist(Map<String, MapReduce> views, String columnName)\n    {\n        if (views.get(columnName) == null)\n        {\n            createView(views, columnName);\n        }\n    }\n\n    /**\n     * Creates the view.\n     * \n     * @param views\n     *            the views\n     * @param columnName\n     *            the column name\n     */\n    private void createView(Map<String, MapReduce> views, String columnName)\n    {\n        MapReduce mapr = new MapReduce();\n        mapr.setMap(\"function(doc){if(doc.\" + columnName + \"){emit(doc.\" + columnName + \", doc);}}\");\n        views.put(columnName, mapr);\n    }\n\n    /**\n     * Creates the view for select all if not exist.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param views\n     *            the views\n     */\n    private void createViewForSelectAllIfNotExist(TableInfo tableInfo, Map<String, MapReduce> views)\n    {\n        if (views.get(\"all\") == null)\n        {\n            createViewForSelectAll(tableInfo, views);\n        }\n    }\n\n    /**\n     * Creates the view for select all.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param views\n     *            the views\n     */\n    private void createViewForSelectAll(TableInfo tableInfo, Map<String, MapReduce> views)\n    {\n        MapReduce mapr = new MapReduce();\n        mapr.setMap(\"function(doc){if(doc.\" + tableInfo.getIdColumnName() + \"){emit(null, doc);}}\");\n        views.put(\"all\", mapr);\n    }\n\n    /**\n     * Creates the database if not exist.\n     * \n     * @param drop\n     *            the drop\n     * @throws URISyntaxException\n     *             the URI syntax exception\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws ClientProtocolException\n     *             the client protocol exception\n     */\n    private void createDatabaseIfNotExist(boolean drop) throws URISyntaxException, IOException, ClientProtocolException\n    {\n        boolean exist = checkForDBExistence();\n\n        if (exist && drop)\n        {\n            dropDatabase();\n            exist = false;\n        }\n        if (!exist)\n        {\n            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase(), null, null);\n\n            HttpPut put = new HttpPut(uri);\n            HttpResponse putRes = null;\n            try\n            {\n                // creating database.\n                putRes = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));\n            }\n            finally\n            {\n                CouchDBUtils.closeContent(putRes);\n            }\n        }\n    }\n\n    /**\n     * Check for db existence.\n     * \n     * @return true, if successful\n     * @throws ClientProtocolException\n     *             the client protocol exception\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws URISyntaxException\n     *             the URI syntax exception\n     */\n    private boolean checkForDBExistence() throws ClientProtocolException, IOException, URISyntaxException\n    {\n        URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase(), null, null);\n\n        HttpGet get = new HttpGet(uri);\n        HttpResponse getRes = null;\n        try\n        {\n            // creating database.\n            getRes = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));\n            if (getRes.getStatusLine().getStatusCode() == HttpStatus.SC_OK)\n            {\n                return true;\n            }\n            return false;\n        }\n        finally\n        {\n            CouchDBUtils.closeContent(getRes);\n        }\n    }\n\n    /**\n     * Drop database.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws ClientProtocolException\n     *             the client protocol exception\n     * @throws URISyntaxException\n     *             the URI syntax exception\n     */\n    private void dropDatabase() throws IOException, ClientProtocolException, URISyntaxException\n    {\n        HttpResponse delRes = null;\n        try\n        {\n            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase(), null, null);\n            HttpDelete delete = new HttpDelete(uri);\n            delRes = httpClient.execute(httpHost, delete, CouchDBUtils.getContext(httpHost));\n        }\n        finally\n        {\n            CouchDBUtils.closeContent(delRes);\n        }\n    }\n\n    /**\n     * Get design document.\n     * \n     * @param id\n     *            the id\n     * @return the design document\n     */\n    private CouchDBDesignDocument getDesignDocument(String id)\n    {\n        HttpResponse response = null;\n        try\n        {\n            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase() + CouchDBConstants.URL_SEPARATOR + id,\n                    null, null);\n            HttpGet get = new HttpGet(uri);\n            get.addHeader(\"Accept\", \"application/json\");\n            response = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));\n\n            InputStream content = response.getEntity().getContent();\n            Reader reader = new InputStreamReader(content);\n\n            JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);\n            return gson.fromJson(jsonObject, CouchDBDesignDocument.class);\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Error while deleting object, Caused by: .\", e);\n            throw new KunderaException(e);\n        }\n        finally\n        {\n            CouchDBUtils.closeContent(response);\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDBUtils.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.Reader;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.AuthCache;\nimport org.apache.http.client.ClientProtocolException;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.client.methods.HttpPut;\nimport org.apache.http.client.protocol.ClientContext;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.auth.BasicScheme;\nimport org.apache.http.impl.client.BasicAuthCache;\nimport org.apache.http.protocol.BasicHttpContext;\nimport org.apache.http.protocol.HttpContext;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.gson.Gson;\nimport com.google.gson.JsonObject;\nimport com.impetus.client.couchdb.CouchDBDesignDocument.MapReduce;\nimport com.impetus.kundera.KunderaException;\n\n/**\n * Utility class for couchdb.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class CouchDBUtils\n{\n\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(CouchDBUtils.class);\n\n    /**\n     * Gets the context.\n     * \n     * @param httpHost\n     *            the http host\n     * @return the context\n     */\n    public static HttpContext getContext(HttpHost httpHost)\n    {\n        AuthCache authCache = new BasicAuthCache();\n        authCache.put(httpHost, new BasicScheme());\n\n        HttpContext context = new BasicHttpContext();\n        context.setAttribute(ClientContext.AUTH_CACHE, authCache);\n        return context;\n    }\n\n    /**\n     * Close content.\n     * \n     * @param response\n     *            the response\n     */\n    public static void closeContent(HttpResponse response)\n    {\n        if (response != null)\n        {\n            try\n            {\n                InputStream content = response.getEntity().getContent();\n                content.close();\n            }\n            catch (Exception e)\n            {\n                throw new KunderaException(e);\n            }\n        }\n    }\n\n    /**\n     * Creates the view.\n     * \n     * @param views\n     *            the views\n     * @param columnName\n     *            the column name\n     * @param columns\n     *            the columns\n     */\n    static void createView(Map<String, MapReduce> views, String columnName, List<String> columns)\n    {\n        Iterator<String> iterator = columns.iterator();\n\n        MapReduce mapr = new MapReduce();\n        StringBuilder mapBuilder = new StringBuilder();\n        StringBuilder ifBuilder = new StringBuilder(\"function(doc){if(\");\n        StringBuilder emitFunction = new StringBuilder(\"{emit(\");\n        if (columns != null && columns.size() > 1)\n        {\n            emitFunction.append(\"[\");\n        }\n        while (iterator.hasNext())\n        {\n            String nextToken = iterator.next();\n            ifBuilder.append(\"doc.\" + nextToken);\n            ifBuilder.append(\" && \");\n            emitFunction.append(\"doc.\" + nextToken);\n            emitFunction.append(\",\");\n        }\n        ifBuilder.delete(ifBuilder.toString().lastIndexOf(\" && \"), ifBuilder.toString().lastIndexOf(\" && \") + 3);\n        emitFunction.deleteCharAt(emitFunction.toString().lastIndexOf(\",\"));\n\n        ifBuilder.append(\")\");\n        if (columns != null && columns.size() > 1)\n        {\n            emitFunction.append(\"]\");\n        }\n        emitFunction.append(\", doc)}}\");\n\n        mapBuilder.append(ifBuilder.toString()).append(emitFunction.toString());\n\n        mapr.setMap(mapBuilder.toString());\n        views.put(columnName, mapr);\n    }\n\n    /**\n     * Append quotes.\n     * \n     * @param value\n     *            the value\n     * @return the object\n     */\n    static Object appendQuotes(Object value)\n    {\n        if (value instanceof String || value instanceof Character)\n        {\n            StringBuilder builder = new StringBuilder();\n            builder.append(\"\\\"\");\n            builder.append(value);\n            builder.append(\"\\\"\");\n            return builder.toString();\n        }\n        return value;\n    }\n\n    /**\n     * Creates the design document if not exist.\n     * \n     * @param httpClient\n     *            the http client\n     * @param httpHost\n     *            the http host\n     * @param gson\n     *            the gson\n     * @param tableName\n     *            the table name\n     * @param schemaName\n     *            the schema name\n     * @param viewName\n     *            the view name\n     * @param columns\n     *            the columns\n     * @throws URISyntaxException\n     *             the URI syntax exception\n     * @throws UnsupportedEncodingException\n     *             the unsupported encoding exception\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws ClientProtocolException\n     *             the client protocol exception\n     */\n    public static void createDesignDocumentIfNotExist(HttpClient httpClient, HttpHost httpHost, Gson gson,\n            String tableName, String schemaName, String viewName, List<String> columns) throws URISyntaxException,\n            UnsupportedEncodingException, IOException, ClientProtocolException\n    {\n        URI uri;\n        HttpResponse response = null;\n        CouchDBDesignDocument designDocument = CouchDBUtils.getDesignDocument(httpClient, httpHost, gson, tableName,\n                schemaName);\n        Map<String, MapReduce> views = designDocument.getViews();\n        if (views == null)\n        {\n            views = new HashMap<String, MapReduce>();\n        }\n\n        if (views.get(viewName.toString()) == null)\n        {\n            CouchDBUtils.createView(views, viewName, columns);\n        }\n        String id = CouchDBConstants.DESIGN + tableName;\n        if (designDocument.get_rev() == null)\n        {\n            uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR + id,\n                    null, null);\n        }\n        else\n        {\n            StringBuilder builder = new StringBuilder(\"rev=\");\n            builder.append(designDocument.get_rev());\n            uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR + id,\n                    builder.toString(), null);\n        }\n        HttpPut put = new HttpPut(uri);\n\n        designDocument.setViews(views);\n        String jsonObject = gson.toJson(designDocument);\n        StringEntity entity = new StringEntity(jsonObject);\n        put.setEntity(entity);\n        try\n        {\n            response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));\n        }\n        finally\n        {\n            CouchDBUtils.closeContent(response);\n        }\n    }\n\n    /**\n     * Gets the design document.\n     * \n     * @param httpClient\n     *            the http client\n     * @param httpHost\n     *            the http host\n     * @param gson\n     *            the gson\n     * @param tableName\n     *            the table name\n     * @param schemaName\n     *            the schema name\n     * @return the design document\n     */\n    private static CouchDBDesignDocument getDesignDocument(HttpClient httpClient, HttpHost httpHost, Gson gson,\n            String tableName, String schemaName)\n    {\n        HttpResponse response = null;\n        try\n        {\n            String id = CouchDBConstants.DESIGN + tableName;\n            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR + id,\n                    null, null);\n            HttpGet get = new HttpGet(uri);\n            get.addHeader(\"Accept\", \"application/json\");\n            response = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));\n\n            InputStream content = response.getEntity().getContent();\n            Reader reader = new InputStreamReader(content);\n\n            JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);\n            return gson.fromJson(jsonObject, CouchDBDesignDocument.class);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while fetching design document object, Caused by: .\", e);\n            throw new KunderaException(e);\n        }\n        finally\n        {\n            CouchDBUtils.closeContent(response);\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/CouchDbDBClientProperties.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb;\n\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.Client;\n\n/**\n * The Class CouchDbDBClientProperties.\n * \n * @author Kuldeep Mishra\n */\npublic class CouchDbDBClientProperties\n{\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(CouchDbDBClientProperties.class);\n\n    /** The Constant BATCH_SIZE. */\n    public static final String BATCH_SIZE = \"batch.size\";\n\n    /** The couch db client. */\n    private CouchDBClient couchDBClient;\n\n    /**\n     * Populate client properties.\n     * \n     * @param client\n     *            the client\n     * @param properties\n     *            the properties\n     */\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        this.couchDBClient = (CouchDBClient) client;\n\n        if (properties != null)\n        {\n            for (String key : properties.keySet())\n            {\n                Object value = properties.get(key);\n                if (checkNull(key, value))\n                {\n                    if (key.equals(BATCH_SIZE))\n                    {\n                        setBatchSize(value);\n                    }\n                }\n                // Add more properties as needed\n            }\n        }\n    }\n\n    /**\n     * set batch size.\n     * \n     * @param value\n     *            the new batch size\n     */\n    private void setBatchSize(Object value)\n    {\n        if (value instanceof Integer)\n        {\n            this.couchDBClient.setBatchSize((Integer) value);\n        }\n        else if (value instanceof String)\n        {\n            this.couchDBClient.setBatchSize(Integer.valueOf((String) value));\n        }\n    }\n\n    /**\n     * check key value map not null.\n     * \n     * @param key\n     *            the key\n     * @param value\n     *            the value\n     * @return true, if successful\n     */\n    private boolean checkNull(String key, Object value)\n    {\n        return key != null && value != null;\n    }\n}"
  },
  {
    "path": "src/kundera-couchdb/src/main/java/com/impetus/client/couchdb/ResultIterator.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.couchdb;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.NoSuchElementException;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.IResultIterator;\n\n/**\n * The Class ResultIterator.\n * \n * @author kuldeep.mishra .\n * \n *         Implementation of CouchDB result iteration.\n * @param <E>\n *            the element type\n */\nclass ResultIterator<E> implements IResultIterator<E>\n{\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(ResultIterator.class);\n\n    /** The m. */\n    private EntityMetadata m;\n\n    /** The client. */\n    private CouchDBClient client;\n\n    /** The fetch size. */\n    private int fetchSize;\n\n    /** The persistence delegator. */\n    private PersistenceDelegator persistenceDelegator;\n\n    /** The _id. */\n    private String _id;\n\n    /** The q. */\n    private StringBuilder q = new StringBuilder();\n\n    /** The interpreter. */\n    private CouchDBQueryInterpreter interpreter;\n\n    /** The skip counter. */\n    private int skipCounter = 0;\n\n    /** The count. */\n    private int count = 0;\n\n    /** The current object. */\n    private E currentObject = null;\n\n    /** The scroll complete. */\n    private boolean scrollComplete = false;\n\n    /** The results. */\n    private List results = new ArrayList();\n\n    /**\n     * Instantiates a new result iterator.\n     * \n     * @param client\n     *            the client\n     * @param m\n     *            the m\n     * @param pd\n     *            the pd\n     * @param interpreter\n     *            the interpreter\n     * @param fetchSize\n     *            the fetch size\n     */\n    public ResultIterator(CouchDBClient client, EntityMetadata m, PersistenceDelegator pd,\n            CouchDBQueryInterpreter interpreter, Integer fetchSize)\n    {\n        this.m = m;\n        this.client = client;\n        this.fetchSize = fetchSize;\n        this.persistenceDelegator = pd;\n        this.interpreter = interpreter;\n        onQuery();\n    }\n\n    /**\n     * On query.\n     */\n    private void onQuery()\n    {\n        try\n        {\n            _id = CouchDBConstants.URL_SEPARATOR + m.getSchema() + CouchDBConstants.URL_SEPARATOR + \"_design/\"\n                    + m.getTableName() + \"/_view/\";\n            _id = client.createQuery(interpreter, m, q, _id);\n\n            if (!q.toString().isEmpty())\n            {\n                q.append(\"&\");\n            }\n            q.append(\"limit=\" + 1);\n        }\n        catch (Exception e)\n        {\n\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.util.Iterator#hasNext()\n     */\n    @Override\n    public boolean hasNext()\n    {\n        currentObject = fetchObject();\n        if (count < fetchSize && fetchSize > 0 && currentObject != null)\n        {\n            count++;\n            return true;\n        }\n        scrollComplete = true;\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.util.Iterator#next()\n     */\n    @Override\n    public E next()\n    {\n        if (fetchSize <= 0 || count > fetchSize || scrollComplete)\n        {\n            throw new NoSuchElementException(\"Nothing to scroll further for:\" + m.getEntityClazz());\n        }\n        else\n        {\n            E objectToReturn = currentObject;\n            currentObject = null;\n            return objectToReturn;\n        }\n    }\n\n    /**\n     * Fetch object.\n     * \n     * @return the e\n     */\n    private E fetchObject()\n    {\n        try\n        {\n            String previousSkip = \"&skip=\" + (skipCounter - 1);\n            String currentSkip = \"&skip=\" + skipCounter;\n            int indexOf = q.indexOf(previousSkip);\n            if (indexOf > 0)\n            {\n                q.replace(indexOf, indexOf + previousSkip.length(), currentSkip);\n            }\n            else if (skipCounter > 0)\n            {\n                q.append(currentSkip);\n            }\n            client.executeQueryAndGetResults(q, _id, m, results, interpreter);\n            skipCounter++;\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Error while executing query, caused by {}.\", e);\n            throw new KunderaException(\"Error while executing query, caused by : \" + e);\n        }\n        if (results != null && !results.isEmpty())\n        {\n            Object object = results.get(0);\n            results = new ArrayList();\n            if (!m.isRelationViaJoinTable() && (m.getRelationNames() == null || (m.getRelationNames().isEmpty())))\n            {\n                return (E) object;\n            }\n            else\n            {\n                return setRelationEntities(object, client, m);\n            }\n        }\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.util.Iterator#remove()\n     */\n    @Override\n    public void remove()\n    {\n        throw new UnsupportedOperationException(\"remove method is not supported over pagination\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.IResultIterator#next(int)\n     */\n    @Override\n    public List<E> next(int chunkSize)\n    {\n        throw new UnsupportedOperationException(\"fetch in chunks is not yet supported\");\n    }\n\n    /**\n     * Sets the relation entities.\n     * \n     * @param enhanceEntity\n     *            the enhance entity\n     * @param client\n     *            the client\n     * @param m\n     *            the m\n     * @return the e\n     */\n    private E setRelationEntities(Object enhanceEntity, Client client, EntityMetadata m)\n    {\n        // Enhance entities can contain or may not contain relation.\n        // if it contain a relation means it is a child\n        // if it does not then it means it is a parent.\n        E result = null;\n        if (enhanceEntity != null)\n        {\n            if (!(enhanceEntity instanceof EnhanceEntity))\n            {\n                enhanceEntity = new EnhanceEntity(enhanceEntity, PropertyAccessorHelper.getId(enhanceEntity, m), null);\n            }\n            EnhanceEntity ee = (EnhanceEntity) enhanceEntity;\n\n            result = (E) client.getReader().recursivelyFindEntities(ee.getEntity(), ee.getRelations(), m,\n                    persistenceDelegator, false, new HashMap<Object, Object>());\n        }\n        return result;\n    }\n}"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/crud/CouchBiAssociationsTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.crud;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.crud.associations.AssociationsBiDirectionalBase;\n\n/**\n * @author Pragalbh Garg\n * \n */\npublic class CouchBiAssociationsTest extends AssociationsBiDirectionalBase\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        _PU = \"couchdb_assoc\";\n        super.setUpInternal();\n    }\n\n    @Test\n    public void test()\n    {\n        assertBegin();\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        tearDownInternal();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/crud/CouchDBClientTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.couchdb.crud;\n\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.http.HttpHost;\nimport org.apache.http.client.ClientProtocolException;\nimport org.apache.http.client.HttpClient;\nimport org.databene.contiperf.PerfTest;\nimport org.databene.contiperf.junit.ContiPerfRule;\nimport org.databene.contiperf.report.CSVSummaryReportModule;\nimport org.databene.contiperf.report.HtmlReportModule;\nimport org.databene.contiperf.report.ReportModule;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.couchdb.CouchDBClient;\nimport com.impetus.client.couchdb.entities.Month;\nimport com.impetus.client.couchdb.entities.PersonCouchDB;\nimport com.impetus.client.couchdb.entities.PersonCouchDB.Day;\nimport com.impetus.client.couchdb.utils.CouchDBTestUtils;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.lifecycle.states.TransientState;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData.OPERATION;\n\n/**\n * Junit for {@link CouchDBClient}.\n * \n * @author vivek.mishra\n */\n\npublic class CouchDBClientTest\n{\n\n    private static final String ROW_KEY = \"1\";\n\n    /** The Constant REDIS_PU. */\n    private static final String _PU = \"couchdb_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    private HttpClient httpClient;\n\n    private HttpHost httpHost;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(CouchDBClientTest.class);\n\n    @Rule\n    public ContiPerfRule i = new ContiPerfRule(new ReportModule[] { new CSVSummaryReportModule(),\n            new HtmlReportModule() });\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(_PU);\n        httpClient = CouchDBTestUtils.initiateHttpClient(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(),\n                _PU);\n        httpHost = new HttpHost(\"localhost\", 5984);\n    }\n\n    @Test\n    @PerfTest(invocations = 10)\n    public void testCRUD()\n    {\n        logger.info(\"On testInsert\");\n        EntityManager em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        CouchDBClient client = (CouchDBClient) clients.get(_PU);\n        onInsert(client);\n        onUpdate(client);\n        onDelete(client);\n        em.close();\n    }\n\n    @Test\n    @PerfTest(invocations = 10)\n    public void testCRUDWithBatch()\n    {\n        Map<String, String> batchProperty = new HashMap<String, String>(1);\n        batchProperty.put(PersistenceProperties.KUNDERA_BATCH_SIZE, \"5\");\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(_PU, batchProperty);\n        EntityManager em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        CouchDBClient client = (CouchDBClient) clients.get(_PU);\n        Assert.assertEquals(5, ((Batcher) client).getBatchSize());\n\n        final String originalName = \"vivek\";\n\n        for (int i = 0; i < 9; i++)\n        {\n            PersonCouchDB object = new PersonCouchDB();\n            object.setAge(32);\n            object.setPersonId(ROW_KEY + i);\n            object.setPersonName(originalName);\n            em.persist(object);\n\n            if (i >= 5)\n            {\n                PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY + i);\n                Assert.assertNull(result);\n            }\n            else if (i > 0 && i % 4 == 0)\n            {\n                PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY + i);\n                Assert.assertNotNull(result);\n                Assert.assertEquals(result.getPersonId(), object.getPersonId());\n                Assert.assertEquals(result.getAge(), object.getAge());\n                Assert.assertEquals(result.getPersonName(), object.getPersonName());\n            }\n        }\n        em.flush();\n        em.clear();\n        em.close();\n        em = null;\n    }\n\n    @Test\n    public void testPersistJoinTableData() throws ClientProtocolException, URISyntaxException, IOException\n    {\n        final String schemaName = \"couchdatabase\";\n        final String tableName = \"couchjointable\";\n        final String joinColumn = \"joinColumnName\";\n        final String inverseJoinColumn = \"inverseJoinColumnName\";\n\n        CouchDBTestUtils.createViews(new String[] { joinColumn, inverseJoinColumn }, tableName, httpHost, schemaName,\n                httpClient);\n        JoinTableData joinTableData = new JoinTableData(OPERATION.INSERT, schemaName, tableName, joinColumn,\n                inverseJoinColumn, null);\n\n        String joinKey = \"4\";\n\n        Integer inverseJoinKey1 = new Integer(10);\n        // inverseJoinKey2 was Double earlier, changed to Integer\n        //CouchDB has an issue with handling fixed precision numbers\n        //So the test case was failing\n        Integer inverseJoinKey2 = new Integer(12);\n        Set inverseJoinKeys = new HashSet();\n        inverseJoinKeys.add(inverseJoinKey1);\n        inverseJoinKeys.add(inverseJoinKey2);\n\n        joinTableData.addJoinTableRecord(joinKey, inverseJoinKeys);\n\n        EntityManager em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        CouchDBClient client = (CouchDBClient) clients.get(_PU);\n        client.persistJoinTable(joinTableData);\n\n        List<String> columns = client.getColumnsById(schemaName, tableName, joinColumn, inverseJoinColumn, joinKey,\n                String.class);\n\n        Assert.assertNotNull(columns);\n        Assert.assertEquals(true, !columns.isEmpty());\n        Assert.assertEquals(2, columns.size());\n        Assert.assertEquals(true, columns.contains(inverseJoinKey1.toString()));\n        Assert.assertEquals(true, columns.contains(inverseJoinKey2.toString()));\n\n        client.deleteByColumn(schemaName, tableName, inverseJoinColumn, inverseJoinKey1);\n        client.deleteByColumn(schemaName, tableName, inverseJoinColumn, inverseJoinKey2);\n\n        columns = client.getColumnsById(schemaName, tableName, joinColumn, inverseJoinColumn, joinKey, String.class);\n\n        Assert.assertTrue(columns.isEmpty());\n    }\n\n    /**\n     * Assertions on delete.\n     * \n     * @param client\n     *            Redis client instance.\n     */\n    private void onUpdate(CouchDBClient client)\n    {\n        PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY);\n        Assert.assertNotNull(result);\n\n        String updatedName = \"Updated\";\n        result.setPersonName(updatedName);\n        result.setAge(33);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(result.getAge(), new Integer(33));\n        Assert.assertEquals(result.getPersonName(), updatedName);\n    }\n\n    /**\n     * Assertions on delete.\n     * \n     * @param client\n     *            Redis client instance.\n     */\n    private void onDelete(CouchDBClient client)\n    {\n        PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY);\n        Assert.assertNotNull(result);\n        client.delete(result, ROW_KEY);\n        result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY);\n        Assert.assertNull(result);\n    }\n\n    /**\n     * Assertions on insert.\n     * \n     * @param client\n     *            Redis client instance.\n     */\n    private void onInsert(CouchDBClient client)\n    {\n        final String nodeId = \"node1\";\n        final String originalName = \"vivek\";\n        PersonCouchDB object = new PersonCouchDB();\n        object.setAge(32);\n        object.setPersonId(ROW_KEY);\n        object.setPersonName(originalName);\n        object.setDay(Day.TUESDAY);\n        object.setMonth(Month.JAN);\n\n        Node node = new Node(nodeId, PersonCouchDB.class, new TransientState(), null, ROW_KEY, null);\n        node.setData(object);\n        client.persist(node);\n\n        PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY);\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(result.getPersonId(), object.getPersonId());\n        Assert.assertEquals(result.getAge(), object.getAge());\n        Assert.assertEquals(result.getPersonName(), object.getPersonName());\n        Assert.assertEquals(result.getDay(), object.getDay());\n        Assert.assertEquals(result.getMonth(), object.getMonth());\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        CouchDBTestUtils.dropDatabase(\"couchdatabase\", httpClient, httpHost);\n    }\n}"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/crud/CouchDBCompositeKeyTest.java",
    "content": "package com.impetus.client.couchdb.crud;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.couchdb.entities.CouchDBCompoundKey;\nimport com.impetus.client.couchdb.entities.CouchDBPrimeUser;\n\npublic class CouchDBCompositeKeyTest\n{\n\n    /** The Constant REDIS_PU. */\n    private static final String COUCHDB_PU = \"couchdb_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(CouchDBCompositeKeyTest.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(COUCHDB_PU);\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        logger.info(\"On testCRUD\");\n        EntityManager em = emf.createEntityManager();\n        final String userId = \"1\";\n        final int tweetId = 12;\n        final UUID timeLineId = UUID.randomUUID();\n        final Date tweetDate = new Date();\n        CouchDBCompoundKey compoundKey = new CouchDBCompoundKey(userId, tweetId, timeLineId);\n        CouchDBPrimeUser user = new CouchDBPrimeUser(compoundKey);\n        user.setTweetBody(\"My tweet\");\n        user.setTweetDate(tweetDate);\n        em.persist(user);\n\n        em.clear(); // clear cache.\n\n        CouchDBPrimeUser found = em.find(CouchDBPrimeUser.class, compoundKey);\n        Assert.assertNotNull(found);\n        Assert.assertNotNull(found.getKey());\n        Assert.assertEquals(userId, found.getKey().getUserId());\n        Assert.assertEquals(tweetDate, found.getTweetDate());\n        em.remove(found);\n\n        em.clear(); // clear cache.\n\n        found = em.find(CouchDBPrimeUser.class, compoundKey);\n        Assert.assertNull(found);\n    }\n\n    @Test\n    public void testQuery()\n    {\n        logger.info(\"On testCRUD\");\n        EntityManager em = emf.createEntityManager();\n        final String userId = \"1\";\n        final int tweetId = 12;\n        final UUID timeLineId = UUID.randomUUID();\n        final Date tweetDate = new Date();\n        CouchDBCompoundKey compoundKey = new CouchDBCompoundKey(userId, tweetId, timeLineId);\n        CouchDBPrimeUser user = new CouchDBPrimeUser(compoundKey);\n        user.setTweetBody(\"My tweet\");\n        user.setTweetDate(tweetDate);\n        em.persist(user);\n\n        em.clear(); // clear cache.\n\n        javax.persistence.Query q = em.createQuery(\"select u from CouchDBPrimeUser u where u.key=:compoundKey\");\n        q.setParameter(\"compoundKey\", compoundKey);\n        List<CouchDBPrimeUser> users = q.getResultList();\n        Assert.assertNotNull(users);\n        Assert.assertEquals(1, users.size());\n\n        em.clear(); // clear cache.\n\n        final String withAllCompositeColClause = \"Select u from CouchDBPrimeUser u where u.key.user_Id = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        q = em.createQuery(withAllCompositeColClause);\n        q.setParameter(\"userId\", \"1\");\n        q.setParameter(\"tweetId\", 12);\n        q.setParameter(\"timeLineId\", timeLineId);\n        users = q.getResultList();\n        Assert.assertNotNull(users);\n        Assert.assertEquals(1, users.size());\n\n        try\n        {\n            final String withOutAllCompositeColClause = \"Select u from CouchDBPrimeUser u where u.key.user_Id = :userId and u.key.tweetId = :tweetId\";\n            q = em.createQuery(withOutAllCompositeColClause);\n            q.setParameter(\"userId\", \"1\");\n            q.setParameter(\"tweetId\", 12);\n            users = q.getResultList();\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\n                    \"com.impetus.kundera.query.QueryHandlerException: There should be each and every field of composite key.\",\n                    e.getMessage());\n        }\n\n        CouchDBPrimeUser found = em.find(CouchDBPrimeUser.class, compoundKey);\n        Assert.assertNotNull(found);\n        Assert.assertNotNull(found.getKey());\n        Assert.assertEquals(userId, found.getKey().getUserId());\n        Assert.assertEquals(tweetDate, found.getTweetDate());\n        em.remove(found);\n\n        em.clear(); // clear cache.\n\n        found = em.find(CouchDBPrimeUser.class, compoundKey);\n        Assert.assertNull(found);\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/crud/CouchDBESAggregationTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.crud;\n\nimport javax.persistence.Persistence;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.query.AggregationsBaseTest;\n\n/**\n * The Class CouchDBESAggregationTest.\n * \n * @author: karthikp.manchala\n */\npublic class CouchDBESAggregationTest extends AggregationsBaseTest\n{\n    /** The node. */\n    private static Node node = null;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n    }\n\n    /**\n     * Setup.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    @Before\n    public void setup() throws InterruptedException\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"couchdbESAggragation_pu\");\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        testAggregation();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (node != null)\n            node.close();\n    }\n\n    /**\n     * Tear down.\n     */\n    @After\n    public void tearDown()\n    {\n        em.createQuery(\"DELETE FROM Person p\").executeUpdate();\n        em.close();\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/crud/CouchDBESGroupByTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.crud;\n\nimport javax.persistence.Persistence;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.query.GroupByBaseTest;\n\n/**\n * The Class CouchDBESGroupByTest.\n * \n * @author: karthikp.manchala\n */\npublic class CouchDBESGroupByTest extends GroupByBaseTest\n{\n    /** The node. */\n    private static Node node = null;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n\n        emf = Persistence.createEntityManagerFactory(\"couchdbESAggragation_pu\");\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Test aggregation.\n     */\n    @Test\n    public void test()\n    {\n        testAggregation();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        em.createQuery(\"Delete from Person p\").executeUpdate();\n        waitThread();\n\n        em.close();\n        emf.close();\n\n        if (node != null)\n            node.close();\n    }\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/crud/CouchDBEmbeddableTest.java",
    "content": "package com.impetus.client.couchdb.crud;\n\nimport java.util.Date;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.couchdb.entities.CouchDBCompoundKey;\nimport com.impetus.client.couchdb.entities.CouchDBEmbeddedUser;\n\n/**\n * The Class RedisEmbeddableTest.\n */\npublic class CouchDBEmbeddableTest\n{\n\n    /** The Constant REDIS_PU. */\n    private static final String COUCHDB_PU = \"couchdb_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(CouchDBCompositeKeyTest.class);\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(COUCHDB_PU);\n    }\n\n    /**\n     * Test crud.\n     */\n    @Test\n    public void testCRUD()\n    {\n        logger.info(\"On testCRUD\");\n        EntityManager em = emf.createEntityManager();\n        final String userId = \"1\";\n        final int tweetId = 12;\n        final UUID timeLineId = UUID.randomUUID();\n        final Date tweetDate = new Date();\n        CouchDBCompoundKey embeddable = new CouchDBCompoundKey(userId, tweetId, timeLineId);\n        CouchDBEmbeddedUser user = new CouchDBEmbeddedUser(userId);\n        user.setTweetBody(\"My tweet\");\n        user.setTweetDate(tweetDate);\n        user.setEmbeddable(embeddable);\n        em.persist(user);\n\n        em.clear(); // clear cache.\n\n        CouchDBEmbeddedUser found = em.find(CouchDBEmbeddedUser.class, userId);\n        Assert.assertNotNull(found);\n        Assert.assertNotNull(found.getUserId());\n        Assert.assertEquals(userId, found.getEmbeddable().getUserId());\n        Assert.assertEquals(tweetDate, found.getTweetDate());\n        em.remove(found);\n\n        em.clear(); // clear cache.\n\n        found = em.find(CouchDBEmbeddedUser.class, userId);\n        Assert.assertNull(found);\n        em.close();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/crud/CouchDBJTATest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.crud;\n\nimport javax.naming.Context;\nimport javax.naming.InitialContext;\nimport javax.naming.NamingException;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.FlushModeType;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport javax.transaction.HeuristicMixedException;\nimport javax.transaction.HeuristicRollbackException;\nimport javax.transaction.NotSupportedException;\nimport javax.transaction.RollbackException;\nimport javax.transaction.SystemException;\nimport javax.transaction.UserTransaction;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.tests.CouchDBBase;\nimport com.impetus.client.couchdb.entities.CouchDBAddressJTAEntity;\nimport com.impetus.client.couchdb.entities.CouchDBPersonJTAEntity;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.jta.KunderaJTAUserTransaction;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class CouchDBJTATest extends CouchDBBase\n{\n    private InitialContext initialContext;\n\n    private UserTransaction userTransaction;\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Integer i = 0;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.naming.java.javaURLContextFactory\");\n        System.setProperty(Context.URL_PKG_PREFIXES, \"org.apache.naming\");\n\n        initialContext = new InitialContext();\n        initialContext.createSubcontext(\"java:comp\");\n        // This is what we need to bind to get handle of JTA's\n        // UserTransaction.\n\n        initialContext.bind(\"java:comp/UserTransaction\", new KunderaJTAUserTransaction());\n\n        emf = Persistence.createEntityManagerFactory(\"couchdbJTA_pu\");\n\n        pu = \"couchdbJTA_pu\";\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testConcurrentPersist() throws NotSupportedException, SystemException, NamingException,\n            SecurityException, IllegalStateException, RollbackException, HeuristicMixedException,\n            HeuristicRollbackException\n    {\n\n        userTransaction = (UserTransaction) initialContext.lookup(\"java:comp/UserTransaction\");\n\n        userTransaction.begin();\n\n        for (i = 0; i < 100; i++)\n        {\n            Runnable r = onExecute();\n            r.run();\n        }\n\n        userTransaction.commit();\n\n        userTransaction.begin();\n        // As data is commited, hence it should return values with other\n        // session.\n        for (i = 0; i < 100; i++)\n        {\n            EntityManager em1 = emf.createEntityManager();\n            Assert.assertNotNull(em1.find(CouchDBPersonJTAEntity.class, \"1_p\" + i));\n        }\n    }\n\n    private Runnable onExecute()\n    {\n        Runnable r = new Runnable()\n        {\n            @Override\n            public void run()\n            {\n                CouchDBPersonJTAEntity person = new CouchDBPersonJTAEntity();\n                person.setPersonId(\"1_p\" + i);\n                person.setPersonName(\"crossdata-store\");\n                CouchDBAddressJTAEntity address = new CouchDBAddressJTAEntity();\n                address.setAddressId(\"1_a\" + i);\n                address.setStreet(\"my street\");\n                person.setAddress(address);\n                try\n                {\n                    em.persist(person);\n                }\n                catch (Exception ex)\n                {\n                    CouchDBAddressJTAEntity found = em.find(CouchDBAddressJTAEntity.class, \"1_a\" + i);\n                    Assert.assertNull(found);\n                }\n\n                // As data is not commited, hence it should return null with\n                // other session.\n                EntityManager em1 = emf.createEntityManager();\n                Assert.assertNull(em1.find(CouchDBPersonJTAEntity.class, \"1_p\" + i));\n            }\n        };\n        return r;\n    }\n\n    @Test\n    public void testPersist() throws NotSupportedException, SystemException, NamingException, SecurityException,\n            IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException\n    {\n        userTransaction = (UserTransaction) initialContext.lookup(\"java:comp/UserTransaction\");\n        em.setFlushMode(FlushModeType.COMMIT);\n\n        userTransaction.begin();\n        CouchDBPersonJTAEntity person = new CouchDBPersonJTAEntity();\n        person.setPersonId(\"1_p\");\n        person.setPersonName(\"crossdata-store\");\n        CouchDBAddressJTAEntity address = new CouchDBAddressJTAEntity();\n        address.setAddressId(\"1_a\");\n        address.setStreet(\"my street\");\n        person.setAddress(address);\n        try\n        {\n            em.persist(person);\n        }\n        catch (Exception ex)\n        {\n            CouchDBAddressJTAEntity found = em.find(CouchDBAddressJTAEntity.class, \"1_a\");\n            Assert.assertNull(found);\n        }\n        userTransaction.commit();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        userTransaction.begin();\n\n        // Delete by query.\n        String deleteQuery = \"Delete from CouchDBPersonJTAEntity p\";\n        Query query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n\n        deleteQuery = \"Delete from CouchDBAddressJTAEntity p\";\n        query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n\n        userTransaction.commit();\n\n        initialContext.unbind(\"java:comp/UserTransaction\");\n        initialContext.destroySubcontext(\"java:comp\");\n        super.dropDatabase();\n    }\n}"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/crud/CouchMTMTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.crud;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.entities.AddressCouchMTM;\nimport com.impetus.client.couchdb.entities.PersonCouchMTM;\n\n/**\n * @author impadmin\n * \n */\npublic class CouchMTMTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"couchdb_pu\");\n        em = getNewEM();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        AddressCouchMTM address1 = new AddressCouchMTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"sector 11\");\n\n        AddressCouchMTM address2 = new AddressCouchMTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"sector 12\");\n\n        AddressCouchMTM address3 = new AddressCouchMTM();\n        address3.setAddressId(\"c\");\n        address3.setStreet(\"sector 13\");\n\n        Set<AddressCouchMTM> addresses1 = new HashSet<AddressCouchMTM>();\n        addresses1.add(address1);\n        addresses1.add(address2);\n\n        Set<AddressCouchMTM> addresses2 = new HashSet<AddressCouchMTM>();\n        addresses2.add(address2);\n        addresses2.add(address3);\n\n        PersonCouchMTM person1 = new PersonCouchMTM();\n        person1.setPersonId(\"1\");\n        person1.setPersonName(\"Kuldeep\");\n\n        PersonCouchMTM person2 = new PersonCouchMTM();\n        person2.setPersonId(\"2\");\n        person2.setPersonName(\"vivek\");\n\n        person1.setAddresses(addresses1);\n        person2.setAddresses(addresses2);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        em = getNewEM();\n\n        PersonCouchMTM foundPerson1 = em.find(PersonCouchMTM.class, 1);\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson1.getPersonName());\n\n        int counter = 0;\n        for (AddressCouchMTM address : foundPerson1.getAddresses())\n        {\n            if (address.getAddressId().equals(\"a\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        PersonCouchMTM foundPerson2 = em.find(PersonCouchMTM.class, 2);\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddresses());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vivek\", foundPerson2.getPersonName());\n\n        counter = 0;\n        for (AddressCouchMTM address : foundPerson2.getAddresses())\n        {\n            if (address.getAddressId().equals(\"b\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"c\", address.getAddressId());\n                Assert.assertEquals(\"sector 13\", address.getStreet());\n                counter++;\n            }\n        }\n\n        foundPerson1.setPersonName(\"KK\");\n\n        foundPerson2.setPersonName(\"vives\");\n\n        em.merge(foundPerson1);\n        em.merge(foundPerson2);\n\n        em = getNewEM();\n\n        foundPerson1 = em.find(PersonCouchMTM.class, 1);\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson1.getPersonName());\n\n        counter = 0;\n        for (AddressCouchMTM address : foundPerson1.getAddresses())\n        {\n            if (address.getAddressId().equals(\"a\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        foundPerson2 = em.find(PersonCouchMTM.class, 2);\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddresses());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vives\", foundPerson2.getPersonName());\n\n        counter = 0;\n        for (AddressCouchMTM address : foundPerson2.getAddresses())\n        {\n            if (address.getAddressId().equals(\"b\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"c\", address.getAddressId());\n                Assert.assertEquals(\"sector 13\", address.getStreet());\n                counter++;\n            }\n        }\n\n        em.remove(foundPerson1);\n        em.remove(foundPerson2);\n\n        foundPerson1 = em.find(PersonCouchMTM.class, 1);\n        foundPerson2 = em.find(PersonCouchMTM.class, 2);\n\n        Assert.assertNull(foundPerson1);\n        Assert.assertNull(foundPerson2);\n    }\n\n    @Test\n    public void testQuery()\n    {\n        AddressCouchMTM address1 = new AddressCouchMTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"sector 11\");\n\n        AddressCouchMTM address2 = new AddressCouchMTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"sector 12\");\n\n        AddressCouchMTM address3 = new AddressCouchMTM();\n        address3.setAddressId(\"c\");\n        address3.setStreet(\"sector 13\");\n\n        Set<AddressCouchMTM> addresses1 = new HashSet<AddressCouchMTM>();\n        addresses1.add(address1);\n        addresses1.add(address2);\n\n        Set<AddressCouchMTM> addresses2 = new HashSet<AddressCouchMTM>();\n        addresses2.add(address2);\n        addresses2.add(address3);\n\n        PersonCouchMTM person1 = new PersonCouchMTM();\n        person1.setPersonId(\"1\");\n        person1.setPersonName(\"Kuldeep\");\n\n        PersonCouchMTM person2 = new PersonCouchMTM();\n        person2.setPersonId(\"2\");\n        person2.setPersonName(\"vivek\");\n\n        person1.setAddresses(addresses1);\n        person2.setAddresses(addresses2);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        em = getNewEM();\n\n        Query q = em.createQuery(\"Select p from PersonCouchMTM p\");\n        List<PersonCouchMTM> results = q.getResultList();\n        Assert.assertEquals(2, results.size());\n\n        for (PersonCouchMTM foundPerson : results)\n        {\n            if (foundPerson.getPersonId().equals(\"1\"))\n            {\n\n                Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n                Assert.assertEquals(2, foundPerson.getAddresses().size());\n\n                for (AddressCouchMTM address : foundPerson.getAddresses())\n                {\n                    if (address.getAddressId().equals(\"a\"))\n                    {\n\n                        Assert.assertEquals(\"sector 11\", address.getStreet());\n                    }\n                    else\n                    {\n                        Assert.assertEquals(\"b\", address.getAddressId());\n                        Assert.assertEquals(\"sector 12\", address.getStreet());\n\n                    }\n                }\n\n            }\n            else if (foundPerson.getPersonId().equals(\"2\"))\n            {\n\n                Assert.assertEquals(\"vivek\", foundPerson.getPersonName());\n                Assert.assertEquals(2, foundPerson.getAddresses().size());\n\n                for (AddressCouchMTM address : foundPerson.getAddresses())\n                {\n                    if (address.getAddressId().equals(\"b\"))\n                    {\n\n                        Assert.assertEquals(\"sector 12\", address.getStreet());\n                    }\n                    else\n                    {\n                        Assert.assertEquals(\"c\", address.getAddressId());\n                        Assert.assertEquals(\"sector 13\", address.getStreet());\n\n                    }\n                }\n\n            }\n        }\n\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/crud/CouchMTOTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.crud;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.entities.AddressCouchMTO;\nimport com.impetus.client.couchdb.entities.PersonCouchMTO;\n\npublic class CouchMTOTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"couchdb_pu\");\n        em = getNewEM();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        AddressCouchMTO address = new AddressCouchMTO();\n        address.setAddressId(\"a\");\n        address.setStreet(\"sector 11\");\n\n        PersonCouchMTO person1 = new PersonCouchMTO();\n        person1.setPersonId(\"1\");\n        person1.setPersonName(\"Kuldeep\");\n\n        PersonCouchMTO person2 = new PersonCouchMTO();\n        person2.setPersonId(\"2\");\n        person2.setPersonName(\"vivek\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        em = getNewEM();\n\n        PersonCouchMTO foundPerson1 = em.find(PersonCouchMTO.class, 1);\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddress());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson1.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson1.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson1.getAddress().getStreet());\n\n        PersonCouchMTO foundPerson2 = em.find(PersonCouchMTO.class, 2);\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddress());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vivek\", foundPerson2.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson2.getAddress().getStreet());\n\n        foundPerson1.setPersonName(\"KK\");\n\n        foundPerson2.setPersonName(\"vives\");\n\n        em.merge(foundPerson1);\n        em.merge(foundPerson2);\n\n        em = getNewEM();\n\n        foundPerson1 = em.find(PersonCouchMTO.class, 1);\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddress());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson1.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson1.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson1.getAddress().getStreet());\n\n        foundPerson2 = em.find(PersonCouchMTO.class, 2);\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddress());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vives\", foundPerson2.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson2.getAddress().getStreet());\n\n        em.remove(foundPerson1);\n        em.remove(foundPerson2);\n\n        foundPerson1 = em.find(PersonCouchMTO.class, 1);\n        foundPerson2 = em.find(PersonCouchMTO.class, 2);\n\n        Assert.assertNull(foundPerson1);\n        Assert.assertNull(foundPerson2);\n    }\n\n    @Test\n    public void testQuery()\n    {\n        AddressCouchMTO address = new AddressCouchMTO();\n        address.setAddressId(\"a\");\n        address.setStreet(\"sector 11\");\n\n        PersonCouchMTO person1 = new PersonCouchMTO();\n        person1.setPersonId(\"1\");\n        person1.setPersonName(\"Kuldeep\");\n\n        PersonCouchMTO person2 = new PersonCouchMTO();\n        person2.setPersonId(\"2\");\n        person2.setPersonName(\"vivek\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        em = getNewEM();\n\n        Query q = em.createQuery(\"Select p from PersonCouchMTO p\");\n        List<PersonCouchMTO> results = q.getResultList();\n        Assert.assertEquals(2, results.size());\n\n        for (PersonCouchMTO foundPerson : results)\n        {\n            if (foundPerson.getPersonId().equals(\"1\"))\n            {\n\n                Assert.assertNotNull(foundPerson);\n                Assert.assertNotNull(foundPerson.getAddress());\n                Assert.assertEquals(\"1\", foundPerson.getPersonId());\n                Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n                Assert.assertEquals(\"a\", foundPerson.getAddress().getAddressId());\n                Assert.assertEquals(\"sector 11\", foundPerson.getAddress().getStreet());\n\n            }\n            else if (foundPerson.getPersonId().equals(\"2\"))\n            {\n\n                Assert.assertNotNull(foundPerson);\n                Assert.assertNotNull(foundPerson.getAddress());\n                Assert.assertEquals(\"2\", foundPerson.getPersonId());\n                Assert.assertEquals(\"vivek\", foundPerson.getPersonName());\n                Assert.assertEquals(\"a\", foundPerson.getAddress().getAddressId());\n                Assert.assertEquals(\"sector 11\", foundPerson.getAddress().getStreet());\n            }\n        }\n        em.remove(person1);\n        em.remove(person2);\n\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/crud/CouchOTMTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.crud;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.entities.AddressCouchOTM;\nimport com.impetus.client.couchdb.entities.PersonCouchOTM;\n\n/**\n * @author impadmin\n * \n */\npublic class CouchOTMTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"couchdb_pu\");\n        em = getNewEM();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        AddressCouchOTM address1 = new AddressCouchOTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"sector 11\");\n\n        AddressCouchOTM address2 = new AddressCouchOTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"sector 12\");\n\n        Set<AddressCouchOTM> addresses = new HashSet<AddressCouchOTM>();\n        addresses.add(address1);\n        addresses.add(address2);\n\n        PersonCouchOTM person = new PersonCouchOTM();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"Kuldeep\");\n        person.setAddresses(addresses);\n\n        em.persist(person);\n\n        em = getNewEM();\n\n        PersonCouchOTM foundPerson = em.find(PersonCouchOTM.class, 1);\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n\n        int counter = 0;\n        for (AddressCouchOTM address : foundPerson.getAddresses())\n        {\n            if (address.getAddressId().equals(\"a\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        Assert.assertEquals(2, counter);\n\n        foundPerson.setPersonName(\"KK\");\n\n        em.merge(foundPerson);\n\n        em = getNewEM();\n\n        foundPerson = em.find(PersonCouchOTM.class, 1);\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson.getPersonName());\n\n        counter = 0;\n        for (AddressCouchOTM address : foundPerson.getAddresses())\n        {\n            if (address.getAddressId().equals(\"a\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        Assert.assertEquals(2, counter);\n\n        em.remove(foundPerson);\n\n        foundPerson = em.find(PersonCouchOTM.class, 1);\n        Assert.assertNull(foundPerson);\n    }\n\n    @Test\n    public void testQuery()\n    {\n        AddressCouchOTM address1 = new AddressCouchOTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"sector 11\");\n\n        AddressCouchOTM address2 = new AddressCouchOTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"sector 12\");\n\n        Set<AddressCouchOTM> addresses = new HashSet<AddressCouchOTM>();\n        addresses.add(address1);\n        addresses.add(address2);\n\n        PersonCouchOTM person = new PersonCouchOTM();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"Kuldeep\");\n        person.setAddresses(addresses);\n\n        em.persist(person);\n\n        PersonCouchOTM person1 = new PersonCouchOTM();\n        person1.setPersonId(\"2\");\n        person1.setPersonName(\"KK\");\n\n        address1.setAddressId(\"a1\");\n        address1.setStreet(\"Sector a1\");\n\n        address2.setAddressId(\"a2\");\n        address2.setStreet(\"Sector a2\");\n\n        AddressCouchOTM address3 = new AddressCouchOTM();\n        address3.setAddressId(\"a3\");\n        address3.setStreet(\"Sector a3\");\n\n        addresses = new HashSet<AddressCouchOTM>();\n        addresses.add(address1);\n        addresses.add(address2);\n        addresses.add(address3);\n\n        person1.setAddresses(addresses);\n\n        em.persist(person1);\n\n        em = getNewEM();\n\n        Query q = em.createQuery(\"Select p from PersonCouchOTM p\");\n        List<PersonCouchOTM> results = q.getResultList();\n        Assert.assertEquals(2, results.size());\n\n        for (PersonCouchOTM foundPerson : results)\n        {\n            if (foundPerson.getPersonId().equals(\"1\"))\n            {\n\n                Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n                Assert.assertEquals(2, foundPerson.getAddresses().size());\n\n                for (AddressCouchOTM address : foundPerson.getAddresses())\n                {\n                    if (address.getAddressId().equals(\"a\"))\n                    {\n                        Assert.assertEquals(\"sector 11\", address.getStreet());\n                    }\n                    else\n                    {\n                        Assert.assertEquals(\"b\", address.getAddressId());\n                        Assert.assertEquals(\"sector 12\", address.getStreet());\n\n                    }\n                }\n\n            }\n            else if (foundPerson.getPersonId().equals(\"2\"))\n            {\n\n                Assert.assertEquals(\"KK\", foundPerson.getPersonName());\n                Assert.assertEquals(3, foundPerson.getAddresses().size());\n\n                for (AddressCouchOTM address : foundPerson.getAddresses())\n                {\n                    if (address.getAddressId().equals(\"a1\"))\n                    {\n\n                        Assert.assertEquals(\"Sector a1\", address.getStreet());\n\n                    }\n                    else if (address.getAddressId().equals(\"a2\"))\n                    {\n\n                        Assert.assertEquals(\"Sector a2\", address.getStreet());\n\n                    }\n                    else\n                    {\n\n                        Assert.assertEquals(\"a3\", address.getAddressId());\n                        Assert.assertEquals(\"Sector a3\", address.getStreet());\n\n                    }\n                }\n\n            }\n        }\n        em.remove(person);\n        em.remove(person1);\n\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/crud/CouchOTOTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.crud;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.entities.AddressCouchOTO;\nimport com.impetus.client.couchdb.entities.PersonCouchOTO;\n\npublic class CouchOTOTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"couchdb_pu\");\n        em = getNewEM();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        AddressCouchOTO address = new AddressCouchOTO();\n        address.setAddressId(\"a\");\n        address.setStreet(\"sector 11\");\n\n        PersonCouchOTO person = new PersonCouchOTO();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"Kuldeep\");\n        person.setAddress(address);\n\n        em.persist(person);\n\n        em = getNewEM();\n\n        PersonCouchOTO foundPerson = em.find(PersonCouchOTO.class, 1);\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddress());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson.getAddress().getStreet());\n\n        foundPerson.setPersonName(\"KK\");\n        foundPerson.getAddress().setStreet(\"sector 12\");\n\n        em.merge(foundPerson);\n\n        em = getNewEM();\n\n        foundPerson = em.find(PersonCouchOTO.class, 1);\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddress());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 12\", foundPerson.getAddress().getStreet());\n\n        em.remove(foundPerson);\n        foundPerson = em.find(PersonCouchOTO.class, 1);\n        Assert.assertNull(foundPerson);\n\n    }\n\n    @Test\n    public void testQuery()\n    {\n        AddressCouchOTO address = new AddressCouchOTO();\n        address.setAddressId(\"a\");\n        address.setStreet(\"sector 11\");\n\n        PersonCouchOTO person = new PersonCouchOTO();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"Kuldeep\");\n        person.setAddress(address);\n\n        em.persist(person);\n\n        AddressCouchOTO address1 = new AddressCouchOTO();\n        address1.setAddressId(\"b\");\n        address1.setStreet(\"sector 12\");\n\n        PersonCouchOTO person1 = new PersonCouchOTO();\n        person1.setPersonId(\"2\");\n        person1.setPersonName(\"KK\");\n        person1.setAddress(address1);\n\n        em.persist(person1);\n\n        em = getNewEM();\n\n        Query q = em.createQuery(\"Select p from PersonCouchOTO p\");\n        List<PersonCouchOTO> results = q.getResultList();\n        Assert.assertEquals(2, results.size());\n\n        for (PersonCouchOTO foundPerson : results)\n        {\n            if (foundPerson.getPersonId().equals(\"1\"))\n            {\n\n                Assert.assertEquals(\"sector 11\", foundPerson.getAddress().getStreet());\n                Assert.assertEquals(\"a\", foundPerson.getAddress().getAddressId());\n                Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n\n            }\n            else if (foundPerson.getPersonId().equals(\"2\"))\n            {\n                Assert.assertEquals(\"sector 12\", foundPerson.getAddress().getStreet());\n                Assert.assertEquals(\"b\", foundPerson.getAddress().getAddressId());\n                Assert.assertEquals(\"KK\", foundPerson.getPersonName());\n\n            }\n        }\n\n        em.remove(person);\n        em.remove(person1);\n\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n}"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBBigDecimal.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport java.math.BigDecimal;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLBigDecimal\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBBigDecimal\n{\n\n    @Id\n    private BigDecimal id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public BigDecimal getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(BigDecimal id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBBigInteger.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport java.math.BigInteger;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLBigInteger\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBBigInteger\n{\n\n    @Id\n    private BigInteger id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public BigInteger getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(BigInteger id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBBooleanPrimitive.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLBooleanPrimitive\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBBooleanPrimitive\n{\n    @Id\n    private boolean id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public boolean getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(boolean id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBBooleanWrapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLBooleanWrapper\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBBooleanWrapper\n{\n    @Id\n    private Boolean id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Boolean getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Boolean id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBBytePrimitive.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLBytePrimitive\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBBytePrimitive\n{\n\n    @Id\n    private byte id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBByteWrapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLByteWrapper\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBByteWrapper\n{\n\n    @Id\n    private Byte id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBCalendar.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport java.util.Calendar;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLCalendar\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBCalendar\n{\n\n    @Id\n    private Calendar id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Calendar getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Calendar id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBChar.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLChar\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBChar\n{\n\n    @Id\n    private char id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public char getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(char id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBCharacter.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLCharacter\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBCharacter\n{\n    @Id\n    private Character id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Character getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Character id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBDate.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLDate\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBDate\n{\n\n    @Id\n    private Date id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBDoublePrimitive.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLDoublePrimitive\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBDoublePrimitive\n{\n\n    @Id\n    private double id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public double getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBDoubleWrapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLDoubleWrapper\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBDoubleWrapper\n{\n\n    @Id\n    private Double id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Double getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBFloatPrimitive.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLFloatPrimitive\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBFloatPrimitive\n{\n    @Id\n    private float id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public float getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBFloatWrapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLFloatWrapper\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBFloatWrapper\n{\n\n    @Id\n    private Float id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Float getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBInt.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLInt\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBInt\n{\n\n    @Id\n    private int id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBInteger.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLInteger\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBInteger\n{\n    @Id\n    private Integer id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Integer getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Integer id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBLongPrimitive.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLLongPrimitive\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBLongPrimitive\n{\n\n    @Id\n    private long id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public long getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBLongWrapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLLongWrapper\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBLongWrapper\n{\n\n    @Id\n    private Long id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Long getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBShortPrimitive.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLShortPrimitive\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBShortPrimitive\n{\n\n    @Id\n    private short id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public short getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBShortWrapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLShortWrapper\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBShortWrapper\n{\n\n    @Id\n    private Short id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Short getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBSqlDate.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport java.sql.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLSqlDate\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBSqlDate\n{\n\n    @Id\n    private Date id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBString.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLString\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBString\n{\n\n    @Id\n    private String id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBTime.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport java.sql.Time;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLTime\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBTime\n{\n\n    @Id\n    private Time id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Time getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Time id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBTimestamp.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport java.sql.Timestamp;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLTimestamp\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBTimestamp\n{\n\n    @Id\n    private Timestamp id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Timestamp getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Timestamp id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/entities/StudentCouchDBUUID.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.entities;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentOracleNoSQLUUID\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class StudentCouchDBUUID\n{\n\n    @Id\n    private UUID id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public UUID getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(UUID id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/CouchDBBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport org.apache.http.HttpHost;\nimport org.apache.http.client.HttpClient;\n\nimport com.impetus.client.couchdb.utils.CouchDBTestUtils;\nimport com.impetus.kundera.datatypes.datagenerator.DataGenerator;\nimport com.impetus.kundera.datatypes.datagenerator.DataGeneratorFactory;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\npublic abstract class CouchDBBase\n{\n\n    protected HttpClient httpClient;\n\n    protected HttpHost httpHost;\n\n    protected String pu = \"couchdb_pu\";\n\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\n\n    DataGenerator<?> dataGenerator;\n\n    DataGeneratorFactory factory = new DataGeneratorFactory();\n\n    protected Object getMaxValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.maxValue();\n    }\n\n    protected Object getMinValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.minValue();\n    }\n\n    protected Object getRandomValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.randomValue();\n    }\n\n    protected Object getPartialValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.partialValue();\n    }\n\n    protected void setUpBase(final KunderaMetadata kunderaMetadata)\n    {\n        httpClient = CouchDBTestUtils.initiateHttpClient(kunderaMetadata, pu);\n        httpHost = new HttpHost(\"localhost\", 5984);\n    }\n\n    protected void createDatabase()\n    {\n        CouchDBTestUtils.createDatabase(\"couchdatabase\", httpClient, httpHost);\n    }\n\n    protected void dropDatabase()\n    {\n        CouchDBTestUtils.dropDatabase(\"couchdatabase\", httpClient, httpHost);\n    }\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBBigDecimalTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.math.BigDecimal;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBBigDecimal;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBBigDecimalTest extends CouchDBBase\n{\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testDummy()\n    {\n\n    }\n\n    // @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    // @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of BigDecimal\n        StudentCouchDBBigDecimal studentMax = new StudentCouchDBBigDecimal();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((BigDecimal) getMaxValue(BigDecimal.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of BigDecimal\n        StudentCouchDBBigDecimal studentMin = new StudentCouchDBBigDecimal();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((BigDecimal) getMinValue(BigDecimal.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of BigDecimal\n        StudentCouchDBBigDecimal student = new StudentCouchDBBigDecimal();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((BigDecimal) getRandomValue(BigDecimal.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBBigDecimal studentMax = em.find(StudentCouchDBBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBigDecimal studentMin = em.find(StudentCouchDBBigDecimal.class, getMinValue(BigDecimal.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBigDecimal student = em.find(StudentCouchDBBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBBigDecimal student = em.find(StudentCouchDBBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBigDecimal newStudent = em.find(StudentCouchDBBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigDecimal s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBigDecimal student : students)\n        {\n            Assert.assertEquals(getMinValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigDecimal> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigDecimal s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(BigDecimal.class));\n        q.setParameter(2, getMaxValue(BigDecimal.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentCouchDBBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigDecimal s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBigDecimal student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigDecimal s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBigDecimal student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBBigDecimal studentMax = em.find(StudentCouchDBBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLBigDecimal s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBigDecimal newStudent = em.find(StudentCouchDBBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLBigDecimal s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBigDecimal newStudent = em.find(StudentCouchDBBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigDecimal s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigDecimal s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigDecimal s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigDecimal.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigDecimal s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigDecimal s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigDecimal.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLBigDecimal s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBBigDecimal> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBBigIntegerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.math.BigInteger;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBBigInteger;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBBigIntegerTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of BigInteger\n        StudentCouchDBBigInteger studentMax = new StudentCouchDBBigInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((BigInteger) getMaxValue(BigInteger.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of BigInteger\n        StudentCouchDBBigInteger studentMin = new StudentCouchDBBigInteger();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((BigInteger) getMinValue(BigInteger.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of BigInteger\n        StudentCouchDBBigInteger student = new StudentCouchDBBigInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((BigInteger) getRandomValue(BigInteger.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBBigInteger studentMax = em.find(StudentCouchDBBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBigInteger studentMin = em.find(StudentCouchDBBigInteger.class, getMinValue(BigInteger.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBigInteger student = em.find(StudentCouchDBBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBBigInteger student = em.find(StudentCouchDBBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBigInteger newStudent = em.find(StudentCouchDBBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigInteger s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBigInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigInteger> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigInteger s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(BigInteger.class));\n        q.setParameter(2, getMaxValue(BigInteger.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentCouchDBBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigInteger s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBigInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigInteger s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBigInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBBigInteger studentMax = em.find(StudentCouchDBBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLBigInteger s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBigInteger newStudent = em.find(StudentCouchDBBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLBigInteger s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBigInteger newStudent = em.find(StudentCouchDBBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigInteger s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigInteger s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigInteger s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigInteger s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBigInteger s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLBigInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBBigInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBBooleanPrimitiveTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBBooleanPrimitive;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class StudentCouchDBBooleanPrimitiveTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of boolean\n        StudentCouchDBBooleanPrimitive studentMax = new StudentCouchDBBooleanPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Boolean) getMaxValue(boolean.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of boolean\n        StudentCouchDBBooleanPrimitive studentMin = new StudentCouchDBBooleanPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Boolean) getMinValue(boolean.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBBooleanPrimitive studentMax = em.find(StudentCouchDBBooleanPrimitive.class,\n                getMaxValue(boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBooleanPrimitive studentMin = em.find(StudentCouchDBBooleanPrimitive.class,\n                getMinValue(boolean.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBBooleanPrimitive student = em.find(StudentCouchDBBooleanPrimitive.class,\n                getMaxValue(boolean.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBooleanPrimitive newStudent = em.find(StudentCouchDBBooleanPrimitive.class,\n                getMaxValue(boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanPrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(boolean.class));\n        q.setParameter(2, getMaxValue(boolean.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentCouchDBBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanPrimitive s where s.name = Kuldeep or s.age > \"\n                + getMinValue(short.class);\n        try\n        {\n            q = em.createQuery(query);\n            students = q.getResultList();\n            Assert.assertNotNull(students);\n            Assert.assertEquals(1, students.size());\n            count = 0;\n            for (StudentCouchDBBooleanPrimitive student : students)\n            {\n                Assert.assertEquals(getMaxValue(boolean.class), student.getId());\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n            em.close();\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertEquals(\"unsupported clause OR for cassandra\", qhe.getMessage());\n        }\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanPrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(boolean.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBBooleanPrimitive studentMax = em.find(StudentCouchDBBooleanPrimitive.class,\n                getMinValue(boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMinValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLBooleanPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBooleanPrimitive newStudent = em.find(StudentCouchDBBooleanPrimitive.class,\n                getRandomValue(boolean.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLBooleanPrimitive s SET s.name=Vivek where s.id=true\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBooleanPrimitive newStudent = em.find(StudentCouchDBBooleanPrimitive.class,\n                getMaxValue(boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanPrimitive s where s.name = Kuldeep and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentCouchDBBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanPrimitive s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanPrimitive s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanPrimitive s where s.age = \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLBooleanPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBBooleanPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentCouchDBBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBBooleanWrapperTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBBooleanWrapper;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class StudentCouchDBBooleanWrapperTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Boolean\n        StudentCouchDBBooleanWrapper studentMax = new StudentCouchDBBooleanWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Boolean) getMaxValue(Boolean.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Boolean\n        StudentCouchDBBooleanWrapper studentMin = new StudentCouchDBBooleanWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Boolean) getMinValue(Boolean.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBBooleanWrapper studentMax = em.find(StudentCouchDBBooleanWrapper.class,\n                getMaxValue(Boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBooleanWrapper studentMin = em.find(StudentCouchDBBooleanWrapper.class,\n                getMinValue(Boolean.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        em.close();\n    }\n\n    public void testMerge(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBBooleanWrapper student = em.find(StudentCouchDBBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBooleanWrapper newStudent = em.find(StudentCouchDBBooleanWrapper.class,\n                getMaxValue(Boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(Boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Boolean.class));\n        q.setParameter(2, getMaxValue(Boolean.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentCouchDBBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanWrapper s where s.name = Kuldeep or s.age > \"\n                + getMinValue(short.class);\n        try\n        {\n            q = em.createQuery(query);\n            students = q.getResultList();\n            Assert.assertNotNull(students);\n            Assert.assertEquals(1, students.size());\n            count = 0;\n            for (StudentCouchDBBooleanWrapper student : students)\n            {\n                Assert.assertEquals(getMaxValue(Boolean.class), student.getId());\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n            em.close();\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertEquals(\"unsupported clause OR for cassandra\", qhe.getMessage());\n        }\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(Boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(Boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBBooleanWrapper studentMax = em.find(StudentCouchDBBooleanWrapper.class,\n                getMinValue(Boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMinValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(Boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLBooleanWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBooleanWrapper newStudent = em.find(StudentCouchDBBooleanWrapper.class,\n                getRandomValue(Boolean.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLBooleanWrapper s SET s.name=Vivek where s.id=true\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBooleanWrapper newStudent = em.find(StudentCouchDBBooleanWrapper.class,\n                getMaxValue(Boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanWrapper s where s.name = Kuldeep and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentCouchDBBooleanWrapper student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(Boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(Boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanWrapper s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanWrapper s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanWrapper s where s.age = \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBooleanWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLBooleanWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBBooleanWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentCouchDBBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBBytePrimitiveTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBBytePrimitive;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBBytePrimitiveTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of byte\n        StudentCouchDBBytePrimitive studentMax = new StudentCouchDBBytePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of byte\n        StudentCouchDBBytePrimitive studentMin = new StudentCouchDBBytePrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Byte) getMinValue(byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of byte\n        StudentCouchDBBytePrimitive student = new StudentCouchDBBytePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBBytePrimitive studentMax = em.find(StudentCouchDBBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBytePrimitive studentMin = em.find(StudentCouchDBBytePrimitive.class, getMinValue(byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBytePrimitive student = em.find(StudentCouchDBBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBBytePrimitive student = em.find(StudentCouchDBBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBytePrimitive newStudent = em.find(StudentCouchDBBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBytePrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(byte.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBytePrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBytePrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(byte.class));\n        q.setParameter(2, getMaxValue(byte.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Byte) getMinValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBytePrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBytePrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBBytePrimitive studentMax = em.find(StudentCouchDBBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLBytePrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBytePrimitive newStudent = em.find(StudentCouchDBBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLBytePrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBBytePrimitive newStudent = em.find(StudentCouchDBBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBytePrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBytePrimitive s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBytePrimitive s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBytePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLBytePrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLBytePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBBytePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Byte) getMinValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBByteWrapperTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBByteWrapper;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBByteWrapperTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Byte\n        StudentCouchDBByteWrapper studentMax = new StudentCouchDBByteWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(Byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Byte\n        StudentCouchDBByteWrapper studentMin = new StudentCouchDBByteWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Byte) getMinValue(Byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Byte\n        StudentCouchDBByteWrapper student = new StudentCouchDBByteWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(Byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBByteWrapper studentMax = em.find(StudentCouchDBByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBByteWrapper studentMin = em.find(StudentCouchDBByteWrapper.class, getMinValue(Byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBByteWrapper student = em.find(StudentCouchDBByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBByteWrapper student = em.find(StudentCouchDBByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBByteWrapper newStudent = em.find(StudentCouchDBByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLByteWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBByteWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Byte.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBByteWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLByteWrapper s where s.id between \" + getMinValue(Byte.class) + \" and \"\n                + getMaxValue(Byte.class);\n        // query =\n        // \"Select s From StudentOracleNoSQLByteWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        // q.setParameter(1, getMinValue(Byte.class));\n        // q.setParameter(2, getMaxValue(Byte.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Byte.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLByteWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBByteWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLByteWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBByteWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBByteWrapper studentMax = em.find(StudentCouchDBByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLByteWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBByteWrapper newStudent = em.find(StudentCouchDBByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLByteWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBByteWrapper newStudent = em.find(StudentCouchDBByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLByteWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLByteWrapper s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLByteWrapper s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLByteWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLByteWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLByteWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBByteWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Byte.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBCharTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBChar;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBCharTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of char\n        StudentCouchDBChar studentMax = new StudentCouchDBChar();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Character) getMaxValue(char.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of char\n        StudentCouchDBChar studentMin = new StudentCouchDBChar();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Character) getMinValue(char.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of char\n        StudentCouchDBChar student = new StudentCouchDBChar();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(char.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBChar studentMax = em.find(StudentCouchDBChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBChar studentMin = em.find(StudentCouchDBChar.class, getMinValue(char.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBChar student = em.find(StudentCouchDBChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBChar student = em.find(StudentCouchDBChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBChar newStudent = em.find(StudentCouchDBChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBChar student : students)\n        {\n            Assert.assertEquals(getMinValue(char.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBChar> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(char.class));\n        q.setParameter(2, getMaxValue(char.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Character) getMinValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(char.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBChar studentMax = em.find(StudentCouchDBChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBChar.class, getMaxValue(char.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLChar s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBChar newStudent = em.find(StudentCouchDBChar.class, getRandomValue(char.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLChar s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBChar newStudent = em.find(StudentCouchDBChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLChar s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBChar> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Character) getMinValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(char.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBCharacterTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBCharacter;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBCharacterTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Character\n        StudentCouchDBCharacter studentMax = new StudentCouchDBCharacter();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Character) getMaxValue(Character.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Character\n        StudentCouchDBCharacter studentMin = new StudentCouchDBCharacter();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Character) getMinValue(Character.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Character\n        StudentCouchDBCharacter student = new StudentCouchDBCharacter();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(Character.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBCharacter studentMax = em.find(StudentCouchDBCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBCharacter studentMin = em.find(StudentCouchDBCharacter.class, getMinValue(Character.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBCharacter student = em.find(StudentCouchDBCharacter.class, getRandomValue(Character.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBCharacter student = em.find(StudentCouchDBCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBCharacter newStudent = em.find(StudentCouchDBCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBCharacter student : students)\n        {\n            Assert.assertEquals(getMinValue(Character.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBCharacter> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Character.class));\n        q.setParameter(2, getMaxValue(Character.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Character.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBCharacter student : students)\n        {\n            Assert.assertEquals(getMaxValue(Character.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBCharacter student : students)\n        {\n            Assert.assertEquals(getMaxValue(Character.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBCharacter studentMax = em.find(StudentCouchDBCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBCharacter.class, getMaxValue(Character.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLCharacter s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBCharacter newStudent = em.find(StudentCouchDBCharacter.class, getRandomValue(Character.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLCharacter s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBCharacter newStudent = em.find(StudentCouchDBCharacter.class, getRandomValue(Character.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLCharacter s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBCharacter> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Character.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBDateTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBDate;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBDateTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentCouchDBDate student = new StudentCouchDBDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue(Date.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Date\n        StudentCouchDBDate studentMax = new StudentCouchDBDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue(Date.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Date\n        StudentCouchDBDate studentMin = new StudentCouchDBDate();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Date) getMinValue(Date.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBDate studentMax = em.find(StudentCouchDBDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDate studentMin = em.find(StudentCouchDBDate.class, getMinValue(Date.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDate student = em.find(StudentCouchDBDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBDate student = em.find(StudentCouchDBDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDate newStudent = em.find(StudentCouchDBDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDate student : students)\n        {\n            Assert.assertEquals(getMinValue(Date.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDate> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.id between ?1  and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Date.class));\n        q.setParameter(2, getMaxValue(Date.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Date.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBDate studentMax = em.find(StudentCouchDBDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBDate.class, getMaxValue(Date.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLDate s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDate newStudent = em.find(StudentCouchDBDate.class, getRandomValue(Date.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLDate s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDate newStudent = em.find(StudentCouchDBDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLDate s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue(Date.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBDoublePrimitiveTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBDoublePrimitive;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBDoublePrimitiveTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Double\n        StudentCouchDBDoublePrimitive studentMax = new StudentCouchDBDoublePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) getMaxValue(Double.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Double\n        StudentCouchDBDoublePrimitive studentMin = new StudentCouchDBDoublePrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Double) getMinValue(Double.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Double\n        StudentCouchDBDoublePrimitive student = new StudentCouchDBDoublePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBDoublePrimitive studentMax = em.find(StudentCouchDBDoublePrimitive.class,\n                getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDoublePrimitive studentMin = em.find(StudentCouchDBDoublePrimitive.class,\n                getMinValue(Double.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDoublePrimitive student = em.find(StudentCouchDBDoublePrimitive.class,\n                getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBDoublePrimitive student = em.find(StudentCouchDBDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDoublePrimitive newStudent = em.find(StudentCouchDBDoublePrimitive.class,\n                getMaxValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(Double.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoublePrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(double.class));\n        q.setParameter(2, getMaxValue(double.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Double) getMinValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBDoublePrimitive studentMax = em.find(StudentCouchDBDoublePrimitive.class,\n                getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLDoublePrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDoublePrimitive newStudent = em.find(StudentCouchDBDoublePrimitive.class,\n                getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLDoublePrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDoublePrimitive newStudent = em.find(StudentCouchDBDoublePrimitive.class,\n                getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLDoublePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBDoublePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Double) getMinValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBDoubleWrapperTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBDoubleWrapper;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBDoubleWrapperTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Double\n        StudentCouchDBDoubleWrapper studentMax = new StudentCouchDBDoubleWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) getMaxValue(Double.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Double\n        StudentCouchDBDoubleWrapper studentMin = new StudentCouchDBDoubleWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Double) getMinValue(Double.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Double\n        StudentCouchDBDoubleWrapper student = new StudentCouchDBDoubleWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBDoubleWrapper studentMax = em.find(StudentCouchDBDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDoubleWrapper studentMin = em.find(StudentCouchDBDoubleWrapper.class, getMinValue(Double.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDoubleWrapper student = em.find(StudentCouchDBDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBDoubleWrapper student = em.find(StudentCouchDBDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDoubleWrapper newStudent = em.find(StudentCouchDBDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Double.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoubleWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Double.class));\n        q.setParameter(2, getMaxValue(Double.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Double.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBDoubleWrapper studentMax = em.find(StudentCouchDBDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLDoubleWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDoubleWrapper newStudent = em.find(StudentCouchDBDoubleWrapper.class,\n                getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLDoubleWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBDoubleWrapper newStudent = em.find(StudentCouchDBDoubleWrapper.class,\n                getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLDoubleWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBDoubleWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Double.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBFloatPrimitiveTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBFloatPrimitive;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBFloatPrimitiveTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of float\n        StudentCouchDBFloatPrimitive studentMax = new StudentCouchDBFloatPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Float) getMaxValue(float.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of float\n        StudentCouchDBFloatPrimitive studentMin = new StudentCouchDBFloatPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Float) getMinValue(float.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of float\n        StudentCouchDBFloatPrimitive student = new StudentCouchDBFloatPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Float) getRandomValue(float.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBFloatPrimitive studentMax = em.find(StudentCouchDBFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBFloatPrimitive studentMin = em.find(StudentCouchDBFloatPrimitive.class, getMinValue(float.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBFloatPrimitive student = em.find(StudentCouchDBFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBFloatPrimitive student = em.find(StudentCouchDBFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBFloatPrimitive newStudent = em.find(StudentCouchDBFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(float.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.id between \" + getMinValue(float.class)\n                + \" and \" + getMaxValue(float.class);\n        // query =\n        // \"Select s From StudentOracleNoSQLFloatPrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        // q.setParameter(1, getMinValue(float.class));\n        // q.setParameter(2, getMaxValue(float.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Float) getMinValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBFloatPrimitive studentMax = em.find(StudentCouchDBFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLFloatPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBFloatPrimitive newStudent = em.find(StudentCouchDBFloatPrimitive.class,\n                getRandomValue(float.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLFloatPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBFloatPrimitive newStudent = em.find(StudentCouchDBFloatPrimitive.class,\n                getRandomValue(float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLFloatPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBFloatPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Float) getMinValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBFloatWrapperTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBFloatWrapper;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBFloatWrapperTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Float\n        StudentCouchDBFloatWrapper studentMax = new StudentCouchDBFloatWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Float) getMaxValue(Float.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Float\n        StudentCouchDBFloatWrapper studentMin = new StudentCouchDBFloatWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Float) getMinValue(Float.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Float\n        StudentCouchDBFloatWrapper student = new StudentCouchDBFloatWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Float) getRandomValue(Float.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBFloatWrapper studentMax = em.find(StudentCouchDBFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBFloatWrapper studentMin = em.find(StudentCouchDBFloatWrapper.class, getMinValue(Float.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBFloatWrapper student = em.find(StudentCouchDBFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBFloatWrapper student = em.find(StudentCouchDBFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBFloatWrapper newStudent = em.find(StudentCouchDBFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Float.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Float.class));\n        q.setParameter(2, getMaxValue(Float.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Float.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBFloatWrapper studentMax = em.find(StudentCouchDBFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLFloatWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBFloatWrapper newStudent = em.find(StudentCouchDBFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLFloatWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBFloatWrapper newStudent = em.find(StudentCouchDBFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLFloatWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBFloatWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Float.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBIntTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBInt;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBIntTest extends CouchDBBase\n{\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of int\n        StudentCouchDBInt studentMax = new StudentCouchDBInt();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(int.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of int\n        StudentCouchDBInt studentMin = new StudentCouchDBInt();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Integer) getMinValue(int.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of int\n        StudentCouchDBInt student = new StudentCouchDBInt();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(int.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBInt studentMax = em.find(StudentCouchDBInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBInt studentMin = em.find(StudentCouchDBInt.class, getMinValue(int.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBInt student = em.find(StudentCouchDBInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBInt student = em.find(StudentCouchDBInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBInt newStudent = em.find(StudentCouchDBInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBInt student : students)\n        {\n            Assert.assertEquals(getMinValue(int.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInt> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.id between \" + getMinValue(int.class) + \" and \"\n                + getMaxValue(int.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Integer) getMinValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBInt studentMax = em.find(StudentCouchDBInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBInt.class, getMaxValue(int.class));\n        Assert.assertNull(studentMax);\n        testPersist(useSameEm);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLInt s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBInt newStudent = em.find(StudentCouchDBInt.class, getRandomValue(int.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLInt s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBInt newStudent = em.find(StudentCouchDBInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLInt s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBInt> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Integer) getMinValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBIntegerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBInteger;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBIntegerTest extends CouchDBBase\n{\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of integer\n        StudentCouchDBInteger studentMax = new StudentCouchDBInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(Integer.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of integer\n        StudentCouchDBInteger studentMin = new StudentCouchDBInteger();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Integer) getMinValue(Integer.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of integer\n        StudentCouchDBInteger student = new StudentCouchDBInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(Integer.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBInteger studentMax = em.find(StudentCouchDBInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBInteger studentMin = em.find(StudentCouchDBInteger.class, getMinValue(Integer.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBInteger student = em.find(StudentCouchDBInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBInteger student = em.find(StudentCouchDBInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBInteger newStudent = em.find(StudentCouchDBInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(Integer.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInteger> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Integer.class));\n        q.setParameter(2, getMaxValue(Integer.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Integer.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBInteger studentMax = em.find(StudentCouchDBInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBInteger.class, getMaxValue(Integer.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLInteger s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBInteger newStudent = em.find(StudentCouchDBInteger.class, getRandomValue(Integer.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLInteger s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBInteger newStudent = em.find(StudentCouchDBInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Integer.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBLongPrimitiveTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBLongPrimitive;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBLongPrimitiveTest extends CouchDBBase\n{\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of long\n        StudentCouchDBLongPrimitive studentMax = new StudentCouchDBLongPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of long\n        StudentCouchDBLongPrimitive studentMin = new StudentCouchDBLongPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Long) getMinValue(long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of long\n        StudentCouchDBLongPrimitive student = new StudentCouchDBLongPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBLongPrimitive studentMax = em.find(StudentCouchDBLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBLongPrimitive studentMin = em.find(StudentCouchDBLongPrimitive.class, getMinValue(long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBLongPrimitive student = em.find(StudentCouchDBLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBLongPrimitive student = em.find(StudentCouchDBLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBLongPrimitive newStudent = em.find(StudentCouchDBLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(long.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.id between \" + getMinValue(long.class)\n                + \" and \" + getMaxValue(long.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Long) getMinValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBLongPrimitive studentMax = em.find(StudentCouchDBLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLLongPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBLongPrimitive newStudent = em.find(StudentCouchDBLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLLongPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBLongPrimitive newStudent = em.find(StudentCouchDBLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLLongPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBLongPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Long) getMinValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBLongWrapperTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBLongWrapper;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBLongWrapperTest extends CouchDBBase\n{\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert min value of Long\n        StudentCouchDBLongWrapper studentMin = new StudentCouchDBLongWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Long) getMinValue(Long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Long\n        StudentCouchDBLongWrapper student = new StudentCouchDBLongWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(Long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Long\n        StudentCouchDBLongWrapper studentMax = new StudentCouchDBLongWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(Long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBLongWrapper studentMax = em.find(StudentCouchDBLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBLongWrapper studentMin = em.find(StudentCouchDBLongWrapper.class, getMinValue(Long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBLongWrapper student = em.find(StudentCouchDBLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBLongWrapper student = em.find(StudentCouchDBLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBLongWrapper newStudent = em.find(StudentCouchDBLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBLongWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Long.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Long.class));\n        q.setParameter(2, getMaxValue(Long.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Long.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBLongWrapper studentMax = em.find(StudentCouchDBLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLLongWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBLongWrapper newStudent = em.find(StudentCouchDBLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLLongWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBLongWrapper newStudent = em.find(StudentCouchDBLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLLongWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBLongWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Long.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBShortPrimitiveTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBShortPrimitive;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBShortPrimitiveTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentCouchDBShortPrimitive studentMax = new StudentCouchDBShortPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentCouchDBShortPrimitive studentMin = new StudentCouchDBShortPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Short) getMinValue(Short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentCouchDBShortPrimitive student = new StudentCouchDBShortPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBShortPrimitive studentMax = em.find(StudentCouchDBShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBShortPrimitive studentMin = em.find(StudentCouchDBShortPrimitive.class, getMinValue(Short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBShortPrimitive student = em.find(StudentCouchDBShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBShortPrimitive student = em.find(StudentCouchDBShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBShortPrimitive newStudent = em.find(StudentCouchDBShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(Short.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortPrimitive s where s.id between \" + getMinValue(Short.class)\n                + \" and \" + getMaxValue(Short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Short) getMinValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortPrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortPrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBShortPrimitive studentMax = em.find(StudentCouchDBShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLShortPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBShortPrimitive newStudent = em.find(StudentCouchDBShortPrimitive.class,\n                getRandomValue(Short.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLShortPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBShortPrimitive newStudent = em.find(StudentCouchDBShortPrimitive.class,\n                getRandomValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortPrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortPrimitive s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortPrimitive s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLShortPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBShortPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Short) getMinValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBShortWrapperTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBShortWrapper;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBShortWrapperTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentCouchDBShortWrapper studentMax = new StudentCouchDBShortWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentCouchDBShortWrapper studentMin = new StudentCouchDBShortWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Short) getMinValue(Short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentCouchDBShortWrapper student = new StudentCouchDBShortWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBShortWrapper studentMax = em.find(StudentCouchDBShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBShortWrapper studentMin = em.find(StudentCouchDBShortWrapper.class, getMinValue(Short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBShortWrapper student = em.find(StudentCouchDBShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBShortWrapper student = em.find(StudentCouchDBShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBShortWrapper newStudent = em.find(StudentCouchDBShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBShortWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Short.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortWrapper s where s.id between \" + getMinValue(Short.class)\n                + \" and \" + getMaxValue(Short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Short.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBShortWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBShortWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBShortWrapper studentMax = em.find(StudentCouchDBShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLShortWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBShortWrapper newStudent = em.find(StudentCouchDBShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLShortWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBShortWrapper newStudent = em.find(StudentCouchDBShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortWrapper s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortWrapper s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLShortWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLShortWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBShortWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Short.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBSqlDateTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.sql.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBSqlDate;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBSqlDateTest extends CouchDBBase\n{\n    private static final Date DATE = new Date(System.currentTimeMillis());\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    private Object getMinValue()\n    {\n        return new Date(1970, 1, 1);\n    }\n\n    private Object getRandomValue()\n    {\n        return DATE;\n    }\n\n    private Object getMaxValue()\n    {\n        return new Date(2100, 1, 1);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentCouchDBSqlDate student = new StudentCouchDBSqlDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue());\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Date\n        StudentCouchDBSqlDate studentMax = new StudentCouchDBSqlDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue());\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Date\n        StudentCouchDBSqlDate studentMin = new StudentCouchDBSqlDate();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Date) getMinValue());\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBSqlDate studentMax = em.find(StudentCouchDBSqlDate.class, getMaxValue());\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBSqlDate studentMin = em.find(StudentCouchDBSqlDate.class, getMinValue());\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBSqlDate student = em.find(StudentCouchDBSqlDate.class, getRandomValue());\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBSqlDate student = em.find(StudentCouchDBSqlDate.class, getMaxValue());\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBSqlDate newStudent = em.find(StudentCouchDBSqlDate.class, getMaxValue());\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBSqlDate student : students)\n        {\n            Assert.assertEquals(getMinValue(), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBSqlDate> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.id between \" + getMinValue() + \" and \"\n                + getMaxValue();\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue()))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBSqlDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBSqlDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBSqlDate studentMax = em.find(StudentCouchDBSqlDate.class, getMaxValue());\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBSqlDate.class, getMaxValue());\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLSqlDate s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBSqlDate newStudent = em.find(StudentCouchDBSqlDate.class, getRandomValue());\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLSqlDate s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBSqlDate newStudent = em.find(StudentCouchDBSqlDate.class, getRandomValue());\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLSqlDate s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBSqlDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue()))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue()).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBStringTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBString;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBStringTest extends CouchDBBase\n{\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of String\n        StudentCouchDBString studentMax = new StudentCouchDBString();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((String) getMaxValue(String.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of String\n        StudentCouchDBString studentMin = new StudentCouchDBString();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((String) getMinValue(String.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of String\n        StudentCouchDBString student = new StudentCouchDBString();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((String) getRandomValue(String.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBString studentMax = em.find(StudentCouchDBString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBString studentMin = em.find(StudentCouchDBString.class, getMinValue(String.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBString student = em.find(StudentCouchDBString.class, getRandomValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBString student = em.find(StudentCouchDBString.class, getMaxValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBString newStudent = em.find(StudentCouchDBString.class, getMaxValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBString student : students)\n        {\n            Assert.assertEquals(getMinValue(String.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBString> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.id between \" + getMinValue(String.class) + \" and \"\n                + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentCouchDBString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBString studentMax = em.find(StudentCouchDBString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBString.class, getMaxValue(String.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLString s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBString newStudent = em.find(StudentCouchDBString.class, getRandomValue(String.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLString s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBString newStudent = em.find(StudentCouchDBString.class, getRandomValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLString s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBString> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(String.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(String.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBTimeTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.sql.Time;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBTime;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBTimeTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Time\n        StudentCouchDBTime student = new StudentCouchDBTime();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Time) getRandomValue(Time.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Time\n        StudentCouchDBTime studentMax = new StudentCouchDBTime();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Time) getMaxValue(Time.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Time\n        StudentCouchDBTime studentMin = new StudentCouchDBTime();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Time) getMinValue(Time.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBTime studentMax = em.find(StudentCouchDBTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBTime studentMin = em.find(StudentCouchDBTime.class, getMinValue(Time.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBTime student = em.find(StudentCouchDBTime.class, getRandomValue(Time.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBTime student = em.find(StudentCouchDBTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBTime newStudent = em.find(StudentCouchDBTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTime s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBTime student : students)\n        {\n            Assert.assertEquals(getMinValue(Time.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTime> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTime s where s.id between \" + getMinValue(Time.class) + \" and \"\n                + getMaxValue(Time.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Time.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Time.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTime s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBTime student : students)\n        {\n            Assert.assertEquals(getMaxValue(Time.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTime s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBTime student : students)\n        {\n            Assert.assertEquals(getMaxValue(Time.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBTime studentMax = em.find(StudentCouchDBTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBTime.class, getMaxValue(Time.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLTime s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBTime newStudent = em.find(StudentCouchDBTime.class, getRandomValue(Time.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String upTimeQuery = \"Update StudentOracleNoSQLTime s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(upTimeQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBTime newStudent = em.find(StudentCouchDBTime.class, getRandomValue(Time.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTime s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTime s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTime s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Time.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTime s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTime s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Time.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLTime s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBTime> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Time.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Time) getRandomValue(Time.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBTimestampTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.sql.Timestamp;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBTimestamp;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBTimestampTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Time\n        StudentCouchDBTimestamp student = new StudentCouchDBTimestamp();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Timestamp) getRandomValue(Timestamp.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Time\n        StudentCouchDBTimestamp studentMax = new StudentCouchDBTimestamp();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Timestamp) getMaxValue(Timestamp.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Timestamp\n        StudentCouchDBTimestamp studentMin = new StudentCouchDBTimestamp();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Timestamp) getMinValue(Timestamp.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBTimestamp studentMax = em.find(StudentCouchDBTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBTimestamp studentMin = em.find(StudentCouchDBTimestamp.class, getMinValue(Timestamp.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBTimestamp student = em.find(StudentCouchDBTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBTimestamp student = em.find(StudentCouchDBTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBTimestamp newStudent = em.find(StudentCouchDBTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTimestamp s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBTimestamp student : students)\n        {\n            Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTimestamp> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTimestamp s where s.id between \" + getMinValue(Timestamp.class)\n                + \" and \" + getMaxValue(Timestamp.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTimestamp s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBTimestamp student : students)\n        {\n            Assert.assertEquals(getMaxValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTimestamp s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBTimestamp student : students)\n        {\n            Assert.assertEquals(getMaxValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBTimestamp studentMax = em.find(StudentCouchDBTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLTimestamp s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBTimestamp newStudent = em.find(StudentCouchDBTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String upTimeQuery = \"Update StudentOracleNoSQLTimestamp s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(upTimeQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBTimestamp newStudent = em.find(StudentCouchDBTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTimestamp s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTimestamp s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTimestamp s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTimestamp s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLTimestamp s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLTimestamp s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBTimestamp> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Timestamp) getRandomValue(Timestamp.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/datatypes/tests/StudentCouchDBUUIDTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.datatypes.tests;\n\nimport java.util.List;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.entities.StudentCouchDBUUID;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class StudentCouchDBUUIDTest extends CouchDBBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(pu);\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        super.dropDatabase();\n\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNativeQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * @param b\n     */\n    private void testNativeQuery(boolean b)\n    {\n        String s = \"Select * From \" + \"\\\"StudentOracleNoSQLUUID\\\"\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createNativeQuery(s, StudentCouchDBUUID.class);\n        List<StudentCouchDBUUID> results = q.getResultList();\n        Assert.assertNotNull(results);\n\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of UUID\n        StudentCouchDBUUID studentMax = new StudentCouchDBUUID();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((UUID) getMaxValue(UUID.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of UUID\n        StudentCouchDBUUID studentMin = new StudentCouchDBUUID();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((UUID) getMinValue(UUID.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of UUID\n        StudentCouchDBUUID student = new StudentCouchDBUUID();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((UUID) getRandomValue(UUID.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBUUID studentMax = em.find(StudentCouchDBUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBUUID studentMin = em.find(StudentCouchDBUUID.class, getMinValue(UUID.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBUUID student = em.find(StudentCouchDBUUID.class, getRandomValue(UUID.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCouchDBUUID student = em.find(StudentCouchDBUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBUUID newStudent = em.find(StudentCouchDBUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLUUID s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBUUID student : students)\n        {\n            Assert.assertEquals(getMinValue(UUID.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBUUID> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLUUID s where s.id between \" + getMinValue(UUID.class) + \" and \"\n                + getMaxValue(UUID.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(UUID.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLUUID s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBUUID student : students)\n        {\n            Assert.assertEquals(getMaxValue(UUID.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLUUID s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBUUID student : students)\n        {\n            Assert.assertEquals(getMaxValue(UUID.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCouchDBUUID studentMax = em.find(StudentCouchDBUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCouchDBUUID.class, getMaxValue(UUID.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLUUID s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBUUID newStudent = em.find(StudentCouchDBUUID.class, getRandomValue(UUID.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLUUID s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCouchDBUUID newStudent = em.find(StudentCouchDBUUID.class, getRandomValue(UUID.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLUUID s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLUUID s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLUUID s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(UUID.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLUUID s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCouchDBUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCouchDBUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLUUID s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCouchDBUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(UUID.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLUUID s \";\n        Query q = em.createQuery(query);\n        List<StudentCouchDBUUID> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCouchDBUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(UUID.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/AddressCouchMTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"AddressCouchMTM\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressCouchMTM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/AddressCouchMTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"AddressCouchMTO\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressCouchMTO\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/AddressCouchOTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"AddressCouchOTM\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressCouchOTM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/AddressCouchOTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"AddressCouchOTO\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressCouchOTO\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/CouchDBAddressJTAEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"couchdatabase@couchdbJTA_pu\")\npublic class CouchDBAddressJTAEntity\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * \n     */\n    public CouchDBAddressJTAEntity()\n    {\n    }\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/CouchDBCompoundKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * @author vivek.mishra\n */\n@Embeddable\npublic class CouchDBCompoundKey\n{\n    @Column\n    private String user_Id;\n\n    @Column\n    private int tweetId;\n\n    @Column\n    private UUID timeLineId;\n\n    /**\n     * \n     */\n    public CouchDBCompoundKey()\n    {\n    }\n\n    /**\n     * @param userId\n     * @param tweetId\n     * @param timeLineId\n     */\n    public CouchDBCompoundKey(String userId, int tweetId, UUID timeLineId)\n    {\n        this.user_Id = userId;\n        this.tweetId = tweetId;\n        this.timeLineId = timeLineId;\n    }\n\n    /**\n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return user_Id;\n    }\n\n    /**\n     * @return the tweetId\n     */\n    public int getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * @return the timeLineId\n     */\n    public UUID getTimeLineId()\n    {\n        return timeLineId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/CouchDBEmbeddedUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class RedisEmbeddedUser.\n * \n * @author vivek.mishra\n */\n\n@Entity\n@Table(name = \"User\", schema = \"couchdatabase@couchdb_pu\")\npublic class CouchDBEmbeddedUser\n{\n\n    /** The user id. */\n    @Id\n    private String userId;\n\n    /** The embeddable. */\n    @Embedded\n    private CouchDBCompoundKey embeddable;\n\n    /** The tweet body. */\n    @Column\n    private String tweetBody;\n\n    /** The tweet date. */\n    @Column\n    private Date tweetDate;\n\n    /**\n     * Instantiates a new redis embedded user.\n     */\n    public CouchDBEmbeddedUser()\n    {\n    }\n\n    /**\n     * Instantiates a new redis embedded user.\n     * \n     * @param userId\n     *            the user id\n     */\n    public CouchDBEmbeddedUser(String userId)\n    {\n        this.userId = userId;\n    }\n\n    /**\n     * Gets the tweet body.\n     * \n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * Gets the tweet date.\n     * \n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * Sets the tweet body.\n     * \n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * Sets the tweet date.\n     * \n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n    /**\n     * Gets the user id.\n     * \n     * @return the user id\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * Gets the embeddable.\n     * \n     * @return the embeddable\n     */\n    public CouchDBCompoundKey getEmbeddable()\n    {\n        return embeddable;\n    }\n\n    /**\n     * Sets the embeddable.\n     * \n     * @param embeddable\n     *            the new embeddable\n     */\n    public void setEmbeddable(CouchDBCompoundKey embeddable)\n    {\n        this.embeddable = embeddable;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/CouchDBPersonJTAEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"PERSONNEL\", schema = \"couchdatabase@couchdbJTA_pu\")\npublic class CouchDBPersonJTAEntity\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private CouchDBAddressJTAEntity address;\n\n    /**\n     * \n     */\n    public CouchDBPersonJTAEntity()\n    {\n    }\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public CouchDBAddressJTAEntity getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(CouchDBAddressJTAEntity address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/CouchDBPrimeUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"User\", schema = \"couchdatabase@couchdb_pu\")\npublic class CouchDBPrimeUser\n{\n\n    @EmbeddedId\n    private CouchDBCompoundKey key;\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private Date tweetDate;\n\n    public CouchDBPrimeUser()\n    {\n    }\n\n    public CouchDBPrimeUser(CouchDBCompoundKey key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the key\n     */\n    public CouchDBCompoundKey getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/CouchDBToken.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"tokens\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"tokenName\") })\npublic class CouchDBToken\n{\n    @Id\n    @Column(name = \"token_id\")\n    private String id;\n\n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"client_id\")\n    private CouchDBTokenClient client;\n\n    @Column\n    private String tokenName;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public CouchDBTokenClient getClient()\n    {\n        return client;\n    }\n\n    public void setClient(CouchDBTokenClient client)\n    {\n        this.client = client;\n    }\n\n    public String getTokenName()\n    {\n        return tokenName;\n    }\n\n    public void setTokenName(String tokenName)\n    {\n        this.tokenName = tokenName;\n    }\n\n}"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/CouchDBTokenClient.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"client\", schema = \"couchdatabase@couchdb_pu\")\npublic class CouchDBTokenClient\n{\n\n    @Id\n    @Column(name = \"client_id\")\n    private String id;\n\n    @Column(name = \"client_name\")\n    private String clientName;\n\n    @OneToMany(mappedBy = \"client\", fetch = FetchType.EAGER)\n    private Set<CouchDBToken> tokens;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public String getClientName()\n    {\n        return clientName;\n    }\n\n    public void setClientName(String clientName)\n    {\n        this.clientName = clientName;\n    }\n\n    public Set<CouchDBToken> getTokens()\n    {\n        return tokens;\n    }\n\n    public void setTokens(Set<CouchDBToken> tokens)\n    {\n        this.tokens = tokens;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/Month.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\npublic enum Month\n{\n    JAN, FEB, MARCH, APRIL, MAY, JUNE;\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/PersonCouchDB.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\npublic class PersonCouchDB\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    @Column(name = \"MONTH_ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Month month;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public Day getDay()\n    {\n        return day;\n    }\n\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n\n    public Month getMonth()\n    {\n        return month;\n    }\n\n    public void setMonth(Month month)\n    {\n        this.month = month;\n    }\n\n    public enum Day\n    {\n        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/PersonCouchMTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonCouchMTM\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonCouchMTM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"PERSONNEL_ADDRESS\", schema = \"couchdatabase\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Set<AddressCouchMTM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressCouchMTM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressCouchMTM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/PersonCouchMTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonCouchMTO\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonCouchMTO\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressCouchMTO address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressCouchMTO getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressCouchMTO address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/PersonCouchOTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonCouchOTM\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonCouchOTM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<AddressCouchOTM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressCouchOTM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressCouchOTM> addresses)\n    {\n        this.addresses = addresses;\n    }\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/entities/PersonCouchOTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonCouchOTO\", schema = \"couchdatabase@couchdb_pu\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonCouchOTO\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressCouchOTO address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressCouchOTO getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressCouchOTO address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/query/CouchDBQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.couchdb.query;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.couchdb.datatypes.tests.CouchDBBase;\nimport com.impetus.client.couchdb.entities.PersonCouchDB;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.query.QueryHandlerException;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class CouchDBQueryTest extends CouchDBBase\n{\n\n    private static final String ROW_KEY = \"1\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(CouchDBQueryTest.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(pu);\n        em = emf.createEntityManager();\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        init();\n    }\n\n    @Test\n    public void testPopulateEntites()\n    {\n        logger.info(\"On testPopulateEntities\");\n\n        final String originalName = \"vivek\";\n\n        // Find without where clause.\n        String findWithOutWhereClause = \"Select p from PersonCouchDB p\";\n        Query query = em.createQuery(findWithOutWhereClause);\n        List<PersonCouchDB> results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n\n        // find by key.\n        String findById = \"Select p from PersonCouchDB p where p.personId=:personId\";\n        query = em.createQuery(findById);\n        query.setParameter(\"personId\", ROW_KEY);\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n\n        // Find by key and now row key\n        String findByAge = \"Select p from PersonCouchDB p where p.age=:age\";\n        query = em.createQuery(findByAge);\n        query.setParameter(\"age\", 32);\n\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n        Assert.assertEquals(ROW_KEY, results.get(0).getPersonId());\n\n        // Find by key and now row key\n        String findByIdAndAge = \"Select p from PersonCouchDB p where p.personId=:personId AND p.age=:age\";\n        query = em.createQuery(findByIdAndAge);\n        query.setParameter(\"personId\", ROW_KEY);\n        query.setParameter(\"age\", 32);\n\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n\n        // find by between over non rowkey\n        String findAgeByBetween = \"Select p from PersonCouchDB p where p.age between :min AND :max\";\n        query = em.createQuery(findAgeByBetween);\n        query.setParameter(\"min\", 32);\n        query.setParameter(\"max\", 35);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n\n        // Between clause over rowkey\n        String findIdByBetween = \"Select p from PersonCouchDB p where p.personId between :min AND :max\";\n        query = em.createQuery(findIdByBetween);\n        query.setParameter(\"min\", ROW_KEY);\n        query.setParameter(\"max\", ROW_KEY + 1);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n\n        // Find by greater than and less than clause over non row key\n        String findAgeByGTELTEClause = \"Select p from PersonCouchDB p where p.age <=:max AND p.age>=:min\";\n        query = em.createQuery(findAgeByGTELTEClause);\n        query.setParameter(\"min\", 32);\n        query.setParameter(\"max\", 35);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n\n        // Find id by greater than and less than clause over non row key\n        String findIdByGTELTEClause = \"Select p from PersonCouchDB p where p.age <=:max AND p.age>=:min\";\n        query = em.createQuery(findIdByGTELTEClause);\n        query.setParameter(\"min\", 32);\n        query.setParameter(\"max\", 35);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNotNull(results.get(0).getPersonName());\n        Assert.assertNotNull(results.get(0).getAge());\n\n        // Invalid scenario.\n        try\n        {\n            // String invalidDifferentClause =\n            // \"Select p from PersonCouchDB p where p.personId=:personId AND p.age >=:age\";\n            // query = em.createQuery(invalidDifferentClause);\n            // query.setParameter(\"personId\", ROW_KEY);\n            // query.setParameter(\"age\", 32);\n            // query.getResultList();\n            // Assert.fail(\"Must have thrown query handler exception!\");\n        }\n\n        catch (QueryHandlerException qhex)\n        {\n            Assert.assertNotNull(qhex);\n        }\n\n        // Delete by query.\n        String deleteQuery = \"Delete from PersonCouchDB p\";\n        query = em.createQuery(deleteQuery);\n        int updateCount = query.executeUpdate();\n\n        Assert.assertEquals(3, updateCount);\n\n        // Search all after delete.\n        findWithOutWhereClause = \"Select p from PersonCouchDB p\";\n        query = em.createQuery(findWithOutWhereClause);\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertTrue(results.isEmpty());\n    }\n\n    @Test\n    public void testSelectedFields()\n    {\n        /*\n         * Test for selecting specific fields IMPORTANT NOTE: Selecting specific\n         * fields with 'WHERE' clause is yet not supported. It works only\n         * without 'WHERE' clause.\n         */\n\n        logger.info(\"On testSelectedFields\");\n\n        Query query = em.createQuery(\"Select p.age from PersonCouchDB p\");\n        List results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        int age = (int) results.get(0);\n        Assert.assertTrue(age == 29 || age == 32 || age == 34);\n        age = (int) results.get(1);\n        Assert.assertTrue(age == 29 || age == 32 || age == 34);\n        age = (int) results.get(2);\n        Assert.assertTrue(age == 29 || age == 32 || age == 34);\n\n        query = em.createQuery(\"Select p.age, p.personName from PersonCouchDB p\");\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(2, ((List) results.get(0)).size());\n        age = (int) ((List) results.get(0)).get(0);\n        Assert.assertTrue(age == 29 || age == 32 || age == 34);\n        Assert.assertEquals(\"vivek\", (String) ((List) results.get(0)).get(1));\n    }\n\n    @Test\n    public void testAggregations()\n    {\n        /*\n         * Test for selecting specific fields IMPORTANT NOTE: Selecting specific\n         * fields with 'WHERE' clause is yet not supported. It works only\n         * without 'WHERE' clause.\n         */\n\n        logger.info(\"On testAggregations\");\n\n        Query query = em.createQuery(\"Select count(p) from PersonCouchDB p\");\n        List results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, (int) results.get(0));\n\n        query = em.createQuery(\"Select count(p.age) from PersonCouchDB p\");\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, (int) results.get(0));\n\n        query = em.createQuery(\"Select sum(p.age) from PersonCouchDB p\");\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(95.0, (double) results.get(0));\n\n        query = em.createQuery(\"Select min(p.age) from PersonCouchDB p\");\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(29.0, (double) results.get(0));\n\n        query = em.createQuery(\"Select max(p.age) from PersonCouchDB p\");\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(34.0, (double) results.get(0));\n\n        query = em.createQuery(\"Select avg(p.age) from PersonCouchDB p\");\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(31.666666666666668, (double) results.get(0));\n    }\n\n    private void init()\n    {\n        String name = \"vivek\";\n        persistObject(name, 32, ROW_KEY);\n        persistObject(name, 34, ROW_KEY + 1);\n        persistObject(name, 29, ROW_KEY + 3);\n    }\n\n    private void persistObject(String name, int age, String id)\n    {\n        PersonCouchDB object = new PersonCouchDB();\n        object.setAge(age);\n        object.setPersonId(id);\n        object.setPersonName(name);\n        em.persist(object);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        emf = null;\n        super.dropDatabase();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/query/ResultIteratorTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.couchdb.query;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.datatypes.tests.CouchDBBase;\nimport com.impetus.client.couchdb.entities.CouchDBToken;\nimport com.impetus.client.couchdb.entities.CouchDBTokenClient;\nimport com.impetus.client.couchdb.entities.Month;\nimport com.impetus.client.couchdb.entities.PersonCouchDB;\nimport com.impetus.client.couchdb.entities.PersonCouchDB.Day;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.query.IResultIterator;\nimport com.impetus.kundera.query.Query;\n\n/**\n * @author Kuldeep.mishra junit for {@link IResultIterator}.\n */\npublic class ResultIteratorTest extends CouchDBBase\n{\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"couchdb_pu\");\n        super.setUpBase(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testScroll() throws Exception\n    {\n        onScroll();\n    }\n\n    @Test\n    public void testScrollAssociation() throws Exception\n    {\n        assertOnTokenScroll();\n    }\n\n    private void assertOnTokenScroll()\n    {\n        CouchDBToken token1 = new CouchDBToken();\n        token1.setId(\"tokenId1\");\n        token1.setTokenName(\"tokenName1\");\n        CouchDBTokenClient client = new CouchDBTokenClient();\n        client.setClientName(\"tokenClient1\");\n        client.setId(\"tokenClientId\");\n        token1.setClient(client);\n\n        CouchDBToken token2 = new CouchDBToken();\n        token2.setId(\"tokenId2\");\n        token2.setTokenName(\"tokenName2\");\n        token2.setClient(client);\n        em.persist(token1);\n        em.persist(token2);\n\n        String queryWithoutClause = \"Select t from CouchDBToken t\";\n        assertOnTokenScroll(queryWithoutClause, 2);\n\n        String queryWithClause = \"Select t from CouchDBToken t where t.tokenName='tokenName1'\";\n\n        assertOnTokenScroll(queryWithClause, 1);\n\n        // TODO:: Need to discuss with KK, this should be working with token\n        // support. Special scenario.\n        String queryWithIdClause = \"Select t from CouchDBToken t where t.id = 'tokenId1'\";\n        //\n        assertOnTokenScroll(queryWithIdClause, 1);\n\n    }\n\n    private void assertOnTokenScroll(String queryClause, int expected)\n    {\n        Query query = (Query) em.createQuery(queryClause, CouchDBToken.class);\n\n        int count = 0;\n        Iterator<CouchDBToken> tokens = query.iterate();\n        while (tokens.hasNext())\n        {\n            CouchDBToken token = tokens.next();\n            Assert.assertNotNull(token);\n            Assert.assertNotNull(token.getClient());\n            Assert.assertEquals(2, token.getClient().getTokens().size());\n            count++;\n        }\n\n        Assert.assertTrue(count > 0);\n        Assert.assertTrue(count == expected);\n    }\n\n    private void onScroll()\n    {\n        PersonCouchDB p1 = new PersonCouchDB();\n        p1.setPersonId(\"1\");\n        p1.setPersonName(\"vivek\");\n        p1.setAge(10);\n        p1.setDay(Day.THURSDAY);\n        p1.setMonth(Month.APRIL);\n\n        PersonCouchDB p2 = new PersonCouchDB();\n        p2.setPersonId(\"2\");\n        p2.setPersonName(\"vivek\");\n        p2.setAge(20);\n        p2.setDay(Day.THURSDAY);\n        p2.setMonth(Month.APRIL);\n\n        PersonCouchDB p3 = new PersonCouchDB();\n        p3.setPersonId(\"3\");\n        p3.setPersonName(\"vivek\");\n        p3.setAge(15);\n        p3.setDay(Day.THURSDAY);\n        p3.setMonth(Month.APRIL);\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        em.flush();\n        em.clear();\n        final String queryWithoutClause = \"Select p from PersonCouchDB p\";\n\n        assertOnScroll(queryWithoutClause, 3);\n\n        final String queryWithClause = \"Select p from PersonCouchDB p where p.personName = vivek\";\n\n        assertOnScroll(queryWithClause, 3);\n\n        final String queryWithAndClause = \"Select p from PersonCouchDB p where p.personName = vivek and p.age = 15\";\n\n        assertOnScroll(queryWithAndClause, 1);\n\n        final String queryWithLTClause = \"Select p from PersonCouchDB p where p.personName = vivek and p.age < 15\";\n\n        assertOnScroll(queryWithLTClause, 1);\n\n        // Don't uncomment it, because only one and clause is supported as of\n        // now.\n\n        // final String queryWithGTClause =\n        // \"Select p from PersonCouchDB p where p.personName = vivek and p.age >= 15\";\n        //\n        // assertOnScroll(queryWithGTClause, 2);\n        //\n        // final String queryWithLTGTClause =\n        // \"Select p from PersonCouchDB p where p.personName = vivek and p.age > 10 and p.age < 20\";\n        //\n        // assertOnScroll(queryWithLTGTClause, 1);\n        //\n        // final String queryWithLTGTEClause =\n        // \"Select p from PersonCouchDB p where p.personName = vivek and p.age >= 10 and p.age < 20\";\n        //\n        // assertOnScroll(queryWithLTGTEClause, 2);\n\n        String queryWithIdClause = \"Select p from PersonCouchDB p where p.personId = '2' \";\n        assertOnScroll(queryWithIdClause, 1);\n    }\n\n    private void assertOnScroll(final String queryWithoutClause, int expectedCount)\n    {\n        Query query = (Query) em.createQuery(queryWithoutClause, PersonCouchDB.class);\n\n        assertOnFetch(query, 0, expectedCount);\n        assertOnFetch(query, 2, expectedCount); // less records\n\n        assertOnFetch(query, 4, expectedCount); // more fetch size than\n                                                // available in db.\n        assertOnFetch(query, 3, expectedCount); // more fetch size than\n                                                // available in db.\n\n        assertOnFetch(query, null, expectedCount); // set to null;\n\n    }\n\n    private void assertOnFetch(Query query, Integer fetchSize, int expectedCount)\n    {\n        query.setFetchSize(fetchSize);\n        int counter = 0;\n        Iterator<PersonCouchDB> iter = query.iterate();\n\n        while (iter.hasNext())\n        {\n            Assert.assertNotNull(iter.next());\n            counter++;\n        }\n\n        Assert.assertEquals(counter, fetchSize == null || expectedCount < fetchSize ? expectedCount : fetchSize);\n        try\n        {\n            iter.next();\n            Assert.fail();\n        }\n        catch (NoSuchElementException nsex)\n        {\n            Assert.assertNotNull(nsex.getMessage());\n        }\n    }\n\n    public void tearDown(final String keyspace)\n    {\n        emf.close();\n        emf = null;\n        super.dropDatabase();\n    }\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/client/couchdb/utils/CouchDBTestUtils.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.couchdb.utils;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpRequest;\nimport org.apache.http.HttpRequestInterceptor;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.HttpResponseInterceptor;\nimport org.apache.http.auth.AuthScope;\nimport org.apache.http.auth.UsernamePasswordCredentials;\nimport org.apache.http.client.ClientProtocolException;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpDelete;\nimport org.apache.http.client.methods.HttpPut;\nimport org.apache.http.conn.scheme.PlainSocketFactory;\nimport org.apache.http.conn.scheme.Scheme;\nimport org.apache.http.conn.scheme.SchemeRegistry;\nimport org.apache.http.conn.scheme.SchemeSocketFactory;\nimport org.apache.http.impl.client.AbstractHttpClient;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport org.apache.http.impl.conn.PoolingClientConnectionManager;\nimport org.apache.http.params.CoreProtocolPNames;\nimport org.apache.http.protocol.HttpContext;\n\nimport com.google.gson.Gson;\nimport com.impetus.client.couchdb.CouchDBConstants;\nimport com.impetus.client.couchdb.CouchDBUtils;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * The Class CouchDBTestUtils.\n * \n * @author Kuldeep Mishra\n */\npublic class CouchDBTestUtils\n{\n\n    /**\n     * Initiate http client.\n     * \n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param persistenceUnit\n     *            the persistence unit\n     * @return the http client\n     */\n    public static HttpClient initiateHttpClient(final KunderaMetadata kunderaMetadata, String persistenceUnit)\n    {\n        PersistenceUnitMetadata pumMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\n                persistenceUnit);\n\n        SchemeSocketFactory ssf = null;\n        ssf = PlainSocketFactory.getSocketFactory();\n        SchemeRegistry schemeRegistry = new SchemeRegistry();\n        int port = Integer.parseInt(pumMetadata.getProperty(PersistenceProperties.KUNDERA_PORT));\n        String host = pumMetadata.getProperty(PersistenceProperties.KUNDERA_NODES);\n        String userName = pumMetadata.getProperty(PersistenceProperties.KUNDERA_USERNAME);\n        String password = pumMetadata.getProperty(PersistenceProperties.KUNDERA_PASSWORD);\n\n        schemeRegistry.register(new Scheme(\"http\", port, ssf));\n        PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);\n        HttpClient httpClient = new DefaultHttpClient(ccm);\n\n        try\n        {\n            // Http params\n            httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, \"UTF-8\");\n\n            // basic authentication\n            if (userName != null && password != null)\n            {\n                ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(new AuthScope(host, port),\n                        new UsernamePasswordCredentials(userName, password));\n            }\n            // request interceptor\n            ((DefaultHttpClient) httpClient).addRequestInterceptor(new HttpRequestInterceptor()\n            {\n                public void process(final HttpRequest request, final HttpContext context) throws IOException\n                {\n\n                }\n            });\n            // response interceptor\n            ((DefaultHttpClient) httpClient).addResponseInterceptor(new HttpResponseInterceptor()\n            {\n                public void process(final HttpResponse response, final HttpContext context) throws IOException\n                {\n\n                }\n            });\n        }\n        catch (Exception e)\n        {\n            throw new IllegalStateException(e);\n        }\n        return httpClient;\n    }\n\n    /**\n     * Creates the database.\n     * \n     * @param databaseName\n     *            the database name\n     * @param client\n     *            the client\n     * @param httpHost\n     *            the http host\n     */\n    public static void createDatabase(String databaseName, HttpClient client, HttpHost httpHost)\n    {\n        HttpResponse response = null;\n        try\n        {\n            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + databaseName, null, null);\n            HttpPut put = new HttpPut(uri);\n            response = client.execute(httpHost, put, CouchDBUtils.getContext(httpHost));\n        }\n        catch (URISyntaxException e)\n        {\n\n        }\n        catch (ClientProtocolException e)\n        {\n\n        }\n        catch (IOException e)\n        {\n\n        }\n        finally\n        {\n            CouchDBUtils.closeContent(response);\n        }\n    }\n\n    /**\n     * Drop database.\n     * \n     * @param databaseName\n     *            the database name\n     * @param client\n     *            the client\n     * @param httpHost\n     *            the http host\n     */\n    public static void dropDatabase(String databaseName, HttpClient client, HttpHost httpHost)\n    {\n        HttpResponse response = null;\n        try\n        {\n            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + databaseName, null, null);\n            HttpDelete delete = new HttpDelete(uri);\n\n            response = client.execute(httpHost, delete, CouchDBUtils.getContext(httpHost));\n        }\n        catch (URISyntaxException e)\n        {\n\n        }\n        catch (ClientProtocolException e)\n        {\n\n        }\n        catch (IOException e)\n        {\n\n        }\n        finally\n        {\n            CouchDBUtils.closeContent(response);\n        }\n    }\n\n    /**\n     * Creates the views.\n     * \n     * @param columns\n     *            the columns\n     * @param tableName\n     *            the table name\n     * @param httpHost\n     *            the http host\n     * @param databaseName\n     *            the database name\n     * @param httpClient\n     *            the http client\n     * @throws URISyntaxException\n     *             the URI syntax exception\n     * @throws ClientProtocolException\n     *             the client protocol exception\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    public static void createViews(String[] columns, String tableName, HttpHost httpHost, String databaseName,\n            HttpClient httpClient) throws URISyntaxException, ClientProtocolException, IOException\n    {\n        Gson gson = new Gson();\n        for (String columnName : columns)\n        {\n            List<String> columnList = new ArrayList<String>();\n            columnList.add(columnName);\n            CouchDBUtils.createDesignDocumentIfNotExist(httpClient, httpHost, gson, tableName, databaseName,\n                    columnName, columnList);\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/CouchDBEntityWithoutFieldsTest.java",
    "content": "package com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.mappedsuperclass.EntityWithoutFieldsBase;\n\n/**\n * @author amitkumar\n * \n *         Class to verify that at least one field in entity class is not\n *         mandatory if the superclass contains all the mandatory fields\n */\npublic class CouchDBEntityWithoutFieldsTest extends EntityWithoutFieldsBase\n{\n    @Before\n    public void setup()\n    {\n        persistenceUnit = \"couchdbMappedSuperClass_pu\";\n        setupInternal();\n    }\n\n    @Test\n    public void testEntityWithNoFields()\n    {\n        testEntityWithNoFieldsBase();\n    }\n\n    @Test\n    public void testEntityWithNoFields2LevelInheritance()\n    {\n        testEntityWithNoFields2LevelInheritanceBase();\n    }\n\n    @After\n    public void tearDown()\n    {\n        tearDownInternal();\n    }\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/CouchDBMappedSuperClassTest.java",
    "content": "package com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.Query;\n\nimport org.apache.http.HttpHost;\nimport org.apache.http.client.HttpClient;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.couchdb.utils.CouchDBTestUtils;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\npublic class CouchDBMappedSuperClassTest extends MappedSuperClassBase\n{\n\n    private HttpClient httpClient;\n\n    private HttpHost httpHost;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        _PU = \"couchdb_pu\";\n        setUpInternal();\n        httpClient = CouchDBTestUtils.initiateHttpClient(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(),\n                _PU);\n        httpHost = new HttpHost(\"localhost\", 5984);\n        CouchDBTestUtils.createViews(new String[] { \"CREDIT_BANK_IDENT\" }, \"TRNX_CREDIT\", httpHost, \"couchdatabase\",\n                httpClient);\n        CouchDBTestUtils.createViews(new String[] { \"DEBIT_BANK_IDENT\" }, \"DebitTransaction\", httpHost,\n                \"couchdatabase\", httpClient);\n    }\n\n    @Test\n    public void test()\n    {\n        assertInternal(true);\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        // Delete by query.\n        String deleteQuery = \"Delete from CreditTransaction p\";\n\n        Query query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n\n        deleteQuery = \"Delete from DebitTransaction p\";\n\n        query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n\n        tearDownInternal();\n        CouchDBTestUtils.dropDatabase(\"couchdatabase\", httpClient, httpHost);\n    }\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/CreditTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra Credit transaction extends {@link Transaction}\n * \n */\n\n@Entity\n@Table(name = \"TRNX_CREDIT\")\n@DiscriminatorValue(value = \"credit\")\n@AttributeOverride(name = \"bankIdentifier\", column = @Column(name = \"CREDIT_BANK_IDENT\"))\npublic class CreditTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public CreditTransaction()\n    {\n\n    }\n\n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/DebitTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\n\n/**\n * @author vivek.mishra Debit transaction extends {@link Transaction}\n * \n */\n@Entity\n@DiscriminatorValue(value = \"debit\")\n@AttributeOverrides(value = { @AttributeOverride(name = \"txId\", column = @Column(name = \"DEBIT_ID\")),\n        @AttributeOverride(name = \"bankIdentifier\", column = @Column(name = \"DEBIT_BANK_IDENT\")),\n        @AttributeOverride(name = \"transactionDt\", column = @Column(name = \"TX_DT\")) })\npublic class DebitTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public DebitTransaction()\n    {\n\n    }\n\n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"couchdb_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"5984\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"couchdatabase\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"couchdb\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"couchdb\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.couchdb.CouchDBClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"couchdb_assoc\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileHandset</class>\r\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileManufacturer</class>\r\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileOperatingSystem</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"5984\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"couchdatabase\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"couchdb\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"couchdb\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.couchdb.CouchDBClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"couchdbJTA_pu\"\r\n\t\ttransaction-type=\"JTA\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"5984\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"couchdatabase\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"couchdb\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"couchdb\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.couchdb.CouchDBClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\t<persistence-unit name=\"couchdbMappedSuperClass_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.Person</class>\r\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.PersonChild</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"5984\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"couchdatabase\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"couchdb\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"couchdb\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.couchdb.CouchDBClientFactory\" />\r\n\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"couchdbESAggragation_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.query.Person</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"5984\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"couchdatabase\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"couchdb\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"couchdb\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.couchdb.CouchDBClientFactory\" />\r\n\t\t\t<property name=\"kundera.indexer.class\" value=\"com.impetus.client.es.index.ESIndexer\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n</persistence>\r\n"
  },
  {
    "path": "src/kundera-couchdb/src/test/resources/esindexer.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<indexerProperties>\n\t<nodes>\n\t\t<node>\n\t\t\t<properties>\n\t\t\t\t<property name=\"host\" value=\"localhost\" />\n\t\t\t\t<property name=\"port\" value=\"9300\" />\n\t\t\t</properties>\n\t\t</node>\n\t</nodes>\n</indexerProperties>"
  },
  {
    "path": "src/kundera-couchdb/src/test/resources/log4j.properties",
    "content": "#log4j.rootLogger=INFO, DRFA, CONSOLE\r\nlog4j.logger.com.impetus=WARN, CONSOLE, DRFA\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n"
  },
  {
    "path": "src/kundera-elastic-search/pom.xml",
    "content": "<?xml version=\"1.0\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<artifactId>kundera</artifactId>\n\t\t<groupId>com.impetus</groupId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-elastic-search</artifactId>\n\t<name>kundera-elastic-search</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<es.version>2.3.3</es.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<!-- Kundera dependencies -->\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\n\t\t<!-- ES dependencies -->\n\t\t<dependency>\n\t\t\t<groupId>org.elasticsearch</groupId>\n\t\t\t<artifactId>elasticsearch</artifactId>\n\t\t\t<version>${es.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.fasterxml.jackson.core</groupId>\n\t\t\t<artifactId>jackson-databind</artifactId>\n\t\t\t<version>2.1.3</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<!-- contiperf dependency should not be here -->\n\t\t<dependency>\n\t\t\t<groupId>org.databene</groupId>\n\t\t\t<artifactId>contiperf</artifactId>\n\t\t\t<version>2.2.0</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<!-- http://mvnrepository.com/artifact/com.carrotsearch/hppc -->\n\t\t<dependency>\n\t\t\t<groupId>com.carrotsearch</groupId>\n\t\t\t<artifactId>hppc</artifactId>\n\t\t\t<version>0.7.1</version>\n\t\t</dependency>\n\t\t<!-- http://mvnrepository.com/artifact/com.ning/compress-lzf -->\n\t\t<dependency>\n\t\t\t<groupId>com.ning</groupId>\n\t\t\t<artifactId>compress-lzf</artifactId>\n\t\t\t<version>1.0.3</version>\n\t\t</dependency>\n\n\t</dependencies>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESClient.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.OrderByItem;\nimport org.elasticsearch.ElasticsearchException;\nimport org.elasticsearch.action.bulk.BulkRequestBuilder;\nimport org.elasticsearch.action.bulk.BulkResponse;\nimport org.elasticsearch.action.delete.DeleteRequest;\nimport org.elasticsearch.action.get.GetResponse;\nimport org.elasticsearch.action.index.IndexRequest;\nimport org.elasticsearch.action.index.IndexResponse;\nimport org.elasticsearch.action.search.SearchRequestBuilder;\nimport org.elasticsearch.action.search.SearchResponse;\nimport org.elasticsearch.action.update.UpdateRequest;\nimport org.elasticsearch.client.transport.TransportClient;\nimport org.elasticsearch.index.query.FilteredQueryBuilder;\nimport org.elasticsearch.index.query.QueryBuilder;\nimport org.elasticsearch.index.query.QueryBuilders;\nimport org.elasticsearch.index.query.TermQueryBuilder;\nimport org.elasticsearch.search.SearchHit;\nimport org.elasticsearch.search.SearchHitField;\nimport org.elasticsearch.search.SearchHits;\nimport org.elasticsearch.search.aggregations.AggregationBuilder;\nimport org.elasticsearch.search.sort.SortOrder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.es.utils.ESResponseWrapper;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.lifecycle.states.RemovedState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQueryUtils;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class ESClient.\n * \n * @author vivek.mishra Elastic search client implementation on {@link Client}\n */\npublic class ESClient extends ClientBase implements Client<ESQuery>, Batcher, ClientPropertiesSetter\n{\n    /** The factory. */\n    private ESClientFactory factory;\n\n    /** The tx client. */\n    private TransportClient txClient;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /** log for this class. */\n    private static Logger logger = LoggerFactory.getLogger(ESClient.class);\n\n    /** list of nodes for batch processing. */\n    private List<Node> nodes = new ArrayList<Node>();\n\n    /** batch size. */\n    private int batchSize;\n\n    /** The client properties. */\n    private Map clientProperties;\n\n    /** The set reresh indexes. */\n    private boolean setRereshIndexes;\n\n    /** The Constant KEY_SEPERATOR. */\n    private static final String KEY_SEPERATOR = \"\\001\";\n\n    /** The es response reader. */\n    private ESResponseWrapper esResponseReader = new ESResponseWrapper();\n\n    /**\n     * Instantiates a new ES client.\n     * \n     * @param factory\n     *            the factory\n     * @param client\n     *            the client\n     * @param externalProperties\n     *            the external properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param persistenceUnit\n     *            the persistence unit\n     */\n    ESClient(final ESClientFactory factory, final TransportClient client, final Map<String, Object> externalProperties,\n            final KunderaMetadata kunderaMetadata, final String persistenceUnit)\n    {\n        super(kunderaMetadata, externalProperties, persistenceUnit);\n        this.factory = factory;\n        this.clientMetadata = factory.getClientMetadata();\n        this.txClient = client;\n        this.reader = new ESEntityReader(kunderaMetadata);\n        setBatchSize(getPersistenceUnit(), externalProperties);\n        setRefreshIndexes(\n                kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit).getProperties(),\n                externalProperties);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.\n     * metadata .model.EntityMetadata, java.lang.Object, java.lang.Object,\n     * java.util.List)\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n        try\n        {\n            Map<String, Object> values = new HashMap<String, Object>();\n\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                    .getMetamodel(entityMetadata.getPersistenceUnit());\n\n            EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n\n            String keyAsString = getKeyAsString(id, entityMetadata, metaModel);\n\n            addSource(entity, values, entityType);\n\n            addRelations(rlHolders, values);\n            addDiscriminator(values, entityType);\n\n            IndexResponse response = txClient\n                    .prepareIndex(entityMetadata.getSchema().toLowerCase(), entityMetadata.getTableName(), keyAsString)\n                    .setSource(values).setRefresh(isRefreshIndexes()).execute().actionGet();\n\n            assert response.getId() != null;\n        }\n        finally\n        {\n            // Nothing as of now.\n        }\n\n    }\n\n    /**\n     * Adds the discriminator.\n     * \n     * @param values\n     *            the values\n     * @param entityType\n     *            the entity type\n     */\n    private void addDiscriminator(Map<String, Object> values, EntityType entityType)\n    {\n        String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n        String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();\n\n        // No need to check for empty or blank, as considering it as valid name\n        // for nosql!\n        if (discrColumn != null && discrValue != null)\n        {\n            values.put(discrColumn, discrValue);\n        }\n    }\n\n    /**\n     * Adds the relations.\n     * \n     * @param rlHolders\n     *            the rl holders\n     * @param values\n     *            the values\n     */\n    private void addRelations(List<RelationHolder> rlHolders, Map<String, Object> values)\n    {\n        if (rlHolders != null)\n        {\n            for (RelationHolder relation : rlHolders)\n            {\n                values.put(relation.getRelationName(), relation.getRelationValue());\n            }\n        }\n    }\n\n    /**\n     * Adds the source.\n     * \n     * @param entity\n     *            the entity\n     * @param values\n     *            the values\n     * @param entityType\n     *            the entity type\n     */\n    private void addSource(Object entity, Map<String, Object> values, EntityType entityType)\n    {\n        Set<Attribute> attributes = entityType.getAttributes();\n        for (Attribute attrib : attributes)\n        {\n            if (!attrib.isAssociation())\n            {\n                Object value = PropertyAccessorHelper.getObject(entity, (Field) attrib.getJavaMember());\n                values.put(((AbstractAttribute) attrib).getJPAColumnName(), value);\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.Object)\n     */\n    @Override\n    public Object find(Class entityClass, Object key)\n    {\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        GetResponse get = null;\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(metadata.getPersistenceUnit());\n\n        EntityType entityType = metaModel.entity(metadata.getEntityClazz());\n\n        String keyAsString = getKeyAsString(key, metadata, metaModel);\n        try\n        {\n            get = txClient.prepareGet(metadata.getSchema().toLowerCase(), metadata.getTableName(), keyAsString)\n                    .setOperationThreaded(false).execute().get();\n        }\n        catch (InterruptedException iex)\n        {\n            logger.error(\"Error while find record of {}, Caused by :.\", entityClass.getSimpleName(), iex);\n            throw new PersistenceException(iex);\n        }\n        catch (ExecutionException eex)\n        {\n            logger.error(\"Error while find record of {}, Caused by :.\", entityClass.getSimpleName(), eex);\n            throw new PersistenceException(eex);\n        }\n\n        Map<String, Object> results = get.getSource();\n\n        Object result = null;\n\n        if (get.isExists())\n        {\n            result = KunderaCoreUtils.createNewInstance(entityClass);\n            PropertyAccessorHelper.setId(result, metadata, key);\n            result = esResponseReader.wrapFindResult(results, entityType, result, metadata, true);\n        }\n\n        return result;\n    }\n\n    /**\n     * Execute query.\n     *\n     * @param filter\n     *            the filter\n     * @param aggregation\n     *            the aggregation\n     * @param entityMetadata\n     *            the entity metadata\n     * @param query\n     *            the query\n     * @param firstResult\n     *            the first result\n     * @param maxResults\n     *            the max results\n     * @return the list\n     */\n    public List executeQuery(QueryBuilder filter, AggregationBuilder aggregation, final EntityMetadata entityMetadata,\n            KunderaQuery query, int firstResult, int maxResults)\n    {\n        String[] fieldsToSelect = query.getResult();\n        Class clazz = entityMetadata.getEntityClazz();\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(entityMetadata.getPersistenceUnit());\n\n        FilteredQueryBuilder queryBuilder = QueryBuilders.filteredQuery(null, filter);\n        SearchRequestBuilder builder = txClient.prepareSearch(entityMetadata.getSchema().toLowerCase())\n                .setTypes(entityMetadata.getTableName());\n\n        addFieldsToBuilder(fieldsToSelect, clazz, metaModel, builder);\n\n        if (aggregation == null)\n        {\n            builder.setQuery(queryBuilder);\n            builder.setFrom(firstResult);\n            builder.setSize(maxResults);\n            addSortOrder(builder, query, entityMetadata);\n        }\n        else\n        {\n            logger.debug(\"Aggregated query identified\");\n            builder.addAggregation(aggregation);\n\n            if (fieldsToSelect.length == 1\n                    || (query.isSelectStatement() && query.getSelectStatement().hasGroupByClause()))\n            {\n                builder.setSize(0);\n            }\n        }\n\n        SearchResponse response = null;\n        logger.debug(\"Query generated: \" + builder);\n\n        try\n        {\n            response = builder.execute().actionGet();\n            logger.debug(\"Query execution response: \" + response);\n        }\n        catch (ElasticsearchException e)\n        {\n            logger.error(\"Exception occured while executing query on Elasticsearch.\", e);\n            throw new KunderaException(\"Exception occured while executing query on Elasticsearch.\", e);\n        }\n\n        return esResponseReader.parseResponse(response, aggregation, fieldsToSelect, metaModel, clazz, entityMetadata,\n                query);\n    }\n\n    /**\n     * Adds the sort order.\n     * \n     * @param builder\n     *            the builder\n     * @param query\n     *            the query\n     * @param entityMetadata\n     *            the entity metadata\n     */\n    private void addSortOrder(SearchRequestBuilder builder, KunderaQuery query, EntityMetadata entityMetadata)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(entityMetadata.getPersistenceUnit());\n\n        List<OrderByItem> orderList = KunderaQueryUtils.getOrderByItems(query.getJpqlExpression());\n\n        for (OrderByItem orderByItem : orderList)\n        {\n            String ordering = orderByItem.getOrdering().toString();\n\n            if (ordering.equalsIgnoreCase(ESConstants.DEFAULT))\n            {\n                ordering = Expression.ASC;\n            }\n\n            builder.addSort(KunderaCoreUtils.getJPAColumnName(orderByItem.getExpression().toParsedText(),\n                    entityMetadata, metaModel), SortOrder.valueOf(ordering));\n        }\n    }\n\n    /**\n     * Adds the fields to builder\n     * \n     * @param fieldsToSelect\n     *            the fields to select\n     * @param clazz\n     *            the clazz\n     * @param metaModel\n     *            the meta model\n     * @param builder\n     *            the builder\n     */\n    private void addFieldsToBuilder(String[] fieldsToSelect, Class clazz, MetamodelImpl metaModel,\n            SearchRequestBuilder builder)\n    {\n        if (fieldsToSelect != null && fieldsToSelect.length > 1 && !(fieldsToSelect[1] == null))\n        {\n            logger.debug(\"Fields added in query are: \");\n            for (int i = 1; i < fieldsToSelect.length; i++)\n            {\n                logger.debug(i + \" : \" + fieldsToSelect[i]);\n                builder = builder.addField(((AbstractAttribute) metaModel.entity(clazz).getAttribute(fieldsToSelect[i]))\n                        .getJPAColumnName());\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.String[], java.lang.Object[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    @Override\n    public void close()\n    {\n        clear();\n        reader = null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    public void delete(Object entity, Object pKey)\n    {\n        if (entity != null)\n        {\n            EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                    .getMetamodel(metadata.getPersistenceUnit());\n\n            EntityType entityType = metaModel.entity(metadata.getEntityClazz());\n\n            String keyAsString = getKeyAsString(pKey, metadata, metaModel);\n\n            try\n            {\n                txClient.prepareDelete(metadata.getSchema().toLowerCase(), metadata.getTableName(),\n                        keyAsString.toString()/* index, type, id */).setRefresh(isRefreshIndexes()).execute().get();\n            }\n            catch (InterruptedException iex)\n            {\n                logger.error(\"Error while deleting record of {}, Caused by :.\", pKey, iex);\n                throw new PersistenceException(iex);\n            }\n            catch (ExecutionException eex)\n            {\n                logger.error(\"Error while deleting record of {}, Caused by :.\", pKey, eex);\n                throw new PersistenceException(eex);\n            }\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera\n     * .persistence.context.jointable.JoinTableData)\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        String tableName = joinTableData.getJoinTableName();\n\n        String inverseJoinColumn = joinTableData.getInverseJoinColumnName();\n\n        String joinColumn = joinTableData.getJoinColumnName();\n\n        String schemaName = joinTableData.getSchemaName();\n\n        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();\n\n        Set<Object> joinKeys = joinTableRecords.keySet();\n\n        BulkRequestBuilder bulkRequest = txClient.prepareBulk().setRefresh(isRefreshIndexes());\n\n        /**\n         * 1_p => 1_a1,1_a2 1_a1=> 1_p,1_p1\n         * \n         * Example: join table : PERSON_ADDRESS join column : PERSON_ID (1_p)\n         * inverse join column : ADDRESS_ID (1_a) store in ES: schema name:\n         * PERSON_ADDRESS type: PERSON id: 1_p\\0011_a\n         * \n         * PERSON_ADDRESS:1_p_1_a PERSON_ID 1_p ADDRESS_ID 1_a\n         * \n         * source: (PERSON_ID, 1_p) (ADDRESS_ID, 1_a)\n         * \n         * embeddable keys over many to many does not work.\n         */\n\n        boolean found = false;\n        for (Object key : joinKeys)\n        {\n            Set<Object> inversejoinTableRecords = joinTableRecords.get(key);\n            Map<String, Object> source = new HashMap<String, Object>();\n\n            for (Object inverseObj : inversejoinTableRecords)\n            {\n                source = new HashMap<String, Object>();\n                source.put(joinTableData.getJoinColumnName(), key);\n                source.put(joinTableData.getInverseJoinColumnName(), inverseObj);\n\n                String joinKeyAsStr = PropertyAccessorHelper.getString(key);\n                String inverseKeyAsStr = PropertyAccessorHelper.getString(inverseObj);\n\n                String keyAsString = joinKeyAsStr + KEY_SEPERATOR + inverseKeyAsStr;\n                IndexRequest request = new IndexRequest(schemaName.toLowerCase(), tableName, keyAsString)\n                        .source(source);\n                found = true;\n                bulkRequest.add(request);\n            }\n        }\n\n        // check made, as bulk request throws an error, in case no request is\n        // present.\n        if (found)\n        {\n            bulkRequest.execute().actionGet();\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,\n            Object pKeyColumnValue, Class columnJavaType)\n    {\n        // fetch list ADDRESS_ID for given PERSON_ID\n        QueryBuilder filterBuilder = new TermQueryBuilder(pKeyColumnName, pKeyColumnValue);\n\n        SearchResponse response = txClient.prepareSearch(schemaName.toLowerCase()).setTypes(tableName)\n                .setPostFilter(filterBuilder).addField(columnName).execute().actionGet();\n\n        SearchHits hits = response.getHits();\n\n        List columns = new ArrayList();\n        for (SearchHit hit : hits.getHits())\n        {\n            Map<String, SearchHitField> fields = hit.getFields();\n            columns.add(fields.get(columnName).getValue());\n        }\n\n        return columns;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n\n        TermQueryBuilder filter = QueryBuilders.termQuery(columnName, columnValue);\n\n        SearchResponse response = txClient.prepareSearch(schemaName.toLowerCase()).setTypes(tableName)\n                .addField(pKeyName).setPostFilter(filter).execute().actionGet();\n\n        SearchHits hits = response.getHits();\n\n        Long length = hits.getTotalHits();\n        int absoluteLength = length.intValue();\n        Object[] ids = new Object[absoluteLength];\n\n        int counter = 0;\n        for (SearchHit hit : hits.getHits())\n        {\n            Map<String, SearchHitField> fields = hit.getFields();\n            ids[counter++] = fields.get(pKeyName).getValue();\n        }\n\n        return ids;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    @Override\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n        // TODO: implement using scroll/scan and bulk delete requests\n        // Map<String, Object> querySource = new HashMap<String, Object>();\n        // querySource.put(columnName, columnValue);\n        //\n        // DeleteByQueryRequestBuilder deleteQueryBuilder =\n        // txClient.prepareDeleteByQuery(schemaName.toLowerCase())\n        // .setSource(querySource).setTypes(tableName);\n        //\n        // deleteQueryBuilder.execute().actionGet();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n        GetResponse get = null;\n\n        List results = new ArrayList();\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n\n        try\n        {\n            SearchResponse response = txClient\n                    .prepareSearch(metadata.getSchema()\n                            .toLowerCase())/*\n                                            * . addFields ( \"*\" )\n                                            */\n                    .setTypes(metadata.getTableName()).setQuery(QueryBuilders.termQuery(colName, colValue)).execute()\n                    .get();\n\n            SearchHits hits = response.getHits();\n            for (SearchHit hit : hits)\n            {\n                MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                        .getMetamodel(metadata.getPersistenceUnit());\n\n                EntityType entityType = metaModel.entity(entityClazz);\n                Map<String, Object> searchResults = hit.getSource();\n                // hit\n                Object result = null;\n                result = KunderaCoreUtils.createNewInstance(entityClazz);\n                result = esResponseReader.wrapFindResult(searchResults, entityType, result, metadata, false);\n                if (result != null)\n                {\n                    results.add(result);\n                }\n            }\n        }\n        catch (InterruptedException iex)\n        {\n            logger.error(\"Error while find record of {}, Caused by :.\", entityClazz.getSimpleName(), iex);\n            throw new PersistenceException(iex);\n        }\n        catch (ExecutionException eex)\n        {\n            logger.error(\"Error while find record of {}, Caused by :.\", entityClazz.getSimpleName(), eex);\n            throw new PersistenceException(eex);\n        }\n\n        return results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<ESQuery> getQueryImplementor()\n    {\n        return ESQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.api.Batcher#addBatch(com.impetus.kundera\n     * .graph.Node)\n     */\n    @Override\n    public void addBatch(Node node)\n    {\n\n        if (node != null)\n        {\n            nodes.add(node);\n        }\n\n        onBatchLimit();\n\n    }\n\n    /**\n     * Check on batch limit.\n     */\n    private void onBatchLimit()\n    {\n        if (batchSize > 0 && batchSize == nodes.size())\n        {\n            executeBatch();\n            nodes.clear();\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#executeBatch()\n     */\n    @Override\n    public int executeBatch()\n    {\n        BulkRequestBuilder bulkRequest = txClient.prepareBulk().setRefresh(isRefreshIndexes());\n\n        try\n        {\n            for (Node node : nodes)\n            {\n                if (node.isDirty())\n                {\n                    node.handlePreEvent();\n                    Object entity = node.getData();\n                    Object id = node.getEntityId();\n                    EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                            node.getDataClass());\n\n                    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                            .getMetamodel(metadata.getPersistenceUnit());\n\n                    EntityType entityType = metaModel.entity(metadata.getEntityClazz());\n\n                    String key = getKeyAsString(id, metadata, metaModel);\n\n                    if (node.isInState(RemovedState.class))\n                    {\n                        // create a delete request.\n\n                        DeleteRequest request = new DeleteRequest(metadata.getSchema().toLowerCase(),\n                                metadata.getTableName(), key);\n                        bulkRequest.add(request);\n\n                    }\n                    else if (node.isUpdate())\n                    {\n                        Map<String, Object> values = new HashMap<String, Object>();\n                        List<RelationHolder> relationHolders = getRelationHolders(node);\n\n                        addSource(entity, values, entityType);\n\n                        addRelations(relationHolders, values);\n\n                        UpdateRequest request = new UpdateRequest(metadata.getSchema().toLowerCase(),\n                                metadata.getTableName(), key).doc(values);\n                        bulkRequest.add(request);\n                    }\n                    else\n                    {\n                        // create an insert request.\n                        Map<String, Object> values = new HashMap<String, Object>();\n                        List<RelationHolder> relationHolders = getRelationHolders(node);\n\n                        addSource(entity, values, entityType);\n\n                        addRelations(relationHolders, values);\n\n                        IndexRequest request = new IndexRequest(metadata.getSchema().toLowerCase(),\n                                metadata.getTableName(), key).source(values);\n                        bulkRequest.add(request);\n\n                    }\n\n                }\n            }\n\n            BulkResponse response = null;\n            if (nodes != null && !nodes.isEmpty())\n            {\n                // bulkRequest.setRefresh(true);\n                response = bulkRequest.execute().actionGet();\n            }\n            return response != null ? response.getItems().length : 0;\n        }\n        finally\n        {\n            clear();\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#getBatchSize()\n     */\n    @Override\n    public int getBatchSize()\n    {\n        return batchSize;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#clear()\n     */\n    @Override\n    public void clear()\n    {\n        if (nodes != null)\n        {\n            nodes.clear();\n            nodes = new ArrayList<Node>();\n        }\n    }\n\n    /**\n     * Gets the key as string.\n     * \n     * @param id\n     *            the id\n     * @param metadata\n     *            the metadata\n     * @param metaModel\n     *            the meta model\n     * @return the key as string\n     */\n    private String getKeyAsString(Object id, EntityMetadata metadata, MetamodelImpl metaModel)\n    {\n        if (metaModel.isEmbeddable(((AbstractAttribute) metadata.getIdAttribute()).getBindableJavaType()))\n        {\n            return KunderaCoreUtils.prepareCompositeKey(metadata, id);\n        }\n        return id.toString();\n    }\n\n    /**\n     * Sets the batch size.\n     * \n     * @param persistenceUnit\n     *            the persistence unit\n     * @param puProperties\n     *            the pu properties\n     */\n    private void setBatchSize(String persistenceUnit, Map<String, Object> puProperties)\n    {\n        String batch_Size = null;\n        if (puProperties != null)\n        {\n            Object externalBatchSize = puProperties.get(PersistenceProperties.KUNDERA_BATCH_SIZE);\n            externalBatchSize = externalBatchSize != null ? externalBatchSize.toString() : null;\n            batch_Size = puProperties != null ? (String) externalBatchSize : null;\n            if (batch_Size != null)\n            {\n                batchSize = Integer.valueOf(batch_Size);\n                if (batchSize == 0)\n                {\n                    throw new IllegalArgumentException(\"kundera.batch.size property must be numeric and > 0.\");\n                }\n            }\n        }\n        else if (batch_Size == null)\n        {\n            PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\n                    persistenceUnit);\n            batchSize = puMetadata != null ? puMetadata.getBatchSize() : 0;\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientPropertiesSetter#\n     * populateClientProperties (com.impetus.kundera.client.Client,\n     * java.util.Map)\n     */\n    @Override\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        this.clientProperties = properties;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        return (Generator) KunderaCoreUtils.createNewInstance(EsIdGenerator.class);\n    }\n\n    /**\n     * Sets the refresh indexes.\n     *\n     * @param puProps\n     *            the pu props\n     * @param externalProperties\n     *            the external properties\n     */\n    private void setRefreshIndexes(Properties puProps, Map<String, Object> externalProperties)\n    {\n        Object refreshIndexes = null;\n\n        /*\n         * Check from properties set while creating emf\n         * \n         */\n        if (externalProperties.get(ESConstants.KUNDERA_ES_REFRESH_INDEXES) != null)\n        {\n\n            refreshIndexes = externalProperties.get(ESConstants.KUNDERA_ES_REFRESH_INDEXES);\n\n        }\n\n        /*\n         * Check from PU Properties\n         * \n         */\n        if (refreshIndexes == null && puProps.get(ESConstants.KUNDERA_ES_REFRESH_INDEXES) != null)\n        {\n\n            refreshIndexes = puProps.get(ESConstants.KUNDERA_ES_REFRESH_INDEXES);\n\n        }\n\n        if (refreshIndexes != null)\n        {\n            if (refreshIndexes instanceof Boolean)\n            {\n                this.setRereshIndexes = (boolean) refreshIndexes;\n            }\n            else\n            {\n                this.setRereshIndexes = Boolean.parseBoolean((String) refreshIndexes);\n            }\n        }\n    }\n\n    /**\n     * Checks if is refresh indexes.\n     *\n     * @return true, if is refresh indexes\n     */\n    private boolean isRefreshIndexes()\n    {\n\n        if (clientProperties != null)\n        {\n\n            Object refreshIndexes = clientProperties.get(ESConstants.ES_REFRESH_INDEXES);\n\n            if (refreshIndexes != null && refreshIndexes instanceof Boolean)\n            {\n                return (boolean) refreshIndexes;\n            }\n            else\n            {\n                return Boolean.parseBoolean((String) refreshIndexes);\n            }\n\n        }\n        else\n        {\n            return this.setRereshIndexes;\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESClientFactory.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.net.InetSocketAddress;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.elasticsearch.client.transport.TransportClient;\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.common.transport.InetSocketTransportAddress;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * @author vivek.mishra Client factory implementation for elastic search.\n */\npublic class ESClientFactory extends GenericClientFactory\n{\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.ClientFactory#getSchemaManager(java.util.Map)\n     */\n    @Override\n    public SchemaManager getSchemaManager(Map<String, Object> puProperties)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.ClientLifeCycleManager#destroy()\n     */\n    @Override\n    public void destroy()\n    {\n        this.externalProperties = null;\n        Object connection = getConnectionPoolOrConnection();\n\n        if (connection != null)\n        {\n            ((TransportClient) connection).close();\n\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initialize(java.util.Map)\n     */\n    @Override\n    public void initialize(Map<String, Object> puProperties)\n    {\n        this.externalProperties = puProperties;\n\n        this.propertyReader = new ESClientPropertyReader(externalProperties, kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(getPersistenceUnit()));\n        propertyReader.read(getPersistenceUnit());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#createPoolOrConnection()\n     */\n    @Override\n    protected Object createPoolOrConnection()\n    {\n        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(getPersistenceUnit());\n\n        Properties props = persistenceUnitMetadata.getProperties();\n\n        String host = externalProperties != null ? (String) externalProperties.get(PersistenceProperties.KUNDERA_NODES)\n                : null;\n        String port = externalProperties != null ? (String) externalProperties.get(PersistenceProperties.KUNDERA_PORT)\n                : null;\n\n        if (host == null)\n        {\n            host = props.getProperty(PersistenceProperties.KUNDERA_NODES);\n        }\n\n        if (port == null)\n        {\n            port = props.getProperty(PersistenceProperties.KUNDERA_PORT);\n        }\n\n        String[] hosts = getHosts(host);\n\n        Properties properties = ((ESClientPropertyReader) propertyReader).getConnectionProperties();\n\n        Builder builder = Settings.settingsBuilder();\n\n        builder.put(\"client.transport.sniff\", true);\n\n        if (properties != null)\n        {\n            builder.put(properties);\n        }\n\n        Settings settings = builder.build();\n\n        TransportClient client = TransportClient.builder().settings(settings).build();\n\n        for (String h : hosts)\n        {\n            client.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress(h, new Integer(port))));\n        }\n\n        return client;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#instantiateClient(java\n     * .lang.String)\n     */\n    @Override\n    protected Client instantiateClient(String persistenceUnit)\n    {\n        return new ESClient(this, ((TransportClient) getConnectionPoolOrConnection()), this.externalProperties,\n                kunderaMetadata, persistenceUnit);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.GenericClientFactory#isThreadSafe()\n     */\n    @Override\n    public boolean isThreadSafe()\n    {\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initializeLoadBalancer\n     * (java.lang.String)\n     */\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n\n    }\n\n    private String[] getHosts(final String host)\n    {\n        return host.split(\",\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESClientPropertyReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.util.Map;\nimport java.util.Properties;\n\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * The Class ESClientPropertyReader.\n * \n * @author vivek.mishra\n */\npublic class ESClientPropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n\n    /** The esmd. */\n    private ESSchemaMetadata esmd;\n\n    /**\n     * Instantiates a new ES client property reader.\n     * \n     * @param externalProperties\n     *            the external properties\n     * @param puMetadata\n     *            the pu metadata\n     */\n    public ESClientPropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        esmd = new ESSchemaMetadata();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.AbstractPropertyReader#onXml(com.impetus\n     * .kundera.configure.ClientProperties)\n     */\n    @Override\n    protected void onXml(ClientProperties cp)\n    {\n        if (cp != null)\n        {\n            esmd.setClientProperties(cp);\n        }\n    }\n\n    /**\n     * Gets the connection properties.\n     * \n     * @return the connection properties\n     */\n    public Properties getConnectionProperties()\n    {\n        return esmd != null ? esmd.getConnectionProperties() : null;\n    }\n\n    /**\n     * The Class ESSchemaMetadata.\n     */\n    private class ESSchemaMetadata extends AbstractSchemaMetadata\n    {\n\n        public Properties getConnectionProperties()\n        {\n            DataStore ds = getDataStore(\"elasticsearch\");\n\n            if (ds != null)\n            {\n                Connection connection = ds.getConnection();\n                if (connection != null)\n                {\n                    Properties properties = connection.getProperties();\n\n                    return properties;\n                }\n            }\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESConstants.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\n/**\n * Constants for ES.\n * \n * @author Amit Kumar\n */\npublic interface ESConstants\n{\n    /** The Constant dot. */\n    public static final char DOT = '.';\n\n    /** The Constant leftBracket. */\n    public static final char LEFT_BRACKET = '(';\n\n    /** The Constant rightBracket. */\n    public static final char RIGHT_BRACKET = ')';\n\n    /** The Constant asterisk. */\n    public static final String ASTERISK = \"*\";\n\n    /** The Constant percentage. */\n    public static final String PERCENTAGE = \"%\";\n\n    /** The Constant infinity. */\n    public static final String INFINITY = \"INFINITY\";\n\n    /** The Constant aggName. */\n    public static final String AGGREGATION_NAME = \"esAggs\";\n\n    /** The Constant groupBy. */\n    public static final String GROUP_BY = \"group by\";\n\n    /** The Constant topHits. */\n    public static final String TOP_HITS = \"top\";\n\n    /** The Constant DEFAULT. */\n    public static final String DEFAULT = \"DEFAULT\";\n\n    /** The Constant ES_REFRESH_INDEXES. */\n    public static final String ES_REFRESH_INDEXES = \"es.refresh.indexes\";\n    \n    /** The Constant KUNDERA_ES_REFRESH_INDEXES. */\n    public static final String KUNDERA_ES_REFRESH_INDEXES = \"kundera.es.refresh.indexes\";\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESEntityReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * The Class ESEntityReader.\n * \n * @author vivek.mishra {@link EntityReader} implementation for elastic search.\n */\npublic class ESEntityReader extends AbstractEntityReader implements EntityReader\n{\n\n    /**\n     * Instantiates a new ES entity reader.\n     * \n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public ESEntityReader(final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    /**\n     * Instantiates a new ES entity reader.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public ESEntityReader(KunderaQuery kunderaQuery, final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n        this.kunderaQuery = kunderaQuery;\n    }\n\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        throw new UnsupportedOperationException(\"Method not supported\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#findById(java.lang.String,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.util.List,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        return super.findById(primaryKey, m, client);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESFilterBuilder.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Iterator;\n\nimport org.eclipse.persistence.jpa.jpql.parser.AdditionExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.AndExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.BetweenExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.CollectionExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.ComparisonExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.DivisionExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable;\nimport org.eclipse.persistence.jpa.jpql.parser.InExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.InputParameter;\nimport org.eclipse.persistence.jpa.jpql.parser.LikeExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.LogicalExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.MultiplicationExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.NullExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.NumericLiteral;\nimport org.eclipse.persistence.jpa.jpql.parser.OrExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.StateFieldPathExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.SubExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.SubtractionExpression;\nimport org.elasticsearch.index.query.AndQueryBuilder;\nimport org.elasticsearch.index.query.NotQueryBuilder;\nimport org.elasticsearch.index.query.OrQueryBuilder;\nimport org.elasticsearch.index.query.QueryBuilder;\nimport org.elasticsearch.index.query.QueryBuilders;\nimport org.elasticsearch.index.query.RangeQueryBuilder;\nimport org.elasticsearch.index.query.TermQueryBuilder;\nimport org.elasticsearch.index.query.TermsQueryBuilder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\n\n/**\n * The Class ESFilterBuilder.\n * \n * @author Amit Kumar\n */\npublic class ESFilterBuilder\n{\n    /** The Kundera query. */\n    private KunderaQuery kunderaQuery;\n\n    /** The Kundera metadata. */\n    private KunderaMetadata kunderaMetadata;\n\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(ESFilterBuilder.class);\n\n    /**\n     * Instantiates a new ES filter builder.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public ESFilterBuilder(KunderaQuery kunderaQuery, KunderaMetadata kunderaMetadata)\n    {\n        this.kunderaQuery = kunderaQuery;\n        this.kunderaMetadata = kunderaMetadata;\n    }\n\n    /**\n     * Populate filter builder.\n     * \n     * @param condtionalExp\n     *            the condtional exp\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @return the filter builder\n     */\n    public QueryBuilder populateFilterBuilder(Expression condtionalExp, EntityMetadata m)\n    {\n        log.info(\"Populating filter for expression: \" + condtionalExp);\n        QueryBuilder filter = null;\n\n        if (condtionalExp instanceof SubExpression)\n        {\n            filter = populateFilterBuilder(((SubExpression) condtionalExp).getExpression(), m);\n        }\n        else if (condtionalExp instanceof ComparisonExpression)\n        {\n            filter = getFilter(populateFilterClause((ComparisonExpression) condtionalExp), m);\n        }\n        else if (condtionalExp instanceof BetweenExpression)\n        {\n            filter = populateBetweenFilter((BetweenExpression) condtionalExp, m);\n        }\n        else if (condtionalExp instanceof LogicalExpression)\n        {\n            filter = populateLogicalFilterBuilder(condtionalExp, m);\n        }\n        else if (condtionalExp instanceof LikeExpression)\n        {\n            filter = populateLikeQuery((LikeExpression) condtionalExp, m);\n        }\n        else if (condtionalExp instanceof InExpression)\n        {\n            filter = populateInQuery((InExpression) condtionalExp, m);\n        }\n        else\n        {\n            log.error(condtionalExp.toParsedText() + \"found in where clause. Not supported in elasticsearch.\");\n            throw new KunderaException(condtionalExp.toParsedText() + \" not supported in ElasticSearch\");\n        }\n\n        log.debug(\"Following is the populated filter for required query: \" + filter);\n        return filter;\n    }\n\n    /**\n     * Populate like query.\n     * \n     * @param likeExpression\n     *            the like expression\n     * @param metadata\n     *            the metadata\n     * @return the filter builder\n     */\n    private QueryBuilder populateLikeQuery(LikeExpression likeExpression, EntityMetadata metadata)\n    {\n        Expression patternValue = likeExpression.getPatternValue();\n        String field = likeExpression.getStringExpression().toString();\n\n        String likePattern = (patternValue instanceof InputParameter) ? kunderaQuery.getParametersMap()\n                .get((patternValue).toParsedText()).toString() : patternValue.toParsedText().toString();\n        String jpaField = getField(field);\n\n        log.debug(\"Pattern value for field \" + field + \" is: \" + patternValue);\n        QueryBuilder filterBuilder = getQueryBuilder(kunderaQuery.new FilterClause(jpaField, Expression.LIKE,\n                likePattern, field), metadata);\n\n        return filterBuilder;\n    }\n\n    /**\n     * Populate IN query filter.\n     * \n     * @param inExpression\n     *            the in expression\n     * @param metadata\n     *            the metadata\n     * @return the filter builder\n     */\n    private QueryBuilder populateInQuery(InExpression inExpression, EntityMetadata metadata)\n    {\n        String property = getField(inExpression.getExpression().toParsedText());\n        Expression inItemsParameter = inExpression.getInItems();\n\n        log.debug(\"IN query parameters for field \" + property + \" is: \" + inItemsParameter);\n        Iterable inItemsIterable = getInValuesCollection(inItemsParameter);\n\n        return getFilter(kunderaQuery.new FilterClause(property, Expression.IN, inItemsIterable, property), metadata);\n    }\n\n    /**\n     * Returns the collection of IN clause values.\n     * \n     * @param inClauseValues\n     *            the in clause values\n     * @return the in values collection\n     */\n    private Collection getInValuesCollection(Expression inClauseValues)\n    {\n        Collection inParameterCollection = new ArrayList<>();\n        if (inClauseValues instanceof NullExpression)\n        {\n            log.debug(\"No items passed in IN clause values, returning blank IN values list\");\n            return inParameterCollection;\n        }\n\n        if (inClauseValues instanceof InputParameter)\n        {\n            Object inValues = kunderaQuery.getParametersMap().get(inClauseValues.toParsedText());\n            log.debug(inClauseValues.toParsedText() + \"named parameter found in query, Replacing parameter with \"\n                    + inValues);\n\n            inParameterCollection = inValues.getClass().isArray() ? Arrays.asList((Object[]) inValues)\n                    : (Collection) kunderaQuery.getParametersMap().get(inClauseValues.toParsedText());\n\n            return inParameterCollection;\n        }\n\n        if (inClauseValues instanceof CollectionExpression)\n        {\n            Iterator inValueIterator = ((CollectionExpression) inClauseValues).children().iterator();\n\n            log.debug(\"Collection object found for IN clause values\");\n            while (inValueIterator.hasNext())\n            {\n                Expression value = (Expression) inValueIterator.next();\n                inParameterCollection.add(value.toParsedText());\n            }\n            return inParameterCollection;\n        }\n\n        throw new KunderaException(inClauseValues.toParsedText() + \" not supported for IN clause\");\n    }\n\n    /**\n     * Gets the field.\n     * \n     * @param fieldValue\n     *            the field value\n     * @return the field\n     */\n    private String getField(String fieldValue)\n    {\n        return fieldValue.substring(fieldValue.indexOf(ESConstants.DOT) + 1, fieldValue.length());\n    }\n\n    /**\n     * Populate between filter.\n     * \n     * @param betweenExpression\n     *            the between expression\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @return the filter builder\n     */\n    private QueryBuilder populateBetweenFilter(BetweenExpression betweenExpression, EntityMetadata m)\n    {\n        String lowerBoundExpression = getBetweenBoundaryValues(betweenExpression.getLowerBoundExpression());\n        String upperBoundExpression = getBetweenBoundaryValues(betweenExpression.getUpperBoundExpression());\n        String field = getField(betweenExpression.getExpression().toParsedText());\n\n        log.debug(\"Between clause for field \" + field + \"with lower bound \" + lowerBoundExpression + \"and upper bound \"\n                + upperBoundExpression);\n\n        return new AndQueryBuilder(getFilter(kunderaQuery.new FilterClause(field, Expression.GREATER_THAN_OR_EQUAL,\n                lowerBoundExpression, field), m), getFilter(kunderaQuery.new FilterClause(field,\n                Expression.LOWER_THAN_OR_EQUAL, upperBoundExpression,field), m));\n    }\n\n    /**\n     * Gets the between boundary values.\n     * \n     * @param boundExpression\n     *            the bound expression\n     * @return the between boundry values\n     */\n    private String getBetweenBoundaryValues(Expression boundExpression)\n    {\n        if (boundExpression instanceof IdentificationVariable || boundExpression instanceof NumericLiteral\n                || boundExpression instanceof InputParameter)\n        {\n            Object value = (boundExpression instanceof InputParameter) ? kunderaQuery.getParametersMap().get(\n                    (boundExpression).toParsedText()) : boundExpression.toParsedText();\n            return value.toString();\n        }\n        else if (boundExpression instanceof AdditionExpression)\n        {\n            String leftValue = checkInputParameter(((AdditionExpression) boundExpression).getLeftExpression());\n            String rightValue = checkInputParameter(((AdditionExpression) boundExpression).getRightExpression());\n\n            return new Integer(Integer.parseInt(leftValue) + Integer.parseInt(rightValue)).toString();\n        }\n        else if (boundExpression instanceof SubtractionExpression)\n        {\n            String leftValue = checkInputParameter(((SubtractionExpression) boundExpression).getLeftExpression());\n            String rightValue = checkInputParameter(((SubtractionExpression) boundExpression).getRightExpression());\n\n            return new Integer(Integer.parseInt(leftValue) - Integer.parseInt(rightValue)).toString();\n        }\n        else if (boundExpression instanceof MultiplicationExpression)\n        {\n            String leftValue = checkInputParameter(((MultiplicationExpression) boundExpression).getLeftExpression());\n            String rightValue = checkInputParameter(((MultiplicationExpression) boundExpression).getRightExpression());\n\n            return new Integer(Integer.parseInt(leftValue) * Integer.parseInt(rightValue)).toString();\n        }\n\n        else if (boundExpression instanceof DivisionExpression)\n        {\n            String leftValue = checkInputParameter(((DivisionExpression) boundExpression).getLeftExpression());\n            String rightValue = checkInputParameter(((DivisionExpression) boundExpression).getRightExpression());\n            return new Integer(Integer.parseInt(leftValue) / Integer.parseInt(rightValue)).toString();\n        }\n\n        return null;\n    }\n\n    /**\n     * Check input parameter.\n     * \n     * @param expression\n     *            the expression\n     * @return the string\n     */\n    private String checkInputParameter(Expression expression)\n    {\n        return (expression instanceof InputParameter) ? kunderaQuery.getParametersMap()\n                .get((expression).toParsedText()).toString() : expression.toParsedText().toString();\n    }\n\n    /**\n     * Populate logical filter builder.\n     * \n     * @param logicalExp\n     *            the logical exp\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @return the filter builder\n     */\n    private QueryBuilder populateLogicalFilterBuilder(Expression logicalExp, EntityMetadata m)\n    {\n        String identifier = ((LogicalExpression) logicalExp).getIdentifier();\n\n        return (identifier.equalsIgnoreCase(LogicalExpression.AND)) ? getAndFilterBuilder(logicalExp, m) : (identifier\n                .equalsIgnoreCase(LogicalExpression.OR)) ? getOrFilterBuilder(logicalExp, m) : null;\n    }\n\n    /**\n     * Gets the and filter builder.\n     * \n     * @param logicalExp\n     *            the logical exp\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @return the and filter builder\n     */\n    private AndQueryBuilder getAndFilterBuilder(Expression logicalExp, EntityMetadata m)\n    {\n        AndExpression andExp = (AndExpression) logicalExp;\n        Expression leftExpression = andExp.getLeftExpression();\n        Expression rightExpression = andExp.getRightExpression();\n\n        return new AndQueryBuilder(populateFilterBuilder(leftExpression, m), populateFilterBuilder(rightExpression, m));\n    }\n\n    /**\n     * Gets the or filter builder.\n     * \n     * @param logicalExp\n     *            the logical exp\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @return the or filter builder\n     */\n    private OrQueryBuilder getOrFilterBuilder(Expression logicalExp, EntityMetadata m)\n    {\n        OrExpression orExp = (OrExpression) logicalExp;\n        Expression leftExpression = orExp.getLeftExpression();\n        Expression rightExpression = orExp.getRightExpression();\n\n        return new OrQueryBuilder(populateFilterBuilder(leftExpression, m), populateFilterBuilder(rightExpression, m));\n    }\n\n    /**\n     * Populate filter clause.\n     * \n     * @param conditionalExpression\n     *            the conditional expression\n     * @return the filter clause\n     */\n    private FilterClause populateFilterClause(ComparisonExpression conditionalExpression)\n    {\n        String property = ((StateFieldPathExpression) conditionalExpression.getLeftExpression()).getPath(1);\n        String condition = conditionalExpression.getComparisonOperator();\n        Expression rightExpression = conditionalExpression.getRightExpression();\n        Object value = (rightExpression instanceof InputParameter) ? kunderaQuery.getParametersMap().get(\n                (rightExpression).toParsedText()) : rightExpression.toParsedText();\n\n        return (condition != null && property != null) ? kunderaQuery.new FilterClause(property, condition, value, property)\n                : null;\n    }\n\n    /**\n     * Gets the filter.\n     * \n     * @param clause\n     *            the clause\n     * @param metadata\n     *            the metadata\n     * @param entityType\n     *            the entity type\n     * @return the filter\n     */\n    private QueryBuilder getFilter(FilterClause clause, final EntityMetadata metadata)\n    {\n        String condition = clause.getCondition();\n        Object value = condition.equals(Expression.IN) ? clause.getValue() : clause.getValue().get(0);\n        String name = ((AbstractAttribute) ((MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                metadata.getPersistenceUnit())).entity(metadata.getEntityClazz()).getAttribute(clause.getProperty()))\n                .getJPAColumnName();\n\n        QueryBuilder filterBuilder = null;\n\n        if (condition.equals(Expression.EQUAL))\n        {\n            filterBuilder = new TermQueryBuilder(name, value);\n        }\n        else if (condition.equals(Expression.GREATER_THAN))\n        {\n            filterBuilder = new RangeQueryBuilder(name).gt(value);\n        }\n        else if (condition.equals(Expression.LOWER_THAN))\n        {\n            filterBuilder = new RangeQueryBuilder(name).lt(value);\n        }\n        else if (condition.equals(Expression.GREATER_THAN_OR_EQUAL))\n        {\n            filterBuilder = new RangeQueryBuilder(name).gte(value);\n        }\n        else if (condition.equals(Expression.LOWER_THAN_OR_EQUAL))\n        {\n            filterBuilder = new RangeQueryBuilder(name).lte(value);\n        }\n        else if (condition.equals(Expression.DIFFERENT))\n        {\n            filterBuilder = new NotQueryBuilder(new TermQueryBuilder(name, value));\n        }\n        else if (condition.equals(Expression.IN))\n        {\n            filterBuilder = new TermsQueryBuilder(name, clause.getValue());\n        }\n\n        return filterBuilder;\n    }\n\n    /**\n     * Gets the query.\n     * \n     * @param clause\n     *            the clause\n     * @param metadata\n     *            the metadata\n     * @return the query\n     */\n    private QueryBuilder getQueryBuilder(FilterClause clause, final EntityMetadata metadata)\n    {\n        String condition = clause.getCondition();\n        String value = clause.getValue().get(0).toString();\n        String name = ((AbstractAttribute) ((MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                metadata.getPersistenceUnit())).entity(metadata.getEntityClazz()).getAttribute(clause.getProperty()))\n                .getJPAColumnName();\n\n        String likePattern = value.contains(ESConstants.PERCENTAGE) ? value.replaceAll(ESConstants.PERCENTAGE,\n                ESConstants.ASTERISK) : ESConstants.ASTERISK + value + ESConstants.ASTERISK;\n\n        QueryBuilder queryBuilder = null;\n        if (condition.equals(Expression.LIKE))\n        {\n            queryBuilder = QueryBuilders.wildcardQuery(name, likePattern);\n        }\n\n        return QueryBuilders.queryFilter(queryBuilder);\n    }\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/main/java/com/impetus/client/es/ESQuery.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.Query;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.lucene.queryparser.xml.FilterBuilder;\nimport org.eclipse.persistence.jpa.jpql.parser.AggregateFunction;\nimport org.eclipse.persistence.jpa.jpql.parser.AndExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.CollectionExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.ComparisonExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.GroupByClause;\nimport org.eclipse.persistence.jpa.jpql.parser.HavingClause;\nimport org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable;\nimport org.eclipse.persistence.jpa.jpql.parser.NullExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.OrExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.OrderByClause;\nimport org.eclipse.persistence.jpa.jpql.parser.OrderByItem;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectClause;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectStatement;\nimport org.eclipse.persistence.jpa.jpql.parser.StateFieldPathExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.WhereClause;\nimport org.eclipse.persistence.jpa.jpql.utility.iterable.ListIterable;\nimport org.elasticsearch.index.query.QueryBuilder;\nimport org.elasticsearch.index.query.QueryBuilders;\nimport org.elasticsearch.search.aggregations.AggregationBuilder;\nimport org.elasticsearch.search.aggregations.AggregationBuilders;\nimport org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;\nimport org.elasticsearch.search.aggregations.bucket.terms.Terms;\nimport org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;\nimport org.elasticsearch.search.aggregations.metrics.MetricsAggregationBuilder;\nimport org.elasticsearch.search.aggregations.metrics.tophits.TopHitsBuilder;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQueryUtils;\nimport com.impetus.kundera.query.QueryImpl;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class ESQuery.\n * \n * @author vivek.mishra Implementation of query interface {@link Query}.\n * @param <E>\n *            the element type\n */\n\npublic class ESQuery<E> extends QueryImpl\n{\n    /** The es filter builder. */\n    private ESFilterBuilder esFilterBuilder;\n\n    /** The aggregations key list. */\n    private Set<String> aggregationsKeySet;\n\n    /** The log. */\n    private static Logger logger = LoggerFactory.getLogger(ESClient.class);\n\n    /**\n     * Instantiates a new ES query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param persistenceDelegator\n     *            the persistence delegator\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public ESQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n        this.esFilterBuilder = new ESFilterBuilder(getKunderaQuery(), kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List<Object> populateEntities(EntityMetadata m, Client client)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        EntityType entity = metaModel.entity(m.getEntityClazz());\n        Expression whereExpression = KunderaQueryUtils.getWhereClause(kunderaQuery.getJpqlExpression());\n\n        QueryBuilder filter = whereExpression == null || whereExpression instanceof NullExpression ? null\n                : esFilterBuilder.populateFilterBuilder(((WhereClause) whereExpression).getConditionalExpression(), m);\n\n        return ((ESClient) client).executeQuery(filter, buildAggregation(kunderaQuery, m, filter), m,\n                getKunderaQuery(),this.firstResult, this.maxResult);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#recursivelyPopulateEntities(com.impetus\n     * .kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n        List result = populateEntities(m, client);\n        return setRelationEntities(result, client, m);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#getReader()\n     */\n    @Override\n    protected EntityReader getReader()\n    {\n        return new ESEntityReader(kunderaQuery, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()\n     */\n    @Override\n    protected int onExecuteUpdate()\n    {\n        return onUpdateDeleteEvent();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#close()\n     */\n    @Override\n    public void close()\n    {\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#iterate()\n     */\n    @Override\n    public Iterator<E> iterate()\n    {\n        return null;\n    }\n\n    /**\n     * Gets the es filter builder.\n     * \n     * @return ES Filter Builder\n     */\n    public ESFilterBuilder getEsFilterBuilder()\n    {\n        return esFilterBuilder;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#findUsingLucene(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n        throw new UnsupportedOperationException(\"select colummn via lucene is unsupported in Elasticsearch\");\n    }\n\n    /**\n     * Use aggregation.\n     * \n     * @param query\n     *            the query\n     * @param entityMetadata\n     *            the entity metadata\n     * @param filter\n     *            the filter\n     * @return the filter aggregation builder\n     */\n    public AggregationBuilder buildAggregation(KunderaQuery query, EntityMetadata entityMetadata, QueryBuilder filter)\n    {\n        SelectStatement selectStatement = query.getSelectStatement();\n\n        // To apply filter for where clause\n        AggregationBuilder aggregationBuilder = buildWhereAggregations(entityMetadata, filter);\n        if (KunderaQueryUtils.hasGroupBy(query.getJpqlExpression()))\n        {\n            TermsBuilder termsBuilder = processGroupByClause(selectStatement.getGroupByClause(), entityMetadata, query);\n            aggregationBuilder.subAggregation(termsBuilder);\n        }\n        else\n        {\n            if (KunderaQueryUtils.hasHaving(query.getJpqlExpression()))\n            {\n                logger.error(\"Identified having clause without group by, Throwing not supported operation Exception\");\n                throw new UnsupportedOperationException(\n                        \"Currently, Having clause without group by caluse is not supported.\");\n            }\n            else\n            {\n                aggregationBuilder = (selectStatement != null) ? query.isAggregated() ? buildSelectAggregations(\n                        aggregationBuilder, selectStatement, entityMetadata) : null : null;\n            }\n        }\n\n        return aggregationBuilder;\n    }\n\n    /**\n     * Adds the having clauses.\n     * \n     * @param havingExpression\n     *            the having expression\n     * @param aggregationBuilder\n     *            the aggregation builder\n     * @param entityMetadata\n     *            the entity metadata\n     * @return the aggregation builder\n     */\n    private AggregationBuilder addHavingClause(Expression havingExpression, AggregationBuilder aggregationBuilder,\n            EntityMetadata entityMetadata)\n    {\n        if (havingExpression instanceof ComparisonExpression)\n        {\n            Expression expression = ((ComparisonExpression) havingExpression).getLeftExpression();\n            if (!isAggregationExpression(expression))\n            {\n                logger.error(\"Having clause conditions over non metric aggregated are not supported.\");\n                throw new UnsupportedOperationException(\n                        \"Currently, Having clause without Metric aggregations are not supported.\");\n            }\n\n            return checkIfKeyExists(expression.toParsedText()) ? aggregationBuilder\n                    .subAggregation(getMetricsAggregation(expression, entityMetadata)) : aggregationBuilder;\n        }\n        else if (havingExpression instanceof AndExpression)\n        {\n            AndExpression andExpression = (AndExpression) havingExpression;\n            addHavingClause(andExpression.getLeftExpression(), aggregationBuilder, entityMetadata);\n            addHavingClause(andExpression.getRightExpression(), aggregationBuilder, entityMetadata);\n\n            return aggregationBuilder;\n        }\n        else if (havingExpression instanceof OrExpression)\n        {\n            OrExpression orExpression = (OrExpression) havingExpression;\n            addHavingClause(orExpression.getLeftExpression(), aggregationBuilder, entityMetadata);\n            addHavingClause(orExpression.getRightExpression(), aggregationBuilder, entityMetadata);\n\n            return aggregationBuilder;\n        }\n        else\n        {\n            logger.error(havingExpression + \"not supported in having clause.\");\n            throw new UnsupportedOperationException(havingExpression + \"not supported in having clause.\");\n        }\n    }\n\n    /**\n     * Process group by clause.\n     * \n     * @param expression\n     *            the expression\n     * @param entityMetadata\n     *            the entity metadata\n     * @param query\n     *            the query\n     * @return the terms builder\n     */\n    private TermsBuilder processGroupByClause(Expression expression, EntityMetadata entityMetadata, KunderaQuery query)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n        Expression groupByClause = ((GroupByClause) expression).getGroupByItems();\n\n        if (groupByClause instanceof CollectionExpression)\n        {\n            logger.error(\"More than one item found in group by clause.\");\n            throw new UnsupportedOperationException(\"Currently, Group By on more than one field is not supported.\");\n        }\n\n        SelectStatement selectStatement = query.getSelectStatement();\n\n        // To apply terms and tophits aggregation to serve group by\n        String jPAField = KunderaCoreUtils.getJPAColumnName(groupByClause.toParsedText(), entityMetadata, metaModel);\n        TermsBuilder termsBuilder = AggregationBuilders.terms(ESConstants.GROUP_BY).field(jPAField).size(0);\n\n        // Hard coded value for a max number of record that a group can contain.\n        TopHitsBuilder topHitsBuilder = getTopHitsAggregation(selectStatement, null, entityMetadata);\n        termsBuilder.subAggregation(topHitsBuilder);\n\n        // To apply the metric aggregations (Min, max... etc) in select clause\n        buildSelectAggregations(termsBuilder, query.getSelectStatement(), entityMetadata);\n\n        if (KunderaQueryUtils.hasHaving(query.getJpqlExpression()))\n        {\n            addHavingClause(((HavingClause) selectStatement.getHavingClause()).getConditionalExpression(),\n                    termsBuilder, entityMetadata);\n        }\n\n        if (KunderaQueryUtils.hasOrderBy(query.getJpqlExpression()))\n        {\n            processOrderByClause(termsBuilder, KunderaQueryUtils.getOrderByClause(query.getJpqlExpression()),\n                    groupByClause, entityMetadata);\n        }\n\n        return termsBuilder;\n    }\n\n    /**\n     * Process order by clause.\n     * \n     * @param termsBuilder\n     *            the terms builder\n     * @param orderByExpression\n     *            the order by expression\n     * @param groupByClause\n     *            the group by clause\n     * @param entityMetadata\n     *            the entity metadata\n     */\n    private void processOrderByClause(TermsBuilder termsBuilder, Expression orderByExpression,\n            Expression groupByClause, EntityMetadata entityMetadata)\n    {\n        Expression orderByClause = (OrderByClause) orderByExpression;\n        OrderByItem orderByItems = (OrderByItem) ((OrderByClause) orderByClause).getOrderByItems();\n\n        if (orderByClause instanceof CollectionExpression\n                || !(orderByItems.getExpression().toParsedText().equalsIgnoreCase(groupByClause.toParsedText())))\n        {\n            logger.error(\"Order by and group by on different field are not supported simultaneously\");\n            throw new UnsupportedOperationException(\n                    \"Order by and group by on different field are not supported simultaneously\");\n        }\n\n        String ordering = orderByItems.getOrdering().toString();\n        termsBuilder.order(Terms.Order.term(!ordering.equalsIgnoreCase(Expression.DESC)));\n    }\n\n    /**\n     * Gets the top hits aggregation.\n     * \n     * @param selectStatement\n     *            the select statement\n     * @param size\n     *            the size\n     * @param entityMetadata\n     *            the entity metadata\n     * @return the top hits aggregation\n     */\n    private TopHitsBuilder getTopHitsAggregation(SelectStatement selectStatement, Integer size,\n            EntityMetadata entityMetadata)\n    {\n        TopHitsBuilder topHitsBuilder = AggregationBuilders.topHits(ESConstants.TOP_HITS);\n        if (size != null)\n        {\n            topHitsBuilder.setSize(size);\n        }\n\n        return topHitsBuilder;\n    }\n\n    /**\n     * Builds the where aggregations.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param filter\n     *            the filter\n     * @return the filter aggregation builder\n     */\n    private FilterAggregationBuilder buildWhereAggregations(EntityMetadata entityMetadata, QueryBuilder filter)\n    {\n        filter = filter != null ? filter : QueryBuilders.matchAllQuery();\n        FilterAggregationBuilder filteragg = AggregationBuilders.filter(ESConstants.AGGREGATION_NAME).filter(filter);\n\n        return filteragg;\n    }\n\n    /**\n     * Builds the select aggregations.\n     * \n     * @param selectStatement\n     *            the select statement\n     * @param entityMetadata\n     *            the entity metadata\n     * @param filter\n     *            the filter\n     * @return the filter aggregation builder\n     */\n    private AggregationBuilder buildSelectAggregations(AggregationBuilder aggregationBuilder,\n            SelectStatement selectStatement, EntityMetadata entityMetadata)\n    {\n        Expression expression = ((SelectClause) selectStatement.getSelectClause()).getSelectExpression();\n\n        if (expression instanceof CollectionExpression)\n        {\n            aggregationBuilder = appendAggregation((CollectionExpression) expression, entityMetadata,\n                    aggregationBuilder);\n        }\n        else\n        {\n            if (isAggregationExpression(expression) && checkIfKeyExists(expression.toParsedText()))\n                aggregationBuilder.subAggregation(getMetricsAggregation(expression, entityMetadata));\n        }\n        return aggregationBuilder;\n    }\n\n    /**\n     * Append aggregation.\n     * \n     * @param collectionExpression\n     *            the collection expression\n     * @param entityMetadata\n     *            the entity metadata\n     * @param nestedAggregation\n     * @param aggregationBuilder\n     *            the aggregation builder\n     * @return the filter aggregation builder\n     */\n    private AggregationBuilder appendAggregation(CollectionExpression collectionExpression,\n            EntityMetadata entityMetadata, AggregationBuilder aggregationBuilder)\n    {\n        ListIterable<Expression> functionlist = collectionExpression.children();\n        for (Expression function : functionlist)\n        {\n            if (isAggregationExpression(function) && checkIfKeyExists(function.toParsedText()))\n            {\n                aggregationBuilder.subAggregation(getMetricsAggregation(function, entityMetadata));\n            }\n        }\n        return aggregationBuilder;\n    }\n\n    /**\n     * Gets the aggregation.\n     * \n     * @param expression\n     *            the expression\n     * @param entityMetadata\n     *            the entity metadata\n     * @return the aggregation\n     */\n    private MetricsAggregationBuilder getMetricsAggregation(Expression expression, EntityMetadata entityMetadata)\n    {\n        AggregateFunction function = (AggregateFunction) expression;\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n        String jPAColumnName = KunderaCoreUtils.getJPAColumnName(function.toParsedText(), entityMetadata, metaModel);\n\n        MetricsAggregationBuilder aggregationBuilder = null;\n\n        switch (function.getIdentifier())\n        {\n        case Expression.MIN:\n            aggregationBuilder = AggregationBuilders.min(function.toParsedText()).field(jPAColumnName);\n            break;\n        case Expression.MAX:\n            aggregationBuilder = AggregationBuilders.max(function.toParsedText()).field(jPAColumnName);\n            break;\n        case Expression.SUM:\n            aggregationBuilder = AggregationBuilders.sum(function.toParsedText()).field(jPAColumnName);\n            break;\n        case Expression.AVG:\n            aggregationBuilder = AggregationBuilders.avg(function.toParsedText()).field(jPAColumnName);\n            break;\n        case Expression.COUNT:\n            aggregationBuilder = AggregationBuilders.count(function.toParsedText()).field(jPAColumnName);\n            break;\n        }\n        return aggregationBuilder;\n    }\n\n    /**\n     * Check expression.\n     * \n     * @param expression\n     *            the expression\n     * @return true, if successful\n     */\n    private boolean isAggregationExpression(Expression expression)\n    {\n        return !(expression instanceof StateFieldPathExpression || expression instanceof IdentificationVariable);\n    }\n\n    /**\n     * Checks whether key exist in ES Query.\n     * \n     * @param key\n     *            the key\n     * @return true, if is new key\n     */\n    private boolean checkIfKeyExists(String key)\n    {\n        if (aggregationsKeySet == null)\n        {\n            aggregationsKeySet = new HashSet<String>();\n        }\n        return aggregationsKeySet.add(key);\n    }\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/main/java/com/impetus/client/es/EsIdGenerator.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.util.UUID;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.generator.AutoGenerator;\n\n/**\n * The Class EsIdGenerator.\n * \n * @author devender.yadav\n * \n */\npublic class EsIdGenerator implements AutoGenerator\n{\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.AutoGenerator#generate(com.impetus.kundera\n     * .client.Client, java.lang.Object)\n     */\n    @Override\n    public Object generate(Client<?> client, String dataType)\n    {\n        return UUID.randomUUID().toString();\n    }\n\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/main/java/com/impetus/client/es/index/ESIndexer.java",
    "content": "package com.impetus.client.es.index;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.InetSocketAddress;\nimport java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.OrderByItem;\nimport org.eclipse.persistence.jpa.jpql.parser.WhereClause;\nimport org.eclipse.persistence.jpa.jpql.utility.iterable.ListIterable;\nimport org.elasticsearch.ElasticsearchException;\nimport org.elasticsearch.action.ListenableActionFuture;\nimport org.elasticsearch.action.delete.DeleteResponse;\nimport org.elasticsearch.action.index.IndexResponse;\nimport org.elasticsearch.action.search.SearchRequestBuilder;\nimport org.elasticsearch.action.search.SearchResponse;\nimport org.elasticsearch.client.Client;\nimport org.elasticsearch.client.transport.TransportClient;\nimport org.elasticsearch.common.transport.InetSocketTransportAddress;\nimport org.elasticsearch.index.query.FilteredQueryBuilder;\nimport org.elasticsearch.index.query.QueryBuilder;\nimport org.elasticsearch.index.query.QueryBuilders;\nimport org.elasticsearch.search.SearchHit;\nimport org.elasticsearch.search.aggregations.AggregationBuilder;\nimport org.elasticsearch.search.sort.SortOrder;\n\nimport com.fasterxml.jackson.core.JsonGenerationException;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.impetus.client.es.ESConstants;\nimport com.impetus.client.es.ESQuery;\nimport com.impetus.client.es.utils.ESResponseWrapper;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.index.Indexer;\nimport com.impetus.kundera.index.IndexerProperties;\nimport com.impetus.kundera.index.IndexerProperties.Node;\nimport com.impetus.kundera.index.IndexingException;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQueryUtils;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.thoughtworks.xstream.XStream;\n\n/**\n * The Class ESIndexer.\n * \n * @author vivek.mishra\n */\npublic class ESIndexer implements Indexer\n{\n\n    /** The client. */\n    private Client client;\n\n    /** The Constant UUID. */\n    private static final long UUID = 6077004083174677888L;\n\n    /** The Constant PARENT_ID_FIELD. */\n    // ES 2.0+ doesn't support '.' in field name (Causes MapperParsingException)\n    public static final String PARENT_ID_FIELD = UUID + \"_parent_id\";\n\n    /** The Constant PARENT_ID_CLASS. */\n    public static final String PARENT_ID_CLASS = UUID + \"_parent_class\";\n\n    /** the log used by this class. */\n    private static Log log = LogFactory.getLog(ESIndexer.class);\n\n    /**\n     * Instantiates a new ES indexer.\n     */\n    public ESIndexer()\n    {\n        init();\n    }\n\n    /**\n     * Sets the client.\n     * \n     * @param client\n     *            the client to set\n     */\n    public void setClient(Client client)\n    {\n        this.client = client;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.index.Indexer#index(java.lang.Class,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.util.Map,\n     * java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public void index(Class entityClazz, EntityMetadata metadata, Map<String, Object> values, Object parentId,\n            Class parentClazz)\n    {\n        ObjectMapper mapper = new ObjectMapper();\n        try\n        {\n            values.put(\"entity_class\", metadata.getEntityClazz().getCanonicalName().toLowerCase());\n            if (parentId != null)\n            {\n                values.put(PARENT_ID_FIELD, parentId);\n            }\n            if (entityClazz != null)\n            {\n                values.put(PARENT_ID_CLASS, parentClazz.getCanonicalName().toLowerCase());\n            }\n            String json = mapper.writeValueAsString(values);\n            String idColumnName = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();\n            Object id = PropertyAccessorHelper.fromSourceToTargetClass(String.class,\n                    ((AbstractAttribute) metadata.getIdAttribute()).getBindableJavaType(), values.get(idColumnName));\n\n            ListenableActionFuture<IndexResponse> listenableActionFuture = client\n                    .prepareIndex(metadata.getSchema().toLowerCase(), entityClazz.getSimpleName(), id.toString())\n                    .setSource(json).execute();\n            IndexResponse response = listenableActionFuture.actionGet();\n        }\n        catch (JsonGenerationException e)\n        {\n            log.error(\"Error while creating json document\", e);\n            throw new KunderaException(e);\n        }\n        catch (JsonMappingException e)\n        {\n            log.error(\"Error while creating json document\", e);\n            throw new KunderaException(e);\n        }\n        catch (IOException e)\n        {\n            log.error(\"Error while creating json document\", e);\n            throw new KunderaException(e);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while creating indexes on document\", e);\n            throw new KunderaException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.index.Indexer#search(java.lang.Class,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.lang.String, int,\n     * int)\n     */\n    @Override\n    public Map<String, Object> search(Class<?> clazz, EntityMetadata m, String luceneQuery, int start, int count)\n    {\n        if (log.isInfoEnabled())\n        {\n            log.info(\"Executing lucene query \" + luceneQuery);\n        }\n\n        ListenableActionFuture<SearchResponse> listenableActionFuture = client\n                .prepareSearch(m.getSchema().toLowerCase()).setQuery(QueryBuilders.queryStringQuery(luceneQuery))\n                .setSize(40000).execute();\n        SearchResponse response = listenableActionFuture.actionGet();\n\n        Map<String, Object> results = new HashMap<String, Object>();\n        for (SearchHit hit : response.getHits())\n        {\n            Object id = PropertyAccessorHelper.fromSourceToTargetClass(\n                    ((AbstractAttribute) m.getIdAttribute()).getBindableJavaType(), String.class, hit.getId());\n            results.put(hit.getId(), id);\n        }\n        return results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.index.Indexer#search(com.impetus.kundera.persistence\n     * .EntityManagerFactoryImpl.KunderaMetadata,\n     * com.impetus.kundera.query.KunderaQuery,\n     * com.impetus.kundera.persistence.PersistenceDelegator,\n     * com.impetus.kundera.metadata.model.EntityMetadata)\n     */\n    @Override\n    public Map<String, Object> search(KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery,\n            PersistenceDelegator persistenceDelegator, EntityMetadata m, int firstResult, int maxResults)\n    {\n        ESQuery query = new ESQuery<>(kunderaQuery, persistenceDelegator, kunderaMetadata);\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(m.getPersistenceUnit());\n        Expression whereExpression = KunderaQueryUtils.getWhereClause(kunderaQuery.getJpqlExpression());\n\n        QueryBuilder filter = whereExpression != null ? query.getEsFilterBuilder()\n                .populateFilterBuilder(((WhereClause) whereExpression).getConditionalExpression(), m) : null;\n\n        FilteredQueryBuilder queryBuilder = QueryBuilders.filteredQuery(null, filter);\n        SearchResponse response = getSearchResponse(kunderaQuery, queryBuilder, filter, query, m, firstResult,\n                maxResults, kunderaMetadata);\n\n        return buildResultMap(response, kunderaQuery, m, metaModel);\n    }\n\n    /**\n     * Builds the result map.\n     * \n     * @param esResponseReader\n     *            the es response reader\n     * @param response\n     *            the response\n     * @param query\n     *            the query\n     * @param m\n     *            the m\n     * @param metaModel\n     *            the meta model\n     * @return the map\n     */\n    private Map<String, Object> buildResultMap(SearchResponse response, KunderaQuery query, EntityMetadata m,\n            MetamodelImpl metaModel)\n    {\n        Map<String, Object> map = new LinkedHashMap<>();\n        ESResponseWrapper esResponseReader = new ESResponseWrapper();\n\n        for (SearchHit hit : response.getHits())\n        {\n            Object id = PropertyAccessorHelper.fromSourceToTargetClass(\n                    ((AbstractAttribute) m.getIdAttribute()).getBindableJavaType(), String.class, hit.getId());\n            map.put(hit.getId(), id);\n        }\n\n        Map<String, Object> aggMap = esResponseReader.parseAggregations(response, query, metaModel, m.getEntityClazz(),\n                m);\n        ListIterable<Expression> selectExpressionOrder = esResponseReader.getSelectExpressionOrder(query);\n\n        Map<String, Object> resultMap = new HashMap<>();\n        resultMap.put(Constants.AGGREGATIONS, aggMap);\n        resultMap.put(Constants.PRIMARY_KEYS, map);\n        resultMap.put(Constants.SELECT_EXPRESSION_ORDER, selectExpressionOrder);\n\n        return resultMap;\n    }\n\n    /**\n     * Gets the search response.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param queryBuilder\n     *            the query builder\n     * @param filter\n     *            the filter\n     * @param query\n     *            the query\n     * @param m\n     *            the m\n     * @param kunderaMetadata\n     * @return the search response\n     */\n    private SearchResponse getSearchResponse(KunderaQuery kunderaQuery, FilteredQueryBuilder queryBuilder,\n            QueryBuilder filter, ESQuery query, EntityMetadata m, int firstResult, int maxResults,\n            KunderaMetadata kunderaMetadata)\n    {\n        SearchRequestBuilder builder = client.prepareSearch(m.getSchema().toLowerCase())\n                .setTypes(m.getEntityClazz().getSimpleName());\n        AggregationBuilder aggregation = query.buildAggregation(kunderaQuery, m, filter);\n\n        if (aggregation == null)\n        {\n            builder.setQuery(queryBuilder);\n            builder.setFrom(firstResult);\n            builder.setSize(maxResults);\n            addSortOrder(builder, kunderaQuery, m, kunderaMetadata);\n        }\n        else\n        {\n            log.debug(\"Aggregated query identified\");\n            builder.addAggregation(aggregation);\n\n            if (kunderaQuery.getResult().length == 1 || (kunderaQuery.isSelectStatement()\n                    && KunderaQueryUtils.hasGroupBy(kunderaQuery.getJpqlExpression())))\n            {\n                builder.setSize(0);\n            }\n        }\n\n        SearchResponse response = null;\n        log.debug(\"Query generated: \" + builder);\n\n        try\n        {\n            response = builder.execute().actionGet();\n            log.debug(\"Query execution response: \" + response);\n        }\n        catch (ElasticsearchException e)\n        {\n            log.error(\"Exception occured while executing query on Elasticsearch.\", e);\n            throw new KunderaException(\"Exception occured while executing query on Elasticsearch.\", e);\n        }\n\n        return response;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.index.Indexer#unIndex(java.lang.Class,\n     * java.lang.Object, com.impetus.kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.metadata.model.MetamodelImpl)\n     */\n    @Override\n    public void unIndex(Class entityClazz, Object entity, EntityMetadata metadata, MetamodelImpl metamodelImpl)\n    {\n        Object id = PropertyAccessorHelper.getId(entity, metadata);\n        DeleteResponse response = client\n                .prepareDelete(metadata.getSchema().toLowerCase(), entityClazz.getSimpleName(), id.toString()).execute()\n                .actionGet();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.index.Indexer#close()\n     */\n    @Override\n    public void close()\n    {\n        if (client != null)\n        {\n            client.close();\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.index.Indexer#search(java.lang.String,\n     * java.lang.Class, com.impetus.kundera.metadata.model.EntityMetadata,\n     * java.lang.Class, com.impetus.kundera.metadata.model.EntityMetadata,\n     * java.lang.Object, int, int)\n     */\n    @Override\n    public Map<String, Object> search(String query, Class<?> parentClass, EntityMetadata parentMetadata,\n            Class<?> childClass, EntityMetadata childMetadata, Object entityId, int start, int count)\n    {\n        return search(parentClass, parentMetadata, query, start, count);\n    }\n\n    /**\n     * Inits the.\n     */\n    public void init()\n    {\n\n        InputStream inStream = this.getClass().getClassLoader().getResourceAsStream(\"esindexer.xml\");\n        XStream xStream = getXStreamObject();\n\n        if (inStream != null)\n        {\n            Object o = xStream.fromXML(inStream);\n            IndexerProperties indexerProperties = (IndexerProperties) o;\n            List<Node> nodes = indexerProperties.getNodes();\n\n            if (nodes == null || (nodes != null && nodes.isEmpty()))\n            {\n                log.error(\"Nodes should not be empty/null\");\n                throw new IndexingException(\"Nodes should not be empty/null\");\n            }\n            else\n            {\n                if (client == null)\n                {\n                    client = TransportClient.builder().build();\n                }\n                for (Node node : nodes)\n                {\n                    Properties properties = node.getProperties();\n                    if (properties != null)\n                    {\n                        if (properties.getProperty(\"host\") == null\n                                || !StringUtils.isNumeric(properties.getProperty(\"port\"))\n                                || properties.getProperty(\"port\").isEmpty())\n                        {\n                            log.error(\"Host or port should not be null / port should be numeric\");\n                            throw new IllegalArgumentException(\n                                    \"Host or port should not be null / port should be numeric\");\n                        }\n                        ((TransportClient) client).addTransportAddress(\n                                new InetSocketTransportAddress(new InetSocketAddress(properties.getProperty(\"host\"),\n                                        Integer.parseInt(properties.getProperty(\"port\")))));\n                    }\n                }\n            }\n        }\n        else\n        {\n            log.error(\"No indexer setting provided, please provide valid indexer settings in esindexer.xml\");\n            throw new IndexingException(\n                    \"No indexer setting provided, please provide valid indexer settings in esindexer.xml\");\n        }\n    }\n\n    /**\n     * get XStream Object.\n     * \n     * @return XStream object.\n     */\n    private XStream getXStreamObject()\n    {\n        XStream stream = new XStream();\n        stream.alias(\"indexerProperties\", IndexerProperties.class);\n        stream.alias(\"node\", IndexerProperties.Node.class);\n        return stream;\n    }\n\n    /**\n     * Adds the sort order.\n     * \n     * @param builder\n     *            the builder\n     * @param query\n     *            the query\n     * @param entityMetadata\n     *            the entity metadata\n     * @param kunderaMetadata\n     */\n    private void addSortOrder(SearchRequestBuilder builder, KunderaQuery query, EntityMetadata entityMetadata,\n            KunderaMetadata kunderaMetadata)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(entityMetadata.getPersistenceUnit());\n        List<OrderByItem> orderList = KunderaQueryUtils.getOrderByItems(query.getJpqlExpression());\n\n        for (OrderByItem orderByItem : orderList)\n        {\n            String ordering = orderByItem.getOrdering().toString();\n\n            if (ordering.equalsIgnoreCase(ESConstants.DEFAULT))\n            {\n                ordering = Expression.ASC;\n            }\n\n            builder.addSort(KunderaCoreUtils.getJPAColumnName(orderByItem.getExpression().toParsedText(),\n                    entityMetadata, metaModel), SortOrder.valueOf(ordering));\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/main/java/com/impetus/client/es/utils/ESResponseWrapper.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es.utils;\n\nimport java.lang.reflect.Field;\nimport java.sql.Timestamp;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.Metamodel;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.eclipse.persistence.jpa.jpql.parser.AggregateFunction;\nimport org.eclipse.persistence.jpa.jpql.parser.AndExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.CollectionExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.ComparisonExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.HavingClause;\nimport org.eclipse.persistence.jpa.jpql.parser.LogicalExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.NullExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.OrExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectClause;\nimport org.eclipse.persistence.jpa.jpql.utility.iterable.ListIterable;\nimport org.eclipse.persistence.jpa.jpql.utility.iterable.SnapshotCloneListIterable;\nimport org.elasticsearch.action.search.SearchResponse;\nimport org.elasticsearch.search.SearchHit;\nimport org.elasticsearch.search.SearchHits;\nimport org.elasticsearch.search.aggregations.AbstractAggregationBuilder;\nimport org.elasticsearch.search.aggregations.Aggregations;\nimport org.elasticsearch.search.aggregations.InternalAggregations;\nimport org.elasticsearch.search.aggregations.bucket.filter.InternalFilter;\nimport org.elasticsearch.search.aggregations.bucket.terms.Terms;\nimport org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;\nimport org.elasticsearch.search.aggregations.metrics.avg.InternalAvg;\nimport org.elasticsearch.search.aggregations.metrics.max.InternalMax;\nimport org.elasticsearch.search.aggregations.metrics.min.InternalMin;\nimport org.elasticsearch.search.aggregations.metrics.sum.InternalSum;\nimport org.elasticsearch.search.aggregations.metrics.tophits.TopHits;\nimport org.elasticsearch.search.aggregations.metrics.valuecount.InternalValueCount;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.es.ESConstants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.property.accessor.EnumAccessor;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQueryUtils;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class ESResponseWrapper.\n * \n * @author Amit Kumar\n * \n */\npublic final class ESResponseWrapper\n{\n    /** log for this class. */\n    private static Logger logger = LoggerFactory.getLogger(ESResponseWrapper.class);\n\n    /**\n     * Parses the response.\n     * \n     * @param response\n     *            the response\n     * @param aggregation\n     *            the aggregation\n     * @param fieldsToSelect\n     *            the fields to select\n     * @param metaModel\n     *            the meta model\n     * @param clazz\n     *            the clazz\n     * @param entityMetadata\n     *            the entity metadata\n     * @param query\n     *            the query\n     * @return the list\n     */\n    public List parseResponse(SearchResponse response, AbstractAggregationBuilder aggregation, String[] fieldsToSelect,\n            MetamodelImpl metaModel, Class clazz, final EntityMetadata entityMetadata, KunderaQuery query)\n    {\n        logger.debug(\"Response of query: \" + response);\n\n        List results = new ArrayList();\n        EntityType entityType = metaModel.entity(clazz);\n\n        if (aggregation == null)\n        {\n            SearchHits hits = response.getHits();\n            if (fieldsToSelect != null && fieldsToSelect.length > 1 && !(fieldsToSelect[1] == null))\n            {\n                for (SearchHit hit : hits.getHits())\n                {\n                    if (fieldsToSelect.length == 2)\n                    {\n                        results.add(hit\n                                .getFields()\n                                .get(((AbstractAttribute) metaModel.entity(clazz).getAttribute(fieldsToSelect[1]))\n                                        .getJPAColumnName()).getValue());\n                    }\n                    else\n                    {\n                        List temp = new ArrayList();\n\n                        for (int i = 1; i < fieldsToSelect.length; i++)\n                        {\n                            temp.add(hit\n                                    .getFields()\n                                    .get(((AbstractAttribute) metaModel.entity(clazz).getAttribute(fieldsToSelect[i]))\n                                            .getJPAColumnName()).getValue());\n                        }\n                        results.add(temp);\n                    }\n                }\n            }\n            else\n            {\n                results = getEntityObjects(clazz, entityMetadata, entityType, hits);\n            }\n        }\n        else\n        {\n            results = parseAggregatedResponse(response, query, metaModel, clazz, entityMetadata);\n        }\n        return results;\n    }\n\n    /**\n     * Parses the aggregated response.\n     * \n     * @param response\n     *            the response\n     * @param query\n     *            the query\n     * @param metaModel\n     *            the meta model\n     * @param clazz\n     *            the clazz\n     * @param entityMetadata\n     *            the entity metadata\n     * @return the list\n     */\n    private List parseAggregatedResponse(SearchResponse response, KunderaQuery query, MetamodelImpl metaModel,\n            Class clazz, EntityMetadata entityMetadata)\n    {\n        List results, temp = new ArrayList<>();\n        InternalAggregations internalAggs = ((InternalFilter) response.getAggregations().getAsMap()\n                .get(ESConstants.AGGREGATION_NAME)).getAggregations();\n\n        if (query.isSelectStatement() && KunderaQueryUtils.hasGroupBy(query.getJpqlExpression()))\n        {\n            Terms buckets = (Terms) (internalAggs).getAsMap().get(ESConstants.GROUP_BY);\n\n            filterBuckets(buckets, query);\n\n            results = onIterateBuckets(buckets, query, metaModel, clazz, entityMetadata);\n        }\n        else\n        {\n            results = new ArrayList<>();\n            temp = buildRecords(internalAggs, response.getHits(), query, metaModel, clazz, entityMetadata);\n\n            for (Object value : temp)\n            {\n                if (!value.toString().equalsIgnoreCase(ESConstants.INFINITY))\n                {\n                    results.add(value);\n                }\n            }\n        }\n        return results;\n    }\n\n    /**\n     * On iterate buckets.\n     * \n     * @param buckets\n     *            the buckets\n     * @param query\n     *            the query\n     * @param metaModel\n     *            the meta model\n     * @param clazz\n     *            the clazz\n     * @param entityMetadata\n     *            the entity metadata\n     * @return the list\n     */\n    private List onIterateBuckets(Terms buckets, KunderaQuery query, MetamodelImpl metaModel, Class clazz,\n            EntityMetadata entityMetadata)\n    {\n        List temp, results = new ArrayList<>();\n\n        for (Terms.Bucket entry : buckets.getBuckets())\n        {\n            logger.debug(\"key [{}], doc_count [{}]\", entry.getKey(), entry.getDocCount());\n            Aggregations aggregations = entry.getAggregations();\n            TopHits topHits = aggregations.get(ESConstants.TOP_HITS);\n\n            temp = buildRecords((InternalAggregations) aggregations, topHits.getHits(), query, metaModel, clazz,\n                    entityMetadata);\n            results.add(temp.size() == 1 ? temp.get(0) : temp);\n        }\n\n        return results;\n    }\n\n    /**\n     * Parses the aggregations.\n     * \n     * @param response\n     *            the response\n     * @param query\n     *            the query\n     * @param metaModel\n     *            the meta model\n     * @param clazz\n     *            the clazz\n     * @param EntityMetadata\n     *            the m\n     * @return the map\n     */\n    public Map<String, Object> parseAggregations(SearchResponse response, KunderaQuery query, MetamodelImpl metaModel,\n            Class clazz, EntityMetadata m)\n    {\n        Map<String, Object> aggregationsMap = new LinkedHashMap<>();\n        if (query.isAggregated() == true && response.getAggregations() != null)\n        {\n            InternalAggregations internalAggs = ((InternalFilter) response.getAggregations().getAsMap()\n                    .get(ESConstants.AGGREGATION_NAME)).getAggregations();\n\n            ListIterable<Expression> iterable = getSelectExpressionOrder(query);\n\n            if (query.isSelectStatement() && KunderaQueryUtils.hasGroupBy(query.getJpqlExpression()))\n            {\n                Terms buckets = (Terms) (internalAggs).getAsMap().get(ESConstants.GROUP_BY);\n\n                filterBuckets(buckets, query);\n\n                for (Terms.Bucket bucket : buckets.getBuckets())\n                {\n                    logger.debug(\"key [{}], doc_count [{}]\", bucket.getKey(), bucket.getDocCount());\n\n                    TopHits topHits = bucket.getAggregations().get(ESConstants.TOP_HITS);\n                    aggregationsMap.put(topHits.getHits().getAt(0).getId(),\n                            buildRecords(iterable, (InternalAggregations) bucket.getAggregations()));\n                }\n            }\n            else\n            {\n                aggregationsMap = buildRecords(iterable, internalAggs);\n            }\n        }\n        return aggregationsMap;\n    }\n\n    /**\n     * Builds the records.\n     * \n     * @param iterable\n     *            the iterable\n     * @param internalAgg\n     *            the internal agg\n     * @return the map\n     */\n    private Map<String, Object> buildRecords(ListIterable<Expression> iterable, InternalAggregations internalAgg)\n    {\n        Map<String, Object> temp = new HashMap<>();\n        Iterator<Expression> itr = iterable.iterator();\n\n        while (itr.hasNext())\n        {\n            Expression exp = itr.next();\n            if (AggregateFunction.class.isAssignableFrom(exp.getClass()))\n            {\n                Object value = getAggregatedResult(internalAgg, ((AggregateFunction) exp).getIdentifier(), exp);\n                if (!value.toString().equalsIgnoreCase(ESConstants.INFINITY))\n                {\n                    temp.put(exp.toParsedText(), Double.valueOf(value.toString()));\n                }\n            }\n        }\n\n        return temp;\n    }\n\n    /**\n     * Parses the records.\n     * \n     * @param internalAgg\n     *            the internal agg\n     * @param topHits\n     *            the top hits\n     * @param query\n     *            the query\n     * @param metaModel\n     *            the meta model\n     * @param clazz\n     *            the clazz\n     * @param entityMetadata\n     *            the entity metadata\n     * @return the list\n     */\n    private List buildRecords(InternalAggregations internalAgg, SearchHits topHits, KunderaQuery query,\n            MetamodelImpl metaModel, Class clazz, EntityMetadata entityMetadata)\n    {\n        List temp = new ArrayList<>();\n\n        Iterator<Expression> orderIterator = getSelectExpressionOrder(query).iterator();\n        while (orderIterator.hasNext())\n        {\n            Expression exp = orderIterator.next();\n            String text = exp.toActualText();\n            String field = KunderaQueryUtils.isAggregatedExpression(exp) ? text.substring(\n                    text.indexOf(ESConstants.DOT) + 1, text.indexOf(ESConstants.RIGHT_BRACKET)) : text.substring(\n                    text.indexOf(ESConstants.DOT) + 1, text.length());\n\n            temp.add(KunderaQueryUtils.isAggregatedExpression(exp) ? getAggregatedResult(internalAgg,\n                    ((AggregateFunction) exp).getIdentifier(), exp) : getFirstResult(query, field, topHits, clazz,\n                    metaModel, entityMetadata));\n        }\n        return temp;\n    }\n\n    /**\n     * Filter buckets.\n     * \n     * @param buckets\n     *            the buckets\n     * @param query\n     *            the query\n     * @return the terms\n     */\n    private Terms filterBuckets(Terms buckets, KunderaQuery query)\n    {\n        Expression havingClause = query.getSelectStatement().getHavingClause();\n\n        if (!(havingClause instanceof NullExpression) && havingClause != null)\n        {\n            Expression conditionalExpression = ((HavingClause) havingClause).getConditionalExpression();\n\n            for (Iterator<Bucket> bucketIterator = buckets.getBuckets().iterator(); bucketIterator.hasNext();)\n            {\n                InternalAggregations internalAgg = (InternalAggregations) bucketIterator.next().getAggregations();\n                if (!isValidBucket(internalAgg, query, conditionalExpression))\n                {\n                    bucketIterator.remove();\n                }\n            }\n        }\n        return buckets;\n    }\n\n    /**\n     * Checks if is valid bucket.\n     * \n     * @param internalAgg\n     *            the internal agg\n     * @param query\n     *            the query\n     * @param conditionalExpression\n     *            the conditional expression\n     * @return true, if is valid bucket\n     */\n    private boolean isValidBucket(InternalAggregations internalAgg, KunderaQuery query, Expression conditionalExpression)\n    {\n        if (conditionalExpression instanceof ComparisonExpression)\n        {\n            Expression expression = ((ComparisonExpression) conditionalExpression).getLeftExpression();\n            Object leftValue = getAggregatedResult(internalAgg, ((AggregateFunction) expression).getIdentifier(),\n                    expression);\n\n            String rightValue = ((ComparisonExpression) conditionalExpression).getRightExpression().toParsedText();\n            return validateBucket(leftValue.toString(), rightValue,\n                    ((ComparisonExpression) conditionalExpression).getIdentifier());\n        }\n        else if (LogicalExpression.class.isAssignableFrom(conditionalExpression.getClass()))\n        {\n            Expression leftExpression = null, rightExpression = null;\n            if (conditionalExpression instanceof AndExpression)\n            {\n                AndExpression andExpression = (AndExpression) conditionalExpression;\n                leftExpression = andExpression.getLeftExpression();\n                rightExpression = andExpression.getRightExpression();\n            }\n            else\n            {\n                OrExpression orExpression = (OrExpression) conditionalExpression;\n                leftExpression = orExpression.getLeftExpression();\n                rightExpression = orExpression.getRightExpression();\n            }\n\n            return validateBucket(isValidBucket(internalAgg, query, leftExpression),\n                    isValidBucket(internalAgg, query, rightExpression),\n                    ((LogicalExpression) conditionalExpression).getIdentifier());\n        }\n        else\n        {\n            logger.error(\"Expression \" + conditionalExpression + \" in having clause is not supported in Kundera\");\n            throw new UnsupportedOperationException(conditionalExpression\n                    + \" in having clause is not supported in Kundera\");\n        }\n    }\n\n    /**\n     * Validate bucket.\n     * \n     * @param left\n     *            the left\n     * @param right\n     *            the right\n     * @param logicalOperation\n     *            the logical operation\n     * @return true, if successful\n     */\n    private boolean validateBucket(boolean left, boolean right, String logicalOperation)\n    {\n        logger.debug(\"Logical opertation \" + logicalOperation + \" found in having clause\");\n        if (Expression.AND.equalsIgnoreCase(logicalOperation))\n        {\n            return left && right;\n        }\n        else if (Expression.OR.equalsIgnoreCase(logicalOperation))\n        {\n            return left || right;\n        }\n        else\n        {\n            logger.error(logicalOperation + \" in having clause is not supported in Kundera\");\n            throw new UnsupportedOperationException(logicalOperation + \" in having clause is not supported in Kundera\");\n        }\n    }\n\n    /**\n     * Validate bucket.\n     * \n     * @param left\n     *            the left\n     * @param right\n     *            the right\n     * @param operator\n     *            the operator\n     * @return true, if successful\n     */\n    private boolean validateBucket(String left, String right, String operator)\n    {\n        Double leftValue = Double.valueOf(left);\n        Double rightValue = Double.valueOf(right);\n\n        logger.debug(\"Comparison expression \" + operator + \"found with left value: \" + left + \" right value: \" + right);\n\n        if (Expression.GREATER_THAN.equals(operator))\n        {\n            return leftValue > rightValue;\n        }\n        else if (Expression.GREATER_THAN_OR_EQUAL.equals(operator))\n        {\n            return leftValue >= rightValue;\n        }\n        else if (Expression.LOWER_THAN.equals(operator))\n        {\n            return leftValue < rightValue;\n        }\n        else if (Expression.LOWER_THAN_OR_EQUAL.equals(operator))\n        {\n            return leftValue <= rightValue;\n        }\n        else if (Expression.EQUAL.equals(operator))\n        {\n            return leftValue == rightValue;\n        }\n        else\n        {\n            logger.error(operator + \" in having clause is not supported in Kundera\");\n            throw new UnsupportedOperationException(operator + \" in having clause is not supported in Kundera\");\n        }\n    }\n\n    /**\n     * Gets the first result.\n     * \n     * @param query\n     *            the query\n     * @param field\n     *            the field\n     * @param hits\n     *            the hits\n     * @param clazz\n     *            the clazz\n     * @param metaModel\n     *            the meta model\n     * @param entityMetadata\n     *            the entity metadata\n     * @return the first\n     */\n    private Object getFirstResult(KunderaQuery query, String field, SearchHits hits, Class clazz, Metamodel metaModel,\n            EntityMetadata entityMetadata)\n    {\n        Object entity;\n\n        if (query.getEntityAlias().equals(field))\n        {\n            entity = getEntityObjects(clazz, entityMetadata, metaModel.entity(clazz), hits).get(0);\n        }\n        else\n        {\n            String jpaField = ((AbstractAttribute) metaModel.entity(clazz).getAttribute(field)).getJPAColumnName();\n            entity = query.getSelectStatement().hasGroupByClause() ? hits.getAt(0).sourceAsMap().get(jpaField) : hits\n                    .getAt(0).getFields().get(jpaField).getValue();\n        }\n        return entity;\n    }\n\n    /**\n     * Gets the aggregated result.\n     * \n     * @param internalAggs\n     *            the internal aggs\n     * @param identifier\n     *            the identifier\n     * @param exp\n     *            the exp\n     * @return the aggregated result\n     */\n    private Object getAggregatedResult(InternalAggregations internalAggs, String identifier, Expression exp)\n    {\n        switch (identifier)\n        {\n        case Expression.MIN:\n            return (((InternalMin) internalAggs.get(exp.toParsedText())).getValue());\n\n        case Expression.MAX:\n            return (((InternalMax) internalAggs.get(exp.toParsedText())).getValue());\n\n        case Expression.AVG:\n            return (((InternalAvg) internalAggs.get(exp.toParsedText())).getValue());\n\n        case Expression.SUM:\n            return (((InternalSum) internalAggs.get(exp.toParsedText())).getValue());\n\n        case Expression.COUNT:\n            return (((InternalValueCount) internalAggs.get(exp.toParsedText())).getValue());\n        }\n\n        throw new KunderaException(\"No support for \" + identifier + \" aggregation.\");\n    }\n\n    /**\n     * Wrap find result.\n     * \n     * @param searchResults\n     *            the search results\n     * @param entityType\n     *            the entity type\n     * @param result\n     *            the result\n     * @param metadata\n     *            the metadata\n     * @param b\n     *            the b\n     * @return the object\n     */\n    public Object wrapFindResult(Map<String, Object> searchResults, EntityType entityType, Object result,\n            EntityMetadata metadata, boolean b)\n    {\n        return wrap(searchResults, entityType, result, metadata, b);\n    }\n\n    /**\n     * Wrap.\n     * \n     * @param results\n     *            the results\n     * @param entityType\n     *            the entity type\n     * @param result\n     *            the result\n     * @param metadata\n     *            the metadata\n     * @param isIdSet\n     *            the is id set\n     * @return the object\n     */\n    private Object wrap(Map<String, Object> results, EntityType entityType, Object result, EntityMetadata metadata,\n            boolean isIdSet)\n    {\n\n        Map<String, Object> relations = new HashMap<String, Object>();\n        Object key = null;\n        Set<Attribute> attributes = entityType.getAttributes();\n        for (Attribute attribute : attributes)\n        {\n            String fieldName = ((AbstractAttribute) attribute).getJPAColumnName();\n\n            if (!attribute.isAssociation())\n            {\n                Object fieldValue = results.get(fieldName);\n\n                key = onId(key, attribute, fieldValue);\n\n                if (!isIdSet && key != null)\n                {\n                    PropertyAccessorHelper.setId(result, metadata, key);\n                }\n\n                fieldValue = onEnum(attribute, fieldValue);\n\n                // TODOO:This has to be corrected. Reason is, in case of execute\n                // query over composite key. It will not work\n\n                setField(result, key, attribute, fieldValue);\n            }\n\n            if (attribute.isAssociation())\n            {\n                Object fieldValue = results.get(fieldName);\n                relations.put(fieldName, fieldValue);\n            }\n        }\n        return relations.isEmpty() ? result : new EnhanceEntity(result, key, relations);\n    }\n\n    /**\n     * On enum.\n     * \n     * @param attribute\n     *            the attribute\n     * @param fieldValue\n     *            the field value\n     * @return the object\n     */\n    private Object onEnum(Attribute attribute, Object fieldValue)\n    {\n        if (((Field) attribute.getJavaMember()).getType().isEnum())\n        {\n            EnumAccessor accessor = new EnumAccessor();\n            fieldValue = accessor.fromString(((AbstractAttribute) attribute).getBindableJavaType(),\n                    fieldValue.toString());\n        }\n        return fieldValue;\n    }\n\n    /**\n     * Sets the field.\n     * \n     * @param result\n     *            the result\n     * @param key\n     *            the key\n     * @param attribute\n     *            the attribute\n     * @param fieldValue\n     *            the field value\n     */\n    private void setField(Object result, Object key, Attribute attribute, Object fieldValue)\n    {\n        if (fieldValue != null)\n        {\n            if (((AbstractAttribute) attribute).getBindableJavaType().isAssignableFrom(Date.class)\n                    || ((AbstractAttribute) attribute).getBindableJavaType().isAssignableFrom(java.sql.Date.class)\n                    || ((AbstractAttribute) attribute).getBindableJavaType().isAssignableFrom(Timestamp.class)\n                    || ((AbstractAttribute) attribute).getBindableJavaType().isAssignableFrom(Calendar.class))\n            {\n                PropertyAccessorFactory.STRING.fromString(((AbstractAttribute) attribute).getBindableJavaType(),\n                        fieldValue.toString());\n            }\n            else if (key == null || !key.equals(fieldValue))\n            {\n                PropertyAccessorHelper.set(result, (Field) attribute.getJavaMember(), fieldValue);\n            }\n        }\n    }\n\n    /**\n     * On id.\n     * \n     * @param key\n     *            the key\n     * @param attribute\n     *            the attribute\n     * @param fieldValue\n     *            the field value\n     * @return the object\n     */\n    private Object onId(Object key, Attribute attribute, Object fieldValue)\n    {\n        if (SingularAttribute.class.isAssignableFrom(attribute.getClass()) && ((SingularAttribute) attribute).isId())\n        {\n            key = fieldValue;\n        }\n        return key;\n    }\n\n    /**\n     * Gets the select expression order.\n     * \n     * @param query\n     *            the query\n     * @return the select expression order\n     */\n    public ListIterable<Expression> getSelectExpressionOrder(KunderaQuery query)\n    {\n        if (!KunderaQueryUtils.isSelectStatement(query.getJpqlExpression()))\n        {\n            return null;\n        }\n        Expression selectExpression = ((SelectClause) (query.getSelectStatement()).getSelectClause())\n                .getSelectExpression();\n\n        List<Expression> list;\n\n        if (!(selectExpression instanceof CollectionExpression))\n        {\n            list = new LinkedList<Expression>();\n            list.add(selectExpression);\n            return new SnapshotCloneListIterable<Expression>(list);\n        }\n        else\n        {\n            return selectExpression.children();\n        }\n    }\n\n    /**\n     * Gets the entity objects.\n     * \n     * @param clazz\n     *            the clazz\n     * @param entityMetadata\n     *            the entity metadata\n     * @param entityType\n     *            the entity type\n     * @param hits\n     *            the hits\n     * @return the entity objects\n     */\n    private List getEntityObjects(Class clazz, final EntityMetadata entityMetadata, EntityType entityType,\n            SearchHits hits)\n    {\n        List results = new ArrayList();\n\n        Object entity = null;\n        for (SearchHit hit : hits.getHits())\n        {\n            entity = KunderaCoreUtils.createNewInstance(clazz);\n            Map<String, Object> hitResult = hit.sourceAsMap();\n            results.add(wrap(hitResult, entityType, entity, entityMetadata, false));\n        }\n\n        return results;\n    }\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/Book.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Book.\n * \n * @author devender.yadav\n * \n */\n@Entity\n@Table(name = \"BOOK\", schema = \"esSchema@es-refresh-indexes-pu\")\npublic class Book\n{\n\n    /** The book id. */\n    @Id\n    @Column(name = \"BOOK_ID\")\n    private int bookId;\n\n    /** The title. */\n    @Column(name = \"TITLE\")\n    private String title;\n\n    /** The author. */\n    @Column(name = \"AUTHOR\")\n    private String author;\n\n    /** The num pages. */\n    @Column(name = \"NUM_PAGES\")\n    private int numPages;\n\n    /**\n     * Gets the book id.\n     *\n     * @return the book id\n     */\n    public int getBookId()\n    {\n        return bookId;\n    }\n\n    /**\n     * Sets the book id.\n     *\n     * @param bookId\n     *            the new book id\n     */\n    public void setBookId(int bookId)\n    {\n        this.bookId = bookId;\n    }\n\n    /**\n     * Gets the title.\n     *\n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * Sets the title.\n     *\n     * @param title\n     *            the new title\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * Gets the author.\n     *\n     * @return the author\n     */\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    /**\n     * Sets the author.\n     *\n     * @param author\n     *            the new author\n     */\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    /**\n     * Gets the num pages.\n     *\n     * @return the num pages\n     */\n    public int getNumPages()\n    {\n        return numPages;\n    }\n\n    /**\n     * Sets the num pages.\n     *\n     * @param numPages\n     *            the new num pages\n     */\n    public void setNumPages(int numPages)\n    {\n        this.numPages = numPages;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/CRUDTestWithRefreshedIndexes.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport junit.framework.Assert;\n\n/**\n * The Class CRUDTestWithRefreshedIndexes.\n * \n * @author devender.yadav\n * \n */\npublic class CRUDTestWithRefreshedIndexes\n{\n\n    /** The emf. */\n    protected EntityManagerFactory emf;\n\n    /** The em. */\n    protected EntityManager em;\n\n    /** The node. */\n    private static Node node = null;\n\n    /**\n     * Sets the up before class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        Builder builder = Settings.settingsBuilder();\n        builder.put(\"path.home\", \"target/data\");\n        node = new NodeBuilder().settings(builder).node();\n    }\n\n    /**\n     * Setup.\n     */\n    @Before\n    public void setup()\n    {\n        emf = Persistence.createEntityManagerFactory(\"es-refresh-indexes-pu\");\n        em = emf.createEntityManager();\n        /*\n         * This property will force ES to refresh indexes on all the nodes after\n         * insert, update and delete operations.\n         * \n         */\n        em.setProperty(\"es.refresh.indexes\", true);\n    }\n\n    /**\n     * Test crud.\n     *\n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    @Test\n    public void testCRUD() throws InterruptedException\n    {\n\n        /*\n         * Insert 100 book records\n         */\n\n        for (int i = 1; i <= 100; i++)\n        {\n            Book b = new Book();\n\n            b.setBookId(1000 + i);\n            b.setAuthor(\"author_\" + i);\n            b.setTitle(\"title_\" + i);\n            b.setNumPages(100 + i);\n\n            em.persist(b);\n        }\n\n        Query q = em.createQuery(\"select count(b) from Book b\");\n        List bookList = q.getResultList();\n        Assert.assertEquals(100L, bookList.get(0));\n\n        /*\n         * Update titles of all the records\n         * \n         */\n        for (int i = 1; i <= 100; i++)\n        {\n            Book book = em.find(Book.class, 1000 + i);\n            Assert.assertEquals(100 + i, book.getNumPages());\n            Assert.assertEquals(\"title_\" + i, book.getTitle());\n            Assert.assertEquals(\"author_\" + i, book.getAuthor());\n            book.setTitle(\"updated_title_\" + i);\n            em.merge(book);\n        }\n\n        for (int i = 1; i <= 100; i++)\n        {\n            Book book = em.find(Book.class, 1000 + i);\n            Assert.assertEquals(100 + i, book.getNumPages());\n            Assert.assertEquals(\"updated_title_\" + i, book.getTitle());\n            Assert.assertEquals(\"author_\" + i, book.getAuthor());\n        }\n\n        /*\n         * Delete all 100 records\n         * \n         */\n        q = em.createQuery(\"delete from Book b\");\n        int count = q.executeUpdate();\n\n        // Assert.assertEquals(100, count);\n\n        bookList = new ArrayList<>();\n        q = em.createQuery(\"select count(b) from Book b\");\n        bookList = q.getResultList();\n        Assert.assertEquals(0L, bookList.get(0));\n\n        for (int i = 1; i <= 100; i++)\n        {\n            Book book = em.find(Book.class, 1000 + i);\n            Assert.assertNull(book);\n        }\n\n    }\n\n    /**\n     * Tear down.\n     */\n    @After\n    public void tearDown()\n    {\n        if (em != null)\n        {\n            em.close();\n        }\n\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n    /**\n     * Tear down after class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        node.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/CRUDTestWithRefreshedIndexesViaExternalProperty.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.util.Properties;\n\nimport javax.persistence.Persistence;\n\nimport org.junit.Before;\n\n/**\n * The Class CRUDTestWithRefreshedIndexesViaPuProperty.\n * \n * @author devender.yadav\n * \n */\npublic class CRUDTestWithRefreshedIndexesViaExternalProperty extends CRUDTestWithRefreshedIndexes\n{\n\n    /**\n     * Setup.\n     */\n    @Before\n    public void setup()\n    {\n\n        Properties prop = new Properties();\n        prop.put(\"kundera.es.refresh.indexes\", true);\n        emf = Persistence.createEntityManagerFactory(\"es-refresh-indexes-pu\", prop);\n        em = emf.createEntityManager();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/ESAggregationTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\n/**\n * @author Amit Kumar\n *\n */\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.es.PersonES.Day;\n\n/**\n * The Class ESAggregationTest.\n */\npublic class ESAggregationTest\n{\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The node. */\n    private static Node node = null;\n\n    /** The person. */\n    private PersonES person;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n    }\n\n    /**\n     * Check if server running.\n     * \n     * @return true, if successful\n     */\n    private static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 9300);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n    }\n\n    /**\n     * Setup.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    @Before\n    public void setup() throws InterruptedException\n    {\n        emf = Persistence.createEntityManagerFactory(\"es-pu\");\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Inits the.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    private void init() throws InterruptedException\n    {\n        createPerson(\"1\", 20, \"Amit\", 100.0);\n        createPerson(\"2\", 10, \"Dev\", 200.0);\n        createPerson(\"3\", 30, \"Karthik\", 300.0);\n        createPerson(\"4\", 40, \"Pragalbh\", 400.0);\n        waitThread();\n    }\n\n    /**\n     * Creates the person.\n     * \n     * @param id\n     *            the id\n     * @param age\n     *            the age\n     * @param name\n     *            the name\n     * @param salary\n     *            the salary\n     */\n    private void createPerson(String id, int age, String name, Double salary)\n    {\n        person = new PersonES();\n        person.setAge(age);\n        person.setDay(Day.FRIDAY);\n        person.setPersonId(id);\n        person.setPersonName(name);\n        person.setSalary(salary);\n        em.persist(person);\n    }\n\n    /**\n     * Test aggregation.\n     */\n    @Test\n    public void testAggregation()\n    {\n        testMinAggregation();\n        testMultiMinAggregation();\n        testMaxAggregation();\n        testMultiMaxAggregation();\n        testSumAggregation();\n        testMultiSumAggregation();\n        testAvgAggregation();\n        testMultiAvgAggregation();\n        testMaxMinSameFieldAggregation();\n        testMultiAggregation();\n        testMinMaxSumAvgAggregation();\n        testAggregationWithWhereClause();\n        testPositionalQuery();\n        testParameterQuery();\n        testBetween();\n        testBetweenWithExpression();\n        testBetweenMin();\n        testLikeQuery();\n    }\n\n    /**\n     * Test min aggregation.\n     */\n    private void testMinAggregation()\n    {\n        String queryString = \"Select min(p.salary) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(100.0, resultList.get(0));\n    }\n\n    /**\n     * Test min aggregation on string.\n     */\n    private void testMinAggregationOnString()\n    {\n        String queryString = \"Select min(p.personName) from PersonES p\";\n        Query query = em.createQuery(queryString);\n\n        try\n        {\n            List resultList = query.getResultList();\n            Assert.fail();\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\"Aggregations can not performed over non-numeric fields.\", e.getMessage());\n        }\n    }\n\n    /**\n     * Test multi min aggregation.\n     */\n    private void testMultiMinAggregation()\n    {\n        String queryString = \"Select min(p.salary), min(p.age) from PersonES p where p.age > 20\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(300.0, resultList.get(0));\n        Assert.assertEquals(30.0, resultList.get(1));\n    }\n\n    /**\n     * Test max aggregation.\n     */\n    private void testMaxAggregation()\n    {\n        String queryString = \"Select max(p.age) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(40.0, resultList.get(0));\n    }\n\n    /**\n     * Test multi max aggregation.\n     */\n    private void testMultiMaxAggregation()\n\n    {\n        String queryString = \"Select max(p.age), max(p.salary) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(40.0, resultList.get(0));\n        Assert.assertEquals(400.0, resultList.get(1));\n    }\n\n    /**\n     * Test sum aggregation.\n     */\n    private void testSumAggregation()\n    {\n        String queryString = \"Select sum(p.salary) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(1000.0, resultList.get(0));\n    }\n\n    /**\n     * Test multi sum aggregation.\n     */\n    private void testMultiSumAggregation()\n    {\n        String queryString = \"Select sum(p.salary), sum(p.age) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(1000.0, resultList.get(0));\n        Assert.assertEquals(100.0, resultList.get(1));\n    }\n\n    /**\n     * Test avg aggregation.\n     */\n    private void testAvgAggregation()\n    {\n        String queryString = \"Select avg(p.salary) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(250.0, resultList.get(0));\n    }\n\n    /**\n     * Test multi avg aggregation.\n     */\n    private void testMultiAvgAggregation()\n    {\n        String avgQuery = \"Select avg(p.salary), avg(p.age) from PersonES p\";\n        Query query = em.createQuery(avgQuery);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(250.0, resultList.get(0));\n        Assert.assertEquals(25.0, resultList.get(1));\n    }\n\n    /**\n     * Test max min same field aggregation.\n     */\n    private void testMaxMinSameFieldAggregation()\n    {\n        String queryString = \"Select max(p.age), min(p.age) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(40.0, resultList.get(0));\n        Assert.assertEquals(10.0, resultList.get(1));\n    }\n\n    /**\n     * Test multi aggregation.\n     */\n    private void testMultiAggregation()\n    {\n        String queryString = \"Select min(p.age), min(p.salary), max(p.age), max(p.salary) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n        Assert.assertEquals(10.0, resultList.get(0));\n        Assert.assertEquals(100.0, resultList.get(1));\n        Assert.assertEquals(40.0, resultList.get(2));\n        Assert.assertEquals(400.0, resultList.get(3));\n    }\n\n    /**\n     * Test min max sum avg aggregation.\n     */\n    private void testMinMaxSumAvgAggregation()\n    {\n        String queryString = \"Select min(p.salary), max(p.salary), sum(p.salary), avg(p.salary) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n        Assert.assertEquals(100.0, resultList.get(0));\n        Assert.assertEquals(400.0, resultList.get(1));\n        Assert.assertEquals(1000.0, resultList.get(2));\n        Assert.assertEquals(250.0, resultList.get(3));\n    }\n\n    /**\n     * Test attribute with min aggregation.\n     */\n    private void testAttributeWithMinAggregation()\n    {\n        String queryString = \"Select p.age, min(p.salary) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(40, resultList.get(0));\n        Assert.assertEquals(100.0, resultList.get(1));\n    }\n\n    /**\n     * Test min with attribute aggregation.\n     */\n    private void testMinWithAttributeAggregation()\n    {\n        String queryString = \"Select min(p.salary), p.age from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(100.0, resultList.get(0));\n        Assert.assertEquals(40, resultList.get(1));\n    }\n\n    /**\n     * Test max with attribute aggregation.\n     */\n    private void testMaxWithAttributeAggregation()\n    {\n        String queryString = \"Select max(p.salary), p.salary from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(400.0, resultList.get(0));\n        Assert.assertEquals(400.0, resultList.get(1));\n    }\n\n    /**\n     * Test attribute with sum aggregation.\n     */\n    private void testAttributeWithSumAggregation()\n    {\n        String queryString = \"Select p.age, sum(p.salary) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(40, resultList.get(0));\n        Assert.assertEquals(1000.0, resultList.get(1));\n    }\n\n    /**\n     * Test sum with attribute same field aggregation.\n     */\n    private void testSumWithAttributeSameFieldAggregation()\n    {\n        String queryString = \"Select sum(p.salary), p.salary from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(1000.0, resultList.get(0));\n        Assert.assertEquals(400.0, resultList.get(1));\n    }\n\n    /**\n     * Test attribute with avg aggregation.\n     */\n    private void testAttributeWithAvgAggregation()\n    {\n        String queryString = \"Select p.age, avg(p.salary) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(40, resultList.get(0));\n        Assert.assertEquals(250.0, resultList.get(1));\n    }\n\n    /**\n     * Test avg with attribute same field aggregation.\n     */\n    private void testAvgWithAttributeSameFieldAggregation()\n    {\n        String queryString = \"Select avg(p.salary), p.salary from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(250.0, resultList.get(0));\n        Assert.assertEquals(400.0, resultList.get(1));\n    }\n\n    /**\n     * Test multi field aggregation.\n     */\n    private void testMultiFieldAggregation()\n    {\n        String queryString = \"Select p.age, min(p.salary), p.salary, max(p.salary), p.personId, sum(p.salary), p.personName, avg(p.salary) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(8, resultList.size());\n        Assert.assertEquals(40, resultList.get(0));\n        Assert.assertEquals(100.0, resultList.get(1));\n        Assert.assertEquals(400.0, resultList.get(2));\n        Assert.assertEquals(400.0, resultList.get(3));\n        Assert.assertEquals(\"4\", resultList.get(4));\n        Assert.assertEquals(1000.0, resultList.get(5));\n        Assert.assertEquals(\"Pragalbh\", resultList.get(6));\n        Assert.assertEquals(250.0, resultList.get(7));\n    }\n\n    /**\n     * Test aggregation with where clause.\n     */\n    private void testAggregationWithWhereClause()\n    {\n        try\n        {\n            waitThread();\n\n            String invalidQueryWithAndClause = \"Select min(p.age) from PersonES p where p.personName like '%it' AND p.age = 34\";\n            Query nameQuery = em.createNamedQuery(invalidQueryWithAndClause);\n            List persons = nameQuery.getResultList();\n\n            Assert.assertTrue(persons.isEmpty());\n\n            String queryWithAndClause = \"Select min(p.age) from PersonES p where p.personName = 'amit' AND p.age = 20\";\n            nameQuery = em.createNamedQuery(queryWithAndClause);\n            persons = nameQuery.getResultList();\n\n            Assert.assertFalse(persons.isEmpty());\n            Assert.assertEquals(1, persons.size());\n            Assert.assertEquals(20.0, persons.get(0));\n\n            String queryWithORClause = \"Select max(p.salary) from PersonES p where p.personName = 'amit' OR p.personName = 'dev'\";\n            nameQuery = em.createNamedQuery(queryWithORClause);\n            persons = nameQuery.getResultList();\n\n            Assert.assertFalse(persons.isEmpty());\n            Assert.assertEquals(1, persons.size());\n            Assert.assertEquals(200.0, persons.get(0));\n\n            String queryMinMaxWithORClause = \"Select max(p.salary), min(p.age) from PersonES p where p.personName = 'amit' OR p.personName = 'karthik'\";\n            nameQuery = em.createNamedQuery(queryMinMaxWithORClause);\n            persons = nameQuery.getResultList();\n\n            Assert.assertFalse(persons.isEmpty());\n            Assert.assertEquals(2, persons.size());\n            Assert.assertEquals(300.0, persons.get(0));\n            Assert.assertEquals(20.0, persons.get(1));\n\n            String invalidQueryWithORClause = \"Select sum(p.age) from PersonES p where p.personName = 'amit' OR p.personName = 'lkl'\";\n            nameQuery = em.createNamedQuery(invalidQueryWithORClause);\n            persons = nameQuery.getResultList();\n\n            Assert.assertFalse(persons.isEmpty());\n            Assert.assertEquals(1, persons.size());\n            Assert.assertEquals(20.0, persons.get(0));\n\n            String testSumWithGreaterThanClause = \"Select sum(p.age) from PersonES p where p.age > 15\";\n            nameQuery = em.createNamedQuery(testSumWithGreaterThanClause);\n            persons = nameQuery.getResultList();\n\n            Assert.assertFalse(persons.isEmpty());\n            Assert.assertEquals(1, persons.size());\n            Assert.assertEquals(90.0, persons.get(0));\n            waitThread();\n        }\n        catch (InterruptedException e)\n        {\n\n        }\n    }\n\n    /**\n     * Test positional query.\n     */\n    private void testPositionalQuery()\n    {\n        String queryString = \"Select min(p.salary) from PersonES p where p.personName = ?1\";\n        Query query = em.createQuery(queryString);\n        query.setParameter(1, \"amit\");\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(100.0, resultList.get(0));\n    }\n\n    /**\n     * Test parameter query.\n     */\n    private void testParameterQuery()\n    {\n        String queryString = \"Select p from PersonES p where p.personName = :personName\";\n        Query query = em.createQuery(queryString);\n        query.setParameter(\"personName\", \"amit\");\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(100.0, ((PersonES) resultList.get(0)).getSalary());\n    }\n\n    /**\n     * Test between.\n     */\n    private void testBetween()\n    {\n        String queryString = \"Select p from PersonES p where p.age between 20 and 34\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n    }\n\n    /**\n     * Test between with expression.\n     */\n    private void testBetweenWithExpression()\n    {\n        String queryString = \"Select p from PersonES p where p.age between 15+5 and 40-6\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n    }\n\n    /**\n     * Test between min.\n     */\n    private void testBetweenMin()\n    {\n        String queryString = \"Select min(p.age) from PersonES p where p.age between 18 and 34\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(20.0, resultList.get(0));\n    }\n\n    /**\n     * Test like query.\n     */\n    private void testLikeQuery()\n    {\n        String queryString = \"Select min(p.age) from PersonES p where p.personName like '%mit'\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(20.0, resultList.get(0));\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (node != null)\n            node.close();\n    }\n\n    /**\n     * Tear down.\n     */\n    @After\n    public void tearDown()\n    {\n        em.remove(em.find(PersonES.class, \"1\"));\n        em.remove(em.find(PersonES.class, \"2\"));\n        em.remove(em.find(PersonES.class, \"3\"));\n        em.remove(em.find(PersonES.class, \"4\"));\n\n        em.close();\n        emf.close();\n    }\n\n    /**\n     * Wait thread.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    private void waitThread() throws InterruptedException\n    {\n        Thread.sleep(2000);\n    }\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/ESClientFactoryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * @author vivek.mishra junit for {@link ESClientFactory}\n * \n */\npublic class ESClientFactoryTest\n{\n    private final static String persistenceUnit = \"es-pu\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setup()\n    {\n        emf = getEntityManagerFactory();\n    }\n\n    @Test\n    public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException, InvocationTargetException, NoSuchMethodException\n    {\n        ESClientFactory esFactory = new ESClientFactory();\n        Map<String, Object> props = new HashMap<String, Object>();\n        props.put(PersistenceProperties.KUNDERA_NODES, \"localhost\");\n        props.put(PersistenceProperties.KUNDERA_PORT, \"9300\");\n\n        Field f = esFactory.getClass().getSuperclass().getDeclaredField(\"persistenceUnit\");\n\n        if (!f.isAccessible())\n        {\n            f.setAccessible(true);\n        }\n        f.set(esFactory, persistenceUnit);\n        Method m = GenericClientFactory.class.getDeclaredMethod(\"setKunderaMetadata\", KunderaMetadata.class);\n        if (!m.isAccessible())\n        {\n            m.setAccessible(true);\n        }\n\n        m.invoke(esFactory, ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n\n        esFactory.initialize(props);\n\n        Assert.assertNotNull(esFactory.getClientInstance());\n    }\n\n    private EntityManagerFactory getEntityManagerFactory()\n    {\n        return Persistence.createEntityManagerFactory(\"es-pu\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/ESClientPropertyReaderTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.lang.reflect.Field;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.Client;\n\n/**\n * @author vivek.mishra junit for {@link ESClientPropertyReader}\n */\npublic class ESClientPropertyReaderTest\n{\n\n    private static final String PERSISTENCE_UNIT = \"es-external-config\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    @Before\n    public void setup()\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException\n    {\n        Map<String, Client<ESQuery>> clients = (Map<String, Client<ESQuery>>) em.getDelegate();\n\n        ESClient client = (ESClient) clients.get(PERSISTENCE_UNIT);\n\n        Field factoryField = client.getClass().getDeclaredField(\"factory\");\n\n        if (!factoryField.isAccessible())\n        {\n            factoryField.setAccessible(true);\n        }\n\n        ESClientFactory factory = (ESClientFactory) factoryField.get(client);\n\n        Field propertyReader = ((ESClientFactory) factory).getClass().getSuperclass()\n                .getDeclaredField(\"propertyReader\");\n\n        if (!propertyReader.isAccessible())\n        {\n            propertyReader.setAccessible(true);\n        }\n\n        ESClientPropertyReader readerInstance = (ESClientPropertyReader) propertyReader.get(factory);\n        Properties props = readerInstance.getConnectionProperties();\n\n        Assert.assertEquals(\"true\", props.get(\"client.transport.sniff\"));\n        Assert.assertEquals(\"false\", props.get(\"discovery.zen.ping.multicast.enabled\"));\n        Assert.assertEquals(\"true\", props.get(\"discovery.zen.ping.unicast.enabled\"));\n        Assert.assertEquals(\"false\", props.get(\"discovery.zen.multicast.enabled\"));\n        Assert.assertEquals(\"true\", props.get(\"discovery.zen.unicast.enabled\"));\n    }\n\n    @After\n    public void tearDown()\n    {\n        if (em != null)\n        {\n            em.close();\n        }\n\n        if (emf != null)\n        {\n            emf.close();\n        }\n        \n        \n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/ESClientTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.io.IOException;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.es.PersonES.Day;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\npublic class ESClientTest\n{\n    private final static String persistenceUnit = \"es-pu\";\n\n    private Node node = null;\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setup() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n        emf = getEntityManagerFactory();\n    }\n\n    @Test\n    public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException, InterruptedException, InvocationTargetException, NoSuchMethodException\n    {\n        ESClientFactory esFactory = new ESClientFactory();\n        Map<String, Object> props = new HashMap<String, Object>();\n        props.put(PersistenceProperties.KUNDERA_NODES, \"localhost\");\n        props.put(PersistenceProperties.KUNDERA_PORT, \"9300\");\n\n        Field f = esFactory.getClass().getSuperclass().getDeclaredField(\"persistenceUnit\");\n\n        if (!f.isAccessible())\n        {\n            f.setAccessible(true);\n        }\n        f.set(esFactory, persistenceUnit);\n\n        Method m = GenericClientFactory.class.getDeclaredMethod(\"setKunderaMetadata\", KunderaMetadata.class);\n        if (!m.isAccessible())\n        {\n            m.setAccessible(true);\n        }\n\n        m.invoke(esFactory, ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance());\n        esFactory.load(persistenceUnit, props);\n\n        ESClient client = (ESClient) esFactory.getClientInstance();\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), PersonES.class);\n\n        PersonES entity = new PersonES();\n        entity.setAge(21);\n        entity.setDay(Day.FRIDAY);\n        entity.setPersonId(\"1\");\n        entity.setPersonName(\"vivek\");\n        client.onPersist(metadata, entity, \"1\", null);\n\n        Thread.sleep(3000);\n        PersonES result = (PersonES) client.find(PersonES.class, \"1\");\n        Assert.assertNotNull(result);\n\n        PersonES invalidResult = (PersonES) client.find(PersonES.class, \"2_p\");\n        Assert.assertNull(invalidResult);\n\n        client.delete(result, \"1\");\n        result = (PersonES) client.find(PersonES.class, \"1\");\n        Assert.assertNull(result);\n    }\n\n    private EntityManagerFactory getEntityManagerFactory()\n    {\n        return Persistence.createEntityManagerFactory(\"es-pu\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        if (checkIfServerRunning() && node != null)\n        {\n            node.close();\n        }\n\n    }\n\n    /**\n     * Check if server running.\n     * \n     * @return true, if successful\n     */\n    private static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 9300);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/ESGroupByTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.es.PersonES.Day;\n\n/**\n * The Class ESGroupByTest.\n * \n * @author Amit Kumar\n */\npublic class ESGroupByTest\n{\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /** The node. */\n    private static Node node = null;\n\n    /** The person. */\n    private static PersonES person;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n\n        emf = Persistence.createEntityManagerFactory(\"es-pu\");\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Check if server running.\n     * \n     * @return true, if successful\n     */\n    private static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 9300);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n    }\n\n    /**\n     * Inits the.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    private static void init() throws InterruptedException\n    {\n        createPerson(\"1\", 10, \"Amit\", 100.0);\n        createPerson(\"2\", 20, \"Dev\", 200.0);\n        createPerson(\"3\", 30, \"Karthik\", 300.0);\n        createPerson(\"4\", 40, \"Pragalbh\", 400.0);\n        createPerson(\"5\", 10, \"AK\", 500.0);\n        createPerson(\"6\", 20, \"D\", 600.0);\n        createPerson(\"7\", 30, \"KPM\", 700.0);\n        createPerson(\"8\", 40, \"PG\", 800.0);\n        waitThread();\n    }\n\n    /**\n     * Creates the person.\n     * \n     * @param id\n     *            the id\n     * @param age\n     *            the age\n     * @param name\n     *            the name\n     * @param salary\n     *            the salary\n     */\n    private static void createPerson(String id, int age, String name, Double salary)\n    {\n        person = new PersonES();\n        person.setAge(age);\n        person.setDay(Day.FRIDAY);\n        person.setPersonId(id);\n        person.setPersonName(name);\n        person.setSalary(salary);\n        em.persist(person);\n    }\n\n    /**\n     * Test aggregation.\n     */\n    @Test\n    public void testAggregation()\n    {\n        testGroupBy();\n        testGroupByRowKey();\n        testGroupByWithWhereClause();\n        testGroupByWithEntity();\n        testGroupByWithFields();\n        testGroupByWithMetricAgg();\n\n        testHaving();\n        testHavingWithWhereClause();\n        testHavingWithEntity();\n        testHavingWithCount();\n        testHavingWithNoMatch();\n        testHavingWithMetricAgg();\n\n        testHavingWithAnd();\n        testHavingWithOr();\n\n        // testGroupByBuckets();\n    }\n\n    /**\n     * Test group by.\n     */\n    private void testGroupBy()\n    {\n        String queryString = \"Select sum(p.salary) from PersonES p group by p.age\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        Assert.assertEquals(600.0, (resultList.get(0)));\n        Assert.assertEquals(800.0, (resultList.get(1)));\n        Assert.assertEquals(1000.0, (resultList.get(2)));\n        Assert.assertEquals(1200.0, (resultList.get(3)));\n    }\n\n    /**\n     * Test group by row key.\n     */\n    private void testGroupByRowKey()\n    {\n        String queryString = \"Select sum(p.salary) from PersonES p group by p.personId\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(8, resultList.size());\n        Assert.assertEquals(100.0, (resultList.get(0)));\n        Assert.assertEquals(200.0, (resultList.get(1)));\n        Assert.assertEquals(300.0, (resultList.get(2)));\n        Assert.assertEquals(400.0, (resultList.get(3)));\n        Assert.assertEquals(500.0, (resultList.get(4)));\n        Assert.assertEquals(600.0, (resultList.get(5)));\n        Assert.assertEquals(700.0, (resultList.get(6)));\n        Assert.assertEquals(800.0, (resultList.get(7)));\n    }\n\n    /**\n     * Test group by with where clause.\n     */\n    private void testGroupByWithWhereClause()\n    {\n        String queryString = \"Select sum(p.salary) from PersonES p where p.age > 20 group by p.age\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n        Assert.assertEquals(1000.0, (resultList.get(0)));\n        Assert.assertEquals(1200.0, (resultList.get(1)));\n    }\n\n    /**\n     * Test group by with entity.\n     */\n    private void testGroupByWithEntity()\n    {\n        String queryString = \"Select p from PersonES p where p.age < 20 group by p.age\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        PersonES person = (PersonES) (resultList.get(0));\n        Assert.assertEquals(\"5\", person.getPersonId());\n        Assert.assertEquals(\"AK\", person.getPersonName());\n        Assert.assertEquals(10, person.getAge().intValue());\n        Assert.assertEquals(500.0, person.getSalary());\n    }\n\n    /**\n     * Test group by with fields.\n     */\n    private void testGroupByWithFields()\n    {\n        String queryString = \"Select p.age, p.personName, p.personId from PersonES p where p.age < 30 group by p.age\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n\n        List result = (List) resultList.get(0);\n        Assert.assertEquals(10, result.get(0));\n\n        result = (List) resultList.get(1);\n        Assert.assertEquals(20, result.get(0));\n    }\n\n    /**\n     * Test group by with metric agg.\n     */\n    private void testGroupByWithMetricAgg()\n    {\n        String queryString = \"Select p.salary, sum(p.age), p.personName, p.personId from PersonES p where p.age < 30 group by p.salary\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        List result = (List) resultList.get(0);\n        Assert.assertEquals(100.0, result.get(0));\n        Assert.assertEquals(10.0, result.get(1));\n        Assert.assertEquals(\"Amit\", result.get(2));\n        Assert.assertEquals(\"1\", result.get(3));\n\n        result = (List) resultList.get(1);\n        Assert.assertEquals(200.0, result.get(0));\n        Assert.assertEquals(20.0, result.get(1));\n        Assert.assertEquals(\"Dev\", result.get(2));\n        Assert.assertEquals(\"2\", result.get(3));\n\n        result = (List) resultList.get(2);\n        Assert.assertEquals(500.0, result.get(0));\n        Assert.assertEquals(10.0, result.get(1));\n        Assert.assertEquals(\"AK\", result.get(2));\n        Assert.assertEquals(\"5\", result.get(3));\n\n        result = (List) resultList.get(3);\n        Assert.assertEquals(600.0, result.get(0));\n        Assert.assertEquals(20.0, result.get(1));\n        Assert.assertEquals(\"D\", result.get(2));\n        Assert.assertEquals(\"6\", result.get(3));\n    }\n\n    /**\n     * Test having.\n     */\n    private void testHaving()\n    {\n        String queryString = \"Select sum(p.salary) from PersonES p group by p.age having avg(p.age) > 20\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n\n        Assert.assertEquals(1000.0, (resultList.get(0)));\n        Assert.assertEquals(1200.0, (resultList.get(1)));\n    }\n\n    /**\n     * Test having with where clause.\n     */\n    private void testHavingWithWhereClause()\n    {\n        String queryString = \"Select sum(p.salary) from PersonES p where p.age > 20 group by p.age having sum(p.age) > 70\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(1200.0, (resultList.get(0)));\n    }\n\n    /**\n     * Test having with entity.\n     */\n    private void testHavingWithEntity()\n    {\n        String queryString = \"Select p from PersonES p where p.age < 40 group by p.age having max(p.salary) > 600\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        PersonES person = (PersonES) (resultList.get(0));\n        Assert.assertEquals(\"7\", person.getPersonId());\n        Assert.assertEquals(\"KPM\", person.getPersonName());\n        Assert.assertEquals(30, person.getAge().intValue());\n        Assert.assertEquals(700.0, person.getSalary());\n    }\n\n    /**\n     * Test having with count.\n     */\n    private void testHavingWithCount()\n    {\n        String queryString = \"Select p.age, p.personName, p.personId from PersonES p where p.age < 30 group by p.age having count(p) > 1\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(2, resultList.size());\n\n        List result = (List) resultList.get(0);\n        Assert.assertEquals(10, result.get(0));\n\n        result = (List) resultList.get(1);\n        Assert.assertEquals(20, result.get(0));\n    }\n\n    /**\n     * Test having with no match.\n     */\n    private void testHavingWithNoMatch()\n    {\n        String queryString = \"Select p.age, p.personName, p.personId from PersonES p where p.age < 30 group by p.age having count(p) > 2\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(0, resultList.size());\n    }\n\n    /**\n     * Test having with metric agg.\n     */\n    private void testHavingWithMetricAgg()\n    {\n        String queryString = \"Select p.salary, sum(p.age), p.personName, p.personId from PersonES p group by p.personId having sum(p.age) < 30\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        List result = (List) resultList.get(0);\n        Assert.assertEquals(100.0, result.get(0));\n        Assert.assertEquals(10.0, result.get(1));\n        Assert.assertEquals(\"Amit\", result.get(2));\n        Assert.assertEquals(\"1\", result.get(3));\n\n        result = (List) resultList.get(1);\n        Assert.assertEquals(200.0, result.get(0));\n        Assert.assertEquals(20.0, result.get(1));\n        Assert.assertEquals(\"Dev\", result.get(2));\n        Assert.assertEquals(\"2\", result.get(3));\n\n        result = (List) resultList.get(2);\n        Assert.assertEquals(500.0, result.get(0));\n        Assert.assertEquals(10.0, result.get(1));\n        Assert.assertEquals(\"AK\", result.get(2));\n        Assert.assertEquals(\"5\", result.get(3));\n\n        result = (List) resultList.get(3);\n        Assert.assertEquals(600.0, result.get(0));\n        Assert.assertEquals(20.0, result.get(1));\n        Assert.assertEquals(\"D\", result.get(2));\n        Assert.assertEquals(\"6\", result.get(3));\n    }\n\n    /**\n     * Test having with and.\n     */\n    private void testHavingWithAnd()\n    {\n        String queryString = \"Select p.age, p.personName, p.personId from PersonES p where p.age > 20 group by p.age having sum(p.age) > 50 and avg(p.age) < 40\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n\n        List result = (List) resultList.get(0);\n        Assert.assertEquals(30, result.get(0));\n        Assert.assertEquals(\"KPM\", result.get(1));\n        Assert.assertEquals(\"7\", result.get(2));\n    }\n\n    /**\n     * Test having with or.\n     */\n    private void testHavingWithOr()\n    {\n        String queryString = \"Select sum(p.age), count(p.age) from PersonES p where p.salary > 200.0 group by p.age having sum(p.age) > 50 or avg(p.age) < 40\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        List result = (List) resultList.get(0);\n        Assert.assertEquals(60.0, result.get(0));\n        Assert.assertEquals(2, ((Long) result.get(1)).intValue());\n\n        result = (List) resultList.get(1);\n        Assert.assertEquals(80.0, result.get(0));\n        Assert.assertEquals(2, ((Long) result.get(1)).intValue());\n\n        result = (List) resultList.get(2);\n        Assert.assertEquals(10.0, result.get(0));\n        Assert.assertEquals(1, ((Long) result.get(1)).intValue());\n\n        result = (List) resultList.get(3);\n        Assert.assertEquals(20.0, result.get(0));\n        Assert.assertEquals(1, ((Long) result.get(1)).intValue());\n    }\n\n    /**\n     * Test group by buckets.\n     */\n    private void testGroupByBuckets()\n    {\n        createPerson(\"9\", 10, \"Amit\", 100.0);\n        createPerson(\"10\", 10, \"Dev\", 200.0);\n        createPerson(\"11\", 10, \"Karthik\", 300.0);\n        createPerson(\"12\", 10, \"Pragalbh\", 400.0);\n        createPerson(\"13\", 10, \"AK\", 500.0);\n        createPerson(\"14\", 10, \"D\", 600.0);\n        createPerson(\"15\", 10, \"KPM\", 700.0);\n        createPerson(\"16\", 10, \"PG\", 800.0);\n        try\n        {\n            waitThread();\n        }\n        catch (InterruptedException e)\n        {\n        }\n\n        String queryString = \"Select sum(p.age) from PersonES p where p.age < 40 group by p.personId\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(14, resultList.size());\n\n        queryString = \"Select sum(p.age) from PersonES p where p.age < 40 group by p.age\";\n        query = em.createQuery(queryString);\n        resultList = query.getResultList();\n\n        Assert.assertEquals(3, resultList.size());\n        Assert.assertEquals(100.0, resultList.get(0));\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        em.createQuery(\"delete from PersonES p\").executeUpdate();\n        waitThread();\n\n        em.close();\n        emf.close();\n\n        if (node != null)\n            node.close();\n    }\n\n    /**\n     * Wait thread.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    private static void waitThread() throws InterruptedException\n    {\n        Thread.sleep(2000);\n    }\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/ESNestedQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.es.PersonES.Day;\n\n/**\n * The Class ESNestedQueryTest.\n * \n * @author Amit Kumar\n */\npublic class ESNestedQueryTest\n{\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The node. */\n    private static Node node = null;\n\n    /** The person1. */\n    private PersonES person1, person2, person3, person4;\n\n    /**\n     * Before class setup.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n    }\n\n    /**\n     * Check if server running.\n     * \n     * @return true, if successful\n     */\n    private static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 9300);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n    }\n\n    /**\n     * Setup.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    @Before\n    public void setup() throws InterruptedException\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"es-pu\");\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Inits the test data.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    private void init() throws InterruptedException\n    {\n\n        person1 = createPerson(\"1\", 20, \"Amit\", 100.0);\n        person2 = createPerson(\"2\", 10, \"Dev\", 200.0);\n        person3 = createPerson(\"3\", 30, \"Karthik\", 300.0);\n        person4 = createPerson(\"4\", 40, \"Pragalbh\", 400.0);\n        waitThread();\n    }\n\n    /**\n     * Creates the person and persist them.\n     * \n     * @param id\n     *            the id\n     * @param age\n     *            the age\n     * @param name\n     *            the name\n     * @param salary\n     *            the salary\n     * @return the person es\n     */\n    private PersonES createPerson(String id, int age, String name, Double salary)\n    {\n        PersonES person = new PersonES();\n        person.setAge(age);\n        person.setDay(Day.FRIDAY);\n        person.setPersonId(id);\n        person.setPersonName(name);\n        person.setSalary(salary);\n        em.persist(person);\n\n        return person;\n    }\n\n    /**\n     * Test nested query.\n     */\n    @Test\n    public void testNestedQuery()\n    {\n        testQueryWithAndClause();\n        testQueryWithMultiAndClause();\n        testQueryWithOrClause();\n        testQueryWithMultiOrClause();\n        testQueryWithNestedAndOrClause();\n        testMinAggregationWithNestedAndOrClause();\n        testMaxAggregationWithNestedAndOrClause();\n        testMinAggregationWithNestedAndOrClause();\n        testMinAggregationWithNestedAndOr();\n    }\n\n    /**\n     * Test query with and clause.\n     */\n    public void testQueryWithAndClause()\n    {\n        String nestedQquery = \"Select p from PersonES p where p.personName = 'karthik' AND p.personName = 'pragalbh'\";\n        Query query = em.createQuery(nestedQquery);\n        List<PersonES> resultList = query.getResultList();\n\n        Assert.assertEquals(0, resultList.size());\n    }\n\n    /**\n     * Test query with multi and clause.\n     */\n    public void testQueryWithMultiAndClause()\n    {\n        String nestedQquery = \"Select p from PersonES p where p.age > 0 AND p.age < 35 AND p.salary > 150\";\n        Query query = em.createQuery(nestedQquery);\n        List<PersonES> resultList = query.getResultList();\n\n        assertResultList(resultList, person2, person3);\n    }\n\n    /**\n     * Test query with or clause.\n     */\n    public void testQueryWithOrClause()\n    {\n        String nestedQquery = \"Select p from PersonES p where p.personName = 'karthik' OR p.personName = 'pragalbh'\";\n        Query query = em.createQuery(nestedQquery);\n        List<PersonES> resultList = query.getResultList();\n\n        assertResultList(resultList, person3, person4);\n    }\n\n    /**\n     * Test query with multi or clause.\n     */\n    public void testQueryWithMultiOrClause()\n    {\n        String nestedQquery = \"Select p from PersonES p where p.personName = 'amit' OR p.age < 15 OR p.age > 35\";\n        Query query = em.createQuery(nestedQquery);\n        List<PersonES> resultList = query.getResultList();\n\n        assertResultList(resultList, person1, person2, person4);\n    }\n\n    /**\n     * Test query with nested and or clause.\n     */\n    public void testQueryWithNestedAndOrClause()\n    {\n        String nestedQuery = \"Select p from PersonES p where p.age > 0 AND (p.salary > 350 and (p.personName = :name OR p.personName = 'pragalbh'))\";\n\n        Query query = em.createQuery(nestedQuery);\n        query.setParameter(\"name\", \"karthik\");\n        List<PersonES> resultList = query.getResultList();\n\n        assertResultList(resultList, person4);\n    }\n\n    /**\n     * Test max aggregation with nested and or clause.\n     */\n    public void testMaxAggregationWithNestedAndOrClause()\n    {\n        String nestedQuery = \"Select max(p.age) from PersonES p where p.age > 0 AND (p.salary > 250 and (p.personName = 'karthik' OR p.personName = 'pragalbh'))\";\n\n        Query query = em.createQuery(nestedQuery);\n        List resultList = query.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(40.0, resultList.get(0));\n    }\n\n    /**\n     * Test min aggregation with nested and or clause.\n     */\n    public void testMinAggregationWithNestedAndOrClause()\n    {\n        String invalidQueryWithAndClause = \"Select min(p.age) from PersonES p where p.age > 0 AND (p.personName = 'amit' OR p.personName = 'dev')\";\n        Query nameQuery = em.createNamedQuery(invalidQueryWithAndClause);\n        List resultList = nameQuery.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(10.0, resultList.get(0));\n    }\n\n    /**\n     * Test min aggregation with nested and or.\n     */\n    public void testMinAggregationWithNestedAndOr()\n    {\n        String invalidQueryWithAndClause = \"Select min(p.age) from PersonES p where p.age > 0 AND (p.personName = 'amit' OR p.personName = 'dev')\";\n        Query nameQuery = em.createNamedQuery(invalidQueryWithAndClause);\n        List resultList = nameQuery.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n    }\n\n    /**\n     * After class tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (node != null)\n            node.close();\n    }\n\n    /**\n     * Tear down.\n     */\n    @After\n    public void tearDown()\n    {\n        purge();\n        em.close();\n        emf.close();\n    }\n\n    /**\n     * Wait thread.\n     * \n     */\n    private void waitThread()\n    {\n        try\n        {\n            Thread.sleep(2000);\n        }\n        catch (InterruptedException e)\n        {\n            e.printStackTrace();\n        }\n    }\n\n    /**\n     * Verify each person object of result list.\n     * \n     * @param resultPersonList\n     *            the result person list\n     * @param persons\n     *            the persons\n     */\n    private void assertResultList(List<PersonES> resultPersonList, PersonES... persons)\n    {\n        boolean flag = false;\n\n        Assert.assertNotNull(resultPersonList);\n        Assert.assertEquals(persons.length, resultPersonList.size());\n\n        for (PersonES person : persons)\n        {\n            flag = false;\n            for (PersonES resultPerson : resultPersonList)\n            {\n                if (person.getPersonId().equals(resultPerson.getPersonId()))\n                {\n                    matchPerson(resultPerson, person);\n                    flag = true;\n                }\n            }\n            Assert.assertEquals(\"Person with id \" + person.getPersonId() + \" not found in Result list.\", true, flag);\n        }\n    }\n\n    /**\n     * Match person to verify each field of both PersonES objects are same.\n     * \n     * @param resultPerson\n     *            the result person\n     * @param person\n     *            the person\n     */\n    private void matchPerson(PersonES resultPerson, PersonES person)\n    {\n        Assert.assertNotNull(resultPerson);\n        Assert.assertEquals(person.getPersonId(), resultPerson.getPersonId());\n        Assert.assertEquals(person.getPersonName(), resultPerson.getPersonName());\n        Assert.assertEquals(person.getAge(), resultPerson.getAge());\n        Assert.assertEquals(person.getSalary(), resultPerson.getSalary());\n    }\n\n    /**\n     * Purge.\n     */\n    private void purge()\n    {\n        em.remove(em.find(PersonES.class, \"1\"));\n        em.remove(em.find(PersonES.class, \"2\"));\n        em.remove(em.find(PersonES.class, \"3\"));\n        em.remove(em.find(PersonES.class, \"4\"));\n        waitThread();\n    }\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/ESOrderByTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.es.PersonES.Day;\n\n/**\n * The Class ESGroupByTest.\n * \n * @author Amit Kumar\n */\npublic class ESOrderByTest\n{\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /** The node. */\n    private static Node node = null;\n\n    /** The person. */\n    private static PersonES persons[] = new PersonES[4];\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n\n        emf = Persistence.createEntityManagerFactory(\"es-pu\");\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Check if server running.\n     * \n     * @return true, if successful\n     */\n    private static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 9300);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n    }\n\n    /**\n     * Inits the.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    private static void init() throws InterruptedException\n    {\n        persons[0] = createPerson(\"1\", 50, \"karthik\", 500.0);\n        persons[1] = createPerson(\"2\", 20, \"pragalbh\", 700.0);\n        persons[2] = createPerson(\"3\", 60, \"amit\", 300.0);\n        persons[3] = createPerson(\"4\", 40, \"dev\", 400.0);\n\n        waitThread();\n    }\n\n    /**\n     * Creates the person.\n     * \n     * @param id\n     *            the id\n     * @param age\n     *            the age\n     * @param name\n     *            the name\n     * @param salary\n     *            the salary\n     * @return the person es\n     */\n    private static PersonES createPerson(String id, int age, String name, Double salary)\n    {\n        PersonES person = new PersonES();\n        person.setAge(age);\n        person.setDay(Day.FRIDAY);\n        person.setPersonId(id);\n        person.setPersonName(name);\n        person.setSalary(salary);\n\n        em.persist(person);\n\n        return person;\n    }\n\n    /**\n     * Test query.\n     */\n    @Test\n    public void testQuery()\n    {\n        testOrderBy();\n        testOrderByDescending();\n        testOrderByRowId();\n        testOrderByRowIdDescending();\n        testOrderByAscending();\n        testOrderByDescWithString();\n        testOrderByASCWhereClause();\n        testOrderByASCMultipleFields();\n        testOrderByWithGroupBy();\n        testOrderByWithGroupByDESC();\n        testOrderByWithGroupByString();\n        testOrderByWithGroupByStringDESC();\n    }\n\n    /**\n     * Test order by.\n     */\n    private void testOrderBy()\n    {\n        String queryString = \"Select p from PersonES p order by p.age\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        assertPerson((PersonES) resultList.get(0), persons[1]);\n        assertPerson((PersonES) resultList.get(1), persons[3]);\n        assertPerson((PersonES) resultList.get(2), persons[0]);\n        assertPerson((PersonES) resultList.get(3), persons[2]);\n    }\n\n    /**\n     * Test order by descending.\n     */\n    private void testOrderByDescending()\n    {\n        String queryString = \"Select p from PersonES p order by p.age DESC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        assertPerson((PersonES) resultList.get(0), persons[2]);\n        assertPerson((PersonES) resultList.get(1), persons[0]);\n        assertPerson((PersonES) resultList.get(2), persons[3]);\n        assertPerson((PersonES) resultList.get(3), persons[1]);\n    }\n\n    /**\n     * Test order by row id.\n     */\n    private void testOrderByRowId()\n    {\n        String queryString = \"Select p from PersonES p order by p.personId\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        assertPerson((PersonES) resultList.get(0), persons[0]);\n        assertPerson((PersonES) resultList.get(1), persons[1]);\n        assertPerson((PersonES) resultList.get(2), persons[2]);\n        assertPerson((PersonES) resultList.get(3), persons[3]);\n    }\n\n    /**\n     * Test order by row id descending.\n     */\n    private void testOrderByRowIdDescending()\n    {\n        String queryString = \"Select p from PersonES p order by p.personId DESC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        assertPerson((PersonES) resultList.get(0), persons[3]);\n        assertPerson((PersonES) resultList.get(1), persons[2]);\n        assertPerson((PersonES) resultList.get(2), persons[1]);\n        assertPerson((PersonES) resultList.get(3), persons[0]);\n    }\n\n    /**\n     * Test order by ascending.\n     */\n    private void testOrderByAscending()\n    {\n        String queryString = \"Select p.personName from PersonES p order by p.age ASC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        Assert.assertEquals(\"pragalbh\", resultList.get(0));\n        Assert.assertEquals(\"dev\", resultList.get(1));\n        Assert.assertEquals(\"karthik\", resultList.get(2));\n        Assert.assertEquals(\"amit\", resultList.get(3));\n    }\n\n    /**\n     * Test order by desc with string.\n     */\n    private void testOrderByDescWithString()\n    {\n        String queryString = \"Select p.personName from PersonES p order by p.personName DESC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        Assert.assertEquals(\"pragalbh\", resultList.get(0));\n        Assert.assertEquals(\"karthik\", resultList.get(1));\n        Assert.assertEquals(\"dev\", resultList.get(2));\n        Assert.assertEquals(\"amit\", resultList.get(3));\n    }\n\n    /**\n     * Test order by asc where clause.\n     */\n    private void testOrderByASCWhereClause()\n    {\n        String queryString = \"Select p.personName from PersonES p where p.salary > 350.0 order by p.age ASC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(3, resultList.size());\n\n        Assert.assertEquals(\"pragalbh\", resultList.get(0));\n        Assert.assertEquals(\"dev\", resultList.get(1));\n        Assert.assertEquals(\"karthik\", resultList.get(2));\n    }\n\n    /**\n     * Test order by asc multiple fields.\n     */\n    private void testOrderByASCMultipleFields()\n    {\n        String queryString = \"Select p.personName, p.age, p.salary from PersonES p where p.salary <> 300.0 order by p.age ASC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(3, resultList.size());\n\n        Assert.assertEquals(\"pragalbh\", ((List) resultList.get(0)).get(0));\n        Assert.assertEquals(20, ((List) resultList.get(0)).get(1));\n        Assert.assertEquals(700.0, ((List) resultList.get(0)).get(2));\n\n        Assert.assertEquals(\"dev\", ((List) resultList.get(1)).get(0));\n        Assert.assertEquals(40, ((List) resultList.get(1)).get(1));\n        Assert.assertEquals(400.0, ((List) resultList.get(1)).get(2));\n\n        Assert.assertEquals(\"karthik\", ((List) resultList.get(2)).get(0));\n        Assert.assertEquals(50, ((List) resultList.get(2)).get(1));\n        Assert.assertEquals(500.0, ((List) resultList.get(2)).get(2));\n    }\n\n    /**\n     * Test order by with group by.\n     */\n    private void testOrderByWithGroupBy()\n    {\n        String queryString = \"Select p from PersonES p where p.salary <> 300.0 group by p.age order by p.age ASC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(3, resultList.size());\n\n        assertPerson((PersonES) resultList.get(0), persons[1]);\n        assertPerson((PersonES) resultList.get(1), persons[3]);\n        assertPerson((PersonES) resultList.get(2), persons[0]);\n    }\n\n    /**\n     * Test order by with group by desc.\n     */\n    private void testOrderByWithGroupByDESC()\n    {\n        String queryString = \"Select p from PersonES p group by p.age order by p.age DESC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n\n        assertPerson((PersonES) resultList.get(0), persons[2]);\n        assertPerson((PersonES) resultList.get(1), persons[0]);\n        assertPerson((PersonES) resultList.get(2), persons[3]);\n        assertPerson((PersonES) resultList.get(3), persons[1]);\n    }\n\n    /**\n     * Test order by with group by string.\n     */\n    private void testOrderByWithGroupByString()\n    {\n        String queryString = \"Select p.personName, p.age, p.salary from PersonES p where p.salary <> 300.0 group by p.personName order by p.personName ASC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(3, resultList.size());\n\n        Assert.assertEquals(\"dev\", ((List) resultList.get(0)).get(0));\n        Assert.assertEquals(40, ((List) resultList.get(0)).get(1));\n        Assert.assertEquals(400.0, ((List) resultList.get(0)).get(2));\n\n        Assert.assertEquals(\"karthik\", ((List) resultList.get(1)).get(0));\n        Assert.assertEquals(50, ((List) resultList.get(1)).get(1));\n        Assert.assertEquals(500.0, ((List) resultList.get(1)).get(2));\n\n        Assert.assertEquals(\"pragalbh\", ((List) resultList.get(2)).get(0));\n        Assert.assertEquals(20, ((List) resultList.get(2)).get(1));\n        Assert.assertEquals(700.0, ((List) resultList.get(2)).get(2));\n    }\n\n    /**\n     * Test order by with group by string desc.\n     */\n    private void testOrderByWithGroupByStringDESC()\n    {\n        String queryString = \"Select p.personName, p.age, p.salary from PersonES p where p.salary <> 300.0 group by p.personName order by p.personName DESC\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(3, resultList.size());\n\n        Assert.assertEquals(\"pragalbh\", ((List) resultList.get(0)).get(0));\n        Assert.assertEquals(20, ((List) resultList.get(0)).get(1));\n        Assert.assertEquals(700.0, ((List) resultList.get(0)).get(2));\n\n        Assert.assertEquals(\"karthik\", ((List) resultList.get(1)).get(0));\n        Assert.assertEquals(50, ((List) resultList.get(1)).get(1));\n        Assert.assertEquals(500.0, ((List) resultList.get(1)).get(2));\n\n        Assert.assertEquals(\"dev\", ((List) resultList.get(2)).get(0));\n        Assert.assertEquals(40, ((List) resultList.get(2)).get(1));\n        Assert.assertEquals(400.0, ((List) resultList.get(2)).get(2));\n    }\n\n    /**\n     * Assert person.\n     * \n     * @param actual\n     *            the actual\n     * @param person\n     *            the person\n     */\n    private void assertPerson(Object actual, PersonES person)\n    {\n        PersonES actualPerson = (PersonES) actual;\n\n        Assert.assertEquals(actualPerson.getPersonId(), person.getPersonId());\n        Assert.assertEquals(actualPerson.getPersonName(), person.getPersonName());\n        Assert.assertEquals(actualPerson.getAge().intValue(), person.getAge().intValue());\n        Assert.assertEquals(actualPerson.getSalary(), person.getSalary());\n        Assert.assertEquals(actualPerson.getDay(), person.getDay());\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        em.createQuery(\"delete from PersonES p\").executeUpdate();\n        waitThread();\n\n        em.close();\n        emf.close();\n\n        if (node != null)\n            node.close();\n    }\n\n    /**\n     * Wait thread.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    private static void waitThread() throws InterruptedException\n    {\n        Thread.sleep(2000);\n    }\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/ESQueryWithPaginationTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.es.PersonES.Day;\n\nimport junit.framework.Assert;\n\n/**\n * The Class ESQueryTest.\n * \n * @author devender.yadav\n * \n */\npublic class ESQueryWithPaginationTest {\n\n\t/** The emf. */\n\tprivate static EntityManagerFactory emf;\n\n\t/** The em. */\n\tprivate static EntityManager em;\n\n\t/** The node. */\n\tprivate static Node node = null;\n\n\t/**\n\t * Sets the up before class.\n\t * \n\t * @throws Exception\n\t *             the exception\n\t */\n\t@BeforeClass\n\tpublic static void setUpBeforeClass() throws Exception {\n\t\tif (!checkIfServerRunning()) {\n\t\t\tBuilder builder = Settings.settingsBuilder();\n\t\t\tbuilder.put(\"path.home\", \"target/data\");\n\t\t\tnode = new NodeBuilder().settings(builder).node();\n\t\t}\n\t}\n\n\t/**\n\t * Check if server running.\n\t * \n\t * @return true, if successful\n\t */\n\tprivate static boolean checkIfServerRunning() {\n\t\ttry {\n\t\t\tSocket socket = new Socket(\"127.0.0.1\", 9300);\n\t\t\treturn socket.getInetAddress() != null;\n\t\t} catch (UnknownHostException e) {\n\t\t\treturn false;\n\t\t} catch (IOException e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Setup.\n\t */\n\t@Before\n\tpublic void setup() {\n\n\t\temf = Persistence.createEntityManagerFactory(\"es-pu\");\n\t\tem = emf.createEntityManager();\n\t\tinit();\n\t}\n\n\t/**\n\t * Test query.\n\t *\n\t * @throws NoSuchFieldException\n\t *             the no such field exception\n\t * @throws SecurityException\n\t *             the security exception\n\t * @throws IllegalArgumentException\n\t *             the illegal argument exception\n\t * @throws IllegalAccessException\n\t *             the illegal access exception\n\t * @throws InterruptedException\n\t *             the interrupted exception\n\t */\n\t@Test\n\tpublic void testQuery() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n\t\t\tIllegalAccessException, InterruptedException {\n\n\t\tQuery qry = em.createQuery(\"select p from PersonES p where p.age > 10 order by p.age\", PersonES.class);\n\n\t\tqry.setFirstResult(5);\n\t\tqry.setMaxResults(3);\n\n\t\tList<PersonES> persons = qry.getResultList();\n\t\tassertResultList(persons);\n\n\t}\n\n\t/**\n\t * Tear down.\n\t */\n\t@After\n\tpublic void tearDown() {\n\t\tpurge();\n\t\tem.close();\n\t\temf.close();\n\t}\n\n\t/**\n\t * Tear down after class.\n\t * \n\t * @throws Exception\n\t *             the exception\n\t */\n\t@AfterClass\n\tpublic static void tearDownAfterClass() throws Exception {\n\t\tif (node != null)\n\t\t\tnode.close();\n\t}\n\n\t/**\n\t * Wait thread.\n\t */\n\tprivate void waitThread() {\n\t\ttry {\n\t\t\tThread.sleep(2000);\n\t\t} catch (InterruptedException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * Inits all the records.\n\t */\n\tprivate void init() {\n\t\tPersonES person = new PersonES();\n\n\t\tfor (int i = 1; i <= 30; i++) {\n\t\t\tperson.setAge(i);\n\t\t\tperson.setDay(Day.FRIDAY);\n\t\t\tperson.setPersonId(i + \"\");\n\t\t\tperson.setPersonName(\"dev_\" + i);\n\t\t\tperson.setSalary(1000.0 * i);\n\t\t\tem.persist(person);\n\n\t\t}\n\t\twaitThread();\n\t}\n\n\t/**\n\t * Delete all the records.\n\t */\n\tprivate void purge() {\n\t\tString deleteQuery = \"delete from PersonES p\";\n\t\tQuery query = em.createQuery(deleteQuery);\n\t\tquery.executeUpdate();\n\t\twaitThread();\n\t}\n\n\t/**\n\t * Verify each person object of result list.\n\t * \n\t * @param resultPersonList\n\t *            the result person list\n\t * @param persons\n\t *            the persons\n\t */\n\tprivate void assertResultList(List<PersonES> persons) {\n\n\t\tAssert.assertNotNull(persons);\n\t\tAssert.assertEquals(3, persons.size());\n\n\t\tfor (PersonES person : persons) {\n\n\t\t\tif (person.getAge().equals(16)) {\n\t\t\t\tAssert.assertEquals(\"dev_16\", person.getPersonName());\n\t\t\t\tAssert.assertEquals(16000.0, person.getSalary());\n\t\t\t} else if (person.getAge().equals(17)) {\n\t\t\t\tAssert.assertEquals(\"dev_17\", person.getPersonName());\n\t\t\t\tAssert.assertEquals(17000.0, person.getSalary());\n\t\t\t}\n\n\t\t\telse if (person.getAge().equals(18)) {\n\t\t\t\tAssert.assertEquals(\"dev_18\", person.getPersonName());\n\t\t\t\tAssert.assertEquals(18000.0, person.getSalary());\n\t\t\t} else {\n\n\t\t\t\tAssert.fail();\n\t\t\t}\n\t\t}\n\t}\n\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/PersonES.java",
    "content": "package com.impetus.client.es;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name=\"ES\", schema=\"esSchema@es-pu\")\npublic class PersonES\n{\n\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n    \n    @Column(name = \"SALARY\")\n    private Double salary;   \n\n\t/**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the day\n     */\n    public Day getDay()\n    {\n        return day;\n    }\n\n    /**\n     * @param day\n     *            the day to set\n     */\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n    \n    public Double getSalary() {\n\t\treturn salary;\n\t}\n\n\tpublic void setSalary(Double salary) {\n\t\tthis.salary = salary;\n\t}\n\n\n    enum Day\n    {\n        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n    }\n\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/PersonESTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.es.PersonES.Day;\nimport com.impetus.kundera.PersistenceProperties;\n\n/**\n * The Class PersonESTest.\n * \n * @author vivek.mishra junit to demonstrate ESQuery implementation.\n */\npublic class PersonESTest\n{\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The node. */\n    private static Node node = null;\n\n    /** The person1. */\n    private PersonES person1, person2, person3, person4;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n    }\n\n    /**\n     * Check if server running.\n     * \n     * @return true, if successful\n     */\n    private static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 9300);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n    }\n\n    /**\n     * Setup.\n     */\n    @Before\n    public void setup()\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"es-pu\");\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Test with batch.\n     * \n     * @throws NoSuchFieldException\n     *             the no such field exception\n     * @throws SecurityException\n     *             the security exception\n     * @throws IllegalArgumentException\n     *             the illegal argument exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    @Test\n    public void testWithBatch() throws NoSuchFieldException, SecurityException, IllegalArgumentException,\n            IllegalAccessException, InterruptedException\n    {\n        Map<String, Object> props = new HashMap<String, Object>();\n        props.put(PersistenceProperties.KUNDERA_NODES, \"localhost\");\n        props.put(PersistenceProperties.KUNDERA_PORT, \"9300\");\n        props.put(PersistenceProperties.KUNDERA_BATCH_SIZE, 10);\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"es-pu\", props);\n        EntityManager em = emf.createEntityManager();\n        // purge();\n\n        PersonES person = new PersonES();\n\n        for (int i = 1; i <= 25; i++)\n        {\n            person.setAge(i);\n            person.setDay(Day.FRIDAY);\n            person.setPersonId(i + \"\");\n            person.setPersonName(\"vivek\" + i);\n            em.persist(person);\n\n            if (i % 10 == 0)\n            {\n                em.clear();\n                for (int i1 = 1; i1 <= 10; i1++)\n                {\n                    PersonES p = em.find(PersonES.class, i1 + \"\");\n                    Assert.assertNotNull(p);\n                    Assert.assertEquals(\"vivek\" + i1, p.getPersonName());\n                }\n            }\n\n        }\n\n        em.flush();\n        em.clear();\n        em.close();\n        emf.close();\n\n        // A scenario to mix and match with\n\n        // 5 inserts, 5 updates and 5 deletes\n\n        props.put(PersistenceProperties.KUNDERA_BATCH_SIZE, 50);\n        emf = Persistence.createEntityManagerFactory(\"es-pu\", props);\n        em = emf.createEntityManager();\n\n        for (int i = 21; i <= 25; i++)\n        {\n            person.setAge(i);\n            person.setDay(Day.FRIDAY);\n            person.setPersonId(i + \"\");\n            person.setPersonName(\"vivek\" + i);\n            em.persist(person);\n        }\n\n        for (int i = 10; i <= 20; i++)\n        {\n            PersonES p = em.find(PersonES.class, i + \"\");\n\n            if (i > 15)\n            {\n                em.remove(p);\n            }\n            else\n            {\n                p.setPersonName(\"updatedName\" + i);\n                em.merge(p);\n            }\n\n        }\n\n        em.flush(); // explicit flush\n        em.clear();\n\n        // Assert after explicit flush\n\n        for (int i = 10; i <= 15; i++)\n        {\n            if (i > 15)\n            {\n                Assert.assertNull(em.find(PersonES.class, i + \"\")); // assert on\n                                                                    // removed\n            }\n            else\n            {\n                PersonES found = em.find(PersonES.class, i + \"\");\n                Assert.assertNotNull(found);\n                Assert.assertEquals(\"updatedName\" + i, found.getPersonName());\n            }\n        }\n\n        for (int i = 1; i <= 25; i++)\n        {\n            PersonES found = em.find(PersonES.class, i + \"\");\n            if (found != null) // as some of record are already removed.\n                em.remove(found);\n        }\n\n        // TODO: Update/delete by JPA query.\n        // String deleteQuery = \"Delete p from PersonES p\";\n\n        em.close();\n        emf.close();\n    }\n\n    /**\n     * Test specific field retrieval.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    @Test\n    public void testSpecificFieldRetrieval() throws InterruptedException\n    {\n        waitThread();\n        String queryWithOutAndClause = \"Select p.personName,p.age from PersonES p where p.personName = 'karthik' OR p.personName = 'pragalbh' ORDER BY p.personName\";\n        Query nameQuery = em.createNamedQuery(queryWithOutAndClause);\n\n        List persons = nameQuery.getResultList();\n\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(2, persons.size());\n        Assert.assertEquals(\"karthik\", ((ArrayList) persons.get(0)).get(0));\n        Assert.assertEquals(10, ((ArrayList) persons.get(0)).get(1));\n        Assert.assertEquals(\"pragalbh\", ((ArrayList) persons.get(1)).get(0));\n        Assert.assertEquals(20, ((ArrayList) persons.get(1)).get(1));\n\n    }\n\n    /**\n     * Test find jpql.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    @Test\n    public void testFindJPQL() throws InterruptedException\n    {\n        String queryWithId = \"Select p from PersonES p where p.personId = 3\";\n        Query nameQuery = em.createNamedQuery(queryWithId);\n\n        List<PersonES> persons = nameQuery.getResultList();\n\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n        Assert.assertEquals(\"amit\", persons.get(0).getPersonName());\n        Assert.assertEquals(30, persons.get(0).getAge().intValue());\n\n        String queryWithOutAndClause = \"Select p from PersonES p where p.personName = 'karthik'\";\n        nameQuery = em.createNamedQuery(queryWithOutAndClause);\n\n        persons = nameQuery.getResultList();\n\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n        Assert.assertEquals(\"karthik\", persons.get(0).getPersonName());\n\n        String queryWithOutClause = \"Select p.personName, p.personId from PersonES p\";\n        nameQuery = em.createNamedQuery(queryWithOutClause);\n\n        List personsNames = nameQuery.getResultList();\n\n        Assert.assertFalse(personsNames.isEmpty());\n        Assert.assertEquals(4, personsNames.size());\n\n        String invalidQueryWithAndClause = \"Select p from PersonES p where p.personName = 'karthik' AND p.age = 34\";\n        nameQuery = em.createNamedQuery(invalidQueryWithAndClause);\n        persons = nameQuery.getResultList();\n\n        Assert.assertTrue(persons.isEmpty());\n\n        String queryWithAndClause = \"Select p from PersonES p where p.personName = 'karthik' AND p.age = 10\";\n        nameQuery = em.createNamedQuery(queryWithAndClause);\n        persons = nameQuery.getResultList();\n\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n        Assert.assertEquals(\"karthik\", persons.get(0).getPersonName());\n\n        String queryWithORClause = \"Select p from PersonES p where p.personName = 'karthik' OR p.personName = 'amit'\";\n        nameQuery = em.createNamedQuery(queryWithORClause);\n        persons = nameQuery.getResultList();\n\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(2, persons.size());\n\n        String invalidQueryWithORClause = \"Select p from PersonES p where p.personName = 'amit' OR p.personName = 'lkl'\";\n        nameQuery = em.createNamedQuery(invalidQueryWithORClause);\n        persons = nameQuery.getResultList();\n\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertEquals(1, persons.size());\n        // TODO: >,<,>=,<=\n\n        String notConditionOnRowKey = \"Select p from PersonES p where p.personId <> '1'\";\n        nameQuery = em.createNamedQuery(notConditionOnRowKey);\n        persons = nameQuery.getResultList();\n\n        assertResultList(persons, person2, person3, person4);\n\n        String notConditionOnNonRowKey = \"Select p from PersonES p where p.personName <> 'amit'\";\n        nameQuery = em.createNamedQuery(notConditionOnNonRowKey);\n        persons = nameQuery.getResultList();\n\n        assertResultList(persons, person1, person2, person4);\n\n        String notConditionOnNonRowKeyWithAnd = \"Select p from PersonES p where p.personName <> 'amit' and p.personId > 2\";\n        nameQuery = em.createNamedQuery(notConditionOnNonRowKeyWithAnd);\n        persons = nameQuery.getResultList();\n\n        assertResultList(persons, person4);\n\n        String notConditionOnNonRowKeyWithOr = \"Select p from PersonES p where p.personName <> 'amit' or p.personId <> 3\";\n        nameQuery = em.createNamedQuery(notConditionOnNonRowKeyWithOr);\n        persons = nameQuery.getResultList();\n\n        assertResultList(persons, person1, person2, person4);\n\n        testCount();\n        testCountWithField();\n        testCountWithWhere();\n        testCountWithWhereAnd();\n        testCountWithWhereNullAnd();\n        testCountWithWhereOr();\n        testCountWithNot();\n        testCountWithIn();\n        testCountWithInString();\n        testInWithStringArray();\n        testInWithIntegerArray();\n        testInWithListPositionalParameter();\n        testInWithStringList();\n        testInWithIntegerList();\n        testInWithObjectList();\n        testInWithBlankList();\n        testInWithIntegerSet();\n        testInWithStringSet();\n        testInWithIntegerValues();\n        testInWithStringValues();\n        testInWithOrClause();\n        testInWithAndClause();\n        testFieldWithInClause();\n        testMinWithIn();\n        testInWithBlankValues();\n    }\n\n    /**\n     * Test not with delete.\n     */\n    @Test\n    public void testNotWithDelete()\n    {\n        String queryString = \"delete from PersonES p where p.personId <> 2\";\n        Query query = em.createQuery(queryString);\n        int rowUpdataCount = query.executeUpdate();\n        waitThread();\n        Assert.assertEquals(3, rowUpdataCount);\n\n        List<PersonES> resultList = em.createQuery(\"Select p from PersonES p\").getResultList();\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(\"2\", resultList.get(0).getPersonId());\n    }\n\n    /**\n     * Test not with update.\n     */\n    @Test\n    public void testNotWithUpdate()\n    {\n        String notConditionUpdateQuery = \"update PersonES p set p.age = 50 where p.personName <> 'amit'\";\n        Query updateQuery = em.createQuery(notConditionUpdateQuery);\n        int updateCount = updateQuery.executeUpdate();\n\n        Assert.assertEquals(3, updateCount);\n        PersonES person = em.find(PersonES.class, \"1\");\n        Assert.assertEquals(50, person.getAge().intValue());\n\n        person = em.find(PersonES.class, \"2\");\n        Assert.assertEquals(50, person.getAge().intValue());\n\n        person = em.find(PersonES.class, \"4\");\n        Assert.assertEquals(50, person.getAge().intValue());\n    }\n\n    /**\n     * Test count.\n     */\n    public void testCount()\n    {\n        String queryString = \"Select count(p) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(4, ((Long) resultList.get(0)).intValue());\n    }\n\n    /**\n     * Test count with field.\n     */\n    public void testCountWithField()\n    {\n        String queryString = \"Select count(p.age) from PersonES p\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(4, ((Long) resultList.get(0)).intValue());\n    }\n\n    /**\n     * Test count with where.\n     */\n    public void testCountWithWhere()\n    {\n        String queryString = \"Select count(p.age) from PersonES p where p.age > 25\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(2, ((Long) resultList.get(0)).intValue());\n    }\n\n    /**\n     * Test count with where and.\n     */\n    public void testCountWithWhereAnd()\n    {\n        String queryString = \"Select count(p.age) from PersonES p where p.age > 25 and p.personName = 'amit'\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(1, ((Long) resultList.get(0)).intValue());\n    }\n\n    /**\n     * Test count with where null and.\n     */\n    public void testCountWithWhereNullAnd()\n    {\n        String queryString = \"Select count(p.age) from PersonES p where p.age < 25 and p.personName = 'amit'\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(0, ((Long) resultList.get(0)).intValue());\n    }\n\n    /**\n     * Test count with where or.\n     */\n    public void testCountWithWhereOr()\n    {\n        String queryString = \"Select count(p) from PersonES p where p.age < 25 or p.personName = 'amit'\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(3, ((Long) resultList.get(0)).intValue());\n    }\n\n    /**\n     * Test count with not.\n     */\n    public void testCountWithNot()\n    {\n        String queryString = \"Select count(p.age) from PersonES p where p.personName <> 'amit'\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(3, ((Long) resultList.get(0)).intValue());\n    }\n\n    /**\n     * Test count with in.\n     */\n    public void testCountWithIn()\n    {\n        String queryString = \"Select count(p.age) from PersonES p where p.age In (20, 30)\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(2, ((Long) resultList.get(0)).intValue());\n    }\n\n    /**\n     * Test count with in string.\n     */\n    public void testCountWithInString()\n    {\n        String queryString = \"Select count(p.age) from PersonES p where p.personName IN ('amit', 'dev', 'lilkl')\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(2, ((Long) resultList.get(0)).intValue());\n    }\n\n    /**\n     * Test in with string array.\n     */\n    public void testInWithStringArray()\n    {\n        String queryString = \"Select p from PersonES p where p.personId IN :values\";\n        Query query = em.createQuery(queryString);\n        String values[] = { \"3\", \"4\", \"1\" };\n        query.setParameter(\"values\", values);\n        List resultList = query.getResultList();\n\n        assertResultList(resultList, person1, person3, person4);\n    }\n\n    /**\n     * Test in with integer array.\n     */\n    public void testInWithIntegerArray()\n    {\n        String queryString = \"Select p from PersonES p where p.age IN :values\";\n        Query query = em.createQuery(queryString);\n        Integer values[] = { 10, 20, 50 };\n        query.setParameter(\"values\", values);\n        List resultList = query.getResultList();\n\n        assertResultList(resultList, person1, person2);\n    }\n\n    /**\n     * Test in with list positional parameter.\n     */\n    public void testInWithListPositionalParameter()\n    {\n        String queryString = \"Select p from PersonES p where p.age IN ?1\";\n        Query query = em.createQuery(queryString);\n        List<Integer> inputList = new ArrayList();\n        inputList.add(20);\n        inputList.add(30);\n        query.setParameter(1, inputList);\n        List<PersonES> resultList = query.getResultList();\n\n        assertResultList(resultList, person2, person3);\n    }\n\n    /**\n     * Test in with string list.\n     */\n    public void testInWithStringList()\n    {\n        String queryString = \"Select p from PersonES p where p.personId IN :list\";\n        Query query = em.createQuery(queryString);\n        ArrayList<String> input = new ArrayList<String>();\n        input.add(\"2\");\n        input.add(\"3\");\n        query.setParameter(\"list\", input);\n        List<PersonES> resultList = query.getResultList();\n\n        assertResultList(resultList, person2, person3);\n    }\n\n    /**\n     * Test in with integer list.\n     */\n    public void testInWithIntegerList()\n    {\n        String queryString = \"Select p from PersonES p where p.age IN :list\";\n        Query query = em.createQuery(queryString);\n        ArrayList<Integer> input = new ArrayList<Integer>();\n        input.add(20);\n        input.add(40);\n        query.setParameter(\"list\", input);\n        List<PersonES> resultList = query.getResultList();\n\n        assertResultList(resultList, person2, person4);\n    }\n\n    /**\n     * Test in with object list.\n     */\n    public void testInWithObjectList()\n    {\n        String queryString = \"Select p from PersonES p where p.personId IN :list\";\n        Query query = em.createQuery(queryString);\n        List inputList = new ArrayList();\n        inputList.add(\"2\");\n        inputList.add(\"3\");\n        query.setParameter(\"list\", inputList);\n        List<PersonES> resultList = query.getResultList();\n\n        assertResultList(resultList, person2, person3);\n    }\n\n    /**\n     * Test in with blank list.\n     */\n    public void testInWithBlankList()\n    {\n        String queryString = \"Select p from PersonES p where p.age IN :list\";\n        Query query = em.createQuery(queryString);\n        ArrayList input = new ArrayList();\n        query.setParameter(\"list\", input);\n        List<PersonES> resultList = query.getResultList();\n\n        assertResultList(resultList);\n    }\n\n    /**\n     * Test in with integer set.\n     */\n    public void testInWithIntegerSet()\n    {\n        String queryString = \"Select p from PersonES p where p.age IN :set\";\n        Query query = em.createQuery(queryString);\n        Set<Integer> inputSet = new HashSet<Integer>();\n        inputSet.add(10);\n        inputSet.add(30);\n        query.setParameter(\"set\", inputSet);\n        List<PersonES> resultList = query.getResultList();\n\n        assertResultList(resultList, person1, person3);\n    }\n\n    /**\n     * Test in with string set.\n     */\n    public void testInWithStringSet()\n    {\n        String queryString = \"Select p from PersonES p where p.personId IN :set\";\n        Query query = em.createQuery(queryString);\n        Set<String> input = new HashSet<String>();\n        input.add(\"2\");\n        input.add(\"3\");\n        query.setParameter(\"set\", input);\n        List<PersonES> resultList = query.getResultList();\n\n        assertResultList(resultList, person2, person3);\n    }\n\n    /**\n     * Test in with integer values.\n     */\n    public void testInWithIntegerValues()\n    {\n        String queryString = \"Select p from PersonES p where p.age IN ( 10, 20)\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        assertResultList(resultList, person1, person2);\n    }\n\n    /**\n     * Test in with string values.\n     */\n    public void testInWithStringValues()\n    {\n        String queryString = \"Select p from PersonES p where p.personId IN ( '2', '3','10')\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        assertResultList(resultList, person2, person3);\n    }\n\n    /**\n     * Test in with or clause.\n     */\n    public void testInWithOrClause()\n    {\n        String queryString = \"Select p from PersonES p where p.age IN ( 10, 20) or p.age = 40\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        assertResultList(resultList, person1, person2, person4);\n    }\n\n    /**\n     * Test in with and clause.\n     */\n    public void testInWithAndClause()\n    {\n        String queryString = \"Select p from PersonES p where p.age IN ( 10, 20) and p.personId = '2'\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        assertResultList(resultList, person2);\n    }\n\n    /**\n     * Test field with in clause.\n     */\n    public void testFieldWithInClause()\n    {\n        String queryString = \"Select p.personName from PersonES p where p.personId IN ( '1', '2') and p.age = 10\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(\"karthik\", resultList.get(0));\n    }\n\n    /**\n     * Test min with in.\n     */\n    public void testMinWithIn()\n    {\n        String queryString = \"Select sum(p.age) from PersonES p where p.personId IN ( '1', '2') or p.age = 40\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertNotNull(resultList);\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(70.0, resultList.get(0));\n    }\n\n    /**\n     * Test in with blank values.\n     */\n    public void testInWithBlankValues()\n    {\n        String queryString = \"Select p from PersonES p where p.personId IN ( )\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        assertResultList(resultList);\n    }\n\n    /**\n     * Test in with delete.\n     */\n    @Test\n    public void testInWithDelete()\n    {\n        String queryString = \"delete from PersonES p where p.personId IN ( '2', '4' )\";\n        Query query = em.createQuery(queryString);\n        int deleteCount = query.executeUpdate();\n\n        Assert.assertEquals(2, deleteCount);\n\n        waitThread();\n        queryString = \"Select p from PersonES p\";\n        query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        assertResultList(resultList, person1, person3);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (node != null)\n            node.close();\n    }\n\n    /**\n     * Tear down.\n     */\n    @After\n    public void tearDown()\n    {\n        purge();\n        em.close();\n        emf.close();\n\n    }\n\n    /**\n     * Wait thread.\n     */\n    private void waitThread()\n    {\n        try\n        {\n            Thread.sleep(2000);\n        }\n        catch (InterruptedException e)\n        {\n            e.printStackTrace();\n        }\n    }\n\n    /**\n     * Inits all the records.\n     */\n    private void init()\n    {\n        person1 = createPerson(\"1\", 10, \"karthik\");\n        person2 = createPerson(\"2\", 20, \"pragalbh\");\n        person3 = createPerson(\"3\", 30, \"amit\");\n        person4 = createPerson(\"4\", 40, \"dev\");\n        waitThread();\n    }\n\n    /**\n     * Creates the person and persist them.\n     * \n     * @param id\n     *            the id\n     * @param age\n     *            the age\n     * @param name\n     *            the name\n     * @return the person es\n     */\n    private PersonES createPerson(String id, int age, String name)\n    {\n        PersonES person = new PersonES();\n        person.setAge(age);\n        person.setDay(Day.FRIDAY);\n        person.setPersonId(id);\n        person.setPersonName(name);\n        em.persist(person);\n\n        return person;\n    }\n\n    /**\n     * Delete all the records.\n     */\n    private void purge()\n    {\n        String deleteQuery = \"delete from PersonES p\";\n        Query query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n        waitThread();\n    }\n\n    /**\n     * Verify each person object of result list.\n     * \n     * @param resultPersonList\n     *            the result person list\n     * @param persons\n     *            the persons\n     */\n    private void assertResultList(List<PersonES> resultPersonList, PersonES... persons)\n    {\n        boolean flag = false;\n\n        Assert.assertNotNull(resultPersonList);\n        Assert.assertEquals(persons.length, resultPersonList.size());\n\n        for (PersonES person : persons)\n        {\n            flag = false;\n            for (PersonES resultPerson : resultPersonList)\n            {\n                if (person.getPersonId().equals(resultPerson.getPersonId()))\n                {\n                    matchPerson(resultPerson, person);\n                    flag = true;\n                }\n            }\n            Assert.assertEquals(\"Person with id \" + person.getPersonId() + \" not found in Result list.\", true, flag);\n        }\n    }\n\n    /**\n     * Match person to verify each field of both PersonES objects are same.\n     * \n     * @param resultPerson\n     *            the result person\n     * @param person\n     *            the person\n     */\n    private void matchPerson(PersonES resultPerson, PersonES person)\n    {\n        Assert.assertNotNull(resultPerson);\n        Assert.assertEquals(person.getPersonId(), resultPerson.getPersonId());\n        Assert.assertEquals(person.getPersonName(), resultPerson.getPersonName());\n        Assert.assertEquals(person.getAge(), resultPerson.getAge());\n        Assert.assertEquals(person.getSalary(), resultPerson.getSalary());\n    }\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/WebTraffic.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n\n/**\n * @author vivek.mishra\n * \n * WebTraffic entity class.\n *\n */\n@Entity\n@Table(name=\"web_traffic\",schema=\"esSchema@es-pu\")\npublic class WebTraffic\n{\n\n    @EmbeddedId\n    private WebTrafficCompositeKey key;\n    \n    private String country;\n\n    public WebTrafficCompositeKey getKey()\n    {\n        return key;\n    }\n\n    public void setKey(WebTrafficCompositeKey key)\n    {\n        this.key = key;\n    }\n\n    public String getCountry()\n    {\n        return country;\n    }\n\n    public void setCountry(String country)\n    {\n        this.country = country;\n    }\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/WebTrafficCompositeKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * @author vivek.mishra\n * WebTraffic embeddable entity.\n *\n */\n@Embeddable\npublic class WebTrafficCompositeKey\n{\n\n    @Column\n    private String url;\n    \n    @Column\n    private String logtime;\n    \n    @Column(name=\"ip_address\")\n    private String ipAddress;\n\n    public String getUrl()\n    {\n        return url;\n    }\n\n    public void setUrl(String url)\n    {\n        this.url = url;\n    }\n\n    public String getLogtime()\n    {\n        return logtime;\n    }\n\n    public void setLogtime(String logtime)\n    {\n        this.logtime = logtime;\n    }\n\n    public String getIpAddress()\n    {\n        return ipAddress;\n    }\n\n    public void setIpAddress(String ipAddress)\n    {\n        this.ipAddress = ipAddress;\n    }\n    \n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/WebTrafficTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\n/**\n * @author vivek.mishra\n * \n *         junit to demonstrate composite key implementation.\n * \n */\npublic class WebTrafficTest\n{\n    private static Node node = null;\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        Builder builder = Settings.settingsBuilder();\n        builder.put(\"path.home\", \"target/data\");\n        node = new NodeBuilder().settings(builder).node();\n    }\n\n    @Before\n    public void setup()\n    {\n        emf = Persistence.createEntityManagerFactory(\"es-pu\");\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void test() throws InterruptedException\n    {\n        WebTrafficCompositeKey compositeKey = new WebTrafficCompositeKey();\n        compositeKey.setIpAddress(\"192.168.112.176\");\n        compositeKey.setLogtime(\"2013-01-23\");\n        compositeKey.setUrl(\"www.google.com\");\n\n        WebTraffic traffic = new WebTraffic();\n        traffic.setKey(compositeKey);\n        traffic.setCountry(\"India\");\n        em.persist(traffic);\n\n        waitThread();\n        \n        em.clear();\n        \n        WebTraffic result = em.find(WebTraffic.class, compositeKey);\n\n        Assert.assertNotNull(result);\n\n        Assert.assertNotNull(result.getKey());\n\n        em.remove(result);\n\n        em.clear();\n        result = em.find(WebTraffic.class, compositeKey);\n        Assert.assertNull(result);\n    }\n\n    private void waitThread() throws InterruptedException\n    {\n        Thread.sleep(2000);\n    }\n\n    @After\n    public void tearDown()\n    {\n        if (em != null)\n        {\n            em.close();\n        }\n\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        node.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/association/Address1M.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es.association;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *  1-M address entity.\n */\n@Entity\n@Table(name = \"ADDRESS\", schema=\"esSchema@es-pu\")\npublic class Address1M\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Person1M person;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public Person1M getPerson()\n    {\n        return person;\n    }\n\n    public void setPerson(Person1M person)\n    {\n        this.person = person;\n    }\n\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/association/AddressBiMM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es.association;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\n\n/**\n * @author vivek.mishra\n *  Bi M-M address entity.\n */\n@Entity\n//@Table(name = \"ADDRESSBIMM\", schema=\"esSchema@es-pu\")\npublic class AddressBiMM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @ManyToMany(mappedBy = \"addresses\", fetch = FetchType.EAGER)\n    private Set<PersonBiMM> people;\n\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public Set<PersonBiMM> getPeople()\n    {\n        return people;\n    }\n\n    public void setPeople(Set<PersonBiMM> people)\n    {\n        this.people = people;\n    }\n\n    \n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/association/AddressM1.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es.association;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n/**\n * @author vivek.mishra\n *  M-1 address entity.\n */\n@Entity\n@Table(name = \"ADDRESSM1\", schema=\"esSchema@es-pu\")\npublic class AddressM1\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @OneToMany(fetch = FetchType.LAZY)\n//    @JoinColumn(name = \"PERSON_ID\")\n    private Set<PersonM1> persons;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public Set<PersonM1> getPersons()\n    {\n        return persons;\n    }\n\n    public void setPersons(Set<PersonM1> persons)\n    {\n        this.persons = persons;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/association/AddressMM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es.association;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *  M-M address entity.\n */\n@Entity\n@Table(name = \"ADDRESSMM\", schema=\"esSchema@es-pu\")\npublic class AddressMM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/association/ESAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es.association;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\n/**\n * @author vivek.mishra junit for Elastic search association.\n */\npublic class ESAssociationTest\n{\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n\n    private static Node node = null;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        Builder builder = Settings.settingsBuilder();\n        builder.put(\"path.home\", \"target/data\");\n        node = new NodeBuilder().settings(builder).node();\n    }\n\n    @Before\n    public void setup()\n    {\n        emf = Persistence.createEntityManagerFactory(\"es-pu\");\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testCRUD1M() throws InterruptedException\n    {\n        Person1M person = new Person1M();\n        person.setPersonId(\"person_1\");\n        person.setPersonName(\"vivek\");\n\n        Address1M address1 = new Address1M();\n        address1.setAddressId(\"noida street\");\n        address1.setPerson(person);\n        address1.setStreet(\"Sector 50\");\n\n        Address1M address2 = new Address1M();\n        address2.setAddressId(\"expressway\");\n        address2.setPerson(person);\n        address2.setStreet(\"Sector 137\");\n\n        Set<Address1M> addresses = new HashSet<Address1M>();\n        addresses.add(address1);\n        addresses.add(address2);\n        person.setAddresses(addresses);\n\n        em.persist(person);\n        waitThread();\n\n        em.clear();\n\n        person = em.find(Person1M.class, \"person_1\");\n        Assert.assertNotNull(person);\n        Assert.assertNotNull(person.getAddresses());\n        Assert.assertEquals(2, person.getAddresses().size());\n\n        Assert.assertEquals(person.getPersonId(), person.getAddresses().iterator().next().getPerson().getPersonId());\n\n        Query q = em.createQuery(\"select p from Person1M p where p.personName = vivek\");\n        List<Person1M> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        Assert.assertNotNull(persons.get(0).getAddresses());\n        Assert.assertEquals(2, persons.get(0).getAddresses().size());\n\n        em.remove(person);\n\n        person = em.find(Person1M.class, \"person_1\");\n        Assert.assertNull(person);\n        Assert.assertNull(em.find(Address1M.class, \"expressway\"));\n        Assert.assertNull(em.find(Address1M.class, \"noida street\"));\n\n    }\n\n    @Test\n    public void testCRUDM1() throws InterruptedException\n    {\n        PersonM1 person1 = new PersonM1();\n        person1.setPersonId(\"person_1\");\n        person1.setPersonName(\"vivek\");\n\n        PersonM1 person2 = new PersonM1();\n        person2.setPersonId(\"person_2\");\n        person2.setPersonName(\"vivek\");\n\n        Set<PersonM1> persons = new HashSet<PersonM1>();\n        persons.add(person1);\n        persons.add(person1);\n\n        AddressM1 address = new AddressM1();\n        address.setAddressId(\"noidastreet\");\n        address.setPersons(persons);\n        address.setStreet(\"Sector 50\");\n\n        person1.setAddresses(address);\n\n        person2.setAddresses(address);\n\n        em.persist(person1);\n        em.persist(person2);\n        // em.persist(address);\n\n        waitThread();\n        em.clear();\n\n        person1 = em.find(PersonM1.class, \"person_1\");\n        Assert.assertNotNull(person1);\n        Assert.assertNotNull(person1.getAddresses());\n        Assert.assertEquals(2, person1.getAddresses().getPersons().size());\n\n        Query q = em.createQuery(\"select p from PersonM1 p where p.personName = vivek\");\n        List<PersonM1> foundPersons = q.getResultList();\n        Assert.assertNotNull(foundPersons);\n        Assert.assertEquals(2, foundPersons.size());\n        Assert.assertNotNull(foundPersons.get(0).getAddresses());\n        Assert.assertEquals(\"Sector 50\", foundPersons.get(0).getAddresses().getStreet());\n        Assert.assertNotNull(foundPersons.get(1).getAddresses());\n        Assert.assertEquals(\"Sector 50\", foundPersons.get(1).getAddresses().getStreet());\n\n        em.remove(person1);\n        em.remove(person2);\n\n    }\n    \n    @After\n    public void tearDown()\n    {\n        if(em != null)\n        {\n            em.close();\n        }\n        \n        if(emf != null)\n        {\n            emf.close();\n        }\n        \n\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        node.close();\n    }\n\n \n    private void waitThread() throws InterruptedException\n    {\n        Thread.sleep(2000);\n    }\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/association/ManyToManyAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es.association;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\npublic class ManyToManyAssociationTest\n{\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    private static Node node = null;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        Builder builder = Settings.settingsBuilder();\n        builder.put(\"path.home\", \"target/data\");\n        node = new NodeBuilder().settings(builder).node();\n    }\n\n    @Before\n    public void setup()\n    {\n        emf = Persistence.createEntityManagerFactory(\"es-pu\");\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testUniMTM()\n    {\n        PersonMM person1 = new PersonMM();\n        person1.setPersonId(\"1_p\");\n        person1.setPersonName(\"vivek\");\n\n        PersonMM person2 = new PersonMM();\n        person2.setPersonId(\"2_p\");\n        person2.setPersonName(\"vivek\");\n\n        Set<AddressMM> addressess = new HashSet<AddressMM>();\n\n        AddressMM address1 = new AddressMM();\n        address1.setAddressId(\"addr_1\");\n        address1.setStreet(\"Noida\");\n\n        AddressMM address2 = new AddressMM();\n        address2.setAddressId(\"addr_2\");\n        address2.setStreet(\"Noida\");\n\n        addressess.add(address1);\n        addressess.add(address2);\n\n        person1.setAddresses(addressess);\n        person2.setAddresses(addressess);\n\n        em.persist(person1);\n\n        em.clear();\n\n        em.persist(person2);\n\n        waitThread();\n\n        em.clear();\n\n        PersonMM result = em.find(PersonMM.class, \"1_p\");\n        Assert.assertNotNull(result);\n        Assert.assertNotNull(result.getAddresses());\n        Assert.assertEquals(2, result.getAddresses().size());\n\n        em.clear();\n\n        Assert.assertNotNull(em.find(AddressMM.class, \"addr_1\"));\n        Assert.assertNotNull(em.find(AddressMM.class, \"addr_2\"));\n\n        Query q = em.createQuery(\"select p from PersonMM p where p.personName = vivek\");\n        List<PersonMM> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(2, persons.size());\n        Assert.assertNotNull(persons.get(0).getAddresses());\n        Assert.assertEquals(2, persons.get(0).getAddresses().size());\n        Assert.assertNotNull(persons.get(1).getAddresses());\n        Assert.assertEquals(2, persons.get(1).getAddresses().size());\n\n        em.remove(result);\n\n        em.clear();\n        result = em.find(PersonMM.class, \"1_p\");\n        Assert.assertNull(result);\n\n        Assert.assertNull(em.find(AddressMM.class, \"addr_1\"));\n        Assert.assertNull(em.find(AddressMM.class, \"addr_2\"));\n\n    }\n\n    @Test\n    public void testBiMTM()\n    {\n        PersonBiMM person1 = new PersonBiMM();\n        person1.setPersonId(\"1_p\");\n        person1.setPersonName(\"vivek\");\n\n        PersonBiMM person2 = new PersonBiMM();\n        person2.setPersonId(\"2_p\");\n        person2.setPersonName(\"vivek\");\n\n        Set<AddressBiMM> addressess = new HashSet<AddressBiMM>();\n\n        AddressBiMM address1 = new AddressBiMM();\n        address1.setAddressId(\"addr_1\");\n        address1.setStreet(\"Noida\");\n\n        AddressBiMM address2 = new AddressBiMM();\n        address2.setAddressId(\"addr_2\");\n        address2.setStreet(\"Noida\");\n\n        addressess.add(address1);\n        addressess.add(address2);\n\n        person1.setAddresses(addressess);\n        person2.setAddresses(addressess);\n\n        em.persist(person1);\n\n        em.clear();\n\n        em.persist(person2);\n\n        waitThread();\n\n        em.clear();\n\n        PersonBiMM result = em.find(PersonBiMM.class, \"1_p\");\n        Assert.assertNotNull(result);\n        Assert.assertNotNull(result.getAddresses());\n        Assert.assertEquals(2, result.getAddresses().size());\n\n        Assert.assertEquals(2, result.getAddresses().iterator().next().getPeople().size());\n        Assert.assertEquals(2, result.getAddresses().iterator().next().getPeople().size());\n\n        em.clear();\n\n        Assert.assertNotNull(em.find(AddressBiMM.class, \"addr_1\"));\n        Assert.assertNotNull(em.find(AddressBiMM.class, \"addr_2\"));\n\n        Query q = em.createQuery(\"select p from PersonBiMM p where p.personName = vivek\");\n        List<PersonBiMM> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(2, persons.size());\n        Assert.assertNotNull(persons.get(0).getAddresses());\n        Assert.assertEquals(2, persons.get(0).getAddresses().size());\n        Assert.assertNotNull(persons.get(1).getAddresses());\n        Assert.assertEquals(2, persons.get(1).getAddresses().size());\n\n        em.remove(result);\n\n        em.clear();\n        result = em.find(PersonBiMM.class, \"1_p\");\n        Assert.assertNull(result);\n\n        Assert.assertNull(em.find(AddressBiMM.class, \"addr_1\"));\n        Assert.assertNull(em.find(AddressBiMM.class, \"addr_2\"));\n\n    }\n\n    @After\n    public void tearDown()\n    {\n        if(em != null)\n        {\n            em.close();\n        }\n        \n        if(emf != null)\n        {\n            emf.close();\n        }\n        \n\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n//        node.stop();\n        node.close();\n    }\n\n    private void waitThread()\n    {\n        try\n        {\n            Thread.sleep(2000);\n        }\n        catch (InterruptedException e)\n        {\n            \n        }\n    }\n\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/association/Person1M.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es.association;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n/**\n * @author vivek.mishra\n *  1-M person entity.\n */\n@Entity\n@Table(name=\"PERSONNEL\", schema=\"esSchema@es-pu\")\npublic class Person1M\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = \"person\")\n    private Set<Address1M> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<Address1M> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<Address1M> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/association/PersonBiMM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es.association;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\n/**\n * @author vivek.mishra\n *  Bi M-M person entity.\n */\n@Entity\n//@Table(name=\"PERSONNELBIMM\", schema=\"esSchema@es-pu\")\npublic class PersonBiMM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @JoinTable(name = \"PERSONNELBI_ADDRESS\", schema = \"esSchema\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Set<AddressBiMM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressBiMM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressBiMM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/association/PersonM1.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es.association;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *  M-1 person entity.\n */\n@Entity\n@Table(name=\"PERSONNELM1\", schema=\"esSchema@es-pu\")\npublic class PersonM1\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @JoinColumn(name=\"ADDRESS_ID\")\n    private AddressM1 address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressM1 getAddresses()\n    {\n        return address;\n    }\n\n    public void setAddresses(AddressM1 addresses)\n    {\n        this.address = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/association/PersonMM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es.association;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n/**\n * @author vivek.mishra\n *  M-M person entity.\n */\n@Entity\n@Table(name=\"PERSONNELMM\", schema=\"esSchema@es-pu\")\npublic class PersonMM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @JoinTable(name = \"PERSONNEL_ADDRESS\", schema = \"esSchema\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Set<AddressMM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressMM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressMM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/autogeneratedid/Employee.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es.autogeneratedid;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Employee.\n * \n * @author devender.yadav\n */\n@Entity\n@Table(name = \"ES_EMPLOYEE\", schema = \"esSchema@es-auto-gen-pu\")\npublic class Employee\n{\n\n    /** The id. */\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    private String empId;\n\n    /** The name. */\n    @Column\n    private String name;\n\n    /** The salary. */\n    @Column\n    private Integer salary;\n\n    /**\n     * Gets the id.\n     *\n     * @return the id\n     */\n    public String getId()\n    {\n        return empId;\n    }\n\n    /**\n     * Sets the id.\n     *\n     * @param id\n     *            the new id\n     */\n    public void setId(String id)\n    {\n        this.empId = id;\n    }\n\n    /**\n     * Gets the name.\n     *\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     *\n     * @param name\n     *            the new name\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * Gets the salary.\n     *\n     * @return the salary\n     */\n    public Integer getSalary()\n    {\n        return salary;\n    }\n\n    /**\n     * Sets the salary.\n     *\n     * @param salary\n     *            the new salary\n     */\n    public void setSalary(int salary)\n    {\n        this.salary = salary;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/autogeneratedid/IdAutoGenerationTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.es.autogeneratedid;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport junit.framework.Assert;\n\npublic class IdAutoGenerationTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private static Node node = null;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        Builder builder = Settings.settingsBuilder();\n        builder.put(\"path.home\", \"target/data\");\n        node = new NodeBuilder().settings(builder).node();\n    }\n\n    @Before\n    public void setup()\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"es-auto-gen-pu\");\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void test() throws InterruptedException\n    {\n\n        Employee emp1 = new Employee();\n        emp1.setName(\"dev\");\n        emp1.setSalary(50000);\n\n        Employee emp2 = new Employee();\n        emp2.setName(\"karthik\");\n        emp2.setSalary(60000);\n\n        em.persist(emp1);\n        em.persist(emp2);\n\n        waitThread();\n\n        List employees = em.createQuery(\"select e from Employee e\").getResultList();\n        Assert.assertEquals(2, employees.size());\n        assertEmployees(employees);\n\n        Query q = em.createQuery(\"delete from Employee e\");\n        int count = q.executeUpdate();\n        Assert.assertEquals(2, count);\n\n    }\n\n    private void assertEmployees(List<Employee> employees)\n    {\n\n        for (Employee e : employees)\n        {\n            if (e.getName().equals(\"dev\"))\n            {\n                Assert.assertEquals(new Integer(50000), e.getSalary());\n            }\n            else if (e.getName().equals(\"karthik\"))\n            {\n                Assert.assertEquals(new Integer(60000), e.getSalary());\n            }\n        }\n\n    }\n\n    @After\n    public void tearDown()\n    {\n        if (em != null)\n        {\n            em.close();\n        }\n\n        if (emf != null)\n        {\n            emf.close();\n        }\n\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        node.close();\n    }\n\n    /**\n     * Wait thread.\n     */\n    private void waitThread()\n    {\n        try\n        {\n            Thread.sleep(2000);\n        }\n        catch (InterruptedException e)\n        {\n            e.printStackTrace();\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/mappedsuperclass/ESEntityWithoutFieldsTest.java",
    "content": "package com.impetus.client.es.mappedsuperclass;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.mappedsuperclass.EntityWithoutFieldsBase;\n\n/**\n * @author amitkumar\n * \n *         Class to verify that at least one field in entity class is not\n *         mandatory if the superclass contains all the mandatory fields\n */\npublic class ESEntityWithoutFieldsTest extends EntityWithoutFieldsBase\n{\n\n    private static Node node;\n\n    @Before\n    public void setup()\n    {\n\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n        persistenceUnit = \"esMappedSuperClass-pu\";\n        setupInternal();\n    }\n\n    @Test\n    public void testEntityWithNoFields()\n    {\n        testEntityWithNoFieldsBase();\n    }\n\n    @Test\n    public void testEntityWithNoFields2LevelInheritance()\n    {\n        testEntityWithNoFields2LevelInheritanceBase();\n    }\n\n    @After\n    public void tearDown()\n    {\n        if (checkIfServerRunning() && node != null)\n        {\n            node.close();\n        }\n        tearDownInternal();\n    }\n\n    /**\n     * Check if server running.\n     * \n     * @return true, if successful\n     */\n    private static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 9300);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n\n    }\n\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/mappedsuperclass/ESMappedSuperClassTest.java",
    "content": "package com.impetus.client.es.mappedsuperclass;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.crud.mappedsuperclass.MappedSuperClassBase;\n\npublic class ESMappedSuperClassTest extends MappedSuperClassBase\n{\n\n    private static Node node;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n        _PU = \"es-pu\";\n        setUpInternal();\n    }\n\n    @Test\n    public void test()\n    {\n        assertInternal(true);\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        if (checkIfServerRunning() && node != null)\n        {\n            node.close();\n        }\n        tearDownInternal();\n\n    }\n\n    /**\n     * Check if server running.\n     * \n     * @return true, if successful\n     */\n    private static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 9300);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n\n    }\n}"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/validator/BookEntity.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.es.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Devender Yadav\n * \n */\n@Entity\n@Table(name = \"BOOK_ENTITY\", schema = \"esSchema@es-pu\")\npublic class BookEntity\n{\n\n    @Id\n    @Column(name = \"ID\")\n    private int bookId;\n\n    @Column(name = \"TITLE\")\n    private String title;\n\n    @Column(name = \"AUTHOR\")\n    private String author;\n\n    @Column(name = \"PAGES\")\n    private int pages;\n\n    protected BookEntity()\n    {\n    }\n\n    public int getBookId()\n    {\n        return bookId;\n    }\n\n    public void setBookId(int bookId)\n    {\n        this.bookId = bookId;\n    }\n\n    public String getTitle()\n    {\n        return title;\n    }\n\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    public int getPages()\n    {\n        return pages;\n    }\n\n    public void setPages(int pages)\n    {\n        this.pages = pages;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/validator/ConstructorValidationTest.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.es.validator;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * @author Devender Yadav\n * \n */\npublic class ConstructorValidationTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n    \n    private Node node = null;\n    \n    @Before\n    public void setup() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n    }\n\n    @Test\n    public void validConstructorTest() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"es-pu\");\n        em = emf.createEntityManager();\n        BookEntity book = new BookEntity();\n        book.setBookId(1);\n        book.setTitle(\"The Complete Reference\");\n        book.setAuthor(\"Herbert Schildt\");\n        book.setPages(500);\n\n        em.persist(book);\n\n        em.clear();\n\n        BookEntity book1 = em.find(BookEntity.class, 1);\n\n        Assert.assertNotNull(book1);\n        Assert.assertEquals(1, book1.getBookId());\n        Assert.assertEquals(\"The Complete Reference\", book1.getTitle());\n        Assert.assertEquals(\"Herbert Schildt\", book1.getAuthor());\n        Assert.assertEquals(500, book1.getPages());\n\n        em.remove(book1);\n\n        BookEntity book2 = em.find(BookEntity.class, 1);\n        Assert.assertNull(book2);\n\n        em.close();\n        emf.close();\n    }\n    \n    @After\n    public void tearDown() throws Exception\n    {\n        if (checkIfServerRunning() && node != null)\n        {\n            node.close();\n        }\n\n    }\n\n    /**\n     * Check if server running.\n     * \n     * @return true, if successful\n     */\n    private static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 9300);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/CreditTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * Credit transaction extends {@link Transaction}\n *\n */\n\n@Entity\n@Table(name = \"TRNX_CREDIT\")\n@DiscriminatorValue(value = \"credit\")\n@AttributeOverride(name=\"bankIdentifier\",column= @Column(name=\"CREDIT_BANK_IDENT\"))\npublic class CreditTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public CreditTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/DebitTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\n\n/**\n * @author vivek.mishra\n * Debit transaction extends {@link Transaction}\n *\n */\n@Entity\n@DiscriminatorValue(value=\"debit\")\n\n@AttributeOverrides(value = { @AttributeOverride(name = \"txId\", column = @Column(name = \"DEBIT_ID\")),\n        @AttributeOverride(name = \"bankIdentifier\", column = @Column(name = \"DEBIT_BANK_IDENT\")),\n        @AttributeOverride(name = \"transactionDt\", column = @Column(name = \"TX_DT\")) })\n\npublic class DebitTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public DebitTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\t<!-- Persistence Units for ES application -->\n\n\n\t<persistence-unit name=\"es-pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9300\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"esSchema\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"es\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.es.ESClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"es-refresh-indexes-pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.es.Book</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9300\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"esSchema\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"es\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.es.ESClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"es-auto-gen-pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.es.autogeneratedid.Employee</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9300\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"esSchema\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"es\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.es.ESClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"esAggregationPU\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.query.Person</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9300\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"esSchema\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"es\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.es.ESClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\n\t<persistence-unit name=\"es-external-config\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9300\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"esSchema\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"es\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.es.ESClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaes.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"esMappedSuperClass-pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.Person</class>\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.PersonChild</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9300\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"esSchema\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"es\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.es.ESClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\n</persistence>\n\n"
  },
  {
    "path": "src/kundera-elastic-search/src/test/resources/esindexer.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<indexerProperties>\n\t<nodes>\n\t\t<node>\n\t\t\t<properties>\n\t\t\t\t<property name=\"host\" value=\"localhost\" />\n\t\t\t\t<property name=\"port\" value=\"9300\" />\n\t\t\t</properties>\n\t\t</node>\n\t</nodes>\n</indexerProperties>"
  },
  {
    "path": "src/kundera-elastic-search/src/test/resources/kunderaes.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>elasticsearch</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"client.transport.sniff\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"discovery.zen.ping.multicast.enabled\"\n\t\t\t\t\t\tvalue=\"false\"></property>\n\t\t\t\t\t<property name=\"discovery.zen.ping.unicast.enabled\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"discovery.zen.multicast.enabled\" value=\"false\"></property>\n\t\t\t\t\t<property name=\"discovery.zen.unicast.enabled\" value=\"true\"></property>\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "src/kundera-ethereum/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-ethereum</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-ethereum</name>\n\t<url>http://maven.apache.org</url>\n\n\t<parent>\n\t\t<groupId>com.impetus</groupId>\n\t\t<artifactId>kundera</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>org.web3j</groupId>\n\t\t\t<artifactId>core</artifactId>\n\t\t\t<version>3.0.1</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.8</source>\n\t\t\t\t\t<target>1.8</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/entities/Block.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.blockchain.entities;\n\nimport java.util.List;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n/**\n * The Class Block.\n * \n * @author devender.yadav\n * \n */\n@Entity\npublic class Block\n{\n\n    /** The number. */\n    @Id\n    private String number;\n\n    /** The hash. */\n    @Column\n    private String hash;\n\n    /** The parent hash. */\n    @Column\n    private String parentHash;\n\n    /** The nonce. */\n    @Column\n    private String nonce;\n\n    /** The sha3 uncles. */\n    @Column\n    private String sha3Uncles;\n\n    /** The logs bloom. */\n    @Column\n    private String logsBloom;\n\n    /** The transactions root. */\n    @Column\n    private String transactionsRoot;\n\n    /** The state root. */\n    @Column\n    private String stateRoot;\n\n    /** The receipts root. */\n    @Column\n    private String receiptsRoot;\n\n    /** The author. */\n    @Column\n    private String author;\n\n    /** The miner. */\n    @Column\n    private String miner;\n\n    /** The mix hash. */\n    @Column\n    private String mixHash;\n\n    /** The difficulty. */\n    @Column\n    private String difficulty;\n\n    /** The total difficulty. */\n    @Column\n    private String totalDifficulty;\n\n    /** The extra data. */\n    @Column\n    private String extraData;\n\n    /** The size. */\n    @Column\n    private String size;\n\n    /** The gas limit. */\n    @Column\n    private String gasLimit;\n\n    /** The gas used. */\n    @Column\n    private String gasUsed;\n\n    /** The timestamp. */\n    @Column\n    private String timestamp;\n\n    /** The transactions. */\n    @Column\n    private List<Transaction> transactions;\n\n    /** The uncles. */\n    @Column\n    private List<String> uncles;\n\n    /** The seal fields. */\n    @Column\n    private List<String> sealFields;\n\n    /**\n     * Gets the number.\n     *\n     * @return the number\n     */\n    public String getNumber()\n    {\n        return number;\n    }\n\n    /**\n     * Sets the number.\n     *\n     * @param number\n     *            the new number\n     */\n    public void setNumber(String number)\n    {\n        this.number = number;\n    }\n\n    /**\n     * Gets the hash.\n     *\n     * @return the hash\n     */\n    public String getHash()\n    {\n        return hash;\n    }\n\n    /**\n     * Sets the hash.\n     *\n     * @param hash\n     *            the new hash\n     */\n    public void setHash(String hash)\n    {\n        this.hash = hash;\n    }\n\n    /**\n     * Gets the parent hash.\n     *\n     * @return the parent hash\n     */\n    public String getParentHash()\n    {\n        return parentHash;\n    }\n\n    /**\n     * Sets the parent hash.\n     *\n     * @param parentHash\n     *            the new parent hash\n     */\n    public void setParentHash(String parentHash)\n    {\n        this.parentHash = parentHash;\n    }\n\n    /**\n     * Gets the nonce.\n     *\n     * @return the nonce\n     */\n    public String getNonce()\n    {\n        return nonce;\n    }\n\n    /**\n     * Sets the nonce.\n     *\n     * @param nonce\n     *            the new nonce\n     */\n    public void setNonce(String nonce)\n    {\n        this.nonce = nonce;\n    }\n\n    /**\n     * Gets the sha3 uncles.\n     *\n     * @return the sha3 uncles\n     */\n    public String getSha3Uncles()\n    {\n        return sha3Uncles;\n    }\n\n    /**\n     * Sets the sha3 uncles.\n     *\n     * @param sha3Uncles\n     *            the new sha3 uncles\n     */\n    public void setSha3Uncles(String sha3Uncles)\n    {\n        this.sha3Uncles = sha3Uncles;\n    }\n\n    /**\n     * Gets the logs bloom.\n     *\n     * @return the logs bloom\n     */\n    public String getLogsBloom()\n    {\n        return logsBloom;\n    }\n\n    /**\n     * Sets the logs bloom.\n     *\n     * @param logsBloom\n     *            the new logs bloom\n     */\n    public void setLogsBloom(String logsBloom)\n    {\n        this.logsBloom = logsBloom;\n    }\n\n    /**\n     * Gets the transactions root.\n     *\n     * @return the transactions root\n     */\n    public String getTransactionsRoot()\n    {\n        return transactionsRoot;\n    }\n\n    /**\n     * Sets the transactions root.\n     *\n     * @param transactionsRoot\n     *            the new transactions root\n     */\n    public void setTransactionsRoot(String transactionsRoot)\n    {\n        this.transactionsRoot = transactionsRoot;\n    }\n\n    /**\n     * Gets the state root.\n     *\n     * @return the state root\n     */\n    public String getStateRoot()\n    {\n        return stateRoot;\n    }\n\n    /**\n     * Sets the state root.\n     *\n     * @param stateRoot\n     *            the new state root\n     */\n    public void setStateRoot(String stateRoot)\n    {\n        this.stateRoot = stateRoot;\n    }\n\n    /**\n     * Gets the receipts root.\n     *\n     * @return the receipts root\n     */\n    public String getReceiptsRoot()\n    {\n        return receiptsRoot;\n    }\n\n    /**\n     * Sets the receipts root.\n     *\n     * @param receiptsRoot\n     *            the new receipts root\n     */\n    public void setReceiptsRoot(String receiptsRoot)\n    {\n        this.receiptsRoot = receiptsRoot;\n    }\n\n    /**\n     * Gets the author.\n     *\n     * @return the author\n     */\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    /**\n     * Sets the author.\n     *\n     * @param author\n     *            the new author\n     */\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    /**\n     * Gets the miner.\n     *\n     * @return the miner\n     */\n    public String getMiner()\n    {\n        return miner;\n    }\n\n    /**\n     * Sets the miner.\n     *\n     * @param miner\n     *            the new miner\n     */\n    public void setMiner(String miner)\n    {\n        this.miner = miner;\n    }\n\n    /**\n     * Gets the mix hash.\n     *\n     * @return the mix hash\n     */\n    public String getMixHash()\n    {\n        return mixHash;\n    }\n\n    /**\n     * Sets the mix hash.\n     *\n     * @param mixHash\n     *            the new mix hash\n     */\n    public void setMixHash(String mixHash)\n    {\n        this.mixHash = mixHash;\n    }\n\n    /**\n     * Gets the difficulty.\n     *\n     * @return the difficulty\n     */\n    public String getDifficulty()\n    {\n        return difficulty;\n    }\n\n    /**\n     * Sets the difficulty.\n     *\n     * @param difficulty\n     *            the new difficulty\n     */\n    public void setDifficulty(String difficulty)\n    {\n        this.difficulty = difficulty;\n    }\n\n    /**\n     * Gets the total difficulty.\n     *\n     * @return the total difficulty\n     */\n    public String getTotalDifficulty()\n    {\n        return totalDifficulty;\n    }\n\n    /**\n     * Sets the total difficulty.\n     *\n     * @param totalDifficulty\n     *            the new total difficulty\n     */\n    public void setTotalDifficulty(String totalDifficulty)\n    {\n        this.totalDifficulty = totalDifficulty;\n    }\n\n    /**\n     * Gets the extra data.\n     *\n     * @return the extra data\n     */\n    public String getExtraData()\n    {\n        return extraData;\n    }\n\n    /**\n     * Sets the extra data.\n     *\n     * @param extraData\n     *            the new extra data\n     */\n    public void setExtraData(String extraData)\n    {\n        this.extraData = extraData;\n    }\n\n    /**\n     * Gets the size.\n     *\n     * @return the size\n     */\n    public String getSize()\n    {\n        return size;\n    }\n\n    /**\n     * Sets the size.\n     *\n     * @param size\n     *            the new size\n     */\n    public void setSize(String size)\n    {\n        this.size = size;\n    }\n\n    /**\n     * Gets the gas limit.\n     *\n     * @return the gas limit\n     */\n    public String getGasLimit()\n    {\n        return gasLimit;\n    }\n\n    /**\n     * Sets the gas limit.\n     *\n     * @param gasLimit\n     *            the new gas limit\n     */\n    public void setGasLimit(String gasLimit)\n    {\n        this.gasLimit = gasLimit;\n    }\n\n    /**\n     * Gets the gas used.\n     *\n     * @return the gas used\n     */\n    public String getGasUsed()\n    {\n        return gasUsed;\n    }\n\n    /**\n     * Sets the gas used.\n     *\n     * @param gasUsed\n     *            the new gas used\n     */\n    public void setGasUsed(String gasUsed)\n    {\n        this.gasUsed = gasUsed;\n    }\n\n    /**\n     * Gets the timestamp.\n     *\n     * @return the timestamp\n     */\n    public String getTimestamp()\n    {\n        return timestamp;\n    }\n\n    /**\n     * Sets the timestamp.\n     *\n     * @param timestamp\n     *            the new timestamp\n     */\n    public void setTimestamp(String timestamp)\n    {\n        this.timestamp = timestamp;\n    }\n\n    /**\n     * Gets the transactions.\n     *\n     * @return the transactions\n     */\n    public List<Transaction> getTransactions()\n    {\n        return transactions;\n    }\n\n    /**\n     * Sets the transactions.\n     *\n     * @param transactions\n     *            the new transactions\n     */\n    public void setTransactions(List<Transaction> transactions)\n    {\n        this.transactions = transactions;\n    }\n\n    /**\n     * Gets the uncles.\n     *\n     * @return the uncles\n     */\n    public List<String> getUncles()\n    {\n        return uncles;\n    }\n\n    /**\n     * Sets the uncles.\n     *\n     * @param uncles\n     *            the new uncles\n     */\n    public void setUncles(List<String> uncles)\n    {\n        this.uncles = uncles;\n    }\n\n    /**\n     * Gets the seal fields.\n     *\n     * @return the seal fields\n     */\n    public List<String> getSealFields()\n    {\n        return sealFields;\n    }\n\n    /**\n     * Sets the seal fields.\n     *\n     * @param sealFields\n     *            the new seal fields\n     */\n    public void setSealFields(List<String> sealFields)\n    {\n        this.sealFields = sealFields;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/entities/Transaction.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.blockchain.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n/**\n * The Class Transaction.\n * \n * @author devender.yadav\n */\n@Entity\npublic class Transaction {\n\t\n\t/** The hash. */\n\t@Id\n\tprivate String hash;\n\t\n\t/** The nonce. */\n\t@Column\n\tprivate String nonce;\n\t\n\t/** The block hash. */\n\t@Column\n\tprivate String blockHash;\n\t\n\t/** The block number. */\n\t@Column\n\tprivate String blockNumber;\n\t\n\t/** The transaction index. */\n\t@Column\n\tprivate String transactionIndex;\n\t\n\t/** The from. */\n\t@Column\n\tprivate String from;\n\t\n\t/** The to. */\n\t@Column\n\tprivate String to;\n\t\n\t/** The value. */\n\t@Column\n\tprivate String value;\n\t\n\t/** The gas price. */\n\t@Column\n\tprivate String gasPrice;\n\t\n\t/** The gas. */\n\t@Column\n\tprivate String gas;\n\t\n\t/** The input. */\n\t@Column\n\tprivate String input;\n\t\n\t/** The creates. */\n\t@Column\n\tprivate String creates;\n\t\n\t/** The public key. */\n\t@Column\n\tprivate String publicKey;\n\t\n\t/** The raw. */\n\t@Column\n\tprivate String raw;\n\t\n\t/** The r. */\n\t@Column\n\tprivate String r;\n\t\n\t/** The s. */\n\t@Column\n\tprivate String s;\n\t\n\t/** The v. */\n\t@Column\n\tprivate int v;\n\n\t/**\n\t * Gets the hash.\n\t *\n\t * @return the hash\n\t */\n\tpublic String getHash() {\n\t\treturn hash;\n\t}\n\n\t/**\n\t * Sets the hash.\n\t *\n\t * @param hash the new hash\n\t */\n\tpublic void setHash(String hash) {\n\t\tthis.hash = hash;\n\t}\n\n\t/**\n\t * Gets the nonce.\n\t *\n\t * @return the nonce\n\t */\n\tpublic String getNonce() {\n\t\treturn nonce;\n\t}\n\n\t/**\n\t * Sets the nonce.\n\t *\n\t * @param nonce the new nonce\n\t */\n\tpublic void setNonce(String nonce) {\n\t\tthis.nonce = nonce;\n\t}\n\n\t/**\n\t * Gets the block hash.\n\t *\n\t * @return the block hash\n\t */\n\tpublic String getBlockHash() {\n\t\treturn blockHash;\n\t}\n\n\t/**\n\t * Sets the block hash.\n\t *\n\t * @param blockHash the new block hash\n\t */\n\tpublic void setBlockHash(String blockHash) {\n\t\tthis.blockHash = blockHash;\n\t}\n\n\t/**\n\t * Gets the block number.\n\t *\n\t * @return the block number\n\t */\n\tpublic String getBlockNumber() {\n\t\treturn blockNumber;\n\t}\n\n\t/**\n\t * Sets the block number.\n\t *\n\t * @param blockNumber the new block number\n\t */\n\tpublic void setBlockNumber(String blockNumber) {\n\t\tthis.blockNumber = blockNumber;\n\t}\n\n\t/**\n\t * Gets the transaction index.\n\t *\n\t * @return the transaction index\n\t */\n\tpublic String getTransactionIndex() {\n\t\treturn transactionIndex;\n\t}\n\n\t/**\n\t * Sets the transaction index.\n\t *\n\t * @param transactionIndex the new transaction index\n\t */\n\tpublic void setTransactionIndex(String transactionIndex) {\n\t\tthis.transactionIndex = transactionIndex;\n\t}\n\n\t/**\n\t * Gets the from.\n\t *\n\t * @return the from\n\t */\n\tpublic String getFrom() {\n\t\treturn from;\n\t}\n\n\t/**\n\t * Sets the from.\n\t *\n\t * @param from the new from\n\t */\n\tpublic void setFrom(String from) {\n\t\tthis.from = from;\n\t}\n\n\t/**\n\t * Gets the to.\n\t *\n\t * @return the to\n\t */\n\tpublic String getTo() {\n\t\treturn to;\n\t}\n\n\t/**\n\t * Sets the to.\n\t *\n\t * @param to the new to\n\t */\n\tpublic void setTo(String to) {\n\t\tthis.to = to;\n\t}\n\n\t/**\n\t * Gets the value.\n\t *\n\t * @return the value\n\t */\n\tpublic String getValue() {\n\t\treturn value;\n\t}\n\n\t/**\n\t * Sets the value.\n\t *\n\t * @param value the new value\n\t */\n\tpublic void setValue(String value) {\n\t\tthis.value = value;\n\t}\n\n\t/**\n\t * Gets the gas price.\n\t *\n\t * @return the gas price\n\t */\n\tpublic String getGasPrice() {\n\t\treturn gasPrice;\n\t}\n\n\t/**\n\t * Sets the gas price.\n\t *\n\t * @param gasPrice the new gas price\n\t */\n\tpublic void setGasPrice(String gasPrice) {\n\t\tthis.gasPrice = gasPrice;\n\t}\n\n\t/**\n\t * Gets the gas.\n\t *\n\t * @return the gas\n\t */\n\tpublic String getGas() {\n\t\treturn gas;\n\t}\n\n\t/**\n\t * Sets the gas.\n\t *\n\t * @param gas the new gas\n\t */\n\tpublic void setGas(String gas) {\n\t\tthis.gas = gas;\n\t}\n\n\t/**\n\t * Gets the input.\n\t *\n\t * @return the input\n\t */\n\tpublic String getInput() {\n\t\treturn input;\n\t}\n\n\t/**\n\t * Sets the input.\n\t *\n\t * @param input the new input\n\t */\n\tpublic void setInput(String input) {\n\t\tthis.input = input;\n\t}\n\n\t/**\n\t * Gets the creates.\n\t *\n\t * @return the creates\n\t */\n\tpublic String getCreates() {\n\t\treturn creates;\n\t}\n\n\t/**\n\t * Sets the creates.\n\t *\n\t * @param creates the new creates\n\t */\n\tpublic void setCreates(String creates) {\n\t\tthis.creates = creates;\n\t}\n\n\t/**\n\t * Gets the public key.\n\t *\n\t * @return the public key\n\t */\n\tpublic String getPublicKey() {\n\t\treturn publicKey;\n\t}\n\n\t/**\n\t * Sets the public key.\n\t *\n\t * @param publicKey the new public key\n\t */\n\tpublic void setPublicKey(String publicKey) {\n\t\tthis.publicKey = publicKey;\n\t}\n\n\t/**\n\t * Gets the raw.\n\t *\n\t * @return the raw\n\t */\n\tpublic String getRaw() {\n\t\treturn raw;\n\t}\n\n\t/**\n\t * Sets the raw.\n\t *\n\t * @param raw the new raw\n\t */\n\tpublic void setRaw(String raw) {\n\t\tthis.raw = raw;\n\t}\n\n\t/**\n\t * Gets the r.\n\t *\n\t * @return the r\n\t */\n\tpublic String getR() {\n\t\treturn r;\n\t}\n\n\t/**\n\t * Sets the r.\n\t *\n\t * @param r the new r\n\t */\n\tpublic void setR(String r) {\n\t\tthis.r = r;\n\t}\n\n\t/**\n\t * Gets the s.\n\t *\n\t * @return the s\n\t */\n\tpublic String getS() {\n\t\treturn s;\n\t}\n\n\t/**\n\t * Sets the s.\n\t *\n\t * @param s the new s\n\t */\n\tpublic void setS(String s) {\n\t\tthis.s = s;\n\t}\n\n\t/**\n\t * Gets the v.\n\t *\n\t * @return the v\n\t */\n\tpublic int getV() {\n\t\treturn v;\n\t}\n\n\t/**\n\t * Sets the v.\n\t *\n\t * @param v the new v\n\t */\n\tpublic void setV(int v) {\n\t\tthis.v = v;\n\t}\n\n}"
  },
  {
    "path": "src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/ethereum/BlockchainImporter.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.blockchain.ethereum;\n\nimport java.math.BigInteger;\n\nimport com.impetus.kundera.blockchain.entities.Block;\n\n/**\n * The Class BlockchainImporter.\n * \n * @author devender.yadav\n * \n */\npublic class BlockchainImporter\n{\n\n    /** The client. */\n    private static KunderaWeb3jClient client;\n\n\n    /**\n     * Instantiates a new blockchain importer.\n     */\n    private BlockchainImporter()\n    {\n    }\n\n    /**\n     * Gets the kundera web3j client.\n     *\n     * @return the kundera web3j client\n     */\n    public static KunderaWeb3jClient getKunderaWeb3jClient()\n    {\n        return client;\n    }\n    \n    /**\n     * Import all blocks from EARLIEST to LATEST and keep importing upcoming new\n     * blocks\n     */\n    public void importUptoLatestAndSyncNewBlocks()\n    {\n\n        client.saveBlocksTillLatest(client.getFirstBlockNumber(), true);\n    }\n\n    /**\n     * Import all blocks from startBlockNumber to LATEST and keep importing\n     * upcoming new blocks\n     * \n     * @param startBlockNumber\n     *            the start block number\n     */\n    public void importUptoLatestAndSyncNewBlocks(BigInteger startBlockNumber)\n    {\n        client.saveBlocksTillLatest(startBlockNumber, true);\n    }\n\n    /**\n     * Import all blocks from EARLIEST to LATEST\n     * \n     */\n    public void importUptoLatestBlock()\n    {\n        client.saveBlocksTillLatest(client.getFirstBlockNumber(), false);\n    }\n\n    /**\n     * Import all blocks from startBlockNumber to LATEST\n     *\n     * @param startBlockNumber\n     *            the start block number\n     */\n    public void importUptoLatestBlock(BigInteger startBlockNumber)\n    {\n        client.saveBlocksTillLatest(startBlockNumber, false);\n    }\n\n    /**\n     * Import all blocks from EARLIEST to endBlockNumber\n     *\n     *\n     * @param endBlockNumber\n     *            the end block number\n     */\n    public void importBlocksFromStarting(BigInteger endBlockNumber)\n    {\n        client.saveBlocks(client.getFirstBlockNumber(), endBlockNumber);\n    }\n\n    /**\n     * Import all blocks from startBlockNumber to endBlockNumber\n     *\n     * @param startBlockNumber\n     *            the start block number\n     * @param endBlockNumber\n     *            the end block number\n     */\n    public void importBlocks(BigInteger startBlockNumber, BigInteger endBlockNumber)\n    {\n        client.saveBlocks(startBlockNumber, endBlockNumber);\n    }\n\n    /**\n     * Gets the first block.\n     *\n     * @return the first block\n     */\n    public Block getFirstBlock()\n    {\n        return EtherObjectConverterUtil.convertEtherBlockToKunderaBlock(client.getFirstBlock(false), false);\n    }\n\n    /**\n     * Gets the first block with transactions.\n     *\n     * @return the first block with transactions\n     */\n    public Block getFirstBlockWithTransactions()\n    {\n        return EtherObjectConverterUtil.convertEtherBlockToKunderaBlock(client.getFirstBlock(true));\n    }\n\n    /**\n     * Gets the first block number.\n     *\n     * @return the first block number\n     */\n    public BigInteger getFirstBlockNumber()\n    {\n        return client.getFirstBlockNumber();\n    }\n\n    /**\n     * Gets the latest block.\n     *\n     * @return the latest block\n     */\n    public Block getLatestBlock()\n    {\n        return EtherObjectConverterUtil.convertEtherBlockToKunderaBlock(client.getLatestBlock(false), false);\n    }\n\n    /**\n     * Gets the latest block with transactions.\n     *\n     * @return the latest block with transactions\n     */\n    public Block getLatestBlockWithTransactions()\n    {\n        return EtherObjectConverterUtil.convertEtherBlockToKunderaBlock(client.getLatestBlock(true));\n    }\n\n    /**\n     * Gets the latest block number.\n     *\n     * @return the latest block number\n     */\n    public BigInteger getLatestBlockNumber()\n    {\n        return client.getLatestBlockNumber();\n    }\n\n    /**\n     * Gets the block.\n     *\n     * @param blockNumber\n     *            the block number\n     * @return the block\n     */\n    public Block getBlock(BigInteger blockNumber)\n    {\n        return EtherObjectConverterUtil.convertEtherBlockToKunderaBlock(client.getBlock(blockNumber, false), false);\n    }\n\n    /**\n     * Gets the block with transactions.\n     *\n     * @param blockNumber\n     *            the block number\n     * @return the block with transactions\n     */\n    public Block getBlockWithTransactions(BigInteger blockNumber)\n    {\n        return EtherObjectConverterUtil.convertEtherBlockToKunderaBlock(client.getBlock(blockNumber, true));\n    }\n\n    /**\n     * Initialize Web3j and Kundera related parameters.\n     *\n     * @return the blockchainImporter object\n     */\n    public static BlockchainImporter initialize()\n    {\n        client = new KunderaWeb3jClient();\n        return new BlockchainImporter();\n    }\n\n    /**\n     * Destroy.\n     */\n    public void destroy()\n    {\n        client.destroy();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/ethereum/Datasource.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.blockchain.ethereum;\n\n/**\n * The Enum Datasource.\n * \n * @author devender.yadav\n */\npublic enum Datasource\n{\n\n    /** The mongodb. */\n    MONGODB,\n    /** The rethinkdb. */\n    RETHINKDB,\n    /** The cassandra. */\n    CASSANDRA,\n    /** The hbase. */\n    HBASE,\n    /** The kudu. */\n    KUDU,\n    /** The redis. */\n    REDIS,\n    /** The couchdb. */\n    COUCHDB,\n    /** The kvstore. */\n    KVSTORE;\n\n}\n"
  },
  {
    "path": "src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/ethereum/EtherObjectConverterUtil.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.blockchain.ethereum;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.web3j.protocol.core.methods.response.EthBlock;\nimport org.web3j.protocol.core.methods.response.EthBlock.TransactionObject;\nimport org.web3j.protocol.core.methods.response.EthBlock.TransactionResult;\n\nimport com.impetus.kundera.blockchain.entities.Block;\nimport com.impetus.kundera.blockchain.entities.Transaction;\n\n/**\n * The Class EtherObjectConverterUtil.\n * \n * @author devender.yadav\n */\npublic class EtherObjectConverterUtil\n{\n\n    /**\n     * Instantiates a new ether object converter util.\n     */\n    private EtherObjectConverterUtil()\n    {\n    }\n\n    /**\n     * Convert ether block to kundera block.\n     *\n     * @param block\n     *            the block\n     * @return the block\n     */\n    public static Block convertEtherBlockToKunderaBlock(EthBlock block)\n    {\n        return convertEtherBlockToKunderaBlock(block, true);\n    }\n\n    /**\n     * Convert ether block to kundera block.\n     *\n     * @param block\n     *            the block\n     * @param includeTransactions\n     *            the include transactions\n     * @return the block\n     */\n    public static Block convertEtherBlockToKunderaBlock(EthBlock block, boolean includeTransactions)\n    {\n\n        Block kunderaBlk = new Block();\n        org.web3j.protocol.core.methods.response.EthBlock.Block blk = block.getBlock();\n\n        kunderaBlk.setAuthor(blk.getAuthor());\n        kunderaBlk.setDifficulty(blk.getDifficultyRaw());\n        kunderaBlk.setExtraData(blk.getExtraData());\n        kunderaBlk.setGasLimit(blk.getGasLimitRaw());\n        kunderaBlk.setGasUsed(blk.getGasUsedRaw());\n        kunderaBlk.setHash(blk.getHash());\n        kunderaBlk.setLogsBloom(blk.getLogsBloom());\n        kunderaBlk.setMiner(blk.getMiner());\n        kunderaBlk.setMixHash(blk.getMixHash());\n        kunderaBlk.setNonce(blk.getNonceRaw());\n        kunderaBlk.setNumber(blk.getNumberRaw());\n        kunderaBlk.setParentHash(blk.getParentHash());\n        kunderaBlk.setReceiptsRoot(blk.getReceiptsRoot());\n        kunderaBlk.setSealFields(blk.getSealFields());\n        kunderaBlk.setSha3Uncles(blk.getSha3Uncles());\n        kunderaBlk.setSize(blk.getSizeRaw());\n        kunderaBlk.setStateRoot(blk.getStateRoot());\n        kunderaBlk.setTimestamp(blk.getTimestampRaw());\n        kunderaBlk.setTotalDifficulty(blk.getTotalDifficultyRaw());\n        kunderaBlk.setTransactionsRoot(blk.getTransactionsRoot());\n        kunderaBlk.setUncles(blk.getUncles());\n\n        if (includeTransactions)\n        {\n            List<Transaction> kunderaTxs = new ArrayList<>();\n            List<TransactionResult> txResults = block.getBlock().getTransactions();\n\n            if (txResults != null && !txResults.isEmpty())\n            {\n                for (TransactionResult transactionResult : txResults)\n                {\n                    kunderaTxs.add(convertEtherTxToKunderaTx(transactionResult));\n                }\n                kunderaBlk.setTransactions(kunderaTxs);\n            }\n        }\n        return kunderaBlk;\n\n    }\n\n    /**\n     * Convert ether tx to kundera tx.\n     *\n     * @param transactionResult\n     *            the transaction result\n     * @return the transaction\n     */\n    public static Transaction convertEtherTxToKunderaTx(TransactionResult transactionResult)\n    {\n\n        Transaction kunderaTx = new Transaction();\n        TransactionObject txObj = (TransactionObject) transactionResult;\n\n        kunderaTx.setBlockHash(txObj.getBlockHash());\n        kunderaTx.setBlockNumber(txObj.getBlockNumberRaw());\n        kunderaTx.setCreates(txObj.getCreates());\n        kunderaTx.setFrom(txObj.getFrom());\n        kunderaTx.setGas(txObj.getGasRaw());\n        kunderaTx.setGasPrice(txObj.getGasPriceRaw());\n        kunderaTx.setHash(txObj.getHash());\n        kunderaTx.setInput(txObj.getInput());\n        kunderaTx.setNonce(txObj.getNonceRaw());\n        kunderaTx.setPublicKey(txObj.getPublicKey());\n        kunderaTx.setR(txObj.getR());\n        kunderaTx.setRaw(txObj.getRaw());\n        kunderaTx.setS(txObj.getS());\n        kunderaTx.setTo(txObj.getTo());\n        kunderaTx.setTransactionIndex(txObj.getTransactionIndexRaw());\n        kunderaTx.setV(txObj.getV());\n        kunderaTx.setValue(txObj.getValueRaw());\n\n        return kunderaTx;\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/ethereum/KunderaWeb3jClient.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.blockchain.ethereum;\n\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.web3j.protocol.Web3j;\nimport org.web3j.protocol.core.DefaultBlockParameter;\nimport org.web3j.protocol.core.DefaultBlockParameterName;\nimport org.web3j.protocol.core.methods.response.EthBlock;\nimport org.web3j.protocol.core.methods.response.EthBlock.TransactionResult;\nimport org.web3j.protocol.http.HttpService;\nimport org.web3j.protocol.ipc.UnixIpcService;\nimport org.web3j.protocol.ipc.WindowsIpcService;\nimport org.web3j.utils.Numeric;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.blockchain.entities.Block;\nimport com.impetus.kundera.blockchain.entities.Transaction;\nimport com.impetus.kundera.blockchain.util.EthConstants;\nimport com.impetus.kundera.blockchain.util.KunderaPropertyBuilder;\nimport com.impetus.kundera.blockchain.util.PropertyReader;\nimport com.impetus.kundera.client.ClientResolverException;\n\n/**\n * The Class KunderaWeb3jClient.\n * \n * @author devender.yadav\n */\npublic class KunderaWeb3jClient\n{\n\n    /** The Constant LOGGER. */\n    private static final Logger LOGGER = LoggerFactory.getLogger(KunderaWeb3jClient.class);\n\n    /** The web3j. */\n    private Web3j web3j;\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The reader. */\n    private PropertyReader reader;\n\n    /**\n     * Instantiates a new kundera web3j client.\n     */\n    public KunderaWeb3jClient()\n    {\n        reader = initializeProperties();\n        initializeWeb3j(reader);\n        initializeKunderaParams(reader);\n    }\n\n    /**\n     * Fetch blocks till latest.\n     *\n     * @param startBlockNum\n     *            the start block number\n     * @param syncUpcomingblocks\n     *            the sync upcomingblocks\n     */\n    public void saveBlocksTillLatest(BigInteger startBlockNum, boolean syncUpcomingblocks)\n    {\n\n        if (syncUpcomingblocks)\n        {\n            web3j.catchUpToLatestAndSubscribeToNewBlocksObservable(DefaultBlockParameter.valueOf(startBlockNum), true)\n                    .subscribe(block -> {\n                        persistBlocksAndTransactions(block);\n                    });\n        }\n        else\n        {\n            web3j.catchUpToLatestBlockObservable(DefaultBlockParameter.valueOf(startBlockNum), true).subscribe(\n                    block -> {\n                        persistBlocksAndTransactions(block);\n                    });\n        }\n    }\n\n    /**\n     * Persist blocks and transactions.\n     *\n     * @param block\n     *            the block\n     */\n    private void persistBlocksAndTransactions(EthBlock block)\n    {\n        Block blk = EtherObjectConverterUtil.convertEtherBlockToKunderaBlock(block, false);\n        try\n        {\n            em.persist(blk);\n            LOGGER.debug(\"Block number \" + getBlockNumberWithRawData(blk.getNumber()) + \" is stored!\");\n        }\n        catch (Exception ex)\n        {\n            LOGGER.error(\"Block number \" + getBlockNumberWithRawData(blk.getNumber()) + \" is not stored. \", ex);\n            throw new KunderaException(\"Block number \" + getBlockNumberWithRawData(blk.getNumber())\n                    + \" is not stored. \", ex);\n        }\n        for (TransactionResult tx : block.getResult().getTransactions())\n        {\n            persistTransactions(EtherObjectConverterUtil.convertEtherTxToKunderaTx(tx), blk.getNumber());\n        }\n        em.clear();\n    }\n\n    /**\n     * Persist transactions.\n     *\n     * @param tx\n     *            the transaction\n     * @param blockNumber\n     *            the block number\n     */\n    private void persistTransactions(Transaction tx, String blockNumber)\n    {\n\n        LOGGER.debug(\"Going to save transactions for Block - \" + getBlockNumberWithRawData(blockNumber) + \"!\");\n        try\n        {\n            em.persist(tx);\n            LOGGER.debug(\"Transaction with hash \" + tx.getHash() + \" is stored!\");\n        }\n        catch (Exception ex)\n        {\n            LOGGER.error(\"Transaction with hash \" + tx.getHash() + \" is not stored. \", ex);\n            throw new KunderaException(\"transaction with hash \" + tx.getHash() + \" is not stored. \", ex);\n        }\n\n    }\n\n    /**\n     * Gets the block.\n     *\n     * @param number\n     *            the number\n     * @param includeTransactions\n     *            the include transactions\n     * @return the block\n     */\n    public EthBlock getBlock(BigInteger number, boolean includeTransactions)\n    {\n        try\n        {\n            return web3j.ethGetBlockByNumber(DefaultBlockParameter.valueOf(number), includeTransactions).send();\n        }\n        catch (IOException ex)\n        {\n            LOGGER.error(\"Not able to find block\" + number + \". \", ex);\n            throw new KunderaException(\"Not able to find block\" + number + \". \", ex);\n        }\n    }\n\n    /**\n     * Gets the latest block.\n     *\n     * @param includeTransactions\n     *            the include transactions\n     * @return the latest block\n     */\n    public EthBlock getLatestBlock(boolean includeTransactions)\n    {\n        try\n        {\n            return web3j.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, includeTransactions).send();\n        }\n        catch (IOException ex)\n        {\n            LOGGER.error(\"Not able to find the LATEST block. \", ex);\n            throw new KunderaException(\"Not able to find the LATEST block. \", ex);\n        }\n    }\n\n    /**\n     * Gets the latest block number.\n     *\n     * @return the latest block number\n     */\n    public BigInteger getLatestBlockNumber()\n    {\n        return getLatestBlock(false).getBlock().getNumber();\n    }\n\n    /**\n     * Gets the first block.\n     *\n     * @param includeTransactions\n     *            the include transactions\n     * @return the first block\n     */\n    public EthBlock getFirstBlock(boolean includeTransactions)\n    {\n        try\n        {\n            return web3j.ethGetBlockByNumber(DefaultBlockParameterName.EARLIEST, includeTransactions).send();\n        }\n        catch (IOException ex)\n        {\n            LOGGER.error(\"Not able to find the EARLIEST block. \", ex);\n            throw new KunderaException(\"Not able to find the EARLIEST block. \", ex);\n        }\n\n    }\n\n    /**\n     * Gets the first block number.\n     *\n     * @return the first block number\n     */\n    public BigInteger getFirstBlockNumber()\n    {\n        return getFirstBlock(false).getBlock().getNumber();\n    }\n\n    /**\n     * Gets the blocks.\n     *\n     * @param startBlockNumber\n     *            the start block number\n     * @param endBlockNumber\n     *            the end block number\n     * @return the blocks\n     */\n    public void saveBlocks(BigInteger startBlockNumber, BigInteger endBlockNumber)\n    {\n\n        if (endBlockNumber.compareTo(startBlockNumber) < 1)\n        {\n            LOGGER.error(\"startBlockNumber must be smaller than endBlockNumer\");\n            throw new KunderaException(\"startBlockNumber must be smaller than endBlockNumer\");\n        }\n\n        if (startBlockNumber.compareTo(getFirstBlockNumber()) < 0)\n        {\n            LOGGER.error(\"start block number can't be smaller than EARLIEST block\");\n            throw new KunderaException(\"starting block number can't be smaller than EARLIEST block\");\n        }\n\n        if (endBlockNumber.compareTo(getLatestBlockNumber()) > 0)\n        {\n            LOGGER.error(\"end block number can't be larger than LATEST block\");\n            throw new KunderaException(\"end block number can't be larger than LATEST block\");\n        }\n\n        long diff = endBlockNumber.subtract(startBlockNumber).longValue();\n\n        for (long i = 0; i <= diff; i++)\n        {\n            EthBlock block = null;\n            BigInteger currentBlockNum = null;\n            try\n            {\n                currentBlockNum = startBlockNumber.add(BigInteger.valueOf(i));\n                block = web3j.ethGetBlockByNumber(DefaultBlockParameter.valueOf(currentBlockNum), true).send();\n            }\n            catch (IOException ex)\n            {\n                LOGGER.error(\"Not able to find block\" + currentBlockNum + \". \", ex);\n                throw new KunderaException(\"Not able to find block\" + currentBlockNum + \". \", ex);\n            }\n            persistBlocksAndTransactions(block);\n        }\n\n    }\n\n    /**\n     * Initialize web3j.\n     *\n     * @param reader\n     *            the reader\n     */\n    private void initializeWeb3j(PropertyReader reader)\n    {\n\n        String endPoint = reader.getProperty(EthConstants.ETHEREUM_NODE_ENDPOINT);\n\n        if (endPoint == null || endPoint.isEmpty())\n        {\n            LOGGER.error(\"Specify - \" + EthConstants.ETHEREUM_NODE_ENDPOINT + \" in \"\n                    + EthConstants.KUNDERA_ETHEREUM_PROPERTIES);\n            throw new KunderaException(\"Specify - \" + EthConstants.ETHEREUM_NODE_ENDPOINT + \" in \"\n                    + EthConstants.KUNDERA_ETHEREUM_PROPERTIES);\n        }\n\n        else if (endPoint.contains(\".ipc\"))\n        {\n            String os = reader.getProperty(EthConstants.ETHEREUM_NODE_OS);\n            LOGGER.info(\"Connecting using IPC socket. IPC Socket File location - \" + endPoint);\n            if (os != null && \"windows\".equalsIgnoreCase(os))\n            {\n                web3j = Web3j.build(new WindowsIpcService(endPoint));\n            }\n            else\n            {\n                web3j = Web3j.build(new UnixIpcService(endPoint));\n            }\n        }\n\n        else\n        {\n            LOGGER.info(\"Connecting via Endpoint - \" + endPoint);\n            web3j = Web3j.build(new HttpService(endPoint));\n        }\n    }\n\n    /**\n     * Initialize kundera params.\n     *\n     * @param reader\n     *            the reader\n     */\n    private void initializeKunderaParams(PropertyReader reader)\n    {\n        Map<String, String> props = KunderaPropertyBuilder.populatePersistenceUnitProperties(reader);\n        try\n        {\n            emf = Persistence.createEntityManagerFactory(EthConstants.PU, props);\n        }\n        catch (ClientResolverException ex)\n        {\n            LOGGER.error(\"Not able to find dependency for Kundera \" + props.get(EthConstants.KUNDERA_DIALECT)\n                    + \" client.\", ex);\n            throw new KunderaException(\"Not able to find dependency for Kundera \"\n                    + props.get(EthConstants.KUNDERA_DIALECT) + \" client.\", ex);\n        }\n        LOGGER.info(\"Kundera EMF created...\");\n        em = emf.createEntityManager();\n        LOGGER.info(\"Kundera EM created...\");\n    }\n\n    /**\n     * Initialize properties.\n     *\n     * @return the property reader\n     */\n    private PropertyReader initializeProperties()\n    {\n        return new PropertyReader(EthConstants.KUNDERA_ETHEREUM_PROPERTIES);\n    }\n\n    /**\n     * Gets the block number with raw data.\n     * \n     * It is used for logging purpose\n     *\n     * @param blockNumberRaw\n     *            the block number raw\n     * @return the block number with raw data\n     */\n    private String getBlockNumberWithRawData(String blockNumberRaw)\n    {\n        return Numeric.decodeQuantity(blockNumberRaw) + \"(\" + blockNumberRaw + \")\";\n    }\n\n    /**\n     * Gets the EntityManager.\n     *\n     * @return the EntityManager\n     */\n    public EntityManager getEntityManager()\n    {\n        return emf.createEntityManager();\n    }\n\n    /**\n     * Destroy.\n     */\n    public void destroy()\n    {\n        if (em != null)\n        {\n            em.close();\n            LOGGER.info(\"Kundera EM closed...\");\n        }\n\n        if (emf != null)\n        {\n            emf.close();\n            LOGGER.info(\"Kundera EMF closed...\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/util/EthConstants.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.blockchain.util;\n\n/**\n * The Class EthConstants.\n * \n * @author devender.yadav\n */\npublic class EthConstants\n{\n\n    /** The Constant PU. */\n    public static final String PU = \"kundera_pu\";\n\n    /** The Constant KUNDERA_ETHEREUM_PROPERTIES. */\n    public static final String KUNDERA_ETHEREUM_PROPERTIES = \"kundera-ethereum.properties\";\n\n    /** The Constant DATABASE_TYPE. */\n    public static final String DATABASE_TYPE = \"database.type\";\n\n    /** The Constant DATABASE_HOST. */\n    public static final String DATABASE_HOST = \"database.host\";\n\n    /** The Constant DATABASE_PORT. */\n    public static final String DATABASE_PORT = \"database.port\";\n\n    /** The Constant DATABASE_NAME. */\n    public static final String DATABASE_NAME = \"database.name\";\n\n    /** The Constant DATABASE_USERNAME. */\n    public static final String DATABASE_USERNAME = \"database.username\";\n\n    /** The Constant DATABASE_PASSWORD. */\n    public static final String DATABASE_PASSWORD = \"database.password\";\n\n    /** The Constant SCHEMA_AUTO_GENERATE. */\n    public static final String SCHEMA_AUTO_GENERATE = \"schema.auto.generate\";\n\n    /** The Constant SCHEMA_DROP_EXISTING. */\n    public static final String SCHEMA_DROP_EXISTING = \"schema.drop.existing\";\n\n    /** The Constant ETHEREUM_NODE_ENDPOINT. */\n    public static final String ETHEREUM_NODE_ENDPOINT = \"ethereum.node.endpoint\";\n\n    /** The Constant ETHEREUM_NODE_OS. */\n    public static final String ETHEREUM_NODE_OS = \"ethereum.node.os\";\n\n    /** The Constant KUNDERA_CLIENT_LOOKUP_CLASS. */\n    public static final String KUNDERA_CLIENT_LOOKUP_CLASS = \"kundera.client.lookup.class\";\n\n    /** The Constant KUNDERA_NODES. */\n    public static final String KUNDERA_NODES = \"kundera.nodes\";\n\n    /** The Constant KUNDERA_PORT. */\n    public static final String KUNDERA_PORT = \"kundera.port\";\n\n    /** The Constant KUNDERA_KEYSPACE. */\n    public static final String KUNDERA_KEYSPACE = \"kundera.keyspace\";\n\n    /** The Constant KUNDERA_DIALECT. */\n    public static final String KUNDERA_DIALECT = \"kundera.dialect\";\n\n    /** The Constant KUNDERA_CLIENT. */\n    public static final String KUNDERA_CLIENT = \"kundera.client\";\n\n    /** The Constant KUNDERA_USERNAME. */\n    public static final String KUNDERA_USERNAME = \"kundera.username\";\n\n    /** The Constant KUNDERA_PASSWORD. */\n    public static final String KUNDERA_PASSWORD = \"kundera.password\";\n\n    /** The Constant KUNDERA_DDL_AUTO_PREPARE. */\n    public static final String KUNDERA_DDL_AUTO_PREPARE = \"kundera.ddl.auto.prepare\";\n\n    /** The Constant KUNDERA_MONGODB_CLIENT_FACTORY. */\n    public static final String KUNDERA_MONGODB_CLIENT_FACTORY = \"com.impetus.client.mongodb.MongoDBClientFactory\";\n\n    /** The Constant KUNDERA_RETHINKDB_CLIENT_FACTORY. */\n    public static final String KUNDERA_RETHINKDB_CLIENT_FACTORY = \"com.impetus.client.rethink.RethinkDBClientFactory\";\n\n    /** The Constant KUNDERA_CASSANDRA_CLIENT_FACTORY. */\n    public static final String KUNDERA_CASSANDRA_CLIENT_FACTORY = \"com.impetus.client.cassandra.thrift.ThriftClientFactory\";\n\n    /** The Constant KUNDERA_HBASE_CLIENT_FACTORY. */\n    public static final String KUNDERA_HBASE_CLIENT_FACTORY = \"com.impetus.client.hbase.HBaseClientFactory\";\n\n    /** The Constant KUNDERA_KUDU_CLIENT_FACTORY. */\n    public static final String KUNDERA_KUDU_CLIENT_FACTORY = \"com.impetus.client.kudu.KuduDBClientFactory\";\n\n    /** The Constant KUNDERA_REDIS_CLIENT_FACTORY. */\n    public static final String KUNDERA_REDIS_CLIENT_FACTORY = \"com.impetus.client.redis.RedisClientFactory\";\n\n    /** The Constant KUNDERA_COUCHDB_CLIENT_FACTORY. */\n    public static final String KUNDERA_COUCHDB_CLIENT_FACTORY = \"com.impetus.client.couchdb.CouchDBClientFactory\";\n\n    /** The Constant KUNDERA_ONS_CLIENT_FACTORY. */\n    public static final String KUNDERA_ONS_CLIENT_FACTORY = \"com.impetus.client.oraclenosql.OracleNoSQLClientFactory\";\n\n    /**\n     * Instantiates a new constants.\n     */\n    private EthConstants()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/util/KunderaPropertyBuilder.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.blockchain.util;\n\nimport java.util.EnumMap;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.blockchain.ethereum.Datasource;\n\n/**\n * The Class KunderaPropertyBuilder.\n */\npublic class KunderaPropertyBuilder\n{\n\n    private static final String _3_0_0 = \"3.0.0\";\n\n    private static final String CQL_VERSION = \"cql.version\";\n\n    private static final String CASSANDRA = \"cassandra\";\n\n    /** The Constant LOGGER. */\n    private static final Logger LOGGER = LoggerFactory.getLogger(PropertyReader.class);\n\n    /** The client name to factory map. */\n    private static Map<Datasource, String> clientNameToFactoryMap = new EnumMap<>(Datasource.class);\n\n    static\n    {\n        clientNameToFactoryMap.put(Datasource.MONGODB, EthConstants.KUNDERA_MONGODB_CLIENT_FACTORY);\n        clientNameToFactoryMap.put(Datasource.RETHINKDB, EthConstants.KUNDERA_RETHINKDB_CLIENT_FACTORY);\n        clientNameToFactoryMap.put(Datasource.CASSANDRA, EthConstants.KUNDERA_CASSANDRA_CLIENT_FACTORY);\n        clientNameToFactoryMap.put(Datasource.HBASE, EthConstants.KUNDERA_HBASE_CLIENT_FACTORY);\n        clientNameToFactoryMap.put(Datasource.KUDU, EthConstants.KUNDERA_KUDU_CLIENT_FACTORY);\n        clientNameToFactoryMap.put(Datasource.REDIS, EthConstants.KUNDERA_REDIS_CLIENT_FACTORY);\n        clientNameToFactoryMap.put(Datasource.COUCHDB, EthConstants.KUNDERA_COUCHDB_CLIENT_FACTORY);\n        clientNameToFactoryMap.put(Datasource.KVSTORE, EthConstants.KUNDERA_ONS_CLIENT_FACTORY);\n    }\n\n    /**\n     * Instantiates a new kundera property builder.\n     */\n    private KunderaPropertyBuilder()\n    {\n    }\n\n    /**\n     * Populate persistence unit properties.\n     *\n     * @param reader\n     *            the reader\n     * @return the map\n     */\n    public static Map<String, String> populatePersistenceUnitProperties(PropertyReader reader)\n    {\n\n        String dbType = reader.getProperty(EthConstants.DATABASE_TYPE);\n        String host = reader.getProperty(EthConstants.DATABASE_HOST);\n        String port = reader.getProperty(EthConstants.DATABASE_PORT);\n        String dbName = reader.getProperty(EthConstants.DATABASE_NAME);\n\n        propertyNullCheck(dbType, host, port, dbName);\n\n        String username = reader.getProperty(EthConstants.DATABASE_USERNAME);\n        String pswd = reader.getProperty(EthConstants.DATABASE_PASSWORD);\n\n        Map<String, String> props = new HashMap<>();\n\n        props.put(EthConstants.KUNDERA_CLIENT_LOOKUP_CLASS, getKunderaClientToLookupClass(dbType));\n        props.put(EthConstants.KUNDERA_NODES, host);\n        props.put(EthConstants.KUNDERA_PORT, port);\n        props.put(EthConstants.KUNDERA_KEYSPACE, dbName);\n        props.put(EthConstants.KUNDERA_DIALECT, dbType);\n\n        if (username != null && !username.isEmpty() && pswd != null)\n        {\n            props.put(EthConstants.KUNDERA_USERNAME, username);\n            props.put(EthConstants.KUNDERA_PASSWORD, pswd);\n        }\n\n        if (dbType.equalsIgnoreCase(CASSANDRA))\n        {\n            props.put(CQL_VERSION, _3_0_0);\n        }\n\n        boolean schemaAutoGen = Boolean.parseBoolean(reader.getProperty(EthConstants.SCHEMA_AUTO_GENERATE));\n        boolean schemaDropExisting = Boolean.parseBoolean(reader.getProperty(EthConstants.SCHEMA_DROP_EXISTING));\n\n        if (schemaAutoGen)\n        {\n            if (schemaDropExisting)\n            {\n                props.put(EthConstants.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n            }\n            else\n            {\n                props.put(EthConstants.KUNDERA_DDL_AUTO_PREPARE, \"update\");\n            }\n        }\n        LOGGER.info(\"Kundera properties : \" + props);\n        return props;\n    }\n\n    /**\n     * Property null check.\n     *\n     * @param dbType\n     *            the db type\n     * @param host\n     *            the host\n     * @param port\n     *            the port\n     * @param dbName\n     *            the db name\n     */\n    private static void propertyNullCheck(String dbType, String host, String port, String dbName)\n    {\n\n        if (dbType == null || dbType.isEmpty())\n        {\n            LOGGER.error(\"Property '\" + EthConstants.DATABASE_TYPE + \"' can't be null or empty\");\n            throw new KunderaException(\"Property '\" + EthConstants.DATABASE_TYPE + \"' can't be null or empty\");\n        }\n\n        if (host == null || host.isEmpty())\n        {\n            LOGGER.error(\"Property '\" + EthConstants.DATABASE_HOST + \"' can't be null or empty\");\n            throw new KunderaException(\"Property '\" + EthConstants.DATABASE_HOST + \"' can't be null or empty\");\n        }\n\n        if (port == null || port.isEmpty())\n        {\n            LOGGER.error(\"Property '\" + EthConstants.DATABASE_PORT + \"' can't be null or empty\");\n            throw new KunderaException(\"Property '\" + EthConstants.DATABASE_PORT + \"' can't be null or empty\");\n        }\n\n        if (dbName == null || dbName.isEmpty())\n        {\n            LOGGER.error(\"Property'\" + EthConstants.DATABASE_NAME + \"' can't be null or empty\");\n            throw new KunderaException(\"Property '\" + EthConstants.DATABASE_NAME + \"' can't be null or empty\");\n        }\n\n    }\n\n    /**\n     * Gets the kundera client to lookup class.\n     *\n     * @param client\n     *            the client\n     * @return the kundera client to lookup class\n     */\n    private static String getKunderaClientToLookupClass(String client)\n    {\n\n        Datasource datasource;\n        try\n        {\n            datasource = Datasource.valueOf(client.toUpperCase());\n        }\n        catch (IllegalArgumentException ex)\n        {\n            LOGGER.error(client + \" is not supported!\", ex);\n            throw new KunderaException(client + \" is not supported!\", ex);\n        }\n\n        return clientNameToFactoryMap.get(datasource);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-ethereum/src/main/java/com/impetus/kundera/blockchain/util/PropertyReader.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.blockchain.util;\n\nimport java.util.Map;\n\nimport org.apache.commons.configuration.Configuration;\nimport org.apache.commons.configuration.ConfigurationConverter;\nimport org.apache.commons.configuration.ConfigurationException;\nimport org.apache.commons.configuration.PropertiesConfiguration;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * The Class PropertyReader.\n * \n * @author devender.yadav\n */\npublic class PropertyReader\n{\n\n    /** The Constant LOGGER. */\n    private static final Logger LOGGER = LoggerFactory.getLogger(PropertyReader.class);\n\n    /** The kundera blockchain props. */\n    private static Map<String, String> kunderaBlockchainProps;\n\n    /**\n     * Instantiates a new property reader.\n     *\n     * @param fileName\n     *            the file name\n     */\n    public PropertyReader(String fileName)\n    {\n        kunderaBlockchainProps = getProperties(fileName);\n    }\n\n    /**\n     * Gets the properties.\n     *\n     * @param fileName\n     *            the file name\n     * @return the properties\n     */\n    private static Map<String, String> getProperties(String fileName)\n    {\n        if (kunderaBlockchainProps == null || kunderaBlockchainProps.isEmpty())\n        {\n            Configuration config = null;\n            try\n            {\n                config = new PropertiesConfiguration(fileName);\n\n            }\n            catch (ConfigurationException ce)\n            {\n                LOGGER.error(\"Not able to load properties from  \" + fileName + \" file. \", ce);\n                throw new KunderaException(\"Not able to load properties from  \" + fileName + \" file. \", ce);\n            }\n            kunderaBlockchainProps = (Map) ConfigurationConverter.getProperties(config);\n            LOGGER.info(\"Properties loaded from \" + fileName + \" file. Properties: \" + kunderaBlockchainProps);\n        }\n        return kunderaBlockchainProps;\n    }\n\n    /**\n     * Gets the property.\n     *\n     * @param key\n     *            the key\n     * @return the property\n     */\n    public String getProperty(String key)\n    {\n        return kunderaBlockchainProps.get(key);\n    }\n\n    /**\n     * Gets the all properties.\n     *\n     * @return the all properties\n     */\n    public Map<String, String> getAllProperties()\n    {\n        return kunderaBlockchainProps;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-ethereum/src/main/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\n\t<persistence-unit name=\"kundera_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t</persistence-unit>\n\n</persistence>\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t<artifactId>kundera-hbase-parent</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-hbase</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-hbase</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<hadoop.version>2.2.0</hadoop.version>\n\t\t<hbase.version>0.96.1.1-hadoop2</hbase.version>\n\t\t<thrift.version>0.9.0</thrift.version>\n\t</properties>\n\n\t<!-- Dependencies -->\n\t<dependencies>\n\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hbase</groupId>\n\t\t\t<artifactId>hbase-client</artifactId>\n\t\t\t<version>${hbase.version}</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.slf4j</groupId>\n\t\t\t\t\t<artifactId>slf4j-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hbase</groupId>\n\t\t\t<artifactId>hbase-server</artifactId>\n\t\t\t<version>${hbase.version}</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.slf4j</groupId>\n\t\t\t\t\t<artifactId>slf4j-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hbase</groupId>\n\t\t\t<artifactId>hbase-server</artifactId>\n\t\t\t<version>${hbase.version}</version>\n\t\t\t<classifier>tests</classifier>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hbase</groupId>\n\t\t\t<artifactId>hbase-common</artifactId>\n\t\t\t<version>${hbase.version}</version>\n\t\t\t<classifier>tests</classifier>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.thrift</groupId>\n\t\t\t<artifactId>libthrift</artifactId>\n\t\t\t<version>${thrift.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hbase</groupId>\n\t\t\t<artifactId>hbase-common</artifactId>\n\t\t\t<version>${hbase.version}</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.slf4j</groupId>\n\t\t\t\t\t<artifactId>slf4j-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hadoop</groupId>\n\t\t\t<artifactId>hadoop-common</artifactId>\n\t\t\t<version>${hadoop.version}</version>\n\t\t</dependency>\n\n\n\t</dependencies>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n\n</project>\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/HBaseClient.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase;\n\nimport java.io.IOException;\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Queue;\nimport java.util.Set;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.hbase.client.HTableInterface;\nimport org.apache.hadoop.hbase.client.HTablePool;\nimport org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;\nimport org.apache.hadoop.hbase.filter.Filter;\nimport org.apache.hadoop.hbase.filter.FilterList;\nimport org.apache.hadoop.hbase.filter.KeyOnlyFilter;\nimport org.apache.hadoop.hbase.filter.SingleColumnValueFilter;\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.admin.DataHandler;\nimport com.impetus.client.hbase.admin.HBaseDataHandler;\nimport com.impetus.client.hbase.admin.HBaseDataHandler.HBaseDataWrapper;\nimport com.impetus.client.hbase.query.HBaseQuery;\nimport com.impetus.client.hbase.utils.HBaseUtils;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.lifecycle.states.RemovedState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.model.annotation.DefaultEntityAnnotationProcessor;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * HBase client.\n * \n * @author impetus\n */\npublic class HBaseClient extends ClientBase implements Client<HBaseQuery>, Batcher, ClientPropertiesSetter\n{\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(HBaseClient.class);\n\n    /** The handler. */\n    DataHandler handler;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /** The nodes. */\n    private List<Node> nodes = new ArrayList<Node>();\n\n    /** The batch size. */\n    private int batchSize;\n\n    /**\n     * Instantiates a new hbase client.\n     * \n     * @param indexManager\n     *            the index manager\n     * @param conf\n     *            the conf\n     * @param hTablePool\n     *            the h table pool\n     * @param reader\n     *            the reader\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param externalProperties\n     *            the external properties\n     * @param clientMetadata\n     *            the client metadata\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public HBaseClient(IndexManager indexManager, Configuration conf, HTablePool hTablePool, EntityReader reader,\n\n    String persistenceUnit, Map<String, Object> externalProperties, ClientMetadata clientMetadata,\n\n    final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata, externalProperties, persistenceUnit);\n        this.indexManager = indexManager;\n        this.handler = new HBaseDataHandler(kunderaMetadata, conf, hTablePool);\n        this.reader = reader;\n        this.clientMetadata = clientMetadata;\n        getBatchSize(persistenceUnit, this.externalProperties);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.Object, java.util.List)\n     */\n    @Override\n    public Object find(Class entityClass, Object rowId)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        List<String> relationNames = entityMetadata.getRelationNames();\n        // columnFamily has a different meaning for HBase, so it won't be used\n        // here\n        String tableName = entityMetadata.getSchema();\n        Object enhancedEntity = null;\n        List results = null;\n        try\n        {\n            if (rowId == null)\n            {\n                return null;\n            }\n\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    entityMetadata.getPersistenceUnit());\n\n            if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n            {\n                rowId = KunderaCoreUtils.prepareCompositeKey(entityMetadata, rowId);\n            }\n\n            results = fetchEntity(entityClass, rowId, entityMetadata, relationNames, tableName, results, null, null);\n\n            if (results != null && !results.isEmpty())\n            {\n                enhancedEntity = results.get(0);\n            }\n        }\n        catch (IOException e)\n        {\n            log.error(\"Error during find by id, Caused by: .\", e);\n            throw new KunderaException(e);\n        }\n        return enhancedEntity;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.Object[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... rowIds)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        if (rowIds == null)\n        {\n            return null;\n        }\n        List results = new ArrayList<E>();\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n\n        EntityType entityType = metaModel.entity(entityClass);\n\n        List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n        try\n        {\n            if (!subManagedType.isEmpty())\n            {\n                for (AbstractManagedType subEntity : subManagedType)\n                {\n                    EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                            subEntity.getJavaType());\n                    results = handler.readAll(subEntityMetadata.getSchema(), subEntityMetadata.getEntityClazz(),\n                            subEntityMetadata, Arrays.asList(rowIds), subEntityMetadata.getRelationNames());\n                    // Result will not be empty for match sub entity.\n                    if (!results.isEmpty())\n                    {\n                        break;\n                    }\n                }\n            }\n            else\n            {\n\n                results = handler.readAll(entityMetadata.getSchema(), entityMetadata.getEntityClazz(), entityMetadata,\n                        Arrays.asList(rowIds), entityMetadata.getRelationNames());\n            }\n        }\n        catch (IOException ioex)\n        {\n            log.error(\"Error during find All , Caused by: .\", ioex);\n            throw new KunderaException(ioex);\n        }\n\n        return results;\n    }\n\n    /**\n     * (non-Javadoc).\n     * \n     * @param <E>\n     *            the element type\n     * @param entityClass\n     *            the entity class\n     * @param col\n     *            the col\n     * @return the list\n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     *      java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> col)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, getPersistenceUnit(),\n                entityClass);\n        List<E> entities = new ArrayList<E>();\n        Map<String, Field> columnFamilyNameToFieldMap = MetadataUtils.createSuperColumnsFieldMap(entityMetadata,\n                kunderaMetadata);\n        for (String columnFamilyName : col.keySet())\n        {\n            String entityId = col.get(columnFamilyName);\n            if (entityId != null)\n            {\n                E e = null;\n                try\n                {\n                    List results = new ArrayList();\n                    fetchEntity(entityClass, entityId, entityMetadata, entityMetadata.getRelationNames(),\n                            entityMetadata.getSchema(), results, null, null);\n                    if (results != null)\n                    {\n                        e = (E) results.get(0);\n                    }\n                }\n                catch (IOException ioex)\n                {\n                    log.error(\"Error during find for embedded entities, Caused by: .\", ioex);\n\n                    throw new KunderaException(ioex);\n                }\n\n                Field columnFamilyField = columnFamilyNameToFieldMap.get(columnFamilyName.substring(0,\n                        columnFamilyName.indexOf(\"|\")));\n                Object columnFamilyValue = PropertyAccessorHelper.getObject(e, columnFamilyField);\n                if (Collection.class.isAssignableFrom(columnFamilyField.getType()))\n                {\n                    entities.addAll((Collection) columnFamilyValue);\n                }\n                else\n                {\n                    entities.add((E) columnFamilyValue);\n                }\n            }\n        }\n        return entities;\n    }\n\n    /**\n     * Method to find entities using JPQL(converted into FilterList.)\n     * \n     * @param <E>\n     *            parameterized entity class.\n     * @param entityClass\n     *            entity class.\n     * @param metadata\n     *            entity metadata.\n     * @param f\n     *            the f\n     * @param filterClausequeue\n     *            the filter clausequeue\n     * @param columns\n     *            the columns\n     * @return list of entities.\n     */\n    public <E> List<E> findByQuery(Class<E> entityClass, EntityMetadata metadata, Filter f, Queue filterClausequeue,\n            String... columns)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        List<String> relationNames = entityMetadata.getRelationNames();\n        // columnFamily has a different meaning for HBase, so it won't be used\n        // here\n        String tableName = entityMetadata.getSchema();\n        List results = null;\n\n        FilterList filter = new FilterList();\n        if (f != null)\n        {\n            filter.addFilter(f);\n        }\n        if (isFindKeyOnly(metadata, columns))\n        {\n            columns = null;\n            filter.addFilter(new KeyOnlyFilter());\n        }\n\n        try\n        {\n            results = fetchEntity(entityClass, null, entityMetadata, relationNames, tableName, results, filter,\n                    filterClausequeue, columns);\n        }\n        catch (IOException ioex)\n        {\n            log.error(\"Error during find by query, Caused by: .\", ioex);\n            throw new KunderaException(ioex);\n        }\n        return results != null ? results : new ArrayList();\n    }\n\n    /**\n     * Handles find by range query for given start and end row key range values.\n     * \n     * @param <E>\n     *            parameterized entity class.\n     * @param entityClass\n     *            entity class.\n     * @param metadata\n     *            entity metadata\n     * @param startRow\n     *            start row.\n     * @param endRow\n     *            end row.\n     * @param columns\n     *            the columns\n     * @param f\n     *            the f\n     * @param filterClausequeue\n     *            the filter clausequeue\n     * @return collection holding results.\n     */\n    public <E> List<E> findByRange(Class<E> entityClass, EntityMetadata metadata, byte[] startRow, byte[] endRow,\n            String[] columns, Filter f, Queue filterClausequeue)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        // columnFamily has a different meaning for HBase, so it won't be used\n        // here\n        String tableName = entityMetadata.getSchema();\n        List results = new ArrayList();\n\n        FilterList filter = new FilterList();\n        if (f != null)\n        {\n            filter.addFilter(f);\n        }\n        if (isFindKeyOnly(metadata, columns))\n        {\n            columns = null;\n            filter.addFilter(new KeyOnlyFilter());\n        }\n\n        try\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    entityMetadata.getPersistenceUnit());\n\n            EntityType entityType = metaModel.entity(entityClass);\n\n            List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n\n            if (!subManagedType.isEmpty())\n            {\n                for (AbstractManagedType subEntity : subManagedType)\n                {\n                    EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                            subEntity.getJavaType());\n                    List found = handler.readDataByRange(tableName, subEntityMetadata.getEntityClazz(),\n                            subEntityMetadata, startRow, endRow, columns, filter);\n                    results.addAll(found);\n                }\n            }\n            else\n            {\n                results = handler.readDataByRange(tableName, entityClass, metadata, startRow, endRow, columns, filter);\n            }\n            if (showQuery && filterClausequeue.size() > 0)\n            {\n                KunderaCoreUtils.printQueryWithFilterClause(filterClausequeue, entityMetadata.getTableName());\n            }\n        }\n        catch (IOException ioex)\n        {\n            log.error(\"Error during find by range, Caused by: .\", ioex);\n            throw new KunderaException(ioex);\n        }\n        return results;\n    }\n\n    /**\n     * Checks if is find key only.\n     * \n     * @param metadata\n     *            the metadata\n     * @param columns\n     *            the columns\n     * @return true, if is find key only\n     */\n    private boolean isFindKeyOnly(EntityMetadata metadata, String[] columns)\n    {\n        int noOFColumnsToFind = 0;\n        boolean findIdOnly = false;\n        if (columns != null)\n        {\n            for (String column : columns)\n            {\n                if (column != null)\n                {\n                    if (column.equals(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName()))\n                    {\n                        noOFColumnsToFind++;\n                        findIdOnly = true;\n                    }\n                    else\n                    {\n                        noOFColumnsToFind++;\n                        findIdOnly = false;\n                    }\n                }\n            }\n        }\n        if (noOFColumnsToFind == 1 && findIdOnly)\n        {\n            return true;\n        }\n        return false;\n    }\n\n    /**\n     * Close handlers instance and reinstate pu properties.\n     * \n     */\n    @Override\n    public void close()\n    {\n        handler.shutdown();\n        externalProperties = null;\n    }\n\n    /**\n     * Setter for filter.\n     * \n     * @param filter\n     *            filter.\n     */\n    public void setFilter(Filter filter)\n    {\n        ((HBaseDataHandler) handler).setFilter(filter);\n    }\n\n    /**\n     * Adds the filter.\n     * \n     * @param columnFamily\n     *            the column family\n     * @param filter\n     *            the filter\n     */\n    public void addFilter(final String columnFamily, Filter filter)\n    {\n        ((HBaseDataHandler) handler).addFilter(columnFamily, filter);\n    }\n\n    /**\n     * Reset filter.\n     */\n    public void resetFilter()\n    {\n        ((HBaseDataHandler) handler).resetFilter();\n    }\n\n    /**\n     * Setter for filter.\n     * \n     * @param fetchSize\n     *            the new fetch size\n     */\n    public void setFetchSize(int fetchSize)\n    {\n        ((HBaseDataHandler) handler).setFetchSize(fetchSize);\n    }\n\n    /**\n     * On persist.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @param id\n     *            the id\n     * @param relations\n     *            the relations\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> relations)\n    {\n        String tableName = entityMetadata.getSchema();\n\n        try\n        {\n            // Write data to HBase\n            handler.writeData(tableName, entityMetadata, entity, id, relations, showQuery);\n        }\n        catch (IOException e)\n        {\n            throw new PersistenceException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera\n     * .persistence.context.jointable.JoinTableData)\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        String joinTableName = joinTableData.getJoinTableName();\n        String invJoinColumnName = joinTableData.getInverseJoinColumnName();\n        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();\n\n        for (Object key : joinTableRecords.keySet())\n        {\n            Set<Object> values = joinTableRecords.get(key);\n            Object joinColumnValue = key;\n\n            Map<String, Object> columns = new HashMap<String, Object>();\n            for (Object childValue : values)\n            {\n                Object invJoinColumnValue = childValue;\n                columns.put(invJoinColumnName + \"_\" + invJoinColumnValue, invJoinColumnValue);\n            }\n\n            if (columns != null && !columns.isEmpty())\n            {\n                try\n                {\n                    handler.createTableIfDoesNotExist(joinTableData.getSchemaName(), joinTableName);\n                    handler.writeJoinTableData(joinTableData.getSchemaName(), joinColumnValue, columns, joinTableName);\n                    KunderaCoreUtils.printQuery(\"Persist Join Table:\" + joinTableName, showQuery);\n                }\n                catch (IOException e)\n                {\n                    throw new PersistenceException(e);\n                }\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#getForeignKeysFromJoinTable(java.lang\n     * .String, java.lang.String, java.lang.String,\n     * com.impetus.kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.persistence.handler.impl.EntitySaveGraph)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String joinTableName, String joinColumnName,\n            String inverseJoinColumnName, Object parentId, Class columnJavaType)\n    {\n        return handler.getForeignKeysFromJoinTable(schemaName, joinTableName, parentId, inverseJoinColumnName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n        try\n        {\n            handler.deleteRow(columnValue, schemaName, tableName);\n            KunderaCoreUtils.printQuery(\"Delete data from \" + tableName + \" for PK \" + columnValue, showQuery);\n        }\n        catch (IOException ioex)\n        {\n            log.error(\"Error during get columns by key. Caused by: .\", ioex);\n            throw new PersistenceException(ioex);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    public void delete(Object entity, Object pKey)\n    {\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                metadata.getPersistenceUnit());\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(metadata.getEntityClazz());\n        List<String> secondaryTables = ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation())\n                .getSecondaryTablesName();\n        secondaryTables.add(metadata.getTableName());\n        if (metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType()))\n        {\n            pKey = KunderaCoreUtils.prepareCompositeKey(metadata, pKey);\n        }\n\n        for (String colTableName : secondaryTables)\n        {\n            deleteByColumn(metadata.getSchema(), colTableName,\n                    ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName(), pKey);\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n\n        String columnFamilyName = m.getTableName();\n\n        byte[] valueInBytes = HBaseUtils.getBytes(colValue);\n        SingleColumnValueFilter f = new SingleColumnValueFilter(Bytes.toBytes(columnFamilyName),\n                Bytes.toBytes(colName), CompareOp.EQUAL, valueInBytes);\n\n        List output = new ArrayList();\n        try\n        {\n            List<AbstractManagedType> subManagedType = getSubManagedType(entityClazz, m);\n\n            if (!subManagedType.isEmpty())\n            {\n                for (AbstractManagedType subEntity : subManagedType)\n                {\n                    EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                            subEntity.getJavaType());\n                    List results = ((HBaseDataHandler) handler).scanData(f, subEntityMetadata.getSchema(),\n                            subEntityMetadata.getEntityClazz(), subEntityMetadata, columnFamilyName, colName);\n                    if (!results.isEmpty())\n                    {\n                        output.addAll(results);\n                    }\n                }\n            }\n            else\n            {\n                return ((HBaseDataHandler) handler).scanData(f, m.getSchema(), entityClazz, m, columnFamilyName,\n                        colName);\n            }\n        }\n        catch (IOException ioe)\n        {\n            log.error(\"Error during find By Relation, Caused by: .\", ioe);\n            throw new KunderaException(ioe);\n        }\n        catch (InstantiationException ie)\n        {\n            log.error(\"Error during find By Relation, Caused by: .\", ie);\n            throw new KunderaException(ie);\n        }\n        catch (IllegalAccessException iae)\n        {\n            log.error(\"Error during find By Relation, Caused by: .\", iae);\n            throw new KunderaException(iae);\n        }\n\n        return output;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<HBaseQuery> getQueryImplementor()\n    {\n        return HBaseQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n\n        byte[] valueInBytes = HBaseUtils.getBytes(columnValue);\n        Filter f = new SingleColumnValueFilter(Bytes.toBytes(tableName), Bytes.toBytes(columnName), CompareOp.EQUAL,\n                valueInBytes);\n        KeyOnlyFilter keyFilter = new KeyOnlyFilter();\n        FilterList filterList = new FilterList(f, keyFilter);\n        try\n        {\n            return handler.scanRowyKeys(filterList, schemaName, tableName, columnName + \"_\" + columnValue, m\n                    .getIdAttribute().getBindableJavaType());\n        }\n        catch (IOException e)\n        {\n            log.error(\"Error while executing findIdsByColumn(), Caused by: .\", e);\n            throw new KunderaException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.api.Batcher#addBatch(com.impetus.kundera\n     * .graph.Node)\n     */\n    public void addBatch(Node node)\n    {\n        if (node != null)\n        {\n            nodes.add(node);\n        }\n        onBatchLimit();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#getBatchSize()\n     */\n    @Override\n    public int getBatchSize()\n    {\n        return batchSize;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#clear()\n     */\n    @Override\n    public void clear()\n    {\n        if (nodes != null)\n        {\n            nodes.clear();\n            nodes = new ArrayList<Node>();\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#executeBatch()\n     */\n    @Override\n    public int executeBatch()\n    {\n        Map<HTableInterface, List<HBaseDataWrapper>> data = new HashMap<HTableInterface, List<HBaseDataWrapper>>();\n\n        try\n        {\n            for (Node node : nodes)\n            {\n                if (node.isDirty())\n                {\n                    node.handlePreEvent();\n                    HTableInterface hTable = null;\n                    Object rowKey = node.getEntityId();\n                    Object entity = node.getData();\n                    if (node.isInState(RemovedState.class))\n                    {\n                        delete(entity, rowKey);\n                    }\n                    else\n                    {\n                        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                                node.getDataClass());\n\n                        HBaseDataWrapper columnWrapper = new HBaseDataHandler.HBaseDataWrapper(rowKey,\n                                new java.util.HashMap<String, Attribute>(), entity, metadata.getTableName());\n\n                        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                                .getMetamodel(metadata.getPersistenceUnit());\n\n                        EntityType entityType = metaModel.entity(node.getDataClass());\n\n                        List<HBaseDataWrapper> embeddableData = new ArrayList<HBaseDataHandler.HBaseDataWrapper>();\n\n                        hTable = ((HBaseDataHandler) handler).gethTable(metadata.getSchema());\n                        ((HBaseDataHandler) handler).preparePersistentData(metadata.getSchema(),\n                                metadata.getTableName(), entity, rowKey, metaModel, entityType.getAttributes(),\n                                columnWrapper, embeddableData, showQuery);\n\n                        List<HBaseDataWrapper> dataSet = null;\n                        if (data.containsKey(hTable))\n                        {\n                            dataSet = data.get(metadata.getTableName());\n                            addRecords(columnWrapper, embeddableData, dataSet);\n                        }\n                        else\n                        {\n                            dataSet = new ArrayList<HBaseDataHandler.HBaseDataWrapper>();\n                            addRecords(columnWrapper, embeddableData, dataSet);\n                            data.put(hTable, dataSet);\n                        }\n                    }\n                    node.handlePostEvent();\n                }\n            }\n\n            if (!data.isEmpty())\n            {\n                ((HBaseDataHandler) handler).batch_insert(data);\n            }\n            return data.size();\n        }\n        catch (IOException ioex)\n        {\n            log.error(\"Error while executing batch insert/update, Caused by: .\", ioex);\n            throw new KunderaException(ioex);\n        }\n\n    }\n\n    /**\n     * Add records to data wrapper.\n     * \n     * @param columnWrapper\n     *            column wrapper\n     * @param embeddableData\n     *            embeddable data\n     * @param dataSet\n     *            data collection set\n     */\n    private void addRecords(HBaseDataWrapper columnWrapper, List<HBaseDataWrapper> embeddableData,\n            List<HBaseDataWrapper> dataSet)\n    {\n        dataSet.add(columnWrapper);\n\n        if (!embeddableData.isEmpty())\n        {\n            dataSet.addAll(embeddableData);\n        }\n    }\n\n    /**\n     * Check on batch limit.\n     */\n    private void onBatchLimit()\n    {\n        if (batchSize > 0 && batchSize == nodes.size())\n        {\n            executeBatch();\n            nodes.clear();\n        }\n    }\n\n    /**\n     * Gets the batch size.\n     * \n     * @param persistenceUnit\n     *            the persistence unit\n     * @param puProperties\n     *            the pu properties\n     * @return the batch size\n     */\n    private void getBatchSize(String persistenceUnit, Map<String, Object> puProperties)\n    {\n        String batch_Size = puProperties != null ? (String) puProperties.get(PersistenceProperties.KUNDERA_BATCH_SIZE)\n                : null;\n        if (batch_Size != null)\n        {\n            setBatchSize(Integer.valueOf(batch_Size));\n        }\n        else\n        {\n            PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\n                    persistenceUnit);\n            setBatchSize(puMetadata.getBatchSize());\n        }\n    }\n\n    /**\n     * Sets the batch size.\n     * \n     * @param batch_Size\n     *            the new batch size\n     */\n    void setBatchSize(int batch_Size)\n    {\n        this.batchSize = batch_Size;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientPropertiesSetter#populateClientProperties\n     * (com.impetus.kundera.client.Client, java.util.Map)\n     */\n    @Override\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        new HBaseClientProperties().populateClientProperties(client, properties);\n    }\n\n    /**\n     * Reset.\n     */\n    public void reset()\n    {\n        ((HBaseDataHandler) handler).reset();\n    }\n\n    /**\n     * Next.\n     * \n     * @param m\n     *            the m\n     * @return the object\n     */\n    public Object next(EntityMetadata m)\n    {\n        return ((HBaseDataHandler) handler).next(m);\n    }\n\n    /**\n     * Checks for next.\n     * \n     * @return true, if successful\n     */\n    public boolean hasNext()\n    {\n        return ((HBaseDataHandler) handler).hasNext();\n    }\n\n    /**\n     * Gets the handle.\n     * \n     * @return the handle\n     */\n    public HBaseDataHandler getHandle()\n    {\n        return ((HBaseDataHandler) handler).getHandle();\n    }\n\n    /**\n     * Fetch entity.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param rowId\n     *            the row id\n     * @param entityMetadata\n     *            the entity metadata\n     * @param relationNames\n     *            the relation names\n     * @param tableName\n     *            the table name\n     * @param results\n     *            the results\n     * @param filter\n     *            the filter\n     * @param filterClausequeue\n     *            the filter clausequeue\n     * @param columns\n     *            the columns\n     * @return the list\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    private List fetchEntity(Class entityClass, Object rowId, EntityMetadata entityMetadata,\n            List<String> relationNames, String tableName, List results, FilterList filter, Queue filterClausequeue,\n            String... columns) throws IOException\n    {\n        results = new ArrayList();\n        List<AbstractManagedType> subManagedType = getSubManagedType(entityClass, entityMetadata);\n\n        if (!subManagedType.isEmpty())\n        {\n            for (AbstractManagedType subEntity : subManagedType)\n            {\n                EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                        subEntity.getJavaType());\n                List tempResults = handler.readData(tableName, subEntityMetadata.getEntityClazz(), subEntityMetadata,\n                        rowId, subEntityMetadata.getRelationNames(), filter, columns);\n                if (tempResults != null && !tempResults.isEmpty())\n                {\n                    results.addAll(tempResults);\n                }\n            }\n        }\n        else\n        {\n            results = handler.readData(tableName, entityMetadata.getEntityClazz(), entityMetadata, rowId,\n                    relationNames, filter, columns);\n        }\n        if (rowId != null)\n        {\n            KunderaCoreUtils.printQuery(\"Fetch data from \" + entityMetadata.getTableName() + \" for PK \" + rowId,\n                    showQuery);\n        }\n        else if (showQuery && filterClausequeue.size() > 0)\n        {\n            KunderaCoreUtils.printQueryWithFilterClause(filterClausequeue, entityMetadata.getTableName());\n        }\n\n        return results;\n    }\n\n    /**\n     * Gets the sub managed type.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param entityMetadata\n     *            the entity metadata\n     * @return the sub managed type\n     */\n    private List<AbstractManagedType> getSubManagedType(Class entityClass, EntityMetadata entityMetadata)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n\n        EntityType entityType = metaModel.entity(entityClass);\n\n        List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n        return subManagedType;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        return (Generator) KunderaCoreUtils.createNewInstance(HBaseIdGenerator.class);\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/HBaseClientFactory.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase;\r\n\r\nimport java.util.Map;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\nimport org.apache.hadoop.conf.Configuration;\r\nimport org.apache.hadoop.hbase.HBaseConfiguration;\r\nimport org.apache.hadoop.hbase.client.HTablePool;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.client.hbase.config.HBasePropertyReader;\r\nimport com.impetus.client.hbase.schemamanager.HBaseSchemaManager;\r\nimport com.impetus.kundera.PersistenceProperties;\r\nimport com.impetus.kundera.client.Client;\r\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection;\r\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\r\nimport com.impetus.kundera.loader.GenericClientFactory;\r\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\r\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\r\n\r\n/**\r\n * HBaseClientFactory, instantiates client for HBase\r\n */\r\npublic class HBaseClientFactory extends GenericClientFactory\r\n{\r\n\r\n    /** The logger. */\r\n    private static Logger logger = LoggerFactory.getLogger(HBaseClientFactory.class);\r\n\r\n    /** The conf. */\r\n    private Configuration conf;\r\n\r\n    /** The h table pool. */\r\n    private HTablePool hTablePool;\r\n\r\n    /** The Constant DEFAULT_POOL_SIZE. */\r\n    private static final int DEFAULT_POOL_SIZE = 100;\r\n\r\n    private static final String DEFAULT_ZOOKEEPER_PORT = \"2181\";\r\n\r\n    /** The pool size. */\r\n    private int poolSize;\r\n\r\n    @Override\r\n    public void initialize(Map<String, Object> externalProperty)\r\n    {\r\n        setExternalProperties(externalProperty);\r\n        initializePropertyReader();\r\n        // Initialize HBase configuration\r\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata, getPersistenceUnit());\r\n\r\n        String node = null;\r\n        String port = null;\r\n        String poolSize = null;\r\n        if (externalProperty != null)\r\n        {\r\n            node = (String) externalProperty.get(PersistenceProperties.KUNDERA_NODES);\r\n            port = (String) externalProperty.get(PersistenceProperties.KUNDERA_PORT);\r\n            poolSize = (String) externalProperty.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE);\r\n        }\r\n        if (node == null)\r\n        {\r\n            node = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_NODES);\r\n        }\r\n        if (port == null)\r\n        {\r\n            port = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_PORT);\r\n        }\r\n        if (poolSize == null)\r\n        {\r\n            poolSize = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE);\r\n        }\r\n\r\n        if (StringUtils.isEmpty(poolSize))\r\n        {\r\n            this.poolSize = DEFAULT_POOL_SIZE;\r\n        }\r\n        else\r\n        {\r\n            this.poolSize = Integer.parseInt(poolSize);\r\n        }\r\n\r\n        onValidation(node, port);\r\n\r\n        Configuration hadoopConf = new Configuration();\r\n        hadoopConf.set(\"hbase.master\", node + \":\" + port);\r\n\r\n        Connection conn = HBasePropertyReader.hsmd.getDataStore() != null ? HBasePropertyReader.hsmd.getDataStore()\r\n                .getConnection() : null;\r\n        if (conn != null && conn.getProperties() != null)\r\n        {\r\n            String zookeeperHost = conn.getProperties().getProperty(\"hbase.zookeeper.quorum\").trim();\r\n            String zookeeperPort = conn.getProperties().getProperty(\"hbase.zookeeper.property.clientPort\").trim();\r\n            hadoopConf.set(\"hbase.zookeeper.quorum\", zookeeperHost != null ? zookeeperHost : node);\r\n            hadoopConf.set(\"hbase.zookeeper.property.clientPort\", zookeeperPort != null ? zookeeperPort\r\n                    : DEFAULT_ZOOKEEPER_PORT);\r\n        }\r\n        else\r\n        {\r\n            // in case \"hbase.zookeeper.property.clientPort\" is not supplied, it\r\n            // is different than hbase master port!\r\n            hadoopConf.set(\"hbase.zookeeper.quorum\", node);\r\n            hadoopConf.set(\"hbase.zookeeper.property.clientPort\", DEFAULT_ZOOKEEPER_PORT);\r\n        }\r\n        conf = HBaseConfiguration.create(hadoopConf);\r\n        reader = new HBaseEntityReader(kunderaMetadata);\r\n    }\r\n\r\n    @Override\r\n    protected Object createPoolOrConnection()\r\n    {\r\n        hTablePool = new HTablePool(conf, poolSize);\r\n        return hTablePool;\r\n    }\r\n\r\n    @Override\r\n    protected Client instantiateClient(String persistenceUnit)\r\n    {\r\n        return new HBaseClient(indexManager, conf, hTablePool, reader, persistenceUnit, externalProperties, clientMetadata, kunderaMetadata);\r\n    }\r\n\r\n    @Override\r\n    public boolean isThreadSafe()\r\n    {\r\n        return false;\r\n    }\r\n\r\n    @Override\r\n    public void destroy()\r\n    {\r\n        // TODO destroy pool\r\n        // hTablePool = null;\r\n\r\n        // indexManager.close();\r\n        if (schemaManager != null)\r\n        {\r\n            schemaManager.dropSchema();\r\n        }\r\n        externalProperties = null;\r\n        schemaManager = null;\r\n    }\r\n\r\n    @Override\r\n    public SchemaManager getSchemaManager(Map<String, Object> externalProperty)\r\n    {\r\n        setExternalProperties(externalProperty);\r\n        if (schemaManager == null)\r\n        {\r\n            initializePropertyReader();\r\n            schemaManager = new HBaseSchemaManager(HBaseClientFactory.class.getName(), externalProperty, kunderaMetadata);\r\n        }\r\n        return schemaManager;\r\n    }\r\n\r\n    /**\r\n     * \r\n     */\r\n    private void initializePropertyReader()\r\n    {\r\n        if (propertyReader == null)\r\n        {\r\n            propertyReader = new HBasePropertyReader(externalProperties, kunderaMetadata.getApplicationMetadata()\r\n                    .getPersistenceUnitMetadata(getPersistenceUnit()));\r\n            propertyReader.read(getPersistenceUnit());\r\n        }\r\n    }\r\n\r\n    @Override\r\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\r\n    {\r\n        throw new UnsupportedOperationException(\"Load balancing feature is not supported in \"\r\n                + this.getClass().getSimpleName());\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/HBaseClientProperties.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.hbase;\n\nimport java.util.Map;\n\nimport org.apache.hadoop.hbase.filter.Filter;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\n\n/**\n * HBase implementation of {@link ClientPropertiesSetter}\n * \n * @author amresh.singh\n */\nclass HBaseClientProperties\n{\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(HBaseClientProperties.class);\n\n    private static final String FILTER = \"hbase.filter\";\n\n    private HBaseClient hbaseClient;\n\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        this.hbaseClient = (HBaseClient) client;\n\n        if (properties != null)\n        {\n\n            for (String key : properties.keySet())\n            {\n                Object value = properties.get(key);\n                if (checkNull(key, value))\n                {\n                    if (key.equals(FILTER) && value instanceof Filter)\n                    {\n                        this.hbaseClient.setFilter((Filter) value);\n                    }\n                    else if (key.equals(PersistenceProperties.KUNDERA_BATCH_SIZE))\n                    {\n                        setBatchSize(value);\n                    }\n                    // Add more\n                }\n            }\n        }\n    }\n\n    private void setBatchSize(Object value)\n    {\n        if (value instanceof Integer)\n        {\n            this.hbaseClient.setBatchSize((Integer) value);\n        }\n        else if (value instanceof String)\n        {\n            this.hbaseClient.setBatchSize(Integer.valueOf((String) value));\n        }\n\n    }\n\n    /**\n     * check key value map not null\n     */\n    private boolean checkNull(String key, Object value)\n    {\n        return key != null && value != null;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/HBaseConstants.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase;\n\n/**\n * Holds constants for kundera-hbase module\n * \n * @author Kuldeep Mishra\n * \n */\npublic final class HBaseConstants\n{\n    public static final String CF_DEFS = \"cf.defs\";\n\n    public static final String ZOOKEEPER_PORT = \"zookeeper.port\";\n\n    public static final String ZOOKEEPER_HOST = \"zookeeper.host\";\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/HBaseData.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport org.apache.hadoop.hbase.KeyValue;\r\nimport org.apache.hadoop.hbase.util.Bytes;\r\n\r\nimport com.impetus.kundera.DataWrapper;\r\n\r\n/**\r\n * The Class HBaseData.\r\n * \r\n * @author impetus\r\n */\r\npublic class HBaseData implements DataWrapper\r\n{\r\n\r\n    /** The column family. */\r\n    private String columnFamily;\r\n\r\n    /** The row key. */\r\n    private byte[] rowKey;\r\n\r\n    private Map<String, byte[]> columns = new HashMap<String, byte[]>();\r\n\r\n    /**\r\n     * constructor with fields.\r\n     * \r\n     * @param columnFamily\r\n     *            HBase column family\r\n     * @param rowKey\r\n     *            Row key\r\n     */\r\n    public HBaseData(String columnFamily, byte[] rowKey)\r\n    {\r\n        this.columnFamily = columnFamily;\r\n        this.rowKey = rowKey;\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new h base data.\r\n     * \r\n     * @param rowKey\r\n     *            the row key\r\n     */\r\n    public HBaseData(byte[] rowKey)\r\n    {\r\n        this.rowKey = rowKey;\r\n    }\r\n\r\n    /**\r\n     * Getter column family.\r\n     * \r\n     * @return columnFamily column family\r\n     */\r\n    public String getColumnFamily()\r\n    {\r\n        return columnFamily;\r\n    }\r\n\r\n    /**\r\n     * Getter for row key.\r\n     * \r\n     * @return rowKey\r\n     */\r\n    public byte[] getRowKey()\r\n    {\r\n        return rowKey;\r\n    }\r\n\r\n    public byte[] getColumnValue(String qualifier )\r\n    {\r\n        return columns.get(qualifier);\r\n    }\r\n    \r\n    public Map<String, byte[]> getColumns()\r\n    {\r\n        return columns;\r\n    }\r\n\r\n    public void setColumns(List<KeyValue> columns)\r\n    {\r\n        for(KeyValue column : columns)\r\n        {\r\n            putColumn(column.getQualifier(), column.getValue());\r\n        }\r\n    }\r\n\r\n    private void putColumn(byte[] qualifier, byte[] qualifierValue)\r\n    {\r\n        this.columns.put(Bytes.toString(qualifier), qualifierValue);\r\n    }\r\n    \r\n    \r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/HBaseEntityReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase;\n\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * The Class HBaseEntityReader.\n * \n * @author vivek.mishra\n */\npublic class HBaseEntityReader extends AbstractEntityReader implements EntityReader\n{\n\n    public HBaseEntityReader(final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    public HBaseEntityReader(KunderaQuery kunderaQuery, final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n        this.kunderaQuery = kunderaQuery;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#populateRelation(com.impetus\n     * .kundera.metadata.model.EntityMetadata, java.util.List, boolean,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        throw new UnsupportedOperationException(\"Method is not supported\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#findById(java.lang.String,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.util.List,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        return super.findById(primaryKey, m, client);\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/HBaseIdGenerator.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase;\n\nimport java.io.IOException;\n\nimport org.apache.hadoop.hbase.client.HTableInterface;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.admin.HBaseDataHandler;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.generator.TableGenerator;\nimport com.impetus.kundera.metadata.model.TableGeneratorDiscriptor;\n\n/**\n * The Class HBaseIdGenerator.\n * \n * @author: karthikp.manchala\n */\npublic class HBaseIdGenerator implements TableGenerator\n{\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(HBaseIdGenerator.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.TableGenerator#generate(com.impetus.kundera\n     * .metadata.model.TableGeneratorDiscriptor,\n     * com.impetus.kundera.client.ClientBase, java.lang.Object)\n     */\n    @Override\n    public Object generate(TableGeneratorDiscriptor discriptor, ClientBase client, String dataType)\n    {\n        try\n        {\n            HTableInterface hTable = ((HBaseDataHandler) ((HBaseClient) client).handler).gethTable(discriptor\n                    .getSchema());\n            Long latestCount = hTable.incrementColumnValue(discriptor.getPkColumnValue().getBytes(), discriptor\n                    .getTable().getBytes(), discriptor.getValueColumnName().getBytes(), 1);\n            if (latestCount == 1)\n            {\n                return (long) discriptor.getInitialValue();\n            }\n            else if (discriptor.getAllocationSize() == 1)\n            {\n                return latestCount + discriptor.getInitialValue();\n            }\n            else\n            {\n                return (latestCount - 1) * discriptor.getAllocationSize() + discriptor.getInitialValue();\n            }\n        }\n        catch (IOException ioex)\n        {\n            log.error(\"Error while generating id for entity, Caused by: .\", ioex);\n            throw new KunderaException(ioex);\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/Reader.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase;\r\n\r\nimport java.io.IOException;\r\nimport java.util.List;\r\n\r\nimport org.apache.hadoop.hbase.client.HTableInterface;\r\nimport org.apache.hadoop.hbase.filter.Filter;\r\n\r\n// TODO: Auto-generated Javadoc\r\n/**\r\n * The Interface Reader.\r\n */\r\npublic interface Reader\r\n{\r\n\r\n    /**\r\n     * Populates HBase data for given family name.\r\n     * \r\n     * @param hTable\r\n     *            HBase table\r\n     * @param columnFamily\r\n     *            HBase column family\r\n     * @param rowKey\r\n     *            HBase row key.\r\n     * @param filter\r\n     *            the filter\r\n     * @return HBase data wrapper containing all column names along with values.\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    List<HBaseData> LoadData(HTableInterface hTable, String columnFamily, Object rowKey, Filter filter,\r\n            String... columns) throws IOException;\r\n\r\n    /**\r\n     * Load data.\r\n     * \r\n     * @param hTable\r\n     *            the h table\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param filter\r\n     *            the filter\r\n     * @return the h base data\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    List<HBaseData> LoadData(HTableInterface hTable, Object rowKey, Filter filter, String... columns)\r\n            throws IOException;\r\n\r\n    /**\r\n     * Load all.\r\n     * \r\n     * @param hTable\r\n     *            the h table\r\n     * @param filter\r\n     *            the filter\r\n     * @param startRow\r\n     *            the start row\r\n     * @param endRow\r\n     *            the end row\r\n     * @param columns\r\n     * @return the list\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    List<HBaseData> loadAll(HTableInterface hTable, Filter filter, byte[] startRow, byte[] endRow, String columnFamily,\r\n            String qualifier, String[] columns) throws IOException;\r\n\r\n    /**\r\n     * Scan row keys.\r\n     * \r\n     * @param hTable\r\n     *            the h table\r\n     * @param filter\r\n     *            the filter\r\n     * @param columnFamilyName\r\n     *            the columnFamily Name\r\n     * @param columnName\r\n     *            the column Name\r\n     * @return object array\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    Object[] scanRowKeys(final HTableInterface hTable, final Filter filter, final String columnFamilyName,\r\n            final String columnName, final Class rowKeyClazz) throws IOException;\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/Writer.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase;\r\n\r\nimport java.io.IOException;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.metamodel.Attribute;\r\n\r\nimport org.apache.hadoop.hbase.client.HTableInterface;\r\n\r\nimport com.impetus.client.hbase.admin.HBaseDataHandler.HBaseDataWrapper;\r\nimport com.impetus.kundera.db.RelationHolder;\r\n\r\n/**\r\n * HBase data writer.\r\n * \r\n * @author impetus\r\n */\r\npublic interface Writer\r\n{\r\n\r\n    /**\r\n     * Write column.\r\n     * \r\n     * @param htable\r\n     *            the htable\r\n     * @param columnFamily\r\n     *            the column family\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param column\r\n     *            the column\r\n     * @param columnObj\r\n     *            the column obj\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void writeColumn(HTableInterface htable, String columnFamily, Object rowKey, Attribute column, Object columnObj)\r\n            throws IOException;\r\n\r\n    /**\r\n     * Writes a column family with name <code>columnFamily</code>, into a table\r\n     * whose columns are <code>columns</code>.\r\n     * \r\n     * @param htable\r\n     *            the htable\r\n     * @param columnFamily\r\n     *            Column Family Name\r\n     * @param rowKey\r\n     *            Row Key\r\n     * @param columns\r\n     *            Columns for a given column family\r\n     * @param values TODO\r\n     * @param columnFamilyObj\r\n     *            the column family obj\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void writeColumns(HTableInterface htable, String columnFamily, Object rowKey, Map<String, Attribute> columns,\r\n            Map<String, Object> values, Object columnFamilyObj) throws IOException;\r\n\r\n    /**\r\n     * Writes Columns <code>columns</code> into a given table. Each columns is\r\n     * written in their own column family(name same as column name)\r\n     * \r\n     * @param htable\r\n     *            the htable\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param columns\r\n     *            Columns of a given table (No column family given)\r\n     * @param entity\r\n     *            the entity\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void writeColumns(HTableInterface htable, Object rowKey, Map<String, Attribute> columns, Object entity,\r\n            String columnFamilyName) throws IOException;\r\n\r\n    /**\r\n     * Write relations.\r\n     * \r\n     * @param htable\r\n     *            the htable\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param containsEmbeddedObjectsOnly\r\n     *            the contains embedded objects only\r\n     * @param relations\r\n     *            the relations\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void writeRelations(HTableInterface htable, Object rowKey, boolean containsEmbeddedObjectsOnly,\r\n            List<RelationHolder> relations, String columnFamilyName) throws IOException;\r\n\r\n    /**\r\n     * Writes foreign keys along with a database table. They are stored into a\r\n     * column family named FKey-TO. Each column corresponds to foreign key field\r\n     * name and values are actual foreign keys (separated by ~ if applicable)\r\n     * \r\n     * @param hTable\r\n     *            the h table\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param foreignKeyMap\r\n     *            the foreign key map\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     * @deprecated\r\n     */\r\n    public void writeForeignKeys(HTableInterface hTable, String rowKey, Map<String, Set<String>> foreignKeyMap)\r\n            throws IOException;\r\n\r\n    /**\r\n     * Writes columns data to HBase table, supplied as a map in Key/ value pair;\r\n     * key and value representing column name and value respectively.\r\n     * \r\n     * @param htable\r\n     *            the htable\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param columns\r\n     *            the columns\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void writeColumns(HTableInterface htable, Object rowKey, Map<String, Object> columns, String columnFamilyName)\r\n            throws IOException;\r\n\r\n    /**\r\n     * Delete.\r\n     * \r\n     * @param hTable\r\n     *            the h table\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param columnFamily\r\n     *            the column family\r\n     */\r\n    void delete(HTableInterface hTable, Object rowKey, String columnFamily);\r\n\r\n    /**\r\n     * method to perform batch insert/update.\r\n     * \r\n     * @param rows\r\n     *            data rows\r\n     * @throws IOException\r\n     *             throws io exception.\r\n     */\r\n    void persistRows(Map<HTableInterface, List<HBaseDataWrapper>> rows) throws IOException;\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/admin/DataHandler.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase.admin;\r\n\r\nimport java.io.IOException;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport org.apache.hadoop.hbase.filter.FilterList;\r\n\r\nimport com.impetus.kundera.db.RelationHolder;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\n\r\n/**\r\n * Data handler for HBase queries.\r\n * \r\n * @author vivek.mishra\r\n */\r\n\r\npublic interface DataHandler\r\n{\r\n\r\n    /**\r\n     * Creates a HBase table.\r\n     * \r\n     * @param tableName\r\n     *            table name.\r\n     * @param colFamily\r\n     *            column family.\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void createTableIfDoesNotExist(String tableName, String... colFamily) throws IOException;\r\n\r\n    /**\r\n     * Populates data for give column family, column name, and HBase table name.\r\n     * \r\n     * @param tableName\r\n     *            the table name\r\n     * @param clazz\r\n     *            the clazz\r\n     * @param m\r\n     *            the m\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param f\r\n     * @param relationNames\r\n     *            the relation names\r\n     * @return the object\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    List readData(String tableName, Class clazz, EntityMetadata m, Object rowKey, List<String> relatationNames,\r\n            FilterList f, String... columns) throws IOException;\r\n\r\n    /**\r\n     * Populates data for give column family, column name, and HBase table name.\r\n     * \r\n     * @param tableName\r\n     *            the table name\r\n     * @param clazz\r\n     *            the clazz\r\n     * @param m\r\n     *            the m\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param relationNames\r\n     *            the relation names\r\n     * @return the object\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    List readAll(String tableName, Class clazz, EntityMetadata m, List<Object> rowKeys, List<String> relatationNames,\r\n            String... columns) throws IOException;\r\n\r\n    /**\r\n     * @param tableName\r\n     * @param clazz\r\n     * @param m\r\n     * @param relationNames\r\n     * @param startRow\r\n     * @param endRow\r\n     * @param columns\r\n     * @param f\r\n     * @return\r\n     */\r\n    List readDataByRange(String tableName, Class clazz, EntityMetadata m, byte[] startRow, byte[] endRow,\r\n            String[] columns, FilterList f) throws IOException;\r\n\r\n    /**\r\n     * Write data.\r\n     * \r\n     * @param tableName\r\n     *            the table name\r\n     * @param m\r\n     *            the m\r\n     * @param entity\r\n     *            the entity\r\n     * @param rowId\r\n     *            the row id\r\n     * @param relations\r\n     *            the relations\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void writeData(String tableName, EntityMetadata m, Object entity, Object rowId, List<RelationHolder> relations,\r\n            boolean showQuery) throws IOException;\r\n\r\n    /**\r\n     * Writes data into Join Table.\r\n     * \r\n     * @param tableName\r\n     *            the table name\r\n     * @param rowId\r\n     *            the row id\r\n     * @param columns\r\n     *            the columns\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void writeJoinTableData(String tableName, Object rowId, Map<String, Object> columns, String columnFamilyName)\r\n            throws IOException;\r\n\r\n    /**\r\n     * Retrieves a list of foreign keys from the join table for a given row key.\r\n     * \r\n     * @param <E>\r\n     *            the element type\r\n     * @param joinTableName\r\n     *            the join table name\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param inverseJoinColumnName\r\n     *            the inverse join column name\r\n     * @return the foreign keys from join table\r\n     */\r\n    <E> List<E> getForeignKeysFromJoinTable(String schemaName, String joinTableName, Object rowKey,\r\n            String inverseJoinColumnName);\r\n\r\n    /**\r\n     * Retrieves a list of parent entity from join table..\r\n     * \r\n     * @param <E>\r\n     * @param parentMetadata\r\n     * @param joinTableName\r\n     * @param joinColumnName\r\n     * @param inverseJoinColumnName\r\n     * @param childId\r\n     * @return\r\n     */\r\n    <E> List<E> findParentEntityFromJoinTable(EntityMetadata parentMetadata, String joinTableName,\r\n            String joinColumnName, String inverseJoinColumnName, Object childId);\r\n\r\n    /**\r\n     * Shutdown.\r\n     */\r\n    void shutdown();\r\n\r\n    /**\r\n     * Delete specific row.\r\n     * \r\n     * @param rowKey\r\n     *            the row key\r\n     * @param tableName\r\n     *            the table name\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void deleteRow(Object rowKey, String tableName, String columnFamilyName) throws IOException;\r\n\r\n    Object[] scanRowyKeys(FilterList filterList, String tableName, String columnFamilyName, String columnName,\r\n            Class rowKeyClazz) throws IOException;\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/admin/HBaseDataHandler.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.admin;\n\nimport java.io.IOException;\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Embedded;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.hbase.HColumnDescriptor;\nimport org.apache.hadoop.hbase.HTableDescriptor;\nimport org.apache.hadoop.hbase.MasterNotRunningException;\nimport org.apache.hadoop.hbase.client.HBaseAdmin;\nimport org.apache.hadoop.hbase.client.HTableInterface;\nimport org.apache.hadoop.hbase.client.HTablePool;\nimport org.apache.hadoop.hbase.filter.Filter;\nimport org.apache.hadoop.hbase.filter.FilterList;\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.jboss.netty.util.internal.ConcurrentHashMap;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.HBaseData;\nimport com.impetus.client.hbase.Reader;\nimport com.impetus.client.hbase.Writer;\nimport com.impetus.client.hbase.service.HBaseReader;\nimport com.impetus.client.hbase.service.HBaseWriter;\nimport com.impetus.client.hbase.utils.HBaseUtils;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.cache.ElementCollectionCacheManager;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.annotation.DefaultEntityAnnotationProcessor;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class HBaseDataHandler.\n * \n * @author vivek.mishra\n */\npublic class HBaseDataHandler implements DataHandler\n{\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(HBaseDataHandler.class);\n\n    /** The admin. */\n    private HBaseAdmin admin;\n\n    /** The conf. */\n    private Configuration conf;\n\n    /** The h table pool. */\n    private HTablePool hTablePool;\n\n    /** The hbase reader. */\n    private Reader hbaseReader = new HBaseReader();\n\n    /** The hbase writer. */\n    private Writer hbaseWriter = new HBaseWriter();\n\n    private FilterList filter = null;\n\n    private Map<String, FilterList> filters = new ConcurrentHashMap<String, FilterList>();\n\n    private KunderaMetadata kunderaMetadata;\n\n    /**\n     * Instantiates a new h base data handler.\n     * \n     * @param conf\n     *            the conf\n     * @param hTablePool\n     *            the h table pool\n     */\n    public HBaseDataHandler(final KunderaMetadata kunderaMetadata, Configuration conf, HTablePool hTablePool)\n    {\n        try\n        {\n            this.kunderaMetadata = kunderaMetadata;\n            this.conf = conf;\n            this.hTablePool = hTablePool;\n            this.admin = new HBaseAdmin(conf);\n        }\n        catch (Exception e)\n        {\n            // TODO We need a generic ExceptionTranslator\n            throw new PersistenceException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#createTableIfDoesNotExist(\n     * java.lang.String, java.lang.String[])\n     */\n    @Override\n    public void createTableIfDoesNotExist(final String tableName, final String... colFamily)\n            throws MasterNotRunningException, IOException\n    {\n        if (!admin.tableExists(Bytes.toBytes(tableName)))\n        {\n            HTableDescriptor htDescriptor = new HTableDescriptor(tableName);\n            for (String columnFamily : colFamily)\n            {\n                HColumnDescriptor familyMetadata = new HColumnDescriptor(columnFamily);\n                htDescriptor.addFamily(familyMetadata);\n            }\n            admin.createTable(htDescriptor);\n        }\n    }\n\n    /**\n     * Adds the column family to table.\n     * \n     * @param tableName\n     *            the table name\n     * @param columnFamilyName\n     *            the column family name\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    private void addColumnFamilyToTable(String tableName, String columnFamilyName) throws IOException\n    {\n        HColumnDescriptor cfDesciptor = new HColumnDescriptor(columnFamilyName);\n\n        try\n        {\n            if (admin.tableExists(tableName))\n            {\n\n                // Before any modification to table schema, it's necessary to\n                // disable it\n                if (!admin.isTableEnabled(tableName))\n                {\n                    admin.enableTable(tableName);\n                }\n                HTableDescriptor descriptor = admin.getTableDescriptor(tableName.getBytes());\n                boolean found = false;\n                for (HColumnDescriptor hColumnDescriptor : descriptor.getColumnFamilies())\n                {\n                    if (hColumnDescriptor.getNameAsString().equalsIgnoreCase(columnFamilyName))\n                        found = true;\n                }\n                if (!found)\n                {\n\n                    if (admin.isTableEnabled(tableName))\n                    {\n                        admin.disableTable(tableName);\n                    }\n\n                    admin.addColumn(tableName, cfDesciptor);\n\n                    // Enable table once done\n                    admin.enableTable(tableName);\n                }\n            }\n            else\n            {\n                log.warn(\"Table {} doesn't exist, so no question of adding column family {} to it!\", tableName,\n                        columnFamilyName);\n            }\n        }\n        catch (IOException e)\n        {\n            log.error(\"Error while adding column family {}, to table{} . \", columnFamilyName, tableName);\n            throw e;\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#readData(java.lang.String,\n     * java.lang.Class, com.impetus.kundera.metadata.model.EntityMetadata,\n     * java.lang.String, java.util.List)\n     */\n    @Override\n    public List readData(final String tableName, Class clazz, EntityMetadata m, final Object rowKey,\n            List<String> relationNames, FilterList f, String... columns) throws IOException\n    {\n\n        List output = null;\n\n        Object entity = null;\n\n        HTableInterface hTable = null;\n\n        hTable = gethTable(tableName);\n\n        if (getFilter(m.getTableName()) != null)\n        {\n            if (f == null)\n            {\n                f = new FilterList();\n            }\n            f.addFilter(getFilter(m.getTableName()));\n        }\n\n        // Load raw data from HBase\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(m.getEntityClazz());\n        // For secondary tables.\n        List<String> secondaryTables = ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation())\n                .getSecondaryTablesName();\n        secondaryTables.add(m.getTableName());\n        Collections.shuffle(secondaryTables);\n        List<HBaseData> results = new ArrayList<HBaseData>();\n        for (String colTableName : secondaryTables)\n        {\n            results.addAll(hbaseReader.LoadData(hTable, colTableName, rowKey, f, columns));\n        }\n\n        output = onRead(tableName, clazz, m, output, hTable, entity, relationNames, results);\n        return output;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#readData(java.lang.String,\n     * java.lang.Class, com.impetus.kundera.metadata.model.EntityMetadata,\n     * java.lang.String, java.util.List)\n     */\n    @Override\n    public List readAll(final String tableName, Class clazz, EntityMetadata m, final List<Object> rowKey,\n            List<String> relationNames, String... columns) throws IOException\n    {\n\n        List output = null;\n\n        Object entity = null;\n\n        HTableInterface hTable = null;\n\n        hTable = gethTable(tableName);\n\n        // Load raw data from HBase\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(m.getEntityClazz());\n        // For secondary tables.\n        List<String> secondaryTables = ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation())\n                .getSecondaryTablesName();\n        secondaryTables.add(m.getTableName());\n        List<HBaseData> results = new ArrayList<HBaseData>();\n        for (String colTableName : secondaryTables)\n        {\n            List table = ((HBaseReader) hbaseReader).loadAll(hTable, rowKey, colTableName, columns);\n            // null check for 'table'. addAll method throws exception if table\n            // is null\n            if (table != null)\n            {\n                results.addAll(table);\n            }\n        }\n\n        output = onRead(tableName, clazz, m, output, hTable, entity, relationNames, results);\n        return output;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#readDataByRange(java.lang.\n     * String, java.lang.Class,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.util.List,\n     * byte[], byte[])\n     */\n    @Override\n    public List readDataByRange(String tableName, Class clazz, EntityMetadata m, byte[] startRow, byte[] endRow,\n            String[] columns, FilterList f) throws IOException\n    {\n        List output = new ArrayList();\n        HTableInterface hTable = null;\n        Object entity = null;\n        List<String> relationNames = m.getRelationNames();\n        Filter filter = getFilter(m.getTableName());\n        if (filter != null)\n        {\n            if (f == null)\n            {\n                f = new FilterList();\n            }\n            f.addFilter(filter);\n        }\n        // Load raw data from HBase\n        hTable = gethTable(tableName);\n        List<HBaseData> results = hbaseReader.loadAll(hTable, f, startRow, endRow, m.getTableName(), null, columns);\n        output = onRead(tableName, clazz, m, output, hTable, entity, relationNames, results);\n\n        return output;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#writeData(java.lang.String,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.lang.Object,\n     * java.lang.String, java.util.List)\n     */\n    @Override\n    public void writeData(String tableName, EntityMetadata m, Object entity, Object rowId,\n            List<RelationHolder> relations, boolean showQuery) throws IOException\n    {\n        HTableInterface hTable = gethTable(tableName);\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n        Set<Attribute> attributes = entityType.getAttributes();\n\n        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n        {\n            rowId = KunderaCoreUtils.prepareCompositeKey(m, rowId);\n        }\n\n        HBaseDataWrapper columnWrapper = new HBaseDataWrapper(rowId, new java.util.HashMap<String, Attribute>(),\n                entity, null);\n        List<HBaseDataWrapper> persistentData = new ArrayList<HBaseDataHandler.HBaseDataWrapper>(attributes.size());\n\n        Map<String, HBaseDataWrapper> columnWrappers = preparePersistentData(tableName, m.getTableName(), entity,\n                rowId, metaModel, attributes, columnWrapper, persistentData, showQuery);\n\n        writeColumnData(hTable, entity, columnWrappers);\n\n        for (HBaseDataWrapper wrapper : persistentData)\n        {\n            hbaseWriter.writeColumns(hTable, wrapper.getColumnFamily(), wrapper.getRowKey(), wrapper.getColumns(),\n                    wrapper.getValues(), wrapper.getEntity());\n        }\n\n        // Persist relationships as a column in newly created Column family by\n        // Kundera\n        boolean containsEmbeddedObjectsOnly = columnWrapper.getColumns().isEmpty() && persistentData.isEmpty();\n\n        if (relations != null && !relations.isEmpty())\n        {\n            hbaseWriter.writeRelations(hTable, rowId, containsEmbeddedObjectsOnly, relations, m.getTableName());\n        }\n\n        // add discriminator column\n        String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n        String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();\n\n        // No need to check for empty or blank, as considering it as valid name\n        // for nosql!\n        if (discrColumn != null && discrValue != null)\n        {\n            List<RelationHolder> discriminator = new ArrayList<RelationHolder>(1);\n            discriminator.add(new RelationHolder(discrColumn, discrValue));\n            hbaseWriter.writeRelations(hTable, rowId, containsEmbeddedObjectsOnly, discriminator, m.getTableName());\n        }\n\n        puthTable(hTable);\n    }\n\n    private void writeColumnData(HTableInterface hTable, Object entity, Map<String, HBaseDataWrapper> columnWrappers)\n            throws IOException\n    {\n\n        for (HBaseDataWrapper wrapper : columnWrappers.values())\n        {\n            hbaseWriter.writeColumns(hTable, wrapper.getRowKey(), wrapper.getColumns(), entity,\n                    wrapper.getColumnFamily());\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#writeJoinTableData(java.lang\n     * .String, java.lang.String, java.util.Map)\n     */\n    @Override\n    public void writeJoinTableData(String tableName, Object rowId, Map<String, Object> columns, String columnFamilyName)\n            throws IOException\n    {\n        HTableInterface hTable = gethTable(tableName);\n\n        hbaseWriter.writeColumns(hTable, rowId, columns, columnFamilyName);\n\n        puthTable(hTable);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#getForeignKeysFromJoinTable\n     * (java.lang.String, java.lang.String, java.lang.String)\n     */\n    @Override\n    public <E> List<E> getForeignKeysFromJoinTable(String schemaName, String joinTableName, Object rowKey,\n            String inverseJoinColumnName)\n    {\n        List<E> foreignKeys = new ArrayList<E>();\n\n        HTableInterface hTable = null;\n\n        // Load raw data from Join Table in HBase\n        try\n        {\n            hTable = gethTable(schemaName);\n\n            List<HBaseData> results = hbaseReader.LoadData(hTable, joinTableName, rowKey, getFilter(joinTableName));\n\n            // assuming rowKey is not null.\n            if (results != null && !results.isEmpty())\n            {\n\n                HBaseData data = results.get(0);\n\n                Map<String, byte[]> hbaseValues = data.getColumns();\n                Set<String> columnNames = hbaseValues.keySet();\n\n                for (String columnName : columnNames)\n                {\n                    if (columnName.startsWith(inverseJoinColumnName) && data.getColumnFamily().equals(joinTableName))\n                    {\n                        byte[] columnValue = data.getColumnValue(columnName);\n\n                        // TODO : Because no attribute class is present, so\n                        // cannot be done.\n                        String hbaseColumnValue = Bytes.toString(columnValue);\n\n                        foreignKeys.add((E) hbaseColumnValue);\n                    }\n                }\n            }\n        }\n        catch (IOException e)\n        {\n            return foreignKeys;\n        }\n        finally\n        {\n            try\n            {\n                if (hTable != null)\n                {\n                    puthTable(hTable);\n                }\n            }\n            catch (IOException e)\n            {\n\n                // Do nothing.\n            }\n        }\n        return foreignKeys;\n    }\n\n    /**\n     * Selects an HTable from the pool and returns.\n     * \n     * @param tableName\n     *            Name of HBase table\n     * @return the h table\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    public HTableInterface gethTable(final String tableName) throws IOException\n    {\n        return hTablePool.getTable(tableName);\n    }\n\n    /**\n     * Puts HTable back into the HBase table pool.\n     * \n     * @param hTable\n     *            HBase Table instance\n     */\n    private void puthTable(HTableInterface hTable) throws IOException\n    {\n        hTablePool.putTable(hTable);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.hbase.admin.DataHandler#shutdown()\n     */\n    @Override\n    public void shutdown()\n    {\n\n        // TODO: Shutting down admin actually shuts down HMaster, something we\n        // don't want.\n        // Devise a better way to release resources.\n\n        /*\n         * try {\n         * \n         * admin.shutdown();\n         * \n         * } catch (IOException e) { throw new RuntimeException(e.getMessage());\n         * }\n         */\n    }\n\n    // TODO: Scope of performance improvement in this method\n    /**\n     * Populate entity from hbase data.\n     * \n     * @param entity\n     *            the entity\n     * @param hbaseData\n     *            the hbase data\n     * @param m\n     *            the m\n     * @param rowKey\n     *            the row key\n     * @param relationNames\n     *            the relation names\n     * @return the object\n     */\n    private Object populateEntityFromHbaseData(Object entity, HBaseData hbaseData, EntityMetadata m, Object rowKey,\n            List<String> relationNames)\n    {\n\n        try\n        {\n\n            // Raw data retrieved from HBase for a particular row key (contains\n            // all column families)\n\n            Map<String, Object> relations = new HashMap<String, Object>();\n\n            if (entity.getClass().isAssignableFrom(EnhanceEntity.class))\n            {\n                relations = ((EnhanceEntity) entity).getRelations();\n                entity = ((EnhanceEntity) entity).getEntity();\n\n            }\n\n            // Populate columns data\n\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n            EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n            Set<Attribute> attributes = entityType.getAttributes();\n\n            String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n            String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();\n\n            if (discrColumn != null && hbaseData.getColumnValue(discrColumn) != null && discrValue != null)\n            {\n                byte[] discrimnatorValue = hbaseData.getColumnValue(discrColumn);\n                String actualDiscriminatorValue = Bytes.toString(discrimnatorValue);\n                if (actualDiscriminatorValue != null && !actualDiscriminatorValue.equals(discrValue))\n                {\n                    entity = null;\n                    return entity;\n                }\n            }\n\n            for (Attribute attribute : attributes)\n            {\n                Class javaType = ((AbstractAttribute) attribute).getBindableJavaType();\n                String key = ((AbstractAttribute) attribute).getJPAColumnName();\n                if (metaModel.isEmbeddable(javaType))\n                {\n                    EmbeddableType columnFamily = metaModel.embeddable(javaType);\n\n                    Field columnFamilyFieldInEntity = (Field) attribute.getJavaMember();\n                    Class<?> columnFamilyClass = columnFamilyFieldInEntity.getType();\n\n                    // Get a name->field map for columns in this column family\n                    Map<String, Field> columnNameToFieldMap = MetadataUtils.createColumnsFieldMap(m, columnFamily);\n\n                    // Column family can be either @Embedded or\n                    // @EmbeddedCollection\n                    if (Collection.class.isAssignableFrom(columnFamilyClass))\n                    {\n                        Map<Integer, Object> elementCollectionObjects = new HashMap<Integer, Object>();\n\n                        Field embeddedCollectionField = (Field) attribute.getJavaMember();\n                        Object[] embeddedObjectArr = new Object[hbaseData.getColumns().size()];\n                        Object embeddedObject = MetadataUtils.getEmbeddedGenericObjectInstance(embeddedCollectionField);\n\n                        Map<String, byte[]> hbaseValues = hbaseData.getColumns();\n\n                        Set<String> columnNames = hbaseValues.keySet();\n\n                        for (String columnName : columnNames)\n                        {\n                            byte[] columnValue = hbaseData.getColumnValue(columnName);\n\n                            if (columnName.startsWith(((AbstractAttribute) attribute).getJPAColumnName()))\n                            {\n                                String cfNamePostfix = MetadataUtils.getEmbeddedCollectionPostfix(columnName);\n                                int cfNameCounter = Integer.parseInt(cfNamePostfix);\n                                embeddedObject = elementCollectionObjects.get(cfNameCounter);\n\n                                if (embeddedObject == null)\n                                {\n\n                                    embeddedObject = MetadataUtils\n                                            .getEmbeddedGenericObjectInstance(embeddedCollectionField);\n                                }\n\n                                // Set Hbase data into the embedded object\n                                setHBaseDataIntoObject(columnName, columnValue, columnNameToFieldMap, embeddedObject,\n                                        metaModel.isEmbeddable(javaType));\n\n                                elementCollectionObjects.put(cfNameCounter, embeddedObject);\n\n                            }\n\n                            if (relationNames != null && relationNames.contains(hbaseData.getColumnFamily())\n                                    && columnValue.length != 0)\n                            {\n                                relations\n                                        .put(hbaseData.getColumnFamily(),\n                                                getObjectFromByteArray(entityType, columnValue,\n                                                        hbaseData.getColumnFamily(), m));\n                            }\n\n                            // Save embedded object into Cache, needed while\n                            // updation and deletion\n                            ElementCollectionCacheManager.getInstance().addElementCollectionCacheMapping(rowKey,\n                                    embeddedObject, hbaseData.getColumnFamily());\n                        }\n\n                        for (Integer integer : elementCollectionObjects.keySet())\n                        {\n                            embeddedObjectArr[integer] = elementCollectionObjects.get(integer);\n                        }\n\n                        Collection embeddedCollection = MetadataUtils\n                                .getEmbeddedCollectionInstance(embeddedCollectionField);\n                        embeddedCollection.addAll(Arrays.asList(embeddedObjectArr));\n                        embeddedCollection.removeAll(Collections.singletonList(null));\n                        embeddedObjectArr = null; // Eligible for GC\n\n                        // Now, set the embedded collection into entity\n                        if (embeddedCollection != null && !embeddedCollection.isEmpty())\n                        {\n                            PropertyAccessorHelper.set(entity, embeddedCollectionField, embeddedCollection);\n                        }\n                    }\n                    else\n                    {\n                        Object existsColumnFamilyObj = PropertyAccessorHelper.getObject(entity,\n                                columnFamilyFieldInEntity);\n                        Object columnFamilyObj = existsColumnFamilyObj != null ? existsColumnFamilyObj\n                                : columnFamilyClass.newInstance();\n\n                        Map<String, byte[]> hbaseValues = hbaseData.getColumns();\n                        Set<String> columnNames = hbaseValues.keySet();\n\n                        for (String columnName : columnNames)\n                        {\n                            byte[] columnValue = hbaseData.getColumnValue(columnName);\n                            if (relationNames != null && relationNames.contains(hbaseData.getColumnFamily())\n                                    && columnValue.length != 0)\n                            {\n                                relations\n                                        .put(hbaseData.getColumnFamily(),\n                                                getObjectFromByteArray(entityType, columnValue,\n                                                        hbaseData.getColumnFamily(), m));\n                            }\n                            // Set Hbase data into the column family object\n                            // Get Column from metadata\n                            Field columnField = columnNameToFieldMap.get(columnName);\n                            if (columnField != null && columnValue.length != 0)\n                            {\n                                if (columnFamilyFieldInEntity.isAnnotationPresent(Embedded.class)\n                                        || columnFamilyFieldInEntity.isAnnotationPresent(EmbeddedId.class)\n                                        || columnFamilyFieldInEntity.isAnnotationPresent(ElementCollection.class))\n                                {\n                                    PropertyAccessorHelper.set(columnFamilyObj, columnField,\n                                            HBaseUtils.fromBytes(columnValue, columnField.getType()));\n                                }\n                                else\n                                {\n                                    columnFamilyObj = getObjectFromByteArray(entityType, columnValue,\n                                            hbaseData.getColumnFamily(), m);\n                                }\n                            }\n                        }\n\n                        PropertyAccessorHelper.set(entity, columnFamilyFieldInEntity, columnFamilyObj);\n                    }\n                }\n                else if (!attribute.getName().equals(m.getIdAttribute().getName()))\n                {\n                    Field columnField = (Field) attribute.getJavaMember();\n                    String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n\n                    byte[] columnValue = hbaseData.getColumnValue(columnName);\n\n                    if (relationNames != null && relationNames.contains(columnName) && columnValue != null\n                            && columnValue.length > 0)\n                    {\n                        relations.put(columnName, getObjectFromByteArray(entityType, columnValue, columnName, m));\n                    }\n                    else if (columnValue != null && columnValue.length > 0)\n\n                    {\n                        PropertyAccessorHelper.set(entity, columnField,\n                                HBaseUtils.fromBytes(columnValue, columnField.getType()));\n                    }\n                }\n            }\n\n            if (!relations.isEmpty())\n            {\n\n                return new EnhanceEntity(entity, rowKey, relations);\n            }\n\n            return entity;\n        }\n        catch (PropertyAccessException e1)\n        {\n            throw new RuntimeException(e1);\n        }\n        catch (InstantiationException e1)\n        {\n            throw new RuntimeException(e1);\n        }\n        catch (IllegalAccessException e1)\n        {\n            throw new RuntimeException(e1);\n        }\n    }\n\n    /**\n     * Sets the h base data into object.\n     * \n     * @param colData\n     *            the col data\n     * @param columnFamilyField\n     *            the column family field\n     * @param columnNameToFieldMap\n     *            the column name to field map\n     * @param columnFamilyObj\n     *            the column family obj\n     * @throws PropertyAccessException\n     *             the property access exception\n     */\n    private void setHBaseDataIntoObject(String columnName, byte[] columnValue, Map<String, Field> columnNameToFieldMap,\n            Object columnFamilyObj, boolean isEmbeddeble) throws PropertyAccessException\n    {\n        String qualifier = columnName.substring(columnName.indexOf(\"#\") + 1, columnName.lastIndexOf(\"#\"));\n\n        // Get Column from metadata\n        Field columnField = columnNameToFieldMap.get(qualifier);\n        if (columnField != null)\n        {\n            if (isEmbeddeble)\n            {\n                PropertyAccessorHelper.set(columnFamilyObj, columnField, columnValue);\n            }\n            else\n            {\n                columnFamilyObj = HBaseUtils.fromBytes(columnValue, columnFamilyObj.getClass());\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#deleteRow(java.lang.String,\n     * java.lang.String)\n     */\n    public void deleteRow(Object rowKey, String tableName, String columnFamilyName) throws IOException\n    {\n        hbaseWriter.delete(gethTable(tableName), rowKey, columnFamilyName);\n    }\n\n    @Override\n    public List<Object> findParentEntityFromJoinTable(EntityMetadata parentMetadata, String joinTableName,\n            String joinColumnName, String inverseJoinColumnName, Object childId)\n    {\n        throw new PersistenceException(\"Not applicable for HBase\");\n    }\n\n    /**\n     * Set filter to data handler.\n     * \n     * @param filter\n     *            hbase filter.\n     */\n    public void setFilter(Filter filter)\n    {\n        if (this.filter == null)\n        {\n            this.filter = new FilterList();\n        }\n        if (filter != null)\n        {\n            this.filter.addFilter(filter);\n        }\n    }\n\n    public void addFilter(final String columnFamily, Filter filter)\n    {\n        FilterList filterList = this.filters.get(columnFamily);\n        if (filterList == null)\n        {\n            filterList = new FilterList();\n        }\n        if (filter != null)\n        {\n            filterList.addFilter(filter);\n        }\n        this.filters.put(columnFamily, filterList);\n    }\n\n    /**\n     * \n     * @param tableName\n     * @param clazz\n     * @param m\n     * @param startRow\n     * @param endRow\n     * @param output\n     * @param hTable\n     * @param entity\n     * @param relationNames\n     * @param results\n     * @return\n     * @throws IOException\n     */\n    private List onRead(String tableName, Class clazz, EntityMetadata m, List output, HTableInterface hTable,\n            Object entity, List<String> relationNames, List<HBaseData> results) throws IOException\n    {\n        try\n        {\n            // Populate raw data from HBase into entity\n\n            if (results != null)\n            {\n                Map<Object, Object> entityListMap = new HashMap<Object, Object>();\n\n                for (HBaseData data : results)\n                {\n                    entity = KunderaCoreUtils.createNewInstance(clazz);\n                    /* Set Row Key */\n\n                    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                            m.getPersistenceUnit());\n                    Object rowKeyValue = HBaseUtils.fromBytes(m, metaModel, data.getRowKey());\n                    if (!metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n                    {\n                        PropertyAccessorHelper.setId(entity, m, rowKeyValue);\n                    }\n\n                    if (entityListMap.get(rowKeyValue) != null)\n                    {\n\n                        entity = entityListMap.get(rowKeyValue);\n\n                    }\n                    entity = populateEntityFromHbaseData(entity, data, m, null, relationNames);\n                    if (output == null)\n                    {\n                        output = new ArrayList();\n                    }\n                    if (entity != null)\n                    {\n                        entityListMap.put(rowKeyValue, entity);\n\n                    }\n                }\n                for (Object obj : entityListMap.values())\n                {\n                    output.add(obj);\n                }\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while creating an instance of {}, Caused by: .\", clazz, e);\n            throw new PersistenceException(e);\n        }\n        finally\n        {\n            if (hTable != null)\n            {\n                puthTable(hTable);\n            }\n        }\n\n        return output;\n    }\n\n    /**\n     * @author vivek.mishra\n     * \n     */\n    public static class HBaseDataWrapper\n    {\n        private Object rowKey;\n\n        // private Set<Attribute> columns;\n\n        private Map<String, Attribute> columns;\n\n        private Map<String, Object> values;\n\n        private Object entity;\n\n        private String columnFamily;\n\n        /**\n         * @param rowKey\n         * @param columns\n         * @param entity\n         * @param columnFamily\n         */\n        public HBaseDataWrapper(Object rowKey, Map<String, Attribute> columns, Object entity, String columnFamily)\n        {\n            super();\n            this.rowKey = rowKey;\n            this.columns = columns;\n            this.entity = entity;\n            this.columnFamily = columnFamily;\n        }\n\n        public HBaseDataWrapper(Object rowKey, Map<String, Attribute> columns, Map<String, Object> values,\n                Object entity, String columnFamily)\n        {\n            super();\n            this.rowKey = rowKey;\n            this.columns = columns;\n            this.values = values;\n            this.entity = entity;\n            this.columnFamily = columnFamily;\n        }\n\n        /**\n         * @return the rowKey\n         */\n        public Object getRowKey()\n        {\n            return rowKey;\n        }\n\n        /**\n         * @return the columns\n         */\n        public Map<String, Attribute> getColumns()\n        {\n            return columns;\n        }\n\n        /**\n         * @return the entity\n         */\n        public Object getEntity()\n        {\n            return entity;\n        }\n\n        public void addColumn(String columnName, Attribute column)\n        {\n            columns.put(columnName, column);\n        }\n\n        public Map<String, Object> getValues()\n        {\n            return values;\n        }\n\n        public void addValue(String columnName, Object value)\n        {\n            if (values == null)\n            {\n                values = new HashMap<String, Object>();\n            }\n            values.put(columnName, value);\n        }\n\n        /**\n         * @return the rowKey\n         */\n        public void setColumnFamily(String columnFamily)\n        {\n            this.columnFamily = columnFamily;\n        }\n\n        /**\n         * @return the rowKey\n         */\n        public String getColumnFamily()\n        {\n            return this.columnFamily;\n        }\n\n    }\n\n    public List scanData(Filter f, final String tableName, Class clazz, EntityMetadata m, String columnFamily,\n            String qualifier) throws IOException, InstantiationException, IllegalAccessException\n    {\n        List returnedResults = new ArrayList();\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n        Set<Attribute> attributes = entityType.getAttributes();\n        String[] columns = new String[attributes.size() - 1];\n        int count = 0;\n        boolean isCollection = false;\n        for (Attribute attr : attributes)\n        {\n            if (!attr.isCollection() && !attr.getName().equalsIgnoreCase(m.getIdAttribute().getName()))\n            {\n                columns[count++] = ((AbstractAttribute) attr).getJPAColumnName();\n            }\n            else if (attr.isCollection())\n            {\n                isCollection = true;\n                break;\n            }\n        }\n        List<HBaseData> results = hbaseReader.loadAll(gethTable(tableName), f, null, null, m.getTableName(),\n                isCollection ? qualifier : null, null);\n        if (results != null)\n        {\n            for (HBaseData row : results)\n            {\n                Object entity = clazz.newInstance();// Entity Object\n                /* Set Row Key */\n                PropertyAccessorHelper.setId(entity, m, HBaseUtils.fromBytes(m, metaModel, row.getRowKey()));\n\n                returnedResults.add(populateEntityFromHbaseData(entity, row, m, row.getRowKey(), m.getRelationNames()));\n            }\n        }\n        return returnedResults;\n    }\n\n    @Override\n    public Object[] scanRowyKeys(FilterList filterList, String tableName, String columnFamilyName, String columnName,\n            final Class rowKeyClazz) throws IOException\n    {\n        HTableInterface hTable = null;\n        hTable = gethTable(tableName);\n        return hbaseReader.scanRowKeys(hTable, filterList, columnFamilyName, columnName, rowKeyClazz);\n    }\n\n    private Object getObjectFromByteArray(EntityType entityType, byte[] value, String jpaColumnName, EntityMetadata m)\n    {\n        if (jpaColumnName != null)\n        {\n            String fieldName = m.getFieldName(jpaColumnName);\n            if (fieldName != null)\n            {\n                Attribute attribute = fieldName != null ? entityType.getAttribute(fieldName) : null;\n\n                EntityMetadata relationMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                        attribute.getJavaType());\n                Object colValue = PropertyAccessorHelper.getObject(relationMetadata.getIdAttribute().getJavaType(),\n                        (byte[]) value);\n                return colValue;\n            }\n        }\n        log.warn(\"No value found for column {}, returning null.\", jpaColumnName);\n        return null;\n    }\n\n    /**\n     * \n     * @param tableName\n     * @param entity\n     * @param rowId\n     * @param metaModel\n     * @param attributes\n     * @param columnWrapper\n     * @param persistentData\n     * @return\n     * @throws IOException\n     */\n    public Map<String, HBaseDataWrapper> preparePersistentData(String tableName, String columnFamily, Object entity,\n            Object rowId, MetamodelImpl metaModel, Set<Attribute> attributes, HBaseDataWrapper columnWrapper,\n            List<HBaseDataWrapper> persistentData, boolean showQuery) throws IOException\n    {\n\n        Map<String, HBaseDataWrapper> persistentDataWrappers = new HashMap<String, HBaseDataWrapper>();\n        persistentDataWrappers.put(columnFamily, columnWrapper);\n        StringBuilder printQuery = null;\n        if (showQuery)\n        {\n            printQuery = new StringBuilder(\"Persist data into \").append(columnFamily).append(\" with PK=\")\n                    .append(rowId.toString()).append(\" , \");\n        }\n\n        for (Attribute column : attributes)\n        {\n            String fieldName = ((AbstractAttribute) column).getJPAColumnName();\n            String columFamilyTableName = ((AbstractAttribute) column).getTableName() != null ? ((AbstractAttribute) column)\n                    .getTableName() : columnFamily;\n\n            persistentDataWrappers = getHBaseWrapperObj(rowId, entity, columFamilyTableName, persistentDataWrappers,\n                    persistentData);\n\n            columnWrapper = persistentDataWrappers.get(columFamilyTableName);\n            columnWrapper.setColumnFamily(columFamilyTableName);\n\n            Class javaType = ((AbstractAttribute) column).getBindableJavaType();\n            if (metaModel.isEmbeddable(javaType))\n            {\n                String columnFamilyName = ((AbstractAttribute) column).getJPAColumnName();\n                Field columnFamilyField = (Field) column.getJavaMember();\n                Object columnFamilyObject = null;\n                try\n                {\n                    columnFamilyObject = PropertyAccessorHelper.getObject(entity, columnFamilyField);\n                }\n                catch (PropertyAccessException paex)\n                {\n                    log.error(\"Error while getting {}, field from entity {} .\", columnFamilyName, entity);\n                    throw new KunderaException(paex);\n                }\n\n                if (columnFamilyObject != null)\n                {\n                    // continue;\n                    Set<Attribute> columns = metaModel.embeddable(javaType).getAttributes();\n\n                    Map<String, Attribute> columnNameToAttribute = new HashMap<String, Attribute>();\n                    Map<String, Object> columnNameToValue = new HashMap<String, Object>();\n                    if (column.isCollection())\n                    {\n                        String dynamicCFName = null;\n\n                        ElementCollectionCacheManager ecCacheHandler = ElementCollectionCacheManager.getInstance();\n                        // Check whether it's first time insert or updation\n                        if (ecCacheHandler.isCacheEmpty())\n                        { // First time insert\n                            int count = 0;\n                            for (Object obj : (Collection) columnFamilyObject)\n                            {\n                                String embeddableColumFamilyName = columFamilyTableName;\n                                Map<Map<String, Class<?>>, HBaseDataWrapper> embeDaableDataWrappers = new HashMap<Map<String, Class<?>>, HBaseDataWrapper>();\n                                for (Attribute attribute : columns)\n                                {\n                                    embeddableColumFamilyName = ((AbstractAttribute) attribute).getTableName() != null ? ((AbstractAttribute) attribute)\n                                            .getTableName() : columFamilyTableName;\n                                    String columnName = columnFamilyName + Constants.EMBEDDED_COLUMN_NAME_DELIMITER\n                                            + ((AbstractAttribute) attribute).getJPAColumnName()\n                                            + Constants.EMBEDDED_COLUMN_NAME_DELIMITER + count;\n\n                                    Map<String, Class<?>> embeddableMap = new HashMap<String, Class<?>>();\n                                    embeddableMap.put(embeddableColumFamilyName, obj.getClass());\n\n                                    embeDaableDataWrappers = getEmbeddableHBaseWrapperObj(rowId, obj,\n                                            embeddableColumFamilyName, embeDaableDataWrappers, persistentData,\n                                            embeddableMap);\n\n                                    HBaseDataWrapper embeddableColumnWrapper = embeDaableDataWrappers\n                                            .get(embeddableMap);\n                                    embeddableColumnWrapper.setColumnFamily(embeddableColumFamilyName);\n\n                                    embeddableColumnWrapper.addColumn(columnName, attribute);\n                                    embeddableColumnWrapper.addValue(columnName,\n                                            PropertyAccessorHelper.getObject(obj, (Field) attribute.getJavaMember()));\n                                }\n                                count++;\n                            }\n                        }\n                        else\n                        {\n                            // Updation\n                            // Check whether this object is already in cache,\n                            // which\n                            // means we already have a column family with that\n                            // name\n                            // Otherwise we need to generate a fresh column\n                            // family\n                            // name\n                            int lastEmbeddedObjectCount = ecCacheHandler.getLastElementCollectionObjectCount(rowId);\n                            for (Object obj : (Collection) columnFamilyObject)\n                            {\n                                String embeddableColumFamilyName = columFamilyTableName;\n                                dynamicCFName = ecCacheHandler.getElementCollectionObjectName(rowId, obj);\n                                if (dynamicCFName == null)\n                                { // Fresh row\n                                    ++lastEmbeddedObjectCount;\n                                    Map<Map<String, Class<?>>, HBaseDataWrapper> embeDaableDataWrappers = new HashMap<Map<String, Class<?>>, HBaseDataWrapper>();\n                                    for (Attribute attribute : columns)\n                                    {\n                                        embeddableColumFamilyName = ((AbstractAttribute) attribute).getTableName() != null ? ((AbstractAttribute) attribute)\n                                                .getTableName() : columFamilyTableName;\n                                        String columnName = columnFamilyName + Constants.EMBEDDED_COLUMN_NAME_DELIMITER\n                                                + ((AbstractAttribute) attribute).getJPAColumnName()\n                                                + Constants.EMBEDDED_COLUMN_NAME_DELIMITER + (lastEmbeddedObjectCount);\n\n                                        Map<String, Class<?>> embeddableMap = new HashMap<String, Class<?>>();\n                                        embeddableMap.put(embeddableColumFamilyName, obj.getClass());\n\n                                        embeDaableDataWrappers = getEmbeddableHBaseWrapperObj(rowId, obj,\n                                                embeddableColumFamilyName, embeDaableDataWrappers, persistentData,\n                                                embeddableMap);\n\n                                        HBaseDataWrapper embeddableColumnWrapper = embeDaableDataWrappers\n                                                .get(embeddableMap);\n                                        embeddableColumnWrapper.setColumnFamily(embeddableColumFamilyName);\n\n                                        embeddableColumnWrapper.addColumn(columnName, attribute);\n                                        embeddableColumnWrapper.addValue(columnName, PropertyAccessorHelper.getObject(\n                                                obj, (Field) attribute.getJavaMember()));\n                                    }\n                                }\n                            }\n                            // Clear embedded collection cache for GC\n                            ecCacheHandler.clearCache();\n                        }\n                    }\n                    else\n                    {\n\n                        // Write Column family which was Embedded object in\n                        // entity\n                        Map<Map<String, Class<?>>, HBaseDataWrapper> embeDaableDataWrappers = new HashMap<Map<String, Class<?>>, HBaseDataWrapper>();\n                        String embeddableColumFamilyName = columFamilyTableName;\n                        for (Attribute attribute : columns)\n                        {\n                            embeddableColumFamilyName = ((AbstractAttribute) attribute).getTableName() != null ? ((AbstractAttribute) attribute)\n                                    .getTableName() : columFamilyTableName;\n\n                            Map<String, Class<?>> embeddableMap = new HashMap<String, Class<?>>();\n                            embeddableMap.put(embeddableColumFamilyName, columnFamilyObject.getClass());\n\n                            embeDaableDataWrappers = getEmbeddableHBaseWrapperObj(rowId, columnFamilyObject,\n                                    embeddableColumFamilyName, embeDaableDataWrappers, persistentData, embeddableMap);\n\n                            HBaseDataWrapper embeddableColumnWrapper = embeDaableDataWrappers.get(embeddableMap);\n\n                            embeddableColumnWrapper.setColumnFamily(embeddableColumFamilyName);\n\n                            embeddableColumnWrapper.addColumn(((AbstractAttribute) attribute).getJPAColumnName(),\n                                    attribute);\n                            embeddableColumnWrapper.addValue(\n                                    ((AbstractAttribute) attribute).getJPAColumnName(),\n                                    PropertyAccessorHelper.getObject(columnFamilyObject,\n                                            (Field) attribute.getJavaMember()));\n                        }\n                    }\n                }\n            }\n            else if (!column.isAssociation())\n            {\n                Object fieldValue = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());\n                columnWrapper.addColumn(fieldName, column);\n                columnWrapper.addValue(fieldName, fieldValue);\n                if (showQuery)\n                {\n                    fieldValue = fieldValue != null ? fieldValue.toString() : fieldValue;\n                    printQuery.append(fieldName).append(\"=\").append(fieldValue).append(\" , \");\n                }\n            }\n        }\n\n        if (showQuery)\n        {\n            KunderaCoreUtils.printQuery(printQuery.substring(0, printQuery.lastIndexOf(\" , \")).toString(), showQuery);\n        }\n\n        return persistentDataWrappers;\n    }\n\n    private Map<String, HBaseDataWrapper> getHBaseWrapperObj(Object rowKey, Object entity, String columnFamily,\n            Map<String, HBaseDataWrapper> persistentDataMap, List<HBaseDataWrapper> persistentData)\n    {\n\n        HBaseDataWrapper existsHbaseWrapper = persistentDataMap.get(columnFamily);\n\n        if (existsHbaseWrapper == null)\n        {\n            HBaseDataWrapper hbaseWrapper = new HBaseDataWrapper(rowKey, new java.util.HashMap<String, Attribute>(),\n                    entity, columnFamily);\n            persistentDataMap.put(columnFamily, hbaseWrapper);\n            persistentData.add(hbaseWrapper);\n\n        }\n        return persistentDataMap;\n    }\n\n    private Map<Map<String, Class<?>>, HBaseDataWrapper> getEmbeddableHBaseWrapperObj(Object rowKey, Object entity,\n            String columnFamily, Map<Map<String, Class<?>>, HBaseDataWrapper> persistentDataMap,\n            List<HBaseDataWrapper> persistentData, Map<String, Class<?>> embeddableMap)\n    {\n        HBaseDataWrapper existsHbaseWrapper = persistentDataMap.get(embeddableMap);\n\n        if (existsHbaseWrapper == null)\n        {\n            HBaseDataWrapper hbaseWrapper = new HBaseDataWrapper(rowKey, new java.util.HashMap<String, Attribute>(),\n                    entity, columnFamily);\n            persistentDataMap.put(embeddableMap, hbaseWrapper);\n            persistentData.add(hbaseWrapper);\n        }\n        return persistentDataMap;\n    }\n\n    /**\n     * @param data\n     * @throws IOException\n     */\n    public void batch_insert(Map<HTableInterface, List<HBaseDataWrapper>> data) throws IOException\n    {\n        hbaseWriter.persistRows(data);\n    }\n\n    public void setFetchSize(final int fetchSize)\n    {\n        ((HBaseReader) hbaseReader).setFetchSize(fetchSize);\n    }\n\n    public Object next(EntityMetadata m)\n    {\n        Object entity = null;\n        HBaseData result = ((HBaseReader) hbaseReader).next();\n        List<HBaseData> results = new ArrayList<HBaseData>();\n        List output = new ArrayList();\n        results.add(result);\n        try\n        {\n            output = onRead(m.getSchema(), m.getEntityClazz(), m, output, gethTable(m.getSchema()), entity,\n                    m.getRelationNames(), results);\n        }\n        catch (IOException e)\n        {\n            log.error(\"Error during finding next record, Caused by: .\", e);\n            throw new KunderaException(e);\n        }\n\n        return output != null && !output.isEmpty() ? output.get(0) : output;\n    }\n\n    public boolean hasNext()\n    {\n        return ((HBaseReader) hbaseReader).hasNext();\n    }\n\n    public void reset()\n    {\n        resetFilter();\n        ((HBaseReader) hbaseReader).reset();\n    }\n\n    public void resetFilter()\n    {\n        filter = null;\n        filters = new ConcurrentHashMap<String, FilterList>();\n    }\n\n    public HBaseDataHandler getHandle()\n    {\n        HBaseDataHandler handler = new HBaseDataHandler(this.kunderaMetadata, this.conf, this.hTablePool);\n        handler.filter = this.filter;\n        handler.filters = this.filters;\n        return handler;\n    }\n\n    private Filter getFilter(final String columnFamily)\n    {\n        FilterList filter = filters.get(columnFamily);\n        if (filter == null)\n        {\n            return this.filter;\n        }\n        if (this.filter != null)\n        {\n            filter.addFilter(this.filter);\n        }\n        return filter;\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/config/HBasePropertyReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.config;\n\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.HBaseConstants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * HBase Property Reader reads hbase properties from property file\n * {kundera-hbase.properties} and put it into hbase schema metadata.\n * \n * @author kuldeep.mishra\n * \n */\npublic class HBasePropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n\n    /**\n     * The log instance.\n     */\n    private static Logger log = LoggerFactory.getLogger(HBasePropertyReader.class);\n\n    /**\n     * The Hbase schema metadata instance.\n     */\n    public static HBaseSchemaMetadata hsmd;\n\n    public HBasePropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        hsmd = new HBaseSchemaMetadata();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.PropertyReader#read(java.lang.String)\n     */\n\n    public void onXml(ClientProperties cp)\n    {\n        hsmd.onInitialize();\n        if (cp != null)\n        {\n            hsmd.setClientProperties(cp);\n        }\n    }\n\n    public class HBaseSchemaMetadata\n    {\n        /**\n         * zookeeper port.\n         */\n        private String zookeeperPort = \"2181\";\n\n        /**\n         * zookeeper host.\n         */\n        private String zookeeperHost;\n\n        /**\n         * client properties.\n         */\n        private ClientProperties clientProperties;\n\n        /**\n         * \n         */\n        private void onInitialize()\n        {\n            zookeeperHost = puMetadata != null ? puMetadata.getProperty(PersistenceProperties.KUNDERA_NODES) : null;\n        }\n\n        /**\n         * @return the clientProperties\n         */\n        public ClientProperties getClientProperties()\n        {\n            return clientProperties;\n        }\n\n        /**\n         * @param clientProperties\n         *            the clientProperties to set\n         */\n        private void setClientProperties(ClientProperties clientProperties)\n        {\n            this.clientProperties = clientProperties;\n        }\n\n        /**\n         * @return the zookeeper_port\n         */\n        public String getZookeeperPort()\n        {\n            DataStore ds = getDataStore();\n            if (ds != null && ds.getConnection() != null)\n            {\n                Connection conn = ds.getConnection();\n                if (conn.getProperties() != null && !conn.getProperties().isEmpty())\n                {\n                    zookeeperPort = conn.getProperties().getProperty(HBaseConstants.ZOOKEEPER_PORT).trim();\n                }\n            }\n            return zookeeperPort;\n        }\n\n        /**\n         * @return the zookeeper_host\n         */\n        public String getZookeeperHost()\n        {\n            DataStore ds = getDataStore();\n            if (ds != null && ds.getConnection() != null)\n            {\n                Connection conn = ds.getConnection();\n                if (conn.getProperties() != null && !conn.getProperties().isEmpty())\n                {\n                    zookeeperHost = conn.getProperties().getProperty(HBaseConstants.ZOOKEEPER_HOST.trim());\n                }\n            }\n            return zookeeperHost;\n        }\n\n        public DataStore getDataStore()\n        {\n            if (getClientProperties() != null && getClientProperties().getDatastores() != null)\n            {\n                for (DataStore dataStore : getClientProperties().getDatastores())\n                {\n                    if (dataStore.getName() != null && dataStore.getName().trim().equalsIgnoreCase(\"hbase\"))\n                    {\n                        return dataStore;\n                    }\n                }\n            }\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/query/BinaryComparatorFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.query;\n\nimport org.apache.hadoop.hbase.filter.BinaryComparator;\nimport org.apache.hadoop.hbase.filter.ByteArrayComparable;\n\nimport com.google.common.base.Function;\n\n/**\n * A factory for creating BinaryComparator objects.\n */\npublic class BinaryComparatorFactory implements Function<byte[], ByteArrayComparable>\n{\n    \n    /** The Constant INSTANCE. */\n    public static final BinaryComparatorFactory INSTANCE = new BinaryComparatorFactory();\n\n    /* (non-Javadoc)\n     * @see com.google.common.base.Function#apply(java.lang.Object)\n     */\n    public ByteArrayComparable apply(byte[] bytes)\n    {\n        return new BinaryComparator(bytes);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/query/HBaseQuery.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.query;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.StringTokenizer;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;\nimport org.apache.hadoop.hbase.filter.Filter;\nimport org.apache.hadoop.hbase.filter.FilterList;\nimport org.apache.hadoop.hbase.filter.PageFilter;\nimport org.apache.hadoop.hbase.filter.SingleColumnValueFilter;\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.HBaseClient;\nimport com.impetus.client.hbase.HBaseEntityReader;\nimport com.impetus.client.hbase.utils.HBaseUtils;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.query.QueryImpl;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * Query implementation for HBase, translates JPQL into HBase Filters using\n * {@link QueryTranslator}.\n * \n * @author vivek.mishra\n * \n */\npublic class HBaseQuery extends QueryImpl\n{\n\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(HBaseQuery.class);\n\n    public HBaseQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List<Object> populateEntities(EntityMetadata m, Client client)\n    {\n\n        ClientMetadata clientMetadata = ((ClientBase) client).getClientMetadata();\n\n        if (!MetadataUtils.useSecondryIndex(clientMetadata) && (clientMetadata.getIndexImplementor() != null))\n        {\n            return populateUsingLucene(m, client, null, kunderaQuery.getResult());\n        }\n        else\n        {\n            List results = onQuery(m, client);\n            return results;\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#recursivelyPopulateEntities(com.impetus\n     * .kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n        // required in case of associated entities.\n        List ls = onQuery(m, client);\n        return setRelationEntities(ls, client, m);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#getReader()\n     */\n    @Override\n    protected EntityReader getReader()\n    {\n        return new HBaseEntityReader(kunderaQuery, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()\n     */\n    @Override\n    protected int onExecuteUpdate()\n    {\n        return onUpdateDeleteEvent();\n    }\n\n    /**\n     * Parses and translates query into HBase filter and invokes client's method\n     * to return list of entities.\n     * \n     * @param m\n     *            Entity metadata\n     * @param client\n     *            hbase client\n     * @return list of entities.\n     */\n    private List onQuery(EntityMetadata m, Client client)\n    {\n        // Called only in case of standalone entity.\n        QueryTranslator translator = new QueryTranslator();\n        translator.translate(getKunderaQuery(), m, ((ClientBase) client).getClientMetadata());\n        // start with 1 as first element is alias.\n        List<String> columns = getTranslatedColumns(m, getKunderaQuery().getResult(), 1);\n        Filter filter = translator.getFilter();\n        if (translator.rowList != null && !translator.rowList.isEmpty())\n        {\n            return ((HBaseClient) client).findAll(m.getEntityClazz(), columns.toArray(new String[columns.size()]),\n                    translator.getRowList());\n        }\n        if (!translator.isWhereQuery() && columns != null)\n        {\n            return ((HBaseClient) client).findByRange(m.getEntityClazz(), m, translator.getStartRow(), translator\n                    .getEndRow(), columns.toArray(new String[columns.size()]), null, getKunderaQuery()\n                    .getFilterClauseQueue());\n        }\n\n        if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))\n        {\n            // if range query. means query over id column. create range\n            // scan method.\n\n            // else setFilter to client and invoke new method. find by\n            // query if isFindById is false! else invoke findById\n            if (translator.isWhereQuery() && !translator.isRangeScan())\n            {\n                return ((HBaseClient) client).findByQuery(m.getEntityClazz(), m, filter, getKunderaQuery()\n                        .getFilterClauseQueue(), columns.toArray(new String[columns.size()]));\n            }\n            else\n            {\n                return ((HBaseClient) client).findByRange(m.getEntityClazz(), m, translator.getStartRow(), translator\n                        .getEndRow(), columns.toArray(new String[columns.size()]), filter, getKunderaQuery()\n                        .getFilterClauseQueue());\n            }\n        }\n        else\n        {\n            return populateUsingLucene(m, client, null, null);\n        }\n    }\n\n    /**\n     * @param columns\n     * @param m\n     * @return\n     */\n    private List<String> getTranslatedColumns(EntityMetadata m, String[] columns, final int startWith)\n    {\n        List<String> translatedColumns = new ArrayList<String>();\n        if (columns != null)\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n\n            EntityType entity = metaModel.entity(m.getEntityClazz());\n            for (int i = startWith; i < columns.length; i++)\n            {\n                if (columns[i] != null)\n                {\n                    String fieldName = null;\n                    String embeddedFieldName = null;\n                    // used string tokenizer to check for embedded column.\n                    StringTokenizer stringTokenizer = new StringTokenizer(columns[i], \".\");\n                    // if need to select embedded columns\n                    if (stringTokenizer.countTokens() > 1)\n                    {\n                        fieldName = stringTokenizer.nextToken();\n                        embeddedFieldName = stringTokenizer.nextToken();\n                        Attribute col = entity.getAttribute(fieldName); // get\n                                                                        // embedded\n                                                                        // column\n                        EmbeddableType embeddableType = metaModel.embeddable(col.getJavaType()); // get\n                                                                                                 // embeddable\n                                                                                                 // type\n                        Attribute attribute = embeddableType.getAttribute(embeddedFieldName);\n                        translatedColumns.add(((AbstractAttribute) attribute).getJPAColumnName());\n                    }\n                    else\n                    {\n                        // For all columns\n                        fieldName = columns[i];\n                        Attribute col = entity.getAttribute(fieldName);\n                        onEmbeddable(translatedColumns, metaModel, col,\n                                metaModel.isEmbeddable(((AbstractAttribute) col).getBindableJavaType()));\n                    }\n                }\n            }\n        }\n        return translatedColumns;\n    }\n\n    /**\n     * @param translatedColumns\n     * @param metaModel\n     * @param col\n     */\n    private void onEmbeddable(List<String> translatedColumns, MetamodelImpl metaModel, Attribute col,\n            boolean isEmbeddable)\n    {\n        if (isEmbeddable)\n        {\n            EmbeddableType embeddableType = metaModel.embeddable(col.getJavaType());\n\n            Set<Attribute> attributes = embeddableType.getAttributes();\n\n            for (Attribute attribute : attributes)\n            {\n                translatedColumns.add(((AbstractAttribute) attribute).getJPAColumnName());\n            }\n        }\n        else\n        {\n            translatedColumns.add(((AbstractAttribute) col).getJPAColumnName());\n        }\n    }\n\n    /**\n     * Query translator to translate JPQL into HBase query definition(e.g.\n     * Filter/Filterlist)\n     * \n     * @author vivek.mishra\n     * \n     */\n    class QueryTranslator\n    {\n\n        private static final String CLOSE_BRACKET = \")\";\n\n        private static final String IN_CLAUSE = \"IN\";\n\n        private static final String OR_OPERATOR = \"OR\";\n\n        private static final String OPEN_BRACKET = \"(\";\n\n        /* filter list to hold collection for applied filters */\n        private List<Filter> filterList;\n\n        /*\n         * byte[] value for start row, in case of range query, else will contain\n         * null.\n         */\n        private byte[] startRow;\n\n        /*\n         * byte[] value for end row, in case of range query, else will contain\n         * null.\n         */\n        private byte[] endRow;\n\n        /*\n         * byte[] value for list of rows null.\n         */\n        private List rowList = new ArrayList();\n\n        /*\n         * boolean value for finding whether its OR or in query.\n         */\n        private boolean isORQuery;\n\n        private boolean isWhereQuery;\n\n        /**\n         * @return\n         */\n        public boolean isORQuery()\n        {\n            return isORQuery;\n        }\n\n        /**\n         * @return\n         */\n        public Object[] getRowList()\n        {\n            return rowList.toArray();\n        }\n\n        /**\n         * @param rowList\n         */\n        public void setRowList(List rowList)\n        {\n            if (rowList == null)\n            {\n                rowList = new ArrayList<Filter>();\n            }\n            this.rowList = rowList;\n        }\n\n        /**\n         * Translates kundera query into collection of to be applied HBase\n         * filter/s.\n         * \n         * @param query\n         *            kundera query.\n         * @param m\n         *            entity's metadata.\n         */\n        void translate(KunderaQuery query, EntityMetadata m, ClientMetadata clientMetadata)\n        {\n            String idColumn = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n\n            boolean useFilter = MetadataUtils.useSecondryIndex(clientMetadata);\n            for (Object obj : query.getFilterClauseQueue())\n            {\n                boolean isIdColumn = false;\n                // parse for filter(e.g. where) clause.\n\n                if (obj instanceof FilterClause)\n                {\n                    String condition = ((FilterClause) obj).getCondition();\n                    String name = ((FilterClause) obj).getProperty();\n                    Object value = ((FilterClause) obj).getValue().get(0);\n                    if (idColumn.equalsIgnoreCase(name))\n                    {\n                        isIdColumn = true;\n                    }\n                    onParseFilter(condition, name, value, isIdColumn, m, useFilter);\n                }\n                else\n                {\n                    // Case of AND and OR clause.\n                    String opr = obj.toString();\n                    if (MetadataUtils.useSecondryIndex(clientMetadata))\n                    {\n                        if (opr.trim().equalsIgnoreCase(OR_OPERATOR))\n                        {\n                            this.isORQuery = true;\n                            // log.error(\"Support for OR clause is not enabled with in Hbase\");\n                            // throw new\n                            // QueryHandlerException(\"Unsupported clause \" + opr\n                            // + \" for Hbase\");\n                        }\n                    }\n                }\n            }\n        }\n\n        /**\n         * Returns collection of parsed filter.\n         * \n         * @return map.\n         */\n        Filter getFilter()\n        {\n            FilterList filters = new FilterList(new PageFilter(getMaxResults()));\n            if (filterList != null)\n            {\n                this.setWhereQuery(true);\n                if (this.isORQuery)\n                {\n                    filters.addFilter(new FilterList(FilterList.Operator.MUST_PASS_ONE, filterList));\n                }\n                else\n                {\n                    filters.addFilter(new FilterList(filterList));\n                }\n            }\n            return filters;\n        }\n\n        /**\n         * On parsing filter clause(e.g. WHERE clause).\n         * \n         * @param condition\n         *            condition\n         * @param name\n         *            column name.\n         * @param value\n         *            column value.\n         * @param isIdColumn\n         *            if it is an id column.\n         * @param m\n         *            entity metadata.\n         */\n        private void onParseFilter(String condition, String name, Object value, boolean isIdColumn, EntityMetadata m,\n                boolean useFilter)\n        {\n            if (condition.trim().equalsIgnoreCase(IN_CLAUSE))\n            {\n\n                onInClause(name, value, m, isIdColumn);\n\n            }\n            else\n            {\n                SingleColumnFilterFactory factory = HBaseUtils.getOperator(condition, isIdColumn, useFilter);\n                CompareOp operator = factory.getOperator();\n                if (!isIdColumn)\n                {\n                    Filter f = createQualifierValueFilter(name, value, m, factory);\n                    addToFilter(f);\n                }\n                else\n                {\n                    if (operator.equals(CompareOp.GREATER_OR_EQUAL) || operator.equals(CompareOp.GREATER))\n                    {\n                        byte[] valueInBytes = getBytes(name, m, value);\n                        startRow = valueInBytes;\n                    }\n                    else if (operator.equals(CompareOp.LESS_OR_EQUAL) || operator.equals(CompareOp.LESS))\n                    {\n                        byte[] valueInBytes = getBytes(name, m, value);\n                        endRow = valueInBytes;\n                    }\n                    else if (operator.equals(CompareOp.EQUAL))\n                    {\n                        startRow = endRow = getBytes(m.getIdAttribute().getName(), m, value);\n                    }\n                    else\n                    {\n                        throw new UnsupportedOperationException(\" Condition \" + condition\n                                + \" is not suported for query on row key!\");\n                    }\n                }\n            }\n        }\n\n        /**\n         * @param name\n         * @param value\n         * @param m\n         * @param factory\n         * @return\n         */\n        private Filter createQualifierValueFilter(String name, Object value,\n                EntityMetadata m, SingleColumnFilterFactory factory)\n        {\n            List<String> columns = null;\n            byte[] valueInBytes = getBytes(name, m, value);\n            if (new StringTokenizer(name, \".\").countTokens() > 1)\n            {\n                columns = getTranslatedColumns(m, new String[] { name }, 0);\n            }\n\n            if (columns != null && !columns.isEmpty())\n            {\n                name = columns.get(0);\n            }\n            return factory.create(m.getTableName(), name, valueInBytes);\n        }\n\n        /**\n         * @param name\n         * @param value\n         * @param m\n         */\n        private void onInClause(String name, Object value, EntityMetadata m, boolean isIdColumn)\n        {\n            List<String> columns = null;\n            FilterList inClauseFilterList = new FilterList(FilterList.Operator.MUST_PASS_ONE);\n            if (new StringTokenizer(name, \".\").countTokens() > 1)\n            {\n                columns = getTranslatedColumns(m, new String[] { name }, 0);\n            }\n\n            if (columns != null && !columns.isEmpty())\n            {\n                name = columns.get(0);\n            }\n\n            String itemValues = String.valueOf(value);\n            itemValues = itemValues.startsWith(OPEN_BRACKET) && itemValues.endsWith(CLOSE_BRACKET) ? itemValues\n                    .substring(1, itemValues.length() - 1) : itemValues;\n            List<String> items = Arrays.asList(((String) itemValues).split(\"\\\\s*,\\\\s*\"));\n\n            for (String str : items)\n            {\n                str = str.trim();\n                str = (str.startsWith(\"\\\"\") && str.endsWith(\"\\\"\")) || (str.startsWith(\"'\") && str.endsWith(\"'\")) ? str\n                        .substring(1, str.length() - 1) : str;\n\n                byte[] valueInBytes = getBytes(name, m, str);\n                if (!isIdColumn)\n                {\n                    Filter f = new SingleColumnValueFilter(Bytes.toBytes(m.getTableName()), Bytes.toBytes(name),\n                            CompareOp.EQUAL, valueInBytes);\n                    inClauseFilterList.addFilter(f);\n\n                }\n                else\n                {\n                    rowList.add(valueInBytes);\n                }\n\n            }\n            if (!inClauseFilterList.getFilters().isEmpty())\n            {\n                addToFilter(inClauseFilterList);\n            }\n        }\n\n        /**\n         * @return the startRow\n         */\n        byte[] getStartRow()\n        {\n            return startRow;\n        }\n\n        /**\n         * @return the endRow\n         */\n        byte[] getEndRow()\n        {\n            return endRow;\n        }\n\n        boolean isRangeScan()\n        {\n            return startRow != null || endRow != null;\n        }\n\n        /**\n         * @param f\n         */\n        private void addToFilter(Filter f)\n        {\n            if (filterList == null)\n            {\n                filterList = new ArrayList<Filter>();\n            }\n            filterList.add(f);\n        }\n\n        public boolean isWhereQuery()\n        {\n            return isWhereQuery;\n        }\n\n        public void setWhereQuery(boolean isWhereQuery)\n        {\n            this.isWhereQuery = isWhereQuery;\n        }\n    }\n\n    /**\n     * Returns bytes of value object.\n     * \n     * @param jpaFieldName\n     * @param m\n     * @param value\n     * @return\n     */\n    private byte[] getBytes(String jpaFieldName, EntityMetadata m, Object value)\n    {\n        AbstractAttribute idCol = (AbstractAttribute) m.getIdAttribute();\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n\n        EntityType entity = metaModel.entity(m.getEntityClazz());\n        Class fieldClazz = null;\n        if (idCol.getName().equals(jpaFieldName))\n        {\n            Field f = (Field) idCol.getJavaMember();\n\n            if (metaModel.isEmbeddable(idCol.getBindableJavaType()))\n            {\n                fieldClazz = String.class;\n                Map<Attribute, List<Object>> columnValues = new HashMap<Attribute, List<Object>>();\n                Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields();\n                EmbeddableType embeddable = metaModel.embeddable(m.getIdAttribute().getBindableJavaType());\n\n                StringBuilder compositeKey = new StringBuilder();\n                for (Field field : fields)\n                {\n                    if (!ReflectUtils.isTransientOrStatic(field))\n                    {\n                        AbstractAttribute attrib = (AbstractAttribute) embeddable.getAttribute(field.getName());\n                        Object obj = PropertyAccessorHelper.getObject(value, field);\n                        compositeKey.append(\n                                PropertyAccessorHelper.fromSourceToTargetClass(String.class,\n                                        attrib.getBindableJavaType(), obj)).append(\"\\001\");\n                    }\n                }\n                compositeKey.delete(compositeKey.lastIndexOf(\"\\001\"), compositeKey.length());\n                value = compositeKey.toString();\n            }\n            else\n            {\n                fieldClazz = f.getType();\n            }\n        }\n        else\n        {\n            StringTokenizer tokenizer = new StringTokenizer(jpaFieldName, \".\");\n            String embeddedFieldName = null;\n            if (tokenizer.countTokens() > 1)\n            {\n                embeddedFieldName = tokenizer.nextToken();\n                String fieldName = tokenizer.nextToken();\n                Attribute embeddableAttribute = entity.getAttribute(embeddedFieldName);\n                EmbeddableType embeddableType = metaModel.embeddable(embeddableAttribute.getJavaType());\n                Attribute embeddedAttribute = embeddableType.getAttribute(fieldName);\n                jpaFieldName = ((AbstractAttribute) embeddedAttribute).getJPAColumnName();\n                fieldClazz = ((AbstractAttribute) embeddedAttribute).getBindableJavaType();\n            }\n            else\n            {\n                String discriminatorColumn = ((AbstractManagedType) entity).getDiscriminatorColumn();\n\n                if (!jpaFieldName.equals(discriminatorColumn))\n                {\n                    String fieldName = m.getFieldName(jpaFieldName);\n                    Attribute col = entity.getAttribute(fieldName);\n                    fieldClazz = ((AbstractAttribute) col).getBindableJavaType();\n                }\n            }\n        }\n\n        if (fieldClazz != null)\n        {\n            return HBaseUtils.getBytes(value, fieldClazz);\n        }\n        else\n        {\n            // Treat default as UTF8-Type. { in case of discriminator column}\n            return HBaseUtils.getBytes(value, String.class);\n        }\n    }\n\n    @Override\n    public void close()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    @Override\n    public Iterator iterate()\n    {\n        EntityMetadata m = getEntityMetadata();\n        Client client = persistenceDelegeator.getClient(m);\n\n        if (!MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))\n        {\n            throw new UnsupportedOperationException(\"Scrolling over hbase is unsupported for lucene queries\");\n        }\n        QueryTranslator translator = new QueryTranslator();\n        translator.translate(getKunderaQuery(), m, ((ClientBase) client).getClientMetadata());\n        // start with 1 as first element is alias.\n        List<String> columns = getTranslatedColumns(m, getKunderaQuery().getResult(), 1);\n\n        return new ResultIterator((HBaseClient) client, m, persistenceDelegeator,\n                getFetchSize() != null ? getFetchSize() : this.maxResult, translator, columns);\n    }\n\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n        QueryTranslator translator = new QueryTranslator();\n        translator.translate(getKunderaQuery(), m, ((ClientBase) client).getClientMetadata());\n        List<String> columns = getTranslatedColumns(m, getKunderaQuery().getResult(), 1);\n\n        return ((HBaseClient) client).findByRange(m.getEntityClazz(), m, translator.getStartRow(), translator\n                .getEndRow(), columns.toArray(new String[columns.size()]), null, getKunderaQuery()\n                .getFilterClauseQueue());\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/query/LikeComparatorFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.query;\n\nimport static java.lang.Character.isLetterOrDigit;\n\nimport com.google.common.base.Function;\nimport org.apache.hadoop.hbase.filter.ByteArrayComparable;\nimport org.apache.hadoop.hbase.filter.RegexStringComparator;\n\n/**\n * A factory for creating LikeComparator objects.\n */\npublic class LikeComparatorFactory implements Function<byte[], ByteArrayComparable>\n{\n\n    /** The Constant INSTANCE. */\n    public static final LikeComparatorFactory INSTANCE = new LikeComparatorFactory();\n\n    /**\n     * Like to regex.\n     * \n     * @param like\n     *            the like\n     * @return the string\n     */\n    static String likeToRegex(String like)\n    {\n        StringBuilder builder = new StringBuilder();\n        boolean wasPercent = false;\n        for (int i = 0; i < like.length(); ++i)\n        {\n            char c = like.charAt(i);\n            if (isPlain(c))\n            {\n                if (wasPercent)\n                {\n                    wasPercent = false;\n                    builder.append(\".*\");\n                }\n                builder.append(c);\n            }\n            else if (wasPercent)\n            {\n                wasPercent = false;\n                if (c == '%')\n                {\n                    builder.append('%');\n                }\n                else\n                {\n                    builder.append(\".*\").append(c);\n                }\n            }\n            else\n            {\n                if (c == '%')\n                {\n                    wasPercent = true;\n                }\n                else\n                {\n                    builder.append('\\\\').append(c);\n                }\n            }\n        }\n        if (wasPercent)\n        {\n            builder.append(\".*\");\n        }\n        return builder.toString();\n    }\n\n    /**\n     * Checks if is plain.\n     * \n     * @param c\n     *            the c\n     * @return true, if is plain\n     */\n    private static boolean isPlain(char c)\n    {\n        return isLetterOrDigit(c) || \"_@ ~`\\\"'#<>,;;=!&\".indexOf(c) >= 0;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.google.common.base.Function#apply(java.lang.Object)\n     */\n    public ByteArrayComparable apply(byte[] bytes)\n    {\n        return new RegexStringComparator(likeToRegex(new String(bytes)));\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/query/RegexComparatorFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.query;\n\nimport org.apache.hadoop.hbase.filter.ByteArrayComparable;\nimport org.apache.hadoop.hbase.filter.RegexStringComparator;\n\nimport com.google.common.base.Function;\n\n/**\n * A factory for creating RegexComparator objects.\n * \n * @author karthikp.manchala\n */\npublic class RegexComparatorFactory implements Function<byte[], ByteArrayComparable>\n{\n\n    /** The Constant INSTANCE. */\n    public static final RegexComparatorFactory INSTANCE = new RegexComparatorFactory();\n\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.google.common.base.Function#apply(java.lang.Object)\n     */\n    public ByteArrayComparable apply(byte[] bytes)\n    {\n        return new RegexStringComparator(new String(bytes));\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/query/ResultIterator.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.query;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.NoSuchElementException;\n\nimport org.apache.hadoop.hbase.filter.FilterList;\nimport org.apache.hadoop.hbase.filter.KeyOnlyFilter;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.HBaseClient;\nimport com.impetus.client.hbase.admin.HBaseDataHandler;\nimport com.impetus.client.hbase.query.HBaseQuery.QueryTranslator;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.IResultIterator;\nimport com.impetus.kundera.query.QueryHandlerException;\n\n/**\n * ResultIterator class, used to iterate over results.\n * \n * @author Vivek.Mishra\n * \n */\nclass ResultIterator<E> implements IResultIterator<E>\n{\n    private HBaseClient client;\n\n    private EntityMetadata entityMetadata;\n\n    private PersistenceDelegator persistenceDelegator;\n\n    private HBaseDataHandler handler;\n\n    private QueryTranslator translator;\n\n    private List<String> columns;\n\n    private int fetchSize;\n\n    private int count;\n\n    private boolean scrollComplete;\n\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(ResultIterator.class);\n\n    public ResultIterator(HBaseClient client, EntityMetadata m, PersistenceDelegator pd, int fetchSize,\n            QueryTranslator translator, List<String> columns)\n    {\n        this.entityMetadata = m;\n        this.client = client;\n        this.persistenceDelegator = pd;\n        this.handler = ((HBaseClient) client).getHandle();\n        this.handler.setFetchSize(fetchSize);\n        this.fetchSize = fetchSize;\n        this.translator = translator;\n        this.columns = columns;\n        onQuery(m, client);\n    }\n\n    @Override\n    public boolean hasNext()\n    {\n\n        boolean available = handler.hasNext();\n        if (!available || fetchSize == 0)\n        {\n            scrollComplete = true;\n            handler.reset();\n            return false;\n        }\n        return available;\n    }\n\n    @Override\n    public E next()\n    {\n        if (!checkOnFetchSize() || scrollComplete)\n        {\n            throw new NoSuchElementException(\"Nothing to scroll further for:\" + entityMetadata.getEntityClazz());\n        }\n\n        E result = (E) handler.next(entityMetadata);\n        if (!entityMetadata.isRelationViaJoinTable()\n                && (entityMetadata.getRelationNames() == null || (entityMetadata.getRelationNames().isEmpty())))\n        {\n            return result;\n        }\n        else\n        {\n            return result = setRelationEntities(result, client, entityMetadata);\n        }\n    }\n\n    @Override\n    public void remove()\n    {\n        throw new UnsupportedOperationException(\"remove() over result iterator is not supported\");\n    }\n\n    private E setRelationEntities(Object enhanceEntity, Client client, EntityMetadata m)\n    {\n        // Enhance entities can contain or may not contain relation.\n        // if it contain a relation means it is a child\n        // if it does not then it means it is a parent.\n        E result = null;\n        if (enhanceEntity != null)\n        {\n\n            if (!(enhanceEntity instanceof EnhanceEntity))\n            {\n                enhanceEntity = new EnhanceEntity(enhanceEntity, PropertyAccessorHelper.getId(enhanceEntity, m), null);\n            }\n\n            EnhanceEntity ee = (EnhanceEntity) enhanceEntity;\n\n            result = (E) client.getReader().recursivelyFindEntities(ee.getEntity(), ee.getRelations(), m,\n                    persistenceDelegator, false, new HashMap<Object, Object>());\n        }\n\n        return result;\n    }\n\n    /**\n     * Parses and translates query into HBase filter and invokes client's method\n     * to return list of entities.\n     * \n     * @param m\n     *            Entity metadata\n     * @param client\n     *            hbase client\n     * @return list of entities.\n     */\n    private void onQuery(EntityMetadata m, Client client)\n    {\n\n        try\n        {\n            // Called only in case of standalone entity.\n            FilterList filter = null;\n            if (translator.getFilter() != null)\n            {\n                filter = new FilterList(translator.getFilter());\n            }\n            String[] columnAsArr = getColumnsAsArray();\n\n            if (isFindKeyOnly(m, columnAsArr))\n            {\n                this.handler.setFilter(new KeyOnlyFilter());\n            }\n\n            if (filter == null && columns != null)\n            {\n                handler.readDataByRange(m.getSchema(), m.getEntityClazz(), m, translator.getStartRow(),\n                        translator.getEndRow(), columnAsArr, null);\n            }\n            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))\n            {\n                if (filter == null)\n                {\n                    // means complete scan without where clause, scan all\n                    // records.\n                    // findAll.\n                    if (translator.isRangeScan())\n                    {\n                        handler.readDataByRange(m.getSchema(), m.getEntityClazz(), m, translator.getStartRow(),\n                                translator.getEndRow(), columnAsArr, null);\n                    }\n                    else\n                    {\n                        handler.readDataByRange(m.getSchema(), m.getEntityClazz(), m, null, null, columnAsArr, null);\n                    }\n                }\n                else\n                {\n                    // means WHERE clause is present.\n                    if (translator.isRangeScan())\n                    {\n                        handler.readDataByRange(m.getSchema(), m.getEntityClazz(), m, translator.getStartRow(),\n                                translator.getEndRow(), columnAsArr, filter);\n                    }\n                    else\n                    {\n                        // if range query. means query over id column. create\n                        // range\n                        // scan method.\n\n                        handler.readData(m.getSchema(), entityMetadata.getEntityClazz(), entityMetadata, null,\n                                m.getRelationNames(), filter, columnAsArr);\n                    }\n                }\n            }\n        }\n        catch (IOException ioex)\n        {\n            log.error(\"Error while executing query{} , Caused by:\", ioex);\n            throw new QueryHandlerException(\"Error while executing , Caused by:\", ioex);\n        }\n    }\n\n    private String[] getColumnsAsArray()\n    {\n        return columns.toArray(new String[columns.size()]);\n    }\n\n    /**\n     * @param metadata\n     * @param columns\n     * @return\n     */\n    private boolean isFindKeyOnly(EntityMetadata metadata, String[] columns)\n    {\n        int noOFColumnsToFind = 0;\n        boolean findIdOnly = false;\n        if (columns != null)\n        {\n            for (String column : columns)\n            {\n                if (column != null)\n                {\n                    if (column.equals(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName()))\n                    {\n                        noOFColumnsToFind++;\n                        findIdOnly = true;\n                    }\n                    else\n                    {\n                        noOFColumnsToFind++;\n                        findIdOnly = false;\n                    }\n                }\n            }\n        }\n        if (noOFColumnsToFind == 1 && findIdOnly)\n        {\n            return true;\n        }\n        return false;\n    }\n\n    @Override\n    public List<E> next(int chunkSize)\n    {\n        int counter = 0;\n        List<E> chunkList = new ArrayList<E>();\n        while (this.hasNext() && counter++ < chunkSize)\n        {\n            chunkList.add(this.next());\n        }\n        return chunkList;\n    }\n\n    /**\n     * Check on fetch size. returns true, if count on fetched rows is less than\n     * fetch size.\n     * \n     * @return\n     */\n    private boolean checkOnFetchSize()\n    {\n        if (count++ < fetchSize)\n        {\n            return true;\n        }\n        count = 0;\n        scrollComplete = true;\n        return false;\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/query/SingleColumnFilterFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.query;\n\nimport static org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;\nimport static org.apache.hadoop.hbase.util.Bytes.toBytes;\n\nimport com.google.common.base.Function;\nimport org.apache.hadoop.hbase.filter.ByteArrayComparable;\nimport org.apache.hadoop.hbase.filter.Filter;\nimport org.apache.hadoop.hbase.filter.SingleColumnValueFilter;\n\n/**\n * A factory for creating SingleColumnFilter objects.\n */\npublic class SingleColumnFilterFactory\n{\n\n    /** The Constant EQUAL. */\n    public static final SingleColumnFilterFactory EQUAL = new SingleColumnFilterFactory(CompareOp.EQUAL,\n            BinaryComparatorFactory.INSTANCE);\n\n    /** The Constant GREATER. */\n    public static final SingleColumnFilterFactory GREATER = new SingleColumnFilterFactory(CompareOp.GREATER,\n            BinaryComparatorFactory.INSTANCE);\n\n    /** The Constant LESS. */\n    public static final SingleColumnFilterFactory LESS = new SingleColumnFilterFactory(CompareOp.LESS,\n            BinaryComparatorFactory.INSTANCE);\n\n    /** The Constant GREATER_OR_EQUAL. */\n    public static final SingleColumnFilterFactory GREATER_OR_EQUAL = new SingleColumnFilterFactory(\n            CompareOp.GREATER_OR_EQUAL, BinaryComparatorFactory.INSTANCE);\n\n    /** The Constant LESS_OR_EQUAL. */\n    public static final SingleColumnFilterFactory LESS_OR_EQUAL = new SingleColumnFilterFactory(\n            CompareOp.LESS_OR_EQUAL, BinaryComparatorFactory.INSTANCE);\n\n    /** The Constant LIKE. */\n    public static final SingleColumnFilterFactory LIKE = new SingleColumnFilterFactory(CompareOp.EQUAL,\n            LikeComparatorFactory.INSTANCE);\n    \n    /** The Constant REGEXP. */\n    public static final SingleColumnFilterFactory REGEXP = new SingleColumnFilterFactory(CompareOp.EQUAL,\n            RegexComparatorFactory.INSTANCE);\n\n    /** The operator. */\n    private final CompareOp operator;\n\n    /**\n     * Gets the operator.\n     * \n     * @return the operator\n     */\n    public CompareOp getOperator()\n    {\n        return operator;\n    }\n\n    /** The comparator factory. */\n    private final Function<byte[], ByteArrayComparable> comparatorFactory;\n\n    /**\n     * Instantiates a new single column filter factory.\n     * \n     * @param operator\n     *            the operator\n     * @param comparatorFactory\n     *            the comparator factory\n     */\n    public SingleColumnFilterFactory(CompareOp operator, Function<byte[], ByteArrayComparable> comparatorFactory)\n    {\n        this.operator = operator;\n        this.comparatorFactory = comparatorFactory;\n    }\n\n    /**\n     * Creates the.\n     * \n     * @param family\n     *            the family\n     * @param column\n     *            the column\n     * @param value\n     *            the value\n     * @return the filter\n     */\n    public Filter create(String family, String column, byte[] value)\n    {\n        return new SingleColumnValueFilter(toBytes(family), toBytes(column), operator, comparatorFactory.apply(value));\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/schemamanager/HBaseSchemaManager.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.schemamanager;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.hbase.HBaseConfiguration;\nimport org.apache.hadoop.hbase.HColumnDescriptor;\nimport org.apache.hadoop.hbase.HTableDescriptor;\nimport org.apache.hadoop.hbase.MasterNotRunningException;\nimport org.apache.hadoop.hbase.TableNotFoundException;\nimport org.apache.hadoop.hbase.ZooKeeperConnectionException;\nimport org.apache.hadoop.hbase.client.HBaseAdmin;\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.config.HBasePropertyReader;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Schema;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Schema.Table;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.configure.schema.TableInfo;\nimport com.impetus.kundera.configure.schema.api.AbstractSchemaManager;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * Manages auto schema operation {@code ScheamOperationType} for HBase data\n * store.\n * \n * @author Kuldeep.kumar\n * \n */\npublic class HBaseSchemaManager extends AbstractSchemaManager implements SchemaManager\n{\n    private static final String DEFAULT_ZOOKEEPER_PORT = \"2181\";\n\n    /**\n     * Hbase admin variable holds the admin authorities.\n     */\n    private static HBaseAdmin admin;\n\n    /**\n     * logger used for logging statement.\n     */\n    private static final Logger logger = LoggerFactory.getLogger(HBaseSchemaManager.class);\n\n    // private Properties schemaProperties;\n\n    private List<Table> tables;\n\n    /**\n     * Initialises HBase schema manager\n     * \n     * @param clientFactory\n     *            client factory.\n     */\n    public HBaseSchemaManager(String clientFactory, Map<String, Object> puProperties, final KunderaMetadata kunderaMetadata)\n    {\n        super(clientFactory, puProperties, kunderaMetadata);\n    }\n\n    @Override\n    /**\n     * Export schema handles the handleOperation method.\n     */\n    public void exportSchema(final String persistenceUnit, List<TableInfo> schemas)\n    {\n        super.exportSchema(persistenceUnit, schemas);\n    }\n\n    /**\n     * update method update schema and table for the list of tableInfos\n     * \n     * @param tableInfos\n     *            list of TableInfos.\n     */\n    protected void update(List<TableInfo> tableInfos)\n    {\n        try\n        {\n            if (admin.isTableAvailable(databaseName))\n            {\n                HTableDescriptor hTableDescriptor = admin.getTableDescriptor(databaseName.getBytes());\n                addColumnFamilies(tableInfos, hTableDescriptor, true);\n            }\n            else\n            {\n                createTable(tableInfos);\n            }\n        }\n        catch (IOException ioe)\n        {\n            logger.error(\"Either check for network connection or table isn't in enabled state, Caused by:\", ioe);\n            throw new SchemaGenerationException(ioe, \"Hbase\");\n        }\n    }\n\n    /**\n     * validate method validate schema and table for the list of tableInfos.\n     * \n     * @param tableInfos\n     *            list of TableInfos.\n     */\n    protected void validate(List<TableInfo> tableInfos)\n    {\n        try\n        {\n            HTableDescriptor hTableDescriptor = admin.getTableDescriptor(databaseName.getBytes());\n            HColumnDescriptor[] columnFamilies = hTableDescriptor.getColumnFamilies();\n            for (TableInfo tableInfo : tableInfos)\n            {\n                if (tableInfo != null)\n                {\n                    boolean isColumnFound = false;\n                    for (HColumnDescriptor columnDescriptor : columnFamilies)\n                    {\n                        if (columnDescriptor.getNameAsString().equalsIgnoreCase(tableInfo.getTableName()))\n                        {\n                            isColumnFound = true;\n                            break;\n                        }\n                    }\n                    if (!isColumnFound)\n                    {\n                        throw new SchemaGenerationException(\"column \" + tableInfo.getTableName()\n                                + \" does not exist in table \" + databaseName + \"\", \"Hbase\", databaseName,\n                                tableInfo.getTableName());\n                    }\n                }\n            }\n        }\n        catch (TableNotFoundException tnfex)\n        {\n            throw new SchemaGenerationException(\"table \" + databaseName + \" does not exist \", tnfex, \"Hbase\");\n        }\n        catch (IOException ioe)\n        {\n            logger.error(\"Either check for network connection or table isn't in enabled state, Caused by:\", ioe);\n            throw new SchemaGenerationException(ioe, \"Hbase\");\n        }\n    }\n\n    /**\n     * create_drop method creates schema and table for the list of tableInfos.\n     * \n     * @param tableInfos\n     *            list of TableInfos.\n     */\n    protected void create_drop(List<TableInfo> tableInfos)\n    {\n        create(tableInfos);\n    }\n\n    /**\n     * create method creates schema and table for the list of tableInfos.\n     * \n     * @param tableInfos\n     *            list of TableInfos.\n     */\n    protected void create(List<TableInfo> tableInfos)\n    {\n        try\n        {\n            if (admin.isTableAvailable(databaseName))\n            {\n                addColumnFamilies(tableInfos, admin.getTableDescriptor(databaseName.getBytes()), false);\n            }\n            else\n            {\n                createTable(tableInfos);\n            }\n            if (admin.isTableDisabled(databaseName))\n            {\n                admin.enableTable(databaseName);\n            }\n        }\n        catch (TableNotFoundException e)\n        {\n            logger.info(\"creating table \" + databaseName);\n        }\n        catch (IOException ioex)\n        {\n            logger.error(\"Either table isn't in enabled state or some network problem, Caused by: \", ioex);\n            throw new SchemaGenerationException(ioex, \"Hbase\");\n        }\n    }\n\n    private void addColumnFamilies(List<TableInfo> tableInfos, HTableDescriptor hTableDescriptor, boolean isUpdate)\n            throws IOException\n    {\n        if (admin.isTableEnabled(databaseName))\n        {\n            admin.disableTable(databaseName);\n        }\n        for (TableInfo tableInfo : tableInfos)\n        {\n            HColumnDescriptor columnDescriptor = hTableDescriptor.getFamily(tableInfo.getTableName().getBytes());\n            if (columnDescriptor != null && !isUpdate)\n            {\n                admin.deleteColumn(databaseName, tableInfo.getTableName());\n                addColumn(tableInfo);\n            }\n            else if (columnDescriptor == null)\n            {\n                addColumn(tableInfo);\n            }\n        }\n\n        if (admin.isTableDisabled(databaseName))\n        {\n            admin.enableTable(databaseName);\n        }\n    }\n\n    private void addColumn(TableInfo tableInfo) throws IOException\n    {\n        HColumnDescriptor columnDescriptor;\n        columnDescriptor = getColumnDescriptor(tableInfo);\n        admin.addColumn(databaseName, columnDescriptor);\n    }\n\n    private void createTable(List<TableInfo> tableInfos) throws IOException\n    {\n        HTableDescriptor hTableDescriptor = getTableMetaData(tableInfos);\n        admin.createTable(hTableDescriptor);\n    }\n\n    /**\n     * drop schema method drop the table\n     */\n    public void dropSchema()\n    {\n        if (operation != null && operation.equalsIgnoreCase(\"create-drop\"))\n        {\n            try\n            {\n                HTableDescriptor hTableDescriptor = null;\n                if (admin.isTableAvailable(databaseName))\n                {\n                    if (admin.isTableEnabled(databaseName))\n                    {\n                        hTableDescriptor = admin.getTableDescriptor(databaseName.getBytes());\n                        admin.disableTable(databaseName);\n                    }\n                    for (TableInfo tableInfo : tableInfos)\n                    {\n                        if (tableInfo != null && tableInfo.getTableName() != null\n                                && hTableDescriptor.getFamily(tableInfo.getTableName().getBytes()) != null)\n                        {\n                            admin.deleteColumn(databaseName, tableInfo.getTableName());\n                        }\n                    }\n                }\n            }\n            catch (TableNotFoundException tnfe)\n            {\n                logger.error(\"Table doesn't exist, Caused by \", tnfe);\n                throw new SchemaGenerationException(tnfe, \"Hbase\");\n            }\n            catch (IOException ioe)\n            {\n                logger.error(\"Table isn't in enabled state, Caused by\", ioe);\n                throw new SchemaGenerationException(ioe, \"Hbase\");\n            }\n            finally\n            {\n                try\n                {\n                    admin.enableTable(databaseName);\n                }\n                catch (IOException ioe)\n                {\n                    logger.error(\"Table isn't in enabled state, Caused by\", ioe);\n                    throw new SchemaGenerationException(ioe, \"Hbase\");\n                }\n            }\n        }\n        operation = null;\n        admin = null;\n    }\n\n    /**\n     * initiate client method initiates the client.\n     * \n     * @return boolean value ie client started or not.\n     * \n     */\n    protected boolean initiateClient()\n    {\n        String message = null;\n        for (String host : hosts)\n        {\n            vaildateHostPort(host, port);\n\n            Configuration hadoopConf = new Configuration();\n            hadoopConf.set(\"hbase.master\", host + \":\" + port);\n            conn = HBasePropertyReader.hsmd.getDataStore() != null ? HBasePropertyReader.hsmd.getDataStore()\n                    .getConnection() : null;\n            if (conn != null && conn.getProperties() != null)\n            {\n                String zookeeperHost = conn.getProperties().getProperty(\"hbase.zookeeper.quorum\").trim();\n                String zookeeperPort = conn.getProperties().getProperty(\"hbase.zookeeper.property.clientPort\").trim();\n                vaildateHostPort(zookeeperHost, zookeeperPort);\n                hadoopConf.set(\"hbase.zookeeper.quorum\", zookeeperHost != null ? zookeeperHost : host);\n                hadoopConf.set(\"hbase.zookeeper.property.clientPort\", zookeeperPort != null ? zookeeperPort\n                        : DEFAULT_ZOOKEEPER_PORT);\n            }\n            else\n            {\n                hadoopConf.set(\"hbase.zookeeper.quorum\", host);\n                hadoopConf.set(\"hbase.zookeeper.property.clientPort\", DEFAULT_ZOOKEEPER_PORT);\n            }\n            Configuration conf = HBaseConfiguration.create(hadoopConf);\n            try\n            {\n                admin = new HBaseAdmin(conf);\n                return true;\n            }\n            catch (MasterNotRunningException mnre)\n            {\n                message = mnre.getMessage();\n                logger.error(\"Master not running exception, Caused by:\", mnre);\n            }\n            catch (ZooKeeperConnectionException zkce)\n            {\n                message = zkce.getMessage();\n                logger.error(\"Unable to connect to zookeeper, Caused by:\", zkce);\n            }\n            catch (IOException ioe)\n            {\n                message = ioe.getMessage();\n                logger.error(\"I/O exception, Caused by:\", ioe);\n            }\n        }\n        throw new SchemaGenerationException(\"Master not running exception, Caused by:\" + message);\n    }\n\n    /**\n     * Validate host and port.\n     * \n     * @param host\n     * @param port\n     */\n    private void vaildateHostPort(String host, String port)\n    {\n        if (host == null || !StringUtils.isNumeric(port) || port.isEmpty())\n        {\n            logger.error(\"Host or port should not be null / port should be numeric\");\n            throw new IllegalArgumentException(\"Host or port should not be null / port should be numeric\");\n        }\n    }\n\n    /**\n     * get Table metadata method returns the HTableDescriptor of table for given\n     * tableInfo\n     * \n     * @return HHTableDescriptor object for tableInfo\n     */\n    private HTableDescriptor getTableMetaData(List<TableInfo> tableInfos)\n    {\n        HTableDescriptor tableDescriptor = new HTableDescriptor(databaseName);\n        Properties tableProperties = null;\n        schemas = HBasePropertyReader.hsmd.getDataStore() != null ? HBasePropertyReader.hsmd.getDataStore()\n                .getSchemas() : null;\n        if (schemas != null && !schemas.isEmpty())\n        {\n            for (Schema s : schemas)\n            {\n                if (s.getName() != null && s.getName().equalsIgnoreCase(databaseName))\n                {\n                    tableProperties = s.getSchemaProperties();\n                    tables = s.getTables();\n                }\n            }\n        }\n        for (TableInfo tableInfo : tableInfos)\n        {\n            if (tableInfo != null)\n            {\n                HColumnDescriptor hColumnDescriptor = getColumnDescriptor(tableInfo);\n                tableDescriptor.addFamily(hColumnDescriptor);\n            }\n        }\n        if (tableProperties != null)\n        {\n            for (Object o : tableProperties.keySet())\n            {\n                tableDescriptor.setValue(Bytes.toBytes(o.toString()), Bytes.toBytes(tableProperties.get(o).toString()));\n            }\n        }\n        return tableDescriptor;\n    }\n\n    private HColumnDescriptor getColumnDescriptor(TableInfo tableInfo)\n    {\n        HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(tableInfo.getTableName());\n        setColumnFamilyProperties(hColumnDescriptor, tableInfo.getTableName());\n        return hColumnDescriptor;\n    }\n\n    private void setColumnFamilyProperties(HColumnDescriptor columnDescriptor, String columnName)\n    {\n        schemas = HBasePropertyReader.hsmd.getDataStore() != null ? HBasePropertyReader.hsmd.getDataStore()\n                .getSchemas() : null;\n        if (schemas != null && !schemas.isEmpty())\n        {\n            for (Schema s : schemas)\n            {\n                if (s.getName() != null && s.getName().equalsIgnoreCase(databaseName))\n                {\n                    tables = s.getTables();\n                }\n            }\n        }\n        dataStore = HBasePropertyReader.hsmd.getDataStore();\n        if (dataStore != null)\n        {\n            if (tables != null && !tables.isEmpty())\n            {\n                for (Table t : tables)\n                {\n                    Properties columnProperties = t.getProperties();\n                    if (t.getName() != null && t.getName().equalsIgnoreCase(columnDescriptor.getNameAsString())\n                            && columnProperties != null)\n                    {\n                        for (Object o : columnProperties.keySet())\n                        {\n                            columnDescriptor.setValue(Bytes.toBytes(o.toString()),\n                                    Bytes.toBytes(columnProperties.get(o).toString()));\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    @Override\n    public boolean validateEntity(Class clazz)\n    {\n        // TODO Auto-generated method stub\n        return true;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/service/HBaseReader.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase.service;\r\n\r\nimport java.io.IOException;\r\nimport java.util.ArrayList;\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\n\r\nimport org.apache.hadoop.hbase.KeyValue;\r\nimport org.apache.hadoop.hbase.client.Get;\r\nimport org.apache.hadoop.hbase.client.HTableInterface;\r\nimport org.apache.hadoop.hbase.client.Result;\r\nimport org.apache.hadoop.hbase.client.ResultScanner;\r\nimport org.apache.hadoop.hbase.client.Scan;\r\nimport org.apache.hadoop.hbase.filter.Filter;\r\nimport org.apache.hadoop.hbase.util.Bytes;\r\n\r\nimport com.impetus.client.hbase.HBaseData;\r\nimport com.impetus.client.hbase.Reader;\r\nimport com.impetus.client.hbase.utils.HBaseUtils;\r\n\r\n/**\r\n * Implmentation class for HBase for <code>Reader</code> interface.\r\n * \r\n * @author vivek.mishra\r\n */\r\npublic class HBaseReader implements Reader\r\n{\r\n    private ResultScanner scanner = null;\r\n\r\n    private Iterator<Result> resultsIter;\r\n\r\n    private Integer fetchSize;\r\n\r\n    private Integer counter = 0;\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.client.hbase.Reader#LoadData(org.apache.hadoop.hbase.client\r\n     * .HTable, java.lang.String, java.lang.String)\r\n     */\r\n\r\n    @Override\r\n    public List<HBaseData> LoadData(HTableInterface hTable, String columnFamily, Object rowKey, Filter filter,\r\n            String... columns) throws IOException\r\n    {\r\n        List<HBaseData> results = new ArrayList<HBaseData>();\r\n        if (scanner == null)\r\n        {\r\n\r\n            // only in case of find by id\r\n            Scan scan = null;\r\n            if (rowKey != null)\r\n            {\r\n                byte[] rowKeyBytes = HBaseUtils.getBytes(rowKey);\r\n                Get g = new Get(rowKeyBytes);\r\n\r\n                // TODO: After more than one column family for 1 table. this\r\n                // should work. currently failing for embeddable entities.\r\n                if (columnFamily != null)\r\n                {\r\n                    g.addFamily(Bytes.toBytes(columnFamily));\r\n                }\r\n\r\n                if (filter != null)\r\n                {\r\n                    g.setFilter(filter);\r\n                }\r\n                Result result = hTable.get(g);\r\n\r\n                if (result != null && result.list() != null)\r\n                {\r\n                    HBaseData data = null;\r\n                    for (KeyValue value : result.list())\r\n                    {\r\n                        data = new HBaseData(columnFamily != null ? columnFamily : new String(value.getFamily()),\r\n                                value.getRow());\r\n                        break;\r\n                    }\r\n\r\n                    if (data != null)\r\n                    {\r\n                        data.setColumns(result.list());\r\n                        results.add(data);\r\n                    }\r\n\r\n                }\r\n                return results;\r\n\r\n                // scan = new Scan(g);\r\n            }\r\n            else\r\n            {\r\n                scan = new Scan();\r\n            }\r\n            setScanCriteria(filter, columnFamily, null, scan, columns);\r\n            scanner = hTable.getScanner(scan);\r\n            resultsIter = scanner.iterator();\r\n        }\r\n        return scanResults(columnFamily, results);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.client.hbase.Reader#LoadData(org.apache.hadoop.hbase.client\r\n     * .HTable, java.lang.String)\r\n     */\r\n    @Override\r\n    public List<HBaseData> LoadData(HTableInterface hTable, Object rowKey, Filter filter, String... columns)\r\n            throws IOException\r\n    {\r\n        return LoadData(hTable, Bytes.toString(hTable.getTableName()), rowKey, filter, columns);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.client.hbase.Reader#loadAll(org.apache.hadoop.hbase.client\r\n     * .HTable, org.apache.hadoop.hbase.filter.Filter, byte[], byte[])\r\n     */\r\n    @Override\r\n    public List<HBaseData> loadAll(HTableInterface hTable, Filter filter, byte[] startRow, byte[] endRow,\r\n            String columnFamily, String qualifier, String[] columns) throws IOException\r\n    {\r\n        List<HBaseData> results = null;\r\n        if (scanner == null)\r\n        {\r\n            Scan s = null;\r\n            if (startRow != null && endRow != null && startRow.equals(endRow))\r\n            {\r\n                Get g = new Get(startRow);\r\n                s = new Scan(g);\r\n            }\r\n            else if (startRow != null && endRow != null)\r\n            {\r\n                s = new Scan(startRow, endRow);\r\n            }\r\n            else if (startRow != null)\r\n            {\r\n                s = new Scan(startRow);\r\n            }\r\n            else if (endRow != null)\r\n            {\r\n                s = new Scan();\r\n                s.setStopRow(endRow);\r\n            }\r\n            else\r\n            {\r\n                s = new Scan();\r\n            }\r\n            setScanCriteria(filter, columnFamily, qualifier, s, columns);\r\n            scanner = hTable.getScanner(s);\r\n            resultsIter = scanner.iterator();\r\n        }\r\n        return scanResults(null, results);\r\n    }\r\n\r\n    /**\r\n     * @param filter\r\n     * @param columnFamily\r\n     * @param s\r\n     */\r\n    private void setScanCriteria(Filter filter, String columnFamily, String qualifier, Scan s, String[] columns)\r\n    {\r\n\r\n        if (filter != null && !filter.toString().equals(\"FilterList AND (0/0): []\"))\r\n        {\r\n            s.setFilter(filter);\r\n        }\r\n        if (columnFamily != null && qualifier != null)\r\n        {\r\n            s.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(qualifier));\r\n        }\r\n        else if (columnFamily != null)\r\n        {\r\n            s.addFamily(Bytes.toBytes(columnFamily));\r\n        }\r\n\r\n        if (columns != null && columns.length > 0)\r\n        {\r\n            for (String columnName : columns)\r\n            {\r\n                if (columnFamily != null && columnName != null)\r\n                {\r\n                    s.addColumn(Bytes.toBytes(columnFamily), Bytes.toBytes(columnName));\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Scan and populate {@link HBaseData} collection using scanned results.\r\n     * \r\n     * @param columnFamily\r\n     *            column family.\r\n     * @param results\r\n     *            results.\r\n     * @param scanner\r\n     *            result scanner.\r\n     * @return collection of scanned results.\r\n     * @throws IOException\r\n     */\r\n    private List<HBaseData> scanResults(final String columnFamily, List<HBaseData> results) throws IOException\r\n    {\r\n        HBaseData data = null;\r\n\r\n        if (fetchSize == null)\r\n        {\r\n            for (Result result : scanner)\r\n            {\r\n                List<KeyValue> values = result.list();\r\n                for (KeyValue value : values)\r\n                {\r\n                    data = new HBaseData(columnFamily != null ? columnFamily : new String(value.getFamily()),\r\n                            value.getRow());\r\n                    break;\r\n                }\r\n                data.setColumns(values);\r\n                if (results == null)\r\n                {\r\n                    results = new ArrayList<HBaseData>();\r\n                }\r\n                results.add(data);\r\n            }\r\n\r\n            scanner = null;\r\n            resultsIter = null;\r\n        }\r\n        return results;\r\n    }\r\n\r\n    @Override\r\n    public Object[] scanRowKeys(final HTableInterface hTable, final Filter filter, final String columnFamilyName,\r\n            final String columnName, final Class rowKeyClazz) throws IOException\r\n    {\r\n        List<Object> rowKeys = new ArrayList<Object>();\r\n\r\n        if (scanner == null)\r\n        {\r\n            Scan s = new Scan();\r\n            s.setFilter(filter);\r\n            s.addColumn(Bytes.toBytes(columnFamilyName), Bytes.toBytes(columnName));\r\n            scanner = hTable.getScanner(s);\r\n            resultsIter = scanner.iterator();\r\n        }\r\n\r\n        if (fetchSize == null)\r\n        {\r\n            for (Result result : scanner)\r\n            {\r\n                for (KeyValue keyValue : result.list())\r\n                {\r\n                    rowKeys.add(HBaseUtils.fromBytes(keyValue.getRow(), rowKeyClazz));\r\n                }\r\n            }\r\n        }\r\n        if (rowKeys != null && !rowKeys.isEmpty())\r\n        {\r\n            return rowKeys.toArray(new Object[0]);\r\n        }\r\n        return null;\r\n    }\r\n\r\n    public List<HBaseData> loadAll(final HTableInterface hTable, final List<Object> rows, final String columnFamily,\r\n            final String[] columns) throws IOException\r\n    {\r\n        List<HBaseData> results = null;\r\n\r\n        HBaseData data = null;\r\n\r\n        List<Get> getRequest = new ArrayList<Get>();\r\n        for (Object rowKey : rows)\r\n        {\r\n            if (rowKey != null)\r\n            {\r\n                byte[] rowKeyBytes = HBaseUtils.getBytes(rowKey);\r\n                Get request = new Get(rowKeyBytes);\r\n                getRequest.add(request);\r\n            }\r\n        }\r\n        Result[] rawResult = hTable.get(getRequest);\r\n\r\n        for (Result result : rawResult)\r\n        {\r\n            List<KeyValue> values = result.list();\r\n\r\n            if (values != null)\r\n            {\r\n                for (KeyValue value : values)\r\n                {\r\n                    data = new HBaseData(columnFamily != null ? columnFamily : new String(value.getFamily()),\r\n                            value.getRow());\r\n                    break;\r\n                }\r\n\r\n                data.setColumns(values);\r\n                if (results == null)\r\n                {\r\n                    results = new ArrayList<HBaseData>();\r\n                }\r\n                results.add(data);\r\n            }\r\n        }\r\n        return results;\r\n    }\r\n\r\n    public void setFetchSize(final int fetchSize)\r\n    {\r\n        this.fetchSize = fetchSize;\r\n    }\r\n\r\n    /**\r\n     * \r\n     * @return next element of HbaseData.\r\n     */\r\n    public HBaseData next()\r\n    {\r\n        HBaseData data = null;\r\n        Result result = resultsIter.next();\r\n        counter++;\r\n        List<KeyValue> values = result.list();\r\n        for (KeyValue value : values)\r\n        {\r\n            data = new HBaseData(new String(value.getFamily()), value.getRow());\r\n            break;\r\n        }\r\n        data.setColumns(values);\r\n        return data;\r\n    }\r\n\r\n    public boolean hasNext()\r\n    {\r\n        if (scanner == null)\r\n        {\r\n            return false;\r\n        }\r\n        else\r\n        {\r\n            if (fetchSize != null)\r\n            {\r\n                if (counter < fetchSize)\r\n                {\r\n                    return resultsIter.hasNext();\r\n                }\r\n            }\r\n            else\r\n            {\r\n                return resultsIter.hasNext();\r\n            }\r\n        }\r\n        return false;\r\n    }\r\n\r\n    public void reset()\r\n    {\r\n        scanner = null;\r\n        fetchSize = null;\r\n        resultsIter = null;\r\n        counter = 0;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/service/HBaseWriter.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.service;\n\nimport java.io.IOException;\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.apache.hadoop.hbase.client.Delete;\nimport org.apache.hadoop.hbase.client.Get;\nimport org.apache.hadoop.hbase.client.HTableInterface;\nimport org.apache.hadoop.hbase.client.Put;\nimport org.apache.hadoop.hbase.client.Result;\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.Writer;\nimport com.impetus.client.hbase.admin.HBaseDataHandler.HBaseDataWrapper;\nimport com.impetus.client.hbase.utils.HBaseUtils;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\n\n/**\n * The Class HBaseWriter responsible for all sort of get and put commands to be\n * executed on a hTable.\n * \n * @author vivek.mishra\n */\npublic class HBaseWriter implements Writer\n{\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(HBaseWriter.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.Writer#writeColumns(org.apache.hadoop.hbase.\n     * client.HTable, java.lang.String, java.lang.Object, java.util.Set,\n     * java.lang.Object)\n     */\n    @Override\n    public void writeColumns(HTableInterface htable, String columnFamily, Object rowKey,\n            Map<String, Attribute> columns,\n\n            Map<String, Object> values, Object columnFamilyObj) throws IOException\n    {\n        Put p = preparePut(columnFamily, rowKey, columns, values);\n        htable.put(p);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.Writer#writeColumn(org.apache.hadoop.hbase.client\n     * .HTable, java.lang.String, java.lang.Object,\n     * javax.persistence.metamodel.Attribute, java.lang.Object)\n     */\n    @Override\n    public void writeColumn(HTableInterface htable, String columnFamily, Object rowKey, Attribute column,\n            Object columnObj) throws IOException\n    {\n        Put p = new Put(HBaseUtils.getBytes(rowKey));\n        p.add(Bytes.toBytes(columnFamily), Bytes.toBytes(((AbstractAttribute) column).getJPAColumnName()),\n                Bytes.toBytes(columnObj.toString()));\n\n        htable.put(p);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.Writer#writeColumns(org.apache.hadoop.hbase.\n     * client.HTable, java.lang.Object, java.util.Set, java.lang.Object)\n     */\n    @Override\n    public void writeColumns(HTableInterface htable, Object rowKey, Map<String, Attribute> columns, Object entity,\n            String columnFamilyName) throws IOException\n    {\n        Put p = new Put(HBaseUtils.getBytes(rowKey));\n\n        boolean present = false;\n        for (String columnName : columns.keySet())\n        {\n            Attribute column = columns.get(columnName);\n            if (!column.isCollection() && !((SingularAttribute) column).isId())\n            {\n                String qualifier = columnName;\n                try\n                {\n                    byte[] qualValInBytes = Bytes.toBytes(qualifier);\n                    Object value = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());\n                    if (value != null)\n                    {\n                        p.add(columnFamilyName.getBytes(), qualValInBytes, System.currentTimeMillis(),\n                                HBaseUtils.getBytes(value));\n                        present = true;\n                    }\n                }\n                catch (PropertyAccessException e1)\n                {\n                    throw new IOException(e1);\n                }\n            }\n        }\n        if (present)\n        {\n            htable.put(p);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.Writer#writeColumns(org.apache.hadoop.hbase.\n     * client.HTable, java.lang.Object, java.util.Map)\n     */\n    @Override\n    public void writeColumns(HTableInterface htable, Object rowKey, Map<String, Object> columns, String columnFamilyName)\n            throws IOException\n    {\n\n        Put p = new Put(HBaseUtils.getBytes(rowKey));\n\n        boolean isPresent = false;\n        for (String columnName : columns.keySet())\n        {\n            p.add(columnFamilyName.getBytes(), Bytes.toBytes(columnName), HBaseUtils.getBytes(columns.get(columnName)));\n            isPresent = true;\n        }\n\n        if (isPresent)\n        {\n            htable.put(p);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.Writer#writeRelations(org.apache.hadoop.hbase\n     * .client.HTable, java.lang.Object, boolean, java.util.List)\n     */\n    @Override\n    public void writeRelations(HTableInterface htable, Object rowKey, boolean containsEmbeddedObjectsOnly,\n            List<RelationHolder> relations, String columnFamilyName) throws IOException\n    {\n        Put p = new Put(HBaseUtils.getBytes(rowKey));\n\n        boolean isPresent = false;\n        for (RelationHolder r : relations)\n        {\n            if (r != null)\n            {\n                if (containsEmbeddedObjectsOnly)\n                {\n                    p.add(Bytes.toBytes(r.getRelationName()), Bytes.toBytes(r.getRelationName()),\n                            PropertyAccessorHelper.getBytes(r.getRelationValue()));\n                    isPresent = true;\n                }\n                else\n                {\n                    p.add(columnFamilyName.getBytes(), Bytes.toBytes(r.getRelationName()), System.currentTimeMillis(),\n                            PropertyAccessorHelper.getBytes(r.getRelationValue()));\n                    isPresent = true;\n                }\n            }\n        }\n\n        if (isPresent)\n        {\n            htable.put(p);\n        }\n    }\n\n    // TODO: Scope of performance improvement in this code\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.Writer#writeForeignKeys(org.apache.hadoop.hbase\n     * .client.HTable, java.lang.String, java.util.Map)\n     */\n    @Override\n    public void writeForeignKeys(HTableInterface hTable, String rowKey, Map<String, Set<String>> foreignKeyMap)\n            throws IOException\n    {\n        Put p = new Put(Bytes.toBytes(rowKey));\n\n        // Checking if foreign key column family exists\n        Get g = new Get(Bytes.toBytes(rowKey));\n        Result r = hTable.get(g);\n\n        boolean isPresent = false;\n\n        for (Map.Entry<String, Set<String>> entry : foreignKeyMap.entrySet())\n        {\n            String property = entry.getKey(); // Foreign key name\n            Set<String> foreignKeys = entry.getValue();\n            String keys = MetadataUtils.serializeKeys(foreignKeys);\n\n            // Check if there was any existing foreign key value, if yes, append\n            // it\n            byte[] value = r.getValue(Bytes.toBytes(Constants.FOREIGN_KEY_EMBEDDED_COLUMN_NAME),\n                    Bytes.toBytes(property));\n            String existingForeignKey = Bytes.toString(value);\n\n            if (existingForeignKey == null || existingForeignKey.isEmpty())\n            {\n                p.add(Bytes.toBytes(Constants.FOREIGN_KEY_EMBEDDED_COLUMN_NAME), Bytes.toBytes(property),\n                        Bytes.toBytes(keys));\n                isPresent = true;\n            }\n            else\n            {\n                p.add(Bytes.toBytes(Constants.FOREIGN_KEY_EMBEDDED_COLUMN_NAME), Bytes.toBytes(property),\n                        Bytes.toBytes(existingForeignKey + Constants.FOREIGN_KEY_SEPARATOR + keys));\n                isPresent = true;\n            }\n        }\n        if (isPresent)\n        {\n            hTable.put(p);\n        }\n    }\n\n    /**\n     * Support for delete over HBase.\n     * \n     * @param hTable\n     *            the h table\n     * @param rowKey\n     *            the row key\n     * @param columnFamily\n     *            the column family\n     */\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.Writer#delete(org.apache.hadoop.hbase.client\n     * .HTable, java.lang.String, java.lang.String)\n     */\n    public void delete(HTableInterface hTable, Object rowKey, String columnFamily)\n    {\n        try\n        {\n            byte[] rowBytes = HBaseUtils.getBytes(rowKey);\n            Delete delete = new Delete(rowBytes);\n            byte[] family = HBaseUtils.getBytes(columnFamily);\n            delete.deleteFamily(family);\n            hTable.delete(delete);\n        }\n        catch (IOException e)\n        {\n            log.error(\"Error while delete on hbase for : \" + rowKey);\n            throw new PersistenceException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.hbase.Writer#persistRows(java.util.Map)\n     */\n    @Override\n    public void persistRows(Map<HTableInterface, List<HBaseDataWrapper>> rows) throws IOException\n    {\n        List<Put> dataSet = new ArrayList<Put>(rows.size());\n        for (HTableInterface hTable : rows.keySet())\n        {\n            List<HBaseDataWrapper> row = rows.get(hTable);\n            for (HBaseDataWrapper data : row)\n            {\n                dataSet.add(preparePut(data.getColumnFamily(), data.getRowKey(), data.getColumns(), data.getValues()));\n            }\n            hTable.put(dataSet);\n            dataSet.clear();\n        }\n    }\n\n    /**\n     * Prepare put.\n     * \n     * @param columnFamily\n     *            the column family\n     * @param rowKey\n     *            the row key\n     * @param columns\n     *            the columns\n     * @param values TODO\n     * @param columnFamilyObj\n     *            the column family obj\n     * @return the put\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    private Put preparePut(String columnFamily, Object rowKey, Map<String, Attribute> columns, Map<String, Object> values)\n            throws IOException\n    {\n        Put p = new Put(HBaseUtils.getBytes(rowKey));\n        for (String columnName : columns.keySet())\n        {\n            Attribute column = columns.get(columnName);\n            if (!column.isCollection() && !((SingularAttribute) column).isId())\n            {\n                String qualifier = columnName;\n                try\n                {\n                    Object o = values.get(columnName);\n                    byte[] value = HBaseUtils.getBytes(o);\n                    if (value != null && columnFamily != null)\n                    {\n                        p.add(Bytes.toBytes(columnFamily), Bytes.toBytes(qualifier), value);\n                    }\n                }\n                catch (PropertyAccessException e1)\n                {\n                    throw new IOException(e1);\n                }\n            }\n        }\n        return p;\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/main/java/com/impetus/client/hbase/utils/HBaseUtils.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.utils;\n\nimport java.math.BigDecimal;\n\nimport com.impetus.client.hbase.query.SingleColumnFilterFactory;\nimport org.apache.hadoop.hbase.util.Bytes;\n\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\n\n/**\n * The Class HBaseUtils.\n */\npublic final class HBaseUtils\n{\n\n    /**\n     * Gets the bytes.\n     * \n     * @param value\n     *            the value\n     * @param clazz\n     *            the clazz\n     * @return the bytes\n     */\n    public static byte[] getBytes(Object value, Class<?> clazz)\n    {\n        if (/* isId || */clazz.isAssignableFrom(String.class))\n        {\n            return Bytes.toBytes(value.toString());\n        }\n        else if (clazz.equals(int.class) || clazz.isAssignableFrom(Integer.class))\n        {\n            return Bytes.toBytes(value instanceof Integer ? (Integer) value : new Integer(value.toString()));\n        }\n        else if (clazz.equals(long.class) || clazz.isAssignableFrom(Long.class))\n        {\n            return Bytes.toBytes(value instanceof Long ? (Long) value : new Long(value.toString()));\n        }\n        else if (clazz.equals(boolean.class) || clazz.isAssignableFrom(Boolean.class))\n        {\n            return Bytes.toBytes(value instanceof Boolean ? (Boolean) value : new Boolean(value.toString()));\n        }\n        else if (clazz.equals(double.class) || clazz.isAssignableFrom(Double.class))\n        {\n            return Bytes.toBytes(value instanceof Double ? (Double) value : new Double(value.toString()));\n        }\n        // else if (clazz.isAssignableFrom(java.util.UUID.class))\n        // {\n        // return Bytes.toBytes(value.toString());\n        // }\n        else if (clazz.equals(float.class) || clazz.isAssignableFrom(Float.class))\n        {\n            return Bytes.toBytes(value instanceof Float ? (Float) value : new Float(value.toString()));\n        }\n        else if (clazz.equals(short.class) || clazz.isAssignableFrom(Short.class))\n        {\n            return Bytes.toBytes(value instanceof Short ? (Short) value : new Short(value.toString()));\n        }\n        else if (clazz.equals(BigDecimal.class))\n        {\n            return Bytes.toBytes(value instanceof BigDecimal ? (BigDecimal) value : new BigDecimal(value.toString()));\n        }\n        else\n        {\n            if (value.getClass().isAssignableFrom(String.class))\n            {\n                value = PropertyAccessorFactory.getPropertyAccessor(clazz).fromString(clazz, value.toString());\n            }\n            return PropertyAccessorFactory.getPropertyAccessor(clazz).toBytes(value);\n        }\n    }\n\n    /**\n     * Returns bytes value for given value.\n     * \n     * @param o\n     *            the o\n     * @return bytes value.\n     */\n    public static byte[] getBytes(Object o)\n    {\n        if (o != null)\n        {\n            return getBytes(o, o.getClass());\n        }\n\n        return null;\n    }\n\n    /**\n     * From bytes.\n     * \n     * @param m\n     *            the m\n     * @param metaModel\n     *            the meta model\n     * @param b\n     *            the b\n     * @return the object\n     */\n    public static Object fromBytes(EntityMetadata m, MetamodelImpl metaModel, byte[] b)\n    {\n        Class idFieldClass = m.getIdAttribute().getJavaType();\n        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n        {\n            return fromBytes(b, String.class);\n        }\n        return fromBytes(b, idFieldClass);\n    }\n\n    /**\n     * From bytes.\n     * \n     * @param b\n     *            the b\n     * @param clazz\n     *            the clazz\n     * @return the object\n     */\n    public static Object fromBytes(byte[] b, Class<?> clazz)\n    {\n\n        if (clazz.isAssignableFrom(String.class))\n        {\n            return Bytes.toString(b);\n        }\n        else if (clazz.equals(int.class) || clazz.isAssignableFrom(Integer.class))\n        {\n            return Bytes.toInt(b);\n        }\n        else if (clazz.equals(long.class) || clazz.isAssignableFrom(Long.class))\n        {\n            return Bytes.toLong(b);\n        }\n        else if (clazz.equals(boolean.class) || clazz.isAssignableFrom(Boolean.class))\n        {\n            return Bytes.toBoolean(b);\n        }\n        else if (clazz.equals(double.class) || clazz.isAssignableFrom(Double.class))\n        {\n            return Bytes.toDouble(b);\n        }\n        else if (clazz.equals(float.class) || clazz.isAssignableFrom(Float.class))\n        {\n            return Bytes.toFloat(b);\n        }\n        else if (clazz.equals(short.class) || clazz.isAssignableFrom(Short.class))\n        {\n            return Bytes.toShort(b);\n        }\n        else if (clazz.equals(BigDecimal.class))\n        {\n            return Bytes.toBigDecimal(b);\n        }\n        else\n        {\n            return PropertyAccessorFactory.getPropertyAccessor(clazz).fromBytes(clazz, b);\n        }\n    }\n\n    /**\n     * Gets the operator.\n     * \n     * @param condition\n     *            the condition\n     * @param idPresent\n     *            the id present\n     * @param useFilter\n     *            the use filter\n     * @return the operator\n     */\n    public static SingleColumnFilterFactory getOperator(String condition, boolean idPresent, boolean useFilter)\n    {\n        if (condition.equals(\"=\"))\n        {\n            return SingleColumnFilterFactory.EQUAL;\n        }\n        else if (condition.equals(\">\"))\n        {\n            return SingleColumnFilterFactory.GREATER;\n        }\n        else if (condition.equals(\"<\"))\n        {\n            return SingleColumnFilterFactory.LESS;\n        }\n        else if (condition.equals(\">=\"))\n        {\n            return SingleColumnFilterFactory.GREATER_OR_EQUAL;\n        }\n        else if (condition.equals(\"<=\"))\n        {\n            return SingleColumnFilterFactory.LESS_OR_EQUAL;\n        }\n        else if (condition.equals(\"LIKE\"))\n        {\n            return SingleColumnFilterFactory.LIKE;\n        }\n        else if (condition.equals(\"REGEXP\"))\n        {\n            return SingleColumnFilterFactory.REGEXP;\n        }\n        else if (useFilter)\n        {\n            if (!idPresent)\n            {\n                throw new UnsupportedOperationException(\" Condition \" + condition + \" is not suported in  hbase!\");\n            }\n            else\n            {\n                throw new UnsupportedOperationException(\" Condition \" + condition\n                        + \" is not suported for query on row key!\");\n\n            }\n        }\n        return null;\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/config/HBaseEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.config;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"HBaseEntity\", schema = \"KunderaHbase@UsePropertyInHbase\")\npublic class HBaseEntity\n{\n\n    @Id\n    private String id;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/config/HBaseUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.config;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"HBASEUSERXYZ\", schema = \"KunderaHbaseXmlTest@XmlPropertyTest\")\npublic class HBaseUser\n{\n\n    @Id\n    private String name;\n\n    @Column\n    private int age;\n\n    @Column\n    private String address;\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/config/HBaseUserTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.hbase.config;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.hadoop.hbase.HColumnDescriptor;\nimport org.apache.hadoop.hbase.HTableDescriptor;\nimport org.apache.hadoop.hbase.TableNotFoundException;\nimport org.apache.hadoop.hbase.io.compress.Compression.Algorithm;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class HBaseUserTest\n{\n\n    private static final String TABLE = \"KunderaHbaseXmlTest\";\n\n    private EntityManagerFactory emf;\n\n    private HBaseCli cli;\n\n    /**\n     * logger used for logging statement.\n     */\n    private static final Logger logger = LoggerFactory.getLogger(HBaseUserTest.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    @Test\n    public void test() throws IOException\n    {\n        emf = Persistence.createEntityManagerFactory(\"XmlPropertyTest\");\n        try\n        {\n            HTableDescriptor hTableDescriptor = HBaseCli.utility.getHBaseAdmin().getTableDescriptor(\n                    TABLE.getBytes());\n            int count = 0;\n            for (HColumnDescriptor columnDescriptor : hTableDescriptor.getColumnFamilies())\n            {\n                if (columnDescriptor.getNameAsString().equalsIgnoreCase(\"HBASEUSERXYZ\"))\n                {\n                    Assert.assertEquals(Algorithm.valueOf(\"GZ\"), columnDescriptor.getCompactionCompressionType());\n                    Assert.assertEquals(Integer.parseInt(\"12345678\"), columnDescriptor.getTimeToLive());\n                    Assert.assertEquals(Algorithm.valueOf(\"GZ\"), columnDescriptor.getCompressionType());\n                    Assert.assertEquals(Integer.parseInt(\"6\"), columnDescriptor.getMaxVersions());\n                    Assert.assertEquals(Integer.parseInt(\"3\"), columnDescriptor.getMinVersions());\n                    count++;\n                }\n            }\n            Assert.assertEquals(1, count);\n        }\n        catch (TableNotFoundException tnfe)\n        {\n            logger.error(\"Error during UserTest, caused by :\" + tnfe);\n        }\n        catch (IOException ie)\n        {\n            logger.error(\"Error during UserTest, caused by :\" + ie);\n        }\n        finally\n        {\n            emf.close();\n            Assert.assertTrue(HBaseCli.utility.getHBaseAdmin().isTableAvailable(TABLE));\n            cli.dropTable(TABLE);\n        }\n    }\n\n    @Test\n    public void testUsingExternalProperty() throws IOException\n    {\n        Map<String, String> puProperties = new HashMap<String, String>();\n        puProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n        puProperties.put(\"kundera.keyspace\", \"KunderaHbaseKeyspace\");\n        emf = Persistence.createEntityManagerFactory(\"XmlPropertyTest\", puProperties);\n        try\n        {\n            Assert.assertTrue(HBaseCli.utility.getHBaseAdmin().isTableAvailable(\"KunderaHbaseKeyspace\"));\n        }\n        catch (TableNotFoundException tnfe)\n        {\n            logger.error(\"Error during UserTest, caused by :\" + tnfe);\n        }\n        catch (IOException ie)\n        {\n            logger.error(\"Error during UserTest, caused by :\" + ie);\n        }\n        finally\n        {\n            emf.close();\n            if (HBaseCli.utility.getHBaseAdmin().isTableAvailable(\"KunderaHbaseKeyspace\"))\n            {\n                cli.dropTable(\"KunderaHbaseKeyspace\");\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/config/HbasePropertySetterTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.config;\n\nimport java.io.IOException;\nimport java.lang.reflect.Field;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.hadoop.hbase.filter.ColumnPaginationFilter;\nimport org.apache.hadoop.hbase.filter.Filter;\nimport org.apache.hadoop.hbase.filter.FilterList;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.HBaseClient;\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\n\n/**\n * @author Chhavi Gangwal\n * \n */\npublic class HbasePropertySetterTest\n{\n\n    private static final String TABLE = \"KunderaHbaseXmlTest\";\n\n    private static final String _PU = \"XmlPropertyTest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private HBaseCli cli;\n\n    /**\n     * logger used for logging statement.\n     */\n    private static final Logger logger = LoggerFactory.getLogger(HbasePropertySetterTest.class);\n\n    /**\n     * setup habse client connection\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n\n        Map<String, String> puProperties = new HashMap<String, String>();\n        puProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n        puProperties.put(\"kundera.keyspace\", \"KunderaHbaseKeyspace\");\n        emf = Persistence.createEntityManagerFactory(_PU, puProperties);\n\n    }\n\n    /**\n     * drops the keyspace and closes connection\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (HBaseCli.utility.getHBaseAdmin().isTableAvailable(\"KunderaHbaseKeyspace\"))\n        {\n            cli.dropTable(\"KunderaHbaseKeyspace\");\n        }\n    }\n\n    /**\n     * Sets property of hbase client in form of String\n     */\n    @Test\n    public void testUsingExternalStringProperty() throws IOException\n    {\n        \n            Map<String, Object> puPropertiesString = new HashMap<String, Object>();\n\n            puPropertiesString.put(PersistenceProperties.KUNDERA_BATCH_SIZE, \"10\");\n\n            em = emf.createEntityManager(puPropertiesString);\n\n            Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n            Client client = clients.get(_PU);\n\n            Assert.assertEquals(((HBaseClient) client).getBatchSize(), 10);\n\n        }\n       \n\n    \n\n    /**\n     * Sets property of hbase client in form of object map\n     */\n    @Test\n    public void testUsingExternalObjectProperty() throws IOException\n    {\n        try\n        {\n            Map<String, Object> puPropertiesString = new HashMap<String, Object>();\n            Filter filter = new ColumnPaginationFilter(2, 0);\n            FilterList filterlist = new FilterList();\n            filterlist.addFilter(filter);\n\n            puPropertiesString.put(\"hbase.filter\", filter);\n            puPropertiesString.put(PersistenceProperties.KUNDERA_BATCH_SIZE, 10);\n\n            em = emf.createEntityManager(puPropertiesString);\n\n            Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n            Client client = clients.get(_PU);\n\n            Field f1, f2;\n\n            f1 = ((HBaseClient) client).getClass().getDeclaredField(\"handler\"); // NoSuchFieldException\n            f1.setAccessible(true);\n            f2 = f1.get((HBaseClient) client).getClass().getDeclaredField(\"filter\");\n            f2.setAccessible(true);\n            Assert.assertEquals(f2.get(f1.get((HBaseClient) client)).toString(), filterlist.toString());\n            Assert.assertEquals(((HBaseClient) client).getBatchSize(), 10);\n        }\n        catch (NoSuchFieldException nfe)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\",nfe.getMessage());\n          \n        }\n        catch (IllegalArgumentException iae)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\",iae.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\",e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/BaseTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport com.impetus.client.hbase.crud.PersonHBase.Day;\n\n/**\n * The Class BaseTest.\n * \n * @author vivek.mishra\n */\npublic abstract class BaseTest\n{\n    /**\n     * Prepare hbase instance.\n     * \n     * @param rowKey\n     *            the row key\n     * @param age\n     *            the age\n     * @return the person h base\n     */\n    protected PersonHBase prepareHbaseInstance(String rowKey, int age)\n    {\n        PersonHBase o = new PersonHBase();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age);\n        o.setDay(Day.MONDAY);\n        o.setMonth(Month.MARCH);\n        return o;\n    }\n\n    /**\n     * Find by id.\n     * \n     * @param <E>\n     *            the element type\n     * @param clazz\n     *            the clazz\n     * @param rowKey\n     *            the row key\n     * @param em\n     *            the em\n     * @return the e\n     */\n    protected <E extends Object> E findById(Class<E> clazz, Object rowKey, EntityManager em)\n    {\n        return em.find(clazz, rowKey);\n    }\n\n    /**\n     * Assert find by name.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByName(EntityManager em, String clazz, E e, String name,\n            String fieldName)\n    {\n\n        String query = \"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name;\n        // // find by name.\n        Query q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n    }\n\n    /**\n     * Assert find by name and age.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param minVal\n     *            the min val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByNameAndAge(EntityManager em, String clazz, E e, String name,\n            String minVal, String fieldName)\n    {\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name + \" and p.age > \"\n                + minVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n    }\n\n    /**\n     * Assert find by name and age gt and lt.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param minVal\n     *            the min val\n     * @param maxVal\n     *            the max val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByNameAndAgeGTAndLT(EntityManager em, String clazz, E e, String name,\n            String minVal, String maxVal, String fieldName)\n    {\n        // // // find by name, age clause\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name + \" and p.age > \"\n                + minVal + \" and p.age < \" + maxVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(1, results.size());\n    }\n\n    /**\n     * Assert find by name and age between.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param minVal\n     *            the min val\n     * @param maxVal\n     *            the max val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByNameAndAgeBetween(EntityManager em, String clazz, E e, String name,\n            String minVal, String maxVal, String fieldName)\n    {\n        // // find by between clause\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name\n                + \" and p.age between \" + minVal + \" and \" + maxVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n\n    }\n\n    /**\n     * Assert find by range.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param minVal\n     *            the min val\n     * @param maxVal\n     *            the max val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByRange(EntityManager em, String clazz, E e, String minVal,\n            String maxVal, String fieldName)\n\n    {\n        // find by Range.\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" Between \" + minVal + \" and \"\n                + maxVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n    }\n    \n    \n    /**\n     * @param em\n     * @param clazz\n     * @param e\n     * @param rowIds\n     * @param fieldName\n     * @param size\n     */\n    protected <E extends Object> void assertFindByRowIds(EntityManager em, String clazz, E e, String rowIds, String fieldName, int size)\n\n    {\n        // find by Range.\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" IN ( \" + rowIds + \" ) \");\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(size, results.size());\n    }\n    \n    /**\n     * @param em\n     * @param clazz\n     * @param e\n     * @param fieldValues\n     * @param fieldName\n     * @param size\n     */\n    protected <E extends Object> void assertFindByFieldValues(EntityManager em, String clazz, E e, String fieldValues, String fieldName, int size)\n\n    {\n        // find by Range.\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" IN ( \" + fieldValues + \" ) \");\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(size, results.size());\n    }\n    \n    \n\n    /**\n     * Assert find without where clause.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     */\n    protected <E extends Object> void assertFindWithoutWhereClause(EntityManager em, String clazz, E e)\n    {\n        // find by without where clause.\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p\");\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n    }\n\n    /**\n     * Assert on merge.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param oldName\n     *            the old name\n     * @param newName\n     *            the new name\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertOnMerge(EntityManager em, String clazz, E e, String oldName,\n            String newName, String fieldName)\n    {\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + oldName);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + newName);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotSame(oldName, getPersonName(e, results.get(0)));\n        Assert.assertEquals(newName, getPersonName(e, results.get(0)));\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @param <E>\n     *            the element type\n     * @param e\n     *            the e\n     * @param result\n     *            the result\n     * @return the person name\n     */\n    private <E extends Object> String getPersonName(E e, Object result)\n    {\n        throw new RuntimeException(\"Support for \" + e + \"is not yet supported\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/Book.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2014 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase.crud;\r\n\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.GeneratedValue;\r\nimport javax.persistence.GenerationType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.JoinTable;\r\nimport javax.persistence.ManyToMany;\r\nimport javax.persistence.ManyToOne;\r\nimport javax.persistence.OneToOne;\r\nimport javax.persistence.Table;\r\n\r\nimport com.impetus.kundera.index.Index;\r\nimport com.impetus.kundera.index.IndexCollection;\r\n\r\n/**\r\n * @author Pragalbh Garg\r\n *\r\n */\r\n@Entity\r\n@Table(name = \"books\", schema = \"KunderaExamples@hbaseTest\")\r\n@IndexCollection(columns = { @Index(name = \"bookId\"), @Index(name = \"title\"), @Index(name = \"author\"),\r\n        @Index(name = \"description\"), @Index(name = \"category\"), @Index(name = \"language\"), @Index(name=\"bookDetails\") })\r\npublic class Book\r\n{\r\n\r\n    /** The book_id. */\r\n    @Id\r\n    @Column(name = \"book_id\")\r\n    @GeneratedValue(strategy = GenerationType.TABLE)\r\n    private String bookId;\r\n\r\n    /** The title. */\r\n    private String title;\r\n\r\n    /** The author. */\r\n    private String author;\r\n\r\n    /** The description. */\r\n    private String description;\r\n\r\n    /** The publisher. */\r\n    private String publisher;\r\n\r\n    /** The image. */\r\n    private String image;\r\n\r\n    /** The language. */\r\n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"language\")\r\n    private Languages language;\r\n\r\n    /** The category. */\r\n    @ManyToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinTable(name = \"book_category\", schema = \"KunderaExamples\", joinColumns = { @JoinColumn(name = \"book_id\") }, inverseJoinColumns = { @JoinColumn(name = \"categories_id\") })\r\n    private Set<Categories> category;\r\n\r\n    @OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"book_details\")\r\n    private BookDetails bookDetails;\r\n\r\n    public BookDetails getBookDetails()\r\n    {\r\n        return bookDetails;\r\n    }\r\n\r\n    public void setBookDetails(BookDetails bookDetails)\r\n    {\r\n        this.bookDetails = bookDetails;\r\n    }\r\n\r\n    public Book()\r\n    {\r\n\r\n    }\r\n\r\n    public Book(String bookId2, String title2)\r\n    {\r\n        setBookId(bookId2);\r\n        setTitle(title2);\r\n    }\r\n\r\n    public void setBookId(String bookId)\r\n    {\r\n        this.bookId = bookId;\r\n    }\r\n\r\n    /**\r\n     * Gets the category.\r\n     * \r\n     * @return the category\r\n     */\r\n    public Set<Categories> getCategory()\r\n    {\r\n        return category;\r\n    }\r\n\r\n    /**\r\n     * Sets the category.\r\n     * \r\n     * @param category\r\n     *            the new category\r\n     */\r\n    public void setCategory(Set<Categories> category)\r\n    {\r\n        this.category = category;\r\n    }\r\n\r\n    /**\r\n     * Gets the title.\r\n     * \r\n     * @return the title\r\n     */\r\n    public String getTitle()\r\n    {\r\n        return title;\r\n    }\r\n\r\n    /**\r\n     * Sets the title.\r\n     * \r\n     * @param title\r\n     *            the new title\r\n     */\r\n    public void setTitle(String title)\r\n    {\r\n        this.title = title;\r\n    }\r\n\r\n    /**\r\n     * Gets the author.\r\n     * \r\n     * @return the author\r\n     */\r\n    public String getAuthor()\r\n    {\r\n        return author;\r\n    }\r\n\r\n    /**\r\n     * Sets the author.\r\n     * \r\n     * @param author\r\n     *            the new author\r\n     */\r\n    public void setAuthor(String author)\r\n    {\r\n        this.author = author;\r\n    }\r\n\r\n    /**\r\n     * Gets the book_id.\r\n     * \r\n     * @return the book_id\r\n     */\r\n    public String getBookId()\r\n    {\r\n        return bookId;\r\n    }\r\n\r\n    /**\r\n     * Gets the description.\r\n     * \r\n     * @return the description\r\n     */\r\n    public String getDescription()\r\n    {\r\n        return description;\r\n    }\r\n\r\n    /**\r\n     * Sets the description.\r\n     * \r\n     * @param description\r\n     *            the new description\r\n     */\r\n    public void setDescription(String description)\r\n    {\r\n        this.description = description;\r\n    }\r\n\r\n    /**\r\n     * Gets the publisher.\r\n     * \r\n     * @return the publisher\r\n     */\r\n    public String getPublisher()\r\n    {\r\n        return publisher;\r\n    }\r\n\r\n    /**\r\n     * Sets the publisher.\r\n     * \r\n     * @param publisher\r\n     *            the new publisher\r\n     */\r\n    public void setPublisher(String publisher)\r\n    {\r\n        this.publisher = publisher;\r\n    }\r\n\r\n    /**\r\n     * Gets the image.\r\n     * \r\n     * @return the image\r\n     */\r\n    public String getImage()\r\n    {\r\n        return image;\r\n    }\r\n\r\n    /**\r\n     * Sets the image.\r\n     * \r\n     * @param image\r\n     *            the new image\r\n     */\r\n    public void setImage(String image)\r\n    {\r\n        this.image = image;\r\n    }\r\n\r\n    /**\r\n     * Gets the language.\r\n     * \r\n     * @return the language\r\n     */\r\n    public Languages getLanguage()\r\n    {\r\n        return language;\r\n    }\r\n\r\n    /**\r\n     * Sets the language.\r\n     * \r\n     * @param language\r\n     *            the new language\r\n     */\r\n    public void setLanguage(Languages language)\r\n    {\r\n        this.language = language;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/BookDetails.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Pragalbh Garg\n *\n */\n@Entity\n@Table(name = \"book_details\", schema = \"KunderaExamples@hbaseTest\")\npublic class BookDetails\n{\n    @Id\n    @Column(name = \"book_details\")\n    @GeneratedValue(strategy = GenerationType.TABLE)\n    private String id;\n\n    /** The isbn. */\n    private String isbn;\n\n    /** The copies_num. */\n    @Column(name = \"copies_num\")\n    private int copiesNum;\n\n    public int getCopiesNum()\n    {\n        return copiesNum;\n    }\n\n    public void setCopiesNum(int copiesNum)\n    {\n        this.copiesNum = copiesNum;\n    }\n\n    /** The hits. */\n    private int hits;\n\n    public int getHits()\n    {\n        return hits;\n    }\n\n    public void setHits(int hits)\n    {\n        this.hits = hits;\n    }\n\n    public String getIsbn()\n    {\n        return isbn;\n    }\n\n    public void setIsbn(String isbn)\n    {\n        this.isbn = isbn;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/Categories.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2014 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase.crud;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\nimport com.impetus.kundera.index.Index;\r\nimport com.impetus.kundera.index.IndexCollection;\r\n\r\n/**\r\n * @author Pragalbh Garg\r\n *\r\n */\r\n@Entity\r\n@Table(name = \"book_categories\", schema = \"KunderaExamples@hbaseTest\")\r\n@IndexCollection(columns = { @Index(name = \"categoryId\"), @Index(name = \"categoryName\") })\r\npublic class Categories\r\n{\r\n\r\n    /** The category_id. */\r\n    @Id\r\n    @Column(name = \"category_id\")\r\n    private String categoryId;\r\n\r\n    /** The category_name. */\r\n    @Column(name = \"category_name\")\r\n    private String categoryName;\r\n\r\n\r\n\r\n    /**\r\n     * Gets the category_name.\r\n     * \r\n     * @return the category_name\r\n     */\r\n    public String getCategoryName()\r\n    {\r\n        return categoryName;\r\n    }\r\n\r\n    /**\r\n     * Sets the category_name.\r\n     * \r\n     * @param categoryName\r\n     *            the new category_name\r\n     */\r\n    public void setCategoryName(String categoryName)\r\n    {\r\n        this.categoryName = categoryName;\r\n    }\r\n\r\n    /**\r\n     * Gets the category_id.\r\n     * \r\n     * @return the category_id\r\n     */\r\n    public String getCategoryId()\r\n    {\r\n        return categoryId;\r\n    }\r\n\r\n    /**\r\n     * Sets the category_id.\r\n     * \r\n     * @param categoryId\r\n     *            the new category_id\r\n     */\r\n    public void setCategoryId(String categoryId)\r\n    {\r\n        this.categoryId = categoryId;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/EmbeddedCollectionEntity.java",
    "content": "package com.impetus.client.hbase.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n@Embeddable\npublic class EmbeddedCollectionEntity\n{\n    @Column(name = \"COLLECTION_ID\")\n    private String collectionId;\n\n    @Column(name = \"COLLECTION_NAME\")\n    private String collectionName;\n\n    public String getCollectionId()\n    {\n        return collectionId;\n    }\n\n    public void setCollectionId(String collectionId)\n    {\n        this.collectionId = collectionId;\n    }\n\n    public String getCollectionName()\n    {\n        return collectionName;\n    }\n\n    public void setCollectionName(String collectionName)\n    {\n        this.collectionName = collectionName;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/EmbeddedEntity.java",
    "content": "package com.impetus.client.hbase.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n@Embeddable\npublic class EmbeddedEntity\n{\n    @Column(name = \"EMAIL_ID\", table = \"HBASE_SECONDARY_TABLE\")\n    private String emailId;\n\n    @Column(name = \"PHONE_NO\")\n    private long phoneNo;\n\n    public String getEmailId()\n    {\n        return emailId;\n    }\n\n    public void setEmailId(String emailId)\n    {\n        this.emailId = emailId;\n    }\n\n    public long getPhoneNo()\n    {\n        return phoneNo;\n    }\n\n    public void setPhoneNo(long phoneNo)\n    {\n        this.phoneNo = phoneNo;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/HBaseBatchProcessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.persistence.api.Batcher;\n\n/**\n * Batch processing test case for cassandra.\n * \n * @author vivek.mishra\n * \n */\npublic class HBaseBatchProcessorTest\n{\n\n    /**\n     * persistence unit.\n     */\n    private static final String PERSISTENCE_UNIT = \"HbaseBatchTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /** Rows. */\n    private List<PersonBatchHBaseEntity> rows;\n\n    private HBaseCli cli;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test case for batch operation.\n     */\n    @Test\n    public void onBatch()\n    {\n        int counter = 0;\n        rows = prepareData(10);\n        for (PersonBatchHBaseEntity entity : rows)\n        {\n            em.persist(entity);\n\n            // check for implicit flush.\n            if (++counter == 5)\n            {\n                Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n\n                Batcher client = (Batcher) clients.get(PERSISTENCE_UNIT);\n                Assert.assertEquals(5, client.getBatchSize());\n                em.clear();\n                for (int i = 0; i < 5; i++)\n                {\n\n                    // assert on each batch size record\n                    Assert.assertNotNull(em.find(PersonBatchHBaseEntity.class, rows.get(i).getPersonId()));\n\n                    // as batch size is 5.\n                    Assert.assertNull(em.find(PersonBatchHBaseEntity.class, rows.get(6).getPersonId()));\n                }\n                // means implicit flush must happen\n            }\n        }\n\n        // flush all on close.\n        // explicit flush on close\n        em.clear();\n        em.flush();\n\n        String sql = \" Select p from PersonBatchHBaseEntity p\";\n        Query query = em.createQuery(sql);\n        List<PersonBatchHBaseEntity> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(10, results.size());\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        for (PersonBatchHBaseEntity o : rows)\n        {\n            em.remove(o);\n        }\n\n        em.close();\n        emf.close();\n\n        if (cli != null )\n        {\n            cli.dropTable(\"KunderaHbaseDataType\");\n            cli.stopCluster(\"KunderaHbaseDataType\");\n        }\n\n    }\n\n    /**\n     * @param noOfRecords\n     * @return\n     */\n    private List<PersonBatchHBaseEntity> prepareData(Integer noOfRecords)\n    {\n        List<PersonBatchHBaseEntity> persons = new ArrayList<PersonBatchHBaseEntity>();\n        for (int i = 1; i <= noOfRecords; i++)\n        {\n            PersonBatchHBaseEntity o = new PersonBatchHBaseEntity();\n            o.setPersonId(i + \"\");\n            o.setPersonName(\"vivek\" + i);\n            o.setAge(10);\n            persons.add(o);\n        }\n\n        return persons;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/HBaseGroupByTest.java",
    "content": "///*******************************************************************************\n// *  * Copyright 2015 Impetus Infotech.\n// *  *\n// *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n// *  * you may not use this file except in compliance with the License.\n// *  * You may obtain a copy of the License at\n// *  *\n// *  *      http://www.apache.org/licenses/LICENSE-2.0\n// *  *\n// *  * Unless required by applicable law or agreed to in writing, software\n// *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n// *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// *  * See the License for the specific language governing permissions and\n// *  * limitations under the License.\n// ******************************************************************************/\n//package com.impetus.client.hbase.crud;\n//\n//import javax.persistence.Persistence;\n//\n//import org.elasticsearch.common.settings.Settings;\n//import org.elasticsearch.common.settings.Settings.Builder;\n//import org.elasticsearch.node.Node;\n//import org.elasticsearch.node.NodeBuilder;\n//import org.junit.AfterClass;\n//import org.junit.BeforeClass;\n//import org.junit.Test;\n//\n//import com.impetus.kundera.client.query.GroupByBaseTest;\n//\n///**\n// * The Class HBaseGroupByTest.\n// * \n// * @author: karthikp.manchala\n// */\n//public class HBaseGroupByTest extends GroupByBaseTest\n//{\n//    /** The node. */\n//    private static Node node = null;\n//\n//    /**\n//     * Sets the up before class.\n//     * \n//     * @throws Exception\n//     *             the exception\n//     */\n//    @BeforeClass\n//    public static void setUpBeforeClass() throws Exception\n//    {\n//        if (!checkIfServerRunning())\n//        {\n//            Builder builder = Settings.settingsBuilder();\n//            builder.put(\"path.home\", \"target/data\");\n//            node = new NodeBuilder().settings(builder).node();\n//        }\n//\n//        emf = Persistence.createEntityManagerFactory(\"hbaseESindexerTest\");\n//        em = emf.createEntityManager();\n//        init();\n//    }\n//\n//    /**\n//     * Test aggregation.\n//     */\n//    @Test\n//    public void test()\n//    {\n//        testAggregation();\n//    }\n//\n//    /**\n//     * Tear down after class.\n//     * \n//     * @throws Exception\n//     *             the exception\n//     */\n//    @AfterClass\n//    public static void tearDownAfterClass() throws Exception\n//    {\n//        em.createQuery(\"Delete from Person p\").executeUpdate();\n//        waitThread();\n//\n//        em.close();\n//        emf.close();\n//\n//        if (node != null)\n//            node.close();\n//    }\n//\n//}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/HBaseIdQueryTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.hbase.crud;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class HBaseIdQueryTest extends BaseTest\n{\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    private Map<Object, Object> col;\n\n    private HBaseCli cli;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n        emf = Persistence.createEntityManagerFactory(\"hbaseTest\");\n        em = emf.createEntityManager();\n        col = new java.util.HashMap<Object, Object>();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        for (Object val : col.values())\n        {\n            em.remove(val);\n        }\n        em.close();\n        if (cli != null)\n        {\n            cli.dropTable(\"KunderaExamples\");\n        }\n        LuceneCleanupUtilities.cleanLuceneDirectory(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance()\n                .getApplicationMetadata().getPersistenceUnitMetadata(\"hbaseTest\"));\n        emf.close();\n    }\n\n    @Test\n    public void test()\n    {\n        init();\n        em.clear();\n        findById();\n        findByWithOutWhereClause();\n        findByIdEQ();\n        findByIdLT();\n        findByIdLTE();\n        findByIdGT();\n        findByIdGTE();\n        findByIdGTEAndLT();\n        findByIdGTAndLTE();\n        findByIdAndAge();\n        findByIdGTAndAgeGTAndLT();\n        findByIdAndAgeGTAndLT();\n        findByIdGTEAndAge();\n        findByIdLTEAndAge();\n    }\n\n    /**\n     * \n     */\n    private void findByIdAndAge()\n    {\n        String qry = \"Select p.personName, p.age from PersonHBase p where p.personId = 1 and p.age = 10\";\n        Query q = em.createQuery(qry);\n        List<PersonHBase> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        for (PersonHBase person : persons)\n        {\n            Assert.assertEquals(new Integer(10), person.getAge());\n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n            Assert.assertEquals(10, person.getAge().intValue());\n        }\n    }\n\n    /**\n     * \n     */\n    private void findByIdAndAgeGTAndLT()\n    {/*\n      * String qry =\n      * \"Select p.personName from PersonHBase p where p.personId = 1 and p.personName = vivek and p.age >=10 and p.age <= 20\"\n      * ; Query q = em.createQuery(qry); List<PersonHBase> persons =\n      * q.getResultList(); Assert.assertNotNull(persons); Assert.assertEquals(1,\n      * persons.size()); int count = 0; for (PersonHBase person : persons) { if\n      * (person.getPersonId().equals(\"1\")) { Assert.assertNull(person.getAge());\n      * Assert.assertEquals(\"vivek\", person.getPersonName()); count++; } }\n      * Assert.assertEquals(1, count);\n      */\n    }\n\n    /**\n     * \n     */\n    private void findByWithOutWhereClause()\n    {\n        String qry = \"Select p.personName from PersonHBase p\";\n        Query q = em.createQuery(qry);\n        List<PersonHBase> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonHBase person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n\n    }\n\n    /**\n     * \n     */\n    private void findByIdEQ()\n    {\n        String qry = \"Select p.personName from PersonHBase p where p.personId = 2\";\n        Query q = em.createQuery(qry);\n        List<PersonHBase> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        for (PersonHBase person : persons)\n        {\n            Assert.assertNull(person.getAge());\n            Assert.assertEquals(\"2\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n        }\n\n    }\n\n    /**\n     * \n     */\n    private void findByIdLT()\n    {\n        String qry = \"Select p.personName from PersonHBase p where p.personId < 3\";\n        Query q = em.createQuery(qry);\n        List<PersonHBase> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(2, persons.size());\n        int count = 0;\n        for (PersonHBase person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdLTE()\n    {\n        String qry = \"Select p.personName, p.age from PersonHBase p where p.personId <= 3\";\n        Query q = em.createQuery(qry);\n        List<PersonHBase> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(2, persons.size());\n        int count = 0;\n        for (PersonHBase person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertEquals(new Integer(20), person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(new Integer(10), person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdGT()\n    {\n        String qry = \"Select p.personName from PersonHBase p where p.personId > 1\";\n        Query q = em.createQuery(qry);\n        List<PersonHBase> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonHBase person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTE()\n    {\n        String qry = \"Select p.personName from PersonHBase p where p.personId >= 1 \";\n        Query q = em.createQuery(qry);\n        List<PersonHBase> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonHBase person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTEAndLT()\n    {\n        String qry = \"Select p.personName from PersonHBase p where p.personId >= 1 and p.personId < 3\";\n        Query q = em.createQuery(qry);\n        List<PersonHBase> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(2, persons.size());\n        int count = 0;\n        for (PersonHBase person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTAndLTE()\n    {\n        String qry = \"Select p.personName from PersonHBase p where p.personId > 1 and p.personId <= 2\";\n        Query q = em.createQuery(qry);\n        List<PersonHBase> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        int count = 0;\n        for (PersonHBase person : persons)\n        {\n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertNull(person.getAge());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTAndAgeGTAndLT()\n    {\n\n        String qry = \"Select p.personName from PersonHBase p where p.personId > 1 and p.age >=10 and p.age <= 20\";\n        Query q = em.createQuery(qry);\n        List<PersonHBase> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonHBase person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n    }\n\n    /**\n     * \n     */\n    private void findById()\n    {\n        PersonHBase personHBase = findById(PersonHBase.class, \"1\", em);\n        Assert.assertNotNull(personHBase);\n        Assert.assertEquals(\"vivek\", personHBase.getPersonName());\n        Assert.assertEquals(new Integer(10), personHBase.getAge());\n\n        personHBase = findById(PersonHBase.class, \"2\", em);\n        Assert.assertNotNull(personHBase);\n        Assert.assertEquals(\"vivek\", personHBase.getPersonName());\n        Assert.assertEquals(new Integer(20), personHBase.getAge());\n\n        personHBase = findById(PersonHBase.class, \"3\", em);\n        Assert.assertNotNull(personHBase);\n        Assert.assertEquals(\"vivek\", personHBase.getPersonName());\n        Assert.assertEquals(new Integer(15), personHBase.getAge());\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTEAndAge()\n    {\n        String qry = \"Select p.personName, p.age from PersonHBase p where p.personId >= 1 and p.age = 10\";\n        Query q = em.createQuery(qry);\n        List<PersonHBase> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        for (PersonHBase person : persons)\n        {\n            Assert.assertEquals(new Integer(10), person.getAge());\n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n        }\n    }\n\n    /**\n     * \n     */\n    private void findByIdLTEAndAge()\n    {\n        String qry = \"Select p.personName, p.age from PersonHBase p where p.personId <= 3 and p.age = 10\";\n        Query q = em.createQuery(qry);\n        List<PersonHBase> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        for (PersonHBase person : persons)\n        {\n            Assert.assertEquals(new Integer(10), person.getAge());\n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n        }\n\n    }\n\n    private void init()\n    {\n\n        // cli.createTable(\"PERSON\");\n        // cli.addColumnFamily(\"PERSON\", \"PERSON\");\n        Object p1 = prepareHbaseInstance(\"1\", 10);\n        Object p2 = prepareHbaseInstance(\"2\", 20);\n        Object p3 = prepareHbaseInstance(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/HBaseLuceneAssociatedEntitiesTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport static org.junit.Assert.assertNotNull;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * @author Pragalbh Garg\n * \n */\npublic class HBaseLuceneAssociatedEntitiesTest extends BaseTest {\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    protected Map<String, String> propertyMap = new HashMap<String, String>();\n\n    private HBaseCli cli;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception {\n        cli = new HBaseCli();\n        cli.startCluster();\n        propertyMap.put(\"index.home.dir\", \"lucene\");\n        emf = Persistence.createEntityManagerFactory(\"hbaseTest\", propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception {\n        em.close();\n        if (cli != null) {\n            cli.dropTable(\"KunderaExamples\");\n        }\n        LuceneCleanupUtilities.cleanDir(\"./lucene\");\n        emf.close();\n    }\n\n    /*\n     * @Test public void test1() { init();\n     * \n     * \n     * }\n     */\n\n    @Test\n    public void test() {\n        init();\n        em.clear();\n\n        String qry = \"select b from Book b\";\n        Query q = em.createQuery(qry);\n        List<Book> books = q.getResultList();\n\n        assertNotNull(books);\n        Assert.assertEquals(\"title\", books.get(0).getTitle());\n        Assert.assertEquals(2, books.get(0).getCategory().size());\n        Iterator<Categories> itr = books.get(0).getCategory().iterator();\n        while (itr.hasNext()) {\n            Categories cat = (Categories) itr.next();\n            if (cat.getCategoryId().equals(\"c1\")) {\n                Assert.assertEquals(\"fiction\", cat.getCategoryName());\n            } else {\n                Assert.assertEquals(\"thriller\", cat.getCategoryName());\n            }\n        }\n        Assert.assertEquals(\"l1\", books.get(0).getLanguage().getLanguageId());\n        Assert.assertEquals(\"isbn\", books.get(0).getBookDetails().getIsbn());\n\n        qry = \"select b from Book b where b.language = :language\";\n        q = em.createQuery(qry);\n        q.setParameter(\"language\", \"l1\");\n        books = q.getResultList();\n        assertNotNull(books);\n        Assert.assertEquals(\"1\", books.get(0).getBookId());\n\n        qry = \"select b from Book b where b.language = :language\";\n        q = em.createQuery(qry);\n        q.setParameter(\"language\", \"l2\");\n        books = q.getResultList();\n        Assert.assertEquals(0, books.size());\n\n        qry = \"select b from Book b where b.bookDetails = :bookdetails\";\n        q = em.createQuery(qry);\n        q.setParameter(\"bookdetails\", \"1\");\n        books = q.getResultList();\n        assertNotNull(books);\n        Assert.assertEquals(\"1\", books.get(0).getBookId());\n    }\n\n    private void init() {\n        Categories cat1 = new Categories();\n        cat1.setCategoryId(\"c1\");\n        cat1.setCategoryName(\"fiction\");\n\n        Categories cat2 = new Categories();\n        cat2.setCategoryId(\"c2\");\n        cat2.setCategoryName(\"thriller\");\n\n        Set<Categories> cat = new HashSet<Categories>();\n        cat.add(cat1);\n        cat.add(cat2);\n        Languages lang1 = new Languages();\n        lang1.setLanguage(\"english\");\n        lang1.setLanguageId(\"l1\");\n\n        Languages lang2 = new Languages();\n        lang2.setLanguage(\"hindi\");\n        lang2.setLanguageId(\"l2\");\n\n        BookDetails bookDetails1 = new BookDetails();\n        bookDetails1.setCopiesNum(50);\n        bookDetails1.setHits(0);\n        bookDetails1.setIsbn(\"isbn\");\n\n        Book book1 = new Book();\n        book1.setAuthor(\"author\");\n        book1.setTitle(\"title\");\n        book1.setCategory(cat);\n        book1.setImage(\"image\");\n        book1.setPublisher(\"publisher\");\n        book1.setDescription(\"description\");\n        book1.setLanguage(lang1);\n        book1.setBookDetails(bookDetails1);\n\n        em.persist(cat1);\n        em.persist(cat2);\n        em.persist(lang1);\n        em.persist(lang2);\n        em.persist(book1);\n\n        em.clear();\n\n       \n\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/HBaseLuceneTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.PersonHBase.Day;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * @author Shaheed.Hussain\n * \n */\npublic class HBaseLuceneTest extends BaseTest\n{\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    protected Map<String, String> propertyMap = new HashMap<String, String>();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        propertyMap.put(\"index.home.dir\", \"lucene\");\n        emf = Persistence.createEntityManagerFactory(\"hbaseTest\", propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        LuceneCleanupUtilities.cleanLuceneDirectory(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance()\n                .getApplicationMetadata().getPersistenceUnitMetadata(\"hbaseTest\"));\n        LuceneCleanupUtilities.cleanDir(\"./lucene\");\n        emf.close();\n    }\n\n    @Test\n    public void likeQueryTest()\n    {\n        init();\n        em.clear();\n\n        String qry = \"Select p from PersonHBase p where p.personName like :name\";\n        Query q = em.createQuery(qry);\n        q.setParameter(\"name\", \"vi\");\n        List<PersonHBase> persons = q.getResultList();\n        assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n\n        qry = \"Select p from PersonHBase p where p.personName like :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"pragalbh\");\n        persons = q.getResultList();\n        assertEquals(0, persons.size());\n        \n        PersonHBase p = new PersonHBase();\n        p.setAge(20);\n        p.setDay(Day.MONDAY);\n        p.setMonth(Month.JAN);\n        p.setPersonId(\"4\");\n        p.setPersonName(\"pragalbh garg\");\n        \n        PersonHBase g = new PersonHBase();\n        g.setAge(20);\n        g.setDay(Day.MONDAY);\n        g.setMonth(Month.JAN);\n        g.setPersonId(\"5\");\n        g.setPersonName(\"karthik prasad\");\n        \n        em.persist(p);\n        em.persist(g);\n        \n        qry = \"Select p from PersonHBase p where p.personName like :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"garg\");\n        persons = q.getResultList();\n        assertEquals(1, persons.size());\n        \n        qry = \"Select p from PersonHBase p where p.personName like :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"karthik \");\n        persons = q.getResultList();\n        assertEquals(1, persons.size());\n    }\n\n    @Test\n    public void test()\n    {\n        init();\n        em.clear();\n        \n        String qry = \"Select p from PersonHBase p where p.personName = :name\";\n        Query q = em.createQuery(qry);\n        q.setParameter(\"name\", \"vivek\");\n        List<PersonHBase> persons = q.getResultList();\n        Assert.assertEquals(3, persons.size());\n\n        qry = \"Select p.personName, p.age from PersonHBase p where p.personId = 1 and p.age = 10\";\n        q = em.createQuery(qry);\n        persons = q.getResultList();\n        assertNotNull(persons);\n        assertEquals(1, persons.size());\n        assertNull(persons.get(0).getMonth());\n        assertNull(persons.get(0).getDay());\n        assertEquals(10, persons.get(0).getAge().intValue());\n        assertEquals(\"vivek\", persons.get(0).getPersonName());\n\n        qry = \"Select p.personName from PersonHBase p where p.age=20\";\n        q = em.createQuery(qry);\n        persons = q.getResultList();\n        assertNotNull(persons);\n        assertEquals(1, persons.size());\n        assertNull(persons.get(0).getMonth());\n        assertNull(persons.get(0).getDay());\n        assertNull(persons.get(0).getAge());\n        assertEquals(\"vivek\", persons.get(0).getPersonName());\n\n        qry = \"Select p.age from PersonHBase p where p.personId = 2\";\n        q = em.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        assertNull(persons.get(0).getMonth());\n        assertNull(persons.get(0).getDay());\n        assertNull(persons.get(0).getPersonName());\n        assertEquals(20, persons.get(0).getAge().intValue());\n\n        qry = \"Select p from PersonHBase p\";\n        q = em.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        \n        PersonHBase p = new PersonHBase();\n        p.setAge(20);\n        p.setDay(Day.MONDAY);\n        p.setMonth(Month.JAN);\n        p.setPersonId(\"4\");\n        p.setPersonName(\"pragalbh garg\");\n        em.persist(p);\n        \n        qry = \"Select p from PersonHBase p where p.personName = :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"pragalbh garg\");\n        persons = q.getResultList();\n        assertEquals(1, persons.size());\n        \n        qry = \"Select p from PersonHBase p where p.personName = :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"pragalbh g\");\n        persons = q.getResultList();\n        assertEquals(0, persons.size());\n\n    }\n\n    private void init()\n    {\n        Object p1 = prepareHbaseInstance(\"1\", 10);\n        Object p2 = prepareHbaseInstance(\"2\", 20);\n        Object p3 = prepareHbaseInstance(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/HbaseESAggregationTest.java",
    "content": "///*******************************************************************************\n// *  * Copyright 2015 Impetus Infotech.\n// *  *\n// *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n// *  * you may not use this file except in compliance with the License.\n// *  * You may obtain a copy of the License at\n// *  *\n// *  *      http://www.apache.org/licenses/LICENSE-2.0\n// *  *\n// *  * Unless required by applicable law or agreed to in writing, software\n// *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n// *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// *  * See the License for the specific language governing permissions and\n// *  * limitations under the License.\n// ******************************************************************************/\n///*\n// * author: karthikp.manchala\n// */\n//package com.impetus.client.hbase.crud;\n//\n//import java.util.List;\n//\n//import javax.persistence.Persistence;\n//\n//import org.elasticsearch.common.settings.Settings;\n//import org.elasticsearch.common.settings.Settings.Builder;\n//import org.elasticsearch.node.Node;\n//import org.elasticsearch.node.NodeBuilder;\n//import org.junit.After;\n//import org.junit.AfterClass;\n//import org.junit.Assert;\n//import org.junit.Before;\n//import org.junit.BeforeClass;\n//import org.junit.Test;\n//\n//import com.impetus.kundera.client.query.AggregationsBaseTest;\n//import com.impetus.kundera.query.Person;\n//\n///**\n// * The Class HBaseESAggregationTest.\n// * \n// * @\n// */\n//public class HbaseESAggregationTest extends AggregationsBaseTest\n//{\n//    /** The node. */\n//    private static Node node = null;\n//\n//    /**\n//     * Sets the up before class.\n//     * \n//     * @throws Exception\n//     *             the exception\n//     */\n//    @BeforeClass\n//    public static void setUpBeforeClass() throws Exception\n//    {\n//        if (!checkIfServerRunning())\n//        {\n//            Builder builder = Settings.settingsBuilder();\n//            builder.put(\"path.home\", \"target/data\");\n//            node = new NodeBuilder().settings(builder).node();\n//        }\n//    }\n//\n//    /**\n//     * Setup.\n//     * \n//     * @throws InterruptedException\n//     *             the interrupted exception\n//     */\n//    @Before\n//    public void setup() throws InterruptedException\n//    {\n//\n//        emf = Persistence.createEntityManagerFactory(\"hbaseESindexerTest\");\n//        em = emf.createEntityManager();\n//        init();\n//    }\n//\n//    /**\n//     * Test.\n//     */\n//    @Test\n//    public void test()\n//    {\n//        testAggregation();\n//    }\n//\n//    @Test\n//    public void indexDeletionTest() throws Exception\n//    {\n//        init();\n//        Thread.sleep(1000);\n//        String query = \"Select min(p.age) from Person p\";\n//        List resultList = em.createQuery(query).getResultList();\n//        Assert.assertEquals(1, resultList.size());\n//        Assert.assertEquals(10.0, resultList.get(0));\n//\n//        Person person = em.find(Person.class, \"2\");\n//        em.remove(person);\n//        Thread.sleep(1000);\n//        query = \"Select min(p.age) from Person p\";\n//        resultList = em.createQuery(query).getResultList();\n//        Assert.assertEquals(1, resultList.size());\n//        Assert.assertEquals(20.0, resultList.get(0));\n//\n//        person = em.find(Person.class, \"1\");\n//        em.remove(person);\n//        Thread.sleep(1000);\n//        query = \"Select min(p.age) from Person p\";\n//        resultList = em.createQuery(query).getResultList();\n//        Assert.assertEquals(1, resultList.size());\n//        Assert.assertEquals(30.0, resultList.get(0));\n//    }\n//\n//    @Override\n//    protected void testBetweenWithExpression()\n//    {\n//        // do nothing.. exception in hbase client for (15 + 5)\n//    }\n//\n//    /**\n//     * Tear down after class.\n//     * \n//     * @throws Exception\n//     *             the exception\n//     */\n//    @AfterClass\n//    public static void tearDownAfterClass() throws Exception\n//    {\n//        if (node != null)\n//            node.close();\n//    }\n//\n//    /**\n//     * Tear down.\n//     */\n//    @After\n//    public void tearDown()\n//    {\n//        em.createQuery(\"DELETE FROM Person p\").executeUpdate();\n//        em.close();\n//        emf.close();\n//    }\n//\n//}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/HbaseSecondaryTableEntity.java",
    "content": "package com.impetus.client.hbase.crud;\n\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.CollectionTable;\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.SecondaryTable;\nimport javax.persistence.SecondaryTables;\nimport javax.persistence.Table;\n\n\n\n\n\n@Table(name = \"HBASE_TABLE\")\n@SecondaryTables({\n    @SecondaryTable(name = \"HBASE_SECONDARY_TABLE\"),\n    @SecondaryTable(name=\"t_country\")\n})\n//@SecondaryTable(name = \"HBASE_SECONDARY_TABLE\")\n@Entity\npublic class HbaseSecondaryTableEntity\n{\n    @Id\n    @Column(name = \"OBJECT_ID\")\n    private String objectId;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    @Column(name = \"AGE\", table = \"HBASE_SECONDARY_TABLE\")\n    private int age;\n    \n    @Column(name = \"Country\", table = \"t_country\")\n    private String country;\n    \n    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private PersonSecondaryTableAddress address;\n    \n    \n    @ElementCollection\n    @CollectionTable(name = \"embeddedEntities\")\n    private List<EmbeddedCollectionEntity> embeddedEntities;\n\n    @Embedded\n    private EmbeddedEntity embeddedEntity;\n\n    public String getObjectId()\n    {\n        return objectId;\n    }\n\n    public void setObjectId(String objectId)\n    {\n        this.objectId = objectId;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n    \n    public void setCountry(String country)\n    {\n        this.country = country;\n    }\n    \n    public String getCountry()\n    {\n        return this.country;\n    }\n\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public EmbeddedEntity getEmbeddedEntity()\n    {\n        return embeddedEntity;\n    }\n\n    public void setEmbeddedEntity(EmbeddedEntity embeddedEntity)\n    {\n        this.embeddedEntity = embeddedEntity;\n    }\n    \n    public List<EmbeddedCollectionEntity> getEmbeddedEntities()\n    {\n        return embeddedEntities;\n    }\n\n    public void setEmbeddedEntities(List<EmbeddedCollectionEntity> embeddedEntities)\n    {\n        this.embeddedEntities = embeddedEntities;\n    }\n    \n    public PersonSecondaryTableAddress getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(PersonSecondaryTableAddress address)\n    {\n        this.address = address;\n    }\n\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/HbaseSecondaryTableTest.java",
    "content": "package com.impetus.client.hbase.crud;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\npublic class HbaseSecondaryTableTest\n{\n\n    private EntityManagerFactory emf;\n    \n    /** The em. */\n    private static EntityManager em;\n    \n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        \n        cli = new HBaseCli();\n        cli.startCluster();\n      \n        emf = Persistence.createEntityManagerFactory(\"hbaseTest\");\n        em = emf.createEntityManager();\n     \n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        cli.dropTable(\"KunderaExamples\");\n        cli.stopCluster(\"KunderaExamples\");\n       \n        LuceneCleanupUtilities.cleanLuceneDirectory(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance()\n                .getApplicationMetadata().getPersistenceUnitMetadata(\"hbaseTest\"));\n        emf.close();\n    }\n\n    @Test\n    public void test()\n    {\n        EntityManager em = emf.createEntityManager();\n        cli.addColumnFamily(\"KunderaExamples\", \"HBASE_SECONDARY_TABLE\");\n        cli.addColumnFamily(\"KunderaExamples\", \"t_country\");\n        \n\n        EmbeddedEntity embeddedEntity = new EmbeddedEntity();\n        embeddedEntity.setEmailId(\"kuldeep.mishra@gmail.com\");\n        embeddedEntity.setPhoneNo(9512345346l);\n        \n        List<EmbeddedCollectionEntity> embeddedEntities = new ArrayList<EmbeddedCollectionEntity>();\n        \n        EmbeddedCollectionEntity collectionEntity1 = new EmbeddedCollectionEntity();\n        collectionEntity1.setCollectionId(\"c1\");\n        collectionEntity1.setCollectionName(\"Collection 1\");\n        embeddedEntities.add(collectionEntity1);\n        \n        EmbeddedCollectionEntity collectionEntity2 = new EmbeddedCollectionEntity();\n        collectionEntity2.setCollectionId(\"c2\");\n        collectionEntity2.setCollectionName(\"Collection 2\");\n        embeddedEntities.add(collectionEntity2);\n       \n        HbaseSecondaryTableEntity entity = new HbaseSecondaryTableEntity();\n        entity.setAge(24);\n        entity.setObjectId(\"123\");\n        entity.setName(\"Kuldeep\");\n        entity.setEmbeddedEntity(embeddedEntity);\n        entity.setCountry(\"Canada\");\n        entity.setEmbeddedEntities(embeddedEntities);\n       \n        \n        PersonSecondaryTableAddress address = new PersonSecondaryTableAddress(12.23);\n        address.setAddress(\"india\");\n        entity.setAddress(address);\n\n        em.persist(entity);\n        \n\n\n        em.clear();\n\n        HbaseSecondaryTableEntity foundEntity = em.find(HbaseSecondaryTableEntity.class, \"123\");\n        Assert.assertNotNull(foundEntity);\n        Assert.assertEquals(\"Kuldeep\", foundEntity.getName());\n        Assert.assertEquals(24, foundEntity.getAge());\n        Assert.assertEquals(\"Canada\", foundEntity.getCountry());\n        Assert.assertNotNull(foundEntity.getEmbeddedEntity());\n        Assert.assertEquals(\"kuldeep.mishra@gmail.com\", foundEntity.getEmbeddedEntity().getEmailId());\n        Assert.assertEquals(9512345346l, foundEntity.getEmbeddedEntity().getPhoneNo());\n        Assert.assertNotNull(foundEntity.getAddress());\n        Assert.assertEquals(\"india\",foundEntity.getAddress().getAddress());\n        Assert.assertEquals(2, foundEntity.getEmbeddedEntities().size());\n        Assert.assertEquals(\"Collection 1\", foundEntity.getEmbeddedEntities().get(0).getCollectionName());\n        Assert.assertEquals(\"Collection 2\", foundEntity.getEmbeddedEntities().get(1).getCollectionName());\n       \n        foundEntity.setAge(25);\n        foundEntity.setName(\"kk\");\n        foundEntity.getEmbeddedEntity().setEmailId(\"kuldeep.mishra@yahoo.com\");\n\n        em.merge(foundEntity);\n\n        em.clear();\n\n        foundEntity = em.find(HbaseSecondaryTableEntity.class, \"123\");\n        Assert.assertNotNull(foundEntity);\n        Assert.assertEquals(\"kk\", foundEntity.getName());\n        Assert.assertEquals(25, foundEntity.getAge());\n        Assert.assertNotNull(foundEntity.getEmbeddedEntity());\n        Assert.assertEquals(\"kuldeep.mishra@yahoo.com\", foundEntity.getEmbeddedEntity().getEmailId());\n        Assert.assertEquals(9512345346l, foundEntity.getEmbeddedEntity().getPhoneNo());\n\n        em.remove(foundEntity);\n\n        foundEntity = em.find(HbaseSecondaryTableEntity.class, \"123\");\n        Assert.assertNull(foundEntity);\n\n    }\n    \n    \n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/HbaseShowQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport static org.junit.Assert.fail;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.io.PrintStream;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * \n * @author shaheed.hussain\n * \n */\npublic class HbaseShowQueryTest\n{\n    private static final String HBASE_PU = \"hbaseTest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Map<String, String> puProperties = new HashMap<String, String>();\n\n    private Logger logger = LoggerFactory.getLogger(HbaseShowQueryTest.class);\n\n    private File file = null;\n\n    @After\n    public void tearDown() throws Exception\n    {\n        file.delete();\n        em.close();\n        emf.close();\n        puProperties = null;\n    }\n\n    /*\n     * testing show.query property when it is disabled\n     */\n    @Test\n    public void testShowQueryDisabled() throws IOException\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n        em = emf.createEntityManager();\n        BufferedReader br = null;\n\n        try\n        {\n            boolean isFileEmpty = false;\n            file = new File(\"showQuery.log\");\n            PrintStream printStream;\n\n            printStream = new PrintStream(new FileOutputStream(file));\n            System.setOut(printStream);\n            Query findQuery = em.createQuery(\"Select s from UserInfo s\");\n            findQuery.getResultList();\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select p from UserInfo p where p.userId=\\\"PK_1\\\"\");\n            findQuery.getResultList();\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select p from UserInfo p where p.userId=\\\"Shahid\\\"\");\n            findQuery.getResultList();\n            System.setOut(printStream);\n\n            br = new BufferedReader(new FileReader(\"showQuery.log\"));\n            isFileEmpty = br.readLine() == null;\n            Assert.assertEquals(isFileEmpty, true);\n\n        }\n        catch (Exception e)\n        {\n            logger.info(e.getMessage());\n        }\n        finally\n        {\n            br.close();\n        }\n    }\n\n    /*\n     * testing kunera.show.query property when it is enabled\n     */\n    @Test\n    public void testShowQueryEnabled() throws IOException\n    {\n        puProperties.put(\"kundera.show.query\", \"true\");\n        emf = Persistence.createEntityManagerFactory(HBASE_PU, puProperties);\n        em = emf.createEntityManager();\n        BufferedReader br = null;\n        try\n        {\n            int i = 0;\n            String expectedQuery[] = new String[5];\n            String actualQuery = null;\n            file = new File(\"showQuery.log\");\n            PrintStream printStream;\n\n            printStream = new PrintStream(new FileOutputStream(file));\n            System.setOut(printStream);\n\n            Query findQuery = em.createQuery(\"Select p from UserInfo p where p.userId=\\\"PK_1\\\"\");\n            findQuery.getResultList();\n            expectedQuery[0] = \"Fetch data from user_info for userId = [PK_1]\";\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select p from UserInfo p where p.userId=Shahid\");\n            findQuery.getResultList();\n            expectedQuery[1] = \"Fetch data from user_info for userId = [Shahid]\";\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select p from UserInfo p where p.age between 32 and 35\");\n            findQuery.getResultList();\n            System.setOut(printStream);\n            expectedQuery[2] = \"Fetch data from user_info for age >= [32] AND age <= [35]\";\n\n            findQuery = em.createQuery(\"Select p from UserInfo p where p.userId=1 OR p.age=29\");\n            findQuery.getResultList();\n            expectedQuery[3] = \"Fetch data from user_info for userId = [1] OR age = [29]\";\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select p from UserInfo p where p.userId=1 AND p.age=32\");\n            findQuery.getResultList();\n            System.setOut(printStream);\n            expectedQuery[4] = \"Fetch data from user_info for userId = [1] AND age = [32]\";\n\n            br = new BufferedReader(new FileReader(\"showQuery.log\"));\n            actualQuery = br.readLine();\n            if (actualQuery == null)\n                fail(\"failed as file is empty\");\n\n            while (actualQuery != null)\n            {\n                Assert.assertEquals(expectedQuery[i++], actualQuery);\n                actualQuery = br.readLine();\n            }\n        }\n        catch (Exception e)\n        {\n            logger.info(e.getMessage());\n        }\n        finally\n        {\n            br.close();\n        }\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/Human.java",
    "content": "package com.impetus.client.hbase.crud;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"Humans\", schema = \"KunderaExamples@ilpMainSchema\")\npublic class Human\n{\n    @Id\n    public String hId;\n\n    @Column(name = \"humanAlive\")\n    public Boolean humanAlive;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"humanId\")\n    // @Column(name = \"HumansPrivatePhoto\")\n    public HumansPrivatePhoto humansPrivatePhoto;\n\n    public Human()\n    {\n\n    }\n\n    public Human(String humanId)\n    {\n        this.hId = humanId;\n    }\n\n    public Boolean getHumanAlive()\n    {\n        return humanAlive;\n    }\n\n    public void setHumanAlive(Boolean humanAlive)\n    {\n        this.humanAlive = humanAlive;\n    }\n\n    public HumansPrivatePhoto getHumansPrivatePhoto()\n    {\n        return humansPrivatePhoto;\n    }\n\n    public void setHumansPrivatePhoto(HumansPrivatePhoto humansPrivatePhoto)\n    {\n        this.humansPrivatePhoto = humansPrivatePhoto;\n    }\n\n    public String getHumanId()\n    {\n        return hId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/HumanTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class HumanTest\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n        emf = Persistence.createEntityManagerFactory(\"ilpMainSchema\");\n        em = emf.createEntityManager();\n\n    }\n\n    @Test\n    public void testOps()\n    {\n        String humanId = \"human1\";\n        Human human = new Human(humanId);\n        human.setHumanAlive(true);\n        HumansPrivatePhoto photo = new HumansPrivatePhoto(humanId);\n        photo.setPhotoName(\"myPhoto\");\n        human.setHumansPrivatePhoto(photo);\n        photo.setHuman(human);\n        em.persist(human);\n\n        em.clear(); // just to clear pc cache\n\n        Human result = em.find(Human.class, humanId);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(humanId, result.getHumanId());\n        Assert.assertEquals(\"myPhoto\", result.getHumansPrivatePhoto().getPhotoName());\n        Assert.assertTrue(result.getHumanAlive());\n\n    }\n\n    @After\n    public void tearDown()\n    {\n        em.close();\n        emf.close();\n        if (cli != null)\n        {\n            cli.dropTable(\"KunderaExamples\");\n        }\n        \n        \n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/HumansPrivatePhoto.java",
    "content": "package com.impetus.client.hbase.crud;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"HumansPrivatePhoto\", schema = \"KunderaExamples@ilpMainSchema\")\npublic class HumansPrivatePhoto\n{\n\n    @Id\n    public String humanId;\n\n    @OneToOne(mappedBy = \"humansPrivatePhoto\", cascade = CascadeType.REFRESH)\n    // @PrimaryKeyJoinColumn\n    public Human human;\n\n    public String photoName;\n\n    public HumansPrivatePhoto()\n    {\n\n    }\n\n    public HumansPrivatePhoto(String humanId)\n    {\n        this.humanId = humanId;\n    }\n\n    public Human getHuman()\n    {\n        return human;\n    }\n\n    public void setHuman(Human human)\n    {\n        this.human = human;\n    }\n\n    public String getPhotoName()\n    {\n        return photoName;\n    }\n\n    public void setPhotoName(String photoName)\n    {\n        this.photoName = photoName;\n    }\n\n    public String getHumanId()\n    {\n        return humanId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/Languages.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2014 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase.crud;\r\n\r\nimport java.util.List;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.GeneratedValue;\r\nimport javax.persistence.GenerationType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.Table;\r\n\r\nimport com.impetus.kundera.index.Index;\r\nimport com.impetus.kundera.index.IndexCollection;\r\n\r\n/**\r\n * @author Pragalbh Garg\r\n *\r\n */\r\n@Entity\r\n@Table(name = \"book_languages\", schema = \"KunderaExamples@hbaseTest\")\r\n@IndexCollection(columns = { @Index(name = \"languageId\"), @Index(name = \"language\") })\r\npublic class Languages\r\n{\r\n\r\n    /** The language_id. */\r\n    @Id\r\n    @GeneratedValue(strategy = GenerationType.TABLE)\r\n    @Column(name = \"language_id\")\r\n    private String languageId;\r\n\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, mappedBy = \"language\")\r\n    private List<Book> books;\r\n    public List<Book> getBooks()\r\n    {\r\n        return books;\r\n    }\r\n\r\n    public void setBooks(List<Book> books)\r\n    {\r\n        this.books = books;\r\n    }\r\n\r\n    /** The language. */\r\n    private String language;\r\n\r\n    /**\r\n     * Gets the language.\r\n     * \r\n     * @return the language\r\n     */\r\n    public String getLanguage()\r\n    {\r\n        return language;\r\n    }\r\n\r\n    /**\r\n     * Sets the language.\r\n     * \r\n     * @param language\r\n     *            the new language\r\n     */\r\n    public void setLanguage(String language)\r\n    {\r\n        this.language = language;\r\n    }\r\n\r\n    /**\r\n     * Gets the language_id.\r\n     * \r\n     * @return the language_id\r\n     */\r\n    public String getLanguageId()\r\n    {\r\n        return languageId;\r\n    }\r\n\r\n    /**\r\n     * Sets the language_id.\r\n     * \r\n     * @param languageId\r\n     *            the new language_id\r\n     */\r\n    public void setLanguageId(String languageId)\r\n    {\r\n        this.languageId = languageId;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/LikeQueryTest.java",
    "content": "package com.impetus.client.hbase.crud;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.schemaManager.HBaseEntitySimple;\n\n/**\n * The Class LikeQueryTest.\n */\npublic class LikeQueryTest\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"hbase\");\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    /**\n     * Like query test.\n     */\n    @Test\n    public void likeQueryTest()\n    {\n        init();\n        em.clear();\n\n        String qry = \"Select p from HBaseEntitySimple p where p.personName like :name\";\n        Query q = em.createQuery(qry);\n        q.setParameter(\"name\", \"pragal\");\n        List<HBaseEntitySimple> persons = q.getResultList();\n        assertNotNull(persons);\n        assertEquals(1, persons.size());\n        assertEquals(\"pragalbh garg\", persons.get(0).getPersonName());\n\n        qry = \"Select p from HBaseEntitySimple p where p.personName like :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"thik\");\n        persons = q.getResultList();\n        assertEquals(1, persons.size());\n        assertEquals(\"karthik prasad\", persons.get(0).getPersonName());\n    }\n\n    /**\n     * Inits the.\n     */\n    private void init()\n    {\n        HBaseEntitySimple p1 = new HBaseEntitySimple();\n        p1.setAge((short) 23);\n        p1.setPersonId(\"1\");\n        p1.setPersonName(\"pragalbh garg\");\n\n        HBaseEntitySimple p2 = new HBaseEntitySimple();\n        p2.setAge((short) 20);\n        p2.setPersonId(\"2\");\n        p2.setPersonName(\"karthik prasad\");\n\n        em.persist(p1);\n        em.persist(p2);\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/Month.java",
    "content": "package com.impetus.client.hbase.crud;\n\nenum Month\n{\n    JAN, FEB, MARCH, APRIL, MAY, JUNE;\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/PersonBatchHBaseEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON_BATCH\", schema = \"KunderaHbaseDataType@HbaseBatchTest\")\n// @Index(index = true, columns = { \"PERSON_NAME\", \"AGE\" })\npublic class PersonBatchHBaseEntity\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"AGEss\")\n    private byte[] a;\n\n    /**\n     * @return the a\n     */\n    public byte[] getA()\n    {\n        return a;\n    }\n\n    /**\n     * @param a\n     *            the a to set\n     */\n    public void setA(byte[] a)\n    {\n        this.a = a;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/PersonESIndexerHbase.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport java.sql.Timestamp;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class PersonESIndexerHbase.\n */\n@Entity\n@Table(name = \"PERSON_ESINDEXER\", schema = \"KunderaExamples@hbaseESindexerTest\")\n@IndexCollection(columns = { @com.impetus.kundera.index.Index(name = \"personName\"),\n        @com.impetus.kundera.index.Index(name = \"age\"), @com.impetus.kundera.index.Index(name = \"date\"),\n        @com.impetus.kundera.index.Index(name = \"salary\") })\npublic class PersonESIndexerHbase\n{\n\n    /** The Constant serialVersionUID. */\n    private static final long serialVersionUID = 6068131491098913126L;\n\n    /** The Constant UID. */\n    public static final String UID = \"uid\";\n\n    /** The Constant EID. */\n    public static final String EID = \"eid\";\n\n    /** The Constant FIRST_NAME. */\n    public static final String FIRST_NAME = \"firstName\";\n\n    /** The Constant LAST_NAME. */\n    public static final String LAST_NAME = \"lastName\";\n\n    /** The Constant CITY. */\n    public static final String CITY = \"city\";\n\n    /** The Constant CREATED. */\n    public static final String CREATED = \"created\";\n\n    /** The Constant LAST_MODIFIED. */\n    public static final String LAST_MODIFIED = \"lastModified\";\n\n    /** The person id. */\n    @Id\n    @Column\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The salary. */\n    @Column\n    private Double salary;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    /** The date. */\n    @Column(name = \"DATE\")\n    private Timestamp date;\n\n    /**\n     * Gets the date.\n     * \n     * @return the date\n     */\n    public Timestamp getDate()\n    {\n        return date;\n    }\n\n    /**\n     * Sets the date.\n     * \n     * @param date\n     *            the new date\n     */\n    public void setDate(Timestamp date)\n    {\n        this.date = date;\n    }\n\n    /** The day. */\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(Integer age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the day.\n     * \n     * @return the day\n     */\n    public Day getDay()\n    {\n        return day;\n    }\n\n    /**\n     * Sets the day.\n     * \n     * @param day\n     *            the day to set\n     */\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n\n    /**\n     * Gets the salary.\n     * \n     * @return the salary\n     */\n    public Double getSalary()\n    {\n        return salary;\n    }\n\n    /**\n     * Sets the salary.\n     * \n     * @param salary\n     *            the new salary\n     */\n    public void setSalary(Double salary)\n    {\n        this.salary = salary;\n    }\n\n    /**\n     * The Enum Day.\n     */\n    enum Day\n    {\n\n        /** The monday. */\n        MONDAY,\n        /** The tuesday. */\n        TUESDAY,\n        /** The wednesday. */\n        WEDNESDAY,\n        /** The thursday. */\n        THURSDAY,\n        /** The friday. */\n        FRIDAY,\n        /** The saturday. */\n        SATURDAY,\n        /** The sunday. */\n        SUNDAY;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/PersonHBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n// TODO: Auto-generated Javadoc\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON_HBASE\", schema = \"KunderaExamples@hbaseTest\")\n@IndexCollection(columns={@Index(name=\"personName\"),@Index(name=\"age\")})\npublic class PersonHBase\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    @Column(name = \"MONTH_ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Month month;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the day\n     */\n    public Day getDay()\n    {\n        return day;\n    }\n\n    /**\n     * @param day\n     *            the day to set\n     */\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n\n    public Month getMonth()\n    {\n        return month;\n    }\n\n    public void setMonth(Month month)\n    {\n        this.month = month;\n    }\n\n    enum Day\n    {\n        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/PersonHBaseTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;\nimport org.apache.hadoop.hbase.filter.Filter;\nimport org.apache.hadoop.hbase.filter.SingleColumnValueFilter;\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.HBaseClient;\nimport com.impetus.client.hbase.crud.PersonHBase.Day;\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\nimport junit.framework.Assert;\n\npublic class PersonHBaseTest extends BaseTest\n{\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    private Map<Object, Object> col;\n\n    private HBaseCli cli;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n        emf = Persistence.createEntityManagerFactory(\"hbaseTest\");\n        em = emf.createEntityManager();\n        col = new java.util.HashMap<Object, Object>();\n    }\n\n    @Test\n    public void onInsertHbase() throws Exception\n    {\n        Query findQuery = em.createQuery(\"Select p from PersonHBase p\");\n        List<PersonHBase> allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = em.createQuery(\"Select p from PersonHBase p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = em.createQuery(\"Select p.age from PersonHBase p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n        init();\n        em.clear();\n        PersonHBase personHBase = findById(PersonHBase.class, \"1\", em);\n\n        Assert.assertNotNull(personHBase);\n        Assert.assertEquals(\"vivek\", personHBase.getPersonName());\n        Assert.assertEquals(Day.MONDAY, personHBase.getDay());\n        Assert.assertEquals(Month.MARCH, personHBase.getMonth());\n\n        assertFindByName(em, \"PersonHBase\", PersonHBase.class, \"vivek\", \"personName\");\n        assertFindByNameAndAge(em, \"PersonHBase\", PersonHBase.class, \"vivek\", \"10\", \"personName\");\n        assertFindByNameAndAgeGTAndLT(em, \"PersonHBase\", PersonHBase.class, \"vivek\", \"10\", \"20\", \"personName\");\n        assertFindByNameAndAgeBetween(em, \"PersonHBase\", PersonHBase.class, \"vivek\", \"10\", \"15\", \"personName\");\n        assertFindByRange(em, \"PersonHBase\", PersonHBase.class, \"1\", \"3\", \"personId\");\n        assertFindWithoutWhereClause(em, \"PersonHBase\", PersonHBase.class);\n        assertFindByRowIds(em, \"PersonHBase\", PersonHBase.class, \"1,2,6\", \"personId\", 2);\n        assertFindByRowIds(em, \"PersonHBase\", PersonHBase.class, \"1,2,3\", \"personId\", 3);\n        selectIdQuery();\n        personHBase.setPersonName(\"Bob\");\n        em.merge(personHBase);\n\n        personHBase = findById(PersonHBase.class, \"2\", em);\n        personHBase.setPersonName(\"John\");\n        em.merge(personHBase);\n        // test case for In clause query\n        assertFindByFieldValues(em, \"PersonHBase\", PersonHBase.class, \"Bob,vivek\", \"personName\", 2);\n        assertFindByFieldValues(em, \"PersonHBase\", PersonHBase.class, \"John,vivek,Bob\", \"personName\", 3);\n        assertFindByFieldValues(em, \"PersonHBase\", PersonHBase.class, \"John,xyz\", \"personName\", 1);\n\n    }\n\n    private void selectIdQuery()\n    {\n        String query = \"select p.personId from PersonHBase p\";\n        Query q = em.createQuery(query);\n        List<PersonHBase> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNull(results.get(0).getPersonName());\n\n        query = \"select p from PersonHBase p\";\n        com.impetus.kundera.query.Query queryObject = (com.impetus.kundera.query.Query) em.createQuery(query);\n        queryObject.setFetchSize(1);\n\n        Iterator<PersonHBase> resultIterator = queryObject.iterate();\n        PersonHBase person = null;\n        int counter = 0;\n        while (resultIterator.hasNext())\n        {\n            counter++;\n            person = resultIterator.next();\n            Assert.assertNotNull(person.getPersonId());\n            Assert.assertNotNull(person.getPersonName());\n        }\n\n        Assert.assertEquals(1, counter);\n\n        query = \"Select p.personId from PersonHBase p where p.personName = vivek\";\n        // // find by name.\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNull(results.get(0).getPersonName());\n\n        q = em.createQuery(\"Select p.personId from PersonHBase p where p.personName = vivek and p.age > \" + 10);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNull(results.get(0).getAge());\n\n        q = em.createQuery(\"Select p.personId from PersonHBase p where p.personName = john OR p.age > \" + 15);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNull(results.get(0).getAge());\n\n        q = em.createQuery(\"Select p.personId from PersonHBase p where p.personName = xyz OR p.age = \" + 15);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNull(results.get(0).getAge());\n\n        q = em.createQuery(\"Select p.personId from PersonHBase p where p.personName = xyz OR p.age = \" + 45);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertTrue(results.isEmpty());\n    }\n\n    //TODO: uncomment after upgrading hbase version\n    //@Test\n    public void onInsertLuceneHbase() throws Exception\n    {\n        // enabled for es indexing.\n        Builder builder = Settings.settingsBuilder();\n        builder.put(\"path.home\", \"target/data\");\n        Node node = new NodeBuilder().settings(builder).node();\n        \n        Map<String, Object> puProperties = new HashMap<String, Object>();\n        puProperties.put(\"kundera.indexer.class\", \"com.impetus.client.es.index.ESIndexer\");\n        // puProperties.put(\"index.home.dir\", \"./lucene\"); // uncomment for\n        // lucene\n\n        EntityManagerFactory emfLucene = Persistence.createEntityManagerFactory(\"hbaseTest\", puProperties);\n        EntityManager emLucene = emfLucene.createEntityManager();\n\n        Object p1 = prepareHbaseInstance(\"1\", 10);\n        Object p2 = prepareHbaseInstance(\"2\", 20);\n        Object p3 = prepareHbaseInstance(\"3\", 15);\n        emLucene.persist(p1);\n        emLucene.persist(p2);\n        emLucene.persist(p3);\n\n        Thread.sleep(1000);\n\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        emLucene.flush();\n        emLucene.clear();\n\n        Query q = emLucene.createQuery(\"Select p from PersonHBase p where p.personName = vivek1 OR p.age= 10\");\n\n        List<PersonHBase> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertEquals(\"vivek\", results.get(0).getPersonName());\n        Assert.assertEquals(10, results.get(0).getAge().intValue());\n\n        q = emLucene\n                .createQuery(\"Select p.personId, p.personName from PersonHBase p where p.personName = vivek1 OR p.age= 10\");\n\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNotNull(results.get(0).getPersonName());\n        Assert.assertNull(results.get(0).getAge());\n\n        node.close();\n        emLucene.close();\n        emfLucene.close();\n    }\n    \n    @Test\n    public void deleteTest() throws Exception{\n        String id = \"commonId\";\n       \n        PersonHBase p = new PersonHBase();\n        p.setPersonId(id);\n        p.setAge(20);\n        p.setDay(Day.MONDAY);\n        p.setMonth(Month.JAN);\n        p.setPersonName(\"pragalbh\");\n        em.persist(p);\n        \n        Categories cat = new Categories();\n        cat.setCategoryId(id);\n        cat.setCategoryName(\"category\");\n        em.persist(cat);\n        em.remove(p);\n        \n        Categories catTest = em.find(Categories.class, id);\n        Assert.assertNotNull(catTest);\n        PersonHBase pTest = em.find(PersonHBase.class, id);\n        Assert.assertNull(pTest);\n        \n        em.remove(cat);\n        catTest = em.find(Categories.class, id);\n        Assert.assertNull(catTest);\n    }\n\n    private void init()\n    {\n        cli.startCluster();\n        // cli.createTable(\"PERSON\");\n        // cli.addColumnFamily(\"PERSON\", \"PERSON\");\n        Object p1 = prepareHbaseInstance(\"1\", 10);\n        Object p2 = prepareHbaseInstance(\"2\", 20);\n        Object p3 = prepareHbaseInstance(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n    }\n\n    @Test\n    public void onFilterOperation()\n    {\n        init();\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(\"hbaseTest\");\n\n        Filter f/* = new QualifierFilter() */;\n        f = new SingleColumnValueFilter(\"PERSON_NAME\".getBytes(), \"PERSON_NAME\".getBytes(), CompareOp.EQUAL,\n                \"vivek\".getBytes());\n\n        ((HBaseClient) client).setFilter(f);\n\n        em.clear();\n        // find by without where clause.\n        Query q = em.createQuery(\"Select p from \" + PersonHBase.class.getSimpleName() + \" p\");\n        List<PersonHBase> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n    }\n\n    // @Test\n    // public void onMergeHbase() {\n    // em.persist(prepareHbaseInstance(\"1\", 10));\n    // PersonHBase personHBase = findById(PersonHBase.class, \"1\", em);\n    // Assert.assertNotNull(personHBase);\n    // Assert.assertEquals(\"vivek\", personHBase.getPersonName());\n    // personHBase.setPersonName(\"Newvivek\");\n    //\n    // em.merge(personHBase);\n    // assertOnMerge(em, \"PersonHBase\", PersonHBase.class);\n    // o.add(PersonHBase.class);\n    // }\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n        /*\n         * * Delete is working, but as row keys are not deleted from cassandra,\n         * so resulting in issue while reading back. // Delete\n         * em.remove(em.find(Person.class, \"1\"));\n         * em.remove(em.find(Person.class, \"2\"));\n         * em.remove(em.find(Person.class, \"3\")); em.close(); emf.close(); em =\n         * null; emf = null;\n         */\n        for (Object val : col.values())\n        {\n            em.remove(val);\n        }\n        em.close();\n        if (cli != null)\n        {\n            cli.dropTable(\"KunderaExamples\");\n            cli.stopCluster(\"KunderaExamples\");\n        }\n        LuceneCleanupUtilities.cleanLuceneDirectory(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance()\n                .getApplicationMetadata().getPersistenceUnitMetadata(\"hbaseTest\"));\n        LuceneCleanupUtilities.cleanDir(\"./lucene\");\n        emf.close();\n        // if (cli.isStarted)\n\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/PersonSecondaryTableAddress.java",
    "content": "package com.impetus.client.hbase.crud;\n\n\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n\n@Entity\npublic class PersonSecondaryTableAddress\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private Double addressId;\n\n    public PersonSecondaryTableAddress()\n    {\n\n    }\n\n    public PersonSecondaryTableAddress(Double addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    @Column(name = \"address\")\n    private String address;\n\n    public String getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    public Double getAddressId()\n    {\n        return addressId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/RegexpQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.schemaManager.HBaseEntitySimple;\n\n/**\n * The Class RegexpQueryTest.\n * \n * @author karthikp.manchala\n */\npublic class RegexpQueryTest\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"hbase\");\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    /**\n     * Regexp query test.\n     */\n    @Test\n    public void regexpQueryTest()\n    {\n        init();\n        em.clear();\n\n        String qry = \"Select p from HBaseEntitySimple p where p.personName regexp :name\";\n        Query q = em.createQuery(qry);\n        q.setParameter(\"name\", \"^pra.*\");\n        List<HBaseEntitySimple> persons = q.getResultList();\n        assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        Assert.assertEquals(\"pragalbh garg\", persons.get(0).getPersonName());\n\n        qry = \"Select p from HBaseEntitySimple p where p.personName regexp :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"^[pk]\");\n        persons = q.getResultList();\n        assertNotNull(persons);\n        Assert.assertEquals(2, persons.size());\n\n        qry = \"Select p from HBaseEntitySimple p where p.personName regexp :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"pra...$\");\n        persons = q.getResultList();\n        assertEquals(1, persons.size());\n        Assert.assertEquals(\"karthik prasad\", persons.get(0).getPersonName());\n    }\n\n    /**\n     * Inits the.\n     */\n    private void init()\n    {\n        HBaseEntitySimple p1 = new HBaseEntitySimple();\n        p1.setAge((short) 23);\n        p1.setPersonId(\"1\");\n        p1.setPersonName(\"pragalbh garg\");\n\n        HBaseEntitySimple p2 = new HBaseEntitySimple();\n        p2.setAge((short) 20);\n        p2.setPersonId(\"2\");\n        p2.setPersonName(\"karthik prasad\");\n\n        em.persist(p1);\n        em.persist(p2);\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/association/AddressOTOHbase.java",
    "content": "package com.impetus.client.hbase.crud.association;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"Address\", schema = \"KunderaExamples@hbaseTest\")\npublic class AddressOTOHbase\n{\n\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private Double addressId;\n\n    public AddressOTOHbase()\n    {\n\n    }\n\n    public AddressOTOHbase(Double addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    @Column(name = \"address\")\n    private String address;\n\n    public String getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    public Double getAddressId()\n    {\n        return addressId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/association/HBaseBiAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.association;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.client.crud.associations.AssociationsBiDirectionalBase;\n\n/**\n * @author Pragalbh Garg\n *\n */\npublic class HBaseBiAssociationTest extends AssociationsBiDirectionalBase\n{\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n        _PU = \"hbase\";\n        super.setUpInternal();\n    }\n\n    @Test\n    public void test()\n    {\n        assertBegin();\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.flush();\n        if (cli != null)\n        {\n            cli.dropTable(\"KunderaHbaseExamples\");\n        }\n        tearDownInternal();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/association/HabitatMToM.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase.crud.association;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\nimport javax.xml.bind.annotation.XmlRootElement;\r\n\r\n@Entity\r\n@Table(name = \"HabitatMToM\"/*, schema = \"KunderaExamples@twissandra\"*/)\r\n@XmlRootElement\r\npublic class HabitatMToM\r\n{\r\n    @Id\r\n    @Column(name = \"ADDRESS_ID\")\r\n    private String addressId;\r\n\r\n    @Column(name = \"STREET\")\r\n    private String street;\r\n\r\n    public String getAddressId()\r\n    {\r\n        return addressId;\r\n    }\r\n\r\n    public void setAddressId(String addressId)\r\n    {\r\n        this.addressId = addressId;\r\n    }\r\n\r\n    public String getStreet()\r\n    {\r\n        return street;\r\n    }\r\n\r\n    public void setStreet(String street)\r\n    {\r\n        this.street = street;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/association/HbaseAssociationTest.java",
    "content": "package com.impetus.client.hbase.crud.association;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.client.twitter.entities.PersonalDetailHbase;\n\npublic class HbaseAssociationTest\n{\n\n    private static final String ROW_KEY = \"1\";\n\n    /** The Constant REDIS_PU. */\n    private static final String HBASE_PU = \"hbaseTest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    private HBaseCli cli;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(HbaseAssociationTest.class);\n\n    @Before\n    public void setUp()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    @Test\n    public void testCrud()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        PersonOTOHbase person = new PersonOTOHbase(ROW_KEY);\n        person.setAge(32);\n        person.setPersonName(\"vivek\");\n        AddressOTOHbase address = new AddressOTOHbase(12.23);\n        address.setAddress(\"india\");\n        person.setAddress(address);\n\n        PersonalDetailHbase detail = new PersonalDetailHbase();\n        detail.setName(\"KK\");\n        detail.setPassword(\"xxxxxxx\");\n        detail.setPersonalDetailId(\"xyz\");\n        detail.setRelationshipStatus(\"single\");\n\n        person.setPersonalDetail(detail);\n\n        em.persist(person);\n\n        em.clear();\n        PersonOTOHbase p = em.find(PersonOTOHbase.class, ROW_KEY);\n\n        // Assertions.\n        Assert.assertNotNull(p);\n        Assert.assertEquals(person.getPersonId(), p.getPersonId());\n        Assert.assertNotNull(p.getAddress());\n        Assert.assertEquals(person.getAddress().getAddress(), p.getAddress().getAddress());\n        Assert.assertNotNull(p.getPersonalDetail());\n        Assert.assertNotNull(p.getPersonalDetail().getName());\n        Assert.assertNotNull(p.getPersonalDetail().getPassword());\n        Assert.assertNotNull(p.getPersonalDetail().getPersonalDetailId());\n        Assert.assertNotNull(p.getPersonalDetail().getRelationshipStatus());\n\n        // Remove\n        em.remove(p);\n\n        em.clear(); // clear cache\n        Assert.assertNull(em.find(AddressOTOHbase.class, 12.23));\n    }\n\n    @After\n    public void tearDown()\n    {\n        cli.dropTable(\"KunderaExamples\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/association/HbaseManyToManyTest.java",
    "content": "/**\n * Copyright 2014 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.hbase.crud.association;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * \n * @author shaheed.Hussain junit for testing manyToMany in hbase\n * \n */\npublic class HbaseManyToManyTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"hbaseTest\");\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testManyToMany()\n    {\n        persistMTM();\n        List<HabitatMToM> habitatMToM = em.createQuery(\"Select h from HabitatMToM h\").getResultList();\n        assertNotNull(habitatMToM);\n        assertEquals(3, habitatMToM.size());\n\n        List<PersonnelMToM> personnelMToM = em.createQuery(\"Select p from PersonnelMToM p\").getResultList();\n        assertNotNull(personnelMToM);\n        assertEquals(2, personnelMToM.size());\n\n        personnelMToM = em.createQuery(\"Select p from PersonnelMToM p where p.personName=John\").getResultList();\n        assertEquals(personnelMToM.get(0).getPersonId(), \"125\");\n        assertNotNull(personnelMToM.get(0).getHabitats().iterator().next());\n\n        HabitatMToM habitatMToM1 = em.find(HabitatMToM.class, \"7\");\n        HabitatMToM habitatMToM2 = em.find(HabitatMToM.class, \"8\");\n        HabitatMToM habitatMToM3 = em.find(HabitatMToM.class, \"9\");\n\n        PersonnelMToM personnelMToM1 = em.find(PersonnelMToM.class, \"125\");\n        PersonnelMToM personnelMToM2 = em.find(PersonnelMToM.class, \"502\");\n\n        assertEquals(habitatMToM1.getStreet(), \"downing street\");\n        assertEquals(habitatMToM2.getStreet(), \"fleet street\");\n        assertEquals(habitatMToM3.getStreet(), \"greet street\");\n\n        assertEquals(personnelMToM1.getPersonName(), \"John\");\n        assertEquals(personnelMToM2.getPersonName(), \"Bully\");\n\n        assertEquals(2, personnelMToM1.getHabitats().size());\n        for (HabitatMToM habitat : personnelMToM1.getHabitats())\n        {\n            if (habitat.getAddressId().equals(\"7\"))\n            {\n                assertEquals(habitat.getStreet(), \"downing street\");\n            }\n            else\n            {\n                assertEquals(habitat.getStreet(), \"fleet street\");\n            }\n        }\n\n    }\n\n    private void persistMTM()\n    {\n        Set<HabitatMToM> habitats1 = new HashSet<HabitatMToM>();\n        Set<HabitatMToM> habitats2 = new HashSet<HabitatMToM>();\n\n        HabitatMToM habitat1 = new HabitatMToM();\n        habitat1.setAddressId(\"7\");\n        habitat1.setStreet(\"downing street\");\n\n        HabitatMToM habitat2 = new HabitatMToM();\n        habitat2.setAddressId(\"8\");\n        habitat2.setStreet(\"fleet street\");\n\n        HabitatMToM habitat3 = new HabitatMToM();\n        habitat3.setAddressId(\"9\");\n        habitat3.setStreet(\"greet street\");\n\n        habitats1.add(habitat1);\n        habitats1.add(habitat2);\n\n        habitats2.add(habitat2);\n        habitats2.add(habitat3);\n\n        PersonnelMToM person1 = new PersonnelMToM();\n        person1.setPersonId(\"125\");\n        person1.setPersonName(\"John\");\n\n        PersonnelMToM person2 = new PersonnelMToM();\n        person2.setPersonId(\"502\");\n        person2.setPersonName(\"Bully\");\n\n        person1.setHabitats(habitats1);\n        person2.setHabitats(habitats2);\n\n        em.persist(person1);\n        em.persist(person2);\n    }\n\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/association/PersonOTOHbase.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.association;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.client.twitter.entities.PersonalDetailHbase;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaExamples@hbaseTest\")\npublic class PersonOTOHbase\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Embedded\n    private PersonalDetailHbase personalDetail;\n\n    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressOTOHbase address;\n\n    public PersonOTOHbase(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public PersonOTOHbase()\n    {\n\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public AddressOTOHbase getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressOTOHbase address)\n    {\n        this.address = address;\n    }\n\n    public void setAge(Integer age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the personalDetail\n     */\n    public PersonalDetailHbase getPersonalDetail()\n    {\n        return personalDetail;\n    }\n\n    /**\n     * @param personalDetail\n     *            the personalDetail to set\n     */\n    public void setPersonalDetail(PersonalDetailHbase personalDetail)\n    {\n        this.personalDetail = personalDetail;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/association/PersonnelMToM.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase.crud.association;\r\n\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.JoinTable;\r\nimport javax.persistence.ManyToMany;\r\nimport javax.persistence.Table;\r\nimport javax.xml.bind.annotation.XmlRootElement;\r\n\r\nimport com.impetus.kundera.index.Index;\r\nimport com.impetus.kundera.index.IndexCollection;\r\n\r\n@Entity\r\n@Table(name = \"PersonnelMToM\"/* , schema = \"KunderaExamples@twissandra\" */)\r\n@IndexCollection(columns = { @Index(name = \"personName\") })\r\npublic class PersonnelMToM\r\n{\r\n    @Id\r\n    @Column(name = \"PERSON_ID\")\r\n    private String personId;\r\n\r\n    @Column(name = \"PERSON_NAME\")\r\n    private String personName;\r\n\r\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\r\n    @JoinTable(name = \"PERSON_ADDRESS\", schema = \"KunderaExamples\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\r\n    private Set<HabitatMToM> habitats;\r\n\r\n    public String getPersonId()\r\n    {\r\n        return personId;\r\n    }\r\n\r\n    public String getPersonName()\r\n    {\r\n        return personName;\r\n    }\r\n\r\n    public void setPersonName(String personName)\r\n    {\r\n        this.personName = personName;\r\n    }\r\n\r\n    public void setPersonId(String personId)\r\n    {\r\n        this.personId = personId;\r\n    }\r\n\r\n    public Set<HabitatMToM> getHabitats()\r\n    {\r\n        return habitats;\r\n    }\r\n\r\n    public void setHabitats(Set<HabitatMToM> habitats)\r\n    {\r\n        this.habitats = habitats;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/compositeType/HBaseCompositeTypeTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.compositeType;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * @author vivek.mishra\n * \n */\n\npublic class HBaseCompositeTypeTest\n{\n    private EntityManagerFactory emf;\n\n    private Date currentDate = new Date();\n\n    private HBaseCli cli;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n        emf = Persistence.createEntityManagerFactory(\"hbaseTest\");\n    }\n\n    /**\n     * CRUD over Compound primary Key.\n     */\n    @Test\n    public synchronized void onCRUD()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        HBaseCompoundKey key = new HBaseCompoundKey(\"mevivs\", 1, timeLineId);\n        HBasePrimeUser user = new HBasePrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.close(); // optional,just to clear persistence cache.\n\n        em = emf.createEntityManager();\n        HBasePrimeUser result = em.find(HBasePrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"my first tweet\", result.getTweetBody());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n\n        em.clear();// optional,just to clear persistence cache.\n\n        user.setTweetBody(\"After merge\");\n        em.merge(user);\n\n        em.close();// optional,just to clear persistence cache.\n\n        em = emf.createEntityManager();\n        result = em.find(HBasePrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"After merge\", result.getTweetBody());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n\n        // deleting composite\n        em.remove(result);\n\n        em.close();// optional,just to clear persistence cache.\n\n        em = emf.createEntityManager();\n        result = em.find(HBasePrimeUser.class, key);\n        Assert.assertNull(result);\n    }\n\n     @Test\n    public synchronized void onQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        HBaseCompoundKey key = new HBaseCompoundKey(\"mevivs\", 1, timeLineId);\n        HBasePrimeUser user = new HBasePrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.close(); // optional,just to clear persistence cache.\n        em = emf.createEntityManager();\n        final String noClause = \"Select u from HBasePrimeUser u\";\n\n        final String withFirstCompositeColClause = \"Select u from HBasePrimeUser u where u.key.userId = :userId\";\n\n        final String withClauseOnNoncomposite = \"Select u from HBasePrimeUser u where u.tweetDate = ?1\";\n\n        // NOSQL Intelligence to teach that query is invalid because partition\n        // key is not present?\n        final String withSecondCompositeColClause = \"Select u from HBasePrimeUser u where u.key.tweetId = :tweetId\";\n        final String withBothCompositeColClause = \"Select u from HBasePrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId\";\n        final String withAllCompositeColClause = \"Select u from HBasePrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        final String withLastCompositeColGTClause = \"Select u from HBasePrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId >= :timeLineId\";\n\n        final String withSelectiveCompositeColClause = \"Select u.key from HBasePrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n\n        // query over 1 composite and 1 non-column\n\n        // query with no clause.\n        Query q = em.createQuery(noClause);\n        List<HBasePrimeUser> results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withFirstCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withClauseOnNoncomposite);\n        q.setParameter(1, currentDate);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withSecondCompositeColClause);\n        q.setParameter(\"tweetId\", 1);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withBothCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withLastCompositeColGTClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key with selective clause.\n        q = em.createQuery(withSelectiveCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertNull(results.get(0).getTweetBody());\n\n        final String selectiveColumnTweetBodyWithAllCompositeColClause = \"Select u.tweetBody from HBasePrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        // Query for selective column tweetBody with composite key clause.\n        q = em.createQuery(selectiveColumnTweetBodyWithAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"my first tweet\", results.get(0).getTweetBody());\n        Assert.assertNull(results.get(0).getTweetDate());\n\n        final String selectiveColumnTweetDateWithAllCompositeColClause = \"Select u.tweetDate from HBasePrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        // Query for selective column tweetDate with composite key clause.\n        q = em.createQuery(selectiveColumnTweetDateWithAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(currentDate.getTime(), results.get(0).getTweetDate().getTime());\n        Assert.assertNull(results.get(0).getTweetBody());\n\n        final String withCompositeKeyClause = \"Select u from HBasePrimeUser u where u.key = :key\";\n        // Query with composite key clause.\n        q = em.createQuery(withCompositeKeyClause);\n        q.setParameter(\"key\", key);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        em.remove(user);\n\n        em.clear();// optional,just to clear persistence cache.\n    }\n\n     @Test\n    public synchronized void onNamedQueryTest()\n    {\n        updateNamed();\n        deleteNamed();\n\n    }\n\n    /**\n     * Update by Named Query.\n     * \n     * @return\n     */\n    private void updateNamed()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n\n        HBaseCompoundKey key = new HBaseCompoundKey(\"mevivs\", 1, timeLineId);\n        HBasePrimeUser user = new HBasePrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.close();\n\n        em = emf.createEntityManager();\n\n        String updateQuery = \"Update HBasePrimeUser u SET u.tweetBody= 'after merge' where u.tweetBody= :beforeUpdate\";\n        Query q = em.createQuery(updateQuery);\n        q.setParameter(\"beforeUpdate\", \"my first tweet\");\n        q.executeUpdate();\n        em.close();\n        em = emf.createEntityManager();\n\n        HBasePrimeUser result = em.find(HBasePrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"after merge\", result.getTweetBody());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n        em.close();\n    }\n\n    /**\n     * delete by Named Query.\n     */\n    private void deleteNamed()\n    {\n        UUID timeLineId = UUID.randomUUID();\n\n        HBaseCompoundKey key = new HBaseCompoundKey(\"mevivs\", 1, timeLineId);\n\n        String deleteQuery = \"Delete From HBasePrimeUser u where u.tweetBody= :tweetBody\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.setParameter(\"tweetBody\", \"after merge\");\n        q.executeUpdate();\n\n        em.close();\n        em = emf.createEntityManager();\n        HBasePrimeUser result = em.find(HBasePrimeUser.class, key);\n        Assert.assertNull(result);\n        em.close();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (cli != null)\n        {\n            cli.dropTable(\"KunderaExamples\");\n            cli.stopCluster(\"KunderaExamples\");\n        }\n        LuceneCleanupUtilities.cleanLuceneDirectory(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance()\n                .getApplicationMetadata().getPersistenceUnitMetadata(\"hbaseTest\"));\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/compositeType/HBaseCompoundKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.compositeType;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * @author vivek.mishra\n */\n@Embeddable\npublic class HBaseCompoundKey\n{\n    @Column\n    private String userId;\n\n    @Column\n    private int tweetId;\n\n    @Column\n    private UUID timeLineId;\n\n    /**\n     * \n     */\n    public HBaseCompoundKey()\n    {\n    }\n\n    /**\n     * @param userId\n     * @param tweetId\n     * @param timeLineId\n     */\n    public HBaseCompoundKey(String userId, int tweetId, UUID timeLineId)\n    {\n        this.userId = userId;\n        this.tweetId = tweetId;\n        this.timeLineId = timeLineId;\n    }\n\n    /**\n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * @return the tweetId\n     */\n    public int getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * @return the timeLineId\n     */\n    public UUID getTimeLineId()\n    {\n        return timeLineId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/compositeType/HBasePrimeUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.compositeType;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"User\", schema = \"KunderaExamples@hbaseTest\")\npublic class HBasePrimeUser\n{\n\n    @EmbeddedId\n    private HBaseCompoundKey key;\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private Date tweetDate;\n\n    public HBasePrimeUser()\n    {\n    }\n\n    public HBasePrimeUser(HBaseCompoundKey key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the key\n     */\n    public HBaseCompoundKey getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/Base.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport com.impetus.kundera.datatypes.datagenerator.DataGenerator;\nimport com.impetus.kundera.datatypes.datagenerator.DataGeneratorFactory;\n\npublic abstract class Base\n{\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\n\n    DataGenerator<?> dataGenerator;\n\n    DataGeneratorFactory factory = new DataGeneratorFactory();\n\n    protected Object getMaxValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.maxValue();\n    }\n\n    protected Object getMinValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.minValue();\n    }\n\n    protected Object getRandomValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.randomValue();\n    }\n\n    protected Object getPartialValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.partialValue();\n    }\n\n    protected abstract void startCluster();\n\n    protected abstract void stopCluster();\n\n    protected abstract void createSchema();\n\n    protected abstract void dropSchema();\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.io.IOException;\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.hadoop.hbase.MasterNotRunningException;\nimport org.apache.hadoop.hbase.ZooKeeperConnectionException;\n\nimport com.impetus.client.hbase.crud.BaseTest;\n\n/**\n * The Class StudentBase.\n * \n * @param <E>\n *            the element type\n */\npublic abstract class StudentBase<E extends StudentEntityDef> extends BaseTest\n{\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\n\n    /** The emf. */\n    protected EntityManagerFactory emf;\n\n    /** The em. */\n    protected EntityManager em;\n\n    // protected String persistenceUnit =\n    // /*\"twissandra,twibase,twingo,picmysql\"*/null;\n\n    /** The student id1. */\n    protected Object studentId1;\n\n    /** The student id2. */\n    protected Object studentId2;\n\n    /** The student id3. */\n    protected Object studentId3;\n\n    /** The enrolment date. */\n    protected Date enrolmentDate = new Date();\n\n    /** The joining date and time. */\n    protected Date joiningDateAndTime = new Date();\n\n    /** The date. */\n    protected long date = new Date().getTime();\n\n    /** The new sql date. */\n    protected java.sql.Date newSqlDate = new java.sql.Date(date);\n\n    /** The enrolment time. */\n    protected Date enrolmentTime = new Date();\n\n    /** The sql time. */\n    protected java.sql.Time sqlTime = new java.sql.Time(date);\n\n    /** The sql timestamp. */\n    protected java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(date);\n\n    /** The big decimal. */\n    protected BigDecimal bigDecimal = new BigDecimal(123456789);\n\n    /** The big integer. */\n    protected BigInteger bigInteger = new BigInteger(\"123456789\");\n\n    /** The number of students. */\n    protected int numberOfStudents = 1000;\n\n    /** The calendar. */\n    protected Calendar calendar = Calendar.getInstance();\n\n    /** The dao. */\n    // StudentDao dao;\n\n    /**\n     * Sets the up internal.\n     * \n     * @param persisntenceUnit\n     *            the new up internal\n     * @throws InterruptedException\n     */\n    protected void setupInternal(String persisntenceUnit) throws InterruptedException\n    {\n        // dao = new StudentDao(persistenceUnit);\n\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            // if (!HBaseCli.isStarted)\n            startServer();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n\n        studentId1 = new Long(12345677);\n        studentId2 = new Long(12345678);\n        studentId3 = new Long(12345679);\n\n        emf = Persistence.createEntityManagerFactory(persisntenceUnit);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Sets the up internal.\n     * \n     * @param persistenceUnit\n     *            the new up internal\n     * @throws InterruptedException\n     * @throws IOException\n     * @throws ZooKeeperConnectionException\n     * @throws MasterNotRunningException\n     */\n    protected void teardownInternal(String persistenceUnit) throws InterruptedException, MasterNotRunningException,\n            ZooKeeperConnectionException, IOException\n    {\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            deleteSchema();\n        }\n        if (em != null)\n        {\n            em.close();\n        }\n        if (emf != null)\n        {\n            emf.close();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            // if (HBaseCli.isStarted)\n            stopServer();\n        }\n    }\n\n    /**\n     * on insert.\n     * \n     * @param instance\n     *            the instance\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    protected void onInsert(E instance) throws InstantiationException, IllegalAccessException\n    {\n\n        em.persist(prepareData((Long) studentId1, 78575785897L, \"Amresh\", false, 10, 'A', (byte) 5, (short) 8,\n                (float) 61.6, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar,\n                ((E) instance.getClass().newInstance())));\n\n        em.persist(prepareData((Long) studentId2, 78575785898L, \"Amresh\", true, 20, 'B', (byte) 50, (short) 8,\n                (float) 63.6, 163.76765655, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar,\n                ((E) instance.getClass().newInstance())));\n\n        em.persist(prepareData((Long) studentId3, 78575785899L, \"Amresh\", true, 15, 'C', (byte) 50, (short) 8,\n                (float) 69.6, 163.76765656, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar,\n                ((E) instance.getClass().newInstance())));\n\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param studentId\n     *            the student id\n     * @param uniqueId\n     *            the unique id\n     * @param studentName\n     *            the student name\n     * @param isExceptional\n     *            the is exceptional\n     * @param age\n     *            the age\n     * @param semester\n     *            the semester\n     * @param digitalSignature\n     *            the digital signature\n     * @param cgpa\n     *            the cgpa\n     * @param percentage\n     *            the percentage\n     * @param height\n     *            the height\n     * @param enrolmentDate\n     *            the enrolment date\n     * @param enrolmentTime\n     *            the enrolment time\n     * @param joiningDateAndTime\n     *            the joining date and time\n     * @param yearsSpent\n     *            the years spent\n     * @param rollNumber\n     *            the roll number\n     * @param monthlyFee\n     *            the monthly fee\n     * @param newSqlDate\n     *            the new sql date\n     * @param sqlTime\n     *            the sql time\n     * @param sqlTimestamp\n     *            the sql timestamp\n     * @param bigDecimal\n     *            the big decimal\n     * @param bigInteger\n     *            the big integer\n     * @param calendar\n     *            the calendar\n     * @param o\n     *            the o\n     * @return the person\n     */\n    protected E prepareData(long studentId, long uniqueId, String studentName, boolean isExceptional, int age,\n            char semester, byte digitalSignature, short cgpa, float percentage, double height,\n            java.util.Date enrolmentDate, java.util.Date enrolmentTime, java.util.Date joiningDateAndTime,\n            Integer yearsSpent, Long rollNumber, Double monthlyFee, java.sql.Date newSqlDate, java.sql.Time sqlTime,\n            java.sql.Timestamp sqlTimestamp, BigDecimal bigDecimal, BigInteger bigInteger, Calendar calendar, E o)\n    {\n        o.setStudentId((Long) studentId);\n        o.setUniqueId(uniqueId);\n        o.setStudentName(studentName);\n        o.setExceptional(isExceptional);\n        o.setAge(age);\n        o.setSemester(semester);\n        o.setDigitalSignature(digitalSignature);\n        o.setCgpa(cgpa);\n        o.setPercentage(percentage);\n        o.setHeight(height);\n\n        o.setEnrolmentDate(enrolmentDate);\n        o.setEnrolmentTime(enrolmentTime);\n        o.setJoiningDateAndTime(joiningDateAndTime);\n\n        o.setYearsSpent(yearsSpent);\n        o.setRollNumber(rollNumber);\n        o.setMonthlyFee(monthlyFee);\n        o.setSqlDate(newSqlDate);\n        o.setSqlTime(sqlTime);\n        o.setSqlTimestamp(sqlTimestamp);\n        o.setBigDecimal(bigDecimal);\n        o.setBigInteger(bigInteger);\n        o.setCalendar(calendar);\n        return (E) o;\n    }\n\n    /**\n     * Assert on data types.\n     * \n     * @param s\n     *            the s\n     */\n    protected void assertOnDataTypes(E s)\n    {\n\n        Assert.assertNotNull(s);\n        Assert.assertEquals(((Long) studentId1).longValue(), s.getStudentId());\n        Assert.assertEquals(78575785897L, s.getUniqueId());\n        Assert.assertEquals(\"Amresh\", s.getStudentName());\n        Assert.assertEquals(false, s.isExceptional());\n        Assert.assertEquals(10, s.getAge());\n        Assert.assertEquals('A', s.getSemester());\n        Assert.assertEquals((byte) 5, s.getDigitalSignature());\n        Assert.assertEquals((short) 8, s.getCgpa());\n        Assert.assertEquals((float) 61.6, s.getPercentage());\n        Assert.assertEquals(163.76765654, s.getHeight());\n\n        Assert.assertEquals(enrolmentDate.getDate(), s.getEnrolmentDate().getDate());\n        Assert.assertEquals(enrolmentDate.getMonth(), s.getEnrolmentDate().getMonth());\n        Assert.assertEquals(enrolmentDate.getYear(), s.getEnrolmentDate().getYear());\n\n        Assert.assertEquals(enrolmentTime.getHours(), s.getEnrolmentTime().getHours());\n        Assert.assertEquals(enrolmentTime.getMinutes(), s.getEnrolmentTime().getMinutes());\n        Assert.assertEquals(enrolmentTime.getSeconds(), s.getEnrolmentTime().getSeconds());\n\n        Assert.assertEquals(joiningDateAndTime.getDate(), s.getJoiningDateAndTime().getDate());\n        Assert.assertEquals(joiningDateAndTime.getMonth(), s.getJoiningDateAndTime().getMonth());\n        Assert.assertEquals(joiningDateAndTime.getYear(), s.getJoiningDateAndTime().getYear());\n        Assert.assertEquals(joiningDateAndTime.getHours(), s.getJoiningDateAndTime().getHours());\n        Assert.assertEquals(joiningDateAndTime.getMinutes(), s.getJoiningDateAndTime().getMinutes());\n        Assert.assertEquals(joiningDateAndTime.getSeconds(), s.getJoiningDateAndTime().getSeconds());\n\n        Assert.assertEquals(newSqlDate.getDate(), s.getSqlDate().getDate());\n        Assert.assertEquals(newSqlDate.getMonth(), s.getSqlDate().getMonth());\n        Assert.assertEquals(newSqlDate.getYear(), s.getSqlDate().getYear());\n\n        Assert.assertEquals(sqlTime.getMinutes(), s.getSqlTime().getMinutes());\n        Assert.assertEquals(sqlTime.getSeconds(), s.getSqlTime().getSeconds());\n        Assert.assertEquals(sqlTime.getHours(), s.getSqlTime().getHours());\n\n        Assert.assertEquals(sqlTimestamp.getDate(), s.getSqlTimestamp().getDate());\n        Assert.assertEquals(sqlTimestamp.getMonth(), s.getSqlTimestamp().getMonth());\n        Assert.assertEquals(sqlTimestamp.getYear(), s.getSqlTimestamp().getYear());\n        Assert.assertEquals(sqlTimestamp.getHours(), s.getSqlTimestamp().getHours());\n        Assert.assertEquals(sqlTimestamp.getMinutes(), s.getSqlTimestamp().getMinutes());\n        Assert.assertEquals(sqlTimestamp.getSeconds(), s.getSqlTimestamp().getSeconds());\n\n        Assert.assertEquals(Math.round(bigDecimal.doubleValue()), Math.round(s.getBigDecimal().doubleValue()));\n        Assert.assertEquals(bigInteger, s.getBigInteger());\n\n        Assert.assertEquals(calendar.get(Calendar.YEAR), s.getCalendar().get(Calendar.YEAR));\n        Assert.assertEquals(calendar.get(Calendar.MONTH), s.getCalendar().get(Calendar.MONTH));\n        Assert.assertEquals(calendar.get(Calendar.WEEK_OF_YEAR), s.getCalendar().get(Calendar.WEEK_OF_YEAR));\n        Assert.assertEquals(calendar.get(Calendar.WEEK_OF_MONTH), s.getCalendar().get(Calendar.WEEK_OF_MONTH));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_MONTH), s.getCalendar().get(Calendar.DAY_OF_MONTH));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_WEEK), s.getCalendar().get(Calendar.DAY_OF_WEEK));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH),\n                s.getCalendar().get(Calendar.DAY_OF_WEEK_IN_MONTH));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_YEAR), s.getCalendar().get(Calendar.DAY_OF_YEAR));\n        Assert.assertEquals(calendar.get(Calendar.HOUR), s.getCalendar().get(Calendar.HOUR));\n        Assert.assertEquals(calendar.get(Calendar.HOUR_OF_DAY), s.getCalendar().get(Calendar.HOUR_OF_DAY));\n        Assert.assertEquals(calendar.get(Calendar.AM), s.getCalendar().get(Calendar.AM));\n        Assert.assertEquals(calendar.get(Calendar.PM), s.getCalendar().get(Calendar.PM));\n        Assert.assertEquals(calendar.get(Calendar.AM_PM), s.getCalendar().get(Calendar.AM_PM));\n\n        Assert.assertEquals(new Integer(3), s.getYearsSpent());\n        Assert.assertEquals(new Long(978423946455l), s.getRollNumber());\n        Assert.assertEquals(new Double(135434.89), s.getMonthlyFee());\n\n    }\n\n    abstract void startServer() throws InterruptedException;\n\n    abstract void stopServer() throws InterruptedException, MasterNotRunningException, ZooKeeperConnectionException,\n            IOException;\n\n    abstract void createSchema();\n\n    abstract void deleteSchema();\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentEntityDef.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\n\n/**\n * @author vivek.mishra\n * \n */\npublic interface StudentEntityDef\n{\n\n    /**\n     * @return the studentId\n     */\n    long getStudentId();\n\n    /**\n     * @param studentId\n     *            the studentId to set\n     */\n    void setStudentId(long studentId);\n\n    /**\n     * @return the uniqueId\n     */\n    long getUniqueId();\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    void setUniqueId(long uniqueId);\n\n    /**\n     * @return the studentName\n     */\n    String getStudentName();\n\n    /**\n     * @param studentName\n     *            the studentName to set\n     */\n    void setStudentName(String studentName);\n\n    /**\n     * @return the isExceptional\n     */\n    boolean isExceptional();\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    void setExceptional(boolean isExceptional);\n\n    /**\n     * @return the age\n     */\n    int getAge();\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    void setAge(int age);\n\n    /**\n     * @return the semester\n     */\n    char getSemester();\n\n    /**\n     * @param semester\n     *            the semester to set\n     */\n    void setSemester(char semester);\n\n    /**\n     * @return the digitalSignature\n     */\n    byte getDigitalSignature();\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    void setDigitalSignature(byte digitalSignature);\n\n    /**\n     * @return the cgpa\n     */\n    short getCgpa();\n\n    /**\n     * @param cgpa\n     *            the cgpa to set\n     */\n    void setCgpa(short cgpa);\n\n    /**\n     * @return the percentage\n     */\n    float getPercentage();\n\n    /**\n     * @param percentage\n     *            the percentage to set\n     */\n    void setPercentage(float percentage);\n\n    /**\n     * @return the height\n     */\n    double getHeight();\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    void setHeight(double height);\n\n    /**\n     * @return the enrolmentDate\n     */\n    java.util.Date getEnrolmentDate();\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    void setEnrolmentDate(java.util.Date enrolmentDate);\n\n    /**\n     * @return the enrolmentTime\n     */\n    java.util.Date getEnrolmentTime();\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    void setEnrolmentTime(java.util.Date enrolmentTime);\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    java.util.Date getJoiningDateAndTime();\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    void setJoiningDateAndTime(java.util.Date joiningDateAndTime);\n\n    /**\n     * @return the yearsSpent\n     */\n    Integer getYearsSpent();\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    void setYearsSpent(Integer yearsSpent);\n\n    /**\n     * @return the rollNumber\n     */\n    Long getRollNumber();\n\n    /**\n     * @param rollNumber\n     *            the rollNumber to set\n     */\n    void setRollNumber(Long rollNumber);\n\n    /**\n     * @return the monthlyFee\n     */\n    Double getMonthlyFee();\n\n    /**\n     * @param monthlyFee\n     *            the monthlyFee to set\n     */\n    void setMonthlyFee(Double monthlyFee);\n\n    java.sql.Date getSqlDate();\n\n    void setSqlDate(java.sql.Date sqlDate);\n\n    /**\n     * @return the sqlTimestamp\n     */\n    java.sql.Timestamp getSqlTimestamp();\n\n    /**\n     * @param sqlTimestamp\n     *            the sqlTimestamp to set\n     */\n    void setSqlTimestamp(java.sql.Timestamp sqlTimestamp);\n\n    /**\n     * @return the sqlTime\n     */\n    java.sql.Time getSqlTime();\n\n    /**\n     * @param sqlTime\n     *            the sqlTime to set\n     */\n    void setSqlTime(java.sql.Time sqlTime);\n\n    /**\n     * @return the bigInteger\n     */\n    BigInteger getBigInteger();\n\n    /**\n     * @param bigInteger\n     *            the bigInteger to set\n     */\n    void setBigInteger(BigInteger bigInteger);\n\n    /**\n     * @return the bigDecimal\n     */\n    BigDecimal getBigDecimal();\n\n    /**\n     * @param bigDecimal\n     *            the bigDecimal to set\n     */\n    void setBigDecimal(BigDecimal bigDecimal);\n\n    /**\n     * @return the calendar\n     */\n    Calendar getCalendar();\n\n    /**\n     * @param calendar\n     *            the calendar to set\n     */\n    void setCalendar(Calendar calendar);\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\n@Entity\n@Table(name = \"STUDENT\", schema = \"KunderaExamples@hbaseTest\")\npublic class StudentHBase implements StudentEntityDef\n{\n    // Primitive Types\n    @Id\n    @Column(name = \"STUDENT_ID\")\n    private long studentId;\n\n    @Column(name = \"UNIQUE_ID\")\n    private long uniqueId;\n\n    @Column(name = \"STUDENT_NAME\")\n    private String studentName;\n\n    @Column(name = \"IS_EXCEPTIONAL\")\n    private boolean isExceptional;\n\n    @Column(name = \"AGE\")\n    private int age;\n\n    @Column(name = \"SEMESTER\")\n    private char semester; // A,B,C,D,E,F for i to vi\n\n    @Column(name = \"DIGITAL_SIGNATURE\")\n    private byte digitalSignature;\n\n    @Column(name = \"CGPA\")\n    private short cgpa; // 1-10\n\n    @Column(name = \"PERCENTAGE\")\n    private float percentage;\n\n    @Column(name = \"HEIGHT\")\n    private double height;\n\n    // Date-time types\n    @Column(name = \"ENROLMENT_DATE\")\n    @Temporal(TemporalType.DATE)\n    private java.util.Date enrolmentDate;\n\n    @Column(name = \"ENROLMENT_TIME\")\n    @Temporal(TemporalType.TIME)\n    private java.util.Date enrolmentTime;\n\n    @Column(name = \"JOINING_DATE_TIME\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private java.util.Date joiningDateAndTime;\n\n    // Wrapper types\n\n    @Column(name = \"YEARS_SPENT\")\n    private Integer yearsSpent;\n\n    @Column(name = \"ROLL_NUMBER\")\n    private Long rollNumber;\n\n    @Column(name = \"MONTHLY_FEE\")\n    private Double monthlyFee;\n\n    @Column(name = \"SQL_DATE\")\n    private java.sql.Date sqlDate;\n\n    @Column(name = \"SQL_TIMESTAMP\")\n    private java.sql.Timestamp sqlTimestamp;\n\n    @Column(name = \"SQL_TIME\")\n    private java.sql.Time sqlTime;\n\n    @Column(name = \"BIG_INT\")\n    private BigInteger bigInteger;\n\n    @Column(name = \"BIG_DECIMAL\")\n    private BigDecimal bigDecimal;\n\n    @Column(name = \"CALENDAR\")\n    private Calendar calendar;\n\n    /**\n     * @return the studentId\n     */\n    public long getStudentId()\n    {\n        return studentId;\n    }\n\n    /**\n     * @param studentId\n     *            the studentId to set\n     */\n    public void setStudentId(long studentId)\n    {\n        this.studentId = studentId;\n    }\n\n    /**\n     * @return the uniqueId\n     */\n    public long getUniqueId()\n    {\n        return uniqueId;\n    }\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    public void setUniqueId(long uniqueId)\n    {\n        this.uniqueId = uniqueId;\n    }\n\n    /**\n     * @return the studentName\n     */\n    public String getStudentName()\n    {\n        return studentName;\n    }\n\n    /**\n     * @param studentName\n     *            the studentName to set\n     */\n    public void setStudentName(String studentName)\n    {\n        this.studentName = studentName;\n    }\n\n    /**\n     * @return the isExceptional\n     */\n    public boolean isExceptional()\n    {\n        return isExceptional;\n    }\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    public void setExceptional(boolean isExceptional)\n    {\n        this.isExceptional = isExceptional;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the semester\n     */\n    public char getSemester()\n    {\n        return semester;\n    }\n\n    /**\n     * @param semester\n     *            the semester to set\n     */\n    public void setSemester(char semester)\n    {\n        this.semester = semester;\n    }\n\n    /**\n     * @return the digitalSignature\n     */\n    public byte getDigitalSignature()\n    {\n        return digitalSignature;\n    }\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    public void setDigitalSignature(byte digitalSignature)\n    {\n        this.digitalSignature = digitalSignature;\n    }\n\n    /**\n     * @return the cgpa\n     */\n    public short getCgpa()\n    {\n        return cgpa;\n    }\n\n    /**\n     * @param cgpa\n     *            the cgpa to set\n     */\n    public void setCgpa(short cgpa)\n    {\n        this.cgpa = cgpa;\n    }\n\n    /**\n     * @return the percentage\n     */\n    public float getPercentage()\n    {\n        return percentage;\n    }\n\n    /**\n     * @param percentage\n     *            the percentage to set\n     */\n    public void setPercentage(float percentage)\n    {\n        this.percentage = percentage;\n    }\n\n    /**\n     * @return the height\n     */\n    public double getHeight()\n    {\n        return height;\n    }\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    public void setHeight(double height)\n    {\n        this.height = height;\n    }\n\n    /**\n     * @return the enrolmentDate\n     */\n    public java.util.Date getEnrolmentDate()\n    {\n        return enrolmentDate;\n    }\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    public void setEnrolmentDate(java.util.Date enrolmentDate)\n    {\n        this.enrolmentDate = enrolmentDate;\n    }\n\n    /**\n     * @return the enrolmentTime\n     */\n    public java.util.Date getEnrolmentTime()\n    {\n        return enrolmentTime;\n    }\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    public void setEnrolmentTime(java.util.Date enrolmentTime)\n    {\n        this.enrolmentTime = enrolmentTime;\n    }\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    public java.util.Date getJoiningDateAndTime()\n    {\n        return joiningDateAndTime;\n    }\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    public void setJoiningDateAndTime(java.util.Date joiningDateAndTime)\n    {\n        this.joiningDateAndTime = joiningDateAndTime;\n    }\n\n    /**\n     * @return the yearsSpent\n     */\n    public Integer getYearsSpent()\n    {\n        return yearsSpent;\n    }\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    public void setYearsSpent(Integer yearsSpent)\n    {\n        this.yearsSpent = yearsSpent;\n    }\n\n    /**\n     * @return the rollNumber\n     */\n    public Long getRollNumber()\n    {\n        return rollNumber;\n    }\n\n    /**\n     * @param rollNumber\n     *            the rollNumber to set\n     */\n    public void setRollNumber(Long rollNumber)\n    {\n        this.rollNumber = rollNumber;\n    }\n\n    /**\n     * @return the monthlyFee\n     */\n    public Double getMonthlyFee()\n    {\n        return monthlyFee;\n    }\n\n    /**\n     * @param monthlyFee\n     *            the monthlyFee to set\n     */\n    public void setMonthlyFee(Double monthlyFee)\n    {\n        this.monthlyFee = monthlyFee;\n    }\n\n    public java.sql.Date getSqlDate()\n    {\n        return sqlDate;\n    }\n\n    public void setSqlDate(java.sql.Date sqlDate)\n    {\n        this.sqlDate = sqlDate;\n    }\n\n    /**\n     * @return the sqlTimestamp\n     */\n    public java.sql.Timestamp getSqlTimestamp()\n    {\n        return sqlTimestamp;\n    }\n\n    /**\n     * @param sqlTimestamp\n     *            the sqlTimestamp to set\n     */\n    public void setSqlTimestamp(java.sql.Timestamp sqlTimestamp)\n    {\n        this.sqlTimestamp = sqlTimestamp;\n    }\n\n    /**\n     * @return the sqlTime\n     */\n    public java.sql.Time getSqlTime()\n    {\n        return sqlTime;\n    }\n\n    /**\n     * @param sqlTime\n     *            the sqlTime to set\n     */\n    public void setSqlTime(java.sql.Time sqlTime)\n    {\n        this.sqlTime = sqlTime;\n    }\n\n    /**\n     * @return the bigInteger\n     */\n    public BigInteger getBigInteger()\n    {\n        return bigInteger;\n    }\n\n    /**\n     * @param bigInteger\n     *            the bigInteger to set\n     */\n    public void setBigInteger(BigInteger bigInteger)\n    {\n        this.bigInteger = bigInteger;\n    }\n\n    /**\n     * @return the bigDecimal\n     */\n    public BigDecimal getBigDecimal()\n    {\n        return bigDecimal;\n    }\n\n    /**\n     * @param bigDecimal\n     *            the bigDecimal to set\n     */\n    public void setBigDecimal(BigDecimal bigDecimal)\n    {\n        this.bigDecimal = bigDecimal;\n    }\n\n    /**\n     * @return the calendar\n     */\n    public Calendar getCalendar()\n    {\n        return calendar;\n    }\n\n    /**\n     * @param calendar\n     *            the calendar to set\n     */\n    public void setCalendar(Calendar calendar)\n    {\n        this.calendar = calendar;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseBigDecimalTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBigDecimal;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseBigDecimalTest extends Base\n{\n    private static final String table = \"StudentHBaseBigDecimal\";\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private HBaseCli cli;\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of BigDecimal\n        StudentHBaseBigDecimal studentMax = new StudentHBaseBigDecimal();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((BigDecimal) getMaxValue(BigDecimal.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of BigDecimal\n        StudentHBaseBigDecimal studentMin = new StudentHBaseBigDecimal();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((BigDecimal) getMinValue(BigDecimal.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of BigDecimal\n        StudentHBaseBigDecimal student = new StudentHBaseBigDecimal();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((BigDecimal) getRandomValue(BigDecimal.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBigDecimal studentMax = em.find(StudentHBaseBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigDecimal studentMin = em.find(StudentHBaseBigDecimal.class, getMinValue(BigDecimal.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigDecimal student = em.find(StudentHBaseBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseBigDecimal student = em.find(StudentHBaseBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigDecimal newStudent = em.find(StudentHBaseBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            Assert.assertEquals(getMinValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.id between \" + getMinValue(BigDecimal.class) + \" and \"\n                + getMaxValue(BigDecimal.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            if (student.getId().equals(getRandomValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBigDecimal studentMax = em.find(StudentHBaseBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseBigDecimal s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigDecimal newStudent = em.find(StudentHBaseBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseBigDecimal s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigDecimal newStudent = em.find(StudentHBaseBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.name = Amresh and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.name = Kuldeep and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigDecimal.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigDecimal.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseBigDecimal s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseBigDecimal> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseBigIntegerTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.math.BigInteger;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBigInteger;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseBigIntegerTest extends Base\n{\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseBigInteger\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of BigInteger\n        StudentHBaseBigInteger studentMax = new StudentHBaseBigInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((BigInteger) getMaxValue(BigInteger.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of BigInteger\n        StudentHBaseBigInteger studentMin = new StudentHBaseBigInteger();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((BigInteger) getMinValue(BigInteger.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of BigInteger\n        StudentHBaseBigInteger student = new StudentHBaseBigInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((BigInteger) getRandomValue(BigInteger.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBigInteger studentMax = em.find(StudentHBaseBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigInteger studentMin = em.find(StudentHBaseBigInteger.class, getMinValue(BigInteger.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigInteger student = em.find(StudentHBaseBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseBigInteger student = em.find(StudentHBaseBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigInteger newStudent = em.find(StudentHBaseBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.id between \" + getMinValue(BigInteger.class) + \" and \"\n                + getRandomValue(BigInteger.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBigInteger studentMax = em.find(StudentHBaseBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseBigInteger s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigInteger newStudent = em.find(StudentHBaseBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseBigInteger s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigInteger newStudent = em.find(StudentHBaseBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.name = Amresh and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.name = Kuldeep and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseBigInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseBigInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseBooleanPrimitiveTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBooleanPrimitive;\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class StudentHBaseBooleanPrimitiveTest extends Base\n{\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseBooleanPrimitive\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of boolean\n        StudentHBaseBooleanPrimitive studentMax = new StudentHBaseBooleanPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Boolean) getMaxValue(boolean.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of boolean\n        StudentHBaseBooleanPrimitive studentMin = new StudentHBaseBooleanPrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Boolean) getMinValue(boolean.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBooleanPrimitive studentMax = em.find(StudentHBaseBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanPrimitive studentMin = em.find(StudentHBaseBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseBooleanPrimitive student = em.find(StudentHBaseBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanPrimitive newStudent = em.find(StudentHBaseBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(boolean.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(boolean.class));\n        q.setParameter(2, getMaxValue(boolean.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        int count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            // if (student.getId() == ((Boolean)\n            // getMaxValue(boolean.class)).booleanValue())\n            // {\n            // Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            // Assert.assertEquals(\"Kuldeep\", student.getName());\n            // count++;\n            // }\n            // else if (student.getId() == ((Boolean)\n            // getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.name = John or s.age > \" + getPartialValue(short.class);\n        try\n        {\n            q = em.createQuery(query);\n            students = q.getResultList();\n          //  Assert.fail(\"Should have gone to catch block\");\n            Assert.assertNotNull(students);\n            Assert.assertEquals(1, students.size());\n            count = 0;\n            for (StudentHBaseBooleanPrimitive student : students)\n            {\n                Assert.assertEquals(getMaxValue(boolean.class), student.getId());\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n            em.close();\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertNotNull(qhe.getMessage());\n        }\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(boolean.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBooleanPrimitive studentMax = em.find(StudentHBaseBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getPartialValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseBooleanPrimitive s where s.id=true\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanPrimitive newStudent = em.find(StudentHBaseBooleanPrimitive.class, getRandomValue(boolean.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseBooleanPrimitive s SET s.name=Vivek where s.id=true\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanPrimitive newStudent = em.find(StudentHBaseBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.name = Kuldeep and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.name = Kuldeep and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(boolean.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.age = \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(boolean.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(boolean.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseBooleanPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseBooleanPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseBooleanWrapperTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBooleanWrapper;\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class StudentHBaseBooleanWrapperTest extends Base\n{\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseBooleanWrapper\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Boolean\n        StudentHBaseBooleanWrapper studentMax = new StudentHBaseBooleanWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Boolean) getMaxValue(Boolean.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Boolean\n        StudentHBaseBooleanWrapper studentMin = new StudentHBaseBooleanWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Boolean) getMinValue(Boolean.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBooleanWrapper studentMax = em.find(StudentHBaseBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanWrapper studentMin = em.find(StudentHBaseBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        em.close();\n    }\n\n    public void testMerge(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseBooleanWrapper student = em.find(StudentHBaseBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanWrapper newStudent = em.find(StudentHBaseBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(Boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Boolean.class));\n        q.setParameter(2, getMaxValue(Boolean.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        int count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {/*\n          * if (student.getId().equals(getMaxValue(Boolean.class))) {\n          * Assert.assertEquals(getMaxValue(short.class), student.getAge());\n          * Assert.assertEquals(\"Kuldeep\", student.getName()); count++; } else\n          */\n            if (student.getId().equals(getMinValue(Boolean.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.name = Chhavi or s.age > \"\n                + getPartialValue(short.class);\n        try\n        {\n            q = em.createQuery(query);\n            students = q.getResultList();\n            //Assert.fail(\"Should have gone to catch block\");\n            Assert.assertNotNull(students);\n            Assert.assertEquals(1, students.size());\n            count = 0;\n            for (StudentHBaseBooleanWrapper student : students)\n            {\n                Assert.assertEquals(getMaxValue(Boolean.class), student.getId());\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n            em.close();\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertNotNull(qhe.getMessage());\n        }\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(Boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(Boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBooleanWrapper studentMax = em.find(StudentHBaseBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getPartialValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(Boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseBooleanWrapper s where s.id=true\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanWrapper newStudent = em.find(StudentHBaseBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseBooleanWrapper s SET s.name=Vivek where s.id=true\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanWrapper newStudent = em.find(StudentHBaseBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.name = Kuldeep and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(Boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(Boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.name = Amresh and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.name = Kuldeep and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.age = \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseBooleanWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseBooleanWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Boolean.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseBytePrimitiveTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBytePrimitive;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseBytePrimitiveTest extends Base\n{\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseBytePrimitive\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of byte\n        StudentHBaseBytePrimitive studentMax = new StudentHBaseBytePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of byte\n        StudentHBaseBytePrimitive studentMin = new StudentHBaseBytePrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Byte) getMinValue(byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of byte\n        StudentHBaseBytePrimitive student = new StudentHBaseBytePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBytePrimitive studentMax = em.find(StudentHBaseBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBytePrimitive studentMin = em.find(StudentHBaseBytePrimitive.class, getMinValue(byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBytePrimitive student = em.find(StudentHBaseBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseBytePrimitive student = em.find(StudentHBaseBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBytePrimitive newStudent = em.find(StudentHBaseBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(byte.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.id between \" + getRandomValue(byte.class) + \" and \"\n                + getMinValue(byte.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            // else if (student.getId() == ((Byte)\n            // getMinValue(byte.class)).byteValue())\n            // {\n            // Assert.assertEquals(getPartialValue(short.class),\n            // student.getAge());\n            // Assert.assertEquals(getMinValue(String.class),\n            // student.getName());\n            // count++;\n            // }\n            else\n            {\n                Assert.assertEquals(getRandomValue(byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBytePrimitive studentMax = em.find(StudentHBaseBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseBytePrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBytePrimitive newStudent = em.find(StudentHBaseBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseBytePrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBytePrimitive newStudent = em.find(StudentHBaseBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.name = Kuldeep and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseBytePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseBytePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Byte) getMinValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseByteWrapperTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseByteWrapper;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseByteWrapperTest extends Base\n{\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseByteWrapper\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Byte\n        StudentHBaseByteWrapper studentMax = new StudentHBaseByteWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(Byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Byte\n        StudentHBaseByteWrapper studentMin = new StudentHBaseByteWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Byte) getMinValue(Byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Byte\n        StudentHBaseByteWrapper student = new StudentHBaseByteWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(Byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseByteWrapper studentMax = em.find(StudentHBaseByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseByteWrapper studentMin = em.find(StudentHBaseByteWrapper.class, getMinValue(Byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseByteWrapper student = em.find(StudentHBaseByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseByteWrapper student = em.find(StudentHBaseByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseByteWrapper newStudent = em.find(StudentHBaseByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Byte.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.id between \" + getRandomValue(Byte.class) + \" and \"\n                + getMinValue(Byte.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            // else if (student.getId().equals(getMinValue(Byte.class)))\n            // {\n            // Assert.assertEquals(getPartialValue(short.class),\n            // student.getAge());\n            // Assert.assertEquals(getMinValue(String.class),\n            // student.getName());\n            // count++;\n            // }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseByteWrapper studentMax = em.find(StudentHBaseByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseByteWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseByteWrapper newStudent = em.find(StudentHBaseByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseByteWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseByteWrapper newStudent = em.find(StudentHBaseByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.name = Kuldeep and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseByteWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseByteWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Byte.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseCalendarTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.Calendar;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseCalendar;\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class StudentHBaseCalendarTest extends Base\n{\n\n    private static final String table = \"StudentHBaseCalendar\";\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n    \n    private EntityManagerFactory emf;\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Calendar\n        StudentHBaseCalendar studentMax = new StudentHBaseCalendar();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId(((Calendar) getMaxValue(Calendar.class)));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseCalendar studentMax = em.find(StudentHBaseCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseCalendar student = em.find(StudentHBaseCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCalendar newStudent = em.find(StudentHBaseCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.age = \" + getMaxValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCalendar student : students)\n        {\n            Assert.assertEquals(getMaxValue(Calendar.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.id between \" + getRandomValue(Calendar.class) + \" and \"\n                + getMaxValue(Calendar.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseCalendar student : students)\n        {\n            if (student.getId().equals(getRandomValue(Calendar.class)))\n            {\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Calendar.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em = null;\n        String query;\n        Query q;\n        try\n        {\n            List<StudentHBaseCalendar> students;\n            int count;\n            em = emf.createEntityManager();\n            query = \"Select s From StudentHBaseCalendar s where s.name = Kuldeep and s.age > \"\n                    + getPartialValue(short.class);\n            q = em.createQuery(query);\n            students = q.getResultList();\n            Assert.assertNotNull(students);\n            Assert.assertEquals(1, students.size());\n            count = 0;\n            for (StudentHBaseCalendar student : students)\n            {\n                Assert.assertEquals(getMaxValue(Calendar.class), student.getId());\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertEquals(\"unsupported clause OR for Hbase\", qhe.getMessage());\n        }\n        finally\n        {\n            if (em != null)\n            {\n                em.close();\n            }\n        }\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCalendar student : students)\n        {\n            Assert.assertEquals(getMaxValue(Calendar.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Calendar\n        StudentHBaseCalendar studentMax = new StudentHBaseCalendar();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId(((Calendar) getMaxValue(Calendar.class)));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        em.close();\n\n        em = emf.createEntityManager();\n\n        studentMax = em.find(StudentHBaseCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseCalendar s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCalendar newStudent = em.find(StudentHBaseCalendar.class, getRandomValue(Calendar.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseCalendar s SET s.name=Vivek where s.name=Kuldeep\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCalendar newStudent = em.find(StudentHBaseCalendar.class, getRandomValue(Calendar.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.name = Kuldeep and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCalendar student : students)\n        {\n            if (student.getId().equals(getMaxValue(Calendar.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.age = \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCalendar student : students)\n        {\n            Assert.assertEquals(getMaxValue(Calendar.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCalendar student : students)\n        {\n            if (student.getId().equals(getMaxValue(Calendar.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseCalendar s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseCalendar> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        int count = 0;\n        for (StudentHBaseCalendar student : students)\n        {\n            if (student.getId().equals(getMaxValue(Calendar.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseCharTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseChar;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseCharTest extends Base\n{\n    private static final String table = \"StudentHBaseChar\";\n\n    private HBaseCli cli;\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of char\n        StudentHBaseChar studentMax = new StudentHBaseChar();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Character) getMaxValue(char.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of char\n        StudentHBaseChar studentMin = new StudentHBaseChar();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Character) getMinValue(char.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of char\n        StudentHBaseChar student = new StudentHBaseChar();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(char.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseChar studentMax = em.find(StudentHBaseChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseChar studentMin = em.find(StudentHBaseChar.class, getMinValue(char.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseChar student = em.find(StudentHBaseChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseChar student = em.find(StudentHBaseChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseChar newStudent = em.find(StudentHBaseChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            Assert.assertEquals(getMinValue(char.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.id between ?1 and ?2\";\n        /*+ getMinValue(char.class) + \" and \"\n                + getMaxValue(char.class);*/\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(char.class));\n        q.setParameter(2, getMaxValue(char.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            /*\n             * if (student.getId() == ((Character)\n             * getMaxValue(char.class)).charValue()) {\n             * Assert.assertEquals(getMaxValue(short.class), student.getAge());\n             * Assert.assertEquals(\"Kuldeep\", student.getName()); count++; }\n             * else\n             */if (student.getId() == ((Character) getMinValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(char.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseChar studentMax = em.find(StudentHBaseChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseChar.class, getMaxValue(char.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseChar s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseChar newStudent = em.find(StudentHBaseChar.class, getRandomValue(char.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseChar s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseChar newStudent = em.find(StudentHBaseChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.name = Kuldeep and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseChar s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseChar> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Character) getMinValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(char.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseCharacterTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseCharacter;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseCharacterTest extends Base\n{\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseCharacter\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Character\n        StudentHBaseCharacter studentMax = new StudentHBaseCharacter();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Character) getMaxValue(Character.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Character\n        StudentHBaseCharacter studentMin = new StudentHBaseCharacter();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Character) getMinValue(Character.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Character\n        StudentHBaseCharacter student = new StudentHBaseCharacter();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(Character.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseCharacter studentMax = em.find(StudentHBaseCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCharacter studentMin = em.find(StudentHBaseCharacter.class, getMinValue(Character.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCharacter student = em.find(StudentHBaseCharacter.class, getRandomValue(Character.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseCharacter student = em.find(StudentHBaseCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCharacter newStudent = em.find(StudentHBaseCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            Assert.assertEquals(getMinValue(Character.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        em = emf.createEntityManager();\n//        query = \"Select s From StudentHBaseCharacter s where s.id between \" + getMinValue(Character.class) + \" and \"\n//                + getMaxValue(Character.class);\n//        \n        query = \"Select s From StudentHBaseCharacter s where s.id between ?1 and ?2\";\n        /*+ getMinValue(char.class) + \" and \"\n                + getMaxValue(char.class);*/\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Character.class));\n        q.setParameter(2, getMaxValue(Character.class));\n        students = q.getResultList();\n\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            // if (student.getId().equals(getMaxValue(Character.class)))\n            // {\n            // Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            // Assert.assertEquals(\"Kuldeep\", student.getName());\n            // count++;\n            // }\n            // else\n            if (student.getId().equals(getMinValue(Character.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            Assert.assertEquals(getMaxValue(Character.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            Assert.assertEquals(getMaxValue(Character.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseCharacter studentMax = em.find(StudentHBaseCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseCharacter.class, getMaxValue(Character.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseCharacter s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCharacter newStudent = em.find(StudentHBaseCharacter.class, getRandomValue(Character.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseCharacter s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCharacter newStudent = em.find(StudentHBaseCharacter.class, getRandomValue(Character.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.name = Amresh and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.name = Kuldeep and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseCharacter s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseCharacter> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Character.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseDateTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseDate;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseDateTest extends Base\n{\n    private static final String table = \"StudentHBaseDate\";\n\n    private HBaseCli cli;\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentHBaseDate student = new StudentHBaseDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue(Date.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Date\n        StudentHBaseDate studentMax = new StudentHBaseDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue(Date.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Date\n        StudentHBaseDate studentMin = new StudentHBaseDate();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Date) getMinValue(Date.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseDate studentMax = em.find(StudentHBaseDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDate studentMin = em.find(StudentHBaseDate.class, getMinValue(Date.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDate student = em.find(StudentHBaseDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseDate student = em.find(StudentHBaseDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDate newStudent = em.find(StudentHBaseDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            Assert.assertEquals(getMinValue(Date.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.id between '\" + getMinValue(Date.class) + \"' and '\"\n                + getMaxValue(Date.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            /*\n             * if (student.getId().equals(getMaxValue(Date.class))) {\n             * Assert.assertEquals(getMaxValue(short.class), student.getAge());\n             * Assert.assertEquals(\"Kuldeep\", student.getName()); count++; }\n             * else\n             */if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Date.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseDate studentMax = em.find(StudentHBaseDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseDate.class, getMaxValue(Date.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseDate s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDate newStudent = em.find(StudentHBaseDate.class, getRandomValue(Date.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseDate s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDate newStudent = em.find(StudentHBaseDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.name = Kuldeep and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseDate s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue(Date.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseDoublePrimitiveTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseDoublePrimitive;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseDoublePrimitiveTest extends Base\n{\n    private static final String table = \"StudentHBaseDoublePrimitive\";\n\n    private HBaseCli cli;\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Double\n        StudentHBaseDoublePrimitive studentMax = new StudentHBaseDoublePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) getMaxValue(Double.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Double\n        StudentHBaseDoublePrimitive studentMin = new StudentHBaseDoublePrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Double) getMinValue(Double.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Double\n        StudentHBaseDoublePrimitive student = new StudentHBaseDoublePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseDoublePrimitive studentMax = em.find(StudentHBaseDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoublePrimitive studentMin = em.find(StudentHBaseDoublePrimitive.class, getMinValue(Double.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoublePrimitive student = em.find(StudentHBaseDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseDoublePrimitive student = em.find(StudentHBaseDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoublePrimitive newStudent = em.find(StudentHBaseDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(Double.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(double.class));\n        q.setParameter(2, getMaxValue(double.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            /*\n             * if (student.getId() == ((Double)\n             * getMaxValue(Double.class)).doubleValue()) {\n             * Assert.assertEquals(getMaxValue(short.class), student.getAge());\n             * Assert.assertEquals(\"Kuldeep\", student.getName()); count++; }\n             * else\n             */if (student.getId() == ((Double) getMinValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseDoublePrimitive studentMax = em.find(StudentHBaseDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseDoublePrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoublePrimitive newStudent = em.find(StudentHBaseDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseDoublePrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoublePrimitive newStudent = em.find(StudentHBaseDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.name = Kuldeep and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseDoublePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseDoublePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Double) getMinValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseDoubleWrapperTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseDoubleWrapper;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseDoubleWrapperTest extends Base\n{\n    private static final String table = \"StudentHBaseDoubleWrapper\";\n\n    private HBaseCli cli;\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Double\n        StudentHBaseDoubleWrapper studentMax = new StudentHBaseDoubleWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) getMaxValue(Double.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Double\n        StudentHBaseDoubleWrapper studentMin = new StudentHBaseDoubleWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Double) getMinValue(Double.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Double\n        StudentHBaseDoubleWrapper student = new StudentHBaseDoubleWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseDoubleWrapper studentMax = em.find(StudentHBaseDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoubleWrapper studentMin = em.find(StudentHBaseDoubleWrapper.class, getMinValue(Double.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoubleWrapper student = em.find(StudentHBaseDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseDoubleWrapper student = em.find(StudentHBaseDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoubleWrapper newStudent = em.find(StudentHBaseDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Double.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Double.class));\n        q.setParameter(2, getMaxValue(Double.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            /*\n             * if (student.getId().equals(getMaxValue(Double.class))) {\n             * Assert.assertEquals(getMaxValue(short.class), student.getAge());\n             * Assert.assertEquals(\"Kuldeep\", student.getName()); count++; }\n             * else\n             */if (student.getId().equals(getMinValue(Double.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseDoubleWrapper studentMax = em.find(StudentHBaseDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseDoubleWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoubleWrapper newStudent = em.find(StudentHBaseDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseDoubleWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoubleWrapper newStudent = em.find(StudentHBaseDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.name = Kuldeep and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseDoubleWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseDoubleWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Double.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseFloatPrimitiveTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseFloatPrimitive;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseFloatPrimitiveTest extends Base\n{\n    private static final String table = \"StudentHBaseFloatPrimitive\";\n\n    private HBaseCli cli;\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of float\n        StudentHBaseFloatPrimitive studentMax = new StudentHBaseFloatPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Float) getMaxValue(float.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of float\n        StudentHBaseFloatPrimitive studentMin = new StudentHBaseFloatPrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Float) getMinValue(float.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of float\n        StudentHBaseFloatPrimitive student = new StudentHBaseFloatPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Float) getRandomValue(float.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseFloatPrimitive studentMax = em.find(StudentHBaseFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatPrimitive studentMin = em.find(StudentHBaseFloatPrimitive.class, getMinValue(float.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatPrimitive student = em.find(StudentHBaseFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseFloatPrimitive student = em.find(StudentHBaseFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatPrimitive newStudent = em.find(StudentHBaseFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(float.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.id between \" + getMinValue(float.class) + \" and \"\n                + getMaxValue(float.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            /*\n             * if (student.getId() == ((Float)\n             * getMaxValue(float.class)).floatValue()) {\n             * Assert.assertEquals(getMaxValue(short.class), student.getAge());\n             * Assert.assertEquals(\"Kuldeep\", student.getName()); count++; }\n             * else\n             */if (student.getId() == ((Float) getMinValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseFloatPrimitive studentMax = em.find(StudentHBaseFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseFloatPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatPrimitive newStudent = em.find(StudentHBaseFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseFloatPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatPrimitive newStudent = em.find(StudentHBaseFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.name = Kuldeep and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(float.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(float.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseFloatPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseFloatPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Float) getMinValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseFloatWrapperTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseFloatWrapper;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseFloatWrapperTest extends Base\n{\n    private static final String table = \"StudentHBaseFloatWrapper\";\n\n    private HBaseCli cli;\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Float\n        StudentHBaseFloatWrapper studentMax = new StudentHBaseFloatWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Float) getMaxValue(Float.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Float\n        StudentHBaseFloatWrapper studentMin = new StudentHBaseFloatWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Float) getMinValue(Float.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Float\n        StudentHBaseFloatWrapper student = new StudentHBaseFloatWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Float) getRandomValue(Float.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseFloatWrapper studentMax = em.find(StudentHBaseFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatWrapper studentMin = em.find(StudentHBaseFloatWrapper.class, getMinValue(Float.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatWrapper student = em.find(StudentHBaseFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseFloatWrapper student = em.find(StudentHBaseFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatWrapper newStudent = em.find(StudentHBaseFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Float.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.id between \" + getMinValue(Float.class) + \" and \"\n                + getMaxValue(Float.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            /*\n             * if (student.getId().equals(getMaxValue(Float.class))) {\n             * Assert.assertEquals(getMaxValue(short.class), student.getAge());\n             * Assert.assertEquals(\"Kuldeep\", student.getName()); count++; }\n             * else\n             */if (student.getId().equals(getMinValue(Float.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseFloatWrapper studentMax = em.find(StudentHBaseFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseFloatWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatWrapper newStudent = em.find(StudentHBaseFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseFloatWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatWrapper newStudent = em.find(StudentHBaseFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.name = Kuldeep and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Float.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Float.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseFloatWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseFloatWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Float.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseIntTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseInt;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseIntTest extends Base\n{\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseInt\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of int\n        StudentHBaseInt studentMax = new StudentHBaseInt();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(int.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert random value of int\n        StudentHBaseInt student = new StudentHBaseInt();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(int.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert min value of int\n        StudentHBaseInt studentMin = new StudentHBaseInt();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Integer) getMinValue(int.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseInt studentMax = em.find(StudentHBaseInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInt studentMin = em.find(StudentHBaseInt.class, getMinValue(int.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInt student = em.find(StudentHBaseInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseInt student = em.find(StudentHBaseInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInt newStudent = em.find(StudentHBaseInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            Assert.assertEquals(getMinValue(int.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.id between \" + getRandomValue(int.class) + \" and \"\n                + getMinValue(int.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            // else if (student.getId() == ((Integer)\n            // getMinValue(int.class)).intValue())\n            // {\n            // Assert.assertEquals(getPartialValue(short.class),\n            // student.getAge());\n            // Assert.assertEquals(getMinValue(String.class),\n            // student.getName());\n            // count++;\n            // }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseInt studentMax = em.find(StudentHBaseInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseInt.class, getMaxValue(int.class));\n        Assert.assertNull(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n\n        StudentHBaseInt studentMin = em.find(StudentHBaseInt.class, getMinValue(int.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMin.getName());\n        em.remove(studentMin);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMin = em.find(StudentHBaseInt.class, getMinValue(int.class));\n        Assert.assertNull(studentMin);\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseInt s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInt newStudent = em.find(StudentHBaseInt.class, getRandomValue(int.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseInt s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInt newStudent = em.find(StudentHBaseInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        // query =\n        // \"Select s From StudentHBaseInt s where s.name = Amresh and s.age > ?1 and s.age < ?2\";\n        q = em.createQuery(query);\n        // q.setParameter(1, getPartialValue(short.class));\n        // q.setParameter(2, getMaxValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.name = Kuldeep and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseInt s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseInt> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Integer) getMinValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseIntegerTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseInteger;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseIntegerTest extends Base\n{\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseInteger\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of integer\n        StudentHBaseInteger studentMax = new StudentHBaseInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(Integer.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of integer\n        StudentHBaseInteger studentMin = new StudentHBaseInteger();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Integer) getMinValue(Integer.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of integer\n        StudentHBaseInteger student = new StudentHBaseInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(Integer.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseInteger studentMax = em.find(StudentHBaseInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInteger studentMin = em.find(StudentHBaseInteger.class, getMinValue(Integer.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInteger student = em.find(StudentHBaseInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseInteger student = em.find(StudentHBaseInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInteger newStudent = em.find(StudentHBaseInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(Integer.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getRandomValue(Integer.class));\n        q.setParameter(2, getMinValue(Integer.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            // else if (student.getId().equals(getMinValue(Integer.class)))\n            // {\n            // Assert.assertEquals(getPartialValue(short.class),\n            // student.getAge());\n            // Assert.assertEquals(getMinValue(String.class),\n            // student.getName());\n            // count++;\n            // }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseInteger studentMax = em.find(StudentHBaseInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseInteger.class, getMaxValue(Integer.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseInteger s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInteger newStudent = em.find(StudentHBaseInteger.class, getRandomValue(Integer.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseInteger s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInteger newStudent = em.find(StudentHBaseInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.name = Kuldeep and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Integer.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseLongPrimitiveTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseLongPrimitive;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseLongPrimitiveTest extends Base\n{\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseLongPrimitive\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of long\n        StudentHBaseLongPrimitive studentMax = new StudentHBaseLongPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of long\n        StudentHBaseLongPrimitive studentMin = new StudentHBaseLongPrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Long) getMinValue(long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of long\n        StudentHBaseLongPrimitive student = new StudentHBaseLongPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseLongPrimitive studentMax = em.find(StudentHBaseLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongPrimitive studentMin = em.find(StudentHBaseLongPrimitive.class, getMinValue(long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongPrimitive student = em.find(StudentHBaseLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseLongPrimitive student = em.find(StudentHBaseLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongPrimitive newStudent = em.find(StudentHBaseLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(long.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getRandomValue(long.class));\n        q.setParameter(2, getMinValue(long.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            // else if (student.getId() == ((Long)\n            // getMinValue(long.class)).longValue())\n            // {\n            // Assert.assertEquals(getPartialValue(short.class),\n            // student.getAge());\n            // Assert.assertEquals(getMinValue(String.class),\n            // student.getName());\n            // count++;\n            // }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseLongPrimitive studentMax = em.find(StudentHBaseLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseLongPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongPrimitive newStudent = em.find(StudentHBaseLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseLongPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongPrimitive newStudent = em.find(StudentHBaseLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.name = Kuldeep and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseLongPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseLongPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Long) getMinValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseLongWrapperTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseLongWrapper;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseLongWrapperTest extends Base\n{\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseLongWrapper\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Long\n        StudentHBaseLongWrapper studentMax = new StudentHBaseLongWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(Long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Long\n        StudentHBaseLongWrapper studentMin = new StudentHBaseLongWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Long) getMinValue(Long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Long\n        StudentHBaseLongWrapper student = new StudentHBaseLongWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(Long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseLongWrapper studentMax = em.find(StudentHBaseLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongWrapper studentMin = em.find(StudentHBaseLongWrapper.class, getMinValue(Long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongWrapper student = em.find(StudentHBaseLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseLongWrapper student = em.find(StudentHBaseLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongWrapper newStudent = em.find(StudentHBaseLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Long.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getRandomValue(Long.class));\n        q.setParameter(2, getMinValue(Long.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            // else if (student.getId().equals(getMinValue(Long.class)))\n            // {\n            // Assert.assertEquals(getPartialValue(short.class),\n            // student.getAge());\n            // Assert.assertEquals(getMinValue(String.class),\n            // student.getName());\n            // count++;\n            // }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseLongWrapper studentMax = em.find(StudentHBaseLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseLongWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongWrapper newStudent = em.find(StudentHBaseLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseLongWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongWrapper newStudent = em.find(StudentHBaseLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.name = Kuldeep and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseLongWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseLongWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Long.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseShortPrimitiveTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseShortPrimitive;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseShortPrimitiveTest extends Base\n{\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseShortPrimitive\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentHBaseShortPrimitive studentMax = new StudentHBaseShortPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentHBaseShortPrimitive studentMin = new StudentHBaseShortPrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Short) getPartialValue(short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentHBaseShortPrimitive student = new StudentHBaseShortPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseShortPrimitive studentMax = em.find(StudentHBaseShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortPrimitive studentMin = em.find(StudentHBaseShortPrimitive.class, getPartialValue(short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortPrimitive student = em.find(StudentHBaseShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseShortPrimitive student = em.find(StudentHBaseShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortPrimitive newStudent = em.find(StudentHBaseShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            Assert.assertEquals(getPartialValue(short.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.id between \" + getPartialValue(short.class) + \" and \"\n                + getMaxValue(Short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            /*\n             * if (student.getId() == ((Short)\n             * getMaxValue(Short.class)).shortValue()) {\n             * Assert.assertEquals(getMaxValue(short.class), student.getAge());\n             * Assert.assertEquals(\"Kuldeep\", student.getName()); count++; }\n             * else\n             */if (student.getId() == ((Short) getPartialValue(short.class)).shortValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseShortPrimitive studentMax = em.find(StudentHBaseShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseShortPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortPrimitive newStudent = em.find(StudentHBaseShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseShortPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortPrimitive newStudent = em.find(StudentHBaseShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.name = Kuldeep and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseShortPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseShortPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Short) getPartialValue(short.class)).shortValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseShortWrapperTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseShortWrapper;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseShortWrapperTest extends Base\n{\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseShortWrapper\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentHBaseShortWrapper studentMax = new StudentHBaseShortWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentHBaseShortWrapper studentMin = new StudentHBaseShortWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Short) getPartialValue(short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentHBaseShortWrapper student = new StudentHBaseShortWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseShortWrapper studentMax = em.find(StudentHBaseShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortWrapper studentMin = em.find(StudentHBaseShortWrapper.class, getPartialValue(short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortWrapper student = em.find(StudentHBaseShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseShortWrapper student = em.find(StudentHBaseShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortWrapper newStudent = em.find(StudentHBaseShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            Assert.assertEquals(getPartialValue(short.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.id between \" + getPartialValue(short.class) + \" and \"\n                + getMaxValue(Short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            /*\n             * if (student.getId().equals(getMaxValue(Short.class))) {\n             * Assert.assertEquals(getMaxValue(short.class), student.getAge());\n             * Assert.assertEquals(\"Kuldeep\", student.getName()); count++; }\n             * else\n             */if (student.getId().equals(getPartialValue(short.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseShortWrapper studentMax = em.find(StudentHBaseShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseShortWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortWrapper newStudent = em.find(StudentHBaseShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseShortWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortWrapper newStudent = em.find(StudentHBaseShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.name = Kuldeep and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseShortWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseShortWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getPartialValue(short.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseSqlDateTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.sql.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseSqlDate;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseSqlDateTest extends Base\n{\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseSqlDate\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentHBaseSqlDate student = new StudentHBaseSqlDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue(Date.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Date\n        StudentHBaseSqlDate studentMax = new StudentHBaseSqlDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue(Date.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Date\n        StudentHBaseSqlDate studentMin = new StudentHBaseSqlDate();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Date) getMinValue(Date.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseSqlDate studentMax = em.find(StudentHBaseSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseSqlDate studentMin = em.find(StudentHBaseSqlDate.class, getMinValue(Date.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseSqlDate student = em.find(StudentHBaseSqlDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseSqlDate student = em.find(StudentHBaseSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseSqlDate newStudent = em.find(StudentHBaseSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            Assert.assertEquals(getMinValue(Date.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.id between \" + getMinValue(Date.class) + \" and \"\n                + getMaxValue(Date.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Date.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseSqlDate studentMax = em.find(StudentHBaseSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseSqlDate s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseSqlDate newStudent = em.find(StudentHBaseSqlDate.class, getRandomValue(Date.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseSqlDate s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseSqlDate newStudent = em.find(StudentHBaseSqlDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.name = Kuldeep and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseSqlDate s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseSqlDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue(Date.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseStringTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseString;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseStringTest extends Base\n{\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    private static final String table = \"StudentHBaseString\";\n\n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of String\n        StudentHBaseString studentMax = new StudentHBaseString();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((String) getMaxValue(String.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of String\n        StudentHBaseString studentMin = new StudentHBaseString();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((String) getMinValue(String.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of String\n        StudentHBaseString student = new StudentHBaseString();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((String) getRandomValue(String.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseString studentMax = em.find(StudentHBaseString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseString studentMin = em.find(StudentHBaseString.class, getMinValue(String.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseString student = em.find(StudentHBaseString.class, getRandomValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseString student = em.find(StudentHBaseString.class, getMaxValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseString newStudent = em.find(StudentHBaseString.class, getMaxValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            Assert.assertEquals(getMinValue(String.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.id between \" + getRandomValue(String.class) + \" and \"\n                + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseString student : students)\n        {\n            if (student.getId().equals(getRandomValue(String.class)))\n            {\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseString studentMax = em.find(StudentHBaseString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseString.class, getMaxValue(String.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseString s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseString newStudent = em.find(StudentHBaseString.class, getRandomValue(String.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseString s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseString newStudent = em.find(StudentHBaseString.class, getRandomValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.age > \" + getPartialValue(short.class) + \" and s.age < \"\n                + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.name = Kuldeep and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseString s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseString> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(String.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(String.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.io.IOException;\nimport java.math.BigInteger;\nimport java.util.List;\n\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.hadoop.hbase.MasterNotRunningException;\nimport org.apache.hadoop.hbase.ZooKeeperConnectionException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\n\n/**\n * The Class Student test case for HBase.\n * \n * @author Kuldeep.mishra\n */\npublic class StudentHBaseTest extends StudentBase<StudentHBase>\n{\n    private String persistenceUnit = \"hbaseTest\";\n\n    private HBaseCli cli;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setupInternal(persistenceUnit);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        teardownInternal(persistenceUnit);\n\n    }\n\n    @Test\n    public void executeTests()\n    {\n        onInsert();\n        onMerge();\n    }\n\n    /**\n     * Test method for.\n     * \n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     *             {@link com.impetus.kundera.examples.student.StudentDao#saveStudent(com.impetus.kundera.StudentHBase.crud.datatype.entities.StudentHbase)}\n     *             .\n     */\n\n    public void onInsert()\n    {\n        try\n        {\n            onInsert(new StudentHBase());\n        }\n        catch (InstantiationException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n\n        // find by id.\n        StudentEntityDef s = em.find(StudentHBase.class, studentId1);\n        assertOnDataTypes((StudentHBase) s);\n\n        // // find by name.\n        assertFindByName(em, \"StudentHBase\", StudentHBase.class, \"Amresh\", \"studentName\");\n\n        // find by name and age.\n        assertFindByNameAndAge(em, \"StudentHBase\", StudentHBase.class, \"Amresh\", \"10\", \"studentName\");\n\n        // find by name, age clause\n        assertFindByNameAndAgeGTAndLT(em, \"StudentHBase\", StudentHBase.class, \"Amresh\", \"10\", \"20\", \"studentName\");\n        //\n        // // find by between clause\n        assertFindByNameAndAgeBetween(em, \"StudentHBase\", StudentHBase.class, \"Amresh\", \"10\", \"15\", \"studentName\");\n\n        // find by Range.\n        assertFindByRange(em, \"StudentHBase\", StudentHBase.class, \"12345677\", \"12345679\", \"studentId\");\n\n        // find by without where clause.\n        assertFindWithoutWhereClause(em, \"StudentHBase\", StudentHBase.class);\n\n        // Query on Date.\n        String query = \"Select s from StudentHBase s where s.enrolmentDate =:enrolmentDate\";\n        Query q = em.createQuery(query);\n        q.setParameter(\"enrolmentDate\", enrolmentDate);\n        List<StudentHBase> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n\n        // Query on long.\n        /* String */query = \"Select s from StudentHBase s where s.uniqueId =?1\";\n        /* Query */q = em.createQuery(query);\n        q.setParameter(1, 78575785897L);\n\n        /* List<StudentHBase> */results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(78575785897L, results.get(0).getUniqueId());\n\n        // Assert on boolean.\n        query = \"Select s from StudentHBase s where s.isExceptional =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, true);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(true, results.get(0).isExceptional());\n\n        // with false.\n        query = \"Select s from StudentHBase s where s.isExceptional =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, false);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n\n        // query on int.\n\n        query = \"Select s from StudentHBase s where s.age =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 10);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(10, results.get(0).getAge());\n\n        // query on char (semester)\n\n        query = \"Select s from StudentHBase s where s.semester =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 'A');\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(10, results.get(0).getAge());\n        Assert.assertEquals('A', results.get(0).getSemester());\n\n        // query on float (percentage)\n        query = \"Select s from StudentHBase s where s.percentage =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 61.6);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(61.6f, results.get(0).getPercentage());\n\n        // query on double (height)\n\n        query = \"Select s from StudentHBase s where s.height =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 163.76765654);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(163.76765654, results.get(0).getHeight());\n\n        // query on cgpa.\n        query = \"Select s from StudentHBase s where s.cgpa =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(8, results.get(0).getCgpa());\n\n        // query on yearsSpent.\n        Integer i = new Integer(3);\n        query = \"Select s from StudentHBase s where s.yearsSpent = 3\";\n        q = em.createQuery(query);\n        // q.setParameter(1, new Integer(3));\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(i, results.get(0).getYearsSpent());\n\n        // query on yearsSpent.\n        query = \"Select s from StudentHBase s where s.yearsSpent =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, new Integer(3));\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(new Integer(3), results.get(0).getYearsSpent());\n\n        // query on digitalSignature.\n        query = \"Select s from StudentHBase s where s.digitalSignature =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, (byte) 50);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(true, results.get(0).isExceptional());\n        Assert.assertEquals((byte) 50, results.get(0).getDigitalSignature());\n\n        // query on cpga and digitalSignature.\n        query = \"Select s from StudentHBase s where s.cgpa =?1 and s.digitalSignature >= ?2 and s.digitalSignature <= ?3\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        q.setParameter(2, (byte) 5);\n        q.setParameter(3, (byte) 50);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n\n        // query on cpga and digitalSignature parameter appended with String\n        // .\n        query = \"Select s from StudentHBase s where s.cgpa = 8 and s.digitalSignature >= 5 and s.digitalSignature <= 50\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n\n        // query on cpga and digitalSignature.\n        query = \"Select s from StudentHBase s where s.digitalSignature >= ?2 and s.digitalSignature <= ?3 and s.cgpa =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        q.setParameter(2, (byte) 5);\n        q.setParameter(3, (byte) 50);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n\n        // query on percentage and height.\n        query = \"Select s from StudentHBase s where s.percentage >= ?2 and s.percentage <= ?3 and s.height =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 163.76765654);\n        q.setParameter(2, 61.6);\n        q.setParameter(3, 69.3);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals(61.6f, results.get(0).getPercentage());\n        Assert.assertEquals(163.76765654, results.get(0).getHeight());\n\n        // query on percentage and height parameter appended in string.\n        query = \"Select s from StudentHBase s where s.percentage >= 61.6 and s.percentage <= 69.3 and s.height = 163.76765654\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals(61.6f, results.get(0).getPercentage());\n        Assert.assertEquals(163.76765654, results.get(0).getHeight());\n\n        // query on cpga and uniqueId.\n        query = \"Select s from StudentHBase s where s.cgpa =?1 and s.uniqueId >= ?2 and s.uniqueId <= ?3\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        q.setParameter(2, 78575785897L);\n        q.setParameter(3, 78575785899L);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n        Assert.assertEquals(78575785897L, results.get(0).getUniqueId());\n        Assert.assertEquals(78575785898L, results.get(1).getUniqueId());\n\n        // query on cpga and semester.\n        query = \"Select s from StudentHBase s where s.cgpa =?1 and s.semester >= ?2 and s.semester < ?3\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        q.setParameter(2, 'A');\n        q.setParameter(3, 'C');\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n        Assert.assertEquals(78575785897L, results.get(0).getUniqueId());\n        Assert.assertEquals(78575785898L, results.get(1).getUniqueId());\n        Assert.assertEquals(10, results.get(0).getAge());\n        Assert.assertEquals(20, results.get(1).getAge());\n\n        // query on cpga and semester with appending in string.\n        query = \"Select s from StudentHBase s where s.cgpa = 8 and s.semester >= A and s.semester < C\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n        Assert.assertEquals(78575785897L, results.get(0).getUniqueId());\n        Assert.assertEquals(78575785898L, results.get(1).getUniqueId());\n        Assert.assertEquals(10, results.get(0).getAge());\n        Assert.assertEquals(20, results.get(1).getAge());\n\n        // query on invalid cpga and uniqueId.\n        query = \"Select s from StudentHBase s where s.cgpa =?1 and s.uniqueId >= ?2 and s.uniqueId <= ?3\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 2);\n        q.setParameter(2, 78575785897L);\n        q.setParameter(3, 78575785899L);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertTrue(results.isEmpty());\n\n        // query on big integer.\n        query = \"Select s from StudentHBase s where s.bigInteger =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, bigInteger);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(163.76765654, results.get(0).getHeight());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(163.76765655, results.get(1).getHeight());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n        Assert.assertEquals(163.76765656, results.get(2).getHeight());\n        Assert.assertEquals(10, results.get(0).getAge());\n        Assert.assertEquals(20, results.get(1).getAge());\n        Assert.assertEquals(15, results.get(2).getAge());\n        Assert.assertEquals('A', results.get(0).getSemester());\n        Assert.assertEquals('B', results.get(1).getSemester());\n        Assert.assertEquals('C', results.get(2).getSemester());\n\n        // invalid.\n        q.setParameter(1, new BigInteger(\"1234567823\"));\n        results = q.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertTrue(results.isEmpty());\n\n        updateQueryTest();\n\n    }\n\n    private void updateQueryTest()\n    {/*\n      * Query q = em.createQuery(\n      * \"update StudentHBase s set s.studentName = :oldName where s.studentName = :newName\"\n      * ); q.setParameter(\"newName\", \"NewAmresh\"); q.setParameter(\"oldName\",\n      * \"Amresh\"); int results = q.executeUpdate();\n      * Assert.assertNotNull(results); Assert.assertEquals(1, results);\n      */\n    }\n\n    /**\n     * On merge.\n     */\n    public void onMerge()\n    {\n        em.persist(prepareData((Long) studentId1, 78575785897L, \"Amresh\", true, 10, 'C', (byte) 5, (short) 8,\n                (float) 69.6, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar,\n                new StudentHBase()));\n        StudentHBase s = em.find(StudentHBase.class, studentId1);\n        Assert.assertNotNull(s);\n        Assert.assertEquals(\"Amresh\", s.getStudentName());\n        // modify record.\n        s.setStudentName(\"NewAmresh\");\n        em.merge(s);\n        // emf.close();\n        Query q = em.createQuery(\"Select p from StudentHBase p where p.studentName = NewAmresh\");\n        List<StudentHBase> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n    }\n\n    @Override\n    void startServer() throws InterruptedException\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    @Override\n    void stopServer() throws InterruptedException, MasterNotRunningException, ZooKeeperConnectionException, IOException\n    {\n    }\n\n    @Override\n    void createSchema()\n    {\n        cli.createTable(\"KunderaExamples\", \"STUDENT\");\n    }\n\n    @Override\n    void deleteSchema()\n    {\n        cli.dropTable(\"KunderaExamples\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseTimeTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.sql.Time;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseTime;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseTimeTest extends Base\n{\n    private static final String table = \"StudentHBaseTime\";\n\n    private HBaseCli cli;\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Time\n        StudentHBaseTime student = new StudentHBaseTime();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Time) getRandomValue(Time.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Time\n        StudentHBaseTime studentMax = new StudentHBaseTime();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Time) getMaxValue(Time.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Time\n        StudentHBaseTime studentMin = new StudentHBaseTime();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Time) getMinValue(Time.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseTime studentMax = em.find(StudentHBaseTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTime studentMin = em.find(StudentHBaseTime.class, getMinValue(Time.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTime student = em.find(StudentHBaseTime.class, getRandomValue(Time.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseTime student = em.find(StudentHBaseTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTime newStudent = em.find(StudentHBaseTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            Assert.assertEquals(getMinValue(Time.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.id between \" + getMinValue(Time.class) + \" and \"\n                + getMaxValue(Time.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Time.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Time.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            Assert.assertEquals(getMaxValue(Time.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            Assert.assertEquals(getMaxValue(Time.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseTime studentMax = em.find(StudentHBaseTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseTime.class, getMaxValue(Time.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseTime s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTime newStudent = em.find(StudentHBaseTime.class, getRandomValue(Time.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String upTimeQuery = \"Update StudentHBaseTime s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(upTimeQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTime newStudent = em.find(StudentHBaseTime.class, getRandomValue(Time.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.name = Kuldeep and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Time.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Time.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseTime s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseTime> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Time.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Time) getRandomValue(Time.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseTimestampTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.sql.Timestamp;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseTimestamp;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseTimestampTest extends Base\n{\n    private static final String table = \"StudentHBaseTimestamp\";\n\n    private HBaseCli cli;\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Time\n        StudentHBaseTimestamp student = new StudentHBaseTimestamp();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Timestamp) getRandomValue(Timestamp.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Time\n        StudentHBaseTimestamp studentMax = new StudentHBaseTimestamp();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Timestamp) getMaxValue(Timestamp.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Timestamp\n        StudentHBaseTimestamp studentMin = new StudentHBaseTimestamp();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Timestamp) getMinValue(Timestamp.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseTimestamp studentMax = em.find(StudentHBaseTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTimestamp studentMin = em.find(StudentHBaseTimestamp.class, getMinValue(Timestamp.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTimestamp student = em.find(StudentHBaseTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseTimestamp student = em.find(StudentHBaseTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTimestamp newStudent = em.find(StudentHBaseTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.id between '\" + getMinValue(Timestamp.class) + \"' and '\"\n                + getMaxValue(Timestamp.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            /*\n             * if (student.getId().equals(getMaxValue(Timestamp.class))) {\n             * Assert.assertEquals(getMaxValue(short.class), student.getAge());\n             * Assert.assertEquals(\"Kuldeep\", student.getName()); count++; }\n             * else\n             */if (student.getId().equals(getMinValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            Assert.assertEquals(getMaxValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            Assert.assertEquals(getMaxValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseTimestamp studentMax = em.find(StudentHBaseTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseTimestamp s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTimestamp newStudent = em.find(StudentHBaseTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String upTimeQuery = \"Update StudentHBaseTimestamp s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(upTimeQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTimestamp newStudent = em.find(StudentHBaseTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.name = Amresh and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.name = Kuldeep and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseTimestamp s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseTimestamp> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Timestamp) getRandomValue(Timestamp.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseUUIDTest.java",
    "content": "package com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseUUID;\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class StudentHBaseUUIDTest extends Base\n{\n    private static final String table = \"StudentHBaseUUID\";\n\n    private HBaseCli cli;\n\n    private static final String keyspace = \"KunderaHbaseDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"HbaseDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of UUID\n        StudentHBaseUUID studentMax = new StudentHBaseUUID();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((UUID) getMaxValue(UUID.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of UUID\n        StudentHBaseUUID studentMin = new StudentHBaseUUID();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((UUID) getMinValue(UUID.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of UUID\n        StudentHBaseUUID student = new StudentHBaseUUID();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((UUID) getRandomValue(UUID.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseUUID studentMax = em.find(StudentHBaseUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseUUID studentMin = em.find(StudentHBaseUUID.class, getMinValue(UUID.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseUUID student = em.find(StudentHBaseUUID.class, getRandomValue(UUID.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseUUID student = em.find(StudentHBaseUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseUUID newStudent = em.find(StudentHBaseUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            Assert.assertEquals(getMinValue(UUID.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMaxValue(UUID.class));\n        q.setParameter(2, getRandomValue(UUID.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(UUID.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            Assert.assertEquals(getMaxValue(UUID.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.name = Kuldeep and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            Assert.assertEquals(getMaxValue(UUID.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseUUID studentMax = em.find(StudentHBaseUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseUUID.class, getMaxValue(UUID.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseUUID s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseUUID newStudent = em.find(StudentHBaseUUID.class, getRandomValue(UUID.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseUUID s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseUUID newStudent = em.find(StudentHBaseUUID.class, getRandomValue(UUID.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.name = Amresh and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.name = Kuldeep and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(UUID.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(UUID.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseUUID s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseUUID> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(UUID.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void stopCluster()\n    {\n        cli.stopCluster();\n    }\n\n    public void createSchema()\n    {\n        cli.createTable(keyspace, table);\n\n    }\n\n    public void dropSchema()\n    {\n        cli.dropTable(keyspace);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/ZkShutDownTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class ZkShutDownTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    @Test\n    public void test()\n    {\n        // HBaseCli.cleanUp();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseBigDecimal.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.math.BigDecimal;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseBigDecimal\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseBigDecimal\n{\n\n    @Id\n    private BigDecimal id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public BigDecimal getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(BigDecimal id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseBigInteger.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.math.BigInteger;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseBigInteger\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseBigInteger\n{\n\n    @Id\n    private BigInteger id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public BigInteger getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(BigInteger id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseBooleanPrimitive.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseBooleanPrimitive\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseBooleanPrimitive\n{\n    @Id\n    private boolean id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public boolean getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(boolean id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseBooleanWrapper.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseBooleanWrapper\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseBooleanWrapper\n{\n    @Id\n    private Boolean id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Boolean getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Boolean id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseBytePrimitive.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseBytePrimitive\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseBytePrimitive\n{\n\n    @Id\n    private byte id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseByteWrapper.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseByteWrapper\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseByteWrapper\n{\n\n    @Id\n    private Byte id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseCalendar.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.util.Calendar;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseCalendar\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseCalendar\n{\n\n    @Id\n    private Calendar id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Calendar getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Calendar id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseChar.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseChar\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseChar\n{\n\n    @Id\n    private char id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public char getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(char id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseCharacter.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseCharacter\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseCharacter\n{\n    @Id\n    private Character id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Character getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Character id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseDate.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseDate\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseDate\n{\n\n    @Id\n    private Date id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseDoublePrimitive.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseDoublePrimitive\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseDoublePrimitive\n{\n\n    @Id\n    private double id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public double getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseDoubleWrapper.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseDoubleWrapper\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseDoubleWrapper\n{\n\n    @Id\n    private Double id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Double getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseFloatPrimitive.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseFloatPrimitive\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseFloatPrimitive\n{\n    @Id\n    private float id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public float getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseFloatWrapper.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseFloatWrapper\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseFloatWrapper\n{\n\n    @Id\n    private Float id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Float getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseInt.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseInt\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseInt\n{\n\n    @Id\n    private int id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseInteger.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseInteger\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseInteger\n{\n    @Id\n    private Integer id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Integer getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Integer id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseLongPrimitive.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseLongPrimitive\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseLongPrimitive\n{\n\n    @Id\n    private long id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public long getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseLongWrapper.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseLongWrapper\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseLongWrapper\n{\n\n    @Id\n    private Long id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Long getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseShortPrimitive.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseShortPrimitive\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseShortPrimitive\n{\n\n    @Id\n    private short id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public short getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseShortWrapper.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseShortWrapper\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseShortWrapper\n{\n\n    @Id\n    private Short id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Short getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseSqlDate.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.sql.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseSqlDate\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseSqlDate\n{\n\n    @Id\n    private Date id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseString.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseString\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseString\n{\n\n    @Id\n    private String id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseTime.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.sql.Time;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseTime\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseTime\n{\n\n    @Id\n    private Time id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Time getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Time id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseTimestamp.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.sql.Timestamp;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseTimestamp\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseTimestamp\n{\n\n    @Id\n    private Timestamp id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Timestamp getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Timestamp id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseUUID.java",
    "content": "package com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentHBaseUUID\", schema = \"KunderaHbaseDataType@HbaseDataTypeTest\")\npublic class StudentHBaseUUID\n{\n\n    @Id\n    private UUID id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public UUID getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(UUID id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/embedded/EmbeddedEntityTest.java",
    "content": "package com.impetus.client.hbase.crud.embedded;\n\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport javax.servlet.UnavailableException;\n\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class EmbeddedEntityTest\n{\n\n    private static final Date CAPTURE_TIME = new Date();\n\n    private static final Date CAPTURE_TIME1 = new Date(\"Feb 14 10:01:25 MST 2010\");\n\n    private static final Date CAPTURE_TIME2 = new Date(Long.MAX_VALUE);\n\n    private static final Date CAPTURE_TIME3 = new Date(\"Feb 14 10:10:17 MST 2016\");\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    private static HBaseCli cli;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws IOException\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n\n        emf = Persistence.createEntityManagerFactory(\"hbaseTest\");\n    }\n\n    @Before\n    public void setUp() throws IOException, TException, UnavailableException\n    {\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testSelectEmbeddedColumn()\n    {\n        persist();\n        String query2 = \"select x.id,\" + \"x.rowKey,\" + \"x.established, \" + \"x.closeWait,\" + \"x.finWait,\" + \"x.finWait2,\"\n                + \"x.idle,\" + \"x.listen,\" + \"x.synRecv,\" + \"x.timeWait,\" + \"x.total \" + \"from NetstatData x \"\n                + \"where x.id.server= :serverid\";\n\n        Query query = em.createQuery(query2);\n        query.setParameter(\"serverid\", \"apdwa570\");\n        List<NetstatData> result = query.getResultList();\n        Assert.assertNotNull(result);\n        Assert.assertEquals(2, result.size());\n        Assert.assertNotNull(result.get(0));\n        Assert.assertNotNull(result.get(0).getId());\n        Assert.assertEquals(CAPTURE_TIME, result.get(0).getId().getCaptureTime());\n        Assert.assertEquals(\"apdwa570\", result.get(0).getId().getServer());\n        Assert.assertNull(result.get(0).getId().getPortMapId());\n    }\n\n    @Test\n    public void testSelectOnlySpecificColumnOfEmbeddable()\n    {\n        persist();\n        String query2 = \"select x.id.server, x.id.captureTime,\" + \"x.rowKey,\" + \"x.established, \" + \"x.closeWait,\"\n                + \"x.finWait,\" + \"x.finWait2,\" + \"x.idle,\" + \"x.listen,\" + \"x.synRecv,\" + \"x.timeWait,\" + \"x.total \"\n                + \"from NetstatData x \" + \"where x.id.server= :serverid\";\n\n        Query query = em.createQuery(query2);\n        query.setParameter(\"serverid\", \"apdwa571\");\n        List<NetstatData> result = query.getResultList();\n        Assert.assertNotNull(result);\n        Assert.assertEquals(2, result.size());\n        Assert.assertNotNull(result.get(0));\n        Assert.assertNotNull(result.get(0).getId());\n        Assert.assertEquals(CAPTURE_TIME2, result.get(0).getId().getCaptureTime());\n        Assert.assertNotNull(result.get(0).getId().getServer());\n        Assert.assertNull(result.get(0).getId().getPortMapId());\n    }\n\n    @Test\n    public void testSelectTwoSpecificColumnOfEmbeddable()\n    {\n        persist();\n        String query2 = \"select x.id.captureTime,\" + \"x.id.server,\" + \"x.rowKey,\" + \"x.established, \" + \"x.closeWait,\"\n                + \"x.finWait,\" + \"x.finWait2,\" + \"x.idle,\" + \"x.listen,\" + \"x.synRecv,\" + \"x.timeWait,\" + \"x.total \"\n                + \"from NetstatData x \" + \"where x.id.portMapTypeCd= :port\"\n                + \" and x.id.captureTime between :captureTime1 and :captureTime2\";\n\n        Query query = em.createQuery(query2);\n        query.setParameter(\"port\", \"portMapTypeCd\");\n        query.setParameter(\"captureTime1\", CAPTURE_TIME1);\n        query.setParameter(\"captureTime2\", CAPTURE_TIME3);\n\n        List<NetstatData> result = query.getResultList();\n        Assert.assertNotNull(result);\n        Assert.assertEquals(2, result.size());\n        Assert.assertNotNull(result.get(0));\n        Assert.assertNotNull(result.get(0).getId());\n        Assert.assertNull(result.get(0).getId().getPortMapId());\n    }\n\n    @Test\n    public void testSelectTwoColumnsOfEmbeddable()\n    {\n        persist();\n        String query2 = \"select x.id.captureTime,\" + \"x.id.server,\" + \"x.rowKey,\" + \"x.established, \" + \"x.closeWait,\"\n                + \"x.finWait,\" + \"x.finWait2,\" + \"x.idle,\" + \"x.listen,\" + \"x.synRecv,\" + \"x.timeWait,\" + \"x.total \"\n                + \"from NetstatData x \" + \"where x.id.server= :serverId\"\n                + \" and x.id.captureTime between :captureTime1 and :captureTime2\";\n\n        Query query = em.createQuery(query2);\n        query.setParameter(\"serverId\", \"apdwa571\");\n        query.setParameter(\"captureTime1\", CAPTURE_TIME1);\n        query.setParameter(\"captureTime2\", CAPTURE_TIME3);\n\n        List<NetstatData> result = query.getResultList();\n        Assert.assertNotNull(result);\n        Assert.assertEquals(1, result.size());\n        Assert.assertNotNull(result.get(0));\n        Assert.assertNotNull(result.get(0).getId());\n        Assert.assertEquals(CAPTURE_TIME3, result.get(0).getId().getCaptureTime());\n        Assert.assertEquals(\"apdwa571\", result.get(0).getId().getServer());\n        Assert.assertNull(result.get(0).getId().getPortMapId());\n    }\n\n    @Test\n    public void testSelectAll()\n    {\n        persist();\n        String query2 = \"select x from NetstatData x \" + \"where x.id.portMapTypeCd= :port\";\n\n        Query query = em.createQuery(query2);\n        query.setParameter(\"port\", \"portMapTypeCd\");\n        List<NetstatData> result = query.getResultList();\n        Assert.assertNotNull(result);\n        Assert.assertEquals(4, result.size());\n        Assert.assertNotNull(result.get(0));\n        Assert.assertNotNull(result.get(0).getId());\n        Assert.assertEquals(CAPTURE_TIME, result.get(0).getId().getCaptureTime());\n        Assert.assertEquals(\"apdwa570\", result.get(0).getId().getServer());\n        Assert.assertNull(result.get(0).getId().getPortMapId());\n    }\n\n    @After\n    public void tearDown()\n    {\n        em.close();\n\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass()\n    {\n        emf.close();\n        if (cli != null)\n        {\n            cli.dropTable(\"KunderaExamples\");\n        }\n    }\n\n    /**\n     * \n     */\n    private void persist()\n    {\n        NetstatData data = new NetstatData();\n        NetstatDataId id = new NetstatDataId();\n        id.setServer(\"apdwa570\");\n        data.setRowKey(\"rowKey1\");\n        id.setCaptureTime(CAPTURE_TIME);\n        id.setPortMapTypeCd(\"portMapTypeCd\");\n        data.setEstablished(1);\n        data.setTotal(1);\n        data.setId(id);\n\n        em.persist(data);\n\n        NetstatData data1 = new NetstatData();\n        NetstatDataId id1 = new NetstatDataId();\n        id1.setServer(\"apdwa570\");\n        data1.setRowKey(\"rowKey2\");\n        id1.setCaptureTime(CAPTURE_TIME1);\n        id1.setPortMapTypeCd(\"portMapTypeCd\");\n        data1.setEstablished(2);\n        data1.setTotal(2);\n        data1.setId(id1);\n\n        em.persist(data1);\n\n        NetstatData data2 = new NetstatData();\n        NetstatDataId id2 = new NetstatDataId();\n        id2.setServer(\"apdwa571\");\n        data2.setRowKey(\"rowKey3\");\n        id2.setCaptureTime(CAPTURE_TIME2);\n        id2.setPortMapTypeCd(\"portMapTypeCd\");\n        data2.setEstablished(3);\n        data2.setTotal(3);\n        data2.setId(id2);\n\n        em.persist(data2);\n\n        NetstatData data3 = new NetstatData();\n        NetstatDataId id3 = new NetstatDataId();\n        id3.setServer(\"apdwa571\");\n        data3.setRowKey(\"rowKey4\");\n        id3.setCaptureTime(CAPTURE_TIME3);\n        id3.setPortMapTypeCd(\"portMapTypeCd\");\n        data3.setEstablished(4);\n        data3.setTotal(4);\n        data3.setId(id3);\n\n        em.persist(data3);\n\n        em.clear();\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/embedded/NetstatData.java",
    "content": "package com.impetus.client.hbase.crud.embedded;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@SuppressWarnings(\"serial\")\n@Entity\n@Table(name = \"NETSTAT_DTL_SMRY\", schema = \"KunderaExamples@hbaseTest\")\npublic class NetstatData implements Serializable\n{\n\n    @Id\n    @Column(name = \"ROW_KEY\")\n    private String rowKey; // added for hbase\n\n    @Embedded\n    private NetstatDataId id;\n\n    @Column(name = \"ESTAB_PORT_CT\", nullable = true)\n    private Integer established;\n\n    @Column(name = \"CLOSE_WAIT_CT\", nullable = true)\n    private Integer closeWait;\n\n    @Column(name = \"FINISH_WAIT_CT\", nullable = true)\n    private Integer finWait;\n\n    @Column(name = \"FINISH_WAIT2_CT\", nullable = true)\n    private Integer finWait2;\n\n    @Column(name = \"IDLE_CT\", nullable = true)\n    private Integer idle;\n\n    @Column(name = \"LISTEN_CT\", nullable = true)\n    private Integer listen;\n\n    @Column(name = \"SYNC_RCV_CT\", nullable = true)\n    private Integer synRecv;\n\n    @Column(name = \"TIME_WAIT_CT\", nullable = true)\n    private Integer timeWait;\n\n    @Column(name = \"PORT_CT\", nullable = true)\n    private Integer total;\n\n    public NetstatData()\n    {\n        NetstatDataId id = new NetstatDataId();\n        this.id = id;\n    }\n\n    private transient String portDesc;\n\n    public NetstatDataId getId()\n    {\n        return this.id;\n    }\n\n    public void setId(NetstatDataId id)\n    {\n        this.id = id;\n    }\n\n    public Integer getEstablished()\n    {\n        return this.established;\n    }\n\n    public void setEstablished(Integer established)\n    {\n        this.established = established;\n    }\n\n    public Integer getCloseWait()\n    {\n        return this.closeWait;\n    }\n\n    public void setCloseWait(Integer closeWait)\n    {\n        this.closeWait = closeWait;\n    }\n\n    public Integer getFinWait()\n    {\n        return this.finWait;\n    }\n\n    public void setFinWait(Integer finWait)\n    {\n        this.finWait = finWait;\n    }\n\n    public Integer getFinWait2()\n    {\n        return this.finWait2;\n    }\n\n    public void setFinWait2(Integer finWait2)\n    {\n        this.finWait2 = finWait2;\n    }\n\n    public Integer getIdle()\n    {\n        return this.idle;\n    }\n\n    public void setIdle(Integer idle)\n    {\n        this.idle = idle;\n    }\n\n    public Integer getListen()\n    {\n        return this.listen;\n    }\n\n    public void setListen(Integer listen)\n    {\n        this.listen = listen;\n    }\n\n    public Integer getSynRecv()\n    {\n        return this.synRecv;\n    }\n\n    public void setSynRecv(Integer synRecv)\n    {\n        this.synRecv = synRecv;\n    }\n\n    public Integer getTimeWait()\n    {\n        return this.timeWait;\n    }\n\n    public void setTimeWait(Integer timeWait)\n    {\n        this.timeWait = timeWait;\n    }\n\n    public Integer getTotal()\n    {\n        return this.total;\n    }\n\n    public void setTotal(Integer total)\n    {\n        this.total = total;\n    }\n\n    public String getPortDesc()\n    {\n        return portDesc;\n    }\n\n    public void setPortDesc(String portDesc)\n    {\n        this.portDesc = portDesc;\n    }\n\n    public String getPortType()\n    {\n        // For DataPower return PortMapTypeCd itself\n        if (id.getPortMapTypeCd().length() > 1)\n        {\n            return id.getPortMapTypeCd();\n        }\n\n        if (id.getPortMapTypeCd() == null)\n            return \"Others\";\n\n        switch (id.getPortMapTypeCd().toCharArray()[0])\n        {\n        case 'A':\n            return \"App Port\";\n        case 'N':\n            return \"Netscaler\";\n        case 'W':\n            return \"Web Port\";\n        case 'Q':\n            return \"MQ\";\n        case 'D':\n            return \"DB\";\n        case 'L':\n            return \"Local\";\n        case '?':\n            return \"?\";\n        default:\n            return \"Others\";\n        }\n\n    }\n\n    public void setPortType(String s)\n    {\n        throw new IllegalArgumentException(\"Can't set a read-only attribute\");\n    }\n\n    public String getRowKey()\n    {\n        return rowKey;\n    }\n\n    public void setRowKey(String rowKey)\n    {\n        this.rowKey = rowKey;\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/embedded/NetstatDataId.java",
    "content": "package com.impetus.client.hbase.crud.embedded;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n@SuppressWarnings(\"serial\")\n@Embeddable\npublic class NetstatDataId implements Serializable\n{\n\n    @Column(name = \"SERVER_ID\", nullable = true)\n    private String server;\n\n    @Column(name = \"CPTR_TS\", nullable = true)\n    private Date captureTime;\n\n    @Column(name = \"PORTMAP_ID\", nullable = true)\n    private Integer portMapId;\n\n    @Column(name = \"PORTMAP_TYP_CD\", nullable = true)\n    private String portMapTypeCd;\n\n    public String getServer()\n    {\n        return this.server;\n    }\n\n    public void setServer(String server)\n    {\n        this.server = server;\n    }\n\n    public Date getCaptureTime()\n    {\n        return this.captureTime;\n    }\n\n    public void setCaptureTime(Date captureTime)\n    {\n        this.captureTime = captureTime;\n    }\n\n    public Integer getPortMapId()\n    {\n        return portMapId;\n    }\n\n    public void setPortMapId(Integer portMapId)\n    {\n        this.portMapId = portMapId;\n    }\n\n    public String getPortMapTypeCd()\n    {\n        return portMapTypeCd;\n    }\n\n    public void setPortMapTypeCd(String portMapTypeCd)\n    {\n        this.portMapTypeCd = portMapTypeCd;\n    }\n\n    public boolean equals(Object o)\n    {\n        if (this == o)\n            return true;\n        if (o == null)\n            return false;\n        if (!(o instanceof NetstatDataId))\n            return false;\n        NetstatDataId that = (NetstatDataId) o;\n\n        return ((server == that.server) || (server != null && that.server != null && server.equals(that.server)))\n                && ((captureTime == that.captureTime) || (captureTime != null && that.captureTime != null && captureTime\n                        .equals(that.captureTime)))\n                && ((portMapId == that.portMapId) || (portMapId != null && that.portMapId != null && this.portMapId\n                        .equals(that.portMapId))) && ((portMapTypeCd == that.portMapTypeCd));\n    }\n\n    public int hashCode()\n    {\n        int result = 17;\n        result = 37 * result + (server == null ? 0 : server.hashCode());\n        result = 37 * result + (captureTime == null ? 0 : captureTime.hashCode());\n        result = 37 * result + (portMapId == null ? 0 : portMapId.hashCode());\n        result = 37 * result + (portMapTypeCd == null ? 0 : portMapTypeCd.hashCode());\n        return result;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/mappedsuperclass/inheritence/HBaseEntityWithoutFieldsTest.java",
    "content": "package com.impetus.client.hbase.crud.mappedsuperclass.inheritence;\n\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.mappedsuperclass.EntityWithoutFieldsBase;\n\n/**\n * @author amitkumar\n *\n *\tClass to verify that at least one field in entity class is not mandatory if the \n *\tsuperclass contains all the mandatory fields\n */\npublic class HBaseEntityWithoutFieldsTest extends EntityWithoutFieldsBase\n{\n\n\t@Before\n\tpublic void setup()\n\t{\n\t\tpersistenceUnit = \"hbase\";\n\t\tsetupInternal();\n\t}\n\t\n\t@Test\n\tpublic void testEntityWithNoFields()\n\t{\n\t\ttestEntityWithNoFieldsBase();\n\t}\n\t\n\t@Test\n\tpublic void testEntityWithNoFields2LevelInheritance()\n\t{\n\t\ttestEntityWithNoFields2LevelInheritanceBase();\n\t}\n\n\t@After\n\tpublic void tearDown()\n\t{\n\t\ttearDownInternal();\n\t}\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/crud/mappedsuperclass/inheritence/HBaseMappedSuperClassTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.mappedsuperclass.inheritence;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.MappedSuperclass;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.client.crud.mappedsuperclass.MappedSuperClassBase;\n\n/**\n * @author vivek.mishra\n * junit for {@link MappedSuperclass}, {@link AttributeOverride}, {@link AttributeOverrides}.\n */\npublic class HBaseMappedSuperClassTest extends MappedSuperClassBase\n{\n    \n    private HBaseCli cli;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        _PU = \"hbaseTest\";\n        cli = new HBaseCli();\n        cli.startCluster();\n        setUpInternal();\n    }\n\n    @Test\n    public void test()\n    {\n        assertInternal();\n    }\n\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        if (cli != null )\n        {\n            cli.dropTable(\"KunderaExamples\");\n            cli.stopCluster(\"KunderaExamples\");\n        }\n        tearDownInternal();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/generatedId/HBaseGeneratedIdTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.generatedId;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.HBaseClient;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdDefault;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdStrategyAuto;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdStrategyIdentity;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdStrategySequence;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdStrategyTable;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdWithOutSequenceGenerator;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdWithOutTableGenerator;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdWithSequenceGenerator;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdWithTableGenerator;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdWithTableGeneratorWihtoutInit;\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.KunderaException;\n\n\n/**\n * @author Kuldeep Mishra\n *\n */\npublic class HBaseGeneratedIdTest\n{\n    private EntityManagerFactory emf;\n\n    private HBaseCli cli;\n\n    private static final String table = \"kundera\";\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n    }\n\n    @Before\n    public void setUp() throws Exception\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n        emf = Persistence.createEntityManagerFactory(\"hbase_generated_id\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        cli.dropTable(\"kundera\");\n\n    }\n\n    @Test\n    public void testPersist()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        try\n        {\n            HBaseGeneratedIdDefault idDefault = new HBaseGeneratedIdDefault();\n            idDefault.setName(\"kuldeep\");\n            em.persist(idDefault);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                    + GenerationType.AUTO + \" Strategy not supported by this client :\" + HBaseClient.class.getName(),\n                    e.getMessage());\n        }\n        try\n        {\n            HBaseGeneratedIdStrategyAuto strategyAuto = new HBaseGeneratedIdStrategyAuto();\n            strategyAuto.setName(\"kuldeep\");\n            em.persist(strategyAuto);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                    + GenerationType.AUTO + \" Strategy not supported by this client :\" + HBaseClient.class.getName(),\n                    e.getMessage());\n        }\n\n        try\n        {\n            HBaseGeneratedIdStrategyIdentity strategyIdentity = new HBaseGeneratedIdStrategyIdentity();\n            strategyIdentity.setName(\"kuldeep\");\n            em.persist(strategyIdentity);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.UnsupportedOperationException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.IDENTITY + \" Strategy not supported by this client :\"\n                            + HBaseClient.class.getName(), e.getMessage());\n        }\n\n        HBaseGeneratedIdStrategySequence strategySequence = new HBaseGeneratedIdStrategySequence();\n        strategySequence.setName(\"Kuldeep\");\n        try\n        {\n            em.persist(strategySequence);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + HBaseClient.class.getName(), e.getMessage());\n        }\n\n        try\n        {\n            HBaseGeneratedIdStrategyTable strategyTable1 = new HBaseGeneratedIdStrategyTable();\n            strategyTable1.setName(\"KK\");\n            em.persist(strategyTable1);\n\n            HBaseGeneratedIdStrategyTable strategyTable2 = new HBaseGeneratedIdStrategyTable();\n            strategyTable2.setName(\"vm\");\n            em.persist(strategyTable2);\n\n            HBaseGeneratedIdStrategyTable strategyTable3 = new HBaseGeneratedIdStrategyTable();\n            strategyTable3.setName(\"vs\");\n            em.persist(strategyTable3);\n\n            HBaseGeneratedIdStrategyTable strategyTable = new HBaseGeneratedIdStrategyTable();\n            strategyTable.setName(\"sh\");\n            em.persist(strategyTable);\n\n            List<HBaseGeneratedIdStrategyTable> list = em.createQuery(\"Select c from HBaseGeneratedIdStrategyTable c\")\n                    .getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(4, list.size());\n            for (HBaseGeneratedIdStrategyTable entity : list)\n            {\n                Assert.assertTrue(entity.getId() == 1 || entity.getId() == 51 || entity.getId() == 101\n                        || entity.getId() == 151);\n            }\n\n            em.clear();\n            strategyTable = em.find(HBaseGeneratedIdStrategyTable.class, strategyTable.getId());\n            Assert.assertNotNull(strategyTable);\n            Assert.assertEquals(\"sh\", strategyTable.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n\n        try\n        {\n            HBaseGeneratedIdWithOutSequenceGenerator withOutSequenceGenerator = new HBaseGeneratedIdWithOutSequenceGenerator();\n            withOutSequenceGenerator.setName(\"Kuldeep Kumar\");\n            em.persist(withOutSequenceGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + HBaseClient.class.getName(), e.getMessage());\n        }\n\n        try\n        {\n            HBaseGeneratedIdWithOutTableGenerator withOutTableGenerator = new HBaseGeneratedIdWithOutTableGenerator();\n            withOutTableGenerator.setName(\"Kuldeep Mishra\");\n            em.persist(withOutTableGenerator);\n            List<HBaseGeneratedIdWithOutTableGenerator> list = em.createQuery(\n                    \"Select c from HBaseGeneratedIdWithOutTableGenerator c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"Kuldeep Mishra\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            withOutTableGenerator = em.find(HBaseGeneratedIdWithOutTableGenerator.class, id);\n            Assert.assertNotNull(withOutTableGenerator);\n            Assert.assertEquals(\"Kuldeep Mishra\", withOutTableGenerator.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n        try\n        {\n            HBaseGeneratedIdWithSequenceGenerator withSequenceGenerator = new HBaseGeneratedIdWithSequenceGenerator();\n            withSequenceGenerator.setName(\"Kuldeep Kumar Mishra\");\n            em.persist(withSequenceGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + HBaseClient.class.getName(), e.getMessage());\n        }\n        try\n        {\n          //Test with initValue paramater = 100 allocationsize = 30\n            HBaseGeneratedIdWithTableGenerator withTableGenerator = new HBaseGeneratedIdWithTableGenerator();\n            withTableGenerator.setName(\"Kumar Mishra\");\n            em.persist(withTableGenerator);\n            List<HBaseGeneratedIdWithTableGenerator> list = em.createQuery(\n                    \"Select c from HBaseGeneratedIdWithTableGenerator c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"Kumar Mishra\", list.get(0).getName());\n            Object id = list.get(0).getId();\n\n            Assert.assertEquals(100, id);\n            HBaseGeneratedIdWithTableGenerator withTableGenerator2 = new HBaseGeneratedIdWithTableGenerator();\n            withTableGenerator2.setName(\"Kumar Mishra2\");\n            em.persist(withTableGenerator2);\n            list = em.createQuery(\"Select c from HBaseGeneratedIdWithTableGenerator c\").getResultList();\n            Assert.assertEquals(2, list.size());\n            \n            if(list.get(0).getName().equals(\"Kumar Mishra2\")){\n            \t  id = list.get(0).getId();\n            }\n            else{\n                id = list.get(1).getId();\n            }\n\n            em.clear();\n            withTableGenerator = em.find(HBaseGeneratedIdWithTableGenerator.class, id);\n            Assert.assertNotNull(withTableGenerator);\n            Assert.assertEquals(\"Kumar Mishra2\", withTableGenerator.getName());\n            \n            //Test without initValue paramater allocationsize = 30\n            HBaseGeneratedIdWithTableGeneratorWihtoutInit person1 = new HBaseGeneratedIdWithTableGeneratorWihtoutInit();\n            person1.setName(\"pragalbh\");\n            em.persist(person1);\n\n            HBaseGeneratedIdWithTableGeneratorWihtoutInit person2 = new HBaseGeneratedIdWithTableGeneratorWihtoutInit();\n            person2.setName(\"pragalbh2\");\n            em.persist(person2);\n\n            List<HBaseGeneratedIdWithTableGeneratorWihtoutInit> results = em.createQuery(\n                    \"Select c from HBaseGeneratedIdWithTableGeneratorWihtoutInit c\").getResultList();\n            Assert.assertTrue(results.get(0).getId() == 1 || results.get(0).getId() == 51);\n            Assert.assertTrue(results.get(1).getId() == 1 || results.get(1).getId() == 51);\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdDefault.java",
    "content": "package com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"HBaseGeneratedIdDefault\", schema = \"kundera@hbase_generated_id\")\npublic class HBaseGeneratedIdDefault\n{\n    @Id\n    @GeneratedValue\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdStrategyAuto.java",
    "content": "package com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"HBaseGeneratedIdStrategyAuto\", schema = \"kundera@hbase_generated_id\")\n@TableGenerator(name = \"id_gen\")\npublic class HBaseGeneratedIdStrategyAuto\n{\n    @Id\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.AUTO)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdStrategyIdentity.java",
    "content": "package com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"HBaseGeneratedIdStrategyIdentity\", schema = \"kundera@hbase_generated_id\")\npublic class HBaseGeneratedIdStrategyIdentity\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdStrategySequence.java",
    "content": "package com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"HBaseGeneratedIdStrategySequence\", schema = \"kundera@hbase_generated_id\")\npublic class HBaseGeneratedIdStrategySequence\n{\n    @Id\n    @SequenceGenerator(name = \"seq_gen\")\n    @GeneratedValue(generator = \"seq_gen\", strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdStrategyTable.java",
    "content": "package com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"HBaseGeneratedIdStrategyTable\", schema = \"kundera@hbase_generated_id\")\n@TableGenerator(name = \"table_gen\")\npublic class HBaseGeneratedIdStrategyTable\n{\n\n    @Id\n    @TableGenerator(name = \"table_gen_1\")\n    @GeneratedValue(generator = \"table_gen\", strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdWithOutSequenceGenerator.java",
    "content": "package com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"HBaseGeneratedIdWithOutSequenceGenerator\", schema = \"kundera@hbase_generated_id\")\npublic class HBaseGeneratedIdWithOutSequenceGenerator\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdWithOutTableGenerator.java",
    "content": "package com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"HBaseGeneratedIdWithOutTableGenerator\", schema = \"kundera@hbase_generated_id\")\npublic class HBaseGeneratedIdWithOutTableGenerator\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdWithSequenceGenerator.java",
    "content": "package com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"HBaseGeneratedIdWithSequenceGenerator\", schema = \"kundera@hbase_generated_id\")\npublic class HBaseGeneratedIdWithSequenceGenerator\n{\n    @Id\n    @SequenceGenerator(name = \"id_gen\", allocationSize = 20, initialValue = 80, schema = \"kundera\", sequenceName = \"newSequence\")\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdWithTableGenerator.java",
    "content": "package com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"HBaseGeneratedIdWithTableGenerator\", schema = \"kundera@hbase_generated_id\")\npublic class HBaseGeneratedIdWithTableGenerator\n{\n\n    @Id\n    @TableGenerator(name = \"id_gen\", allocationSize = 30, initialValue = 100, schema = \"kundera\", table = \"kunderahbase\", pkColumnName = \"sequence\", valueColumnName = \"sequenceValue\", pkColumnValue = \"kk\")\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdWithTableGeneratorWihtoutInit.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n/**\n * @author Pragalbh Garg\n *\n */\n@Entity\n@Table(name = \"HBaseGeneratedIdWithTableGeneratorWithoutInit\", schema = \"kundera@hbase_generated_id\")\npublic class HBaseGeneratedIdWithTableGeneratorWihtoutInit\n{\n\n    @Id\n    @TableGenerator(name = \"id_gen_2\")\n    @GeneratedValue(generator = \"id_gen_2\", strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/junits/HBaseCli.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.junits;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.MalformedURLException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\n\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.fs.FileUtil;\nimport org.apache.hadoop.hbase.HBaseConfiguration;\nimport org.apache.hadoop.hbase.HBaseTestingUtility;\nimport org.apache.hadoop.hbase.HColumnDescriptor;\nimport org.apache.hadoop.hbase.HConstants;\nimport org.apache.hadoop.hbase.InvalidFamilyOperationException;\nimport org.apache.hadoop.hbase.client.HTablePool;\nimport org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Embedded HBase client.\n * \n * @author vivek.mishra\n * \n */\npublic class HBaseCli\n{\n    /** The utility. */\n    public static HBaseTestingUtility utility;\n\n    private static final Logger logger = LoggerFactory.getLogger(HBaseCli.class);\n\n    private static File zkDir;\n\n    private static File masterDir;\n\n    private MiniZooKeeperCluster zkCluster;\n\n    private HTablePool hTablePool;\n\n    public static void main(String arg[])\n    {\n        HBaseCli cli = new HBaseCli();\n        cli.startCluster();\n    }\n\n    public void startCluster()\n    {\n        File workingDirectory = new File(\"./\");\n        Configuration conf = new Configuration();\n        System.setProperty(\"test.build.data\", workingDirectory.getAbsolutePath());\n        conf.set(\"test.build.data\", new File(workingDirectory, \"zookeeper\").getAbsolutePath());\n        conf.set(\"fs.default.name\", \"file:///\");\n        conf.set(\"zookeeper.session.timeout\", \"180000\");\n        conf.set(\"hbase.zookeeper.peerport\", \"2888\");\n        conf.set(\"hbase.zookeeper.property.clientPort\", \"2181\");\n        // conf.set(\"dfs.datanode.data.dir.perm\", \"700\");\n        try\n        {\n            masterDir = new File(workingDirectory, \"hbase\");\n            conf.set(HConstants.HBASE_DIR, masterDir.toURI().toURL().toString());\n        }\n        catch (MalformedURLException e1)\n        {\n            logger.error(e1.getMessage());\n        }\n\n        Configuration hbaseConf = HBaseConfiguration.create(conf);\n        utility = new HBaseTestingUtility(hbaseConf);\n\n        // Change permission for dfs.data.dir, please refer\n        // https://issues.apache.org/jira/browse/HBASE-5711 for more details.\n        try\n        {\n            Process process = Runtime.getRuntime().exec(\"/bin/sh -c umask\");\n            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));\n            int rc = process.waitFor();\n            if (rc == 0)\n            {\n                String umask = br.readLine();\n\n                int umaskBits = Integer.parseInt(umask, 8);\n                int permBits = 0777 & ~umaskBits;\n                String perms = Integer.toString(permBits, 8);\n\n                logger.info(\"Setting dfs.datanode.data.dir.perm to \" + perms);\n                utility.getConfiguration().set(\"dfs.datanode.data.dir.perm\", perms);\n            }\n            else\n            {\n                logger.warn(\"Failed running umask command in a shell, nonzero return value\");\n            }\n        }\n        catch (Exception e)\n        {\n            // ignore errors, we might not be running on POSIX, or \"sh\" might\n            // not be on the path\n            logger.warn(\"Couldn't get umask\", e);\n        }\n        if (!checkIfServerRunning())\n        {\n            hTablePool = new HTablePool(conf, 1);\n            try\n            {\n                zkCluster = new MiniZooKeeperCluster(conf);\n                zkCluster.setDefaultClientPort(2181);\n                zkCluster.setTickTime(18000);\n                // utility.setupClusterTestDir();\n                zkDir = new File(utility.getDataTestDir().toString()).getAbsoluteFile();\n\n                zkCluster.startup(zkDir);\n                utility.setZkCluster(zkCluster);\n                utility.startMiniCluster();\n                utility.getHBaseCluster().startMaster();\n            }\n            catch (Exception e)\n            {\n                \n                logger.error(e.getMessage());\n                throw new RuntimeException(e);\n            }\n        }\n    }\n\n    /**\n     * Creates the table.\n     * \n     * @param tableName\n     *            the table name\n     */\n    public void createTable(String tableName, String columnFamily)\n    {\n        try\n        {\n            if (!utility.getHBaseAdmin().tableExists(tableName))\n            {\n                utility.createTable(tableName.getBytes(), columnFamily.getBytes());\n                if (utility.getHBaseAdmin().isTableDisabled(tableName))\n                {\n                    utility.getHBaseAdmin().enableTable(tableName);\n                }\n            }\n            else\n            {\n                logger.info(\"Table:\" + tableName + \" already exist:\");\n            }\n        }\n        catch (IOException e)\n        {\n            logger.error(e.getMessage());\n        }\n\n    }\n\n    public void createTable(byte[] tableName, byte[][] families)\n    {\n        try\n        {\n            utility.createTable(tableName, families);\n        }\n        catch (IOException e)\n        {\n\n        }\n    }\n\n    /**\n     * Adds the column family.\n     * \n     * @param tableName\n     *            the table name\n     * @param columnFamily\n     *            the column family\n     */\n    public void addColumnFamily(String tableName, String columnFamily)\n    {\n        try\n        {\n            utility.getHBaseAdmin().disableTable(tableName);\n            utility.getHBaseAdmin().addColumn(tableName, new HColumnDescriptor(columnFamily));\n            utility.getHBaseAdmin().enableTable(tableName);\n            while (utility.getHBaseAdmin().isTableEnabled(tableName))\n            {\n                return;\n            }\n\n        }\n        catch (InvalidFamilyOperationException ife)\n        {\n            logger.info(\"Column family:\" + columnFamily + \" already exist!\", ife);\n        }\n        catch (IOException e)\n        {\n            logger.error(\"\", e);\n        }\n    }\n\n    public void dropTable(String tableName)\n    {\n        try\n        {\n            utility.getHBaseAdmin().disableTable(tableName);\n            utility.getHBaseAdmin().deleteTable(tableName);\n        }\n        catch (IOException e)\n        {\n            logger.error(e.getMessage());\n        }\n    }\n\n    /**\n     * Destroys cluster.\n     */\n    public static void stopCluster(String... tableName)\n    {\n        // try\n        // {\n        // if (utility != null)\n        // {\n        // // utility.getMiniHBaseCluster().shutdown();\n        // // File workingDirectory = new File(\"./\");\n        // // utility.closeRegion(\"localhost\");\n        // utility.cleanupTestDir();\n        // // utility.cleanupTestDir(dir.getAbsolutePath());\n        // // ZooKeeperServer server = new ZooKeeperServer(zkDir, zkDir,\n        // // 2000);\n        // // ZooKeeperServerBean bean = new ZooKeeperServerBean(server);\n        // // String path = (String)this.makeFullPath(null,bean);\n        //\n        // // MBeanS\n        // // MBeanRegistry.getInstance().unregister(bean);\n        // // MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();\n        // // mbs.unregisterMBean(makeObjectName(path,bean));\n        // // utility.getHbaseCluster().shutdown();\n        // utility.shutdownMiniCluster();\n        // FileUtil.fullyDelete(zkDir);\n        // FileUtil.fullyDelete(masterDir);\n        // utility = null;\n        // isStarted = false;\n        // }\n        // }\n        // catch (IOException e)\n        // {\n        // logger.error(e.getMessage());\n        // }\n        // catch (NullPointerException e)\n        // {\n        // // TODO Auto-generated catch block\n        // \n        // }\n        // catch (Exception e)\n        // {\n        // // TODO Auto-generated catch block\n        // \n        // }\n        //\n    }\n\n    public static void cleanUp()\n    {\n        try\n        {\n            if (utility != null)\n            {\n                // utility.getMiniHBaseCluster().shutdown();\n                // File workingDirectory = new File(\"./\");\n                // utility.closeRegion(\"localhost\");\n                utility.cleanupTestDir();\n                // utility.cleanupTestDir(dir.getAbsolutePath());\n                // ZooKeeperServer server = new ZooKeeperServer(zkDir, zkDir,\n                // 2000);\n                // ZooKeeperServerBean bean = new ZooKeeperServerBean(server);\n                // String path = (String)this.makeFullPath(null,bean);\n\n                // MBeanS\n                // MBeanRegistry.getInstance().unregister(bean);\n                // MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();\n                // mbs.unregisterMBean(makeObjectName(path,bean));\n                // utility.getHbaseCluster().shutdown();\n                utility.shutdownMiniCluster();\n                FileUtil.fullyDelete(zkDir);\n                FileUtil.fullyDelete(masterDir);\n                utility = null;\n            }\n        }\n        catch (IOException e)\n        {\n            logger.error(e.getMessage());\n        }\n        catch (NullPointerException e)\n        {\n            // TODO Auto-generated catch block\n            \n        }\n        catch (Exception e)\n        {\n            // TODO Auto-generated catch block\n            \n        }\n\n    }\n\n    /**\n     * Check if server running.\n     * \n     * @return true, if successful\n     */\n    private static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 2181);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/query/LikeComparatorFactoryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.query;\n\nimport static com.impetus.client.hbase.query.LikeComparatorFactory.likeToRegex;\nimport static org.junit.Assert.assertEquals;\n\nimport org.junit.Test;\n\n/**\n * The Class LikeComparatorFactoryTest.\n */\npublic class LikeComparatorFactoryTest\n{\n\n    /**\n     * Like to regex conversion.\n     */\n    @Test\n    public void likeToRegexConversion()\n    {\n        assertEquals(\"as is\", likeToRegex(\"as is\"));\n        assertEquals(\"last percent .*\", likeToRegex(\"last percent %\"));\n        assertEquals(\"middle.*percent\", likeToRegex(\"middle%percent\"));\n        assertEquals(\".*first percent\", likeToRegex(\"%first percent\"));\n        assertEquals(\"%\", likeToRegex(\"%%\"));\n        assertEquals(\"%.*\", likeToRegex(\"%%%\"));\n        assertEquals(\"\\\\\" + \"{\" + \"\\\\\" + \"[\", likeToRegex(\"{[\"));\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBaseEntityAddressUni1To1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.hbase.schemaManager;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class HbaseEntityAddressUni1To1.\n */\n@Entity\n@Table(name = \"HbaseEntityAddressUni1To1\", schema = \"KunderaHbaseExamples@hbase\")\npublic class HBaseEntityAddressUni1To1\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBaseEntityAddressUni1To1PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.schemaManager;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class HbaseEntityAddressUni1To1PK.\n */\n@Entity\n@Table(name = \"HbaseEntityAddressUni1To1PK\", schema = \"KunderaHbaseExamples@hbase\")\npublic class HBaseEntityAddressUni1To1PK\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The address id. */\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBaseEntityAddressUni1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.schemaManager;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class HbaseEntityAddressUni1ToM.\n */\n@Entity\n@Table(name = \"HbaseEntityAddressUni1ToM\", schema = \"KunderaHbaseExamples@hbase\")\npublic class HBaseEntityAddressUni1ToM\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBaseEntityAddressUniMTo1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.schemaManager;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class HbaseEntityAddressUniMTo1.\n */\n@Entity\n@Table(name = \"HbaseEntityAddressUniMTo1\", schema = \"KunderaHbaseExamples@hbase\")\npublic class HBaseEntityAddressUniMTo1\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBaseEntityPersonUni1To1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.schemaManager;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class HbaseEntityPersonUni1To1.\n */\n@Entity\n@Table(name = \"HbaseEntityPersonUni1To1\", schema = \"KunderaHbaseExamples@hbase\")\npublic class HBaseEntityPersonUni1To1\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The personal data. */\n    @Embedded\n    private HBasePersonalData personalData;\n\n    /** The address. */\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HBaseEntityAddressUni1To1 address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public HBasePersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(HBasePersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public HBaseEntityAddressUni1To1 getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the address to set\n     */\n    public void setAddress(HBaseEntityAddressUni1To1 address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBaseEntityPersonUni1To1PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.schemaManager;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\nimport javax.persistence.Table;\n\n/**\n * The Class HbaseEntityPersonUni1To1PK.\n */\n@Entity\n@Table(name = \"HbaseEntityPersonUni1To1PK\", schema = \"KunderaHbaseExamples@hbase\")\npublic class HBaseEntityPersonUni1To1PK\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The personal data. */\n    @Embedded\n    HBasePersonalData personalData;\n\n    /** The address. */\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)\n    @PrimaryKeyJoinColumn\n    private HBaseEntityAddressUni1To1PK address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public HBasePersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(HBasePersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public HBaseEntityAddressUni1To1PK getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the address to set\n     */\n    public void setAddress(HBaseEntityAddressUni1To1PK address)\n    {\n        this.address = address;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBaseEntityPersonUni1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.schemaManager;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * The Class HbaseEntityPersonUni1ToM.\n */\n@Entity\n@Table(name = \"HbaseEntityPersonUni1ToM\", schema = \"KunderaHbaseExamples@hbase\")\npublic class HBaseEntityPersonUni1ToM\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The personal data. */\n    @Embedded\n    private HBasePersonalData personalData;\n\n    /** The addresses. */\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<HBaseEntityAddressUni1ToM> addresses;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public HBasePersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(HBasePersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the addresses.\n     * \n     * @return the addresses\n     */\n    public Set<HBaseEntityAddressUni1ToM> getAddresses()\n    {\n        return addresses;\n    }\n\n    /**\n     * Sets the addresses.\n     * \n     * @param addresses\n     *            the addresses to set\n     */\n    public void setAddresses(Set<HBaseEntityAddressUni1ToM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBaseEntityPersonUniMto1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.schemaManager;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class HbaseEntityPersonUniMto1.\n */\n@Entity\n@Table(name = \"HbaseEntityPersonUniMto1\", schema = \"KunderaHbaseExamples@hbase\")\npublic class HBaseEntityPersonUniMto1\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The personal data. */\n    @Embedded\n    private HBasePersonalData personalData;\n\n    /** The address. */\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HBaseEntityAddressUniMTo1 address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public HBasePersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(HBasePersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public HBaseEntityAddressUniMTo1 getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the address to set\n     */\n    public void setAddress(HBaseEntityAddressUniMTo1 address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBaseEntitySimple.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.hbase.schemaManager;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class HbaseEntitySimple.\n */\n@Entity\n@Table(name = \"HbaseEntitySimple\"/*, schema = \"KunderaHbaseTests@HBaseSchemaOperationTest\"*/)\npublic class HBaseEntitySimple\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBaseEntitySuper.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.schemaManager;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class HbaseEntitySuper.\n */\n@Entity\n@Table(name = \"HbaseEntitySuper\", schema = \"KunderaHbaseExamples@hbase\")\npublic class HBaseEntitySuper\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The personal data. */\n    @Embedded\n    private HBasePersonalData personalData;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the personal data.\n     * \n     * @return the personalData\n     */\n    public HBasePersonalData getPersonalData()\n    {\n        return personalData;\n    }\n\n    /**\n     * Sets the personal data.\n     * \n     * @param personalData\n     *            the personalData to set\n     */\n    public void setPersonalData(HBasePersonalData personalData)\n    {\n        this.personalData = personalData;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBaseGeneratedIdSchemaTest.java",
    "content": "package com.impetus.client.hbase.schemaManager;\n\nimport java.io.IOException;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.hadoop.hbase.HTableDescriptor;\nimport org.apache.hadoop.hbase.client.HBaseAdmin;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\n\npublic class HBaseGeneratedIdSchemaTest\n{\n    private static final String table = \"kundera\";\n\n    private EntityManagerFactory emf;\n\n    private HBaseCli cli;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n    }\n\n    @Before\n    public void setUp() throws Exception\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n        emf = Persistence.createEntityManagerFactory(\"hbase_generated_id\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        cli.dropTable(\"kundera\");\n    }\n\n    @Test\n    public void test()\n    {\n        try\n        {\n            HBaseAdmin admin = HBaseCli.utility.getHBaseAdmin();\n            Assert.assertTrue(admin.isTableAvailable(table.getBytes()));\n            HTableDescriptor descriptor = admin.getTableDescriptor(table.getBytes());\n            Assert.assertNotNull(descriptor.getFamily(\"HBaseGeneratedIdDefault\".getBytes()));\n            Assert.assertNotNull(descriptor.getFamily(\"HBaseGeneratedIdStrategyAuto\".getBytes()));\n            Assert.assertNotNull(descriptor.getFamily(\"HBaseGeneratedIdStrategyIdentity\".getBytes()));\n            Assert.assertNotNull(descriptor.getFamily(\"HBaseGeneratedIdStrategySequence\".getBytes()));\n            Assert.assertNotNull(descriptor.getFamily(\"HBaseGeneratedIdStrategyTable\".getBytes()));\n            Assert.assertNotNull(descriptor.getFamily(\"HBaseGeneratedIdWithOutSequenceGenerator\".getBytes()));\n            Assert.assertNotNull(descriptor.getFamily(\"HBaseGeneratedIdWithOutTableGenerator\".getBytes()));\n            Assert.assertNotNull(descriptor.getFamily(\"HBaseGeneratedIdWithSequenceGenerator\".getBytes()));\n            Assert.assertNotNull(descriptor.getFamily(\"HBaseGeneratedIdWithTableGenerator\".getBytes()));\n            Assert.assertNotNull(descriptor.getFamily(\"kunderahbase\".getBytes()));\n            Assert.assertNotNull(descriptor.getFamily(\"kundera_sequences\".getBytes()));\n        }\n        catch (IOException e)\n        {\n            Assert.fail();\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBasePersonalData.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\n\r\npackage com.impetus.client.hbase.schemaManager;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\n/**\r\n * The Class HbasePersonalData.\r\n */\r\n@Embeddable\r\npublic class HBasePersonalData\r\n{\r\n\r\n    /** The website. */\r\n    @Column(name = \"p_website\")\r\n    private String website;\r\n\r\n    /** The email. */\r\n    @Column(name = \"p_email\")\r\n    private String email;\r\n\r\n    /** The yahoo id. */\r\n    @Column(name = \"p_yahoo_id\")\r\n    private String yahooId;\r\n\r\n    /**\r\n     * Instantiates a new hbase personal data.\r\n     */\r\n    public HBasePersonalData()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new hbase personal data.\r\n     * \r\n     * @param website\r\n     *            the website\r\n     * @param email\r\n     *            the email\r\n     * @param yahooId\r\n     *            the yahoo id\r\n     */\r\n    public HBasePersonalData(String website, String email, String yahooId)\r\n    {\r\n        this.website = website;\r\n        this.email = email;\r\n        this.yahooId = yahooId;\r\n    }\r\n\r\n    /**\r\n     * Gets the website.\r\n     * \r\n     * @return the website\r\n     */\r\n    public String getWebsite()\r\n    {\r\n        return website;\r\n    }\r\n\r\n    /**\r\n     * Sets the website.\r\n     * \r\n     * @param website\r\n     *            the new website\r\n     */\r\n    public void setWebsite(String website)\r\n    {\r\n        this.website = website;\r\n    }\r\n\r\n    /**\r\n     * Gets the email.\r\n     * \r\n     * @return the email\r\n     */\r\n    public String getEmail()\r\n    {\r\n        return email;\r\n    }\r\n\r\n    /**\r\n     * Sets the email.\r\n     * \r\n     * @param email\r\n     *            the email to set\r\n     */\r\n    public void setEmail(String email)\r\n    {\r\n        this.email = email;\r\n    }\r\n\r\n    /**\r\n     * Gets the yahoo id.\r\n     * \r\n     * @return the yahoo id\r\n     */\r\n    public String getYahooId()\r\n    {\r\n        return yahooId;\r\n    }\r\n\r\n    /**\r\n     * Sets the yahoo id.\r\n     * \r\n     * @param yahooId\r\n     *            the new yahoo id\r\n     */\r\n    public void setYahooId(String yahooId)\r\n    {\r\n        this.yahooId = yahooId;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBaseSchemaManagerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.schemaManager;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.hadoop.hbase.client.HBaseAdmin;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.PersistenceProperties;\n\n/**\n * HbaseSchemaManagerTest class test the auto creation schema property in hbase\n * data store.\n * \n * @author Kuldeep.Kumar\n * \n */\npublic class HBaseSchemaManagerTest\n{\n    private final boolean useLucene = true;\n\n    /** The admin. */\n    private static HBaseAdmin admin;\n\n    private HBaseCli cli;\n\n    private String persistenceUnit = \"hbase\";\n\n    /** The Constant logger. */\n    private static final Logger logger = LoggerFactory.getLogger(HBaseSchemaManagerTest.class);\n\n    private static final String TABLE = \"KunderaHbaseExamples\";\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        cli = new HBaseCli();\n        logger.info(\"starting server\");\n        cli.startCluster();\n        if (admin == null)\n        {\n            admin = cli.utility.getHBaseAdmin();\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        cli.stopCluster();\n    }\n\n    /**\n     * Test schema operation.\n     */\n    @Test\n    public void testSchemaOperation()\n    {\n        try\n        {\n            Map propertyMap = new HashMap();\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n            EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, propertyMap);\n            Assert.assertTrue(admin.isTableAvailable(TABLE));\n            Assert.assertFalse(admin.isTableAvailable(\"HbaseEntitySimple\"));\n            Assert.assertFalse(admin.isTableAvailable(\"HbaseEntitySuper\"));\n            Assert.assertFalse(admin.isTableAvailable(\"HbaseEntityAddressUni1To1\"));\n            Assert.assertFalse(admin.isTableAvailable(\"HbaseEntityAddressUniMTo1\"));\n            Assert.assertFalse(admin.isTableAvailable(\"HbaseEntityAddressUni1ToM\"));\n            Assert.assertFalse(admin.isTableAvailable(\"HbaseEntityPersonUni1ToM\"));\n            Assert.assertFalse(admin.isTableAvailable(\"HbaseEntityPersonUni1To1\"));\n            Assert.assertFalse(admin.isTableAvailable(\"HbaseEntityPersonUniMto1\"));\n            Assert.assertFalse(admin.isTableAvailable(\"HbaseEntityAddressUni1To1PK\"));\n            Assert.assertFalse(admin.isTableAvailable(\"HbaseEntityPersonUni1To1PK\"));\n        }\n        catch (IOException e)\n        {\n            Assert.fail(\"Failed, Caused by:\" + e.getMessage());\n        }\n        catch (Exception e)\n        {\n            Assert.fail(\"Failed, Caused by:\" + e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/schemaManager/HBaseSchemaOperationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.schemaManager;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.hadoop.hbase.HColumnDescriptor;\nimport org.apache.hadoop.hbase.HTableDescriptor;\nimport org.apache.hadoop.hbase.client.HBaseAdmin;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.HBaseClientFactory;\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.ClientResolver;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\n\n/**\n * @author Kuldeep.Kumar\n * \n */\npublic class HBaseSchemaOperationTest\n{\n    private static final String HBASE_ENTITY_SIMPLE = \"HbaseEntitySimple\";\n\n    private static final String TABLE = \"KunderaHbaseTests\";\n\n    private static HBaseAdmin admin;\n\n    private static HBaseCli cli;\n\n    private String persistenceUnit = \"HBaseSchemaOperationTest\";\n\n    private Map propertyMap = new HashMap();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        cli = new HBaseCli();\n        cli.startCluster();\n        if (admin == null)\n        {\n            admin = HBaseCli.utility.getHBaseAdmin();\n        }\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        cli.dropTable(TABLE);\n        HBaseCli.stopCluster();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    @Test\n    public void testCreate() throws IOException\n    {\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, propertyMap);\n        Assert.assertTrue(admin.isTableAvailable(TABLE));\n\n        HTableDescriptor descriptor = admin.getTableDescriptor(TABLE.getBytes());\n        Assert.assertNotNull(descriptor.getFamilies());\n        Assert.assertEquals(1, descriptor.getFamilies().size());\n        for (HColumnDescriptor columnDescriptor : descriptor.getFamilies())\n        {\n            Assert.assertNotNull(columnDescriptor);\n            Assert.assertNotNull(columnDescriptor.getNameAsString());\n            Assert.assertEquals(HBASE_ENTITY_SIMPLE, columnDescriptor.getNameAsString());\n        }\n\n        admin.disableTable(TABLE);\n        admin.deleteTable(TABLE);\n        Assert.assertFalse(admin.isTableAvailable(TABLE));\n    }\n\n    @Test\n    public void testCreatedrop() throws IOException\n    {\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create-drop\");\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, propertyMap);\n        // schemaManager = new\n        // HBaseSchemaManager(HBaseClientFactory.class.getName(), null);\n        // schemaManager.exportSchema();\n        Assert.assertTrue(admin.isTableAvailable(TABLE));\n\n        HTableDescriptor descriptor = admin.getTableDescriptor(TABLE.getBytes());\n        Assert.assertNotNull(descriptor.getFamilies());\n        Assert.assertEquals(1, descriptor.getFamilies().size());\n        for (HColumnDescriptor columnDescriptor : descriptor.getFamilies())\n        {\n            Assert.assertNotNull(columnDescriptor);\n            Assert.assertNotNull(columnDescriptor.getNameAsString());\n            Assert.assertEquals(HBASE_ENTITY_SIMPLE, columnDescriptor.getNameAsString());\n        }\n\n        HBaseClientFactory clientFactory = (HBaseClientFactory) ClientResolver.getClientFactory(persistenceUnit);\n        clientFactory.getSchemaManager(null).dropSchema();\n        Assert.assertTrue(admin.isTableAvailable(TABLE));\n        Assert.assertNull(admin.getTableDescriptor(TABLE.getBytes()).getFamily(HBASE_ENTITY_SIMPLE.getBytes()));\n    }\n\n    @Test\n    public void testUpdate() throws IOException\n    {\n        HTableDescriptor descriptor1 = new HTableDescriptor(TABLE);\n        HColumnDescriptor columnDescriptor1 = new HColumnDescriptor(\"PERSON_NAME\");\n        descriptor1.addFamily(columnDescriptor1);\n        if (admin.isTableAvailable(TABLE))\n        {\n            admin.disableTable(TABLE);\n            admin.deleteTable(TABLE);\n        }\n        admin.createTable(descriptor1);\n        Assert.assertTrue(admin.isTableAvailable(TABLE));\n        HTableDescriptor descriptor2 = admin.getTableDescriptor(TABLE.getBytes());\n        Assert.assertNotNull(descriptor2.getFamilies());\n        Assert.assertEquals(1, descriptor2.getFamilies().size());\n        for (HColumnDescriptor columnDescriptor : descriptor2.getFamilies())\n        {\n            Assert.assertNotNull(columnDescriptor);\n            Assert.assertNotNull(columnDescriptor.getNameAsString());\n            Assert.assertEquals(\"PERSON_NAME\", columnDescriptor.getNameAsString());\n        }\n\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"update\");\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, propertyMap);\n        // schemaManager = new\n        // HBaseSchemaManager(HBaseClientFactory.class.getName(), null);\n        // schemaManager.exportSchema();\n\n        Assert.assertTrue(admin.isTableAvailable(TABLE));\n\n        HTableDescriptor descriptor = admin.getTableDescriptor(TABLE.getBytes());\n        Assert.assertNotNull(descriptor.getFamilies());\n        Assert.assertEquals(2, descriptor.getFamilies().size());\n        List<String> columns = new ArrayList<String>();\n        columns.add(HBASE_ENTITY_SIMPLE);\n        columns.add(\"PERSON_NAME\");\n        for (HColumnDescriptor columnDescriptor : descriptor.getFamilies())\n        {\n            Assert.assertNotNull(columnDescriptor);\n            Assert.assertNotNull(columnDescriptor.getNameAsString());\n            Assert.assertTrue(columns.contains(columnDescriptor.getNameAsString()));\n        }\n\n        if (!admin.isTableDisabled(TABLE))\n        {\n            admin.disableTable(TABLE);\n        }\n\n        admin.deleteTable(TABLE);\n        Assert.assertFalse(admin.isTableAvailable(TABLE));\n    }\n\n    @Test\n    public void testValidate() throws IOException\n    {\n        HTableDescriptor descriptor1 = new HTableDescriptor(TABLE);\n        HColumnDescriptor columnDescriptor1 = new HColumnDescriptor(HBASE_ENTITY_SIMPLE);\n        descriptor1.addFamily(columnDescriptor1);\n        if (admin.isTableAvailable(TABLE))\n        {\n            admin.disableTable(TABLE);\n            admin.deleteTable(TABLE);\n        }\n        admin.createTable(descriptor1);\n\n        Assert.assertTrue(admin.isTableAvailable(TABLE));\n        HTableDescriptor descriptor2 = admin.getTableDescriptor(TABLE.getBytes());\n        Assert.assertNotNull(descriptor2.getFamilies());\n        Assert.assertEquals(1, descriptor2.getFamilies().size());\n        List<String> columns = new ArrayList<String>();\n        columns.add(HBASE_ENTITY_SIMPLE);\n        for (HColumnDescriptor columnDescriptor : descriptor2.getFamilies())\n        {\n            Assert.assertNotNull(columnDescriptor);\n            Assert.assertNotNull(columnDescriptor.getNameAsString());\n            Assert.assertTrue(columns.contains(columnDescriptor.getNameAsString()));\n        }\n\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"validate\");\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, propertyMap);\n        // schemaManager = new\n        // HBaseSchemaManager(HBaseClientFactory.class.getName(), null);\n        // schemaManager.exportSchema();\n        if (!admin.isTableDisabled(TABLE))\n        {\n            admin.disableTable(TABLE);\n        }\n        admin.deleteTable(TABLE);\n        Assert.assertFalse(admin.isTableAvailable(TABLE));\n    }\n\n    @Test\n    public void testValidateInValid() throws IOException\n    {\n        try\n        {\n            HTableDescriptor descriptor1 = new HTableDescriptor(TABLE);\n            HColumnDescriptor columnDescriptor1 = new HColumnDescriptor(HBASE_ENTITY_SIMPLE);\n            descriptor1.addFamily(columnDescriptor1);\n            if (admin.isTableAvailable(TABLE))\n            {\n                admin.disableTable(TABLE);\n                admin.deleteTable(TABLE);\n            }\n            admin.createTable(descriptor1);\n            Assert.assertTrue(admin.isTableAvailable(TABLE));\n            HTableDescriptor descriptor2 = admin.getTableDescriptor(TABLE.getBytes());\n            Assert.assertNotNull(descriptor2.getFamilies());\n            Assert.assertEquals(1, descriptor2.getFamilies().size());\n            for (HColumnDescriptor columnDescriptor : descriptor2.getFamilies())\n            {\n                Assert.assertNotNull(columnDescriptor);\n                Assert.assertNotNull(columnDescriptor.getNameAsString());\n                Assert.assertEquals(HBASE_ENTITY_SIMPLE, columnDescriptor.getNameAsString());\n            }\n\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"validate\");\n            EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, propertyMap);\n            // schemaManager = new\n            // HBaseSchemaManager(HBaseClientFactory.class.getName(), null);\n            // schemaManager.exportSchema();\n        }\n        catch (SchemaGenerationException sgex)\n        {\n            List<String> errors = new ArrayList<String>();\n            errors.add(\"column \" + \"AGE\" + \" does not exist in table \" + TABLE + \"\");\n            errors.add(\"column \" + \"PERSON_NAME\" + \" does not exist in table \" + TABLE + \"\");\n            Assert.assertTrue(errors.contains(sgex.getMessage()));\n\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/transaction/HBaseTransactionTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.transaction;\n\nimport java.io.IOException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport javax.xml.registry.InvalidRequestException;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.config.HBaseUser;\n/**\n * @author Chhavi Gangwal\n * \n */\npublic class HBaseTransactionTest{\n\t\n  \n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"XmlPropertyTest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(HBaseTransactionTest.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * On rollback.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onRollback() throws Exception\n    {\n        em.getTransaction().begin();\n\n        Object p1 = prepareData(\"test1\", 10);\n        Object p2 = prepareData(\"test2\", 20);\n        Object p3 = prepareData(\"test3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        // roll back.\n        em.getTransaction().rollback();\n        HBaseUser p = em.find(HBaseUser.class, \"test1\");\n        Assert.assertNull(p);\n\n        // on commit.\n\n        // Still no record should be flushed as already rollback!\n        p = em.find(HBaseUser.class, \"test1\");\n        Assert.assertNull(p);\n    }\n\n    /**\n     * On commit.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onCommit() throws Exception\n    {\n        // em.setFlushMode(FlushModeType.COMMIT);\n\n        em.getTransaction().begin();\n\n        Object p1 = prepareData(\"test1\", 10);\n        Object p2 = prepareData(\"test2\", 20);\n        Object p3 = prepareData(\"test3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        // on commit.\n        em.getTransaction().commit();\n\n        em.getTransaction().begin();\n\n        HBaseUser p = em.find(HBaseUser.class, \"test1\");\n        Assert.assertNotNull(p);\n\n        ((HBaseUser) p2).setAddress(\"rollback\");\n        em.merge(p2);\n\n        // roll back, should roll back person name for p2!\n        em.getTransaction().rollback();\n\n        p = em.find(HBaseUser.class, \"test1\");\n        Assert.assertNotNull(p);\n\n        p = em.find(HBaseUser.class, \"test2\");\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"test2\", p.getName());\n        Assert.assertNotSame(\"rollback\", p.getAddress());\n\n        em.getTransaction().begin();\n        em.merge(p2);\n        em.getTransaction().commit();\n        \n        p = em.find(HBaseUser.class, \"test2\");\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"test2\", p.getName());\n        Assert.assertEquals(\"rollback\", p.getAddress());\n    }\n\n    /**\n     * Rollback on error.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void rollbackOnError() throws Exception\n    {\n        try\n        {\n            em.getTransaction().begin();\n            Object p1 = prepareData(\"test1\", 10);\n            Object p2 = prepareData(\"test2\", 20);\n            Object p3 = prepareData(\"test3\", 15);\n            em.persist(p1);\n            em.persist(p2);\n            em.persist(p3);\n            em.merge(null);\n            em.getTransaction().commit();\n        }\n        catch (Exception ex)\n        {\n            em.clear();\n            HBaseUser user = em.find(HBaseUser.class, \"test1\");\n            Assert.assertNull(user);\n            user = em.find(HBaseUser.class, \"test2\");\n            Assert.assertNull(user);\n            user = em.find(HBaseUser.class, \"test3\");\n            Assert.assertNull(user);\n        }\n    }\n\n\n    /**\n     * Roll back with multi transactions.\n     */\n    @Test\n    public void rollBackWithMultiTransactions()\n    {\n        EntityManager em1 = emf.createEntityManager();\n        // em1.setFlushMode(FlushModeType.COMMIT);\n\n        // Begin transaction.\n        em1.getTransaction().begin();\n        Object p1 = prepareData(\"test11\", 10);\n        em1.persist(p1);\n\n        // commit p1.\n        em1.getTransaction().commit();\n\n        // another em instance\n        EntityManager em2 = emf.createEntityManager();\n        // em2.setFlushMode(FlushModeType.COMMIT);\n\n        // begin transaction.\n        HBaseUser found = em2.find(HBaseUser.class, \"test11\");\n\n        em2.getTransaction().begin();\n        found.setAddress(\"merged\");\n        em2.merge(found);\n\n        // // commit p1 after modification.\n        em2.getTransaction().commit();\n\n        // open another entity manager.\n        EntityManager em3 = emf.createEntityManager();\n        found = em3.find(HBaseUser.class, \"test11\");\n        Assert.assertEquals(\"merged\", found.getAddress());\n        found.setAddress(\"lastemerge\");\n        try\n        {\n            em3.merge(found);\n            em3.merge(null);\n        }\n        catch (Exception ex)\n        {\n            HBaseUser finalFound = em2.find(HBaseUser.class, \"test11\");\n            Assert.assertNotNull(finalFound);\n            Assert.assertEquals(\"merged\", finalFound.getAddress());\n        }\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param rowKey\n     *            the row key\n     * @param age\n     *            the age\n     * @return the person\n     */\n    private HBaseUser prepareData(String id,  int age){\n    \t\n        HBaseUser user = new HBaseUser();\n        user.setName(id);\n        user.setAge(age);\n        user.setAddress(\"D-40\");\n        return user;\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception{\n    \t\n        EntityManager em = emf.createEntityManager();\n\n        // Delete by query.\n        String deleteQuery = \"Delete from HBaseUser p\";\n        Query query = em.createQuery(deleteQuery);\n        int updateCount = query.executeUpdate();\n\n        em.close();\n        emf.close();\n        emf = null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/validator/BookEntity.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.hbase.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Devender Yadav\n * \n */\n@Entity\n@Table(name = \"BOOK_ENTITY\", schema = \"KunderaExamples@hbaseTest\")\npublic class BookEntity\n{\n\n    @Id\n    @Column(name = \"ID\")\n    private int bookId;\n\n    @Column(name = \"TITLE\")\n    private String title;\n\n    @Column(name = \"AUTHOR\")\n    private String author;\n\n    @Column(name = \"PAGES\")\n    private int pages;\n\n    protected BookEntity()\n    {\n    }\n\n    public int getBookId()\n    {\n        return bookId;\n    }\n\n    public void setBookId(int bookId)\n    {\n        this.bookId = bookId;\n    }\n\n    public String getTitle()\n    {\n        return title;\n    }\n\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    public int getPages()\n    {\n        return pages;\n    }\n\n    public void setPages(int pages)\n    {\n        this.pages = pages;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/validator/ConstructorValidationTest.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.hbase.validator;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\n/**\n * @author Devender Yadav\n * \n */\npublic class ConstructorValidationTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    @Test\n    public void validConstructorTest() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"hbaseTest\");\n        em = emf.createEntityManager();\n        BookEntity book = new BookEntity();\n        book.setBookId(1);\n        book.setTitle(\"The Complete Reference\");\n        book.setAuthor(\"Herbert Schildt\");\n        book.setPages(500);\n\n        em.persist(book);\n\n        em.clear();\n\n        BookEntity book1 = em.find(BookEntity.class, 1);\n\n        Assert.assertNotNull(book1);\n        Assert.assertEquals(1, book1.getBookId());\n        Assert.assertEquals(\"The Complete Reference\", book1.getTitle());\n        Assert.assertEquals(\"Herbert Schildt\", book1.getAuthor());\n        Assert.assertEquals(500, book1.getPages());\n\n        em.remove(book1);\n\n        BookEntity book2 = em.find(BookEntity.class, 1);\n        Assert.assertNull(book2);\n\n        em.close();\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/query/HbaseToken.java",
    "content": "package com.impetus.client.query;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"tokens\", schema = \"KunderaExamples@hbaseTest\")\npublic class HbaseToken\n{\n    @Id\n    @Column(name = \"token_id\")\n    private String id;\n\n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"client_id\")\n    private HbaseTokenClient client;\n    \n    @Column\n    private String tokenName;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public HbaseTokenClient getClient()\n    {\n        return client;\n    }\n\n    public void setClient(HbaseTokenClient client)\n    {\n        this.client = client;\n    }\n\n    public String getTokenName()\n    {\n        return tokenName;\n    }\n\n    public void setTokenName(String tokenName)\n    {\n        this.tokenName = tokenName;\n    }\n\n    \n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/query/HbaseTokenClient.java",
    "content": "package com.impetus.client.query;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"client\", schema = \"KunderaExamples@hbaseTest\")\npublic class HbaseTokenClient\n{\n\n    @Id\n    @Column(name = \"client_id\")\n    private String id;\n\n    @Column(name = \"client_name\")\n    private String clientName;\n\n    @OneToMany(mappedBy = \"client\", fetch = FetchType.LAZY)\n    private Set<HbaseToken> tokens;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public String getClientName()\n    {\n        return clientName;\n    }\n\n    public void setClientName(String clientName)\n    {\n        this.clientName = clientName;\n    }\n\n    public Set<HbaseToken> getTokens()\n    {\n        return tokens;\n    }\n\n    public void setTokens(Set<HbaseToken> tokens)\n    {\n        this.tokens = tokens;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/query/PaginationTests.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.query;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.BaseTest;\nimport com.impetus.client.hbase.crud.PersonHBase;\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.query.IResultIterator;\nimport com.impetus.kundera.query.Query;\n\n/**\n * @author Pragalbh Garg junit for {@link IResultIterator}.\n */\npublic class PaginationTests extends BaseTest\n{\n    private static final int NO_OF_RECORDS = 1000;\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    private HBaseCli cli = new HBaseCli();\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        cli.startCluster();\n        emf = Persistence.createEntityManagerFactory(\"hbaseTest\");\n        em = emf.createEntityManager();\n        persistData(NO_OF_RECORDS);\n    }\n\n    @After\n    public void tearDown()\n    {\n        cli.stopCluster(\"PERSON_HBASE\");\n    }\n\n    @Test\n    public void chunkScrollTest() throws Exception\n    {\n        //without where clause\n        int chunkSize = 50;\n        Query query = (Query) em.createQuery(\"Select p from PersonHBase p\", PersonHBase.class);\n        query.setFetchSize(1000);\n        Iterator<PersonHBase> iter = query.iterate();\n        IResultIterator<PersonHBase> iIter = (IResultIterator<PersonHBase>) iter;\n        assertScrolling(chunkSize, iIter);\n        \n        //with where clause\n        String name = \"vivek\";\n        query = (Query) em.createQuery(\"Select p from PersonHBase p where p.personName = '\"+name+\"'\", PersonHBase.class);\n        query.setFetchSize(1000);\n        iter = query.iterate();\n        iIter = (IResultIterator<PersonHBase>) iter;\n        assertScrolling(chunkSize, iIter);\n    }\n\n    private void assertScrolling(int chunkSize, IResultIterator<PersonHBase> iIter)\n    {\n        while (iIter.hasNext())\n        {\n            List<PersonHBase> result = iIter.next(chunkSize);\n            Assert.assertNotNull(result);\n            Assert.assertEquals(chunkSize, result.size());\n        }\n    }\n\n    private void persistData(int noOfRecords)\n    {\n        while (noOfRecords--!= 0)\n        {\n            Object p = prepareHbaseInstance(\"\" + noOfRecords, 20);\n            em.persist(p);\n            em.clear();\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/query/ResultIteratorTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.query;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.BaseTest;\nimport com.impetus.client.hbase.crud.PersonHBase;\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.query.IResultIterator;\nimport com.impetus.kundera.query.Query;\n\n/**\n * @author vivek.mishra junit for {@link IResultIterator}.\n */\npublic class ResultIteratorTest extends BaseTest\n{\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    private HBaseCli cli = new HBaseCli();\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        \n        cli.startCluster();\n        emf = Persistence.createEntityManagerFactory(\"hbaseTest\");\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testScrollViaCQL2() throws Exception\n    {\n        onScroll();\n    }\n\n    @Test\n    public void testCQL2ScrollAssociation() throws Exception\n    {\n        assertOnTokenScroll();\n    }\n\n    private void assertOnTokenScroll()\n    {\n        HbaseToken token1 = new HbaseToken();\n        token1.setId(\"tokenId1\");\n        token1.setTokenName(\"tokenName1\");\n        HbaseTokenClient client = new HbaseTokenClient();\n        client.setClientName(\"tokenClient1\");\n        client.setId(\"tokenClientId\");\n        token1.setClient(client);\n\n        HbaseToken token2 = new HbaseToken();\n        token2.setId(\"tokenId2\");\n        token2.setTokenName(\"tokenName2\");\n        token2.setClient(client);\n        em.persist(token1);\n        em.persist(token2);\n\n        String queryWithoutClause = \"Select t from HbaseToken t\";\n        assertOnTokenScroll(queryWithoutClause, 2);\n\n        String queryWithClause = \"Select t from HbaseToken t where t.tokenName='tokenName1'\";\n\n        assertOnTokenScroll(queryWithClause, 1);\n\n        // TODO:: Need to discuss with KK, this should be working with token\n        // support. Special scenario.\n        String queryWithIdClause = \"Select t from HbaseToken t where t.id = 'tokenId1'\";\n        //\n        assertOnTokenScroll(queryWithIdClause, 1);\n\n    }\n\n    private void assertOnTokenScroll(String queryClause, int expected)\n    {\n        Query query = (Query) em.createQuery(queryClause, HbaseToken.class);\n\n        int count = 0;\n        Iterator<HbaseToken> tokens = query.iterate();\n        while (tokens.hasNext())\n        {\n            HbaseToken token = tokens.next();\n            Assert.assertNotNull(token);\n            Assert.assertNotNull(token.getClient());\n            Assert.assertEquals(2, token.getClient().getTokens().size());\n            count++;\n        }\n\n        Assert.assertTrue(count > 0);\n        Assert.assertTrue(count == expected);\n    }\n\n    private void onScroll()\n    {\n        Object p1 = prepareHbaseInstance(\"1\", 10);\n        Object p2 = prepareHbaseInstance(\"2\", 20);\n        Object p3 = prepareHbaseInstance(\"3\", 15);\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        em.flush();\n        em.clear();\n        final String queryWithoutClause = \"Select p from PersonHBase p\";\n\n        assertOnScroll(queryWithoutClause, 3);\n\n        final String queryWithClause = \"Select p from PersonHBase p where p.personName = vivek\";\n\n        assertOnScroll(queryWithClause, 3);\n\n        final String queryWithAndClause = \"Select p from PersonHBase p where p.personName = vivek and p.age = 15\";\n\n        assertOnScroll(queryWithAndClause, 1);\n\n        final String queryWithLTClause = \"Select p from PersonHBase p where p.personName = vivek and p.age < 15\";\n\n        assertOnScroll(queryWithLTClause, 1);\n\n        final String queryWithGTClause = \"Select p from PersonHBase p where p.personName = vivek and p.age >= 15\";\n\n        assertOnScroll(queryWithGTClause, 2);\n\n        final String queryWithLTGTClause = \"Select p from PersonHBase p where p.personName = vivek and p.age > 10 and p.age < 20\";\n\n        assertOnScroll(queryWithLTGTClause, 1);\n\n        final String queryWithLTGTEClause = \"Select p from PersonHBase p where p.personName = vivek and p.age >= 10 and p.age < 20\";\n\n        assertOnScroll(queryWithLTGTEClause, 2);\n\n        String queryWithIdClause = \"Select p from PersonHBase p where p.personId = '2' \";\n        assertOnScroll(queryWithIdClause, 1);\n    }\n\n    private void assertOnScroll(final String queryWithoutClause, int expectedCount)\n    {\n        Query query = (Query) em.createQuery(queryWithoutClause, PersonHBase.class);\n\n        assertOnFetch(query, 0, expectedCount);\n        assertOnFetch(query, 2, expectedCount); // less records\n\n        assertOnFetch(query, 4, expectedCount); // more fetch size than\n                                                // available in db.\n        assertOnFetch(query, 3, expectedCount); // more fetch size than\n                                                // available in db.\n\n        assertOnFetch(query, null, expectedCount); // set to null;\n\n    }\n\n    private void assertOnFetch(Query query, Integer fetchSize, int available)\n    {\n        query.setFetchSize(fetchSize);\n        int counter = 0;\n        Iterator<PersonHBase> iter = query.iterate();\n\n        while (iter.hasNext())\n        {\n            Assert.assertNotNull(iter.next());\n            counter++;\n        }\n\n        Assert.assertEquals(counter, fetchSize == null || available < fetchSize ? available : fetchSize);\n        try\n        {\n            iter.next();\n            Assert.fail();\n        }\n        catch (NoSuchElementException nsex)\n        {\n            Assert.assertNotNull(nsex.getMessage());\n        }\n    }\n\n    @After\n    public void tearDown()\n    {\n        cli.stopCluster(\"PERSON_HBASE\");\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/twitter/TwibaseTest.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter;\r\n\r\nimport org.junit.Test;\r\n\r\nimport com.impetus.client.hbase.junits.HBaseCli;\r\n\r\n/**\r\n * Test case for Twitter like application on HBase\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class TwibaseTest extends TwitterTestBaseHbase\r\n{\r\n\r\n    HBaseCli cli = new HBaseCli();\r\n\r\n    @Override\r\n    protected void setUp() throws Exception\r\n    {\r\n        \r\n        setUpInternal(\"twibaseTest\");\r\n    }\r\n\r\n    /**\r\n     * Test on execute.\r\n     */\r\n    @Test\r\n    public void testOnExecute()\r\n    {\r\n        executeTestSuite();\r\n    }\r\n\r\n    @Override\r\n    protected void tearDown() throws Exception\r\n    {\r\n        tearDownInternal();\r\n    }\r\n\r\n    @Override\r\n    void startServer()\r\n    {\r\n        cli.startCluster();\r\n    }\r\n\r\n    @Override\r\n    void stopServer()\r\n    {\r\n        cli.stopCluster();\r\n    }\r\n\r\n    @Override\r\n    void createSchema()\r\n    {\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {/*\r\n          * cli.createTable(\"USER\"); cli.addColumnFamily(\"USER\",\r\n          * \"PREFERENCE_ID\"); cli.addColumnFamily(\"USER\", \"FRIEND_ID\");\r\n          * cli.addColumnFamily(\"USER\", \"FOLLOWER_ID\");\r\n          * cli.addColumnFamily(\"USER\", \"personalDetail\");\r\n          * \r\n          * cli.createTable(\"PREFERENCE\"); cli.addColumnFamily(\"PREFERENCE\",\r\n          * \"WEBSITE_THEME\"); cli.addColumnFamily(\"PREFERENCE\",\r\n          * \"PRIVACY_LEVEL\");\r\n          * \r\n          * cli.createTable(\"EXTERNAL_LINK\");\r\n          * cli.addColumnFamily(\"EXTERNAL_LINK\", \"LINK_TYPE\");\r\n          * cli.addColumnFamily(\"EXTERNAL_LINK\", \"USER_ID\");\r\n          * cli.addColumnFamily(\"EXTERNAL_LINK\", \"LINK_ADDRESS\");\r\n          */\r\n        }\r\n    }\r\n\r\n    @Override\r\n    void deleteSchema()\r\n    {\r\n        cli.dropTable(\"KunderaExamples\");\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/twitter/TwitterTestBaseHbase.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter;\r\n\r\nimport java.util.List;\r\n\r\nimport junit.framework.TestCase;\r\n\r\nimport org.junit.Assert;\r\n\r\nimport com.impetus.client.twitter.dao.TwitterHbase;\r\nimport com.impetus.client.twitter.dao.TwitterServiceHbase;\r\nimport com.impetus.client.twitter.entities.ExternalLinkHBase;\r\nimport com.impetus.client.twitter.entities.PersonalDetailHbase;\r\nimport com.impetus.client.twitter.entities.PreferenceHBase;\r\nimport com.impetus.client.twitter.entities.TweetHbase;\r\nimport com.impetus.client.twitter.entities.UserHBase;\r\n\r\n/**\r\n * Test case for MongoDB.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic abstract class TwitterTestBaseHbase extends TestCase\r\n{\r\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\r\n\r\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\r\n\r\n    /** The user id1. */\r\n    String userId1;\r\n\r\n    /** The user id2. */\r\n    String userId2;\r\n\r\n    /** The twitter. */\r\n    protected TwitterHbase twitter;\r\n\r\n    private String persistenceUnitName;\r\n\r\n    /**\r\n     * Sets the up internal.\r\n     * \r\n     * @param persistenceUnitName\r\n     *            the new up internal\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    protected void setUpInternal(String persistenceUnitName) throws Exception\r\n    {\r\n        this.persistenceUnitName = persistenceUnitName;\r\n        userId1 = \"0001\";\r\n        userId2 = \"0002\";\r\n\r\n        // Start Cassandra Server\r\n        if (RUN_IN_EMBEDDED_MODE)\r\n        {\r\n            startServer();\r\n        }\r\n\r\n        twitter = new TwitterServiceHbase(persistenceUnitName);\r\n\r\n        // Create Schema\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            createSchema();\r\n        }\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see junit.framework.TestCase#tearDown()\r\n     */\r\n    /**\r\n     * Tear down internal.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    protected void tearDownInternal() throws Exception\r\n    {\r\n        if (twitter != null)\r\n        {\r\n            twitter.close();\r\n        }\r\n\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            deleteSchema();\r\n        }\r\n\r\n        // Stop Server\r\n        if (RUN_IN_EMBEDDED_MODE)\r\n        {\r\n            stopServer();\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Execute suite.\r\n     */\r\n    protected void executeTestSuite()\r\n    {\r\n        // Insert, Find and Update\r\n        addAllUserInfo();\r\n        getUserById();\r\n        updateUser();\r\n\r\n        // Queries\r\n        getAllUsers();\r\n        getAllTweets();\r\n\r\n        // Remove Users\r\n        removeUser();\r\n\r\n    }\r\n\r\n    protected void addAllUserInfo()\r\n    {\r\n        UserHBase user1 = buildUser1();\r\n        UserHBase user2 = buildUser2();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addUser(user1);\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addUser(user2);\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    protected void getUserById()\r\n    {\r\n        twitter.createEntityManager();\r\n        UserHBase user1 = twitter.findUserById(userId1);\r\n        assertUser1(user1);\r\n\r\n        UserHBase user2 = twitter.findUserById(userId2);\r\n        assertUser2(user2);\r\n\r\n    }\r\n\r\n    protected void updateUser()\r\n    {\r\n        twitter.createEntityManager();\r\n        UserHBase user1 = twitter.findUserById(userId1);\r\n        assertUser1(user1);\r\n\r\n        user1.setPersonalDetail(new PersonalDetailHbase(\"Vivek\", \"unknown\", \"Married\"));\r\n        user1.addTweet(new TweetHbase(\"My Third Tweet\", \"iPhone\"));\r\n        twitter.mergeUser(user1);\r\n\r\n        UserHBase user1AfterMerge = twitter.findUserById(userId1);\r\n\r\n        assertUpdatedUser1(user1AfterMerge);\r\n\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    protected void removeUser()\r\n    {\r\n        twitter.createEntityManager();\r\n        UserHBase user1 = twitter.findUserById(userId1);\r\n        assertUpdatedUser1(user1);\r\n\r\n        twitter.removeUser(user1);\r\n\r\n        UserHBase user1AfterRemoval = twitter.findUserById(userId1);\r\n        Assert.assertNull(user1AfterRemoval);\r\n\r\n        twitter.closeEntityManager();\r\n\r\n    }\r\n\r\n    protected void getAllUsers()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<UserHBase> users = twitter.getAllUsers();\r\n        Assert.assertNotNull(users);\r\n        Assert.assertFalse(users.isEmpty());\r\n        Assert.assertEquals(2, users.size());\r\n\r\n        for (UserHBase u : users)\r\n        {\r\n            Assert.assertNotNull(u);\r\n            if (u.getUserId().equals(userId1))\r\n            {\r\n                assertUpdatedUser1(u);\r\n            }\r\n            else if (u.getUserId().equals(userId2))\r\n            {\r\n                assertUser2(u);\r\n            }\r\n        }\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Adds the users.\r\n     */\r\n    protected void addUsers()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addUser(userId1, \"Amresh\", \"password1\", \"married\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addUser(userId2, \"Saurabh\", \"password2\", \"single\");\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Save preference.\r\n     */\r\n    protected void savePreference()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.savePreference(userId1, new PreferenceHBase(\"P1\", \"Motif\", \"2\"));\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.savePreference(userId2, new PreferenceHBase(\"P2\", \"High Contrast\", \"3\"));\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Adds the external links.\r\n     */\r\n    protected void addExternalLinks()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId1, \"L1\", \"Facebook\", \"http://facebook.com/coolnerd\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId1, \"L2\", \"LinkedIn\", \"http://linkedin.com/in/devilmate\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId2, \"L3\", \"GooglePlus\", \"http://plus.google.com/inviteme\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId2, \"L4\", \"Yahoo\", \"http://yahoo.com/profiles/itsmeamry\");\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Adds the tweets.\r\n     */\r\n    protected void addTweets()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId1, \"Here is my first tweet\", \"Web\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId1, \"Second Tweet from me\", \"Mobile\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId2, \"Saurabh tweets for the first time\", \"Phone\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId2, \"Another tweet from Saurabh\", \"text\");\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * User1 follows user2.\r\n     */\r\n    protected void user1FollowsUser2()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.startFollowing(userId1, userId2);\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * User1 adds user2 as follower.\r\n     */\r\n    protected void user1AddsUser2AsFollower()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addFollower(userId1, userId2);\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Gets the all tweets.\r\n     * \r\n     * @return the all tweets\r\n     */\r\n    protected void getAllTweets()\r\n    {\r\n        twitter.createEntityManager();\r\n\r\n        List<TweetHbase> tweetsUser1 = twitter.getAllTweets(userId1);\r\n        List<TweetHbase> tweetsUser2 = twitter.getAllTweets(userId2);\r\n\r\n        twitter.closeEntityManager();\r\n\r\n        assertNotNull(tweetsUser1);\r\n        assertNotNull(tweetsUser2);\r\n\r\n        assertFalse(tweetsUser1.isEmpty());\r\n        assertFalse(tweetsUser2.isEmpty());\r\n\r\n        assertEquals(3, tweetsUser1.size());\r\n        assertEquals(2, tweetsUser2.size());\r\n    }\r\n\r\n    /**\r\n     * Gets the tweets by body.\r\n     * \r\n     * @return the tweets by body\r\n     */\r\n    public void getTweetsByBody()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<TweetHbase> user1Tweet = twitter.findTweetByBody(\"Here\");\r\n        List<TweetHbase> user2Tweet = twitter.findTweetByBody(\"Saurabh\");\r\n\r\n        twitter.closeEntityManager();\r\n\r\n        assertNotNull(user1Tweet);\r\n        assertNotNull(user2Tweet);\r\n        assertEquals(1, user1Tweet.size());\r\n        assertEquals(1, user2Tweet.size());\r\n    }\r\n\r\n    /**\r\n     * Gets the tweet by device.\r\n     * \r\n     * @return the tweet by device\r\n     */\r\n    public void getTweetsByDevice()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<TweetHbase> webTweets = twitter.findTweetByDevice(\"Web\");\r\n        List<TweetHbase> mobileTweets = twitter.findTweetByDevice(\"Mobile\");\r\n\r\n        twitter.closeEntityManager();\r\n\r\n        assertNotNull(webTweets);\r\n        assertNotNull(mobileTweets);\r\n        assertEquals(1, webTweets.size());\r\n        assertEquals(1, mobileTweets.size());\r\n\r\n    }\r\n\r\n    /**\r\n     * Gets the all followers.\r\n     * \r\n     * @return the all followers\r\n     */\r\n    protected void getAllFollowers()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<UserHBase> follower1 = twitter.getFollowers(userId1);\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        List<UserHBase> follower2 = twitter.getFollowers(userId2);\r\n        twitter.closeEntityManager();\r\n\r\n        assertNull(follower1);\r\n        assertNotNull(follower2);\r\n    }\r\n\r\n    /**\r\n     * @return\r\n     */\r\n    private UserHBase buildUser1()\r\n    {\r\n        UserHBase user1 = new UserHBase(userId1, \"Amresh\", \"password1\", \"married\");\r\n\r\n        user1.setPreference(new PreferenceHBase(\"P1\", \"Motif\", \"2\"));\r\n\r\n        user1.addExternalLink(new ExternalLinkHBase(\"L1\", \"Facebook\", \"http://facebook.com/coolnerd\"));\r\n        user1.addExternalLink(new ExternalLinkHBase(\"L2\", \"LinkedIn\", \"http://linkedin.com/in/devilmate\"));\r\n\r\n        user1.addTweet(new TweetHbase(\"Here is my first tweet\", \"Web\"));\r\n        user1.addTweet(new TweetHbase(\"Second Tweet from me\", \"Mobile\"));\r\n        return user1;\r\n    }\r\n\r\n    /**\r\n     * @return\r\n     */\r\n    private UserHBase buildUser2()\r\n    {\r\n        UserHBase user2 = new UserHBase(userId2, \"Saurabh\", \"password2\", \"single\");\r\n\r\n        user2.setPreference(new PreferenceHBase(\"P2\", \"High Contrast\", \"3\"));\r\n\r\n        user2.addExternalLink(new ExternalLinkHBase(\"L3\", \"GooglePlus\", \"http://plus.google.com/inviteme\"));\r\n        user2.addExternalLink(new ExternalLinkHBase(\"L4\", \"Yahoo\", \"http://yahoo.com/profiles/itsmeamry\"));\r\n\r\n        user2.addTweet(new TweetHbase(\"Saurabh tweets for the first time\", \"Phone\"));\r\n        user2.addTweet(new TweetHbase(\"Another tweet from Saurabh\", \"text\"));\r\n        return user2;\r\n    }\r\n\r\n    private void assertUser1(UserHBase user1)\r\n    {\r\n        Assert.assertNotNull(user1);\r\n        Assert.assertEquals(userId1, user1.getUserId());\r\n        Assert.assertNotNull(user1.getPersonalDetail());\r\n        Assert.assertEquals(\"Amresh\", user1.getPersonalDetail().getName());\r\n        Assert.assertNotNull(user1.getPreference());\r\n        Assert.assertEquals(\"2\", user1.getPreference().getPrivacyLevel());\r\n        Assert.assertNotNull(user1.getTweets());\r\n        Assert.assertFalse(user1.getTweets().isEmpty());\r\n        Assert.assertEquals(2, user1.getTweets().size());\r\n        Assert.assertNotNull(user1.getExternalLinks());\r\n        Assert.assertFalse(user1.getExternalLinks().isEmpty());\r\n        Assert.assertEquals(2, user1.getExternalLinks().size());\r\n    }\r\n\r\n    private void assertUser2(UserHBase user2)\r\n    {\r\n        Assert.assertNotNull(user2);\r\n        Assert.assertEquals(userId2, user2.getUserId());\r\n        Assert.assertNotNull(user2.getPersonalDetail());\r\n        Assert.assertEquals(\"Saurabh\", user2.getPersonalDetail().getName());\r\n        Assert.assertNotNull(user2.getPreference());\r\n        Assert.assertEquals(\"3\", user2.getPreference().getPrivacyLevel());\r\n        Assert.assertNotNull(user2.getTweets());\r\n        Assert.assertFalse(user2.getTweets().isEmpty());\r\n        Assert.assertEquals(2, user2.getTweets().size());\r\n        Assert.assertNotNull(user2.getExternalLinks());\r\n        Assert.assertFalse(user2.getExternalLinks().isEmpty());\r\n        Assert.assertEquals(2, user2.getExternalLinks().size());\r\n    }\r\n\r\n    private void assertUpdatedUser1(UserHBase user1)\r\n    {\r\n        Assert.assertNotNull(user1);\r\n        Assert.assertEquals(userId1, user1.getUserId());\r\n        Assert.assertNotNull(user1.getPersonalDetail());\r\n        Assert.assertEquals(\"Vivek\", user1.getPersonalDetail().getName());\r\n        Assert.assertEquals(\"unknown\", user1.getPersonalDetail().getPassword());\r\n        Assert.assertNotNull(user1.getPreference());\r\n        Assert.assertEquals(\"2\", user1.getPreference().getPrivacyLevel());\r\n        Assert.assertNotNull(user1.getTweets());\r\n        Assert.assertFalse(user1.getTweets().isEmpty());\r\n        Assert.assertEquals(3, user1.getTweets().size());\r\n        Assert.assertNotNull(user1.getExternalLinks());\r\n        Assert.assertFalse(user1.getExternalLinks().isEmpty());\r\n        Assert.assertEquals(2, user1.getExternalLinks().size());\r\n    }\r\n\r\n    abstract void startServer();\r\n\r\n    abstract void stopServer();\r\n\r\n    abstract void deleteSchema();\r\n\r\n    abstract void createSchema();\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/twitter/dao/SuperDaoHbase.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.dao;\r\n\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Persistence;\r\n\r\n/**\r\n * The Class SuperDao.\r\n * \r\n * @author impetus\r\n */\r\npublic class SuperDaoHbase\r\n{\r\n\r\n    /**\r\n     * Inits the.\r\n     * \r\n     * @param persistenceUnitName\r\n     *            the persistence unit name\r\n     * @return the entity manager\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    protected EntityManagerFactory createEntityManagerFactory(String persistenceUnitName)\r\n    {\r\n        return Persistence.createEntityManagerFactory(persistenceUnitName);\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/twitter/dao/TwitterHbase.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.dao;\r\n\r\nimport java.util.List;\r\n\r\nimport com.impetus.client.twitter.entities.PreferenceHBase;\r\nimport com.impetus.client.twitter.entities.TweetHbase;\r\nimport com.impetus.client.twitter.entities.UserHBase;\r\n\r\n/**\r\n * Single window application for Twitter application. Contains methods for\r\n * performing CRUD operations on users and their tweets.\r\n */\r\npublic interface TwitterHbase\r\n{\r\n\r\n    void addUser(UserHBase user);\r\n\r\n    /**\r\n     * Registers a new user with Twitter application\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param name\r\n     *            the name\r\n     * @param password\r\n     *            the password\r\n     * @param relationshipStatus\r\n     *            the relationship status\r\n     */\r\n    void addUser(String userId, String name, String password, String relationshipStatus);\r\n\r\n    /**\r\n     * Save preference for a given user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param preference\r\n     *            the preference\r\n     */\r\n    void savePreference(String userId, PreferenceHBase preference);\r\n\r\n    /**\r\n     * Adds an external link for the given user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param linkType\r\n     *            the link type\r\n     * @param linkAddress\r\n     *            the link address\r\n     */\r\n    void addExternalLink(String userId, String linkId, String linkType, String linkAddress);\r\n\r\n    /**\r\n     * Adds a new tweet for a user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param tweetBody\r\n     *            the tweet body\r\n     * @param device\r\n     *            the device\r\n     */\r\n    void addTweet(String userId, String tweetBody, String device);\r\n\r\n    /**\r\n     * Makes User whose row key is <code>userId</code> follow a user whose row\r\n     * key is <code>friendUserId</code>\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param friendUserId\r\n     *            the friend user id\r\n     */\r\n    void startFollowing(String userId, String friendUserId);\r\n\r\n    /**\r\n     * Adds the follower whose row key is <code>followerUserId</code> to User\r\n     * whose row key is <code>userId</code>\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param followerUserId\r\n     *            the follower user id\r\n     */\r\n    void addFollower(String userId, String followerUserId);\r\n\r\n    UserHBase findUserById(String userId);\r\n\r\n    void removeUser(UserHBase user);\r\n\r\n    void mergeUser(UserHBase user);\r\n\r\n    /**\r\n     * Retrieves all tweets for a given user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @return the all tweets\r\n     */\r\n    List<UserHBase> getAllUsers();\r\n\r\n    List<TweetHbase> getAllTweets(String userId);\r\n\r\n    /**\r\n     * Returns a list of followers for a given user.\r\n     * \r\n     * @param userId\r\n     *            user id\r\n     * @return list of all followers.\r\n     */\r\n    List<UserHBase> getFollowers(String userId);\r\n\r\n    /**\r\n     * Find tweet by tweet body.\r\n     * \r\n     * @param tweetBody\r\n     *            the tweet body\r\n     * @return the list\r\n     */\r\n    List<TweetHbase> findTweetByBody(String tweetBody);\r\n\r\n    /**\r\n     * Find tweet by device.\r\n     * \r\n     * @param deviceName\r\n     *            the device name\r\n     * @return the list\r\n     */\r\n    List<TweetHbase> findTweetByDevice(String deviceName);\r\n\r\n    /**\r\n     * Close.\r\n     */\r\n    void close();\r\n\r\n    void createEntityManager();\r\n\r\n    void closeEntityManager();\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/twitter/dao/TwitterServiceHbase.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.dao;\r\n\r\nimport java.util.List;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Query;\r\n\r\nimport com.impetus.client.twitter.entities.ExternalLinkHBase;\r\nimport com.impetus.client.twitter.entities.PreferenceHBase;\r\nimport com.impetus.client.twitter.entities.TweetHbase;\r\nimport com.impetus.client.twitter.entities.UserHBase;\r\n\r\n/**\r\n * Data access object class for implementation of twitter.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class TwitterServiceHbase extends SuperDaoHbase implements TwitterHbase\r\n{\r\n    private EntityManager em;\r\n\r\n    private EntityManagerFactory emf;\r\n\r\n    public TwitterServiceHbase(String persistenceUnitName)\r\n    {\r\n        if (emf == null)\r\n        {\r\n            try\r\n            {\r\n                emf = createEntityManagerFactory(persistenceUnitName);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                \r\n            }\r\n        }\r\n\r\n    }\r\n\r\n    @Override\r\n    public void createEntityManager()\r\n    {\r\n        if (em == null)\r\n        {\r\n            em = emf.createEntityManager();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void closeEntityManager()\r\n    {\r\n        if (em != null)\r\n        {\r\n            em.clear();\r\n            em.close();\r\n            em = null;\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void close()\r\n    {\r\n        if (emf != null)\r\n        {\r\n            emf.close();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void addUser(UserHBase user)\r\n    {\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void addUser(String userId, String name, String password, String relationshipStatus)\r\n    {\r\n        UserHBase user = new UserHBase(userId, name, password, relationshipStatus);\r\n        em.persist(user);\r\n\r\n    }\r\n\r\n    @Override\r\n    public void savePreference(String userId, PreferenceHBase preference)\r\n    {\r\n\r\n        UserHBase user = em.find(UserHBase.class, userId);\r\n        user.setPreference(preference);\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void addExternalLink(String userId, String linkId, String linkType, String linkAddress)\r\n    {\r\n        UserHBase user = em.find(UserHBase.class, userId);\r\n        user.addExternalLink(new ExternalLinkHBase(linkId, linkType, linkAddress));\r\n\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void addTweet(String userId, String tweetBody, String device)\r\n    {\r\n        UserHBase user = em.find(UserHBase.class, userId);\r\n        user.addTweet(new TweetHbase(tweetBody, device));\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void startFollowing(String userId, String friendUserId)\r\n    {\r\n        UserHBase user = em.find(UserHBase.class, userId);\r\n        UserHBase friend = em.find(UserHBase.class, friendUserId);\r\n\r\n        user.addFriend(friend);\r\n        em.persist(user);\r\n\r\n        friend.addFollower(user);\r\n        em.persist(friend);\r\n    }\r\n\r\n    @Override\r\n    public void addFollower(String userId, String followerUserId)\r\n    {\r\n        UserHBase user = em.find(UserHBase.class, userId);\r\n        UserHBase follower = em.find(UserHBase.class, followerUserId);\r\n\r\n        user.addFollower(follower);\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public UserHBase findUserById(String userId)\r\n    {\r\n        UserHBase user = em.find(UserHBase.class, userId);\r\n        return user;\r\n    }\r\n\r\n    @Override\r\n    public void removeUser(UserHBase user)\r\n    {\r\n        em.remove(user);\r\n    }\r\n\r\n    @Override\r\n    public void mergeUser(UserHBase user)\r\n    {\r\n        em.merge(user);\r\n    }\r\n\r\n    @Override\r\n    public List<UserHBase> getAllUsers()\r\n    {\r\n\r\n        Query q = em.createQuery(\"select u from UserHBase u\");\r\n\r\n        List<UserHBase> users = q.getResultList();\r\n\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<TweetHbase> getAllTweets(String userId)\r\n    {\r\n        Query q = em.createQuery(\"select u from UserHBase u where u.userId =:userId\");\r\n        q.setParameter(\"userId\", userId);\r\n        List<UserHBase> users = q.getResultList();\r\n        if (users == null || users.isEmpty())\r\n        {\r\n            return null;\r\n        }\r\n        else\r\n        {\r\n            return users.get(0).getTweets();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public List<UserHBase> getFollowers(String userId)\r\n    {\r\n        Query q = em.createQuery(\"select u from UserHBase u where u.userId =:userId\");\r\n        q.setParameter(\"userId\", userId);\r\n        List<UserHBase> users = q.getResultList();\r\n        if (users == null || users.isEmpty())\r\n        {\r\n            return null;\r\n        }\r\n        return users.get(0).getFollowers();\r\n    }\r\n\r\n    @Override\r\n    public List<TweetHbase> findTweetByBody(String tweetBody)\r\n    {\r\n        Query q = em.createQuery(\"select u.tweet_body from UserHBase u where u.tweet_body like :body\");\r\n        q.setParameter(\"body\", tweetBody);\r\n        List<TweetHbase> tweets = q.getResultList();\r\n        return tweets;\r\n    }\r\n\r\n    @Override\r\n    public List<TweetHbase> findTweetByDevice(String deviceName)\r\n    {\r\n        Query q = em.createQuery(\"select u.tweeted_from from UserHBase u where u.tweeted_from like :device\");\r\n        q.setParameter(\"device\", deviceName);\r\n        List<TweetHbase> tweets = q.getResultList();\r\n        return tweets;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/twitter/entities/ExternalLinkHBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.twitter.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class for user's External link details\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"EXTERNAL_LINK\", schema = \"KunderaExamples@twibaseTest\")\npublic class ExternalLinkHBase\n{\n\n    @Id\n    @Column(name = \"EXT_LINK_ID\")\n    private String extLinkId;\n\n    @Column(name = \"LINK_TYPE\")\n    private String linkType;\n\n    @Column(name = \"LINK_ADDRESS\")\n    private String linkAddress;\n\n    public ExternalLinkHBase()\n    {\n    }\n\n    public ExternalLinkHBase(String extLinkId, String type, String address)\n    {\n        this.extLinkId = extLinkId;\n        this.linkType = type;\n        this.linkAddress = address;\n    }\n\n    /**\n     * @return the extLinkId\n     */\n    public String getExtLinkId()\n    {\n        return extLinkId;\n    }\n\n    /**\n     * @param extLinkId\n     *            the extLinkId to set\n     */\n    public void setExtLinkId(String extLinkId)\n    {\n        this.extLinkId = extLinkId;\n    }\n\n    /**\n     * @return the linkType\n     */\n    public String getLinkType()\n    {\n        return linkType;\n    }\n\n    /**\n     * @param linkType\n     *            the linkType to set\n     */\n    public void setLinkType(String linkType)\n    {\n        this.linkType = linkType;\n    }\n\n    /**\n     * @return the linkAddress\n     */\n    public String getLinkAddress()\n    {\n        return linkAddress;\n    }\n\n    /**\n     * @param linkAddress\n     *            the linkAddress to set\n     */\n    public void setLinkAddress(String linkAddress)\n    {\n        this.linkAddress = linkAddress;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/twitter/entities/PersonalDetailHbase.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\nimport com.impetus.client.twitter.utils.ExampleUtilsHbase;\r\n\r\n/**\r\n * Entity class for user's personal details\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\npublic class PersonalDetailHbase\r\n{\r\n    @Column(name = \"personal_detail_id\")\r\n    private String personalDetailId;\r\n\r\n    @Column(name = \"name\")\r\n    private String name;\r\n\r\n    @Column(name = \"password\")\r\n    private String password;\r\n\r\n    @Column(name = \"rel_status\")\r\n    private String relationshipStatus;\r\n\r\n    public PersonalDetailHbase()\r\n    {\r\n\r\n    }\r\n\r\n    public PersonalDetailHbase(String name, String password, String relationshipStatus)\r\n    {\r\n        setPersonalDetailId(ExampleUtilsHbase.getUniqueId());\r\n        setName(name);\r\n        setPassword(password);\r\n        setRelationshipStatus(relationshipStatus);\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetailId\r\n     */\r\n    public String getPersonalDetailId()\r\n    {\r\n        return personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetailId\r\n     *            the personalDetailId to set\r\n     */\r\n    public void setPersonalDetailId(String personalDetailId)\r\n    {\r\n        this.personalDetailId = personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @return the name\r\n     */\r\n    public String getName()\r\n    {\r\n        return name;\r\n    }\r\n\r\n    /**\r\n     * @param name\r\n     *            the name to set\r\n     */\r\n    public void setName(String name)\r\n    {\r\n        this.name = name;\r\n    }\r\n\r\n    /**\r\n     * @return the password\r\n     */\r\n    public String getPassword()\r\n    {\r\n        return password;\r\n    }\r\n\r\n    /**\r\n     * @param password\r\n     *            the password to set\r\n     */\r\n    public void setPassword(String password)\r\n    {\r\n        this.password = password;\r\n    }\r\n\r\n    /**\r\n     * @return the relationshipStatus\r\n     */\r\n    public String getRelationshipStatus()\r\n    {\r\n        return relationshipStatus;\r\n    }\r\n\r\n    /**\r\n     * @param relationshipStatus\r\n     *            the relationshipStatus to set\r\n     */\r\n    public void setRelationshipStatus(String relationshipStatus)\r\n    {\r\n        this.relationshipStatus = relationshipStatus;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/twitter/entities/PreferenceHBase.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * Entity class for User Preferences\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"PREFERENCE\", schema = \"KunderaExamples@twibaseTest\")\r\npublic class PreferenceHBase\r\n{\r\n    @Id\r\n    @Column(name = \"PREFERENCE_ID\")\r\n    String preferenceId;\r\n\r\n    @Column(name = \"WEBSITE_THEME\")\r\n    String websiteTheme;\r\n\r\n    @Column(name = \"PRIVACY_LEVEL\")\r\n    String privacyLevel; // 1, 2, 3\r\n\r\n    public PreferenceHBase()\r\n    {\r\n\r\n    }\r\n\r\n    public PreferenceHBase(String preferenceId, String theme, String privacyLevel)\r\n    {\r\n        this.preferenceId = preferenceId;\r\n        this.websiteTheme = theme;\r\n        this.privacyLevel = privacyLevel;\r\n    }\r\n\r\n    /**\r\n     * @return the preferenceId\r\n     */\r\n    public String getPreferenceId()\r\n    {\r\n        return preferenceId;\r\n    }\r\n\r\n    /**\r\n     * @param preferenceId\r\n     *            the preferenceId to set\r\n     */\r\n    public void setPreferenceId(String preferenceId)\r\n    {\r\n        this.preferenceId = preferenceId;\r\n    }\r\n\r\n    /**\r\n     * @return the websiteTheme\r\n     */\r\n    public String getWebsiteTheme()\r\n    {\r\n        return websiteTheme;\r\n    }\r\n\r\n    /**\r\n     * @param websiteTheme\r\n     *            the websiteTheme to set\r\n     */\r\n    public void setWebsiteTheme(String websiteTheme)\r\n    {\r\n        this.websiteTheme = websiteTheme;\r\n    }\r\n\r\n    /**\r\n     * @return the privacyLevel\r\n     */\r\n    public String getPrivacyLevel()\r\n    {\r\n        return privacyLevel;\r\n    }\r\n\r\n    /**\r\n     * @param privacyLevel\r\n     *            the privacyLevel to set\r\n     */\r\n    public void setPrivacyLevel(String privacyLevel)\r\n    {\r\n        this.privacyLevel = privacyLevel;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/twitter/entities/TweetHbase.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\nimport com.impetus.client.twitter.utils.ExampleUtilsHbase;\r\n\r\n/**\r\n * Class for Tweets\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\npublic class TweetHbase\r\n{\r\n\r\n    @Column(name = \"tweet_id\")\r\n    private String tweetId;\r\n\r\n    @Column(name = \"tweet_body\")\r\n    private String body;\r\n\r\n    @Column(name = \"tweeted_from\")\r\n    private String device;\r\n\r\n    // private long timestamp;\r\n\r\n    public TweetHbase(String body, String device)\r\n    {\r\n        this.tweetId = ExampleUtilsHbase.getUniqueId();\r\n        this.body = body;\r\n        this.device = device;\r\n        // this.timestamp = ExampleUtils.getCurrentTimestamp();\r\n    }\r\n\r\n    public TweetHbase()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * @return the tweetId\r\n     */\r\n    public String getTweetId()\r\n    {\r\n        return tweetId;\r\n    }\r\n\r\n    /**\r\n     * @param tweetId\r\n     *            the tweetId to set\r\n     */\r\n    public void setTweetId(String tweetId)\r\n    {\r\n        this.tweetId = tweetId;\r\n    }\r\n\r\n    /**\r\n     * @return the body\r\n     */\r\n    public String getBody()\r\n    {\r\n        return body;\r\n    }\r\n\r\n    /**\r\n     * @param body\r\n     *            the body to set\r\n     */\r\n    public void setBody(String body)\r\n    {\r\n        this.body = body;\r\n    }\r\n\r\n    /**\r\n     * @return the device\r\n     */\r\n    public String getDevice()\r\n    {\r\n        return device;\r\n    }\r\n\r\n    /**\r\n     * @param device\r\n     *            the device to set\r\n     */\r\n    public void setDevice(String device)\r\n    {\r\n        this.device = device;\r\n    }\r\n\r\n    /*    *//**\r\n     * @return the timestamp\r\n     */\r\n    /*\r\n     * public long getTimestamp() { return timestamp; }\r\n     *//**\r\n     * @param timestamp\r\n     *            the timestamp to set\r\n     */\r\n    /*\r\n     * public void setTimestamp(long timestamp) { this.timestamp = timestamp; }\r\n     */\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/twitter/entities/UserHBase.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.CollectionTable;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.ElementCollection;\r\nimport javax.persistence.Embedded;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.OneToOne;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * @author impetus\r\n * \r\n */\r\n@Entity\r\n@Table(name = \"USER_HBASE\", schema = \"KunderaExamples@twibaseTest\")\r\npublic class UserHBase\r\n{\r\n\r\n    @Id\r\n    @Column(name = \"USER_ID\")\r\n    private String userId;\r\n\r\n    // Embedded object, will persist co-located\r\n    @Embedded\r\n    private PersonalDetailHbase personalDetail;\r\n\r\n    // Element collection, will persist co-located\r\n    @ElementCollection\r\n    @CollectionTable(name = \"tweeted\")\r\n    private List<TweetHbase> tweets;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"FRIEND_ID\")\r\n    private List<UserHBase> friends; // List of users whom I follow\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"FOLLOWER_ID\")\r\n    private List<UserHBase> followers; // List of users who are following me\r\n\r\n    // One-to-one, will be persisted separately\r\n    @OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"PREFERENCE_ID\")\r\n    private PreferenceHBase preference;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"USER_ID\")\r\n    private Set<ExternalLinkHBase> externalLinks;\r\n\r\n    public UserHBase()\r\n    {\r\n\r\n    }\r\n\r\n    public UserHBase(String userId, String name, String password, String relationshipStatus)\r\n    {\r\n        PersonalDetailHbase pd = new PersonalDetailHbase(name, password, relationshipStatus);\r\n        setUserId(userId);\r\n        setPersonalDetail(pd);\r\n    }\r\n\r\n    /**\r\n     * @return the userId\r\n     */\r\n    public String getUserId()\r\n    {\r\n        return userId;\r\n    }\r\n\r\n    /**\r\n     * @param userId\r\n     *            the userId to set\r\n     */\r\n    public void setUserId(String userId)\r\n    {\r\n        this.userId = userId;\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetail\r\n     */\r\n    public PersonalDetailHbase getPersonalDetail()\r\n    {\r\n        return personalDetail;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetail\r\n     *            the personalDetail to set\r\n     */\r\n    public void setPersonalDetail(PersonalDetailHbase personalDetail)\r\n    {\r\n        this.personalDetail = personalDetail;\r\n    }\r\n\r\n    /**\r\n     * @return the tweets\r\n     */\r\n    public List<TweetHbase> getTweets()\r\n    {\r\n        return tweets;\r\n    }\r\n\r\n    /**\r\n     * @param tweets\r\n     *            the tweets to set\r\n     */\r\n    public void addTweet(TweetHbase tweet)\r\n    {\r\n        if (this.tweets == null || this.tweets.isEmpty())\r\n        {\r\n            this.tweets = new ArrayList<TweetHbase>();\r\n        }\r\n        this.tweets.add(tweet);\r\n    }\r\n\r\n    /**\r\n     * @return the preference\r\n     */\r\n    public PreferenceHBase getPreference()\r\n    {\r\n        return preference;\r\n    }\r\n\r\n    /**\r\n     * @param preference\r\n     *            the preference to set\r\n     */\r\n    public void setPreference(PreferenceHBase preference)\r\n    {\r\n        this.preference = preference;\r\n    }\r\n\r\n    /**\r\n     * @return the externalLinks\r\n     */\r\n    public Set<ExternalLinkHBase> getExternalLinks()\r\n    {\r\n        return externalLinks;\r\n    }\r\n\r\n    /**\r\n     * @param imDetails\r\n     *            the imDetails to set\r\n     */\r\n    public void addExternalLink(ExternalLinkHBase externalLink)\r\n    {\r\n        if (this.externalLinks == null || this.externalLinks.isEmpty())\r\n        {\r\n            this.externalLinks = new HashSet<ExternalLinkHBase>();\r\n        }\r\n\r\n        this.externalLinks.add(externalLink);\r\n    }\r\n\r\n    /**\r\n     * @return the friends\r\n     */\r\n    public List<UserHBase> getFriends()\r\n    {\r\n        return friends;\r\n    }\r\n\r\n    /**\r\n     * @param friends\r\n     *            the friends to set\r\n     */\r\n    public void addFriend(UserHBase friend)\r\n    {\r\n        if (this.friends == null || this.friends.isEmpty())\r\n        {\r\n            this.friends = new ArrayList<UserHBase>();\r\n        }\r\n        this.friends.add(friend);\r\n    }\r\n\r\n    /**\r\n     * @return the followers\r\n     */\r\n    public List<UserHBase> getFollowers()\r\n    {\r\n        return followers;\r\n    }\r\n\r\n    /**\r\n     * @param followers\r\n     *            the followers to set\r\n     */\r\n    public void addFollower(UserHBase follower)\r\n    {\r\n        if (this.followers == null || this.followers.isEmpty())\r\n        {\r\n            this.followers = new ArrayList<UserHBase>();\r\n        }\r\n\r\n        this.followers.add(follower);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/twitter/utils/ExampleUtilsHbase.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.utils;\r\n\r\nimport java.util.Date;\r\nimport java.util.UUID;\r\n\r\n/**\r\n * Class for utility methods\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class ExampleUtilsHbase\r\n{\r\n    public static String getUniqueId()\r\n    {\r\n        return UUID.randomUUID().toString();\r\n    }\r\n\r\n    public static long getCurrentTimestamp()\r\n    {\r\n        return new Date().getTime();\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/kundera/client/crud/inheritence/FacebookProfile.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.DiscriminatorValue;\r\nimport javax.persistence.Entity;\r\n\r\n/**\r\n * Facebook profile entity\r\n * @author vivek.mishra\r\n *\r\n */\r\n@Entity\r\n@DiscriminatorValue(\"fb\")\r\npublic class FacebookProfile extends SocialProfile\r\n{\r\n    // protected static final String TYPE = \"twitter\";\r\n\r\n    // @Id\r\n    // // @GeneratedValue\r\n    // @Column(name = \"guid\", updatable = false, nullable = false)\r\n    // private String id;\r\n\r\n    @Column(name = \"facebook_id\", updatable = false)\r\n    private String facebookId;\r\n\r\n    @Column(name = \"facebook_user\", length = 128)\r\n    private String facebookUser;\r\n\r\n    public String getFacebookId()\r\n    {\r\n        return facebookId;\r\n    }\r\n\r\n    public void setFacebookId(String facebookId)\r\n    {\r\n        this.facebookId = facebookId;\r\n    }\r\n\r\n    public String getFacebookUser()\r\n    {\r\n        return facebookUser;\r\n    }\r\n\r\n    public void setFacebookUser(String facebookUser)\r\n    {\r\n        this.facebookUser = facebookUser;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/kundera/client/crud/inheritence/GuidDomainObject.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\nimport javax.persistence.Id;\r\nimport javax.persistence.MappedSuperclass;\r\n\r\n\r\n\r\n/**\r\n * Abstract mapped super class.\r\n * @author vivek.mishra\r\n *\r\n */\r\n@MappedSuperclass\r\nabstract public class GuidDomainObject \r\n{\r\n    @Id\r\n    private Long id;\r\n\r\n    public Long getId()\r\n    {\r\n        return id;\r\n    }\r\n\r\n    public void setId(Long id)\r\n    {\r\n        this.id = id;\r\n    }\r\n\r\n    \r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/kundera/client/crud/inheritence/InheritenceDomainTest.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Persistence;\r\nimport javax.persistence.Query;\r\n\r\nimport junit.framework.Assert;\r\n\r\nimport org.junit.After;\r\nimport org.junit.AfterClass;\r\nimport org.junit.BeforeClass;\r\nimport org.junit.Test;\r\n\r\nimport com.impetus.client.hbase.junits.HBaseCli;\r\n\r\n/**\r\n * Junit for abstract entity class's operation.\r\n * @author vivek.mishra\r\n *\r\n */\r\npublic class InheritenceDomainTest\r\n{\r\n\r\n    protected static String _PU = \"HbaseDataTypeTest\";\r\n\r\n    /** The emf. */\r\n    protected static EntityManagerFactory emf;\r\n\r\n    /** The em. */\r\n    protected static EntityManager em;\r\n    private static HBaseCli cli;\r\n\r\n    private List objCache = new ArrayList();\r\n    \r\n    private static String tableName = \"KunderaHbaseDataType\";\r\n\r\n    @BeforeClass\r\n    public static void setUpBeforeClass() throws Exception\r\n    {\r\n        \r\n        cli = new HBaseCli();\r\n        cli.startCluster();\r\n       \r\n        emf = Persistence.createEntityManagerFactory(_PU);\r\n        em = emf.createEntityManager();\r\n    }\r\n\r\n    @Test\r\n    public void testRelation()\r\n    {\r\n\r\n        List<SocialProfile> profiles = new ArrayList<SocialProfile>();\r\n\r\n        FacebookProfile fbprofile = new FacebookProfile();\r\n        fbprofile.setId(103l);\r\n        fbprofile.setFacebookId(\"fbtestRelation\");\r\n        fbprofile.setFacebookUser(\"facebook\");\r\n        fbprofile.setuserType(\"testRelation\");\r\n\r\n        profiles.add(fbprofile);\r\n\r\n        TwitterProfile twprofile1 = new TwitterProfile();\r\n        twprofile1.setTwitterId(\"2\");\r\n        twprofile1.setTwitterName(\"testTwitterRelation\");\r\n        twprofile1.setId(102l);\r\n        profiles.add(twprofile1);\r\n        twprofile1.setuserType(\"testRelation\");\r\n        \r\n        UserAccount uacc = new UserAccount();\r\n\r\n        uacc.setId(101l);\r\n        uacc.setDispName(\"Test\");\r\n        uacc.setSocialProfiles(profiles);\r\n\r\n        twprofile1.setuserAccount(uacc);\r\n        fbprofile.setuserAccount(uacc);\r\n\r\n        em.getTransaction().begin();\r\n        em.persist(uacc);\r\n        em.getTransaction().commit();\r\n        \r\n        objCache.add(uacc);\r\n        objCache.add(twprofile1);\r\n        objCache.add(fbprofile);\r\n        \r\n        //TODOO: Stack over flow error.\r\n//        em.persist(fbprofile);\r\n//        em.persist(twprofile1);\r\n        em.clear();\r\n\r\n        String uaQuery = \"Select ua from UserAccount ua\";\r\n\r\n        Query q = em.createQuery(uaQuery);\r\n        List<UserAccount> results = q.getResultList();\r\n\r\n\r\n        Assert.assertEquals(1, results.size());\r\n        Assert.assertEquals(\"Test\", results.get(0).getDispName());\r\n         Assert.assertEquals(2, results.get(0).getSocialProfiles().size());\r\n\r\n         em.remove(results.get(0));\r\n\r\n        em.clear();\r\n\r\n\r\n    }\r\n\r\n    @Test\r\n    public void testAbstractEntity()\r\n    {\r\n        FacebookProfile fbprofile = new FacebookProfile();\r\n        fbprofile.setId(Long.MIN_VALUE);\r\n        fbprofile.setFacebookId(\"fbEntity\");\r\n        fbprofile.setFacebookUser(\"facebookEntity\");\r\n        fbprofile.setuserType(\"abstractEntity\");\r\n\r\n        em.persist(fbprofile);\r\n        \r\n        \r\n        TwitterProfile twprofile = new TwitterProfile();\r\n        twprofile.setTwitterId(\"2\");\r\n        twprofile.setTwitterName(\"twitterEntity\");\r\n        twprofile.setId(Long.MAX_VALUE);\r\n        twprofile.setuserType(\"abstractEntity\");\r\n        \r\n        em.persist(twprofile);\r\n        \r\n        em.clear();\r\n        objCache.add(twprofile);\r\n        objCache.add(fbprofile);\r\n        \r\n        SocialProfile facebookProfile = em.find(SocialProfile.class,Long.MIN_VALUE);\r\n        Assert.assertNotNull(facebookProfile);\r\n        Assert.assertTrue(facebookProfile.getClass().isAssignableFrom(FacebookProfile.class));\r\n        \r\n        SocialProfile twitterProfile = em.find(SocialProfile.class,Long.MAX_VALUE);\r\n        Assert.assertNotNull(twitterProfile);\r\n        Assert.assertTrue(twitterProfile.getClass().isAssignableFrom(TwitterProfile.class));\r\n        \r\n        em.clear();\r\n        String queryStr = \"Select s from SocialProfile s\";\r\n        \r\n        Query query = em.createQuery(queryStr);\r\n        \r\n        List<SocialProfile> socialProfiles = query.getResultList();\r\n        \r\n        Assert.assertFalse(socialProfiles.isEmpty());\r\n        Assert.assertEquals(2, socialProfiles.size());\r\n        Assert.assertFalse(socialProfiles.get(0).getClass().getSimpleName().equals(socialProfiles.get(1).getClass().getSimpleName()));\r\n\r\n        em.clear();\r\n\r\n        \r\n        String deleteQuery = \"Delete from SocialProfile s\";\r\n        query = em.createQuery(deleteQuery);\r\n        query.executeUpdate();\r\n\r\n        query = em.createQuery(queryStr);\r\n        \r\n        socialProfiles = query.getResultList();\r\n        Assert.assertTrue(socialProfiles.isEmpty());\r\n    }\r\n    \r\n    /**\r\n     * Tear down.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n     @After\r\n    public void tearDown() throws Exception\r\n    {\r\n         for (Object o : objCache)\r\n         {\r\n             em.remove(o);\r\n         }\r\n/*        String deleteQuery = \"Delete from UserAccount uacc\";\r\n        Query query = em.createQuery(deleteQuery);\r\n        query.executeUpdate();\r\n*/    }\r\n\r\n     \r\n     \r\n     @AfterClass\r\n     public static void tearDownAfterClass()\r\n     {\r\n\r\n         if(em != null)\r\n         {\r\n             em.close();\r\n             em=null;\r\n         }\r\n         if(emf != null)\r\n         {\r\n             emf.close();\r\n             emf=null;\r\n         }\r\n         \r\n//         if (cli != null )\r\n//         {\r\n//            cli.dropTable(tableName);\r\n//             cli.stopCluster(tableName);\r\n//         }\r\n//         LuceneCleanupUtilities.cleanLuceneDirectory(_PU);         \r\n         \r\n     }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/kundera/client/crud/inheritence/SocialProfile.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.crud.inheritence;\n\nimport java.io.Serializable;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorColumn;\nimport javax.persistence.DiscriminatorType;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * Abstract entity class.\n * @author vivek.mishra\n *\n */\n@Entity\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@Table(name = \"social_profile\")\n@DiscriminatorColumn(name = \"type\", length = 64, discriminatorType = DiscriminatorType.STRING)\npublic abstract class SocialProfile extends GuidDomainObject implements Serializable\n{\n    @Column(name = \"userType\")\n    private String userType;\n\n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"user_account_id\")\n    private UserAccount account;\n    \n    public String getuserType()\n    {\n        return userType;\n    }\n\n    public void setuserType(String userType)\n    {\n        this.userType = userType;\n    }\n    \n    public UserAccount getuserAccount()\n    {\n        return account;\n    }\n\n    public void setuserAccount(UserAccount account)\n    {\n        this.account = account;\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/kundera/client/crud/inheritence/TwitterProfile.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.DiscriminatorValue;\r\nimport javax.persistence.Entity;\r\n\r\n/**\r\n * Twitter profile entity.\r\n * @author vivek.mishra\r\n *\r\n */\r\n@Entity\r\n@DiscriminatorValue(\"twitter\")\r\npublic class TwitterProfile extends SocialProfile\r\n{\r\n\r\n    @Column(name = \"twitter_id\", updatable = false)\r\n    private String twitterId;\r\n\r\n    @Column(name = \"twitter_user\", length = 128)\r\n    private String twitterUser;\r\n    \r\n    public String getTwitterId()\r\n    {\r\n        return twitterId;\r\n    }\r\n\r\n    public void setTwitterId(String twitterId)\r\n    {\r\n        this.twitterId = twitterId;\r\n    }\r\n    \r\n    public String getTwitterName()\r\n    {\r\n        return twitterUser;\r\n    }\r\n\r\n    public void setTwitterName(String twitterUser)\r\n    {\r\n        this.twitterUser = twitterUser;\r\n    }\r\n\r\n\r\n}  \r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/kundera/client/crud/inheritence/UserAccount.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\n\r\nimport java.util.List;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.Table;\r\n\r\n\r\n/**\r\n * User account entity.\r\n * @author vivek.mishra\r\n *\r\n */\r\n@Entity\r\n@Table(name = \"user_account\")\r\npublic class UserAccount extends GuidDomainObject\r\n{\r\n   \r\n    @Column(name = \"display_name\", length = 128)\r\n    private String displayName = null;\r\n\r\n    @Column(name = \"email\", length = 128, unique = true)\r\n    private String email = null;\r\n\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER,mappedBy = \"account\")\r\n    private List<SocialProfile> profiles;\r\n    \r\n    public String getDispName()\r\n    {\r\n        return displayName;\r\n    }\r\n\r\n    public void setDispName(String displayName)\r\n    {\r\n        this.displayName = displayName;\r\n    }\r\n    \r\n    public String getEmail()\r\n    {\r\n        return email;\r\n    }\r\n\r\n    public void setEmail(String email)\r\n    {\r\n        this.email = email;\r\n    }\r\n    \r\n    public List<SocialProfile> getSocialProfiles()\r\n    {\r\n        return profiles;\r\n    }\r\n\r\n    public void setSocialProfiles(List<SocialProfile> profiles)\r\n    {\r\n        this.profiles = profiles;\r\n    }\r\n} \r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/CreditTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * Credit transaction extends {@link Transaction}\n *\n */\n\n@Entity\n@Table(name = \"TRNX_CREDIT\")\n@DiscriminatorValue(value = \"CREDIT\")\n@AttributeOverride(name=\"bankIdentifier\",column= @Column(name=\"CREDIT_BANK_IDENT\"))\npublic class CreditTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public CreditTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/DebitTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\n\n/**\n * @author vivek.mishra\n * Debit transaction extends {@link Transaction}\n *\n */\n@Entity\n@DiscriminatorValue(value=\"DEBIT\")\n\n@AttributeOverrides(value = { @AttributeOverride(name = \"txId\", column = @Column(name = \"DEBIT_ID\")),\n        @AttributeOverride(name = \"bankIdentifier\", column = @Column(name = \"DEBIT_BANK_IDENT\")),\n        @AttributeOverride(name = \"transactionDt\", column = @Column(name = \"TX_DT\")) })\n\npublic class DebitTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public DebitTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/recommendation/hbase/model/BookInfo.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2013 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.recommendation.hbase.model;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * \r\n * @author Kuldeep.Mishra\r\n *\r\n */\r\n@Entity\r\n@Table(name = \"bookinfo\", schema = \"KunderaExamples@hbaseTest\")\r\npublic class BookInfo\r\n{\r\n    @Id\r\n    @Column(name = \"bookId\")\r\n    private String bookId;\r\n\r\n    @Column(name = \"md5\")\r\n    private String md5;\r\n\r\n    @Column(name = \"title\")\r\n    private String title;\r\n\r\n    @Column(name = \"author\")\r\n    private String author;\r\n\r\n    @Column(name = \"yearofpub\")\r\n    private String yearofpub;\r\n\r\n    @Column(name = \"publisher\")\r\n    private String publisher;\r\n\r\n    @Column(name = \"imageurls\")\r\n    private String imageurls;\r\n\r\n    @Column(name = \"imageurlm\")\r\n    private String imageurlm;\r\n\r\n    @Column(name = \"imageurll\")\r\n    private String imageurll;\r\n\r\n    @Column(name = \"price\")\r\n    private Float price;\r\n\r\n    public String getBookId()\r\n    {\r\n        return bookId;\r\n    }\r\n\r\n    public void setBookId(String bookId)\r\n    {\r\n        this.bookId = bookId;\r\n    }\r\n\r\n    public String getMd5()\r\n    {\r\n        return md5;\r\n    }\r\n\r\n    public void setMd5(String md5)\r\n    {\r\n        this.md5 = md5;\r\n    }\r\n\r\n    public String getTitle()\r\n    {\r\n        return title;\r\n    }\r\n\r\n    public void setTitle(String title)\r\n    {\r\n        this.title = title;\r\n    }\r\n\r\n    public String getAuthor()\r\n    {\r\n        return author;\r\n    }\r\n\r\n    public void setAuthor(String author)\r\n    {\r\n        this.author = author;\r\n    }\r\n\r\n    public String getYearofpub()\r\n    {\r\n        return yearofpub;\r\n    }\r\n\r\n    public void setYearofpub(String yearofpub)\r\n    {\r\n        this.yearofpub = yearofpub;\r\n    }\r\n\r\n    public String getPublisher()\r\n    {\r\n        return publisher;\r\n    }\r\n\r\n    public void setPublisher(String publisher)\r\n    {\r\n        this.publisher = publisher;\r\n    }\r\n\r\n    public String getImageurls()\r\n    {\r\n        return imageurls;\r\n    }\r\n\r\n    public void setImageurls(String imageurls)\r\n    {\r\n        this.imageurls = imageurls;\r\n    }\r\n\r\n    public String getImageurlm()\r\n    {\r\n        return imageurlm;\r\n    }\r\n\r\n    public void setImageurlm(String imageurlm)\r\n    {\r\n        this.imageurlm = imageurlm;\r\n    }\r\n\r\n    public String getImageurll()\r\n    {\r\n        return imageurll;\r\n    }\r\n\r\n    public void setImageurll(String imageurll)\r\n    {\r\n        this.imageurll = imageurll;\r\n    }\r\n\r\n    public Float getPrice()\r\n    {\r\n        return price;\r\n    }\r\n\r\n    public void setPrice(Float price)\r\n    {\r\n        this.price = price;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/recommendation/hbase/model/CitySimilarity.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2013 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.recommendation.hbase.model;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.OneToOne;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * \r\n * @author Kuldeep.Mishra\r\n *\r\n */\r\n@Entity\r\n@Table(name = \"city_similarity\", schema = \"KunderaExamples@hbaseTest\")\r\npublic class CitySimilarity\r\n{\r\n\r\n    @Id\r\n    @Column(name = \"id\")\r\n    private String id;\r\n\r\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"bookId\")\r\n    private BookInfo bookInfo;\r\n    \r\n//    priva\r\n\r\n    public void setId(String id)\r\n    {\r\n        this.id = id;\r\n    }\r\n\r\n    public String getId()\r\n    {\r\n        return id;\r\n    }\r\n\r\n    public void setBookInfo(BookInfo bookInfo)\r\n    {\r\n        this.bookInfo = bookInfo;\r\n    }\r\n\r\n    public BookInfo getBookInfo()\r\n    {\r\n        return bookInfo;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/recommendation/hbase/model/CitySimilarityTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.recommendation.hbase.model;\n\nimport java.util.Iterator;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.hadoop.hbase.filter.Filter;\nimport org.apache.hadoop.hbase.filter.KeyOnlyFilter;\nimport org.apache.hadoop.hbase.filter.PrefixFilter;\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.HBaseClient;\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.client.Client;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class CitySimilarityTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private HBaseCli cli = new HBaseCli();\n\n    @Before\n    public void setUp() throws Exception\n    {\n        cli.startCluster();\n        emf = Persistence.createEntityManagerFactory(\"hbaseTest\");\n        em = emf.createEntityManager();\n        BookInfo info1 = new BookInfo();\n        info1.setBookId(\"book1\");\n        info1.setAuthor(\"Vivek\");\n\n        BookInfo info2 = new BookInfo();\n        info2.setBookId(\"book2\");\n        info2.setAuthor(\"Amresh\");\n\n        CitySimilarity city1 = new CitySimilarity();\n        city1.setId(\"100_1\");\n        city1.setBookInfo(info1);\n\n        CitySimilarity city2 = new CitySimilarity();\n        city2.setId(\"100_2\");\n        city2.setBookInfo(info2);\n\n        em.persist(city1);\n        em.persist(city2);\n\n        em.flush();\n        em.clear();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        em.remove(em.find(CitySimilarity.class, \"100_1\"));\n        em.remove(em.find(CitySimilarity.class, \"100_2\"));\n        em.close();\n        \n        emf.close();\n        cli.stopCluster(null);\n    }\n\n    @Test\n    public void testIterator()\n    {\n        String query2 = \"select u from CitySimilarity u\";\n        com.impetus.kundera.query.Query queryObject = (com.impetus.kundera.query.Query) em\n                .createQuery(query2);\n\n        queryObject.setFetchSize(10);\n\n        Iterator<CitySimilarity> resultIterator = queryObject.iterate();\n        CitySimilarity cityS = null;\n        int counter = 0;\n        while (resultIterator.hasNext())\n        {\n            counter++;\n            cityS = resultIterator.next();\n            Assert.assertNotNull(cityS);\n            Assert.assertNotNull(cityS.getId());\n            Assert.assertNotNull(cityS.getBookInfo());\n            Assert.assertNotNull(cityS.getBookInfo().getBookId());\n        }\n        Assert.assertEquals(2, counter);\n    }\n\n    @Test\n    public void testIteratorWithOneFilter()\n    {\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n\n        HBaseClient client = (HBaseClient) clients.get(\"hbaseTest\");\n\n        Filter filter = new PrefixFilter(Bytes.toBytes(\"100\" + \"_\"));\n\n        client.setFilter(new KeyOnlyFilter());\n        client.addFilter(\"city_similarity\", filter);\n\n        String query2 = \"select u from CitySimilarity u\";\n        com.impetus.kundera.query.Query queryObject = (com.impetus.kundera.query.Query) em\n                .createQuery(query2);\n\n        queryObject.setFetchSize(10);\n\n        Iterator<CitySimilarity> resultIterator = queryObject.iterate();\n        CitySimilarity cityS = null;\n        int counter = 0;\n        while (resultIterator.hasNext())\n        {\n            counter++;\n            cityS = resultIterator.next();\n            Assert.assertNotNull(cityS);\n            Assert.assertNotNull(cityS.getId());\n            Assert.assertNull(cityS.getBookInfo());\n        }\n        Assert.assertEquals(2, counter);\n    }\n\n    @Test\n    public void testIteratorWithTwoFilter()\n    {\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n\n        HBaseClient client = (HBaseClient) clients.get(\"hbaseTest\");\n\n        Filter filter = new PrefixFilter(Bytes.toBytes(\"100\" + \"_\"));\n\n        client.addFilter(\"city_similarity\", filter);\n        client.addFilter(\"bookinfo\", new KeyOnlyFilter());\n\n        String query2 = \"select u from CitySimilarity u\";\n        com.impetus.kundera.query.Query queryObject = (com.impetus.kundera.query.Query) em\n                .createQuery(query2);\n\n        queryObject.setFetchSize(10);\n\n        Iterator<CitySimilarity> resultIterator = queryObject.iterate();\n        CitySimilarity cityS = null;\n        int counter = 0;\n        while (resultIterator.hasNext())\n        {\n            counter++;\n            cityS = resultIterator.next();\n            Assert.assertNotNull(cityS);\n            Assert.assertNotNull(cityS.getBookInfo());\n            Assert.assertNotNull(cityS.getBookInfo().getBookId());\n            Assert.assertNull(cityS.getBookInfo().getTitle());\n            Assert.assertNull(cityS.getBookInfo().getAuthor());\n            Assert.assertNull(cityS.getBookInfo().getImageurll());\n            Assert.assertNull(cityS.getBookInfo().getImageurlm());\n            Assert.assertNull(cityS.getBookInfo().getImageurls());\n            Assert.assertNull(cityS.getBookInfo().getMd5());\n            Assert.assertNull(cityS.getBookInfo().getPublisher());\n            Assert.assertNull(cityS.getBookInfo().getYearofpub());\n        }\n        Assert.assertEquals(2, counter);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/recommendation/hbase/model/UserAndPassword.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2013 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.recommendation.hbase.model;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n@Entity\r\n@Table(name = \"userandpassword\", schema = \"KunderaExamples@hbaseTest\")\r\npublic class UserAndPassword\r\n{\r\n    public static final String CF = \"userandpassword\";\r\n\r\n    public static final String CQ_USER_NAME = \"username\";\r\n\r\n    @Id\r\n    @Column(name = \"id\")\r\n    private String id;\r\n\r\n    @Column(name = \"username\")\r\n    private String userName;\r\n\r\n    @Column(name = \"firstName\")\r\n    private String firstName;\r\n\r\n    @Column(name = \"lastName\")\r\n    private String lastName;\r\n\r\n    @Column(name = \"password\")\r\n    private String password;\r\n\r\n    public String getPassword()\r\n    {\r\n        return password;\r\n    }\r\n\r\n    public void setPassword(String password)\r\n    {\r\n        this.password = password;\r\n    }\r\n\r\n    public void setId(String id)\r\n    {\r\n        this.id = id;\r\n    }\r\n\r\n    public String getId()\r\n    {\r\n        return id;\r\n    }\r\n\r\n    public void setUserName(String userName)\r\n    {\r\n        this.userName = userName;\r\n    }\r\n\r\n    public String getUserName()\r\n    {\r\n        return userName;\r\n    }\r\n\r\n    public void setFirstName(String firstName)\r\n    {\r\n        this.firstName = firstName;\r\n    }\r\n\r\n    public String getFirstName()\r\n    {\r\n        return firstName;\r\n    }\r\n\r\n    public void setLastName(String lastName)\r\n    {\r\n        this.lastName = lastName;\r\n    }\r\n\r\n    public String getLastName()\r\n    {\r\n        return lastName;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/recommendation/hbase/model/UserAndPasswordTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.recommendation.hbase.model;\n\nimport java.util.Iterator;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic class UserAndPasswordTest\n{\n\t\n\t/** The Constant logger. */\n    private static final Logger logger = LoggerFactory.getLogger(UserAndPasswordTest.class);\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private HBaseCli cli = new HBaseCli();\n\n    @Before\n    public void setUp() throws Exception\n    {\n        cli.startCluster();\n        emf = Persistence.createEntityManagerFactory(\"hbaseTest\");\n        em = emf.createEntityManager();\n        for (int i = 1; i < 10; i++)\n        {\n            UserAndPassword user = new UserAndPassword();\n            user.setId(i + \"\");\n            user.setUserName(\"KK\" + i);\n            user.setFirstName(\"Kuldeep\" + i);\n            user.setLastName(\"Mishra\" + i);\n            user.setPassword(\"xxx\" + i);\n            em.persist(user);\n        }\n        em.clear();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        for (int i = 1; i < 10; i++)\n        {\n            em.remove(em.find(UserAndPassword.class, i + \"\"));\n        }\n        em.close();\n        emf.close();\n        cli.stopCluster(null);\n    }\n\n    @Test\n    public void testWithSameEM()\n    {\n        try\n        {\n            String query = \"select u from UserAndPassword u where u.userName=KK5\";\n            com.impetus.kundera.query.Query q = (com.impetus.kundera.query.Query) em\n                    .createQuery(query);\n            q.setFetchSize(1);\n            Iterator<UserAndPassword> results = q.iterate();\n            while (results.hasNext())\n            {\n                UserAndPassword user = results.next();\n                Assert.assertNotNull(user);\n                Assert.assertEquals(\"KK5\", user.getUserName());\n                Assert.assertEquals(\"Kuldeep5\", user.getFirstName());\n                Assert.assertEquals(\"Mishra5\", user.getLastName());\n                Assert.assertEquals(\"xxx5\", user.getPassword());\n                Assert.assertEquals(\"5\", user.getId());\n            }\n\n            query = \"select u from UserAndPassword u where u.userName=KK6\";\n            q = (com.impetus.kundera.query.Query) em.createQuery(query);\n            q.setFetchSize(1);\n            results = q.iterate();\n            while (results.hasNext())\n            {\n                UserAndPassword user = results.next();\n                Assert.assertNotNull(user);\n                Assert.assertEquals(\"KK6\", user.getUserName());\n                Assert.assertEquals(\"Kuldeep6\", user.getFirstName());\n                Assert.assertEquals(\"Mishra6\", user.getLastName());\n                Assert.assertEquals(\"xxx6\", user.getPassword());\n                Assert.assertEquals(\"6\", user.getId());\n            }\n        }\n        catch (Exception ex)\n        {\n        \tlogger.warn(ex.getMessage());\n            Assert.fail(ex.getMessage());\n        }\n    }\n\n    @Test\n    public void testWithDifferentEM()\n    {\n        try\n        {\n            String query = \"select u from UserAndPassword u where u.userName=KK5\";\n            com.impetus.kundera.query.Query q = (com.impetus.kundera.query.Query) em\n                    .createQuery(query);\n            q.setFetchSize(1);\n            Iterator<UserAndPassword> results = q.iterate();\n            while (results.hasNext())\n            {\n                UserAndPassword user = results.next();\n                Assert.assertNotNull(user);\n                Assert.assertEquals(\"KK5\", user.getUserName());\n                Assert.assertEquals(\"Kuldeep5\", user.getFirstName());\n                Assert.assertEquals(\"Mishra5\", user.getLastName());\n                Assert.assertEquals(\"xxx5\", user.getPassword());\n                Assert.assertEquals(\"5\", user.getId());\n            }\n\n            // query = \"select u from UserAndPassword u\";\n            // q = (com.impetus.kundera.query.Query<UserAndPassword>)\n            // em.createQuery(query);\n            //\n            // Map<String, Client> clients = (Map<String, Client>)\n            // em.getDelegate();\n            // HBaseClient client = (HBaseClient) clients.get(\"hbaseTest\");\n            //\n            // Filter filter = new PrefixFilter(Bytes.toBytes(\"KK\"));\n            //\n            // client.setFilter(new KeyOnlyFilter());\n            // client.addFilter(\"city_similarity\", filter);\n            //\n            // q.setFetchSize(4);\n            // results = q.iterate();\n            // while (results.hasNext())\n            // {\n            // List<UserAndPassword> users =\n            // ((com.impetus.client.hbase.query.ResultIterator<UserAndPassword>)\n            // results)\n            // .next(2);\n            // Assert.assertNotNull(users);\n            // Assert.assertEquals(2, users.size());\n            // }\n            // em.close();\n\n            em = emf.createEntityManager();\n            query = \"select u from UserAndPassword u where u.userName=KK6\";\n            q = (com.impetus.kundera.query.Query) em.createQuery(query);\n            q.setFetchSize(1);\n            results = q.iterate();\n            while (results.hasNext())\n            {\n                UserAndPassword user = results.next();\n                Assert.assertNotNull(user);\n                Assert.assertEquals(\"KK6\", user.getUserName());\n                Assert.assertEquals(\"Kuldeep6\", user.getFirstName());\n                Assert.assertEquals(\"Mishra6\", user.getLastName());\n                Assert.assertEquals(\"xxx6\", user.getPassword());\n                Assert.assertEquals(\"6\", user.getId());\n            }\n        }\n        catch (Exception ex)\n        {\n        \tlogger.warn(ex.getMessage());\n            Assert.fail(ex.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/recommendation/hbase/model/UserInfo.java",
    "content": "package com.impetus.recommendation.hbase.model;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n@Entity\r\n@Table(name = \"user_info\", schema = \"KunderaExamples@hbaseTest\")\r\npublic class UserInfo\r\n{\r\n    @Id\r\n    @Column(name = \"userId\")\r\n    private String userId;\r\n\r\n    @Column(name = \"age\")\r\n    private String age;\r\n\r\n    @Column(name = \"cityName\")\r\n    private String cityName;\r\n\r\n    @Column(name = \"cityId\")\r\n    private String cityId;\r\n\r\n    @Column(name = \"state\")\r\n    private String state;\r\n\r\n    @Column(name = \"country\")\r\n    private String country;\r\n\r\n    @Column(name = \"firstName\")\r\n    private String firstName;\r\n\r\n    @Column(name = \"lastName\")\r\n    private String lastName;\r\n\r\n    @Column(name = \"md5\")\r\n    private String md5;\r\n\r\n    public String getAge()\r\n    {\r\n        return age;\r\n    }\r\n\r\n    public void setAge(String age)\r\n    {\r\n        this.age = age;\r\n    }\r\n\r\n    public String getCityName()\r\n    {\r\n        return cityName;\r\n    }\r\n\r\n    public void setCityName(String cityName)\r\n    {\r\n        this.cityName = cityName;\r\n    }\r\n\r\n    public String getCityId()\r\n    {\r\n        return cityId;\r\n    }\r\n\r\n    public void setCityId(String cityId)\r\n    {\r\n        this.cityId = cityId;\r\n    }\r\n\r\n    public String getState()\r\n    {\r\n        return state;\r\n    }\r\n\r\n    public void setState(String state)\r\n    {\r\n        this.state = state;\r\n    }\r\n\r\n    public String getCountry()\r\n    {\r\n        return country;\r\n    }\r\n\r\n    public void setCountry(String country)\r\n    {\r\n        this.country = country;\r\n    }\r\n\r\n    public String getFirstName()\r\n    {\r\n        return firstName;\r\n    }\r\n\r\n    public void setFirstName(String firstName)\r\n    {\r\n        this.firstName = firstName;\r\n    }\r\n\r\n    public String getLastName()\r\n    {\r\n        return lastName;\r\n    }\r\n\r\n    public void setLastName(String lastName)\r\n    {\r\n        this.lastName = lastName;\r\n    }\r\n\r\n    public String getMd5()\r\n    {\r\n        return md5;\r\n    }\r\n\r\n    public void setMd5(String md5)\r\n    {\r\n        this.md5 = md5;\r\n    }\r\n\r\n    public void setUserId(String userId)\r\n    {\r\n        this.userId = userId;\r\n    }\r\n\r\n    public String getUserId()\r\n    {\r\n        return userId;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\t<!-- Persistence Units for Twitter application -->\n\n\n\t<persistence-unit name=\"hbaseTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"./lucene\" /> -->\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"HBaseSchemaOperationTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.hbase.schemaManager.HBaseEntitySimple</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"2181\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaHbaseTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kundera-hbase.properties\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"hbase\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.hbase.schemaManager.HBaseEntitySimple</class>\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileHandset</class>\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileManufacturer</class>\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileOperatingSystem</class>\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.Person</class>\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.PersonChild</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"2181\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaHbaseExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kundera-hbase.properties\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"HbaseDataTypeTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaHbaseDataType\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\n\t<persistence-unit name=\"XmlPropertyTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaHbaseXmlTest\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"HbaseBatchTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaHbaseDataType\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.batch.size\" value=\"5\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"ilpMainSchema\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"twibaseTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"2181\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"./lucene\" /> -->\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"hbase_generated_id\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"2181\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"kundera\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"hbaseESindexerTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.query.Person</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.indexer.class\" value=\"com.impetus.client.es.index.ESIndexer\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\n\n</persistence>\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/resources/META-INF/persistence_2_0.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!-- persistence.xml schema -->\r\n<xsd:schema targetNamespace=\"http://java.sun.com/xml/ns/persistence\" \r\n  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\r\n  xmlns:persistence=\"http://java.sun.com/xml/ns/persistence\"\r\n  elementFormDefault=\"qualified\" \r\n  attributeFormDefault=\"unqualified\" \r\n  version=\"2.0\">\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n      @(#)persistence_2_0.xsd  1.0  October 1 2009\r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n\r\n  Copyright (c) 2008, 2009 Sun Microsystems. All rights reserved. \r\n  \r\n  This program and the accompanying materials are made available under the \r\n  terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 \r\n  which accompanies this distribution. \r\n  The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html\r\n  and the Eclipse Distribution License is available at \r\n  http://www.eclipse.org/org/documents/edl-v10.php.\r\n  \r\n  Contributors:\r\n      Linda DeMichiel - Java Persistence 2.0, Version 2.0 (October 1, 2009)\r\n      Specification available from http://jcp.org/en/jsr/detail?id=317\r\n \r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n   <xsd:annotation>\r\n     <xsd:documentation><![CDATA[\r\n\r\n     This is the XML Schema for the persistence configuration file.\r\n     The file must be named \"META-INF/persistence.xml\" in the \r\n     persistence archive.\r\n\r\n     Persistence configuration files must indicate\r\n     the persistence schema by using the persistence namespace:\r\n\r\n     http://java.sun.com/xml/ns/persistence\r\n\r\n     and indicate the version of the schema by\r\n     using the version element as shown below:\r\n\r\n      <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n        xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n          http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\"\r\n        version=\"2.0\">\r\n          ...\r\n      </persistence>\r\n\r\n    ]]></xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:simpleType name=\"versionType\">\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:pattern value=\"[0-9]+(\\.[0-9]+)*\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:element name=\"persistence\">\r\n    <xsd:complexType>\r\n      <xsd:sequence>\r\n\r\n        <!-- **************************************************** -->\r\n\r\n        <xsd:element name=\"persistence-unit\" \r\n                     minOccurs=\"1\" maxOccurs=\"unbounded\">\r\n          <xsd:complexType>\r\n            <xsd:annotation>\r\n              <xsd:documentation>\r\n\r\n                Configuration of a persistence unit.\r\n\r\n              </xsd:documentation>\r\n            </xsd:annotation>\r\n            <xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"description\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Description of this persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"provider\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Provider class that supplies EntityManagers for this \r\n                    persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of the JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"non-jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of a non-JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"mapping-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    File containing mapping information. Loaded as a resource \r\n                    by the persistence provider.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jar-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Jar file that is to be scanned for managed classes. \r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"class\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Managed class to be included in the persistence unit and\r\n                    to scan for annotations.  It should be annotated \r\n                    with either @Entity, @Embeddable or @MappedSuperclass.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"exclude-unlisted-classes\" type=\"xsd:boolean\" \r\n                           default=\"true\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    When set to true then only listed classes and jars will \r\n                    be scanned for persistent classes, otherwise the \r\n                    enclosing jar or directory will also be scanned. \r\n                    Not applicable to Java SE persistence units.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"shared-cache-mode\" \r\n                           type=\"persistence:persistence-unit-caching-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Defines whether caching is enabled for the \r\n                    persistence unit if caching is supported by the\r\n                    persistence provider. When set to ALL, all entities \r\n                    will be cached. When set to NONE, no entities will\r\n                    be cached. When set to ENABLE_SELECTIVE, only entities\r\n                    specified as cacheable will be cached. When set to\r\n                    DISABLE_SELECTIVE, entities specified as not cacheable\r\n                    will not be cached. When not specified or when set to\r\n                    UNSPECIFIED, provider defaults may apply.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"validation-mode\" \r\n                           type=\"persistence:persistence-unit-validation-mode-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The validation mode to be used for the persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"properties\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    A list of standard and vendor-specific properties \r\n                    and hints.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n                <xsd:complexType>\r\n                  <xsd:sequence>\r\n                    <xsd:element name=\"property\" \r\n                                 minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                      <xsd:annotation>\r\n                        <xsd:documentation>\r\n                          A name-value pair.\r\n                        </xsd:documentation>\r\n                      </xsd:annotation>\r\n                      <xsd:complexType>\r\n                        <xsd:attribute name=\"name\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                        <xsd:attribute name=\"value\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                      </xsd:complexType>\r\n                    </xsd:element>\r\n                  </xsd:sequence>\r\n                </xsd:complexType>\r\n              </xsd:element>\r\n\r\n            </xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Name used in code to reference this persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"transaction-type\" \r\n                           type=\"persistence:persistence-unit-transaction-type\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Type of transactions used by EntityManagers from this \r\n                  persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n          </xsd:complexType>\r\n        </xsd:element>\r\n      </xsd:sequence>\r\n      <xsd:attribute name=\"version\" type=\"persistence:versionType\" \r\n                     fixed=\"2.0\" use=\"required\"/>\r\n    </xsd:complexType>\r\n  </xsd:element>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-transaction-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum PersistenceUnitTransactionType {JTA, RESOURCE_LOCAL};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"JTA\"/>\r\n      <xsd:enumeration value=\"RESOURCE_LOCAL\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-caching-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum SharedCacheMode { ALL, NONE, ENABLE_SELECTIVE, DISABLE_SELECTIVE, UNSPECIFIED};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"ALL\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n      <xsd:enumeration value=\"ENABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"DISABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"UNSPECIFIED\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-validation-mode-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum ValidationMode { AUTO, CALLBACK, NONE};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"AUTO\"/>\r\n      <xsd:enumeration value=\"CALLBACK\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n</xsd:schema>\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/resources/esindexer.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<indexerProperties>\n\t<nodes>\n\t\t<node>\n\t\t\t<properties>\n\t\t\t\t<property name=\"host\" value=\"localhost\" />\n\t\t\t\t<property name=\"port\" value=\"9300\" />\n\t\t\t</properties>\n\t\t</node>\n\t</nodes>\n</indexerProperties>"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/resources/kundera-hbase.properties",
    "content": "zookeeper.port = 2181\nzookeeper.host = localhost\ncf.defs=HBaseEntity|GZ|123456|5|2"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase/src/test/resources/log4j.properties",
    "content": "log4j.rootLogger=ERROR, DRFA, CONSOLE\r\n\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t<artifactId>kundera-hbase-parent</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-hbase-v2</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-hbase-v2</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<hbase.version>1.2.2</hbase.version>\n\t\t<thrift.version>0.9.2</thrift.version>\n\t</properties>\n\n\t<!-- Hadoop dependency has been removed from here because it was creating \n\t\tversion conflict with hbase dep. (hbase also has hadoop dependency) -->\n\t<dependencies>\n\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hbase</groupId>\n\t\t\t<artifactId>hbase-client</artifactId>\n\t\t\t<version>${hbase.version}</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.slf4j</groupId>\n\t\t\t\t\t<artifactId>slf4j-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hbase</groupId>\n\t\t\t<artifactId>hbase-server</artifactId>\n\t\t\t<version>${hbase.version}</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.slf4j</groupId>\n\t\t\t\t\t<artifactId>slf4j-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hbase</groupId>\n\t\t\t<artifactId>hbase-server</artifactId>\n\t\t\t<version>${hbase.version}</version>\n\t\t\t<classifier>tests</classifier>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hbase</groupId>\n\t\t\t<artifactId>hbase-common</artifactId>\n\t\t\t<version>${hbase.version}</version>\n\t\t\t<classifier>tests</classifier>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.thrift</groupId>\n\t\t\t<artifactId>libthrift</artifactId>\n\t\t\t<version>${thrift.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hbase</groupId>\n\t\t\t<artifactId>hbase-common</artifactId>\n\t\t\t<version>${hbase.version}</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.slf4j</groupId>\n\t\t\t\t\t<artifactId>slf4j-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hbase</groupId>\n\t\t\t<artifactId>hbase-hadoop-compat</artifactId>\n\t\t\t<version>${hbase.version}</version>\n\t\t</dependency>\n\n\t</dependencies>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-clean-plugin</artifactId>\n\t\t\t\t<version>2.4.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<filesets>\n\t\t\t\t\t\t<fileset>\n\t\t\t\t\t\t\t<directory>${basedir}</directory>\n\t\t\t\t\t\t\t<excludes>\n\t\t\t\t\t\t\t\t<exclude>.git/**</exclude>\n\t\t\t\t\t\t\t\t<exclude>.gitignore</exclude>\n\t\t\t\t\t\t\t</excludes>\n\t\t\t\t\t\t\t<includes>\n\t\t\t\t\t\t\t\t<include>lucene/**</include>\n\t\t\t\t\t\t\t</includes>\n\t\t\t\t\t\t</fileset>\n\t\t\t\t\t</filesets>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/HBaseClient.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.hbase.client.Connection;\nimport org.apache.hadoop.hbase.client.Row;\nimport org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;\nimport org.apache.hadoop.hbase.filter.Filter;\nimport org.apache.hadoop.hbase.filter.FilterList;\nimport org.apache.hadoop.hbase.filter.KeyOnlyFilter;\nimport org.apache.hadoop.hbase.filter.SingleColumnValueFilter;\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.admin.DataHandler;\nimport com.impetus.client.hbase.admin.HBaseDataHandler;\nimport com.impetus.client.hbase.admin.HBaseRow;\nimport com.impetus.client.hbase.query.HBaseQuery;\nimport com.impetus.client.hbase.utils.HBaseUtils;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.lifecycle.states.RemovedState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class HBaseClient.\n * \n * @author Devender Yadav\n */\npublic class HBaseClient extends ClientBase implements Client<HBaseQuery>, Batcher, ClientPropertiesSetter\n{\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(HBaseClient.class);\n\n    /** The handler. */\n    DataHandler handler;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /** The nodes. */\n    private List<Node> nodes = new ArrayList<Node>();\n\n    /** The batch size. */\n    private int batchSize;\n\n    /**\n     * Instantiates a new h base client.\n     * \n     * @param indexManager\n     *            the index manager\n     * @param conf\n     *            the conf\n     * @param connection\n     *            the connection\n     * @param reader\n     *            the reader\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param externalProperties\n     *            the external properties\n     * @param clientMetadata\n     *            the client metadata\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public HBaseClient(IndexManager indexManager, Configuration conf, Connection connection, EntityReader reader,\n            String persistenceUnit, Map<String, Object> externalProperties, ClientMetadata clientMetadata,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata, externalProperties, persistenceUnit);\n        this.indexManager = indexManager;\n        this.handler = new HBaseDataHandler(kunderaMetadata, connection);\n        this.reader = reader;\n        this.clientMetadata = clientMetadata;\n        this.batchSize = getBatchSize(persistenceUnit, this.externalProperties);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.Object, java.util.List)\n     */\n    @Override\n    public Object find(Class entityClass, Object rowId)\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        Object enhancedEntity = null;\n        if (rowId == null)\n        {\n            return null;\n        }\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n        {\n            rowId = KunderaCoreUtils.prepareCompositeKey(m, rowId);\n        }\n        try\n        {\n            List results = findData(m, rowId, null, null, null, null);\n            if (results != null && !results.isEmpty())\n            {\n                enhancedEntity = results.get(0);\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error during find by id, Caused by: .\", e);\n            throw new KunderaException(\"Error during find by id, Caused by: .\", e);\n        }\n        return enhancedEntity;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.Object[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... rowIds)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        if (rowIds == null)\n        {\n            return null;\n        }\n        List<E> results = new ArrayList<E>();\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(entityClass);\n        List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n        try\n        {\n            if (!subManagedType.isEmpty())\n            {\n                for (AbstractManagedType subEntity : subManagedType)\n                {\n                    EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                            subEntity.getJavaType());\n                    results = handler.readAll(subEntityMetadata.getSchema(), subEntityMetadata.getEntityClazz(),\n                            subEntityMetadata, Arrays.asList(rowIds), subEntityMetadata.getRelationNames());\n                    if (!results.isEmpty())\n                    {\n                        break;\n                    }\n                }\n            }\n            else\n            {\n                results = handler.readAll(entityMetadata.getSchema(), entityMetadata.getEntityClazz(), entityMetadata,\n                        Arrays.asList(rowIds), entityMetadata.getRelationNames());\n            }\n        }\n        catch (IOException ioex)\n        {\n            log.error(\"Error during find All , Caused by: .\", ioex);\n            throw new KunderaException(\"Error during find All , Caused by: .\", ioex);\n        }\n\n        return results;\n    }\n\n    /**\n     * (non-Javadoc).\n     * \n     * @param <E>\n     *            the element type\n     * @param entityClass\n     *            the entity class\n     * @param column\n     *            the column\n     * @return the list\n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     *      java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> column)\n    {\n        throw new UnsupportedOperationException(\"This feature is not supported in HBase\");\n    }\n\n    /**\n     * Find data.\n     * \n     * @param <E>\n     *            the element type\n     * @param m\n     *            the m\n     * @param rowKey\n     *            the row key\n     * @param startRow\n     *            the start row\n     * @param endRow\n     *            the end row\n     * @param columnsToOutput\n     *            the columns to output\n     * @param filters\n     *            the filters\n     * @return the list\n     */\n    public <E> List<E> findData(EntityMetadata m, Object rowKey, byte[] startRow, byte[] endRow,\n            List<Map<String, Object>> columnsToOutput, Filter filters)\n    {\n        String tableName = HBaseUtils.getHTableName(m.getSchema(), m.getTableName());\n        FilterList filterList = getFilterList(filters);\n        try\n        {\n            return handler.readData(tableName, m, rowKey, startRow, endRow, columnsToOutput, filterList);\n        }\n        catch (IOException ioex)\n        {\n            log.error(\"Error during find by range, Caused by: .\", ioex);\n            throw new KunderaException(\"Error during find by range, Caused by: .\", ioex);\n        }\n    }\n\n    /**\n     * Gets the filter list.\n     * \n     * @param filters\n     *            the filters\n     * @return the filter list\n     */\n    private FilterList getFilterList(Filter filters)\n    {\n        FilterList filterList = null;\n        if (filters != null)\n        {\n            if (FilterList.class.isAssignableFrom(filters.getClass()))\n            {\n                filterList = (FilterList) filters;\n            }\n            else\n            {\n                filterList = new FilterList();\n                filterList.addFilter(filters);\n            }\n        }\n        return filterList;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    @Override\n    public void close()\n    {\n        handler.shutdown();\n        externalProperties = null;\n    }\n\n    /**\n     * Sets the filter.\n     * \n     * @param filter\n     *            the new filter\n     */\n    public void setFilter(Filter filter)\n    {\n        ((HBaseDataHandler) handler).setFilter(filter);\n    }\n\n    /**\n     * Adds the filter.\n     * \n     * @param columnFamily\n     *            the column family\n     * @param filter\n     *            the filter\n     */\n    public void addFilter(final String columnFamily, Filter filter)\n    {\n        ((HBaseDataHandler) handler).addFilter(columnFamily, filter);\n    }\n\n    /**\n     * Reset filter.\n     */\n    public void resetFilter()\n    {\n        ((HBaseDataHandler) handler).resetFilter();\n    }\n\n    /**\n     * Sets the fetch size.\n     * \n     * @param fetchSize\n     *            the new fetch size\n     */\n    public void setFetchSize(int fetchSize)\n    {\n        ((HBaseDataHandler) handler).setFetchSize(fetchSize);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.metadata\n     * .model.EntityMetadata, java.lang.Object, java.lang.Object,\n     * java.util.List)\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> relations)\n    {\n        String tableName = HBaseUtils.getHTableName(entityMetadata.getSchema(), entityMetadata.getTableName());\n        try\n        {\n            handler.writeData(tableName, entityMetadata, entity, id, relations, showQuery);\n        }\n        catch (IOException e)\n        {\n            throw new PersistenceException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera\n     * .persistence.context.jointable.JoinTableData)\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        String joinTableName = joinTableData.getJoinTableName();\n        String invJoinColumnName = joinTableData.getInverseJoinColumnName();\n        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();\n        String tableName = HBaseUtils.getHTableName(joinTableData.getSchemaName(), joinTableName);\n        for (Object key : joinTableRecords.keySet())\n        {\n            Set<Object> values = joinTableRecords.get(key);\n            Object joinColumnValue = key;\n            Map<String, Object> columns = new HashMap<String, Object>();\n            for (Object childValue : values)\n            {\n                columns.put(invJoinColumnName + \"_\" + childValue, childValue);\n            }\n            if (columns != null && !columns.isEmpty())\n            {\n                try\n                {\n                    handler.writeJoinTableData(tableName, joinColumnValue, columns, joinTableName);\n                    KunderaCoreUtils.printQuery(\"Persist Join Table:\" + joinTableName, showQuery);\n                }\n                catch (IOException e)\n                {\n                    throw new PersistenceException(e);\n                }\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#getForeignKeysFromJoinTable(java.lang\n     * .String, java.lang.String, java.lang.String,\n     * com.impetus.kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.persistence.handler.impl.EntitySaveGraph)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String joinTableName, String joinColumnName,\n            String inverseJoinColumnName, Object parentId, Class columnJavaType)\n    {\n        return handler.getForeignKeysFromJoinTable(schemaName, joinTableName, parentId, inverseJoinColumnName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    @Override\n    public void deleteByColumn(String tableName, String colFamily, String columnName, Object columnValue)\n    {\n        try\n        {\n            String hTableName = HBaseUtils.getHTableName(tableName, colFamily);\n            handler.deleteRow(columnValue, columnName, colFamily, hTableName);\n        }\n        catch (IOException ioex)\n        {\n            log.error(\"Error during get columns by key. Caused by: .\", ioex);\n            throw new PersistenceException(ioex);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    public void delete(Object entity, Object rowKey)\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n        {\n            rowKey = KunderaCoreUtils.prepareCompositeKey(m, rowKey);\n        }\n        deleteByColumn(m.getSchema(), m.getTableName(), null, rowKey);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n        String tableName = HBaseUtils.getHTableName(m.getSchema(), m.getTableName());\n        String columnFamilyName = m.getTableName();\n        byte[] valueInBytes = HBaseUtils.getBytes(colValue);\n        SingleColumnValueFilter filter = new SingleColumnValueFilter(Bytes.toBytes(columnFamilyName),\n                Bytes.toBytes(colName), CompareOp.EQUAL, valueInBytes);\n        filter.setFilterIfMissing(true);\n        try\n        {\n            return ((HBaseDataHandler) handler).readData(tableName, m, null, null, null, null, getFilterList(filter));\n        }\n        catch (IOException ex)\n        {\n            log.error(\"Error during find By Relation, Caused by: .\", ex);\n            throw new KunderaException(\"Error during find By Relation, Caused by: .\", ex);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<HBaseQuery> getQueryImplementor()\n    {\n        return HBaseQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n        CompareOp operator = HBaseUtils.getOperator(\"=\", false, false).getOperator();\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n\n        byte[] valueInBytes = HBaseUtils.getBytes(columnValue);\n        Filter f = new SingleColumnValueFilter(Bytes.toBytes(tableName), Bytes.toBytes(columnName), operator,\n                valueInBytes);\n        KeyOnlyFilter keyFilter = new KeyOnlyFilter();\n        FilterList filterList = new FilterList(f, keyFilter);\n        try\n        {\n            return handler.scanRowyKeys(filterList, schemaName, tableName, columnName + \"_\" + columnValue, m\n                    .getIdAttribute().getBindableJavaType());\n        }\n        catch (IOException e)\n        {\n            log.error(\"Error while executing findIdsByColumn(), Caused by: .\", e);\n            throw new KunderaException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.api.Batcher#addBatch(com.impetus.kundera\n     * .graph.Node)\n     */\n    @Override\n    public void addBatch(Node node)\n    {\n        if (node != null)\n        {\n            nodes.add(node);\n        }\n        onBatchLimit();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#getBatchSize()\n     */\n    @Override\n    public int getBatchSize()\n    {\n        return batchSize;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#clear()\n     */\n    @Override\n    public void clear()\n    {\n        if (nodes != null)\n        {\n            nodes.clear();\n            nodes = new ArrayList<Node>();\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#executeBatch()\n     */\n    @Override\n    public int executeBatch()\n    {\n        Map<String, List<Row>> batchData = new HashMap<String, List<Row>>();\n        try\n        {\n            for (Node node : nodes)\n            {\n                if (node.isDirty())\n                {\n                    Row action = null;\n                    node.handlePreEvent();\n                    Object rowKey = node.getEntityId();\n                    Object entity = node.getData();\n                    EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, node.getDataClass());\n                    String tableName = HBaseUtils.getHTableName(m.getSchema(), m.getTableName());\n                    if (node.isInState(RemovedState.class))\n                    {\n                        action = handler.prepareDelete(rowKey);\n                    }\n                    else\n                    {\n                        HBaseRow hbaseRow = ((HBaseDataHandler) handler).createHbaseRow(m, entity, rowKey, null);\n                        action = handler.preparePut(hbaseRow);\n                    }\n                    node.handlePostEvent();\n                    if (!batchData.containsKey(tableName))\n                    {\n                        batchData.put(tableName, new ArrayList<Row>());\n                    }\n                    batchData.get(tableName).add(action);\n                }\n            }\n\n            if (!batchData.isEmpty())\n            {\n                ((HBaseDataHandler) handler).batchProcess(batchData);\n            }\n            return batchData.size();\n        }\n        catch (IOException ioex)\n        {\n            log.error(\"Error while executing batch insert/update, Caused by: .\", ioex);\n            throw new KunderaException(ioex);\n        }\n\n    }\n\n    /**\n     * On batch limit.\n     */\n    private void onBatchLimit()\n    {\n        if (batchSize > 0 && batchSize == nodes.size())\n        {\n            executeBatch();\n            nodes.clear();\n        }\n    }\n\n    /**\n     * Gets the batch size.\n     * \n     * @param persistenceUnit\n     *            the persistence unit\n     * @param puProperties\n     *            the pu properties\n     * @return the batch size\n     */\n    private int getBatchSize(String persistenceUnit, Map<String, Object> puProperties)\n    {\n        String batch_size = puProperties != null ? (String) puProperties.get(PersistenceProperties.KUNDERA_BATCH_SIZE)\n                : null;\n        return batch_size != null ? Integer.valueOf(batch_size) : KunderaMetadataManager.getPersistenceUnitMetadata(\n                kunderaMetadata, persistenceUnit).getBatchSize();\n    }\n\n    /**\n     * Sets the batch size.\n     * \n     * @param batch_size\n     *            the new batch size\n     */\n    public void setBatchSize(int batch_size)\n    {\n        this.batchSize = batch_size;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientPropertiesSetter#populateClientProperties\n     * (com.impetus.kundera.client.Client, java.util.Map)\n     */\n    @Override\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        new HBaseClientProperties().populateClientProperties(client, properties);\n    }\n\n    /**\n     * Reset.\n     */\n    public void reset()\n    {\n        ((HBaseDataHandler) handler).reset();\n    }\n\n    /**\n     * Next.\n     * \n     * @param m\n     *            the m\n     * @param columnsToOutput\n     *            the columns to output\n     * @return the object\n     */\n    public Object next(EntityMetadata m, List<Map<String, Object>> columnsToOutput)\n    {\n        return ((HBaseDataHandler) handler).next(m, columnsToOutput);\n    }\n\n    /**\n     * Checks for next.\n     * \n     * @return true, if successful\n     */\n    public boolean hasNext()\n    {\n        return ((HBaseDataHandler) handler).hasNext();\n    }\n\n    /**\n     * Gets the handle.\n     * \n     * @return the handle\n     */\n    public HBaseDataHandler getHandle()\n    {\n        return ((HBaseDataHandler) handler).getHandle();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        return (Generator) KunderaCoreUtils.createNewInstance(HBaseIdGenerator.class);\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/HBaseClientFactory.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2015 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase;\r\n\r\nimport java.io.IOException;\r\nimport java.util.Map;\r\n\r\nimport org.apache.hadoop.conf.Configuration;\r\nimport org.apache.hadoop.hbase.HBaseConfiguration;\r\nimport org.apache.hadoop.hbase.client.ConnectionFactory;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.client.hbase.config.HBasePropertyReader;\r\nimport com.impetus.client.hbase.schemamanager.HBaseSchemaManager;\r\nimport com.impetus.kundera.KunderaException;\r\nimport com.impetus.kundera.PersistenceProperties;\r\nimport com.impetus.kundera.client.Client;\r\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection;\r\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\r\nimport com.impetus.kundera.loader.GenericClientFactory;\r\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\r\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\r\n\r\n/**\r\n * HBaseClientFactory, instantiates client for HBase.\r\n */\r\n/**\r\n * @author Devender Yadav\r\n * \r\n */\r\npublic class HBaseClientFactory extends GenericClientFactory\r\n{\r\n    /** The logger. */\r\n    private static Logger logger = LoggerFactory.getLogger(HBaseClientFactory.class);\r\n\r\n    /** The conf. */\r\n    private Configuration conf;\r\n\r\n    /** The connection. */\r\n    private org.apache.hadoop.hbase.client.Connection connection;\r\n\r\n    /** The Constant DEFAULT_ZOOKEEPER_PORT. */\r\n    private static final String DEFAULT_ZOOKEEPER_PORT = \"2181\";\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.loader.GenericClientFactory#initialize(java.util.Map)\r\n     */\r\n    @Override\r\n    public void initialize(Map<String, Object> externalProperty)\r\n    {\r\n        setExternalProperties(externalProperty);\r\n        initializePropertyReader();\r\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\r\n                getPersistenceUnit());\r\n\r\n        String node = null;\r\n        String port = null;\r\n        String poolSize = null;\r\n        if (externalProperty != null)\r\n        {\r\n            node = (String) externalProperty.get(PersistenceProperties.KUNDERA_NODES);\r\n            port = (String) externalProperty.get(PersistenceProperties.KUNDERA_PORT);\r\n            poolSize = (String) externalProperty.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE);\r\n        }\r\n        if (node == null)\r\n        {\r\n            node = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_NODES);\r\n        }\r\n        if (port == null)\r\n        {\r\n            port = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_PORT);\r\n        }\r\n        if (poolSize == null)\r\n        {\r\n            poolSize = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE);\r\n        }\r\n        onValidation(node, port);\r\n\r\n        Configuration hadoopConf = new Configuration();\r\n        hadoopConf.set(\"hbase.master\", node + \":\" + port);\r\n\r\n        Connection conn = HBasePropertyReader.hsmd.getDataStore() != null ? HBasePropertyReader.hsmd.getDataStore()\r\n                .getConnection() : null;\r\n        if (conn != null && conn.getProperties() != null)\r\n        {\r\n            String zookeeperHost = conn.getProperties().getProperty(\"hbase.zookeeper.quorum\").trim();\r\n            String zookeeperPort = conn.getProperties().getProperty(\"hbase.zookeeper.property.clientPort\").trim();\r\n            hadoopConf.set(\"hbase.zookeeper.quorum\", zookeeperHost != null ? zookeeperHost : node);\r\n            hadoopConf.set(\"hbase.zookeeper.property.clientPort\", zookeeperPort != null ? zookeeperPort\r\n                    : DEFAULT_ZOOKEEPER_PORT);\r\n        }\r\n        else\r\n        {\r\n            hadoopConf.set(\"hbase.zookeeper.quorum\", node);\r\n            hadoopConf.set(\"hbase.zookeeper.property.clientPort\", DEFAULT_ZOOKEEPER_PORT);\r\n        }\r\n        conf = HBaseConfiguration.create(hadoopConf);\r\n        reader = new HBaseEntityReader(kunderaMetadata);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.loader.GenericClientFactory#createPoolOrConnection()\r\n     */\r\n    @Override\r\n    protected Object createPoolOrConnection()\r\n    {\r\n        try\r\n        {\r\n            this.connection = ConnectionFactory.createConnection(conf);\r\n            return connection;\r\n        }\r\n        catch (IOException e)\r\n        {\r\n            logger.error(\"Connection could not be established\", e);\r\n            throw new KunderaException(\"Connection could not be established\", e);\r\n        }\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.loader.GenericClientFactory#instantiateClient(java\r\n     * .lang.String)\r\n     */\r\n    @Override\r\n    protected Client instantiateClient(String persistenceUnit)\r\n    {\r\n        return new HBaseClient(indexManager, conf, connection, reader, persistenceUnit, externalProperties,\r\n                clientMetadata, kunderaMetadata);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.loader.GenericClientFactory#isThreadSafe()\r\n     */\r\n    @Override\r\n    public boolean isThreadSafe()\r\n    {\r\n        return false;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.loader.ClientLifeCycleManager#destroy()\r\n     */\r\n    @Override\r\n    public void destroy()\r\n    {\r\n        try\r\n        {\r\n            if (schemaManager != null)\r\n            {\r\n                schemaManager.dropSchema();\r\n            }\r\n            externalProperties = null;\r\n            schemaManager = null;\r\n            connection.close();\r\n\r\n        }\r\n        catch (IOException e)\r\n        {\r\n            logger.error(\"connection already closed\", e);\r\n            throw new KunderaException(\"connection already closed\", e);\r\n        }\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.loader.ClientFactory#getSchemaManager(java.util.Map)\r\n     */\r\n    @Override\r\n    public SchemaManager getSchemaManager(Map<String, Object> externalProperty)\r\n    {\r\n        setExternalProperties(externalProperty);\r\n        if (schemaManager == null)\r\n        {\r\n            initializePropertyReader();\r\n            schemaManager = new HBaseSchemaManager(HBaseClientFactory.class.getName(), externalProperty,\r\n                    kunderaMetadata);\r\n        }\r\n        return schemaManager;\r\n    }\r\n\r\n    /**\r\n     * Initialize property reader.\r\n     */\r\n    private void initializePropertyReader()\r\n    {\r\n        if (propertyReader == null)\r\n        {\r\n            propertyReader = new HBasePropertyReader(externalProperties, kunderaMetadata.getApplicationMetadata()\r\n                    .getPersistenceUnitMetadata(getPersistenceUnit()));\r\n            propertyReader.read(getPersistenceUnit());\r\n        }\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.loader.GenericClientFactory#initializeLoadBalancer\r\n     * (java.lang.String)\r\n     */\r\n    @Override\r\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\r\n    {\r\n        throw new UnsupportedOperationException(\"Load balancing feature is not supported in \"\r\n                + this.getClass().getSimpleName());\r\n    }\r\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/HBaseClientProperties.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase;\n\nimport java.util.Map;\n\nimport org.apache.hadoop.hbase.filter.Filter;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\n\n/**\n * The Class HBaseClientProperties.\n */\n/**\n * @author Devender Yadav\n * \n */\nclass HBaseClientProperties\n{\n    /** The Constant FILTER. */\n    private static final String FILTER = \"hbase.filter\";\n\n    /** The hbase client. */\n    private HBaseClient hbaseClient;\n\n    /**\n     * Populate client properties.\n     * \n     * @param client\n     *            the client\n     * @param properties\n     *            the properties\n     */\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        this.hbaseClient = (HBaseClient) client;\n\n        if (properties != null)\n        {\n\n            for (String key : properties.keySet())\n            {\n                Object value = properties.get(key);\n                if (checkNull(key, value))\n                {\n                    if (key.equals(FILTER) && value instanceof Filter)\n                    {\n                        this.hbaseClient.setFilter((Filter) value);\n                    }\n                    else if (key.equals(PersistenceProperties.KUNDERA_BATCH_SIZE))\n                    {\n                        setBatchSize(value);\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * Sets the batch size.\n     * \n     * @param value\n     *            the new batch size\n     */\n    private void setBatchSize(Object value)\n    {\n        if (value instanceof Integer)\n        {\n            this.hbaseClient.setBatchSize((Integer) value);\n        }\n        else if (value instanceof String)\n        {\n            this.hbaseClient.setBatchSize(Integer.valueOf((String) value));\n        }\n\n    }\n\n    /**\n     * Check null.\n     * \n     * @param key\n     *            the key\n     * @param value\n     *            the value\n     * @return true, if successful\n     */\n    private boolean checkNull(String key, Object value)\n    {\n        return key != null && value != null;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/HBaseConstants.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase;\n\n/**\n * The Class HBaseConstants.\n * \n * @author Pragalbh Garg\n */\npublic final class HBaseConstants\n{\n\n    /** The Constant CF_DEFS. */\n    public static final String CF_DEFS = \"cf.defs\";\n\n    /** The Constant ZOOKEEPER_PORT. */\n    public static final String ZOOKEEPER_PORT = \"zookeeper.port\";\n\n    /** The Constant ZOOKEEPER_HOST. */\n    public static final String ZOOKEEPER_HOST = \"zookeeper.host\";\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/HBaseDataWrapper.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2015 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport org.apache.hadoop.hbase.Cell;\r\nimport org.apache.hadoop.hbase.CellUtil;\r\nimport org.apache.hadoop.hbase.util.Bytes;\r\n\r\nimport com.impetus.kundera.DataWrapper;\r\n\r\n/**\r\n * The Class HBaseData.\r\n * \r\n * @author Pragalbh Garg\r\n */\r\npublic class HBaseDataWrapper implements DataWrapper\r\n{\r\n\r\n    /** The table name. */\r\n    private String tableName;\r\n\r\n    /** The row key. */\r\n    private byte[] rowKey;\r\n\r\n    /** The columns. */\r\n    private Map<String, byte[]> columns = new HashMap<String, byte[]>();\r\n\r\n    /**\r\n     * Instantiates a new h base data.\r\n     * \r\n     * @param tableName\r\n     *            the table name\r\n     * @param rowKey\r\n     *            the row key\r\n     */\r\n    public HBaseDataWrapper(String tableName, byte[] rowKey)\r\n    {\r\n        this.tableName = tableName;\r\n        this.rowKey = rowKey;\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new h base data.\r\n     * \r\n     * @param rowKey\r\n     *            the row key\r\n     */\r\n    public HBaseDataWrapper(byte[] rowKey)\r\n    {\r\n        this.rowKey = rowKey;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.DataWrapper#getColumnFamily()\r\n     */\r\n    @Override\r\n    public String getColumnFamily()\r\n    {\r\n        return tableName;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see com.impetus.kundera.DataWrapper#getRowKey()\r\n     */\r\n    @Override\r\n    public byte[] getRowKey()\r\n    {\r\n        return rowKey;\r\n    }\r\n\r\n    /**\r\n     * Gets the column value.\r\n     * \r\n     * @param qualifier\r\n     *            the qualifier\r\n     * @return the column value\r\n     */\r\n    public byte[] getColumnValue(String qualifier)\r\n    {\r\n        return columns.get(qualifier);\r\n    }\r\n\r\n    /**\r\n     * Gets the columns.\r\n     * \r\n     * @return the columns\r\n     */\r\n    public Map<String, byte[]> getColumns()\r\n    {\r\n        return columns;\r\n    }\r\n\r\n    /**\r\n     * Sets the columns.\r\n     * \r\n     * @param columns\r\n     *            the new columns\r\n     */\r\n    public void setColumns(List<Cell> columns)\r\n    {\r\n        for (Cell column : columns)\r\n        {\r\n            putColumn(CellUtil.cloneFamily(column), CellUtil.cloneQualifier(column), CellUtil.cloneValue(column));\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Put column.\r\n     * \r\n     * @param family\r\n     *            the family\r\n     * @param qualifier\r\n     *            the qualifier\r\n     * @param qualifierValue\r\n     *            the qualifier value\r\n     */\r\n    private void putColumn(byte[] family, byte[] qualifier, byte[] qualifierValue)\r\n    {\r\n        this.columns.put(Bytes.toString(family) + \":\" + Bytes.toString(qualifier), qualifierValue);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/HBaseEntityReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase;\n\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * The Class HBaseEntityReader.\n * \n * @author Pragalbh Garg\n */\npublic class HBaseEntityReader extends AbstractEntityReader implements EntityReader\n{\n\n    /**\n     * Instantiates a new h base entity reader.\n     * \n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public HBaseEntityReader(final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    /**\n     * Instantiates a new h base entity reader.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public HBaseEntityReader(KunderaQuery kunderaQuery, final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n        this.kunderaQuery = kunderaQuery;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#populateRelation(com.impetus\n     * .kundera.metadata.model.EntityMetadata, java.util.List, boolean,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        throw new UnsupportedOperationException(\"Method is not supported\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#findById(java.lang.String,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.util.List,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        return super.findById(primaryKey, m, client);\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/HBaseIdGenerator.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase;\n\nimport java.io.IOException;\n\nimport org.apache.hadoop.hbase.client.Table;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.admin.HBaseDataHandler;\nimport com.impetus.client.hbase.utils.HBaseUtils;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.generator.TableGenerator;\nimport com.impetus.kundera.metadata.model.TableGeneratorDiscriptor;\n\n/**\n * The Class HBaseIdGenerator.\n * \n * @author: karthikp.manchala\n */\npublic class HBaseIdGenerator implements TableGenerator\n{\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(HBaseIdGenerator.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.TableGenerator#generate(com.impetus.kundera\n     * .metadata.model.TableGeneratorDiscriptor,\n     * com.impetus.kundera.client.ClientBase, java.lang.Object)\n     */\n    @Override\n    public Object generate(TableGeneratorDiscriptor discriptor, ClientBase client, String dataType)\n    {\n        String tableName = HBaseUtils.getHTableName(discriptor.getSchema(), discriptor.getPkColumnValue());\n        try\n        {\n            Table hTable = ((HBaseDataHandler) ((HBaseClient) client).handler).gethTable(tableName);\n            Long latestCount = hTable.incrementColumnValue(HBaseUtils.AUTO_ID_ROW.getBytes(), discriptor\n                    .getPkColumnValue().getBytes(), discriptor.getValueColumnName().getBytes(), 1);\n            if (latestCount == 1)\n            {\n                return (long) discriptor.getInitialValue();\n            }\n            else if (discriptor.getAllocationSize() == 1)\n            {\n                return latestCount + discriptor.getInitialValue();\n            }\n            else\n            {\n                return (latestCount - 1) * discriptor.getAllocationSize() + discriptor.getInitialValue();\n            }\n        }\n        catch (IOException ioex)\n        {\n            log.error(\"Error while generating id for entity, Caused by: .\", ioex);\n            throw new KunderaException(ioex);\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/Reader.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2015 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase;\r\n\r\nimport java.io.IOException;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport org.apache.hadoop.hbase.client.Table;\r\nimport org.apache.hadoop.hbase.filter.Filter;\r\n\r\n/**\r\n * The Interface Reader.\r\n * \r\n * @author Pragalbh Garg\r\n */\r\npublic interface Reader\r\n{\r\n    /**\r\n     * Scan row keys.\r\n     * \r\n     * @param hTable\r\n     *            the h table\r\n     * @param filter\r\n     *            the filter\r\n     * @param columnFamilyName\r\n     *            the column family name\r\n     * @param columnName\r\n     *            the column name\r\n     * @param rowKeyClazz\r\n     *            the row key clazz\r\n     * @return the object[]\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    Object[] scanRowKeys(final Table hTable, final Filter filter, final String columnFamilyName,\r\n            final String columnName, final Class rowKeyClazz) throws IOException;\r\n\r\n    /**\r\n     * Load data.\r\n     * \r\n     * @param hTable\r\n     *            the h table\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param startRow\r\n     *            the start row\r\n     * @param endRow\r\n     *            the end row\r\n     * @param columnFamily\r\n     *            the column family\r\n     * @param filter\r\n     *            the filter\r\n     * @param outputColumns\r\n     *            the output columns\r\n     * @return the list\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    List<HBaseDataWrapper> loadData(Table hTable, Object rowKey, byte[] startRow, byte[] endRow, String columnFamily,\r\n            Filter filter, List<Map<String, Object>> outputColumns) throws IOException;\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/Writer.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2015 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase;\r\n\r\nimport java.io.IOException;\r\nimport java.util.Map;\r\n\r\nimport org.apache.hadoop.hbase.client.Table;\r\n\r\nimport com.impetus.client.hbase.admin.HBaseRow;\r\n\r\n/**\r\n * The Interface Writer.\r\n * \r\n * @author Pragalbh Garg\r\n */\r\npublic interface Writer\r\n{\r\n\r\n    /**\r\n     * Writes columns data to HBase table, supplied as a map in Key/ value pair;\r\n     * key and value representing column name and value respectively.\r\n     * \r\n     * @param htable\r\n     *            the htable\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param columns\r\n     *            the columns\r\n     * @param columnFamilyName\r\n     *            the column family name\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void writeColumns(Table htable, Object rowKey, Map<String, Object> columns, String columnFamilyName)\r\n            throws IOException;\r\n\r\n    /**\r\n     * Delete.\r\n     * \r\n     * @param hTable\r\n     *            the h table\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param colFamily\r\n     *            the col family\r\n     * @param colName\r\n     *            the col name\r\n     */\r\n    void delete(Table hTable, Object rowKey, String colFamily, String colName);\r\n\r\n    /**\r\n     * Write row.\r\n     * \r\n     * @param hTable\r\n     *            the h table\r\n     * @param hbaseRow\r\n     *            the hbase row\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void writeRow(Table hTable, HBaseRow hbaseRow) throws IOException;\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/admin/DataHandler.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2015 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase.admin;\r\n\r\nimport java.io.IOException;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport org.apache.hadoop.hbase.client.Put;\r\nimport org.apache.hadoop.hbase.client.Row;\r\nimport org.apache.hadoop.hbase.filter.FilterList;\r\n\r\nimport com.impetus.kundera.db.RelationHolder;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\n\r\n/**\r\n * The Interface DataHandler.\r\n * \r\n * @author Pragalbh Garg\r\n */\r\npublic interface DataHandler\r\n{\r\n\r\n    /**\r\n     * Creates the table if does not exist.\r\n     * \r\n     * @param tableName\r\n     *            the table name\r\n     * @param colFamily\r\n     *            the col family\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void createTableIfDoesNotExist(String tableName, String... colFamily) throws IOException;\r\n\r\n    // /**\r\n    // * Read data.\r\n    // *\r\n    // * @param tableName\r\n    // * the table name\r\n    // * @param clazz\r\n    // * the clazz\r\n    // * @param m\r\n    // * the m\r\n    // * @param rowKey\r\n    // * the row key\r\n    // * @param relatationNames\r\n    // * the relatation names\r\n    // * @param f\r\n    // * the f\r\n    // * @param colToOutput\r\n    // * the col to output\r\n    // * @return the list\r\n    // * @throws IOException\r\n    // * Signals that an I/O exception has occurred.\r\n    // */\r\n    // List readData(String tableName, Class clazz, EntityMetadata m, Object\r\n    // rowKey, List<String> relatationNames,\r\n    // FilterList f, List<Map<String, Object>> colToOutput) throws IOException;\r\n\r\n    /**\r\n     * Read data.\r\n     * \r\n     * @param tableName\r\n     *            the table name\r\n     * @param m\r\n     *            the m\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param startRow\r\n     *            the start row\r\n     * @param endRow\r\n     *            the end row\r\n     * @param columnsToOutput\r\n     *            the columns to output\r\n     * @param filterList\r\n     *            the filter list\r\n     * @return the list\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    List readData(String tableName, EntityMetadata m, final Object rowKey, byte[] startRow, byte[] endRow,\r\n            List<Map<String, Object>> columnsToOutput, FilterList filterList) throws IOException;\r\n\r\n    /**\r\n     * Read all.\r\n     * \r\n     * @param tableName\r\n     *            the table name\r\n     * @param clazz\r\n     *            the clazz\r\n     * @param m\r\n     *            the m\r\n     * @param rowKeys\r\n     *            the row keys\r\n     * @param relatationNames\r\n     *            the relatation names\r\n     * @param columns\r\n     *            the columns\r\n     * @return the list\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    List readAll(String tableName, Class clazz, EntityMetadata m, List<Object> rowKeys, List<String> relatationNames,\r\n            String... columns) throws IOException;\r\n\r\n    // /**\r\n    // * Read data by range.\r\n    // *\r\n    // * @param tableName\r\n    // * the table name\r\n    // * @param clazz\r\n    // * the clazz\r\n    // * @param m\r\n    // * the m\r\n    // * @param startRow\r\n    // * the start row\r\n    // * @param endRow\r\n    // * the end row\r\n    // * @param colToOutput\r\n    // * the col to output\r\n    // * @param f\r\n    // * the f\r\n    // * @return the list\r\n    // * @throws IOException\r\n    // * Signals that an I/O exception has occurred.\r\n    // */\r\n    // List readDataByRange(String tableName, Class clazz, EntityMetadata m,\r\n    // byte[] startRow, byte[] endRow,\r\n    // List<Map<String, Object>> colToOutput, FilterList f) throws IOException;\r\n\r\n    /**\r\n     * Write data.\r\n     * \r\n     * @param schemaName\r\n     *            the schema name\r\n     * @param m\r\n     *            the m\r\n     * @param entity\r\n     *            the entity\r\n     * @param rowId\r\n     *            the row id\r\n     * @param relations\r\n     *            the relations\r\n     * @param showQuery\r\n     *            the show query\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void writeData(String schemaName, EntityMetadata m, Object entity, Object rowId, List<RelationHolder> relations,\r\n            boolean showQuery) throws IOException;\r\n\r\n    /**\r\n     * Write join table data.\r\n     * \r\n     * @param tableName\r\n     *            the table name\r\n     * @param rowId\r\n     *            the row id\r\n     * @param columns\r\n     *            the columns\r\n     * @param columnFamilyName\r\n     *            the column family name\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void writeJoinTableData(String tableName, Object rowId, Map<String, Object> columns, String columnFamilyName)\r\n            throws IOException;\r\n\r\n    /**\r\n     * Gets the foreign keys from join table.\r\n     * \r\n     * @param <E>\r\n     *            the element type\r\n     * @param schemaName\r\n     *            the schema name\r\n     * @param joinTableName\r\n     *            the join table name\r\n     * @param rowKey\r\n     *            the row key\r\n     * @param inverseJoinColumnName\r\n     *            the inverse join column name\r\n     * @return the foreign keys from join table\r\n     */\r\n    <E> List<E> getForeignKeysFromJoinTable(String schemaName, String joinTableName, Object rowKey,\r\n            String inverseJoinColumnName);\r\n\r\n    /**\r\n     * Find parent entity from join table.\r\n     * \r\n     * @param <E>\r\n     *            the element type\r\n     * @param parentMetadata\r\n     *            the parent metadata\r\n     * @param joinTableName\r\n     *            the join table name\r\n     * @param joinColumnName\r\n     *            the join column name\r\n     * @param inverseJoinColumnName\r\n     *            the inverse join column name\r\n     * @param childId\r\n     *            the child id\r\n     * @return the list\r\n     */\r\n    <E> List<E> findParentEntityFromJoinTable(EntityMetadata parentMetadata, String joinTableName,\r\n            String joinColumnName, String inverseJoinColumnName, Object childId);\r\n\r\n    /**\r\n     * Shutdown.\r\n     */\r\n    void shutdown();\r\n\r\n    /**\r\n     * Delete row.\r\n     * \r\n     * @param rowKey\r\n     *            the row key\r\n     * @param colName\r\n     *            the col name\r\n     * @param colFamily\r\n     *            the col family\r\n     * @param tableName\r\n     *            the table name\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    void deleteRow(Object rowKey, String colName, String colFamily, String tableName) throws IOException;\r\n\r\n    /**\r\n     * Scan rowy keys.\r\n     * \r\n     * @param filterList\r\n     *            the filter list\r\n     * @param tableName\r\n     *            the table name\r\n     * @param columnFamilyName\r\n     *            the column family name\r\n     * @param columnName\r\n     *            the column name\r\n     * @param rowKeyClazz\r\n     *            the row key clazz\r\n     * @return the object[]\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    Object[] scanRowyKeys(FilterList filterList, String tableName, String columnFamilyName, String columnName,\r\n            Class rowKeyClazz) throws IOException;\r\n\r\n    /**\r\n     * Prepare put.\r\n     * \r\n     * @param hbaseRow\r\n     *            the hbase row\r\n     * @return the put\r\n     */\r\n    Put preparePut(HBaseRow hbaseRow);\r\n\r\n    /**\r\n     * Prepare delete.\r\n     * \r\n     * @param rowKey\r\n     *            the row key\r\n     * @return the row\r\n     */\r\n    Row prepareDelete(Object rowKey);\r\n\r\n    /**\r\n     * Batch process.\r\n     * \r\n     * @param batchData\r\n     *            the batch data\r\n     */\r\n    void batchProcess(Map<String, List<Row>> batchData);\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/admin/HBaseCell.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.admin;\n\n/**\n * The Class HBaseCell.\n * \n * @author Pragalbh Garg\n */\npublic class HBaseCell\n{\n\n    /** The column family. */\n    private String columnFamily;\n\n    /** The column name. */\n    private String columnName;\n\n    /** The value. */\n    private Object value;\n\n    /**\n     * Instantiates a new h base cell.\n     * \n     * @param columnFamily\n     *            the column family\n     * @param columnName\n     *            the column name\n     * @param value\n     *            the value\n     */\n    public HBaseCell(String columnFamily, String columnName, Object value)\n    {\n        super();\n        this.columnFamily = columnFamily;\n        this.columnName = columnName;\n        this.value = value;\n    }\n\n    /**\n     * Gets the column family.\n     * \n     * @return the column family\n     */\n    public String getColumnFamily()\n    {\n        return columnFamily;\n    }\n\n    /**\n     * Sets the column family.\n     * \n     * @param columnFamily\n     *            the new column family\n     */\n    public void setColumnFamily(String columnFamily)\n    {\n        this.columnFamily = columnFamily;\n    }\n\n    /**\n     * Gets the column name.\n     * \n     * @return the column name\n     */\n    public String getColumnName()\n    {\n        return columnName;\n    }\n\n    /**\n     * Sets the column name.\n     * \n     * @param columnName\n     *            the new column name\n     */\n    public void setColumnName(String columnName)\n    {\n        this.columnName = columnName;\n    }\n\n    /**\n     * Gets the value.\n     * \n     * @return the value\n     */\n    public Object getValue()\n    {\n        return value;\n    }\n\n    /**\n     * Sets the value.\n     * \n     * @param value\n     *            the new value\n     */\n    public void setValue(Object value)\n    {\n        this.value = value;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/admin/HBaseDataHandler.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.admin;\n\nimport java.io.IOException;\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.hadoop.hbase.HColumnDescriptor;\nimport org.apache.hadoop.hbase.HTableDescriptor;\nimport org.apache.hadoop.hbase.MasterNotRunningException;\nimport org.apache.hadoop.hbase.TableName;\nimport org.apache.hadoop.hbase.client.Connection;\nimport org.apache.hadoop.hbase.client.Delete;\nimport org.apache.hadoop.hbase.client.HBaseAdmin;\nimport org.apache.hadoop.hbase.client.Put;\nimport org.apache.hadoop.hbase.client.Row;\nimport org.apache.hadoop.hbase.client.Table;\nimport org.apache.hadoop.hbase.filter.Filter;\nimport org.apache.hadoop.hbase.filter.FilterList;\nimport org.apache.hadoop.hbase.filter.KeyOnlyFilter;\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.jboss.netty.util.internal.ConcurrentHashMap;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.HBaseDataWrapper;\nimport com.impetus.client.hbase.Reader;\nimport com.impetus.client.hbase.Writer;\nimport com.impetus.client.hbase.service.HBaseReader;\nimport com.impetus.client.hbase.service.HBaseWriter;\nimport com.impetus.client.hbase.utils.HBaseUtils;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class HBaseDataHandler.\n * \n * @author Pragalbh Garg\n */\npublic class HBaseDataHandler implements DataHandler\n{\n    /** the log used by this class. */\n    private static Logger logger = LoggerFactory.getLogger(HBaseDataHandler.class);\n\n    /** The admin. */\n    private HBaseAdmin admin;\n\n    /** The connection. */\n    private Connection connection;\n\n    /** The hbase reader. */\n    private Reader hbaseReader = new HBaseReader();\n\n    /** The hbase writer. */\n    private Writer hbaseWriter = new HBaseWriter();\n\n    /** The filter. */\n    private FilterList filter = null;\n\n    /** The filters. */\n    private Map<String, FilterList> filters = new ConcurrentHashMap<String, FilterList>();\n\n    /** The kundera metadata. */\n    private KunderaMetadata kunderaMetadata;\n\n    /**\n     * Instantiates a new hBase data handler.\n     * \n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param connection\n     *            the connection\n     */\n    public HBaseDataHandler(final KunderaMetadata kunderaMetadata, final Connection connection)\n    {\n        this.kunderaMetadata = kunderaMetadata;\n        this.connection = connection;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#createTableIfDoesNotExist(\n     * java.lang.String, java.lang.String[])\n     */\n    @Override\n    public void createTableIfDoesNotExist(final String tableName, final String... colFamily)\n            throws MasterNotRunningException, IOException\n    {\n        if (!admin.tableExists(Bytes.toBytes(tableName)))\n        {\n            HTableDescriptor htDescriptor = new HTableDescriptor(TableName.valueOf(tableName));\n            for (String columnFamily : colFamily)\n            {\n                HColumnDescriptor familyMetadata = new HColumnDescriptor(columnFamily);\n                htDescriptor.addFamily(familyMetadata);\n            }\n            admin.createTable(htDescriptor);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#readData(java.lang.String,\n     * java.lang.Class, com.impetus.kundera.metadata.model.EntityMetadata,\n     * java.lang.String, java.util.List)\n     */\n    @Override\n    public List readAll(final String tableName, Class clazz, EntityMetadata m, final List<Object> rowKey,\n            List<String> relationNames, String... columns) throws IOException\n    {\n        Table hTable = gethTable(tableName);\n        List<HBaseDataWrapper> results = ((HBaseReader) hbaseReader).loadAll(hTable, rowKey, null, columns);\n        return onRead(m, null, hTable, results);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#readData(java.lang.String,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.lang.Object,\n     * byte[], byte[], java.util.List,\n     * org.apache.hadoop.hbase.filter.FilterList)\n     */\n    @Override\n    public List readData(String tableName, EntityMetadata m, final Object rowKey, byte[] startRow, byte[] endRow,\n            List<Map<String, Object>> columnsToOutput, FilterList filterList) throws IOException\n    {\n        Table hTable = gethTable(tableName);\n        filterList = getExtPropertyFilters(m, filterList);\n        boolean isFindKeyOnly = HBaseUtils.isFindKeyOnly(m, columnsToOutput);\n        filterList = onFindKeyOnly(filterList, isFindKeyOnly);\n        List<HBaseDataWrapper> results = hbaseReader.loadData(hTable, rowKey, startRow, endRow, null, filterList,\n                !isFindKeyOnly ? columnsToOutput : new ArrayList<Map<String, Object>>());\n        return onRead(m, columnsToOutput, hTable, results);\n    }\n\n    /**\n     * On find key only.\n     * \n     * @param filterList\n     *            the filter list\n     * @param isFindKeyOnly\n     *            the is find key only\n     * @return the filter list\n     */\n    private FilterList onFindKeyOnly(FilterList filterList, boolean isFindKeyOnly)\n    {\n        if (isFindKeyOnly)\n        {\n            if (filterList == null)\n            {\n                filterList = new FilterList();\n            }\n            filterList.addFilter(new KeyOnlyFilter());\n        }\n        return filterList;\n    }\n\n    /**\n     * Gets the ext property filters.\n     * \n     * @param m\n     *            the m\n     * @param filterList\n     *            the filter list\n     * @return the ext property filters\n     */\n    private FilterList getExtPropertyFilters(EntityMetadata m, FilterList filterList)\n    {\n        Filter filter = getFilter(m.getTableName());\n        if (filter != null)\n        {\n            if (filterList == null)\n            {\n                filterList = new FilterList();\n            }\n            filterList.addFilter(filter);\n        }\n        return filterList;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#writeData(java.lang.String,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.lang.Object,\n     * java.lang.Object, java.util.List, boolean)\n     */\n    @Override\n    public void writeData(String tableName, EntityMetadata m, Object entity, Object rowId,\n            List<RelationHolder> relations, boolean showQuery) throws IOException\n    {\n        HBaseRow hbaseRow = createHbaseRow(m, entity, rowId, relations);\n        writeHbaseRowInATable(tableName, hbaseRow);\n    }\n\n    /**\n     * Creates the hbase row.\n     * \n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param rowId\n     *            the row id\n     * @param relations\n     *            the relations\n     * @return the hBase row\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    public HBaseRow createHbaseRow(EntityMetadata m, Object entity, Object rowId, List<RelationHolder> relations)\n            throws IOException\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n        Set<Attribute> attributes = entityType.getAttributes();\n        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n        {\n            rowId = KunderaCoreUtils.prepareCompositeKey(m, rowId);\n        }\n        HBaseRow hbaseRow = new HBaseRow(rowId, new ArrayList<HBaseCell>());\n        // handle attributes and embeddables\n        createCellsAndAddToRow(entity, metaModel, attributes, hbaseRow, m, -1, \"\");\n        // handle relations\n        if (relations != null && !relations.isEmpty())\n        {\n            hbaseRow.addCells(getRelationCell(m, rowId, relations));\n        }\n        // handle inheritence\n        String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n        String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();\n        if (discrColumn != null && discrValue != null)\n        {\n            hbaseRow.addCell(new HBaseCell(m.getTableName(), discrColumn, discrValue));\n        }\n        return hbaseRow;\n    }\n\n    /**\n     * Gets the relation cell.\n     * \n     * @param m\n     *            the m\n     * @param rowId\n     *            the row id\n     * @param relations\n     *            the relations\n     * @return the relation cell\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    private List<HBaseCell> getRelationCell(EntityMetadata m, Object rowId, List<RelationHolder> relations)\n            throws IOException\n    {\n        List<HBaseCell> relationCells = new ArrayList<HBaseCell>();\n        for (RelationHolder relation : relations)\n        {\n            HBaseCell hBaseCell = new HBaseCell(m.getTableName(), relation.getRelationName(),\n                    relation.getRelationValue());\n            relationCells.add(hBaseCell);\n        }\n        return relationCells;\n    }\n\n    /**\n     * Write hbase row in a table.\n     * \n     * @param tableName\n     *            the table name\n     * @param hbaseRow\n     *            the hbase row\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    private void writeHbaseRowInATable(String tableName, HBaseRow hbaseRow) throws IOException\n    {\n        Table hTable = gethTable(tableName);\n        ((HBaseWriter) hbaseWriter).writeRow(hTable, hbaseRow);\n        hTable.close();\n    }\n\n    /**\n     * Creates the cells and add to row.\n     * \n     * @param entity\n     *            the entity\n     * @param metaModel\n     *            the meta model\n     * @param attributes\n     *            the attributes\n     * @param hbaseRow\n     *            the hbase row\n     * @param m\n     *            the m\n     * @param count\n     *            the count\n     * @param prefix\n     *            the prefix\n     */\n    private void createCellsAndAddToRow(Object entity, MetamodelImpl metaModel, Set<Attribute> attributes,\n            HBaseRow hbaseRow, EntityMetadata m, int count, String prefix)\n    {\n        AbstractAttribute idCol = (AbstractAttribute) m.getIdAttribute();\n        for (Attribute attribute : attributes)\n        {\n            AbstractAttribute absAttrib = (AbstractAttribute) attribute;\n            Class clazz = absAttrib.getBindableJavaType();\n            if (metaModel.isEmbeddable(clazz))\n            {\n                Set<Attribute> attribEmbeddables = metaModel.embeddable(absAttrib.getBindableJavaType())\n                        .getAttributes();\n                Object embeddedField = PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());\n                if (attribute.isCollection() && embeddedField != null)\n                {\n                    int newCount = count + 1;\n                    String newPrefix = prefix != \"\" ? prefix + absAttrib.getJPAColumnName() + HBaseUtils.DELIM\n                            : absAttrib.getJPAColumnName() + HBaseUtils.DELIM;\n                    List listOfEmbeddables = (List) embeddedField;\n                    addColumnForCollectionSize(hbaseRow, listOfEmbeddables.size(), newPrefix, m.getTableName());\n                    for (Object obj : listOfEmbeddables)\n                    {\n                        createCellsAndAddToRow(obj, metaModel, attribEmbeddables, hbaseRow, m, newCount++, newPrefix);\n                    }\n                }\n                else if (embeddedField != null)\n                {\n                    String newPrefix = prefix != \"\" ? prefix + absAttrib.getJPAColumnName() + HBaseUtils.DOT\n                            : absAttrib.getJPAColumnName() + HBaseUtils.DOT;\n                    createCellsAndAddToRow(embeddedField, metaModel, attribEmbeddables, hbaseRow, m, count, newPrefix);\n                }\n            }\n            else if (!attribute.isCollection() && !attribute.isAssociation())\n            {\n                String columnFamily = absAttrib.getTableName() != null ? absAttrib.getTableName() : m.getTableName();\n                String columnName = absAttrib.getJPAColumnName();\n                columnName = count != -1 ? prefix + columnName + HBaseUtils.DELIM + count : prefix + columnName;\n                Object value = PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());\n                HBaseCell hbaseCell = new HBaseCell(columnFamily, columnName, value);\n                if (!idCol.getName().equals(attribute.getName()) && value != null)\n                {\n                    hbaseRow.addCell(hbaseCell);\n                }\n            }\n        }\n    }\n\n    private void addColumnForCollectionSize(HBaseRow hbaseRow, int size, String prefix, String colFamily)\n    {\n        String columnName = prefix + HBaseUtils.SIZE;\n        HBaseCell hbaseCell = new HBaseCell(colFamily, columnName, size);\n        hbaseRow.addCell(hbaseCell);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#writeJoinTableData(java.lang\n     * .String, java.lang.String, java.util.Map)\n     */\n    @Override\n    public void writeJoinTableData(String tableName, Object rowId, Map<String, Object> columns, String columnFamilyName)\n            throws IOException\n    {\n        Table hTable = gethTable(tableName);\n\n        hbaseWriter.writeColumns(hTable, rowId, columns, columnFamilyName);\n\n        closeHTable(hTable);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#getForeignKeysFromJoinTable\n     * (java.lang.String, java.lang.String, java.lang.String)\n     */\n    @Override\n    public <E> List<E> getForeignKeysFromJoinTable(String schemaName, String joinTableName, Object rowKey,\n            String inverseJoinColumnName)\n    {\n        List<E> foreignKeys = new ArrayList<E>();\n        Table hTable = null;\n        String tableName = HBaseUtils.getHTableName(schemaName, joinTableName);\n        try\n        {\n            hTable = gethTable(tableName);\n            List<HBaseDataWrapper> results = hbaseReader.loadData(hTable, rowKey, null, null, joinTableName,\n                    getFilter(joinTableName), null);\n            if (results != null && !results.isEmpty())\n            {\n                HBaseDataWrapper data = results.get(0);\n                Map<String, byte[]> hbaseValues = data.getColumns();\n                Set<String> columnNames = hbaseValues.keySet();\n                for (String columnName : columnNames)\n                {\n                    if (columnName.startsWith(HBaseUtils.getColumnDataKey(joinTableName, inverseJoinColumnName)))\n                    {\n                        byte[] columnValue = data.getColumnValue(columnName);\n                        String hbaseColumnValue = Bytes.toString(columnValue);\n                        foreignKeys.add((E) hbaseColumnValue);\n                    }\n                }\n            }\n        }\n        catch (IOException e)\n        {\n            return foreignKeys;\n        }\n        finally\n        {\n            try\n            {\n                if (hTable != null)\n                {\n                    closeHTable(hTable);\n                }\n            }\n            catch (IOException e)\n            {\n                logger.error(\"Error in closing hTable, caused by: \", e);\n            }\n        }\n        return foreignKeys;\n    }\n\n    /**\n     * Gets the h table.\n     * \n     * @param tableName\n     *            the table name\n     * @return the h table\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    public Table gethTable(final String tableName) throws IOException\n    {\n        return connection.getTable(TableName.valueOf(tableName));\n    }\n\n    /**\n     * Puth table.\n     * \n     * @param hTable\n     *            the h table\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    private void closeHTable(Table hTable) throws IOException\n    {\n        hTable.close();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.hbase.admin.DataHandler#shutdown()\n     */\n    @Override\n    public void shutdown()\n    {\n    }\n\n    /**\n     * Populate entity from hBase data.\n     * \n     * @param entity\n     *            the entity\n     * @param hbaseData\n     *            the hbase data\n     * @param m\n     *            the m\n     * @param rowKey\n     *            the row key\n     * @return the object\n     */\n    private Object populateEntityFromHBaseData(Object entity, HBaseDataWrapper hbaseData, EntityMetadata m,\n            Object rowKey)\n    {\n        try\n        {\n            Map<String, Object> relations = new HashMap<String, Object>();\n            if (entity.getClass().isAssignableFrom(EnhanceEntity.class))\n            {\n                relations = ((EnhanceEntity) entity).getRelations();\n                entity = ((EnhanceEntity) entity).getEntity();\n            }\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n            EntityType entityType = metaModel.entity(m.getEntityClazz());\n            Set<Attribute> attributes = ((AbstractManagedType) entityType).getAttributes();\n\n            writeValuesToEntity(entity, hbaseData, m, metaModel, attributes, m.getRelationNames(), relations, -1, \"\");\n            if (!relations.isEmpty())\n            {\n                return new EnhanceEntity(entity, rowKey, relations);\n            }\n            return entity;\n        }\n        catch (PropertyAccessException e1)\n        {\n            throw new RuntimeException(e1);\n        }\n    }\n\n    /**\n     * Write values to entity.\n     * \n     * @param entity\n     *            the entity\n     * @param hbaseData\n     *            the hbase data\n     * @param m\n     *            the m\n     * @param metaModel\n     *            the meta model\n     * @param attributes\n     *            the attributes\n     * @param relationNames\n     *            the relation names\n     * @param relations\n     *            the relations\n     * @param count\n     *            the count\n     * @param prefix\n     *            the prefix\n     * @return the int\n     */\n    private void writeValuesToEntity(Object entity, HBaseDataWrapper hbaseData, EntityMetadata m,\n            MetamodelImpl metaModel, Set<Attribute> attributes, List<String> relationNames,\n            Map<String, Object> relations, int count, String prefix)\n    {\n        for (Attribute attribute : attributes)\n        {\n            Class javaType = ((AbstractAttribute) attribute).getBindableJavaType();\n            if (metaModel.isEmbeddable(javaType))\n            {\n                processEmbeddable(entity, hbaseData, m, metaModel, count, prefix, attribute, javaType);\n            }\n            else if (!attribute.isCollection())\n            {\n                String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                columnName = count != -1 ? prefix + columnName + HBaseUtils.DELIM + count : prefix + columnName;\n                String idColName = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n                String colFamily = ((AbstractAttribute) attribute).getTableName() != null ? ((AbstractAttribute) attribute)\n                        .getTableName() : m.getTableName();\n                byte[] columnValue = hbaseData.getColumnValue(HBaseUtils.getColumnDataKey(colFamily, columnName));\n                if (relationNames != null && relationNames.contains(columnName) && columnValue != null\n                        && columnValue.length > 0)\n                {\n                    EntityType entityType = metaModel.entity(m.getEntityClazz());\n                    relations.put(columnName, getObjectFromByteArray(entityType, columnValue, columnName, m));\n                }\n                else if (!idColName.equals(columnName) && columnValue != null)\n                {\n                    PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), columnValue);\n                }\n            }\n        }\n    }\n\n    /**\n     * Process embeddable.\n     * \n     * @param entity\n     *            the entity\n     * @param hbaseData\n     *            the hbase data\n     * @param m\n     *            the m\n     * @param metaModel\n     *            the meta model\n     * @param count\n     *            the count\n     * @param prefix\n     *            the prefix\n     * @param attribute\n     *            the attribute\n     * @param javaType\n     *            the java type\n     */\n    private void processEmbeddable(Object entity, HBaseDataWrapper hbaseData, EntityMetadata m,\n            MetamodelImpl metaModel, int count, String prefix, Attribute attribute, Class javaType)\n    {\n        Set<Attribute> attribEmbeddables = metaModel.embeddable(javaType).getAttributes();\n        Object embeddedField = KunderaCoreUtils.createNewInstance(javaType);\n        if (!attribute.isCollection())\n        {\n            String newPrefix = prefix != \"\" ? prefix + ((AbstractAttribute) attribute).getJPAColumnName()\n                    + HBaseUtils.DOT : ((AbstractAttribute) attribute).getJPAColumnName() + HBaseUtils.DOT;\n            writeValuesToEntity(embeddedField, hbaseData, m, metaModel, attribEmbeddables, null, null, count, newPrefix);\n            PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), embeddedField);\n        }\n        else\n        {\n            int newCount = count + 1;\n            String newPrefix = prefix != \"\" ? prefix + ((AbstractAttribute) attribute).getJPAColumnName()\n                    + HBaseUtils.DELIM : ((AbstractAttribute) attribute).getJPAColumnName() + HBaseUtils.DELIM;\n            List embeddedCollection = new ArrayList();\n            byte[] columnValue = hbaseData.getColumnValue(HBaseUtils.getColumnDataKey(m.getTableName(), newPrefix\n                    + HBaseUtils.SIZE));\n            int size = 0;\n            if (columnValue != null)\n            {\n                size = Bytes.toInt(columnValue);\n            }\n            while (size != newCount)\n            {\n                embeddedField = KunderaCoreUtils.createNewInstance(javaType);\n                writeValuesToEntity(embeddedField, hbaseData, m, metaModel, attribEmbeddables, null, null, newCount++,\n                        newPrefix);\n                embeddedCollection.add(embeddedField);\n            }\n            PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), embeddedCollection);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#deleteRow(java.lang.String,\n     * java.lang.String)\n     */\n    @Override\n    public void deleteRow(Object rowKey, String colName, String colFamily, String tableName) throws IOException\n    {\n        Table hTable = gethTable(tableName);\n        hbaseWriter.delete(hTable, rowKey, colFamily, colName);\n        closeHTable(hTable);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#findParentEntityFromJoinTable\n     * (com.impetus.kundera.metadata.model.EntityMetadata, java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    @Override\n    public List<Object> findParentEntityFromJoinTable(EntityMetadata parentMetadata, String joinTableName,\n            String joinColumnName, String inverseJoinColumnName, Object childId)\n    {\n        throw new PersistenceException(\"Not applicable for HBase\");\n    }\n\n    /**\n     * Sets the filter.\n     * \n     * @param filter\n     *            the new filter\n     */\n    public void setFilter(Filter filter)\n    {\n        if (this.filter == null)\n        {\n            this.filter = new FilterList();\n        }\n        if (filter != null)\n        {\n            this.filter.addFilter(filter);\n        }\n    }\n\n    /**\n     * Adds the filter.\n     * \n     * @param columnFamily\n     *            the column family\n     * @param filter\n     *            the filter\n     */\n    public void addFilter(final String columnFamily, Filter filter)\n    {\n        FilterList filterList = this.filters.get(columnFamily);\n        if (filterList == null)\n        {\n            filterList = new FilterList();\n        }\n        if (filter != null)\n        {\n            filterList.addFilter(filter);\n        }\n        this.filters.put(columnFamily, filterList);\n    }\n\n    /**\n     * On read.\n     * \n     * @param m\n     *            the m\n     * @param columnsToOutput\n     *            the columns to output\n     * @param hTable\n     *            the h table\n     * @param results\n     *            the results\n     * @return the list\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    private List onRead(EntityMetadata m, List<Map<String, Object>> columnsToOutput, Table hTable,\n            List<HBaseDataWrapper> results) throws IOException\n    {\n        Class clazz = m.getEntityClazz();\n        List outputResults = new ArrayList();\n        try\n        {\n            if (results != null)\n            {\n                return columnsToOutput != null && !columnsToOutput.isEmpty() ? returnSpecificFieldList(m,\n                        columnsToOutput, results, outputResults) : returnEntityObjectList(m, results, outputResults);\n            }\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Error while creating an instance of {}, Caused by: .\", clazz, e);\n            throw new PersistenceException(e);\n        }\n        finally\n        {\n            if (hTable != null)\n            {\n                closeHTable(hTable);\n            }\n        }\n        return outputResults;\n    }\n\n    /**\n     * Return entity object list.\n     * \n     * @param m\n     *            the m\n     * @param results\n     *            the results\n     * @param outputResults\n     *            the output results\n     * @return the list\n     */\n    private List returnEntityObjectList(EntityMetadata m, List<HBaseDataWrapper> results, List outputResults)\n    {\n        Map<Object, Object> entityListMap = new HashMap<Object, Object>();\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n        List<AbstractManagedType> subManagedTypes = ((AbstractManagedType) entityType).getSubManagedType();\n        Map<String, Class> discrValueToEntityClazz = new HashMap<String, Class>();\n        String discrColumn = null;\n        if (subManagedTypes != null && !subManagedTypes.isEmpty())\n        {\n            for (AbstractManagedType subEntity : subManagedTypes)\n            {\n                discrColumn = ((AbstractManagedType) subEntity).getDiscriminatorColumn();\n                discrValueToEntityClazz.put(subEntity.getDiscriminatorValue(), subEntity.getJavaType());\n            }\n        }\n        for (HBaseDataWrapper data : results)\n        {\n            Class clazz = null;\n            if (discrValueToEntityClazz != null && !discrValueToEntityClazz.isEmpty())\n            {\n                String discrColumnKey = HBaseUtils.getColumnDataKey(m.getTableName(), discrColumn);\n                String discrValue = Bytes.toString(data.getColumnValue(discrColumnKey));\n                clazz = discrValueToEntityClazz.get(discrValue);\n                m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n            }\n            else\n            {\n                clazz = m.getEntityClazz();\n            }\n\n            Object entity = KunderaCoreUtils.createNewInstance(clazz); // Entity\n            Object rowKeyValue = HBaseUtils.fromBytes(m, metaModel, data.getRowKey());\n            if (!metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n            {\n                PropertyAccessorHelper.setId(entity, m, rowKeyValue);\n            }\n            if (entityListMap.get(rowKeyValue) != null)\n            {\n                entity = entityListMap.get(rowKeyValue);\n            }\n            entity = populateEntityFromHBaseData(entity, data, m, null);\n            if (entity != null)\n            {\n                entityListMap.put(rowKeyValue, entity);\n            }\n        }\n        for (Object obj : entityListMap.values())\n        {\n            outputResults.add(obj);\n        }\n        return outputResults;\n    }\n\n    /**\n     * Return specific field list.\n     * \n     * @param m\n     *            the m\n     * @param columnsToOutput\n     *            the columns to output\n     * @param results\n     *            the results\n     * @param outputResults\n     *            the output results\n     * @return the list\n     */\n    private List returnSpecificFieldList(EntityMetadata m, List<Map<String, Object>> columnsToOutput,\n            List<HBaseDataWrapper> results, List outputResults)\n    {\n        for (HBaseDataWrapper data : results)\n        {\n            List result = new ArrayList();\n            Map<String, byte[]> columns = data.getColumns();\n            for (Map<String, Object> map : columnsToOutput)\n            {\n                Object obj;\n                String colDataKey = HBaseUtils.getColumnDataKey((String) map.get(Constants.COL_FAMILY),\n                        (String) map.get(Constants.DB_COL_NAME));\n                if ((boolean) map.get(Constants.IS_EMBEDDABLE))\n                {\n                    Class embedClazz = (Class) map.get(Constants.FIELD_CLAZZ);\n                    String prefix = (String) map.get(Constants.DB_COL_NAME) + HBaseUtils.DOT;\n                    obj = populateEmbeddableObject(data, KunderaCoreUtils.createNewInstance(embedClazz), m, embedClazz,\n                            prefix);\n                }\n                else if (isIdCol(m, (String) map.get(Constants.DB_COL_NAME)))\n                {\n                    obj = HBaseUtils.fromBytes(data.getRowKey(), (Class) map.get(Constants.FIELD_CLAZZ));\n                }\n                else\n                {\n                    obj = HBaseUtils.fromBytes(columns.get(colDataKey), (Class) map.get(Constants.FIELD_CLAZZ));\n                }\n                result.add(obj);\n            }\n            if (columnsToOutput.size() == 1)\n                outputResults.addAll(result);\n            else\n                outputResults.add(result);\n        }\n        return outputResults;\n    }\n\n    /**\n     * Checks if is id col.\n     * \n     * @param m\n     *            the m\n     * @param colName\n     *            the col name\n     * @return true, if is id col\n     */\n    private boolean isIdCol(EntityMetadata m, String colName)\n    {\n        return ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName().equals(colName);\n    }\n\n    /**\n     * Populate embeddable object.\n     * \n     * @param data\n     *            the data\n     * @param obj\n     *            the obj\n     * @param m\n     *            the m\n     * @param clazz\n     *            the clazz\n     * @param prefix\n     * @return the object\n     */\n    private Object populateEmbeddableObject(HBaseDataWrapper data, Object obj, EntityMetadata m, Class clazz,\n            String prefix)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        Set<Attribute> attributes = metaModel.embeddable(clazz).getAttributes();\n        writeValuesToEntity(obj, data, m, metaModel, attributes, null, null, -1, prefix);\n        return obj;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#preparePut(com.impetus.client\n     * .hbase.admin.HBaseRow)\n     */\n    @Override\n    public Put preparePut(HBaseRow hbaseRow)\n    {\n        return ((HBaseWriter) hbaseWriter).preparePut(hbaseRow);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#scanRowyKeys(org.apache.hadoop\n     * .hbase.filter.FilterList, java.lang.String, java.lang.String,\n     * java.lang.String, java.lang.Class)\n     */\n    @Override\n    public Object[] scanRowyKeys(FilterList filterList, String tableName, String columnFamilyName, String columnName,\n            final Class rowKeyClazz) throws IOException\n    {\n        Table hTable = gethTable(tableName);\n        return hbaseReader.scanRowKeys(hTable, filterList, columnFamilyName, columnName, rowKeyClazz);\n    }\n\n    /**\n     * Gets the object from byte array.\n     * \n     * @param entityType\n     *            the entity type\n     * @param value\n     *            the value\n     * @param jpaColumnName\n     *            the jpa column name\n     * @param m\n     *            the m\n     * @return the object from byte array\n     */\n    private Object getObjectFromByteArray(EntityType entityType, byte[] value, String jpaColumnName, EntityMetadata m)\n    {\n        if (jpaColumnName != null)\n        {\n            String fieldName = m.getFieldName(jpaColumnName);\n            if (fieldName != null)\n            {\n                Attribute attribute = fieldName != null ? entityType.getAttribute(fieldName) : null;\n\n                EntityMetadata relationMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                        attribute.getJavaType());\n                Object colValue = PropertyAccessorHelper.getObject(relationMetadata.getIdAttribute().getJavaType(),\n                        value);\n                return colValue;\n            }\n        }\n        logger.warn(\"No value found for column {}, returning null.\", jpaColumnName);\n        return null;\n    }\n\n    /**\n     * Sets the fetch size.\n     * \n     * @param fetchSize\n     *            the new fetch size\n     */\n    public void setFetchSize(final int fetchSize)\n    {\n        ((HBaseReader) hbaseReader).setFetchSize(fetchSize);\n    }\n\n    /**\n     * Next.\n     * \n     * @param m\n     *            the m\n     * @param columnsToOutput\n     *            the columns to output\n     * @return the object\n     */\n    public Object next(EntityMetadata m, List<Map<String, Object>> columnsToOutput)\n    {\n        Object entity = null;\n        HBaseDataWrapper result = ((HBaseReader) hbaseReader).next();\n        List<HBaseDataWrapper> results = new ArrayList<HBaseDataWrapper>();\n        results.add(result);\n        try\n        {\n            List output = onRead(m, columnsToOutput,\n                    gethTable(HBaseUtils.getHTableName(m.getSchema(), m.getTableName())), results);\n            return output != null && !output.isEmpty() ? output.get(0) : output;\n        }\n        catch (IOException e)\n        {\n            logger.error(\"Error during finding next record, Caused by: .\", e);\n            throw new KunderaException(e);\n        }\n    }\n\n    /**\n     * Checks for next.\n     * \n     * @return true, if successful\n     */\n    public boolean hasNext()\n    {\n        return ((HBaseReader) hbaseReader).hasNext();\n    }\n\n    /**\n     * Reset.\n     */\n    public void reset()\n    {\n        resetFilter();\n        ((HBaseReader) hbaseReader).reset();\n    }\n\n    /**\n     * Reset filter.\n     */\n    public void resetFilter()\n    {\n        filter = null;\n        filters = new ConcurrentHashMap<String, FilterList>();\n    }\n\n    /**\n     * Gets the handle.\n     * \n     * @return the handle\n     */\n    public HBaseDataHandler getHandle()\n    {\n        HBaseDataHandler handler = new HBaseDataHandler(this.kunderaMetadata, this.connection);\n        handler.filter = this.filter;\n        handler.filters = this.filters;\n        return handler;\n    }\n\n    /**\n     * Gets the filter.\n     * \n     * @param columnFamily\n     *            the column family\n     * @return the filter\n     */\n    private Filter getFilter(final String columnFamily)\n    {\n        FilterList filter = filters.get(columnFamily);\n        if (filter == null)\n        {\n            return this.filter;\n        }\n        if (this.filter != null)\n        {\n            filter.addFilter(this.filter);\n        }\n        return filter;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#prepareDelete(java.lang.Object\n     * )\n     */\n    @Override\n    public Row prepareDelete(Object rowKey)\n    {\n        byte[] rowBytes = HBaseUtils.getBytes(rowKey);\n        return new Delete(rowBytes);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.admin.DataHandler#batchProcess(java.util.Map)\n     */\n    @Override\n    public void batchProcess(Map<String, List<Row>> batchData)\n    {\n        for (String tableName : batchData.keySet())\n        {\n            List<Row> actions = batchData.get(tableName);\n            try\n            {\n                Table hTable = gethTable(tableName);\n                hTable.batch(actions, new Object[actions.size()]);\n            }\n            catch (IOException | InterruptedException e)\n            {\n                logger.error(\"Error while batch processing on HTable: \" + tableName);\n                throw new PersistenceException(e);\n            }\n\n        }\n\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/admin/HBaseRow.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.admin;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * The Class HBaseRow.\n * \n * @author Pragalbh Garg\n */\npublic class HBaseRow\n{\n\n    /** The row key. */\n    private Object rowKey;\n\n    /** The row cells. */\n    private List<HBaseCell> rowCells = new ArrayList<HBaseCell>();\n\n    /**\n     * Instantiates a new h base row.\n     * \n     * @param rowKey\n     *            the row key\n     * @param rowCells\n     *            the row cells\n     */\n    public HBaseRow(Object rowKey, List<HBaseCell> rowCells)\n    {\n        this.setRowKey(rowKey);\n        this.setRowCells(rowCells);\n    }\n\n    /**\n     * Instantiates a new h base row.\n     */\n    public HBaseRow()\n    {\n    }\n\n    /**\n     * Adds the cell.\n     * \n     * @param hbaseCell\n     *            the hbase cell\n     */\n    public void addCell(HBaseCell hbaseCell)\n    {\n        this.rowCells.add(hbaseCell);\n    }\n\n    /**\n     * Gets the row key.\n     * \n     * @return the row key\n     */\n    public Object getRowKey()\n    {\n        return rowKey;\n    }\n\n    /**\n     * Sets the row key.\n     * \n     * @param rowKey\n     *            the new row key\n     */\n    public void setRowKey(Object rowKey)\n    {\n        this.rowKey = rowKey;\n    }\n\n    /**\n     * Gets the row cells.\n     * \n     * @return the row cells\n     */\n    public List<HBaseCell> getRowCells()\n    {\n        return rowCells;\n    }\n\n    /**\n     * Sets the row cells.\n     * \n     * @param rowCells\n     *            the new row cells\n     */\n    public void setRowCells(List<HBaseCell> rowCells)\n    {\n        this.rowCells = rowCells;\n    }\n\n    /**\n     * Adds the cells.\n     * \n     * @param rowCells\n     *            the row cells\n     */\n    public void addCells(List<HBaseCell> rowCells)\n    {\n        this.rowCells.addAll(rowCells);\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/config/HBasePropertyReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.config;\n\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.HBaseConstants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * The Class HBasePropertyReader.\n * \n * @author Devender Yadav\n */\npublic class HBasePropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n\n    /**\n     * The log instance.\n     */\n    private static Logger logger = LoggerFactory.getLogger(HBasePropertyReader.class);\n\n    /**\n     * The Hbase schema metadata instance.\n     */\n    public static HBaseSchemaMetadata hsmd;\n\n    /**\n     * Instantiates a new h base property reader.\n     * \n     * @param externalProperties\n     *            the external properties\n     * @param puMetadata\n     *            the pu metadata\n     */\n    public HBasePropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        hsmd = new HBaseSchemaMetadata();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.PropertyReader#read(java.lang.String)\n     */\n\n    @Override\n    public void onXml(ClientProperties cp)\n    {\n        hsmd.onInitialize();\n        if (cp != null)\n        {\n            hsmd.setClientProperties(cp);\n        }\n    }\n\n    /**\n     * The Class HBaseSchemaMetadata.\n     */\n    public class HBaseSchemaMetadata\n    {\n\n        /** The Constant HBASE. */\n        private static final String HBASE = \"hbase\";\n\n        /**\n         * zookeeper port.\n         */\n        private String zookeeperPort = \"2181\";\n\n        /**\n         * zookeeper host.\n         */\n        private String zookeeperHost;\n\n        /**\n         * client properties.\n         */\n        private ClientProperties clientProperties;\n\n        /**\n         * On initialize.\n         */\n        private void onInitialize()\n        {\n            zookeeperHost = puMetadata != null ? puMetadata.getProperty(PersistenceProperties.KUNDERA_NODES) : null;\n        }\n\n        /**\n         * Gets the client properties.\n         * \n         * @return the client properties\n         */\n        public ClientProperties getClientProperties()\n        {\n            return clientProperties;\n        }\n\n        /**\n         * Sets the client properties.\n         * \n         * @param clientProperties\n         *            the new client properties\n         */\n        private void setClientProperties(ClientProperties clientProperties)\n        {\n            this.clientProperties = clientProperties;\n        }\n\n        /**\n         * Gets the zookeeper port.\n         * \n         * @return the zookeeper port\n         */\n        public String getZookeeperPort()\n        {\n            DataStore ds = getDataStore();\n            if (ds != null && ds.getConnection() != null)\n            {\n                Connection conn = ds.getConnection();\n                if (conn.getProperties() != null && !conn.getProperties().isEmpty())\n                {\n                    zookeeperPort = conn.getProperties().getProperty(HBaseConstants.ZOOKEEPER_PORT).trim();\n                }\n            }\n            return zookeeperPort;\n        }\n\n        /**\n         * Gets the zookeeper host.\n         * \n         * @return the zookeeper host\n         */\n        public String getZookeeperHost()\n        {\n            DataStore ds = getDataStore();\n            if (ds != null && ds.getConnection() != null)\n            {\n                Connection conn = ds.getConnection();\n                if (conn.getProperties() != null && !conn.getProperties().isEmpty())\n                {\n                    zookeeperHost = conn.getProperties().getProperty(HBaseConstants.ZOOKEEPER_HOST.trim());\n                }\n            }\n            return zookeeperHost;\n        }\n\n        /**\n         * Gets the data store.\n         * \n         * @return the data store\n         */\n        public DataStore getDataStore()\n        {\n            if (getClientProperties() != null && getClientProperties().getDatastores() != null)\n            {\n                for (DataStore dataStore : getClientProperties().getDatastores())\n                {\n                    if (dataStore.getName() != null && dataStore.getName().trim().equalsIgnoreCase(HBASE))\n                    {\n                        return dataStore;\n                    }\n                }\n            }\n            return null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/query/BinaryComparatorFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.query;\n\nimport org.apache.hadoop.hbase.filter.BinaryComparator;\nimport org.apache.hadoop.hbase.filter.ByteArrayComparable;\n\nimport com.google.common.base.Function;\n\n/**\n * A factory for creating BinaryComparator objects.\n */\npublic class BinaryComparatorFactory implements Function<byte[], ByteArrayComparable>\n{\n    \n    /** The Constant INSTANCE. */\n    public static final BinaryComparatorFactory INSTANCE = new BinaryComparatorFactory();\n\n    /* (non-Javadoc)\n     * @see com.google.common.base.Function#apply(java.lang.Object)\n     */\n    public ByteArrayComparable apply(byte[] bytes)\n    {\n        return new BinaryComparator(bytes);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/query/HBaseQuery.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.query;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\n\nimport org.apache.hadoop.hbase.filter.BinaryComparator;\nimport org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;\nimport org.apache.hadoop.hbase.filter.Filter;\nimport org.apache.hadoop.hbase.filter.FilterList;\nimport org.apache.hadoop.hbase.filter.PageFilter;\nimport org.apache.hadoop.hbase.filter.RegexStringComparator;\nimport org.apache.hadoop.hbase.filter.RowFilter;\nimport org.apache.hadoop.hbase.filter.SingleColumnValueFilter;\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.eclipse.persistence.jpa.jpql.parser.CollectionExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.ComparisonExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.InExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.InputParameter;\nimport org.eclipse.persistence.jpa.jpql.parser.LikeExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.LogicalExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectClause;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectStatement;\nimport org.eclipse.persistence.jpa.jpql.parser.StateFieldPathExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.WhereClause;\nimport org.eclipse.persistence.jpa.jpql.parser.RegexpExpression;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.HBaseClient;\nimport com.impetus.client.hbase.HBaseEntityReader;\nimport com.impetus.client.hbase.utils.HBaseUtils;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.query.KunderaQueryUtils;\nimport com.impetus.kundera.query.QueryImpl;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * The Class HBaseQuery.\n * \n * @author Pragalbh Garg\n */\npublic class HBaseQuery extends QueryImpl\n{\n\n    /** the log used by this class. */\n    private static Logger logger = LoggerFactory.getLogger(HBaseQuery.class);\n\n    /**\n     * Instantiates a new h base query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param persistenceDelegator\n     *            the persistence delegator\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public HBaseQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List<Object> populateEntities(EntityMetadata m, Client client)\n    {\n        return onQuery(m, client);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#recursivelyPopulateEntities(com.\n     * impetus .kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n        // required in case of associated entities.\n        List ls = onQuery(m, client);\n        return setRelationEntities(ls, client, m);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#getReader()\n     */\n    @Override\n    protected EntityReader getReader()\n    {\n        return new HBaseEntityReader(kunderaQuery, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()\n     */\n    @Override\n    protected int onExecuteUpdate()\n    {\n        return onUpdateDeleteEvent();\n    }\n\n    /**\n     * On query.\n     * \n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     * @return the list\n     */\n    private List onQuery(EntityMetadata m, Client client)\n    {\n        boolean useLuceneOrES = !MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata());\n        QueryTranslator translator = new QueryTranslator();\n        List<Map<String, Object>> columnsToOutput = translator.getColumnsToOutput(m, getKunderaQuery(), useLuceneOrES);\n        translator.translate(getKunderaQuery(), m, useLuceneOrES);\n        Filter filters = translator.getFilters();\n        if (!translator.isWhereOrAggregationQuery() || !useLuceneOrES)\n        {\n            return ((HBaseClient) client).findData(m, null, translator.getStartRow(), translator.getEndRow(),\n                    columnsToOutput, filters);\n        }\n        else\n        {\n            return populateUsingLucene(m, client, null, null);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#close()\n     */\n    @Override\n    public void close()\n    {\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#iterate()\n     */\n    @Override\n    public Iterator iterate()\n    {\n        EntityMetadata m = getEntityMetadata();\n        Client client = persistenceDelegeator.getClient(m);\n        boolean useLuceneOrES = !MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata());\n        QueryTranslator translator = new QueryTranslator();\n        translator.translate(getKunderaQuery(), m, useLuceneOrES);\n        if (useLuceneOrES && translator.isWhereOrAggregationQuery())\n        {\n            throw new UnsupportedOperationException(\"Scrolling over hbase is unsupported for lucene or ES queries\");\n        }\n        List<Map<String, Object>> columns = translator.getColumnsToOutput(m, getKunderaQuery(), useLuceneOrES);\n        return new ResultIterator((HBaseClient) client, m, persistenceDelegeator,\n                getFetchSize() != null ? getFetchSize() : this.maxResult, translator, columns);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#findUsingLucene(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n        QueryTranslator translator = new QueryTranslator();\n        translator.translate(getKunderaQuery(), m, true);\n        List<Map<String, Object>> columns = translator.getColumnsToOutput(m, getKunderaQuery(), true);\n        Object value = null;\n        for (Object obj : getKunderaQuery().getFilterClauseQueue())\n        {\n            if (obj instanceof FilterClause)\n            {\n                value = ((FilterClause) obj).getValue().get(0);\n            }\n        }\n        byte[] valueInBytes = HBaseUtils.getBytes(value,\n                ((AbstractAttribute) m.getIdAttribute()).getBindableJavaType());\n        return ((HBaseClient) client).findData(m, valueInBytes, null, null, columns, null);\n    }\n\n    /**\n     * The Class QueryTranslator.\n     */\n    class QueryTranslator\n    {\n        /** The filter. */\n        private Filter filter = null;\n\n        /*\n         * byte[] value for start row, in case of range query, else will contain\n         * null.\n         */\n        /** The start row. */\n        private byte[] startRow = null;\n\n        /*\n         * byte[] value for end row, in case of range query, else will contain\n         * null.\n         */\n        /** The end row. */\n        private byte[] endRow = null;\n\n        /** The is where or aggregation. */\n        private boolean isWhereOrAggregation = false;\n\n        /**\n         * Checks if is where or aggregation query.\n         * \n         * @return true, if is where or aggregation query\n         */\n        public boolean isWhereOrAggregationQuery()\n        {\n            return isWhereOrAggregation;\n        }\n\n        /**\n         * Gets the columns to output.\n         * \n         * @param m\n         *            the m\n         * @param kunderaQuery\n         *            the kundera query\n         * @param useLuceneOrES\n         *            the use lucene or es\n         * @return the columns to output\n         */\n        private List<Map<String, Object>> getColumnsToOutput(EntityMetadata m, KunderaQuery kunderaQuery,\n                Boolean useLuceneOrES)\n        {\n            if (kunderaQuery.isAggregated())\n            {\n                if (!useLuceneOrES)\n                {\n                    throw new KunderaException(\"Aggregations are not supported in this database. \"\n                            + \"Please use Lucene or ES to create indexes if you want to do it\");\n                }\n                else\n                {\n                    this.isWhereOrAggregation = true;\n                }\n            }\n            if (kunderaQuery.isSelectStatement())\n            {\n                SelectStatement selectStatement = kunderaQuery.getSelectStatement();\n                SelectClause selectClause = (SelectClause) selectStatement.getSelectClause();\n                return KunderaQueryUtils.readSelectClause(selectClause.getSelectExpression(), m, useLuceneOrES,\n                        kunderaMetadata);\n            }\n            return new ArrayList();\n        }\n\n        /**\n         * Translate.\n         * \n         * @param query\n         *            the query\n         * @param m\n         *            the m\n         * @param useLuceneOrES\n         *            the use lucene or es\n         */\n        void translate(KunderaQuery query, EntityMetadata m, Boolean useLuceneOrES)\n        {\n            FilterList filterList = new FilterList();\n            // add filter for pagination\n            filterList.addFilter(new PageFilter(getMaxResults()));\n            // add filter for kundera auto id generation row\n            filterList.addFilter(\n                    new RowFilter(CompareOp.NOT_EQUAL, new BinaryComparator(HBaseUtils.AUTO_ID_ROW.getBytes())));\n            // get filters from where clause\n            Filter filterFromWhereClause = getFiltersFromWhereClause(query, m, useLuceneOrES);\n            if (filterFromWhereClause != null)\n            {\n                filterList.addFilter(filterFromWhereClause);\n            }\n            // get filters for discriminator column\n            Filter filterForDiscrCol = getFilterForDiscrColumn(m);\n            if (filterForDiscrCol != null)\n            {\n                filterList.addFilter(filterForDiscrCol);\n            }\n            this.filter = filterList;\n        }\n\n        /**\n         * Gets the filter for discr column.\n         * \n         * @param m\n         *            the m\n         * @return the filter for discr column\n         */\n        private Filter getFilterForDiscrColumn(EntityMetadata m)\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                    .getMetamodel(m.getPersistenceUnit());\n            AbstractManagedType entity = (AbstractManagedType) metaModel.entity(m.getEntityClazz());\n            if (entity.isInherited())\n            {\n                return new SingleColumnValueFilter(Bytes.toBytes(m.getTableName()),\n                        Bytes.toBytes(entity.getDiscriminatorColumn()), CompareOp.EQUAL,\n                        Bytes.toBytes(entity.getDiscriminatorValue()));\n            }\n            return null;\n        }\n\n        /**\n         * Sets the filters from where clause.\n         * \n         * @param query\n         *            the query\n         * @param m\n         *            the m\n         * @param useLuceneOrES\n         *            the use lucene or es\n         * @return the filters from where clause\n         */\n        private Filter getFiltersFromWhereClause(KunderaQuery query, EntityMetadata m, Boolean useLuceneOrES)\n        {\n            String idColumn = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n            WhereClause whereClause = KunderaQueryUtils.getWhereClause(query.getJpqlExpression());\n            if (whereClause != null)\n            {\n                this.isWhereOrAggregation = true;\n                if (!useLuceneOrES)\n                    return traverse(whereClause.getConditionalExpression(), m, idColumn);\n            }\n            return null;\n        }\n\n        /**\n         * Traverse.\n         * \n         * @param expression\n         *            the expression\n         * @param m\n         *            the m\n         * @param idColumn\n         *            the id column\n         * @return the filter\n         */\n        private Filter traverse(Expression expression, EntityMetadata m, String idColumn)\n        {\n            Boolean isIdColumn = false;\n            if (ComparisonExpression.class.isAssignableFrom(expression.getClass()))\n            {\n                return onComparisonExpression(expression, m, idColumn, isIdColumn);\n            }\n            else if (LogicalExpression.class.isAssignableFrom(expression.getClass()))\n            {\n                return onLogicalExpression(expression, m, idColumn);\n            }\n            else if (InExpression.class.isAssignableFrom(expression.getClass()))\n            {\n                return onInExpression(expression, m, idColumn, isIdColumn);\n            }\n            else if (LikeExpression.class.isAssignableFrom(expression.getClass()))\n            {\n                return onLikeExpression(expression, m, idColumn, isIdColumn);\n            }\n            else if (RegexpExpression.class.isAssignableFrom(expression.getClass()))\n            {\n                return onRegExpression(expression, m, idColumn, isIdColumn);\n            }\n            return null;\n        }\n\n        /**\n         * On comparison expression.\n         * \n         * @param expression\n         *            the expression\n         * @param m\n         *            the m\n         * @param idColumn\n         *            the id column\n         * @param isIdColumn\n         *            the is id column\n         * @return the filter\n         */\n        private Filter onComparisonExpression(Expression expression, EntityMetadata m, String idColumn,\n                Boolean isIdColumn)\n        {\n\n            Map<String, Object> map = KunderaQueryUtils.onComparisonExpression(expression, m, kunderaMetadata,\n                    getKunderaQuery());\n            Class fieldClazz = (Class) map.get(Constants.FIELD_CLAZZ);\n            String colFamily = (String) map.get(Constants.COL_FAMILY);\n            String columnName = (String) map.get(Constants.DB_COL_NAME);\n\n            isIdColumn = idColumn.equalsIgnoreCase(columnName);\n\n            Object value = KunderaQueryUtils.getValue(((ComparisonExpression) expression).getRightExpression(),\n                    fieldClazz, kunderaQuery);\n            if (!isEmbeddable(map))\n            {\n                byte[] valueInBytes = getValueInBytes(value, fieldClazz, isIdColumn, m);\n                return createNewFilter(((ComparisonExpression) expression).getIdentifier(), Bytes.toBytes(colFamily),\n                        Bytes.toBytes(columnName), valueInBytes, isIdColumn);\n            }\n            else\n            {\n                return createFilterForEmbeddables(((ComparisonExpression) expression).getIdentifier(), isIdColumn, m,\n                        fieldClazz, value, columnName);\n            }\n        }\n\n        private Filter onLikeExpression(Expression expression, EntityMetadata m, String idColumn, Boolean isIdColumn)\n        {\n\n            Map<String, Object> map = KunderaQueryUtils.setFieldClazzAndColumnFamily(\n                    (StateFieldPathExpression) ((LikeExpression) expression).getStringExpression(), m, kunderaMetadata);\n            Class fieldClazz = (Class) map.get(Constants.FIELD_CLAZZ);\n            String colFamily = (String) map.get(Constants.COL_FAMILY);\n            String columnName = (String) map.get(Constants.DB_COL_NAME);\n\n            isIdColumn = idColumn.equalsIgnoreCase(columnName);\n\n            Object value = KunderaQueryUtils.getValue(((LikeExpression) expression).getPatternValue(), fieldClazz,\n                    kunderaQuery);\n            if (!isEmbeddable(map))\n            {\n                byte[] valueInBytes = getValueInBytes(value, fieldClazz, isIdColumn, m);\n                return createNewFilter(((LikeExpression) expression).getIdentifier(), Bytes.toBytes(colFamily),\n                        Bytes.toBytes(columnName), valueInBytes, isIdColumn);\n            }\n            else\n            {\n                return createFilterForEmbeddables(((LikeExpression) expression).getIdentifier(), isIdColumn, m,\n                        fieldClazz, value, columnName);\n            }\n        }\n\n        private Filter onRegExpression(Expression expression, EntityMetadata m, String idColumn, Boolean isIdColumn)\n        {\n\n            Map<String, Object> map = KunderaQueryUtils.setFieldClazzAndColumnFamily(\n                    (StateFieldPathExpression) ((RegexpExpression) expression).getStringExpression(), m,\n                    kunderaMetadata);\n            Class fieldClazz = (Class) map.get(Constants.FIELD_CLAZZ);\n            String colFamily = (String) map.get(Constants.COL_FAMILY);\n            String columnName = (String) map.get(Constants.DB_COL_NAME);\n\n            isIdColumn = idColumn.equalsIgnoreCase(columnName);\n\n            Object value = KunderaQueryUtils.getValue(((RegexpExpression) expression).getPatternValue(), fieldClazz,\n                    kunderaQuery);\n            if (!isEmbeddable(map))\n            {\n                byte[] valueInBytes = getValueInBytes(value, fieldClazz, isIdColumn, m);\n                return createNewFilter(((RegexpExpression) expression).getActualRegexpIdentifier().toUpperCase(),\n                        Bytes.toBytes(colFamily), Bytes.toBytes(columnName), valueInBytes, isIdColumn);\n            }\n            else\n            {\n                return createFilterForEmbeddables(\n                        ((RegexpExpression) expression).getActualRegexpIdentifier().toUpperCase(), isIdColumn, m,\n                        fieldClazz, value, columnName);\n            }\n        }\n\n        /**\n         * Creates the filter for embeddables.\n         * \n         * @param condition\n         *            the condition\n         * @param isIdColumn\n         *            the is id column\n         * @param m\n         *            the m\n         * @param fieldClazz\n         *            the field clazz\n         * @param value\n         *            the value\n         * @param prefix\n         * @return the filter\n         */\n        private Filter createFilterForEmbeddables(String condition, Boolean isIdColumn, EntityMetadata m,\n                Class fieldClazz, Object value, String prefix)\n        {\n            if (isIdColumn)\n            {\n                String compositeKey = KunderaCoreUtils.prepareCompositeKey(m, value);\n                return createNewFilter(condition, null, null, Bytes.toBytes(compositeKey), isIdColumn);\n            }\n            else\n            {\n                MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                        .getMetamodel(m.getPersistenceUnit());\n                EmbeddableType embeddable = metaModel.embeddable(fieldClazz);\n                Set<Attribute> attributes = embeddable.getAttributes();\n                FilterList filterList = new FilterList();\n                onEmbeddableField(value, attributes, condition, m, metaModel, filterList, prefix);\n                return filterList;\n            }\n        }\n\n        /**\n         * On embeddable field.\n         * \n         * @param embeddable\n         *            the embeddable\n         * @param attributes\n         *            the attributes\n         * @param condition\n         *            the condition\n         * @param m\n         *            the m\n         * @param metaModel\n         *            the meta model\n         * @param filterList\n         *            the filter list\n         * @param prefix\n         */\n        private void onEmbeddableField(Object embeddable, Set<Attribute> attributes, String condition, EntityMetadata m,\n                MetamodelImpl metaModel, FilterList filterList, String prefix)\n        {\n            for (Attribute attrib : attributes)\n            {\n                Class clazz = ((AbstractAttribute) attrib).getBindableJavaType();\n                if (!metaModel.isEmbeddable(clazz))\n                {\n                    Object fieldValue = PropertyAccessorHelper.getObject(embeddable, (Field) attrib.getJavaMember());\n                    String colFamily = ((AbstractAttribute) attrib).getTableName() != null\n                            ? ((AbstractAttribute) attrib).getTableName() : m.getTableName();\n                    String columnName = prefix + HBaseUtils.DOT + ((AbstractAttribute) attrib).getJPAColumnName();\n                    byte[] valueInBytes = getValueInBytes(fieldValue, clazz, false, m);\n                    filterList.addFilter(createNewFilter(condition, Bytes.toBytes(colFamily), Bytes.toBytes(columnName),\n                            valueInBytes, false));\n                }\n                else if (!attrib.isCollection())\n                {\n                    Set<Attribute> attribEmbeddables = metaModel\n                            .embeddable(((AbstractAttribute) attrib).getBindableJavaType()).getAttributes();\n                    Object fieldValue = PropertyAccessorHelper.getObject(embeddable, (Field) attrib.getJavaMember());\n                    String newPrefix = prefix + HBaseUtils.DOT + ((AbstractAttribute) attrib).getJPAColumnName();\n                    onEmbeddableField(fieldValue, attribEmbeddables, condition, m, metaModel, filterList, newPrefix);\n                }\n                else\n                {\n                    throw new KunderaException(\n                            \"Either the field is collection or it contains a collection. This query is not supported in HBase\");\n                }\n            }\n        }\n\n        /**\n         * Checks if is embeddable.\n         * \n         * @param map\n         *            the map\n         * @return true, if is embeddable\n         */\n        private boolean isEmbeddable(Map<String, Object> map)\n        {\n            return (boolean) map.get(Constants.IS_EMBEDDABLE);\n        }\n\n        /**\n         * On logical expression.\n         * \n         * @param expression\n         *            the expression\n         * @param m\n         *            the m\n         * @param idColumn\n         *            the id column\n         * @return the filter\n         */\n        private Filter onLogicalExpression(Expression expression, EntityMetadata m, String idColumn)\n        {\n            FilterList filterList = checkOperationAndReturnFilter((LogicalExpression) expression);\n            Filter f = traverse(((LogicalExpression) expression).getLeftExpression(), m, idColumn);\n            if (f != null)\n            {\n                filterList.addFilter(f);\n            }\n            f = traverse(((LogicalExpression) expression).getRightExpression(), m, idColumn);\n            if (f != null)\n            {\n                filterList.addFilter(f);\n            }\n            return filterList.getFilters().size() == 0 ? null : filterList;\n        }\n\n        /**\n         * On in expression.\n         * \n         * @param expression\n         *            the expression\n         * @param m\n         *            the m\n         * @param idColumn\n         *            the id column\n         * @param isIdColumn\n         *            the is id column\n         * @return the filter\n         */\n        private Filter onInExpression(Expression expression, EntityMetadata m, String idColumn, Boolean isIdColumn)\n        {\n            Map<String, Object> map = KunderaQueryUtils.onInExpression(expression, m, kunderaMetadata,\n                    getKunderaQuery());\n            Class fieldClazz = (Class) map.get(Constants.FIELD_CLAZZ);\n            String colFamily = (String) map.get(Constants.COL_FAMILY);\n            String columnName = (String) map.get(Constants.DB_COL_NAME);\n            isIdColumn = idColumn.equalsIgnoreCase(columnName);\n            return onInClause((InExpression) expression, m, isIdColumn, Bytes.toBytes(colFamily),\n                    Bytes.toBytes(columnName), fieldClazz);\n        }\n\n        /**\n         * On in clause.\n         * \n         * @param values\n         *            the values\n         * @param m\n         *            the m\n         * @param isIdColumn\n         *            the is id column\n         * @param colFamily\n         *            the col family\n         * @param colName\n         *            the col name\n         * @param fieldClazz\n         *            the field clazz\n         * @return the filter\n         */\n        private Filter onInClause(Object values, EntityMetadata m, Boolean isIdColumn, byte[] colFamily, byte[] colName,\n                Class fieldClazz)\n        {\n            InExpression inExp = (InExpression) values;\n            Iterable listIterable = null;\n            boolean isParameter = false;\n            if (CollectionExpression.class.isAssignableFrom(inExp.getInItems().getClass()))\n            {\n                listIterable = ((CollectionExpression) inExp.getInItems()).children();\n            }\n            else\n            {\n                String param = ((InputParameter) inExp.getInItems()).getParameter();\n                Object items = getKunderaQuery().getParametersMap().get(param);\n                // If the input parameter is an Array\n                if (items.getClass().isArray())\n                {\n                    listIterable = Arrays.asList((Object[]) items);\n                }\n                // If the input parameter is a List\n                else if (Iterable.class.isAssignableFrom(items.getClass()))\n                {\n                    listIterable = (Iterable) items;\n                }\n                else\n                {\n                    throw new UnsupportedOperationException(\"Input parameter must either be an array or a list\");\n                }\n                isParameter = true;\n            }\n            Iterator itr = listIterable.iterator();\n            FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ONE);\n            while (itr.hasNext())\n            {\n                Object value = isParameter ? itr.next()\n                        : KunderaQueryUtils.getValue((Expression) itr.next(), fieldClazz, kunderaQuery);\n                byte[] valueInBytes = getValueInBytes(value, fieldClazz, isIdColumn, m);\n                Filter filter = !isIdColumn\n                        ? createNewFilter(HBaseUtils.EQUALS, colFamily, colName, valueInBytes, isIdColumn)\n                        : new RowFilter(CompareOp.EQUAL, new BinaryComparator(valueInBytes));\n                filterList.addFilter(filter);\n            }\n            return filterList.getFilters().size() == 0 ? null : filterList;\n        }\n\n        /**\n         * Gets the value in bytes.\n         * \n         * @param value\n         *            the value\n         * @param fieldClazz\n         *            the field clazz\n         * @param isIdColumn\n         *            the is id column\n         * @param m\n         *            the m\n         * @return the value in bytes\n         */\n        private byte[] getValueInBytes(Object value, Class fieldClazz, Boolean isIdColumn, EntityMetadata m)\n        {\n            AbstractAttribute idCol = (AbstractAttribute) m.getIdAttribute();\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                    .getMetamodel(m.getPersistenceUnit());\n            if (isIdColumn && metaModel.isEmbeddable(idCol.getBindableJavaType()))\n            {\n                Map<Attribute, List<Object>> columnValues = new HashMap<Attribute, List<Object>>();\n                Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields();\n                EmbeddableType embeddable = metaModel.embeddable(m.getIdAttribute().getBindableJavaType());\n\n                StringBuilder compositeKey = new StringBuilder();\n                for (Field field : fields)\n                {\n                    if (!ReflectUtils.isTransientOrStatic(field))\n                    {\n                        AbstractAttribute attrib = (AbstractAttribute) embeddable.getAttribute(field.getName());\n                        Object obj = PropertyAccessorHelper.getObject(value, field);\n                        compositeKey.append(PropertyAccessorHelper.fromSourceToTargetClass(String.class,\n                                attrib.getBindableJavaType(), obj)).append(HBaseUtils.COMP_KEY_DELIM);\n                    }\n                }\n                compositeKey.delete(compositeKey.lastIndexOf(HBaseUtils.COMP_KEY_DELIM), compositeKey.length());\n                value = compositeKey.toString();\n                fieldClazz = String.class;\n            }\n            return HBaseUtils.getBytes(value, fieldClazz);\n        }\n\n        /**\n         * Check operation and return filter.\n         * \n         * @param expression\n         *            the expression\n         * @return the filter list\n         */\n        private FilterList checkOperationAndReturnFilter(LogicalExpression expression)\n        {\n            if (expression.getIdentifier().equals(HBaseUtils.AND))\n            {\n                return new FilterList(FilterList.Operator.MUST_PASS_ALL);\n            }\n            else if (expression.getIdentifier().equals(HBaseUtils.OR))\n            {\n                return new FilterList(FilterList.Operator.MUST_PASS_ONE);\n            }\n\n            return null;\n        }\n\n        /**\n         * Creates the new filter.\n         * \n         * @param condition\n         *            the condition\n         * @param colFamily\n         *            the col family\n         * @param colName\n         *            the col name\n         * @param value\n         *            the value\n         * @param isIdColumn\n         *            the is id column\n         * @return the filter\n         */\n        private Filter createNewFilter(String condition, byte[] colFamily, byte[] colName, byte[] value,\n                Boolean isIdColumn)\n        {\n            SingleColumnFilterFactory factory = HBaseUtils.getOperator(condition, isIdColumn, true);\n            CompareOp operator = factory.getOperator();\n            if (!isIdColumn)\n            {\n                return factory.create(colFamily, colName, value);\n            }\n            else\n            {\n                switch (operator)\n                {\n                case GREATER_OR_EQUAL:\n                    startRow = value;\n                    break;\n                case GREATER:\n                    startRow = new byte[value.length + 1];\n                    System.arraycopy(value, 0, startRow, 0, value.length);\n                    break;\n                case LESS:\n                    endRow = value;\n                    break;\n                case LESS_OR_EQUAL:\n                    endRow = new byte[value.length + 1];\n                    System.arraycopy(value, 0, endRow, 0, value.length);\n                    break;\n                case EQUAL:\n                    return createNewRowFiterForLikeRegex(condition, value, operator);\n                case NOT_EQUAL:\n                    return new RowFilter(CompareOp.NOT_EQUAL, new BinaryComparator(value));\n                default:\n                    throw new KunderaException(\"This comparison operator is currently not supported\");\n                }\n                return null;\n            }\n        }\n\n        /**\n         * Creates the new row fiter for like and regex queries.\n         * \n         * Fix for issue #889\n         * (https://github.com/impetus-opensource/Kundera/issues/889)\n         *\n         * @param condition\n         *            the condition\n         * @param value\n         *            the value\n         * @param operator\n         *            the operator\n         * @return the row filter\n         */\n        private RowFilter createNewRowFiterForLikeRegex(String condition, byte[] value, CompareOp operator)\n        {\n            if (\"LIKE\".equalsIgnoreCase(condition))\n            {\n                return new RowFilter(operator,\n                        new RegexStringComparator(LikeComparatorFactory.likeToRegex(new String(value))));\n            }\n            else if (\"REGEXP\".equalsIgnoreCase(condition))\n            {\n                return new RowFilter(operator, new RegexStringComparator(new String(value)));\n            }\n            else\n            {\n                startRow = endRow = value;\n                return null;\n            }\n        }\n\n        /**\n         * Gets the filter.\n         * \n         * @return the filter\n         */\n        Filter getFilters()\n        {\n            return this.filter;\n        }\n\n        /**\n         * Gets the start row.\n         * \n         * @return the start row\n         */\n        byte[] getStartRow()\n        {\n            return startRow;\n        }\n\n        /**\n         * Gets the end row.\n         * \n         * @return the end row\n         */\n        byte[] getEndRow()\n        {\n            return endRow;\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/query/LikeComparatorFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.query;\n\nimport static java.lang.Character.isLetterOrDigit;\n\nimport com.google.common.base.Function;\nimport org.apache.hadoop.hbase.filter.ByteArrayComparable;\nimport org.apache.hadoop.hbase.filter.RegexStringComparator;\n\n/**\n * A factory for creating LikeComparator objects.\n */\npublic class LikeComparatorFactory implements Function<byte[], ByteArrayComparable>\n{\n\n    /** The Constant INSTANCE. */\n    public static final LikeComparatorFactory INSTANCE = new LikeComparatorFactory();\n\n    /**\n     * Like to regex.\n     * \n     * @param like\n     *            the like\n     * @return the string\n     */\n    static String likeToRegex(String like)\n    {\n        StringBuilder builder = new StringBuilder();\n        boolean wasPercent = false;\n        for (int i = 0; i < like.length(); ++i)\n        {\n            char c = like.charAt(i);\n            if (isPlain(c))\n            {\n                if (wasPercent)\n                {\n                    wasPercent = false;\n                    builder.append(\".*\");\n                }\n                builder.append(c);\n            }\n            else if (wasPercent)\n            {\n                wasPercent = false;\n                if (c == '%')\n                {\n                    builder.append('%');\n                }\n                else\n                {\n                    builder.append(\".*\").append(c);\n                }\n            }\n            else\n            {\n                if (c == '%')\n                {\n                    wasPercent = true;\n                }\n                else\n                {\n                    builder.append('\\\\').append(c);\n                }\n            }\n        }\n        if (wasPercent)\n        {\n            builder.append(\".*\");\n        }\n        return builder.toString();\n    }\n\n    /**\n     * Checks if is plain.\n     * \n     * @param c\n     *            the c\n     * @return true, if is plain\n     */\n    private static boolean isPlain(char c)\n    {\n        return isLetterOrDigit(c) || \"_@ ~`\\\"'#<>,;;=!&\".indexOf(c) >= 0;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.google.common.base.Function#apply(java.lang.Object)\n     */\n    public ByteArrayComparable apply(byte[] bytes)\n    {\n        return new RegexStringComparator(likeToRegex(new String(bytes)));\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/query/RegexComparatorFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.query;\n\nimport org.apache.hadoop.hbase.filter.ByteArrayComparable;\nimport org.apache.hadoop.hbase.filter.RegexStringComparator;\n\nimport com.google.common.base.Function;\n\n/**\n * A factory for creating RegexComparator objects.\n * \n * @author karthikp.manchala\n */\npublic class RegexComparatorFactory implements Function<byte[], ByteArrayComparable>\n{\n\n    /** The Constant INSTANCE. */\n    public static final RegexComparatorFactory INSTANCE = new RegexComparatorFactory();\n\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.google.common.base.Function#apply(java.lang.Object)\n     */\n    public ByteArrayComparable apply(byte[] bytes)\n    {\n        return new RegexStringComparator(new String(bytes));\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/query/ResultIterator.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.query;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport org.apache.hadoop.hbase.filter.FilterList;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.HBaseClient;\nimport com.impetus.client.hbase.admin.HBaseDataHandler;\nimport com.impetus.client.hbase.query.HBaseQuery.QueryTranslator;\nimport com.impetus.client.hbase.utils.HBaseUtils;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.IResultIterator;\n\n/**\n * The Class ResultIterator.\n * \n * @author Pragalbh Garg\n * @param <E>\n *            the element type\n */\nclass ResultIterator<E> implements IResultIterator<E>\n{\n\n    /** The client. */\n    private HBaseClient client;\n\n    /** The entity metadata. */\n    private EntityMetadata entityMetadata;\n\n    /** The persistence delegator. */\n    private PersistenceDelegator persistenceDelegator;\n\n    /** The handler. */\n    private HBaseDataHandler handler;\n\n    /** The translator. */\n    private QueryTranslator translator;\n\n    /** The columns. */\n    private List<Map<String, Object>> columns;\n\n    /** The fetch size. */\n    private int fetchSize;\n\n    /** The count. */\n    private int count;\n\n    /** The scroll complete. */\n    private boolean scrollComplete;\n\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(ResultIterator.class);\n\n    /**\n     * Instantiates a new result iterator.\n     * \n     * @param client\n     *            the client\n     * @param m\n     *            the entity metadata\n     * @param pd\n     *            the pd\n     * @param fetchSize\n     *            the fetch size\n     * @param translator\n     *            the translator\n     * @param columns\n     *            the columns\n     */\n    public ResultIterator(HBaseClient client, EntityMetadata m, PersistenceDelegator pd, int fetchSize,\n            QueryTranslator translator, List<Map<String, Object>> columns)\n    {\n        this.entityMetadata = m;\n        this.client = client;\n        this.persistenceDelegator = pd;\n        this.handler = client.getHandle();\n        this.handler.setFetchSize(fetchSize);\n        this.fetchSize = fetchSize;\n        this.translator = translator;\n        this.columns = columns;\n        onQuery(m, client);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.util.Iterator#hasNext()\n     */\n    @Override\n    public boolean hasNext()\n    {\n        boolean available = handler.hasNext();\n        if (!available || fetchSize == 0)\n        {\n            scrollComplete = true;\n            handler.reset();\n            return false;\n        }\n        return available;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.util.Iterator#next()\n     */\n    @Override\n    public E next()\n    {\n        if (!checkOnFetchSize() || scrollComplete)\n        {\n            throw new NoSuchElementException(\"Nothing to scroll further for:\" + entityMetadata.getEntityClazz());\n        }\n        E result = (E) handler.next(entityMetadata, columns);\n        if (!entityMetadata.isRelationViaJoinTable()\n                && (entityMetadata.getRelationNames() == null || (entityMetadata.getRelationNames().isEmpty())))\n        {\n            return result;\n        }\n        else\n        {\n            return result = setRelationEntities(result, client, entityMetadata);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see java.util.Iterator#remove()\n     */\n    @Override\n    public void remove()\n    {\n        throw new UnsupportedOperationException(\"remove() over result iterator is not supported\");\n    }\n\n    /**\n     * Sets the relation entities.\n     * \n     * @param enhanceEntity\n     *            the enhance entity\n     * @param client\n     *            the client\n     * @param m\n     *            the m\n     * @return the e\n     */\n    private E setRelationEntities(Object enhanceEntity, Client client, EntityMetadata m)\n    {\n        E result = null;\n        if (enhanceEntity != null)\n        {\n            if (!(enhanceEntity instanceof EnhanceEntity))\n            {\n                enhanceEntity = new EnhanceEntity(enhanceEntity, PropertyAccessorHelper.getId(enhanceEntity, m), null);\n            }\n\n            EnhanceEntity ee = (EnhanceEntity) enhanceEntity;\n\n            result = (E) client.getReader().recursivelyFindEntities(ee.getEntity(), ee.getRelations(), m,\n                    persistenceDelegator, false, new HashMap<Object, Object>());\n        }\n        return result;\n    }\n\n    /**\n     * On query.\n     * \n     * @param m\n     *            the m\n     * @param client\n     *            the client\n     */\n    private void onQuery(EntityMetadata m, Client client)\n    {\n        String tableName = HBaseUtils.getHTableName(m.getSchema(), m.getTableName());\n        try\n        {\n            handler.readData(tableName, m, null, translator.getStartRow(), translator.getEndRow(), getColumnsToOuput(),\n                    (FilterList) translator.getFilters());\n        }\n        catch (IOException e)\n        {\n            log.error(e.getMessage());\n            throw new KunderaException(\"Error in connecting to database or some network problem. Caused by: \", e);\n        }\n    }\n\n    /**\n     * Gets the col as list.\n     * \n     * @return the col as list\n     */\n    private List<Map<String, Object>> getColumnsToOuput()\n    {\n        return this.columns;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.IResultIterator#next(int)\n     */\n    @Override\n    public List<E> next(int chunkSize)\n    {\n        int counter = 0;\n        List<E> chunkList = new ArrayList<E>();\n        while (this.hasNext() && counter++ < chunkSize)\n        {\n            chunkList.add(this.next());\n        }\n        return chunkList;\n    }\n\n    /**\n     * Check on fetch size.\n     * \n     * @return true, if successful\n     */\n    private boolean checkOnFetchSize()\n    {\n        if (count++ < fetchSize)\n        {\n            return true;\n        }\n        count = 0;\n        scrollComplete = true;\n        return false;\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/query/SingleColumnFilterFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.query;\n\nimport static org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;\nimport static org.apache.hadoop.hbase.util.Bytes.toBytes;\n\nimport com.google.common.base.Function;\nimport org.apache.hadoop.hbase.filter.ByteArrayComparable;\nimport org.apache.hadoop.hbase.filter.Filter;\nimport org.apache.hadoop.hbase.filter.SingleColumnValueFilter;\n\n/**\n * A factory for creating SingleColumnFilter objects.\n */\npublic class SingleColumnFilterFactory\n{\n\n    /** The Constant EQUAL. */\n    public static final SingleColumnFilterFactory EQUAL = new SingleColumnFilterFactory(CompareOp.EQUAL,\n            BinaryComparatorFactory.INSTANCE);\n\n    /** The Constant NOT_EQUAL. */\n    public static final SingleColumnFilterFactory NOT_EQUAL = new SingleColumnFilterFactory(CompareOp.NOT_EQUAL,\n            BinaryComparatorFactory.INSTANCE);\n\n    /** The Constant GREATER. */\n    public static final SingleColumnFilterFactory GREATER = new SingleColumnFilterFactory(CompareOp.GREATER,\n            BinaryComparatorFactory.INSTANCE);\n\n    /** The Constant LESS. */\n    public static final SingleColumnFilterFactory LESS = new SingleColumnFilterFactory(CompareOp.LESS,\n            BinaryComparatorFactory.INSTANCE);\n\n    /** The Constant GREATER_OR_EQUAL. */\n    public static final SingleColumnFilterFactory GREATER_OR_EQUAL = new SingleColumnFilterFactory(\n            CompareOp.GREATER_OR_EQUAL, BinaryComparatorFactory.INSTANCE);\n\n    /** The Constant LESS_OR_EQUAL. */\n    public static final SingleColumnFilterFactory LESS_OR_EQUAL = new SingleColumnFilterFactory(\n            CompareOp.LESS_OR_EQUAL, BinaryComparatorFactory.INSTANCE);\n\n    /** The Constant LIKE. */\n    public static final SingleColumnFilterFactory LIKE = new SingleColumnFilterFactory(CompareOp.EQUAL,\n            LikeComparatorFactory.INSTANCE);\n\n    /** The Constant REGEXP. */\n    public static final SingleColumnFilterFactory REGEXP = new SingleColumnFilterFactory(CompareOp.EQUAL,\n            RegexComparatorFactory.INSTANCE);\n\n    /** The operator. */\n    private final CompareOp operator;\n\n    /**\n     * Gets the operator.\n     * \n     * @return the operator\n     */\n    public CompareOp getOperator()\n    {\n        return operator;\n    }\n\n    /** The comparator factory. */\n    private final Function<byte[], ByteArrayComparable> comparatorFactory;\n\n    /**\n     * Instantiates a new single column filter factory.\n     * \n     * @param operator\n     *            the operator\n     * @param comparatorFactory\n     *            the comparator factory\n     */\n    public SingleColumnFilterFactory(CompareOp operator, Function<byte[], ByteArrayComparable> comparatorFactory)\n    {\n        this.operator = operator;\n        this.comparatorFactory = comparatorFactory;\n    }\n\n    /**\n     * Creates the.\n     * \n     * @param family\n     *            the family\n     * @param column\n     *            the column\n     * @param value\n     *            the value\n     * @return the filter\n     */\n    public Filter create(byte[] family, byte[] column, byte[] value)\n    {\n        return new SingleColumnValueFilter(family, column, operator, comparatorFactory.apply(value));\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/schemamanager/HBaseSchemaManager.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.schemamanager;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.hbase.HBaseConfiguration;\nimport org.apache.hadoop.hbase.HColumnDescriptor;\nimport org.apache.hadoop.hbase.HTableDescriptor;\nimport org.apache.hadoop.hbase.MasterNotRunningException;\nimport org.apache.hadoop.hbase.NamespaceDescriptor;\nimport org.apache.hadoop.hbase.TableName;\nimport org.apache.hadoop.hbase.TableNotFoundException;\nimport org.apache.hadoop.hbase.ZooKeeperConnectionException;\nimport org.apache.hadoop.hbase.client.Connection;\nimport org.apache.hadoop.hbase.client.ConnectionFactory;\nimport org.apache.hadoop.hbase.client.HBaseAdmin;\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.config.HBasePropertyReader;\nimport com.impetus.client.hbase.utils.HBaseUtils;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Schema;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Schema.Table;\nimport com.impetus.kundera.configure.schema.CollectionColumnInfo;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.configure.schema.TableInfo;\nimport com.impetus.kundera.configure.schema.api.AbstractSchemaManager;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.Relation.ForeignKey;\nimport com.impetus.kundera.metadata.model.annotation.DefaultEntityAnnotationProcessor;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * The Class HBaseSchemaManager.\n * \n * @author Pragalbh Garg\n */\npublic class HBaseSchemaManager extends AbstractSchemaManager implements SchemaManager\n{\n\n    /** The Constant DEFAULT_ZOOKEEPER_PORT. */\n    private static final String DEFAULT_ZOOKEEPER_PORT = \"2181\";\n\n    /**\n     * Hbase admin variable holds the admin authorities.\n     */\n    private static HBaseAdmin admin;\n\n    /**\n     * logger used for logging statement.\n     */\n    private static final Logger logger = LoggerFactory.getLogger(HBaseSchemaManager.class);\n\n    /** The Constant WILDCARD. */\n    private static final String WILDCARD = \".*\";\n\n    /** The external properties. */\n    private Map<String, Properties> externalProperties = new HashMap<String, Properties>();\n\n    /**\n     * Instantiates a new h base schema manager.\n     * \n     * @param clientFactory\n     *            the client factory\n     * @param puProperties\n     *            the pu properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public HBaseSchemaManager(String clientFactory, Map<String, Object> puProperties,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(clientFactory, puProperties, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#exportSchema\n     * (java.lang.String, java.util.List)\n     */\n    @Override\n    /**\n     * Export schema handles the handleOperation method.\n     */\n    public void exportSchema(final String persistenceUnit, List<TableInfo> schemas)\n    {\n        super.exportSchema(persistenceUnit, schemas);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#update\n     * (java.util.List)\n     */\n    @Override\n    protected void update(List<TableInfo> tableInfos)\n    {\n        createOrUpdateSchema(true);\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#validate\n     * (java.util.List)\n     */\n    @Override\n    protected void validate(List<TableInfo> tableInfos)\n    {\n        try\n        {\n            if (isNamespaceAvailable(databaseName))\n            {\n                for (TableInfo tableInfo : tableInfos)\n                {\n                    if (tableInfo != null)\n                    {\n                        HTableDescriptor hTableDescriptor = admin.getTableDescriptor((databaseName + \":\" + tableInfo\n                                .getTableName()).getBytes());\n                        boolean columnFamilyFound = false;\n                        Boolean f = false;\n                        for (HColumnDescriptor columnDescriptor : hTableDescriptor.getColumnFamilies())\n                        {\n\n                            if (!columnFamilyFound\n                                    && columnDescriptor.getNameAsString().equalsIgnoreCase(tableInfo.getTableName()))\n                            {\n                                columnFamilyFound = true;\n                            }\n\n                            for (CollectionColumnInfo cci : tableInfo.getCollectionColumnMetadatas())\n                            {\n                                if (columnDescriptor.getNameAsString().equalsIgnoreCase(cci.getCollectionColumnName()))\n                                {\n                                    f = true;\n                                    break;\n                                }\n\n                            }\n                            if (!(columnFamilyFound || f))\n                            {\n                                throw new SchemaGenerationException(\"column \" + tableInfo.getTableName()\n                                        + \" does not exist in table \" + databaseName + \"\", \"Hbase\", databaseName,\n                                        tableInfo.getTableName());\n                            }\n                            // TODO make a check for sec table\n                        }\n\n                    }\n                }\n            }\n            else\n            {\n                throw new SchemaGenerationException(\"Namespace\" + databaseName + \"does not exist\", \"HBase\",\n                        databaseName);\n            }\n\n        }\n        catch (TableNotFoundException tnfex)\n        {\n            throw new SchemaGenerationException(\"table \" + databaseName + \" does not exist \", tnfex, \"Hbase\");\n        }\n        catch (IOException ioe)\n        {\n            logger.error(\"Either check for network connection or table isn't in enabled state, Caused by:\", ioe);\n            throw new SchemaGenerationException(ioe, \"Hbase\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#create_drop\n     * (java.util.List)\n     */\n    @Override\n    protected void create_drop(List<TableInfo> tableInfos)\n    {\n        createOrUpdateSchema(false);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#create\n     * (java.util.List)\n     */\n    @Override\n    protected void create(List<TableInfo> tableInfos)\n    {\n        createOrUpdateSchema(false);\n    }\n\n    /**\n     * Drop.\n     */\n    protected void drop()\n    {\n        try\n        {\n            admin.disableTables(HBaseUtils.getHTableName(databaseName, WILDCARD));\n            admin.deleteTables(HBaseUtils.getHTableName(databaseName, WILDCARD));\n        }\n        catch (TableNotFoundException tnfe)\n        {\n            logger.error(\"Table doesn't exist, Caused by \", tnfe);\n        }\n        catch (IOException ioe)\n        {\n            logger.error(\"Table isn't in enabled state, Caused by\", ioe);\n            throw new SchemaGenerationException(ioe, \"Hbase\");\n        }\n        finally\n        {\n            try\n            {\n                admin.deleteNamespace(databaseName);\n            }\n            catch (IOException ioe)\n            {\n                logger.error(\"Table isn't in enabled state, Caused by\", ioe);\n                throw new SchemaGenerationException(ioe, \"Hbase\");\n            }\n        }\n    }\n\n    /**\n     * Creates the or update schema.\n     * \n     * @param isUpdate\n     *            the is update\n     */\n    private void createOrUpdateSchema(Boolean isUpdate)\n\n    {\n        createNamespace(isUpdate);\n        readExternalProperties();\n        Map<Class<?>, EntityType<?>> entityMap = kunderaMetadata.getApplicationMetadata()\n                .getMetaModelBuilder(puMetadata.getPersistenceUnitName()).getManagedTypes();\n        // iterating all classes of pu to generate schema\n        for (Class<?> clazz : entityMap.keySet())\n        {\n            EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n            if (m != null)\n            {\n                String tablename = m.getTableName();\n                HTableDescriptor hTableDescriptor = getTableDescriptor(clazz, entityMap.get(clazz), tablename);\n                String hTableName = HBaseUtils.getHTableName(databaseName, tablename);\n                createOrUpdateTable(hTableName, hTableDescriptor);\n            }\n        }\n    }\n\n    /**\n     * Gets the table descriptor.\n     * \n     * @param clazz\n     *            the clazz\n     * @param entityType\n     *            the entity type\n     * @param tableName\n     *            the table name\n     * @return the table descriptor\n     */\n    private HTableDescriptor getTableDescriptor(Class<?> clazz, EntityType<?> entityType, String tableName)\n    {\n        try\n        {\n            AbstractManagedType<?> ent = (AbstractManagedType<?>) entityType;\n            HTableDescriptor tableDescriptor = null;\n            String hTableName = HBaseUtils.getHTableName(databaseName, tableName);\n            tableDescriptor = !admin.tableExists(TableName.valueOf(hTableName)) ? new HTableDescriptor(\n                    TableName.valueOf(hTableName)) : admin.getTableDescriptor(TableName.valueOf(hTableName));\n            addColumnFamilyAndSetProperties(tableDescriptor, tableName);\n\n            // Add column families for @SecondaryTable\n            List<String> secondaryTables = ((DefaultEntityAnnotationProcessor) ent.getEntityAnnotation())\n                    .getSecondaryTablesName();\n            for (String secTable : secondaryTables)\n            {\n                addColumnFamilyAndSetProperties(tableDescriptor, secTable);\n            }\n\n            // handle @JoinTable for @ManyToMany\n            List<Relation> relations = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz).getRelations();\n            addJoinTable(relations);\n\n            // @CollectionTable is not handled.\n            return tableDescriptor;\n        }\n        catch (IOException ex)\n        {\n            logger.error(\"Either table isn't in enabled state or some network problem, Caused by: \", ex);\n            throw new SchemaGenerationException(ex, \"Hbase\");\n        }\n    }\n\n    /**\n     * Adds the join table.\n     * \n     * @param relations\n     *            the relations\n     */\n    private void addJoinTable(List<Relation> relations)\n    {\n        for (Relation relation : relations)\n        {\n            if (relation.getType().equals(ForeignKey.MANY_TO_MANY) && relation.isRelatedViaJoinTable())\n            {\n                String joinTableName = relation.getJoinTableMetadata().getJoinTableName();\n                String hTableName = HBaseUtils.getHTableName(databaseName, joinTableName);\n                HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(hTableName));\n                tableDescriptor.addFamily(new HColumnDescriptor(joinTableName));\n                createOrUpdateTable(hTableName, tableDescriptor);\n            }\n        }\n    }\n\n    /**\n     * Adds the column family and set properties.\n     * \n     * @param tableDescriptor\n     *            the table descriptor\n     * @param colFamilyName\n     *            the sec table\n     */\n    private void addColumnFamilyAndSetProperties(HTableDescriptor tableDescriptor, String colFamilyName)\n    {\n        if (!tableDescriptor.hasFamily(colFamilyName.getBytes()))\n        {\n            HColumnDescriptor hColumnDescriptor = getColumnDescriptor(colFamilyName);\n            tableDescriptor.addFamily(hColumnDescriptor);\n            setExternalProperties(tableDescriptor.getNameAsString(), hColumnDescriptor);\n        }\n    }\n\n    /**\n     * Sets the external properties.\n     * \n     * @param name\n     *            the name\n     * @param hColumnDescriptor\n     *            the h column descriptor\n     */\n    private void setExternalProperties(String name, HColumnDescriptor hColumnDescriptor)\n    {\n        Properties properties = externalProperties != null ? externalProperties.get(name) : null;\n        if (properties != null && !properties.isEmpty())\n        {\n            for (Object obj : properties.keySet())\n            {\n                hColumnDescriptor\n                        .setValue(Bytes.toBytes(obj.toString()), Bytes.toBytes(properties.get(obj).toString()));\n            }\n        }\n    }\n\n    /**\n     * Creates the namespace.\n     * \n     * @param isUpdate\n     *            the is update\n     */\n    private void createNamespace(boolean isUpdate)\n    {\n        boolean isNameSpaceAvailable = isNamespaceAvailable(databaseName);\n        if (isNameSpaceAvailable && !isUpdate)\n        {\n            drop();\n        }\n        if (!(isNameSpaceAvailable && isUpdate))\n        {\n            try\n            {\n                NamespaceDescriptor descriptor = NamespaceDescriptor.create(databaseName).build();\n                admin.createNamespace(descriptor);\n            }\n            catch (IOException ioex)\n            {\n                logger.error(\"Either table isn't in enabled state or some network problem, Caused by: \", ioex);\n                throw new SchemaGenerationException(ioex, \"Hbase\");\n            }\n        }\n    }\n\n    /**\n     * Checks if is namespace available.\n     * \n     * @param databaseName\n     *            the database name\n     * @return true, if is namespace available\n     */\n    private boolean isNamespaceAvailable(String databaseName)\n    {\n        try\n        {\n            for (NamespaceDescriptor ns : admin.listNamespaceDescriptors())\n            {\n                if (ns.getName().equals(databaseName))\n                {\n                    return true;\n                }\n            }\n            return false;\n        }\n        catch (IOException ioex)\n        {\n            logger.error(\"Either table isn't in enabled state or some network problem, Caused by: \", ioex);\n            throw new SchemaGenerationException(ioex, \"Either table isn't in enabled state or some network problem.\");\n        }\n    }\n\n    /**\n     * Creates the or update table.\n     * \n     * @param tablename\n     *            the tablename\n     * @param hTableDescriptor\n     *            the h table descriptor\n     */\n    private void createOrUpdateTable(String tablename, HTableDescriptor hTableDescriptor)\n    {\n        try\n        {\n            if (admin.isTableAvailable(tablename))\n            {\n                admin.modifyTable(tablename, hTableDescriptor);\n            }\n            else\n            {\n                admin.createTable(hTableDescriptor);\n            }\n        }\n        catch (IOException ioex)\n        {\n            logger.error(\"Either table isn't in enabled state or some network problem, Caused by: \", ioex);\n            throw new SchemaGenerationException(ioex, \"Either table isn't in enabled state or some network problem.\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.SchemaManager#dropSchema()\n     */\n    @Override\n    public void dropSchema()\n    {\n        if (operation != null && operation.equalsIgnoreCase(\"create-drop\"))\n        {\n            drop();\n        }\n        operation = null;\n        admin = null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#initiateClient\n     * ()\n     */\n    @Override\n    protected boolean initiateClient()\n    {\n        String message = null;\n        for (String host : hosts)\n        {\n            vaildateHostPort(host, port);\n            Configuration hadoopConf = new Configuration();\n            hadoopConf.set(\"hbase.master\", host + \":\" + port);\n            conn = HBasePropertyReader.hsmd.getDataStore() != null ? HBasePropertyReader.hsmd.getDataStore()\n                    .getConnection() : null;\n            if (conn != null && conn.getProperties() != null)\n            {\n                String zookeeperHost = conn.getProperties().getProperty(\"hbase.zookeeper.quorum\").trim();\n                String zookeeperPort = conn.getProperties().getProperty(\"hbase.zookeeper.property.clientPort\").trim();\n                vaildateHostPort(zookeeperHost, zookeeperPort);\n                hadoopConf.set(\"hbase.zookeeper.quorum\", zookeeperHost != null ? zookeeperHost : host);\n                hadoopConf.set(\"hbase.zookeeper.property.clientPort\", zookeeperPort != null ? zookeeperPort\n                        : DEFAULT_ZOOKEEPER_PORT);\n            }\n            else\n            {\n                hadoopConf.set(\"hbase.zookeeper.quorum\", host);\n                hadoopConf.set(\"hbase.zookeeper.property.clientPort\", DEFAULT_ZOOKEEPER_PORT);\n            }\n            Configuration conf = HBaseConfiguration.create(hadoopConf);\n            try\n            {\n                Connection connection = ConnectionFactory.createConnection(conf);\n                admin = (HBaseAdmin) connection.getAdmin();\n                return true;\n            }\n            catch (MasterNotRunningException mnre)\n            {\n                message = mnre.getMessage();\n                logger.error(\"Master not running exception, Caused by:\", mnre);\n            }\n            catch (ZooKeeperConnectionException zkce)\n            {\n                message = zkce.getMessage();\n                logger.error(\"Unable to connect to zookeeper, Caused by:\", zkce);\n            }\n            catch (IOException ioe)\n            {\n                message = ioe.getMessage();\n                logger.error(\"I/O exception, Caused by:\", ioe);\n            }\n        }\n        throw new SchemaGenerationException(\"Master not running exception, Caused by:\" + message);\n    }\n\n    /**\n     * Vaildate host port.\n     * \n     * @param host\n     *            the host\n     * @param port\n     *            the port\n     */\n    private void vaildateHostPort(String host, String port)\n    {\n        if (host == null || !StringUtils.isNumeric(port) || port.isEmpty())\n        {\n            logger.error(\"Host or port should not be null / port should be numeric\");\n            throw new IllegalArgumentException(\"Host or port should not be null / port should be numeric\");\n        }\n    }\n\n    /**\n     * Gets the column descriptor.\n     * \n     * @param tableName\n     *            the table name\n     * @return the column descriptor\n     */\n    private HColumnDescriptor getColumnDescriptor(String tableName)\n    {\n        HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(tableName);\n        return hColumnDescriptor;\n    }\n\n    /**\n     * Read external properties.\n     */\n    private void readExternalProperties()\n    {\n        schemas = HBasePropertyReader.hsmd.getDataStore() != null ? HBasePropertyReader.hsmd.getDataStore()\n                .getSchemas() : null;\n        List<Table> tables = null;\n        if (schemas != null && !schemas.isEmpty())\n        {\n            for (Schema s : schemas)\n            {\n                if (s.getName() != null && s.getName().equalsIgnoreCase(databaseName))\n                {\n                    tables = s.getTables();\n                }\n            }\n        }\n        if (tables != null && !tables.isEmpty())\n        {\n            for (Table table : tables)\n            {\n                externalProperties.put(HBaseUtils.getHTableName(databaseName, table.getName()), table.getProperties());\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.SchemaManager#validateEntity\n     * (java.lang.Class)\n     */\n    @Override\n    public boolean validateEntity(Class clazz)\n    {\n        return true;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/service/HBaseReader.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2015 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase.service;\r\n\r\nimport java.io.IOException;\r\nimport java.util.ArrayList;\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport org.apache.hadoop.hbase.Cell;\r\nimport org.apache.hadoop.hbase.CellUtil;\r\nimport org.apache.hadoop.hbase.client.Get;\r\nimport org.apache.hadoop.hbase.client.Result;\r\nimport org.apache.hadoop.hbase.client.ResultScanner;\r\nimport org.apache.hadoop.hbase.client.Scan;\r\nimport org.apache.hadoop.hbase.client.Table;\r\nimport org.apache.hadoop.hbase.filter.Filter;\r\nimport org.apache.hadoop.hbase.util.Bytes;\r\n\r\nimport com.impetus.client.hbase.HBaseDataWrapper;\r\nimport com.impetus.client.hbase.Reader;\r\nimport com.impetus.client.hbase.utils.HBaseUtils;\r\n\r\n/**\r\n * The Class HBaseReader.\r\n * \r\n * @author Pragalbh Garg\r\n */\r\npublic class HBaseReader implements Reader\r\n{\r\n\r\n    /** The scanner. */\r\n    private ResultScanner scanner = null;\r\n\r\n    /** The results iter. */\r\n    private Iterator<Result> resultsIter;\r\n\r\n    /** The fetch size. */\r\n    private Integer fetchSize;\r\n\r\n    /** The counter. */\r\n    private Integer counter = 0;\r\n\r\n    /** The table name. */\r\n    private String tableName = null;\r\n\r\n    /**\r\n     * Sets the table name.\r\n     * \r\n     * @param hTable\r\n     *            the new table name\r\n     */\r\n    private void setTableName(Table hTable)\r\n    {\r\n        this.tableName = hTable.getName().getNameAsString();\r\n\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.client.hbase.Reader#loadData(org.apache.hadoop.hbase.client\r\n     * .Table, java.lang.Object, byte[], byte[], java.lang.String,\r\n     * org.apache.hadoop.hbase.filter.Filter, java.util.List)\r\n     */\r\n    @Override\r\n    public List<HBaseDataWrapper> loadData(Table hTable, Object rowKey, byte[] startRow, byte[] endRow,\r\n            String columnFamily, Filter filter, List<Map<String, Object>> outputColumns) throws IOException\r\n    {\r\n        setTableName(hTable);\r\n        List<HBaseDataWrapper> results = new ArrayList<HBaseDataWrapper>();\r\n        if (rowKey != null)\r\n        {\r\n            Result result = hTable.get(new Get(HBaseUtils.getBytes(rowKey)));\r\n            if (result != null && !result.isEmpty())\r\n            {\r\n                HBaseDataWrapper data = new HBaseDataWrapper(tableName, result.getRow());\r\n                data.setColumns(result.listCells());\r\n                results.add(data);\r\n            }\r\n            return results;\r\n        }\r\n        if (scanner == null)\r\n        {\r\n            Scan scan = new Scan();\r\n            if (startRow != null)\r\n            {\r\n                scan.setStartRow(startRow);\r\n            }\r\n            if (endRow != null)\r\n            {\r\n                scan.setStopRow(endRow);\r\n            }\r\n            setScanCriteria(scan, columnFamily, outputColumns, filter);\r\n            scanner = hTable.getScanner(scan);\r\n            resultsIter = scanner.iterator();\r\n        }\r\n        return scanResults(tableName, results);\r\n    }\r\n\r\n    /**\r\n     * Sets the scan criteria.\r\n     * \r\n     * @param scan\r\n     *            the scan\r\n     * @param columnFamily\r\n     *            the column family\r\n     * @param columnsToOutput\r\n     *            the columns to output\r\n     * @param filter\r\n     *            the filter\r\n     */\r\n    private void setScanCriteria(Scan scan, String columnFamily, List<Map<String, Object>> columnsToOutput,\r\n            Filter filter)\r\n    {\r\n        if (filter != null)\r\n        {\r\n            scan.setFilter(filter);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Scan results.\r\n     * \r\n     * @param tableName\r\n     *            the table name\r\n     * @param results\r\n     *            the results\r\n     * @return the list\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    private List<HBaseDataWrapper> scanResults(final String tableName, List<HBaseDataWrapper> results)\r\n            throws IOException\r\n    {\r\n        if (fetchSize == null)\r\n        {\r\n            for (Result result : scanner)\r\n            {\r\n                HBaseDataWrapper data = new HBaseDataWrapper(tableName, result.getRow());\r\n                data.setColumns(result.listCells());\r\n                results.add(data);\r\n            }\r\n\r\n            scanner = null;\r\n            resultsIter = null;\r\n        }\r\n        return results;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.client.hbase.Reader#scanRowKeys(org.apache.hadoop.hbase.client\r\n     * .Table, org.apache.hadoop.hbase.filter.Filter, java.lang.String,\r\n     * java.lang.String, java.lang.Class)\r\n     */\r\n    @Override\r\n    public Object[] scanRowKeys(final Table hTable, final Filter filter, final String columnFamilyName,\r\n            final String columnName, final Class rowKeyClazz) throws IOException\r\n    {\r\n        List<Object> rowKeys = new ArrayList<Object>();\r\n\r\n        if (scanner == null)\r\n        {\r\n            Scan s = new Scan();\r\n            s.setFilter(filter);\r\n            s.addColumn(Bytes.toBytes(columnFamilyName), Bytes.toBytes(columnName));\r\n            scanner = hTable.getScanner(s);\r\n            resultsIter = scanner.iterator();\r\n        }\r\n        if (fetchSize == null)\r\n        {\r\n            for (Result result : scanner)\r\n            {\r\n                for (Cell cell : result.listCells())\r\n                {\r\n                    rowKeys.add(HBaseUtils.fromBytes(CellUtil.cloneFamily(cell), rowKeyClazz));\r\n                }\r\n            }\r\n        }\r\n        if (rowKeys != null && !rowKeys.isEmpty())\r\n        {\r\n            return rowKeys.toArray(new Object[0]);\r\n        }\r\n        return null;\r\n    }\r\n\r\n    /**\r\n     * Load all.\r\n     * \r\n     * @param hTable\r\n     *            the h table\r\n     * @param rows\r\n     *            the rows\r\n     * @param columnFamily\r\n     *            the column family\r\n     * @param columns\r\n     *            the columns\r\n     * @return the list\r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     */\r\n    public List<HBaseDataWrapper> loadAll(final Table hTable, final List<Object> rows, final String columnFamily,\r\n            final String[] columns) throws IOException\r\n    {\r\n        setTableName(hTable);\r\n        List<HBaseDataWrapper> results = new ArrayList<HBaseDataWrapper>();\r\n        List<Get> getRequest = new ArrayList<Get>();\r\n        for (Object rowKey : rows)\r\n        {\r\n            if (rowKey != null)\r\n            {\r\n                byte[] rowKeyBytes = HBaseUtils.getBytes(rowKey);\r\n                Get request = new Get(rowKeyBytes);\r\n                getRequest.add(request);\r\n            }\r\n        }\r\n        Result[] rawResult = hTable.get(getRequest);\r\n        for (Result result : rawResult)\r\n        {\r\n            List<Cell> cells = result.listCells();\r\n            if (cells != null)\r\n            {\r\n                HBaseDataWrapper data = new HBaseDataWrapper(tableName, result.getRow());\r\n                data.setColumns(cells);\r\n                results.add(data);\r\n            }\r\n        }\r\n        return results;\r\n    }\r\n\r\n    /**\r\n     * Sets the fetch size.\r\n     * \r\n     * @param fetchSize\r\n     *            the new fetch size\r\n     */\r\n    public void setFetchSize(final int fetchSize)\r\n    {\r\n        this.fetchSize = fetchSize;\r\n    }\r\n\r\n    /**\r\n     * Next.\r\n     * \r\n     * @return the h base data\r\n     */\r\n    public HBaseDataWrapper next()\r\n    {\r\n        Result result = resultsIter.next();\r\n        counter++;\r\n        List<Cell> cells = result.listCells();\r\n        HBaseDataWrapper data = new HBaseDataWrapper(tableName, result.getRow());\r\n        data.setColumns(cells);\r\n        return data;\r\n    }\r\n\r\n    /**\r\n     * Checks for next.\r\n     * \r\n     * @return true, if successful\r\n     */\r\n    public boolean hasNext()\r\n    {\r\n        if (scanner == null)\r\n        {\r\n            return false;\r\n        }\r\n        else\r\n        {\r\n            if (fetchSize != null)\r\n            {\r\n                if (counter < fetchSize)\r\n                {\r\n                    return resultsIter.hasNext();\r\n                }\r\n            }\r\n            else\r\n            {\r\n                return resultsIter.hasNext();\r\n            }\r\n        }\r\n        return false;\r\n    }\r\n\r\n    /**\r\n     * Reset.\r\n     */\r\n    public void reset()\r\n    {\r\n        scanner = null;\r\n        fetchSize = null;\r\n        resultsIter = null;\r\n        tableName = null;\r\n        counter = 0;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/service/HBaseWriter.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.service;\n\nimport java.io.IOException;\nimport java.util.Map;\n\nimport javax.persistence.PersistenceException;\n\nimport org.apache.hadoop.hbase.client.Delete;\nimport org.apache.hadoop.hbase.client.Put;\nimport org.apache.hadoop.hbase.client.Table;\nimport org.apache.hadoop.hbase.util.Bytes;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.Writer;\nimport com.impetus.client.hbase.admin.HBaseCell;\nimport com.impetus.client.hbase.admin.HBaseRow;\nimport com.impetus.client.hbase.utils.HBaseUtils;\n\n/**\n * The Class HBaseWriter.\n * \n * @author Pragalbh Garg\n */\npublic class HBaseWriter implements Writer\n{\n    /** the log used by this class. */\n    private static Logger logger = LoggerFactory.getLogger(HBaseWriter.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.Writer#writeRow(org.apache.hadoop.hbase.client\n     * .Table, com.impetus.client.hbase.admin.HBaseRow)\n     */\n    @Override\n    public void writeRow(Table hTable, HBaseRow hbaseRow) throws IOException\n    {\n        Put p = preparePut(hbaseRow);\n        hTable.put(p);\n    }\n\n    /**\n     * Prepare put.\n     * \n     * @param hbaseRow\n     *            the hbase row\n     * @return the put\n     */\n    public Put preparePut(HBaseRow hbaseRow)\n    {\n        Put p = new Put(HBaseUtils.getBytes(hbaseRow.getRowKey()));\n        for (HBaseCell hbaseCell : hbaseRow.getRowCells())\n        {\n            String colFamily = hbaseCell.getColumnFamily();\n            String colQualifier = hbaseCell.getColumnName();\n            Object colValue = hbaseCell.getValue();\n            if (colFamily != null && colQualifier != null && colValue != null)\n                p.addColumn(Bytes.toBytes(colFamily), Bytes.toBytes(colQualifier), HBaseUtils.getBytes(colValue));\n        }\n        return p;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.Writer#writeColumns(org.apache.hadoop.hbase.\n     * client.Table, java.lang.Object, java.util.Map, java.lang.String)\n     */\n    @Override\n    public void writeColumns(Table htable, Object rowKey, Map<String, Object> columns, String columnFamilyName)\n            throws IOException\n    {\n        if (columns != null && !columns.isEmpty())\n        {\n            Put p = new Put(HBaseUtils.getBytes(rowKey));\n            for (String columnName : columns.keySet())\n            {\n                p.addColumn(columnFamilyName.getBytes(), Bytes.toBytes(columnName),\n                        HBaseUtils.getBytes(columns.get(columnName)));\n            }\n            htable.put(p);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.client.hbase.Writer#delete(org.apache.hadoop.hbase.client\n     * .Table, java.lang.Object)\n     */\n    @Override\n    public void delete(Table hTable, Object rowKey, String colFamily, String colName)\n    {\n        try\n        {\n            byte[] rowBytes = HBaseUtils.getBytes(rowKey);\n            Delete delete = new Delete(rowBytes);\n            hTable.delete(delete);\n        }\n        catch (IOException e)\n        {\n            logger.error(\"Error while delete on hbase for : \" + rowKey);\n            throw new PersistenceException(\"Could not perform delete. Caused by: \", e);\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/utils/HBaseUtils.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.utils;\n\nimport java.math.BigDecimal;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;\nimport org.apache.hadoop.hbase.util.Bytes;\n\nimport com.impetus.client.hbase.query.SingleColumnFilterFactory;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\n\n/**\n * The Class HBaseUtils.\n * \n * @author Pragalbh Garg\n */\npublic final class HBaseUtils\n{\n\n    /** The Constant AUTO_ID_ROW. */\n    public static final String AUTO_ID_ROW = \"kunderaAutoIdRow\";\n\n     /** The Constant DELIM. */\n    public static final String DELIM = \"#\";\n\n    /** The Constant EQUALS. */\n    public static final String EQUALS = \"=\";\n\n    /** The Constant COMP_KEY_DELIM. */\n    public static final String COMP_KEY_DELIM = \"\\001\";\n\n    /** The Constant AND. */\n    public static final String AND = \"AND\";\n\n    /** The Constant OR. */\n    public static final String OR = \"OR\";\n\n    /** The Constant COLON. */\n    public static final String COLON = \":\";\n\n    public static final String SIZE = \"size\";\n    \n    public static final String DOT = \".\";\n\n    /**\n     * Gets the bytes.\n     * \n     * @param value\n     *            the value\n     * @param clazz\n     *            the clazz\n     * @return the bytes\n     */\n    public static byte[] getBytes(Object value, Class<?> clazz)\n    {\n        if (clazz.isAssignableFrom(String.class))\n        {\n            return Bytes.toBytes(value.toString());\n        }\n        else if (clazz.equals(int.class) || clazz.isAssignableFrom(Integer.class))\n        {\n            return Bytes.toBytes(value instanceof Integer ? (Integer) value : new Integer(value.toString()));\n        }\n        else if (clazz.equals(long.class) || clazz.isAssignableFrom(Long.class))\n        {\n            return Bytes.toBytes(value instanceof Long ? (Long) value : new Long(value.toString()));\n        }\n        else if (clazz.equals(boolean.class) || clazz.isAssignableFrom(Boolean.class))\n        {\n            return Bytes.toBytes(value instanceof Boolean ? (Boolean) value : new Boolean(value.toString()));\n        }\n        else if (clazz.equals(double.class) || clazz.isAssignableFrom(Double.class))\n        {\n            return Bytes.toBytes(value instanceof Double ? (Double) value : new Double(value.toString()));\n        }\n        else if (clazz.equals(float.class) || clazz.isAssignableFrom(Float.class))\n        {\n            return Bytes.toBytes(value instanceof Float ? (Float) value : new Float(value.toString()));\n        }\n        else if (clazz.equals(short.class) || clazz.isAssignableFrom(Short.class))\n        {\n            return Bytes.toBytes(value instanceof Short ? (Short) value : new Short(value.toString()));\n        }\n        else if (clazz.equals(BigDecimal.class))\n        {\n            return Bytes.toBytes(value instanceof BigDecimal ? (BigDecimal) value : new BigDecimal(value.toString()));\n        }\n        else\n        {\n            if (value.getClass().isAssignableFrom(String.class))\n            {\n                value = PropertyAccessorFactory.getPropertyAccessor(clazz).fromString(clazz, value.toString());\n            }\n            return PropertyAccessorFactory.getPropertyAccessor(clazz).toBytes(value);\n        }\n    }\n\n    /**\n     * Gets the bytes.\n     * \n     * @param o\n     *            the o\n     * @return the bytes\n     */\n    public static byte[] getBytes(Object o)\n    {\n        if (o != null)\n        {\n            return getBytes(o, o.getClass());\n        }\n\n        return null;\n    }\n\n    /**\n     * From bytes.\n     * \n     * @param m\n     *            the m\n     * @param metaModel\n     *            the meta model\n     * @param b\n     *            the b\n     * @return the object\n     */\n    public static Object fromBytes(EntityMetadata m, MetamodelImpl metaModel, byte[] b)\n    {\n        Class idFieldClass = m.getIdAttribute().getJavaType();\n        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n        {\n            return fromBytes(b, String.class);\n        }\n        return fromBytes(b, idFieldClass);\n    }\n\n    /**\n     * From bytes.\n     * \n     * @param b\n     *            the b\n     * @param clazz\n     *            the clazz\n     * @return the object\n     */\n    public static Object fromBytes(byte[] b, Class<?> clazz)\n    {\n\n        if (clazz.isAssignableFrom(String.class))\n        {\n            return Bytes.toString(b);\n        }\n        else if (clazz.equals(int.class) || clazz.isAssignableFrom(Integer.class))\n        {\n            return Bytes.toInt(b);\n        }\n        else if (clazz.equals(long.class) || clazz.isAssignableFrom(Long.class))\n        {\n            return Bytes.toLong(b);\n        }\n        else if (clazz.equals(boolean.class) || clazz.isAssignableFrom(Boolean.class))\n        {\n            return Bytes.toBoolean(b);\n        }\n        else if (clazz.equals(double.class) || clazz.isAssignableFrom(Double.class))\n        {\n            return Bytes.toDouble(b);\n        }\n        else if (clazz.equals(float.class) || clazz.isAssignableFrom(Float.class))\n        {\n            return Bytes.toFloat(b);\n        }\n        else if (clazz.equals(short.class) || clazz.isAssignableFrom(Short.class))\n        {\n            return Bytes.toShort(b);\n        }\n        else if (clazz.equals(BigDecimal.class))\n        {\n            return Bytes.toBigDecimal(b);\n        }\n        else\n        {\n            return PropertyAccessorFactory.getPropertyAccessor(clazz).fromBytes(clazz, b);\n        }\n    }\n\n    /**\n     * Gets the operator.\n     * \n     * @param condition\n     *            the condition\n     * @param idPresent\n     *            the id present\n     * @param useFilter\n     *            the use filter\n     * @return the operator\n     */\n    public static SingleColumnFilterFactory getOperator(String condition, boolean idPresent, boolean useFilter)\n    {\n        if (condition.equals(\"=\"))\n        {\n            return SingleColumnFilterFactory.EQUAL;\n        }\n        else if (condition.equals(\">\"))\n        {\n            return SingleColumnFilterFactory.GREATER;\n        }\n        else if (condition.equals(\"<\"))\n        {\n            return SingleColumnFilterFactory.LESS;\n        }\n        else if (condition.equals(\">=\"))\n        {\n            return SingleColumnFilterFactory.GREATER_OR_EQUAL;\n        }\n        else if (condition.equals(\"<=\"))\n        {\n            return SingleColumnFilterFactory.LESS_OR_EQUAL;\n        }\n        else if (condition.equals(\"<>\"))\n        {\n            return SingleColumnFilterFactory.NOT_EQUAL;\n        }\n        else if (condition.equals(\"LIKE\"))\n        {\n            return SingleColumnFilterFactory.LIKE;\n        }\n        else if (condition.equals(\"REGEXP\"))\n        {\n            return SingleColumnFilterFactory.REGEXP;\n        }\n        else if (useFilter)\n        {\n            if (!idPresent)\n            {\n                throw new UnsupportedOperationException(\" Condition \" + condition + \" is not suported in  hbase!\");\n            }\n            else\n            {\n                throw new UnsupportedOperationException(\" Condition \" + condition\n                        + \" is not suported for query on row key!\");\n\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Gets the h table name.\n     * \n     * @param namespace\n     *            the namespace\n     * @param tableName\n     *            the table name\n     * @return the h table name\n     */\n    public static String getHTableName(String namespace, String tableName)\n    {\n        return namespace + COLON + tableName;\n    }\n\n    /**\n     * Gets the column data key.\n     * \n     * @param string\n     *            the string\n     * @param string2\n     *            the string2\n     * @return the column data key\n     */\n    public static String getColumnDataKey(String string, String string2)\n    {\n        return string + COLON + string2;\n\n    }\n\n    /**\n     * Checks if is find key only.\n     * \n     * @param metadata\n     *            the metadata\n     * @param colToOutput\n     *            the col to output\n     * @return true, if is find key only\n     */\n    public static boolean isFindKeyOnly(EntityMetadata metadata, List<Map<String, Object>> colToOutput)\n    {\n        if (colToOutput != null && colToOutput.size() == 1)\n        {\n            String idCol = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();\n            return idCol.equals(colToOutput.get(0).get(Constants.DB_COL_NAME)) && !(boolean) colToOutput.get(0).get(Constants.IS_EMBEDDABLE);\n        }\n        else\n        {\n            return false;\n        }\n    }\n\n    /**\n     * Checks if is auto id value row.\n     * \n     * @param row\n     *            the row\n     * @return true, if is auto id value row\n     */\n    public static boolean isAutoIdValueRow(byte[] row)\n    {\n        return ((String) HBaseUtils.fromBytes(row, String.class)).equals(AUTO_ID_ROW);\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/configuration/HBaseUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.configuration;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class HBaseUser.\n * \n * @author Kuldeep Mishra\n */\n@Entity\n@Table(name = \"HBASEUSERXYZ\", schema = \"KunderaHbaseXmlTest@XmlPropertyTest\")\npublic class HBaseUser\n{\n\n    /** The name. */\n    @Id\n    private String name;\n\n    /** The age. */\n    @Column\n    private int age;\n\n    /** The address. */\n    @Column\n    private String address;\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/configuration/HBaseUserTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.configuration;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.hadoop.hbase.HColumnDescriptor;\nimport org.apache.hadoop.hbase.HTableDescriptor;\nimport org.apache.hadoop.hbase.TableNotFoundException;\nimport org.apache.hadoop.hbase.client.Connection;\nimport org.apache.hadoop.hbase.client.ConnectionFactory;\nimport org.apache.hadoop.hbase.client.HBaseAdmin;\nimport org.apache.hadoop.hbase.io.compress.Compression.Algorithm;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class HBaseUserTest.\n * \n * @author Kuldeep Mishra\n */\npublic class HBaseUserTest\n{\n\n    /** The Constant TABLE. */\n    private static final String TABLE = \"KunderaHbaseXmlTest:HBASEUSERXYZ\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The admin. */\n    private static HBaseAdmin admin;\n\n    /** The connection. */\n    private static Connection connection;\n\n    /**\n     * logger used for logging statement.\n     */\n    private static final Logger logger = LoggerFactory.getLogger(HBaseUserTest.class);\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        connection = ConnectionFactory.createConnection();\n        admin = (HBaseAdmin) connection.getAdmin();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        HBaseTestingUtils.dropSchema(\"HBaseNew\");\n        HBaseTestingUtils.dropSchema(\"KunderaHbaseXmlTest\");\n    }\n\n    /**\n     * Test.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    @Test\n    public void test() throws IOException\n    {\n        emf = Persistence.createEntityManagerFactory(\"XmlPropertyTest\");\n        try\n        {\n            HTableDescriptor hTableDescriptor = admin.getTableDescriptor(TABLE.getBytes());\n            int count = 0;\n            for (HColumnDescriptor columnDescriptor : hTableDescriptor.getColumnFamilies())\n            {\n                if (columnDescriptor.getNameAsString().equalsIgnoreCase(\"HBASEUSERXYZ\"))\n                {\n                    Assert.assertEquals(Algorithm.valueOf(\"GZ\"), columnDescriptor.getCompactionCompressionType());\n                    Assert.assertEquals(Integer.parseInt(\"12345678\"), columnDescriptor.getTimeToLive());\n                    Assert.assertEquals(Algorithm.valueOf(\"GZ\"), columnDescriptor.getCompressionType());\n                    Assert.assertEquals(Integer.parseInt(\"6\"), columnDescriptor.getMaxVersions());\n                    Assert.assertEquals(Integer.parseInt(\"3\"), columnDescriptor.getMinVersions());\n                    count++;\n                }\n            }\n            Assert.assertEquals(1, count);\n        }\n        catch (TableNotFoundException tnfe)\n        {\n            logger.error(\"Error during UserTest, caused by :\" + tnfe);\n        }\n        catch (IOException ie)\n        {\n            logger.error(\"Error during UserTest, caused by :\" + ie);\n        }\n        finally\n        {\n            emf.close();\n            Assert.assertTrue(admin.isTableAvailable(TABLE));\n        }\n    }\n\n    /**\n     * Test using external property.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    @Test\n    public void testUsingExternalProperty() throws IOException\n    {\n        Map<String, String> puProperties = new HashMap<String, String>();\n        puProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n        puProperties.put(\"kundera.keyspace\", \"KunderaHbaseKeyspace\");\n        emf = Persistence.createEntityManagerFactory(\"XmlPropertyTest\", puProperties);\n        Assert.assertTrue(admin.isTableAvailable(\"KunderaHbaseKeyspace:HBASEUSERXYZ\"));\n        emf.close();\n        Assert.assertFalse(admin.isTableAvailable(\"KunderaHbaseKeyspace:HBASEUSERXYZ\"));\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/configuration/HbasePropertySetterTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.configuration;\n\nimport java.io.IOException;\nimport java.lang.reflect.Field;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.hadoop.hbase.filter.ColumnPaginationFilter;\nimport org.apache.hadoop.hbase.filter.Filter;\nimport org.apache.hadoop.hbase.filter.FilterList;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.hbase.HBaseClient;\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\n\n/**\n * The Class HbasePropertySetterTest.\n * \n * @author Chhavi Gangwal\n */\npublic class HbasePropertySetterTest\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"XmlPropertyTest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * logger used for logging statement.\n     */\n    private static final Logger logger = LoggerFactory.getLogger(HbasePropertySetterTest.class);\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        Map<String, String> puProperties = new HashMap<String, String>();\n        puProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n        puProperties.put(\"kundera.keyspace\", \"KunderaHbaseKeyspace\");\n        emf = Persistence.createEntityManagerFactory(HBASE_PU, puProperties);\n\n    }\n\n    /**\n     * drops the keyspace and closes connection.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        HBaseTestingUtils.dropSchema(\"KunderaHbaseKeyspace\");\n    }\n\n    /**\n     * Sets property of hbase client in form of String.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    @Test\n    public void testUsingExternalStringProperty() throws IOException\n    {\n\n        Map<String, Object> puPropertiesString = new HashMap<String, Object>();\n\n        puPropertiesString.put(PersistenceProperties.KUNDERA_BATCH_SIZE, \"10\");\n\n        em = emf.createEntityManager(puPropertiesString);\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        Client client = clients.get(HBASE_PU);\n\n        Assert.assertEquals(((HBaseClient) client).getBatchSize(), 10);\n\n    }\n\n    /**\n     * Sets property of hbase client in form of object map.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    @Test\n    public void testUsingExternalObjectProperty() throws IOException\n    {\n        try\n        {\n            Map<String, Object> puPropertiesString = new HashMap<String, Object>();\n            Filter filter = new ColumnPaginationFilter(2, 0);\n            FilterList filterlist = new FilterList();\n            filterlist.addFilter(filter);\n\n            puPropertiesString.put(\"hbase.filter\", filter);\n            puPropertiesString.put(PersistenceProperties.KUNDERA_BATCH_SIZE, 10);\n\n            em = emf.createEntityManager(puPropertiesString);\n\n            Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n            Client client = clients.get(HBASE_PU);\n\n            Field f1, f2;\n\n            f1 = ((HBaseClient) client).getClass().getDeclaredField(\"handler\"); // NoSuchFieldException\n            f1.setAccessible(true);\n            f2 = f1.get((HBaseClient) client).getClass().getDeclaredField(\"filter\");\n            f2.setAccessible(true);\n            Assert.assertEquals(f2.get(f1.get((HBaseClient) client)).toString(), filterlist.toString());\n            Assert.assertEquals(((HBaseClient) client).getBatchSize(), 10);\n        }\n        catch (NoSuchFieldException nfe)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\", nfe.getMessage());\n\n        }\n        catch (IllegalArgumentException iae)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\", iae.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            Assert.fail();\n            logger.error(\"Error in test, Caused by: .\", e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/BasicCRUDTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.PersonHBase.Day;\nimport com.impetus.client.hbase.crud.PersonHBase.Month;\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class CrudTestBasic.\n * \n * @author Pragalbh Garg\n */\npublic class BasicCRUDTest\n{\n    /** The Constant SCHEMA. */\n    private static final String SCHEMA = \"HBaseNew\";\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"crudTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test crud operations.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testCRUDOperations() throws Exception\n    {\n        testInsert();\n        testMerge();\n        testRemove();\n    }\n\n    /**\n     * Test insert.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    private void testInsert() throws Exception\n    {\n        em.clear();\n        PersonHBase p = new PersonHBase();\n        p.setPersonId(\"1\");\n        p.setPersonName(\"pragalbh\");\n        p.setAge(22);\n        p.setMonth(Month.JAN);\n        p.setDay(Day.FRIDAY);\n        em.persist(p);\n        em.clear();\n        PersonHBase p2 = em.find(PersonHBase.class, \"1\");\n        Assert.assertNotNull(p2);\n        Assert.assertEquals(\"1\", p2.getPersonId());\n        Assert.assertEquals(\"pragalbh\", p2.getPersonName());\n\n    }\n\n    /**\n     * Test merge.\n     */\n    private void testMerge()\n    {\n        em.clear();\n        PersonHBase p = em.find(PersonHBase.class, \"1\");\n        p.setPersonName(\"devender\");\n        em.merge(p);\n        em.clear();\n        PersonHBase p1 = em.find(PersonHBase.class, \"1\");\n        Assert.assertEquals(\"devender\", p1.getPersonName());\n    }\n\n    /**\n     * Test remove.\n     */\n    private void testRemove()\n    {\n        em.clear();\n        PersonHBase p = em.find(PersonHBase.class, \"1\");\n        em.remove(p);\n        em.clear();\n        PersonHBase p1 = em.find(PersonHBase.class, \"1\");\n        Assert.assertNull(p1);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/HBaseBatchProcessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.persistence.api.Batcher;\n\n/**\n * The Class HBaseBatchProcessorTest.\n * \n * @author Devender Yadav\n */\npublic class HBaseBatchProcessorTest\n{\n\n    /** The Constant SCHEMA. */\n    private static final String SCHEMA = \"HBaseNew\";\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"crudTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The rows. */\n    private List<PersonHBase> rows;\n\n    /** The batch size. */\n    private int BATCH_SIZE = 5;\n\n    /** The property map. */\n    private static Map<String, String> propertyMap = new HashMap<String, String>();\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        // as Batch size is 5.\n        propertyMap.put(\"kundera.batch.size\", \"5\");\n        emf = Persistence.createEntityManagerFactory(HBASE_PU, propertyMap);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test case for batch operation.\n     */\n    @Test\n    public void onBatch()\n    {\n        int counter = 1;\n        rows = prepareData(10);\n        for (PersonHBase entity : rows)\n        {\n            em.persist(entity);\n\n            if (counter < BATCH_SIZE)\n            {\n                Assert.assertNull(em.find(PersonHBase.class, entity.getPersonId()));\n            }\n            else if (counter == BATCH_SIZE)\n            {\n                Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n\n                Batcher client = (Batcher) clients.get(HBASE_PU);\n                Assert.assertEquals(5, client.getBatchSize());\n                em.clear();\n                for (int i = 0; i < BATCH_SIZE; i++)\n                {\n                    // assert on each batch size record\n                    Assert.assertNotNull(em.find(PersonHBase.class, rows.get(i).getPersonId()));\n                }\n                counter = 0;\n            }\n            counter++;\n        }\n\n        em.clear();\n        em.flush();\n\n        String sql = \" Select p from PersonHBase p\";\n        Query query = em.createQuery(sql);\n        List<PersonHBase> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(10, results.size());\n\n        for (PersonHBase entity : results)\n        {\n            entity.setPersonName(\"dev\");\n            em.merge(entity);\n            if (counter < BATCH_SIZE)\n            {\n                PersonHBase p = em.find(PersonHBase.class, entity.getPersonId());\n                Assert.assertEquals(\"vivek\", p.getPersonName());\n            }\n            else if (counter == BATCH_SIZE)\n            {\n                em.clear();\n                for (int i = 0; i < BATCH_SIZE; i++)\n                {\n                    PersonHBase p = em.find(PersonHBase.class, results.get(i).getPersonId());\n                    Assert.assertEquals(\"dev\", p.getPersonName());\n                }\n                counter = 0;\n            }\n            counter++;\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param noOfRecords\n     *            the no of records\n     * @return the list\n     */\n    private List<PersonHBase> prepareData(Integer noOfRecords)\n    {\n        List<PersonHBase> persons = new ArrayList<PersonHBase>();\n        for (int i = 1; i <= noOfRecords; i++)\n        {\n            PersonHBase o = new PersonHBase();\n            o.setPersonId(i + \"\");\n            o.setPersonName(\"vivek\");\n            o.setAge(10);\n            persons.add(o);\n        }\n        return persons;\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/PersonHBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud;\n\n/**\n * @author Pragalbh Garg\n *\n */\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class PersonHBase.\n */\n@Entity\n@Table(name = \"PERSON_HBASE\", schema = \"HBaseNew@crudTest\")\npublic class PersonHBase\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    /** The day. */\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    /** The month. */\n    @Column(name = \"MONTH_ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Month month;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the day.\n     * \n     * @return the day\n     */\n    public Day getDay()\n    {\n        return day;\n    }\n\n    /**\n     * Sets the day.\n     * \n     * @param day\n     *            the day to set\n     */\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n\n    /**\n     * Gets the month.\n     * \n     * @return the month\n     */\n    public Month getMonth()\n    {\n        return month;\n    }\n\n    /**\n     * Sets the month.\n     * \n     * @param month\n     *            the new month\n     */\n    public void setMonth(Month month)\n    {\n        this.month = month;\n    }\n\n    /**\n     * The Enum Day.\n     */\n    enum Day\n    {\n\n        /** The monday. */\n        MONDAY,\n        /** The tuesday. */\n        TUESDAY,\n        /** The wednesday. */\n        WEDNESDAY,\n        /** The thursday. */\n        THURSDAY,\n        /** The friday. */\n        FRIDAY,\n        /** The saturday. */\n        SATURDAY,\n        /** The sunday. */\n        SUNDAY;\n    }\n\n    /**\n     * The Enum Month.\n     */\n    enum Month\n    {\n\n        /** The jan. */\n        JAN,\n        /** The feb. */\n        FEB,\n        /** The march. */\n        MARCH,\n        /** The april. */\n        APRIL,\n        /** The may. */\n        MAY,\n        /** The june. */\n        JUNE;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/AddressBiOTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.association;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class AddressBiOTO.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"ADDRESS_BOTO\", schema = \"HBaseNew@associationTest\")\npublic class AddressBiOTO\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private int addressId;\n\n    /** The city. */\n    @Column(name = \"CITY\")\n    private String city;\n\n    /** The person. */\n    @OneToOne(mappedBy = \"address\", cascade = CascadeType.ALL)\n    private PersonBiOTO person;\n\n    /**\n     * Instantiates a new address bi oto.\n     */\n    public AddressBiOTO()\n    {\n\n    }\n\n    /**\n     * Instantiates a new address bi oto.\n     * \n     * @param addressId\n     *            the address id\n     * @param city\n     *            the city\n     */\n    public AddressBiOTO(int addressId, String city)\n    {\n        this.addressId = addressId;\n        this.city = city;\n    }\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public int getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(int addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the city.\n     * \n     * @return the city\n     */\n    public String getCity()\n    {\n        return city;\n    }\n\n    /**\n     * Sets the city.\n     * \n     * @param city\n     *            the new city\n     */\n    public void setCity(String city)\n    {\n        this.city = city;\n    }\n\n    /**\n     * Gets the person.\n     * \n     * @return the person\n     */\n    public PersonBiOTO getPerson()\n    {\n        return person;\n    }\n\n    /**\n     * Sets the person.\n     * \n     * @param person\n     *            the new person\n     */\n    public void setPerson(PersonBiOTO person)\n    {\n        this.person = person;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/AddressUniOTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.association;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class AddressUniOTO.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"ADDRESS_UOTO\", schema = \"HBaseNew@associationTest\")\npublic class AddressUniOTO\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private int addressId;\n\n    /** The city. */\n    @Column(name = \"CITY\")\n    private String city;\n\n    /**\n     * Instantiates a new address uni oto.\n     */\n    public AddressUniOTO()\n    {\n\n    }\n\n    /**\n     * Instantiates a new address uni oto.\n     * \n     * @param addressId\n     *            the address id\n     * @param city\n     *            the city\n     */\n    public AddressUniOTO(int addressId, String city)\n    {\n        this.addressId = addressId;\n        this.city = city;\n    }\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public int getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(int addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the city.\n     * \n     * @return the city\n     */\n    public String getCity()\n    {\n        return city;\n    }\n\n    /**\n     * Sets the city.\n     * \n     * @param city\n     *            the new city\n     */\n    public void setCity(String city)\n    {\n        this.city = city;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/HBaseBiAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.association;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\nimport com.impetus.kundera.client.crud.associations.AssociationsBiDirectionalBase;\n\n/**\n * The Class HBaseBiAssociationTest.\n * \n * @author Pragalbh Garg\n */\npublic class HBaseBiAssociationTest extends AssociationsBiDirectionalBase\n{\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        _PU = \"associationTest\";\n        super.setUpInternal();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        assertBegin();\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        HBaseTestingUtils.dropSchema(\"HBaseNew\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/HBaseBiOneToOneTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.association;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class HBaseAssociationBiOTOTest.\n * \n * @author Devender Yadav\n */\npublic class HBaseBiOneToOneTest\n{\n\n    /** The Constant SCHEMA. */\n    private static final String SCHEMA = \"HBaseNew\";\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"associationTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test assocations bidirectional one to one.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testAssocationsBiOTO() throws Exception\n    {\n        testInsert();\n        testUpdate();\n        testDelete();\n    }\n\n    /**\n     * Test insert.\n     */\n    private void testInsert()\n    {\n\n        insertPersonAndAddress();\n\n        em.clear();\n        PersonBiOTO p = em.find(PersonBiOTO.class, 1);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPersonId());\n        Assert.assertEquals(\"Devender\", p.getPersonName());\n        Assert.assertEquals(23, p.getAge());\n        Assert.assertNotNull(p.getAddress());\n        Assert.assertEquals(101, p.getAddress().getAddressId());\n        Assert.assertEquals(\"Noida\", p.getAddress().getCity());\n\n        em.clear();\n        AddressBiOTO add = em.find(AddressBiOTO.class, 101);\n        Assert.assertEquals(101, add.getAddressId());\n        Assert.assertEquals(\"Noida\", add.getCity());\n    }\n\n    /**\n     * Test update.\n     */\n    private void testUpdate()\n    {\n        insertPersonAndAddress();\n\n        em.clear();\n        PersonBiOTO p = em.find(PersonBiOTO.class, 1);\n        p.setPersonName(\"Pragalbh\");\n        p.getAddress().setCity(\"Indore\");\n\n        em.merge(p);\n\n        em.clear();\n        PersonBiOTO p1 = em.find(PersonBiOTO.class, 1);\n\n        em.clear();\n        AddressBiOTO add1 = em.find(AddressBiOTO.class, 101);\n\n        Assert.assertEquals(\"Pragalbh\", p1.getPersonName());\n        Assert.assertEquals(\"Indore\", p1.getAddress().getCity());\n        Assert.assertEquals(\"Indore\", add1.getCity());\n\n        insertPersonAndAddress();\n\n        em.clear();\n        AddressBiOTO add = em.find(AddressBiOTO.class, 101);\n        add.setCity(\"Delhi\");\n\n        em.merge(add);\n\n        em.clear();\n        PersonBiOTO p2 = em.find(PersonBiOTO.class, 1);\n        Assert.assertEquals(\"Delhi\", p2.getAddress().getCity());\n        em.clear();\n        AddressBiOTO add2 = em.find(AddressBiOTO.class, 101);\n\n        Assert.assertEquals(\"Delhi\", add2.getCity());\n\n    }\n\n    /**\n     * Test delete.\n     */\n    private void testDelete()\n    {\n        insertPersonAndAddress();\n        em.clear();\n        em.remove(em.find(PersonBiOTO.class, 1));\n        em.clear();\n        PersonBiOTO p = em.find(PersonBiOTO.class, 1);\n        em.clear();\n        AddressBiOTO add = em.find(AddressBiOTO.class, 101);\n        Assert.assertNull(p);\n        Assert.assertNull(add);\n\n        insertPersonAndAddress();\n        em.clear();\n        em.remove(em.find(AddressBiOTO.class, 101));\n        em.clear();\n        AddressBiOTO add1 = em.find(AddressBiOTO.class, 101);\n        Assert.assertNull(add1);\n        em.clear();\n        PersonBiOTO p1 = em.find(PersonBiOTO.class, 1);\n        Assert.assertNull(p1.getAddress());\n    }\n\n    /**\n     * Insert person and address.\n     */\n    private void insertPersonAndAddress()\n    {\n        PersonBiOTO person = new PersonBiOTO(1, \"Devender\", 23);\n        AddressBiOTO address = new AddressBiOTO(101, \"Noida\");\n        person.setAddress(address);\n        em.persist(person);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/HBaseUniOneToOneTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.association;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class HBaseAssociationUniOTOTest.\n * \n * @author Devender Yadav\n */\npublic class HBaseUniOneToOneTest\n{\n\n    /** The Constant SCHEMA. */\n    private static final String SCHEMA = \"HBaseNew\";\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"associationTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test assocations unidirectional one to one.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testAssocationsUniOTO() throws Exception\n    {\n        testInsert();\n        testUpdate();\n        testDelete();\n    }\n\n    /**\n     * Test insert.\n     */\n    private void testInsert()\n    {\n\n        insertPersonAndAddress();\n\n        em.clear();\n        PersonUniOTO p = em.find(PersonUniOTO.class, 1);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPersonId());\n        Assert.assertEquals(\"Devender\", p.getPersonName());\n        Assert.assertEquals(23, p.getAge());\n        Assert.assertNotNull(p.getAddress());\n        Assert.assertEquals(101, p.getAddress().getAddressId());\n        Assert.assertEquals(\"Noida\", p.getAddress().getCity());\n\n        em.clear();\n        AddressUniOTO add = em.find(AddressUniOTO.class, 101);\n        Assert.assertNotNull(add);\n        Assert.assertEquals(101, add.getAddressId());\n        Assert.assertEquals(\"Noida\", add.getCity());\n    }\n\n    /**\n     * Test update.\n     */\n    private void testUpdate()\n    {\n        insertPersonAndAddress();\n\n        em.clear();\n        PersonUniOTO p = em.find(PersonUniOTO.class, 1);\n        p.setPersonName(\"Pragalbh\");\n        p.getAddress().setCity(\"Indore\");\n\n        em.clear();\n        em.merge(p);\n\n        em.clear();\n        PersonUniOTO p1 = em.find(PersonUniOTO.class, 1);\n        em.clear();\n        AddressUniOTO add1 = em.find(AddressUniOTO.class, 101);\n\n        Assert.assertEquals(\"Pragalbh\", p1.getPersonName());\n        Assert.assertEquals(\"Indore\", p1.getAddress().getCity());\n        Assert.assertEquals(\"Indore\", add1.getCity());\n\n    }\n\n    /**\n     * Test delete.\n     */\n    private void testDelete()\n    {\n        insertPersonAndAddress();\n        em.clear();\n        em.remove(em.find(PersonUniOTO.class, 1));\n\n        em.clear();\n        PersonUniOTO p = em.find(PersonUniOTO.class, 1);\n\n        em.clear();\n        AddressUniOTO add = em.find(AddressUniOTO.class, 101);\n\n        Assert.assertNull(p);\n        Assert.assertNull(add);\n\n        insertPersonAndAddress();\n        em.clear();\n        em.remove(em.find(AddressUniOTO.class, 101));\n\n        em.clear();\n        AddressUniOTO add1 = em.find(AddressUniOTO.class, 101);\n        Assert.assertNull(add1);\n\n        em.clear();\n        PersonUniOTO p1 = em.find(PersonUniOTO.class, 1);\n        Assert.assertNull(p1.getAddress());\n    }\n\n    /**\n     * Insert person and address.\n     */\n    private void insertPersonAndAddress()\n    {\n        PersonUniOTO person = new PersonUniOTO(1, \"Devender\", 23);\n        AddressUniOTO address = new AddressUniOTO(101, \"Noida\");\n        person.setAddress(address);\n        em.persist(person);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/HabitatMToM.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2015 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase.crud.association;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * The Class HabitatMToM.\r\n */\r\n@Entity\r\n@Table(name = \"HABITAT_MTM\", schema = \"HBaseNew@mtmTest\")\r\n/**\r\n * @author Pragalbh Garg\r\n * \r\n */\r\npublic class HabitatMToM\r\n{\r\n\r\n    /** The address id. */\r\n    @Id\r\n    @Column(name = \"ADDRESS_ID\")\r\n    private String addressId;\r\n\r\n    /** The street. */\r\n    @Column(name = \"STREET\")\r\n    private String street;\r\n\r\n    /**\r\n     * Gets the address id.\r\n     * \r\n     * @return the address id\r\n     */\r\n    public String getAddressId()\r\n    {\r\n        return addressId;\r\n    }\r\n\r\n    /**\r\n     * Sets the address id.\r\n     * \r\n     * @param addressId\r\n     *            the new address id\r\n     */\r\n    public void setAddressId(String addressId)\r\n    {\r\n        this.addressId = addressId;\r\n    }\r\n\r\n    /**\r\n     * Gets the street.\r\n     * \r\n     * @return the street\r\n     */\r\n    public String getStreet()\r\n    {\r\n        return street;\r\n    }\r\n\r\n    /**\r\n     * Sets the street.\r\n     * \r\n     * @param street\r\n     *            the new street\r\n     */\r\n    public void setStreet(String street)\r\n    {\r\n        this.street = street;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/HbaseManyToManyTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.association;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class HbaseManyToManyTest.\n * \n * @author Pragalbh Garg\n */\npublic class HbaseManyToManyTest\n{\n\n    /** The Constant SCHEMA. */\n    private static final String SCHEMA = \"HBaseNew\";\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"mtmTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test many to many.\n     */\n    @Test\n    public void testManyToMany()\n    {\n        persistMTM();\n        List<HabitatMToM> habitatMToM = em.createQuery(\"Select h from HabitatMToM h\").getResultList();\n        assertNotNull(habitatMToM);\n        assertEquals(3, habitatMToM.size());\n\n        List<PersonnelMToM> personnelMToM = em.createQuery(\"Select p from PersonnelMToM p\").getResultList();\n        assertNotNull(personnelMToM);\n        assertEquals(2, personnelMToM.size());\n\n        personnelMToM = em.createQuery(\"Select p from PersonnelMToM p where p.personName='John'\").getResultList();\n        assertEquals(personnelMToM.get(0).getPersonId(), \"125\");\n        assertNotNull(personnelMToM.get(0).getHabitats().iterator().next());\n\n        HabitatMToM habitatMToM1 = em.find(HabitatMToM.class, \"7\");\n        HabitatMToM habitatMToM2 = em.find(HabitatMToM.class, \"8\");\n        HabitatMToM habitatMToM3 = em.find(HabitatMToM.class, \"9\");\n\n        PersonnelMToM personnelMToM1 = em.find(PersonnelMToM.class, \"125\");\n        PersonnelMToM personnelMToM2 = em.find(PersonnelMToM.class, \"502\");\n\n        assertEquals(habitatMToM1.getStreet(), \"downing street\");\n        assertEquals(habitatMToM2.getStreet(), \"fleet street\");\n        assertEquals(habitatMToM3.getStreet(), \"greet street\");\n\n        assertEquals(personnelMToM1.getPersonName(), \"John\");\n        assertEquals(personnelMToM2.getPersonName(), \"Bully\");\n\n        assertEquals(2, personnelMToM1.getHabitats().size());\n        for (HabitatMToM habitat : personnelMToM1.getHabitats())\n        {\n            if (habitat.getAddressId().equals(\"7\"))\n            {\n                assertEquals(habitat.getStreet(), \"downing street\");\n            }\n            else\n            {\n                assertEquals(habitat.getStreet(), \"fleet street\");\n            }\n        }\n\n    }\n\n    /**\n     * Persist mtm.\n     */\n    private void persistMTM()\n    {\n        Set<HabitatMToM> habitats1 = new HashSet<HabitatMToM>();\n        Set<HabitatMToM> habitats2 = new HashSet<HabitatMToM>();\n\n        HabitatMToM habitat1 = new HabitatMToM();\n        habitat1.setAddressId(\"7\");\n        habitat1.setStreet(\"downing street\");\n\n        HabitatMToM habitat2 = new HabitatMToM();\n        habitat2.setAddressId(\"8\");\n        habitat2.setStreet(\"fleet street\");\n\n        HabitatMToM habitat3 = new HabitatMToM();\n        habitat3.setAddressId(\"9\");\n        habitat3.setStreet(\"greet street\");\n\n        habitats1.add(habitat1);\n        habitats1.add(habitat2);\n\n        habitats2.add(habitat2);\n        habitats2.add(habitat3);\n\n        PersonnelMToM person1 = new PersonnelMToM();\n        person1.setPersonId(\"125\");\n        person1.setPersonName(\"John\");\n\n        PersonnelMToM person2 = new PersonnelMToM();\n        person2.setPersonId(\"502\");\n        person2.setPersonName(\"Bully\");\n\n        person1.setHabitats(habitats1);\n        person2.setHabitats(habitats2);\n\n        em.persist(person1);\n        em.persist(person2);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/PersonBiOTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.association;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class PersonBiOTO.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"PERSON_BOTO\", schema = \"HBaseNew@associationTest\")\npublic class PersonBiOTO\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private int personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private int age;\n\n    /**\n     * Instantiates a new person bi oto.\n     */\n    public PersonBiOTO()\n    {\n\n    }\n\n    /**\n     * Instantiates a new person bi oto.\n     * \n     * @param personId\n     *            the person id\n     * @param personName\n     *            the person name\n     * @param age\n     *            the age\n     */\n    public PersonBiOTO(int personId, String personName, int age)\n    {\n        this.personId = personId;\n        this.personName = personName;\n        this.age = age;\n    }\n\n    /** The address. */\n    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressBiOTO address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the new age\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public AddressBiOTO getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the new address\n     */\n    public void setAddress(AddressBiOTO address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/PersonUniOTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.association;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class PersonUniOTO.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"PERSON_UOTO\", schema = \"HBaseNew@associationTest\")\npublic class PersonUniOTO\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private int personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private int age;\n\n    /**\n     * Instantiates a new person uni oto.\n     */\n    public PersonUniOTO()\n    {\n\n    }\n\n    /**\n     * Instantiates a new person uni oto.\n     * \n     * @param personId\n     *            the person id\n     * @param personName\n     *            the person name\n     * @param age\n     *            the age\n     */\n    public PersonUniOTO(int personId, String personName, int age)\n    {\n        this.personId = personId;\n        this.personName = personName;\n        this.age = age;\n    }\n\n    /** The address. */\n    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressUniOTO address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the new age\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public AddressUniOTO getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the new address\n     */\n    public void setAddress(AddressUniOTO address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/PersonnelMToM.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2015 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.hbase.crud.association;\r\n\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.JoinTable;\r\nimport javax.persistence.ManyToMany;\r\nimport javax.persistence.Table;\r\n\r\nimport com.impetus.kundera.index.Index;\r\nimport com.impetus.kundera.index.IndexCollection;\r\n\r\n/**\r\n * The Class PersonnelMToM.\r\n * \r\n * @author Pragalbh Garg\r\n */\r\n@Entity\r\n@Table(name = \"PERSONNEL_MTM\", schema = \"HBaseNew@mtmTest\")\r\n@IndexCollection(columns = { @Index(name = \"personName\") })\r\npublic class PersonnelMToM\r\n{\r\n\r\n    /** The person id. */\r\n    @Id\r\n    @Column(name = \"PERSON_ID\")\r\n    private String personId;\r\n\r\n    /** The person name. */\r\n    @Column(name = \"PERSON_NAME\")\r\n    private String personName;\r\n\r\n    /** The habitats. */\r\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\r\n    @JoinTable(name = \"PERSON_ADDRESS\", schema = \"HBaseNew\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\r\n    private Set<HabitatMToM> habitats;\r\n\r\n    /**\r\n     * Gets the person id.\r\n     * \r\n     * @return the person id\r\n     */\r\n    public String getPersonId()\r\n    {\r\n        return personId;\r\n    }\r\n\r\n    /**\r\n     * Gets the person name.\r\n     * \r\n     * @return the person name\r\n     */\r\n    public String getPersonName()\r\n    {\r\n        return personName;\r\n    }\r\n\r\n    /**\r\n     * Sets the person name.\r\n     * \r\n     * @param personName\r\n     *            the new person name\r\n     */\r\n    public void setPersonName(String personName)\r\n    {\r\n        this.personName = personName;\r\n    }\r\n\r\n    /**\r\n     * Sets the person id.\r\n     * \r\n     * @param personId\r\n     *            the new person id\r\n     */\r\n    public void setPersonId(String personId)\r\n    {\r\n        this.personId = personId;\r\n    }\r\n\r\n    /**\r\n     * Gets the habitats.\r\n     * \r\n     * @return the habitats\r\n     */\r\n    public Set<HabitatMToM> getHabitats()\r\n    {\r\n        return habitats;\r\n    }\r\n\r\n    /**\r\n     * Sets the habitats.\r\n     * \r\n     * @param habitats\r\n     *            the new habitats\r\n     */\r\n    public void setHabitats(Set<HabitatMToM> habitats)\r\n    {\r\n        this.habitats = habitats;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/SelfReferentialUserOTMTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.association;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class SelfReferentialUserOTMTest.\n * \n * @author devender.yadav\n */\npublic class SelfReferentialUserOTMTest\n{\n\n    /** The Constant SCHEMA. */\n    private static final String SCHEMA = \"HBaseNew\";\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"associationTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test association.\n     */\n    @Test\n    public void testAssociation()\n    {\n\n        UserOTM user1 = new UserOTM();\n        user1.setUserId(\"1\");\n        user1.setUsername(\"dev\");\n\n        UserOTM user2 = new UserOTM();\n        user2.setUserId(\"2\");\n        user2.setUsername(\"karthik\");\n\n        UserOTM user3 = new UserOTM();\n        user3.setUserId(\"3\");\n        user3.setUsername(\"amit\");\n\n        user1.addFollower(user2);\n        user2.addFollower(user3);\n\n        em.persist(user1);\n\n        UserOTM u1 = em.find(UserOTM.class, \"1\");\n        Assert.assertEquals(\"1\", u1.getUserId());\n        Assert.assertEquals(\"dev\", u1.getUsername());\n        Assert.assertEquals(1, u1.getFollowers().size());\n        Assert.assertEquals(\"2\", u1.getFollowers().get(0).getUserId());\n        Assert.assertEquals(\"karthik\", u1.getFollowers().get(0).getUsername());\n\n        UserOTM u2 = em.find(UserOTM.class, \"2\");\n        Assert.assertEquals(\"2\", u2.getUserId());\n        Assert.assertEquals(\"karthik\", u2.getUsername());\n        Assert.assertEquals(1, u2.getFollowers().size());\n        Assert.assertEquals(\"3\", u2.getFollowers().get(0).getUserId());\n        Assert.assertEquals(\"amit\", u2.getFollowers().get(0).getUsername());\n\n        UserOTM u3 = em.find(UserOTM.class, \"3\");\n        Assert.assertEquals(\"3\", u3.getUserId());\n        Assert.assertEquals(\"amit\", u3.getUsername());\n\n        List<UserOTM> userList = em.createQuery(\"select u from UserOTM u \").getResultList();\n        Assert.assertNotNull(userList);\n        Assert.assertEquals(3, userList.size());\n\n        userList = em.createQuery(\"select u from UserOTM u where u.username = 'dev'\").getResultList();\n        Assert.assertEquals(1, userList.size());\n        UserOTM user = userList.get(0);\n        Assert.assertEquals(\"1\", user.getUserId());\n        Assert.assertEquals(\"dev\", user.getUsername());\n        Assert.assertEquals(1, user.getFollowers().size());\n        Assert.assertEquals(\"2\", user.getFollowers().get(0).getUserId());\n        Assert.assertEquals(\"karthik\", user.getFollowers().get(0).getUsername());\n\n        userList = em.createQuery(\"select u from UserOTM u where u.username = 'amit'\").getResultList();\n        Assert.assertEquals(1, userList.size());\n        user = userList.get(0);\n        Assert.assertEquals(\"3\", user.getUserId());\n        Assert.assertEquals(\"amit\", user.getUsername());\n        Assert.assertEquals(0, user.getFollowers().size());\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/UserOTM.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.association;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * The Class UserOTM.\n * \n * @author devender.yadav\n */\n@Entity\n@Table(name = \"USER_OTM\", schema = \"HBaseNew@associationTest\")\npublic class UserOTM\n{\n\n    /** The user id. */\n    @Id\n    @Column(name = \"USER_ID\")\n    private String userId;\n\n    /** The username. */\n    @Column(name = \"USER_NAME\")\n    private String username;\n\n    /** The followers. */\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"FOLLOWER_ID\")\n    private List<UserOTM> followers;\n\n    /**\n     * Adds the follower.\n     * \n     * @param follower\n     *            the follower\n     */\n    public void addFollower(UserOTM follower)\n    {\n        if (this.followers == null || this.followers.isEmpty())\n        {\n            this.followers = new ArrayList<UserOTM>();\n        }\n\n        this.followers.add(follower);\n    }\n\n    /**\n     * Sets the user id.\n     * \n     * @param userId\n     *            the new user id\n     */\n    public void setUserId(String userId)\n    {\n        this.userId = userId;\n    }\n\n    /**\n     * Gets the user id.\n     * \n     * @return the user id\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * Gets the username.\n     * \n     * @return the username\n     */\n    public String getUsername()\n    {\n        return username;\n    }\n\n    /**\n     * Sets the username.\n     * \n     * @param username\n     *            the new username\n     */\n    public void setUsername(String username)\n    {\n        this.username = username;\n    }\n\n    /**\n     * Gets the followers.\n     * \n     * @return the followers\n     */\n    public List<UserOTM> getFollowers()\n    {\n        return followers;\n    }\n\n    /**\n     * Sets the followers.\n     * \n     * @param followers\n     *            the new followers\n     */\n    public void setFollowers(List<UserOTM> followers)\n    {\n        this.followers = followers;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/compositetype/HBaseCompositeTypeTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.compositetype;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class HBaseCompositeTypeTest.\n * \n * @author vivek.mishra\n */\n\npublic class HBaseCompositeTypeTest\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"queryTest\";\n\n    /** The Constant SCHEMA. */\n    private static final String SCHEMA = \"HBaseNew\";\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The time line id. */\n    private UUID timeLineId;\n\n    /** The current date. */\n    private Date currentDate = new Date();\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * CRUD over Compound primary Key.\n     */\n    @Test\n    public void onCRUD()\n    {\n        timeLineId = UUID.randomUUID();\n        HBaseCompoundKey key = new HBaseCompoundKey(\"mevivs\", 1, timeLineId);\n        HBasePrimeUser user = new HBasePrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.close(); // optional,just to clear persistence cache.\n        em = emf.createEntityManager();\n\n        HBasePrimeUser result = em.find(HBasePrimeUser.class, key);\n        validatePrimeUser(result);\n\n        em.clear();\n\n        user.setTweetBody(\"After merge\");\n        em.merge(user);\n\n        em.clear();\n        result = em.find(HBasePrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"After merge\", result.getTweetBody());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n\n        em.remove(result);\n        em.clear();\n\n        result = em.find(HBasePrimeUser.class, key);\n        Assert.assertNull(result);\n    }\n\n    /**\n     * On query.\n     */\n    @Test\n    public void onQuery()\n    {\n        timeLineId = UUID.randomUUID();\n        HBaseCompoundKey key = new HBaseCompoundKey(\"mevivs\", 1, timeLineId);\n        HBasePrimeUser user = new HBasePrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        final String noClause = \"Select u from HBasePrimeUser u\";\n        Query q = em.createQuery(noClause);\n        List results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        validatePrimeUser(results.get(0));\n\n        final String withFirstCompositeColClause = \"Select u from HBasePrimeUser u where u.key.userId = :userId\";\n        q = em.createQuery(withFirstCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        validatePrimeUser(results.get(0));\n\n        final String withClauseOnNoncomposite = \"Select u from HBasePrimeUser u where u.tweetDate = ?1\";\n        q = em.createQuery(withClauseOnNoncomposite);\n        q.setParameter(1, currentDate);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        validatePrimeUser(results.get(0));\n\n        final String withSecondCompositeColClause = \"Select u from HBasePrimeUser u where u.key.tweetId = :tweetId\";\n        q = em.createQuery(withSecondCompositeColClause);\n        q.setParameter(\"tweetId\", 1);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        final String withBothCompositeColClause = \"Select u from HBasePrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId\";\n        q = em.createQuery(withBothCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        validatePrimeUser(results.get(0));\n\n        final String withAllCompositeColClause = \"Select u from HBasePrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        q = em.createQuery(withAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        validatePrimeUser(results.get(0));\n\n        final String withLastCompositeColGTClause = \"Select u from HBasePrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId >= :timeLineId\";\n        q = em.createQuery(withLastCompositeColGTClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        validatePrimeUser(results.get(0));\n\n        final String withCompositeKeyClause = \"Select u from HBasePrimeUser u where u.key = :key\";\n        q = em.createQuery(withCompositeKeyClause);\n        q.setParameter(\"key\", key);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        validatePrimeUser(results.get(0));\n\n        final String withSelectiveCompositeColClause = \"Select u.key from HBasePrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        q = em.createQuery(withSelectiveCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"mevivs\", ((HBaseCompoundKey) results.get(0)).getUserId());\n        Assert.assertEquals(1, ((HBaseCompoundKey) results.get(0)).getTweetId());\n        Assert.assertEquals(timeLineId, ((HBaseCompoundKey) results.get(0)).getTimeLineId());\n\n        final String withSelectiveNestedCompositeColClause = \"Select u.key.userId from HBasePrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        q = em.createQuery(withSelectiveNestedCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"mevivs\", results.get(0));\n\n        em.remove(user);\n        em.clear();// optional,just to clear persistence cache.\n    }\n\n    /**\n     * On named query test.\n     */\n    @Test\n    public void onNamedQueryTest()\n    {\n        updateNamed();\n        deleteNamed();\n\n    }\n\n    /**\n     * Update by Named Query.\n     * \n     * \n     */\n    private void updateNamed()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        timeLineId = UUID.randomUUID();\n\n        HBaseCompoundKey key = new HBaseCompoundKey(\"mevivs\", 1, timeLineId);\n        HBasePrimeUser user = new HBasePrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.close();\n\n        em = emf.createEntityManager();\n\n        String updateQuery = \"Update HBasePrimeUser u SET u.tweetBody= 'after merge' where u.tweetBody= :beforeUpdate\";\n        Query q = em.createQuery(updateQuery);\n        q.setParameter(\"beforeUpdate\", \"my first tweet\");\n        q.executeUpdate();\n\n        em.close();\n        em = emf.createEntityManager();\n\n        HBasePrimeUser result = em.find(HBasePrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"after merge\", result.getTweetBody());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n    }\n\n    /**\n     * delete by Named Query.\n     */\n    private void deleteNamed()\n    {\n        timeLineId = UUID.randomUUID();\n\n        HBaseCompoundKey key = new HBaseCompoundKey(\"mevivs\", 1, timeLineId);\n\n        String deleteQuery = \"Delete From HBasePrimeUser u where u.tweetBody= :tweetBody\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.setParameter(\"tweetBody\", \"after merge\");\n        q.executeUpdate();\n\n        em.close();\n        em = emf.createEntityManager();\n        HBasePrimeUser result = em.find(HBasePrimeUser.class, key);\n        Assert.assertNull(result);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n\n    /**\n     * Assert prime user.\n     * \n     * @param result\n     *            the result\n     */\n    private void validatePrimeUser(Object result)\n    {\n        HBasePrimeUser user = (HBasePrimeUser) result;\n        Assert.assertNotNull(user);\n        Assert.assertEquals(\"my first tweet\", user.getTweetBody());\n        Assert.assertEquals(currentDate, user.getTweetDate());\n        Assert.assertEquals(currentDate.getTime(), user.getTweetDate().getTime());\n        Assert.assertNotNull(user.getKey());\n        Assert.assertEquals(\"mevivs\", user.getKey().getUserId());\n        Assert.assertEquals(1, user.getKey().getTweetId());\n        Assert.assertEquals(timeLineId, user.getKey().getTimeLineId());\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/compositetype/HBaseCompoundKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.compositetype;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * The Class HBaseCompoundKey.\n * \n * @author vivek.mishra\n */\n@Embeddable\npublic class HBaseCompoundKey\n{\n\n    /** The user id. */\n    @Column\n    private String userId;\n\n    /** The tweet id. */\n    @Column\n    private int tweetId;\n\n    /** The time line id. */\n    @Column\n    private UUID timeLineId;\n\n    /**\n     * Instantiates a new HBase compound key.\n     */\n    public HBaseCompoundKey()\n    {\n    }\n\n    /**\n     * Instantiates a new HBase compound key.\n     * \n     * @param userId\n     *            the user id\n     * @param tweetId\n     *            the tweet id\n     * @param timeLineId\n     *            the time line id\n     */\n    public HBaseCompoundKey(String userId, int tweetId, UUID timeLineId)\n    {\n        this.userId = userId;\n        this.tweetId = tweetId;\n        this.timeLineId = timeLineId;\n    }\n\n    /**\n     * Gets the user id.\n     * \n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * Gets the tweet id.\n     * \n     * @return the tweetId\n     */\n    public int getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * Gets the time line id.\n     * \n     * @return the timeLineId\n     */\n    public UUID getTimeLineId()\n    {\n        return timeLineId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/compositetype/HBasePrimeUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.compositetype;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * The Class HBasePrimeUser.\n * \n * @author vivek.mishra\n */\n\n@Entity\n@Table(name = \"PRIME_USER\", schema = \"HBaseNew@queryTest\")\npublic class HBasePrimeUser\n{\n\n    /** The key. */\n    @EmbeddedId\n    private HBaseCompoundKey key;\n\n    /** The tweet body. */\n    @Column\n    private String tweetBody;\n\n    /** The tweet date. */\n    @Column\n    private Date tweetDate;\n\n    /**\n     * Instantiates a new HBase prime user.\n     */\n    public HBasePrimeUser()\n    {\n    }\n\n    /**\n     * Instantiates a new HBase prime user.\n     * \n     * @param key\n     *            the key\n     */\n    public HBasePrimeUser(HBaseCompoundKey key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * Gets the key.\n     * \n     * @return the key\n     */\n    public HBaseCompoundKey getKey()\n    {\n        return key;\n    }\n\n    /**\n     * Gets the tweet body.\n     * \n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * Gets the tweet date.\n     * \n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * Sets the tweet body.\n     * \n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * Sets the tweet date.\n     * \n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/Base.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport com.impetus.kundera.datatypes.datagenerator.DataGenerator;\nimport com.impetus.kundera.datatypes.datagenerator.DataGeneratorFactory;\n\n/**\n * The Class Base.\n * \n * @author Devender Yadav\n */\npublic abstract class Base\n{\n\n    /** The data generator. */\n    DataGenerator<?> dataGenerator;\n\n    /** The factory. */\n    DataGeneratorFactory factory = new DataGeneratorFactory();\n\n    /**\n     * Gets the max value.\n     * \n     * @param clazz\n     *            the clazz\n     * @return the max value\n     */\n    protected Object getMaxValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.maxValue();\n    }\n\n    /**\n     * Gets the min value.\n     * \n     * @param clazz\n     *            the clazz\n     * @return the min value\n     */\n    protected Object getMinValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.minValue();\n    }\n\n    /**\n     * Gets the random value.\n     * \n     * @param clazz\n     *            the clazz\n     * @return the random value\n     */\n    protected Object getRandomValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.randomValue();\n    }\n\n    /**\n     * Gets the partial value.\n     * \n     * @param clazz\n     *            the clazz\n     * @return the partial value\n     */\n    protected Object getPartialValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.partialValue();\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseBigDecimalTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBigDecimal;\n\n/**\n * The Class StudentHBaseBigDecimalTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseBigDecimalTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of BigDecimal\n        StudentHBaseBigDecimal studentMax = new StudentHBaseBigDecimal();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((BigDecimal) getMaxValue(BigDecimal.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of BigDecimal\n        StudentHBaseBigDecimal studentMin = new StudentHBaseBigDecimal();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((BigDecimal) getMinValue(BigDecimal.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of BigDecimal\n        StudentHBaseBigDecimal student = new StudentHBaseBigDecimal();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((BigDecimal) getRandomValue(BigDecimal.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBigDecimal studentMax = em.find(StudentHBaseBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigDecimal studentMin = em.find(StudentHBaseBigDecimal.class, getMinValue(BigDecimal.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigDecimal student = em.find(StudentHBaseBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseBigDecimal student = em.find(StudentHBaseBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigDecimal newStudent = em.find(StudentHBaseBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAll();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            Assert.assertEquals(getMinValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBigDecimal studentMax = em.find(StudentHBaseBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseBigDecimal s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigDecimal newStudent = em.find(StudentHBaseBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseBigDecimal s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigDecimal newStudent = em.find(StudentHBaseBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigDecimal.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigDecimal s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigDecimal.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAll()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseBigDecimal s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseBigDecimal> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseBigIntegerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.math.BigInteger;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBigInteger;\n\n/**\n * The Class StudentHBaseBigIntegerTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseBigIntegerTest extends Base\n{\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of BigInteger\n        StudentHBaseBigInteger studentMax = new StudentHBaseBigInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((BigInteger) getMaxValue(BigInteger.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of BigInteger\n        StudentHBaseBigInteger studentMin = new StudentHBaseBigInteger();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((BigInteger) getMinValue(BigInteger.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of BigInteger\n        StudentHBaseBigInteger student = new StudentHBaseBigInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((BigInteger) getRandomValue(BigInteger.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBigInteger studentMax = em.find(StudentHBaseBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigInteger studentMin = em.find(StudentHBaseBigInteger.class, getMinValue(BigInteger.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigInteger student = em.find(StudentHBaseBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseBigInteger student = em.find(StudentHBaseBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigInteger newStudent = em.find(StudentHBaseBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBigInteger studentMax = em.find(StudentHBaseBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseBigInteger s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigInteger newStudent = em.find(StudentHBaseBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseBigInteger s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBigInteger newStudent = em.find(StudentHBaseBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBigInteger s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseBigInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseBigInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseBooleanPrimitiveTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBooleanPrimitive;\nimport com.impetus.kundera.query.QueryHandlerException;\n\n/**\n * The Class StudentHBaseBooleanPrimitiveTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseBooleanPrimitiveTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of boolean\n        StudentHBaseBooleanPrimitive studentMax = new StudentHBaseBooleanPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Boolean) getMaxValue(boolean.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of boolean\n        StudentHBaseBooleanPrimitive studentMin = new StudentHBaseBooleanPrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Boolean) getMinValue(boolean.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBooleanPrimitive studentMax = em.find(StudentHBaseBooleanPrimitive.class,\n                getMaxValue(boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanPrimitive studentMin = em.find(StudentHBaseBooleanPrimitive.class,\n                getMinValue(boolean.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseBooleanPrimitive student = em.find(StudentHBaseBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanPrimitive newStudent = em.find(StudentHBaseBooleanPrimitive.class,\n                getMaxValue(boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(boolean.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.name = 'John' or s.age > \"\n                + getPartialValue(short.class);\n        try\n        {\n            q = em.createQuery(query);\n            students = q.getResultList();\n            // Assert.fail(\"Should have gone to catch block\");\n            Assert.assertNotNull(students);\n            Assert.assertEquals(1, students.size());\n            count = 0;\n            for (StudentHBaseBooleanPrimitive student : students)\n            {\n                Assert.assertEquals(getMaxValue(boolean.class), student.getId());\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n            em.close();\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertNotNull(qhe.getMessage());\n        }\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(boolean.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBooleanPrimitive studentMax = em.find(StudentHBaseBooleanPrimitive.class,\n                getMinValue(boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getPartialValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseBooleanPrimitive s where s.id=true\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanPrimitive newStudent = em.find(StudentHBaseBooleanPrimitive.class,\n                getRandomValue(boolean.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseBooleanPrimitive s SET s.name='Vivek' where s.id=true\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanPrimitive newStudent = em.find(StudentHBaseBooleanPrimitive.class,\n                getMaxValue(boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(boolean.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.age = \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(boolean.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanPrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(boolean.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseBooleanPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseBooleanPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseBooleanWrapperTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBooleanWrapper;\nimport com.impetus.kundera.query.QueryHandlerException;\n\n/**\n * The Class StudentHBaseBooleanWrapperTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseBooleanWrapperTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Boolean\n        StudentHBaseBooleanWrapper studentMax = new StudentHBaseBooleanWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Boolean) getMaxValue(Boolean.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Boolean\n        StudentHBaseBooleanWrapper studentMin = new StudentHBaseBooleanWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Boolean) getMinValue(Boolean.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBooleanWrapper studentMax = em.find(StudentHBaseBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanWrapper studentMin = em.find(StudentHBaseBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseBooleanWrapper student = em.find(StudentHBaseBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanWrapper newStudent = em.find(StudentHBaseBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(Boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.name = 'Chhavi' or s.age > \"\n                + getPartialValue(short.class);\n        try\n        {\n            q = em.createQuery(query);\n            students = q.getResultList();\n            // Assert.fail(\"Should have gone to catch block\");\n            Assert.assertNotNull(students);\n            Assert.assertEquals(1, students.size());\n            count = 0;\n            for (StudentHBaseBooleanWrapper student : students)\n            {\n                Assert.assertEquals(getMaxValue(Boolean.class), student.getId());\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n            em.close();\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertNotNull(qhe.getMessage());\n        }\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.name = 'Kuldeep'and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(Boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(Boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBooleanWrapper studentMax = em.find(StudentHBaseBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getPartialValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(Boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseBooleanWrapper s where s.id=true\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanWrapper newStudent = em.find(StudentHBaseBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseBooleanWrapper s SET s.name='Vivek' where s.id=true\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBooleanWrapper newStudent = em.find(StudentHBaseBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.age = \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBooleanWrapper s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseBooleanWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseBooleanWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentHBaseBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Boolean.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseBytePrimitiveTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBytePrimitive;\n\n/**\n * The Class StudentHBaseBytePrimitiveTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseBytePrimitiveTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of byte\n        StudentHBaseBytePrimitive studentMax = new StudentHBaseBytePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of byte\n        StudentHBaseBytePrimitive studentMin = new StudentHBaseBytePrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Byte) getMinValue(byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of byte\n        StudentHBaseBytePrimitive student = new StudentHBaseBytePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBytePrimitive studentMax = em.find(StudentHBaseBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBytePrimitive studentMin = em.find(StudentHBaseBytePrimitive.class, getMinValue(byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBytePrimitive student = em.find(StudentHBaseBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseBytePrimitive student = em.find(StudentHBaseBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBytePrimitive newStudent = em.find(StudentHBaseBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(byte.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseBytePrimitive studentMax = em.find(StudentHBaseBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseBytePrimitive s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBytePrimitive newStudent = em.find(StudentHBaseBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseBytePrimitive s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseBytePrimitive newStudent = em.find(StudentHBaseBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseBytePrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseBytePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseBytePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Byte) getMinValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseByteWrapperTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseByteWrapper;\n\n/**\n * The Class StudentHBaseByteWrapperTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseByteWrapperTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Byte\n        StudentHBaseByteWrapper studentMax = new StudentHBaseByteWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(Byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Byte\n        StudentHBaseByteWrapper studentMin = new StudentHBaseByteWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Byte) getMinValue(Byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Byte\n        StudentHBaseByteWrapper student = new StudentHBaseByteWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(Byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseByteWrapper studentMax = em.find(StudentHBaseByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseByteWrapper studentMin = em.find(StudentHBaseByteWrapper.class, getMinValue(Byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseByteWrapper student = em.find(StudentHBaseByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseByteWrapper student = em.find(StudentHBaseByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseByteWrapper newStudent = em.find(StudentHBaseByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Byte.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseByteWrapper studentMax = em.find(StudentHBaseByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseByteWrapper s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseByteWrapper newStudent = em.find(StudentHBaseByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseByteWrapper s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseByteWrapper newStudent = em.find(StudentHBaseByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseByteWrapper s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseByteWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseByteWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Byte.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseCalendarTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.Calendar;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseCalendar;\nimport com.impetus.kundera.query.QueryHandlerException;\n\n/**\n * The Class StudentHBaseCalendarTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseCalendarTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Calendar\n        StudentHBaseCalendar studentMax = new StudentHBaseCalendar();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId(((Calendar) getMaxValue(Calendar.class)));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseCalendar studentMax = em.find(StudentHBaseCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseCalendar student = em.find(StudentHBaseCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCalendar newStudent = em.find(StudentHBaseCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.age = \" + getMaxValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCalendar student : students)\n        {\n            Assert.assertEquals(getMaxValue(Calendar.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em = null;\n        String query;\n        Query q;\n        try\n        {\n            List<StudentHBaseCalendar> students;\n            int count;\n            em = emf.createEntityManager();\n            query = \"Select s From StudentHBaseCalendar s where s.name = 'Kuldeep' and s.age > \"\n                    + getPartialValue(short.class);\n            q = em.createQuery(query);\n            students = q.getResultList();\n            Assert.assertNotNull(students);\n            Assert.assertEquals(1, students.size());\n            count = 0;\n            for (StudentHBaseCalendar student : students)\n            {\n                Assert.assertEquals(getMaxValue(Calendar.class), student.getId());\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertEquals(\"unsupported clause OR for Hbase\", qhe.getMessage());\n        }\n        finally\n        {\n            if (em != null)\n            {\n                em.close();\n            }\n        }\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCalendar student : students)\n        {\n            Assert.assertEquals(getMaxValue(Calendar.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Calendar\n        StudentHBaseCalendar studentMax = new StudentHBaseCalendar();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId(((Calendar) getMaxValue(Calendar.class)));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        em.close();\n\n        em = emf.createEntityManager();\n\n        studentMax = em.find(StudentHBaseCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseCalendar s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCalendar newStudent = em.find(StudentHBaseCalendar.class, getRandomValue(Calendar.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseCalendar s SET s.name='Vivek' where s.name='Kuldeep'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCalendar newStudent = em.find(StudentHBaseCalendar.class, getRandomValue(Calendar.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCalendar student : students)\n        {\n            if (student.getId().equals(getMaxValue(Calendar.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.age = \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCalendar student : students)\n        {\n            Assert.assertEquals(getMaxValue(Calendar.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCalendar s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCalendar student : students)\n        {\n            if (student.getId().equals(getMaxValue(Calendar.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseCalendar s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseCalendar> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        int count = 0;\n        for (StudentHBaseCalendar student : students)\n        {\n            if (student.getId().equals(getMaxValue(Calendar.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseCharTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseChar;\n\n/**\n * The Class StudentHBaseCharTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseCharTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of char\n        StudentHBaseChar studentMax = new StudentHBaseChar();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Character) getMaxValue(char.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of char\n        StudentHBaseChar studentMin = new StudentHBaseChar();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Character) getMinValue(char.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of char\n        StudentHBaseChar student = new StudentHBaseChar();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(char.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseChar studentMax = em.find(StudentHBaseChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseChar studentMin = em.find(StudentHBaseChar.class, getMinValue(char.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseChar student = em.find(StudentHBaseChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseChar student = em.find(StudentHBaseChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseChar newStudent = em.find(StudentHBaseChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            Assert.assertEquals(getMinValue(char.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.name = 'Kuldeep' and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.name = 'Kuldeep' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseChar studentMax = em.find(StudentHBaseChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseChar.class, getMaxValue(char.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseChar s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseChar newStudent = em.find(StudentHBaseChar.class, getRandomValue(char.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseChar s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseChar newStudent = em.find(StudentHBaseChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.name = 'Amresh' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseChar s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseChar s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseChar> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Character) getMinValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(char.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseCharacterTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseCharacter;\n\n/**\n * The Class StudentHBaseCharacterTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseCharacterTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Character\n        StudentHBaseCharacter studentMax = new StudentHBaseCharacter();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Character) getMaxValue(Character.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Character\n        StudentHBaseCharacter studentMin = new StudentHBaseCharacter();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Character) getMinValue(Character.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Character\n        StudentHBaseCharacter student = new StudentHBaseCharacter();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(Character.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseCharacter studentMax = em.find(StudentHBaseCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCharacter studentMin = em.find(StudentHBaseCharacter.class, getMinValue(Character.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCharacter student = em.find(StudentHBaseCharacter.class, getRandomValue(Character.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseCharacter student = em.find(StudentHBaseCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCharacter newStudent = em.find(StudentHBaseCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            Assert.assertEquals(getMinValue(Character.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            Assert.assertEquals(getMaxValue(Character.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            Assert.assertEquals(getMaxValue(Character.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseCharacter studentMax = em.find(StudentHBaseCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseCharacter.class, getMaxValue(Character.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseCharacter s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCharacter newStudent = em.find(StudentHBaseCharacter.class, getRandomValue(Character.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseCharacter s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseCharacter newStudent = em.find(StudentHBaseCharacter.class, getRandomValue(Character.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseCharacter s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseCharacter s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseCharacter> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Character.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseDateTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseDate;\n\n/**\n * The Class StudentHBaseDateTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseDateTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentHBaseDate student = new StudentHBaseDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue(Date.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Date\n        StudentHBaseDate studentMax = new StudentHBaseDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue(Date.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Date\n        StudentHBaseDate studentMin = new StudentHBaseDate();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Date) getMinValue(Date.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseDate studentMax = em.find(StudentHBaseDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDate studentMin = em.find(StudentHBaseDate.class, getMinValue(Date.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDate student = em.find(StudentHBaseDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseDate student = em.find(StudentHBaseDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDate newStudent = em.find(StudentHBaseDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            Assert.assertEquals(getMinValue(Date.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.name = 'Kuldeep' and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.name = 'Kuldeep' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseDate studentMax = em.find(StudentHBaseDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseDate.class, getMaxValue(Date.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseDate s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDate newStudent = em.find(StudentHBaseDate.class, getRandomValue(Date.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseDate s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDate newStudent = em.find(StudentHBaseDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.name = 'Amresh' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDate s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseDate s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue(Date.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseDoublePrimitiveTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseDoublePrimitive;\n\n/**\n * The Class StudentHBaseDoublePrimitiveTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseDoublePrimitiveTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Double\n        StudentHBaseDoublePrimitive studentMax = new StudentHBaseDoublePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) getMaxValue(Double.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Double\n        StudentHBaseDoublePrimitive studentMin = new StudentHBaseDoublePrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Double) getMinValue(Double.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Double\n        StudentHBaseDoublePrimitive student = new StudentHBaseDoublePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseDoublePrimitive studentMax = em.find(StudentHBaseDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoublePrimitive studentMin = em.find(StudentHBaseDoublePrimitive.class, getMinValue(Double.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoublePrimitive student = em.find(StudentHBaseDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseDoublePrimitive student = em.find(StudentHBaseDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoublePrimitive newStudent = em.find(StudentHBaseDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(Double.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseDoublePrimitive studentMax = em.find(StudentHBaseDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseDoublePrimitive s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoublePrimitive newStudent = em.find(StudentHBaseDoublePrimitive.class,\n                getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseDoublePrimitive s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoublePrimitive newStudent = em.find(StudentHBaseDoublePrimitive.class,\n                getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoublePrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseDoublePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseDoublePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Double) getMinValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseDoubleWrapperTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseDoubleWrapper;\n\n/**\n * The Class StudentHBaseDoubleWrapperTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseDoubleWrapperTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Double\n        StudentHBaseDoubleWrapper studentMax = new StudentHBaseDoubleWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) getMaxValue(Double.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Double\n        StudentHBaseDoubleWrapper studentMin = new StudentHBaseDoubleWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Double) getMinValue(Double.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Double\n        StudentHBaseDoubleWrapper student = new StudentHBaseDoubleWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseDoubleWrapper studentMax = em.find(StudentHBaseDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoubleWrapper studentMin = em.find(StudentHBaseDoubleWrapper.class, getMinValue(Double.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoubleWrapper student = em.find(StudentHBaseDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseDoubleWrapper student = em.find(StudentHBaseDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoubleWrapper newStudent = em.find(StudentHBaseDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Double.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseDoubleWrapper studentMax = em.find(StudentHBaseDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseDoubleWrapper s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoubleWrapper newStudent = em.find(StudentHBaseDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseDoubleWrapper s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseDoubleWrapper newStudent = em.find(StudentHBaseDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseDoubleWrapper s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseDoubleWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseDoubleWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Double.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseFloatPrimitiveTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseFloatPrimitive;\n\n/**\n * The Class StudentHBaseFloatPrimitiveTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseFloatPrimitiveTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of float\n        StudentHBaseFloatPrimitive studentMax = new StudentHBaseFloatPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Float) getMaxValue(float.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of float\n        StudentHBaseFloatPrimitive studentMin = new StudentHBaseFloatPrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Float) getMinValue(float.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of float\n        StudentHBaseFloatPrimitive student = new StudentHBaseFloatPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Float) getRandomValue(float.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseFloatPrimitive studentMax = em.find(StudentHBaseFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatPrimitive studentMin = em.find(StudentHBaseFloatPrimitive.class, getMinValue(float.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatPrimitive student = em.find(StudentHBaseFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseFloatPrimitive student = em.find(StudentHBaseFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatPrimitive newStudent = em.find(StudentHBaseFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(float.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseFloatPrimitive studentMax = em.find(StudentHBaseFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseFloatPrimitive s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatPrimitive newStudent = em.find(StudentHBaseFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseFloatPrimitive s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatPrimitive newStudent = em.find(StudentHBaseFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(float.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatPrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(float.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseFloatPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseFloatPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Float) getMinValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseFloatWrapperTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseFloatWrapper;\n\n/**\n * The Class StudentHBaseFloatWrapperTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseFloatWrapperTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Float\n        StudentHBaseFloatWrapper studentMax = new StudentHBaseFloatWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Float) getMaxValue(Float.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Float\n        StudentHBaseFloatWrapper studentMin = new StudentHBaseFloatWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Float) getMinValue(Float.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Float\n        StudentHBaseFloatWrapper student = new StudentHBaseFloatWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Float) getRandomValue(Float.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseFloatWrapper studentMax = em.find(StudentHBaseFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatWrapper studentMin = em.find(StudentHBaseFloatWrapper.class, getMinValue(Float.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatWrapper student = em.find(StudentHBaseFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseFloatWrapper student = em.find(StudentHBaseFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatWrapper newStudent = em.find(StudentHBaseFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Float.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseFloatWrapper studentMax = em.find(StudentHBaseFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseFloatWrapper s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatWrapper newStudent = em.find(StudentHBaseFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseFloatWrapper s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseFloatWrapper newStudent = em.find(StudentHBaseFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Float.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseFloatWrapper s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Float.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseFloatWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseFloatWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Float.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseIntTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseInt;\n\n/**\n * The Class StudentHBaseIntTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseIntTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of int\n        StudentHBaseInt studentMax = new StudentHBaseInt();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(int.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert random value of int\n        StudentHBaseInt student = new StudentHBaseInt();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(int.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert min value of int\n        StudentHBaseInt studentMin = new StudentHBaseInt();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Integer) getMinValue(int.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseInt studentMax = em.find(StudentHBaseInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInt studentMin = em.find(StudentHBaseInt.class, getMinValue(int.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInt student = em.find(StudentHBaseInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseInt student = em.find(StudentHBaseInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInt newStudent = em.find(StudentHBaseInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            Assert.assertEquals(getMinValue(int.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.name = 'Kuldeep' and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.name = 'Kuldeep' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseInt studentMax = em.find(StudentHBaseInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseInt.class, getMaxValue(int.class));\n        Assert.assertNull(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n\n        StudentHBaseInt studentMin = em.find(StudentHBaseInt.class, getMinValue(int.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMin.getName());\n        em.remove(studentMin);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMin = em.find(StudentHBaseInt.class, getMinValue(int.class));\n        Assert.assertNull(studentMin);\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseInt s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInt newStudent = em.find(StudentHBaseInt.class, getRandomValue(int.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseInt s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInt newStudent = em.find(StudentHBaseInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.name = 'Amresh' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        // query =\n        // \"Select s From StudentHBaseInt s where s.name = Amresh and s.age > ?1 and s.age < ?2\";\n        q = em.createQuery(query);\n        // q.setParameter(1, getPartialValue(short.class));\n        // q.setParameter(2, getMaxValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.name = 'Kuldeep' and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInt s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseInt s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseInt> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Integer) getMinValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseIntegerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseInteger;\n\n/**\n * The Class StudentHBaseIntegerTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseIntegerTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of integer\n        StudentHBaseInteger studentMax = new StudentHBaseInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(Integer.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of integer\n        StudentHBaseInteger studentMin = new StudentHBaseInteger();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Integer) getMinValue(Integer.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of integer\n        StudentHBaseInteger student = new StudentHBaseInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(Integer.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseInteger studentMax = em.find(StudentHBaseInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInteger studentMin = em.find(StudentHBaseInteger.class, getMinValue(Integer.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInteger student = em.find(StudentHBaseInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseInteger student = em.find(StudentHBaseInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInteger newStudent = em.find(StudentHBaseInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(Integer.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseInteger studentMax = em.find(StudentHBaseInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseInteger.class, getMaxValue(Integer.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseInteger s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInteger newStudent = em.find(StudentHBaseInteger.class, getRandomValue(Integer.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseInteger s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseInteger newStudent = em.find(StudentHBaseInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseInteger s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Integer.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseLongPrimitiveTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseLongPrimitive;\n\n/**\n * The Class StudentHBaseLongPrimitiveTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseLongPrimitiveTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of long\n        StudentHBaseLongPrimitive studentMax = new StudentHBaseLongPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of long\n        StudentHBaseLongPrimitive studentMin = new StudentHBaseLongPrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Long) getMinValue(long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of long\n        StudentHBaseLongPrimitive student = new StudentHBaseLongPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseLongPrimitive studentMax = em.find(StudentHBaseLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongPrimitive studentMin = em.find(StudentHBaseLongPrimitive.class, getMinValue(long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongPrimitive student = em.find(StudentHBaseLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseLongPrimitive student = em.find(StudentHBaseLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongPrimitive newStudent = em.find(StudentHBaseLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(long.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseLongPrimitive studentMax = em.find(StudentHBaseLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseLongPrimitive s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongPrimitive newStudent = em.find(StudentHBaseLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseLongPrimitive s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongPrimitive newStudent = em.find(StudentHBaseLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongPrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseLongPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseLongPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Long) getMinValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseLongWrapperTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseLongWrapper;\n\n/**\n * The Class StudentHBaseLongWrapperTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseLongWrapperTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Long\n        StudentHBaseLongWrapper studentMax = new StudentHBaseLongWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(Long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Long\n        StudentHBaseLongWrapper studentMin = new StudentHBaseLongWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Long) getMinValue(Long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Long\n        StudentHBaseLongWrapper student = new StudentHBaseLongWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(Long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseLongWrapper studentMax = em.find(StudentHBaseLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongWrapper studentMin = em.find(StudentHBaseLongWrapper.class, getMinValue(Long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongWrapper student = em.find(StudentHBaseLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseLongWrapper student = em.find(StudentHBaseLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongWrapper newStudent = em.find(StudentHBaseLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Long.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseLongWrapper studentMax = em.find(StudentHBaseLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseLongWrapper s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongWrapper newStudent = em.find(StudentHBaseLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseLongWrapper s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseLongWrapper newStudent = em.find(StudentHBaseLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseLongWrapper s where s.name ='Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseLongWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseLongWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Long.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseShortPrimitiveTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseShortPrimitive;\n\n/**\n * The Class StudentHBaseShortPrimitiveTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseShortPrimitiveTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentHBaseShortPrimitive studentMax = new StudentHBaseShortPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentHBaseShortPrimitive studentMin = new StudentHBaseShortPrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Short) getPartialValue(short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentHBaseShortPrimitive student = new StudentHBaseShortPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseShortPrimitive studentMax = em.find(StudentHBaseShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortPrimitive studentMin = em.find(StudentHBaseShortPrimitive.class, getPartialValue(short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortPrimitive student = em.find(StudentHBaseShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseShortPrimitive student = em.find(StudentHBaseShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortPrimitive newStudent = em.find(StudentHBaseShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            Assert.assertEquals(getPartialValue(short.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseShortPrimitive studentMax = em.find(StudentHBaseShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseShortPrimitive s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortPrimitive newStudent = em.find(StudentHBaseShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseShortPrimitive s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortPrimitive newStudent = em.find(StudentHBaseShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortPrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseShortPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseShortPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Short) getPartialValue(short.class)).shortValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseShortWrapperTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseShortWrapper;\n\n/**\n * The Class StudentHBaseShortWrapperTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseShortWrapperTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentHBaseShortWrapper studentMax = new StudentHBaseShortWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentHBaseShortWrapper studentMin = new StudentHBaseShortWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Short) getPartialValue(short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentHBaseShortWrapper student = new StudentHBaseShortWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseShortWrapper studentMax = em.find(StudentHBaseShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortWrapper studentMin = em.find(StudentHBaseShortWrapper.class, getPartialValue(short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortWrapper student = em.find(StudentHBaseShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseShortWrapper student = em.find(StudentHBaseShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortWrapper newStudent = em.find(StudentHBaseShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            Assert.assertEquals(getPartialValue(short.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseShortWrapper studentMax = em.find(StudentHBaseShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseShortWrapper s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortWrapper newStudent = em.find(StudentHBaseShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseShortWrapper s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseShortWrapper newStudent = em.find(StudentHBaseShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseShortWrapper s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseShortWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseShortWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getPartialValue(short.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseSqlDateTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.sql.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseSqlDate;\n\n/**\n * The Class StudentHBaseSqlDateTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseSqlDateTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentHBaseSqlDate student = new StudentHBaseSqlDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue(Date.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Date\n        StudentHBaseSqlDate studentMax = new StudentHBaseSqlDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue(Date.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Date\n        StudentHBaseSqlDate studentMin = new StudentHBaseSqlDate();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Date) getMinValue(Date.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseSqlDate studentMax = em.find(StudentHBaseSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseSqlDate studentMin = em.find(StudentHBaseSqlDate.class, getMinValue(Date.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseSqlDate student = em.find(StudentHBaseSqlDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseSqlDate student = em.find(StudentHBaseSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseSqlDate newStudent = em.find(StudentHBaseSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            Assert.assertEquals(getMinValue(Date.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseSqlDate studentMax = em.find(StudentHBaseSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseSqlDate s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseSqlDate newStudent = em.find(StudentHBaseSqlDate.class, getRandomValue(Date.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseSqlDate s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseSqlDate newStudent = em.find(StudentHBaseSqlDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseSqlDate s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseSqlDate s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseSqlDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue(Date.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseStringTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseString;\n\n/**\n * The Class StudentHBaseStringTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseStringTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of String\n        StudentHBaseString studentMax = new StudentHBaseString();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((String) getMaxValue(String.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of String\n        StudentHBaseString studentMin = new StudentHBaseString();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((String) getMinValue(String.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of String\n        StudentHBaseString student = new StudentHBaseString();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((String) getRandomValue(String.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseString studentMax = em.find(StudentHBaseString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseString studentMin = em.find(StudentHBaseString.class, getMinValue(String.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseString student = em.find(StudentHBaseString.class, getRandomValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseString student = em.find(StudentHBaseString.class, getMaxValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseString newStudent = em.find(StudentHBaseString.class, getMaxValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            Assert.assertEquals(getMinValue(String.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseString studentMax = em.find(StudentHBaseString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseString.class, getMaxValue(String.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseString s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseString newStudent = em.find(StudentHBaseString.class, getRandomValue(String.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseString s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseString newStudent = em.find(StudentHBaseString.class, getRandomValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.age > \" + getPartialValue(short.class) + \" and s.age < \"\n                + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseString s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseString s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseString> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(String.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(String.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseTimeTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.sql.Time;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseTime;\n\n/**\n * The Class StudentHBaseTimeTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseTimeTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Time\n        StudentHBaseTime student = new StudentHBaseTime();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Time) getRandomValue(Time.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Time\n        StudentHBaseTime studentMax = new StudentHBaseTime();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Time) getMaxValue(Time.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Time\n        StudentHBaseTime studentMin = new StudentHBaseTime();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Time) getMinValue(Time.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseTime studentMax = em.find(StudentHBaseTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTime studentMin = em.find(StudentHBaseTime.class, getMinValue(Time.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTime student = em.find(StudentHBaseTime.class, getRandomValue(Time.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseTime student = em.find(StudentHBaseTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTime newStudent = em.find(StudentHBaseTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            Assert.assertEquals(getMinValue(Time.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.name = 'Kuldeep' and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            Assert.assertEquals(getMaxValue(Time.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.name = 'Kuldeep' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            Assert.assertEquals(getMaxValue(Time.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseTime studentMax = em.find(StudentHBaseTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseTime.class, getMaxValue(Time.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseTime s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTime newStudent = em.find(StudentHBaseTime.class, getRandomValue(Time.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String upTimeQuery = \"Update StudentHBaseTime s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(upTimeQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTime newStudent = em.find(StudentHBaseTime.class, getRandomValue(Time.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.name = 'Amresh' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Time.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTime s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Time.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseTime s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseTime> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Time.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Time) getRandomValue(Time.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseTimestampTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.sql.Timestamp;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseTimestamp;\n\n/**\n * The Class StudentHBaseTimestampTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseTimestampTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Time\n        StudentHBaseTimestamp student = new StudentHBaseTimestamp();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Timestamp) getRandomValue(Timestamp.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Time\n        StudentHBaseTimestamp studentMax = new StudentHBaseTimestamp();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Timestamp) getMaxValue(Timestamp.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Timestamp\n        StudentHBaseTimestamp studentMin = new StudentHBaseTimestamp();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Timestamp) getMinValue(Timestamp.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseTimestamp studentMax = em.find(StudentHBaseTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTimestamp studentMin = em.find(StudentHBaseTimestamp.class, getMinValue(Timestamp.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTimestamp student = em.find(StudentHBaseTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseTimestamp student = em.find(StudentHBaseTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTimestamp newStudent = em.find(StudentHBaseTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            Assert.assertEquals(getMaxValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            Assert.assertEquals(getMaxValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseTimestamp studentMax = em.find(StudentHBaseTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseTimestamp s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTimestamp newStudent = em.find(StudentHBaseTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String upTimeQuery = \"Update StudentHBaseTimestamp s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(upTimeQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseTimestamp newStudent = em.find(StudentHBaseTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseTimestamp s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseTimestamp s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseTimestamp> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Timestamp) getRandomValue(Timestamp.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/StudentHBaseUUIDTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes;\n\nimport java.util.List;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseUUID;\n\n/**\n * The Class StudentHBaseUUIDTest.\n * \n * @author Devender Yadav\n */\npublic class StudentHBaseUUIDTest extends Base\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of UUID\n        StudentHBaseUUID studentMax = new StudentHBaseUUID();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((UUID) getMaxValue(UUID.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of UUID\n        StudentHBaseUUID studentMin = new StudentHBaseUUID();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((UUID) getMinValue(UUID.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of UUID\n        StudentHBaseUUID student = new StudentHBaseUUID();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((UUID) getRandomValue(UUID.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseUUID studentMax = em.find(StudentHBaseUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseUUID studentMin = em.find(StudentHBaseUUID.class, getMinValue(UUID.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseUUID student = em.find(StudentHBaseUUID.class, getRandomValue(UUID.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentHBaseUUID student = em.find(StudentHBaseUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseUUID newStudent = em.find(StudentHBaseUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            Assert.assertEquals(getMinValue(UUID.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age with or clause.\n     */\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.name = 'Kuldeep' and s.age > \" + getPartialValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            Assert.assertEquals(getMaxValue(UUID.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.name = 'Kuldeep' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            Assert.assertEquals(getMaxValue(UUID.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test named query use same em.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    /**\n     * Test named query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentHBaseUUID studentMax = em.find(StudentHBaseUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentHBaseUUID.class, getMaxValue(UUID.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Delete named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentHBaseUUID s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseUUID newStudent = em.find(StudentHBaseUUID.class, getRandomValue(UUID.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * Update named.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentHBaseUUID s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentHBaseUUID newStudent = em.find(StudentHBaseUUID.class, getRandomValue(UUID.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.name = 'Amresh' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(UUID.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentHBaseUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentHBaseUUID s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(UUID.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentHBaseUUID s \";\n        Query q = em.createQuery(query);\n        List<StudentHBaseUUID> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentHBaseUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(UUID.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseBigDecimal.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.math.BigDecimal;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseBigDecimal.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_BIGDECIMAL\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseBigDecimal\n{\n\n    /** The id. */\n    @Id\n    private BigDecimal id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public BigDecimal getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(BigDecimal id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseBigInteger.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.math.BigInteger;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseBigInteger.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_BIGINTEGER\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseBigInteger\n{\n\n    /** The id. */\n    @Id\n    private BigInteger id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public BigInteger getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(BigInteger id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseBooleanPrimitive.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseBooleanPrimitive.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_BOOLEAN_PRIMITIVE\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseBooleanPrimitive\n{\n\n    /** The id. */\n    @Id\n    private boolean id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public boolean getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(boolean id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseBooleanWrapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseBooleanWrapper.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_BOOLEAN_WRAPPER\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseBooleanWrapper\n{\n\n    /** The id. */\n    @Id\n    private Boolean id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Boolean getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Boolean id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseBytePrimitive.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseBytePrimitive.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_BYTE_PRIMITIVE\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseBytePrimitive\n{\n\n    /** The id. */\n    @Id\n    private byte id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseByteWrapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseByteWrapper.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_BYTE_WRAPPER\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseByteWrapper\n{\n\n    /** The id. */\n    @Id\n    private Byte id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseCalendar.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.util.Calendar;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseCalendar.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_CALENDAR\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseCalendar\n{\n\n    /** The id. */\n    @Id\n    private Calendar id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Calendar getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Calendar id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseChar.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseChar.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_CHAR\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseChar\n{\n\n    /** The id. */\n    @Id\n    private char id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public char getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(char id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseCharacter.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseCharacter.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_CHARACTER\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseCharacter\n{\n\n    /** The id. */\n    @Id\n    private Character id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Character getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Character id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseDate.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseDate.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_DATE\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseDate\n{\n\n    /** The id. */\n    @Id\n    private Date id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseDoublePrimitive.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseDoublePrimitive.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_DOUBLE_PRIMITIVE\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseDoublePrimitive\n{\n\n    /** The id. */\n    @Id\n    private double id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public double getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseDoubleWrapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseDoubleWrapper.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_DOUBLE_WRAPPER\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseDoubleWrapper\n{\n\n    /** The id. */\n    @Id\n    private Double id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Double getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseFloatPrimitive.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseFloatPrimitive.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_FLOAT_PRIMITIVE\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseFloatPrimitive\n{\n\n    /** The id. */\n    @Id\n    private float id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public float getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseFloatWrapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseFloatWrapper.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_FLOAT_WRAPPER\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseFloatWrapper\n{\n\n    /** The id. */\n    @Id\n    private Float id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Float getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseInt.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseInt.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_INT\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseInt\n{\n\n    /** The id. */\n    @Id\n    private int id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseInteger.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseInteger.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_INTEGER\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseInteger\n{\n\n    /** The id. */\n    @Id\n    private Integer id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Integer getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Integer id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseLongPrimitive.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseLongPrimitive.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_LONG_PRIMITIVE\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseLongPrimitive\n{\n\n    /** The id. */\n    @Id\n    private long id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public long getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseLongWrapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseLongWrapper.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_LONG_WRAPPER\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseLongWrapper\n{\n\n    /** The id. */\n    @Id\n    private Long id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Long getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseShortPrimitive.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseShortPrimitive.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_SHORT_PRIMITIVE\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseShortPrimitive\n{\n\n    /** The id. */\n    @Id\n    private short id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public short getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseShortWrapper.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseShortWrapper.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_SHORT_WRAPPER\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseShortWrapper\n{\n\n    /** The id. */\n    @Id\n    private Short id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Short getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseSqlDate.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.sql.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseSqlDate.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_SQL_DATE\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseSqlDate\n{\n\n    /** The id. */\n    @Id\n    private Date id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseString.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseString.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_STRING\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseString\n{\n\n    /** The id. */\n    @Id\n    private String id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseTime.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.sql.Time;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseTime.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_TIME\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseTime\n{\n\n    /** The id. */\n    @Id\n    private Time id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Time getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Time id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseTimestamp.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.sql.Timestamp;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseTimestamp.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_TIMESTAMP\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseTimestamp\n{\n\n    /** The id. */\n    @Id\n    private Timestamp id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Timestamp getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Timestamp id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/datatypes/entities/StudentHBaseUUID.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.datatypes.entities;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentHBaseUUID.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_HBASE_UUID\", schema = \"HBaseNew@dataTypeTest\")\npublic class StudentHBaseUUID\n{\n\n    /** The id. */\n    @Id\n    private UUID id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public UUID getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(UUID id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/embedded/Address.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.embedded;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * The Class Address.\n * \n * @author Pragalbh Garg\n */\n@Embeddable\npublic class Address\n{\n\n    /** The street. */\n    @Column(name = \"street\")\n    private String street;\n\n    /** The city. */\n    @Column(name = \"city\")\n    private String city;\n\n    /** The pin. */\n    @Column(name = \"pin\")\n    private String pin;\n\n    /**\n     * Instantiates a new address.\n     */\n    public Address()\n    {\n\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    /**\n     * Gets the city.\n     * \n     * @return the city\n     */\n    public String getCity()\n    {\n        return city;\n    }\n\n    /**\n     * Sets the city.\n     * \n     * @param city\n     *            the new city\n     */\n    public void setCity(String city)\n    {\n        this.city = city;\n    }\n\n    /**\n     * Gets the pin.\n     * \n     * @return the pin\n     */\n    public String getPin()\n    {\n        return pin;\n    }\n\n    /**\n     * Sets the pin.\n     * \n     * @param pin\n     *            the new pin\n     */\n    public void setPin(String pin)\n    {\n        this.pin = pin;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/embedded/EmbeddablesBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.embedded;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\n\nimport junit.framework.Assert;\n\n/**\n * The Class EmbeddablesBase.\n * \n * @author Pragalbh Garg\n */\npublic class EmbeddablesBase\n{\n    /** The Constant SCHEMA. */\n    protected static final String SCHEMA = \"HBaseNew\";\n\n    /** The Constant HBASE_PU. */\n    protected static final String HBASE_PU = \"embeddablesTest\";\n\n    /** The emf. */\n    protected static EntityManagerFactory emf;\n\n    /** The em. */\n    protected EntityManager em;\n\n    /** The Constant T. */\n    protected static final boolean T = true;\n\n    /** The Constant F. */\n    protected static final boolean F = false;\n\n    /** The p4. */\n    protected PersonEmbed p1, p2, p3, p4;\n\n    /**\n     * Inits the.\n     */\n    protected void init()\n    {\n        this.p1 = getPerson_1();\n        this.p2 = getPerson_2();\n        this.p3 = getPerson_3();\n        this.p4 = getPerson_4();\n    }\n\n    /**\n     * Prepare person.\n     * \n     * @param id\n     *            the id\n     * @param email\n     *            the email\n     * @param details1\n     *            the details1\n     * @param details2\n     *            the details2\n     * @return the person embed\n     */\n    protected PersonEmbed preparePerson(int id, String email, PersonalDetails details1, ProfessionalDetails details2)\n    {\n        PersonEmbed p = new PersonEmbed();\n        p.setPersonId(id);\n        p.setEmail(email);\n        p.setPersonalDetails(details1);\n        p.setProfessionalDetails(details2);\n        return p;\n    }\n\n    /**\n     * Prepare personal details.\n     * \n     * @param fname\n     *            the fname\n     * @param mname\n     *            the mname\n     * @param lname\n     *            the lname\n     * @param address\n     *            the address\n     * @return the personal details\n     */\n    protected PersonalDetails preparePersonalDetails(String fname, String mname, String lname, List address)\n    {\n        PersonalDetails p = new PersonalDetails();\n        Fullname f = new Fullname();\n        f.setFirstName(fname);\n        f.setMiddleName(mname);\n        f.setLastName(lname);\n        p.setFullname(f);\n        p.setAddresses(address);\n        return p;\n    }\n\n    /**\n     * Prepare pro details.\n     * \n     * @param project\n     *            the project\n     * @param comp\n     *            the comp\n     * @param salary\n     *            the salary\n     * @return the professional details\n     */\n    protected ProfessionalDetails prepareProDetails(String project, String comp, Double salary)\n    {\n        ProfessionalDetails p = new ProfessionalDetails();\n        p.setCompany(comp);\n        p.setMonthlySalary(salary);\n        p.setProject(project);\n        return p;\n    }\n\n    /**\n     * Gets the person_1.\n     * \n     * @return the person_1\n     */\n    protected PersonEmbed getPerson_1()\n    {\n        ProfessionalDetails pro = prepareProDetails(\"kundera\", \"impetus\", (double) 40000);\n        Address add1 = new Address();\n        add1.setCity(\"indore\");\n        add1.setPin(\"452001\");\n        add1.setStreet(\"palasia\");\n\n        Address add2 = new Address();\n        add2.setCity(\"gwalior\");\n        add2.setPin(\"474011\");\n        add2.setStreet(\"thatipur\");\n\n        List<Address> address = new ArrayList<Address>();\n        address.add(add1);\n        address.add(add2);\n        PersonalDetails personal = preparePersonalDetails(\"pragalbh\", \"rocking\", \"garg\", address);\n\n        return preparePerson(1, \"pg@gmail.com\", personal, pro);\n    }\n\n    /**\n     * Gets the person_2.\n     * \n     * @return the person_2\n     */\n    protected PersonEmbed getPerson_2()\n    {\n        ProfessionalDetails pro = prepareProDetails(\"kundera\", \"impetus\", (double) 40000);\n        Address add1 = new Address();\n        add1.setCity(\"noida\");\n        add1.setPin(\"100100\");\n        add1.setStreet(\"k block\");\n\n        Address add2 = new Address();\n        add2.setCity(\"delhi\");\n        add2.setPin(\"100200\");\n        add2.setStreet(\"cp\");\n\n        List<Address> address = new ArrayList<Address>();\n        address.add(add1);\n        address.add(add2);\n        PersonalDetails personal = preparePersonalDetails(\"dev\", \"cool\", \"yadav\", address);\n\n        return preparePerson(2, \"dev@gmail.com\", personal, pro);\n    }\n\n    /**\n     * Gets the person_3.\n     * \n     * @return the person_3\n     */\n    protected PersonEmbed getPerson_3()\n    {\n        ProfessionalDetails pro = prepareProDetails(\"kundera\", \"impetus\", (double) 50000);\n        Address add1 = new Address();\n        add1.setCity(\"indore\");\n        add1.setPin(\"452001\");\n        add1.setStreet(\"bengali\");\n\n        Address add2 = new Address();\n        add2.setCity(\"hyderabad\");\n        add2.setPin(\"200020\");\n        add2.setStreet(\"some street\");\n\n        List<Address> address = new ArrayList<Address>();\n        address.add(add1);\n        address.add(add2);\n        PersonalDetails personal = preparePersonalDetails(\"karthik\", \"cherry\", \"manchala\", address);\n\n        return preparePerson(3, \"karthik@gmail.com\", personal, pro);\n    }\n\n    /**\n     * Gets the person_4.\n     * \n     * @return the person_4\n     */\n    protected PersonEmbed getPerson_4()\n    {\n        ProfessionalDetails pro = prepareProDetails(\"kundera\", \"impetus\", (double) 50000);\n        Address add1 = new Address();\n        add1.setCity(\"noida\");\n        add1.setPin(\"100100\");\n        add1.setStreet(\"k block\");\n\n        Address add2 = new Address();\n        add2.setCity(\"delhi\");\n        add2.setPin(\"100300\");\n        add2.setStreet(\"karol bag\");\n\n        List<Address> address = new ArrayList<Address>();\n        address.add(add1);\n        address.add(add2);\n        PersonalDetails personal = preparePersonalDetails(\"amit\", \"star\", \"kumar\", address);\n\n        return preparePerson(4, \"amit@gmail.com\", personal, pro);\n    }\n\n    /**\n     * Assert person.\n     * \n     * @param expected\n     *            the expected\n     * @param actual\n     *            the actual\n     */\n    protected void assertPerson(PersonEmbed expected, PersonEmbed actual)\n    {\n        Assert.assertNotNull(actual);\n        Assert.assertEquals(expected.getPersonId(), actual.getPersonId());\n        Assert.assertEquals(expected.getEmail(), actual.getEmail());\n        Assert.assertNotNull(actual.getPersonalDetails());\n        Assert.assertEquals(expected.getProfessionalDetails().getCompany(), actual.getProfessionalDetails()\n                .getCompany());\n        Assert.assertEquals(expected.getProfessionalDetails().getProject(), actual.getProfessionalDetails()\n                .getProject());\n        Assert.assertEquals(expected.getProfessionalDetails().getMonthlySalary(), actual.getProfessionalDetails()\n                .getMonthlySalary());\n        Fullname exp = expected.getPersonalDetails().getFullname();\n        Fullname act = actual.getPersonalDetails().getFullname();\n        Assert.assertNotNull(act);\n        Assert.assertEquals(exp.getFirstName(), act.getFirstName());\n        Assert.assertEquals(exp.getMiddleName(), act.getMiddleName());\n        Assert.assertEquals(exp.getLastName(), act.getLastName());\n        List<Address> expAdd = expected.getPersonalDetails().getAddresses();\n        List<Address> actAdd = actual.getPersonalDetails().getAddresses();\n        Assert.assertNotNull(actAdd);\n        Assert.assertEquals(expAdd.size(), actAdd.size());\n\n    }\n\n    /**\n     * Persist data.\n     */\n    protected void persistData()\n    {\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        em.persist(p4);\n        em.clear();\n    }\n\n    /**\n     * Assert results.\n     * \n     * @param results\n     *            the results\n     * @param b1\n     *            the b1\n     * @param b2\n     *            the b2\n     * @param b3\n     *            the b3\n     * @param b4\n     *            the b4\n     */\n    protected void assertResults(List results, Boolean b1, Boolean b2, Boolean b3, Boolean b4)\n    {\n        Assert.assertNotNull(results);\n        for (PersonEmbed p : (List<PersonEmbed>) results)\n        {\n            switch (p.getPersonId())\n            {\n            case 1:\n                if (b1)\n                    assertPerson(p1, p);\n                else\n                    Assert.assertTrue(false);\n                break;\n            case 2:\n                if (b2)\n                    assertPerson(p2, p);\n                else\n                    Assert.assertTrue(false);\n                break;\n            case 3:\n                if (b3)\n                    assertPerson(p3, p);\n                else\n                    Assert.assertTrue(false);\n                break;\n            case 4:\n                if (b4)\n                    assertPerson(p4, p);\n                else\n                    Assert.assertTrue(false);\n                break;\n            }\n\n        }\n    }\n\n    /**\n     * Assert deleted.\n     * \n     * @param b1\n     *            the b1\n     * @param b2\n     *            the b2\n     * @param b3\n     *            the b3\n     * @param b4\n     *            the b4\n     */\n    protected void assertDeleted(Boolean b1, Boolean b2, Boolean b3, Boolean b4)\n    {\n        em.clear();\n        PersonEmbed person1 = em.find(PersonEmbed.class, 1);\n        PersonEmbed person2 = em.find(PersonEmbed.class, 2);\n        PersonEmbed person3 = em.find(PersonEmbed.class, 3);\n        PersonEmbed person4 = em.find(PersonEmbed.class, 4);\n        if (b1)\n        {\n            Assert.assertNull(person1);\n        }\n        else\n        {\n            Assert.assertNotNull(person1);\n        }\n        if (b2)\n        {\n            Assert.assertNull(person2);\n        }\n        else\n        {\n            Assert.assertNotNull(person2);\n        }\n        if (b3)\n        {\n            Assert.assertNull(person3);\n        }\n        else\n        {\n            Assert.assertNotNull(person3);\n        }\n        if (b4)\n        {\n            Assert.assertNull(person4);\n        }\n        else\n        {\n            Assert.assertNotNull(person4);\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/embedded/EmbeddablesCrudTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n/*\n * author: karthikp.manchala\n */\npackage com.impetus.client.hbase.crud.embedded;\n\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class EmbeddablesCrudTest.\n * \n * @author Pragalbh Garg\n */\npublic class EmbeddablesCrudTest extends EmbeddablesBase\n{\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test crud operations.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testCRUDOperations() throws Exception\n    {\n        init();\n        testInsert();\n        testMerge();\n        testRemove();\n\n    }\n\n    /**\n     * Test remove.\n     */\n    private void testRemove()\n    {\n        PersonEmbed person1 = em.find(PersonEmbed.class, 1);\n        PersonEmbed person2 = em.find(PersonEmbed.class, 2);\n        em.remove(person1);\n        em.remove(person2);\n        em.clear();\n\n        person1 = em.find(PersonEmbed.class, 1);\n        person2 = em.find(PersonEmbed.class, 2);\n        Assert.assertNull(person1);\n        Assert.assertNull(person2);\n    }\n\n    /**\n     * Test merge.\n     */\n    private void testMerge()\n    {\n        PersonEmbed person1 = em.find(PersonEmbed.class, 1);\n        person1.setEmail(\"pg@impetus.com\");\n        person1.getProfessionalDetails().setCompany(\"impetus ilabs\");\n        em.merge(person1);\n        em.clear();\n        person1 = em.find(PersonEmbed.class, 1);\n        p1.setEmail(\"pg@impetus.com\");\n        p1.getProfessionalDetails().setCompany(\"impetus ilabs\");\n        assertPerson(p1, person1);\n    }\n\n    /**\n     * Test insert.\n     */\n    private void testInsert()\n    {\n        em.persist(p1);\n        em.persist(p2);\n        em.clear();\n        PersonEmbed person1 = em.find(PersonEmbed.class, 1);\n        PersonEmbed person2 = em.find(PersonEmbed.class, 2);\n        assertPerson(p1, person1);\n        assertPerson(p2, person2);\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     */\n    @AfterClass\n    public static void tearDownAfterClass()\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/embedded/EmbeddablesQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.hbase.crud.embedded;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class EmbeddablesQueryTest.\n * \n * @author Pragalbh Garg\n */\npublic class EmbeddablesQueryTest extends EmbeddablesBase\n{\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n        init();\n\n    }\n\n    /**\n     * Test select queries.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testSelectQueries() throws Exception\n    {\n        persistData();\n        testSelectSimple();\n        testSelectWithWhere();\n        testSelectWithWhereIn();\n\n    }\n\n    /**\n     * Test delete queries.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testDeleteQueries() throws Exception\n    {\n        testDeleteSimple();\n        testDeleteWithWhere();\n        testDeleteWithWhereIn();\n\n    }\n\n    // update is not working on embeddables. issue in core.\n    // @Test\n    /**\n     * Test update queries.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    public void testUpdateQueries() throws Exception\n    {\n        testUpdateQuery();\n\n    }\n\n    /**\n     * Test select simple.\n     */\n    private void testSelectSimple()\n    {\n        List<PersonEmbed> results = em.createQuery(\"select p from PersonEmbed p\").getResultList();\n        assertResults(results, T, T, T, T);\n    }\n\n    /**\n     * Test select with where.\n     */\n    private void testSelectWithWhere()\n    {\n        List<PersonEmbed> results = em.createQuery(\"select p from PersonEmbed p where p.email = 'pg@gmail.com'\")\n                .getResultList();\n        assertResults(results, T, F, F, F);\n\n        results = em.createQuery(\"select p from PersonEmbed p where p.personal.fullname.firstName = 'dev'\")\n                .getResultList();\n        assertResults(results, F, T, F, F);\n\n        results = em.createQuery(\"select p from PersonEmbed p where p.personal.fullname.firstName <> 'pragalbh'\")\n                .getResultList();\n        assertResults(results, F, T, T, T);\n\n        results = em.createQuery(\"select p from PersonEmbed p where p.professional.company='impetus'\").getResultList();\n        assertResults(results, T, T, T, T);\n\n        results = em.createQuery(\"select p from PersonEmbed p where p.professional.salary = 50000\").getResultList();\n        assertResults(results, F, F, T, T);\n\n        results = em.createQuery(\"select p from PersonEmbed p where p.professional.salary < 50000\").getResultList();\n        assertResults(results, T, T, F, F);\n\n        results = em\n                .createQuery(\n                        \"select p from PersonEmbed p where p.personal.fullname.firstName = 'dev' and p.professional.salary = 50000\")\n                .getResultList();\n        assertResults(results, F, F, F, F);\n\n        results = em\n                .createQuery(\n                        \"select p from PersonEmbed p where p.professional.company='impetus' and p.personal.fullname.middleName = 'star'\")\n                .getResultList();\n        assertResults(results, F, F, F, T);\n\n        results = em\n                .createQuery(\n                        \"select p from PersonEmbed p where p.professional.salary = 50000 or p.personal.fullname.lastName = 'garg'\")\n                .getResultList();\n        assertResults(results, T, F, T, T);\n\n        ProfessionalDetails pro = new ProfessionalDetails();\n        pro.setCompany(\"impetus\");\n        pro.setMonthlySalary((double) 50000);\n        pro.setProject(\"kundera\");\n        Query qry = em.createQuery(\"select p from PersonEmbed p where p.professional = :pro\");\n        qry.setParameter(\"pro\", pro);\n        results = qry.getResultList();\n        assertResults(results, F, F, T, T);\n    }\n\n    /**\n     * Test select with where in.\n     */\n    private void testSelectWithWhereIn()\n    {\n        List<PersonEmbed> results = em.createQuery(\n                \"select p from PersonEmbed p where p.personal.fullname.firstName in ('pragalbh','amit')\")\n                .getResultList();\n        assertResults(results, T, F, F, T);\n\n        results = em.createQuery(\"select p from PersonEmbed p where p.professional.salary in (40000,50000)\")\n                .getResultList();\n        assertResults(results, T, T, T, T);\n\n        List<String> names = new ArrayList<String>();\n        names.add(\"amit\");\n        names.add(\"cherry\");\n        names.add(\"dev\");\n\n        Query query = em.createQuery(\"select p from PersonEmbed p where p.personal.fullname.firstName in :names\");\n        query.setParameter(\"names\", names);\n        results = query.getResultList();\n        assertResults(results, F, T, F, T);\n\n    }\n\n    /**\n     * Test delete simple.\n     */\n    private void testDeleteSimple()\n    {\n        persistData();\n        int result = em.createQuery(\"delete from PersonEmbed p\").executeUpdate();\n        Assert.assertEquals(4, result);\n        assertDeleted(T, T, T, T);\n\n    }\n\n    /**\n     * Test delete with where.\n     */\n    private void testDeleteWithWhere()\n    {\n        persistData();\n        int result = em.createQuery(\"delete from PersonEmbed p where p.email = 'pg@gmail.com'\").executeUpdate();\n        Assert.assertEquals(1, result);\n        assertDeleted(T, F, F, F);\n\n        persistData();\n        result = em.createQuery(\"delete from PersonEmbed p where p.personal.fullname.firstName <> 'pragalbh'\")\n                .executeUpdate();\n        Assert.assertEquals(3, result);\n        assertDeleted(F, T, T, T);\n\n        persistData();\n        result = em.createQuery(\"delete from PersonEmbed p where p.professional.salary < 50000\").executeUpdate();\n        Assert.assertEquals(2, result);\n        assertDeleted(T, T, F, F);\n\n        persistData();\n        result = em\n                .createQuery(\n                        \"delete from PersonEmbed p where p.personal.fullname.firstName = 'dev' and p.professional.salary = 50000\")\n                .executeUpdate();\n        Assert.assertEquals(0, result);\n        assertDeleted(F, F, F, F);\n\n        persistData();\n        result = em\n                .createQuery(\n                        \"delete from PersonEmbed p where p.professional.company='impetus' and p.personal.fullname.middleName = 'star'\")\n                .executeUpdate();\n        Assert.assertEquals(1, result);\n        assertDeleted(F, F, F, T);\n\n    }\n\n    /**\n     * Test delete with where in.\n     */\n    private void testDeleteWithWhereIn()\n    {\n        persistData();\n        int result = em.createQuery(\n                \"delete from PersonEmbed p where p.personal.fullname.firstName in ('pragalbh','amit')\").executeUpdate();\n        assertDeleted(T, F, F, T);\n\n        persistData();\n        result = em.createQuery(\"delete from PersonEmbed p where p.professional.salary in (40000,50000)\")\n                .executeUpdate();\n        assertDeleted(T, T, T, T);\n\n        List<String> names = new ArrayList<String>();\n        names.add(\"amit\");\n        names.add(\"cherry\");\n        names.add(\"dev\");\n\n        persistData();\n        Query query = em.createQuery(\"delete from PersonEmbed p where p.personal.fullname.firstName in :names\");\n        query.setParameter(\"names\", names);\n        result = query.executeUpdate();\n        assertDeleted(F, T, F, T);\n\n    }\n\n    /**\n     * Test update query.\n     */\n    private void testUpdateQuery()\n    {\n        persistData();\n        int result = em.createQuery(\"update PersonEmbed p set p.personal.fullname.firstName = 'newname'\")\n                .executeUpdate();\n        Assert.assertEquals(4, result);\n        em.clear();\n        PersonEmbed person1 = em.find(PersonEmbed.class, 1);\n        PersonEmbed person2 = em.find(PersonEmbed.class, 2);\n        PersonEmbed person3 = em.find(PersonEmbed.class, 3);\n        PersonEmbed person4 = em.find(PersonEmbed.class, 4);\n        Assert.assertEquals(\"newname\", person1.getPersonalDetails().getFullname().getFirstName());\n        Assert.assertEquals(\"newname\", person2.getPersonalDetails().getFullname().getFirstName());\n        Assert.assertEquals(\"newname\", person3.getPersonalDetails().getFullname().getFirstName());\n        Assert.assertEquals(\"newname\", person4.getPersonalDetails().getFullname().getFirstName());\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     */\n    @AfterClass\n    public static void tearDownAfterClass()\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/embedded/Fullname.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.embedded;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * The Class Fullname.\n * \n * @author Pragalbh Garg\n */\n@Embeddable\npublic class Fullname\n{\n\n    /** The first name. */\n    @Column\n    private String firstName;\n\n    /** The middle name. */\n    @Column\n    private String middleName;\n\n    /** The last name. */\n    @Column\n    private String lastName;\n\n    /**\n     * Instantiates a new fullname.\n     */\n    public Fullname()\n    {\n\n    }\n\n    /**\n     * Gets the first name.\n     * \n     * @return the first name\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * Sets the first name.\n     * \n     * @param firstName\n     *            the new first name\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * Gets the middle name.\n     * \n     * @return the middle name\n     */\n    public String getMiddleName()\n    {\n        return middleName;\n    }\n\n    /**\n     * Sets the middle name.\n     * \n     * @param middleName\n     *            the new middle name\n     */\n    public void setMiddleName(String middleName)\n    {\n        this.middleName = middleName;\n    }\n\n    /**\n     * Gets the last name.\n     * \n     * @return the last name\n     */\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    /**\n     * Sets the last name.\n     * \n     * @param lastName\n     *            the new last name\n     */\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/embedded/PersonEmbed.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.embedded;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class PersonEmbed.\n * \n * @author Pragalbh Garg\n */\n@Entity\n@Table(name = \"PERSON\", schema = \"HBaseNew@embeddablesTest\")\npublic class PersonEmbed\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"ID\")\n    private int personId;\n\n    /** The personal details. */\n    @Embedded\n    private PersonalDetails personal;\n\n    /** The professional details. */\n    @Embedded\n    private ProfessionalDetails professional;\n\n    /** The email. */\n    @Column(name = \"EMAIL\")\n    private String email;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the personal details.\n     * \n     * @return the personal details\n     */\n    public PersonalDetails getPersonalDetails()\n    {\n        return personal;\n    }\n\n    /**\n     * Sets the personal details.\n     * \n     * @param personalDetails\n     *            the new personal details\n     */\n    public void setPersonalDetails(PersonalDetails personalDetails)\n    {\n        this.personal = personalDetails;\n    }\n\n    /**\n     * Gets the professional details.\n     * \n     * @return the professional details\n     */\n    public ProfessionalDetails getProfessionalDetails()\n    {\n        return professional;\n    }\n\n    /**\n     * Sets the professional details.\n     * \n     * @param professionalDetails\n     *            the new professional details\n     */\n    public void setProfessionalDetails(ProfessionalDetails professionalDetails)\n    {\n        this.professional = professionalDetails;\n    }\n\n    /**\n     * Gets the email.\n     * \n     * @return the email\n     */\n    public String getEmail()\n    {\n        return email;\n    }\n\n    /**\n     * Sets the email.\n     * \n     * @param email\n     *            the new email\n     */\n    public void setEmail(String email)\n    {\n        this.email = email;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/embedded/PersonalDetails.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.embedded;\n\nimport java.util.List;\n\nimport javax.persistence.CollectionTable;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Embedded;\n\n/**\n * The Class PersonalDetails.\n * \n * @author Pragalbh Garg\n */\n@Embeddable\npublic class PersonalDetails\n{\n\n    /** The fullname. */\n    @Embedded\n    private Fullname fullname;\n\n    /** The addresses. */\n    @ElementCollection\n    @CollectionTable(name = \"add\")\n    private List<Address> addresses;\n\n    /**\n     * Gets the fullname.\n     * \n     * @return the fullname\n     */\n    public Fullname getFullname()\n    {\n        return fullname;\n    }\n\n    /**\n     * Sets the fullname.\n     * \n     * @param fullname\n     *            the new fullname\n     */\n    public void setFullname(Fullname fullname)\n    {\n        this.fullname = fullname;\n    }\n\n    /**\n     * Gets the addresses.\n     * \n     * @return the addresses\n     */\n    public List<Address> getAddresses()\n    {\n        return addresses;\n    }\n\n    /**\n     * Sets the addresses.\n     * \n     * @param addresses\n     *            the new addresses\n     */\n    public void setAddresses(List<Address> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/embedded/ProfessionalDetails.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.embedded;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * The Class ProfessionalDetails.\n * \n * @author Pragalbh Garg\n */\n@Embeddable\npublic class ProfessionalDetails\n{\n\n    /** The company. */\n    @Column\n    private String company;\n\n    /** The project. */\n    @Column\n    private String project;\n\n    /** The monthly salary. */\n    @Column\n    private Double salary;\n\n    /**\n     * Gets the company.\n     * \n     * @return the company\n     */\n    public String getCompany()\n    {\n        return company;\n    }\n\n    /**\n     * Sets the company.\n     * \n     * @param company\n     *            the new company\n     */\n    public void setCompany(String company)\n    {\n        this.company = company;\n    }\n\n    /**\n     * Gets the project.\n     * \n     * @return the project\n     */\n    public String getProject()\n    {\n        return project;\n    }\n\n    /**\n     * Sets the project.\n     * \n     * @param project\n     *            the new project\n     */\n    public void setProject(String project)\n    {\n        this.project = project;\n    }\n\n    /**\n     * Gets the monthly salary.\n     * \n     * @return the monthly salary\n     */\n    public Double getMonthlySalary()\n    {\n        return salary;\n    }\n\n    /**\n     * Sets the monthly salary.\n     * \n     * @param monthlySalary\n     *            the new monthly salary\n     */\n    public void setMonthlySalary(Double monthlySalary)\n    {\n        this.salary = monthlySalary;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/inheritence/FacebookProfile.java",
    "content": "/**\r\n * Copyright 2015 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.client.hbase.crud.inheritence;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.DiscriminatorValue;\r\nimport javax.persistence.Entity;\r\n\r\n/**\r\n * Facebook profile entity.\r\n * \r\n * @author Pragalbh Garg\r\n */\r\n@Entity\r\n@DiscriminatorValue(\"fb\")\r\npublic class FacebookProfile extends SocialProfile\r\n{\r\n    /** The facebook id. */\r\n    @Column(name = \"facebook_id\", updatable = false)\r\n    private String facebookId;\r\n\r\n    /** The facebook user. */\r\n    @Column(name = \"facebook_user\", length = 128)\r\n    private String facebookUser;\r\n\r\n    /**\r\n     * Gets the facebook id.\r\n     * \r\n     * @return the facebook id\r\n     */\r\n    public String getFacebookId()\r\n    {\r\n        return facebookId;\r\n    }\r\n\r\n    /**\r\n     * Sets the facebook id.\r\n     * \r\n     * @param facebookId\r\n     *            the new facebook id\r\n     */\r\n    public void setFacebookId(String facebookId)\r\n    {\r\n        this.facebookId = facebookId;\r\n    }\r\n\r\n    /**\r\n     * Gets the facebook user.\r\n     * \r\n     * @return the facebook user\r\n     */\r\n    public String getFacebookUser()\r\n    {\r\n        return facebookUser;\r\n    }\r\n\r\n    /**\r\n     * Sets the facebook user.\r\n     * \r\n     * @param facebookUser\r\n     *            the new facebook user\r\n     */\r\n    public void setFacebookUser(String facebookUser)\r\n    {\r\n        this.facebookUser = facebookUser;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/inheritence/GuidDomainObject.java",
    "content": "/**\r\n * Copyright 2015 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.client.hbase.crud.inheritence;\r\n\r\nimport javax.persistence.Id;\r\nimport javax.persistence.MappedSuperclass;\r\n\r\n/**\r\n * Abstract mapped super class.\r\n * \r\n * @author Pragalbh Garg\r\n * \r\n */\r\n@MappedSuperclass\r\nabstract public class GuidDomainObject\r\n{\r\n    /** The id. */\r\n    @Id\r\n    private Long id;\r\n\r\n    /**\r\n     * Gets the id.\r\n     * \r\n     * @return the id\r\n     */\r\n    public Long getId()\r\n    {\r\n        return id;\r\n    }\r\n\r\n    /**\r\n     * Sets the id.\r\n     * \r\n     * @param id\r\n     *            the new id\r\n     */\r\n    public void setId(Long id)\r\n    {\r\n        this.id = id;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/inheritence/InheritenceDomainTest.java",
    "content": "/**\r\n * Copyright 2015 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.client.hbase.crud.inheritence;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Persistence;\r\nimport javax.persistence.Query;\r\n\r\nimport junit.framework.Assert;\r\n\r\nimport org.junit.After;\r\nimport org.junit.AfterClass;\r\nimport org.junit.BeforeClass;\r\nimport org.junit.Test;\r\n\r\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\r\n\r\n/**\r\n * Junit for abstract entity class's operation.\r\n * \r\n * @author Pragalbh Garg\r\n * \r\n */\r\npublic class InheritenceDomainTest\r\n{\r\n\r\n    /** The pu. */\r\n    protected static String _PU = \"inheritenceTest\";\r\n\r\n    /** The emf. */\r\n    protected static EntityManagerFactory emf;\r\n\r\n    /** The em. */\r\n    protected static EntityManager em;\r\n\r\n    /** The obj cache. */\r\n    private List objCache = new ArrayList();\r\n\r\n    /**\r\n     * Sets the up before class.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    @BeforeClass\r\n    public static void setUpBeforeClass() throws Exception\r\n    {\r\n        emf = Persistence.createEntityManagerFactory(_PU);\r\n        em = emf.createEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Test relation.\r\n     */\r\n    @Test\r\n    public void testRelation()\r\n    {\r\n\r\n        List<SocialProfile> profiles = new ArrayList<SocialProfile>();\r\n\r\n        FacebookProfile fbprofile = new FacebookProfile();\r\n        fbprofile.setId(103l);\r\n        fbprofile.setFacebookId(\"fbtestRelation\");\r\n        fbprofile.setFacebookUser(\"facebook\");\r\n        fbprofile.setuserType(\"testRelation\");\r\n\r\n        profiles.add(fbprofile);\r\n\r\n        TwitterProfile twprofile1 = new TwitterProfile();\r\n        twprofile1.setTwitterId(\"2\");\r\n        twprofile1.setTwitterName(\"testTwitterRelation\");\r\n        twprofile1.setId(102l);\r\n        profiles.add(twprofile1);\r\n        twprofile1.setuserType(\"testRelation\");\r\n\r\n        UserAccount uacc = new UserAccount();\r\n\r\n        uacc.setId(101l);\r\n        uacc.setDispName(\"Test\");\r\n        uacc.setSocialProfiles(profiles);\r\n\r\n        twprofile1.setuserAccount(uacc);\r\n        fbprofile.setuserAccount(uacc);\r\n\r\n        em.getTransaction().begin();\r\n        em.persist(uacc);\r\n        em.getTransaction().commit();\r\n\r\n        objCache.add(uacc);\r\n        objCache.add(twprofile1);\r\n        objCache.add(fbprofile);\r\n\r\n        em.clear();\r\n\r\n        String uaQuery = \"Select ua from UserAccount ua\";\r\n\r\n        Query q = em.createQuery(uaQuery);\r\n        List<UserAccount> results = q.getResultList();\r\n\r\n        Assert.assertEquals(1, results.size());\r\n        Assert.assertEquals(\"Test\", results.get(0).getDispName());\r\n        Assert.assertEquals(2, results.get(0).getSocialProfiles().size());\r\n\r\n        em.remove(results.get(0));\r\n\r\n        em.clear();\r\n\r\n    }\r\n\r\n    /**\r\n     * Test abstract entity.\r\n     */\r\n    @Test\r\n    public void testAbstractEntity()\r\n    {\r\n        FacebookProfile fbprofile = new FacebookProfile();\r\n        fbprofile.setId(Long.MIN_VALUE);\r\n        fbprofile.setFacebookId(\"fbEntity\");\r\n        fbprofile.setFacebookUser(\"facebookEntity\");\r\n        fbprofile.setuserType(\"abstractEntity\");\r\n\r\n        em.persist(fbprofile);\r\n\r\n        TwitterProfile twprofile = new TwitterProfile();\r\n        twprofile.setTwitterId(\"2\");\r\n        twprofile.setTwitterName(\"twitterEntity\");\r\n        twprofile.setId(Long.MAX_VALUE);\r\n        twprofile.setuserType(\"abstractEntity\");\r\n\r\n        em.persist(twprofile);\r\n\r\n        em.clear();\r\n        objCache.add(twprofile);\r\n        objCache.add(fbprofile);\r\n\r\n        SocialProfile facebookProfile = em.find(SocialProfile.class, Long.MIN_VALUE);\r\n        Assert.assertNotNull(facebookProfile);\r\n        Assert.assertTrue(facebookProfile.getClass().isAssignableFrom(FacebookProfile.class));\r\n\r\n        SocialProfile twitterProfile = em.find(SocialProfile.class, Long.MAX_VALUE);\r\n        Assert.assertNotNull(twitterProfile);\r\n        Assert.assertTrue(twitterProfile.getClass().isAssignableFrom(TwitterProfile.class));\r\n\r\n        em.clear();\r\n        String queryStr = \"Select s from SocialProfile s\";\r\n\r\n        Query query = em.createQuery(queryStr);\r\n\r\n        List<SocialProfile> socialProfiles = query.getResultList();\r\n\r\n        Assert.assertFalse(socialProfiles.isEmpty());\r\n        Assert.assertEquals(2, socialProfiles.size());\r\n        Assert.assertFalse(socialProfiles.get(0).getClass().getSimpleName()\r\n                .equals(socialProfiles.get(1).getClass().getSimpleName()));\r\n\r\n        em.clear();\r\n\r\n        String deleteQuery = \"Delete from SocialProfile s\";\r\n        query = em.createQuery(deleteQuery);\r\n        query.executeUpdate();\r\n\r\n        query = em.createQuery(queryStr);\r\n\r\n        socialProfiles = query.getResultList();\r\n        Assert.assertTrue(socialProfiles.isEmpty());\r\n    }\r\n\r\n    /**\r\n     * Tear down.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    @After\r\n    public void tearDown() throws Exception\r\n    {\r\n        for (Object o : objCache)\r\n        {\r\n            em.remove(o);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Tear down after class.\r\n     */\r\n    @AfterClass\r\n    public static void tearDownAfterClass()\r\n    {\r\n        HBaseTestingUtils.dropSchema(\"HBaseNew\");\r\n        if (em != null)\r\n        {\r\n            em.close();\r\n            em = null;\r\n        }\r\n        if (emf != null)\r\n        {\r\n            emf.close();\r\n            emf = null;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/inheritence/SocialProfile.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.hbase.crud.inheritence;\n\nimport java.io.Serializable;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorColumn;\nimport javax.persistence.DiscriminatorType;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * Abstract entity class.\n * \n * @author Pragalbh Garg\n * \n */\n@Entity\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@Table(name = \"social_profile\")\n@DiscriminatorColumn(name = \"type\", length = 64, discriminatorType = DiscriminatorType.STRING)\npublic abstract class SocialProfile extends GuidDomainObject implements Serializable\n{\n    /** The user type. */\n    @Column(name = \"userType\")\n    private String userType;\n\n    /** The account. */\n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"user_account_id\")\n    private UserAccount account;\n\n    /**\n     * Gets the user type.\n     * \n     * @return the user type\n     */\n    public String getuserType()\n    {\n        return userType;\n    }\n\n    /**\n     * Sets the user type.\n     * \n     * @param userType\n     *            the new user type\n     */\n    public void setuserType(String userType)\n    {\n        this.userType = userType;\n    }\n\n    /**\n     * Gets the user account.\n     * \n     * @return the user account\n     */\n    public UserAccount getuserAccount()\n    {\n        return account;\n    }\n\n    /**\n     * Sets the user account.\n     * \n     * @param account\n     *            the new user account\n     */\n    public void setuserAccount(UserAccount account)\n    {\n        this.account = account;\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/inheritence/TwitterProfile.java",
    "content": "/**\r\n * Copyright 2015 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.client.hbase.crud.inheritence;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.DiscriminatorValue;\r\nimport javax.persistence.Entity;\r\n\r\n/**\r\n * Twitter profile entity.\r\n * \r\n * @author Pragalbh Garg\r\n * \r\n */\r\n@Entity\r\n@DiscriminatorValue(\"twitter\")\r\npublic class TwitterProfile extends SocialProfile\r\n{\r\n    /** The twitter id. */\r\n    @Column(name = \"twitter_id\", updatable = false)\r\n    private String twitterId;\r\n\r\n    /** The twitter user. */\r\n    @Column(name = \"twitter_user\", length = 128)\r\n    private String twitterUser;\r\n\r\n    /**\r\n     * Gets the twitter id.\r\n     * \r\n     * @return the twitter id\r\n     */\r\n    public String getTwitterId()\r\n    {\r\n        return twitterId;\r\n    }\r\n\r\n    /**\r\n     * Sets the twitter id.\r\n     * \r\n     * @param twitterId\r\n     *            the new twitter id\r\n     */\r\n    public void setTwitterId(String twitterId)\r\n    {\r\n        this.twitterId = twitterId;\r\n    }\r\n\r\n    /**\r\n     * Gets the twitter name.\r\n     * \r\n     * @return the twitter name\r\n     */\r\n    public String getTwitterName()\r\n    {\r\n        return twitterUser;\r\n    }\r\n\r\n    /**\r\n     * Sets the twitter name.\r\n     * \r\n     * @param twitterUser\r\n     *            the new twitter name\r\n     */\r\n    public void setTwitterName(String twitterUser)\r\n    {\r\n        this.twitterUser = twitterUser;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/inheritence/UserAccount.java",
    "content": "/**\r\n * Copyright 2015 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.client.hbase.crud.inheritence;\r\n\r\nimport java.util.List;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * User account entity.\r\n * \r\n * @author Pragalbh Garg\r\n * \r\n */\r\n@Entity\r\n@Table(name = \"user_account\")\r\npublic class UserAccount extends GuidDomainObject\r\n{\r\n    /** The display name. */\r\n    @Column(name = \"display_name\", length = 128)\r\n    private String displayName = null;\r\n\r\n    /** The email. */\r\n    @Column(name = \"email\", length = 128, unique = true)\r\n    private String email = null;\r\n\r\n    /** The profiles. */\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, mappedBy = \"account\")\r\n    private List<SocialProfile> profiles;\r\n\r\n    /**\r\n     * Gets the disp name.\r\n     * \r\n     * @return the disp name\r\n     */\r\n    public String getDispName()\r\n    {\r\n        return displayName;\r\n    }\r\n\r\n    /**\r\n     * Sets the disp name.\r\n     * \r\n     * @param displayName\r\n     *            the new disp name\r\n     */\r\n    public void setDispName(String displayName)\r\n    {\r\n        this.displayName = displayName;\r\n    }\r\n\r\n    /**\r\n     * Gets the email.\r\n     * \r\n     * @return the email\r\n     */\r\n    public String getEmail()\r\n    {\r\n        return email;\r\n    }\r\n\r\n    /**\r\n     * Sets the email.\r\n     * \r\n     * @param email\r\n     *            the new email\r\n     */\r\n    public void setEmail(String email)\r\n    {\r\n        this.email = email;\r\n    }\r\n\r\n    /**\r\n     * Gets the social profiles.\r\n     * \r\n     * @return the social profiles\r\n     */\r\n    public List<SocialProfile> getSocialProfiles()\r\n    {\r\n        return profiles;\r\n    }\r\n\r\n    /**\r\n     * Sets the social profiles.\r\n     * \r\n     * @param profiles\r\n     *            the new social profiles\r\n     */\r\n    public void setSocialProfiles(List<SocialProfile> profiles)\r\n    {\r\n        this.profiles = profiles;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/mappedsuperclass/inheritence/HBaseEntityWithoutFieldsTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.mappedsuperclass.inheritence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\nimport com.impetus.kundera.metadata.mappedsuperclass.EntityWithoutFieldsBase;\n\n/**\n * The Class HBaseEntityWithoutFieldsTest.\n * \n * @author Pragalbh Garg\n * \n *         Class to verify that at least one field in entity class is not\n *         mandatory if the superclass contains all the mandatory fields\n */\npublic class HBaseEntityWithoutFieldsTest extends EntityWithoutFieldsBase\n{\n\n    /**\n     * Setup.\n     */\n    @Before\n    public void setup()\n    {\n        persistenceUnit = \"entityWithoutFieldTest\";\n        setupInternal();\n    }\n\n    /**\n     * Test entity with no fields.\n     */\n    @Test\n    public void testEntityWithNoFields()\n    {\n        testEntityWithNoFieldsBase();\n    }\n\n    /**\n     * Test entity with no fields2 level inheritance.\n     */\n    @Test\n    public void testEntityWithNoFields2LevelInheritance()\n    {\n        testEntityWithNoFields2LevelInheritanceBase();\n    }\n\n    /**\n     * Tear down.\n     */\n    @After\n    public void tearDown()\n    {\n        tearDownInternal();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        HBaseTestingUtils.dropSchema(\"HBaseNew\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/mappedsuperclass/inheritence/HBaseMappedSuperClassTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.crud.mappedsuperclass.inheritence;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\nimport com.impetus.kundera.client.crud.mappedsuperclass.MappedSuperClassBase;\n\n/**\n * The Class HBaseMappedSuperClassTest.\n * \n * @author Pragalbh Garg\n * \n */\npublic class HBaseMappedSuperClassTest extends MappedSuperClassBase\n{\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        _PU = \"mappedSuperClassTest\";\n        setUpInternal();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        assertInternal();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        tearDownInternal();\n        HBaseTestingUtils.dropSchema(\"HBaseNew\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/generatedId/HBaseGeneratedIdTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.generatedId;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.HBaseClient;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdDefault;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdStrategyAuto;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdStrategyIdentity;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdStrategySequence;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdStrategyTable;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdWithOutSequenceGenerator;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdWithOutTableGenerator;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdWithSequenceGenerator;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdWithTableGenerator;\nimport com.impetus.client.hbase.generatedId.entites.HBaseGeneratedIdWithTableGeneratorWihtoutInit;\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\nimport com.impetus.kundera.KunderaException;\n\n/**\n * The Class HBaseGeneratedIdTest.\n * \n * @author Pragalbh Garg\n */\npublic class HBaseGeneratedIdTest\n{\n    /** The Constant SCHEMA. */\n    private static final String SCHEMA = \"HBaseNew\";\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"autoIdTest\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n\n    /**\n     * Test persist.\n     */\n    @Test\n    public void testPersist()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        try\n        {\n            HBaseGeneratedIdDefault idDefault = new HBaseGeneratedIdDefault();\n            idDefault.setName(\"kuldeep\");\n            em.persist(idDefault);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                    + GenerationType.AUTO + \" Strategy not supported by this client :\" + HBaseClient.class.getName(),\n                    e.getMessage());\n        }\n        try\n        {\n            HBaseGeneratedIdStrategyAuto strategyAuto = new HBaseGeneratedIdStrategyAuto();\n            strategyAuto.setName(\"kuldeep\");\n            em.persist(strategyAuto);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                    + GenerationType.AUTO + \" Strategy not supported by this client :\" + HBaseClient.class.getName(),\n                    e.getMessage());\n        }\n\n        try\n        {\n            HBaseGeneratedIdStrategyIdentity strategyIdentity = new HBaseGeneratedIdStrategyIdentity();\n            strategyIdentity.setName(\"kuldeep\");\n            em.persist(strategyIdentity);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.UnsupportedOperationException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.IDENTITY + \" Strategy not supported by this client :\"\n                            + HBaseClient.class.getName(), e.getMessage());\n        }\n\n        HBaseGeneratedIdStrategySequence strategySequence = new HBaseGeneratedIdStrategySequence();\n        strategySequence.setName(\"Kuldeep\");\n        try\n        {\n            em.persist(strategySequence);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + HBaseClient.class.getName(), e.getMessage());\n        }\n\n        try\n        {\n            HBaseGeneratedIdStrategyTable strategyTable1 = new HBaseGeneratedIdStrategyTable();\n            strategyTable1.setName(\"KK\");\n            em.persist(strategyTable1);\n\n            HBaseGeneratedIdStrategyTable strategyTable2 = new HBaseGeneratedIdStrategyTable();\n            strategyTable2.setName(\"vm\");\n            em.persist(strategyTable2);\n\n            HBaseGeneratedIdStrategyTable strategyTable3 = new HBaseGeneratedIdStrategyTable();\n            strategyTable3.setName(\"vs\");\n            em.persist(strategyTable3);\n\n            HBaseGeneratedIdStrategyTable strategyTable = new HBaseGeneratedIdStrategyTable();\n            strategyTable.setName(\"sh\");\n            em.persist(strategyTable);\n\n            List<HBaseGeneratedIdStrategyTable> list = em.createQuery(\"Select c from HBaseGeneratedIdStrategyTable c\")\n                    .getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(4, list.size());\n            for (HBaseGeneratedIdStrategyTable entity : list)\n            {\n                Assert.assertTrue(entity.getId() == 1 || entity.getId() == 51 || entity.getId() == 101\n                        || entity.getId() == 151);\n            }\n\n            em.clear();\n            strategyTable = em.find(HBaseGeneratedIdStrategyTable.class, strategyTable.getId());\n            Assert.assertNotNull(strategyTable);\n            Assert.assertEquals(\"sh\", strategyTable.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n\n        try\n        {\n            HBaseGeneratedIdWithOutSequenceGenerator withOutSequenceGenerator = new HBaseGeneratedIdWithOutSequenceGenerator();\n            withOutSequenceGenerator.setName(\"Kuldeep Kumar\");\n            em.persist(withOutSequenceGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + HBaseClient.class.getName(), e.getMessage());\n        }\n\n        try\n        {\n            HBaseGeneratedIdWithOutTableGenerator withOutTableGenerator = new HBaseGeneratedIdWithOutTableGenerator();\n            withOutTableGenerator.setName(\"Kuldeep Mishra\");\n            em.persist(withOutTableGenerator);\n            List<HBaseGeneratedIdWithOutTableGenerator> list = em.createQuery(\n                    \"Select c from HBaseGeneratedIdWithOutTableGenerator c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"Kuldeep Mishra\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            withOutTableGenerator = em.find(HBaseGeneratedIdWithOutTableGenerator.class, id);\n            Assert.assertNotNull(withOutTableGenerator);\n            Assert.assertEquals(\"Kuldeep Mishra\", withOutTableGenerator.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n        try\n        {\n            HBaseGeneratedIdWithSequenceGenerator withSequenceGenerator = new HBaseGeneratedIdWithSequenceGenerator();\n            withSequenceGenerator.setName(\"Kuldeep Kumar Mishra\");\n            em.persist(withSequenceGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + HBaseClient.class.getName(), e.getMessage());\n        }\n        try\n        {\n            // Test with initValue paramater = 100 allocationsize = 30\n            HBaseGeneratedIdWithTableGenerator withTableGenerator = new HBaseGeneratedIdWithTableGenerator();\n            withTableGenerator.setName(\"Kumar Mishra\");\n            em.persist(withTableGenerator);\n            List<HBaseGeneratedIdWithTableGenerator> list = em.createQuery(\n                    \"Select c from HBaseGeneratedIdWithTableGenerator c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"Kumar Mishra\", list.get(0).getName());\n            Object id = list.get(0).getId();\n\n            Assert.assertEquals(100, id);\n            HBaseGeneratedIdWithTableGenerator withTableGenerator2 = new HBaseGeneratedIdWithTableGenerator();\n            withTableGenerator2.setName(\"Kumar Mishra2\");\n            em.persist(withTableGenerator2);\n            list = em.createQuery(\"Select c from HBaseGeneratedIdWithTableGenerator c\").getResultList();\n            Assert.assertEquals(2, list.size());\n            if(list.get(0).getName().equals(\"Kumar Mishra2\")){\n          \t  id = list.get(0).getId();\n          }\n          else{\n              id = list.get(1).getId();\n          }\n            em.clear();\n            withTableGenerator = em.find(HBaseGeneratedIdWithTableGenerator.class, id);\n            Assert.assertNotNull(withTableGenerator);\n            Assert.assertEquals(\"Kumar Mishra2\", withTableGenerator.getName());\n\n            // Test without initValue paramater allocationsize = 30\n            HBaseGeneratedIdWithTableGeneratorWihtoutInit person1 = new HBaseGeneratedIdWithTableGeneratorWihtoutInit();\n            person1.setName(\"pragalbh\");\n            em.persist(person1);\n\n            HBaseGeneratedIdWithTableGeneratorWihtoutInit person2 = new HBaseGeneratedIdWithTableGeneratorWihtoutInit();\n            person2.setName(\"pragalbh2\");\n            em.persist(person2);\n\n            List<HBaseGeneratedIdWithTableGeneratorWihtoutInit> results = em.createQuery(\n                    \"Select c from HBaseGeneratedIdWithTableGeneratorWihtoutInit c\").getResultList();\n            Assert.assertTrue(results.get(0).getId() == 1 || results.get(0).getId() == 51);\n            Assert.assertTrue(results.get(1).getId() == 1 || results.get(1).getId() == 51);\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdDefault.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class HBaseGeneratedIdDefault.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"HBaseGeneratedIdDefault\", schema = \"HBaseNew@autoIdTest\")\npublic class HBaseGeneratedIdDefault\n{\n\n    /** The id. */\n    @Id\n    @GeneratedValue\n    private int id;\n\n    /** The name. */\n    @Column\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdStrategyAuto.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n/**\n * The Class HBaseGeneratedIdStrategyAuto.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"HBaseGeneratedIdStrategyAuto\", schema = \"HBaseNew@autoIdTest\")\n@TableGenerator(name = \"id_gen\")\npublic class HBaseGeneratedIdStrategyAuto\n{\n\n    /** The id. */\n    @Id\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.AUTO)\n    private int id;\n\n    /** The name. */\n    @Column\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdStrategyIdentity.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class HBaseGeneratedIdStrategyIdentity.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"HBaseGeneratedIdStrategyIdentity\", schema = \"HBaseNew@autoIdTest\")\npublic class HBaseGeneratedIdStrategyIdentity\n{\n\n    /** The id. */\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    private int id;\n\n    /** The name. */\n    @Column\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdStrategySequence.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\n\n/**\n * The Class HBaseGeneratedIdStrategySequence.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"HBaseGeneratedIdStrategySequence\", schema = \"HBaseNew@autoIdTest\")\npublic class HBaseGeneratedIdStrategySequence\n{\n\n    /** The id. */\n    @Id\n    @SequenceGenerator(name = \"seq_gen\")\n    @GeneratedValue(generator = \"seq_gen\", strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    /** The name. */\n    @Column\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdStrategyTable.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n/**\n * The Class HBaseGeneratedIdStrategyTable.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"HBaseGeneratedIdStrategyTable\", schema = \"HBaseNew@autoIdTest\")\n@TableGenerator(name = \"table_gen\")\npublic class HBaseGeneratedIdStrategyTable\n{\n\n    /** The id. */\n    @Id\n    @TableGenerator(name = \"table_gen_1\")\n    @GeneratedValue(generator = \"table_gen\", strategy = GenerationType.TABLE)\n    private int id;\n\n    /** The name. */\n    @Column\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdWithOutSequenceGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class HBaseGeneratedIdWithOutSequenceGenerator.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"HBaseGeneratedIdWithOutSequenceGenerator\", schema = \"HBaseNew@autoIdTest\")\npublic class HBaseGeneratedIdWithOutSequenceGenerator\n{\n\n    /** The id. */\n    @Id\n    @GeneratedValue(strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    /** The name. */\n    @Column\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdWithOutTableGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class HBaseGeneratedIdWithOutTableGenerator.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"HBaseGeneratedIdWithOutTableGenerator\", schema = \"HBaseNew@autoIdTest\")\npublic class HBaseGeneratedIdWithOutTableGenerator\n{\n\n    /** The id. */\n    @Id\n    @GeneratedValue(strategy = GenerationType.TABLE)\n    private int id;\n\n    /** The name. */\n    @Column\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdWithSequenceGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\n\n/**\n * The Class HBaseGeneratedIdWithSequenceGenerator.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"HBaseGeneratedIdWithSequenceGenerator\", schema = \"HBaseNew@autoIdTest\")\npublic class HBaseGeneratedIdWithSequenceGenerator\n{\n\n    /** The id. */\n    @Id\n    @SequenceGenerator(name = \"id_gen\", allocationSize = 20, initialValue = 80, schema = \"HBaseNew\", sequenceName = \"newSequence\")\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    /** The name. */\n    @Column\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdWithTableGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n/**\n * The Class HBaseGeneratedIdWithTableGenerator.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"HBaseGeneratedIdWithTableGenerator\", schema = \"HBaseNew@autoIdTest\")\npublic class HBaseGeneratedIdWithTableGenerator\n{\n\n    /** The id. */\n    @Id\n    @TableGenerator(name = \"id_gen\", allocationSize = 30, initialValue = 100, schema = \"HBaseNew\", valueColumnName = \"sequenceValue\")\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.TABLE)\n    private int id;\n\n    /** The name. */\n    @Column\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdWithTableGeneratorWihtoutInit.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n/**\n * The Class HBaseGeneratedIdWithTableGeneratorWihtoutInit.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"HBaseGeneratedIdWithTableGeneratorWithoutInit\", schema = \"HBaseNew@autoIdTest\")\npublic class HBaseGeneratedIdWithTableGeneratorWihtoutInit\n{\n\n    /** The id. */\n    @Id\n    @TableGenerator(name = \"id_gen_2\")\n    @GeneratedValue(generator = \"id_gen_2\", strategy = GenerationType.TABLE)\n    private int id;\n\n    /** The name. */\n    @Column\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/schema/HBaseSchemaGenerationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.schema;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.apache.hadoop.hbase.HTableDescriptor;\nimport org.apache.hadoop.hbase.NamespaceDescriptor;\nimport org.apache.hadoop.hbase.NamespaceNotFoundException;\nimport org.apache.hadoop.hbase.TableName;\nimport org.apache.hadoop.hbase.client.Connection;\nimport org.apache.hadoop.hbase.client.ConnectionFactory;\nimport org.apache.hadoop.hbase.client.HBaseAdmin;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\nimport com.impetus.client.hbase.utils.HBaseUtils;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\n\n/**\n * The Class HBaseSchemaGenerationTest.\n * \n * @author Pragalbh Garg\n */\npublic class HBaseSchemaGenerationTest\n{\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"schemaTest\";\n\n    /** The Constant SCHEMA. */\n    private static final String SCHEMA = \"HBaseNew\";\n\n    /** The TABL e_1. */\n    private String TABLE_1 = HBaseUtils.getHTableName(SCHEMA, \"USER_HBASE\");\n\n    /** The TABL e_2. */\n    private String TABLE_2 = HBaseUtils.getHTableName(SCHEMA, \"PRODUCT_HBASE\");\n\n    /** The admin. */\n    private static HBaseAdmin admin;\n\n    /** The property map. */\n    private Map propertyMap = new HashMap();\n\n    /** The connection. */\n    private static Connection connection;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        connection = ConnectionFactory.createConnection();\n        admin = (HBaseAdmin) connection.getAdmin();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        admin.close();\n        connection.close();\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n\n    /**\n     * Test operations.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    @Test\n    public void testOperations() throws IOException\n    {\n        testCreate();\n        testUpdate();\n        testValidate();\n        testCreateDrop();\n    }\n\n    /**\n     * Test create.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    public void testCreate() throws IOException\n    {\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        assertSchema();\n    }\n\n    /**\n     * Test update.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    public void testUpdate() throws IOException\n    {\n\n        init();\n\n        admin.disableTable(TABLE_2);\n        admin.deleteTable(TABLE_2);\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"update\");\n\n        assertSchema();\n\n        postAssert();\n    }\n\n    /**\n     * Test validate.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    private void testValidate() throws IOException\n    {\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"validate\");\n        assertSchema();\n\n        assertInValidate();\n\n    }\n\n    /**\n     * Assert in validate.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    private void assertInValidate() throws IOException\n    {\n        admin.disableTable(TABLE_2);\n        admin.deleteTable(TABLE_2);\n        try\n        {\n            EntityManagerFactory emf = Persistence.createEntityManagerFactory(HBASE_PU, propertyMap);\n            EntityManager em = emf.createEntityManager();\n            Assert.assertTrue(false);\n            em.close();\n            emf.close();\n        }\n        catch (SchemaGenerationException sge)\n        {\n            Assert.assertTrue(true);\n        }\n\n    }\n\n    /**\n     * Test create drop.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    public void testCreateDrop() throws IOException\n    {\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create-drop\");\n        assertSchema();\n\n        assertDrop();\n\n    }\n\n    /**\n     * Assert drop.\n     */\n    private void assertDrop()\n    {\n        try\n        {\n            for (NamespaceDescriptor ns : admin.listNamespaceDescriptors())\n            {\n                if (ns.getName().equals(SCHEMA))\n                {\n                    Assert.assertTrue(false);\n                    break;\n                }\n            }\n        }\n        catch (IOException ioex)\n        {\n            throw new SchemaGenerationException(ioex, \"Hbase\");\n        }\n\n    }\n\n    /**\n     * Assert schema.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     */\n    private void assertSchema() throws IOException\n    {\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(HBASE_PU, propertyMap);\n        EntityManager em = emf.createEntityManager();\n\n        try\n        {\n            admin.getNamespaceDescriptor(SCHEMA);\n            Assert.assertTrue(true);\n        }\n        catch (NamespaceNotFoundException e)\n        {\n            Assert.assertTrue(false);\n        }\n\n        Assert.assertTrue(admin.isTableAvailable(TABLE_1));\n        Assert.assertTrue(admin.isTableAvailable(TABLE_2));\n\n        HTableDescriptor descriptor = admin.getTableDescriptor(TableName.valueOf(TABLE_1));\n        Assert.assertTrue(descriptor.hasFamily(\"USER_HBASE\".getBytes()));\n\n        descriptor = admin.getTableDescriptor(TableName.valueOf(TABLE_2));\n        Assert.assertTrue(descriptor.hasFamily(\"PRODUCT_HBASE\".getBytes()));\n\n        em.close();\n        emf.close();\n    }\n\n    /**\n     * Inits the.\n     */\n    private void init()\n    {\n        propertyMap.remove(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE);\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(HBASE_PU, propertyMap);\n        EntityManager em = emf.createEntityManager();\n        UserHBase user = new UserHBase();\n        user.setUserId(\"1\");\n        user.setUserName(\"personHbase\");\n        user.setPhoneNo(88888);\n        em.persist(user);\n        em.close();\n        emf.close();\n\n    }\n\n    /**\n     * Post assert.\n     */\n    private void postAssert()\n    {\n        propertyMap.remove(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE);\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(HBASE_PU, propertyMap);\n        EntityManager em = emf.createEntityManager();\n        try\n        {\n            UserHBase user = em.find(UserHBase.class, \"1\");\n            if (user != null)\n            {\n                Assert.assertTrue(true);\n            }\n            else\n            {\n                Assert.assertTrue(false);\n            }\n        }\n        catch (Exception e)\n        {\n            Assert.assertTrue(false);\n        }\n\n        em.close();\n        emf.close();\n\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/schema/ProductHBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.hbase.schema;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class ProductHBase.\n * \n * @author Pragalbh Garg\n */\n@Entity\n@Table(name = \"PRODUCT_HBASE\", schema = \"HBaseNew@schemaTest\")\npublic class ProductHBase\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PRODUCT_ID\")\n    private String productId;\n\n    /** The person name. */\n    @Column(name = \"PRODUCT_NAME\")\n    private String productName;\n\n    /** The age. */\n    @Column(name = \"DESCRIPTION\")\n    private String description;\n\n    /** The price. */\n    @Column(name = \"PRICE\")\n    private int price;\n\n    /**\n     * Gets the product id.\n     * \n     * @return the product id\n     */\n    public String getProductId()\n    {\n        return productId;\n    }\n\n    /**\n     * Sets the product id.\n     * \n     * @param productId\n     *            the new product id\n     */\n    public void setProductId(String productId)\n    {\n        this.productId = productId;\n    }\n\n    /**\n     * Gets the product name.\n     * \n     * @return the product name\n     */\n    public String getProductName()\n    {\n        return productName;\n    }\n\n    /**\n     * Sets the product name.\n     * \n     * @param productName\n     *            the new product name\n     */\n    public void setProductName(String productName)\n    {\n        this.productName = productName;\n    }\n\n    /**\n     * Gets the description.\n     * \n     * @return the description\n     */\n    public String getDescription()\n    {\n        return description;\n    }\n\n    /**\n     * Sets the description.\n     * \n     * @param description\n     *            the new description\n     */\n    public void setDescription(String description)\n    {\n        this.description = description;\n    }\n\n    /**\n     * Gets the price.\n     * \n     * @return the price\n     */\n    public int getPrice()\n    {\n        return price;\n    }\n\n    /**\n     * Sets the price.\n     * \n     * @param price\n     *            the new price\n     */\n    public void setPrice(int price)\n    {\n        this.price = price;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/schema/UserHBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.hbase.schema;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class UserHBase.\n * \n * @author Pragalbh Garg\n */\n@Entity\n@Table(name = \"USER_HBASE\", schema = \"HBaseNew@schemaTest\")\npublic class UserHBase\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String userId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String userName;\n\n    /** The age. */\n    @Column(name = \"EMAIL_ID\")\n    private String email;\n\n    /** The phone no. */\n    @Column(name = \"PHONE_NO\")\n    private long phoneNo;\n\n    /**\n     * Gets the user id.\n     * \n     * @return the user id\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * Sets the user id.\n     * \n     * @param userId\n     *            the new user id\n     */\n    public void setUserId(String userId)\n    {\n        this.userId = userId;\n    }\n\n    /**\n     * Gets the user name.\n     * \n     * @return the user name\n     */\n    public String getUserName()\n    {\n        return userName;\n    }\n\n    /**\n     * Sets the user name.\n     * \n     * @param userName\n     *            the new user name\n     */\n    public void setUserName(String userName)\n    {\n        this.userName = userName;\n    }\n\n    /**\n     * Gets the email.\n     * \n     * @return the email\n     */\n    public String getEmail()\n    {\n        return email;\n    }\n\n    /**\n     * Sets the email.\n     * \n     * @param email\n     *            the new email\n     */\n    public void setEmail(String email)\n    {\n        this.email = email;\n    }\n\n    /**\n     * Gets the phone no.\n     * \n     * @return the phone no\n     */\n    public long getPhoneNo()\n    {\n        return phoneNo;\n    }\n\n    /**\n     * Sets the phone no.\n     * \n     * @param phoneNo\n     *            the new phone no\n     */\n    public void setPhoneNo(long phoneNo)\n    {\n        this.phoneNo = phoneNo;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/secondarytable/EmbeddedCollectionEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.secondarytable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * The Class EmbeddedCollectionEntity.\n * \n * @author Pragalbh Garg\n */\n@Embeddable\npublic class EmbeddedCollectionEntity\n{\n\n    /** The collection id. */\n    @Column(name = \"COLLECTION_ID\")\n    private String collectionId;\n\n    /** The collection name. */\n    @Column(name = \"COLLECTION_NAME\")\n    private String collectionName;\n\n    /**\n     * Gets the collection id.\n     * \n     * @return the collection id\n     */\n    public String getCollectionId()\n    {\n        return collectionId;\n    }\n\n    /**\n     * Sets the collection id.\n     * \n     * @param collectionId\n     *            the new collection id\n     */\n    public void setCollectionId(String collectionId)\n    {\n        this.collectionId = collectionId;\n    }\n\n    /**\n     * Gets the collection name.\n     * \n     * @return the collection name\n     */\n    public String getCollectionName()\n    {\n        return collectionName;\n    }\n\n    /**\n     * Sets the collection name.\n     * \n     * @param collectionName\n     *            the new collection name\n     */\n    public void setCollectionName(String collectionName)\n    {\n        this.collectionName = collectionName;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/secondarytable/EmbeddedEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.secondarytable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * The Class EmbeddedEntity.\n * \n * @author Pragalbh Garg\n */\n@Embeddable\npublic class EmbeddedEntity\n{\n\n    /** The email id. */\n    @Column(name = \"EMAIL_ID\", table = \"HBASE_SECONDARY_TABLE\")\n    private String emailId;\n\n    /** The phone no. */\n    @Column(name = \"PHONE_NO\")\n    private long phoneNo;\n\n    /**\n     * Gets the email id.\n     * \n     * @return the email id\n     */\n    public String getEmailId()\n    {\n        return emailId;\n    }\n\n    /**\n     * Sets the email id.\n     * \n     * @param emailId\n     *            the new email id\n     */\n    public void setEmailId(String emailId)\n    {\n        this.emailId = emailId;\n    }\n\n    /**\n     * Gets the phone no.\n     * \n     * @return the phone no\n     */\n    public long getPhoneNo()\n    {\n        return phoneNo;\n    }\n\n    /**\n     * Sets the phone no.\n     * \n     * @param phoneNo\n     *            the new phone no\n     */\n    public void setPhoneNo(long phoneNo)\n    {\n        this.phoneNo = phoneNo;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/secondarytable/HbaseSecondaryTableEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.secondarytable;\n\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.CollectionTable;\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.SecondaryTable;\nimport javax.persistence.SecondaryTables;\nimport javax.persistence.Table;\n\n/**\n * The Class HbaseSecondaryTableEntity.\n * \n * @author Pragalbh Garg\n */\n@Table(name = \"HBASE_TABLE\", schema = \"HBaseNew@secTableTest\")\n@SecondaryTables({ @SecondaryTable(name = \"HBASE_SECONDARY_TABLE\"), @SecondaryTable(name = \"t_country\") })\n@Entity\npublic class HbaseSecondaryTableEntity\n{\n\n    /** The object id. */\n    @Id\n    @Column(name = \"OBJECT_ID\")\n    private String objectId;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /** The age. */\n    @Column(name = \"AGE\", table = \"HBASE_SECONDARY_TABLE\")\n    private int age;\n\n    /** The country. */\n    @Column(name = \"Country\", table = \"t_country\")\n    private String country;\n\n    /** The address. */\n    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private PersonSecondaryTableAddress address;\n\n    /** The embedded entities. */\n    @ElementCollection\n    @CollectionTable(name = \"embeddedEntities\")\n    private List<EmbeddedCollectionEntity> embeddedEntities;\n\n    /** The embedded entity. */\n    @Embedded\n    private EmbeddedEntity embeddedEntity;\n\n    /**\n     * Gets the object id.\n     * \n     * @return the object id\n     */\n    public String getObjectId()\n    {\n        return objectId;\n    }\n\n    /**\n     * Sets the object id.\n     * \n     * @param objectId\n     *            the new object id\n     */\n    public void setObjectId(String objectId)\n    {\n        this.objectId = objectId;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the new name\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * Sets the country.\n     * \n     * @param country\n     *            the new country\n     */\n    public void setCountry(String country)\n    {\n        this.country = country;\n    }\n\n    /**\n     * Gets the country.\n     * \n     * @return the country\n     */\n    public String getCountry()\n    {\n        return this.country;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the new age\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the embedded entity.\n     * \n     * @return the embedded entity\n     */\n    public EmbeddedEntity getEmbeddedEntity()\n    {\n        return embeddedEntity;\n    }\n\n    /**\n     * Sets the embedded entity.\n     * \n     * @param embeddedEntity\n     *            the new embedded entity\n     */\n    public void setEmbeddedEntity(EmbeddedEntity embeddedEntity)\n    {\n        this.embeddedEntity = embeddedEntity;\n    }\n\n    /**\n     * Gets the embedded entities.\n     * \n     * @return the embedded entities\n     */\n    public List<EmbeddedCollectionEntity> getEmbeddedEntities()\n    {\n        return embeddedEntities;\n    }\n\n    /**\n     * Sets the embedded entities.\n     * \n     * @param embeddedEntities\n     *            the new embedded entities\n     */\n    public void setEmbeddedEntities(List<EmbeddedCollectionEntity> embeddedEntities)\n    {\n        this.embeddedEntities = embeddedEntities;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public PersonSecondaryTableAddress getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the new address\n     */\n    public void setAddress(PersonSecondaryTableAddress address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/secondarytable/HbaseSecondaryTableTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.secondarytable;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class HbaseSecondaryTableTest.\n * \n * @author Pragalbh Garg\n */\npublic class HbaseSecondaryTableTest\n{\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"secTableTest\";\n\n    /** The Constant SCHEMA. */\n    private static final String SCHEMA = \"HBaseNew\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        EmbeddedEntity embeddedEntity = new EmbeddedEntity();\n        embeddedEntity.setEmailId(\"kuldeep.mishra@gmail.com\");\n        embeddedEntity.setPhoneNo(9512345346l);\n        List<EmbeddedCollectionEntity> embeddedEntities = new ArrayList<EmbeddedCollectionEntity>();\n\n        EmbeddedCollectionEntity collectionEntity1 = new EmbeddedCollectionEntity();\n        collectionEntity1.setCollectionId(\"c1\");\n        collectionEntity1.setCollectionName(\"Collection 1\");\n        embeddedEntities.add(collectionEntity1);\n\n        EmbeddedCollectionEntity collectionEntity2 = new EmbeddedCollectionEntity();\n        collectionEntity2.setCollectionId(\"c2\");\n        collectionEntity2.setCollectionName(\"Collection 2\");\n        embeddedEntities.add(collectionEntity2);\n\n        HbaseSecondaryTableEntity entity = new HbaseSecondaryTableEntity();\n        entity.setAge(24);\n        entity.setObjectId(\"123\");\n        entity.setName(\"Kuldeep\");\n        entity.setEmbeddedEntity(embeddedEntity);\n        entity.setCountry(\"Canada\");\n        entity.setEmbeddedEntities(embeddedEntities);\n\n        PersonSecondaryTableAddress address = new PersonSecondaryTableAddress(12.23);\n        address.setAddress(\"india\");\n        entity.setAddress(address);\n\n        em.persist(entity);\n        em.clear();\n\n        HbaseSecondaryTableEntity foundEntity = em.find(HbaseSecondaryTableEntity.class, \"123\");\n        Assert.assertNotNull(foundEntity);\n        Assert.assertEquals(\"Kuldeep\", foundEntity.getName());\n        Assert.assertEquals(24, foundEntity.getAge());\n        Assert.assertEquals(\"Canada\", foundEntity.getCountry());\n        Assert.assertNotNull(foundEntity.getEmbeddedEntity());\n        Assert.assertEquals(\"kuldeep.mishra@gmail.com\", foundEntity.getEmbeddedEntity().getEmailId());\n        Assert.assertEquals(9512345346l, foundEntity.getEmbeddedEntity().getPhoneNo());\n        Assert.assertNotNull(foundEntity.getAddress());\n        Assert.assertEquals(\"india\", foundEntity.getAddress().getAddress());\n        Assert.assertEquals(2, foundEntity.getEmbeddedEntities().size());\n        Assert.assertEquals(\"Collection 1\", foundEntity.getEmbeddedEntities().get(0).getCollectionName());\n        Assert.assertEquals(\"Collection 2\", foundEntity.getEmbeddedEntities().get(1).getCollectionName());\n\n        foundEntity.setAge(25);\n        foundEntity.setName(\"kk\");\n        foundEntity.getEmbeddedEntity().setEmailId(\"kuldeep.mishra@yahoo.com\");\n\n        em.merge(foundEntity);\n\n        em.clear();\n\n        foundEntity = em.find(HbaseSecondaryTableEntity.class, \"123\");\n        Assert.assertNotNull(foundEntity);\n        Assert.assertEquals(\"kk\", foundEntity.getName());\n        Assert.assertEquals(25, foundEntity.getAge());\n        Assert.assertNotNull(foundEntity.getEmbeddedEntity());\n        Assert.assertEquals(\"kuldeep.mishra@yahoo.com\", foundEntity.getEmbeddedEntity().getEmailId());\n        Assert.assertEquals(9512345346l, foundEntity.getEmbeddedEntity().getPhoneNo());\n\n        em.remove(foundEntity);\n\n        foundEntity = em.find(HbaseSecondaryTableEntity.class, \"123\");\n        Assert.assertNull(foundEntity);\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/secondarytable/PersonSecondaryTableAddress.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.secondarytable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class PersonSecondaryTableAddress.\n * \n * @author Pragalbh Garg\n */\n@Entity\n@Table(name = \"SEC_TABLE\", schema = \"HBaseNew@secTableTest\")\npublic class PersonSecondaryTableAddress\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private Double addressId;\n\n    /**\n     * Instantiates a new person secondary table address.\n     */\n    public PersonSecondaryTableAddress()\n    {\n\n    }\n\n    /**\n     * Instantiates a new person secondary table address.\n     * \n     * @param addressId\n     *            the address id\n     */\n    public PersonSecondaryTableAddress(Double addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /** The address. */\n    @Column(name = \"address\")\n    private String address;\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the new address\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public Double getAddressId()\n    {\n        return addressId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/testingutil/HBaseTestingUtils.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.testingutil;\n\nimport java.io.IOException;\n\nimport org.apache.hadoop.hbase.client.Connection;\nimport org.apache.hadoop.hbase.client.ConnectionFactory;\nimport org.apache.hadoop.hbase.client.HBaseAdmin;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * The Class HBaseTestingUtils.\n * \n * @author Pragalbh Garg\n */\npublic final class HBaseTestingUtils\n{\n\n    /**\n     * Drop schema.\n     * \n     * @param databaseName\n     *            the database name\n     */\n    public static void dropSchema(String databaseName)\n    {\n        try\n        {\n            Connection connection = ConnectionFactory.createConnection();\n            try\n            {\n                HBaseAdmin admin = (HBaseAdmin) connection.getAdmin();\n                admin.disableTables(databaseName + \":.*\");\n                admin.deleteTables(databaseName + \":.*\");\n                admin.deleteNamespace(databaseName);\n            }\n            catch (Exception e)\n            {\n                // do nothing\n            }\n            finally\n            {\n                connection.close();\n            }\n        }\n        catch (IOException e)\n        {\n            throw new KunderaException(\"Could not connect to database, caused by:\", e);\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/transaction/HBaseTransactionTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.transaction;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class HBaseTransactionTest.\n * \n * @author Devender Yadav\n */\npublic class HBaseTransactionTest\n{\n    /** The Constant SCHEMA. */\n    private static final String SCHEMA = \"HBaseNew\";\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"transactionTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * On commit.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onCommit() throws Exception\n    {\n        em.getTransaction().begin();\n        persistUsers();\n        em.getTransaction().commit();\n\n        em.clear();\n        User user = em.find(User.class, \"1\");\n        Assert.assertNotNull(user);\n        Assert.assertEquals(\"1\", user.getId());\n        Assert.assertEquals(\"dev\", user.getName());\n        Assert.assertEquals(20, user.getAge());\n\n        user = em.find(User.class, \"2\");\n        Assert.assertNotNull(user);\n        Assert.assertEquals(\"2\", user.getId());\n        Assert.assertEquals(\"amit\", user.getName());\n        Assert.assertEquals(25, user.getAge());\n\n        user = em.find(User.class, \"3\");\n        Assert.assertNotNull(user);\n        Assert.assertEquals(\"3\", user.getId());\n        Assert.assertEquals(\"vivek\", user.getName());\n        Assert.assertEquals(30, user.getAge());\n\n        em.getTransaction().begin();\n        user = em.find(User.class, \"1\");\n        user.setName(\"pragalbh\");\n        em.merge(user);\n        em.getTransaction().commit();\n\n        Assert.assertEquals(\"pragalbh\", user.getName());\n\n    }\n\n    /**\n     * On rollback after persist.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onRollbackAfterPersist() throws Exception\n    {\n        em.getTransaction().begin();\n        persistUsers();\n        em.getTransaction().rollback();\n        em.clear();\n        User user = em.find(User.class, \"1\");\n        Assert.assertNull(user);\n        user = em.find(User.class, \"2\");\n        Assert.assertNull(user);\n        user = em.find(User.class, \"3\");\n        Assert.assertNull(user);\n\n    }\n\n    /**\n     * On rollback after merge.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onRollbackAfterMerge() throws Exception\n    {\n\n        em.getTransaction().begin();\n        persistUsers();\n        em.getTransaction().commit();\n        em.clear();\n\n        em.getTransaction().begin();\n        User user = em.find(User.class, \"1\");\n        user.setName(\"pragalbh\");\n        em.merge(user);\n        em.getTransaction().rollback();\n        em.clear();\n\n        user = em.find(User.class, \"1\");\n        Assert.assertEquals(\"dev\", user.getName());\n        Assert.assertNotSame(\"pragalbh\", user.getName());\n    }\n\n    /**\n     * Rollback on error.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void rollbackOnError() throws Exception\n    {\n        try\n        {\n            em.getTransaction().begin();\n            persistUsers();\n            em.merge(null);\n            em.getTransaction().commit();\n        }\n        catch (Exception ex)\n        {\n            em.clear();\n            User user = em.find(User.class, \"1\");\n            Assert.assertNull(user);\n            user = em.find(User.class, \"2\");\n            Assert.assertNull(user);\n            user = em.find(User.class, \"3\");\n            Assert.assertNull(user);\n        }\n    }\n\n    /**\n     * Roll back with multi transactions.\n     */\n    @Test\n    public void rollBackWithMultiTransactions()\n    {\n        em.getTransaction().begin();\n        persistUsers();\n        em.getTransaction().commit();\n        em.clear();\n\n        EntityManager em1 = emf.createEntityManager();\n\n        User user = em1.find(User.class, \"1\");\n        em1.getTransaction().begin();\n        user.setName(\"pragalbh\");\n        em1.merge(user);\n        em1.getTransaction().commit();\n\n        EntityManager em2 = emf.createEntityManager();\n        user = em2.find(User.class, \"1\");\n        Assert.assertEquals(\"pragalbh\", user.getName());\n        user.setName(\"karthik\");\n        try\n        {\n            em2.merge(user);\n            em2.merge(null);\n        }\n        catch (Exception ex)\n        {\n            EntityManager em3 = emf.createEntityManager();\n            User userNew = em3.find(User.class, \"1\");\n            Assert.assertNotNull(userNew);\n            Assert.assertEquals(\"pragalbh\", userNew.getName());\n        }\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param id\n     *            the id\n     * @param name\n     *            the name\n     * @param age\n     *            the age\n     * @return the user\n     */\n    private User prepareData(String id, String name, int age)\n    {\n        User user = new User();\n        user.setId(id);\n        user.setName(name);\n        user.setAge(age);\n        return user;\n    }\n\n    /**\n     * Persist users.\n     */\n    private void persistUsers()\n    {\n        Object user1 = prepareData(\"1\", \"dev\", 20);\n        Object user2 = prepareData(\"2\", \"amit\", 25);\n        Object user3 = prepareData(\"3\", \"vivek\", 30);\n        em.persist(user1);\n        em.persist(user2);\n        em.persist(user3);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        String deleteQuery = \"Delete from User u\";\n        em.createQuery(deleteQuery).executeUpdate();\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/transaction/User.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.hbase.transaction;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class User.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"USER\", schema = \"HBaseNew@transactionTest\")\npublic class User\n{\n\n    /** The id. */\n    @Id\n    @Column(name = \"ID\")\n    private String id;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private int age;\n\n    /**\n     * Instantiates a new user.\n     */\n    public User()\n    {\n    }\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the new id\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the new name\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the new age\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/validator/BookEntity.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.hbase.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class BookEntity.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"BOOK_ENTITY\", schema = \"HBaseNew@queryTest\")\npublic class BookEntity\n{\n\n    /** The book id. */\n    @Id\n    @Column(name = \"ID\")\n    private int bookId;\n\n    /** The title. */\n    @Column(name = \"TITLE\")\n    private String title;\n\n    /** The author. */\n    @Column(name = \"AUTHOR\")\n    private String author;\n\n    /** The pages. */\n    @Column(name = \"PAGES\")\n    private int pages;\n\n    /**\n     * Instantiates a new book entity.\n     */\n    protected BookEntity()\n    {\n    }\n\n    /**\n     * Gets the book id.\n     * \n     * @return the book id\n     */\n    public int getBookId()\n    {\n        return bookId;\n    }\n\n    /**\n     * Sets the book id.\n     * \n     * @param bookId\n     *            the new book id\n     */\n    public void setBookId(int bookId)\n    {\n        this.bookId = bookId;\n    }\n\n    /**\n     * Gets the title.\n     * \n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * Sets the title.\n     * \n     * @param title\n     *            the new title\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * Gets the author.\n     * \n     * @return the author\n     */\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    /**\n     * Sets the author.\n     * \n     * @param author\n     *            the new author\n     */\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    /**\n     * Gets the pages.\n     * \n     * @return the pages\n     */\n    public int getPages()\n    {\n        return pages;\n    }\n\n    /**\n     * Sets the pages.\n     * \n     * @param pages\n     *            the new pages\n     */\n    public void setPages(int pages)\n    {\n        this.pages = pages;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/validator/ConstructorValidationTest.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.hbase.validator;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class ConstructorValidationTest.\n * \n * @author Devender Yadav\n */\npublic class ConstructorValidationTest\n{\n    /** The Constant SCHEMA. */\n    private static final String SCHEMA = \"HBaseNew\";\n\n    /** The Constant HBASE_PU. */\n    private static final String HBASE_PU = \"queryTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Valid constructor test.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void validConstructorTest() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n        em = emf.createEntityManager();\n        BookEntity book = new BookEntity();\n        book.setBookId(1);\n        book.setTitle(\"The Complete Reference\");\n        book.setAuthor(\"Herbert Schildt\");\n        book.setPages(500);\n\n        em.persist(book);\n\n        em.clear();\n\n        BookEntity book1 = em.find(BookEntity.class, 1);\n\n        Assert.assertNotNull(book1);\n        Assert.assertEquals(1, book1.getBookId());\n        Assert.assertEquals(\"The Complete Reference\", book1.getTitle());\n        Assert.assertEquals(\"Herbert Schildt\", book1.getAuthor());\n        Assert.assertEquals(500, book1.getPages());\n\n        em.remove(book1);\n\n        BookEntity book2 = em.find(BookEntity.class, 1);\n        Assert.assertNull(book2);\n\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/query/Book.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.query;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Book.\n * \n * @author Pragalbh Garg\n */\n@Entity\n@Table(name = \"BOOKS\", schema = \"HBaseNew@queryTest\")\n@IndexCollection(columns = { @Index(name = \"title\"), @Index(name = \"author\"), @Index(name = \"year\"),\n        @Index(name = \"pages\") })\npublic class Book\n{\n    /** The book_id. */\n    @Id\n    @Column(name = \"ID\")\n    private int bookId;\n\n    /** The title. */\n    @Column(name = \"TITLE\")\n    private String title;\n\n    /** The author. */\n    @Column(name = \"AUTHOR\")\n    private String author;\n\n    /** The year. */\n    @Column(name = \"YEAR\")\n    private int year;\n\n    /** The pages. */\n    @Column(name = \"PAGES\")\n    private int pages;\n\n    /**\n     * Gets the book id.\n     * \n     * @return the book id\n     */\n    public int getBookId()\n    {\n        return bookId;\n    }\n\n    /**\n     * Sets the book id.\n     * \n     * @param bookId\n     *            the new book id\n     */\n    public void setBookId(int bookId)\n    {\n        this.bookId = bookId;\n    }\n\n    /**\n     * Gets the title.\n     * \n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * Sets the title.\n     * \n     * @param title\n     *            the new title\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * Gets the author.\n     * \n     * @return the author\n     */\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    /**\n     * Sets the author.\n     * \n     * @param author\n     *            the new author\n     */\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    /**\n     * Gets the year.\n     * \n     * @return the year\n     */\n    public int getYear()\n    {\n        return year;\n    }\n\n    /**\n     * Sets the year.\n     * \n     * @param year\n     *            the new year\n     */\n    public void setYear(int year)\n    {\n        this.year = year;\n    }\n\n    /**\n     * Gets the pages.\n     * \n     * @return the pages\n     */\n    public int getPages()\n    {\n        return pages;\n    }\n\n    /**\n     * Sets the pages.\n     * \n     * @param pages\n     *            the new pages\n     */\n    public void setPages(int pages)\n    {\n        this.pages = pages;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/query/BookBaseTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.query;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\n\nimport junit.framework.Assert;\n\n/**\n * The Class BookBaseTest.\n * \n * @author Pragalbh Garg\n */\npublic abstract class BookBaseTest\n{\n\n    /** The Constant SCHEMA. */\n    protected static final String SCHEMA = \"HBaseNew\";\n\n    /** The Constant HBASE_PU. */\n    protected static final String HBASE_PU = \"queryTest\";\n\n    /** The emf. */\n    protected static EntityManagerFactory emf;\n\n    /** The em. */\n    protected EntityManager em;\n\n    /** The t. */\n    protected boolean T = true;\n\n    /** The f. */\n    protected boolean F = false;\n\n    /**\n     * Persist books.\n     */\n    protected void persistBooks()\n    {\n        Book book1 = prepareData(1, \"book1\", \"author1\", 2000, 100);\n        Book book2 = prepareData(2, \"book2\", \"author2\", 2005, 200);\n        Book book3 = prepareData(3, \"book3\", \"author3\", 2010, 300);\n        Book book4 = prepareData(4, \"book4\", \"author1\", 2015, 400);\n        em.persist(book1);\n        em.persist(book2);\n        em.persist(book3);\n        em.persist(book4);\n        em.clear();\n    }\n\n    /**\n     * Delete books.\n     */\n    protected void deleteBooks()\n    {\n        em.createQuery(\"delete from Book b\").executeUpdate();\n        em.clear();\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param bookId\n     *            the book id\n     * @param title\n     *            the title\n     * @param author\n     *            the author\n     * @param year\n     *            the year\n     * @param pages\n     *            the pages\n     * @return the book\n     */\n    protected Book prepareData(int bookId, String title, String author, int year, int pages)\n    {\n        Book book = new Book();\n        book.setBookId(bookId);\n        book.setTitle(title);\n        book.setAuthor(author);\n        book.setYear(year);\n        book.setPages(pages);\n        return book;\n    }\n\n    /**\n     * Validate book1.\n     * \n     * @param book\n     *            the book\n     */\n    protected void validateBook1(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(1, book.getBookId());\n        Assert.assertEquals(\"book1\", book.getTitle());\n        Assert.assertEquals(\"author1\", book.getAuthor());\n        Assert.assertEquals(2000, book.getYear());\n        Assert.assertEquals(100, book.getPages());\n    }\n\n    /**\n     * Validate book2.\n     * \n     * @param book\n     *            the book\n     */\n    protected void validateBook2(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(2, book.getBookId());\n        Assert.assertEquals(\"book2\", book.getTitle());\n        Assert.assertEquals(\"author2\", book.getAuthor());\n        Assert.assertEquals(2005, book.getYear());\n        Assert.assertEquals(200, book.getPages());\n    }\n\n    /**\n     * Validate book3.\n     * \n     * @param book\n     *            the book\n     */\n    protected void validateBook3(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(3, book.getBookId());\n        Assert.assertEquals(\"book3\", book.getTitle());\n        Assert.assertEquals(\"author3\", book.getAuthor());\n        Assert.assertEquals(2010, book.getYear());\n        Assert.assertEquals(300, book.getPages());\n    }\n\n    /**\n     * Validate book4.\n     * \n     * @param book\n     *            the book\n     */\n    protected void validateBook4(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(4, book.getBookId());\n        Assert.assertEquals(\"book4\", book.getTitle());\n        Assert.assertEquals(\"author1\", book.getAuthor());\n        Assert.assertEquals(2015, book.getYear());\n        Assert.assertEquals(400, book.getPages());\n    }\n\n    /**\n     * Assert results.\n     * \n     * @param results\n     *            the results\n     * @param foundBook1\n     *            the found book1\n     * @param foundBook2\n     *            the found book2\n     * @param foundBook3\n     *            the found book3\n     * @param foundBook4\n     *            the found book4\n     */\n    protected void assertResults(List<Book> results, boolean foundBook1, boolean foundBook2, boolean foundBook3,\n            boolean foundBook4)\n    {\n        for (Book book : (List<Book>) results)\n        {\n            switch (book.getBookId())\n            {\n            case 1:\n                if (foundBook1)\n                    validateBook1(book);\n                else\n                    Assert.fail();\n                break;\n            case 2:\n                if (foundBook2)\n                    validateBook2(book);\n                else\n                    Assert.fail();\n                break;\n            case 3:\n                if (foundBook3)\n                    validateBook3(book);\n                else\n                    Assert.fail();\n                break;\n            case 4:\n                if (foundBook4)\n                    validateBook4(book);\n                else\n                    Assert.fail();\n                break;\n            }\n        }\n    }\n\n    /**\n     * Assert deleted.\n     * \n     * @param foundBook1\n     *            the b1\n     * @param foundBook2\n     *            the b2\n     * @param foundBook3\n     *            the b3\n     * @param foundBook4\n     *            the b4\n     */\n    protected void assertDeleted(Boolean foundBook1, Boolean foundBook2, Boolean foundBook3, Boolean foundBook4)\n    {\n        Book book1 = em.find(Book.class, 1);\n        Book book2 = em.find(Book.class, 2);\n        Book book3 = em.find(Book.class, 3);\n        Book book4 = em.find(Book.class, 4);\n        if (foundBook1)\n        {\n            Assert.assertNull(book1);\n        }\n        else\n        {\n            Assert.assertNotNull(book1);\n        }\n        if (foundBook2)\n        {\n            Assert.assertNull(book2);\n        }\n        else\n        {\n            Assert.assertNotNull(book2);\n        }\n        if (foundBook3)\n        {\n            Assert.assertNull(book3);\n        }\n        else\n        {\n            Assert.assertNotNull(book3);\n        }\n        if (foundBook4)\n        {\n            Assert.assertNull(book4);\n        }\n        else\n        {\n            Assert.assertNotNull(book4);\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/query/HBaseESQueryTest.java",
    "content": "///*******************************************************************************\n// * * Copyright 2015 Impetus Infotech.\n// *  *\n// *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n// *  * you may not use this file except in compliance with the License.\n// *  * You may obtain a copy of the License at\n// *  *\n// *  *      http://www.apache.org/licenses/LICENSE-2.0\n// *  *\n// *  * Unless required by applicable law or agreed to in writing, software\n// *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n// *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// *  * See the License for the specific language governing permissions and\n// *  * limitations under the License.\n// ******************************************************************************/\n//package com.impetus.client.query;\n//\n//import java.io.IOException;\n//import java.net.Socket;\n//import java.net.UnknownHostException;\n//import java.util.HashMap;\n//import java.util.List;\n//import java.util.Map;\n//\n//import javax.persistence.Persistence;\n//\n//import org.elasticsearch.common.settings.Settings;\n//import org.elasticsearch.common.settings.Settings.Builder;\n//import org.elasticsearch.node.Node;\n//import org.elasticsearch.node.NodeBuilder;\n//import org.junit.After;\n//import org.junit.AfterClass;\n//import org.junit.Before;\n//import org.junit.BeforeClass;\n//import org.junit.Test;\n//\n//import com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n//import com.impetus.kundera.utils.LuceneCleanupUtilities;\n//\n//import junit.framework.Assert;\n//\n///**\n// * The Class HBaseESQueryTest.\n// * \n// * @author Devender Yadav\n// */\n//public class HBaseESQueryTest extends HBaseQueryBaseTest\n//{\n//\n//    /** The property map. */\n//    private static Map<String, String> propertyMap = new HashMap<String, String>();\n//\n//    /** The node. */\n//    private static Node node = null;\n//\n//    /**\n//     * Sets the up before class.\n//     * \n//     * @throws Exception\n//     *             the exception\n//     */\n//    @BeforeClass\n//    public static void setUpBeforeClass() throws Exception\n//    {\n//\n//        propertyMap.put(\"kundera.indexer.class\", \"com.impetus.client.es.index.ESIndexer\");\n//        \n//\n//        if (!checkIfServerRunning())\n//        {\n//            Builder builder = Settings.settingsBuilder();\n//            builder.put(\"path.home\", \"target/data\");\n//            node = new NodeBuilder().settings(builder).node();\n//        }\n//    } \n//\n//    /*\n//     * (non-Javadoc)\n//     * \n//     * @see com.impetus.client.query.HBaseQueryBaseTest#setUp()\n//     */\n//    @Before\n//    public void setUp() throws Exception\n//    {\n//    \temf = Persistence.createEntityManagerFactory(HBASE_PU, propertyMap);\n//        em = emf.createEntityManager();\n//        persistBooks();\n//        \n//    }\n//\n//    /*\n//     * (non-Javadoc)\n//     * \n//     * @see com.impetus.client.query.HBaseQueryBaseTest#tearDown()\n//     */\n//    @After\n//    public void tearDown() throws Exception\n//    {\n//        deleteBooks();\n//        em.close();\n//        emf.close();\n//        emf = null;\n//    }\n//\n//    /**\n//     * Tear down after class.\n//     * \n//     * @throws Exception\n//     *             the exception\n//     */\n//    @AfterClass\n//    public static void tearDownAfterClass() throws Exception\n//    {\n//        if (node != null)\n//            node.close();\n//        \n//        HBaseTestingUtils.dropSchema(SCHEMA);\n//        LuceneCleanupUtilities.cleanDir(\"target/data\");\n//    }\n//\n//    /**\n//     * Check if server running.\n//     * \n//     * @return true, if successful\n//     */\n//    private static boolean checkIfServerRunning()\n//    {\n//        try\n//        {\n//            Socket socket = new Socket(\"127.0.0.1\", 9300);\n//            return socket.getInetAddress() != null;\n//        }\n//        catch (UnknownHostException e)\n//        {\n//            return false;\n//        }\n//        catch (IOException e)\n//        {\n//            return false;\n//        }\n//    }\n//\n//    /**\n//     * Aggregation test.\n//     * \n//     * @throws Exception\n//     *             the exception\n//     */\n//    @Test\n//    public void aggregationTest() throws Exception\n//    {\n//        minAggregation();\n//        minAggregationError();\n//        multiMinAggregation();\n//        minAggregationWithWhere();\n//        multiMinAggregationWithWhere();\n//        maxAggregation();\n//        multiMaxAggregation();\n//        maxAggregationWithWhere();\n//        multiMaxAggregationWithWhere();\n//        maxMinSameFieldAggregation();\n//        maxMinDiffFieldAggregation();\n//        multiMaxMinAggregation();\n//        sumAggregation();\n//        sumAggregationWithWhere();\n//        multiSumAggregation();\n//        multiSumAggregationWithWhere();\n//        avgAggregation();\n//        avgAggregationWithWhere();\n//        multiAvgAggregation();\n//        multiAvgAggregationWithWhere();\n//        minMaxSumAvgAggregation();\n//    }\n//    \n//    @Test\n//    public void indexDeletionTest() throws Exception\n//    {\n//        Thread.sleep(1000);\n//        String query = \"Select min(b.pages) from Book b\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 100.0);\n//        \n//        Book book = em.find(Book.class, 1);\n//        em.remove(book);\n//        Thread.sleep(1000);\n//        query = \"Select min(b.pages) from Book b\";\n//        resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 200.0);\n//        \n//        book = em.find(Book.class, 2);\n//        em.remove(book);\n//        Thread.sleep(1000);\n//        query = \"Select min(b.pages) from Book b\";\n//        resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 300.0);\n//    }\n//\n//    /**\n//     * Min aggregation.\n//     */\n//    public void minAggregation()\n//    {\n//        String query = \"Select min(b.pages) from Book b\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 100.0);\n//    }\n//\n//    /**\n//     * Min aggregation error.\n//     */\n//    public void minAggregationError()\n//    {\n//        String query = \"Select min(b.title)from Book b\";\n//        try\n//        {\n//            List resultList = em.createQuery(query).getResultList();\n//            Assert.fail();\n//        }\n//        catch (Exception ex)\n//        {\n//            Assert.assertEquals(\"Exception occured while executing query on Elasticsearch.\", ex.getMessage());\n//        }\n//    }\n//\n//    /**\n//     * Min aggregation with where.\n//     */\n//    private void minAggregationWithWhere()\n//    {\n//        String query = \"Select min(b.pages) from Book b where b.year>2005\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 300.0);\n//    }\n//\n//    /**\n//     * Multi min aggregation.\n//     */\n//    public void multiMinAggregation()\n//    {\n//        String query = \"Select min(b.pages), min(b.year) from Book b\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 100.0, 2000.0);\n//    }\n//\n//    /**\n//     * Multi min aggregation with where.\n//     */\n//    private void multiMinAggregationWithWhere()\n//    {\n//        String query = \"Select min(b.pages), min(b.year) from Book b where b.pages > 200\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 300.0, 2010.0);\n//    }\n//\n//    /**\n//     * Max aggregation.\n//     */\n//    public void maxAggregation()\n//    {\n//        String query = \"Select max(b.pages) from Book b\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 400.0);\n//    }\n//\n//    /**\n//     * Max aggregation with where.\n//     */\n//    private void maxAggregationWithWhere()\n//    {\n//        String query = \"Select max(b.pages) from Book b where b.year<2010\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 200.0);\n//    }\n//\n//    /**\n//     * Multi max aggregation.\n//     */\n//    public void multiMaxAggregation()\n//    {\n//        String query = \"Select max(b.pages), max(b.year) from Book b\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 400.0, 2015.0);\n//\n//    }\n//\n//    /**\n//     * Multi max aggregation with where.\n//     */\n//    private void multiMaxAggregationWithWhere()\n//    {\n//        String query = \"Select max(b.pages), max(b.year) from Book b where b.pages < 300\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 200.0, 2005.0);\n//    }\n//\n//    /**\n//     * Max min same field aggregation.\n//     */\n//    public void maxMinSameFieldAggregation()\n//    {\n//        String query = \"Select max(b.pages), min(b.pages) from Book b\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 400.0, 100.0);\n//    }\n//\n//    /**\n//     * Max min diff field aggregation.\n//     */\n//    public void maxMinDiffFieldAggregation()\n//    {\n//        String query = \"Select max(b.pages), min(b.year) from Book b\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 400.0, 2000.0);\n//    }\n//\n//    /**\n//     * Multi max min aggregation.\n//     */\n//    public void multiMaxMinAggregation()\n//    {\n//        String query = \"Select max(b.pages), min(b.year), min(b.pages) from Book b\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 400.0, 2000.0, 100.0);\n//    }\n//\n//    /**\n//     * Sum aggregation.\n//     */\n//    public void sumAggregation()\n//    {\n//        String query = \"Select sum(b.pages) from Book b\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 1000.0);\n//    }\n//\n//    /**\n//     * Sum aggregation with where.\n//     */\n//    private void sumAggregationWithWhere()\n//    {\n//        String query = \"Select sum(b.pages) from Book b where b.year>2005\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 700.0);\n//    }\n//\n//    /**\n//     * Multi sum aggregation.\n//     */\n//    public void multiSumAggregation()\n//    {\n//        String query = \"Select sum(b.pages), sum(b.year) from Book b\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 1000.0, 8030.0);\n//    }\n//\n//    /**\n//     * Multi sum aggregation with where.\n//     */\n//    private void multiSumAggregationWithWhere()\n//    {\n//        String query = \"Select sum(b.pages), sum(b.year) from Book b where b.pages > 200\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 700.0, 4025.0);\n//    }\n//\n//    /**\n//     * Avg aggregation.\n//     */\n//    public void avgAggregation()\n//    {\n//        String query = \"Select avg(b.pages) from Book b\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 250.0);\n//    }\n//\n//    /**\n//     * Avg aggregation with where.\n//     */\n//    private void avgAggregationWithWhere()\n//    {\n//        String query = \"Select avg(b.pages) from Book b where b.year>2005\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 350.0);\n//    }\n//\n//    /**\n//     * Multi avg aggregation.\n//     */\n//    public void multiAvgAggregation()\n//    {\n//        String query = \"Select avg(b.pages), avg(b.year) from Book b\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 250.0, 2007.5);\n//    }\n//\n//    /**\n//     * Multi avg aggregation with where.\n//     */\n//    private void multiAvgAggregationWithWhere()\n//    {\n//        String query = \"Select avg(b.pages), avg(b.year) from Book b where b.pages > 200\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 350.0, 2012.5);\n//    }\n//\n//    /**\n//     * Min max sum avg aggregation.\n//     */\n//    public void minMaxSumAvgAggregation()\n//    {\n//        String query = \"Select min(b.pages), max(b.year), sum(b.pages), avg(b.year) from Book b\";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 100.0, 2015.0, 1000.0, 2007.5);\n//    }\n//\n//    /**\n//     * Min max sum avg aggregation with where.\n//     */\n//    public void minMaxSumAvgAggregationWithWhere()\n//    {\n//        String query = \"Select min(b.pages), max(b.year), sum(b.pages), avg(b.year) from Book b where b.pages > 100 \";\n//        List resultList = em.createQuery(query).getResultList();\n//        assertES(resultList, 200.0, 2015.0, 900.0, 2010.0);\n//    }\n//\n//    /**\n//     * Assert es.\n//     * \n//     * @param resultList\n//     *            the result list\n//     * @param value\n//     *            the value\n//     */\n//    public void assertES(List resultList, double value)\n//    {\n//        Assert.assertEquals(1, resultList.size());\n//        Assert.assertEquals(value, resultList.get(0));\n//    }\n//\n//    /**\n//     * Assert es.\n//     * \n//     * @param resultList\n//     *            the result list\n//     * @param value1\n//     *            the value1\n//     * @param value2\n//     *            the value2\n//     */\n//    public void assertES(List resultList, double value1, double value2)\n//    {\n//        Assert.assertEquals(2, resultList.size());\n//        Assert.assertEquals(value1, resultList.get(0));\n//        Assert.assertEquals(value2, resultList.get(1));\n//    }\n//\n//    /**\n//     * Assert es.\n//     * \n//     * @param resultList\n//     *            the result list\n//     * @param value1\n//     *            the value1\n//     * @param value2\n//     *            the value2\n//     * @param value3\n//     *            the value3\n//     */\n//    public void assertES(List resultList, double value1, double value2, double value3)\n//    {\n//        Assert.assertEquals(3, resultList.size());\n//        Assert.assertEquals(value1, resultList.get(0));\n//        Assert.assertEquals(value2, resultList.get(1));\n//        Assert.assertEquals(value3, resultList.get(2));\n//    }\n//\n//    /**\n//     * Assert es.\n//     * \n//     * @param resultList\n//     *            the result list\n//     * @param value1\n//     *            the value1\n//     * @param value2\n//     *            the value2\n//     * @param value3\n//     *            the value3\n//     * @param value4\n//     *            the value4\n//     */\n//    public void assertES(List resultList, double value1, double value2, double value3, double value4)\n//    {\n//        Assert.assertEquals(4, resultList.size());\n//        Assert.assertEquals(value1, resultList.get(0));\n//        Assert.assertEquals(value2, resultList.get(1));\n//        Assert.assertEquals(value3, resultList.get(2));\n//        Assert.assertEquals(value4, resultList.get(3));\n//    }\n//\n//    /*\n//     * (non-Javadoc)\n//     * \n//     * @see com.impetus.client.query.BookBaseTest#persistBooks()\n//     */\n//    protected void persistBooks()\n//    {\n//        Book book1 = prepareData(1, \"book1\", \"author1\", 2000, 100);\n//        Book book2 = prepareData(2, \"book2\", \"author2\", 2005, 200);\n//        Book book3 = prepareData(3, \"book3\", \"author3\", 2010, 300);\n//        Book book4 = prepareData(4, \"book4\", \"author1\", 2015, 400);\n//        em.persist(book1);\n//        em.persist(book2);\n//        em.persist(book3);\n//        em.persist(book4);\n//        em.clear();\n//        try\n//        {\n//            Thread.sleep(1000);\n//        }\n//        catch (InterruptedException e)\n//        {\n//            e.printStackTrace();\n//        }\n//    }\n//\n//}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/query/HBaseGroupByTest.java",
    "content": "///*******************************************************************************\n// *  * Copyright 2015 Impetus Infotech.\n// *  *\n// *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n// *  * you may not use this file except in compliance with the License.\n// *  * You may obtain a copy of the License at\n// *  *\n// *  *      http://www.apache.org/licenses/LICENSE-2.0\n// *  *\n// *  * Unless required by applicable law or agreed to in writing, software\n// *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n// *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// *  * See the License for the specific language governing permissions and\n// *  * limitations under the License.\n// ******************************************************************************/\n//package com.impetus.client.query;\n//\n//import java.util.HashMap;\n//import java.util.Map;\n//\n//import javax.persistence.Persistence;\n//\n//import org.elasticsearch.common.settings.Settings;\n//import org.elasticsearch.common.settings.Settings.Builder;\n//import org.elasticsearch.node.Node;\n//import org.elasticsearch.node.NodeBuilder;\n//import org.junit.AfterClass;\n//import org.junit.BeforeClass;\n//import org.junit.Test;\n//\n//import com.impetus.kundera.client.query.GroupByBaseTest;\n//\n///**\n// * The Class HBaseGroupByTest.\n// * \n// * @author: karthikp.manchala\n// */\n//public class HBaseGroupByTest extends GroupByBaseTest\n//{\n//    /** The node. */\n//    private static Node node = null;\n//\n//    /** The property map. */\n//    private static Map<String, String> propertyMap = new HashMap<String, String>();\n//\n//    /**\n//     * Sets the up before class.\n//     * \n//     * @throws Exception\n//     *             the exception\n//     */\n//    @BeforeClass\n//    public static void setUpBeforeClass() throws Exception\n//    {\n//        if (!checkIfServerRunning())\n//        {\n//            Builder builder = Settings.settingsBuilder();\n//            builder.put(\"path.home\", \"target/data\");\n//            node = new NodeBuilder().settings(builder).node();\n//        }\n//        propertyMap.put(\"kundera.indexer.class\", \"com.impetus.client.es.index.ESIndexer\");\n//        emf = Persistence.createEntityManagerFactory(\"queryTest\", propertyMap);\n//        em = emf.createEntityManager();\n//        init();\n//    }\n//\n//    /**\n//     * Test aggregation.\n//     */\n//    @Test\n//    public void test()\n//    {\n//        testAggregation();\n//    }\n//\n//    /**\n//     * Tear down after class.\n//     * \n//     * @throws Exception\n//     *             the exception\n//     */\n//    @AfterClass\n//    public static void tearDownAfterClass() throws Exception\n//    {\n//        em.createQuery(\"Delete from Person p\").executeUpdate();\n//        waitThread();\n//\n//        em.close();\n//        emf.close();\n//\n//        if (node != null)\n//            node.close();\n//    }\n//\n//}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/query/HBaseLuceneQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.query;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * The Class HBaseLuceneQueryTest.\n * \n * @author Devender Yadav\n */\npublic class HBaseLuceneQueryTest extends HBaseQueryBaseTest\n{\n\n    /** The property map. */\n    private static Map<String, String> propertyMap = new HashMap<String, String>();\n\n    /**\n     * Sets the up before class.\n     */\n    @BeforeClass\n    public static void setUpBeforeClass()\n    {\n        propertyMap.put(\"index.home.dir\", \"lucene\");\n        emf = Persistence.createEntityManagerFactory(HBASE_PU, propertyMap);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n        persistBooks();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.client.query.HBaseQueryBaseTest#tearDown()\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        deleteBooks();\n        LuceneCleanupUtilities.cleanDir(\"lucene\");\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n\n    /**\n     * Lucene test.\n     */\n    @Test\n    public void luceneTest()\n    {\n        likeQueryTest();\n    }\n\n    /**\n     * Like query test.\n     */\n    private void likeQueryTest()\n    {\n        Book b1 = prepareData(11, \"TO THE LIGHTHOUSE\", \"Virginia Woolf\", 1927, 100);\n        Book b2 = prepareData(12, \"The House Of Mirth\", \"Edith Wharton\", 1905, 200);\n        Book b3 = prepareData(13, \"under the volcano\", \"Malcolm Lowry\", 1947, 300);\n        em.persist(b1);\n        em.persist(b2);\n        em.persist(b3);\n        em.clear();\n\n        String qry = \"Select b from Book b where b.title like :title\";\n        Query q = em.createQuery(qry);\n        q.setParameter(\"title\", \"volcano\");\n        List<Book> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        assertBook3(results.get(0));\n\n        qry = \"Select b from Book b where b.title like :title\";\n        q = em.createQuery(qry);\n        q.setParameter(\"title\", \"House\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        for (Book book : results)\n        {\n            if (book.getBookId() == 11)\n            {\n                assertBook1(book);\n            }\n\n            else if (book.getBookId() == 12)\n            {\n                assertBook2(book);\n            }\n        }\n\n        qry = \"Select b from Book b where b.title like :title\";\n        q = em.createQuery(qry);\n        q.setParameter(\"title\", \"%der\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        assertBook3(results.get(0));\n\n        qry = \"Select b from Book b where b.title like :title\";\n        q = em.createQuery(qry);\n        q.setParameter(\"title\", \"und%\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        assertBook3(results.get(0));\n\n        qry = \"Select b from Book b where b.author like :author\";\n        q = em.createQuery(qry);\n        q.setParameter(\"author\", \"Lowry\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        assertBook3(results.get(0));\n\n        qry = \"Select b from Book b where b.author like :author\";\n        q = em.createQuery(qry);\n        q.setParameter(\"author\", \"%hart%\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        assertBook2(results.get(0));\n    }\n\n    /**\n     * Assert book1.\n     * \n     * @param book\n     *            the book\n     */\n    private void assertBook1(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(11, book.getBookId());\n        Assert.assertEquals(\"TO THE LIGHTHOUSE\", book.getTitle());\n        Assert.assertEquals(\"Virginia Woolf\", book.getAuthor());\n        Assert.assertEquals(1927, book.getYear());\n        Assert.assertEquals(100, book.getPages());\n    }\n\n    /**\n     * Assert book2.\n     * \n     * @param book\n     *            the book\n     */\n    private void assertBook2(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(12, book.getBookId());\n        Assert.assertEquals(\"The House Of Mirth\", book.getTitle());\n        Assert.assertEquals(\"Edith Wharton\", book.getAuthor());\n        Assert.assertEquals(1905, book.getYear());\n        Assert.assertEquals(200, book.getPages());\n    }\n\n    /**\n     * Assert book3.\n     * \n     * @param book\n     *            the book\n     */\n    private void assertBook3(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(13, book.getBookId());\n        Assert.assertEquals(\"under the volcano\", book.getTitle());\n        Assert.assertEquals(\"Malcolm Lowry\", book.getAuthor());\n        Assert.assertEquals(1947, book.getYear());\n        Assert.assertEquals(300, book.getPages());\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/query/HBaseParameterizedQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.query;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class Student test case for HBase.\n * \n * @author Kuldeep.mishra\n * \n */\npublic class HBaseParameterizedQueryTest extends StudentBaseTest\n{\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n        try\n        {\n            persistStudents();\n        }\n        catch (Exception e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Parameterized select query test.\n     */\n    @Test\n    public void parameterizedSelectQueryTest()\n    {\n\n        namedParametersSelectQueryTest();\n        ordinalParametersSelectQueryTest();\n    }\n\n    /**\n     * Parameterized update query test.\n     */\n    @Test\n    public void parameterizedUpdateQueryTest()\n    {\n\n        namedParametersUpdateQueryTest();\n        ordinalParametersupdateQueryTest();\n    }\n\n    /**\n     * Parameterized delete query test.\n     */\n    @Test\n    public void parameterizedDeleteQueryTest()\n    {\n\n        namedParametersDeleteQueryTest();\n        ordinalParametersDeleteQueryTest();\n    }\n\n    /**\n     * Named parameters select query test.\n     */\n    private void namedParametersSelectQueryTest()\n    {\n\n        // Query on studentId(long).\n        String query = \"Select s from Student s where s.studentId = :studentId\";\n        Query q = em.createQuery(query);\n        q.setParameter(\"studentId\", 12345677L);\n        List<Student> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(12345677L, results.get(0).getStudentId());\n        Assert.assertEquals(\"Amresh\", results.get(0).getStudentName());\n\n        // Query on studentName(String).\n        query = \"Select s from Student s where s.studentName = :studentName\";\n        q = em.createQuery(query);\n        q.setParameter(\"studentName\", \"Devender\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"Devender\", results.get(0).getStudentName());\n        Assert.assertEquals(true, results.get(0).isExceptional());\n\n        // Assert on isExceptional(boolean(true)).\n        query = \"Select s from Student s where s.isExceptional =:flag\";\n        q = em.createQuery(query);\n        q.setParameter(\"flag\", true);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(true, results.get(0).isExceptional());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n\n        // Assert on isExceptional(boolean(false)).\n        query = \"Select s from Student s where s.isExceptional = :flag\";\n        q = em.createQuery(query);\n        q.setParameter(\"flag\", false);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n\n        // query on age(int).\n        query = \"Select s from Student s where s.age = :age\";\n        q = em.createQuery(query);\n        q.setParameter(\"age\", 10);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(10, results.get(0).getAge());\n\n        // query on semester(char)\n        query = \"Select s from Student s where s.semester = :semester\";\n        q = em.createQuery(query);\n        q.setParameter(\"semester\", 'A');\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals('A', results.get(0).getSemester());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(10, results.get(0).getAge());\n\n        // query on digitalSignature (byte).\n        query = \"Select s from Student s where s.digitalSignature = :digitalSignature\";\n        q = em.createQuery(query);\n        q.setParameter(\"digitalSignature\", (byte) 50);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals((byte) 50, results.get(0).getDigitalSignature());\n        Assert.assertEquals(true, results.get(0).isExceptional());\n        Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n\n        // query on cgpa (short).\n        query = \"Select s from Student s where s.cgpa = :cgpa\";\n        q = em.createQuery(query);\n        q.setParameter(\"cgpa\", (short) 8);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(8, results.get(0).getCgpa());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(8, results.get(1).getCgpa());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(8, results.get(2).getCgpa());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on percentage(float)\n        query = \"Select s from Student s where s.percentage =:percentage\";\n        q = em.createQuery(query);\n        q.setParameter(\"percentage\", 61.6);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(61.6f, results.get(0).getPercentage());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n\n        // query on height (double)\n        query = \"Select s from Student s where s.height =:height\";\n        q = em.createQuery(query);\n        q.setParameter(\"height\", 163.76765654);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(163.76765654, results.get(0).getHeight());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n\n        // Query on enrolmentDate\n        query = \"Select s from Student s where s.enrolmentDate = :date\";\n        q = em.createQuery(query);\n        q.setParameter(\"date\", enrolmentDate);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(enrolmentDate, results.get(0).getEnrolmentDate());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(enrolmentDate, results.get(1).getEnrolmentDate());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(enrolmentDate, results.get(2).getEnrolmentDate());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // Query on enrolmentTime\n        query = \"Select s from Student s where s.enrolmentTime = :time\";\n        q = em.createQuery(query);\n        q.setParameter(\"time\", enrolmentTime);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(enrolmentTime, results.get(0).getEnrolmentTime());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(enrolmentTime, results.get(1).getEnrolmentTime());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(enrolmentTime, results.get(2).getEnrolmentTime());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // Query on joiningDateAndTime\n        query = \"Select s from Student s where s.joiningDateAndTime = :time\";\n        q = em.createQuery(query);\n        q.setParameter(\"time\", joiningDateAndTime);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(joiningDateAndTime, results.get(0).getJoiningDateAndTime());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(joiningDateAndTime, results.get(1).getJoiningDateAndTime());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(joiningDateAndTime, results.get(2).getJoiningDateAndTime());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on yearsSpent (Integer).\n        query = \"Select s from Student s where s.yearsSpent = :years\";\n        q = em.createQuery(query);\n        q.setParameter(\"years\", new Integer(3));\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(new Integer(3), results.get(0).getYearsSpent());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(new Integer(3), results.get(1).getYearsSpent());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(new Integer(3), results.get(2).getYearsSpent());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on rollNumber (Long).\n        query = \"Select s from Student s where s.rollNumber= :rollNumber\";\n        q = em.createQuery(query);\n        q.setParameter(\"rollNumber\", new Long(978423946455l));\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(new Long(978423946455l), results.get(0).getRollNumber());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(new Long(978423946455l), results.get(1).getRollNumber());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(new Long(978423946455l), results.get(2).getRollNumber());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on monthlyFee (Double).\n        query = \"Select s from Student s where s.monthlyFee= :monthlyFee\";\n        q = em.createQuery(query);\n        q.setParameter(\"monthlyFee\", 135434.89);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(135434.89, results.get(0).getMonthlyFee());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(135434.89, results.get(1).getMonthlyFee());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(135434.89, results.get(2).getMonthlyFee());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on sqlDate.\n        query = \"Select s from Student s where s.sqlDate= :date\";\n        q = em.createQuery(query);\n        q.setParameter(\"date\", sqlDate);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(sqlDate, results.get(0).getSqlDate());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(sqlDate, results.get(1).getSqlDate());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(sqlDate, results.get(2).getSqlDate());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on sqlTimestamp.\n        query = \"Select s from Student s where s.sqlTimestamp= :timeStamp\";\n        q = em.createQuery(query);\n        q.setParameter(\"timeStamp\", sqlTimestamp);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(sqlTimestamp, results.get(0).getSqlTimestamp());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(sqlTimestamp, results.get(1).getSqlTimestamp());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(sqlTimestamp, results.get(2).getSqlTimestamp());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on sqlTime.\n        query = \"Select s from Student s where s.sqlTime=:time\";\n        q = em.createQuery(query);\n        q.setParameter(\"time\", sqlTime);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(sqlTime, results.get(0).getSqlTime());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(sqlTime, results.get(1).getSqlTime());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(sqlTime, results.get(2).getSqlTime());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on big integer.\n        query = \"Select s from Student s where s.bigInteger = :bigInt\";\n        q = em.createQuery(query);\n        q.setParameter(\"bigInt\", bigInteger);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(bigInteger, results.get(0).getBigInteger());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(bigInteger, results.get(1).getBigInteger());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(bigInteger, results.get(2).getBigInteger());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on big integer.\n        query = \"Select s from Student s where s.bigDecimal = :bigDeci\";\n        q = em.createQuery(query);\n        q.setParameter(\"bigDeci\", bigDecimal);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(bigDecimal, results.get(0).getBigDecimal());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(bigDecimal, results.get(1).getBigDecimal());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(bigDecimal, results.get(2).getBigDecimal());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on calendar.\n        query = \"Select s from Student s where s.calendar = :cal\";\n        q = em.createQuery(query);\n        q.setParameter(\"cal\", calendar);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(calendar, results.get(0).getCalendar());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(calendar, results.get(1).getCalendar());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(calendar, results.get(2).getCalendar());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on cpga and digitalSignature.\n        query = \"Select s from Student s where s.cgpa = :cgpa and s.digitalSignature >= :ds1 and s.digitalSignature <= :ds2\";\n        q = em.createQuery(query);\n        q.setParameter(\"cgpa\", (short) 8);\n        q.setParameter(\"ds1\", (byte) 5);\n        q.setParameter(\"ds2\", (byte) 50);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals((short) 8, results.get(1).getCgpa());\n        Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n        Assert.assertEquals((short) 8, results.get(2).getCgpa());\n        Assert.assertEquals((byte) 50, results.get(2).getDigitalSignature());\n\n        // query on percentage and height.\n        query = \"Select s from Student s where s.percentage >= :percent1 and s.percentage <= :percent2 and s.height = :height\";\n        q = em.createQuery(query);\n        q.setParameter(\"height\", 163.76765654);\n        q.setParameter(\"percent1\", 61.6);\n        q.setParameter(\"percent2\", 69.3);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(163.76765654, results.get(0).getHeight());\n        Assert.assertEquals(61.6f, results.get(0).getPercentage());\n\n        // query on cpga and semester.\n        query = \"Select s from Student s where s.cgpa = :cgpa and s.semester >= :sem1 and s.semester < :sem2\";\n        q = em.createQuery(query);\n        q.setParameter(\"cgpa\", (short) 8);\n        q.setParameter(\"sem1\", 'A');\n        q.setParameter(\"sem2\", 'C');\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals('A', results.get(0).getSemester());\n        Assert.assertEquals((short) 8, results.get(1).getCgpa());\n        Assert.assertEquals('B', results.get(1).getSemester());\n\n        // query on invalid cpga and studentId.\n        query = \"Select s from Student s where s.cgpa = :cgpa and s.studentId >= :id1 and s.studentId <= :id2\";\n        q = em.createQuery(query);\n        q.setParameter(\"cgpa\", (short) 2);\n        q.setParameter(\"id1\", 12345687L);\n        q.setParameter(\"id2\", 12345689L);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertTrue(results.isEmpty());\n\n    }\n\n    /**\n     * Ordinal parameters select query test.\n     */\n    private void ordinalParametersSelectQueryTest()\n    {\n\n        // Query on studentId(long).\n        String query = \"Select s from Student s where s.studentId = ?1\";\n        Query q = em.createQuery(query);\n        q.setParameter(1, 12345677L);\n        List<Student> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(12345677L, results.get(0).getStudentId());\n        Assert.assertEquals(\"Amresh\", results.get(0).getStudentName());\n\n        // Query on studentName(String).\n        query = \"Select s from Student s where s.studentName = ?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, \"Devender\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"Devender\", results.get(0).getStudentName());\n        Assert.assertEquals(true, results.get(0).isExceptional());\n\n        // Assert on isExceptional(boolean(true)).\n        query = \"Select s from Student s where s.isExceptional =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, true);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(true, results.get(0).isExceptional());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n\n        // Assert on isExceptional(boolean(false)).\n        query = \"Select s from Student s where s.isExceptional =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, false);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n\n        // query on age(int).\n        query = \"Select s from Student s where s.age =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 10);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(10, results.get(0).getAge());\n\n        // query on semester(char)\n        query = \"Select s from Student s where s.semester =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 'A');\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals('A', results.get(0).getSemester());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(10, results.get(0).getAge());\n\n        // query on digitalSignature (byte).\n        query = \"Select s from Student s where s.digitalSignature =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, (byte) 50);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals((byte) 50, results.get(0).getDigitalSignature());\n        Assert.assertEquals(true, results.get(0).isExceptional());\n        Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n\n        // query on cgpa (short).\n        query = \"Select s from Student s where s.cgpa =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(8, results.get(0).getCgpa());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(8, results.get(1).getCgpa());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(8, results.get(2).getCgpa());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on percentage(float)\n        query = \"Select s from Student s where s.percentage =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 61.6);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(61.6f, results.get(0).getPercentage());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n\n        // query on height (double)\n        query = \"Select s from Student s where s.height =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 163.76765654);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(163.76765654, results.get(0).getHeight());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n\n        // Query on enrolmentDate\n        query = \"Select s from Student s where s.enrolmentDate = ?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, enrolmentDate);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(enrolmentDate, results.get(0).getEnrolmentDate());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(enrolmentDate, results.get(1).getEnrolmentDate());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(enrolmentDate, results.get(2).getEnrolmentDate());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // Query on enrolmentTime\n        query = \"Select s from Student s where s.enrolmentTime = ?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, enrolmentTime);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(enrolmentTime, results.get(0).getEnrolmentTime());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(enrolmentTime, results.get(1).getEnrolmentTime());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(enrolmentTime, results.get(2).getEnrolmentTime());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // Query on joiningDateAndTime\n        query = \"Select s from Student s where s.joiningDateAndTime = ?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, joiningDateAndTime);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(joiningDateAndTime, results.get(0).getJoiningDateAndTime());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(joiningDateAndTime, results.get(1).getJoiningDateAndTime());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(joiningDateAndTime, results.get(2).getJoiningDateAndTime());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on yearsSpent (Integer).\n        query = \"Select s from Student s where s.yearsSpent =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, new Integer(3));\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(new Integer(3), results.get(0).getYearsSpent());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(new Integer(3), results.get(1).getYearsSpent());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(new Integer(3), results.get(2).getYearsSpent());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on rollNumber (Long).\n        query = \"Select s from Student s where s.rollNumber=?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, new Long(978423946455l));\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(new Long(978423946455l), results.get(0).getRollNumber());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(new Long(978423946455l), results.get(1).getRollNumber());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(new Long(978423946455l), results.get(2).getRollNumber());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on monthlyFee (Double).\n        query = \"Select s from Student s where s.monthlyFee=?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 135434.89);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(135434.89, results.get(0).getMonthlyFee());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(135434.89, results.get(1).getMonthlyFee());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(135434.89, results.get(2).getMonthlyFee());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on sqlDate.\n        query = \"Select s from Student s where s.sqlDate=?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, sqlDate);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(sqlDate, results.get(0).getSqlDate());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(sqlDate, results.get(1).getSqlDate());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(sqlDate, results.get(2).getSqlDate());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on sqlTimestamp.\n        query = \"Select s from Student s where s.sqlTimestamp=?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, sqlTimestamp);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(sqlTimestamp, results.get(0).getSqlTimestamp());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(sqlTimestamp, results.get(1).getSqlTimestamp());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(sqlTimestamp, results.get(2).getSqlTimestamp());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on sqlTime.\n        query = \"Select s from Student s where s.sqlTime=?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, sqlTime);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(sqlTime, results.get(0).getSqlTime());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(sqlTime, results.get(1).getSqlTime());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(sqlTime, results.get(2).getSqlTime());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on big integer.\n        query = \"Select s from Student s where s.bigInteger =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, bigInteger);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(bigInteger, results.get(0).getBigInteger());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(bigInteger, results.get(1).getBigInteger());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(bigInteger, results.get(2).getBigInteger());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on big integer.\n        query = \"Select s from Student s where s.bigDecimal =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, bigDecimal);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(bigDecimal, results.get(0).getBigDecimal());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(bigDecimal, results.get(1).getBigDecimal());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(bigDecimal, results.get(2).getBigDecimal());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on calendar.\n        query = \"Select s from Student s where s.calendar =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, calendar);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(calendar, results.get(0).getCalendar());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(calendar, results.get(1).getCalendar());\n        Assert.assertEquals(true, results.get(1).isExceptional());\n        Assert.assertEquals(calendar, results.get(2).getCalendar());\n        Assert.assertEquals(true, results.get(2).isExceptional());\n\n        // query on cpga and digitalSignature.\n        query = \"Select s from Student s where s.cgpa =?1 and s.digitalSignature >= ?2 and s.digitalSignature <= ?3\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        q.setParameter(2, (byte) 5);\n        q.setParameter(3, (byte) 50);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals((short) 8, results.get(1).getCgpa());\n        Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n        Assert.assertEquals((short) 8, results.get(2).getCgpa());\n        Assert.assertEquals((byte) 50, results.get(2).getDigitalSignature());\n\n        // query on cpga and digitalSignature.\n        query = \"Select s from Student s where s.digitalSignature >= ?2 and s.digitalSignature <= ?3 and s.cgpa =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        q.setParameter(2, (byte) 5);\n        q.setParameter(3, (byte) 50);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals((short) 8, results.get(1).getCgpa());\n        Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n        Assert.assertEquals((short) 8, results.get(2).getCgpa());\n        Assert.assertEquals((byte) 50, results.get(2).getDigitalSignature());\n\n        // query on percentage and height.\n        query = \"Select s from Student s where s.percentage >= ?2 and s.percentage <= ?3 and s.height =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 163.76765654);\n        q.setParameter(2, 61.6);\n        q.setParameter(3, 69.3);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(163.76765654, results.get(0).getHeight());\n        Assert.assertEquals(61.6f, results.get(0).getPercentage());\n\n        // query on cpga and semester.\n        query = \"Select s from Student s where s.cgpa =?1 and s.semester >= ?2 and s.semester < ?3\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        q.setParameter(2, 'A');\n        q.setParameter(3, 'C');\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals('A', results.get(0).getSemester());\n        Assert.assertEquals((short) 8, results.get(1).getCgpa());\n        Assert.assertEquals('B', results.get(1).getSemester());\n\n        // query on invalid cpga and studentId.\n        query = \"Select s from Student s where s.cgpa =?1 and s.studentId >= ?2 and s.studentId <= ?3\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 2);\n        q.setParameter(2, 12345677L);\n        q.setParameter(3, 12345679L);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertTrue(results.isEmpty());\n    }\n\n    /**\n     * Named parameters update query test.\n     */\n    private void namedParametersUpdateQueryTest()\n    {\n        persistStudents();\n        Query q = em.createQuery(\"update Student s set s.studentName = :newName where s.studentName = :name\");\n        q.setParameter(\"newName\", \"NewAmresh\");\n        q.setParameter(\"name\", \"Amresh\");\n        int results = q.executeUpdate();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results);\n        Student s1 = em.find(Student.class, 12345677L);\n        Assert.assertEquals(\"NewAmresh\", s1.getStudentName());\n\n        persistStudents();\n        q = em.createQuery(\"update Student s set s.studentName = :newName,s.semester=:newSemester where s.isExceptional = :flag and s.semester= :semester\");\n        q.setParameter(\"newName\", \"NewDevender\");\n        q.setParameter(\"newSemester\", 'A');\n        q.setParameter(\"flag\", true);\n        q.setParameter(\"semester\", 'B');\n        results = q.executeUpdate();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results);\n        s1 = em.find(Student.class, 12345678L);\n        Assert.assertEquals(\"NewDevender\", s1.getStudentName());\n        Assert.assertEquals('A', s1.getSemester());\n\n        persistStudents();\n        q = em.createQuery(\"update Student s set s.studentName = :newName,s.semester=:newSemester where s.isExceptional = :flag or s.semester= :semester\");\n        q.setParameter(\"newName\", \"NewDevender\");\n        q.setParameter(\"newSemester\", 'A');\n        q.setParameter(\"flag\", true);\n        q.setParameter(\"semester\", 'B');\n        results = q.executeUpdate();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results);\n        s1 = em.find(Student.class, 12345678L);\n        Assert.assertEquals(\"NewDevender\", s1.getStudentName());\n        Assert.assertEquals('A', s1.getSemester());\n\n        Student s2 = em.find(Student.class, 12345679L);\n        Assert.assertEquals(\"NewDevender\", s2.getStudentName());\n        Assert.assertEquals('A', s2.getSemester());\n\n    }\n\n    /**\n     * Ordinal parametersupdate query test.\n     */\n    private void ordinalParametersupdateQueryTest()\n    {\n        persistStudents();\n        Query q = em.createQuery(\"update Student s set s.studentName = ?1 where s.studentName = ?2\");\n        q.setParameter(1, \"NewAmresh\");\n        q.setParameter(2, \"Amresh\");\n        int results = q.executeUpdate();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results);\n        Student s1 = em.find(Student.class, 12345677L);\n        Assert.assertEquals(\"NewAmresh\", s1.getStudentName());\n\n        persistStudents();\n        q = em.createQuery(\"update Student s set s.studentName = ?1,s.semester= ?2 where s.isExceptional = ?3 and s.semester= ?4\");\n        q.setParameter(1, \"NewDevender\");\n        q.setParameter(2, 'A');\n        q.setParameter(3, true);\n        q.setParameter(4, 'B');\n        results = q.executeUpdate();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results);\n        s1 = em.find(Student.class, 12345678L);\n        Assert.assertEquals(\"NewDevender\", s1.getStudentName());\n        Assert.assertEquals('A', s1.getSemester());\n\n        persistStudents();\n        q = em.createQuery(\"update Student s set s.studentName = ?1,s.semester= ?2 where s.isExceptional = ?3 or s.semester= ?4\");\n        q.setParameter(1, \"NewDevender\");\n        q.setParameter(2, 'A');\n        q.setParameter(3, true);\n        q.setParameter(4, 'B');\n        results = q.executeUpdate();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results);\n        s1 = em.find(Student.class, 12345678L);\n        Assert.assertEquals(\"NewDevender\", s1.getStudentName());\n        Assert.assertEquals('A', s1.getSemester());\n\n        Student s2 = em.find(Student.class, 12345679L);\n        Assert.assertEquals(\"NewDevender\", s2.getStudentName());\n        Assert.assertEquals('A', s2.getSemester());\n\n    }\n\n    /**\n     * Named parameters delete query test.\n     */\n    private void namedParametersDeleteQueryTest()\n    {\n        persistStudents();\n        Student s1 = em.find(Student.class, 12345677L);\n        Assert.assertNotNull(s1);\n        Query q = em.createQuery(\"delete from Student s where s.studentName = :name\");\n        q.setParameter(\"name\", \"Amresh\");\n        int results = q.executeUpdate();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results);\n        em.clear();\n        s1 = em.find(Student.class, 12345677L);\n        Assert.assertNull(s1);\n\n        persistStudents();\n        s1 = em.find(Student.class, 12345678L);\n        Assert.assertNotNull(s1);\n        q = em.createQuery(\"delete from Student s where s.isExceptional = :flag and s.semester= :semester\");\n        q.setParameter(\"flag\", true);\n        q.setParameter(\"semester\", 'B');\n        results = q.executeUpdate();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results);\n        em.clear();\n        s1 = em.find(Student.class, 12345678L);\n        Assert.assertNull(s1);\n\n        persistStudents();\n        s1 = em.find(Student.class, 12345678L);\n        Assert.assertNotNull(s1);\n        Student s2 = em.find(Student.class, 12345679L);\n        Assert.assertNotNull(s2);\n        q = em.createQuery(\"delete from Student s where s.isExceptional = :flag or s.semester= :semester\");\n        q.setParameter(\"flag\", true);\n        q.setParameter(\"semester\", 'B');\n        results = q.executeUpdate();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results);\n        em.clear();\n        s1 = em.find(Student.class, 12345678L);\n        Assert.assertNull(s1);\n        em.clear();\n        s2 = em.find(Student.class, 12345679L);\n        Assert.assertNull(s2);\n    }\n\n    /**\n     * Ordinal parameters delete query test.\n     */\n    private void ordinalParametersDeleteQueryTest()\n    {\n        persistStudents();\n        Student s1 = em.find(Student.class, 12345677L);\n        Assert.assertNotNull(s1);\n        Query q = em.createQuery(\"delete from Student s where s.studentName = ?1\");\n        q.setParameter(1, \"Amresh\");\n        int results = q.executeUpdate();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results);\n        em.clear();\n        s1 = em.find(Student.class, 12345677L);\n        Assert.assertNull(s1);\n\n        persistStudents();\n        s1 = em.find(Student.class, 12345678L);\n        Assert.assertNotNull(s1);\n        q = em.createQuery(\"delete from Student s where s.isExceptional = ?1 and s.semester= ?2\");\n        q.setParameter(1, true);\n        q.setParameter(2, 'B');\n        results = q.executeUpdate();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results);\n        em.clear();\n        s1 = em.find(Student.class, 12345678L);\n        Assert.assertNull(s1);\n\n        persistStudents();\n        s1 = em.find(Student.class, 12345678L);\n        Assert.assertNotNull(s1);\n        Student s2 = em.find(Student.class, 12345679L);\n        Assert.assertNotNull(s2);\n        q = em.createQuery(\"delete from Student s where s.isExceptional = ?1 or s.semester= ?2\");\n        q.setParameter(1, true);\n        q.setParameter(2, 'B');\n        results = q.executeUpdate();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results);\n        em.clear();\n        s1 = em.find(Student.class, 12345678L);\n        Assert.assertNull(s1);\n        em.clear();\n        s2 = em.find(Student.class, 12345679L);\n        Assert.assertNull(s2);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        deleteStudents();\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/query/HBasePerson.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.query;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class HbaseEntitySimple.\n */\n@Entity\n@Table(name = \"HBASE_PERSON\", schema = \"HBaseNew@queryTest\")\npublic class HBasePerson\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/query/HBaseQueryBaseTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.query;\n\nimport java.util.Collections;\nimport java.util.List;\n\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\n\n/**\n * The Class HBaseQueryBaseTest.\n * \n * @author Devender Yadav\n */\npublic class HBaseQueryBaseTest extends BookBaseTest\n{\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n        persistBooks();\n    }\n\n    /**\n     * Test select queries.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testSelectQueries() throws Exception\n    {\n        testSelectAll();\n        testSelectOnId();\n        testSelectWithWhereClause();\n        testSelectWithInClause();\n        testSelectFields();\n    }\n\n    /**\n     * Test delete queries.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testDeleteQueries() throws Exception\n    {\n        testDeleteAll();\n        testDeleteOnId();\n        testDeleteWithWhereClause();\n        testDeleteWithInClause();\n    }\n\n    /**\n     * Test update queries.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testUpdateQueries() throws Exception\n    {\n        testUpdateAll();\n        testUpdateOnId();\n        testUpdateWithWhereClause();\n        testUpdateWithInClause();\n    }\n\n    /**\n     * Test select all.\n     */\n    private void testSelectAll()\n    {\n        List<Book> results = em.createQuery(\"select b from Book b\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        Assert.assertTrue(Book.class.isAssignableFrom(results.get(0).getClass()));\n        assertResults(results, T, T, T, T);\n    }\n\n    /**\n     * Test select on id.\n     */\n    private void testSelectOnId()\n    {\n        List<Book> results = em.createQuery(\"select b from Book b where b.bookId=1\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        validateBook1(results.get(0));\n\n        results = em.createQuery(\"select b from Book b where b.bookId <> 1\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        assertResults(results, F, T, T, T);\n\n        results = em.createQuery(\"Select b from Book b where b.bookId < 3\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, T, T, F, F);\n\n        results = em.createQuery(\"Select b from Book b where b.bookId <= 3\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        assertResults(results, T, T, T, F);\n\n        results = em.createQuery(\"Select b from Book b where b.bookId > 2\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, F, F, T, T);\n\n        results = em.createQuery(\"Select b from Book b where b.bookId >= 2\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        assertResults(results, F, T, T, T);\n\n        results = em.createQuery(\"Select b from Book b where  b.bookId >= 1 and b.bookId < 3\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, T, T, F, F);\n\n        results = em.createQuery(\"Select b from Book b where  b.bookId > 1 and b.bookId <= 3\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, F, T, T, F);\n\n        results = em.createQuery(\"select b from Book b where b.bookId in (3,4,5,6)\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, F, F, T, T);\n\n    }\n\n    /**\n     * Test select with where clause.\n     */\n    private void testSelectWithWhereClause()\n    {\n        /*------queries with where clause------*/\n        List<Book> results = em.createQuery(\"select b from Book b where b.title = 'book1'\").getResultList();\n        Assert.assertNotNull(results);\n        validateBook1(results.get(0));\n\n        results = em.createQuery(\"select b from Book b where b.author = 'author2'\").getResultList();\n        Assert.assertNotNull(results);\n        validateBook2(results.get(0));\n\n        results = em.createQuery(\"select b from Book b where b.author = 'author1'\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, T, F, F, T);\n\n        /*------queries with where clause and comparison operators------*/\n        results = em.createQuery(\"select b from Book b where b.year > 2000\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        assertResults(results, F, T, T, T);\n\n        results = em.createQuery(\"select b from Book b where b.year >= 2000\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        assertResults(results, T, T, T, T);\n\n        results = em.createQuery(\"select b from Book b where b.year < 2015\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        assertResults(results, T, T, T, F);\n\n        results = em.createQuery(\"select b from Book b where b.year <= 2015\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        assertResults(results, T, T, T, T);\n\n        results = em.createQuery(\"select b from Book b where b.year = 2005\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        validateBook2(results.get(0));\n\n        results = em.createQuery(\"select b from Book b where b.year <> 2010\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        assertResults(results, T, T, F, T);\n\n        /*------queries with where clause, comparison operators and logical operators------*/\n        results = em.createQuery(\"select b from Book b where b.author = 'author1' and b.pages > 200\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        validateBook4(results.get(0));\n\n        results = em.createQuery(\"select b from Book b where b.year > 2000 and b.pages > 200\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, F, F, T, T);\n\n        results = em.createQuery(\"select b from Book b where b.year >= 2000 and b.pages < 500\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        assertResults(results, T, T, T, T);\n\n        // not working with lucene\n        results = em.createQuery(\"select b from Book b where b.year > 2010 or b.year <= 2005\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        assertResults(results, T, T, F, T);\n\n        results = em.createQuery(\"select b from Book b where b.year < 2010 or b.pages >= 350\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        assertResults(results, T, T, F, T);\n\n        /*\n         * This type of query is not working with Lucene as indexing store\n         * meanwhile you can use it directly with HBase.\n         */\n\n        // results = em.createQuery(\n        // \"select b from Book b where b.year > 2010 and b.pages > 300 or b.year <= 2005 and b.pages > 100\")\n        // .getResultList();\n        // Assert.assertNotNull(results);\n        // Assert.assertEquals(2, results.size());\n        // assertResults(results, F, T, F, T);\n\n        results = em\n                .createQuery(\"select b from Book b where b.author = 'author1' and b.year <> 2015 and b.pages < 300\")\n                .getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        validateBook1(results.get(0));\n\n        results = em.createQuery(\"select b from Book b where b.pages = 100 or b.year <= 2005 or b.title = 'book4'\")\n                .getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        assertResults(results, T, T, F, T);\n\n    }\n\n    /**\n     * Test select with in clause.\n     */\n    private void testSelectWithInClause()\n    {\n        List<Book> results = em.createQuery(\"select b from Book b where b.title in ('book1','book2')\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, T, T, F, F);\n\n        results = em.createQuery(\"select b from Book b where b.year in (2005,2010)\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, F, T, T, F);\n\n    }\n\n    /**\n     * Test select fields.\n     */\n    private void testSelectFields()\n    {\n        List results = em.createQuery(\"select b.title from Book b\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        Collections.sort(results);\n        Assert.assertEquals(\"book1\", results.get(0));\n        Assert.assertEquals(\"book2\", results.get(1));\n        Assert.assertEquals(\"book3\", results.get(2));\n        Assert.assertEquals(\"book4\", results.get(3));\n\n        results = em.createQuery(\"select b.author from Book b where b.bookId=1\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"author1\", results.get(0));\n\n        results = em.createQuery(\"select b.pages from Book b where b.year > 2000\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Collections.sort(results);\n        Assert.assertEquals(200, results.get(0));\n        Assert.assertEquals(300, results.get(1));\n        Assert.assertEquals(400, results.get(2));\n\n        results = em.createQuery(\"select b.title, b.year from Book b where b.year <> 2010\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        for (Object result : results)\n        {\n            if (\"book1\".equals(((List) result).get(0)))\n            {\n                Assert.assertEquals(2000, ((List) result).get(1));\n            }\n            else if (\"book2\".equals(((List) result).get(0)))\n            {\n\n                Assert.assertEquals(2005, ((List) result).get(1));\n            }\n            else if (\"book3\".equals(((List) result).get(0)))\n            {\n                Assert.assertEquals(2015, ((List) result).get(1));\n            }\n        }\n\n        results = em.createQuery(\"select b.title , b.pages from Book b where b.author = 'author1' and b.pages > 200\")\n                .getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"book4\", ((List) results.get(0)).get(0));\n        Assert.assertEquals(400, ((List) results.get(0)).get(1));\n\n        results = em\n                .createQuery(\n                        \"select b.author, b.pages, b.year from Book b where b.author = 'author1' and b.year <> 2015 and b.pages < 300\")\n                .getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"author1\", ((List) results.get(0)).get(0));\n        Assert.assertEquals(100, ((List) results.get(0)).get(1));\n        Assert.assertEquals(2000, ((List) results.get(0)).get(2));\n\n        results = em.createQuery(\"select b.title from Book b where b.bookId in (3,4,5,6)\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Collections.sort(results);\n        Assert.assertEquals(\"book3\", results.get(0));\n        Assert.assertEquals(\"book4\", results.get(1));\n\n        results = em.createQuery(\"select b.author,b.pages from Book b where b.title in ('book1','book5','book6')\")\n                .getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"author1\", ((List) results.get(0)).get(0));\n        Assert.assertEquals(100, ((List) results.get(0)).get(1));\n    }\n\n    /**\n     * Test delete all.\n     */\n    private void testDeleteAll()\n    {\n        persistBooks();\n        int result = em.createQuery(\"delete from Book b\").executeUpdate();\n        Assert.assertEquals(4, result);\n        assertDeleted(T, T, T, T);\n    }\n\n    /**\n     * Test delete on id.\n     */\n    private void testDeleteOnId()\n    {\n        persistBooks();\n        int result = em.createQuery(\"delete from Book b where b.bookId = 1\").executeUpdate();\n        Assert.assertEquals(1, result);\n        assertDeleted(T, F, F, F);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where b.bookId <> 1\").executeUpdate();\n        Assert.assertEquals(3, result);\n        assertDeleted(F, T, T, T);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where b.bookId < 3\").executeUpdate();\n        Assert.assertEquals(2, result);\n        assertDeleted(T, T, F, F);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where b.bookId <= 3\").executeUpdate();\n        Assert.assertEquals(3, result);\n        assertDeleted(T, T, T, F);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where b.bookId > 2\").executeUpdate();\n        Assert.assertEquals(2, result);\n        assertDeleted(F, F, T, T);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where b.bookId >= 2\").executeUpdate();\n        Assert.assertEquals(3, result);\n        assertDeleted(F, T, T, T);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where  b.bookId >= 1 and b.bookId < 3\").executeUpdate();\n        Assert.assertEquals(2, result);\n        assertDeleted(T, T, F, F);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where  b.bookId > 1 and b.bookId <= 3\").executeUpdate();\n        Assert.assertEquals(2, result);\n        assertDeleted(F, T, T, F);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where b.bookId in (2,3,4,5)\").executeUpdate();\n        Assert.assertEquals(3, result);\n        assertDeleted(F, T, T, T);\n\n    }\n\n    /**\n     * Test delete with where clause.\n     */\n    private void testDeleteWithWhereClause()\n    {\n        persistBooks();\n        int result = em.createQuery(\"delete from Book b where b.title = 'book1'\").executeUpdate();\n        Assert.assertEquals(1, result);\n        assertDeleted(T, F, F, F);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where b.author = 'author1'\").executeUpdate();\n        Assert.assertEquals(2, result);\n        assertDeleted(T, F, F, T);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where b.year <= 2015\").executeUpdate();\n        Assert.assertNotNull(result);\n        Assert.assertEquals(4, result);\n        assertDeleted(T, T, T, T);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where b.year = 2005\").executeUpdate();\n        Assert.assertEquals(1, result);\n        assertDeleted(F, T, F, F);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where b.year <> 2010\").executeUpdate();\n        Assert.assertNotNull(result);\n        Assert.assertEquals(3, result);\n        assertDeleted(T, T, F, T);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where b.author = 'author1' and b.year <> 2015 and b.pages < 300\")\n                .executeUpdate();\n        Assert.assertNotNull(result);\n        Assert.assertEquals(1, result);\n        assertDeleted(T, F, F, F);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where b.pages = 100 or b.year <= 2005 or b.title = 'book4'\")\n                .executeUpdate();\n        Assert.assertNotNull(result);\n        Assert.assertEquals(3, result);\n        assertDeleted(T, T, F, T);\n\n    }\n\n    /**\n     * Test delete with in clause.\n     */\n    private void testDeleteWithInClause()\n    {\n        persistBooks();\n        int result = em.createQuery(\"delete from Book b where b.title in ('book1','book2')\").executeUpdate();\n        Assert.assertEquals(2, result);\n        assertDeleted(T, T, F, F);\n\n        persistBooks();\n        result = em.createQuery(\"delete from Book b where b.year in (2005,2010)\").executeUpdate();\n        Assert.assertEquals(2, result);\n        assertDeleted(F, T, T, F);\n\n    }\n\n    /**\n     * Test update all.\n     */\n    private void testUpdateAll()\n    {\n        persistBooks();\n        int result = em.createQuery(\"update Book b set b.title = 'book'\").executeUpdate();\n        Assert.assertEquals(4, result);\n        em.clear();\n        Book book1 = em.find(Book.class, 1);\n        Book book2 = em.find(Book.class, 2);\n        Book book3 = em.find(Book.class, 3);\n        Book book4 = em.find(Book.class, 4);\n        Assert.assertEquals(\"book\", book1.getTitle());\n        Assert.assertEquals(\"book\", book2.getTitle());\n        Assert.assertEquals(\"book\", book3.getTitle());\n        Assert.assertEquals(\"book\", book4.getTitle());\n\n        persistBooks();\n        result = em.createQuery(\"update Book b set b.pages = 300\").executeUpdate();\n        Assert.assertEquals(4, result);\n        em.clear();\n        book1 = em.find(Book.class, 1);\n        book2 = em.find(Book.class, 2);\n        book3 = em.find(Book.class, 3);\n        book4 = em.find(Book.class, 4);\n        Assert.assertEquals(300, book1.getPages());\n        Assert.assertEquals(300, book2.getPages());\n        Assert.assertEquals(300, book3.getPages());\n        Assert.assertEquals(300, book4.getPages());\n    }\n\n    /**\n     * Test update on id.\n     */\n    private void testUpdateOnId()\n    {\n        persistBooks();\n        int result = em.createQuery(\"update Book b set b.year = 2009 where b.bookId = 1\").executeUpdate();\n        Assert.assertEquals(1, result);\n        em.clear();\n        Book book1 = em.find(Book.class, 1);\n        Assert.assertEquals(2009, book1.getYear());\n        Assert.assertEquals(\"book1\", book1.getTitle());\n\n        persistBooks();\n        result = em.createQuery(\"update Book b set b.year = 2009 where b.bookId <> 1\").executeUpdate();\n        Assert.assertEquals(3, result);\n        em.clear();\n        Book book2 = em.find(Book.class, 2);\n        Assert.assertEquals(2009, book2.getYear());\n        Assert.assertEquals(\"book2\", book2.getTitle());\n\n        Book book3 = em.find(Book.class, 3);\n        Assert.assertEquals(2009, book3.getYear());\n        Assert.assertEquals(\"book3\", book3.getTitle());\n\n        Book book4 = em.find(Book.class, 4);\n        Assert.assertEquals(2009, book4.getYear());\n        Assert.assertEquals(\"book4\", book4.getTitle());\n\n        persistBooks();\n        result = em.createQuery(\"update Book b set b.pages = 500 where b.bookId < 3\").executeUpdate();\n        Assert.assertEquals(2, result);\n        em.clear();\n        book1 = em.find(Book.class, 1);\n        Assert.assertEquals(500, book1.getPages());\n        Assert.assertEquals(\"book1\", book1.getTitle());\n        book2 = em.find(Book.class, 2);\n        Assert.assertEquals(500, book2.getPages());\n        Assert.assertEquals(\"book2\", book2.getTitle());\n\n        persistBooks();\n        result = em.createQuery(\"update Book b set b.author = 'author5' where b.bookId in (2,3,5)\").executeUpdate();\n        Assert.assertEquals(2, result);\n        em.clear();\n        book2 = em.find(Book.class, 2);\n        book3 = em.find(Book.class, 3);\n        Assert.assertEquals(\"author5\", book2.getAuthor());\n        Assert.assertEquals(\"author5\", book3.getAuthor());\n    }\n\n    /**\n     * Test update with where clause.\n     */\n    private void testUpdateWithWhereClause()\n    {\n        persistBooks();\n        int result = em.createQuery(\"update Book b set b.year = 2009 where b.title = 'book1'\").executeUpdate();\n        Assert.assertEquals(1, result);\n        em.clear();\n        Book book1 = em.find(Book.class, 1);\n        Assert.assertEquals(2009, book1.getYear());\n        Assert.assertEquals(\"book1\", book1.getTitle());\n\n        persistBooks();\n        result = em.createQuery(\"update Book b set b.year = 2009,b.title='book' where b.title = 'book1'\")\n                .executeUpdate();\n        Assert.assertEquals(1, result);\n        em.clear();\n        book1 = em.find(Book.class, 1);\n        Assert.assertEquals(2009, book1.getYear());\n        Assert.assertEquals(\"book\", book1.getTitle());\n\n        persistBooks();\n        result = em\n                .createQuery(\n                        \"update Book b set b.author = 'author', b.pages = 500 where b.author = 'author1' and b.year <> 2015 and b.pages < 300\")\n                .executeUpdate();\n        Assert.assertEquals(1, result);\n        em.clear();\n        book1 = em.find(Book.class, 1);\n        Assert.assertEquals(\"author\", book1.getAuthor());\n        Assert.assertEquals(500, book1.getPages());\n    }\n\n    /**\n     * Test update with in clause.\n     */\n    private void testUpdateWithInClause()\n    {\n        persistBooks();\n        int result = em.createQuery(\"update Book b set b.author = 'author5' where b.title in ('book1','book2')\")\n                .executeUpdate();\n        Assert.assertEquals(2, result);\n        em.clear();\n        Book book1 = em.find(Book.class, 1);\n        Book book2 = em.find(Book.class, 2);\n        Assert.assertEquals(\"author5\", book1.getAuthor());\n        Assert.assertEquals(\"author5\", book2.getAuthor());\n\n        persistBooks();\n        result = em.createQuery(\"update Book b set b.title = 'book', b.year = 2000 where b.year in (2005,2010)\")\n                .executeUpdate();\n\n        Assert.assertEquals(2, result);\n\n        em.clear();\n        book1 = em.find(Book.class, 2);\n        book2 = em.find(Book.class, 3);\n        Assert.assertEquals(\"book\", book1.getTitle());\n        Assert.assertEquals(\"book\", book2.getTitle());\n        Assert.assertEquals(2000, book1.getYear());\n        Assert.assertEquals(2000, book2.getYear());\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        deleteBooks();\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/query/LikeQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.query;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * The Class LikeQueryTest.\n */\npublic class LikeQueryTest\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"queryTest\");\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Tear down.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        removePersons();\n        emf.close();\n    }\n\n    /**\n     * Like query test.\n     */\n    @Test\n    public void likeQueryTest()\n    {\n        init();\n        em.clear();\n\n        String qry = \"Select p from HBasePerson p where p.personName like :name\";\n        Query q = em.createQuery(qry);\n        q.setParameter(\"name\", \"pragal\");\n        List<HBasePerson> persons = q.getResultList();\n        assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        Assert.assertEquals(\"pragalbh garg\", persons.get(0).getPersonName());\n\n        qry = \"Select p from HBasePerson p where p.personName like :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"thik\");\n        persons = q.getResultList();\n        assertEquals(1, persons.size());\n        assertEquals(\"karthik prasad\", persons.get(0).getPersonName());\n        \n        qry = \"Select p from HBasePerson p where p.personId like :id\";\n        q = em.createQuery(qry);\n        q.setParameter(\"id\", \"abc\");\n        persons = q.getResultList();\n        assertEquals(2, persons.size());\n    }\n\n    /**\n     * Inits the.\n     */\n    private void init()\n    {\n        HBasePerson p1 = new HBasePerson();\n        p1.setAge((short) 23);\n        p1.setPersonId(\"12_abc_56\");\n        p1.setPersonName(\"pragalbh garg\");\n\n        HBasePerson p2 = new HBasePerson();\n        p2.setAge((short) 20);\n        p2.setPersonId(\"45_abc_34\");\n        p2.setPersonName(\"karthik prasad\");\n\n        em.persist(p1);\n        em.persist(p2);\n    }\n\n    /**\n     * Remove Persons.\n     */\n    private void removePersons()\n    {\n        HBasePerson p1 = em.find(HBasePerson.class, \"12_abc_56\");\n        em.remove(p1);\n        HBasePerson p2 = em.find(HBasePerson.class, \"45_abc_34\");\n        em.remove(p2);\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/query/RegexpQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.query;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * The Class RegexpQueryTest.\n * \n * @author karthikp.manchala\n */\npublic class RegexpQueryTest\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"queryTest\");\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        removePersons();\n        emf.close();\n    }\n\n    /**\n     * Regexp query test.\n     */\n    @Test\n    public void regexpQueryTest()\n    {\n        init();\n        em.clear();\n\n        String qry = \"Select p from HBasePerson p where p.personName regexp :name\";\n        Query q = em.createQuery(qry);\n        q.setParameter(\"name\", \"^pra.*\");\n        List<HBasePerson> persons = q.getResultList();\n        assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        Assert.assertEquals(\"pragalbh garg\", persons.get(0).getPersonName());\n\n        qry = \"Select p from HBasePerson p where p.personName regexp :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"^[pk]\");\n        persons = q.getResultList();\n        assertNotNull(persons);\n        Assert.assertEquals(2, persons.size());\n\n        qry = \"Select p from HBasePerson p where p.personName regexp :name\";\n        q = em.createQuery(qry);\n        q.setParameter(\"name\", \"pra...$\");\n        persons = q.getResultList();\n        assertEquals(1, persons.size());\n        Assert.assertEquals(\"karthik prasad\", persons.get(0).getPersonName());\n    }\n\n    /**\n     * Inits the.\n     */\n    private void init()\n    {\n        HBasePerson p1 = new HBasePerson();\n        p1.setAge((short) 23);\n        p1.setPersonId(\"1\");\n        p1.setPersonName(\"pragalbh garg\");\n\n        HBasePerson p2 = new HBasePerson();\n        p2.setAge((short) 20);\n        p2.setPersonId(\"2\");\n        p2.setPersonName(\"karthik prasad\");\n\n        em.persist(p1);\n        em.persist(p2);\n    }\n\n    /**\n     * Remove Persons.\n     */\n    private void removePersons()\n    {\n        HBasePerson p1 = em.find(HBasePerson.class, \"1\");\n        em.remove(p1);\n        HBasePerson p2 = em.find(HBasePerson.class, \"2\");\n        em.remove(p2);\n    }\n\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/query/ResultIteratorTest.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.query;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.NoSuchElementException;\n\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.testingutil.HBaseTestingUtils;\nimport com.impetus.kundera.query.IResultIterator;\nimport com.impetus.kundera.query.Query;\n\n/**\n * The Class ResultIteratorTest.\n * \n * @author vivek.mishra junit for {@link IResultIterator}.\n */\npublic class ResultIteratorTest extends BookBaseTest\n{\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(HBASE_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n        persistBooks();\n    }\n\n    /**\n     * Scroll test.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void scrollTest() throws Exception\n    {\n        assertBegin();\n    }\n\n    /**\n     * Assert begin.\n     */\n    private void assertBegin()\n    {\n        String query = \"Select b from Book b\";\n        List<Book> results = assertBookScrolling(query, 4);\n        assertResults(results, T, T, T, T);\n        assertForFetchSize(query, 4);\n\n        query = \"select b from Book b where b.title = 'book1'\";\n        results = assertBookScrolling(query, 1);\n        assertResults(results, T, F, F, F);\n        assertForFetchSize(query, 1);\n\n        query = \"select b from Book b where b.author = 'author2'\";\n        results = assertBookScrolling(query, 1);\n        assertResults(results, F, T, F, F);\n\n        query = \"select b from Book b where b.author = 'author1'\";\n        results = assertBookScrolling(query, 2);\n        assertResults(results, T, F, F, T);\n\n        query = \"select b from Book b where b.year > 2000\";\n        results = assertBookScrolling(query, 3);\n        assertResults(results, F, T, T, T);\n        assertForFetchSize(query, 3);\n\n        query = \"select b from Book b where b.year >= 2000\";\n        results = assertBookScrolling(query, 4);\n        assertResults(results, T, T, T, T);\n        assertForFetchSize(query, 4);\n\n        query = \"select b from Book b where b.year < 2015\";\n        results = assertBookScrolling(query, 3);\n        assertResults(results, T, T, T, F);\n        assertForFetchSize(query, 3);\n\n    }\n\n    /**\n     * Assert book scrolling.\n     * \n     * @param queryClause\n     *            the query clause\n     * @param expected\n     *            the expected\n     * @return the list\n     */\n    private List<Book> assertBookScrolling(String queryClause, int expected)\n    {\n        Query query = (Query) em.createQuery(queryClause, Book.class);\n\n        int count = 0;\n        Iterator<Book> bookItr = query.iterate();\n        List<Book> books = new ArrayList<Book>();\n        while (bookItr.hasNext())\n        {\n            Book book = bookItr.next();\n            Assert.assertNotNull(book);\n            count++;\n            books.add(book);\n        }\n        Assert.assertTrue(count > 0);\n        Assert.assertTrue(count == expected);\n        return books;\n    }\n\n    /**\n     * Assert for fetch size.\n     * \n     * @param qry\n     *            the qry\n     * @param expectedCount\n     *            the expected count\n     */\n    private void assertForFetchSize(final String qry, int expectedCount)\n    {\n        Query query = (Query) em.createQuery(qry, Book.class);\n\n        assertOnFetch(query, 0, expectedCount);\n        assertOnFetch(query, 1, expectedCount);\n        assertOnFetch(query, 2, expectedCount);\n        assertOnFetch(query, 3, expectedCount);\n        assertOnFetch(query, 4, expectedCount);\n        assertOnFetch(query, null, expectedCount);\n\n    }\n\n    /**\n     * Assert on fetch.\n     * \n     * @param query\n     *            the query\n     * @param fetchSize\n     *            the fetch size\n     * @param available\n     *            the available\n     */\n    private void assertOnFetch(Query query, Integer fetchSize, int available)\n    {\n        query.setFetchSize(fetchSize);\n        int counter = 0;\n        Iterator<Book> iter = query.iterate();\n\n        while (iter.hasNext())\n        {\n            Assert.assertNotNull(iter.next());\n            counter++;\n        }\n\n        Assert.assertEquals(counter, fetchSize == null || available < fetchSize ? available : fetchSize);\n        try\n        {\n            iter.next();\n            Assert.fail();\n        }\n        catch (NoSuchElementException nsex)\n        {\n            Assert.assertNotNull(nsex.getMessage());\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        deleteBooks();\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        HBaseTestingUtils.dropSchema(SCHEMA);\n    }\n}"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/query/Student.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.query;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\n/**\n * The Class Student.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENTS\", schema = \"HBaseNew@queryTest\")\npublic class Student\n{\n    // Primitive Types\n    /** The student id. */\n    @Id\n    @Column(name = \"STUDENT_ID\")\n    private long studentId;\n\n    /** The student name. */\n    @Column(name = \"STUDENT_NAME\")\n    private String studentName;\n\n    /** The is exceptional. */\n    @Column(name = \"IS_EXCEPTIONAL\")\n    private boolean isExceptional;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private int age;\n\n    /** The semester. */\n    @Column(name = \"SEMESTER\")\n    private char semester; // A,B,C,D,E,F for i to vi\n\n    /** The digital signature. */\n    @Column(name = \"DIGITAL_SIGNATURE\")\n    private byte digitalSignature;\n\n    /** The cgpa. */\n    @Column(name = \"CGPA\")\n    private short cgpa; // 1-10\n\n    /** The percentage. */\n    @Column(name = \"PERCENTAGE\")\n    private float percentage;\n\n    /** The height. */\n    @Column(name = \"HEIGHT\")\n    private double height;\n\n    // Date-time types\n    /** The enrolment date. */\n    @Column(name = \"ENROLMENT_DATE\")\n    @Temporal(TemporalType.DATE)\n    private java.util.Date enrolmentDate;\n\n    /** The enrolment time. */\n    @Column(name = \"ENROLMENT_TIME\")\n    @Temporal(TemporalType.TIME)\n    private java.util.Date enrolmentTime;\n\n    /** The joining date and time. */\n    @Column(name = \"JOINING_DATE_TIME\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private java.util.Date joiningDateAndTime;\n\n    // Wrapper types\n\n    /** The years spent. */\n    @Column(name = \"YEARS_SPENT\")\n    private Integer yearsSpent;\n\n    /** The roll number. */\n    @Column(name = \"ROLL_NUMBER\")\n    private Long rollNumber;\n\n    /** The monthly fee. */\n    @Column(name = \"MONTHLY_FEE\")\n    private Double monthlyFee;\n\n    /** The sql date. */\n    @Column(name = \"SQL_DATE\")\n    private java.sql.Date sqlDate;\n\n    /** The sql timestamp. */\n    @Column(name = \"SQL_TIMESTAMP\")\n    private java.sql.Timestamp sqlTimestamp;\n\n    /** The sql time. */\n    @Column(name = \"SQL_TIME\")\n    private java.sql.Time sqlTime;\n\n    /** The big integer. */\n    @Column(name = \"BIG_INT\")\n    private BigInteger bigInteger;\n\n    /** The big decimal. */\n    @Column(name = \"BIG_DECIMAL\")\n    private BigDecimal bigDecimal;\n\n    /** The calendar. */\n    @Column(name = \"CALENDAR\")\n    private Calendar calendar;\n\n    /**\n     * Gets the student id.\n     * \n     * @return the studentId\n     */\n    public long getStudentId()\n    {\n        return studentId;\n    }\n\n    /**\n     * Sets the student id.\n     * \n     * @param studentId\n     *            the studentId to set\n     */\n    public void setStudentId(long studentId)\n    {\n        this.studentId = studentId;\n    }\n\n    /**\n     * Gets the student name.\n     * \n     * @return the studentName\n     */\n    public String getStudentName()\n    {\n        return studentName;\n    }\n\n    /**\n     * Sets the student name.\n     * \n     * @param studentName\n     *            the studentName to set\n     */\n    public void setStudentName(String studentName)\n    {\n        this.studentName = studentName;\n    }\n\n    /**\n     * Checks if is exceptional.\n     * \n     * @return the isExceptional\n     */\n    public boolean isExceptional()\n    {\n        return isExceptional;\n    }\n\n    /**\n     * Sets the exceptional.\n     * \n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    public void setExceptional(boolean isExceptional)\n    {\n        this.isExceptional = isExceptional;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the semester.\n     * \n     * @return the semester\n     */\n    public char getSemester()\n    {\n        return semester;\n    }\n\n    /**\n     * Sets the semester.\n     * \n     * @param semester\n     *            the semester to set\n     */\n    public void setSemester(char semester)\n    {\n        this.semester = semester;\n    }\n\n    /**\n     * Gets the digital signature.\n     * \n     * @return the digitalSignature\n     */\n    public byte getDigitalSignature()\n    {\n        return digitalSignature;\n    }\n\n    /**\n     * Sets the digital signature.\n     * \n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    public void setDigitalSignature(byte digitalSignature)\n    {\n        this.digitalSignature = digitalSignature;\n    }\n\n    /**\n     * Gets the cgpa.\n     * \n     * @return the cgpa\n     */\n    public short getCgpa()\n    {\n        return cgpa;\n    }\n\n    /**\n     * Sets the cgpa.\n     * \n     * @param cgpa\n     *            the cgpa to set\n     */\n    public void setCgpa(short cgpa)\n    {\n        this.cgpa = cgpa;\n    }\n\n    /**\n     * Gets the percentage.\n     * \n     * @return the percentage\n     */\n    public float getPercentage()\n    {\n        return percentage;\n    }\n\n    /**\n     * Sets the percentage.\n     * \n     * @param percentage\n     *            the percentage to set\n     */\n    public void setPercentage(float percentage)\n    {\n        this.percentage = percentage;\n    }\n\n    /**\n     * Gets the height.\n     * \n     * @return the height\n     */\n    public double getHeight()\n    {\n        return height;\n    }\n\n    /**\n     * Sets the height.\n     * \n     * @param height\n     *            the height to set\n     */\n    public void setHeight(double height)\n    {\n        this.height = height;\n    }\n\n    /**\n     * Gets the enrolment date.\n     * \n     * @return the enrolmentDate\n     */\n    public java.util.Date getEnrolmentDate()\n    {\n        return enrolmentDate;\n    }\n\n    /**\n     * Sets the enrolment date.\n     * \n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    public void setEnrolmentDate(java.util.Date enrolmentDate)\n    {\n        this.enrolmentDate = enrolmentDate;\n    }\n\n    /**\n     * Gets the enrolment time.\n     * \n     * @return the enrolmentTime\n     */\n    public java.util.Date getEnrolmentTime()\n    {\n        return enrolmentTime;\n    }\n\n    /**\n     * Sets the enrolment time.\n     * \n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    public void setEnrolmentTime(java.util.Date enrolmentTime)\n    {\n        this.enrolmentTime = enrolmentTime;\n    }\n\n    /**\n     * Gets the joining date and time.\n     * \n     * @return the joiningDateAndTime\n     */\n    public java.util.Date getJoiningDateAndTime()\n    {\n        return joiningDateAndTime;\n    }\n\n    /**\n     * Sets the joining date and time.\n     * \n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    public void setJoiningDateAndTime(java.util.Date joiningDateAndTime)\n    {\n        this.joiningDateAndTime = joiningDateAndTime;\n    }\n\n    /**\n     * Gets the years spent.\n     * \n     * @return the yearsSpent\n     */\n    public Integer getYearsSpent()\n    {\n        return yearsSpent;\n    }\n\n    /**\n     * Sets the years spent.\n     * \n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    public void setYearsSpent(Integer yearsSpent)\n    {\n        this.yearsSpent = yearsSpent;\n    }\n\n    /**\n     * Gets the roll number.\n     * \n     * @return the rollNumber\n     */\n    public Long getRollNumber()\n    {\n        return rollNumber;\n    }\n\n    /**\n     * Sets the roll number.\n     * \n     * @param rollNumber\n     *            the rollNumber to set\n     */\n    public void setRollNumber(Long rollNumber)\n    {\n        this.rollNumber = rollNumber;\n    }\n\n    /**\n     * Gets the monthly fee.\n     * \n     * @return the monthlyFee\n     */\n    public Double getMonthlyFee()\n    {\n        return monthlyFee;\n    }\n\n    /**\n     * Sets the monthly fee.\n     * \n     * @param monthlyFee\n     *            the monthlyFee to set\n     */\n    public void setMonthlyFee(Double monthlyFee)\n    {\n        this.monthlyFee = monthlyFee;\n    }\n\n    /**\n     * Gets the sql date.\n     * \n     * @return the sql date\n     */\n    public java.sql.Date getSqlDate()\n    {\n        return sqlDate;\n    }\n\n    /**\n     * Sets the sql date.\n     * \n     * @param sqlDate\n     *            the new sql date\n     */\n    public void setSqlDate(java.sql.Date sqlDate)\n    {\n        this.sqlDate = sqlDate;\n    }\n\n    /**\n     * Gets the sql timestamp.\n     * \n     * @return the sqlTimestamp\n     */\n    public java.sql.Timestamp getSqlTimestamp()\n    {\n        return sqlTimestamp;\n    }\n\n    /**\n     * Sets the sql timestamp.\n     * \n     * @param sqlTimestamp\n     *            the sqlTimestamp to set\n     */\n    public void setSqlTimestamp(java.sql.Timestamp sqlTimestamp)\n    {\n        this.sqlTimestamp = sqlTimestamp;\n    }\n\n    /**\n     * Gets the sql time.\n     * \n     * @return the sqlTime\n     */\n    public java.sql.Time getSqlTime()\n    {\n        return sqlTime;\n    }\n\n    /**\n     * Sets the sql time.\n     * \n     * @param sqlTime\n     *            the sqlTime to set\n     */\n    public void setSqlTime(java.sql.Time sqlTime)\n    {\n        this.sqlTime = sqlTime;\n    }\n\n    /**\n     * Gets the big integer.\n     * \n     * @return the bigInteger\n     */\n    public BigInteger getBigInteger()\n    {\n        return bigInteger;\n    }\n\n    /**\n     * Sets the big integer.\n     * \n     * @param bigInteger\n     *            the bigInteger to set\n     */\n    public void setBigInteger(BigInteger bigInteger)\n    {\n        this.bigInteger = bigInteger;\n    }\n\n    /**\n     * Gets the big decimal.\n     * \n     * @return the bigDecimal\n     */\n    public BigDecimal getBigDecimal()\n    {\n        return bigDecimal;\n    }\n\n    /**\n     * Sets the big decimal.\n     * \n     * @param bigDecimal\n     *            the bigDecimal to set\n     */\n    public void setBigDecimal(BigDecimal bigDecimal)\n    {\n        this.bigDecimal = bigDecimal;\n    }\n\n    /**\n     * Gets the calendar.\n     * \n     * @return the calendar\n     */\n    public Calendar getCalendar()\n    {\n        return calendar;\n    }\n\n    /**\n     * Sets the calendar.\n     * \n     * @param calendar\n     *            the calendar to set\n     */\n    public void setCalendar(Calendar calendar)\n    {\n        this.calendar = calendar;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/query/StudentBaseTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.query;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\n\n/**\n * The Class StudentBase.\n * \n * @author Devender Yadav\n * \n */\npublic abstract class StudentBaseTest\n{\n\n    /** The Constant SCHEMA. */\n    protected static final String SCHEMA = \"HBaseNew\";\n\n    /** The Constant HBASE_PU. */\n    protected static final String HBASE_PU = \"queryTest\";\n\n    /** The emf. */\n    protected static EntityManagerFactory emf;\n\n    /** The em. */\n    protected EntityManager em;\n\n    /** The enrolment date. */\n    protected Date enrolmentDate = new Date();\n\n    /** The joining date and time. */\n    protected Date joiningDateAndTime = new Date();\n\n    /** The date. */\n    protected long date = new Date().getTime();\n\n    /** The new sql date. */\n    protected java.sql.Date sqlDate = new java.sql.Date(date);\n\n    /** The enrolment time. */\n    protected Date enrolmentTime = new Date();\n\n    /** The sql time. */\n    protected java.sql.Time sqlTime = new java.sql.Time(date);\n\n    /** The sql timestamp. */\n    protected java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(date);\n\n    /** The big decimal. */\n    protected BigDecimal bigDecimal = new BigDecimal(123456789);\n\n    /** The big integer. */\n    protected BigInteger bigInteger = new BigInteger(\"123456789\");\n\n    /** The calendar. */\n    protected Calendar calendar = Calendar.getInstance();\n\n    /**\n     * Persist students.\n     */\n    protected void persistStudents()\n    {\n\n        Student s1 = prepareData(12345677L, \"Amresh\", false, 10, 'A', (byte) 5, (short) 8, (float) 61.6, 163.76765654,\n                enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(978423946455l), 135434.89,\n                sqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar);\n        Student s2 = prepareData(12345678L, \"Devender\", true, 20, 'B', (byte) 50, (short) 8, (float) 63.6,\n                163.76765655, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3),\n                new Long(978423946455l), 135434.89, sqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar);\n        Student s3 = prepareData(12345679L, \"Pragalbh\", true, 15, 'C', (byte) 50, (short) 8, (float) 69.6,\n                163.76765656, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3),\n                new Long(978423946455l), 135434.89, sqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar);\n\n        em.persist(s1);\n        em.persist(s2);\n        em.persist(s3);\n        em.clear();\n\n    }\n\n    /**\n     * Delete students.\n     */\n    protected void deleteStudents()\n    {\n        em.createQuery(\"delete from Student s\").executeUpdate();\n        em.clear();\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param studentId\n     *            the student id\n     * @param studentName\n     *            the student name\n     * @param isExceptional\n     *            the is exceptional\n     * @param age\n     *            the age\n     * @param semester\n     *            the semester\n     * @param digitalSignature\n     *            the digital signature\n     * @param cgpa\n     *            the cgpa\n     * @param percentage\n     *            the percentage\n     * @param height\n     *            the height\n     * @param enrolmentDate\n     *            the enrolment date\n     * @param enrolmentTime\n     *            the enrolment time\n     * @param joiningDateAndTime\n     *            the joining date and time\n     * @param yearsSpent\n     *            the years spent\n     * @param rollNumber\n     *            the roll number\n     * @param monthlyFee\n     *            the monthly fee\n     * @param newSqlDate\n     *            the new sql date\n     * @param sqlTime\n     *            the sql time\n     * @param sqlTimestamp\n     *            the sql timestamp\n     * @param bigDecimal\n     *            the big decimal\n     * @param bigInteger\n     *            the big integer\n     * @param calendar\n     *            the calendar\n     * @return the student\n     */\n    protected Student prepareData(long studentId, String studentName, boolean isExceptional, int age, char semester,\n            byte digitalSignature, short cgpa, float percentage, double height, java.util.Date enrolmentDate,\n            java.util.Date enrolmentTime, java.util.Date joiningDateAndTime, Integer yearsSpent, Long rollNumber,\n            Double monthlyFee, java.sql.Date newSqlDate, java.sql.Time sqlTime, java.sql.Timestamp sqlTimestamp,\n            BigDecimal bigDecimal, BigInteger bigInteger, Calendar calendar)\n    {\n        Student s = new Student();\n        s.setStudentId(studentId);\n        s.setStudentName(studentName);\n        s.setExceptional(isExceptional);\n        s.setAge(age);\n        s.setSemester(semester);\n        s.setDigitalSignature(digitalSignature);\n        s.setCgpa(cgpa);\n        s.setPercentage(percentage);\n        s.setHeight(height);\n        s.setEnrolmentDate(enrolmentDate);\n        s.setEnrolmentTime(enrolmentTime);\n        s.setJoiningDateAndTime(joiningDateAndTime);\n        s.setYearsSpent(yearsSpent);\n        s.setRollNumber(rollNumber);\n        s.setMonthlyFee(monthlyFee);\n        s.setSqlDate(newSqlDate);\n        s.setSqlTime(sqlTime);\n        s.setSqlTimestamp(sqlTimestamp);\n        s.setBigDecimal(bigDecimal);\n        s.setBigInteger(bigInteger);\n        s.setCalendar(calendar);\n        return s;\n    }\n}\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\n\t<persistence-unit name=\"schemaTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.hbase.schema.ProductHBase</class>\n\t\t<class>com.impetus.client.hbase.schema.UserHBase</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"HBaseNew\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kundera-hbase.properties\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"secTableTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.hbase.secondarytable.HbaseSecondaryTableEntity</class>\n\t\t<class>com.impetus.client.hbase.secondarytable.PersonSecondaryTableAddress</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"HBaseNew\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kundera-hbase.properties\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"crudTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.hbase.crud.PersonHBase</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"HBaseNew\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kundera-hbase.properties\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"queryTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.query.Book</class>\n\t\t<class>com.impetus.client.query.HBasePerson</class>\n\t\t<class>com.impetus.client.hbase.validator.BookEntity</class>\n\t\t<class>com.impetus.client.query.Student</class>\n\t\t<class>com.impetus.client.hbase.crud.compositetype.HBasePrimeUser</class>\n\t\t<class>com.impetus.kundera.query.Person</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"HBaseNew\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kundera-hbase.properties\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"associationTest\">\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileHandset</class>\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileManufacturer</class>\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileOperatingSystem</class>\n\t\t<class>com.impetus.client.hbase.crud.association.UserOTM</class>\n\t\t<class>com.impetus.client.hbase.crud.association.PersonUniOTO</class>\n\t\t<class>com.impetus.client.hbase.crud.association.PersonBiOTO</class>\n\t\t<class>com.impetus.client.hbase.crud.association.AddressUniOTO</class>\n\t\t<class>com.impetus.client.hbase.crud.association.AddressBiOTO</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"HBaseNew\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"embeddablesTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.hbase.crud.embedded.PersonEmbed</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"HBaseNew\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"autoIdTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"HBaseNew\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"dataTypeTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBigDecimal</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBigInteger</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBooleanPrimitive</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBooleanWrapper</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseBytePrimitive</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseByteWrapper</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseCalendar</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseChar</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseCharacter</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseDate</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseDoublePrimitive</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseDoubleWrapper</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseFloatPrimitive</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseFloatWrapper</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseInt</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseInteger</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseLongPrimitive</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseLongWrapper</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseShortPrimitive</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseShortWrapper</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseSqlDate</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseString</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseTime</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseTimestamp</class>\n\t\t<class>com.impetus.client.hbase.crud.datatypes.entities.StudentHBaseUUID</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"HBaseNew\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kundera-hbase.properties\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"transactionTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.hbase.transaction.User</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"HBaseNew\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"XmlPropertyTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaHbaseXmlTest\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaTest.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"mtmTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.hbase.crud.association.PersonnelMToM</class>\n\t\t<class>com.impetus.client.hbase.crud.association.HabitatMToM</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"HBaseNew\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"inheritenceTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.hbase.crud.inheritence.SocialProfile</class>\n\t\t<class>com.impetus.client.hbase.crud.inheritence.TwitterProfile</class>\n\t\t<class>com.impetus.client.hbase.crud.inheritence.FacebookProfile</class>\n\t\t<class>com.impetus.client.hbase.crud.inheritence.UserAccount</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"HBaseNew\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"mappedSuperClassTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.client.crud.mappedsuperclass.Transaction</class>\n\t\t<class>com.impetus.kundera.client.crud.mappedsuperclass.CreditTransaction</class>\n\t\t<class>com.impetus.kundera.client.crud.mappedsuperclass.DebitTransaction</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"HBaseNew\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"entityWithoutFieldTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.MappedPerson</class>\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.Person</class>\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.PersonChild</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"HBaseNew\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n</persistence>\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/resources/META-INF/persistence_2_0.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!-- persistence.xml schema -->\r\n<xsd:schema targetNamespace=\"http://java.sun.com/xml/ns/persistence\" \r\n  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\r\n  xmlns:persistence=\"http://java.sun.com/xml/ns/persistence\"\r\n  elementFormDefault=\"qualified\" \r\n  attributeFormDefault=\"unqualified\" \r\n  version=\"2.0\">\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n      @(#)persistence_2_0.xsd  1.0  October 1 2009\r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n\r\n  Copyright (c) 2008, 2009 Sun Microsystems. All rights reserved. \r\n  \r\n  This program and the accompanying materials are made available under the \r\n  terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 \r\n  which accompanies this distribution. \r\n  The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html\r\n  and the Eclipse Distribution License is available at \r\n  http://www.eclipse.org/org/documents/edl-v10.php.\r\n  \r\n  Contributors:\r\n      Linda DeMichiel - Java Persistence 2.0, Version 2.0 (October 1, 2009)\r\n      Specification available from http://jcp.org/en/jsr/detail?id=317\r\n \r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n   <xsd:annotation>\r\n     <xsd:documentation><![CDATA[\r\n\r\n     This is the XML Schema for the persistence configuration file.\r\n     The file must be named \"META-INF/persistence.xml\" in the \r\n     persistence archive.\r\n\r\n     Persistence configuration files must indicate\r\n     the persistence schema by using the persistence namespace:\r\n\r\n     http://java.sun.com/xml/ns/persistence\r\n\r\n     and indicate the version of the schema by\r\n     using the version element as shown below:\r\n\r\n      <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n        xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n          http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\"\r\n        version=\"2.0\">\r\n          ...\r\n      </persistence>\r\n\r\n    ]]></xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:simpleType name=\"versionType\">\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:pattern value=\"[0-9]+(\\.[0-9]+)*\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:element name=\"persistence\">\r\n    <xsd:complexType>\r\n      <xsd:sequence>\r\n\r\n        <!-- **************************************************** -->\r\n\r\n        <xsd:element name=\"persistence-unit\" \r\n                     minOccurs=\"1\" maxOccurs=\"unbounded\">\r\n          <xsd:complexType>\r\n            <xsd:annotation>\r\n              <xsd:documentation>\r\n\r\n                Configuration of a persistence unit.\r\n\r\n              </xsd:documentation>\r\n            </xsd:annotation>\r\n            <xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"description\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Description of this persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"provider\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Provider class that supplies EntityManagers for this \r\n                    persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of the JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"non-jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of a non-JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"mapping-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    File containing mapping information. Loaded as a resource \r\n                    by the persistence provider.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jar-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Jar file that is to be scanned for managed classes. \r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"class\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Managed class to be included in the persistence unit and\r\n                    to scan for annotations.  It should be annotated \r\n                    with either @Entity, @Embeddable or @MappedSuperclass.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"exclude-unlisted-classes\" type=\"xsd:boolean\" \r\n                           default=\"true\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    When set to true then only listed classes and jars will \r\n                    be scanned for persistent classes, otherwise the \r\n                    enclosing jar or directory will also be scanned. \r\n                    Not applicable to Java SE persistence units.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"shared-cache-mode\" \r\n                           type=\"persistence:persistence-unit-caching-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Defines whether caching is enabled for the \r\n                    persistence unit if caching is supported by the\r\n                    persistence provider. When set to ALL, all entities \r\n                    will be cached. When set to NONE, no entities will\r\n                    be cached. When set to ENABLE_SELECTIVE, only entities\r\n                    specified as cacheable will be cached. When set to\r\n                    DISABLE_SELECTIVE, entities specified as not cacheable\r\n                    will not be cached. When not specified or when set to\r\n                    UNSPECIFIED, provider defaults may apply.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"validation-mode\" \r\n                           type=\"persistence:persistence-unit-validation-mode-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The validation mode to be used for the persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"properties\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    A list of standard and vendor-specific properties \r\n                    and hints.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n                <xsd:complexType>\r\n                  <xsd:sequence>\r\n                    <xsd:element name=\"property\" \r\n                                 minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                      <xsd:annotation>\r\n                        <xsd:documentation>\r\n                          A name-value pair.\r\n                        </xsd:documentation>\r\n                      </xsd:annotation>\r\n                      <xsd:complexType>\r\n                        <xsd:attribute name=\"name\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                        <xsd:attribute name=\"value\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                      </xsd:complexType>\r\n                    </xsd:element>\r\n                  </xsd:sequence>\r\n                </xsd:complexType>\r\n              </xsd:element>\r\n\r\n            </xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Name used in code to reference this persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"transaction-type\" \r\n                           type=\"persistence:persistence-unit-transaction-type\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Type of transactions used by EntityManagers from this \r\n                  persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n          </xsd:complexType>\r\n        </xsd:element>\r\n      </xsd:sequence>\r\n      <xsd:attribute name=\"version\" type=\"persistence:versionType\" \r\n                     fixed=\"2.0\" use=\"required\"/>\r\n    </xsd:complexType>\r\n  </xsd:element>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-transaction-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum PersistenceUnitTransactionType {JTA, RESOURCE_LOCAL};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"JTA\"/>\r\n      <xsd:enumeration value=\"RESOURCE_LOCAL\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-caching-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum SharedCacheMode { ALL, NONE, ENABLE_SELECTIVE, DISABLE_SELECTIVE, UNSPECIFIED};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"ALL\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n      <xsd:enumeration value=\"ENABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"DISABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"UNSPECIFIED\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-validation-mode-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum ValidationMode { AUTO, CALLBACK, NONE};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"AUTO\"/>\r\n      <xsd:enumeration value=\"CALLBACK\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n</xsd:schema>\r\n"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/resources/esindexer.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<indexerProperties>\n\t<nodes>\n\t\t<node>\n\t\t\t<properties>\n\t\t\t\t<property name=\"host\" value=\"localhost\" />\n\t\t\t\t<property name=\"port\" value=\"9300\" />\n\t\t\t</properties>\n\t\t</node>\n\t</nodes>\n</indexerProperties>"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/resources/kundera-hbase.properties",
    "content": "zookeeper.port = 2182\nzookeeper.host = localhost\ncf.defs=HBaseEntity|GZ|123456|5|2"
  },
  {
    "path": "src/kundera-hbase/kundera-hbase-v2/src/test/resources/log4j.properties",
    "content": "log4j.rootLogger=ERROR, DRFA, CONSOLE\r\n\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n"
  },
  {
    "path": "src/kundera-hbase/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus</groupId>\n\t\t<artifactId>kundera</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-hbase-parent</artifactId>\n\t<packaging>pom</packaging>\n\t<name>kundera-hbase-parent</name>\n\t<url>http://maven.apache.org</url>\n\n\t<!-- Dependencies -->\n\t<dependencies>\n\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-elastic-search</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\n\t\t<dependency>\n\t\t\t<groupId>org.slf4j</groupId>\n\t\t\t<artifactId>slf4j-log4j12</artifactId>\n\t\t\t<version>1.6.3</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.slf4j</groupId>\n\t\t\t<artifactId>slf4j-api</artifactId>\n\t\t\t<version>1.6.3</version>\n\t\t</dependency>\n\n\t</dependencies>\n\t<profiles>\n\n\t\t<profile>\n\t\t\t<id>all</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>true</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>kundera-hbase</module>\n\t\t\t\t<module>kundera-hbase-v2</module>\n\t\t\t</modules>\n\t\t</profile>\n\t\t<profile>\n\t\t\t<id>hbase</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>kundera-hbase</module>\n\t\t\t</modules>\n\t\t</profile>\n\n\t\t<profile>\n\t\t\t<id>hbase-v2</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>kundera-hbase-v2</module>\n\t\t\t</modules>\n\t\t</profile>\n\t</profiles>\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-clean-plugin</artifactId>\n\t\t\t\t<version>2.4.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<filesets>\n\t\t\t\t\t\t<fileset>\n\t\t\t\t\t\t\t<directory>${basedir}</directory>\n\t\t\t\t\t\t\t<excludes>\n\t\t\t\t\t\t\t\t<exclude>.git/**</exclude>\n\t\t\t\t\t\t\t\t<exclude>.gitignore</exclude>\n\t\t\t\t\t\t\t</excludes>\n\t\t\t\t\t\t\t<includes>\n\t\t\t\t\t\t\t\t<include>lucene/**</include>\n\t\t\t\t\t\t\t</includes>\n\t\t\t\t\t\t</fileset>\n\t\t\t\t\t</filesets>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\n\n</project>\n"
  },
  {
    "path": "src/kundera-kudu/pom.xml",
    "content": "<?xml version=\"1.0\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<artifactId>kundera</artifactId>\n\t\t<groupId>com.impetus</groupId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-kudu</artifactId>\n\t<name>kundera-kudu</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<kudu.version>1.2.0</kudu.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<!-- Kundera dependencies -->\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-elastic-search</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<!-- kudu dependencies -->\n\n\t\t<dependency>\n\t\t\t<groupId>org.apache.kudu</groupId>\n\t\t\t<artifactId>kudu-client</artifactId>\n\t\t\t<version>${kudu.version}</version>\n\t\t</dependency>\n\n\t</dependencies>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n"
  },
  {
    "path": "src/kundera-kudu/src/main/java/com/impetus/client/kudu/KuduDBClient.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu;\n\nimport java.lang.reflect.Field;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Embeddable;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.kudu.ColumnSchema;\nimport org.apache.kudu.Type;\nimport org.apache.kudu.client.Delete;\nimport org.apache.kudu.client.KuduClient;\nimport org.apache.kudu.client.KuduPredicate;\nimport org.apache.kudu.client.KuduScanner;\nimport org.apache.kudu.client.KuduScanner.KuduScannerBuilder;\nimport org.apache.kudu.client.KuduSession;\nimport org.apache.kudu.client.KuduTable;\nimport org.apache.kudu.client.Operation;\nimport org.apache.kudu.client.PartialRow;\nimport org.apache.kudu.client.RowResult;\nimport org.apache.kudu.client.RowResultIterator;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.kudu.query.KuduDBQuery;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * The Class KuduDBClient.\n * \n * @author karthikp.manchala\n */\npublic class KuduDBClient extends ClientBase implements Client<KuduDBQuery>, ClientPropertiesSetter\n{\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(KuduDBClient.class);\n\n    /** The kudu client. */\n    private KuduClient kuduClient;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /**\n     * Instantiates a new kudu db client.\n     *\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param indexManager\n     *            the index manager\n     * @param reader\n     *            the reader\n     * @param properties\n     *            the properties\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param kuduClient\n     *            the kudu client\n     * @param clientMetadata\n     *            the client metadata\n     */\n    protected KuduDBClient(KunderaMetadata kunderaMetadata, IndexManager indexManager, EntityReader reader,\n            Map<String, Object> properties, String persistenceUnit, KuduClient kuduClient,\n            ClientMetadata clientMetadata)\n    {\n        super(kunderaMetadata, properties, persistenceUnit);\n        this.reader = reader;\n        this.kuduClient = kuduClient;\n        this.indexManager = indexManager;\n        this.clientMetadata = clientMetadata;\n    }\n\n    /**\n     * Gets the kudu client.\n     * \n     * @return the kudu client\n     */\n    public KuduClient getKuduClient()\n    {\n        return kuduClient;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientPropertiesSetter#\n     * populateClientProperties(com.impetus.kundera.client.Client,\n     * java.util.Map)\n     */\n    /**\n     * Populate client properties.\n     * \n     * @param client\n     *            the client\n     * @param properties\n     *            the properties\n     */\n    @Override\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    { // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.Object)\n     */\n    /**\n     * Find.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param key\n     *            the key\n     * @return the object\n     */\n    @Override\n    public Object find(Class entityClass, Object key)\n    {\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(entityMetadata.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n\n        String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getName();\n\n        Field field = (Field) entityType.getAttribute(idColumnName).getJavaMember();\n\n        Type idType = KuduDBValidationClassMapper.getValidTypeForClass(field.getType());\n\n        KuduTable table;\n        try\n        {\n            table = kuduClient.openTable(entityMetadata.getTableName());\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Cannot open table : \" + entityMetadata.getTableName(), e);\n            throw new KunderaException(\"Cannot open table : \" + entityMetadata.getTableName(), e);\n        }\n\n        KuduScannerBuilder scannerBuilder = kuduClient.newScannerBuilder(table);\n        KuduScanner scanner = null;\n\n        if (entityType.getAttribute(idColumnName).getJavaType().isAnnotationPresent(Embeddable.class))\n        {\n            // Composite Id\n            EmbeddableType embeddableIdType = metaModel.embeddable(entityType.getAttribute(idColumnName).getJavaType());\n            Field[] fields = entityType.getAttribute(idColumnName).getJavaType().getDeclaredFields();\n\n            addPredicatesToScannerBuilder(scannerBuilder, embeddableIdType, fields, metaModel, key);\n        }\n        else\n        {\n            // Simple Id\n            ColumnSchema column = new ColumnSchema.ColumnSchemaBuilder(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName(), idType).build();\n\n            KuduPredicate predicate = KuduDBDataHandler.getEqualComparisonPredicate(column, idType, key);\n            scannerBuilder.addPredicate(predicate);\n        }\n\n        scanner = scannerBuilder.build();\n\n        Object entity = null;\n        while (scanner.hasMoreRows())\n        {\n            RowResultIterator results;\n            try\n            {\n                results = scanner.nextRows();\n            }\n            catch (Exception e)\n            {\n                logger.error(\"Cannot get results from table : \" + entityMetadata.getTableName(), e);\n                throw new KunderaException(\"Cannot get results from table : \" + entityMetadata.getTableName(), e);\n            }\n\n            while (results.hasNext())\n            {\n                RowResult result = results.next();\n                entity = KunderaCoreUtils.createNewInstance(entityClass);\n                populateEntity(entity, result, entityType, metaModel);\n                logger.debug(result.rowToString());\n            }\n        }\n        return entity;\n    }\n\n    /**\n     * Adds the predicates to scanner builder.\n     *\n     * @param scannerBuilder\n     *            the scanner builder\n     * @param embeddable\n     *            the embeddable\n     * @param fields\n     *            the fields\n     * @param metaModel\n     *            the meta model\n     * @param key\n     *            the key\n     */\n    private void addPredicatesToScannerBuilder(KuduScannerBuilder scannerBuilder, EmbeddableType embeddable,\n            Field[] fields, MetamodelImpl metaModel, Object key)\n    {\n        for (Field f : fields)\n        {\n            if (!ReflectUtils.isTransientOrStatic(f))\n            {\n                Object value = PropertyAccessorHelper.getObject(key, f);\n                if (f.getType().isAnnotationPresent(Embeddable.class))\n                {\n                    // nested\n                    addPredicatesToScannerBuilder(scannerBuilder, (EmbeddableType) metaModel.embeddable(f.getType()),\n                            f.getType().getDeclaredFields(), metaModel, value);\n                }\n                else\n                {\n\n                    Attribute attribute = embeddable.getAttribute(f.getName());\n                    Type type = KuduDBValidationClassMapper.getValidTypeForClass(f.getType());\n                    ColumnSchema column = new ColumnSchema.ColumnSchemaBuilder(\n                            ((AbstractAttribute) attribute).getJPAColumnName(), type).build();\n                    KuduPredicate predicate = KuduDBDataHandler.getEqualComparisonPredicate(column, type, value);\n                    scannerBuilder.addPredicate(predicate);\n                }\n            }\n        }\n\n    }\n\n    /**\n     * Populate entity.\n     * \n     * @param entity\n     *            the entity\n     * @param result\n     *            the result\n     * @param entityType\n     *            the entity type\n     * @param metaModel\n     *            the meta model\n     */\n    public void populateEntity(Object entity, RowResult result, EntityType entityType, MetamodelImpl metaModel)\n    {\n        Set<Attribute> attributes = entityType.getAttributes();\n        Iterator<Attribute> iterator = attributes.iterator();\n        iterateAndPopulateEntity(entity, result, metaModel, iterator);\n    }\n\n    /**\n     * Populate embedded column.\n     * \n     * @param entity\n     *            the entity\n     * @param result\n     *            the result\n     * @param embeddable\n     *            the embeddable\n     * @param metaModel\n     *            the meta model\n     */\n    private void populateEmbeddedColumn(Object entity, RowResult result, EmbeddableType embeddable,\n            MetamodelImpl metaModel)\n    {\n        Set<Attribute> attributes = embeddable.getAttributes();\n        Iterator<Attribute> iterator = attributes.iterator();\n\n        iterateAndPopulateEntity(entity, result, metaModel, iterator);\n    }\n\n    /**\n     * Iterate and populate entity.\n     * \n     * @param entity\n     *            the entity\n     * @param result\n     *            the result\n     * @param metaModel\n     *            the meta model\n     * @param iterator\n     *            the iterator\n     */\n    private void iterateAndPopulateEntity(Object entity, RowResult result, MetamodelImpl metaModel,\n            Iterator<Attribute> iterator)\n    {\n        while (iterator.hasNext())\n        {\n            Attribute attribute = iterator.next();\n            Field field = (Field) attribute.getJavaMember();\n            // handle for embeddables\n            if (attribute.getJavaType().isAnnotationPresent(Embeddable.class))\n            {\n                EmbeddableType emb = metaModel.embeddable(attribute.getJavaType());\n                Object embeddableObj = KunderaCoreUtils.createNewInstance(attribute.getJavaType());\n                populateEmbeddedColumn(embeddableObj, result, emb, metaModel);\n                PropertyAccessorHelper.set(entity, field, embeddableObj);\n            }\n            else\n            {\n                if (KuduDBDataHandler.hasColumn(result.getSchema(), ((AbstractAttribute) attribute).getJPAColumnName()))\n                {\n                    PropertyAccessorHelper.set(entity, field, KuduDBDataHandler.getColumnValue(result,\n                            ((AbstractAttribute) attribute).getJPAColumnName()));\n                }\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.String[], java.lang.Object[])\n     */\n    /**\n     * Find all.\n     * \n     * @param <E>\n     *            the element type\n     * @param entityClass\n     *            the entity class\n     * @param columnsToSelect\n     *            the columns to select\n     * @param keys\n     *            the keys\n     * @return the list\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    /**\n     * Find.\n     * \n     * @param <E>\n     *            the element type\n     * @param entityClass\n     *            the entity class\n     * @param embeddedColumnMap\n     *            the embedded column map\n     * @return the list\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    { // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    /**\n     * Close.\n     */\n    @Override\n    public void close()\n    {// TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera.\n     * persistence.context.jointable.JoinTableData )\n     */\n    /**\n     * Persist join table.\n     * \n     * @param joinTableData\n     *            the join table data\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {// TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    /**\n     * Gets the columns by id.\n     * \n     * @param <E>\n     *            the element type\n     * @param schemaName\n     *            the schema name\n     * @param tableName\n     *            the table name\n     * @param pKeyColumnName\n     *            the key column name\n     * @param columnName\n     *            the column name\n     * @param pKeyColumnValue\n     *            the key column value\n     * @param columnJavaType\n     *            the column java type\n     * @return the columns by id\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,\n            Object pKeyColumnValue, Class columnJavaType)\n    {// TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    /**\n     * Find ids by column.\n     * \n     * @param schemaName\n     *            the schema name\n     * @param tableName\n     *            the table name\n     * @param pKeyName\n     *            the key name\n     * @param columnName\n     *            the column name\n     * @param columnValue\n     *            the column value\n     * @param entityClazz\n     *            the entity clazz\n     * @return the object[]\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {// TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    /**\n     * Delete by column.\n     * \n     * @param schemaName\n     *            the schema name\n     * @param tableName\n     *            the table name\n     * @param columnName\n     *            the column name\n     * @param columnValue\n     *            the column value\n     */\n    @Override\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    { // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    /**\n     * Find by relation.\n     * \n     * @param colName\n     *            the col name\n     * @param colValue\n     *            the col value\n     * @param entityClazz\n     *            the entity clazz\n     * @return the list\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {// TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    /**\n     * Gets the reader.\n     * \n     * @return the reader\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    /**\n     * Gets the query implementor.\n     * \n     * @return the query implementor\n     */\n    @Override\n    public Class<KuduDBQuery> getQueryImplementor()\n    {\n        return KuduDBQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    /**\n     * Gets the id generator.\n     * \n     * @return the id generator\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        return (Generator) KunderaCoreUtils.createNewInstance(KuduDBIdGenerator.class);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.\n     * metadata.model.EntityMetadata, java.lang.Object, java.lang.Object,\n     * java.util.List)\n     */\n    /**\n     * On persist.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @param id\n     *            the id\n     * @param rlHolders\n     *            the rl holders\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n\n        KuduSession session = kuduClient.newSession();\n        KuduTable table = null;\n        try\n        {\n            table = kuduClient.openTable(entityMetadata.getTableName());\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Cannot open table : \" + entityMetadata.getTableName(), e);\n            throw new KunderaException(\"Cannot open table : \" + entityMetadata.getTableName(), e);\n        }\n        Operation operation = isUpdate ? table.newUpdate() : table.newInsert();\n        PartialRow row = operation.getRow();\n        populatePartialRow(row, entityMetadata, entity);\n        try\n        {\n            session.apply(operation);\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Cannot insert/update row in table : \" + entityMetadata.getTableName(), e);\n            throw new KunderaException(\"Cannot insert/update row in table : \" + entityMetadata.getTableName(), e);\n        }\n        finally\n        {\n            try\n            {\n                session.close();\n            }\n            catch (Exception e)\n            {\n                logger.error(\"Cannot close session\", e);\n                throw new KunderaException(\"Cannot close session\", e);\n            }\n        }\n    }\n\n    /**\n     * Populate partial row.\n     * \n     * @param row\n     *            the row\n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     */\n    private void populatePartialRow(PartialRow row, EntityMetadata entityMetadata, Object entity)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(entityMetadata.getPersistenceUnit());\n        Class entityClazz = entityMetadata.getEntityClazz();\n        EntityType entityType = metaModel.entity(entityClazz);\n        Set<Attribute> attributes = entityType.getAttributes();\n        Iterator<Attribute> iterator = attributes.iterator();\n        iterateAndPopulateRow(row, entity, metaModel, iterator);\n    }\n\n    /**\n     * Populate partial row for embedded column.\n     * \n     * @param row\n     *            the row\n     * @param embeddable\n     *            the embeddable\n     * @param EmbEntity\n     *            the emb entity\n     * @param metaModel\n     *            the meta model\n     */\n    private void populatePartialRowForEmbeddedColumn(PartialRow row, EmbeddableType embeddable, Object EmbEntity,\n            MetamodelImpl metaModel)\n    {\n        Set<Attribute> attributes = embeddable.getAttributes();\n        Iterator<Attribute> iterator = attributes.iterator();\n        iterateAndPopulateRow(row, EmbEntity, metaModel, iterator);\n    }\n\n    /**\n     * Iterate and populate row.\n     * \n     * @param row\n     *            the row\n     * @param entity\n     *            the entity\n     * @param metaModel\n     *            the meta model\n     * @param iterator\n     *            the iterator\n     */\n    private void iterateAndPopulateRow(PartialRow row, Object entity, MetamodelImpl metaModel,\n            Iterator<Attribute> iterator)\n    {\n        while (iterator.hasNext())\n        {\n            Attribute attribute = iterator.next();\n            Field field = (Field) attribute.getJavaMember();\n            Object value = PropertyAccessorHelper.getObject(entity, field);\n            if (attribute.getJavaType().isAnnotationPresent(Embeddable.class))\n            {\n                EmbeddableType emb = metaModel.embeddable(attribute.getJavaType());\n                populatePartialRowForEmbeddedColumn(row, emb, value, metaModel);\n            }\n            else\n            {\n                Type type = KuduDBValidationClassMapper.getValidTypeForClass(field.getType());\n                if (type != null)\n                {\n                    KuduDBDataHandler.addToRow(row, ((AbstractAttribute) attribute).getJPAColumnName(), value, type);\n                }\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientBase#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    /**\n     * Delete.\n     * \n     * @param entity\n     *            the entity\n     * @param pKey\n     *            the key\n     */\n    @Override\n    protected void delete(Object entity, Object pKey)\n    {\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(entityMetadata.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n\n        KuduSession session = kuduClient.newSession();\n        KuduTable table = null;\n        try\n        {\n            table = kuduClient.openTable(entityMetadata.getTableName());\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Cannot open table : \" + entityMetadata.getTableName(), e);\n            throw new KunderaException(\"Cannot open table : \" + entityMetadata.getTableName(), e);\n        }\n        Delete delete = table.newDelete();\n        PartialRow row = delete.getRow();\n        String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getName();\n\n        Field field = (Field) entityType.getAttribute(idColumnName).getJavaMember();\n        Object value = PropertyAccessorHelper.getObject(entity, field);\n        Type idType = KuduDBValidationClassMapper.getValidTypeForClass(field.getType());\n\n        if (entityType.getAttribute(idColumnName).getJavaType().isAnnotationPresent(Embeddable.class))\n        {\n            // Composite Id\n            EmbeddableType embeddableIdType = metaModel.embeddable(entityType.getAttribute(idColumnName).getJavaType());\n            Field[] fields = entityType.getAttribute(idColumnName).getJavaType().getDeclaredFields();\n            addPrimaryKeyToRow(row, embeddableIdType, fields, metaModel, value);\n        }\n        else\n        {\n            // Simple Id\n            KuduDBDataHandler.addToRow(row, ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName(),\n                    value, idType);\n        }\n\n        try\n        {\n            session.apply(delete);\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Cannot delete row from table : \" + entityMetadata.getTableName(), e);\n            throw new KunderaException(\"Cannot delete row from table : \" + entityMetadata.getTableName(), e);\n        }\n        finally\n        {\n            try\n            {\n                session.close();\n            }\n            catch (Exception e)\n            {\n                logger.error(\"Cannot close session\", e);\n                throw new KunderaException(\"Cannot close session\", e);\n            }\n        }\n    }\n\n    /**\n     * Adds the primary key to row.\n     *\n     * @param row\n     *            the row\n     * @param embeddable\n     *            the embeddable\n     * @param fields\n     *            the fields\n     * @param metaModel\n     *            the meta model\n     * @param key\n     *            the key\n     */\n    private void addPrimaryKeyToRow(PartialRow row, EmbeddableType embeddable, Field[] fields, MetamodelImpl metaModel,\n            Object key)\n    {\n        for (Field f : fields)\n        {\n            if (!ReflectUtils.isTransientOrStatic(f))\n            {\n                Object value = PropertyAccessorHelper.getObject(key, f);\n                if (f.getType().isAnnotationPresent(Embeddable.class))\n                {\n                    // nested\n                    addPrimaryKeyToRow(row, (EmbeddableType) metaModel.embeddable(f.getType()),\n                            f.getType().getDeclaredFields(), metaModel, value);\n                }\n                else\n                {\n                    Attribute attribute = embeddable.getAttribute(f.getName());\n                    Type type = KuduDBValidationClassMapper.getValidTypeForClass(f.getType());\n                    KuduDBDataHandler.addToRow(row, ((AbstractAttribute) attribute).getJPAColumnName(), value, type);\n                }\n\n            }\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/main/java/com/impetus/client/kudu/KuduDBClientFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu;\n\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.apache.kudu.client.KuduClient;\n\nimport com.impetus.client.kudu.query.KuduDBEntityReader;\nimport com.impetus.client.kudu.schemamanager.KuduDBSchemaManager;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * A factory for creating KuduDBClient objects.\n * \n * @author karthikp.manchala\n */\npublic class KuduDBClientFactory extends GenericClientFactory\n{\n\n    /** The kudu client. */\n    private KuduClient kuduClient;\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.ClientFactory#getSchemaManager(java.util.Map)\n     */\n    @Override\n    public SchemaManager getSchemaManager(Map<String, Object> puProperties)\n    {\n        if (schemaManager == null)\n        {\n            initializePropertyReader();\n            setExternalProperties(puProperties);\n            schemaManager = new KuduDBSchemaManager(KuduDBClientFactory.class.getName(), puProperties, kunderaMetadata);\n        }\n        return schemaManager;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.ClientLifeCycleManager#destroy()\n     */\n    @Override\n    public void destroy()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initialize(java.util.Map)\n     */\n    @Override\n    public void initialize(Map<String, Object> puProperties)\n    {\n        reader = new KuduDBEntityReader(kunderaMetadata);\n        setExternalProperties(puProperties);\n        initializePropertyReader();\n        PersistenceUnitMetadata pum = kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(getPersistenceUnit());\n\n        Properties pumProps = pum.getProperties();\n\n        if (puProperties != null)\n        {\n            pumProps.putAll(puProperties);\n        }\n\n        String kuduMasterHost = (String) pumProps.getProperty(\"kundera.nodes\");\n\n        String kuduMasterPort = (String) pumProps.getProperty(\"kundera.port\");\n\n        if (kuduMasterHost == null || kuduMasterPort == null)\n        {\n            throw new KunderaException(\"Hostname/IP or Port is null.\");\n        }\n\n        kuduClient = new KuduClient.KuduClientBuilder(kuduMasterHost + \":\" + kuduMasterPort).build();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#createPoolOrConnection()\n     */\n    @Override\n    protected Object createPoolOrConnection()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#instantiateClient(java.\n     * lang.String)\n     */\n    @Override\n    protected Client instantiateClient(String persistenceUnit)\n    {\n        return new KuduDBClient(kunderaMetadata, indexManager, reader, externalProperties, persistenceUnit,\n                this.kuduClient, this.clientMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.GenericClientFactory#isThreadSafe()\n     */\n    @Override\n    public boolean isThreadSafe()\n    {\n        // TODO Auto-generated method stub\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initializeLoadBalancer(\n     * java.lang.String)\n     */\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    /**\n     * Initialize property reader.\n     */\n    private void initializePropertyReader()\n    {\n        if (propertyReader == null)\n        {\n            propertyReader = new KuduDBPropertyReader(externalProperties,\n                    kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(getPersistenceUnit()));\n            propertyReader.read(getPersistenceUnit());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/main/java/com/impetus/client/kudu/KuduDBDataHandler.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu;\n\nimport java.util.List;\n\nimport org.apache.kudu.ColumnSchema;\nimport org.apache.kudu.Schema;\nimport org.apache.kudu.Type;\nimport org.apache.kudu.client.KuduPredicate;\nimport org.apache.kudu.client.PartialRow;\nimport org.apache.kudu.client.RowResult;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * The Class KuduDBDataHandler.\n * \n * @author karthikp.manchala\n */\npublic class KuduDBDataHandler\n{\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(KuduDBDataHandler.class);\n\n    /** The kundera metadata. */\n    private KunderaMetadata kunderaMetadata;\n\n    /**\n     * Instantiates a new kudu db data handler.\n     * \n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public KuduDBDataHandler(KunderaMetadata kunderaMetadata)\n    {\n        this.kunderaMetadata = kunderaMetadata;\n    }\n\n    /**\n     * Adds the to row.\n     * \n     * @param row\n     *            the row\n     * @param jpaColumnName\n     *            the jpa column name\n     * @param value\n     *            the value\n     * @param type\n     *            the type\n     */\n    public static void addToRow(PartialRow row, String jpaColumnName, Object value, Type type)\n    {\n        if (value == null)\n        {\n            row.setNull(jpaColumnName);\n        }\n        else\n        {\n            switch (type)\n            {\n            case BINARY:\n                row.addBinary(jpaColumnName, (byte[]) value);\n                break;\n            case BOOL:\n                row.addBoolean(jpaColumnName, (Boolean) value);\n                break;\n            case DOUBLE:\n                row.addDouble(jpaColumnName, (Double) value);\n                break;\n            case FLOAT:\n                row.addFloat(jpaColumnName, (Float) value);\n                break;\n            case INT16:\n                row.addShort(jpaColumnName, (Short) value);\n                break;\n            case INT32:\n                row.addInt(jpaColumnName, (Integer) value);\n                break;\n            case INT64:\n                row.addLong(jpaColumnName, (Long) value);\n                break;\n            case INT8:\n                row.addByte(jpaColumnName, (Byte) value);\n                break;\n            case STRING:\n                row.addString(jpaColumnName, (String) value);\n                break;\n            case UNIXTIME_MICROS:\n            default:\n                logger.error(type + \" type is not supported by Kudu\");\n                throw new KunderaException(type + \" type is not supported by Kudu\");\n            }\n        }\n    }\n\n    /**\n     * Gets the predicate.\n     * \n     * @param column\n     *            the column\n     * @param operator\n     *            the operator\n     * @param type\n     *            the type\n     * @param key\n     *            the key\n     * @return the predicate\n     */\n    public static KuduPredicate getPredicate(ColumnSchema column, KuduPredicate.ComparisonOp operator, Type type,\n            Object key)\n    {\n        switch (type)\n        {\n        case BINARY:\n            return KuduPredicate.newComparisonPredicate(column, operator, (byte[]) key);\n        case BOOL:\n            return KuduPredicate.newComparisonPredicate(column, operator, (Boolean) key);\n        case DOUBLE:\n            return KuduPredicate.newComparisonPredicate(column, operator, (Double) key);\n        case FLOAT:\n            return KuduPredicate.newComparisonPredicate(column, operator, (Float) key);\n        case INT16:\n            return KuduPredicate.newComparisonPredicate(column, operator, (Short) key);\n        case INT32:\n            return KuduPredicate.newComparisonPredicate(column, operator, (Integer) key);\n        case INT64:\n            return KuduPredicate.newComparisonPredicate(column, operator, (Long) key);\n        case INT8:\n            return KuduPredicate.newComparisonPredicate(column, operator, (Byte) key);\n        case STRING:\n            return KuduPredicate.newComparisonPredicate(column, operator, (String) key);\n        case UNIXTIME_MICROS:\n        default:\n            logger.error(type + \" type is not supported by Kudu\");\n            throw new KunderaException(type + \" type is not supported by Kudu\");\n        }\n    }\n\n    /**\n     * Gets the equal comparison predicate.\n     * \n     * @param column\n     *            the column\n     * @param type\n     *            the type\n     * @param key\n     *            the key\n     * @return the equal comparison predicate\n     */\n    public static KuduPredicate getEqualComparisonPredicate(ColumnSchema column, Type type, Object key)\n    {\n        return getPredicate(column, KuduPredicate.ComparisonOp.EQUAL, type, key);\n\n    }\n\n    /**\n     * Gets the column value.\n     * \n     * @param result\n     *            the result\n     * @param jpaColumnName\n     *            the jpa column name\n     * @return the column value\n     */\n    public static Object getColumnValue(RowResult result, String jpaColumnName)\n    {\n\n        if (result.isNull(jpaColumnName))\n        {\n            return null;\n        }\n\n        switch (result.getColumnType(jpaColumnName))\n        {\n        case BINARY:\n            return result.getBinary(jpaColumnName);\n        case BOOL:\n            return result.getBoolean(jpaColumnName);\n        case DOUBLE:\n            return result.getDouble(jpaColumnName);\n        case FLOAT:\n            return result.getFloat(jpaColumnName);\n        case INT16:\n            return result.getShort(jpaColumnName);\n        case INT32:\n            return result.getInt(jpaColumnName);\n        case INT64:\n            return result.getLong(jpaColumnName);\n        case INT8:\n            return result.getByte(jpaColumnName);\n        case STRING:\n            return result.getString(jpaColumnName);\n        case UNIXTIME_MICROS:\n        default:\n            logger.error(jpaColumnName + \" type is not supported by Kudu\");\n            throw new KunderaException(jpaColumnName + \" type is not supported by Kudu\");\n\n        }\n    }\n\n    /**\n     * Parses the.\n     * \n     * @param type\n     *            the type\n     * @param value\n     *            the value\n     * @return the object\n     */\n    public static Object parse(Type type, String value)\n    {\n        value = value.replaceAll(\"^['\\\\\\\"]|['\\\\\\\"]$\", \"\");\n        switch (type)\n        {\n        case BINARY:\n            return value.getBytes();\n        case BOOL:\n            return Boolean.parseBoolean(value);\n        case DOUBLE:\n            return Double.parseDouble(value);\n        case FLOAT:\n            return Float.parseFloat(value);\n        case INT16:\n            return Short.parseShort(value);\n        case INT32:\n            return Integer.parseInt(value);\n        case INT64:\n            return Long.parseLong(value);\n        case INT8:\n            return Byte.parseByte(value);\n        case STRING:\n            return value;\n        case UNIXTIME_MICROS:\n        default:\n            logger.error(type + \" type is not supported by Kudu\");\n            throw new KunderaException(type + \" type is not supported by Kudu\");\n\n        }\n    }\n\n    /**\n     * Checks for column.\n     * \n     * @param schema\n     *            the schema\n     * @param columnName\n     *            the column name\n     * @return true, if successful\n     */\n    public static boolean hasColumn(Schema schema, String columnName)\n    {\n        try\n        {\n            schema.getColumn(columnName);\n            return true;\n        }\n        catch (IllegalArgumentException e)\n        {\n            return false;\n        }\n    }\n\n    public static KuduPredicate getInPredicate(ColumnSchema column, List<Object> values)\n    {\n\n        return KuduPredicate.newInListPredicate(column, values);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/main/java/com/impetus/client/kudu/KuduDBIdGenerator.java",
    "content": "/*******************************************************************************\n * * Copyright 2017 Impetus Infotech.\n * *\n * * Licensed under the Apache License, Version 2.0 (the \"License\");\n * * you may not use this file except in compliance with the License.\n * * You may obtain a copy of the License at\n * *\n * * http://www.apache.org/licenses/LICENSE-2.0\n * *\n * * Unless required by applicable law or agreed to in writing, software\n * * distributed under the License is distributed on an \"AS IS\" BASIS,\n * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * * See the License for the specific language governing permissions and\n * * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu;\n\nimport java.util.UUID;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.generator.AutoGenerator;\n\n/**\n * The Class KuduDBIdGenerator.\n * \n * @author karthikp.manchala\n */\npublic class KuduDBIdGenerator implements AutoGenerator\n{\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.AutoGenerator#generate(com.impetus.kundera\n     * .client.Client, java.lang.Object)\n     */\n    @Override\n    public Object generate(Client<?> client, String dataType)\n    {\n        return UUID.randomUUID().toString();\n    }\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/main/java/com/impetus/client/kudu/KuduDBPropertyReader.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu;\n\nimport java.util.Map;\n\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * The Class KuduDBPropertyReader.\n * \n * @author karthikp.manchala\n */\npublic class KuduDBPropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n\n    /** The ksmd. */\n    public static KuduDBSchemaMetadata ksmd;\n\n    /**\n     * Instantiates a new kudu db property reader.\n     * \n     * @param externalProperties\n     *            the external properties\n     * @param puMetadata\n     *            the pu metadata\n     */\n    public KuduDBPropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        ksmd = new KuduDBSchemaMetadata();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.AbstractPropertyReader#onXml(com.impetus.\n     * kundera.configure.ClientProperties)\n     */\n    public void onXml(ClientProperties cp)\n    {\n        if (cp != null)\n        {\n            ksmd.setClientProperties(cp);\n        }\n    }\n\n    /**\n     * The Class KuduDBSchemaMetadata.\n     */\n    public class KuduDBSchemaMetadata\n    {\n\n        /** The client properties. */\n        private ClientProperties clientProperties;\n\n        /**\n         * Instantiates a new kudu db schema metadata.\n         */\n        public KuduDBSchemaMetadata()\n        {\n\n        }\n\n        /**\n         * Gets the client properties.\n         * \n         * @return the client properties\n         */\n        public ClientProperties getClientProperties()\n        {\n            return clientProperties;\n        }\n\n        /**\n         * Sets the client properties.\n         * \n         * @param clientProperties\n         *            the new client properties\n         */\n        private void setClientProperties(ClientProperties clientProperties)\n        {\n            this.clientProperties = clientProperties;\n        }\n\n        /**\n         * Gets the data store.\n         * \n         * @param datastore\n         *            the datastore\n         * @return the data store\n         */\n        public DataStore getDataStore(String datastore)\n        {\n            if (getClientProperties() != null && getClientProperties().getDatastores() != null)\n            {\n                for (DataStore dataStore : getClientProperties().getDatastores())\n                {\n                    if (dataStore.getName() != null && dataStore.getName().trim().equalsIgnoreCase(datastore))\n                    {\n                        return dataStore;\n                    }\n                }\n            }\n            return null;\n        }\n\n    }\n}"
  },
  {
    "path": "src/kundera-kudu/src/main/java/com/impetus/client/kudu/KuduDBValidationClassMapper.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu;\n\nimport java.util.Calendar;\nimport java.util.HashMap;\n\nimport org.apache.kudu.Type;\n\n/**\n * The Class KuduDBValidationClassMapper.\n * \n * @author karthikp.manchala\n */\npublic class KuduDBValidationClassMapper\n{\n\n    /** The Constant validationClassMapper. */\n    private final static HashMap<Class<?>, Type> validationClassMapper = new HashMap<Class<?>, Type>();\n\n    static\n    {\n        validationClassMapper.put(java.lang.String.class, Type.STRING);\n        validationClassMapper.put(Character.class, Type.STRING);\n        validationClassMapper.put(char.class, Type.STRING);\n\n        validationClassMapper.put(java.sql.Time.class, Type.UNIXTIME_MICROS);\n        validationClassMapper.put(java.lang.Integer.class, Type.INT32);\n        validationClassMapper.put(int.class, Type.INT32);\n        validationClassMapper.put(java.sql.Timestamp.class, Type.UNIXTIME_MICROS);\n        validationClassMapper.put(Short.class, Type.INT16);\n        validationClassMapper.put(short.class, Type.INT16);\n        validationClassMapper.put(java.sql.Date.class, Type.UNIXTIME_MICROS);\n        validationClassMapper.put(java.util.Date.class, Type.UNIXTIME_MICROS);\n        validationClassMapper.put(java.math.BigInteger.class, Type.INT64);\n        validationClassMapper.put(java.math.BigDecimal.class, Type.INT64);\n\n        validationClassMapper.put(java.lang.Double.class, Type.DOUBLE);\n        validationClassMapper.put(double.class, Type.DOUBLE);\n\n        validationClassMapper.put(boolean.class, Type.BOOL);\n        validationClassMapper.put(Boolean.class, Type.BOOL);\n\n        validationClassMapper.put(java.lang.Long.class, Type.INT64);\n        validationClassMapper.put(long.class, Type.INT64);\n\n        validationClassMapper.put(Byte.class, Type.INT8);\n        validationClassMapper.put(byte.class, Type.INT8);\n\n        validationClassMapper.put(Float.class, Type.FLOAT);\n        validationClassMapper.put(float.class, Type.FLOAT);\n\n        validationClassMapper.put(Byte[].class, Type.BINARY);\n        validationClassMapper.put(byte[].class, Type.BINARY);\n\n        validationClassMapper.put(Calendar.class, Type.UNIXTIME_MICROS);\n    }\n\n    /**\n     * Gets the valid type for class.\n     * \n     * @param clazz\n     *            the clazz\n     * @return the valid type for class\n     */\n    public static Type getValidTypeForClass(Class clazz)\n    {\n        return validationClassMapper.get(clazz);\n    }\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/main/java/com/impetus/client/kudu/query/KuduDBEntityReader.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.query;\n\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\n\n/**\n * The Class KuduDBEntityReader.\n * \n * @author karthikp.manchala\n */\npublic class KuduDBEntityReader extends AbstractEntityReader implements EntityReader\n{\n\n    /**\n     * Instantiates a new kudu db entity reader.\n     * \n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public KuduDBEntityReader(KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.AbstractEntityReader#findById(java.lang.\n     * Object, com.impetus.kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        return super.findById(primaryKey, m, client);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#populateRelation(com.impetus\n     * .kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client, int)\n     */\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/main/java/com/impetus/client/kudu/query/KuduDBQuery.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.query;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.ListIterator;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.kudu.ColumnSchema;\nimport org.apache.kudu.Type;\nimport org.apache.kudu.client.KuduClient;\nimport org.apache.kudu.client.KuduPredicate;\nimport org.apache.kudu.client.KuduScanner;\nimport org.apache.kudu.client.KuduScanner.KuduScannerBuilder;\nimport org.apache.kudu.client.KuduTable;\nimport org.apache.kudu.client.RowResult;\nimport org.apache.kudu.client.RowResultIterator;\nimport org.eclipse.persistence.jpa.jpql.parser.AndExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.ComparisonExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.InExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.JPQLExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.WhereClause;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.kudu.KuduDBClient;\nimport com.impetus.client.kudu.KuduDBDataHandler;\nimport com.impetus.client.kudu.KuduDBValidationClassMapper;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQueryUtils;\nimport com.impetus.kundera.query.Query;\nimport com.impetus.kundera.query.QueryImpl;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class KuduDBQuery.\n * \n * @author karthikp.manchala\n */\npublic class KuduDBQuery extends QueryImpl implements Query\n{\n\n    /** The Constant DOT_REGEX. */\n    private static final String DOT_REGEX = \"[.]\";\n\n    /** The Constant PARAMETERIZED_PREFIX. */\n    private static final String PARAMETERIZED_PREFIX = \":\";\n\n    /** The Constant POSITIONAL_PREFIX. */\n    private static final String POSITIONAL_PREFIX = \"?\";\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(KuduDBQuery.class);\n\n    /**\n     * Instantiates a new kudu db query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param persistenceDelegator\n     *            the persistence delegator\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public KuduDBQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera.\n     * metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List populateEntities(EntityMetadata m, Client client)\n    {\n        List results = new ArrayList();\n\n        if (!MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))\n        {\n            results.addAll(populateUsingLucene(m, client, null, getKunderaQuery().getResult()));\n        }\n\n        else\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n            EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n            KuduClient kuduClient = ((KuduDBClient) client).getKuduClient();\n            KuduTable table;\n            try\n            {\n                table = kuduClient.openTable(m.getTableName());\n            }\n            catch (Exception e)\n            {\n                logger.error(\"Cannot open table : \" + m.getTableName(), e);\n                throw new KunderaException(\"Cannot open table : \" + m.getTableName(), e);\n            }\n\n            KuduScannerBuilder scannerBuilder = kuduClient.newScannerBuilder(table);\n            JPQLExpression jpqlExp = kunderaQuery.getJpqlExpression();\n            List<String> selectColumns = KunderaQueryUtils.getSelectColumns(jpqlExp);\n            if (!selectColumns.isEmpty())\n            {\n                // select by specific columns, set projection\n                scannerBuilder.setProjectedColumnNames(selectColumns);\n            }\n            if (KunderaQueryUtils.hasWhereClause(jpqlExp))\n            {\n                // add predicate filters\n                WhereClause whereClause = KunderaQueryUtils.getWhereClause(jpqlExp);\n                Expression whereExp = whereClause.getConditionalExpression();\n                parseAndBuildFilters(entityType, scannerBuilder, whereExp);\n            }\n\n            KuduScanner scanner = scannerBuilder.build();\n\n            Object entity;\n            while (scanner.hasMoreRows())\n            {\n                RowResultIterator rowResultIter;\n                try\n                {\n                    rowResultIter = scanner.nextRows();\n                }\n                catch (Exception e)\n                {\n                    logger.error(\"Cannot get results from table : \" + m.getTableName(), e);\n                    throw new KunderaException(\"Cannot get results from table : \" + m.getTableName(), e);\n                }\n\n                while (rowResultIter.hasNext())\n                {\n                    RowResult result = rowResultIter.next();\n                    entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());\n                    // populate RowResult to entity object and return\n                    ((KuduDBClient) client).populateEntity(entity, result, entityType, metaModel);\n                    results.add(entity);\n                    logger.debug(result.rowToString());\n                }\n            }\n        }\n        return results;\n    }\n\n    /**\n     * Parses the and build filters.\n     * \n     * @param entityType\n     *            the entity type\n     * @param scannerBuilder\n     *            the scanner builder\n     * @param whereExp\n     *            the where exp\n     */\n    private void parseAndBuildFilters(EntityType entityType, KuduScannerBuilder scannerBuilder, Expression whereExp)\n    {\n        if (whereExp instanceof ComparisonExpression)\n        {\n            String left = ((ComparisonExpression) whereExp).getLeftExpression().toActualText();\n\n            String right = ((ComparisonExpression) whereExp).getRightExpression().toActualText();\n            if (right.startsWith(POSITIONAL_PREFIX) || right.startsWith(PARAMETERIZED_PREFIX))\n            {\n                right = kunderaQuery.getParametersMap().get(right) + \"\";\n            }\n            Attribute attribute = entityType.getAttribute(left.split(DOT_REGEX)[1]);\n            addColumnRangePredicateToBuilder((Field) attribute.getJavaMember(), scannerBuilder,\n                    ((AbstractAttribute) attribute).getJPAColumnName(), right,\n                    ((ComparisonExpression) whereExp).getActualIdentifier());\n        }\n        else if (whereExp instanceof AndExpression)\n        {\n            parseAndBuildFilters(entityType, scannerBuilder, ((AndExpression) whereExp).getLeftExpression());\n            parseAndBuildFilters(entityType, scannerBuilder, ((AndExpression) whereExp).getRightExpression());\n        }\n        else if (whereExp instanceof InExpression)\n        {\n\n            ListIterator<Expression> inIter = ((InExpression) whereExp).getInItems().children().iterator();\n            Attribute attribute = entityType.getAttribute(((InExpression) whereExp).getExpression().toActualText()\n                    .split(DOT_REGEX)[1]);\n            addInPredicateToBuilder(scannerBuilder, inIter, attribute);\n        }\n\n        else\n        {\n            logger.error(\"Operation not supported\");\n            throw new KunderaException(\"Operation not supported\");\n        }\n    }\n\n    /**\n     * Adds the in predicate to builder.\n     * \n     * @param scannerBuilder\n     *            the scanner builder\n     * @param inIter\n     *            the in iter\n     * @param attribute\n     *            the attribute\n     */\n    private void addInPredicateToBuilder(KuduScannerBuilder scannerBuilder, ListIterator<Expression> inIter,\n            Attribute attribute)\n    {\n        List<Object> finalVals = new ArrayList<>();\n        Type type = KuduDBValidationClassMapper.getValidTypeForClass(((Field) attribute.getJavaMember()).getType());\n        ColumnSchema column = new ColumnSchema.ColumnSchemaBuilder(((AbstractAttribute) attribute).getJPAColumnName(),\n                type).build();\n        while (inIter.hasNext())\n        {\n            String val = inIter.next().toActualText();\n            finalVals.add(KuduDBDataHandler.parse(type, val));\n        }\n        scannerBuilder.addPredicate(KuduDBDataHandler.getInPredicate(column, finalVals));\n    }\n\n    /**\n     * Adds the column range predicate to builder.\n     * \n     * @param field\n     *            the entity type\n     * @param scannerBuilder\n     *            the scanner builder\n     * @param columnName\n     *            the column name\n     * @param value\n     *            the value\n     * @param identifier\n     *            the identifier\n     */\n    private void addColumnRangePredicateToBuilder(Field field, KuduScannerBuilder scannerBuilder, String columnName,\n            String value, String identifier)\n    {\n        Type type = KuduDBValidationClassMapper.getValidTypeForClass(field.getType());\n        ColumnSchema column = new ColumnSchema.ColumnSchemaBuilder(columnName, type).build();\n\n        KuduPredicate predicate;\n\n        Object valueObject = KuduDBDataHandler.parse(type, value);\n\n        switch (identifier)\n        {\n        case \">=\":\n            predicate = KuduDBDataHandler.getPredicate(column, KuduPredicate.ComparisonOp.GREATER_EQUAL, type,\n                    valueObject);\n            break;\n        case \">\":\n            predicate = KuduDBDataHandler.getPredicate(column, KuduPredicate.ComparisonOp.GREATER, type, valueObject);\n            break;\n        case \"<\":\n            predicate = KuduDBDataHandler.getPredicate(column, KuduPredicate.ComparisonOp.LESS, type, valueObject);\n            break;\n        case \"<=\":\n            predicate = KuduDBDataHandler\n                    .getPredicate(column, KuduPredicate.ComparisonOp.LESS_EQUAL, type, valueObject);\n            break;\n        case \"=\":\n            predicate = KuduDBDataHandler.getPredicate(column, KuduPredicate.ComparisonOp.EQUAL, type, valueObject);\n            break;\n        default:\n            logger.error(\"Operation not supported\");\n            throw new KunderaException(\"Operation not supported\");\n        }\n\n        scannerBuilder.addPredicate(predicate);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#findUsingLucene(com.impetus.kundera.\n     * metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#recursivelyPopulateEntities(com.\n     * impetus.kundera.metadata.model.EntityMetadata ,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#getReader()\n     */\n    @Override\n    protected EntityReader getReader()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()\n     */\n    @Override\n    protected int onExecuteUpdate()\n    {\n        // TODO Auto-generated method stub\n        return 0;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#close()\n     */\n    @Override\n    public void close()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#iterate()\n     */\n    @Override\n    public Iterator iterate()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/main/java/com/impetus/client/kudu/schemamanager/KuduDBSchemaManager.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.schemamanager;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\nimport javax.persistence.Embeddable;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.kudu.ColumnSchema;\nimport org.apache.kudu.ColumnSchema.ColumnSchemaBuilder;\nimport org.apache.kudu.Schema;\nimport org.apache.kudu.client.AlterTableOptions;\nimport org.apache.kudu.client.CreateTableOptions;\nimport org.apache.kudu.client.KuduClient;\nimport org.apache.kudu.client.KuduTable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.kudu.KuduDBDataHandler;\nimport com.impetus.client.kudu.KuduDBValidationClassMapper;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.configure.schema.ColumnInfo;\nimport com.impetus.kundera.configure.schema.EmbeddedColumnInfo;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.configure.schema.TableInfo;\nimport com.impetus.kundera.configure.schema.api.AbstractSchemaManager;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * The Class KuduDBSchemaManager.\n * \n * @author karthikp.manchala\n */\npublic class KuduDBSchemaManager extends AbstractSchemaManager implements SchemaManager\n{\n\n    /** The Constant logger. */\n    private static final Logger logger = LoggerFactory.getLogger(KuduDBSchemaManager.class);\n\n    /** The client. */\n    private KuduClient client;\n\n    /**\n     * Instantiates a new kudu db schema manager.\n     * \n     * @param clientFactory\n     *            the client factory\n     * @param externalProperties\n     *            the external properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public KuduDBSchemaManager(String clientFactory, Map<String, Object> externalProperties,\n            KunderaMetadata kunderaMetadata)\n    {\n        super(clientFactory, externalProperties, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.AbstractSchemaManager#\n     * exportSchema(java.lang.String, java.util.List)\n     */\n    public void exportSchema(final String persistenceUnit, List<TableInfo> schemas)\n    {\n        super.exportSchema(persistenceUnit, schemas);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.SchemaManager#dropSchema()\n     */\n    @Override\n    public void dropSchema()\n    {\n        for (TableInfo tableInfo : tableInfos)\n        {\n            try\n            {\n                client.deleteTable(tableInfo.getTableName());\n            }\n            catch (Exception ex)\n            {\n                logger.error(\"Error during deleting tables in kudu, Caused by: \", ex);\n                throw new SchemaGenerationException(ex, \"Kudu\");\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.SchemaManager#validateEntity(\n     * java.lang.Class)\n     */\n    @Override\n    public boolean validateEntity(Class clazz)\n    {\n        // TODO Auto-generated method stub\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.AbstractSchemaManager#\n     * initiateClient()\n     */\n    @Override\n    protected boolean initiateClient()\n    {\n        for (String host : hosts)\n        {\n            if (host == null || !StringUtils.isNumeric(port) || port.isEmpty())\n            {\n                logger.error(\"Host or port should not be null / port should be numeric\");\n                throw new IllegalArgumentException(\"Host or port should not be null / port should be numeric\");\n            }\n            try\n            {\n                client = new KuduClient.KuduClientBuilder(host + \":\" + port).build();\n            }\n            catch (Exception e)\n            {\n                logger.error(\"Database host cannot be resolved, Caused by: \" + e.getMessage());\n                throw new SchemaGenerationException(\"Database host cannot be resolved, Caused by: \" + e.getMessage());\n            }\n        }\n        return true;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#validate(\n     * java.util.List)\n     */\n    @Override\n    protected void validate(List<TableInfo> tableInfos)\n    {\n        for (TableInfo tableInfo : tableInfos)\n        {\n            try\n            {\n                if (!client.tableExists(tableInfo.getTableName()))\n                {\n                    throw new SchemaGenerationException(\"Table: \" + tableInfo.getTableName() + \" does not exist \");\n                }\n            }\n            catch (Exception e)\n            {\n                logger.error(\"Error while validating tables, Caused by: \" + e.getMessage());\n                throw new KunderaException(\"Error while validating tables, Caused by: \" + e.getMessage());\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#update(\n     * java.util.List)\n     */\n    @Override\n    protected void update(List<TableInfo> tableInfos)\n    {\n        for (TableInfo tableInfo : tableInfos)\n        {\n            try\n            {\n                if (!client.tableExists(tableInfo.getTableName()))\n                {\n                    createKuduTable(tableInfo);\n                }\n                else\n                {\n                    List<String> entityColumns = new ArrayList<String>();\n                    KuduTable table = client.openTable(tableInfo.getTableName());\n                    AlterTableOptions alterTableOptions = new AlterTableOptions();\n                    AtomicBoolean updated = new AtomicBoolean(false);\n                    Schema schema = table.getSchema();\n                    // add modify columns\n                    for (ColumnInfo columnInfo : tableInfo.getColumnMetadatas())\n                    {\n                        entityColumns.add(columnInfo.getColumnName());\n                        alterColumn(alterTableOptions, schema, columnInfo, updated);\n                    }\n                    // update for embeddables logic\n                    for (EmbeddedColumnInfo embColumnInfo : tableInfo.getEmbeddedColumnMetadatas())\n                    {\n                        for (ColumnInfo columnInfo : embColumnInfo.getColumns())\n                        {\n                            entityColumns.add(columnInfo.getColumnName());\n                            alterColumn(alterTableOptions, schema, columnInfo, updated);\n                        }\n                    }\n\n                    // delete columns\n                    for (ColumnSchema columnSchema : schema.getColumns())\n                    {\n                        // if not in tableInfo and not a key then delete\n                        if (!entityColumns.contains(columnSchema.getName()) && !columnSchema.isKey())\n                        {\n                            alterTableOptions.dropColumn(columnSchema.getName());\n                            updated.set(true);\n                        }\n                    }\n\n                    if (updated.get())\n                    {\n                        client.alterTable(tableInfo.getTableName(), alterTableOptions);\n                    }\n                }\n            }\n            catch (Exception e)\n            {\n                logger.error(\"Error while updating tables, Caused by: \" + e.getMessage());\n                throw new KunderaException(\"Error while updating tables, Caused by: \" + e.getMessage());\n            }\n        }\n    }\n\n    /**\n     * Alter column.\n     * \n     * @param alterTableOptions\n     *            the alter table options\n     * @param schema\n     *            the schema\n     * @param columnInfo\n     *            the column info\n     * @param updated\n     *            the updated\n     */\n    private void alterColumn(AlterTableOptions alterTableOptions, Schema schema, ColumnInfo columnInfo,\n            AtomicBoolean updated)\n    {\n        if (!KuduDBDataHandler.hasColumn(schema, columnInfo.getColumnName()))\n        {\n            // add if column is not in schema\n            alterTableOptions.addNullableColumn(columnInfo.getColumnName(),\n                    KuduDBValidationClassMapper.getValidTypeForClass(columnInfo.getType()));\n            updated.set(true);\n        }\n        else\n        {\n            // check for type, drop and add if not consistent TODO: throw\n            // exception or override?\n            if (!schema.getColumn(columnInfo.getColumnName()).getType()\n                    .equals(KuduDBValidationClassMapper.getValidTypeForClass(columnInfo.getType())))\n            {\n                alterTableOptions.dropColumn(columnInfo.getColumnName());\n                alterTableOptions.addNullableColumn(columnInfo.getColumnName(),\n                        KuduDBValidationClassMapper.getValidTypeForClass(columnInfo.getType()));\n                updated.set(true);\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#create(\n     * java.util.List)\n     */\n    @Override\n    protected void create(List<TableInfo> tableInfos)\n    {\n\n        for (TableInfo tableInfo : tableInfos)\n        {\n            try\n            {\n                if (client.tableExists(tableInfo.getTableName()))\n                {\n                    client.deleteTable(tableInfo.getTableName());\n                }\n            }\n            catch (Exception e)\n            {\n                logger.error(\"Cannot check table existence for table \" + tableInfo.getTableName() + \". Caused By: \" + e);\n                throw new KunderaException(\"Cannot check table existence for table \" + tableInfo.getTableName()\n                        + \". Caused By: \" + e);\n            }\n            createKuduTable(tableInfo);\n        }\n    }\n\n    /**\n     * Creates the kudu table.\n     * \n     * @param tableInfo\n     *            the table info\n     */\n    private void createKuduTable(TableInfo tableInfo)\n    {\n        List<ColumnSchema> columns = new ArrayList<ColumnSchema>();\n        // add key\n        if (tableInfo.getTableIdType().isAnnotationPresent(Embeddable.class))\n        {\n            // composite keys\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    puMetadata.getPersistenceUnitName());\n            EmbeddableType embeddableIdType = metaModel.embeddable(tableInfo.getTableIdType());\n            Field[] fields = tableInfo.getTableIdType().getDeclaredFields();\n\n            addPrimaryKeyColumnsFromEmbeddable(columns, embeddableIdType, fields, metaModel);\n\n        }\n        else\n        {\n            // simple key\n            columns.add(new ColumnSchema.ColumnSchemaBuilder(tableInfo.getIdColumnName(), KuduDBValidationClassMapper\n                    .getValidTypeForClass(tableInfo.getTableIdType())).key(true).build());\n        }\n        // add other columns\n        for (ColumnInfo columnInfo : tableInfo.getColumnMetadatas())\n        {\n            ColumnSchemaBuilder columnSchemaBuilder = new ColumnSchema.ColumnSchemaBuilder(columnInfo.getColumnName(),\n                    KuduDBValidationClassMapper.getValidTypeForClass(columnInfo.getType()));\n            columns.add(columnSchemaBuilder.build());\n        }\n\n        // add embedded columns\n        for (EmbeddedColumnInfo embColumnInfo : tableInfo.getEmbeddedColumnMetadatas())\n        {\n            if (embColumnInfo.getEmbeddedColumnName().equals(tableInfo.getIdColumnName()))\n            {\n                // skip for embeddable ids\n                continue;\n            }\n            buildColumnsFromEmbeddableColumn(embColumnInfo, columns);\n        }\n        Schema schema = new Schema(columns);\n        try\n        {\n            CreateTableOptions builder = new CreateTableOptions();\n\n            List<String> rangeKeys = new ArrayList<>();\n\n            // handle for composite Id\n            if (tableInfo.getTableIdType().isAnnotationPresent(Embeddable.class))\n            {\n                Iterator<ColumnSchema> colIter = columns.iterator();\n                while (colIter.hasNext())\n                {\n                    ColumnSchema col = colIter.next();\n                    if (col.isKey())\n                    {\n                        rangeKeys.add(col.getName());\n                    }\n                }\n            }\n            else\n            {\n                rangeKeys.add(tableInfo.getIdColumnName());\n            }\n\n            // TODO: Hard Coded Range Partitioning\n            builder.setRangePartitionColumns(rangeKeys);\n            client.createTable(tableInfo.getTableName(), schema, builder);\n            logger.debug(\"Table: \" + tableInfo.getTableName() + \" created successfully\");\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Table: \" + tableInfo.getTableName() + \" cannot be created, Caused by: \" + e.getMessage(), e);\n            throw new SchemaGenerationException(\"Table: \" + tableInfo.getTableName()\n                    + \" cannot be created, Caused by: \" + e.getMessage(), e, \"Kudu\");\n        }\n    }\n\n    private void addPrimaryKeyColumnsFromEmbeddable(List<ColumnSchema> columns, EmbeddableType embeddable,\n            Field[] fields, MetamodelImpl metaModel)\n    {\n        for (Field f : fields)\n        {\n            if (!ReflectUtils.isTransientOrStatic(f))\n            {\n                if (f.getType().isAnnotationPresent(Embeddable.class))\n                {\n                    // nested\n                    addPrimaryKeyColumnsFromEmbeddable(columns, (EmbeddableType) metaModel.embeddable(f.getType()), f\n                            .getType().getDeclaredFields(), metaModel);\n                }\n                else\n                {\n                    Attribute attribute = embeddable.getAttribute(f.getName());\n                    columns.add(new ColumnSchema.ColumnSchemaBuilder(\n                            ((AbstractAttribute) attribute).getJPAColumnName(), KuduDBValidationClassMapper\n                                    .getValidTypeForClass(f.getType())).key(true).build());\n                }\n            }\n        }\n\n    }\n\n    private void buildColumnsFromEmbeddableColumn(EmbeddedColumnInfo embColumnInfo, List<ColumnSchema> columns)\n    {\n        for (ColumnInfo columnInfo : embColumnInfo.getColumns())\n        {\n            ColumnSchemaBuilder columnSchemaBuilder = new ColumnSchema.ColumnSchemaBuilder(columnInfo.getColumnName(),\n                    KuduDBValidationClassMapper.getValidTypeForClass(columnInfo.getType()));\n            columns.add(columnSchemaBuilder.build());\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.AbstractSchemaManager#\n     * create_drop(java.util.List)\n     */\n    @Override\n    protected void create_drop(List<TableInfo> tableInfos)\n    {\n        create(tableInfos);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/autogeneratedid/Employee.java",
    "content": "/*******************************************************************************\n * * Copyright 2017 Impetus Infotech.\n * *\n * * Licensed under the Apache License, Version 2.0 (the \"License\");\n * * you may not use this file except in compliance with the License.\n * * You may obtain a copy of the License at\n * *\n * * http://www.apache.org/licenses/LICENSE-2.0\n * *\n * * Unless required by applicable law or agreed to in writing, software\n * * distributed under the License is distributed on an \"AS IS\" BASIS,\n * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * * See the License for the specific language governing permissions and\n * * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.autogeneratedid;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Employee.\n * \n * @author devender.yadav\n */\n@Entity\n@Table(name = \"KUDU_EMPLOYEE\", schema = \"kudutest@kudu-auto-gen-pu\")\npublic class Employee\n{\n\n    /** The id. */\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    private String empId;\n\n    /** The name. */\n    @Column\n    private String name;\n\n    /** The salary. */\n    @Column\n    private Integer salary;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public String getId()\n    {\n        return empId;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the new id\n     */\n    public void setId(String id)\n    {\n        this.empId = id;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the new name\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * Gets the salary.\n     * \n     * @return the salary\n     */\n    public Integer getSalary()\n    {\n        return salary;\n    }\n\n    /**\n     * Sets the salary.\n     * \n     * @param salary\n     *            the new salary\n     */\n    public void setSalary(int salary)\n    {\n        this.salary = salary;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/autogeneratedid/KuduIdAutoGenerationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2017 Impetus Infotech.\n * *\n * * Licensed under the Apache License, Version 2.0 (the \"License\");\n * * you may not use this file except in compliance with the License.\n * * You may obtain a copy of the License at\n * *\n * * http://www.apache.org/licenses/LICENSE-2.0\n * *\n * * Unless required by applicable law or agreed to in writing, software\n * * distributed under the License is distributed on an \"AS IS\" BASIS,\n * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * * See the License for the specific language governing permissions and\n * * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.autogeneratedid;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport junit.framework.Assert;\n\n/**\n * The Class KuduIdAutoGenerationTest.\n * \n * @author karthikp.manchala\n */\npublic class KuduIdAutoGenerationTest\n{\n\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"kudu-auto-gen-pu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Setup.\n     */\n    @Before\n    public void setup()\n    {\n\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    @Test\n    public void test() throws InterruptedException\n    {\n\n        Employee emp1 = new Employee();\n        emp1.setName(\"dev\");\n        emp1.setSalary(50000);\n\n        Employee emp2 = new Employee();\n        emp2.setName(\"karthik\");\n        emp2.setSalary(60000);\n\n        em.persist(emp1);\n        em.persist(emp2);\n        em.clear();\n\n        List<Employee> employees = em.createQuery(\"select e from Employee e\").getResultList();\n        Assert.assertEquals(2, employees.size());\n        assertEmployees(employees);\n\n        for (Employee emp : employees)\n        {\n            em.remove(emp);\n        }\n\n        employees = em.createQuery(\"select e from Employee e\").getResultList();\n        Assert.assertEquals(0, employees.size());\n\n    }\n\n    /**\n     * Assert employees.\n     * \n     * @param employees\n     *            the employees\n     */\n    private void assertEmployees(List<Employee> employees)\n    {\n\n        for (Employee e : employees)\n        {\n            if (e.getName().equals(\"dev\"))\n            {\n                Assert.assertEquals(new Integer(50000), e.getSalary());\n            }\n            else if (e.getName().equals(\"karthik\"))\n            {\n                Assert.assertEquals(new Integer(60000), e.getSalary());\n            }\n        }\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/KuduCRUDTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.kudu.entities.Person;\n\nimport junit.framework.Assert;\n\n/**\n * The Class KuduCRUDTest.\n */\npublic class KuduCRUDTest\n{\n\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"kudu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test CRUD.\n     */\n    @Test\n    public void testCRUD()\n    {\n        testInsert();\n        testMerge();\n        testDelete();\n    }\n\n    /**\n     * Test insert.\n     */\n    private void testInsert()\n    {\n        Person person = new Person(\"101\", \"dev\", 22, 30000.5);\n        em.persist(person);\n        em.clear();\n        Person p = em.find(Person.class, \"101\");\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"101\", p.getPersonId());\n        Assert.assertEquals(\"dev\", p.getPersonName());\n        Assert.assertEquals(22, p.getAge());\n        Assert.assertEquals(30000.5, p.getSalary());\n    }\n\n    /**\n     * Test merge.\n     */\n    private void testMerge()\n    {\n        Person p = em.find(Person.class, \"101\");\n        p.setPersonName(\"karthik\");\n        em.merge(p);\n        em.clear();\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertNotNull(p1);\n        Assert.assertEquals(\"karthik\", p1.getPersonName());\n    }\n\n    /**\n     * Test delete.\n     */\n    private void testDelete()\n    {\n        Person p = em.find(Person.class, \"101\");\n        em.remove(p);\n        em.clear();\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertNull(p1);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/KuduBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes;\n\nimport com.impetus.kundera.datatypes.datagenerator.DataGenerator;\nimport com.impetus.kundera.datatypes.datagenerator.DataGeneratorFactory;\n\n/**\n * KuduBase class for different data type test.\n * \n * @author Devender Yadav\n */\npublic abstract class KuduBase\n{\n\n    /** The data generator. */\n    DataGenerator<?> dataGenerator;\n\n    /** The factory. */\n    DataGeneratorFactory factory = new DataGeneratorFactory();\n\n    /**\n     * Gets the max value.\n     * \n     * @param clazz\n     *            the clazz\n     * @return the max value\n     */\n    protected Object getMaxValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.maxValue();\n    }\n\n    /**\n     * Gets the min value.\n     * \n     * @param clazz\n     *            the clazz\n     * @return the min value\n     */\n    protected Object getMinValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.minValue();\n    }\n\n    /**\n     * Gets the random value.\n     * \n     * @param clazz\n     *            the clazz\n     * @return the random value\n     */\n    protected Object getRandomValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.randomValue();\n    }\n\n    /**\n     * Gets the partial value.\n     * \n     * @param clazz\n     *            the clazz\n     * @return the partial value\n     */\n    protected Object getPartialValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.partialValue();\n    }\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/StudentKuduBytePrimitiveTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.kudu.crud.datatypes.entities.StudentKuduBytePrimitive;\n\nimport junit.framework.Assert;\n\n/**\n * The Class StudentKuduBytePrimitiveTest.\n * \n * @author Devender Yadav\n */\npublic class StudentKuduBytePrimitiveTest extends KuduBase\n{\n\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of byte\n        StudentKuduBytePrimitive studentMax = new StudentKuduBytePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of byte\n        StudentKuduBytePrimitive studentMin = new StudentKuduBytePrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Byte) getMinValue(byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of byte\n        StudentKuduBytePrimitive student = new StudentKuduBytePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduBytePrimitive studentMax = em.find(StudentKuduBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduBytePrimitive studentMin = em.find(StudentKuduBytePrimitive.class, getMinValue(byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduBytePrimitive student = em.find(StudentKuduBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentKuduBytePrimitive student = em.find(StudentKuduBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduBytePrimitive newStudent = em.find(StudentKuduBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        // findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        // findByNameAndAgeGTAndLTEQ();\n        // findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduBytePrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(byte.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduBytePrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduBytePrimitive studentMax = em.find(StudentKuduBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentKuduBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduBytePrimitive s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduBytePrimitive s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduBytePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduBytePrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentKuduBytePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentKuduBytePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentKuduBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Byte) getMinValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/StudentKuduByteWrapperTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.kudu.crud.datatypes.entities.StudentKuduByteWrapper;\n\nimport junit.framework.Assert;\n\n/**\n * The Class StudentKuduByteWrapperTest.\n * \n * @author Devender Yadav\n */\npublic class StudentKuduByteWrapperTest extends KuduBase\n{\n\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Byte\n        StudentKuduByteWrapper studentMax = new StudentKuduByteWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(Byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Byte\n        StudentKuduByteWrapper studentMin = new StudentKuduByteWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Byte) getMinValue(Byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Byte\n        StudentKuduByteWrapper student = new StudentKuduByteWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(Byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduByteWrapper studentMax = em.find(StudentKuduByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduByteWrapper studentMin = em.find(StudentKuduByteWrapper.class, getMinValue(Byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduByteWrapper student = em.find(StudentKuduByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentKuduByteWrapper student = em.find(StudentKuduByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduByteWrapper newStudent = em.find(StudentKuduByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        // findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        // findByNameAndAgeGTAndLTEQ();\n        // findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduByteWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduByteWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Byte.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduByteWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduByteWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduByteWrapper studentMax = em.find(StudentKuduByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentKuduByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduByteWrapper s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduByteWrapper s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduByteWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduByteWrapper s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentKuduByteWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentKuduByteWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentKuduByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Byte.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/StudentKuduIntTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.kudu.crud.datatypes.entities.StudentKuduInt;\n\nimport junit.framework.Assert;\n\n/**\n * The Class StudentKuduIntTest.\n * \n * @author Devender Yadav\n */\npublic class StudentKuduIntTest extends KuduBase\n{\n\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of int\n        StudentKuduInt studentMax = new StudentKuduInt();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(int.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert random value of int\n        StudentKuduInt student = new StudentKuduInt();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(int.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert min value of int\n        StudentKuduInt studentMin = new StudentKuduInt();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Integer) getMinValue(int.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduInt studentMax = em.find(StudentKuduInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduInt studentMin = em.find(StudentKuduInt.class, getMinValue(int.class));\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduInt student = em.find(StudentKuduInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentKuduInt student = em.find(StudentKuduInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduInt newStudent = em.find(StudentKuduInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        // findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        // findByNameAndAgeGTAndLTEQ();\n        // findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduInt s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduInt student : students)\n        {\n            Assert.assertEquals(getMinValue(int.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduInt s where s.name = 'Kuldeep' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduInt studentMax = em.find(StudentKuduInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentKuduInt.class, getMaxValue(int.class));\n        Assert.assertNull(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n\n        StudentKuduInt studentMin = em.find(StudentKuduInt.class, getMinValue(int.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMin.getName());\n        em.remove(studentMin);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMin = em.find(StudentKuduInt.class, getMinValue(int.class));\n        Assert.assertNull(studentMin);\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduInt s where s.name = 'Amresh' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        // query =\n        // \"Select s From StudentKuduInt s where s.name = Amresh and s.age > ?1\n        // and s.age < ?2\";\n        q = em.createQuery(query);\n        // q.setParameter(1, getPartialValue(short.class));\n        // q.setParameter(2, getMaxValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduInt s where s.name = 'Kuldeep' and s.age >= \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduInt s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduInt s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentKuduInt s \";\n        Query q = em.createQuery(query);\n        List<StudentKuduInt> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentKuduInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Integer) getMinValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/StudentKuduIntegerTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.kudu.crud.datatypes.entities.StudentKuduInteger;\n\nimport junit.framework.Assert;\n\n/**\n * The Class StudentKuduIntegerTest.\n * \n * @author Devender Yadav\n */\npublic class StudentKuduIntegerTest extends KuduBase\n{\n\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of integer\n        StudentKuduInteger studentMax = new StudentKuduInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(Integer.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of integer\n        StudentKuduInteger studentMin = new StudentKuduInteger();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Integer) getMinValue(Integer.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of integer\n        StudentKuduInteger student = new StudentKuduInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(Integer.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduInteger studentMax = em.find(StudentKuduInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduInteger studentMin = em.find(StudentKuduInteger.class, getMinValue(Integer.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduInteger student = em.find(StudentKuduInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentKuduInteger student = em.find(StudentKuduInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduInteger newStudent = em.find(StudentKuduInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        // findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        // findByNameAndAgeGTAndLTEQ();\n        // findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduInteger s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(Integer.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduInteger s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduInteger studentMax = em.find(StudentKuduInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentKuduInteger.class, getMaxValue(Integer.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduInteger s where s.name = 'Amresh' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduInteger s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduInteger s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduInteger s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentKuduInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentKuduInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentKuduInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Integer.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/StudentKuduLongPrimitiveTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.kudu.crud.datatypes.entities.StudentKuduLongPrimitive;\n\nimport junit.framework.Assert;\n\n/**\n * The Class StudentKuduLongPrimitiveTest.\n * \n * @author Devender Yadav\n */\npublic class StudentKuduLongPrimitiveTest extends KuduBase\n{\n\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of long\n        StudentKuduLongPrimitive studentMax = new StudentKuduLongPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of long\n        StudentKuduLongPrimitive studentMin = new StudentKuduLongPrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Long) getMinValue(long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of long\n        StudentKuduLongPrimitive student = new StudentKuduLongPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduLongPrimitive studentMax = em.find(StudentKuduLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduLongPrimitive studentMin = em.find(StudentKuduLongPrimitive.class, getMinValue(long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduLongPrimitive student = em.find(StudentKuduLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentKuduLongPrimitive student = em.find(StudentKuduLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduLongPrimitive newStudent = em.find(StudentKuduLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        // findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        // findByNameAndAgeGTAndLTEQ();\n        // findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduLongPrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(long.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduLongPrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduLongPrimitive studentMax = em.find(StudentKuduLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentKuduLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduLongPrimitive s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduLongPrimitive s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduLongPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduLongPrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentKuduLongPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentKuduLongPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentKuduLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Long) getMinValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/StudentKuduLongWrapperTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.kudu.crud.datatypes.entities.StudentKuduLongWrapper;\n\nimport junit.framework.Assert;\n\n/**\n * The Class StudentKuduLongPrimitive.\n * \n * @author Devender Yadav\n */\npublic class StudentKuduLongWrapperTest extends KuduBase\n{\n\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Long\n        StudentKuduLongWrapper studentMax = new StudentKuduLongWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(Long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Long\n        StudentKuduLongWrapper studentMin = new StudentKuduLongWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Long) getMinValue(Long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Long\n        StudentKuduLongWrapper student = new StudentKuduLongWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(Long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduLongWrapper studentMax = em.find(StudentKuduLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduLongWrapper studentMin = em.find(StudentKuduLongWrapper.class, getMinValue(Long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduLongWrapper student = em.find(StudentKuduLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentKuduLongWrapper student = em.find(StudentKuduLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduLongWrapper newStudent = em.find(StudentKuduLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        // findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        // findByNameAndAgeGTAndLTEQ();\n        // findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduLongWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduLongWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Long.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduLongWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduLongWrapper studentMax = em.find(StudentKuduLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentKuduLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduLongWrapper s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduLongWrapper s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduLongWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduLongWrapper s where s.name ='Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentKuduLongWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentKuduLongWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentKuduLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Long.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/StudentKuduShortPrimitiveTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.kudu.crud.datatypes.entities.StudentKuduShortPrimitive;\n\nimport junit.framework.Assert;\n\n/**\n * StudentKuduShortPrimitiveTest The Class StudentKuduShortPrimitiveTest.\n * \n * @author Devender Yadav\n */\npublic class StudentKuduShortPrimitiveTest extends KuduBase\n{\n\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentKuduShortPrimitive studentMax = new StudentKuduShortPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentKuduShortPrimitive studentMin = new StudentKuduShortPrimitive();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Short) getPartialValue(short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentKuduShortPrimitive student = new StudentKuduShortPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduShortPrimitive studentMax = em.find(StudentKuduShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduShortPrimitive studentMin = em.find(StudentKuduShortPrimitive.class, getPartialValue(short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduShortPrimitive student = em.find(StudentKuduShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentKuduShortPrimitive student = em.find(StudentKuduShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduShortPrimitive newStudent = em.find(StudentKuduShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        // findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        // findByNameAndAgeGTAndLTEQ();\n        // findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduShortPrimitive s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduShortPrimitive student : students)\n        {\n            Assert.assertEquals(getPartialValue(short.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduShortPrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduShortPrimitive studentMax = em.find(StudentKuduShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentKuduShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduShortPrimitive s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduShortPrimitive s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduShortPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduShortPrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentKuduShortPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentKuduShortPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentKuduShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Short) getPartialValue(short.class)).shortValue())\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/StudentKuduShortWrapperTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.kudu.crud.datatypes.entities.StudentKuduShortWrapper;\n\nimport junit.framework.Assert;\n\n/**\n * The Class StudentKuduShortWrapperTest.\n * \n * @author Devender Yadav\n */\npublic class StudentKuduShortWrapperTest extends KuduBase\n{\n\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentKuduShortWrapper studentMax = new StudentKuduShortWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentKuduShortWrapper studentMin = new StudentKuduShortWrapper();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((Short) getPartialValue(short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentKuduShortWrapper student = new StudentKuduShortWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduShortWrapper studentMax = em.find(StudentKuduShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduShortWrapper studentMin = em.find(StudentKuduShortWrapper.class, getPartialValue(short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduShortWrapper student = em.find(StudentKuduShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentKuduShortWrapper student = em.find(StudentKuduShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduShortWrapper newStudent = em.find(StudentKuduShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        // findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        // findByNameAndAgeGTAndLTEQ();\n        // findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduShortWrapper s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduShortWrapper student : students)\n        {\n            Assert.assertEquals(getPartialValue(short.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduShortWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduShortWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduShortWrapper studentMax = em.find(StudentKuduShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentKuduShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduShortWrapper s where s.name = 'Amresh' and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduShortWrapper s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduShortWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduShortWrapper s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentKuduShortWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentKuduShortWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentKuduShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getPartialValue(short.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/StudentKuduStringTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.kudu.crud.datatypes.entities.StudentKuduString;\n\nimport junit.framework.Assert;\n\n/**\n * The Class StudentKuduStringTest.\n * \n * @author Devender Yadav\n */\npublic class StudentKuduStringTest extends KuduBase\n{\n\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"dataTypeTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n\n    }\n\n    /**\n     * Test execute use same em.\n     */\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        persistStudents();\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testDelete(true);\n    }\n\n    /**\n     * Test execute.\n     */\n    @Test\n    public void testExecute()\n    {\n        persistStudents();\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testDelete(false);\n    }\n\n    /**\n     * Persist students.\n     */\n    public void persistStudents()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of String\n        StudentKuduString studentMax = new StudentKuduString();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((String) getMaxValue(String.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of String\n        StudentKuduString studentMin = new StudentKuduString();\n        studentMin.setAge((Short) getPartialValue(short.class));\n        studentMin.setId((String) getMinValue(String.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of String\n        StudentKuduString student = new StudentKuduString();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((String) getRandomValue(String.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    /**\n     * Test find by id.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduString studentMax = em.find(StudentKuduString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduString studentMin = em.find(StudentKuduString.class, getMinValue(String.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getPartialValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduString student = em.find(StudentKuduString.class, getRandomValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    /**\n     * Test merge.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentKuduString student = em.find(StudentKuduString.class, getMaxValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentKuduString newStudent = em.find(StudentKuduString.class, getMaxValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    /**\n     * Test find by query.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        // findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        // findByNameAndAgeGTAndLTEQ();\n        // findByAgeAndNameGTAndLT();\n    }\n\n    /**\n     * Find by age and name gt and lt.\n     */\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduString s where s.age = \" + getPartialValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduString student : students)\n        {\n            Assert.assertEquals(getMinValue(String.class), student.getId());\n            Assert.assertEquals(getPartialValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gt and lteq.\n     */\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduString s where s.name = 'Kuldeep' and s.age > \" + getPartialValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Test delete.\n     * \n     * @param useSameEm\n     *            the use same em\n     */\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentKuduString studentMax = em.find(StudentKuduString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentKuduString.class, getMaxValue(String.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * Find by name and age gt and lt.\n     */\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduString s where s.age > \" + getPartialValue(short.class) + \" and s.age < \"\n                + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by name and age gteq and lteq.\n     */\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduString s where s.name = 'Kuldeep' and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    /**\n     * Find by age.\n     */\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduString s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentKuduString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * Find by name.\n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentKuduString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentKuduString s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentKuduString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * Find all query.\n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentKuduString s \";\n        Query q = em.createQuery(query);\n        List<StudentKuduString> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentKuduString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(String.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(String.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/entities/StudentKuduBytePrimitive.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentKuduBytePrimitive.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_KUDU_BYTE_PRIMITIVE\", schema = \"kudutest@dataTypeTest\")\npublic class StudentKuduBytePrimitive\n{\n\n    /** The id. */\n    @Id\n    private byte id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/entities/StudentKuduByteWrapper.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentKuduByteWrapper.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_KUDU_BYTE_WRAPPER\", schema = \"kudutest@dataTypeTest\")\npublic class StudentKuduByteWrapper\n{\n\n    /** The id. */\n    @Id\n    private Byte id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/entities/StudentKuduInt.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentKuduInt.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_KUDU_INT\", schema = \"kudutest@dataTypeTest\")\npublic class StudentKuduInt\n{\n\n    /** The id. */\n    @Id\n    private int id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/entities/StudentKuduInteger.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentKuduInteger.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_KUDU_INTEGER\", schema = \"kudutest@dataTypeTest\")\npublic class StudentKuduInteger\n{\n\n    /** The id. */\n    @Id\n    private Integer id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Integer getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Integer id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/entities/StudentKuduLongPrimitive.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentKuduLongPrimitive.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_KUDU_LONG_PRIMITIVE\", schema = \"kudutest@dataTypeTest\")\npublic class StudentKuduLongPrimitive\n{\n\n    /** The id. */\n    @Id\n    private long id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public long getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/entities/StudentKuduLongWrapper.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentKuduLongWrapper.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_KUDU_LONG_WRAPPER\", schema = \"kudutest@dataTypeTest\")\npublic class StudentKuduLongWrapper\n{\n\n    /** The id. */\n    @Id\n    private Long id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Long getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/entities/StudentKuduShortPrimitive.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentKuduShortPrimitive.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_KUDU_SHORT_PRIMITIVE\", schema = \"kudutest@dataTypeTest\")\npublic class StudentKuduShortPrimitive\n{\n\n    /** The id. */\n    @Id\n    private short id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public short getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/entities/StudentKuduShortWrapper.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentKuduShortWrapper.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_KUDU_SHORT_WRAPPER\", schema = \"kudutest@dataTypeTest\")\npublic class StudentKuduShortWrapper\n{\n\n    /** The id. */\n    @Id\n    private Short id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public Short getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(Short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/crud/datatypes/entities/StudentKuduString.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class StudentKuduString.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"STUDENT_KUDU_STRING\", schema = \"kudutest@dataTypeTest\")\npublic class StudentKuduString\n{\n\n    /** The id. */\n    @Id\n    private String id;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/embeddables/Address.java",
    "content": "package com.impetus.client.kudu.embeddables;\n\nimport javax.persistence.Embeddable;\n\n@Embeddable\npublic class Address\n{\n    private String street;\n\n    private String city;\n\n    private String country;\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public String getCity()\n    {\n        return city;\n    }\n\n    public void setCity(String city)\n    {\n        this.city = city;\n    }\n\n    public String getCountry()\n    {\n        return country;\n    }\n\n    public void setCountry(String country)\n    {\n        this.country = country;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/embeddables/EmbeddablePerson.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.embeddables;\n\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Person.\n * \n * @author: karthikp.manchala\n */\n@Entity\n@Table(name = \"PERSON_EMBED_KUDU\", schema = \"kudutest@kudu\")\npublic class EmbeddablePerson\n{\n\n    /** The person id. */\n    @Id\n    private String personId;\n\n    /** The person name. */\n    private String personName;\n    \n    @Embedded\n    private Address address;\n\n    public Address getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(Address address)\n    {\n        this.address = address;\n    }\n\n    /**\n     * Instantiates a new person.\n     */\n    public EmbeddablePerson()\n    {\n    }\n\n    /**\n     * Instantiates a new person.\n     *\n     * @param personId\n     *            the person id\n     * @param personName\n     *            the person name\n     * @param age\n     *            the age\n     * @param salary\n     *            the salary\n     */\n    public EmbeddablePerson(String personId, String personName, Address address)\n    {\n        super();\n        this.personId = personId;\n        this.personName = personName;\n        this.address = address;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/embeddables/KuduEmbeddableIdTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.embeddables;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport junit.framework.Assert;\n\n/**\n * The Class KuduEmbeddableIdTest.\n */\npublic class KuduEmbeddableIdTest\n{\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"kudu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test CRUD.\n     */\n    @Test\n    public void testCRUD()\n    {\n        testInsert();\n        testMerge();\n        testDelete();\n    }\n\n    /**\n     * Test insert.\n     */\n    private void testInsert()\n    {\n\n        Metrics metrics = new Metrics();\n        metrics.setId(getMetricsId());\n        metrics.setValue(100.0);\n\n        em.persist(metrics);\n        em.clear();\n\n        Metrics m = em.find(Metrics.class, getMetricsId());\n\n        Assert.assertNotNull(m);\n        Assert.assertEquals(100.0, m.getValue());\n        Assert.assertNotNull(m.getId());\n        Assert.assertEquals(\"192.xx.xx.xx\", m.getId().getHost());\n        Assert.assertEquals(\"some info\", m.getId().getMetric());\n        Assert.assertEquals(1487142529001l, m.getId().getTime());\n    }\n\n    /**\n     * Test merge.\n     */\n    private void testMerge()\n    {\n\n        Metrics m = em.find(Metrics.class, getMetricsId());\n        m.setValue(200.0);\n\n        em.merge(m);\n        em.clear();\n        Metrics m1 = em.find(Metrics.class, getMetricsId());\n        Assert.assertNotNull(m1);\n        Assert.assertEquals(200.0, m1.getValue());\n        Assert.assertNotNull(m1.getId());\n        Assert.assertEquals(\"192.xx.xx.xx\", m1.getId().getHost());\n        Assert.assertEquals(\"some info\", m1.getId().getMetric());\n        Assert.assertEquals(1487142529001l, m1.getId().getTime());\n    }\n\n    /**\n     * Test delete.\n     */\n    private void testDelete()\n    {\n        Metrics m = em.find(Metrics.class, getMetricsId());\n        em.remove(m);\n        em.clear();\n        Metrics m1 = em.find(Metrics.class, getMetricsId());\n        Assert.assertNull(m1);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n    /**\n     * Gets the metrics id.\n     *\n     * @return the metrics id\n     */\n    private MetricsId getMetricsId()\n    {\n        return new MetricsId(\"192.xx.xx.xx\", \"some info\", 1487142529001l);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/embeddables/KuduEmbeddableTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.embeddables;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\npublic class KuduEmbeddableTest\n{\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"kudu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test CRUD.\n     */\n    @Test\n    public void testCRUD()\n    {\n        testInsert();\n        testMerge();\n        testDelete();\n    }\n\n    /**\n     * Test insert.\n     */\n    private void testInsert()\n    {\n        Address addr = new Address();\n        addr.setStreet(\"4th main\");\n        addr.setCity(\"Bangalore\");\n        addr.setCountry(\"India\");\n        EmbeddablePerson embeddablePerson = new EmbeddablePerson(\"101\", \"karthik\", addr);\n        em.persist(embeddablePerson);\n        em.clear();\n        EmbeddablePerson p = em.find(EmbeddablePerson.class, \"101\");\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"101\", p.getPersonId());\n        Assert.assertEquals(\"karthik\", p.getPersonName());\n        Assert.assertNotNull(p.getAddress());\n        Assert.assertEquals(\"4th main\", p.getAddress().getStreet());\n        Assert.assertEquals(\"Bangalore\", p.getAddress().getCity());\n        Assert.assertEquals(\"India\", p.getAddress().getCountry());\n    }\n\n    /**\n     * Test merge.\n     */\n    private void testMerge()\n    {\n        EmbeddablePerson p = em.find(EmbeddablePerson.class, \"101\");\n        p.setPersonName(\"kp\");\n        Address addr = new Address();\n        addr.setStreet(\"Sector-59\");\n        addr.setCity(\"Noida\");\n        addr.setCountry(\"India\");\n        p.setAddress(addr);\n        em.merge(p);\n        em.clear();\n        EmbeddablePerson p1 = em.find(EmbeddablePerson.class, \"101\");\n        Assert.assertNotNull(p1);\n        Assert.assertEquals(\"101\", p.getPersonId());\n        Assert.assertEquals(\"kp\", p.getPersonName());\n        Assert.assertNotNull(p.getAddress());\n        Assert.assertEquals(\"Sector-59\", p.getAddress().getStreet());\n        Assert.assertEquals(\"Noida\", p.getAddress().getCity());\n        Assert.assertEquals(\"India\", p.getAddress().getCountry());\n    }\n\n    /**\n     * Test delete.\n     */\n    private void testDelete()\n    {\n        EmbeddablePerson p = em.find(EmbeddablePerson.class, \"101\");\n        em.remove(p);\n        em.clear();\n        EmbeddablePerson p1 = em.find(EmbeddablePerson.class, \"101\");\n        Assert.assertNull(p1);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/embeddables/Metrics.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.kudu.embeddables;\n\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * The Class Metrics.\n */\n@Entity\n@Table(name = \"METRICS\", schema = \"kudutest@kudu\")\npublic class Metrics\n{\n\n    /** The id. */\n    @EmbeddedId\n    private MetricsId id;\n\n    /** The value. */\n    private double value;\n\n    /**\n     * Gets the id.\n     *\n     * @return the id\n     */\n    public MetricsId getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     *\n     * @param id\n     *            the new id\n     */\n    public void setId(MetricsId id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the value.\n     *\n     * @return the value\n     */\n    public double getValue()\n    {\n        return value;\n    }\n\n    /**\n     * Sets the value.\n     *\n     * @param value\n     *            the new value\n     */\n    public void setValue(double value)\n    {\n        this.value = value;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/embeddables/MetricsId.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.kudu.embeddables;\n\nimport javax.persistence.Embeddable;\n\n/**\n * The Class MetricsId.\n */\n@Embeddable\npublic class MetricsId\n{\n\n    /** The host. */\n    private String host;\n\n    /** The metric. */\n    private String metric;\n\n    /** The time. */\n    private long time;\n\n    /**\n     * Instantiates a new metrics id.\n     */\n    public MetricsId()\n    {\n    }\n\n    /**\n     * Instantiates a new metrics id.\n     *\n     * @param host\n     *            the host\n     * @param metric\n     *            the metric\n     * @param time\n     *            the time\n     */\n    public MetricsId(String host, String metric, long time)\n    {\n        this.host = host;\n        this.metric = metric;\n        this.time = time;\n    }\n\n    /**\n     * Gets the host.\n     *\n     * @return the host\n     */\n    public String getHost()\n    {\n        return host;\n    }\n\n    /**\n     * Sets the host.\n     *\n     * @param host\n     *            the new host\n     */\n    public void setHost(String host)\n    {\n        this.host = host;\n    }\n\n    /**\n     * Gets the metric.\n     *\n     * @return the metric\n     */\n    public String getMetric()\n    {\n        return metric;\n    }\n\n    /**\n     * Sets the metric.\n     *\n     * @param metric\n     *            the new metric\n     */\n    public void setMetric(String metric)\n    {\n        this.metric = metric;\n    }\n\n    /**\n     * Gets the time.\n     *\n     * @return the time\n     */\n    public long getTime()\n    {\n        return time;\n    }\n\n    /**\n     * Sets the time.\n     *\n     * @param time\n     *            the new time\n     */\n    public void setTime(long time)\n    {\n        this.time = time;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/entities/Item.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Item.\n * \n * @author: devender.yadav\n */\n@Entity\n@Table(name = \"ITEM_KUDU\", schema = \"kudutest@esIndexerTest\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"quantity\"), @Index(name = \"price\") })\npublic class Item\n{\n\n    /** The id. */\n    @Id\n    @Column(name = \"ID\")\n    private String id;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /** The age. */\n    @Column(name = \"QUANTITY\")\n    private int quantity;\n\n    /** The salary. */\n    @Column(name = \"PRICE\")\n    private Double price;\n\n    /**\n     * Instantiates a new item.\n     */\n    public Item()\n    {\n    }\n\n    /**\n     * Instantiates a new item.\n     *\n     * @param id\n     *            the id\n     * @param name\n     *            the name\n     * @param quantity\n     *            the quantity\n     * @param price\n     *            the price\n     */\n    public Item(String id, String name, int quantity, Double price)\n    {\n        super();\n        this.id = id;\n        this.name = name;\n        this.quantity = quantity;\n        this.price = price;\n    }\n\n    /**\n     * Gets the id.\n     *\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     *\n     * @param id\n     *            the new id\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the name.\n     *\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     *\n     * @param name\n     *            the new name\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * Gets the quantity.\n     *\n     * @return the quantity\n     */\n    public int getQuantity()\n    {\n        return quantity;\n    }\n\n    /**\n     * Sets the quantity.\n     *\n     * @param quantity\n     *            the new quantity\n     */\n    public void setQuantity(int quantity)\n    {\n        this.quantity = quantity;\n    }\n\n    /**\n     * Gets the price.\n     *\n     * @return the price\n     */\n    public Double getPrice()\n    {\n        return price;\n    }\n\n    /**\n     * Sets the price.\n     *\n     * @param price\n     *            the new price\n     */\n    public void setPrice(Double price)\n    {\n        this.price = price;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/entities/Person.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.entities;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Person.\n * \n * @author: karthikp.manchala\n */\n@Entity\n@Table(name = \"PERSON_KUDU\", schema = \"kudutest@kudu\")\npublic class Person\n{\n\n    /** The person id. */\n    @Id\n    private String personId;\n\n    /** The person name. */\n    private String personName;\n\n    /** The age. */\n    private long age;\n\n    /** The salary. */\n    private Double salary;\n\n    /**\n     * Instantiates a new person.\n     */\n    public Person()\n    {\n    }\n\n    /**\n     * Instantiates a new person.\n     *\n     * @param personId\n     *            the person id\n     * @param personName\n     *            the person name\n     * @param age\n     *            the age\n     * @param salary\n     *            the salary\n     */\n    public Person(String personId, String personName, long age, Double salary)\n    {\n        super();\n        this.personId = personId;\n        this.personName = personName;\n        this.age = age;\n        this.salary = salary;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public long getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the new age\n     */\n    public void setAge(long age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the salary.\n     * \n     * @return the salary\n     */\n    public Double getSalary()\n    {\n        return salary;\n    }\n\n    /**\n     * Sets the salary.\n     * \n     * @param salary\n     *            the new salary\n     */\n    public void setSalary(Double salary)\n    {\n        this.salary = salary;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/es/KuduESAggregationTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.es;\n\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.kudu.entities.Item;\n\nimport junit.framework.Assert;\n\n/**\n * The Class KuduESAggregationTest.\n * \n * @author devender.yadav\n */\npublic class KuduESAggregationTest\n{\n\n    /** The node. */\n    private static Node node = null;\n\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"esIndexerTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Test aggregation.\n     */\n    @Test\n    public void testAggregations()\n    {\n        testMinAggregation();\n        testMaxAggregation();\n        testSumAggregation();\n        testAvgAggregation();\n        testMinMaxSumAvgAggregation();\n        testAggregationWithWhereClause();\n        testLikeQuery();\n    }\n\n    /**\n     * Test min aggregation.\n     */\n    private void testMinAggregation()\n    {\n        String queryString = \"Select min(i.price) from Item i\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(100.0, resultList.get(0));\n    }\n\n    /**\n     * Test max aggregation.\n     */\n    private void testMaxAggregation()\n    {\n        String queryString = \"Select max(i.price) from Item i\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(400.0, resultList.get(0));\n    }\n\n    /**\n     * Test sum aggregation.\n     */\n    private void testSumAggregation()\n    {\n        String queryString = \"Select sum(i.quantity) from Item i\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(100.0, resultList.get(0));\n    }\n\n    /**\n     * Test avg aggregation.\n     */\n    private void testAvgAggregation()\n    {\n        String queryString = \"Select avg(i.quantity) from Item i\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(25.0, resultList.get(0));\n    }\n\n    /**\n     * Test min max sum avg aggregation.\n     */\n    private void testMinMaxSumAvgAggregation()\n    {\n        String queryString = \"Select min(i.price), max(i.price), sum(i.price), avg(i.price) from Item i\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(4, resultList.size());\n        Assert.assertEquals(100.0, resultList.get(0));\n        Assert.assertEquals(400.0, resultList.get(1));\n        Assert.assertEquals(1000.0, resultList.get(2));\n        Assert.assertEquals(250.0, resultList.get(3));\n    }\n\n    /**\n     * Test aggregation with where clause.\n     */\n    private void testAggregationWithWhereClause()\n    {\n\n        String queryString = \"Select min(i.price) from Item i where i.quantity > 25\";\n        Query query = em.createNamedQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(300.0, resultList.get(0));\n    }\n\n    /**\n     * Test like query.\n     */\n    private void testLikeQuery()\n    {\n        String queryString = \"Select max(i.quantity) from Item i where i.name like 'item%'\";\n        Query query = em.createQuery(queryString);\n        List resultList = query.getResultList();\n\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(40.0, resultList.get(0));\n    }\n\n    /**\n     * Inits the.\n     *\n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    private void init() throws InterruptedException\n    {\n\n        Item item1 = new Item(\"1\", \"item1\", 10, 100.0);\n        Item item2 = new Item(\"2\", \"item2\", 20, 200.0);\n        Item item3 = new Item(\"3\", \"item3\", 30, 300.0);\n        Item item4 = new Item(\"4\", \"item4\", 40, 400.0);\n\n        em.persist(item1);\n        em.persist(item2);\n        em.persist(item3);\n        em.persist(item4);\n\n        waitThread();\n    }\n\n    /**\n     * Delete records.\n     *\n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    private void deleteRecords() throws InterruptedException\n    {\n        em.remove(em.find(Item.class, \"1\"));\n        em.remove(em.find(Item.class, \"2\"));\n        em.remove(em.find(Item.class, \"3\"));\n        em.remove(em.find(Item.class, \"4\"));\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        deleteRecords();\n        if (em != null)\n        {\n            em.close();\n        }\n    }\n\n    /**\n     * Tear down after class.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n\n        if (emf != null)\n        {\n            emf.close();\n        }\n\n        if (node != null)\n            node.close();\n    }\n\n    /**\n     * Check if server running.\n     *\n     * @return true, if successful\n     */\n    private static boolean checkIfServerRunning()\n    {\n        try\n        {\n            Socket socket = new Socket(\"127.0.0.1\", 9300);\n            return socket.getInetAddress() != null;\n        }\n        catch (UnknownHostException e)\n        {\n            return false;\n        }\n        catch (IOException e)\n        {\n            return false;\n        }\n    }\n\n    /**\n     * Wait thread.\n     *\n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    private void waitThread() throws InterruptedException\n    {\n        Thread.sleep(2000);\n    }\n\n}"
  },
  {
    "path": "src/kundera-kudu/src/test/java/com/impetus/client/kudu/query/KuduQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.kudu.query;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.kudu.entities.Person;\n\nimport junit.framework.Assert;\n\n/**\n * The Class KuduQueryTest.\n */\npublic class KuduQueryTest\n{\n    /** The Constant KUDU_PU. */\n    private static final String KUDU_PU = \"kudu\";\n\n    /** The Constant T. */\n    private static final boolean T = true;\n\n    /** The Constant F. */\n    private static final boolean F = false;\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(KUDU_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n        createPersons();\n    }\n\n    /**\n     * Test select.\n     */\n    @Test\n    public void testSelect()\n    {\n\n        Query query = em.createQuery(\"Select p from Person p\");\n        List<Person> results = query.getResultList();\n        Assert.assertEquals(5, results.size());\n        assertResults(results, T, T, T, T, T);\n\n        query = em.createQuery(\"Select p.personName from Person p where p.age = 20\");\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Person person = results.get(0);\n        Assert.assertNotNull(person);\n        Assert.assertEquals(\"karthik\", person.getPersonName());\n        Assert.assertNull(person.getPersonId());\n        Assert.assertNull(person.getSalary());\n        Assert.assertEquals(0, person.getAge());\n\n        query = em.createQuery(\"Select p from Person p where p.age >= 20\");\n        results = query.getResultList();\n        Assert.assertEquals(4, results.size());\n        assertResults(results, F, T, T, T, T);\n\n        query = em.createQuery(\"Select p from Person p where p.age > 20\");\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        assertResults(results, F, F, T, T, T);\n\n        query = em.createQuery(\"Select p from Person p where p.personId = '101'\");\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        assertResults(results, T, F, F, F, F);\n\n        query = em.createQuery(\"Select p.age, p.salary from Person p where p.age >= 20 and p.age <= 40\");\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n\n        query = em.createQuery(\"Select p.age, p.salary from Person p where p.age >= ?1 and p.age <= ?2\");\n        query.setParameter(1, 20);\n        query.setParameter(2, 40);\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n\n        query = em.createQuery(\"Select p.age, p.salary from Person p where p.age >= :age1 and p.age <= :age2\");\n        query.setParameter(\"age1\", 20);\n        query.setParameter(\"age2\", 40);\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n\n        query = em.createQuery(\"Select p from Person p where p.personId in (101, 104)\");\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        assertResults(results, T, F, F, T, F);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        deletePersons();\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n    /**\n     * Creates the persons.\n     */\n    private static void createPersons()\n    {\n        Person person1 = new Person(\"101\", \"dev\", 10, 10000.1);\n        em.persist(person1);\n        Person person2 = new Person(\"102\", \"karthik\", 20, 20000.2);\n        em.persist(person2);\n        Person person3 = new Person(\"103\", \"pg\", 30, 30000.3);\n        em.persist(person3);\n        Person person4 = new Person(\"104\", \"amit\", 40, 40000.4);\n        em.persist(person4);\n        Person person5 = new Person(\"105\", \"vivek\", 50, 50000.5);\n        em.persist(person5);\n    }\n\n    /**\n     * Delete persons.\n     */\n    private static void deletePersons()\n    {\n        Query query = em.createQuery(\"Select p from Person p\");\n        List<Person> results = query.getResultList();\n        for (Person p : results)\n        {\n            em.remove(p);\n        }\n    }\n\n    /**\n     * Validate person1.\n     *\n     * @param p\n     *            the p\n     */\n    protected void validatePerson1(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"101\", p.getPersonId());\n        Assert.assertEquals(\"dev\", p.getPersonName());\n        Assert.assertEquals(10, p.getAge());\n        Assert.assertEquals(10000.1, p.getSalary());\n    }\n\n    /**\n     * Validate person2.\n     *\n     * @param p\n     *            the p\n     */\n    protected void validatePerson2(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"102\", p.getPersonId());\n        Assert.assertEquals(\"karthik\", p.getPersonName());\n        Assert.assertEquals(20, p.getAge());\n        Assert.assertEquals(20000.2, p.getSalary());\n    }\n\n    /**\n     * Validate person3.\n     *\n     * @param p\n     *            the p\n     */\n    protected void validatePerson3(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"103\", p.getPersonId());\n        Assert.assertEquals(\"pg\", p.getPersonName());\n        Assert.assertEquals(30, p.getAge());\n        Assert.assertEquals(30000.3, p.getSalary());\n    }\n\n    /**\n     * Validate person4.\n     *\n     * @param p\n     *            the p\n     */\n    protected void validatePerson4(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"104\", p.getPersonId());\n        Assert.assertEquals(\"amit\", p.getPersonName());\n        Assert.assertEquals(40, p.getAge());\n        Assert.assertEquals(40000.4, p.getSalary());\n    }\n\n    /**\n     * Validate person5.\n     *\n     * @param p\n     *            the p\n     */\n    protected void validatePerson5(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"105\", p.getPersonId());\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertEquals(50, p.getAge());\n        Assert.assertEquals(50000.5, p.getSalary());\n    }\n\n    /**\n     * Assert results.\n     *\n     * @param results\n     *            the results\n     * @param foundPerson1\n     *            the found person1\n     * @param foundPerson2\n     *            the found person2\n     * @param foundPerson3\n     *            the found person3\n     * @param foundPerson4\n     *            the found person4\n     * @param foundPerson5\n     *            the found person5\n     */\n    protected void assertResults(List<Person> results, boolean foundPerson1, boolean foundPerson2, boolean foundPerson3,\n            boolean foundPerson4, boolean foundPerson5)\n    {\n        for (Person person : results)\n        {\n            switch (person.getPersonId())\n            {\n            case \"101\":\n                if (foundPerson1)\n                    validatePerson1(person);\n                else\n                    Assert.fail();\n                break;\n            case \"102\":\n                if (foundPerson2)\n                    validatePerson2(person);\n                else\n                    Assert.fail();\n                break;\n            case \"103\":\n                if (foundPerson3)\n                    validatePerson3(person);\n                else\n                    Assert.fail();\n                break;\n            case \"104\":\n                if (foundPerson4)\n                    validatePerson4(person);\n                else\n                    Assert.fail();\n                break;\n            case \"105\":\n                if (foundPerson5)\n                    validatePerson5(person);\n                else\n                    Assert.fail();\n                break;\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-kudu/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"kudu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.client.kudu.entities.Person</class>\r\n\t\t<class>com.impetus.client.kudu.embeddables.EmbeddablePerson</class>\r\n\t\t<class>com.impetus.client.kudu.embeddables.Metrics</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"quickstart.cloudera\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"7051\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"kudutest\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"kudu\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.kudu.KuduDBClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"kudu-auto-gen-pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.client.kudu.autogeneratedid.Employee</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"quickstart.cloudera\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"7051\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"kudutest\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"kudu\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.kudu.KuduDBClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"esIndexerTest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.client.kudu.entities.Item</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"quickstart.cloudera\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"7051\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"kudutest\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"kudu\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.kudu.KuduDBClientFactory\" />\r\n\t\t\t<property name=\"kundera.indexer.class\" value=\"com.impetus.client.es.index.ESIndexer\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"dataTypeTest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.client.kudu.crud.datatypes.entities.StudentKuduBytePrimitive</class>\r\n\t\t<class>com.impetus.client.kudu.crud.datatypes.entities.StudentKuduByteWrapper</class>\r\n\t\t<class>com.impetus.client.kudu.crud.datatypes.entities.StudentKuduInt</class>\r\n\t\t<class>com.impetus.client.kudu.crud.datatypes.entities.StudentKuduInteger</class>\r\n\t\t<class>com.impetus.client.kudu.crud.datatypes.entities.StudentKuduLongPrimitive</class>\r\n\t\t<class>com.impetus.client.kudu.crud.datatypes.entities.StudentKuduLongWrapper</class>\r\n\t\t<class>com.impetus.client.kudu.crud.datatypes.entities.StudentKuduShortPrimitive</class>\r\n\t\t<class>com.impetus.client.kudu.crud.datatypes.entities.StudentKuduShortWrapper</class>\r\n\t\t<class>com.impetus.client.kudu.crud.datatypes.entities.StudentKuduString</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"quickstart.cloudera\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"7051\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"kudutest\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"kudu\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.kudu.KuduDBClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\r\n</persistence>\r\n"
  },
  {
    "path": "src/kundera-kudu/src/test/resources/esindexer.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<indexerProperties>\n\t<nodes>\n\t\t<node>\n\t\t\t<properties>\n\t\t\t\t<property name=\"host\" value=\"localhost\" />\n\t\t\t\t<property name=\"port\" value=\"9300\" />\n\t\t\t</properties>\n\t\t</node>\n\t</nodes>\n</indexerProperties>"
  },
  {
    "path": "src/kundera-mongo/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus</groupId>\n\t\t<artifactId>kundera</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-mongo</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-mongo</name>\n\t<url>http://maven.apache.org</url>\n\n\t<dependencies>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.mongodb</groupId>\n\t\t\t<artifactId>mongo-java-driver</artifactId>\n\t\t\t<version>3.4.2</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<!-- contiperf dependency should not be here -->\n\t\t<dependency>\n\t\t\t<groupId>org.databene</groupId>\n\t\t\t<artifactId>contiperf</artifactId>\n\t\t\t<version>2.2.0</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-elastic-search</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<!-- <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> \n\t\t\t\t<configuration> The destination file for the code coverage report has to \n\t\t\t\tbe set to the same value in the parent pom and in each module pom. Then JaCoCo \n\t\t\t\twill add up information in the same report, so that, it will give the cross-module \n\t\t\t\tcode coverage. <destFile>${project.basedir}/../target/jacoco-it.exec</destFile> \n\t\t\t\t</configuration> <executions> <execution> <id>post-test</id> <configuration> \n\t\t\t\t<skip>true</skip> </configuration> </execution> </executions> </plugin> -->\n\n\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/META-INF/MANIFEST.MF",
    "content": "Manifest-Version: 1.0\r\nClass-Path: \r\n\r\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/DefaultMongoDBDataHandler.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Lob;\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.Metamodel;\n\nimport org.bson.types.ObjectId;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.google.common.io.ByteStreams;\nimport com.impetus.client.mongodb.utils.MongoDBUtils;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.mongodb.BasicDBList;\nimport com.mongodb.BasicDBObject;\nimport com.mongodb.DBCollection;\nimport com.mongodb.DBCursor;\nimport com.mongodb.DBObject;\nimport com.mongodb.gridfs.GridFS;\nimport com.mongodb.gridfs.GridFSDBFile;\nimport com.mongodb.gridfs.GridFSInputFile;\n\n/**\n * Provides utility methods for handling data held in MongoDB.\n * \n * @author amresh.singh\n */\npublic final class DefaultMongoDBDataHandler implements MongoDBDataHandler\n{\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(DefaultMongoDBDataHandler.class);\n\n    /**\n     * Gets the entity from document.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param m\n     *            the m\n     * @param document\n     *            the document\n     * @param relations\n     *            the relations\n     * @return the entity from document\n     */\n    public Map<String, Object> getEntityFromDocument(Class<?> entityClass, Object entity, EntityMetadata m,\n            DBObject document, List<String> relations, Map<String, Object> relationValue,\n            final KunderaMetadata kunderaMetadata)\n    {\n        // Map to hold property-name=>foreign-entity relations\n        try\n        {\n            // Populate primary key column\n            Object rowKey = document.get(\"_id\");\n            Class<?> rowKeyValueClass = rowKey.getClass();\n            Class<?> idClass = null;\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                    .getMetamodel(m.getPersistenceUnit());\n            idClass = m.getIdAttribute().getJavaType();\n            rowKey = MongoDBUtils.populateValue(rowKey, idClass);\n            AbstractAttribute idAttrib = (AbstractAttribute) m.getIdAttribute();\n            if (metaModel.isEmbeddable(idAttrib.getBindableJavaType()))\n            {\n                populateEntityFromDocument(entity, rowKey, metaModel, idAttrib);\n            }\n            else\n            {\n                rowKey = MongoDBUtils.getTranslatedObject(rowKey, rowKeyValueClass, idClass);\n                PropertyAccessorHelper.setId(entity, m, rowKey);\n            }\n\n            // Populate entity columns\n            EntityType entityType = metaModel.entity(entityClass);\n\n            Set<Attribute> columns = entityType.getAttributes();\n\n            for (Attribute column : columns)\n            {\n                if (!column.equals(m.getIdAttribute()))\n                {\n                    String jpaColumnName = ((AbstractAttribute) column).getJPAColumnName();\n\n                    Class javaType = ((AbstractAttribute) column).getBindableJavaType();\n                    if (metaModel.isEmbeddable(javaType))\n                    {\n                        onViaEmbeddable(column, entity, metaModel, document);\n                    }\n                    else if (!column.isAssociation())\n                    {\n                        DocumentObjectMapper.setFieldValue(document, entity, column, false);\n                    }\n                    else if (relations != null)\n                    {\n                        if (relationValue == null)\n                        {\n                            relationValue = new HashMap<>();\n                        }\n\n                        if (relations.contains(jpaColumnName)\n                                && !jpaColumnName.equals(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName()))\n                        {\n                            Object colValue = document.get(jpaColumnName);\n                            if (colValue != null)\n                            {\n                                String colFieldName = m.getFieldName(jpaColumnName);\n\n                                EntityMetadata relationMetadata = KunderaMetadataManager.getEntityMetadata(\n                                        kunderaMetadata, ((AbstractAttribute) entityType.getAttribute(colFieldName))\n                                                .getBindableJavaType());\n\n                                colValue = MongoDBUtils.getTranslatedObject(colValue, colValue.getClass(),\n                                        relationMetadata.getIdAttribute().getJavaType());\n\n                            }\n                            relationValue.put(jpaColumnName, colValue);\n                        }\n                    }\n                }\n            }\n            return relationValue;\n        }\n        catch (InstantiationException e)\n        {\n            log.error(\"Error while instantiating \" + entityClass + \", Caused by: \", e);\n            return relationValue;\n        }\n        catch (IllegalAccessException e)\n        {\n            log.error(\"Error while Getting entity from Document, Caused by: \", e);\n            return relationValue;\n        }\n        catch (PropertyAccessException e)\n        {\n            log.error(\"Error while Getting entity from Document, Caused by: \", e);\n            return relationValue;\n        }\n    }\n\n    private void populateEntityFromDocument(Object entity, Object rowKey, MetamodelImpl metaModel,\n            AbstractAttribute attrib) throws InstantiationException, IllegalAccessException\n    {\n        EmbeddableType embeddable = metaModel.embeddable(attrib.getBindableJavaType());\n        Iterator<Attribute> iter = embeddable.getAttributes().iterator();\n        Object compoundKey = attrib.getBindableJavaType().newInstance();\n        while (iter.hasNext())\n        {\n            AbstractAttribute compositeAttrib = (AbstractAttribute) iter.next();\n            Object value = ((BasicDBObject) rowKey).get(compositeAttrib.getJPAColumnName());\n\n            if (metaModel.isEmbeddable(compositeAttrib.getBindableJavaType()))\n            {\n                populateEntityFromDocument(compoundKey, value, metaModel, compositeAttrib);\n\n            }\n            else\n            {\n                PropertyAccessorHelper.set(compoundKey, (Field) compositeAttrib.getJavaMember(), value);\n            }\n        }\n        PropertyAccessorHelper.set(entity, (Field) attrib.getJavaMember(), compoundKey);\n    }\n\n    /**\n     * Gets the entity from GFSDBFile.\n     * \n     * @param entityClazz\n     *            the entity clazz\n     * @param entity\n     *            the entity\n     * @param m\n     *            the m\n     * @param outputFile\n     *            the output file\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @return the entity from GFSDBFile\n     */\n    public Object getEntityFromGFSDBFile(Class<?> entityClazz, Object entity, EntityMetadata m, GridFSDBFile outputFile,\n            KunderaMetadata kunderaMetadata)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(m.getPersistenceUnit());\n        String id = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n        Object rowKey = ((DBObject) outputFile.get(MongoDBUtils.METADATA)).get(id);\n        Class<?> rowKeyValueClass = rowKey.getClass();\n        Class<?> idClass = m.getIdAttribute().getJavaType();\n        rowKey = MongoDBUtils.populateValue(rowKey, idClass);\n        rowKey = MongoDBUtils.getTranslatedObject(rowKey, rowKeyValueClass, idClass);\n        PropertyAccessorHelper.setId(entity, m, rowKey);\n        EntityType entityType = metaModel.entity(entityClazz);\n\n        Set<Attribute> columns = entityType.getAttributes();\n        for (Attribute column : columns)\n        {\n            boolean isLob = ((Field) column.getJavaMember()).getAnnotation(Lob.class) != null;\n            if (isLob)\n            {\n                if (column.getJavaType().isAssignableFrom(byte[].class))\n                {\n                    InputStream is = outputFile.getInputStream();\n                    try\n                    {\n                        PropertyAccessorHelper.set(entity, (Field) column.getJavaMember(), ByteStreams.toByteArray(is));\n                    }\n                    catch (IOException e)\n                    {\n                        log.error(\"Error while converting inputstream from GridFSDBFile to byte array, Caused by: \", e);\n                        throw new KunderaException(\n                                \"Error while converting inputstream from GridFSDBFile to byte array, Caused by: \", e);\n                    }\n                }\n            }\n            else if (!column.equals(m.getIdAttribute()))\n                DocumentObjectMapper.setFieldValue(outputFile, entity, column, true);\n        }\n        return entity;\n    }\n\n    /**\n     * Gets the document from entity.\n     * \n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param relations\n     *            the relations\n     * @return the document from entity\n     * @throws PropertyAccessException\n     *             the property access exception\n     */\n    public Map<String, DBObject> getDocumentFromEntity(EntityMetadata m, Object entity, List<RelationHolder> relations,\n            final KunderaMetadata kunderaMetadata) throws PropertyAccessException\n    {\n        Map<String, DBObject> dbObjects = new HashMap<String, DBObject>();\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n        // Populate Row Key\n        Object id = PropertyAccessorHelper.getId(entity, m);\n\n        DBObject dbObj = MongoDBUtils.getDBObject(m, m.getTableName(), dbObjects, metaModel, id);\n\n        // dbObjects.put(m.getTableName(), dbObj);\n\n        // Populate columns\n        Set<Attribute> columns = entityType.getAttributes();\n        for (Attribute column : columns)\n        {\n            // String tableName = ((AbstractAttribute) column).getTableName() !=\n            // null ? ((AbstractAttribute) column)\n            // .getTableName() : m.getTableName();\n            // dbObj = MongoDBUtils.getDBObject(m, tableName, dbObjects,\n            // metaModel, id);\n\n            if (!column.equals(m.getIdAttribute()))\n            {\n                try\n                {\n                    Class javaType = ((AbstractAttribute) column).getBindableJavaType();\n                    if (metaModel.isEmbeddable(javaType))\n                    {\n                        Map<String, DBObject> embeddedObjects = onEmbeddable(column, entity, metaModel, dbObj,\n                                m.getTableName());\n                        for (String documentName : embeddedObjects.keySet())\n                        {\n                            DBObject db = dbObjects.get(documentName);\n                            if (db == null)\n                            {\n                                db = MongoDBUtils.getDBObject(m, documentName, dbObjects, metaModel, id);\n                            }\n                            db.put(((AbstractAttribute) column).getJPAColumnName(), embeddedObjects.get(documentName));\n                            dbObjects.put(documentName, db);\n\n                        }\n                    }\n                    else if (!column.isAssociation())\n                    {\n                        DocumentObjectMapper.extractFieldValue(entity, dbObj, column);\n                    }\n                }\n                catch (PropertyAccessException paex)\n                {\n                    log.error(\"Can't access property \" + column.getName());\n                }\n            }\n            // dbObjects.put(tableName, dbObj);\n        }\n        if (relations != null)\n        {\n            dbObj = dbObjects.get(m.getTableName());\n            for (RelationHolder rh : relations)\n            {\n                dbObj.put(rh.getRelationName(),\n                        MongoDBUtils.populateValue(rh.getRelationValue(), rh.getRelationValue().getClass()));\n            }\n            // dbObjects.put(m.getTableName(), dbObj);\n        }\n\n        if (((AbstractManagedType) entityType).isInherited())\n        {\n            dbObj = dbObjects.get(m.getTableName());\n            String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n            String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();\n\n            // No need to check for empty or blank, as considering it as valid\n            // name for nosql!\n            if (discrColumn != null && discrValue != null)\n            {\n                dbObj.put(discrColumn, discrValue);\n            }\n            // dbObjects.put(m.getTableName(), dbObj);\n        }\n        return dbObjects;\n    }\n\n    /**\n     * Gets the GFSInputFile from entity.\n     * \n     * @param gfs\n     *            the gfs\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @return the GFS iuput file from entity\n     */\n    public GridFSInputFile getGFSInputFileFromEntity(GridFS gfs, EntityMetadata m, Object entity,\n            KunderaMetadata kunderaMetadata, boolean isUpdate)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n        GridFSInputFile gridFSInputFile = null;\n\n        DBObject gfsMetadata = new BasicDBObject();\n\n        Set<Attribute> columns = entityType.getAttributes();\n        for (Attribute column : columns)\n        {\n            boolean isLob = ((Field) column.getJavaMember()).getAnnotation(Lob.class) != null;\n            if (isLob)\n            {\n                gridFSInputFile = createGFSInputFile(gfs, entity, (Field) column.getJavaMember());\n                gridFSInputFile.setFilename(column.getName());\n            }\n            else\n            {\n                if (isUpdate && column.getName().equals(m.getIdAttribute().getName()))\n                {\n                    gfsMetadata.put(((AbstractAttribute) column).getJPAColumnName(), new ObjectId());\n                }\n                else\n                    DocumentObjectMapper.extractFieldValue(entity, gfsMetadata, column);\n            }\n        }\n        gridFSInputFile.setMetaData(gfsMetadata);\n        return gridFSInputFile;\n    }\n\n    /**\n     * Creates the GFS Input file.\n     * \n     * @param gfs\n     *            the gfs\n     * @param entity\n     *            the entity\n     * @param f\n     *            the f\n     * @return the grid fs input file\n     */\n    private GridFSInputFile createGFSInputFile(GridFS gfs, Object entity, Field f)\n    {\n        Object obj = PropertyAccessorHelper.getObject(entity, f);\n        GridFSInputFile gridFSInputFile = null;\n        if (f.getType().isAssignableFrom(byte[].class))\n            gridFSInputFile = gfs.createFile((byte[]) obj);\n        else if (f.getType().isAssignableFrom(File.class))\n        {\n            try\n            {\n                gridFSInputFile = gfs.createFile((File) obj);\n            }\n            catch (IOException e)\n            {\n                log.error(\"Error while creating GridFS file for \\\"\" + f.getName() + \"\\\". Caused by: \", e);\n                throw new KunderaException(\"Error while creating GridFS file for \\\"\" + f.getName() + \"\\\". Caused by: \",\n                        e);\n            }\n        }\n        else\n            new UnsupportedOperationException(f.getType().getSimpleName() + \" is unsupported Lob object\");\n        return gridFSInputFile;\n    }\n\n    /**\n     * Retrieves A collection of embedded object within a document that match a\n     * criteria specified in <code>query</code> TODO: This code requires a\n     * serious overhawl. Currently it assumes that user query is in the form\n     * \"Select alias.columnName from EntityName alias\". However, correct query\n     * to be supported is\n     * \"Select alias.superColumnName.columnName from EntityName alias\"\n     * \n     * @param dbCollection\n     *            the db collection\n     * @param m\n     *            the m\n     * @param documentName\n     *            the document name\n     * @param mongoQuery\n     *            the mongo query\n     * @param result\n     *            the result\n     * @param orderBy\n     *            the order by\n     * @param maxResult\n     * @return the embedded object list\n     * @throws PropertyAccessException\n     *             the property access exception\n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     */\n    public List getEmbeddedObjectList(DBCollection dbCollection, EntityMetadata m, String documentName,\n            BasicDBObject mongoQuery, String result, BasicDBObject orderBy, int maxResult, int firstResult,\n            BasicDBObject keys, final KunderaMetadata kunderaMetadata)\n                    throws PropertyAccessException, InstantiationException, IllegalAccessException\n    {\n        List list = new ArrayList();// List of embedded object to be returned\n\n        // Specified after entity alias in query\n        String columnName = result;\n\n        // Something user didn't specify and we have to derive\n        // TODO: User must specify this in query and remove this logic once\n        // query format is changed\n\n        String enclosingDocumentName = null;\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n        EmbeddableType superColumn = null;\n        Set<Attribute> columns = null;\n        Attribute attrib = null;\n        try\n        {\n            attrib = entityType.getAttribute(columnName);\n            Map<String, EmbeddableType> embeddables = metaModel.getEmbeddables(m.getEntityClazz());\n            for (String key : embeddables.keySet())\n            {\n                superColumn = embeddables.get(key);\n                columns = superColumn.getAttributes();\n\n                for (Attribute column : columns)\n                {\n                    if (((AbstractAttribute) column).getJPAColumnName().equals(columnName))\n                    {\n                        enclosingDocumentName = key;\n                        break;\n                    }\n                }\n            }\n        }\n        catch (IllegalArgumentException iax)\n        {\n            if (log.isWarnEnabled())\n            {\n                log.warn(\"No column found for: \" + columnName);\n            }\n        }\n\n        // Query for fetching entities based on user specified criteria\n        DBCursor cursor = orderBy != null ? dbCollection.find(mongoQuery, keys).sort(orderBy)\n                : dbCollection.find(mongoQuery, keys).limit(maxResult).skip(firstResult);\n\n        if (superColumn != null)\n        {\n            Field superColumnField = (Field) attrib.getJavaMember();\n            while (cursor.hasNext())\n            {\n                DBObject fetchedDocument = cursor.next();\n                Object embeddedDocumentObject = fetchedDocument.get(superColumnField.getName());\n\n                if (embeddedDocumentObject != null)\n                {\n                    if (embeddedDocumentObject instanceof BasicDBList)\n                    {\n                        Class embeddedObjectClass = PropertyAccessorHelper.getGenericClass(superColumnField);\n                        for (Object dbObj : (BasicDBList) embeddedDocumentObject)\n                        {\n                            Object obj = embeddedObjectClass.newInstance();\n                            Object embeddedObject = new DocumentObjectMapper().getObjectFromDocument(metaModel,\n                                    (BasicDBObject) dbObj, superColumn.getAttributes(), obj);\n                            Object fieldValue = PropertyAccessorHelper.getObject(embeddedObject, columnName);\n                        }\n                    }\n                    else if (embeddedDocumentObject instanceof BasicDBObject)\n                    {\n                        Object obj = superColumn.getJavaType().newInstance();\n                        Object embeddedObject = DocumentObjectMapper.getObjectFromDocument(metaModel,\n                                (BasicDBObject) embeddedDocumentObject, superColumn.getAttributes(), obj);\n                        list.add(embeddedObject);\n                    }\n                    else\n                    {\n                        throw new PersistenceException(\"Can't retrieve embedded object from MONGODB document coz \"\n                                + \"it wasn't stored as BasicDBObject, possible problem in format.\");\n                    }\n                }\n            }\n        }\n        return list;\n    }\n\n    /**\n     * @param entityType\n     * @param column\n     * @param m\n     * @param entity\n     */\n    Map<String, DBObject> onEmbeddable(Attribute column, Object entity, Metamodel metaModel, DBObject dbObj,\n            String tableName)\n    {\n        EmbeddableType embeddableType = metaModel.embeddable(((AbstractAttribute) column).getBindableJavaType());\n        Object embeddedObject = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());\n        Map<String, DBObject> embeddedObjects = new HashMap<String, DBObject>();\n\n        if (embeddedObject != null)\n        {\n            if (column.isCollection())\n            {\n                Collection embeddedCollection = (Collection) embeddedObject;\n                // means it is case of element collection\n\n                dbObj.put(((AbstractAttribute) column).getJPAColumnName(),\n                        DocumentObjectMapper.getDocumentListFromCollection(metaModel, embeddedCollection,\n                                embeddableType.getAttributes(), tableName));\n            }\n            else\n            {\n                embeddedObjects = DocumentObjectMapper.getDocumentFromObject(metaModel, embeddedObject,\n                        embeddableType.getAttributes(), tableName);\n                dbObj.put(((AbstractAttribute) column).getJPAColumnName(), embeddedObjects.get(tableName));\n            }\n        }\n        return embeddedObjects;\n    }\n\n    /**\n     * @param entityType\n     * @param column\n     * @param m\n     * @param entity\n     * @param embeddable\n     * @param document\n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     */\n    void onViaEmbeddable(Attribute column, Object entity, Metamodel metamodel, DBObject document)\n            throws InstantiationException, IllegalAccessException\n    {\n        EmbeddableType embeddable = metamodel.embeddable(((AbstractAttribute) column).getBindableJavaType());\n        Field embeddedField = (Field) column.getJavaMember();\n        Object embeddedDocumentObject = null;\n\n        if (column.isCollection())\n        {\n            Class embeddedObjectClass = PropertyAccessorHelper.getGenericClass(embeddedField);\n\n            embeddedDocumentObject = document.get(((AbstractAttribute) column).getJPAColumnName());\n\n            if (embeddedDocumentObject != null)\n            {\n                Collection embeddedCollection = DocumentObjectMapper.getCollectionFromDocumentList(metamodel,\n                        (BasicDBList) embeddedDocumentObject, embeddedField.getType(), embeddedObjectClass,\n                        embeddable.getAttributes());\n                PropertyAccessorHelper.set(entity, embeddedField, embeddedCollection);\n            }\n        }\n        else\n        {\n            Object obj = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());\n            if (obj == null)\n            {\n                obj = ((AbstractAttribute) column).getBindableJavaType().newInstance();\n            }\n            embeddedDocumentObject = document.get(((AbstractAttribute) column).getJPAColumnName());\n            PropertyAccessorHelper.set(entity, embeddedField, DocumentObjectMapper.getObjectFromDocument(metamodel,\n                    (BasicDBObject) embeddedDocumentObject, embeddable.getAttributes(), obj));\n        }\n    }\n\n    /**\n     * Gets the lob from GFS entity.\n     * \n     * @param gfs\n     *            the gfs\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @return the lob from gfs entity\n     */\n    public Object getLobFromGFSEntity(GridFS gfs, EntityMetadata m, Object entity, KunderaMetadata kunderaMetadata)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n        Set<Attribute> columns = entityType.getAttributes();\n        for (Attribute column : columns)\n        {\n            boolean isLob = ((Field) column.getJavaMember()).getAnnotation(Lob.class) != null;\n            if (isLob)\n            {\n                return PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Gets the metadata from GFS entity.\n     * \n     * @param gfs\n     *            the gfs\n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @return the metadata from GFS entity\n     */\n    public DBObject getMetadataFromGFSEntity(GridFS gfs, EntityMetadata m, Object entity,\n            KunderaMetadata kunderaMetadata)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(m.getPersistenceUnit());\n\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n        DBObject gfsMetadata = new BasicDBObject();\n        Set<Attribute> columns = entityType.getAttributes();\n        for (Attribute column : columns)\n        {\n            boolean isLob = ((Field) column.getJavaMember()).getAnnotation(Lob.class) != null;\n            if (!isLob)\n            {\n                DocumentObjectMapper.extractFieldValue(entity, gfsMetadata, column);\n            }\n        }\n        return gfsMetadata;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/DocumentObjectMapper.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.mongodb;\r\n\r\nimport java.lang.reflect.Field;\r\nimport java.util.ArrayList;\r\nimport java.util.Arrays;\r\nimport java.util.Collection;\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.Iterator;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.PersistenceException;\r\nimport javax.persistence.metamodel.Attribute;\r\nimport javax.persistence.metamodel.Metamodel;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.client.mongodb.utils.MongoDBUtils;\r\nimport com.impetus.kundera.gis.geometry.Point;\r\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\r\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\r\nimport com.impetus.kundera.metadata.model.attributes.AttributeType;\r\nimport com.impetus.kundera.persistence.EntityReaderException;\r\nimport com.impetus.kundera.property.PropertyAccessException;\r\nimport com.impetus.kundera.property.PropertyAccessorHelper;\r\nimport com.impetus.kundera.property.accessor.EnumAccessor;\r\nimport com.mongodb.BasicDBList;\r\nimport com.mongodb.BasicDBObject;\r\nimport com.mongodb.BasicDBObjectBuilder;\r\nimport com.mongodb.DBObject;\r\n\r\n/**\r\n * Provides functionality for mapping between MongoDB documents and POJOs.\r\n * Contains utility methods for converting one form into another.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class DocumentObjectMapper\r\n{\r\n\r\n    /** The log. */\r\n    private static Logger log = LoggerFactory.getLogger(DocumentObjectMapper.class);\r\n\r\n    /**\r\n     * Creates a MongoDB document object wrt a given Java object. columns in the\r\n     * document correspond Columns provided as List.\r\n     * \r\n     * @param obj\r\n     *            the obj\r\n     * @param columns\r\n     *            the columns\r\n     * @return the document from object\r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    static Map<String, DBObject> getDocumentFromObject(Metamodel metaModel, Object obj, Set<Attribute> columns,\r\n            String tableName) throws PropertyAccessException\r\n    {\r\n        Map<String, DBObject> embeddedObjects = new HashMap<String, DBObject>();\r\n        // BasicDBObject dBObj = new BasicDBObject();\r\n\r\n        for (Attribute column : columns)\r\n        {\r\n            String collectionName = ((AbstractAttribute) column).getTableName() != null\r\n                    ? ((AbstractAttribute) column).getTableName() : tableName;\r\n\r\n            DBObject dbObject = embeddedObjects.get(collectionName);\r\n            if (dbObject == null)\r\n            {\r\n                dbObject = new BasicDBObject();\r\n                embeddedObjects.put(collectionName, dbObject);\r\n            }\r\n\r\n            if (((MetamodelImpl) metaModel).isEmbeddable(((AbstractAttribute) column).getBindableJavaType()))\r\n            {\r\n                DefaultMongoDBDataHandler handler = new DefaultMongoDBDataHandler();\r\n                // handler.onEmbeddable(column, obj, metaModel, dBObj,\r\n                // collectionName);\r\n                handler.onEmbeddable(column, obj, metaModel, dbObject, collectionName);\r\n            }\r\n            else\r\n            {\r\n                extractFieldValue(obj, dbObject, column);\r\n            }\r\n        }\r\n        return embeddedObjects;\r\n    }\r\n\r\n    /**\r\n     * Creates a MongoDB document list from a given java collection. columns in\r\n     * the document correspond Columns provided as List.\r\n     * \r\n     * @param coll\r\n     *            the coll\r\n     * @param columns\r\n     *            the columns\r\n     * @return the document list from collection\r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    static BasicDBObject[] getDocumentListFromCollection(Metamodel metaModel, Collection coll, Set<Attribute> columns,\r\n            String tableName) throws PropertyAccessException\r\n    {\r\n        BasicDBObject[] dBObjects = new BasicDBObject[coll.size()];\r\n        int count = 0;\r\n        for (Object o : coll)\r\n        {\r\n            dBObjects[count] = (BasicDBObject) getDocumentFromObject(metaModel, o, columns, tableName).values()\r\n                    .toArray()[0];\r\n            count++;\r\n        }\r\n        return dBObjects;\r\n    }\r\n\r\n    /**\r\n     * Creates an instance of <code>clazz</code> and populates fields fetched\r\n     * from MongoDB document object. Field names are determined from\r\n     * <code>columns</code>\r\n     * \r\n     * @param documentObj\r\n     *            the document obj\r\n     * @param clazz\r\n     *            the clazz\r\n     * @param columns\r\n     *            the columns\r\n     * @return the object from document\r\n     * @throws IllegalAccessException\r\n     * @throws InstantiationException\r\n     */\r\n    static Object getObjectFromDocument(Metamodel metamodel, BasicDBObject documentObj, Set<Attribute> columns,\r\n            Object obj) throws InstantiationException, IllegalAccessException\r\n    {\r\n        // try\r\n        // {\r\n        // Object obj = clazz.newInstance();\r\n        for (Attribute column : columns)\r\n        {\r\n            if (((MetamodelImpl) metamodel).isEmbeddable(((AbstractAttribute) column).getBindableJavaType()))\r\n            {\r\n                DefaultMongoDBDataHandler handler = new DefaultMongoDBDataHandler();\r\n                handler.onViaEmbeddable(column, obj, metamodel, documentObj);\r\n            }\r\n            else\r\n            {\r\n                setFieldValue(documentObj, obj, column, false);\r\n            }\r\n        }\r\n        return obj;\r\n        // }\r\n        // catch (InstantiationException e)\r\n        // {\r\n        // throw new PersistenceException(e);\r\n        // }\r\n        // catch (IllegalAccessException e)\r\n        // {\r\n        // throw new PersistenceException(e);\r\n        // }\r\n    }\r\n\r\n    /**\r\n     * Setter for column value, by default converted from string value, in case\r\n     * of map it is automatically converted into map using BasicDBObject.\r\n     * \r\n     * @param document\r\n     *            mongo document\r\n     * @param entityObject\r\n     *            searched entity.\r\n     * @param column\r\n     *            column field.\r\n     */\r\n    static void setFieldValue(DBObject document, Object entityObject, Attribute column, boolean isLob)\r\n    {\r\n        Object value = null;\r\n\r\n        if (document != null)\r\n        {\r\n            value = isLob ? ((DBObject) document.get(\"metadata\")).get(((AbstractAttribute) column).getJPAColumnName())\r\n                    : document.get(((AbstractAttribute) column).getJPAColumnName());\r\n        }\r\n        if (value != null)\r\n        {\r\n            Class javaType = column.getJavaType();\r\n            try\r\n            {\r\n                switch (AttributeType.getType(javaType))\r\n                {\r\n                case MAP:\r\n                    PropertyAccessorHelper.set(entityObject, (Field) column.getJavaMember(),\r\n                            ((BasicDBObject) value).toMap());\r\n                    break;\r\n                case SET:\r\n                    List collectionValues = Arrays.asList(((BasicDBList) value).toArray());\r\n                    PropertyAccessorHelper.set(entityObject, (Field) column.getJavaMember(),\r\n                            new HashSet(collectionValues));\r\n                    break;\r\n                case LIST:\r\n                    PropertyAccessorHelper.set(entityObject, (Field) column.getJavaMember(),\r\n                            Arrays.asList(((BasicDBList) value).toArray()));\r\n                    break;\r\n                case POINT:\r\n\r\n                    BasicDBList list = (BasicDBList) value;\r\n\r\n                    Object xObj = list.get(0);\r\n                    Object yObj = list.get(1);\r\n\r\n                    if (xObj != null && yObj != null)\r\n                    {\r\n                        try\r\n                        {\r\n                            double x = Double.parseDouble(xObj.toString());\r\n                            double y = Double.parseDouble(yObj.toString());\r\n\r\n                            Point point = new Point(x, y);\r\n                            PropertyAccessorHelper.set(entityObject, (Field) column.getJavaMember(), point);\r\n                        }\r\n                        catch (NumberFormatException e)\r\n                        {\r\n                            log.error(\r\n                                    \"Error while reading geolocation data for column {} ; Reason - possible corrupt data, Caused by : .\",\r\n                                    column, e);\r\n                            throw new EntityReaderException(\"Error while reading geolocation data for column \" + column\r\n                                    + \"; Reason - possible corrupt data.\", e);\r\n                        }\r\n                    }\r\n                    break;\r\n                case ENUM:\r\n                    EnumAccessor accessor = new EnumAccessor();\r\n                    value = accessor.fromString(javaType, value.toString());\r\n                    PropertyAccessorHelper.set(entityObject, (Field) column.getJavaMember(), value);\r\n                    break;\r\n                case PRIMITIVE:\r\n                    value = MongoDBUtils.populateValue(value, value.getClass());\r\n                    value = MongoDBUtils.getTranslatedObject(value, value.getClass(), javaType);\r\n                    PropertyAccessorHelper.set(entityObject, (Field) column.getJavaMember(), value);\r\n                    break;\r\n                }\r\n            }\r\n            catch (PropertyAccessException paex)\r\n            {\r\n                log.error(\"Error while setting column {} value, caused by : .\",\r\n                        ((AbstractAttribute) column).getJPAColumnName(), paex);\r\n                throw new PersistenceException(paex);\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Extract entity field.\r\n     * \r\n     * @param entity\r\n     *            the entity\r\n     * @param dbObj\r\n     *            the db obj\r\n     * @param column\r\n     *            the column\r\n     * @throws PropertyAccessException\r\n     *             the property access exception\r\n     */\r\n    static void extractFieldValue(Object entity, DBObject dbObj, Attribute column) throws PropertyAccessException\r\n    {\r\n        try\r\n        {\r\n            Object valueObject = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());\r\n\r\n            if (valueObject != null)\r\n            {\r\n                Class javaType = column.getJavaType();\r\n                switch (AttributeType.getType(javaType))\r\n                {\r\n                case MAP:\r\n                    Map mapObj = (Map) valueObject;\r\n                    // BasicDBObjectBuilder builder =\r\n                    // BasicDBObjectBuilder.start(mapObj);\r\n                    BasicDBObjectBuilder b = new BasicDBObjectBuilder();\r\n                    Iterator i = mapObj.entrySet().iterator();\r\n                    while (i.hasNext())\r\n                    {\r\n                        Map.Entry entry = (Map.Entry) i.next();\r\n                        b.add(entry.getKey().toString(),\r\n                                MongoDBUtils.populateValue(entry.getValue(), entry.getValue().getClass()));\r\n                    }\r\n                    dbObj.put(((AbstractAttribute) column).getJPAColumnName(), b.get());\r\n                    break;\r\n                case SET:\r\n                case LIST:\r\n                    Collection collection = (Collection) valueObject;\r\n                    BasicDBList basicDBList = new BasicDBList();\r\n                    for (Object o : collection)\r\n                    {\r\n                        basicDBList.add(o);\r\n                    }\r\n                    dbObj.put(((AbstractAttribute) column).getJPAColumnName(), basicDBList);\r\n                    break;\r\n                case POINT:\r\n\r\n                    Point p = (Point) valueObject;\r\n                    double[] coordinate = new double[] { p.getX(), p.getY() };\r\n                    dbObj.put(((AbstractAttribute) column).getJPAColumnName(), coordinate);\r\n                    break;\r\n                case ENUM:\r\n                case PRIMITIVE:\r\n                    dbObj.put(((AbstractAttribute) column).getJPAColumnName(),\r\n                            MongoDBUtils.populateValue(valueObject, javaType));\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n        catch (PropertyAccessException paex)\r\n        {\r\n            log.error(\"Error while getting column {} value, caused by : .\",\r\n                    ((AbstractAttribute) column).getJPAColumnName(), paex);\r\n            throw new PersistenceException(paex);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Creates a collection of <code>embeddedObjectClass</code> instances\r\n     * wherein each element is java object representation of MongoDB document\r\n     * object contained in <code>documentList</code>. Field names are determined\r\n     * from <code>columns</code>.\r\n     * \r\n     * @param documentList\r\n     *            the document list\r\n     * @param embeddedCollectionClass\r\n     *            the embedded collection class\r\n     * @param embeddedObjectClass\r\n     *            the embedded object class\r\n     * @param columns\r\n     *            the columns\r\n     * @param metamodel\r\n     * @return the collection from document list\r\n     */\r\n    static Collection<?> getCollectionFromDocumentList(Metamodel metamodel, BasicDBList documentList,\r\n            Class embeddedCollectionClass, Class embeddedObjectClass, Set<Attribute> columns)\r\n    {\r\n        Collection<Object> embeddedCollection = null;\r\n        if (embeddedCollectionClass.equals(Set.class))\r\n        {\r\n            embeddedCollection = new HashSet<Object>();\r\n        }\r\n        else if (embeddedCollectionClass.equals(List.class))\r\n        {\r\n            embeddedCollection = new ArrayList<Object>();\r\n        }\r\n        else\r\n        {\r\n            throw new PersistenceException(\r\n                    \"Invalid collection class \" + embeddedCollectionClass + \"; only Set and List allowed\");\r\n        }\r\n\r\n        for (Object dbObj : documentList)\r\n        {\r\n            try\r\n            {\r\n                Object obj = embeddedObjectClass.newInstance();\r\n                embeddedCollection.add(getObjectFromDocument(metamodel, (BasicDBObject) dbObj, columns, obj));\r\n            }\r\n            catch (InstantiationException e)\r\n            {\r\n                throw new PersistenceException(e);\r\n            }\r\n            catch (IllegalAccessException e)\r\n            {\r\n                throw new PersistenceException(e);\r\n            }\r\n        }\r\n\r\n        return embeddedCollection;\r\n    }\r\n}"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClient.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.commons.lang.NotImplementedException;\nimport org.bson.types.ObjectId;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.mongodb.query.MongoDBQuery;\nimport com.impetus.client.mongodb.query.gfs.KunderaGridFS;\nimport com.impetus.client.mongodb.utils.MongoDBUtils;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.lifecycle.states.RemovedState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.annotation.DefaultEntityAnnotationProcessor;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.mongodb.AggregationOutput;\nimport com.mongodb.BasicDBList;\nimport com.mongodb.BasicDBObject;\nimport com.mongodb.BulkWriteException;\nimport com.mongodb.BulkWriteOperation;\nimport com.mongodb.DB;\nimport com.mongodb.DBCollection;\nimport com.mongodb.DBCursor;\nimport com.mongodb.DBEncoder;\nimport com.mongodb.DBObject;\nimport com.mongodb.DefaultDBEncoder;\nimport com.mongodb.MapReduceCommand;\nimport com.mongodb.MapReduceOutput;\nimport com.mongodb.MongoException;\nimport com.mongodb.WriteConcern;\nimport com.mongodb.WriteResult;\nimport com.mongodb.gridfs.GridFSDBFile;\nimport com.mongodb.gridfs.GridFSInputFile;\nimport com.mongodb.util.JSON;\nimport com.mongodb.util.JSONParseException;\n\n/**\n * Client class for MongoDB database.\n * \n * @author devender.yadav\n */\npublic class MongoDBClient extends ClientBase implements Client<MongoDBQuery>, Batcher, ClientPropertiesSetter\n\n{\n    /** The mongo db. */\n    private DB mongoDb;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /** The data handler. */\n    private DefaultMongoDBDataHandler handler;\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(MongoDBClient.class);\n\n    /** The nodes. */\n    private List<Node> nodes = new ArrayList<Node>();\n\n    /** The batch size. */\n    private int batchSize;\n\n    /** The ordered bulk operation. */\n    private boolean orderedBulkOperation;\n\n    /**\n     * Checks if is ordered bulk operation.\n     * \n     * @return true, if is ordered bulk operation\n     */\n    public boolean isOrderedBulkOperation()\n    {\n        return orderedBulkOperation;\n    }\n\n    /**\n     * Sets the ordered bulk operation.\n     * \n     * @param orderedBulkOperation\n     *            the new ordered bulk operation\n     */\n    public void setOrderedBulkOperation(boolean orderedBulkOperation)\n    {\n        this.orderedBulkOperation = orderedBulkOperation;\n    }\n\n    /** The write concern. */\n    private WriteConcern writeConcern = null;\n\n    /** The encoder. */\n    private DBEncoder encoder = DefaultDBEncoder.FACTORY.create();\n\n    /**\n     * Instantiates a new mongo db client.\n     * \n     * @param mongo\n     *            the mongo\n     * @param mgr\n     *            the mgr\n     * @param reader\n     *            the reader\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param externalProperties\n     *            the external properties\n     * @param clientMetadata\n     *            the client metadata\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public MongoDBClient(Object mongo, IndexManager mgr, EntityReader reader, String persistenceUnit,\n            Map<String, Object> externalProperties, ClientMetadata clientMetadata, final KunderaMetadata kunderaMetadata)\n    {\n        // TODO: This could be a constantly called, see how connection pooling\n        // is\n        // relevant here\n        super(kunderaMetadata, externalProperties, persistenceUnit);\n        this.mongoDb = (DB) mongo;\n        this.indexManager = mgr;\n        this.reader = reader;\n        handler = new DefaultMongoDBDataHandler();\n        this.clientMetadata = clientMetadata;\n        populateBatchSize(persistenceUnit, this.externalProperties);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera\n     * .persistence.context.jointable.JoinTableData)\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        String joinTableName = joinTableData.getJoinTableName();\n        String joinColumnName = joinTableData.getJoinColumnName();\n        String invJoinColumnName = joinTableData.getInverseJoinColumnName();\n        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();\n\n        DBCollection dbCollection = mongoDb.getCollection(joinTableName);\n        KunderaCoreUtils.printQuery(\"Persist join table:\" + joinTableName, showQuery);\n\n        for (Object key : joinTableRecords.keySet())\n        {\n            Set<Object> values = joinTableRecords.get(key);\n            Object joinColumnValue = key;\n\n            for (Object childId : values)\n            {\n                DBObject dbObj = new BasicDBObject();\n                dbObj.put(\"_id\", joinColumnValue.toString() + childId);\n                dbObj.put(joinColumnName, MongoDBUtils.populateValue(joinColumnValue, joinColumnValue.getClass()));\n                dbObj.put(invJoinColumnName, MongoDBUtils.populateValue(childId, childId.getClass()));\n                KunderaCoreUtils.printQuery(\"id:\" + joinColumnValue.toString() + childId + \"   \" + joinColumnName + \":\"\n                        + joinColumnValue + \"   \" + invJoinColumnName + \":\" + childId, showQuery);\n\n                dbCollection.save(dbObj, getWriteConcern());\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String joinTableName, String joinColumnName,\n            String inverseJoinColumnName, Object parentId, Class columnJavaType)\n    {\n        List<E> foreignKeys = new ArrayList<E>();\n\n        DBCollection dbCollection = mongoDb.getCollection(joinTableName);\n        BasicDBObject query = new BasicDBObject();\n\n        query.put(joinColumnName, MongoDBUtils.populateValue(parentId, parentId.getClass()));\n        KunderaCoreUtils.printQuery(\"Find by Id:\" + query, showQuery);\n        DBCursor cursor = dbCollection.find(query);\n        DBObject fetchedDocument = null;\n\n        while (cursor.hasNext())\n        {\n            fetchedDocument = cursor.next();\n            Object foreignKey = fetchedDocument.get(inverseJoinColumnName);\n            foreignKey = MongoDBUtils.getTranslatedObject(foreignKey, foreignKey.getClass(), columnJavaType);\n            foreignKeys.add((E) foreignKey);\n        }\n        return foreignKeys;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n\n        List<Object> primaryKeys = new ArrayList<Object>();\n\n        DBCollection dbCollection = mongoDb.getCollection(tableName);\n        BasicDBObject query = new BasicDBObject();\n\n        query.put(columnName, MongoDBUtils.populateValue(columnValue, columnValue.getClass()));\n\n        DBCursor cursor = dbCollection.find(query);\n        KunderaCoreUtils.printQuery(\"Find id by column:\" + query, showQuery);\n        DBObject fetchedDocument = null;\n\n        while (cursor.hasNext())\n        {\n            fetchedDocument = cursor.next();\n            Object primaryKey = fetchedDocument.get(pKeyName);\n            primaryKey = MongoDBUtils.getTranslatedObject(primaryKey, primaryKey.getClass(), metadata.getIdAttribute()\n                    .getJavaType());\n            primaryKeys.add(primaryKey);\n        }\n\n        if (primaryKeys != null && !primaryKeys.isEmpty())\n        {\n            return primaryKeys.toArray(new Object[0]);\n        }\n        return null;\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @seecom.impetus.kundera.Client#loadColumns(com.impetus.kundera.ejb.\n     * EntityManager, java.lang.Class, java.lang.String, java.lang.String,\n     * java.lang.String, com.impetus.kundera.metadata.EntityMetadata)\n     */\n    @Override\n    public Object find(Class entityClass, Object key)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(entityMetadata.getEntityClazz());\n\n        return managedType.hasLobAttribute() ? findGFSEntity(entityMetadata, entityClass, key) : find(entityClass, key,\n                entityMetadata, metaModel, managedType);\n    }\n\n    /**\n     * Find.\n     *\n     * @param entityClass\n     *            the entity class\n     * @param key\n     *            the key\n     * @param entityMetadata\n     *            the entity metadata\n     * @param metaModel\n     *            the meta model\n     * @param managedType\n     *            the managed type\n     * @return the object\n     */\n    private Object find(Class entityClass, Object key, EntityMetadata entityMetadata, MetamodelImpl metaModel,\n            AbstractManagedType managedType)\n    {\n        List<String> relationNames = entityMetadata.getRelationNames();\n\n        BasicDBObject query = new BasicDBObject();\n\n        if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n        {\n            MongoDBUtils.populateCompoundKey(query, entityMetadata, metaModel, key);\n        }\n        else\n        {\n            query.put(\"_id\", MongoDBUtils.populateValue(key, key.getClass()));\n        }\n\n        // For secondary tables.\n        List<String> secondaryTables = ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation())\n                .getSecondaryTablesName();\n        secondaryTables.add(entityMetadata.getTableName());\n\n        Object enhancedEntity = null;\n        Map<String, Object> relationValue = null;\n        // Here you need to fetch by sub managed type.\n\n        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n\n        for (String tableName : secondaryTables)\n        {\n            DBCollection dbCollection = mongoDb.getCollection(tableName);\n            KunderaCoreUtils.printQuery(\"Find document:\" + query, showQuery);\n            DBObject fetchedDocument = dbCollection.findOne(query);\n\n            if (fetchedDocument != null)\n            {\n                List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n\n                EntityMetadata subEntityMetadata = null;\n                if (!subManagedType.isEmpty())\n                {\n                    for (AbstractManagedType subEntity : subManagedType)\n                    {\n                        String discColumn = subEntity.getDiscriminatorColumn();\n                        String disColValue = subEntity.getDiscriminatorValue();\n                        Object value = fetchedDocument.get(discColumn);\n                        if (value != null && value.toString().equals(disColValue))\n                        {\n                            subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                                    subEntity.getJavaType());\n                            break;\n                        }\n                    }\n\n                    enhancedEntity = instantiateEntity(subEntityMetadata.getEntityClazz(), enhancedEntity);\n                    relationValue = handler.getEntityFromDocument(subEntityMetadata.getEntityClazz(), enhancedEntity,\n                            subEntityMetadata, fetchedDocument, subEntityMetadata.getRelationNames(), relationValue,\n                            kunderaMetadata);\n                }\n                else\n                {\n                    enhancedEntity = instantiateEntity(entityClass, enhancedEntity);\n                    relationValue = handler.getEntityFromDocument(entityMetadata.getEntityClazz(), enhancedEntity,\n                            entityMetadata, fetchedDocument, relationNames, relationValue, kunderaMetadata);\n                }\n\n            }\n        }\n\n        if (relationValue != null && !relationValue.isEmpty())\n        {\n            EnhanceEntity entity = new EnhanceEntity(enhancedEntity, PropertyAccessorHelper.getId(enhancedEntity,\n                    entityMetadata), relationValue);\n            return entity;\n        }\n        else\n        {\n            return enhancedEntity;\n        }\n    }\n\n    /**\n     * Find GFS entity.\n     *\n     * @param entityMetadata\n     *            the entity metadata\n     * @param entityClass\n     *            the entity class\n     * @param key\n     *            the key\n     * @return the object\n     */\n    private Object findGFSEntity(EntityMetadata entityMetadata, Class entityClass, Object key)\n    {\n        GridFSDBFile outputFile = findGridFSDBFile(entityMetadata, key);\n        return outputFile != null ? handler.getEntityFromGFSDBFile(entityMetadata.getEntityClazz(),\n                instantiateEntity(entityClass, null), entityMetadata, outputFile, kunderaMetadata) : null;\n    }\n\n    /**\n     * Find GRIDFSDBFile.\n     *\n     * @param entityMetadata\n     *            the entity metadata\n     * @param key\n     *            the key\n     * @return the grid fsdb file\n     */\n    private GridFSDBFile findGridFSDBFile(EntityMetadata entityMetadata, Object key)\n    {\n        String id = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();\n        DBObject query = new BasicDBObject(\"metadata.\" + id, key);\n        KunderaGridFS gfs = new KunderaGridFS(mongoDb, entityMetadata.getTableName());\n        return gfs.findOne(query);\n    }\n\n    /**\n     * Instantiate entity.\n     *\n     * @param entityClass\n     *            the entity class\n     * @param entity\n     *            the entity\n     * @return the object\n     */\n    private Object instantiateEntity(Class entityClass, Object entity)\n    {\n        if (entity == null)\n        {\n            return KunderaCoreUtils.createNewInstance(entityClass);\n        }\n        return entity;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.Object[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n\n        log.debug(\"Fetching data from \" + entityMetadata.getTableName() + \" for Keys \" + keys);\n\n        DBCollection dbCollection = mongoDb.getCollection(entityMetadata.getTableName());\n\n        BasicDBObject query = new BasicDBObject();\n\n        query.put(\"_id\", new BasicDBObject(\"$in\", keys));\n\n        DBCursor cursor = dbCollection.find(query);\n        KunderaCoreUtils.printQuery(\"Find collection:\" + query, showQuery);\n        List entities = new ArrayList<E>();\n        while (cursor.hasNext())\n        {\n            DBObject fetchedDocument = cursor.next();\n\n            populateEntity(entityMetadata, entities, fetchedDocument);\n        }\n        return entities;\n    }\n\n    public <E> List<E> aggregate(EntityMetadata entityMetadata, BasicDBObject mongoQuery, BasicDBList lookup,\n            BasicDBObject aggregation, BasicDBObject orderBy, int maxResult) throws Exception\n    {\n        String collectionName = entityMetadata.getTableName();\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(entityMetadata.getEntityClazz());\n        boolean hasLob = managedType.hasLobAttribute();\n\n        List<DBObject> pipeline = new LinkedList<DBObject>();\n        addLookupAndMatchToPipeline(lookup, mongoQuery, pipeline);\n        if (aggregation != null)\n        {\n            pipeline.add(new BasicDBObject(\"$group\", aggregation));\n        }\n        if (orderBy != null && aggregation != null)\n        {\n            addSortToPipeline(orderBy, aggregation, hasLob, pipeline);\n        }\n        if (maxResult > 0)\n        {\n            pipeline.add(new BasicDBObject(\"$limit\", maxResult));\n        }\n\n        Iterable<DBObject> aggregationResults;\n\n        if (hasLob)\n        {\n            // KunderaGridFS gridFS = new KunderaGridFS(mongoDb,\n            // collectionName);\n            // AggregationOutput output = gridFS.aggregate(pipeline);\n            // aggregationResults = output.results();\n            throw new KunderaException(\"Aggregation not supported for MongoDB with GridFS.\");\n\n        }\n        else\n        {\n            AggregationOutput output = mongoDb.getCollection(collectionName).aggregate(pipeline);\n            aggregationResults = output.results();\n        }\n\n        return (List<E>) extractAggregationValues(aggregationResults, aggregation);\n    }\n\n    private void addLookupAndMatchToPipeline(BasicDBList lookup, BasicDBObject mongoQuery, List<DBObject> pipeline)\n    {\n        BasicDBObject matchBeforeLookup = new BasicDBObject();\n        BasicDBObject matchAfterLookup = new BasicDBObject();\n\n        for (String key : mongoQuery.keySet())\n        {\n            if (key.contains(\".\"))\n            {\n                matchAfterLookup.append(key, mongoQuery.get(key));\n            }\n            else\n            {\n                matchBeforeLookup.append(key, mongoQuery.get(key));\n            }\n        }\n\n        if (matchBeforeLookup.size() > 0)\n        {\n            pipeline.add(new BasicDBObject(\"$match\", matchBeforeLookup));\n        }\n        for (Object lookupItem : lookup)\n        {\n            pipeline.add((DBObject) lookupItem);\n        }\n        if (matchAfterLookup.size() > 0)\n        {\n            pipeline.add(new BasicDBObject(\"$match\", matchAfterLookup));\n        }\n    }\n\n    private void addSortToPipeline(BasicDBObject orderBy, BasicDBObject aggregation, boolean hasLob,\n            List<DBObject> pipeline)\n    {\n        BasicDBObject actual = new BasicDBObject();\n        for (String key : orderBy.keySet())\n        {\n            if (aggregation.containsField(key))\n            {\n                actual.put(key, orderBy.get(key));\n            }\n            else if (aggregation.containsField(\"_id\"))\n            {\n                if (((BasicDBObject) aggregation.get(\"_id\")).containsField(key))\n                {\n                    actual.put(\"_id\", orderBy.get(key));\n                }\n                else if (hasLob && key.startsWith(\"metadata.\"))\n                {\n                    // check the key without the \"metadata.\" prefix for GridFS\n                    if (((BasicDBObject) aggregation.get(\"_id\")).containsField(key.substring(9)))\n                    {\n                        actual.put(\"_id\", orderBy.get(key));\n                    }\n                }\n            }\n        }\n\n        if (actual.size() > 0)\n        {\n            pipeline.add(new BasicDBObject(\"$sort\", actual));\n        }\n    }\n\n    private List extractAggregationValues(Iterable<DBObject> documents, BasicDBObject aggregation)\n    {\n        List results = new LinkedList();\n\n        if (aggregation != null)\n        {\n            if (aggregation.containsField(\"_id\") && aggregation.get(\"_id\") == null)\n            {\n                aggregation.removeField(\"_id\");\n            }\n        }\n\n        for (DBObject document : documents)\n        {\n            if (document.containsField(\"_id\") && document.get(\"_id\") == null)\n            {\n                document.removeField(\"_id\");\n            }\n\n            extractAggregationValues(document, results, aggregation != null ? aggregation : (BasicDBObject) document);\n        }\n\n        return results;\n    }\n\n    private void extractAggregationValues(DBObject document, List results, DBObject keyMap)\n    {\n        if (document.keySet().size() == 1)\n        {\n            String key = document.keySet().iterator().next();\n            Object value = document.get(key);\n\n            // special case for count\n            if (key.equals(\"count\"))\n            {\n                value = Long.parseLong(value.toString());\n            }\n\n            if (value instanceof DBObject)\n            {\n                extractAggregationValues((DBObject) value, results, (DBObject) keyMap.get(key));\n            }\n            else\n            {\n                results.add(value);\n            }\n        }\n        else if (document.keySet().size() > 1)\n        {\n            List<Object> values = new ArrayList<Object>(document.keySet().size());\n            for (String key : keyMap.keySet())\n            {\n                Object value = document.get(key);\n\n                // special case for count\n                if (key.equals(\"count\"))\n                {\n                    value = Long.parseLong(value.toString());\n                }\n\n                if (value instanceof DBObject)\n                {\n                    extractAggregationValues((DBObject) value, values, (DBObject) keyMap.get(key));\n                }\n                else\n                {\n                    values.add(value);\n                }\n            }\n            results.add(values.toArray());\n        }\n    }\n\n    /**\n     * Loads columns from multiple rows restricting results to conditions stored\n     * in <code>filterClauseQueue</code>.\n     * \n     * @param <E>\n     *            the element type\n     * @param entityMetadata\n     *            the entity metadata\n     * @param mongoQuery\n     *            the mongo query\n     * @param relationNames\n     *            the relation names\n     * @param orderBy\n     *            the order by\n     * @param maxResult\n     *            the max result\n     * @param firstResult\n     *            the first result\n     * @param isCountQuery\n     *            the is count query\n     * @param keys\n     *            the keys\n     * @param results\n     *            the results\n     * @return the list\n     * @throws Exception\n     *             the exception\n     */\n    public <E> List<E> loadData(EntityMetadata entityMetadata, BasicDBObject mongoQuery, List<String> relationNames,\n            BasicDBObject orderBy, int maxResult, int firstResult, boolean isCountQuery, BasicDBObject keys,\n            String... results) throws Exception\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(entityMetadata.getEntityClazz());\n        boolean hasLob = managedType.hasLobAttribute();\n        return (List<E>) (!hasLob ? loadQueryData(entityMetadata, mongoQuery, orderBy, maxResult, firstResult,\n                isCountQuery, keys, results) : loadQueryDataGFS(entityMetadata, mongoQuery, orderBy, maxResult,\n                firstResult, isCountQuery));\n    }\n\n    /**\n     * Load query data gfs.\n     * \n     * @param <E>\n     *            the element type\n     * @param entityMetadata\n     *            the entity metadata\n     * @param mongoQuery\n     *            the mongo query\n     * @param orderBy\n     *            the order by\n     * @param maxResult\n     *            the max result\n     * @param firstResult\n     *            the first result\n     * @param isCountQuery\n     *            the is count query\n     * @return the list\n     */\n    private <E> List<E> loadQueryDataGFS(EntityMetadata entityMetadata, BasicDBObject mongoQuery,\n            BasicDBObject orderBy, int maxResult, int firstResult, boolean isCountQuery)\n    {\n        List<GridFSDBFile> gfsDBfiles = getGFSDBFiles(mongoQuery, orderBy, entityMetadata.getTableName(), maxResult,\n                firstResult);\n\n        if (isCountQuery)\n        {\n            return (List<E>) Collections.singletonList(gfsDBfiles.size());\n        }\n\n        List entities = new ArrayList<E>();\n        for (GridFSDBFile file : gfsDBfiles)\n        {\n            populateGFSEntity(entityMetadata, entities, file);\n        }\n        return entities;\n    }\n\n    /**\n     * Load query data.\n     * \n     * @param <E>\n     *            the element type\n     * @param entityMetadata\n     *            the entity metadata\n     * @param mongoQuery\n     *            the mongo query\n     * @param orderBy\n     *            the order by\n     * @param maxResult\n     *            the max result\n     * @param firstResult\n     *            the first result\n     * @param isCountQuery\n     *            the is count query\n     * @param keys\n     *            the keys\n     * @param results\n     *            the results\n     * @return the list\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    private <E> List<E> loadQueryData(EntityMetadata entityMetadata, BasicDBObject mongoQuery, BasicDBObject orderBy,\n            int maxResult, int firstResult, boolean isCountQuery, BasicDBObject keys, String... results)\n            throws InstantiationException, IllegalAccessException\n    {\n        String documentName = entityMetadata.getTableName();\n\n        List entities = new ArrayList<E>();\n\n        Object object = getDBCursorInstance(mongoQuery, orderBy, maxResult, firstResult, keys, documentName,\n                isCountQuery);\n\n        DBCursor cursor = null;\n\n        if (object instanceof Long)\n        {\n            List<Long> lst = new ArrayList<Long>();\n            lst.add((Long) object);\n            return (List<E>) lst;\n        }\n        else\n        {\n            cursor = (DBCursor) object;\n        }\n\n        if (results != null && results.length > 0)\n        {\n            DBCollection dbCollection = mongoDb.getCollection(documentName);\n            KunderaCoreUtils.printQuery(\"Find document: \" + mongoQuery, showQuery);\n            for (int i = 1; i < results.length; i++)\n            {\n                String result = results[i];\n\n                // If User wants search on a column within a particular super\n                // column,\n                // fetch that embedded object collection only\n                // otherwise retrieve whole entity\n                // TODO: improve code\n                if (result != null && result.indexOf(\".\") >= 0)\n                {\n                    // TODO i need to discuss with Amresh before modifying it.\n                    entities.addAll(handler.getEmbeddedObjectList(dbCollection, entityMetadata, documentName,\n                            mongoQuery, result, orderBy, maxResult, firstResult, keys, kunderaMetadata));\n                    return entities;\n                }\n            }\n        }\n        log.debug(\"Fetching data from \" + documentName + \" for Filter \" + mongoQuery.toString());\n\n        while (cursor.hasNext())\n        {\n            DBObject fetchedDocument = cursor.next();\n\n            populateEntity(entityMetadata, entities, fetchedDocument);\n        }\n        return entities;\n    }\n\n    /**\n     * Populate gfs entity.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entities\n     *            the entities\n     * @param gfsDBFile\n     *            the gfs db file\n     */\n    private void populateGFSEntity(EntityMetadata entityMetadata, List entities, GridFSDBFile gfsDBFile)\n    {\n        Object entity = instantiateEntity(entityMetadata.getEntityClazz(), null);\n        handler.getEntityFromGFSDBFile(entityMetadata.getEntityClazz(), entity, entityMetadata, gfsDBFile,\n                kunderaMetadata);\n        entities.add(entity);\n    }\n\n    /**\n     * Gets the DB cursor instance.\n     * \n     * @param mongoQuery\n     *            the mongo query\n     * @param orderBy\n     *            the order by\n     * @param maxResult\n     *            the max result\n     * @param firstResult\n     *            the first result\n     * @param keys\n     *            the keys\n     * @param documentName\n     *            the document name\n     * @param isCountQuery\n     *            the is count query\n     * @return the DB cursor instance\n     */\n    public Object getDBCursorInstance(BasicDBObject mongoQuery, BasicDBObject orderBy, int maxResult, int firstResult,\n            BasicDBObject keys, String documentName, boolean isCountQuery)\n    {\n        DBCollection dbCollection = mongoDb.getCollection(documentName);\n        DBCursor cursor = null;\n        if (isCountQuery)\n            return dbCollection.count(mongoQuery);\n        else\n            cursor = orderBy != null ? dbCollection.find(mongoQuery, keys).sort(orderBy).limit(maxResult)\n                    .skip(firstResult) : dbCollection.find(mongoQuery, keys).limit(maxResult).skip(firstResult);\n        return cursor;\n    }\n\n    /**\n     * Gets the GFSDB files.\n     * \n     * @param mongoQuery\n     *            the mongo query\n     * @param sort\n     *            the sort\n     * @param collectionName\n     *            the collection name\n     * @param maxResult\n     *            the max result\n     * @param firstResult\n     *            the first result\n     * @return the GFSDB files\n     */\n    private List<GridFSDBFile> getGFSDBFiles(BasicDBObject mongoQuery, BasicDBObject sort, String collectionName,\n            int maxResult, int firstResult)\n    {\n        KunderaGridFS gfs = new KunderaGridFS(mongoDb, collectionName);\n        return gfs.find(mongoQuery, sort, firstResult, maxResult);\n    }\n\n    /*\n     * (non-Javadoc) object\n     * \n     * @see com.impetus.kundera.client.Client#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    public void delete(Object entity, Object pKey)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(entityMetadata.getEntityClazz());\n\n        DBObject query = new BasicDBObject();\n\n        if (managedType.hasLobAttribute())\n        {\n            KunderaGridFS gfs = new KunderaGridFS(mongoDb, entityMetadata.getTableName());\n            String id = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();\n            query.put(\"metadata.\" + id, pKey);\n            gfs.remove(query);\n        }\n\n        else\n        {\n            if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n            {\n                MongoDBUtils.populateCompoundKey(query, entityMetadata, metaModel, pKey);\n            }\n            else\n            {\n                query.put(\"_id\", MongoDBUtils.populateValue(pKey, pKey.getClass()));\n            }\n            // For secondary tables.\n            List<String> secondaryTables = ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation())\n                    .getSecondaryTablesName();\n            secondaryTables.add(entityMetadata.getTableName());\n\n            for (String collectionName : secondaryTables)\n            {\n                KunderaCoreUtils.printQuery(\"Drop existing collection:\" + query, showQuery);\n                DBCollection dbCollection = mongoDb.getCollection(collectionName);\n                dbCollection.remove(query, getWriteConcern(), encoder);\n            }\n\n            getIndexManager().remove(entityMetadata, entity, pKey);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    @Override\n    public void close()\n    {\n        // TODO Once pool is implemented this code should not be there.\n        // Workaround for pool\n        this.indexManager.flush();\n        externalProperties = null;\n        clear();\n    }\n\n    /**\n     * Creates the index.\n     * \n     * @param collectionName\n     *            the collection name\n     * @param columnList\n     *            the column list\n     * @param order\n     *            the order\n     */\n    public void createIndex(String collectionName, List<String> columnList, int order)\n    {\n        DBCollection coll = mongoDb.getCollection(collectionName);\n\n        List<DBObject> indexes = coll.getIndexInfo(); // List of all current\n        // indexes on collection\n        Set<String> indexNames = new HashSet<String>(); // List of all current\n        // index names\n        for (DBObject index : indexes)\n        {\n            BasicDBObject obj = (BasicDBObject) index.get(\"key\");\n            Set<String> set = obj.keySet(); // Set containing index name which\n            // is key\n            indexNames.addAll(set);\n        }\n\n        // Create index if not already created\n        for (String columnName : columnList)\n        {\n            if (!indexNames.contains(columnName))\n            {\n                KunderaCoreUtils.printQuery(\"Create index on:\" + columnName, showQuery);\n                coll.createIndex(new BasicDBObject(columnName, order));\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> col)\n    {\n        throw new NotImplementedException(\"Not yet implemented\");\n    }\n\n    /**\n     * Method to find entity for given association name and association value.\n     * \n     * @param colName\n     *            the col name\n     * @param colValue\n     *            the col value\n     * @param entityClazz\n     *            the entity clazz\n     * @return the list\n     */\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n        // you got column name and column value.\n        DBCollection dbCollection = mongoDb.getCollection(m.getTableName());\n\n        BasicDBObject query = new BasicDBObject();\n\n        query.put(colName, MongoDBUtils.populateValue(colValue, colValue.getClass()));\n        KunderaCoreUtils.printQuery(\"Find by relation:\" + query, showQuery);\n        DBCursor cursor = dbCollection.find(query);\n        DBObject fetchedDocument = null;\n        List<Object> results = new ArrayList<Object>();\n        while (cursor.hasNext())\n        {\n            fetchedDocument = cursor.next();\n            populateEntity(m, results, fetchedDocument);\n        }\n\n        return results.isEmpty() ? null : results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.Object)\n     */\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n        DBCollection dbCollection = mongoDb.getCollection(tableName);\n        BasicDBObject query = new BasicDBObject();\n        query.put(columnName, columnValue);\n        KunderaCoreUtils.printQuery(\"Delete column:\" + query, showQuery);\n        dbCollection.remove(query, getWriteConcern(), encoder);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<MongoDBQuery> getQueryImplementor()\n    {\n        return MongoDBQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.metadata\n     * .model.EntityMetadata, java.lang.Object, java.lang.Object,\n     * java.util.List)\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(entityMetadata.getEntityClazz());\n\n        if (managedType.hasLobAttribute())\n        {\n            onPersistGFS(entity, id, entityMetadata, isUpdate);\n        }\n\n        else\n        {\n            Map<String, List<DBObject>> collections = new HashMap<String, List<DBObject>>();\n            collections = onPersist(collections, entity, id, entityMetadata, rlHolders, isUpdate);\n            onFlushCollection(collections);\n        }\n    }\n\n    /**\n     * Save GRID FS file.\n     * \n     * @param gfsInputFile\n     *            the gfs input file\n     * @param m\n     *            the m\n     */\n    private void saveGridFSFile(GridFSInputFile gfsInputFile, EntityMetadata m)\n    {\n        try\n        {\n            DBCollection coll = mongoDb.getCollection(m.getTableName() + MongoDBUtils.FILES);\n            createUniqueIndexGFS(coll, ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName());\n            gfsInputFile.save();\n            log.info(\"Input GridFS file: \" + gfsInputFile.getFilename() + \" is saved successfully in \"\n                    + m.getTableName() + MongoDBUtils.CHUNKS + \" and metadata in \" + m.getTableName()\n                    + MongoDBUtils.FILES);\n        }\n        catch (MongoException e)\n        {\n            log.error(\"Error in saving GridFS file in \" + m.getTableName() + MongoDBUtils.FILES + \" or \"\n                    + m.getTableName() + MongoDBUtils.CHUNKS + \" collections.\");\n            throw new KunderaException(\"Error in saving GridFS file in \" + m.getTableName() + MongoDBUtils.FILES\n                    + \" or \" + m.getTableName() + MongoDBUtils.CHUNKS + \" collections. Caused By: \", e);\n        }\n        try\n        {\n            gfsInputFile.validate();\n            log.info(\"Input GridFS file: \" + gfsInputFile.getFilename() + \" is validated.\");\n        }\n        catch (MongoException e)\n        {\n            log.error(\"Error in validating GridFS file in \" + m.getTableName() + MongoDBUtils.FILES + \" collection.\");\n            throw new KunderaException(\"Error in validating GridFS file in \" + m.getTableName() + MongoDBUtils.FILES\n                    + \" collection. Caused By: \", e);\n        }\n    }\n\n    /**\n     * On persist GFS.\n     * \n     * @param entity\n     *            the entity\n     * @param entityId\n     *            the entityId\n     * @param entityMetadata\n     *            the entity metadata\n     * @param isUpdate\n     *            the is update\n     */\n    private void onPersistGFS(Object entity, Object entityId, EntityMetadata entityMetadata, boolean isUpdate)\n    {\n        KunderaGridFS gfs = new KunderaGridFS(mongoDb, entityMetadata.getTableName());\n        if (!isUpdate)\n        {\n            GridFSInputFile gfsInputFile = handler.getGFSInputFileFromEntity(gfs, entityMetadata, entity,\n                    kunderaMetadata, isUpdate);\n            saveGridFSFile(gfsInputFile, entityMetadata);\n        }\n        else\n        {\n            Object val = handler.getLobFromGFSEntity(gfs, entityMetadata, entity, kunderaMetadata);\n            String md5 = MongoDBUtils.calculateMD5(val);\n            GridFSDBFile outputFile = findGridFSDBFile(entityMetadata, entityId);\n\n            // checking MD5 of the file to be updated with the file saved in DB\n            if (md5.equals(outputFile.getMD5()))\n            {\n                DBObject metadata = handler.getMetadataFromGFSEntity(gfs, entityMetadata, entity, kunderaMetadata);\n                outputFile.setMetaData(metadata);\n                outputFile.save();\n            }\n            else\n            {\n                // GFSInput file is created corresponding to the entity to be\n                // merged with a new ObjectID()\n                GridFSInputFile gfsInputFile = handler.getGFSInputFileFromEntity(gfs, entityMetadata, entity,\n                        kunderaMetadata, isUpdate);\n                ObjectId updatedId = (ObjectId) gfsInputFile.getId();\n                DBObject metadata = gfsInputFile.getMetaData();\n\n                // updated file is saved in DB\n                saveGridFSFile(gfsInputFile, entityMetadata);\n\n                // last version of file is deleted\n                DBObject query = new BasicDBObject(\"_id\", outputFile.getId());\n                gfs.remove(query);\n\n                // newly added file is found using its _id\n                outputFile = gfs.findOne(updatedId);\n\n                // Id of entity (which is saved in metadata) is updated to its\n                // actual Id\n                metadata.put(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName(), entityId);\n                outputFile.setMetaData(metadata);\n\n                // output file is updated\n                outputFile.save();\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.api.Batcher#addBatch(com.impetus.kundera\n     * .graph.Node)\n     */\n    public void addBatch(Node node)\n    {\n        if (node != null)\n        {\n            nodes.add(node);\n        }\n        onBatchLimit();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#getBatchSize()\n     */\n    @Override\n    public int getBatchSize()\n    {\n        return batchSize;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#clear()\n     */\n    @Override\n    public void clear()\n    {\n        if (nodes != null)\n        {\n            nodes.clear();\n            nodes = new ArrayList<Node>();\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#executeBatch()\n     */\n    @Override\n    public int executeBatch()\n    {\n        Map<String, BulkWriteOperation> bulkWriteOperationMap = new HashMap<String, BulkWriteOperation>();\n        int size = 0;\n        for (Node node : nodes)\n        {\n            if (node.isDirty())\n            {\n                node.handlePreEvent();\n                // delete can not be executed in batch\n                if (node.isInState(RemovedState.class))\n                {\n                    delete(node.getData(), node.getEntityId());\n                }\n                else\n                {\n                    List<RelationHolder> relationHolders = getRelationHolders(node);\n                    EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                            node.getDataClass());\n                    Map<String, DBObject> documents = handler.getDocumentFromEntity(metadata, node.getData(),\n                            relationHolders, kunderaMetadata);\n                    for (String tableName : documents.keySet())\n                    {\n                        if (!bulkWriteOperationMap.containsKey(tableName))\n                        {\n                            DBCollection collection = mongoDb.getCollection(tableName);\n                            BulkWriteOperation builder = null;\n                            if (isOrderedBulkOperation())\n                            {\n                                builder = collection.initializeOrderedBulkOperation();\n                            }\n                            else\n                            {\n                                builder = collection.initializeUnorderedBulkOperation();\n                            }\n                            bulkWriteOperationMap.put(tableName, builder);\n                        }\n\n                        if (!node.isUpdate())\n                        {\n                            bulkWriteOperationMap.get(tableName).insert(documents.get(tableName));\n                        }\n\n                        else\n                        {\n                            bulkWriteOperationMap.get(tableName).find(new BasicDBObject(\"_id\", node.getEntityId()))\n                                    .upsert().replaceOne(documents.get(tableName));\n                        }\n                        size++;\n                    }\n                    indexNode(node, metadata);\n                }\n                node.handlePostEvent();\n            }\n        }\n        onFlushBatch(bulkWriteOperationMap);\n        return size;\n    }\n\n    /**\n     * On flush batch.\n     * \n     * @param bulkWriteOperationMap\n     *            the bulk write operation map\n     */\n    private void onFlushBatch(Map<String, BulkWriteOperation> bulkWriteOperationMap)\n    {\n        if (!bulkWriteOperationMap.isEmpty())\n        {\n            for (BulkWriteOperation builder : bulkWriteOperationMap.values())\n            {\n                try\n                {\n                    builder.execute(getWriteConcern());\n                }\n                catch (BulkWriteException bwex)\n                {\n                    log.error(\"Batch insertion is not performed due to error in write command. Caused By: \", bwex);\n                    throw new KunderaException(\n                            \"Batch insertion is not performed due to error in write command. Caused By: \", bwex);\n                }\n                catch (MongoException mex)\n                {\n                    log.error(\"Batch insertion is not performed. Caused By: \", mex);\n                    throw new KunderaException(\"Batch insertion is not performed. Caused By: \", mex);\n                }\n            }\n        }\n    }\n\n    /**\n     * On collections flush.\n     * \n     * @param collections\n     *            collection containing records to be inserted in mongo db.\n     */\n    private void onFlushCollection(Map<String, List<DBObject>> collections)\n    {\n        for (String tableName : collections.keySet())\n        {\n            DBCollection dbCollection = mongoDb.getCollection(tableName);\n            KunderaCoreUtils.printQuery(\"Persist collection:\" + tableName, showQuery);\n            try\n            {\n                dbCollection.insert(collections.get(tableName).toArray(new DBObject[0]), getWriteConcern(), encoder);\n            }\n            catch (MongoException ex)\n            {\n                throw new KunderaException(\"document is not inserted in \" + dbCollection.getFullName()\n                        + \" collection. Caused By:\", ex);\n            }\n        }\n\n    }\n\n    /**\n     * Executes on list of entities to be persisted.\n     * \n     * @param collections\n     *            collection containing list of db objects.\n     * @param entity\n     *            entity in question.\n     * @param id\n     *            entity id.\n     * @param metadata\n     *            entity metadata\n     * @param relationHolders\n     *            relation holders.\n     * @param isUpdate\n     *            if it is an update\n     * @return collection of DB objects.\n     */\n    private Map<String, List<DBObject>> onPersist(Map<String, List<DBObject>> collections, Object entity, Object id,\n            EntityMetadata metadata, List<RelationHolder> relationHolders, boolean isUpdate)\n    {\n        persistenceUnit = metadata.getPersistenceUnit();\n        Map<String, DBObject> documents = handler.getDocumentFromEntity(metadata, entity, relationHolders,\n                kunderaMetadata);\n\n        if (isUpdate)\n        {\n            for (String documentName : documents.keySet())\n            {\n                BasicDBObject query = new BasicDBObject();\n\n                MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                        metadata.getPersistenceUnit());\n\n                if (metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType()))\n                {\n                    MongoDBUtils.populateCompoundKey(query, metadata, metaModel, id);\n                }\n                else\n                {\n                    query.put(\"_id\", MongoDBUtils.populateValue(id, id.getClass()));\n                }\n                DBCollection dbCollection = mongoDb.getCollection(documentName);\n                KunderaCoreUtils.printQuery(\"Persist collection:\" + documentName, showQuery);\n\n                dbCollection.save(documents.get(documentName), getWriteConcern());\n            }\n        }\n        else\n        {\n            for (String documentName : documents.keySet())\n            {\n                // a db collection can have multiple records..\n                // and we can have a collection of records as well.\n                List<DBObject> dbStatements = null;\n                if (collections.containsKey(documentName))\n                {\n                    dbStatements = collections.get(documentName);\n                    dbStatements.add(documents.get(documentName));\n                }\n                else\n                {\n                    dbStatements = new ArrayList<DBObject>();\n                    dbStatements.add(documents.get(documentName));\n                    collections.put(documentName, dbStatements);\n                }\n            }\n        }\n        return collections;\n    }\n\n    /**\n     * Check on batch limit.\n     */\n    private void onBatchLimit()\n    {\n        if (batchSize > 0 && batchSize == nodes.size())\n        {\n            executeBatch();\n            nodes.clear();\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientPropertiesSetter#populateClientProperties\n     * (com.impetus.kundera.client.Client, java.util.Map)\n     */\n    @Override\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        new MongoDBClientProperties().populateClientProperties(client, properties);\n    }\n\n    /**\n     * Sets the mongo db.\n     * \n     * @param mongoDb\n     *            the mongoDb to set\n     */\n    public void setMongoDb(DB mongoDb)\n    {\n        this.mongoDb = mongoDb;\n    }\n\n    /**\n     * Sets the handler.\n     * \n     * @param handler\n     *            the handler to set\n     */\n    public void setHandler(DefaultMongoDBDataHandler handler)\n    {\n        this.handler = handler;\n    }\n\n    /**\n     * Sets the nodes.\n     * \n     * @param nodes\n     *            the nodes to set\n     */\n    public void setNodes(List<Node> nodes)\n    {\n        this.nodes = nodes;\n    }\n\n    /**\n     * Sets the write concern.\n     * \n     * @param writeConcern\n     *            the writeConcern to set\n     */\n    public void setWriteConcern(WriteConcern writeConcern)\n    {\n        this.writeConcern = writeConcern;\n    }\n\n    /**\n     * Sets the encoder.\n     * \n     * @param encoder\n     *            the encoder to set\n     */\n    public void setEncoder(DBEncoder encoder)\n    {\n        this.encoder = encoder;\n    }\n\n    /**\n     * Gets the encoder.\n     * \n     * @return the encoder\n     */\n    public DBEncoder getEncoder()\n    {\n        return encoder;\n    }\n\n    /**\n     * Gets the write concern.\n     * \n     * @return the writeConcern\n     */\n    public WriteConcern getWriteConcern()\n    {\n        if (writeConcern == null)\n        {\n            return mongoDb.getWriteConcern();\n        }\n        return writeConcern;\n    }\n\n    /**\n     * Sets the batch size.\n     * \n     * @param batchSize\n     *            the batchSize to set\n     */\n    public void setBatchSize(int batchSize)\n    {\n        this.batchSize = batchSize;\n    }\n\n    /**\n     * Populate batch size.\n     * \n     * @param persistenceUnit\n     *            the persistence unit\n     * @param puProperties\n     *            the pu properties\n     */\n    private void populateBatchSize(String persistenceUnit, Map<String, Object> puProperties)\n    {\n        String batch_Size = puProperties != null ? (String) puProperties.get(PersistenceProperties.KUNDERA_BATCH_SIZE)\n                : null;\n        if (batch_Size != null)\n        {\n            batchSize = Integer.valueOf(batch_Size);\n            if (batchSize == 0)\n            {\n                throw new IllegalArgumentException(\"kundera.batch.size property must be numeric and > 0\");\n            }\n        }\n        else\n        {\n            PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\n                    persistenceUnit);\n            batchSize = puMetadata.getBatchSize();\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        return (Generator) KunderaCoreUtils.createNewInstance(MongoDBIdGenerator.class);\n    }\n\n    /**\n     * Method to execute mongo jscripts.\n     * \n     * @param script\n     *            jscript in string format\n     * \n     * @return result object.\n     */\n    @Override\n    public Object executeScript(String script)\n    {\n        Object result = mongoDb.eval(script);\n        KunderaCoreUtils.printQuery(\"Execute mongo jscripts:\" + script, showQuery);\n        return result;\n    }\n\n    /**\n     * Execute query.\n     * \n     * @param jsonClause\n     *            the json clause\n     * @param entityMetadata\n     *            the entity metadata\n     * @return the list\n     */\n    public List executeQuery(String jsonClause, EntityMetadata entityMetadata)\n    {\n        List entities = new ArrayList();\n        try\n        {\n            DBCursor cursor = parseAndScroll(jsonClause, entityMetadata.getTableName());\n\n            while (cursor.hasNext())\n            {\n                DBObject fetchedDocument = cursor.next();\n\n                populateEntity(entityMetadata, entities, fetchedDocument);\n            }\n            return entities;\n\n        }\n        catch (JSONParseException jex)\n        {\n            entities = executeNativeQuery(jsonClause, entityMetadata);\n            List result = new ArrayList();\n            if (entities.size() > 0 && (entities.get(0) instanceof EnhanceEntity))\n            {\n                for (Object obj : entities)\n                {\n                    result.add(((EnhanceEntity) obj).getEntity());\n                }\n                return result;\n            }\n            return entities;\n        }\n    }\n\n    /**\n     * Execute native query.\n     * \n     * @param jsonClause\n     *            the json clause\n     * @param entityMetadata\n     *            the entity metadata\n     * @return the list\n     */\n    public List executeNativeQuery(String jsonClause, EntityMetadata entityMetadata)\n    {\n        List entities = new ArrayList();\n        String[] tempArray = jsonClause.split(\"\\\\.\");\n        String tempClause = tempArray[tempArray.length - 1];\n\n        if (tempClause.contains(\"findOne(\") || tempClause.contains(\"findAndModify(\"))\n        {\n            DBObject obj = (BasicDBObject) executeScript(jsonClause);\n            populateEntity(entityMetadata, entities, obj);\n            return entities;\n\n        }\n        else if (tempClause.contains(\"find(\") || jsonClause.contains(\"aggregate(\"))\n        {\n            jsonClause = jsonClause.concat(\".toArray()\");\n            BasicDBList list = (BasicDBList) executeScript(jsonClause);\n            for (Object obj : list)\n            {\n                populateEntity(entityMetadata, entities, (DBObject) obj);\n            }\n            return entities;\n\n        }\n        else if (tempClause.contains(\"count(\") || tempClause.contains(\"dataSize(\")\n                || tempClause.contains(\"storageSize(\") || tempClause.contains(\"totalIndexSize(\")\n                || tempClause.contains(\"totalSize(\"))\n        {\n            Long count = ((Double) executeScript(jsonClause)).longValue();\n            entities.add(count);\n            return entities;\n\n        }\n        else if (tempClause.contains(\"distinct(\"))\n        {\n            BasicDBList list = (BasicDBList) executeScript(jsonClause);\n            for (Object obj : list)\n            {\n                entities.add(obj);\n            }\n            return entities;\n\n        }\n        else if (jsonClause.contains(\"mapReduce(\"))\n        {\n            final MapReduceCommand command = parseMapReduceCommand(jsonClause);\n            final MapReduceOutput output = mongoDb.getCollection(command.getInput()).mapReduce(command);\n\n            final BasicDBList list = new BasicDBList();\n            for (final DBObject item : output.results())\n            {\n                list.add(item);\n            }\n            return list;\n        }\n        else\n        {\n            BasicDBList list = (BasicDBList) executeScript(jsonClause);\n            for (Object obj : list)\n            {\n                entities.add(obj);\n            }\n            return entities;\n        }\n    }\n\n    /**\n     * Parses the map reduce command.\n     * \n     * @param jsonClause\n     *            the json clause\n     * @return the map reduce command\n     */\n    private MapReduceCommand parseMapReduceCommand(String jsonClause)\n    {\n        String collectionName = jsonClause.replaceFirst(\"(?ms).*?\\\\.\\\\s*(.+?)\\\\s*\\\\.\\\\s*mapReduce\\\\s*\\\\(.*\", \"$1\");\n        if (collectionName.contains(\"getCollection\"))\n        {\n            collectionName = collectionName\n                    .replaceFirst(\".*getCollection\\\\s*\\\\(\\\\s*(['\\\"])([^'\\\"]+)\\\\1\\\\s*\\\\).*\", \"$2\");\n        }\n\n        DBCollection collection = mongoDb.getCollection(collectionName);\n\n        String body = jsonClause.replaceFirst(\"^(?ms).*?mapReduce\\\\s*\\\\(\\\\s*(.*)\\\\s*\\\\)\\\\s*;?\\\\s*$\", \"$1\");\n        String mapFunction = findCommaSeparatedArgument(body, 0).trim();\n        String reduceFunction = findCommaSeparatedArgument(body, 1).trim();\n\n        String query = findCommaSeparatedArgument(body, 2).trim();\n        DBObject parameters = (DBObject) JSON.parse(query);\n        DBObject mongoQuery;\n        if (parameters.containsField(\"query\"))\n        {\n            mongoQuery = (DBObject) parameters.get(\"query\");\n        }\n        else\n        {\n            mongoQuery = new BasicDBObject();\n        }\n\n        return new MapReduceCommand(collection, mapFunction, reduceFunction, null, MapReduceCommand.OutputType.INLINE,\n                mongoQuery);\n    }\n\n    /**\n     * Find comma separated argument.\n     * \n     * @param functionBody\n     *            the function body\n     * @param index\n     *            the index\n     * @return the string\n     */\n    private String findCommaSeparatedArgument(String functionBody, int index)\n    {\n        int start = 0;\n        int found = -1;\n        int brackets = 0;\n        int pos = 0;\n        int length = functionBody.length();\n\n        while (found < index && pos < length)\n        {\n            char ch = functionBody.charAt(pos);\n            switch (ch)\n            {\n            case ',':\n                if (brackets == 0)\n                {\n                    found++;\n\n                    if (found < index)\n                    {\n                        start = pos + 1;\n                    }\n                }\n                break;\n            case '(':\n            case '[':\n            case '{':\n                brackets++;\n                break;\n            case ')':\n            case ']':\n            case '}':\n                brackets--;\n                break;\n            }\n\n            pos++;\n        }\n\n        if (found == index)\n        {\n            return functionBody.substring(start, pos - 1);\n        }\n        else if (pos == length)\n        {\n            return functionBody.substring(start);\n        }\n        else\n        {\n            return \"\";\n        }\n    }\n\n    /**\n     * Parses the and scroll.\n     * \n     * @param jsonClause\n     *            the json clause\n     * @param collectionName\n     *            the collection name\n     * @return the DB cursor\n     * @throws JSONParseException\n     *             the JSON parse exception\n     */\n    private DBCursor parseAndScroll(String jsonClause, String collectionName) throws JSONParseException\n    {\n        BasicDBObject clause = (BasicDBObject) JSON.parse(jsonClause);\n        DBCursor cursor = mongoDb.getCollection(collectionName).find(clause);\n        return cursor;\n    }\n\n    /**\n     * Populate entity.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entities\n     *            the entities\n     * @param fetchedDocument\n     *            the fetched document\n     */\n    private void populateEntity(EntityMetadata entityMetadata, List entities, DBObject fetchedDocument)\n    {\n\n        // handler.getEntityFromGFSDBFile(entityClazz, entity, m, outputFile,\n        // kunderaMetadata)\n        Map<String, Object> relationValue = null;\n        if (fetchedDocument != null)\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    entityMetadata.getPersistenceUnit());\n\n            EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n\n            List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n\n            EntityMetadata subEntityMetadata = null;\n            Object enhancedEntity = null;\n            if (!subManagedType.isEmpty())\n            {\n                for (AbstractManagedType subEntity : subManagedType)\n                {\n                    String discColumn = subEntity.getDiscriminatorColumn();\n                    String disColValue = subEntity.getDiscriminatorValue();\n                    Object value = fetchedDocument.get(discColumn);\n                    if (value != null && value.toString().equals(disColValue))\n                    {\n                        subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                                subEntity.getJavaType());\n                        break;\n                    }\n                }\n                enhancedEntity = instantiateEntity(subEntityMetadata.getEntityClazz(), enhancedEntity);\n                relationValue = handler.getEntityFromDocument(subEntityMetadata.getEntityClazz(), enhancedEntity,\n                        subEntityMetadata, fetchedDocument, subEntityMetadata.getRelationNames(), relationValue,\n                        kunderaMetadata);\n\n            }\n            else\n            {\n                enhancedEntity = instantiateEntity(entityMetadata.getEntityClazz(), enhancedEntity);\n                relationValue = handler.getEntityFromDocument(entityMetadata.getEntityClazz(), enhancedEntity,\n                        entityMetadata, fetchedDocument, entityMetadata.getRelationNames(), relationValue,\n                        kunderaMetadata);\n            }\n\n            if (relationValue != null && !relationValue.isEmpty())\n            {\n                enhancedEntity = new EnhanceEntity(enhancedEntity, PropertyAccessorHelper.getId(enhancedEntity,\n                        entityMetadata), relationValue);\n            }\n\n            if (enhancedEntity != null)\n            {\n                entities.add(enhancedEntity);\n            }\n        }\n    }\n\n    /**\n     * Handle update functions.\n     * \n     * @param query\n     *            the query\n     * @param update\n     *            the update\n     * @param collName\n     *            the coll name\n     * @return the int\n     */\n    public int handleUpdateFunctions(BasicDBObject query, BasicDBObject update, String collName)\n    {\n        DBCollection collection = mongoDb.getCollection(collName);\n        KunderaCoreUtils.printQuery(\"Update collection:\" + query, showQuery);\n        WriteResult result = null;\n        try\n        {\n            result = collection.update(query, update);\n        }\n        catch (MongoException ex)\n        {\n            return -1;\n        }\n        if (result.getN() <= 0)\n            return -1;\n        return result.getN();\n    }\n\n    /**\n     * Creates the unique index gfs.\n     * \n     * @param coll\n     *            the coll\n     * @param id\n     *            the id\n     */\n    private void createUniqueIndexGFS(DBCollection coll, String id)\n    {\n        try\n        {\n            coll.createIndex(new BasicDBObject(\"metadata.\" + id, 1), new BasicDBObject(\"unique\", true));\n        }\n        catch (MongoException ex)\n        {\n            throw new KunderaException(\"Error in creating unique indexes in \" + coll.getFullName() + \" collection on \"\n                    + id + \" field\");\n        }\n    }\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClientFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.net.UnknownHostException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport javax.net.SocketFactory;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.mongodb.config.MongoDBPropertyReader;\nimport com.impetus.client.mongodb.config.MongoDBPropertyReader.MongoDBSchemaMetadata;\nimport com.impetus.client.mongodb.schemamanager.MongoDBSchemaManager;\nimport com.impetus.client.mongodb.utils.MongoDBUtils;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection.Server;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.loader.ClientLoaderException;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.mongodb.DB;\nimport com.mongodb.DBDecoderFactory;\nimport com.mongodb.DBEncoderFactory;\nimport com.mongodb.MongoClient;\nimport com.mongodb.MongoClientOptions;\nimport com.mongodb.MongoCredential;\nimport com.mongodb.MongoException;\nimport com.mongodb.ServerAddress;\nimport com.mongodb.WriteConcern;\n\n/**\n * A factory for creating MongoDBClient objects.\n * \n * @author Devender Yadav\n */\npublic class MongoDBClientFactory extends GenericClientFactory\n{\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(MongoDBClientFactory.class);\n\n    /** The mongo db. */\n    private DB mongoDB;\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initialize(java.util.Map)\n     */\n    @Override\n    public void initialize(Map<String, Object> externalProperty)\n    {\n        reader = new MongoEntityReader(kunderaMetadata);\n        initializePropertyReader();\n        setExternalProperties(externalProperty);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#createPoolOrConnection()\n     */\n    @Override\n    protected Object createPoolOrConnection()\n    {\n        mongoDB = getConnection();\n        return mongoDB;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#instantiateClient(java\n     * .lang.String)\n     */\n    @Override\n    protected Client instantiateClient(String persistenceUnit)\n    {\n        return new MongoDBClient(mongoDB, indexManager, reader, persistenceUnit, externalProperties, clientMetadata,\n                kunderaMetadata);\n    }\n\n    /**\n     * Gets the connection.\n     * \n     * @return the connection\n     */\n    private DB getConnection()\n    {\n\n        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(\n                getPersistenceUnit());\n\n        Properties props = puMetadata.getProperties();\n        String contactNode = null;\n        String defaultPort = null;\n        String keyspace = null;\n        String poolSize = null;\n        if (externalProperties != null)\n        {\n            contactNode = (String) externalProperties.get(PersistenceProperties.KUNDERA_NODES);\n            defaultPort = (String) externalProperties.get(PersistenceProperties.KUNDERA_PORT);\n            keyspace = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);\n            poolSize = (String) externalProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE);\n        }\n        if (contactNode == null)\n        {\n            contactNode = (String) props.get(PersistenceProperties.KUNDERA_NODES);\n        }\n        if (defaultPort == null)\n        {\n            defaultPort = (String) props.get(PersistenceProperties.KUNDERA_PORT);\n        }\n        if (keyspace == null)\n        {\n            keyspace = (String) props.get(PersistenceProperties.KUNDERA_KEYSPACE);\n        }\n        if (poolSize == null)\n        {\n            poolSize = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE);\n        }\n\n        onValidation(contactNode, defaultPort);\n\n        List<ServerAddress> addrs = new ArrayList<>();\n\n        MongoClient mongo = null;\n        try\n        {\n            mongo = onSetMongoServerProperties(contactNode, defaultPort, poolSize, addrs,\n                    MongoDBUtils.fetchCredentials(props, externalProperties));\n\n            logger.info(\"Connected to mongodb at \" + contactNode + \" on port \" + defaultPort);\n        }\n        catch (NumberFormatException e)\n        {\n            logger.error(\"Invalid format for MONGODB port, Unale to connect!\" + \"; Caused by:\" + e.getMessage());\n            throw new ClientLoaderException(e);\n        }\n        catch (MongoException e)\n        {\n            logger.error(\"Unable to connect to MONGODB; Caused by:\" + e.getMessage());\n            throw new ClientLoaderException(e);\n        }\n        return mongo.getDB(keyspace);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#onValidation(java.lang\n     * .String, java.lang.String)\n     */\n    @Override\n    protected void onValidation(final String contactNode, final String defaultPort)\n    {\n        if (contactNode != null)\n        {\n            // allow configuration as comma-separated list of host:port\n            // addresses without the default port\n            boolean allAddressesHaveHostAndPort = true;\n\n            for (String node : contactNode.split(Constants.COMMA))\n            {\n                if (StringUtils.countMatches(node, Constants.COLON) == 1)\n                {\n                    // node is given with hostname and port\n                    // count == 1 is to exclude IPv6 addresses\n                    if (StringUtils.isNumeric(node.split(Constants.COLON)[1]))\n                    {\n                        continue;\n                    }\n                }\n\n                allAddressesHaveHostAndPort = false;\n                break;\n            }\n\n            if (allAddressesHaveHostAndPort)\n            {\n                return;\n            }\n        }\n\n        // fall back to the generic validation which requires the default port\n        // to be set\n        super.onValidation(contactNode, defaultPort);\n    }\n\n    /**\n     * On set mongo server properties.\n     * \n     * @param contactNode\n     *            the contact node\n     * @param defaultPort\n     *            the default port\n     * @param poolSize\n     *            the pool size\n     * @param addrs\n     *            the addrs\n     * @return the mongo client\n     * @throws UnknownHostException\n     *             the unknown host exception\n     */\n    private MongoClient onSetMongoServerProperties(String contactNode, String defaultPort, String poolSize,\n            List<ServerAddress> addrs, List<MongoCredential> credentials)\n    {\n        MongoClientOptions mo;\n        MongoDBSchemaMetadata metadata = MongoDBPropertyReader.msmd;\n        ClientProperties cp = metadata != null ? metadata.getClientProperties() : null;\n        Properties propsFromCp = null;\n        if (cp != null)\n        {\n            DataStore dataStore = metadata != null ? metadata.getDataStore() : null;\n            List<Server> servers = dataStore != null && dataStore.getConnection() != null ? dataStore.getConnection()\n                    .getServers() : null;\n            if (servers != null && !servers.isEmpty())\n            {\n                for (Server server : servers)\n                {\n                    addrs.add(new ServerAddress(server.getHost().trim(), Integer.parseInt(server.getPort().trim())));\n                }\n            }\n\n            propsFromCp = dataStore != null && dataStore.getConnection() != null ? dataStore.getConnection()\n                    .getProperties() : null;\n        }\n        else\n        {\n            for (String node : contactNode.split(Constants.COMMA))\n            {\n                if (StringUtils.countMatches(node, Constants.COLON) == 1)\n                {\n                    // node is given with hostname and port\n                    // count == 1 is to exclude IPv6 addresses\n                    String host = node.split(\":\")[0];\n                    int port = Integer.parseInt(node.split(Constants.COLON)[1]);\n\n                    addrs.add(new ServerAddress(host.trim(), port));\n                }\n                else\n                {\n                    addrs.add(new ServerAddress(node.trim(), Integer.parseInt(defaultPort.trim())));\n                }\n            }\n        }\n\n        MongoClientOptions.Builder b = new PopulateMongoOptions(propsFromCp, externalProperties).prepareBuilder();\n        mo = b.build();\n\n        if (mo.getConnectionsPerHost() <= 0 && !StringUtils.isEmpty(poolSize))\n        {\n            mo = b.connectionsPerHost(Integer.parseInt(poolSize)).build();\n        }\n\n        return new MongoClient(addrs, credentials, mo);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.GenericClientFactory#isThreadSafe()\n     */\n    @Override\n    public boolean isThreadSafe()\n    {\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.ClientLifeCycleManager#destroy()\n     */\n    @Override\n    public void destroy()\n    {\n        indexManager.close();\n        if (schemaManager != null)\n        {\n            schemaManager.dropSchema();\n        }\n        if (mongoDB != null)\n        {\n            logger.info(\"Closing connection to mongodb.\");\n            mongoDB.getMongo().close();\n            logger.info(\"Closed connection to mongodb.\");\n        }\n        else\n        {\n            logger.warn(\"Can't close connection to MONGODB, it was already disconnected\");\n        }\n        externalProperties = null;\n        schemaManager = null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.ClientFactory#getSchemaManager(java.util.Map)\n     */\n    @Override\n    public SchemaManager getSchemaManager(Map<String, Object> externalProperty)\n    {\n        if (schemaManager == null)\n        {\n            initializePropertyReader();\n            setExternalProperties(externalProperty);\n            schemaManager = new MongoDBSchemaManager(MongoDBClientFactory.class.getName(), externalProperty,\n                    kunderaMetadata);\n        }\n        return schemaManager;\n    }\n\n    /**\n     * Initialize property reader.\n     */\n    private void initializePropertyReader()\n    {\n        if (propertyReader == null)\n        {\n            propertyReader = new MongoDBPropertyReader(externalProperties, kunderaMetadata.getApplicationMetadata()\n                    .getPersistenceUnitMetadata(getPersistenceUnit()));\n            propertyReader.read(getPersistenceUnit());\n        }\n    }\n\n    /**\n     * The Class PopulateMongoOptions.\n     */\n    public static class PopulateMongoOptions\n    {\n\n        /** The Constant INSTANCE_CREATION_EXCEPTION. */\n        private static final String INSTANCE_CREATION_EXCEPTION = \"Cannot create instace from property\";\n\n        /** The logger. */\n        private static Logger logger = LoggerFactory.getLogger(PopulateMongoOptions.class);\n\n        /** The client properties. */\n        private final Properties clientProperties;\n\n        /** The external properties. */\n        private final Map<String, ?> externalProperties;\n\n        /**\n         * Constructor.\n         * \n         * @param clientProperties\n         *            the properties from the 'kundera.client.property' file\n         * @param externalProperties\n         *            the external properties of the client factory\n         */\n        public PopulateMongoOptions(final Properties clientProperties, final Map<String, ?> externalProperties)\n        {\n            this.clientProperties = clientProperties;\n            this.externalProperties = externalProperties;\n        }\n\n        /**\n         * Prepare a mongo options builder.\n         * \n         * @return the mongo client options. builder\n         */\n        public MongoClientOptions.Builder prepareBuilder()\n        {\n            MongoClientOptions.Builder builder = MongoClientOptions.builder();\n\n            try\n            {\n                /*\n                 * if value of SAFE is provided in client properties. Then it is\n                 * given preference over other parameters values like W,\n                 * W_TIME_OUT, FSYNC, J\n                 * \n                 * So, whether choose simply write concern SAFE or not. Or you\n                 * can put values like W, W_TIME_OUT\n                 */\n                int w = getProperty(MongoDBConstants.W, 1, int.class);\n                int wTimeOut = getProperty(MongoDBConstants.W_TIME_OUT, 0, int.class);\n\n                boolean j = getProperty(MongoDBConstants.J, false, boolean.class);\n\n                boolean fsync = getProperty(MongoDBConstants.FSYNC, false, boolean.class);\n\n                if (hasProperty(MongoDBConstants.SAFE))\n                {\n                    if (getProperty(MongoDBConstants.SAFE, false, boolean.class))\n                    {\n                        builder.writeConcern(WriteConcern.SAFE);\n                    }\n                    else\n                    {\n                        builder.writeConcern(WriteConcern.NORMAL);\n                    }\n                }\n                else\n                {\n                    builder.writeConcern(new WriteConcern(w, wTimeOut, fsync, j));\n                }\n\n                if (hasProperty(MongoDBConstants.DB_DECODER_FACTORY))\n                {\n                    builder.dbDecoderFactory(getProperty(MongoDBConstants.DB_DECODER_FACTORY, DBDecoderFactory.class));\n                }\n                if (hasProperty(MongoDBConstants.DB_ENCODER_FACTORY))\n                {\n                    builder.dbEncoderFactory(getProperty(MongoDBConstants.DB_ENCODER_FACTORY, DBEncoderFactory.class));\n                }\n                if (hasProperty(MongoDBConstants.SOCKET_FACTORY))\n                {\n                    builder.socketFactory(getProperty(MongoDBConstants.SOCKET_FACTORY, SocketFactory.class));\n                }\n                if (hasProperty(MongoDBConstants.CONNECTION_PER_HOST))\n                {\n                    builder.connectionsPerHost(getProperty(MongoDBConstants.CONNECTION_PER_HOST, int.class));\n                }\n                if (hasProperty(MongoDBConstants.CONNECT_TIME_OUT))\n                {\n                    builder.connectTimeout(getProperty(MongoDBConstants.CONNECT_TIME_OUT, int.class));\n                }\n                if (hasProperty(MongoDBConstants.MAX_WAIT_TIME))\n                {\n                    builder.maxWaitTime(getProperty(MongoDBConstants.MAX_WAIT_TIME, int.class));\n                }\n                if (hasProperty(MongoDBConstants.TABCM))\n                {\n                    builder.threadsAllowedToBlockForConnectionMultiplier(getProperty(MongoDBConstants.TABCM, int.class));\n                }\n                if (hasProperty(MongoDBConstants.REPLICA_SET_NAME))\n                {\n                    builder.requiredReplicaSetName(getProperty(MongoDBConstants.REPLICA_SET_NAME, String.class));\n                }\n            }\n            catch (NumberFormatException nfe)\n            {\n                logger.error(\"Error while setting mongo properties, caused by :\" + nfe);\n                throw new NumberFormatException(\"Error while setting mongo properties, caused by :\" + nfe);\n            }\n\n            return builder;\n        }\n\n        /**\n         * Checks for property.\n         * \n         * @param key\n         *            the key\n         * @return true, if successful\n         */\n        private boolean hasProperty(String key)\n        {\n            boolean result = false;\n\n            if (externalProperties != null)\n            {\n                result = externalProperties.containsKey(key);\n            }\n\n            if (!result && clientProperties != null)\n            {\n                result = clientProperties.containsKey(key);\n            }\n\n            return result;\n        }\n\n        /**\n         * Gets the property.\n         * \n         * @param <T>\n         *            the generic type\n         * @param key\n         *            the key\n         * @param targetClass\n         *            the target class\n         * @return the property\n         */\n        private <T> T getProperty(String key, Class<T> targetClass)\n        {\n            return getProperty(key, null, targetClass);\n        }\n\n        /**\n         * Gets the property.\n         * \n         * @param <T>\n         *            the generic type\n         * @param key\n         *            the key\n         * @param defaultValue\n         *            the default value\n         * @param targetClass\n         *            the target class\n         * @return the property\n         */\n        private <T> T getProperty(String key, T defaultValue, Class<T> targetClass)\n        {\n            T value = null;\n\n            if (externalProperties != null)\n            {\n                value = instanceFromProperty(externalProperties.get(key), targetClass);\n            }\n\n            if (value == null && clientProperties != null)\n            {\n                value = instanceFromProperty(clientProperties.get(key), targetClass);\n            }\n\n            if (value != null)\n            {\n                return value;\n            }\n            else\n            {\n                return defaultValue;\n            }\n        }\n\n        /**\n         * Instance from property.\n         * \n         * @param <T>\n         *            the generic type\n         * @param property\n         *            the property\n         * @param targetClass\n         *            the target class\n         * @return the t\n         */\n        private <T> T instanceFromProperty(Object property, Class<T> targetClass)\n        {\n            if (property == null)\n            {\n                return null;\n            }\n\n            if (targetClass.isInstance(property))\n            {\n                return (T) property;\n            }\n\n            if (property instanceof String)\n            {\n                String target = property.toString().trim();\n\n                // try primitive parsers\n                if (Integer.class.equals(targetClass) || int.class.equals(targetClass))\n                {\n                    return (T) Integer.valueOf(target);\n                }\n                else if (Long.class.equals(targetClass) || long.class.equals(targetClass))\n                {\n                    return (T) Long.valueOf(target);\n                }\n                else if (Boolean.class.equals(targetClass) || boolean.class.equals(targetClass))\n                {\n                    return (T) Boolean.valueOf(target);\n                }\n\n                // try instantiating from a class\n                try\n                {\n                    Class<?> clazz = Class.forName(target).asSubclass(targetClass);\n                    return (T) KunderaCoreUtils.createNewInstance(clazz);\n                }\n                catch (ClassNotFoundException ex)\n                {\n                    // this wasn't a class then in the configuration\n                }\n\n                // try accessing a static member\n                int lastDot = target.lastIndexOf('.');\n                if (lastDot > 0)\n                {\n                    String className = target.substring(0, lastDot);\n                    String memberName = target.substring(lastDot + 1);\n\n                    try\n                    {\n                        Class<?> clazz = Class.forName(className);\n\n                        if (memberName.contains(Constants.OPEN_ROUND_BRACKET))\n                        {\n                            // static method without arguments - e.g.\n                            // javax.net.ssl.SSLSocketFactory.getDefault()\n                            String methodName = memberName.substring(0, memberName.indexOf('('));\n\n                            Method method = clazz.getMethod(methodName);\n                            return (T) method.invoke(null);\n                        }\n                        else\n                        {\n                            // static field - e.g.\n                            // com.mongodb.LazyDBDecoder.FACTORY\n                            Field field = clazz.getField(memberName);\n                            return (T) field.get(null);\n                        }\n                    }\n                    catch (ClassNotFoundException ex)\n                    {\n                        logger.error(\"Parent class not found\", ex);\n                        throw new KunderaException(INSTANCE_CREATION_EXCEPTION, ex);\n                    }\n                    catch (NoSuchMethodException ex)\n                    {\n                        logger.error(\"Static method not found\", ex);\n                        throw new KunderaException(INSTANCE_CREATION_EXCEPTION, ex);\n                    }\n                    catch (NoSuchFieldException ex)\n                    {\n                        logger.error(\"Static field not found\", ex);\n                        throw new KunderaException(INSTANCE_CREATION_EXCEPTION, ex);\n                    }\n                    catch (IllegalAccessException ex)\n                    {\n                        logger.error(\"Static method or field was not accessible\", ex);\n                        throw new KunderaException(INSTANCE_CREATION_EXCEPTION, ex);\n                    }\n                    catch (InvocationTargetException ex)\n                    {\n                        logger.error(\"Static method invocation failed\", ex);\n                        throw new KunderaException(INSTANCE_CREATION_EXCEPTION, ex);\n                    }\n                }\n            }\n\n            return null;\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initializeLoadBalancer\n     * (java.lang.String)\n     */\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n        throw new UnsupportedOperationException(\"Load balancing feature is not supported in \"\n                + this.getClass().getSimpleName());\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClientProperties.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.mongodb;\n\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.mongodb.DBEncoder;\nimport com.mongodb.WriteConcern;\n\n/**\n * MongoDB implementation of {@link ClientPropertiesSetter}.\n * \n * @author amresh.singh\n */\npublic class MongoDBClientProperties\n{\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(MongoDBClientProperties.class);\n\n    /** The Constant WRITE_CONCERN. */\n    public static final String WRITE_CONCERN = \"write.concern\";\n\n    /** The Constant DB_ENCODER. */\n    public static final String DB_ENCODER = \"db.encoder\";\n\n    /** The Constant BATCH_SIZE. */\n    public static final String BATCH_SIZE = \"batch.size\";\n\n    /** The Constant ORDERED_BULK_OPERATION. */\n    public static final String ORDERED_BULK_OPERATION = \"ordered.bulk.operation\";\n\n    /** The mongo db client. */\n    private MongoDBClient mongoDBClient;\n\n    /**\n     * Populate client properties.\n     * \n     * @param client\n     *            the client\n     * @param properties\n     *            the properties\n     */\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        this.mongoDBClient = (MongoDBClient) client;\n\n        if (properties != null)\n        {\n            for (String key : properties.keySet())\n            {\n                Object value = properties.get(key);\n                if (checkNull(key, value))\n                {\n                    if (key.equals(WRITE_CONCERN) && value instanceof WriteConcern)\n                    {\n                        this.mongoDBClient.setWriteConcern((WriteConcern) value);\n                    }\n                    else if (key.equals(DB_ENCODER) && value instanceof DBEncoder)\n                    {\n                        this.mongoDBClient.setEncoder((DBEncoder) value);\n                    }\n                    else if (key.equals(BATCH_SIZE))\n                    {\n                        setBatchSize(value);\n                    }\n                    else if (key.equals(ORDERED_BULK_OPERATION))\n                    {\n                        try\n                        {\n                            this.mongoDBClient.setOrderedBulkOperation((boolean) value);\n                        }\n                        catch (ClassCastException ex)\n                        {\n                            log.error(\n                                    \"only boolean value is supported for ORDERED_BULK_OPERATION property. Caused By: \",\n                                    ex);\n                            throw new KunderaException(\n                                    \"only boolean value is supported for ORDERED_BULK_OPERATION property. Caused By: \",\n                                    ex);\n\n                        }\n                    }\n                }\n                // Add more properties as needed\n            }\n        }\n    }\n\n    /**\n     * set batch size.\n     * \n     * @param value\n     *            the new batch size\n     */\n    private void setBatchSize(Object value)\n    {\n        if (value instanceof Integer)\n        {\n            this.mongoDBClient.setBatchSize((Integer) value);\n        }\n        else if (value instanceof String)\n        {\n            this.mongoDBClient.setBatchSize(Integer.valueOf((String) value));\n        }\n    }\n\n    /**\n     * check key value map not null.\n     * \n     * @param key\n     *            the key\n     * @param value\n     *            the value\n     * @return true, if successful\n     */\n    private boolean checkNull(String key, Object value)\n    {\n        return key != null && value != null;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBConstants.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb;\n\n/**\n * Holds constants for kundera-mongo module.\n * \n * @author Kuldeep Mishra\n */\npublic interface MongoDBConstants\n{\n\n    /** The Constant CONNECTIONS. */\n    public static final String CONNECTIONS = \"mongodb.servers\";\n\n    /** The Constant SOCKET_TIMEOUT. */\n    public static final String SOCKET_TIMEOUT = \"socket.timeout\";\n\n    /** The Constant READ_PREFERENCE. */\n    public static final String READ_PREFERENCE = \"read.preference\";\n\n    /** The Constant AUTO_CONNECT_RETRY. */\n    public static final String AUTO_CONNECT_RETRY = \"autoconnect.retry\";\n\n    /** The Constant CONNECTION_PER_HOST. */\n    public static final String CONNECTION_PER_HOST = \"connection.perhost\";\n\n    /** The Constant CONNECT_TIME_OUT. */\n    public static final String CONNECT_TIME_OUT = \"connection.timeout\";\n\n    /** The Constant DB_DECODER_FACTORY. */\n    public static final String DB_DECODER_FACTORY = \"dbdecoder.factory\";\n\n    /** The Constant DB_ENCODER_FACTORY. */\n    public static final String DB_ENCODER_FACTORY = \"dbencoder.factory\";\n\n    /** The Constant FSYNC. */\n    public static final String FSYNC = \"fsync\";\n\n    /** The Constant MAX_AUTO_CONNECT_RETRY. */\n    public static final String MAX_AUTO_CONNECT_RETRY = \"max.autoconnect.retry\";\n\n    /** The Constant J. */\n    public static final String J = \"j\";\n\n    /** The Constant MAX_WAIT_TIME. */\n    public static final String MAX_WAIT_TIME = \"maxwait.time\";\n\n    /** The Constant SAFE. */\n    public static final String SAFE = \"safe\";\n\n    /** The Constant SOCKET_FACTORY. */\n    public static final String SOCKET_FACTORY = \"socket.factory\";\n\n    /** The Constant TABCM. */\n    public static final String TABCM = \"threadsallowed.block.connectionmultiplier\";\n\n    /** The Constant W. */\n    public static final String W = \"w\";\n\n    /** The Constant W_TIME_OUT. */\n    public static final String W_TIME_OUT = \"w.timeout\";\n\n    // public static final int DEFAULT_MAX_WAIT_TIME = 120000;\n\n    // public static final int DEFAULT_TABCM = 5;\n\n    /** The Constant CAPPED. */\n    public static final String CAPPED = \"capped\";\n\n    /** The Constant SIZE. */\n    public static final String SIZE = \"size\";\n\n    /** The Constant MAX. */\n    public static final String MAX = \"max\";\n\n    /** The Constant MIN. */\n    public static final String MIN = \"min\";\n\n    /** The Constant WRITE_CONCERN. */\n    public final static String WRITE_CONCERN = \"write.concern\";\n\n    /** The Constant ORDERED_BULK_OPERATION. */\n    public final static String ORDERED_BULK_OPERATION = \"ordered.bulk.operation\";\n\n    /** The Constant REPLICA_SET_NAME. */\n    public final static String REPLICA_SET_NAME = \"replica.set.name\";\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBDataHandler.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n * *\n * * Licensed under the Apache License, Version 2.0 (the \"License\");\n * * you may not use this file except in compliance with the License.\n * * You may obtain a copy of the License at\n * *\n * * http://www.apache.org/licenses/LICENSE-2.0\n * *\n * * Unless required by applicable law or agreed to in writing, software\n * * distributed under the License is distributed on an \"AS IS\" BASIS,\n * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * * See the License for the specific language governing permissions and\n * * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.mongodb.BasicDBObject;\nimport com.mongodb.DBCollection;\nimport com.mongodb.DBObject;\n\n/**\n * Provides utility methods for handling data held in MongoDB.\n * \n * @author Sergei @bsideup Egorov\n * \n */\npublic interface MongoDBDataHandler\n{\n    /**\n     * Gets the entity from document.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param m\n     *            the m\n     * @param document\n     *            the document\n     * @param relations\n     *            the relations\n     * @return the entity from document\n     */\n    Map<String, Object> getEntityFromDocument(Class<?> entityClass, Object entity, EntityMetadata m, DBObject document,\n            List<String> relations, Map<String, Object> relationValue, final KunderaMetadata kunderaMetadata);\n\n    /**\n     * Retrieves A collection of embedded object within a document that match a\n     * criteria specified in <code>query</code> TODO: This code requires a\n     * serious overhawl. Currently it assumes that user query is in the form\n     * \"Select alias.columnName from EntityName alias\". However, correct query\n     * to be supported is\n     * \"Select alias.superColumnName.columnName from EntityName alias\"\n     * \n     * @param dbCollection\n     *            the db collection\n     * @param m\n     *            the m\n     * @param documentName\n     *            the document name\n     * @param mongoQuery\n     *            the mongo query\n     * @param result\n     *            the result\n     * @param orderBy\n     *            the order by\n     * @param maxResult\n     * @return the embedded object list\n     * @throws com.impetus.kundera.property.PropertyAccessException\n     *             the property access exception\n     */\n    List getEmbeddedObjectList(DBCollection dbCollection, EntityMetadata m, String documentName,\n            BasicDBObject mongoQuery, String result, BasicDBObject orderBy, int maxResult, int firstResult,\n            BasicDBObject keys, final KunderaMetadata kunderaMetadata) throws PropertyAccessException,\n            InstantiationException, IllegalAccessException;\n\n    /**\n     * Gets the document from entity.\n     * \n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param relations\n     *            the relations\n     * @return the document from entity\n     * @throws PropertyAccessException\n     *             the property access exception\n     */\n    Map<String, DBObject> getDocumentFromEntity(EntityMetadata m, Object entity, List<RelationHolder> relations,\n            final KunderaMetadata kunderaMetadata) throws PropertyAccessException;\n}"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBIdGenerator.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb;\n\nimport org.bson.types.ObjectId;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.generator.AutoGenerator;\n\n/**\n * The Class MongoDBIdGenerator.\n * \n * @author: karthikp.manchala\n */\npublic class MongoDBIdGenerator implements AutoGenerator\n{\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.AutoGenerator#generate(com.impetus.kundera\n     * .client.Client, java.lang.Object)\n     */\n    @Override\n    public Object generate(Client<?> client, String dataType)\n    {\n        // return auto generated id used by mongodb.\n        return new ObjectId();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoEntityReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb;\n\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * The Class MongoEntityReader. Default entity reader for mongo db.\n * \n * @author vivek.mishra\n */\npublic class MongoEntityReader extends AbstractEntityReader implements EntityReader\n{\n\n    public MongoEntityReader(final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    public MongoEntityReader(KunderaQuery kunderaQuery, final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n        this.kunderaQuery = kunderaQuery;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#populateRelation(com.impetus\n     * .kundera.metadata.model.EntityMetadata, java.util.List, boolean,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        throw new UnsupportedOperationException(\"Method supported not required for mongo\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#findById(java.lang.String,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.util.List,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        return super.findById(primaryKey, m, client);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/config/MongoDBPropertyReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb.config;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.mongodb.MongoDBConstants;\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Schema;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Schema.Table;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * Mongo Property Reader reads mongo properties from property file\n * {kundera-mongo.properties} and put it into mongo schema metadata.\n * \n * @author kuldeep.mishra\n * \n */\npublic class MongoDBPropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n    /** log instance */\n    private static Logger log = LoggerFactory.getLogger(MongoDBPropertyReader.class);\n\n    /** MongoDB schema metadata instance */\n    public static MongoDBSchemaMetadata msmd;\n\n    public MongoDBPropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        msmd = new MongoDBSchemaMetadata();\n    }\n\n    public void onXml(ClientProperties cp)\n    {\n        if (cp != null)\n        {\n            msmd.setClientProperties(cp);\n        }\n    }\n\n    /**\n     * MongoDBSchemaMetadata class holds property related to metadata\n     * \n     * @author kuldeep.mishra\n     * \n     */\n    public class MongoDBSchemaMetadata\n    {\n        private ClientProperties clientProperties;\n\n        public MongoDBSchemaMetadata()\n        {\n\n        }\n\n        /**\n         * @return the clientProperties\n         */\n        public ClientProperties getClientProperties()\n        {\n            return clientProperties;\n        }\n\n        /**\n         * @param clientProperties\n         *            the clientProperties to set\n         */\n        private void setClientProperties(ClientProperties clientProperties)\n        {\n            this.clientProperties = clientProperties;\n        }\n\n        public DataStore getDataStore()\n        {\n            if (getClientProperties() != null && getClientProperties().getDatastores() != null)\n            {\n                for (DataStore dataStore : getClientProperties().getDatastores())\n                {\n                    if (dataStore.getName() != null && dataStore.getName().trim().equalsIgnoreCase(\"mongo\"))\n                    {\n                        return dataStore;\n                    }\n                }\n            }\n            return null;\n        }\n\n        /**\n         * @param databaseName\n         * @param tableName\n         * @return\n         */\n        public boolean isCappedCollection(String databaseName, String tableName)\n        {\n            List<Schema> schemas = getDataStore() != null ? getDataStore().getSchemas() : null;\n            if (schemas != null)\n            {\n                for (Schema schema : schemas)\n                {\n                    if (schema != null && schema.getName() != null && schema.getName().equalsIgnoreCase(databaseName))\n                    {\n                        for (Table table : schema.getTables())\n                        {\n                            if (table.getProperties() != null && tableName.equals(table.getName()))\n                            {\n                                return Boolean.parseBoolean(table.getProperties().getProperty(MongoDBConstants.CAPPED));\n                            }\n                        }\n                    }\n                }\n            }\n            return false;\n        }\n\n        /**\n         * @param databaseName\n         * @param tableName\n         * @return\n         */\n        public int getCollectionSize(String databaseName, String tableName)\n        {\n            List<Schema> schemas = getDataStore() != null ? getDataStore().getSchemas() : null;\n            if (schemas != null)\n            {\n                for (Schema schema : schemas)\n                {\n                    if (schema != null && schema.getName() != null && schema.getName().equalsIgnoreCase(databaseName))\n                    {\n                        for (Table table : schema.getTables())\n                        {\n                            if (table.getProperties() != null)\n                            {\n                                try\n                                {\n                                    String size = table.getProperties().getProperty(MongoDBConstants.SIZE);\n                                    if (size != null && !size.isEmpty())\n                                    {\n                                        return Integer.parseInt(size);\n                                    }\n                                }\n                                catch (NumberFormatException nfe)\n                                {\n                                    throw new SchemaGenerationException(nfe);\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n            return 100000;\n        }\n\n        /**\n         * @param databaseName\n         * @param tableName\n         * @return\n         */\n        public int getMaxSize(String databaseName, String tableName)\n        {\n            List<Schema> schemas = getDataStore() != null ? getDataStore().getSchemas() : null;\n            if (schemas != null)\n            {\n                for (Schema schema : schemas)\n                {\n                    if (schema != null && schema.getName() != null && schema.getName().equalsIgnoreCase(databaseName))\n                    {\n                        for (Table table : schema.getTables())\n                        {\n                            if (table.getProperties() != null)\n                            {\n                                try\n                                {\n                                    String max = table.getProperties().getProperty(MongoDBConstants.MAX);\n                                    if (max != null && !max.isEmpty())\n                                    {\n                                        return Integer.parseInt(max);\n                                    }\n                                }\n                                catch (NumberFormatException nfe)\n                                {\n                                    throw new SchemaGenerationException(nfe);\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n            return 100;\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/index/IndexType.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.mongodb.index;\n\n/**\n * MongoDB Index Type\n * \n * @author amresh.singh\n */\npublic enum IndexType\n{\n    ASC, DSC, GEO2D;\n\n    public static String findByValue(IndexType value)\n    {\n        switch (value)\n        {\n        case ASC:\n            return \"1\";\n        case DSC:\n            return \"-1\";\n        case GEO2D:\n            return \"2D\";\n        default:\n            return \"1\";\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/query/MongoDBQuery.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb.query;\n\nimport java.lang.reflect.Field;\nimport java.util.Arrays;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Queue;\nimport java.util.StringTokenizer;\nimport java.util.regex.Pattern;\n\nimport javax.persistence.Query;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.Metamodel;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.eclipse.persistence.jpa.jpql.parser.AggregateFunction;\nimport org.eclipse.persistence.jpa.jpql.parser.CollectionExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.CountFunction;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectClause;\nimport org.eclipse.persistence.jpa.jpql.parser.StateFieldPathExpression;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.mongodb.MongoDBClient;\nimport com.impetus.client.mongodb.MongoEntityReader;\nimport com.impetus.client.mongodb.query.gis.GeospatialQueryFactory;\nimport com.impetus.client.mongodb.utils.MongoDBUtils;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.gis.geometry.Point;\nimport com.impetus.kundera.gis.query.GeospatialQuery;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.attributes.DefaultSingularAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.query.JPQLParseException;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.query.KunderaQuery.SortOrder;\nimport com.impetus.kundera.query.KunderaQuery.SortOrdering;\nimport com.impetus.kundera.query.KunderaQuery.UpdateClause;\nimport com.impetus.kundera.query.QueryHandlerException;\nimport com.impetus.kundera.query.QueryImpl;\nimport com.mongodb.DBObject;\nimport com.mongodb.BasicDBList;\nimport com.mongodb.BasicDBObject;\n\n/**\n * Query class for MongoDB data store.\n * \n * @author amresh.singh\n */\npublic class MongoDBQuery extends QueryImpl\n{\n    /** The log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(MongoDBQuery.class);\n\n    /** The is single result. */\n    private boolean isSingleResult;\n\n    /**\n     * Instantiates a new mongo db query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param persistenceDelegator\n     *            the persistence delegator\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public MongoDBQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#executeUpdate()\n     */\n    @Override\n    public int executeUpdate()\n    {\n        return super.executeUpdate();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#setFirstResult(int)\n     */\n    @Override\n    public Query setFirstResult(int firstResult)\n    {\n        return super.setFirstResult(firstResult);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#setMaxResults(int)\n     */\n    @Override\n    public Query setMaxResults(int maxResult)\n    {\n        return super.setMaxResults(maxResult);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n\n    @Override\n    protected List<Object> populateEntities(EntityMetadata m, Client client)\n    {\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\n\n        try\n        {\n            String query = appMetadata.getQuery(getJPAQuery());\n\n            boolean isNative = kunderaQuery.isNative();\n\n            if (isNative)\n            { // Native Query Support is enabled\n                return ((MongoDBClient) client).executeQuery(query == null ? getJPAQuery() : query, m);\n            }\n\n            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))\n            {\n                if (kunderaQuery.isAggregated())\n                {\n                    return ((MongoDBClient) client).aggregate(m,\n                            createMongoQuery(m, getKunderaQuery().getFilterClauseQueue()), createAggregationLookup(m),\n                            createAggregation(m), getAggregationOrderByClause(m), isSingleResult ? 1 : maxResult);\n                }\n                else\n                {\n                    BasicDBObject orderByClause = getOrderByClause(m);\n                    return ((MongoDBClient) client).loadData(m,\n                            createMongoQuery(m, getKunderaQuery().getFilterClauseQueue()), null, orderByClause,\n                            isSingleResult ? 1 : maxResult, firstResult, isCountQuery(),\n                            getKeys(m, getKunderaQuery().getResult()), getKunderaQuery().getResult());\n                }\n            }\n            else\n            {\n                return populateUsingLucene(m, client, null, getKunderaQuery().getResult());\n            }\n\n        }\n        catch (Exception e)\n        {\n\n            log.error(\"Error during executing query, Caused by:\", e);\n            throw new QueryHandlerException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#findUsingLucene(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n        try\n        {\n            BasicDBObject orderByClause = getOrderByClause(m);\n            // find on id, so no need to add skip() [firstResult hardcoded 0]\n            return ((MongoDBClient) client).loadData(m, createMongoQuery(m, getKunderaQuery().getFilterClauseQueue()),\n                    null, orderByClause, isSingleResult ? 1 : maxResult, 0, isCountQuery(),\n                    getKeys(m, getKunderaQuery().getResult()), getKunderaQuery().getResult());\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error during executing query, Caused by:\", e);\n            throw new QueryHandlerException(e);\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#recursivelyPopulateEntities(com.\n     * impetus .kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n        // TODO : required to modify client return relation.\n        // if it is a parent..then find data related to it only\n        // else u need to load for associated fields too.\n        List<EnhanceEntity> ls = new ArrayList<EnhanceEntity>();\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\n        try\n        {\n            String query = appMetadata.getQuery(getJPAQuery());\n            boolean isNative = kunderaQuery.isNative();\n\n            if (isNative)\n            {\n                return ((MongoDBClient) client).executeQuery(query == null ? getJPAQuery() : query, m);\n\n            }\n\n            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))\n            {\n                if (kunderaQuery.isAggregated())\n                {\n                    return ((MongoDBClient) client).aggregate(m,\n                            createMongoQuery(m, getKunderaQuery().getFilterClauseQueue()), createAggregationLookup(m),\n                            createAggregation(m), getAggregationOrderByClause(m), isSingleResult ? 1 : maxResult);\n                }\n                else\n                {\n                    BasicDBObject orderByClause = getOrderByClause(m);\n                    ls = ((MongoDBClient) client).loadData(m,\n                            createMongoQuery(m, getKunderaQuery().getFilterClauseQueue()), m.getRelationNames(),\n                            orderByClause, isSingleResult ? 1 : maxResult, firstResult, isCountQuery(),\n                            getKeys(m, getKunderaQuery().getResult()), getKunderaQuery().getResult());\n                }\n            }\n            else\n            {\n                return populateUsingLucene(m, client, null, getKunderaQuery().getResult());\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error during executing query, Caused by:\", e);\n            throw new QueryHandlerException(e);\n        }\n\n        return setRelationEntities(ls, client, m);\n    }\n\n    /**\n     * Checks if is count query.\n     * \n     * @return true, if is count query\n     */\n    private boolean isCountQuery()\n    {\n        if (getKunderaQuery().getSelectStatement() != null)\n        {\n            final Expression selectClause = getKunderaQuery().getSelectStatement().getSelectClause();\n\n            if (selectClause instanceof SelectClause)\n            {\n                final Expression expression = ((SelectClause) selectClause).getSelectExpression();\n\n                return expression instanceof CountFunction;\n            }\n        }\n\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#getReader()\n     */\n    @Override\n    protected EntityReader getReader()\n    {\n        return new MongoEntityReader(kunderaQuery, kunderaMetadata);\n    }\n\n    /**\n     * The Class QueryComponent.\n     */\n    static class QueryComponent\n    {\n\n        /** The is and. */\n        boolean isAnd;\n\n        /** The clauses. */\n        Queue clauses = new LinkedList();\n\n        /** The children. */\n        List<QueryComponent> children = new ArrayList<MongoDBQuery.QueryComponent>();\n\n        /** The parent. */\n        QueryComponent parent;\n\n        /** The actual query. */\n        BasicDBObject actualQuery;\n    }\n\n    /**\n     * Populate query components.\n     * \n     * @param m\n     *            the m\n     * @param sq\n     *            the sq\n     */\n    private void populateQueryComponents(EntityMetadata m, QueryComponent sq)\n    {\n        boolean hasChildren = false;\n        if (sq.children != null && sq.children.size() > 0)\n        {\n            hasChildren = true;\n            for (QueryComponent subQ : sq.children)\n            {\n                populateQueryComponents(m, subQ);\n            }\n        }\n        if (sq.clauses.size() > 0 || hasChildren)\n        {\n            if (sq.clauses.size() > 0)\n            {\n                sq.actualQuery = createSubMongoQuery(m, sq.clauses);\n            }\n            if (hasChildren)\n            {\n                List<BasicDBObject> childQs = new ArrayList<BasicDBObject>();\n                if (sq.clauses.size() > 0)\n                    childQs.add(sq.actualQuery);\n                for (QueryComponent subQ : sq.children)\n                {\n                    childQs.add(subQ.actualQuery);\n                }\n                if (childQs.size() == 1)\n                {\n                    sq.actualQuery = childQs.get(0);\n                }\n                else if (sq.isAnd)\n                {\n                    BasicDBObject dbo = new BasicDBObject(\"$and\", childQs);\n                    sq.actualQuery = dbo;\n                }\n                else\n                {\n                    BasicDBObject dbo = new BasicDBObject(\"$or\", childQs);\n                    sq.actualQuery = dbo;\n                }\n            }\n        }\n    }\n\n    /**\n     * Gets the query component.\n     * \n     * @param filterClauseQueue\n     *            the filter clause queue\n     * @return the query component\n     */\n    private static QueryComponent getQueryComponent(Queue filterClauseQueue)\n    {\n        QueryComponent subQuery = new QueryComponent();\n        QueryComponent currentSubQuery = subQuery;\n\n        for (Object object : filterClauseQueue)\n        {\n            if (object instanceof FilterClause)\n            {\n                currentSubQuery.clauses.add(object);\n            }\n            else if (object instanceof String)\n            {\n                String interClauseConstruct = (String) object;\n                if (interClauseConstruct.equals(\"(\"))\n                {\n                    QueryComponent temp = new QueryComponent();\n                    currentSubQuery.children.add(temp);\n                    temp.parent = currentSubQuery;\n                    currentSubQuery = temp;\n                }\n                else if (interClauseConstruct.equals(\")\"))\n                {\n                    currentSubQuery = currentSubQuery.parent;\n                }\n                else if (interClauseConstruct.equalsIgnoreCase(\"AND\"))\n                {\n                    currentSubQuery.isAnd = true;\n                }\n                else if (interClauseConstruct.equalsIgnoreCase(\"OR\"))\n                {\n                    currentSubQuery.isAnd = false;\n                }\n            }\n        }\n\n        return subQuery;\n    }\n\n    /**\n     * Creates the mongo query.\n     * \n     * @param m\n     *            the m\n     * @param filterClauseQueue\n     *            the filter clause queue\n     * @return the basic db object\n     */\n    public BasicDBObject createMongoQuery(EntityMetadata m, Queue filterClauseQueue)\n    {\n        QueryComponent sq = getQueryComponent(filterClauseQueue);\n        populateQueryComponents(m, sq);\n        return sq.actualQuery == null ? new BasicDBObject() : sq.actualQuery;\n    }\n\n    /**\n     * Creates MongoDB Query object from filterClauseQueue.\n     * \n     * @param m\n     *            the m\n     * @param filterClauseQueue\n     *            the filter clause queue\n     * @return the basic db object\n     */\n    public BasicDBObject createSubMongoQuery(EntityMetadata m, Queue filterClauseQueue)\n    {\n        BasicDBObject query = new BasicDBObject();\n        BasicDBObject compositeColumns = new BasicDBObject();\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(m.getPersistenceUnit());\n\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(m.getEntityClazz());\n\n        for (Object object : filterClauseQueue)\n        {\n            boolean isCompositeColumn = false;\n\n            boolean isSubCondition = false;\n\n            if (object instanceof FilterClause)\n            {\n                FilterClause filter = (FilterClause) object;\n                String property = filter.getProperty();\n                String condition = filter.getCondition();\n                boolean ignoreCase = filter.isIgnoreCase();\n\n                Object value;\n                if (filter.getValue().size() == 1)\n                {\n                    value = filter.getValue().get(0);\n                }\n                else\n                {\n                    value = filter.getValue();\n                }\n\n                // value is string but field.getType is different, then get\n                // value using\n\n                Field f = null;\n\n                // if alias is still present .. means it is an enclosing\n                // document search.\n\n                if (managedType.hasLobAttribute())\n                {\n                    EntityType entity = metaModel.entity(m.getEntityClazz());\n                    String fieldName = m.getFieldName(property);\n\n                    f = (Field) entity.getAttribute(fieldName).getJavaMember();\n\n                    if (value != null)\n                    {\n                        if (value.getClass().isAssignableFrom(String.class) && f != null\n                                && !f.getType().equals(value.getClass()))\n                        {\n                            value = PropertyAccessorFactory.getPropertyAccessor(f).fromString(f.getType().getClass(),\n                                    value.toString());\n                        }\n                        value = MongoDBUtils.populateValue(value, value.getClass());\n                    }\n\n                    property = \"metadata.\" + property;\n                }\n                else\n                {\n                    if (((AbstractAttribute) m.getIdAttribute()).getJPAColumnName().equalsIgnoreCase(property))\n                    {\n                        if (value != null)\n                        {\n                            property = \"_id\";\n                            f = (Field) m.getIdAttribute().getJavaMember();\n                            if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())\n                                    && value.getClass().isAssignableFrom(f.getType()))\n                            {\n                                EmbeddableType compoundKey = metaModel\n                                        .embeddable(m.getIdAttribute().getBindableJavaType());\n                                compositeColumns = MongoDBUtils.getCompoundKeyColumns(m, value, compoundKey, metaModel);\n                                isCompositeColumn = true;\n                                continue;\n                            }\n                        }\n                    }\n                    else if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())\n                            && StringUtils.contains(property, '.'))\n                    {\n                        // Means it is a case of composite column.\n                        property = property.substring(property.indexOf(\".\") + 1);\n                        isCompositeColumn = true;\n                    } /*\n                       * if a composite key. \".\" assuming \".\" is part of\n                       * property in case of embeddable only\n                       */\n                    else if (StringUtils.contains(property, '.'))\n                    {\n                        EntityType entity = metaModel.entity(m.getEntityClazz());\n                        StringTokenizer tokenizer = new StringTokenizer(property, \".\");\n                        String embeddedAttributeAsStr = tokenizer.nextToken();\n                        String embeddableAttributeAsStr = tokenizer.nextToken();\n                        Attribute embeddedAttribute = entity.getAttribute(embeddedAttributeAsStr);\n\n                        if (embeddedAttribute.isAssociation())\n                        {\n                            Relation relation = m.getRelation(embeddedAttributeAsStr);\n                            f = relation.getProperty();\n\n                            AbstractAttribute targetAttribute = (AbstractAttribute) metaModel\n                                    .entity(relation.getTargetEntity()).getAttribute(embeddableAttributeAsStr);\n                            String targetColumnName = targetAttribute.getJPAColumnName();\n\n                            if (targetAttribute instanceof DefaultSingularAttribute\n                                    && ((DefaultSingularAttribute) targetAttribute).isId())\n                            {\n                                property = relation.getJoinColumnName(kunderaMetadata);\n                            }\n                            else\n                            {\n                                property = embeddedAttributeAsStr + \".\" + targetColumnName;\n                            }\n                        }\n                        else\n                        {\n                            EmbeddableType embeddableEntity = metaModel\n                                    .embeddable(((AbstractAttribute) embeddedAttribute).getBindableJavaType());\n                            f = (Field) embeddableEntity.getAttribute(embeddableAttributeAsStr).getJavaMember();\n                            property = ((AbstractAttribute) embeddedAttribute).getJPAColumnName() + \".\"\n                                    + ((AbstractAttribute) embeddableEntity.getAttribute(embeddableAttributeAsStr))\n                                            .getJPAColumnName();\n                        }\n                    }\n                    else\n                    {\n                        EntityType entity = metaModel.entity(m.getEntityClazz());\n                        String discriminatorColumn = ((AbstractManagedType) entity).getDiscriminatorColumn();\n\n                        if (!property.equals(discriminatorColumn))\n                        {\n                            String fieldName = m.getFieldName(property);\n                            f = (Field) entity.getAttribute(fieldName).getJavaMember();\n                        }\n                    }\n\n                    if (value != null)\n                    {\n                        if (value.getClass().isAssignableFrom(String.class) && f != null\n                                && !f.getType().equals(value.getClass()))\n                        {\n                            value = PropertyAccessorFactory.getPropertyAccessor(f).fromString(f.getType(),\n                                    value.toString());\n                        }\n                        value = MongoDBUtils.populateValue(value, value.getClass());\n                    }\n\n                }\n\n                // Property, if doesn't exist in entity, may be there in a\n                // document embedded within it, so we have to check that\n                // TODO: Query should actually be in a format\n                // documentName.embeddedDocumentName.column, remove below if\n                // block once this is decided\n\n                // Query could be geospatial in nature\n                if (f != null && f.getType().equals(Point.class))\n                {\n                    GeospatialQuery geospatialQueryimpl = GeospatialQueryFactory\n                            .getGeospatialQueryImplementor(condition, value);\n                    query = (BasicDBObject) geospatialQueryimpl.createGeospatialQuery(property, value, query);\n\n                }\n                else\n                {\n\n                    if (isCompositeColumn)\n                    {\n                        EmbeddableType embeddableType = metaModel.embeddable(m.getIdAttribute().getBindableJavaType());\n                        AbstractAttribute attribute = (AbstractAttribute) embeddableType.getAttribute(property);\n\n                        property = new StringBuffer(\"_id.\").append(attribute.getJPAColumnName()).toString();\n                    }\n\n                    if (ignoreCase)\n                    {\n                        // let 'like' and 'not like' take care of this on its\n                        // own\n                        if (!condition.equalsIgnoreCase(\"like\") && !condition.equalsIgnoreCase(\"not like\"))\n                        {\n\n                            if (value instanceof String)\n                            {\n                                value = Pattern.compile(createLikeRegex((String) value, ignoreCase));\n\n                            }\n                            else if (value instanceof Collection)\n                            {\n                                Collection<?> original = (Collection<?>) value;\n                                List<Pattern> values = new ArrayList<Pattern>(original.size());\n\n                                for (Object item : original)\n                                {\n                                    values.add(Pattern.compile(createLikeRegex((String) item, ignoreCase)));\n                                }\n\n                                value = values;\n\n                            }\n                        }\n                    }\n\n                    if (condition.equals(\"=\"))\n                    {\n\n                        if (query.containsField(property))\n                        {\n                            appendToQuery(query, property, \"$eq\", value);\n                        }\n                        else\n                        {\n                            query.append(property, value);\n                        }\n\n                    }\n                    else if (condition.equalsIgnoreCase(\"is null\"))\n                    {\n                        if (query.containsField(property))\n                        {\n                            appendToQuery(query, property, \"$eq\", null);\n                        }\n                        else\n                        {\n                            query.append(property, null);\n                        }\n                    }\n                    else if (condition.toLowerCase().contains(\"like\"))\n                    {\n\n                        Pattern regEx = Pattern.compile(createLikeRegex((String) value, ignoreCase));\n                        boolean negative = condition.toLowerCase().contains(\"not\");\n\n                        appendToQuery(query, property, negative ? \"$not\" : \"$regex\", regEx);\n\n                    }\n                    else if (condition.equalsIgnoreCase(\">\"))\n                    {\n\n                        appendToQuery(query, property, \"$gt\", value);\n\n                    }\n                    else if (condition.equalsIgnoreCase(\">=\"))\n                    {\n\n                        appendToQuery(query, property, \"$gte\", value);\n\n                    }\n                    else if (condition.equalsIgnoreCase(\"<\"))\n                    {\n\n                        appendToQuery(query, property, \"$lt\", value);\n\n                    }\n                    else if (condition.equalsIgnoreCase(\"<=\"))\n                    {\n\n                        appendToQuery(query, property, \"$lte\", value);\n\n                    }\n                    else if (condition.equalsIgnoreCase(\"in\"))\n                    {\n\n                        if (value != null)\n                        {\n                            if (!value.getClass().isArray() && !(value instanceof Collection))\n                            {\n                                value = Collections.singletonList(value);\n                            }\n                        }\n\n                        appendToQuery(query, property, \"$in\", value);\n\n                    }\n                    else if (condition.equalsIgnoreCase(\"not in\"))\n                    {\n\n                        if (value != null)\n                        {\n                            if (!value.getClass().isArray() && !(value instanceof Collection))\n                            {\n                                value = Collections.singletonList(value);\n                            }\n                        }\n\n                        appendToQuery(query, property, \"$nin\", value);\n\n                    }\n                    else if (condition.equalsIgnoreCase(\"<>\"))\n                    {\n\n                        String operator = value instanceof Pattern ? \"$not\" : \"$ne\";\n\n                        appendToQuery(query, property, operator, value);\n\n                    }\n                    else if (condition.equalsIgnoreCase(\"is not null\"))\n                    {\n\n                        appendToQuery(query, property, \"$not\", null);\n\n                    }\n                }\n\n                // TODO: Add support for other operators like >, <, >=, <=,\n                // order by asc/ desc, limit, skip, count etc\n            }\n        }\n        if (!compositeColumns.isEmpty())\n        {\n            query.append(\"_id\", compositeColumns);\n        }\n\n        return query;\n    }\n\n    private void appendToQuery(BasicDBObject query, String property, String operator, Object value)\n    {\n        if (query.containsField(property))\n        {\n            Object existing = query.get(property);\n\n            if (!(existing instanceof BasicDBObject))\n            {\n                query.put(property, new BasicDBObject(\"$eq\", existing));\n            }\n\n            query.put(property, ((BasicDBObject) query.get(property)).append(operator, value));\n        }\n        else\n        {\n            query.append(property, new BasicDBObject(operator, value));\n        }\n    }\n\n    /**\n     * Gets the keys.\n     * \n     * @param m\n     *            the m\n     * @param columns\n     *            the columns\n     * @return the keys\n     */\n    private BasicDBObject getKeys(EntityMetadata m, String[] columns)\n    {\n        BasicDBObject keys = new BasicDBObject();\n        if (columns != null && columns.length > 0)\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                    .getMetamodel(m.getPersistenceUnit());\n            EntityType entity = metaModel.entity(m.getEntityClazz());\n            for (int i = 1; i < columns.length; i++)\n            {\n                if (columns[i] != null)\n                {\n                    Attribute col = entity.getAttribute(columns[i]);\n                    if (col == null)\n                    {\n                        throw new QueryHandlerException(\"column type is null for: \" + columns);\n                    }\n                    keys.put(((AbstractAttribute) col).getJPAColumnName(), 1);\n                }\n            }\n        }\n        return keys;\n    }\n\n    private BasicDBList createAggregationLookup(EntityMetadata metadata)\n    {\n        BasicDBList lookup = new BasicDBList();\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(metadata.getPersistenceUnit());\n\n        for (Relation relation : metadata.getRelations())\n        {\n            EntityType entityType = metaModel.entity(metadata.getEntityClazz());\n\n            AbstractAttribute attribute = (AbstractAttribute) entityType.getAttribute(relation.getProperty().getName());\n            boolean optional = false;\n            if (attribute instanceof SingularAttribute)\n            {\n                optional = ((SingularAttribute) attribute).isOptional();\n            }\n\n            EntityMetadata associatedMetadata = metaModel.getEntityMetadata(relation.getTargetEntity());\n            EntityType associatedEntityType = metaModel.entity(associatedMetadata.getEntityClazz());\n\n            String joinColumn = relation.getJoinColumnName(kunderaMetadata);\n            String localField = metadata.getFieldName(joinColumn);\n            String foreignField = associatedMetadata.getFieldName(joinColumn);\n            Attribute localAttribute = entityType.getAttribute(localField);\n\n            if (foreignField != null)\n            {\n                Attribute foreignAttribute = associatedEntityType.getAttribute(foreignField);\n                foreignField = getActualColumnName(foreignAttribute);\n            }\n            else\n            {\n                foreignField = \"_id\";\n            }\n\n            BasicDBObject item = new BasicDBObject();\n            item.put(\"from\", associatedMetadata.getTableName());\n            item.put(\"localField\", getActualColumnName(localAttribute));\n            item.put(\"foreignField\", foreignField);\n            item.put(\"as\", attribute.getName());\n            lookup.add(new BasicDBObject(\"$lookup\", item));\n\n            if (Arrays.asList(Relation.ForeignKey.ONE_TO_ONE, Relation.ForeignKey.MANY_TO_ONE)\n                    .contains(relation.getType()))\n            {\n                BasicDBObject unwind = new BasicDBObject();\n                unwind.append(\"path\", \"$\" + attribute.getName());\n                unwind.append(\"preserveNullAndEmptyArrays\", optional);\n                lookup.add(new BasicDBObject(\"$unwind\", unwind));\n            }\n        }\n\n        return lookup;\n    }\n\n    private String getActualColumnName(Attribute attribute)\n    {\n        if (attribute instanceof DefaultSingularAttribute)\n        {\n            DefaultSingularAttribute dsAttribute = (DefaultSingularAttribute) attribute;\n\n            if (dsAttribute.isId())\n            {\n                return \"_id\";\n            }\n            else\n            {\n                return dsAttribute.getJPAColumnName();\n            }\n        }\n        else if (attribute instanceof AbstractAttribute)\n        {\n            return ((AbstractAttribute) attribute).getJPAColumnName();\n        }\n        else\n        {\n            return attribute.getName();\n        }\n    }\n\n    /**\n     * Get the aggregation object.\n     *\n     * @param metadata\n     * @return\n     */\n    private BasicDBObject createAggregation(EntityMetadata metadata)\n    {\n        if (kunderaQuery.getSelectStatement() != null)\n        {\n            Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());\n            EntityType entityType = metaModel.entity(metadata.getEntityClazz());\n            AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(metadata.getEntityClazz());\n            boolean hasLob = managedType.hasLobAttribute();\n\n            BasicDBObject aggregation = new BasicDBObject();\n\n            SelectClause selectClause = (SelectClause) kunderaQuery.getSelectStatement().getSelectClause();\n            Expression expression = selectClause.getSelectExpression();\n\n            buildAggregation(aggregation, expression, metadata, entityType, hasLob);\n\n            if (aggregation.size() == 0)\n            {\n                return null;\n            }\n\n            if (!aggregation.containsField(\"_id\"))\n            {\n                aggregation.put(\"_id\", null);\n            }\n\n            return aggregation;\n        }\n\n        return null;\n    }\n\n    /**\n     * Build the aggregation parameters.\n     *\n     * @param group\n     * @param expression\n     * @param metadata\n     * @param entityType\n     */\n    private void buildAggregation(DBObject group, Expression expression, EntityMetadata metadata, EntityType entityType,\n            boolean hasLob)\n    {\n        if (expression instanceof AggregateFunction)\n        {\n            AggregateFunction aggregateFunction = (AggregateFunction) expression;\n            String identifier = aggregateFunction.getIdentifier().toLowerCase();\n\n            Expression child = aggregateFunction.getExpression();\n\n            if (child instanceof StateFieldPathExpression)\n            {\n                StateFieldPathExpression sfpExp = (StateFieldPathExpression) child;\n                String columnName = getColumnName(metadata, entityType, sfpExp.toActualText());\n                String actualColumnName = columnName;\n                if (hasLob)\n                {\n                    actualColumnName = \"metadata.\" + columnName;\n                }\n                else if (metadata.getIdAttribute().equals(entityType.getAttribute(metadata.getFieldName(columnName))))\n                {\n                    actualColumnName = \"_id\";\n                }\n\n                BasicDBObject item = new BasicDBObject(\"$\" + identifier, \"$\" + actualColumnName);\n                group.put(identifier + \"_\" + columnName, item);\n            }\n            else if (expression instanceof CountFunction)\n            {\n                group.put(\"count\", new BasicDBObject(\"$sum\", 1));\n            }\n        }\n        else if (expression instanceof CollectionExpression)\n        {\n            for (Expression child : expression.children())\n            {\n                buildAggregation(group, child, metadata, entityType, hasLob);\n            }\n        }\n        else if (expression instanceof StateFieldPathExpression)\n        {\n            StateFieldPathExpression sfpExp = (StateFieldPathExpression) expression;\n\n            BasicDBObject idObject;\n            Object existing = group.get(\"_id\");\n            if (existing != null)\n            {\n                idObject = (BasicDBObject) existing;\n            }\n            else\n            {\n                idObject = new BasicDBObject();\n                group.put(\"_id\", idObject);\n            }\n\n            String columnName = getColumnName(metadata, entityType, sfpExp.toActualText());\n            String actualColumnName = columnName;\n            if (hasLob)\n            {\n                actualColumnName = \"metadata.\" + columnName;\n            }\n\n            idObject.put(columnName, \"$\" + actualColumnName);\n        }\n    }\n\n    /**\n     * Prepare order by clause.\n     * \n     * @param metadata\n     *            the metadata\n     * @return order by clause.\n     */\n    private BasicDBObject getOrderByClause(final EntityMetadata metadata)\n    {\n\n        BasicDBObject orderByClause = null;\n        Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(metadata.getEntityClazz());\n\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(metadata.getEntityClazz());\n\n        List<SortOrdering> orders = kunderaQuery.getOrdering();\n        if (orders != null)\n        {\n            orderByClause = new BasicDBObject();\n            if (!managedType.hasLobAttribute())\n            {\n                for (SortOrdering order : orders)\n                {\n                    orderByClause.append(getColumnName(metadata, entityType, order.getColumnName()),\n                            order.getOrder().equals(SortOrder.ASC) ? 1 : -1);\n                }\n            }\n            else\n            {\n                for (SortOrdering order : orders)\n                {\n                    orderByClause.append(\"metadata.\" + getColumnName(metadata, entityType, order.getColumnName()),\n                            order.getOrder().equals(SortOrder.ASC) ? 1 : -1);\n                }\n            }\n        }\n\n        return orderByClause;\n    }\n\n    private BasicDBObject getAggregationOrderByClause(final EntityMetadata metadata)\n    {\n        BasicDBObject orderByClause = null;\n        Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(metadata.getEntityClazz());\n\n        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(metadata.getEntityClazz());\n\n        List<SortOrdering> orders = kunderaQuery.getOrdering();\n        if (orders != null)\n        {\n            orderByClause = new BasicDBObject();\n\n            for (SortOrdering order : orders)\n            {\n                if (order.getColumnName().contains(\"(\"))\n                {\n                    String function = order.getColumnName().replaceFirst(\"\\\\s*(.*?)\\\\s*\\\\(.*\", \"$1\");\n                    String property = order.getColumnName().replaceFirst(\".*?\\\\(\\\\s*(.*)\\\\s*\\\\).*\", \"$1\");\n                    String columnName = getColumnName(metadata, entityType, property);\n\n                    orderByClause.append(function.toLowerCase() + \"_\" + columnName,\n                            order.getOrder().equals(SortOrder.ASC) ? 1 : -1);\n                }\n                else\n                {\n                    if (!managedType.hasLobAttribute())\n                    {\n                        orderByClause.append(getColumnName(metadata, entityType, order.getColumnName()),\n                                order.getOrder().equals(SortOrder.ASC) ? 1 : -1);\n                    }\n                    else\n                    {\n                        orderByClause.append(\"metadata.\" + getColumnName(metadata, entityType, order.getColumnName()),\n                                order.getOrder().equals(SortOrder.ASC) ? 1 : -1);\n                    }\n                }\n            }\n        }\n\n        return orderByClause;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()\n     */\n    @Override\n    protected int onExecuteUpdate()\n    {\n        int ret = handleSpecialFunctions();\n        if (ret == -1)\n        {\n            return onUpdateDeleteEvent();\n        }\n        return ret;\n    }\n\n    /** The Constant SINGLE_STRING_KEYWORDS. */\n    public static final String[] FUNCTION_KEYWORDS = { \"INCREMENT\\\\(\\\\d+\\\\)\", \"DECREMENT\\\\(\\\\d+\\\\)\" };\n\n    /**\n     * Handle special functions.\n     * \n     * @return the int\n     */\n    private int handleSpecialFunctions()\n    {\n\n        boolean needsSpecialAttention = false;\n        outer: for (UpdateClause c : kunderaQuery.getUpdateClauseQueue())\n        {\n            for (int i = 0; i < FUNCTION_KEYWORDS.length; i++)\n            {\n                if (c.getValue() instanceof String)\n                {\n                    String func = c.getValue().toString();\n                    func = func.replaceAll(\" \", \"\");\n                    if (func.toUpperCase().matches(FUNCTION_KEYWORDS[i]))\n                    {\n                        needsSpecialAttention = true;\n                        c.setValue(func);\n                        break outer;\n                    }\n                }\n            }\n        }\n\n        if (!needsSpecialAttention)\n            return -1;\n\n        EntityMetadata m = getEntityMetadata();\n        Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());\n        Queue filterClauseQueue = kunderaQuery.getFilterClauseQueue();\n        BasicDBObject query = createMongoQuery(m, filterClauseQueue);\n\n        BasicDBObject update = new BasicDBObject();\n        for (UpdateClause c : kunderaQuery.getUpdateClauseQueue())\n        {\n            String columName = getColumnName(m, metaModel.entity(m.getEntityClazz()), c.getProperty());\n            boolean isSpecialFunction = false;\n            for (int i = 0; i < FUNCTION_KEYWORDS.length; i++)\n            {\n\n                if (c.getValue() instanceof String\n                        && c.getValue().toString().toUpperCase().matches(FUNCTION_KEYWORDS[i]))\n                {\n                    isSpecialFunction = true;\n\n                    if (c.getValue().toString().toUpperCase().startsWith(\"INCREMENT(\"))\n                    {\n                        String val = c.getValue().toString().toUpperCase();\n                        val = val.substring(10, val.indexOf(\")\"));\n                        update.put(\"$inc\", new BasicDBObject(columName, Integer.valueOf(val)));\n                    }\n                    else if (c.getValue().toString().toUpperCase().startsWith(\"DECREMENT(\"))\n                    {\n                        String val = c.getValue().toString().toUpperCase();\n                        val = val.substring(10, val.indexOf(\")\"));\n                        update.put(\"$inc\", new BasicDBObject(columName, -Integer.valueOf(val)));\n                    }\n                }\n            }\n            if (!isSpecialFunction)\n            {\n                update.put(columName, c.getValue());\n            }\n        }\n\n        Client client = persistenceDelegeator.getClient(m);\n        return ((MongoDBClient) client).handleUpdateFunctions(query, update, m.getTableName());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#close()\n     */\n    @Override\n    public void close()\n    {\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#iterate()\n     */\n    @Override\n    public Iterator iterate()\n    {\n        EntityMetadata m = getEntityMetadata();\n        Client client = persistenceDelegeator.getClient(m);\n        return new ResultIterator((MongoDBClient) client, m,\n                createMongoQuery(m, getKunderaQuery().getFilterClauseQueue()), getOrderByClause(m),\n                getKeys(m, getKunderaQuery().getResult()), persistenceDelegeator,\n                getFetchSize() != null ? getFetchSize() : this.maxResult);\n    }\n\n    /**\n     * Gets the column name.\n     * \n     * @param metadata\n     *            the metadata\n     * @param entityType\n     *            the entity type\n     * @param property\n     *            the property\n     * @return the column name\n     */\n    private String getColumnName(EntityMetadata metadata, EntityType entityType, String property)\n    {\n        String columnName = null;\n\n        if (property.indexOf(\".\") > 0)\n        {\n            property = property.substring((kunderaQuery.getEntityAlias() + \".\").length());\n        }\n        try\n        {\n            columnName = ((AbstractAttribute) entityType.getAttribute(property)).getJPAColumnName();\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            log.warn(\"No column found by this name : \" + property + \" checking for embeddedfield\");\n        }\n        // where condition may be for search within embedded object\n        if (columnName == null && property.indexOf(\".\") > 0)\n        {\n            String enclosingEmbeddedField = MetadataUtils.getEnclosingEmbeddedFieldName(metadata, property, true,\n                    kunderaMetadata);\n            if (enclosingEmbeddedField != null)\n            {\n                columnName = property;\n            }\n        }\n\n        if (columnName == null)\n        {\n            log.error(\"No column found by this name : \" + property);\n            throw new JPQLParseException(\"No column found by this name : \" + property + \". Check your query.\");\n        }\n        return columnName;\n    }\n\n    /**\n     * Create regular expression equivalent to any like operator string match\n     * function.\n     * \n     * @param expr\n     *            the expr\n     * @param ignoreCase\n     *            whether to ignore the case\n     * @return the string\n     */\n    public static String createLikeRegex(String expr, boolean ignoreCase)\n    {\n        String regex = createRegex(expr, ignoreCase);\n        regex = regex.replace(\"_\", \".\").replace(\"%\", \".*?\");\n\n        return regex;\n    }\n\n    /**\n     * Generates the regular expression for matching string for like operator.\n     * \n     * @param value\n     *            the value\n     * @param ignoreCase\n     *            whether to ignore the case\n     * @return the string\n     */\n    public static String createRegex(String value, boolean ignoreCase)\n    {\n        if (value == null)\n        {\n            throw new IllegalArgumentException(\"String cannot be null\");\n        }\n\n        int len = value.length();\n        if (len == 0)\n        {\n            return \"\";\n        }\n\n        StringBuilder sb = new StringBuilder(len * 2);\n\n        if (ignoreCase)\n        {\n            sb.append(\"(?i)\");\n        }\n\n        sb.append(\"^\");\n\n        for (int i = 0; i < len; i++)\n        {\n            char c = value.charAt(i);\n            if (\"[](){}.*+?$^|#\\\\\".indexOf(c) != -1)\n            {\n                sb.append(\"\\\\\");\n            }\n            sb.append(c);\n        }\n        sb.append(\"$\");\n        return sb.toString();\n    }\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/query/ResultIterator.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.mongodb.query;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport com.impetus.client.mongodb.DefaultMongoDBDataHandler;\nimport com.impetus.client.mongodb.MongoDBClient;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.IResultIterator;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.mongodb.BasicDBObject;\nimport com.mongodb.DBCursor;\nimport com.mongodb.DBObject;\n\n/**\n * @author kuldeep.mishra .\n * \n *         Implementation of MongoDB result iteration.\n * \n * @param <E>\n */\nclass ResultIterator<E> implements IResultIterator<E>\n{\n    private DBCursor cursor;\n\n    private EntityMetadata m;\n\n    private MongoDBClient client;\n\n    private int fetchSize;\n\n    private DefaultMongoDBDataHandler handler;\n\n    private PersistenceDelegator persistenceDelegator;\n\n    ResultIterator(MongoDBClient client, EntityMetadata m, BasicDBObject basicDBObject, BasicDBObject orderByClause,\n            BasicDBObject keys, PersistenceDelegator pd, int fetchSize)\n    {\n        this.m = m;\n        this.client = client;\n        this.fetchSize = fetchSize;\n        this.persistenceDelegator = pd;\n        this.handler = new DefaultMongoDBDataHandler();\n        this.cursor = (DBCursor) client.getDBCursorInstance(basicDBObject, orderByClause, fetchSize, 0, keys,\n                m.getTableName(), false);\n    }\n\n    @Override\n    public boolean hasNext()\n    {\n        if (cursor != null && fetchSize != 0)\n        {\n            return cursor.hasNext();\n        }\n        return false;\n    }\n\n    @Override\n    public E next()\n    {\n        if (!cursor.hasNext() || fetchSize == 0)\n        {\n            throw new NoSuchElementException(\"Nothing to scroll further for:\" + m.getEntityClazz());\n        }\n        if (cursor.hasNext())\n        {\n            fetchSize--;\n            DBObject document = cursor.next();\n            E entityFromDocument = instantiateEntity(m.getEntityClazz(), null);\n            Map<String, Object> relationValue = null;\n            relationValue = handler.getEntityFromDocument(m.getEntityClazz(), entityFromDocument, m, document,\n                    m.getRelationNames(), relationValue, persistenceDelegator.getKunderaMetadata());\n\n            if (relationValue != null && !relationValue.isEmpty())\n            {\n                entityFromDocument = (E) new EnhanceEntity(entityFromDocument, PropertyAccessorHelper.getId(\n                        entityFromDocument, m), relationValue);\n            }\n\n            if (!m.isRelationViaJoinTable() && (m.getRelationNames() == null || (m.getRelationNames().isEmpty())))\n            {\n                return entityFromDocument;\n            }\n            else\n            {\n                List<EnhanceEntity> ls = new ArrayList<EnhanceEntity>();\n                ls.add((EnhanceEntity) entityFromDocument);\n                return setRelationEntities(ls.get(0), client, m);\n            }\n        }\n        return null;\n    }\n\n    /**\n     * \n     * @param entityClazz\n     * @param entity\n     * @return\n     */\n    private E instantiateEntity(Class<?> entityClazz, Object entity)\n    {\n        if (entity == null)\n        {\n            return (E) KunderaCoreUtils.createNewInstance(entityClazz);\n        }\n        return (E) entity;\n    }\n\n    @Override\n    public void remove()\n    {\n        throw new UnsupportedOperationException(\"Remove method is not supported over pagination\");\n    }\n\n    @Override\n    public List<E> next(int chunkSize)\n    {\n        throw new UnsupportedOperationException(\"Fetch in chunks is not yet supported\");\n    }\n\n    /**\n     * \n     * @param enhanceEntity\n     * @param client\n     * @param m\n     * @return\n     */\n    private E setRelationEntities(Object enhanceEntity, Client client, EntityMetadata m)\n    {\n        // Enhance entities can contain or may not contain relation.\n        // if it contain a relation means it is a child\n        // if it does not then it means it is a parent.\n        E result = null;\n        if (enhanceEntity != null)\n        {\n            if (!(enhanceEntity instanceof EnhanceEntity))\n            {\n                enhanceEntity = new EnhanceEntity(enhanceEntity, PropertyAccessorHelper.getId(enhanceEntity, m), null);\n            }\n            EnhanceEntity ee = (EnhanceEntity) enhanceEntity;\n\n            result = (E) client.getReader().recursivelyFindEntities(ee.getEntity(), ee.getRelations(), m,\n                    persistenceDelegator, false, new HashMap<Object, Object>());\n        }\n        return result;\n    }\n}"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/query/gfs/KunderaGridFS.java",
    "content": "/*******************************************************************************\n * * Copyright 2017 Impetus Infotech.\n * *\n * * Licensed under the Apache License, Version 2.0 (the \"License\");\n * * you may not use this file except in compliance with the License.\n * * You may obtain a copy of the License at\n * *\n * * http://www.apache.org/licenses/LICENSE-2.0\n * *\n * * Unless required by applicable law or agreed to in writing, software\n * * distributed under the License is distributed on an \"AS IS\" BASIS,\n * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * * See the License for the specific language governing permissions and\n * * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.mongodb.query.gfs;\n\nimport com.mongodb.AggregationOutput;\nimport com.mongodb.DB;\nimport com.mongodb.DBCursor;\nimport com.mongodb.DBObject;\nimport com.mongodb.gridfs.GridFS;\nimport com.mongodb.gridfs.GridFSDBFile;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * Extension over the native GridFS implementation to provide more efficient\n * queries with offsets and limits.\n */\npublic class KunderaGridFS extends GridFS\n{\n\n    /**\n     * Creates a GridFS instance for the default bucket \"fs\" in the given\n     * database. Set the preferred WriteConcern on the give DB with\n     * DB.setWriteConcern\n     * \n     * @param db\n     *            database to work with\n     * @see com.mongodb.WriteConcern\n     */\n    public KunderaGridFS(final DB db)\n    {\n        super(db);\n    }\n\n    /**\n     * Creates a GridFS instance for the specified bucket in the given database.\n     * Set the preferred WriteConcern on the give DB with DB.setWriteConcern\n     * \n     * @param db\n     *            database to work with\n     * @param bucket\n     *            bucket to use in the given database\n     * @see com.mongodb.WriteConcern\n     */\n    public KunderaGridFS(final DB db, final String bucket)\n    {\n        super(db, bucket);\n    }\n\n    /**\n     * Finds a list of files matching the given query.\n     * \n     * @param query\n     *            the filter to apply\n     * @param sort\n     *            the fields to sort with\n     * @param firstResult\n     *            number of files to skip\n     * @param maxResult\n     *            number of files to return\n     * @return list of gridfs files\n     */\n    public List<GridFSDBFile> find(final DBObject query, final DBObject sort, final int firstResult,\n            final int maxResult)\n    {\n        List<GridFSDBFile> files = new ArrayList<GridFSDBFile>();\n\n        DBCursor c = null;\n        try\n        {\n            c = getFilesCollection().find(query);\n            if (sort != null)\n            {\n                c.sort(sort);\n            }\n            c.skip(firstResult).limit(maxResult);\n            while (c.hasNext())\n            {\n                files.add(findOne(c.next()));\n            }\n        }\n        finally\n        {\n            if (c != null)\n            {\n                c.close();\n            }\n        }\n        return files;\n    }\n\n    /**\n     * MongoDB aggregation.\n     *\n     * @param pipeline\n     * @return\n     */\n    public AggregationOutput aggregate(List<DBObject> pipeline)\n    {\n        return getFilesCollection().aggregate(pipeline);\n    }\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/query/gis/CircleQueryImpl.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.mongodb.query.gis;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.impetus.kundera.gis.SurfaceType;\nimport com.impetus.kundera.gis.geometry.Circle;\nimport com.impetus.kundera.gis.query.GeospatialQuery;\nimport com.mongodb.BasicDBObject;\n\n/**\n * Provides methods for geospatial queries specific to circle shape\n * \n * @author amresh.singh\n */\npublic class CircleQueryImpl implements GeospatialQuery\n{\n    @Override\n    public Object createGeospatialQuery(String geolocationColumnName, Object shape, Object query)\n    {\n        Circle circle = (Circle) shape;\n        List circleList = new ArrayList();\n\n        circleList.add(new double[] { circle.getCentre().x, circle.getCentre().y }); // Centre\n                                                                                     // of\n                                                                                     // circle\n        circleList.add(circle.getRadius()); // Radius\n\n        BasicDBObject q = (BasicDBObject) query;\n\n        if (q == null)\n            q = new BasicDBObject();\n\n        if (circle.getSurfaceType().equals(SurfaceType.SPHERICAL))\n        {\n            q.put(geolocationColumnName, new BasicDBObject(\"$geoWithin\", new BasicDBObject(\"$centerSphere\", circleList)));\n        }\n        else\n        {\n            q.put(geolocationColumnName, new BasicDBObject(\"$geoWithin\", new BasicDBObject(\"$center\", circleList)));\n        }\n\n        return q;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/query/gis/EnvelopeQueryImpl.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.mongodb.query.gis;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.impetus.kundera.gis.geometry.Envelope;\nimport com.impetus.kundera.gis.query.GeospatialQuery;\nimport com.mongodb.BasicDBObject;\n\n/**\n * Provides methods for geospatial queries specific to box shape\n * \n * @author amresh.singh\n */\npublic class EnvelopeQueryImpl implements GeospatialQuery\n{\n\n    @Override\n    public Object createGeospatialQuery(String geolocationColumnName, Object shape, Object query)\n    {\n        List boxList = new ArrayList();\n\n        Envelope box = (Envelope) shape;\n\n        boxList.add(new double[] { box.getMinX(), box.getMinY() }); // Starting\n                                                                    // coordinate\n        boxList.add(new double[] { box.getMaxX(), box.getMaxY() }); // Ending\n                                                                    // coordinate\n\n        BasicDBObject q = (BasicDBObject) query;\n\n        if (q == null)\n            q = new BasicDBObject();\n\n        q.put(geolocationColumnName, new BasicDBObject(\"$geoWithin\", new BasicDBObject(\"$box\", boxList)));\n\n        return q;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/query/gis/GeospatialQueryFactory.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.mongodb.query.gis;\n\nimport com.impetus.kundera.gis.geometry.Circle;\nimport com.impetus.kundera.gis.geometry.Envelope;\nimport com.impetus.kundera.gis.geometry.Polygon;\nimport com.impetus.kundera.gis.geometry.Triangle;\nimport com.impetus.kundera.gis.query.GeospatialQuery;\nimport com.impetus.kundera.query.QueryHandlerException;\n\n/**\n * Factory for {@link GeospatialQuery}\n * \n * @author amresh.singh\n */\npublic class GeospatialQueryFactory\n{\n    public static GeospatialQuery getGeospatialQueryImplementor(String operator, Object shape)\n    {\n        if (operator.equalsIgnoreCase(\"in\"))\n        {\n            if (shape.getClass().isAssignableFrom(Circle.class))\n            {\n                return new CircleQueryImpl();\n            }\n            else if (shape.getClass().isAssignableFrom(Envelope.class))\n            {\n                return new EnvelopeQueryImpl();\n            }\n            else if (shape.getClass().isAssignableFrom(Triangle.class))\n            {\n                return new TriangleQueryImpl();\n            }\n            else if (shape.getClass().isAssignableFrom(Polygon.class))\n            {\n                return new PolygonQueryImpl();\n            }\n            else\n            {\n                throw new QueryHandlerException(\"Shape \" + shape.getClass() + \" is not supported\"\n                        + \" in JPA queries for operator \" + operator + \" in Kundera currently\");\n            }\n        }\n        else if (operator.equals(\">\") || operator.equals(\">=\") || operator.equals(\"<\") || operator.equals(\"<=\"))\n        {\n            return new NearQueryImpl();\n        }\n        else\n        {\n            throw new QueryHandlerException(\"Shape \" + shape.getClass() + \" is not supported\"\n                    + \" in JPA queries for operator \" + operator + \" in Kundera currently\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/query/gis/NearQueryImpl.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.mongodb.query.gis;\n\nimport com.impetus.kundera.gis.SurfaceType;\nimport com.impetus.kundera.gis.geometry.Point;\nimport com.impetus.kundera.gis.query.GeospatialQuery;\nimport com.mongodb.BasicDBObject;\n\n/**\n * <Prove description of functionality provided by this Type>\n * \n * @author amresh.singh\n */\npublic class NearQueryImpl implements GeospatialQuery\n{\n\n    @Override\n    public Object createGeospatialQuery(String geolocationColumnName, Object shape, Object query)\n    {\n        BasicDBObject q = (BasicDBObject) query;\n\n        if (q == null)\n            q = new BasicDBObject();\n\n        // Set point in query which is involved in near search\n        if (shape != null && shape.getClass().isAssignableFrom(Point.class))\n        {\n            Point point = (Point) shape;\n            BasicDBObject filter = (BasicDBObject) q.get(geolocationColumnName);\n\n            if (filter == null)\n                filter = new BasicDBObject();\n\n            if (point.getSurfaceType().equals(SurfaceType.SPHERICAL))\n            {\n                filter.put(\"$nearSphere\", new double[] { point.getX(), point.getY() });\n            }\n            else\n            {\n                filter.put(\"$near\", new double[] { point.getX(), point.getY() });\n            }\n\n            q.put(geolocationColumnName, filter);\n        }\n\n        // Set maximum distance from the given point\n        if (shape != null\n                && (shape.getClass().isAssignableFrom(Double.class) || shape.getClass().isAssignableFrom(double.class)))\n        {\n            Double maxDistance = (Double) shape;\n\n            BasicDBObject filter = (BasicDBObject) q.get(geolocationColumnName);\n\n            if (filter == null)\n                filter = new BasicDBObject();\n\n            filter.put(\"$maxDistance\", maxDistance);\n\n            q.put(geolocationColumnName, filter);\n        }\n\n        return q;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/query/gis/PolygonQueryImpl.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.mongodb.query.gis;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.impetus.kundera.gis.geometry.Coordinate;\nimport com.impetus.kundera.gis.geometry.Polygon;\nimport com.impetus.kundera.gis.query.GeospatialQuery;\nimport com.mongodb.BasicDBObject;\n\n/**\n * Provides methods for geospatial queries specific to polygon shape\n * \n * @author amresh.singh\n */\npublic class PolygonQueryImpl implements GeospatialQuery\n{\n    @Override\n    public Object createGeospatialQuery(String geolocationColumnName, Object shape, Object query)\n    {\n        List polygonList = new ArrayList();\n\n        Polygon polygon = (Polygon) shape;\n\n        for (Coordinate c : polygon.getCoordinates())\n        {\n            polygonList.add(new double[] { c.x, c.y });\n        }\n\n        BasicDBObject q = (BasicDBObject) query;\n\n        if (q == null)\n            q = new BasicDBObject();\n\n        q.put(geolocationColumnName, new BasicDBObject(\"$geoWithin\", new BasicDBObject(\"$polygon\", polygonList)));\n\n        return q;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/query/gis/TriangleQueryImpl.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.mongodb.query.gis;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.impetus.kundera.gis.geometry.Triangle;\nimport com.impetus.kundera.gis.query.GeospatialQuery;\nimport com.mongodb.BasicDBObject;\n\n/**\n * Provides methods for geospatial queries specific to triangle shape\n * \n * @author amresh.singh\n */\npublic class TriangleQueryImpl implements GeospatialQuery\n{\n\n    @Override\n    public Object createGeospatialQuery(String geolocationColumnName, Object shape, Object query)\n    {\n        List triangleList = new ArrayList();\n\n        Triangle triangle = (Triangle) shape;\n\n        triangleList.add(new double[] { triangle.p0.x, triangle.p0.y }); // A\n        triangleList.add(new double[] { triangle.p1.x, triangle.p1.y }); // B\n        triangleList.add(new double[] { triangle.p2.x, triangle.p2.y }); // C\n\n        BasicDBObject q = (BasicDBObject) query;\n\n        if (q == null)\n            q = new BasicDBObject();\n\n        q.put(geolocationColumnName, new BasicDBObject(\"$geoWithin\", new BasicDBObject(\"$polygon\", triangleList)));\n\n        return q;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/schemamanager/MongoDBSchemaManager.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.mongodb.schemamanager;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.mongodb.MongoDBConstants;\nimport com.impetus.client.mongodb.config.MongoDBPropertyReader;\nimport com.impetus.client.mongodb.index.IndexType;\nimport com.impetus.client.mongodb.utils.MongoDBUtils;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.configure.schema.ColumnInfo;\nimport com.impetus.kundera.configure.schema.EmbeddedColumnInfo;\nimport com.impetus.kundera.configure.schema.IndexInfo;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.configure.schema.TableInfo;\nimport com.impetus.kundera.configure.schema.api.AbstractSchemaManager;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.mongodb.BasicDBObject;\nimport com.mongodb.DB;\nimport com.mongodb.DBCollection;\nimport com.mongodb.DBObject;\nimport com.mongodb.MongoClient;\nimport com.mongodb.MongoCredential;\nimport com.mongodb.MongoException;\nimport com.mongodb.ServerAddress;\n\n/**\n * The Class MongoDBSchemaManager manages auto schema operation\n * {@code ScheamOperationType} for mongoDb database.\n * \n * @author Kuldeep.kumar\n * \n */\npublic class MongoDBSchemaManager extends AbstractSchemaManager implements SchemaManager\n{\n\n    /** The m. */\n    private MongoClient mongo;\n\n    /** The db. */\n    private DB db;\n\n    /** The coll. */\n    private DBCollection coll;\n\n    /** The Constant logger. */\n    private static final Logger logger = LoggerFactory.getLogger(MongoDBSchemaManager.class);\n\n    Logger mongoLogger = LoggerFactory.getLogger(com.mongodb.DB.class);\n\n    public MongoDBSchemaManager(String clientFactory, Map<String, Object> externalProperties,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(clientFactory, externalProperties, kunderaMetadata);\n    }\n\n    @Override\n    /**\n     * Export schema handles the handleOperation method.\n     */\n    public void exportSchema(final String persistenceUnit, List<TableInfo> schemas)\n    {\n        super.exportSchema(persistenceUnit, schemas);\n    }\n\n    /**\n     * drop schema method drop the table\n     */\n    public void dropSchema()\n    {\n        if (operation != null && operation.equalsIgnoreCase(\"create-drop\"))\n        {\n            for (TableInfo tableInfo : tableInfos)\n            {\n                if (tableInfo.getLobColumnInfo().isEmpty())\n                {\n                    coll = db.getCollection(tableInfo.getTableName());\n                    coll.drop();\n                    KunderaCoreUtils.printQuery(\"Drop collection:\" + tableInfo.getTableName(), showQuery);\n                }\n                else\n                {\n                    coll = db.getCollection(tableInfo.getTableName() + MongoDBUtils.FILES);\n                    coll.drop();\n                    KunderaCoreUtils.printQuery(\"Drop collection:\" + tableInfo.getTableName() + MongoDBUtils.FILES,\n                            showQuery);\n                    coll = db.getCollection(tableInfo.getTableName() + MongoDBUtils.CHUNKS);\n                    coll.drop();\n                    KunderaCoreUtils.printQuery(\"Drop collection:\" + tableInfo.getTableName() + MongoDBUtils.CHUNKS,\n                            showQuery);\n                }\n            }\n        }\n        db = null;\n    }\n\n    /**\n     * create method creates schema and table for the list of tableInfos.\n     * \n     * @param tableInfos\n     *            list of TableInfos.\n     */\n    protected void create(List<TableInfo> tableInfos)\n    {\n        for (TableInfo tableInfo : tableInfos)\n        {\n            DBObject options = setCollectionProperties(tableInfo);\n            DB db = mongo.getDB(databaseName);\n\n            if (tableInfo.getLobColumnInfo().isEmpty())\n            {\n                if (db.collectionExists(tableInfo.getTableName()))\n                {\n                    db.getCollection(tableInfo.getTableName()).drop();\n\n                    KunderaCoreUtils.printQuery(\"Drop existing collection: \" + tableInfo.getTableName(), showQuery);\n                }\n                DBCollection collection = db.createCollection(tableInfo.getTableName(), options);\n                KunderaCoreUtils.printQuery(\"Create collection: \" + tableInfo.getTableName(), showQuery);\n\n                boolean isCappedCollection = isCappedCollection(tableInfo);\n                if (!isCappedCollection)\n                {\n                    createIndexes(tableInfo, collection);\n                }\n            }\n            else\n            {\n                /*\n                 * In GridFS we have 2 collections. TABLE_NAME.chunks for\n                 * storing chunks of data and TABLE_NAME.MongoDBUtils.FILES for\n                 * storing it's metadata.\n                 */\n                checkMultipleLobs(tableInfo);\n                if (db.collectionExists(tableInfo.getTableName() + MongoDBUtils.FILES))\n                {\n                    db.getCollection(tableInfo.getTableName() + MongoDBUtils.FILES).drop();\n                    KunderaCoreUtils.printQuery(\n                            \"Drop existing Grid FS Metadata collection: \" + tableInfo.getTableName()\n                                    + MongoDBUtils.FILES, showQuery);\n                }\n\n                if (db.collectionExists(tableInfo.getTableName() + MongoDBUtils.CHUNKS))\n                {\n                    db.getCollection(tableInfo.getTableName() + MongoDBUtils.CHUNKS).drop();\n                    KunderaCoreUtils.printQuery(\"Drop existing Grid FS data collection: \" + tableInfo.getTableName()\n                            + MongoDBUtils.CHUNKS, showQuery);\n                }\n                coll = db.createCollection(tableInfo.getTableName() + MongoDBUtils.FILES, options);\n                createUniqueIndexGFS(coll, tableInfo.getIdColumnName());\n                KunderaCoreUtils.printQuery(\"Create collection: \" + tableInfo.getTableName() + MongoDBUtils.FILES,\n                        showQuery);\n                db.createCollection(tableInfo.getTableName() + MongoDBUtils.CHUNKS, options);\n                KunderaCoreUtils.printQuery(\"Create collection: \" + tableInfo.getTableName() + MongoDBUtils.CHUNKS,\n                        showQuery);\n\n            }\n        }\n    }\n\n    /**\n     * create_drop method creates schema and table for the list of tableInfos.\n     * \n     * @param tableInfos\n     *            list of TableInfos.\n     */\n    protected void create_drop(List<TableInfo> tableInfos)\n    {\n        create(tableInfos);\n    }\n\n    /**\n     * update method update schema and table for the list of tableInfos\n     * \n     * @param tableInfos\n     *            list of TableInfos.\n     */\n    protected void update(List<TableInfo> tableInfos)\n    {\n        for (TableInfo tableInfo : tableInfos)\n        {\n            DBObject options = setCollectionProperties(tableInfo);\n            DB db = mongo.getDB(databaseName);\n            DBCollection collection = null;\n            if (tableInfo.getLobColumnInfo().isEmpty())\n            {\n                if (!db.collectionExists(tableInfo.getTableName()))\n                {\n                    collection = db.createCollection(tableInfo.getTableName(), options);\n                    KunderaCoreUtils.printQuery(\"Create collection: \" + tableInfo.getTableName(), showQuery);\n                }\n\n                collection = collection != null ? collection : db.getCollection(tableInfo.getTableName());\n\n                boolean isCappedCollection = isCappedCollection(tableInfo);\n                if (!isCappedCollection)\n                {\n                    createIndexes(tableInfo, collection);\n                }\n            }\n            else\n            {\n                checkMultipleLobs(tableInfo);\n                if (!db.collectionExists(tableInfo.getTableName() + MongoDBUtils.FILES))\n                {\n                    coll = db.createCollection(tableInfo.getTableName() + MongoDBUtils.FILES, options);\n                    createUniqueIndexGFS(coll, tableInfo.getIdColumnName());\n                    KunderaCoreUtils.printQuery(\"Create collection: \" + tableInfo.getTableName() + MongoDBUtils.FILES,\n                            showQuery);\n                }\n\n                if (!db.collectionExists(tableInfo.getTableName() + MongoDBUtils.CHUNKS))\n                {\n                    db.createCollection(tableInfo.getTableName() + MongoDBUtils.CHUNKS, options);\n                    KunderaCoreUtils.printQuery(\"Create collection: \" + tableInfo.getTableName() + MongoDBUtils.CHUNKS,\n                            showQuery);\n                }\n            }\n        }\n    }\n\n    /**\n     * validate method validate schema and table for the list of tableInfos.\n     * \n     * @param tableInfos\n     *            list of TableInfos.\n     */\n    protected void validate(List<TableInfo> tableInfos)\n    {\n        db = mongo.getDB(databaseName);\n        if (db == null)\n        {\n            logger.error(\"Database \" + databaseName + \"does not exist\");\n            throw new SchemaGenerationException(\"database \" + databaseName + \"does not exist\", \"mongoDb\", databaseName);\n        }\n        else\n        {\n            for (TableInfo tableInfo : tableInfos)\n            {\n                if (tableInfo.getLobColumnInfo().isEmpty())\n                {\n                    if (!db.collectionExists(tableInfo.getTableName()))\n                    {\n                        logger.error(\"Collection \" + tableInfo.getTableName() + \"does not exist in db \" + db.getName());\n                        throw new SchemaGenerationException(\"Collection \" + tableInfo.getTableName()\n                                + \" does not exist in db \" + db.getName(), \"mongoDb\", databaseName,\n                                tableInfo.getTableName());\n                    }\n                }\n                else\n                {\n                    checkMultipleLobs(tableInfo);\n                    if (!db.collectionExists(tableInfo.getTableName() + MongoDBUtils.FILES))\n                    {\n                        logger.error(\"Collection \" + tableInfo.getTableName() + MongoDBUtils.FILES\n                                + \"does not exist in db \" + db.getName());\n                        throw new SchemaGenerationException(\"Collection \" + tableInfo.getTableName()\n                                + \" does not exist in db \" + db.getName(), \"mongoDb\", databaseName,\n                                tableInfo.getTableName());\n                    }\n                    if (!db.collectionExists(tableInfo.getTableName() + MongoDBUtils.CHUNKS))\n                    {\n                        logger.error(\"Collection \" + tableInfo.getTableName() + MongoDBUtils.CHUNKS\n                                + \"does not exist in db \" + db.getName());\n                        throw new SchemaGenerationException(\"Collection \" + tableInfo.getTableName()\n                                + \" does not exist in db \" + db.getName(), \"mongoDb\", databaseName,\n                                tableInfo.getTableName());\n                    }\n\n                }\n            }\n        }\n    }\n\n    /**\n     * initiate client method initiates the client.\n     * \n     * @return boolean value ie client started or not.\n     * \n     */\n    protected boolean initiateClient()\n    {\n        for (String host : hosts)\n        {\n            if (host == null || !StringUtils.isNumeric(port) || port.isEmpty())\n            {\n                logger.error(\"Host or port should not be null / port should be numeric\");\n                throw new IllegalArgumentException(\"Host or port should not be null / port should be numeric\");\n            }\n\n            List<MongoCredential> credentials = MongoDBUtils.fetchCredentials(puMetadata.getProperties(),\n                    externalProperties);\n            ServerAddress addr;\n            try\n            {\n                addr = new ServerAddress(host, Integer.parseInt(port));\n            }\n            catch (NumberFormatException ex)\n            {\n                throw new SchemaGenerationException(ex);\n            }\n\n            mongo = new MongoClient(addr, credentials);\n            db = mongo.getDB(databaseName);\n            return true;\n        }\n        return false;\n    }\n\n    /**\n     * @param tableInfo\n     * @return\n     */\n    private DBObject setCollectionProperties(TableInfo tableInfo)\n    {\n        boolean isCappedCollection = isCappedCollection(tableInfo);\n        DBObject options = new BasicDBObject();\n        if ((tableInfo.getLobColumnInfo().isEmpty() || tableInfo.getLobColumnInfo() == null) && isCappedCollection)\n        {\n            int collectionSize = MongoDBPropertyReader.msmd != null ? MongoDBPropertyReader.msmd.getCollectionSize(\n                    databaseName, tableInfo.getTableName()) : 100000;\n            int max = MongoDBPropertyReader.msmd != null ? MongoDBPropertyReader.msmd.getMaxSize(databaseName,\n                    tableInfo.getTableName()) : 100;\n            options.put(MongoDBConstants.CAPPED, isCappedCollection);\n            options.put(MongoDBConstants.SIZE, collectionSize);\n            options.put(MongoDBConstants.MAX, max);\n        }\n        return options;\n    }\n\n    /**\n     * Checks whether the given table is a capped collection\n     */\n    protected boolean isCappedCollection(TableInfo tableInfo)\n    {\n        return MongoDBPropertyReader.msmd != null ? MongoDBPropertyReader.msmd.isCappedCollection(databaseName,\n                tableInfo.getTableName()) : false;\n    }\n\n    /**\n     * @param tableInfo\n     * @param collection\n     */\n    private void createIndexes(TableInfo tableInfo, DBCollection collection)\n    {\n        // index normal column\n        for (ColumnInfo columnInfo : tableInfo.getColumnMetadatas())\n        {\n            if (columnInfo.isIndexable())\n            {\n                IndexInfo indexInfo = tableInfo.getColumnToBeIndexed(columnInfo.getColumnName());\n                indexColumn(indexInfo, collection);\n            }\n        }\n\n        // index embedded column.\n        for (EmbeddedColumnInfo info : tableInfo.getEmbeddedColumnMetadatas())\n        {\n            for (ColumnInfo columnInfo : info.getColumns())\n            {\n                if (columnInfo.isIndexable())\n                {\n                    IndexInfo indexInfo = tableInfo.getColumnToBeIndexed(columnInfo.getColumnName());\n                    indexEmbeddedColumn(indexInfo, info.getEmbeddedColumnName(), collection);\n                }\n            }\n        }\n    }\n\n    private void indexColumn(IndexInfo indexInfo, DBCollection collection)\n    {\n        DBObject keys = new BasicDBObject();\n        getIndexType(indexInfo.getIndexType(), keys, indexInfo.getColumnName());\n        DBObject options = new BasicDBObject();\n        if (indexInfo.getMinValue() != null)\n        {\n            options.put(MongoDBConstants.MIN, indexInfo.getMinValue());\n        }\n        if (indexInfo.getMaxValue() != null)\n        {\n            options.put(MongoDBConstants.MAX, indexInfo.getMaxValue());\n        }\n\n        if (indexInfo.getIndexType() != null && (indexInfo.getIndexType().toLowerCase()).equals(\"unique\"))\n        {\n            options.put(\"unique\", true);\n        }\n        collection.createIndex(keys, options);\n        KunderaCoreUtils.printQuery(\"Create indexes on:\" + keys, showQuery);\n    }\n\n    private void indexEmbeddedColumn(IndexInfo indexInfo, String embeddedColumnName, DBCollection collection)\n    {\n        DBObject keys = new BasicDBObject();\n        getIndexType(indexInfo.getIndexType(), keys, embeddedColumnName + \".\" + indexInfo.getColumnName());\n        DBObject options = new BasicDBObject();\n        if (indexInfo.getMinValue() != null)\n        {\n            options.put(MongoDBConstants.MIN, indexInfo.getMinValue());\n        }\n        if (indexInfo.getMaxValue() != null)\n        {\n            options.put(MongoDBConstants.MAX, indexInfo.getMaxValue());\n        }\n        collection.createIndex(keys, options);\n        KunderaCoreUtils.printQuery(\"Create indexes on:\" + keys, showQuery);\n    }\n\n    /**\n     * @param indexType\n     * @param clazz\n     * @return\n     */\n    private void getIndexType(String indexType, DBObject keys, String columnName)\n    {\n        // TODO validation for indexType and attribute type\n\n        if (indexType != null)\n        {\n            if (indexType.equals(IndexType.ASC.name()))\n            {\n                keys.put(columnName, 1);\n                return;\n            }\n            else if (indexType.equals(IndexType.DSC.name()))\n            {\n                keys.put(columnName, -1);\n                return;\n            }\n            else if (indexType.equals(IndexType.GEO2D.name()))\n            {\n                keys.put(columnName, \"2d\");\n                return;\n            }\n        }\n        keys.put(columnName, 1);\n        return;\n    }\n\n    private void checkMultipleLobs(TableInfo tableInfo)\n    {\n        if (tableInfo.getLobColumnInfo().size() > 1)\n            throw new KunderaException(\"Multiple Lob fields in a single Entity are not supported in Kundera\");\n    }\n\n    private void createUniqueIndexGFS(DBCollection coll, String id)\n    {\n        try\n        {\n            coll.createIndex(new BasicDBObject(\"metadata.\" + id, 1), new BasicDBObject(\"unique\", true));\n        }\n        catch (MongoException ex)\n        {\n            throw new KunderaException(\"Error in creating unique indexes in \" + coll.getFullName() + \" collection on \"\n                    + id + \" field\");\n        }\n    }\n\n    @Override\n    public boolean validateEntity(Class clazz)\n    {\n        return true;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/main/java/com/impetus/client/mongodb/utils/MongoDBUtils.java",
    "content": "/**\n * \n */\npackage com.impetus.client.mongodb.utils;\n\nimport java.lang.reflect.Field;\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\nimport java.sql.Date;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.GregorianCalendar;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport javax.persistence.Embedded;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.xml.bind.DatatypeConverter;\n\nimport org.eclipse.persistence.jpa.jpql.parser.CollectionExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.StringLiteral;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.loader.ClientLoaderException;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.ReflectUtils;\nimport com.mongodb.BasicDBObject;\nimport com.mongodb.DBObject;\nimport com.mongodb.MongoCredential;\n\n/**\n * The Class MongoDBUtils.\n * \n * @author Kuldeep Mishra\n */\npublic class MongoDBUtils\n{\n    /** The Constant logger. */\n    private static final Logger logger = LoggerFactory.getLogger(MongoDBUtils.class);\n\n    /** The Constant METADATA. */\n    public static final String METADATA = \"metadata\";\n\n    /** The Constant FILES. */\n    public static final String FILES = \".files\";\n\n    /** The Constant CHUNKS. */\n    public static final String CHUNKS = \".chunks\";\n\n    /**\n     * Populate compound key.\n     * \n     * @param dbObj\n     *            the db obj\n     * @param m\n     *            the m\n     * @param metaModel\n     *            the meta model\n     * @param id\n     *            the id\n     */\n    public static void populateCompoundKey(DBObject dbObj, EntityMetadata m, MetamodelImpl metaModel, Object id)\n    {\n        EmbeddableType compoundKey = metaModel.embeddable(m.getIdAttribute().getBindableJavaType());\n        // Iterator<Attribute> iter = compoundKey.getAttributes().iterator();\n        BasicDBObject compoundKeyObj = new BasicDBObject();\n\n        compoundKeyObj = getCompoundKeyColumns(m, id, compoundKey, metaModel);\n\n        dbObj.put(\"_id\", compoundKeyObj);\n    }\n\n    /**\n     * Gets the compound key columns.\n     * \n     * @param m\n     *            the m\n     * @param id\n     *            the id\n     * @param compoundKey\n     *            the compound key\n     * @param metaModel\n     * @return the compound key columns\n     */\n    public static BasicDBObject getCompoundKeyColumns(EntityMetadata m, Object id, EmbeddableType compoundKey,\n            MetamodelImpl metaModel)\n    {\n        BasicDBObject compoundKeyObj = new BasicDBObject();\n\n        Set<Attribute> attribs = compoundKey.getDeclaredAttributes();\n\n        Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields();\n\n        // To ensure order.\n        for (Attribute attr : attribs)\n        {\n            Field f = (Field) attr.getJavaMember();\n            if (!ReflectUtils.isTransientOrStatic(f))\n            {\n                if (f.getAnnotation(Embedded.class) != null)\n                {\n                    EmbeddableType emb = metaModel.embeddable(f.getType());\n                    Object val = PropertyAccessorHelper.getObject(id, f);\n                    BasicDBObject dbVal = getCompoundKeyColumns(m, val, emb, metaModel);\n                    compoundKeyObj.put(((AbstractAttribute) attr).getJPAColumnName(), dbVal);\n                }\n                else\n                {\n                    compoundKeyObj.put(\n                            ((AbstractAttribute) attr).getJPAColumnName(),\n                            populateValue(PropertyAccessorHelper.getObject(id, (Field) attr.getJavaMember()),\n                                    ((AbstractAttribute) attr).getBindableJavaType()));\n\n                }\n            }\n        }\n        return compoundKeyObj;\n    }\n\n    /**\n     * Populate value.\n     * \n     * @param valObj\n     *            the val obj\n     * @param clazz\n     *            the clazz\n     * @return the object\n     */\n    public static Object populateValue(Object valObj, Class clazz)\n    {\n        if (isUTF8Value(clazz) || clazz.isEnum())\n        {\n            return valObj.toString();\n        }\n        else if ((valObj instanceof Calendar) || (valObj instanceof GregorianCalendar))\n        {\n            return ((Calendar) valObj).getTime();\n        }\n        else if (CollectionExpression.class.isAssignableFrom(clazz))\n        {\n            CollectionExpression collExpr = (CollectionExpression) valObj;\n            List<String> texts = new ArrayList<String>(collExpr.childrenSize());\n\n            for (Expression childExpr : collExpr.orderedChildren())\n            {\n                if (childExpr instanceof StringLiteral)\n                {\n                    StringLiteral stringLiteral = (StringLiteral) childExpr;\n                    texts.add(stringLiteral.getUnquotedText());\n                }\n            }\n\n            return texts;\n        }\n        return valObj;\n    }\n\n    /**\n     * Checks if is UT f8 value.\n     * \n     * @param clazz\n     *            the clazz\n     * @return true, if is UT f8 value\n     */\n    private static boolean isUTF8Value(Class<?> clazz)\n    {\n        return (clazz.isAssignableFrom(BigDecimal.class))\n                || (clazz.isAssignableFrom(BigInteger.class) || (clazz.isAssignableFrom(String.class))\n                        || (clazz.isAssignableFrom(char.class)) || (clazz.isAssignableFrom(Character.class)));\n    }\n\n    /**\n     * Gets the translated object.\n     * \n     * @param value\n     *            the value\n     * @param sourceClass\n     *            the source class\n     * @param targetClass\n     *            the target class\n     * @return the translated object\n     */\n    public static Object getTranslatedObject(Object value, Class<?> sourceClass, Class<?> targetClass)\n    {\n        if (sourceClass.isAssignableFrom(Date.class))\n        {\n            value = PropertyAccessorHelper.fromDate(targetClass, sourceClass, value);\n        }\n        else\n        {\n            value = PropertyAccessorHelper.fromSourceToTargetClass(targetClass, sourceClass, value);\n        }\n        return value;\n    }\n\n    /**\n     * Gets the DB object.\n     * \n     * @param m\n     *            the m\n     * @param tableName\n     *            the table name\n     * @param dbObjects\n     *            the db objects\n     * @param metaModel\n     *            the meta model\n     * @param id\n     *            the id\n     * @return the DB object\n     */\n    public static DBObject getDBObject(EntityMetadata m, String tableName, Map<String, DBObject> dbObjects,\n            MetamodelImpl metaModel, Object id)\n    {\n        tableName = tableName != null ? tableName : m.getTableName();\n        DBObject dbObj = dbObjects.get(tableName);\n        if (dbObj == null)\n        {\n            dbObj = new BasicDBObject();\n            dbObjects.put(tableName, dbObj);\n        }\n\n        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n        {\n            MongoDBUtils.populateCompoundKey(dbObj, m, metaModel, id);\n        }\n        else\n        {\n            dbObj.put(\"_id\", MongoDBUtils.populateValue(id, id.getClass()));\n        }\n        return dbObj;\n    }\n\n    /**\n     * Calculate m d5.\n     * \n     * @param val\n     *            the val\n     * @return the string\n     */\n    public static String calculateMD5(Object val)\n    {\n        MessageDigest md = null;\n        try\n        {\n            md = MessageDigest.getInstance(\"MD5\");\n        }\n        catch (NoSuchAlgorithmException e)\n        {\n            logger.error(\"Unable to calculate MD5 for file, Caused By: \", e);\n        }\n        md.update((byte[]) val);\n\n        byte[] digest = md.digest();\n        return DatatypeConverter.printHexBinary(digest).toLowerCase();\n    }\n\n    /**\n     * @param props\n     * @param externalProperties\n     * @return List of MongoCredential\n     */\n    public static List<MongoCredential> fetchCredentials(Properties props, Map<String, Object> externalProperties)\n    {\n        String password = null;\n        String userName = null;\n        String keyspace = null;\n        if (externalProperties != null)\n        {\n            userName = (String) externalProperties.get(PersistenceProperties.KUNDERA_USERNAME);\n            password = (String) externalProperties.get(PersistenceProperties.KUNDERA_PASSWORD);\n            keyspace = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);\n        }\n        if (userName == null)\n        {\n            userName = (String) props.get(PersistenceProperties.KUNDERA_USERNAME);\n        }\n        if (password == null)\n        {\n            password = (String) props.get(PersistenceProperties.KUNDERA_PASSWORD);\n        }\n        if (keyspace == null)\n        {\n            keyspace = (String) props.get(PersistenceProperties.KUNDERA_KEYSPACE);\n        }\n\n        List<MongoCredential> credentials = new ArrayList<>();\n        if (userName != null && password != null)\n        {\n            MongoCredential credential = MongoCredential.createCredential(userName, keyspace, password.toCharArray());\n            credentials.add(credential);\n            return credentials;\n        }\n        else if (userName == null && password == null)\n        {\n            return credentials;\n        }\n        else\n        {\n            String errMsg = \"Invalid configuration provided for authentication, please specify both non-nullable\"\n                    + \" 'kundera.username' and 'kundera.password' properties\";\n            throw new ClientLoaderException(errMsg);\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/AddressMTM.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class AddressMTM.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"ADDRESS_MTM\", schema = \"KunderaExamples\")\npublic class AddressMTM\n{\n\n    /** The address id. */\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The street. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * Gets the address id.\n     * \n     * @return the address id\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * Sets the address id.\n     * \n     * @param addressId\n     *            the new address id\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * Gets the street.\n     * \n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * Sets the street.\n     * \n     * @param street\n     *            the new street\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/AddressMongoMTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"AddressMongoMTO\", schema = \"KunderaExamples@mongoTest\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressMongoMTO\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/ArticleGFSTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Arrays;\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.ArticleGFS;\nimport com.impetus.client.utils.MongoUtils;\nimport com.impetus.kundera.KunderaException;\n\n/**\n * The Class ArticleGFSTest.\n */\npublic class ArticleGFSTest\n{\n\n    /** The Constant _PU. */\n    private static final String _PU = \"mongoTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * @throws Exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testComplexQueries()\n    {\n        prepareArticle(\"article1\", date(\"2017-01-05 10:00\"), date(\"2017-01-05 10:00\"), \"First article\", \"important\", 0,\n                true);\n        prepareArticle(\"article2\", date(\"2017-01-15 10:00\"), date(\"2017-01-15 10:00\"), \"Second article\", null, 0, true);\n        prepareArticle(\"article3\", date(\"2017-01-25 10:00\"), date(\"2017-01-25 10:00\"), \"Third article\", \"important\", 0,\n                true);\n        prepareArticle(\"article4\", date(\"2017-01-30 10:00\"), null, \"Fourth article\", \"important\", 0, true);\n        prepareArticle(\"article5\", date(\"2017-02-05 10:00\"), date(\"2017-02-55 10:00\"), \"Fifth article\", null, 0, true);\n\n        Query query = em.createQuery(\"select a from ArticleGFS a where a.show = :show and \"\n                + \"(a.displayDate is null or a.displayDate < :date1 or a.displayDate > :date2) \"\n                + \"order by a.createDate asc\");\n        query.setParameter(\"show\", true);\n        query.setParameter(\"date1\", date(\"2017-01-20 00:00\"));\n        query.setParameter(\"date2\", date(\"2017-02-01 00:00\"));\n        List<ArticleGFS> results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        Assert.assertEquals(\"First article\", results.get(0).getTitle());\n        Assert.assertEquals(\"Second article\", results.get(1).getTitle());\n        Assert.assertEquals(\"Fourth article\", results.get(2).getTitle());\n        Assert.assertEquals(\"Fifth article\", results.get(3).getTitle());\n\n        query = em.createQuery(\"select a from ArticleGFS a where a.show = :show and \"\n                + \"(a.displayDate is null or a.displayDate < :date1 or a.displayDate > :date2 and a.category is null) \"\n                + \"order by a.createDate asc\");\n        query.setParameter(\"show\", true);\n        query.setParameter(\"date1\", date(\"2017-01-20 00:00\"));\n        query.setParameter(\"date2\", date(\"2017-02-01 00:00\"));\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        Assert.assertEquals(\"First article\", results.get(0).getTitle());\n        Assert.assertEquals(\"Second article\", results.get(1).getTitle());\n        Assert.assertEquals(\"Fourth article\", results.get(2).getTitle());\n        Assert.assertEquals(\"Fifth article\", results.get(3).getTitle());\n\n        query = em.createQuery(\"select a from ArticleGFS a where a.show = :show and \"\n                + \"(a.displayDate > :date2 and a.category is null or a.displayDate is null or a.displayDate < :date1) \"\n                + \"order by a.createDate asc\");\n        query.setParameter(\"show\", true);\n        query.setParameter(\"date1\", date(\"2017-01-20 00:00\"));\n        query.setParameter(\"date2\", date(\"2017-02-01 00:00\"));\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        Assert.assertEquals(\"First article\", results.get(0).getTitle());\n        Assert.assertEquals(\"Second article\", results.get(1).getTitle());\n        Assert.assertEquals(\"Fourth article\", results.get(2).getTitle());\n        Assert.assertEquals(\"Fifth article\", results.get(3).getTitle());\n\n        query = em\n                .createQuery(\"select a from ArticleGFS a where a.show = :show and \"\n                        + \"(a.category is null and (a.displayDate > :date2 or a.displayDate is null or a.displayDate < :date1)) \"\n                        + \"order by a.createDate asc\");\n        query.setParameter(\"show\", true);\n        query.setParameter(\"date1\", date(\"2017-01-20 00:00\"));\n        query.setParameter(\"date2\", date(\"2017-02-01 00:00\"));\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(\"Second article\", results.get(0).getTitle());\n        Assert.assertEquals(\"Fifth article\", results.get(1).getTitle());\n\n        query = em.createQuery(\"select a from ArticleGFS a where a.show = :show and \"\n                + \"(a.createDate < :date and (a.displayDate is null or a.displayDate < :date)) \"\n                + \"and a.category = :category \" + \"order by a.createDate asc\");\n        query.setParameter(\"show\", true);\n        query.setParameter(\"date\", date(\"2017-03-30 00:00\"));\n        query.setParameter(\"category\", \"important\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(\"First article\", results.get(0).getTitle());\n        Assert.assertEquals(\"Third article\", results.get(1).getTitle());\n        Assert.assertEquals(\"Fourth article\", results.get(2).getTitle());\n    }\n\n    @Test(expected = Exception.class)\n    public void testAggregation()\n    {\n        prepareArticle(\"article1\", date(\"2017-01-05 10:00\"), null, \"First article\", \"A\", 1, true);\n        prepareArticle(\"article2\", date(\"2017-01-15 10:00\"), null, \"Second article\", \"B\", 3, true);\n        prepareArticle(\"article3\", date(\"2017-01-25 10:00\"), null, \"Third article\", \"A\", 6, true);\n\n        Query query = em.createQuery(\"select max(a.priority) from ArticleGFS a\");\n        List<?> results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(6, results.get(0));\n\n        query = em.createQuery(\"select max(a.priority), min(a.priority) from ArticleGFS a\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        Object[] resultArray = (Object[]) results.get(0);\n        Assert.assertEquals(\"Results: \" + Arrays.toString(resultArray), 2, resultArray.length);\n        Assert.assertEquals(6, resultArray[0]);\n        Assert.assertEquals(1, resultArray[1]);\n\n        query = em\n                .createQuery(\"select avg(a.priority), sum(a.priority), max(a.priority), min(a.priority) from ArticleGFS a\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        resultArray = (Object[]) results.get(0);\n        Assert.assertEquals(\"Results: \" + Arrays.toString(resultArray), 4, resultArray.length);\n        assertAlmostEqual(3.3333, resultArray[0]);\n        Assert.assertEquals(10, resultArray[1]);\n        Assert.assertEquals(6, resultArray[2]);\n        Assert.assertEquals(1, resultArray[3]);\n\n        query = em\n                .createQuery(\"select sum(a.priority), a.category from ArticleGFS a group by a.category order by a.category\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(\"A\", ((Object[]) results.get(0))[1]);\n        Assert.assertEquals(\"B\", ((Object[]) results.get(1))[1]);\n\n        for (Object item : results)\n        {\n            resultArray = (Object[]) item;\n            Assert.assertEquals(\"Result Item: \" + Arrays.toString(resultArray), 2, resultArray.length);\n            Assert.assertTrue(Arrays.asList(\"A\", \"B\").contains(resultArray[1]));\n\n            if (resultArray[1].equals(\"A\"))\n            {\n                Assert.assertEquals(7, resultArray[0]);\n            }\n            else if (resultArray[1].equals(\"B\"))\n            {\n                Assert.assertEquals(3, resultArray[0]);\n            }\n        }\n\n        query = em\n                .createQuery(\"select sum(a.priority), a.category, avg(a.priority), min(a.priority) from ArticleGFS a group by a.category\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertSumsMatch(results, 4);\n\n        query = em\n                .createQuery(\"select sum(a.priority), a.category from ArticleGFS a group by a.category order by sum(a.priority) desc\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(\"A\", ((Object[]) results.get(0))[1]);\n        Assert.assertEquals(\"B\", ((Object[]) results.get(1))[1]);\n        assertSumsMatch(results, 2);\n    }\n\n    @Test(expected = Exception.class)\n    public void testCountAggregation()\n    {\n        prepareArticle(\"article1\", date(\"2017-01-05 10:00\"), null, \"First article\", \"A\", 1, true);\n        prepareArticle(\"article2\", date(\"2017-01-15 10:00\"), null, \"Second article\", \"B\", 3, true);\n        prepareArticle(\"article3\", date(\"2017-01-25 10:00\"), null, \"Third article\", \"A\", 6, true);\n\n        Query query = em\n                .createQuery(\"select sum(a.priority), count(a), a.category from ArticleGFS a group by a.category order by a.category\");\n        List results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(2L, ((Object[]) results.get(0))[1]);\n        Assert.assertEquals(1L, ((Object[]) results.get(1))[1]);\n\n        query = em.createQuery(\"select count(a) from ArticleGFS a\");\n        Object result = query.getSingleResult();\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(3L, result);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * @throws Exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        MongoUtils.dropDatabase(emf, _PU);\n        emf.close();\n    }\n\n    private void assertAlmostEqual(double expected, Object actual)\n    {\n        double value = (double) actual;\n        Assert.assertTrue(\n                String.format(\"%.4f != %.4f\\nExpected: %.4f\\nActual  : %.4f\", expected, value, expected, value),\n                Math.abs(value - expected) < 0.0001);\n    }\n\n    private void assertSumsMatch(List results, int expectedNumberOfItems)\n    {\n        for (Object item : results)\n        {\n            Object[] resultArray = (Object[]) item;\n            Assert.assertEquals(\"Result Item: \" + Arrays.toString(resultArray), expectedNumberOfItems,\n                    resultArray.length);\n            Assert.assertTrue(Arrays.asList(\"A\", \"B\").contains(resultArray[1]));\n\n            if (resultArray[1].equals(\"A\"))\n            {\n                Assert.assertEquals(7, resultArray[0]);\n            }\n            else if (resultArray[1].equals(\"B\"))\n            {\n                Assert.assertEquals(3, resultArray[0]);\n            }\n        }\n    }\n\n    private void prepareArticle(String id, Date createDate, Date displayDate, String title, String category,\n            int priority, boolean show)\n    {\n        ArticleGFS item = new ArticleGFS();\n        item.setArticleId(id);\n        item.setCreateDate(createDate);\n        item.setDisplayDate(displayDate);\n        item.setTitle(title);\n        item.setCategory(category);\n        item.setPriority(priority);\n        item.setShow(show);\n        item.setData(\"TestData\".getBytes());\n        em.persist(item);\n    }\n\n    private static Date date(String value)\n    {\n        SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");\n        try\n        {\n            return format.parse(value);\n        }\n        catch (ParseException ex)\n        {\n            throw new AssertionError(\"Invalid date: \" + value, ex);\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/ArticleMongoTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport com.impetus.client.crud.entities.ArticleDetails;\nimport com.impetus.client.crud.entities.ArticleMTO;\nimport com.impetus.client.crud.entities.ArticleMongo;\nimport com.impetus.client.utils.MongoUtils;\nimport junit.framework.Assert;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.List;\n\n/**\n * The Class ArticleMongoTest.\n */\npublic class ArticleMongoTest\n{\n\n    /** The Constant _PU. */\n    private static final String _PU = \"mongoTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(_PU);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        MongoUtils.dropDatabase(emf, _PU);\n        emf.close();\n    }\n\n    @Test\n    public void testComplexQueries()\n    {\n        prepareArticle(\"article1\", date(\"2017-01-05 10:00\"), date(\"2017-01-05 10:00\"), \"First article\", \"important\", 0,\n                true);\n        prepareArticle(\"article2\", date(\"2017-01-15 10:00\"), date(\"2017-01-15 10:00\"), \"Second article\", null, 0, true);\n        prepareArticle(\"article3\", date(\"2017-01-25 10:00\"), date(\"2017-01-25 10:00\"), \"Third article\", \"important\", 0,\n                true);\n        prepareArticle(\"article4\", date(\"2017-01-30 10:00\"), null, \"Fourth article\", \"important\", 0, true);\n        prepareArticle(\"article5\", date(\"2017-02-05 10:00\"), date(\"2017-02-55 10:00\"), \"Fifth article\", null, 0, true);\n\n        Query query = em.createQuery(\"select a from ArticleMongo a where a.show = :show and \"\n                + \"(a.displayDate is null or a.displayDate < :date1 or a.displayDate > :date2) \"\n                + \"order by a.createDate asc\");\n        query.setParameter(\"show\", true);\n        query.setParameter(\"date1\", date(\"2017-01-20 00:00\"));\n        query.setParameter(\"date2\", date(\"2017-02-01 00:00\"));\n        List<ArticleMongo> results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        Assert.assertEquals(\"First article\", results.get(0).getTitle());\n        Assert.assertEquals(\"Second article\", results.get(1).getTitle());\n        Assert.assertEquals(\"Fourth article\", results.get(2).getTitle());\n        Assert.assertEquals(\"Fifth article\", results.get(3).getTitle());\n\n        query = em.createQuery(\"select a from ArticleMongo a where a.show = :show and \"\n                + \"(a.displayDate is null or a.displayDate < :date1 or a.displayDate > :date2 and a.category is null) \"\n                + \"order by a.createDate asc\");\n        query.setParameter(\"show\", true);\n        query.setParameter(\"date1\", date(\"2017-01-20 00:00\"));\n        query.setParameter(\"date2\", date(\"2017-02-01 00:00\"));\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        Assert.assertEquals(\"First article\", results.get(0).getTitle());\n        Assert.assertEquals(\"Second article\", results.get(1).getTitle());\n        Assert.assertEquals(\"Fourth article\", results.get(2).getTitle());\n        Assert.assertEquals(\"Fifth article\", results.get(3).getTitle());\n\n        query = em.createQuery(\"select a from ArticleMongo a where a.show = :show and \"\n                + \"(a.displayDate > :date2 and a.category is null or a.displayDate is null or a.displayDate < :date1) \"\n                + \"order by a.createDate asc\");\n        query.setParameter(\"show\", true);\n        query.setParameter(\"date1\", date(\"2017-01-20 00:00\"));\n        query.setParameter(\"date2\", date(\"2017-02-01 00:00\"));\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        Assert.assertEquals(\"First article\", results.get(0).getTitle());\n        Assert.assertEquals(\"Second article\", results.get(1).getTitle());\n        Assert.assertEquals(\"Fourth article\", results.get(2).getTitle());\n        Assert.assertEquals(\"Fifth article\", results.get(3).getTitle());\n\n        query = em\n                .createQuery(\"select a from ArticleMongo a where a.show = :show and \"\n                        + \"(a.category is null and (a.displayDate > :date2 or a.displayDate is null or a.displayDate < :date1)) \"\n                        + \"order by a.createDate asc\");\n        query.setParameter(\"show\", true);\n        query.setParameter(\"date1\", date(\"2017-01-20 00:00\"));\n        query.setParameter(\"date2\", date(\"2017-02-01 00:00\"));\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(\"Second article\", results.get(0).getTitle());\n        Assert.assertEquals(\"Fifth article\", results.get(1).getTitle());\n\n        query = em.createQuery(\"select a from ArticleMongo a where a.show = :show and \"\n                + \"(a.createDate < :date and (a.displayDate is null or a.displayDate < :date)) \"\n                + \"and a.category = :category \" + \"order by a.createDate asc\");\n        query.setParameter(\"show\", true);\n        query.setParameter(\"date\", date(\"2017-03-30 00:00\"));\n        query.setParameter(\"category\", \"important\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(\"First article\", results.get(0).getTitle());\n        Assert.assertEquals(\"Third article\", results.get(1).getTitle());\n        Assert.assertEquals(\"Fourth article\", results.get(2).getTitle());\n\n        query = em.createQuery(\"select a from ArticleMongo a where a.category IN :category \"\n                + \"order by a.createDate asc\");\n        query.setParameter(\"category\", Collections.singletonList(\"important\"));\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(\"First article\", results.get(0).getTitle());\n        Assert.assertEquals(\"Third article\", results.get(1).getTitle());\n        Assert.assertEquals(\"Fourth article\", results.get(2).getTitle());\n    }\n\n    @Test\n    public void testJoins()\n    {\n        prepareArticle(\"article1\", date(\"2017-01-05 10:00\"), null, \"First article\", \"A\", 1, true);\n        prepareArticle(\"article2\", date(\"2017-01-15 10:00\"), null, \"Second article\", \"B\", 3, true);\n        prepareArticle(\"article3\", date(\"2017-01-25 10:00\"), null, \"Third article\", \"A\", 6, true);\n        prepareArticleDetails(\"det1\", \"First author\", \"Intro #1\", \"Contents #1\");\n        prepareArticleDetails(\"det2\", \"Second author\", \"Intro #2\", \"Contents #2\");\n        prepareArticleDetails(\"det3\", \"Third author\", \"Intro #3\", \"Contents #3\");\n        prepareArticleExtension(\"ext1\", \"article1\", \"det1\", 30);\n        prepareArticleExtension(\"ext2\", \"article1\", \"det2\", 20);\n        prepareArticleExtension(\"ext3\", \"article3\", \"det3\", 50);\n        prepareArticleExtension(\"ext4\", \"article2\", null, 10);\n\n        Query query = em.createQuery(\"select e from ArticleMTO e order by e.id\");\n        List<ArticleMTO> results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        Assert.assertEquals(\"ext1\", results.get(0).getId());\n        Assert.assertEquals(\"article1\", results.get(0).getArticle().getArticleId());\n        Assert.assertEquals(\"det1\", results.get(0).getDetails().getId());\n        Assert.assertEquals(\"ext2\", results.get(1).getId());\n        Assert.assertEquals(\"article1\", results.get(1).getArticle().getArticleId());\n        Assert.assertEquals(\"det2\", results.get(1).getDetails().getId());\n        Assert.assertEquals(\"ext3\", results.get(2).getId());\n        Assert.assertEquals(\"article3\", results.get(2).getArticle().getArticleId());\n        Assert.assertEquals(\"det3\", results.get(2).getDetails().getId());\n        Assert.assertEquals(\"ext4\", results.get(3).getId());\n        Assert.assertEquals(\"article2\", results.get(3).getArticle().getArticleId());\n        Assert.assertNull(results.get(3).getDetails());\n\n        query = em.createQuery(\"select e from ArticleMTO e where e.article.articleId in :ids order by e.id\");\n        query.setParameter(\"ids\", Arrays.asList(\"article2\", \"article3\"));\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(\"ext3\", results.get(0).getId());\n        Assert.assertEquals(\"article3\", results.get(0).getArticle().getArticleId());\n        Assert.assertEquals(\"ext4\", results.get(1).getId());\n        Assert.assertEquals(\"article2\", results.get(1).getArticle().getArticleId());\n\n        query = em.createQuery(\"select max(e.value) from ArticleMTO e where e.article.priority < :priority\");\n        query.setParameter(\"priority\", 5);\n        Object singleResult = query.getSingleResult();\n\n        Assert.assertNotNull(singleResult);\n        Assert.assertEquals(30L, singleResult);\n    }\n\n    @Test\n    public void testAggregation()\n    {\n        prepareArticle(\"article1\", date(\"2017-01-05 10:00\"), null, \"First article\", \"A\", 1, true);\n        prepareArticle(\"article2\", date(\"2017-01-15 10:00\"), null, \"Second article\", \"B\", 3, true);\n        prepareArticle(\"article3\", date(\"2017-01-25 10:00\"), null, \"Third article\", \"A\", 6, true);\n\n        Query query = em.createQuery(\"select max(a.priority) from ArticleMongo a\");\n        List<?> results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(6, results.get(0));\n\n        query = em.createQuery(\"select max(a.priority), min(a.priority) from ArticleMongo a\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        Object[] resultArray = (Object[]) results.get(0);\n        Assert.assertEquals(\"Results: \" + Arrays.toString(resultArray), 2, resultArray.length);\n        Assert.assertEquals(6, resultArray[0]);\n        Assert.assertEquals(1, resultArray[1]);\n\n        query = em\n                .createQuery(\"select avg(a.priority), sum(a.priority), max(a.priority), min(a.priority) from ArticleMongo a\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        resultArray = (Object[]) results.get(0);\n        Assert.assertEquals(\"Results: \" + Arrays.toString(resultArray), 4, resultArray.length);\n        assertAlmostEqual(3.3333, resultArray[0]);\n        Assert.assertEquals(10, resultArray[1]);\n        Assert.assertEquals(6, resultArray[2]);\n        Assert.assertEquals(1, resultArray[3]);\n\n        query = em\n                .createQuery(\"select sum(a.priority), a.category from ArticleMongo a group by a.category order by a.category\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(\"A\", ((Object[]) results.get(0))[1]);\n        Assert.assertEquals(\"B\", ((Object[]) results.get(1))[1]);\n\n        for (Object item : results)\n        {\n            resultArray = (Object[]) item;\n            Assert.assertEquals(\"Result Item: \" + Arrays.toString(resultArray), 2, resultArray.length);\n            Assert.assertTrue(Arrays.asList(\"A\", \"B\").contains(resultArray[1]));\n\n            if (resultArray[1].equals(\"A\"))\n            {\n                Assert.assertEquals(7, resultArray[0]);\n            }\n            else if (resultArray[1].equals(\"B\"))\n            {\n                Assert.assertEquals(3, resultArray[0]);\n            }\n        }\n\n        query = em\n                .createQuery(\"select sum(a.priority), a.category, avg(a.priority), min(a.priority) from ArticleMongo a group by a.category\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertSumsMatch(results, 4);\n\n        query = em\n                .createQuery(\"select sum(a.priority), a.category from ArticleMongo a group by a.category order by sum(a.priority) desc\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(\"A\", ((Object[]) results.get(0))[1]);\n        Assert.assertEquals(\"B\", ((Object[]) results.get(1))[1]);\n        assertSumsMatch(results, 2);\n    }\n\n    @Test\n    public void testCountAggregation()\n    {\n        prepareArticle(\"article1\", date(\"2017-01-05 10:00\"), null, \"First article\", \"A\", 1, true);\n        prepareArticle(\"article2\", date(\"2017-01-15 10:00\"), null, \"Second article\", \"B\", 3, true);\n        prepareArticle(\"article3\", date(\"2017-01-25 10:00\"), null, \"Third article\", \"A\", 6, true);\n\n        Query query = em\n                .createQuery(\"select sum(a.priority), count(a), a.category from ArticleMongo a group by a.category order by a.category\");\n        List results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(2L, ((Object[]) results.get(0))[1]);\n        Assert.assertEquals(1L, ((Object[]) results.get(1))[1]);\n\n        query = em.createQuery(\"select count(a) from ArticleMongo a\");\n        Object result = query.getSingleResult();\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(3L, result);\n    }\n\n    private void assertAlmostEqual(double expected, Object actual)\n    {\n        double value = (double) actual;\n        Assert.assertTrue(\n                String.format(\"%.4f != %.4f\\nExpected: %.4f\\nActual  : %.4f\", expected, value, expected, value),\n                Math.abs(value - expected) < 0.0001);\n    }\n\n    private void assertSumsMatch(List results, int expectedNumberOfItems)\n    {\n        for (Object item : results)\n        {\n            Object[] resultArray = (Object[]) item;\n            Assert.assertEquals(\"Result Item: \" + Arrays.toString(resultArray), expectedNumberOfItems,\n                    resultArray.length);\n            Assert.assertTrue(Arrays.asList(\"A\", \"B\").contains(resultArray[1]));\n\n            if (resultArray[1].equals(\"A\"))\n            {\n                Assert.assertEquals(7, resultArray[0]);\n            }\n            else if (resultArray[1].equals(\"B\"))\n            {\n                Assert.assertEquals(3, resultArray[0]);\n            }\n        }\n    }\n\n    private void prepareArticle(String id, Date createDate, Date displayDate, String title, String category,\n            int priority, boolean show)\n    {\n        ArticleMongo item = new ArticleMongo();\n        item.setArticleId(id);\n        item.setCreateDate(createDate);\n        item.setDisplayDate(displayDate);\n        item.setTitle(title);\n        item.setCategory(category);\n        item.setPriority(priority);\n        item.setShow(show);\n        em.persist(item);\n    }\n\n    private void prepareArticleDetails(String id, String author, String intro, String body)\n    {\n        ArticleDetails details = new ArticleDetails();\n        details.setId(id);\n        details.setAuthor(author);\n        details.setIntro(intro);\n        details.setBody(body);\n        em.persist(details);\n    }\n\n    private void prepareArticleExtension(String id, String articleId, String detailsId, long value)\n    {\n        ArticleMongo article = articleId != null ? em.find(ArticleMongo.class, articleId) : null;\n        ArticleDetails details = detailsId != null ? em.find(ArticleDetails.class, detailsId) : null;\n\n        ArticleMTO extension = new ArticleMTO();\n        extension.setId(id);\n        extension.setArticle(article);\n        extension.setDetails(details);\n        extension.setValue(value);\n        em.persist(extension);\n    }\n\n    private static Date date(String value)\n    {\n        SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd HH:mm\");\n        try\n        {\n            return format.parse(value);\n        }\n        catch (ParseException ex)\n        {\n            throw new AssertionError(\"Invalid date: \" + value, ex);\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/BaseTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport com.impetus.client.crud.entities.Day;\nimport com.impetus.client.crud.entities.PersonMongo;\nimport com.impetus.client.crud.entities.PersonMongo.Month;\n\n/**\n * The Class BaseTest.\n * \n * @author vivek.mishra\n */\npublic abstract class BaseTest\n{\n    /**\n     * Prepare data.\n     * \n     * @param rowKey\n     *            the row key\n     * @param age\n     *            the age\n     * @return the person\n     */\n    protected PersonMongo prepareMongoInstance(String rowKey, int age)\n    {\n        PersonMongo o = new PersonMongo();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age);\n        o.setDay(Day.FRIDAY);\n        o.setMonth(Month.JAN);\n        Map<String, Month> map = new HashMap<String, Month>();\n        map.put(\"first month\", Month.JAN);\n        map.put(\"second month\", Month.FEB);\n        o.setMap(map);\n        return o;\n    }\n\n    /**\n     * Find by id.\n     * \n     * @param <E>\n     *            the element type\n     * @param clazz\n     *            the clazz\n     * @param rowKey\n     *            the row key\n     * @param em\n     *            the em\n     * @return the e\n     */\n    protected <E extends Object> E findById(Class<E> clazz, Object rowKey, EntityManager em)\n    {\n        return em.find(clazz, rowKey);\n    }\n\n    /**\n     * Assert find by name.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByName(EntityManager em, String clazz, E e, String name,\n            String fieldName)\n    {\n        String query = \"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name;\n        // // find by name.\n        Query q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n    }\n\n    /**\n     * Assert find by name and age.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param minVal\n     *            the min val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByNameAndAge(EntityManager em, String clazz, E e, String name,\n            String minVal, String fieldName)\n    {\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name + \" and p.age > \"\n                + minVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n    }\n\n    /**\n     * Assert find by name and age gt and lt.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param minVal\n     *            the min val\n     * @param maxVal\n     *            the max val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByNameAndAgeGTAndLT(EntityManager em, String clazz, E e, String name,\n            String minVal, String maxVal, String fieldName)\n    {\n        // // // find by name, age clause\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name + \" and p.age > \"\n                + minVal + \" and p.age < \" + maxVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(1, results.size());\n    }\n\n    /**\n     * Assert find by name and age between.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param minVal\n     *            the min val\n     * @param maxVal\n     *            the max val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByNameAndAgeBetween(EntityManager em, String clazz, E e, String name,\n            String minVal, String maxVal, String fieldName)\n    {\n        // // find by between clause\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name\n                + \" and p.age between \" + minVal + \" and \" + maxVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n\n    }\n\n    /**\n     * Assert find by range.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param minVal\n     *            the min val\n     * @param maxVal\n     *            the max val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByRange(EntityManager em, String clazz, E e, String minVal,\n            String maxVal, String fieldName)\n\n    {\n        // find by Range.\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" Between \" + minVal + \" and \"\n                + maxVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n    }\n\n    /**\n     * Assert find without where clause.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     */\n    protected <E extends Object> void assertFindWithoutWhereClause(EntityManager em, String clazz, E e)\n    {\n        // find by without where clause.\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p\");\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n    }\n\n    /**\n     * Assert on merge.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param oldName\n     *            the old name\n     * @param newName\n     *            the new name\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertOnMerge(EntityManager em, String clazz, E e, String oldName,\n            String newName, String fieldName)\n    {\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = '\" + oldName+\"'\");\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = '\" + newName+\"'\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotSame(oldName, getPersonName(e, results.get(0)));\n        Assert.assertEquals(newName, getPersonName(e, results.get(0)));\n        \n  \n        \n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" like :name\");\n        q.setParameter(\"name\", \"Mc.John Doe\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n     \n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" like :name\");\n        q.setParameter(\"name\", \"Mc.\");\n        results = q.getResultList();\n        Assert.assertEquals(0, results.size());\n        \n        q = em.createQuery(\"Select p from \" + clazz + \" p where UPPER(p.\" + fieldName + \") like :name\");\n        q.setParameter(\"name\", \"MC.JOHN DOE\");\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        \n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" like :name\");\n        q.setParameter(\"name\", \"%Doe\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        \n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" like :name\");\n        q.setParameter(\"name\", \"Mc%\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        \n        q = em.createQuery(\"Select p from \" + clazz + \" p where (p.\" + fieldName + \" like :name) AND (p.personId like :personId)\");\n        q.setParameter(\"name\", \"Mc%\");\n        q.setParameter(\"personId\", \"1\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        \n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" like :name AND p.personId like :personId\");\n        q.setParameter(\"name\", \"Mc%\");\n        q.setParameter(\"personId\", \"2\");\n        results = q.getResultList();\n        Assert.assertEquals(0, results.size());\n        \n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" like :name AND p.personId = :personId\");\n        q.setParameter(\"name\", \"Mc%\");\n        q.setParameter(\"personId\", \"2\");\n        results = q.getResultList();\n        Assert.assertEquals(0, results.size());\n        \n        q = em.createQuery(\"Select p from \" + clazz + \" p where UPPER(p.\" + fieldName + \") like :name\");\n        q.setParameter(\"name\", \"MC_%\");\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        \n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" like :name\");\n        q.setParameter(\"name\", \"%_Jo%\");\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        \n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" like :name\");\n        q.setParameter(\"name\", \"%_M%\");\n        results = q.getResultList();\n        Assert.assertEquals(0, results.size());\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @param <E>\n     *            the element type\n     * @param e\n     *            the e\n     * @param result\n     *            the result\n     * @return the person name\n     */\n    private <E extends Object> String getPersonName(E e, Object result)\n    {\n        return ((PersonMongo) result).getPersonName();\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/CappedCollectionTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud;\n\nimport java.lang.reflect.Field;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.crud.entities.MongoDBCappedEntity;\nimport com.impetus.client.mongodb.MongoDBClient;\nimport com.impetus.client.mongodb.MongoDBConstants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.mongodb.CommandResult;\nimport com.mongodb.DB;\nimport com.mongodb.DBCollection;\nimport com.mongodb.DBObject;\n\n/**\n * Test case for Capped Collections\n * \n * @author amresh.singh\n */\npublic class CappedCollectionTest\n{\n    private DB db;\n\n    private String persistenceUnit = \"mongoSchemaGenerationTest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Logger logger = LoggerFactory.getLogger(CappedCollectionTest.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        em = emf.createEntityManager();\n        em.getDelegate();\n        getDB();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        truncateMongo();\n        emf.close();\n    }\n\n    @Test\n    public void testCappedCollection()\n    {\n        // Validate schema\n        DBCollection collection = db.getCollection(\"MongoDBCappedEntity\");\n        Assert.assertTrue(collection.isCapped());\n        CommandResult stats = collection.getStats();\n\n        Object maxObj = stats.get(MongoDBConstants.MAX);\n        Assert.assertNotNull(maxObj);\n        int max = Integer.parseInt(maxObj.toString());\n        Assert.assertEquals(10, max);\n\n        /*\n         * Object size = stats.get(MongoDBConstants.SIZE);\n         * Assert.assertNotNull(size); Assert.assertEquals(10240,\n         * Integer.parseInt(size.toString()));\n         */\n\n        // Index should not have been created\n        List<DBObject> indexInfo = collection.getIndexInfo();\n        Assert.assertTrue(indexInfo.isEmpty() || indexInfo.size() == 1);\n\n        // Insert \"Max\" records successfully\n        for (int i = 1; i <= max; i++)\n        {\n            MongoDBCappedEntity entity = new MongoDBCappedEntity();\n            entity.setPersonId(i + \"\");\n            entity.setPersonName(\"Person_Name_\" + i);\n            entity.setAge((short) i);\n\n            em.persist(entity);\n        }\n\n        // Insert one more record and check whether it replaces first one\n        MongoDBCappedEntity entity = new MongoDBCappedEntity();\n        entity.setPersonId((max + 1) + \"\");\n        entity.setPersonName(\"Person_Name_\" + (max + 1));\n        entity.setAge((short) (max + 1));\n        em.persist(entity);\n\n        em.clear();\n        MongoDBCappedEntity firstRecord = em.find(MongoDBCappedEntity.class, \"1\");\n        Assert.assertNull(firstRecord);\n\n        MongoDBCappedEntity lastRecord = em.find(MongoDBCappedEntity.class, \"\" + (max + 1));\n        Assert.assertNotNull(lastRecord);\n\n        // Deleting documents within a capped collection should simply ignore,\n        // as is done by native API\n        try\n        {\n            em.remove(lastRecord);\n            Assert.fail();\n        }\n        catch (KunderaException ex)\n        {\n            em.clear();\n            lastRecord = em.find(MongoDBCappedEntity.class, \"\" + (max + 1));\n            Assert.assertNotNull(lastRecord);\n        }\n\n    }\n\n    private void truncateMongo()\n    {\n\n        if (db != null)\n        {\n            db.dropDatabase();\n        }\n    }\n\n    /**\n     * \n     */\n    private void getDB()\n    {\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        MongoDBClient client = (MongoDBClient) clients.get(persistenceUnit);\n        if (client != null)\n        {\n            try\n            {\n                Field mongodb = client.getClass().getDeclaredField(\"mongoDb\");\n                if (!mongodb.isAccessible())\n                {\n                    mongodb.setAccessible(true);\n                }\n                db = (DB) mongodb.get(client);\n            }\n\n            catch (SecurityException e)\n            {\n                logger.error(\"Error in test, Caused by: .\", e.getMessage());\n            }\n            catch (NoSuchFieldException e)\n            {\n                logger.error(\"Error in test, Caused by: .\", e.getMessage());\n            }\n            catch (IllegalArgumentException e)\n            {\n                logger.error(\"Error in test, Caused by: .\", e.getMessage());\n            }\n            catch (IllegalAccessException e)\n            {\n                logger.error(\"Error in test, Caused by: .\", e.getMessage());\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/CollecteTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.Collecte;\nimport com.impetus.client.crud.datatypes.entities.Photoo;\n\n/**\n * Junit for https://github.com/impetus-opensource/Kundera/issues/237\n * \n * @author vivek.mishra\n * \n */\npublic class CollecteTest\n{\n\n    private static final String _PU = \"mongoTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(_PU);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testInsert()\n    {\n        // une collecte\n        Collecte c = new Collecte();\n        c.setId(\"0001\");\n        c.setEAN(\"3251248033108\");\n        c.setIdProduit(123342124L);\n        c.setDateStatut(new Date());\n        c.setStatut(0);\n        // qq photos\n        List<Photoo> photos = new ArrayList<Photoo>();\n        Photoo p1 = new Photoo();\n        p1.setNomPhoto(\"Photo de Face\");\n        p1.setMd5(\"1235847EA873\");\n        p1.setNomFichier(\"photo1.jpg\");\n        photos.add(p1);\n        Photoo p2 = new Photoo();\n        p2.setNomPhoto(\"Photo composition\");\n        p2.setMd5(\"234847EA873\");\n        p2.setNomFichier(\"photo2.jpg\");\n        photos.add(p2);\n        Photoo p3 = new Photoo();\n        p3.setNomPhoto(\"Photo prix\");\n        p3.setMd5(\"5164847EA873\");\n        p3.setNomFichier(\"photo3.jpg\");\n        photos.add(p3);\n\n        c.setPhotos(photos);\n        em.persist(c);\n        testSelect();\n\n    }\n    \n    @Test\n    public void testNullEmbeddableInsert()\n    {\n        // une collecte\n        Collecte c = new Collecte();\n        c.setId(\"0001\");\n        c.setEAN(\"3251248033108\");\n        c.setIdProduit(123342124L);\n        c.setDateStatut(new Date());\n        c.setStatut(0);\n               \n        em.persist(c);\n        testNullEmbeddable();\n\n    }\n\n    private void testSelect()\n    {\n        Query q = em.createQuery(\"select c from Collecte c where c.id =:id\");\n        q.setParameter(\"id\", \"0001\");\n        List<Collecte> collectes = q.getResultList();\n        Collecte c = collectes.get(0);\n        Assert.assertEquals(c.getEAN(), \"3251248033108\");\n        Assert.assertEquals(c.getPhotos().size(), 3);\n        Assert.assertEquals(c.getPhotos().iterator().next().getMd5(), \"1235847EA873\");\n    }\n    \n    private void testNullEmbeddable()\n    {\n        Query q = em.createQuery(\"select c from Collecte c where c.id =:id\");\n        q.setParameter(\"id\", \"0001\");\n        List<Collecte> collectes = q.getResultList();\n        Collecte c = collectes.get(0);\n        Assert.assertEquals(c.getEAN(), \"3251248033108\");\n        Assert.assertNull(c.getPhotos());\n        \n    }\n\n    @After\n    public void tearDown()\n    {\n        em.close();\n        emf.close();\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/EmbeddableIdTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2017 Impetus Infotech.\n * *\n * * Licensed under the Apache License, Version 2.0 (the \"License\");\n * * you may not use this file except in compliance with the License.\n * * You may obtain a copy of the License at\n * *\n * * http://www.apache.org/licenses/LICENSE-2.0\n * *\n * * Unless required by applicable law or agreed to in writing, software\n * * distributed under the License is distributed on an \"AS IS\" BASIS,\n * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * * See the License for the specific language governing permissions and\n * * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport com.impetus.client.crud.entities.CompositeId;\nimport com.impetus.client.crud.entities.CompositeUser;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport java.util.List;\n\n/**\n * This test verifies embedded IDs work in queries when the field name is\n * different from the column name.\n */\npublic class EmbeddableIdTest\n{\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up.\n     */\n    @Before\n    public void setUp()\n    {\n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n        em = emf.createEntityManager();\n\n        prepareData();\n    }\n\n    /**\n     * Test select.\n     */\n    @Test\n    public void testSelect()\n    {\n        Query query = null;\n        List<?> results = null;\n\n        query = em.createQuery(\"select u from CompositeUser u\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(results.size(), 3);\n\n        query = em.createQuery(\"select u from CompositeUser u where u.id.birthDate = :year\");\n        query.setParameter(\"year\", \"1986\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(results.size(), 1);\n\n        query = em.createQuery(\"select u from CompositeUser u where u.id.birthDate <= :year\");\n        query.setParameter(\"year\", \"1986\");\n        results = query.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(results.size(), 2);\n    }\n\n    /**\n     * Prepare data.\n     */\n    private void prepareData()\n    {\n        CompositeId id1 = new CompositeId();\n        id1.setFirstName(\"John\");\n        id1.setBirthDate(\"1981\");\n\n        CompositeUser user1 = new CompositeUser();\n        user1.setId(id1);\n        user1.setPhone(\"90001\");\n\n        em.persist(user1);\n\n        CompositeId id2 = new CompositeId();\n        id2.setFirstName(\"Carl\");\n        id2.setBirthDate(\"1988\");\n\n        CompositeUser user2 = new CompositeUser();\n        user2.setId(id2);\n        user2.setPhone(\"90002\");\n\n        em.persist(user2);\n\n        CompositeId id3 = new CompositeId();\n        id3.setFirstName(\"Viktor\");\n        id3.setBirthDate(\"1986\");\n\n        CompositeUser user3 = new CompositeUser();\n        user3.setId(id3);\n        user3.setPhone(\"90003\");\n\n        em.persist(user3);\n    }\n\n    /**\n     * Tear down.\n     */\n    @After\n    public void tearDown()\n    {\n        em.close();\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/EmbeddableUserTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Embeddable;\nimport javax.persistence.Entity;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.AppUser;\nimport com.impetus.client.crud.entities.PhoneDirectory;\n\n/**\n * EmbeddableUserTest tests @{@link Entity} and {@link Embeddable} having\n * {@link Set, List, Map} as its attribute.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class EmbeddableUserTest\n{\n\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    @Before\n    public void setUp()\n    {\n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void test()\n    {\n        AppUser user = new AppUser();\n        user.setId(\"id\");\n        List<String> contactList = new ArrayList<>();\n        contactList.add(\"xamry\");\n\n        Map<String, String> contactMap = new HashMap<>();\n        contactMap.put(\"xamry\", \"9891991919\");\n\n        Set<String> contactSet = new HashSet<>();\n        contactSet.add(\"xamry\");\n\n        PhoneDirectory properties = new PhoneDirectory(\"MyPhoneDirectory\", contactList, contactMap, contactSet);\n        user.setPropertyContainer(properties);\n        em.persist(user);\n\n        em.clear();\n\n        AppUser result = em.find(AppUser.class, \"id\");\n\n        Assert.assertNotNull(result);\n        Assert.assertNotNull(result.getId());\n        Assert.assertNotNull(result.getPropertyKeys());\n        Assert.assertFalse(result.getPropertyKeys().isEmpty());\n        Assert.assertEquals(1, result.getPropertyKeys().size());\n        Assert.assertNotNull(result.getNickName());\n        Assert.assertFalse(result.getNickName().isEmpty());\n        Assert.assertEquals(1, result.getNickName().size());\n        Assert.assertTrue(result.getNickName().contains(\"kk\"));\n        Assert.assertNotNull(result.getFriendList());\n        Assert.assertFalse(result.getFriendList().isEmpty());\n        Assert.assertEquals(2, result.getFriendList().size());\n        Assert.assertNotNull(result.getTags());\n        Assert.assertFalse(result.getTags().isEmpty());\n        Assert.assertEquals(1, result.getTags().size());\n        Assert.assertEquals(\"yo\", result.getTags().get(0));\n\n        PhoneDirectory propertyContainer = result.getPhoneDirectory();\n        Assert.assertNotNull(propertyContainer);\n        Assert.assertEquals(\"MyPhoneDirectory\", propertyContainer.getPhoneDirectoryName());\n        Assert.assertNotNull(propertyContainer.getContactMap());\n        Assert.assertFalse(propertyContainer.getContactMap().isEmpty());\n        Assert.assertEquals(1, propertyContainer.getContactMap().size());\n        Assert.assertEquals(\"9891991919\", propertyContainer.getContactMap().get(\"xamry\"));\n        Assert.assertNotNull(propertyContainer.getContactNumber());\n        Assert.assertFalse(propertyContainer.getContactNumber().isEmpty());\n        Assert.assertEquals(1, propertyContainer.getContactNumber().size());\n        Assert.assertNotNull(propertyContainer.getContactName());\n        Assert.assertFalse(propertyContainer.getContactName().isEmpty());\n        Assert.assertEquals(1, propertyContainer.getContactName().size());\n        Assert.assertEquals(\"xamry\", propertyContainer.getContactName().get(0));\n\n    }\n\n    /**\n     * Tests validation constraint on embeddable object\n     */\n    @Test\n    public void testConstraints()\n    {\n        try\n        {\n            AppUser user = new AppUser();\n            user.setId(\"id\");\n            List<String> contactName = new LinkedList<String>();\n            Map<String, String> contactMap = new HashMap<String, String>();\n            Set<String> contactNumber = new HashSet<String>();\n            contactName.add(\"xamry\");\n            contactMap.put(\"xamry\", \"9891991919\");\n            contactMap.put(\"xamry1\", \"98919919129\");\n            contactMap.put(\"xamry2\", \"98919919319\");\n            contactNumber.add(\"9891991919\");\n            String phoneDirectoryName = \"MyPhoneDirectory\";\n            PhoneDirectory properties = new PhoneDirectory(phoneDirectoryName, contactName, contactMap, contactNumber);\n            user.setPropertyContainer(properties);\n            em.persist(user);\n\n            em.clear();\n\n        }\n        catch (Exception e)\n        {\n            Assert.fail();\n            Assert.assertEquals(\n                    \"javax.validation.ValidationException: The size should be at least equal to one but not more than 2\",\n                    e.getMessage());\n\n        }\n\n    }\n\n    @After\n    public void tearDown()\n    {\n        em.close();\n        emf.close();\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/EmbeddedEntity.java",
    "content": "package com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n@Embeddable\npublic class EmbeddedEntity\n{\n    @Column(name = \"EMAIL_ID\", table = \"SECONDARY_TABLE\")\n    private String emailId;\n\n    @Column(name = \"PHONE_NO\")\n    private long phoneNo;\n\n    public String getEmailId()\n    {\n        return emailId;\n    }\n\n    public void setEmailId(String emailId)\n    {\n        this.emailId = emailId;\n    }\n\n    public long getPhoneNo()\n    {\n        return phoneNo;\n    }\n\n    public void setPhoneNo(long phoneNo)\n    {\n        this.phoneNo = phoneNo;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/MongoAuthenticationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.Arrays;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.utils.MongoUtils;\nimport com.impetus.kundera.loader.KunderaAuthenticationException;\nimport com.mongodb.BasicDBObject;\nimport com.mongodb.DB;\nimport com.mongodb.MongoClient;\nimport com.mongodb.MongoCredential;\nimport com.mongodb.ServerAddress;\n\n/**\n * The Class MongoAuthenticationTest.\n * \n * @author Devender yadav\n */\npublic class MongoAuthenticationTest\n{\n\n    private final static String ADMIN_DB = \"admin\";\n\n    private final static String DB = \"KunderaAuthTests\";\n\n    private static String _PU;\n\n    private static EntityManagerFactory emf;\n\n    private static MongoClient m;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        m = new MongoClient(new ServerAddress(\"localhost\", 27017));\n        addUsers();\n    }\n\n    /**\n     * Authenticate with valid credentials\n     * \n     * \n     */\n    // @Test\n    public void authenticateWithValidCredentials()\n    {\n        try\n        {\n            _PU = \"validAuthenticationMongoPu\";\n            String dbname = \"KunderaAuthTests\";\n            String username = \"kunderaUser\";\n            String password = \"kunderapassword\";\n\n            MongoCredential credential = MongoCredential.createMongoCRCredential(username, dbname,\n                    password.toCharArray());\n\n            MongoClient m = new MongoClient(new ServerAddress(\"localhost\", 27017), Arrays.asList(credential));\n\n            DB db = m.getDB(dbname);\n\n            Assert.assertNotNull(db.getCollectionNames());\n\n            m.close();\n            emf = Persistence.createEntityManagerFactory(_PU);\n            Assert.assertNotNull(emf);\n            EntityManager em = emf.createEntityManager();\n            Assert.assertNotNull(em);\n        }\n        catch (Exception e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Authenticate with valid credentials in case of multiple DBs\n     * \n     * Here user is in \"admin\" database assigned a role readWriteAnyDatabase. So\n     * it can access \"KunderaAuthTests\" database too.\n     */\n    // @Test\n    public void authenticateWithValidCredentialsMultipleDbs()\n    {\n        try\n        {\n            _PU = \"validAuthenticationMongoPuAdminDb\";\n            String adminDb = \"admin\";\n            String dbname = \"KunderaAuthTests\";\n            String username = \"admin\";\n            String password = \"password\";\n\n            MongoCredential credential = MongoCredential.createMongoCRCredential(username, adminDb,\n                    password.toCharArray());\n            MongoClient m = new MongoClient(new ServerAddress(\"localhost\", 27017), Arrays.asList(credential));\n\n            DB db = m.getDB(dbname);\n            DB db_admin = m.getDB(adminDb);\n\n            Assert.assertNotNull(db.getCollectionNames());\n            Assert.assertNotNull(db_admin.getCollectionNames());\n\n            m.close();\n            emf = Persistence.createEntityManagerFactory(_PU);\n            Assert.assertNotNull(emf);\n            EntityManager em = emf.createEntityManager();\n            Assert.assertNotNull(em);\n        }\n        catch (Exception e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Authenticate with invalid credentials.\n     * \n     */\n    // @Test\n    public void authenticateWithInValidCredentials()\n    {\n        Set<String> collectionList = new HashSet<String>();\n        try\n        {\n            _PU = \"validAuthenticationMongoPu\";\n            String dbname = \"KunderaAuthTests\";\n            String username = \"kunderaUser\";\n            String password = \"wrongPassword\";\n\n            MongoCredential credential = MongoCredential.createMongoCRCredential(username, dbname,\n                    password.toCharArray());\n\n            MongoClient m = new MongoClient(new ServerAddress(\"localhost\", 27017), Arrays.asList(credential));\n\n            DB db = m.getDB(dbname);\n            collectionList = db.getCollectionNames();\n\n            Assert.fail(\"Shouldn't be called\");\n\n            m.close();\n            emf = Persistence.createEntityManagerFactory(_PU);\n            Assert.assertNotNull(emf);\n            EntityManager em = emf.createEntityManager();\n            Assert.assertNotNull(em);\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(true, collectionList.isEmpty());\n        }\n    }\n\n    /**\n     * Authenticate with invalid credentials in Persistence Unit.\n     */\n    // @Test\n    public void authenticateWithInValidCredentialsPu()\n    {\n        EntityManager em = null;\n        try\n        {\n            _PU = \"invalidAuthenticationMongoPu\";\n            emf = Persistence.createEntityManagerFactory(_PU);\n            em = emf.createEntityManager();\n            Assert.fail(\"Shouldn't be called\");\n        }\n        catch (KunderaAuthenticationException e)\n        {\n            // Moved authentication at client level.\n            // Assert.assertNull(emf);\n            Assert.assertNull(em);\n        }\n    }\n\n    /**\n     * No authentication test.\n     * \n     */\n    // @Test\n    public void noAuthenticationTest()\n    {\n        try\n        {\n            _PU = \"mongoTest\";\n            String dbname = \"KunderaAuthTests\";\n            MongoClient m = new MongoClient(new ServerAddress(\"localhost\", 27017));\n            DB db = m.getDB(dbname);\n\n            Assert.assertNotNull(db.getCollectionNames());\n\n            emf = Persistence.createEntityManagerFactory(_PU);\n            Assert.assertNotNull(emf);\n            EntityManager em = emf.createEntityManager();\n            Assert.assertNotNull(em);\n        }\n        catch (Exception e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        dropUsers();\n        MongoUtils.dropDatabase(emf, _PU);\n    }\n\n    private static void addUsers()\n    {\n        DB db = m.getDB(DB);\n        Map<String, Object> commandArguments = new BasicDBObject();\n        commandArguments.put(\"createUser\", \"kunderaUser\");\n        commandArguments.put(\"pwd\", \"kunderapassword\");\n        String[] roles = { \"readWrite\" };\n        commandArguments.put(\"roles\", roles);\n        BasicDBObject command = new BasicDBObject(commandArguments);\n        db.command(command);\n\n        DB db_admin = m.getDB(ADMIN_DB);\n        commandArguments = new BasicDBObject();\n        commandArguments.put(\"createUser\", \"admin\");\n        commandArguments.put(\"pwd\", \"password\");\n        String[] admin_roles = { \"readWriteAnyDatabase\" };\n        commandArguments.put(\"roles\", admin_roles);\n        command = new BasicDBObject(commandArguments);\n        db_admin.command(command);\n    }\n\n    private static void dropUsers()\n    {\n        DB db_admin = m.getDB(ADMIN_DB);\n        db_admin.command(new BasicDBObject(\"dropUser\", \"admin\"));\n\n        DB db = m.getDB(DB);\n        db.command(new BasicDBObject(\"dropUser\", \"kunderaUser\"));\n    }\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/MongoBatchProcessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.PersonBatchMongoEntity;\nimport com.impetus.client.mongodb.MongoDBClientProperties;\nimport com.impetus.client.utils.MongoUtils;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.mongodb.WriteConcern;\n\n/**\n * Batch processing test case for MongoDB.\n * \n * @author Devender Yadav\n * \n */\npublic class MongoBatchProcessorTest\n{\n\n    /**\n     * persistence unit.\n     */\n    private static final String MONGO_PU = \"MongoBatchTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /** The rows. */\n    private List<PersonBatchMongoEntity> rows;\n\n    /** The batch size. */\n    private int BATCH_SIZE = 5;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(MONGO_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n\n        /*\n         * By default Bulk Operation is UNORDERED. But you can set this to\n         * ORDERED/UNORDERED using boolean true/false for a particular em\n         * instance\n         */\n        em.setProperty(MongoDBClientProperties.ORDERED_BULK_OPERATION, true);\n\n        /*\n         * \n         * By default WriteConcern is ACKNOWLEDGED. But it can be changed to any\n         * desired value for a particular em instance\n         */\n        em.setProperty(MongoDBClientProperties.WRITE_CONCERN, new WriteConcern(1));\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        for (PersonBatchMongoEntity o : rows)\n        {\n            em.remove(o);\n        }\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n        MongoUtils.dropDatabase(emf, MONGO_PU);\n    }\n\n    /**\n     * Test case for batch operation.\n     */\n    @Test\n    public void onBatch()\n    {\n        int counter = 1;\n        rows = prepareData(5);\n        for (PersonBatchMongoEntity entity : rows)\n        {\n            em.persist(entity);\n            if (counter < BATCH_SIZE)\n            {\n                Assert.assertNull(em.find(PersonBatchMongoEntity.class, entity.getPersonId()));\n            }\n\n            else if (counter == BATCH_SIZE)\n            {\n                Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n                Batcher client = (Batcher) clients.get(MONGO_PU);\n                Assert.assertEquals(5, client.getBatchSize());\n                em.clear();\n                for (int i = 0; i < BATCH_SIZE; i++)\n                {\n                    Assert.assertNotNull(em.find(PersonBatchMongoEntity.class, rows.get(i).getPersonId()));\n                }\n                counter = 0;\n            }\n            counter++;\n        }\n        em.clear();\n\n        String sql = \" Select p from PersonBatchMongoEntity p\";\n        Query query = em.createQuery(sql);\n        List<PersonBatchMongoEntity> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(5, results.size());\n\n        for (PersonBatchMongoEntity entity : results)\n        {\n            entity.setPersonName(\"dev\");\n            em.merge(entity);\n            if (counter < BATCH_SIZE)\n            {\n                PersonBatchMongoEntity p = em.find(PersonBatchMongoEntity.class, entity.getPersonId());\n                Assert.assertEquals(\"vivek\", p.getPersonName());\n            }\n            else if (counter == BATCH_SIZE)\n            {\n                em.clear();\n                for (int i = 0; i < BATCH_SIZE; i++)\n                {\n                    PersonBatchMongoEntity p = em.find(PersonBatchMongoEntity.class, results.get(i).getPersonId());\n                    Assert.assertEquals(\"dev\", p.getPersonName());\n                }\n                counter = 0;\n            }\n            counter++;\n        }\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param noOfRecords\n     *            the no of records\n     * @return the list\n     */\n    private List<PersonBatchMongoEntity> prepareData(Integer noOfRecords)\n    {\n        List<PersonBatchMongoEntity> persons = new ArrayList<PersonBatchMongoEntity>();\n        for (int i = 1; i <= noOfRecords; i++)\n        {\n            PersonBatchMongoEntity o = new PersonBatchMongoEntity();\n            o.setPersonId(i + \"\");\n            o.setPersonName(\"vivek\");\n            o.setAge(20);\n            persons.add(o);\n        }\n\n        return persons;\n    }\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/MongoBiAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.crud.associations.AssociationsBiDirectionalBase;\n\n/**\n * @author Pragalbh Garg\n *\n */\npublic class MongoBiAssociationTest extends AssociationsBiDirectionalBase\n{\n\n\n    @Before\n    public void setUp() throws Exception\n    {\n        _PU = \"mongoShowQueryDisabledPU\";\n        super.setUpInternal();\n    }\n\n    @Test\n    public void test()\n    {\n        assertBegin();\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        tearDownInternal();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/MongoDBQueryOnIdTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.crud;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.PersonMongo;\nimport com.impetus.client.utils.MongoUtils;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class MongoDBQueryOnIdTest extends BaseTest\n{\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    private Map<Object, Object> col;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n        em = emf.createEntityManager();\n        col = new java.util.HashMap<Object, Object>();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        for (Object val : col.values())\n        {\n            em.remove(val);\n        }\n        MongoUtils.dropDatabase(emf, \"mongoTest\");\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void test()\n    {\n        init();\n        em.clear();\n        findById();\n        findByWithOutWhereClause();\n        findByIdEQ();\n        findByIdLT();\n        findByIdLTE();\n        findByIdGT();\n        findByIdGTE();\n        findByIdGTEAndLT();\n        findByIdGTAndLTE();\n        findByIdAndAge();\n        findByIdAndAgeGTAndLT();\n        findByIdGTAndAgeGTAndLT();\n        findByIdGTEAndAge();\n        findByIdLTEAndAge();\n    }\n\n    /**\n     * \n     */\n    private void findByWithOutWhereClause()\n    {\n        String qry = \"Select p.personName from PersonMongo p\";\n        Query q = em.createQuery(qry);\n        List<PersonMongo> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonMongo person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n\n    }\n\n    /**\n     * \n     */\n    private void findByIdEQ()\n    {\n        String qry = \"Select p.personName from PersonMongo p where p.personId = 2\";\n        Query q = em.createQuery(qry);\n        List<PersonMongo> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        for (PersonMongo person : persons)\n        {\n            Assert.assertNull(person.getAge());\n            Assert.assertEquals(\"2\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n        }\n\n    }\n\n    /**\n     * \n     */\n    private void findByIdLT()\n    {\n        String qry = \"Select p.personName from PersonMongo p where p.personId < 3\";\n        Query q = em.createQuery(qry);\n        List<PersonMongo> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(2, persons.size());\n        int count = 0;\n        for (PersonMongo person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdLTE()\n    {\n        String qry = \"Select p.personName, p.age from PersonMongo p where p.personId <= 3\";\n        Query q = em.createQuery(qry);\n        List<PersonMongo> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonMongo person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertEquals(new Integer(20), person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertEquals(new Integer(15), person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(new Integer(10), person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdGT()\n    {\n        String qry = \"Select p.personName from PersonMongo p where p.personId > 1\";\n        Query q = em.createQuery(qry);\n        List<PersonMongo> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(2, persons.size());\n        int count = 0;\n        for (PersonMongo person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"3\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTE()\n    {\n        String qry = \"Select p.personName from PersonMongo p where p.personId >= 1 \";\n        Query q = em.createQuery(qry);\n        List<PersonMongo> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n        int count = 0;\n        for (PersonMongo person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else if (person.getPersonId().equals(\"3\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTEAndLT()\n    {\n        String qry = \"Select p.personName from PersonMongo p where p.personId >= 1 and p.personId < 3\";\n        Query q = em.createQuery(qry);\n        List<PersonMongo> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(2, persons.size());\n        int count = 0;\n        for (PersonMongo person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"1\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTAndLTE()\n    {\n        String qry = \"Select p.personName from PersonMongo p where p.personId > 1 and p.personId <= 2\";\n        Query q = em.createQuery(qry);\n        List<PersonMongo> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        int count = 0;\n        for (PersonMongo person : persons)\n        {\n            Assert.assertNull(person.getAge());\n            Assert.assertEquals(\"2\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTAndAgeGTAndLT()\n    {\n\n        String qry = \"Select p.personName from PersonMongo p where p.personId > 1 and p.age >=10 and p.age <= 20\";\n        Query q = em.createQuery(qry);\n        List<PersonMongo> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(2, persons.size());\n        int count = 0;\n        for (PersonMongo person : persons)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n            else\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"3\", person.getPersonId());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n    }\n\n    /**\n     * \n     */\n    private void findById()\n    {\n        PersonMongo personHBase = findById(PersonMongo.class, \"1\", em);\n        Assert.assertNotNull(personHBase);\n        Assert.assertEquals(\"vivek\", personHBase.getPersonName());\n        Assert.assertEquals(new Integer(10), personHBase.getAge());\n\n        personHBase = findById(PersonMongo.class, \"2\", em);\n        Assert.assertNotNull(personHBase);\n        Assert.assertEquals(\"vivek\", personHBase.getPersonName());\n        Assert.assertEquals(new Integer(20), personHBase.getAge());\n\n        personHBase = findById(PersonMongo.class, \"3\", em);\n        Assert.assertNotNull(personHBase);\n        Assert.assertEquals(\"vivek\", personHBase.getPersonName());\n        Assert.assertEquals(new Integer(15), personHBase.getAge());\n    }\n\n    /**\n     * \n     */\n    private void findByIdGTEAndAge()\n    {\n        String qry = \"Select p.personName, p.age from PersonMongo p where p.personId >= 1 and p.age = 10\";\n        Query q = em.createQuery(qry);\n        List<PersonMongo> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        for (PersonMongo person : persons)\n        {\n            Assert.assertEquals(new Integer(10), person.getAge());\n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n        }\n    }\n\n    /**\n     * \n     */\n    private void findByIdLTEAndAge()\n    {\n        String qry = \"Select p.personName, p.age from PersonMongo p where p.personId <= 3 and p.age = 10\";\n        Query q = em.createQuery(qry);\n        List<PersonMongo> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        for (PersonMongo person : persons)\n        {\n            Assert.assertEquals(new Integer(10), person.getAge());\n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n        }\n\n    }\n\n    /**\n     * \n     */\n    private void findByIdAndAge()\n    {\n        String qry = \"Select p.personName, p.age from PersonMongo p where p.personId = 1 and p.age = 10\";\n        Query q = em.createQuery(qry);\n        List<PersonMongo> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        for (PersonMongo person : persons)\n        {\n            Assert.assertEquals(new Integer(10), person.getAge());\n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"vivek\", person.getPersonName());\n            Assert.assertEquals(10, person.getAge().intValue());\n        }\n    }\n\n    /**\n     * \n     */\n    private void findByIdAndAgeGTAndLT()\n    {\n        String qry = \"Select p.personName from PersonMongo p where p.personId = 1 and p.personName = vivek and p.age >=10 and p.age <= 20\";\n        Query q = em.createQuery(qry);\n        List<PersonMongo> persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        int count = 0;\n        for (PersonMongo person : persons)\n        {\n            if (person.getPersonId().equals(\"1\"))\n            {\n                Assert.assertNull(person.getAge());\n                Assert.assertEquals(\"vivek\", person.getPersonName());\n                count++;\n            }\n        }\n        Assert.assertEquals(1, count);\n    }\n\n    private void init()\n    {\n        Object p1 = prepareMongoInstance(\"1\", 10);\n        Object p2 = prepareMongoInstance(\"2\", 20);\n        Object p3 = prepareMongoInstance(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/MongoLuceneTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.Day;\nimport com.impetus.client.crud.entities.PersonMongoEmptyTableName;\nimport com.impetus.client.crud.entities.PersonMongoNameAnnotation;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * Test case to check lucene support in mongodb select)\n */\npublic class MongoLuceneTest\n{\n    private static final String PU = \"mongoTest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    protected Map<String, String> propertyMap = new HashMap<String, String>();\n\n    @Before\n    public void setUp() throws Exception\n    {\n        propertyMap.put(\"index.home.dir\", \"lucene\");\n        emf = Persistence.createEntityManagerFactory(PU, propertyMap);\n        em = emf.createEntityManager();\n\n    }\n\n    @Test\n    public void test() throws Exception\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        PersonMongoNameAnnotation personWithKey = new PersonMongoNameAnnotation();\n        personWithKey.setPersonId(\"111\");\n        em.persist(personWithKey);\n\n        em.clear();\n        PersonMongoNameAnnotation p = findById(PersonMongoNameAnnotation.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertEquals(Day.THURSDAY, p.getDay());\n\n        em.clear();\n        String qry = \"Select p.personId,p.personName from PesonMongo p where p.personId >= 1\";\n        Query q = em.createQuery(qry);\n        List<PersonMongoNameAnnotation> persons = q.getResultList();\n\n        assertFindByName(em, \"PersonEntityNameAnnotation\", PersonMongoNameAnnotation.class, \"vivek\", \"personName\");\n\n        // Delete without WHERE clause.\n        String deleteQuery = \"DELETE from PesonMongo\";\n        q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n\n    }\n\n    @Test\n    public void testEmptytableName() throws Exception\n    {\n        PersonMongoEmptyTableName p1 = new PersonMongoEmptyTableName();\n        p1.setPersonId(\"1\");\n        p1.setPersonName(\"vivek\");\n        p1.setAge(10);\n\n        Query findQuery = em.createQuery(\"Select p from PersonMongoEmptyTableName p\", PersonMongoEmptyTableName.class);\n        List<PersonMongoEmptyTableName> allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        findQuery = em.createQuery(\"Select p from PersonMongoEmptyTableName p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        findQuery = em.createQuery(\"Select p.age from PersonMongoEmptyTableName p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        em.persist(p1);\n\n        PersonMongoEmptyTableName personWithKey = new PersonMongoEmptyTableName();\n        personWithKey.setPersonId(\"111\");\n        em.persist(personWithKey);\n\n        em.clear();\n        PersonMongoEmptyTableName p = findById(PersonMongoEmptyTableName.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n\n        em.clear();\n        String qry = \"Select p.personId,p.personName from PersonMongoEmptyTableName p where p.personId = 1\";\n        Query q = em.createQuery(qry);\n        List<PersonMongoEmptyTableName> persons = q.getResultList();\n        Assert.assertNotNull(persons.get(0).getPersonName());\n        Assert.assertNull(persons.get(0).getAge());\n\n        // Delete without WHERE clause.\n        String deleteQuery = \"DELETE from PersonMongoEmptyTableName\";\n        q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        LuceneCleanupUtilities.cleanLuceneDirectory(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance()\n                .getApplicationMetadata().getPersistenceUnitMetadata(\"hbaseTest\"));\n        em.close();\n        emf.close();\n    }\n\n    private PersonMongoNameAnnotation prepareData(String rowKey, int age)\n    {\n        PersonMongoNameAnnotation o = new PersonMongoNameAnnotation();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age);\n        o.setDay(Day.THURSDAY);\n        return o;\n    }\n\n    private <E extends Object> E findById(Class<E> clazz, Object rowKey, EntityManager em)\n    {\n        return em.find(clazz, rowKey);\n    }\n\n    private <E extends Object> void assertFindByName(EntityManager em, String clazz, E e, String name, String fieldName)\n    {\n\n        String query = \"Select p from PesonMongo p where p.\" + fieldName + \" = \" + name;\n        // // find by name.\n        Query q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n    }\n\n    private <E extends Object> String getPersonName(E e, Object result)\n    {\n        return ((PersonMongoNameAnnotation) result).getPersonName();\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/MongoMTOTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\n\nimport com.impetus.client.crud.entities.PersonMongoMTO;\n\npublic class MongoMTOTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n        em = getNewEM();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        AddressMongoMTO address = new AddressMongoMTO();\n        address.setAddressId(\"a\");\n        address.setStreet(\"sector 11\");\n\n        PersonMongoMTO person1 = new PersonMongoMTO();\n        person1.setPersonId(\"1\");\n        person1.setPersonName(\"Kuldeep\");\n\n        PersonMongoMTO person2 = new PersonMongoMTO();\n        person2.setPersonId(\"2\");\n        person2.setPersonName(\"vivek\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        em = getNewEM();\n\n        /**\n         * \n         * Native Queries in case of Entities having Relations\n         * \n         */\n        \n        String test = \"db.PersonMongoMTO.findOne()\";\n        List<PersonMongoMTO> list = em.createNativeQuery(test, PersonMongoMTO.class).getResultList();\n        Assert.assertEquals(1, list.size());\n        Assert.assertEquals(\"1\", list.get(0).getPersonId());\n        \n        test = \"db.PersonMongoMTO.find({ \\\"PERSON_NAME\\\":\\\"vivek\\\"})\";\n        list = em.createNativeQuery(test, PersonMongoMTO.class).getResultList();\n        Assert.assertEquals(1, list.size());\n        Assert.assertEquals(\"vivek\", list.get(0).getPersonName());\n        \n        test = \"db.PersonMongoMTO.count()\";\n        List count = em.createNativeQuery(test, PersonMongoMTO.class).getResultList();\n        Assert.assertEquals((long) 2, count.get(0));\n        \n        PersonMongoMTO foundPerson1 = em.find(PersonMongoMTO.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddress());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson1.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson1.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson1.getAddress().getStreet());\n\n        PersonMongoMTO foundPerson2 = em.find(PersonMongoMTO.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddress());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vivek\", foundPerson2.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson2.getAddress().getStreet());\n\n        foundPerson1.setPersonName(\"KK\");\n\n        foundPerson2.setPersonName(\"vives\");\n\n        em.merge(foundPerson1);\n        em.merge(foundPerson2);\n\n        em = getNewEM();\n\n        foundPerson1 = em.find(PersonMongoMTO.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddress());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson1.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson1.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson1.getAddress().getStreet());\n\n        foundPerson2 = em.find(PersonMongoMTO.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddress());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vives\", foundPerson2.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson2.getAddress().getStreet());\n\n        em.remove(foundPerson1);\n        em.remove(foundPerson2);\n\n        foundPerson1 = em.find(PersonMongoMTO.class, \"1\");\n        foundPerson2 = em.find(PersonMongoMTO.class, \"2\");\n\n        Assert.assertNull(foundPerson1);\n        Assert.assertNull(foundPerson2);\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/MongoSecondaryTableTest.java",
    "content": "package com.impetus.client.crud;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\npublic class MongoSecondaryTableTest extends SecondaryTableTestBase\n{\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void test()\n    {\n        testCRUD(emf);\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/MongoUniMTMTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.utils.MongoUtils;\n\n/**\n * The Class MongoUniMTMTest.\n * \n * @author Devender Yadav\n */\npublic class MongoUniMTMTest\n{\n\n    /** The Constant _PU. */\n    private static final String _PU = \"mongoTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        MongoUtils.dropDatabase(emf, _PU);\n        emf.close();\n    }\n\n    /**\n     * Test CRUD for Many to Many.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testMTMCRUD() throws Exception\n    {\n        testInsert();\n        testUpdate();\n        testDelete();\n    }\n\n    /**\n     * Test insert.\n     */\n    private void testInsert()\n    {\n        PersonMTM person1 = new PersonMTM();\n        person1.setPersonId(\"p1\");\n        person1.setPersonName(\"Dev\");\n\n        PersonMTM person2 = new PersonMTM();\n        person2.setPersonId(\"p2\");\n        person2.setPersonName(\"PG\");\n\n        AddressMTM address1 = new AddressMTM();\n        address1.setAddressId(\"a1\");\n        address1.setStreet(\"AAAAAAAAAAAAA\");\n\n        AddressMTM address2 = new AddressMTM();\n        address2.setAddressId(\"a2\");\n        address2.setStreet(\"BBBBBBBBBBBBBBB\");\n\n        AddressMTM address3 = new AddressMTM();\n        address3.setAddressId(\"a3\");\n        address3.setStreet(\"CCCCCCCCCCC\");\n\n        Set<AddressMTM> person1Addresses = new HashSet<AddressMTM>();\n        Set<AddressMTM> person2Addresses = new HashSet<AddressMTM>();\n\n        person1Addresses.add(address1);\n        person1Addresses.add(address2);\n\n        person2Addresses.add(address2);\n        person2Addresses.add(address3);\n\n        person1.setAddresses(person1Addresses);\n        person2.setAddresses(person2Addresses);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        em.clear();\n\n        PersonMTM p1 = em.find(PersonMTM.class, \"p1\");\n        Assert.assertEquals(\"Dev\", p1.getPersonName());\n        Assert.assertEquals(2, p1.getAddresses().size());\n\n        PersonMTM p2 = em.find(PersonMTM.class, \"p2\");\n        Assert.assertEquals(\"PG\", p2.getPersonName());\n        Assert.assertEquals(2, p2.getAddresses().size());\n\n        AddressMTM a1 = em.find(AddressMTM.class, \"a1\");\n        Assert.assertEquals(\"AAAAAAAAAAAAA\", a1.getStreet());\n\n        AddressMTM a2 = em.find(AddressMTM.class, \"a2\");\n        Assert.assertEquals(\"BBBBBBBBBBBBBBB\", a2.getStreet());\n\n        AddressMTM a3 = em.find(AddressMTM.class, \"a3\");\n        Assert.assertEquals(\"CCCCCCCCCCC\", a3.getStreet());\n    }\n\n    /**\n     * Test update.\n     */\n    private void testUpdate()\n    {\n        PersonMTM p1 = em.find(PersonMTM.class, \"p1\");\n        p1.setPersonName(\"Devender\");\n        em.merge(p1);\n\n        em.clear();\n\n        PersonMTM p = em.find(PersonMTM.class, \"p1\");\n        Assert.assertEquals(\"Devender\", p.getPersonName());\n    }\n\n    /**\n     * Test delete.\n     */\n    private void testDelete()\n    {\n        PersonMTM p1 = em.find(PersonMTM.class, \"p1\");\n        Assert.assertNotNull(p1);\n\n        em.remove(p1);\n\n        PersonMTM p = em.find(PersonMTM.class, \"p1\");\n        Assert.assertNull(p);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/PersonMTM.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\n/**\n * The Class PersonMTM.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"PERSON_MTM\", schema = \"KunderaExamples\")\npublic class PersonMTM\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The addresses. */\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"PERSON_ADDRESS\", schema = \"KunderaExamples\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Set<AddressMTM> addresses;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Gets the addresses.\n     * \n     * @return the addresses\n     */\n    public Set<AddressMTM> getAddresses()\n    {\n        return addresses;\n    }\n\n    /**\n     * Sets the addresses.\n     * \n     * @param addresses\n     *            the new addresses\n     */\n    public void setAddresses(Set<AddressMTM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/PersonMongoNameTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.Day;\nimport com.impetus.client.crud.entities.PersonMongoEmptyTableName;\nimport com.impetus.client.crud.entities.PersonMongoNameAnnotation;\nimport com.impetus.kundera.client.DummyDatabase;\n\n/**\n * Test case to perform check entity name annotation support\n * select)\n */\npublic class PersonMongoNameTest \n{\n    private static final String PU = \"mongoTest\";\n\n\n    private EntityManagerFactory emf;\n    private EntityManager em;\n\n    protected Map propertyMap = null;\n\n    @Before\n    public void setUp() throws Exception\n    {\n                \n        emf = Persistence.createEntityManagerFactory(PU, propertyMap);\n        em = emf.createEntityManager();\n\n    }\n\n    @Test\n    public void test() throws Exception\n    {\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n\n        Query findQuery = em.createQuery(\"Select p from PesonMongo p\", PersonMongoNameAnnotation.class);\n        List<PersonMongoNameAnnotation> allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        findQuery = em.createQuery(\"Select p from PesonMongo p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        findQuery = em.createQuery(\"Select p.age from PesonMongo p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        PersonMongoNameAnnotation personWithKey = new PersonMongoNameAnnotation();\n        personWithKey.setPersonId(\"111\");\n        em.persist(personWithKey);        \n\n        em.clear();\n        PersonMongoNameAnnotation p = findById(PersonMongoNameAnnotation.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertEquals(Day.THURSDAY, p.getDay());\n\n        em.clear();\n        String qry = \"Select p.personId,p.personName from PesonMongo p where p.personId >= 1\";\n        Query q = em.createQuery(qry);\n        List<PersonMongoNameAnnotation> persons = q.getResultList();\n\n        assertFindByName(em, \"PersonEntityNameAnnotation\", PersonMongoNameAnnotation.class, \"vivek\", \"personName\");  \n        \n        // Delete without WHERE clause.\n        String deleteQuery = \"DELETE from PesonMongo\";\n        q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n\n    }\n    \n    @Test\n    public void testEmptytableName() throws Exception\n    {\n        PersonMongoEmptyTableName p1 = new PersonMongoEmptyTableName();\n        p1.setPersonId(\"1\");\n        p1.setPersonName(\"vivek\");\n        p1.setAge(10);\n       \n\n        Query findQuery = em.createQuery(\"Select p from PersonMongoEmptyTableName p\", PersonMongoEmptyTableName.class);\n        List<PersonMongoEmptyTableName> allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        findQuery = em.createQuery(\"Select p from PersonMongoEmptyTableName p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        findQuery = em.createQuery(\"Select p.age from PersonMongoEmptyTableName p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        em.persist(p1);\n     \n\n        PersonMongoEmptyTableName personWithKey = new PersonMongoEmptyTableName();\n        personWithKey.setPersonId(\"111\");\n        em.persist(personWithKey);        \n\n        em.clear();\n        PersonMongoEmptyTableName p = findById(PersonMongoEmptyTableName.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n       \n\n        em.clear();\n        String qry = \"Select p.personId,p.personName from PersonMongoEmptyTableName p where p.personId = 1\";\n        Query q = em.createQuery(qry);\n        List<PersonMongoEmptyTableName> persons = q.getResultList();\n\n        \n        \n        // Delete without WHERE clause.\n        String deleteQuery = \"DELETE from PersonMongoEmptyTableName\";\n        q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n\n    }\n \n \n   \n\n   \n\n   \n\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        DummyDatabase.INSTANCE.dropDatabase();\n    }\n    \n\n    private PersonMongoNameAnnotation prepareData(String rowKey, int age)\n    {\n        PersonMongoNameAnnotation o = new PersonMongoNameAnnotation();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age);\n        o.setDay(Day.THURSDAY);\n        return o;\n    }\n\n \n    private <E extends Object> E findById(Class<E> clazz, Object rowKey, EntityManager em)\n    {\n        return em.find(clazz, rowKey);\n    }\n\n \n    private <E extends Object> void assertFindByName(EntityManager em, String clazz, E e, String name,\n            String fieldName)\n    {\n\n        String query = \"Select p from PesonMongo p where p.\" + fieldName + \" = \" + name;\n        // // find by name.\n        Query q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n    }\n\n   \n   \n\n \n    private <E extends Object> String getPersonName(E e, Object result)\n    {\n\n        return ((PersonMongoNameAnnotation) result).getPersonName();\n    }\n}\n\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/PersonMongoTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.NoResultException;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport javax.persistence.TypedQuery;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.Day;\nimport com.impetus.client.crud.entities.PersonBatchMongoEntity;\nimport com.impetus.client.crud.entities.PersonMongo;\nimport com.impetus.client.crud.entities.PersonMongo.Month;\nimport com.impetus.client.utils.MongoUtils;\nimport com.impetus.kundera.client.Client;\nimport com.mongodb.BasicDBList;\nimport com.mongodb.BasicDBObject;\n\n/**\n * The Class PersonMongoTest.\n */\npublic class PersonMongoTest extends BaseTest\n{\n\n    /** The Constant _PU. */\n    private static final String _PU = \"mongoTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /** The col. */\n    private Map<Object, Object> col;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(_PU);\n        em = emf.createEntityManager();\n        col = new java.util.HashMap<Object, Object>();\n    }\n\n    /**\n     * On insert mongo.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onInsertMongo() throws Exception\n    {\n        Object p1 = prepareMongoInstance(\"1\", 10);\n        Object p2 = prepareMongoInstance(\"2\", 20);\n        Object p3 = prepareMongoInstance(\"3\", 15);\n\n        Query findQuery = em.createQuery(\"Select p from PersonMongo p\");\n        List<PersonMongo> allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = em.createQuery(\"Select p from PersonMongo p where p.personName = vivek\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        em.clear();\n        PersonMongo p = findById(PersonMongo.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(Day.FRIDAY, p.getDay());\n        Assert.assertEquals(Month.JAN, p.getMonth());\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertNotNull(p.getMap());\n        Assert.assertFalse(p.getMap().isEmpty());\n        Assert.assertEquals(2, p.getMap().size());\n\n        assertFindByName(em, \"PersonMongo\", PersonMongo.class, \"vivek\", \"personName\");\n        assertFindByNameAndAge(em, \"PersonMongo\", PersonMongo.class, \"vivek\", \"10\", \"personName\");\n        assertFindByNameAndAgeGTAndLT(em, \"PersonMongo\", PersonMongo.class, \"vivek\", \"10\", \"20\", \"personName\");\n        assertFindByNameAndAgeBetween(em, \"PersonMongo\", PersonMongo.class, \"vivek\", \"10\", \"15\", \"personName\");\n        assertFindByRange(em, \"PersonMongo\", PersonMongo.class, \"1\", \"2\", \"personId\");\n        assertFindWithoutWhereClause(em, \"PersonMongo\", PersonMongo.class);\n\n        Query query = em.createNamedQuery(\"mongo.named.query\");\n        query.setParameter(\"name\", \"vivek\");\n        List<PersonMongo> results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(Month.JAN, results.get(0).getMonth());\n\n        query = em.createNamedQuery(\"mongo.position.query\");\n        query.setParameter(1, \"vivek\");\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(Month.JAN, results.get(0).getMonth());\n\n        findQuery = em.createQuery(\"Select p from PersonMongo p where p.day = :day\");\n        findQuery.setParameter(\"day\", Day.FRIDAY);\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(3, allPersons.size());\n\n        query = em.createQuery(\"select p from PersonMongo p\");\n        query.setMaxResults(2);\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(Month.JAN, results.get(0).getMonth());\n\n        query = em.createQuery(\"select p from PersonMongo p\");\n        query.setMaxResults(1);\n        PersonMongo result = (PersonMongo) (query.getSingleResult());\n        Assert.assertNotNull(result);\n        Assert.assertEquals(Month.JAN, result.getMonth());\n\n        query = em.createQuery(\"select p from PersonMongo p where p.personName = kuldeep\");\n        try\n        {\n            result = (PersonMongo) (query.getSingleResult());\n            Assert.fail(\"Should have gone to catch block!\");\n        }\n        catch (NoResultException nrex)\n        {\n            Assert.assertNotNull(nrex.getMessage());\n        }\n\n        selectIdQuery();\n        onExecuteScript();\n        onExecuteNativeQuery();\n\n    }\n\n    /**\n     * Select id query.\n     */\n    private void selectIdQuery()\n    {\n        String query = \"select p.personId from PersonMongo p\";\n        Query q = em.createQuery(query);\n        List<PersonMongo> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNull(results.get(0).getAge());\n\n        query = \"Select p.personId from PersonMongo p where p.personName = vivek\";\n        // // find by name.\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNull(results.get(0).getAge());\n\n        query = \"Select p.personId from PersonMongo p where p.personName = vivek\";\n        // // find by name.\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNull(results.get(0).getAge());\n\n        q = em.createQuery(\"Select p.personId from PersonMongo p where p.personName = vivek and p.age > \" + 10);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNull(results.get(0).getAge());\n    }\n\n    /**\n     * On typed named query.\n     */\n    @Test\n    public void onNamedTypedQuery()\n    {\n        Object p1 = prepareMongoInstance(\"1\", 10);\n        Object p2 = prepareMongoInstance(\"2\", 20);\n        Object p3 = prepareMongoInstance(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        TypedQuery<PersonMongo> query = em.createNamedQuery(\"mongo.named.query\", PersonMongo.class);\n        query.setParameter(\"name\", \"vivek\");\n        List<PersonMongo> results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(Month.JAN, results.get(0).getMonth());\n    }\n\n    /**\n     * On generic typed named query.\n     */\n    @Test\n    public void onGenericTypedNamedQuery()\n    {\n        Object p1 = prepareMongoInstance(\"1\", 10);\n        Object p2 = prepareMongoInstance(\"2\", 20);\n        Object p3 = prepareMongoInstance(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        TypedQuery<Object> query = em.createNamedQuery(\"mongo.named.query\", Object.class);\n        query.setParameter(\"name\", \"vivek\");\n        List<Object> results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(PersonMongo.class, results.get(0).getClass());\n    }\n\n    /**\n     * On invalid typed query.\n     * \n     */\n    @Test\n    public void onInvalidTypedNamedQuery()\n    {\n        Object p1 = prepareMongoInstance(\"1\", 10);\n        Object p2 = prepareMongoInstance(\"2\", 20);\n        Object p3 = prepareMongoInstance(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        TypedQuery<PersonBatchMongoEntity> query = null;\n        try\n        {\n            query = em.createNamedQuery(\"mongo.named.query\", PersonBatchMongoEntity.class);\n            query.setParameter(\"name\", \"vivek\");\n            Assert.fail(\"Should have gone to catch block, as it is an invalid scenario!\");\n        }\n        catch (IllegalArgumentException iaex)\n        {\n            Assert.assertNull(query);\n        }\n    }\n\n    /**\n     * On merge mongo.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void onMergeMongo() throws Exception\n    {\n        Object p1 = prepareMongoInstance(\"1\", 10);\n        Object p2 = prepareMongoInstance(\"2\", 20);\n        Object p3 = prepareMongoInstance(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        PersonMongo p = findById(PersonMongo.class, \"1\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        // modify record.\n        p.setPersonName(\"Mc.John Doe\");\n        em.merge(p);\n        assertOnMerge(em, \"PersonMongo\", PersonMongo.class, \"vivek\", \"Mc.John Doe\", \"personName\");\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {/*\n      * Delete is working, but as row keys are not deleted from cassandra, so\n      * resulting in issue while reading back. // Delete\n      * em.remove(em.find(Person.class, \"1\")); em.remove(em.find(Person.class,\n      * \"2\")); em.remove(em.find(Person.class, \"3\")); em.close(); emf.close();\n      * em = null; emf = null;\n      */\n        for (Object val : col.values())\n        {\n            em.remove(val);\n        }\n        MongoUtils.dropDatabase(emf, _PU);\n        emf.close();\n\n    }\n\n    /**\n     * On execute script.\n     */\n    private void onExecuteScript()\n    {\n\n        Map<String, Client<Query>> clients = (Map<String, Client<Query>>) em.getDelegate();\n        Client client = clients.get(_PU);\n\n        /*\n         * To find a single document from DB\n         */\n        String script = \"db.PERSON.findOne()\";\n        Object result = (client).executeScript(script);\n        Assert.assertNotNull(result);\n\n        /*\n         * Aggregation in mongoDB match query on PERSON_NAME is done and JSON\n         * list of type BasicDBList is returned this JSON object can be easily\n         * converted to java PersonMongo Object using GSON, etc.\n         */\n        script = \"db.PERSON.aggregate([{ $match: { \\\"PERSON_NAME\\\": \\\"vivek\\\" } } ]).toArray()\";\n        result = (client).executeScript(script);\n        BasicDBList resultList = (BasicDBList) result;\n        Assert.assertEquals(3, resultList.size());\n        Assert.assertNotNull(result);\n\n        /*\n         * To count number of documents in an collection\n         */\n\n        script = \"db.PERSON.count()\";\n        result = (client).executeScript(script);\n        long totalDocuments = ((Double) result).longValue();\n        Assert.assertEquals(3, totalDocuments);\n\n        /*\n         * \n         * To get an array of distinct values\n         */\n\n        script = \"db.PERSON.distinct(\\\"PERSON_NAME\\\")\";\n        result = (client).executeScript(script);\n        resultList = (BasicDBList) result;\n        Assert.assertEquals(\"vivek\", resultList.get(0));\n        Assert.assertEquals(1, resultList.size());\n\n        /*\n         * \n         * Native Query on the Key of Map<String, Month> map\n         */\n        script = \"db.PERSON.find({'map.first month':'JAN'}).toArray()\";\n        result = (client).executeScript(script);\n        resultList = (BasicDBList) result;\n        Assert.assertEquals(3, resultList.size());\n\n        /*\n         * \n         * Native Query to find a person with age > 15\n         */\n        script = \"db.PERSON.find({ \\\"AGE\\\": { $gt: 15 } }).toArray()\";\n        result = (client).executeScript(script);\n        resultList = (BasicDBList) result;\n        Assert.assertEquals(1, resultList.size());\n\n    }\n\n    /**\n     * On execute native query.\n     */\n    private void onExecuteNativeQuery()\n    {\n\n        /**\n         * \n         * In case of Native Find Queries, Criteria can be written directly\n         * \n         */\n\n        String test = \"{\\\"AGE\\\":10}\";\n        List<PersonMongo> list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(1, list.size());\n        Assert.assertEquals(new Integer(10), list.get(0).getAge());\n\n        test = \"{ \\\"PERSON_NAME\\\":\\\"vivek\\\"}\";\n        list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(3, list.size());\n        Assert.assertEquals(\"vivek\", list.get(0).getPersonName());\n        Assert.assertEquals(\"vivek\", list.get(1).getPersonName());\n        Assert.assertEquals(\"vivek\", list.get(2).getPersonName());\n\n        /**\n         * \n         * Matches values that are greater than the value specified in the\n         * query.\n         * \n         */\n        test = \"{ \\\"AGE\\\": { $gt: 12 } }\";\n        list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(2, list.size());\n        for (PersonMongo person : list)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertEquals(new Integer(20), person.getAge());\n            }\n            else\n            {\n                Assert.assertEquals(new Integer(15), person.getAge());\n            }\n        }\n\n        /**\n         * \n         * Matches values that are greater than or equal to the value specified\n         * in the query.\n         * \n         */\n        test = \"{ \\\"AGE\\\": { $gte: 15 } }\";\n        list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(2, list.size());\n        for (PersonMongo person : list)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertEquals(new Integer(20), person.getAge());\n            }\n            else\n            {\n                Assert.assertEquals(new Integer(15), person.getAge());\n            }\n        }\n\n        /**\n         * \n         * Matches values that are less than the value specified in the query.\n         * \n         */\n        test = \"{ \\\"AGE\\\": { $lt: 15 } }\";\n        list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(1, list.size());\n        Assert.assertEquals(new Integer(10), list.get(0).getAge());\n\n        /**\n         * \n         * Matches values that are less than or equal to the value specified in\n         * the query.\n         * \n         */\n        test = \"{ \\\"AGE\\\": { $lte: 15 } }\";\n        list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(2, list.size());\n        for (PersonMongo person : list)\n        {\n            if (person.getPersonId().equals(\"1\"))\n            {\n                Assert.assertEquals(new Integer(10), person.getAge());\n            }\n            else\n            {\n                Assert.assertEquals(new Integer(15), person.getAge());\n            }\n        }\n\n        /**\n         * \n         * Matches all values that are not equal to the value specified in the\n         * query.\n         * \n         */\n        test = \"{ \\\"AGE\\\": { $ne: 10 } }\";\n        list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(2, list.size());\n        for (PersonMongo person : list)\n        {\n            if (person.getPersonId().equals(\"2\"))\n            {\n                Assert.assertEquals(new Integer(20), person.getAge());\n            }\n            else\n            {\n                Assert.assertEquals(new Integer(15), person.getAge());\n            }\n        }\n\n        /**\n         * \n         * Matches any of the values that exist in an array specified in the\n         * query.\n         * \n         */\n        test = \"{ \\\"AGE\\\": { $in: [10,15] } }\";\n        list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(2, list.size());\n        for (PersonMongo person : list)\n        {\n            if (person.getPersonId().equals(\"1\"))\n            {\n                Assert.assertEquals(new Integer(10), person.getAge());\n            }\n            else\n            {\n                Assert.assertEquals(new Integer(15), person.getAge());\n            }\n        }\n\n        /**\n         * \n         * Joins query clauses with a logical AND returns all documents that\n         * match the conditions of both clauses.\n         * \n         */\n        test = \"{ $and : [{\\\"_id\\\":\\\"1\\\"},{ \\\"AGE\\\": 10 }]}\";\n        list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(1, list.size());\n        Assert.assertEquals(new Integer(10), list.get(0).getAge());\n        Assert.assertEquals(\"1\", list.get(0).getPersonId());\n\n        /**\n         * \n         * Joins query clauses with a logical OR returns all documents that\n         * match the conditions of either clause.\n         * \n         */\n        test = \"{ $or : [{\\\"_id\\\":\\\"1\\\"},{ \\\"AGE\\\": 20 }]}\";\n        list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(2, list.size());\n        for (PersonMongo person : list)\n        {\n            if (person.getPersonId().equals(\"1\"))\n            {\n                Assert.assertEquals(new Integer(10), person.getAge());\n            }\n            else\n            {\n                Assert.assertEquals(new Integer(20), person.getAge());\n            }\n        }\n\n        test = \"db.PERSON.findOne()\";\n        list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(1, list.size());\n\n        test = \"db.PERSON.find({ \\\"PERSON_NAME\\\":\\\"vivek\\\"})\";\n        list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(3, list.size());\n        Assert.assertEquals(\"vivek\", list.get(0).getPersonName());\n        Assert.assertEquals(\"vivek\", list.get(1).getPersonName());\n        Assert.assertEquals(\"vivek\", list.get(2).getPersonName());\n\n        test = \"db.PERSON.aggregate([{ $match: { \\\"PERSON_NAME\\\": \\\"vivek\\\" } } ])\";\n        list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(3, list.size());\n        Assert.assertEquals(\"vivek\", list.get(0).getPersonName());\n        Assert.assertEquals(\"vivek\", list.get(1).getPersonName());\n        Assert.assertEquals(\"vivek\", list.get(2).getPersonName());\n\n        test = \"db.PERSON.count()\";\n        List count = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals((long) 3, count.get(0));\n\n        test = \"db.PERSON.dataSize()\";\n        count = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertNotNull(count);\n\n        /**\n         * total allocated size to a collection\n         */\n        test = \"db.PERSON.storageSize()\";\n        count = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertNotNull(count);\n\n        test = \"db.PERSON.totalIndexSize()\";\n        count = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertNotNull(count);\n\n        /**\n         * Total size of Collection (documents+indexes)\n         * \n         */\n        test = \"db.PERSON.totalSize()\";\n        count = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertNotNull(count);\n\n        test = \"db.PERSON.distinct(\\\"PERSON_NAME\\\")\";\n        List distinctList = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(\"vivek\", distinctList.get(0));\n\n        test = \"db.PERSON.findAndModify({query: { \\\"AGE\\\": 10},update: { $set: { \\\"PERSON_NAME\\\": \\\"dev\\\" } },new:true,upsert:true })\";\n        list = em.createNativeQuery(test, PersonMongo.class).getResultList();\n        Assert.assertEquals(\"dev\", list.get(0).getPersonName());\n    }\n\n    /**\n     * Increment function test.\n     */\n    @Test\n    public void incrementFunctionTest()\n    {\n        Object p1 = prepareMongoInstance(\"1\", 10);\n        em.persist(p1);\n\n        String updateFunc = \"UPDATE PersonMongo p set p.age = INCREMENT(1) where p.personId = :personId\";\n        Query q = em.createQuery(updateFunc);\n        q.setParameter(\"personId\", \"1\");\n        Assert.assertEquals(1, q.executeUpdate());\n\n        updateFunc = \"UPDATE PersonMongo set p.age = DECREMENT(1) where p.personId = :personId\";\n        q = em.createQuery(updateFunc);\n        q.setParameter(\"personId\", \"1\");\n        Assert.assertEquals(1, q.executeUpdate());\n\n        updateFunc = \"UPDATE PersonMongo p set p.age = DECREMENT(2)\";\n        q = em.createQuery(updateFunc);\n        Assert.assertEquals(1, q.executeUpdate());\n\n        em.clear();\n\n        String query = \"Select p from PersonMongo p \";\n        q = em.createQuery(query);\n        List<PersonMongo> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(new Integer(8), results.get(0).getAge());\n\n        updateFunc = \"UPDATE PersonMongo p set p.age = INCREMENT(5)\";\n        q = em.createQuery(updateFunc);\n        Assert.assertEquals(1, q.executeUpdate());\n\n        em.clear();\n\n        query = \"Select p from PersonMongo p \";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(new Integer(13), results.get(0).getAge());\n    }\n\n    /**\n     * Sub query test.\n     */\n    @Test\n    public void subQueryTest()\n    {\n        Object p1 = prepareMongoInstance(\"1\", 10);\n        Object p2 = prepareMongoInstance(\"2\", 20);\n        Object p3 = prepareMongoInstance(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        String query = \"Select p from PersonMongo p where p.personName <> :name and p.age NOT IN :ageList\"\n                + \" and (p.personId = :personId)\";\n        Query q = em.createQuery(query);\n        q.setParameter(\"name\", \"vivek\");\n        q.setParameter(\"ageList\", new ArrayList<Integer>()\n        {\n            {\n                add(20);\n                add(21);\n            }\n        });\n        q.setParameter(\"personId\", \"1\");\n        List<PersonMongo> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(0, results.size());\n\n        query = \"Select p from PersonMongo p where (p.personName = :name and p.age NOT IN :ageList)\"\n                + \" and (p.personId = :personId)\";\n        q = em.createQuery(query);\n        q.setParameter(\"name\", \"vivek\");\n        q.setParameter(\"ageList\", new ArrayList<Integer>()\n        {\n            {\n                add(20);\n                add(21);\n            }\n        });\n        q.setParameter(\"personId\", \"1\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNotNull(results.get(0).getPersonName());\n        Assert.assertNotNull(results.get(0).getAge());\n\n    }\n\n    /**\n     * Inter clause operator test.\n     */\n    @Test\n    public void interClauseOperatorTest()\n    {\n        Object p1 = prepareMongoInstance(\"1\", 10);\n        Object p2 = prepareMongoInstance(\"2\", 20);\n        Object p3 = prepareMongoInstance(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        String query = \"Select p from PersonMongo p where (p.personName = :name OR p.age NOT IN :ageList)\"\n                + \" AND (p.personId = :personId)\";\n        Query q = em.createQuery(query);\n        q.setParameter(\"name\", \"vivek\");\n        q.setParameter(\"ageList\", new ArrayList<Integer>()\n        {\n            {\n                add(10);\n                add(20);\n            }\n        });\n        q.setParameter(\"personId\", \"1\");\n        List<PersonMongo> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"1\", results.get(0).getPersonId());\n\n        query = \"Select p from PersonMongo p where (p.personName = :name AND p.age NOT IN :ageList)\"\n                + \" OR (p.personId = :personId)\";\n        q = em.createQuery(query);\n        q.setParameter(\"name\", \"vivek\");\n        q.setParameter(\"ageList\", new ArrayList<Integer>()\n        {\n            {\n                add(10);\n                add(21);\n            }\n        });\n        q.setParameter(\"personId\", \"1\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n\n        query = \"Select p from PersonMongo p where (p.personName = :name OR p.age NOT IN :ageList)\"\n                + \" OR (p.personId = :personId) ORDER BY p.age\";\n        q = em.createQuery(query);\n        q.setParameter(\"name\", \"vivek\");\n        q.setParameter(\"ageList\", new ArrayList<Integer>()\n        {\n            {\n                add(10);\n                add(21);\n            }\n        });\n        q.setParameter(\"personId\", \"1\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNotNull(results.get(0).getPersonName());\n        Assert.assertNotNull(results.get(0).getAge());\n\n        Assert.assertEquals(\"1\", results.get(0).getPersonId());\n        Assert.assertEquals(\"2\", results.get(2).getPersonId());\n\n    }\n\n    /**\n     * Pagination query test.\n     */\n    @Test\n    public void paginationQueryTest()\n    {\n        Object p1 = prepareMongoInstance(\"1\", 10);\n        Object p2 = prepareMongoInstance(\"2\", 20);\n        Object p3 = prepareMongoInstance(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        String query = \"Select p from PersonMongo p \";\n        Query q = em.createQuery(query);\n        q.setFirstResult(1);\n        q.setMaxResults(3);\n        List<PersonMongo> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        query = \"Select p from PersonMongo p where (p.personName = :name and p.age NOT IN :ageList)\"\n                + \" and (p.personId = :personId)\";\n        q = em.createQuery(query);\n        q.setFirstResult(0);\n        q.setMaxResults(3);\n        q.setParameter(\"name\", \"vivek\");\n        q.setParameter(\"ageList\", new ArrayList<Integer>()\n        {\n            {\n                add(20);\n                add(21);\n            }\n        });\n        q.setParameter(\"personId\", \"1\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNotNull(results.get(0).getPersonName());\n        Assert.assertNotNull(results.get(0).getAge());\n\n    }\n\n    /**\n     * Map reduce test (simple).\n     */\n    @Test\n    public void mapReduceTest()\n    {\n        String query = \"db.PERSON.mapReduce(\\n\" + \"  function () { emit( this.AGE - this.AGE % 10, 1 ); },\\n\"\n                + \"  function (key, values) { return { age: key, count: Array.sum(values) }; },\\n\"\n                + \"  { query: {}, out: { inline: 1 } }\\n\" + \")\";\n\n        executeMapReduceTest(query);\n    }\n\n    /**\n     * Map reduce test (with db.getCollection(..)).\n     */\n    @Test\n    public void mapReduceTestWithGetCollection()\n    {\n        String query = \"db.getCollection('PERSON').mapReduce(\\n\"\n                + \"  function () { emit( this.AGE - this.AGE % 10, 1 ); },\\n\"\n                + \"  function (key, values) { return { age: key, count: Array.sum(values) }; },\\n\"\n                + \"  { query: {}, out: { inline: 1 } }\\n\" + \")\";\n\n        executeMapReduceTest(query);\n\n        query = \"db.getCollection(\\\"PERSON\\\").mapReduce(\\n\"\n                + \"  function () { emit( this.AGE - this.AGE % 10, 1 ); },\\n\"\n                + \"  function (key, values) { return { age: key, count: Array.sum(values) }; },\\n\"\n                + \"  { query: {}, out: { inline: 1 } }\\n\" + \")\";\n\n        executeMapReduceTest(query);\n    }\n\n    @Test\n    public void testUpperAndLower()\n    {\n        Object p1 = prepareMongoInstance(\"alexander\", 10);\n        Object p2 = prepareMongoInstance(\"sandra\", 20);\n        Object p3 = prepareMongoInstance(\"CASSANDRA\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        String query = \"Select p from PersonMongo p where UPPER(p.personId) = 'SANDRA'\";\n        Query q = em.createQuery(query);\n        List<PersonMongo> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        query = \"Select p from PersonMongo p where LOWER(p.personId) = 'cassandra'\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        query = \"Select p from PersonMongo p where LOWER(p.personId) IN ('sandra', 'cassandra')\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        query = \"Select p from PersonMongo p where LOWER(p.personId) NOT IN ('sandra', 'cassandra')\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        query = \"Select p from PersonMongo p where UPPER(p.personId) <> 'ALEXANDER'\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n    }\n\n    @Test\n    public void testLikeAndUpperLower()\n    {\n        Object p1 = prepareMongoInstance(\"alexander\", 10);\n        Object p2 = prepareMongoInstance(\"sandra\", 20);\n        Object p3 = prepareMongoInstance(\"CASSANDRA\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        String query = \"Select p from PersonMongo p where p.personId LIKE '%and%'\";\n        Query q = em.createQuery(query);\n        List<PersonMongo> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        query = \"Select p from PersonMongo p where UPPER(p.personId) LIKE '%and%'\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n\n        query = \"Select p from PersonMongo p where LOWER(p.personId) LIKE '%and%'\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n    }\n\n    @Test\n    public void testNotLike()\n    {\n        Object p1 = prepareMongoInstance(\"alexander\", 10);\n        Object p2 = prepareMongoInstance(\"sandra\", 20);\n        Object p3 = prepareMongoInstance(\"CASSANDRA\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        String query = \"Select p from PersonMongo p where p.personId NOT LIKE '%andr%'\";\n        Query q = em.createQuery(query);\n        List<PersonMongo> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        query = \"Select p from PersonMongo p where p.personId NOT LIKE '%andr%' AND p.personId = 'alexander'\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        query = \"Select p from PersonMongo p where p.personId = 'alexander' AND p.personId NOT LIKE '%andr%'\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        query = \"Select p from PersonMongo p where p.personId LIKE '%lex%' AND p.personId NOT LIKE 'cass%'\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n    }\n\n    /**\n     * Execute map reduce test.\n     * \n     * @param query\n     *            the query\n     */\n    private void executeMapReduceTest(String query)\n    {\n        Object p1 = prepareMongoInstance(\"1\", 10);\n        Object p2 = prepareMongoInstance(\"2\", 20);\n        Object p3 = prepareMongoInstance(\"3\", 15);\n        Object p4 = prepareMongoInstance(\"4\", 12);\n        Object p5 = prepareMongoInstance(\"5\", 19);\n        Object p6 = prepareMongoInstance(\"6\", 23);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        em.persist(p4);\n        em.persist(p5);\n        em.persist(p6);\n\n        Query q = em.createNativeQuery(query);\n        List<BasicDBObject> results = q.getResultList();\n\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        for (BasicDBObject item : results)\n        {\n            Assert.assertTrue(item.containsField(\"value\"));\n\n            BasicDBObject value = (BasicDBObject) item.get(\"value\");\n\n            Assert.assertTrue(value.containsField(\"age\"));\n            Assert.assertTrue(value.containsField(\"count\"));\n\n            int age = value.getInt(\"age\");\n            int count = value.getInt(\"count\");\n\n            if (age == 10)\n            {\n                Assert.assertEquals(4, count);\n            }\n            else if (age == 20)\n            {\n                Assert.assertEquals(2, count);\n            }\n            else\n            {\n                Assert.fail(\"Unexpected result\");\n            }\n        }\n    }\n\n    /**\n     * Count test.\n     */\n    @Test\n    public void countTest()\n    {\n        Object p1 = prepareMongoInstance(\"1\", 10);\n        Object p2 = prepareMongoInstance(\"2\", 20);\n        Object p3 = prepareMongoInstance(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        Query query = em.createQuery(\"select count(p) from PersonMongo p\");\n        List<?> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(results.size(), 1);\n        Assert.assertEquals(results.get(0), 3L);\n\n        query = em.createQuery(\"select count(p) from PersonMongo p where p.age < 18\");\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(results.size(), 1);\n        Assert.assertEquals(results.get(0), 2L);\n\n        query = em.createQuery(\"select count(p) from PersonMongo p\");\n        Object singleResult = query.getSingleResult();\n        Assert.assertEquals(singleResult, 3L);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/PersonnelEmbeddedTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.PersonalDetailEmbedded;\nimport com.impetus.client.crud.entities.PersonnelEmbedded;\nimport com.impetus.client.crud.entities.PhoneDirectory;\nimport com.impetus.client.utils.MongoUtils;\n\n/**\n * @author Kuldeep.Mishra\n * \n */\npublic class PersonnelEmbeddedTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        MongoUtils.dropDatabase(emf, \"mongoTest\");\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void test()\n    {\n        \n        List<String> contactName = new ArrayList<String>();\n        contactName.add(\"xamry\");\n        \n        Map<String, String> contactMap =  new HashMap<>();\n        contactMap.put(\"xamry\", \"9891991919\");\n        \n        Set<String> contactNumber = new HashSet<>();\n        contactNumber.add(\"9891991919\");\n        \n        PhoneDirectory phone = new PhoneDirectory(\"MyPhoneDirectory\",contactName,contactMap,contactNumber);\n        \n        PersonalDetailEmbedded detail = new PersonalDetailEmbedded();\n        detail.setPhoneNo(12456);\n        detail.setEmailId(\"xyz@gmail.com\");\n        detail.setAddress(\"BBBBB\");\n        detail.setPhone(phone);\n\n        PersonnelEmbedded personnel = new PersonnelEmbedded();\n        personnel.setId(1);\n        personnel.setAge(24);\n        personnel.setName(\"Kuldeep\");\n        personnel.setPersonalDetail(detail);\n\n        em.persist(personnel);\n\n        em.clear();\n\n        PersonnelEmbedded foundPersonnel = em.find(PersonnelEmbedded.class, 1);\n        Assert.assertNotNull(foundPersonnel);\n        Assert.assertNotNull(foundPersonnel.getPersonalDetail());\n        Assert.assertNotNull(foundPersonnel.getPersonalDetail().getPhone());\n        Assert.assertEquals(\"xamry\", foundPersonnel.getPersonalDetail().getPhone().getContactName().get(0));\n        Set<String> hashSet = new HashSet<String>();\n        hashSet.add(\"9891991919\");\n        Assert.assertEquals(hashSet, foundPersonnel.getPersonalDetail().getPhone().getContactNumber());\n\n        List<PersonnelEmbedded> personnels = em.createQuery(\"Select p from PersonnelEmbedded p\").getResultList();\n        Assert.assertNotNull(personnels);\n        Assert.assertFalse(personnels.isEmpty());\n        Assert.assertNotNull(personnels.get(0));\n        Assert.assertNotNull(personnels.get(0).getPersonalDetail());\n        Assert.assertNotNull(personnels.get(0).getPersonalDetail().getPhone());\n        Assert.assertEquals(\"xamry\", personnels.get(0).getPersonalDetail().getPhone().getContactName().get(0));\n        Assert.assertEquals(hashSet, personnels.get(0).getPersonalDetail().getPhone().getContactNumber());\n\n        personnels = em.createQuery(\"Select p from PersonnelEmbedded p where p.age=24\").getResultList();\n        Assert.assertNotNull(personnels);\n        Assert.assertFalse(personnels.isEmpty());\n        Assert.assertNotNull(personnels.get(0));\n        Assert.assertNotNull(personnels.get(0).getPersonalDetail());\n        Assert.assertNotNull(personnels.get(0).getPersonalDetail().getPhone());\n        Assert.assertEquals(\"xamry\", personnels.get(0).getPersonalDetail().getPhone().getContactName().get(0));\n        Assert.assertEquals(hashSet, personnels.get(0).getPersonalDetail().getPhone().getContactNumber());\n        \n        personnels = em.createQuery(\"Select p from PersonnelEmbedded p where p.personalDetail.phoneNo = 12456 and p.age=24\").getResultList();\n        Assert.assertNotNull(personnels);\n        Assert.assertFalse(personnels.isEmpty());\n        Assert.assertNotNull(personnels.get(0));\n        Assert.assertNotNull(personnels.get(0).getPersonalDetail());\n        Assert.assertNotNull(personnels.get(0).getPersonalDetail().getPhone());\n        Assert.assertEquals(\"xamry\", personnels.get(0).getPersonalDetail().getPhone().getContactName().get(0));\n        Assert.assertEquals(hashSet, personnels.get(0).getPersonalDetail().getPhone().getContactNumber());\n\n        personnels = em.createQuery(\"Select p from PersonnelEmbedded p where p.personalDetail.phoneNo = 12456 and p.age=2\").getResultList();\n        Assert.assertTrue(personnels.isEmpty());\n\n        personnels = em.createQuery(\"Select p from PersonnelEmbedded p where (p.personalDetail.phoneNo = 1245) or (p.age=24)\").getResultList();\n        Assert.assertNotNull(personnels);\n        Assert.assertFalse(personnels.isEmpty());\n        Assert.assertNotNull(personnels.get(0));\n        Assert.assertNotNull(personnels.get(0).getPersonalDetail());\n        Assert.assertNotNull(personnels.get(0).getPersonalDetail().getPhone());\n        Assert.assertEquals(\"xamry\", personnels.get(0).getPersonalDetail().getPhone().getContactName().get(0));\n        Assert.assertEquals(hashSet, personnels.get(0).getPersonalDetail().getPhone().getContactNumber());\n        \n        personnels = em.createQuery(\"Select p from PersonnelEmbedded p where p.personalDetail.emailId like :email\").setParameter(\"email\" , \"xyz%\").getResultList();\n        Assert.assertNotNull(personnels);\n        Assert.assertFalse(personnels.isEmpty());\n        Assert.assertNotNull(personnels.get(0));\n        Assert.assertNotNull(personnels.get(0).getPersonalDetail());\n        Assert.assertNotNull(personnels.get(0).getPersonalDetail().getPhone());\n        Assert.assertEquals(\"xamry\", personnels.get(0).getPersonalDetail().getPhone().getContactName().get(0));\n        Assert.assertEquals(hashSet, personnels.get(0).getPersonalDetail().getPhone().getContactNumber());\n        \n        personnels = em.createQuery(\"Select p from PersonnelEmbedded p where p.personalDetail.emailId like :email\").setParameter(\"email\" , \"xyz_%\").getResultList();\n        Assert.assertNotNull(personnels);\n        Assert.assertFalse(personnels.isEmpty());\n        Assert.assertNotNull(personnels.get(0));\n        Assert.assertEquals(1, personnels.size());\n        \n        personnels = em.createQuery(\"Select p from PersonnelEmbedded p where p.personalDetail.emailId like :email\").setParameter(\"email\" , \"xyz_%\").getResultList();\n        Assert.assertNotNull(personnels);\n        Assert.assertFalse(personnels.isEmpty());\n        Assert.assertEquals(1, personnels.size());\n        \n        personnels = em.createQuery(\"Select p from PersonnelEmbedded p where p.personalDetail.emailId like :email\").setParameter(\"email\" , \"xyz\").getResultList();\n        Assert.assertNotNull(personnels);\n        Assert.assertTrue(personnels.isEmpty());\n        Assert.assertEquals(0, personnels.size());\n       \n\n    }\n\n    @Test\n    public void testAggregation()\n    {\n        PersonalDetailEmbedded embedded1 = new PersonalDetailEmbedded();\n        embedded1.setAddress(\"Address 1\");\n        embedded1.setEmailId(\"email1@company.com\");\n        embedded1.setPhoneNo(90001);\n        embedded1.setPhone(new PhoneDirectory(\"dir1\",\n              Collections.singletonList(\"contact1\"), Collections.singletonMap(\"contact1\", \"90091\"),\n              Collections.singleton(\"90091\")));\n\n        PersonnelEmbedded personnel1 = new PersonnelEmbedded();\n        personnel1.setId(1);\n        personnel1.setAge(25);\n        personnel1.setName(\"Person 1\");\n        personnel1.setPersonalDetail(embedded1);\n\n        em.persist(personnel1);\n\n        PersonalDetailEmbedded embedded2 = new PersonalDetailEmbedded();\n        embedded2.setAddress(\"Address 2\");\n        embedded2.setEmailId(\"email2@company.com\");\n        embedded2.setPhoneNo(90002);\n        embedded2.setPhone(new PhoneDirectory(\"dir2\",\n              Collections.singletonList(\"contact2\"), Collections.singletonMap(\"contact2\", \"90092\"),\n              Collections.singleton(\"90092\")));\n\n        PersonnelEmbedded personnel2 = new PersonnelEmbedded();\n        personnel2.setId(2);\n        personnel2.setAge(32);\n        personnel2.setName(\"Person 2\");\n        personnel2.setPersonalDetail(embedded2);\n\n        em.persist(personnel2);\n\n        Query query = em.createQuery(\"select max(p.id) from PersonnelEmbedded p\");\n        Object result = query.getSingleResult();\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(2, result);\n\n        query = em.createQuery(\"select min(p.id) from PersonnelEmbedded p\");\n        result = query.getSingleResult();\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(1, result);\n\n        query = em.createQuery(\"select avg(p.id) from PersonnelEmbedded p\");\n        result = query.getSingleResult();\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(1.5, result);\n\n        query = em.createQuery(\"select sum(p.id) from PersonnelEmbedded p\");\n        result = query.getSingleResult();\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(3, result);\n    }\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/ResultIteratorTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.MongoToken;\nimport com.impetus.client.crud.entities.MongoTokenClient;\nimport com.impetus.client.crud.entities.PersonMongo;\nimport com.impetus.kundera.query.IResultIterator;\nimport com.impetus.kundera.query.Query;\n\n/**\n * @author kuldeep.mishra junit for {@link IResultIterator}.\n */\npublic class ResultIteratorTest extends BaseTest\n{\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        \n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testScroll() throws Exception\n    {\n        onScroll();\n    }\n\n    @Test\n    public void testScrollAssociation() throws Exception\n    {\n        assertOnTokenScroll();\n    }\n\n    private void assertOnTokenScroll()\n    {\n        MongoToken token1 = new MongoToken();\n        token1.setId(\"MongoTokenId1\");\n        token1.setTokenName(\"tokenName1\");\n        MongoTokenClient client = new MongoTokenClient();\n        client.setClientName(\"tokenClient1\");\n        client.setId(\"tokenClientId\");\n        token1.setClient(client);\n\n        MongoToken token2 = new MongoToken();\n        token2.setId(\"tokenId2\");\n        token2.setTokenName(\"tokenName2\");\n        token2.setClient(client);\n        em.persist(token1);\n        em.persist(token2);\n\n        String queryWithoutClause = \"Select t from MongoToken t\";\n        assertOnTokenScroll(queryWithoutClause, 2);\n\n        String queryWithClause = \"Select t from MongoToken t where t.tokenName='tokenName1'\";\n\n        assertOnTokenScroll(queryWithClause, 1);\n\n        // TODO:: Need to discuss with KK, this should be working with token\n        // support. Special scenario.\n        String queryWithIdClause = \"Select t from MongoToken t where t.tokenId = 'MongoTokenId1'\";\n        //\n        assertOnTokenScroll(queryWithIdClause, 1);\n\n    }\n\n    private void assertOnTokenScroll(String queryClause, int expected)\n    {\n        Query query = (Query) em.createQuery(queryClause, MongoToken.class);\n\n        int count = 0;\n        Iterator<MongoToken> tokens = query.iterate();\n        while (tokens.hasNext())\n        {\n            MongoToken token = tokens.next();\n            Assert.assertNotNull(token);\n            Assert.assertNotNull(token.getClient());\n            Assert.assertEquals(2, token.getClient().getTokens().size());\n            count++;\n        }\n\n        Assert.assertTrue(count > 0);\n        Assert.assertTrue(count == expected);\n    }\n\n    private void onScroll()\n    {\n        Object p1 = prepareMongoInstance(\"1\", 10);\n        Object p2 = prepareMongoInstance(\"2\", 20);\n        Object p3 = prepareMongoInstance(\"3\", 15);\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        em.flush();\n        em.clear();\n        final String queryWithoutClause = \"Select p from PersonMongo p\";\n\n        assertOnScroll(queryWithoutClause, 3);\n\n        final String queryWithClause = \"Select p from PersonMongo p where p.personName = vivek\";\n\n        assertOnScroll(queryWithClause, 3);\n\n        final String queryWithAndClause = \"Select p from PersonMongo p where p.personName = vivek and p.age = 15\";\n\n        assertOnScroll(queryWithAndClause, 1);\n\n        final String queryWithLTClause = \"Select p from PersonMongo p where p.personName = vivek and p.age < 15\";\n\n        assertOnScroll(queryWithLTClause, 1);\n\n        final String queryWithGTClause = \"Select p from PersonMongo p where p.personName = vivek and p.age >= 15\";\n\n        assertOnScroll(queryWithGTClause, 2);\n\n        final String queryWithLTGTClause = \"Select p from PersonMongo p where p.personName = vivek and p.age > 10 and p.age < 20\";\n\n        assertOnScroll(queryWithLTGTClause, 1);\n\n        final String queryWithLTGTEClause = \"Select p from PersonMongo p where p.personName = vivek and p.age >= 10 and p.age < 20\";\n\n        assertOnScroll(queryWithLTGTEClause, 2);\n\n        String queryWithIdClause = \"Select p from PersonMongo p where p.personId = '2' \";\n        assertOnScroll(queryWithIdClause, 1);\n    }\n\n    private void assertOnScroll(final String queryWithoutClause, int expectedCount)\n    {\n        Query query = (Query) em.createQuery(queryWithoutClause, PersonMongo.class);\n\n        assertOnFetch(query, 0, expectedCount);\n        assertOnFetch(query, 2, expectedCount); // less records\n\n        assertOnFetch(query, 4, expectedCount); // more fetch size than\n                                                // available in db.\n        assertOnFetch(query, 3, expectedCount); // more fetch size than\n                                                // available in db.\n\n        assertOnFetch(query, null, expectedCount); // set to null;\n\n    }\n\n    private void assertOnFetch(Query query, Integer fetchSize, int available)\n    {\n        query.setFetchSize(fetchSize);\n        int counter = 0;\n        Iterator<PersonMongo> iter = query.iterate();\n\n        while (iter.hasNext())\n        {\n            Assert.assertNotNull(iter.next());\n            counter++;\n        }\n\n        Assert.assertEquals(counter, fetchSize == null || available < fetchSize ? available : fetchSize);\n        try\n        {\n            iter.next();\n            Assert.fail();\n        }\n        catch (NoSuchElementException nsex)\n        {\n            Assert.assertNotNull(nsex.getMessage());\n        }\n    }\n\n    @After\n    public void tearDown()\n    {\n\n    }\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/SecondaryTableEntity.java",
    "content": "package com.impetus.client.crud;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.SecondaryTable;\nimport javax.persistence.Table;\n\n\n@Table(name = \"PRIMARY_TABLE\")\n@SecondaryTable(name = \"SECONDARY_TABLE\")\n@Entity\npublic class SecondaryTableEntity\n{\n    @Id\n    @Column(name = \"OBJECT_ID\")\n    private String objectId;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    @Column(name = \"AGE\", table = \"SECONDARY_TABLE\")\n    private int age;\n\n    @Embedded\n    private EmbeddedEntity embeddedEntity;\n\n    public String getObjectId()\n    {\n        return objectId;\n    }\n\n    public void setObjectId(String objectId)\n    {\n        this.objectId = objectId;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public EmbeddedEntity getEmbeddedEntity()\n    {\n        return embeddedEntity;\n    }\n\n    public void setEmbeddedEntity(EmbeddedEntity embeddedEntity)\n    {\n        this.embeddedEntity = embeddedEntity;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/SelfReferentialUserOTMTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * @author Devender Yadav\n * \n */\n\npublic class SelfReferentialUserOTMTest {\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception {\n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n        em = getNewEM();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void test() {\n\n        em = getNewEM();\n\n        UserOTM user1 = new UserOTM();\n        user1.setUserId(\"1\");\n        user1.setUsername(\"vivek\");\n\n        UserOTM user2 = new UserOTM();\n        user2.setUserId(\"2\");\n        user2.setUsername(\"dev\");\n\n        UserOTM user3 = new UserOTM();\n        user3.setUserId(\"3\");\n        user3.setUsername(\"amit\");\n\n        user1.addFollower(user2);\n        user2.addFollower(user3);\n\n        em.persist(user1);\n\n        em = getNewEM();\n\n        UserOTM u1 = em.find(UserOTM.class, \"1\");\n        Assert.assertEquals(\"1\", u1.getUserId());\n        Assert.assertEquals(\"vivek\", u1.getUsername());\n        Assert.assertEquals(1, u1.getFollowers().size());\n        Assert.assertEquals(\"2\", u1.getFollowers().get(0).getUserId());\n        Assert.assertEquals(\"dev\", u1.getFollowers().get(0).getUsername());\n\n        UserOTM u2 = em.find(UserOTM.class, \"2\");\n        Assert.assertEquals(\"2\", u2.getUserId());\n        Assert.assertEquals(\"dev\", u2.getUsername());\n        Assert.assertEquals(1, u2.getFollowers().size());\n        Assert.assertEquals(\"3\", u2.getFollowers().get(0).getUserId());\n        Assert.assertEquals(\"amit\", u2.getFollowers().get(0).getUsername());\n\n        UserOTM u3 = em.find(UserOTM.class, \"3\");\n        Assert.assertEquals(\"3\", u3.getUserId());\n        Assert.assertEquals(\"amit\", u3.getUsername());\n        \n        List<UserOTM> userList = em.createQuery(\"select u from UserOTM u \").getResultList();\n        Assert.assertNotNull(userList);\n        Assert.assertEquals(3, userList.size());\n        \n        \n        userList = em.createQuery(\"select u from UserOTM u where u.username = 'vivek'\").getResultList();\n        Assert.assertEquals(1, userList.size());\n        UserOTM user = userList.get(0);\n        Assert.assertEquals(\"1\", user.getUserId());\n        Assert.assertEquals(\"vivek\", user.getUsername());\n        Assert.assertEquals(1, user.getFollowers().size());\n        Assert.assertEquals(\"2\", user.getFollowers().get(0).getUserId());\n        Assert.assertEquals(\"dev\", user.getFollowers().get(0).getUsername());\n\n        userList = em.createQuery(\"select u from UserOTM u where u.username = 'dev'\").getResultList();\n        Assert.assertEquals(1, userList.size());\n        user = userList.get(0);\n        Assert.assertEquals(\"2\", user.getUserId());\n        Assert.assertEquals(\"dev\", user.getUsername());\n        Assert.assertEquals(1, user.getFollowers().size());\n        Assert.assertEquals(\"3\", user.getFollowers().get(0).getUserId());\n        Assert.assertEquals(\"amit\", user.getFollowers().get(0).getUsername());\n\n        userList = em.createQuery(\"select u from UserOTM u where u.username = 'amit'\").getResultList();\n        Assert.assertEquals(1, userList.size());\n        user = userList.get(0);\n        Assert.assertEquals(\"3\", user.getUserId());\n        Assert.assertEquals(\"amit\", user.getUsername());\n\n    }\n\n    /**\n     * @return\n     */\n    private EntityManager getNewEM() {\n        if (em != null && em.isOpen()) {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/UserOTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * @author Devender Yadav\n * \n */\n\n@Entity\n@Table(name = \"USER\", schema = \"KunderaExamples@mongoTest\")\npublic class UserOTM {\n\n    @Id\n    @Column(name = \"USER_ID\")\n    private String userId;\n\n    @Column(name = \"USER_NAME\")\n    private String username;\n    \n   \n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"FOLLOWER_ID\")\n    private List<UserOTM> followers; \n\n    public void addFollower(UserOTM follower) {\n        if (this.followers == null || this.followers.isEmpty()) {\n            this.followers = new ArrayList<UserOTM>();\n        }\n\n        this.followers.add(follower);\n    }\n    \n    \n    public void setUserId(String userId) {\n        this.userId = userId;\n    }\n\n    public String getUserId() {\n        return userId;\n    }\n\n\n    public String getUsername() {\n        return username;\n    }\n\n    public void setUsername(String username) {\n        this.username = username;\n    }\n\n    public List<UserOTM> getFollowers() {\n        return followers;\n    }\n\n    public void setFollowers(List<UserOTM> followers) {\n        this.followers = followers;\n    }   \n    \n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/UserRoleTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.crud;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.twitter.entities.RoleMongo;\nimport com.impetus.client.twitter.entities.User;\nimport com.impetus.client.utils.MongoUtils;\n\n/**\n * The Class UserRoleTest.\n */\npublic class UserRoleTest\n{\n\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up.\n     */\n    @Before\n    public void setUp()\n    {\n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test association.\n     */\n    @Test\n    public void testPersist()\n    {\n        RoleMongo rol = new RoleMongo();\n        rol.setRolId(1);\n        rol.setName(\"Administrador\");\n        User u = new User();\n        u.setAge(15);\n        u.setEmail(\"usuario1@infos.com\");\n        u.setName(\"usuario1\");\n        u.setUserId(1);\n        u.setLastName(\"apellido1\");\n        User u2 = new User();\n        u2.setAge(17);\n        u2.setEmail(\"usuario2@infos.com\");\n        u2.setName(\"usuario2\");\n        u2.setUserId(2);\n        u2.setLastName(\"apellido2\");\n        u.setUserRol(rol);\n        u2.setUserRol(rol);\n        List<User> users = new ArrayList<User>();\n        users.add(u);\n        users.add(u2);\n        rol.setSegUsuarioList(users);\n        em.persist(rol);\n\n    }\n\n    /**\n     * Test findby role.\n     */\n    @Test\n    public void testFindbyRole()\n    {\n        testPersist();\n        String query = \"Select r from RoleMongo r\";\n        Query q = em.createQuery(query);\n        List<RoleMongo> roles = q.getResultList();\n        Assert.assertNotNull(roles);\n        Assert.assertEquals(1, roles.size());\n    }\n\n    /**\n     * Test findby user.\n     */\n    @Test\n    public void testFindbyUser()\n    {\n        testPersist();\n        List<User> users = getAllUsers();\n        Assert.assertNotNull(users);\n        Assert.assertEquals(2, users.size());\n    }\n\n    /**\n     * Tear down.\n     */\n    @After\n    public void tearDown()\n    {\n        RoleMongo rol = em.find(RoleMongo.class, 1);\n        if (rol != null)\n        {\n            em.remove(rol);\n        }\n\n        MongoUtils.dropDatabase(emf, \"mongoTest\");\n        em.close();\n\n        em = null;\n        emf.close();\n    }\n\n    /**\n     * @return\n     */\n    private List<User> getAllUsers()\n    {\n        String query = \"Select u from User u\";\n        Query q = em.createQuery(query);\n        List<User> users = q.getResultList();\n        return users;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/autogeneratedid/AutoGeneratedUser.java",
    "content": "package com.impetus.client.crud.autogeneratedid;\r\n\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.GeneratedValue;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.Table;\r\n\r\n@Entity\r\n@Table(name = \"AutoGeneratedUser\", schema = \"KunderaExamples@mongoTest\")\r\npublic class AutoGeneratedUser\r\n{\r\n\r\n    @GeneratedValue\r\n    @Id\r\n    private String userID;\r\n\r\n    @Column(name = \"name\")\r\n    private String name;\r\n\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    private Set<Document> documents;\r\n\r\n    /**\r\n     * @return the userID\r\n     */\r\n    public String getUserID()\r\n    {\r\n        return userID;\r\n    }\r\n\r\n    /**\r\n     * @param userID\r\n     *            the userID to set\r\n     */\r\n    public void setUserID(String userID)\r\n    {\r\n        this.userID = userID;\r\n    }\r\n\r\n    /**\r\n     * @return the name\r\n     */\r\n    public String getName()\r\n    {\r\n        return name;\r\n    }\r\n\r\n    /**\r\n     * @param name\r\n     *            the name to set\r\n     */\r\n    public void setName(String name)\r\n    {\r\n        this.name = name;\r\n    }\r\n\r\n    /**\r\n     * @return the documents\r\n     */\r\n    public Set<Document> getDocuments()\r\n    {\r\n        return documents;\r\n    }\r\n\r\n    /**\r\n     * @param documents\r\n     *            the documents to set\r\n     */\r\n    public void setDocuments(Set<Document> documents)\r\n    {\r\n        this.documents = documents;\r\n    }\r\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/autogeneratedid/Cubicle.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.autogeneratedid;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"Cubicle\", schema = \"KunderaExamples@mongoTest\")\npublic class Cubicle\n{\n\n    @GeneratedValue\n    @Id\n    private String cubeID;\n\n    @Column(name = \"name\")\n    private String name;\n\n    @OneToOne(fetch = FetchType.EAGER)\n    private EmployeeCubicle residentEmployee;\n\n    public String getCubeID()\n    {\n        return cubeID;\n    }\n\n    public void setCubeID(String cubeID)\n    {\n        this.cubeID = cubeID;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    // @OneToOne(mappedBy=\"assignedCubicle\")\n    public EmployeeCubicle getResidentEmployee()\n    {\n        return residentEmployee;\n    }\n\n    public void setResidentEmployee(EmployeeCubicle employee)\n    {\n        this.residentEmployee = employee;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/autogeneratedid/Document.java",
    "content": "package com.impetus.client.crud.autogeneratedid;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.GeneratedValue;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.ManyToOne;\r\nimport javax.persistence.Table;\r\n\r\n@Entity\r\n@Table(name = \"Document\", schema = \"KunderaExamples@mongoTest\")\r\npublic class Document\r\n{\r\n\r\n    @GeneratedValue\r\n    @Id\r\n    private String documentID;\r\n\r\n    @Column(name = \"name\")\r\n    private String name;\r\n\r\n    @ManyToOne(fetch = FetchType.EAGER)\r\n    private AutoGeneratedUser user;\r\n\r\n    public Document()\r\n    {\r\n    }\r\n\r\n    public String getDocumentID()\r\n    {\r\n        return documentID;\r\n    }\r\n\r\n    public void setDocumentID(String documentID)\r\n    {\r\n        this.documentID = documentID;\r\n    }\r\n\r\n    public String getName()\r\n    {\r\n        return name;\r\n    }\r\n\r\n    public void setName(String name)\r\n    {\r\n        this.name = name;\r\n    }\r\n\r\n    public AutoGeneratedUser getUser()\r\n    {\r\n        return user;\r\n    }\r\n\r\n    public void setUser(AutoGeneratedUser user)\r\n    {\r\n        this.user = user;\r\n    }\r\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/autogeneratedid/EmployeeCubicle.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.autogeneratedid;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"EmployeeCubicle\", schema = \"KunderaExamples@mongoTest\")\npublic class EmployeeCubicle\n{\n\n    @GeneratedValue\n    @Id\n    private String empId;\n\n    @Column(name = \"emp_name\")\n    private String name;\n\n    @OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    private Cubicle assignedCubicle;\n\n    /**\n     * @return the userID\n     */\n    public String getEMPID()\n    {\n        return empId;\n    }\n\n    /**\n     * @param userID\n     *            the userID to set\n     */\n    public void setEMPID(String empId)\n    {\n        this.empId = empId;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public Cubicle getAssignedCubicle()\n    {\n        return assignedCubicle;\n    }\n\n    public void setAssignedCubicle(Cubicle cubicle)\n    {\n        this.assignedCubicle = cubicle;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/autogeneratedid/EmployeeCubicleTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.autogeneratedid;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.utils.MongoUtils;\n\npublic class EmployeeCubicleTest\n{\n    private static final String _PU = \"mongoTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(_PU);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testUser()\n    {\n        EmployeeCubicle emp1 = new EmployeeCubicle();\n        emp1.setName(\"test1\");\n\n        Cubicle cube1 = new Cubicle();\n        cube1.setName(\"Cube 1\");\n\n        cube1.setResidentEmployee(emp1);\n        emp1.setAssignedCubicle(cube1);\n\n        em.persist(emp1);\n        em.clear();\n        \n        EmployeeCubicle emp2 = new EmployeeCubicle();\n        emp2.setName(\"test2\");\n\n        Cubicle cube2 = new Cubicle();\n        cube2.setName(\"Cube 2\");\n\n        Query q = em.createQuery(\"select e from EmployeeCubicle e where e.name = 'test1'\");\n        List<EmployeeCubicle> employees = q.getResultList();\n\n        Assert.assertNotNull(employees);\n        EmployeeCubicle employee = employees.get(0);\n        Assert.assertNotNull(employee.getAssignedCubicle());\n        Assert.assertEquals(\"Cube 1\", employee.getAssignedCubicle().getName());\n        Assert.assertEquals(employee.getEMPID(), cube1.getResidentEmployee().getEMPID());\n\n        employee.setAssignedCubicle(cube2);\n\n        em.merge(employee);\n        em.clear();\n        \n        q = em.createQuery(\"select e from EmployeeCubicle e where e.name = 'test1'\");\n        employees = q.getResultList();\n        Assert.assertNotNull(employees);\n        employee = employees.get(0);\n        Assert.assertNotNull(employee.getAssignedCubicle());\n        Assert.assertEquals(\"Cube 2\", employee.getAssignedCubicle().getName());\n        em.clear();\n\n    }\n\n    @After\n    public void tearDown()\n    {\n        em.close();\n        MongoUtils.dropDatabase(emf, _PU);\n        emf.close();\n        \n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/autogeneratedid/OneToManyAutoGenerationTest.java",
    "content": "package com.impetus.client.crud.autogeneratedid;\r\n\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Persistence;\r\nimport javax.persistence.Query;\r\n\r\nimport org.junit.After;\r\nimport org.junit.Assert;\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\n\r\nimport com.impetus.client.utils.MongoUtils;\r\n\r\npublic class OneToManyAutoGenerationTest\r\n{\r\n    private static final String _PU = \"mongoTest\";\r\n\r\n    /** The emf. */\r\n    private static EntityManagerFactory emf;\r\n\r\n    /** The em. */\r\n    private static EntityManager em;\r\n\r\n    @Before\r\n    public void setUp() throws Exception\r\n    {\r\n        emf = Persistence.createEntityManagerFactory(_PU);\r\n        em = emf.createEntityManager();\r\n    }\r\n\r\n    @Test\r\n    public void testUser()\r\n    {\r\n        AutoGeneratedUser user1 = new AutoGeneratedUser();\r\n        user1.setName(\"test1\");\r\n\r\n        Set<Document> documents = new HashSet<Document>();\r\n\r\n        Document document1 = new Document();\r\n        document1.setName(\"Doc 1\");\r\n\r\n        documents.add(document1);\r\n\r\n        Document document2 = new Document();\r\n        document2.setName(\"Doc 2\");\r\n\r\n        documents.add(document2);\r\n\r\n        user1.setDocuments(documents);\r\n\r\n        em.persist(user1);\r\n\r\n        Query q = em.createQuery(\"select u from AutoGeneratedUser u where u.name = 'test1'\");\r\n        List<AutoGeneratedUser> users = q.getResultList();\r\n        Assert.assertNotNull(users);\r\n        AutoGeneratedUser autoGeneratedUser = users.get(0);\r\n        Assert.assertNotNull(autoGeneratedUser.getDocuments());\r\n        Assert.assertEquals(2, autoGeneratedUser.getDocuments().size());\r\n        for (Document document : autoGeneratedUser.getDocuments())\r\n        {\r\n            Assert.assertNotNull(document.getUser());\r\n            Assert.assertEquals(\"test1\", document.getUser().getName());\r\n        }\r\n\r\n        Document document3 = new Document();\r\n        document3.setName(\"Doc 3\");\r\n\r\n        autoGeneratedUser.getDocuments().add(document3);\r\n\r\n        em.persist(autoGeneratedUser);\r\n\r\n        em.clear();\r\n\r\n        q = em.createQuery(\"select u from AutoGeneratedUser u where u.name = 'test1'\");\r\n        users = q.getResultList();\r\n        Assert.assertNotNull(users);\r\n        autoGeneratedUser = users.get(0);\r\n        Assert.assertNotNull(autoGeneratedUser.getDocuments());\r\n        Assert.assertEquals(3, autoGeneratedUser.getDocuments().size());\r\n        for (Document document : autoGeneratedUser.getDocuments())\r\n        {\r\n            Assert.assertNotNull(document.getUser());\r\n            Assert.assertEquals(\"test1\", document.getUser().getName());\r\n        }\r\n        Document document4 = new Document();\r\n        document4.setName(\"Doc 4\");\r\n        document4.setDocumentID(\"doc4\");\r\n\r\n        autoGeneratedUser.getDocuments().add(document4);\r\n\r\n        em.merge(autoGeneratedUser);\r\n        \r\n        em.clear();\r\n\r\n        q = em.createQuery(\"select u from AutoGeneratedUser u where u.name = 'test1'\");\r\n        users = q.getResultList();\r\n        Assert.assertNotNull(users);\r\n        autoGeneratedUser = users.get(0);\r\n        Assert.assertNotNull(autoGeneratedUser.getDocuments());\r\n        Assert.assertEquals(4, autoGeneratedUser.getDocuments().size());\r\n        for (Document document : autoGeneratedUser.getDocuments())\r\n        {\r\n            Assert.assertNotNull(document.getUser());\r\n            Assert.assertEquals(\"test1\", document.getUser().getName());\r\n        }\r\n        boolean persisted = false;\r\n        for (Document document : autoGeneratedUser.getDocuments())\r\n        {\r\n            if (document.getDocumentID().equals(\"doc4\"))\r\n            {\r\n                Assert.assertEquals(\"Doc 4\", document.getName());\r\n                persisted = true;\r\n            }\r\n        }\r\n        Assert.assertTrue(persisted);\r\n\r\n    }\r\n\r\n    @After\r\n    public void tearDown()\r\n    {\r\n        em.close();\r\n        MongoUtils.dropDatabase(emf, _PU);\r\n        emf.close();\r\n        \r\n    }\r\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/autogeneratedid/Product.java",
    "content": "package com.impetus.client.crud.autogeneratedid;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"product\", schema = \"KunderaExamples@mongoTest\")\npublic class Product implements Serializable\n{\n    private static final long serialVersionUID = 4242890624607140773L;\n\n    /**\n     * Id of the product\n     */\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    @Column(name = \"product_id\")\n    private String productId;\n\n    /**\n     * Name of the product\n     */\n    @Column(name = \"product_name\")\n    private String productName;\n\n    public String getProductId()\n    {\n        return productId;\n    }\n\n    public String getProductName()\n    {\n        return productName;\n    }\n\n    public void setProductName(String productName)\n    {\n        this.productName = productName;\n    }\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/autogeneratedid/ProductEcosystemMap.java",
    "content": "package com.impetus.client.crud.autogeneratedid;\n\nimport java.io.Serializable;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"product_ecosystem_map\", schema = \"KunderaExamples@mongoTest\")\npublic class ProductEcosystemMap implements Serializable\n{\n    private static final long serialVersionUID = 8153462679027161808L;\n\n    /**\n     * Primary key for the table\n     */\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    @Column\n    private String _id;\n\n    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)\n    @JoinColumn(name = \"product_id\", referencedColumnName = \"product_id\")\n    private Product product;\n\n    @Column(name = \"product_ref_id\")\n    private String productRefId;\n\n    public String get_id()\n    {\n        return _id;\n    }\n\n    public Product getProduct()\n    {\n        return product;\n    }\n\n    public void setProduct(Product product)\n    {\n        this.product = product;\n    }\n\n    public String getProductRefId()\n    {\n        return productRefId;\n    }\n\n    public void setProductRefId(String productRefId)\n    {\n        this.productRefId = productRefId;\n    }\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/autogeneratedid/ProductEcosystemMapTest.java",
    "content": "package com.impetus.client.crud.autogeneratedid;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.utils.MongoUtils;\n\npublic class ProductEcosystemMapTest\n{\n    private static final String _PU = \"mongoTest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(_PU);\n        em = emf.createEntityManager();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        MongoUtils.dropDatabase(emf, _PU);\n        emf.close();\n        \n    }\n\n    @Test\n    public void test()\n    {\n        Product product = new Product();\n        product.setProductName(\"Pen\");\n\n        em.persist(product);\n\n        em.clear();\n\n        Query q = em.createQuery(\"Select p from Product p\");\n        List<Product> products = q.getResultList();\n        Assert.assertNotNull(products);\n        Assert.assertEquals(1, products.size());\n        \n        em.remove(em.find(Product.class, products.get(0).getProductId()));\n\n        ProductEcosystemMap ecosystem = new ProductEcosystemMap();\n        ecosystem.setProduct(products.get(0));\n        ecosystem.setProductRefId(\"p\");\n\n        em.persist(ecosystem);\n\n        em.clear();\n\n        q = em.createQuery(\"Select p from ProductEcosystemMap p\");\n        List<ProductEcosystemMap> productMaps = q.getResultList();\n        Assert.assertNotNull(productMaps);\n        Assert.assertNotNull(productMaps.get(0).getProduct());\n    }\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/compositeType/MongoCompositeTypeTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.lang.reflect.Field;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.databene.contiperf.PerfTest;\nimport org.databene.contiperf.junit.ContiPerfRule;\nimport org.databene.contiperf.report.CSVSummaryReportModule;\nimport org.databene.contiperf.report.HtmlReportModule;\nimport org.databene.contiperf.report.ReportModule;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.mongodb.MongoDBClient;\nimport com.impetus.kundera.client.Client;\nimport com.mongodb.DB;\n\n/**\n * @author vivek.mishra\n * \n */\n\npublic class MongoCompositeTypeTest\n{\n    private EntityManagerFactory emf;\n\n    private static final Logger logger = LoggerFactory.getLogger(MongoCompositeTypeTest.class);\n\n    @Rule\n    public ContiPerfRule i = new ContiPerfRule(new ReportModule[] { new CSVSummaryReportModule(),\n            new HtmlReportModule() });\n\n    private Date currentDate = new Date();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = null;\n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n    }\n\n    /**\n     * CRUD over Compound primary Key.\n     */\n    @Test\n    @PerfTest(invocations = 10)\n    public synchronized void onCRUD()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        MongoCompoundKey key = new MongoCompoundKey(\"mevivs\", 1, timeLineId);\n        MongoPrimeUser user = new MongoPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.close(); // optional,just to clear persistence cache.\n\n        em = emf.createEntityManager();\n        MongoPrimeUser result = em.find(MongoPrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"my first tweet\", result.getTweetBody());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n\n        em.clear();// optional,just to clear persistence cache.\n\n        user.setTweetBody(\"After merge\");\n        em.merge(user);\n\n        em.close();// optional,just to clear persistence cache.\n\n        em = emf.createEntityManager();\n        result = em.find(MongoPrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"After merge\", result.getTweetBody());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n\n        // deleting composite\n        em.remove(result);\n\n        em.close();// optional,just to clear persistence cache.\n\n        em = emf.createEntityManager();\n        result = em.find(MongoPrimeUser.class, key);\n        Assert.assertNull(result);\n    }\n\n    @Test\n    public synchronized void onQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        MongoCompoundKey key = new MongoCompoundKey(\"mevivs\", 1, timeLineId);\n        MongoPrimeUser user = new MongoPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.close(); // optional,just to clear persistence cache.\n        em = emf.createEntityManager();\n        final String noClause = \"Select u from MongoPrimeUser u\";\n\n        final String withFirstCompositeColClause = \"Select u from MongoPrimeUser u where u.key.userId = :userId\";\n\n        final String withClauseOnNoncomposite = \"Select u from MongoPrimeUser u where u.tweetDate = ?1\";\n\n        // NOSQL Intelligence to teach that query is invalid because partition\n        // key is not present?\n        final String withSecondCompositeColClause = \"Select u from MongoPrimeUser u where u.key.tweetId = :tweetId\";\n        final String withBothCompositeColClause = \"Select u from MongoPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId\";\n        final String withAllCompositeColClause = \"Select u from MongoPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        final String withLastCompositeColGTClause = \"Select u from MongoPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId >= :timeLineId\";\n\n        final String withSelectiveCompositeColClause = \"Select u.key from MongoPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n\n        // query over 1 composite and 1 non-column\n\n        // query with no clause.\n        Query q = em.createQuery(noClause);\n        List<MongoPrimeUser> results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withFirstCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        \n     // Query with composite key clause.\n        q = em.createQuery(withFirstCompositeColClause);\n        q.setParameter(\"userId\", \"kkmishra\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(0, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withClauseOnNoncomposite);\n        q.setParameter(1, currentDate);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withSecondCompositeColClause);\n        q.setParameter(\"tweetId\", 1);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        \n        // Query with composite key clause.\n        q = em.createQuery(withBothCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withLastCompositeColGTClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        // TODO::\n         Assert.assertEquals(1, results.size());\n\n        // Query with composite key with selective clause.\n        q = em.createQuery(withSelectiveCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertNull(results.get(0).getTweetBody());\n\n        final String selectiveColumnTweetBodyWithAllCompositeColClause = \"Select u.tweetBody from MongoPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        // Query for selective column tweetBody with composite key clause.\n        q = em.createQuery(selectiveColumnTweetBodyWithAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"my first tweet\", results.get(0).getTweetBody());\n        Assert.assertNull(results.get(0).getTweetDate());\n\n        final String selectiveColumnTweetDateWithAllCompositeColClause = \"Select u.tweetDate from MongoPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        // Query for selective column tweetDate with composite key clause.\n        q = em.createQuery(selectiveColumnTweetDateWithAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(currentDate.getTime(), results.get(0).getTweetDate().getTime());\n        Assert.assertNull(results.get(0).getTweetBody());\n\n        final String withCompositeKeyClause = \"Select u from MongoPrimeUser u where u.key = :key\";\n        // Query with composite key clause.\n        q = em.createQuery(withCompositeKeyClause);\n        q.setParameter(\"key\", key);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        em.remove(user);\n\n        em.clear();// optional,just to clear persistence cache.\n    }\n\n    @Test\n    public synchronized void onNamedQueryTest()\n    {\n        updateNamed();\n        deleteNamed();\n\n    }\n\n    /**\n     * Update by Named Query.\n     * \n     * @return\n     */\n    private void updateNamed()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n\n        MongoCompoundKey key = new MongoCompoundKey(\"mevivs\", 1, timeLineId);\n        MongoPrimeUser user = new MongoPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setTweetDate(currentDate);\n        em.persist(user);\n\n        em.close();\n\n        em = emf.createEntityManager();\n\n        String updateQuery = \"Update MongoPrimeUser u SET u.tweetBody= 'after merge' where u.tweetBody= :beforeUpdate\";\n        Query q = em.createQuery(updateQuery);\n        q.setParameter(\"beforeUpdate\", \"my first tweet\");\n        q.executeUpdate();\n        em.close();\n        em = emf.createEntityManager();\n\n        MongoPrimeUser result = em.find(MongoPrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"after merge\", result.getTweetBody());\n        Assert.assertEquals(timeLineId, result.getKey().getTimeLineId());\n        Assert.assertEquals(currentDate.getTime(), result.getTweetDate().getTime());\n        em.close();\n    }\n\n    /**\n     * delete by Named Query.\n     */\n    private void deleteNamed()\n    {\n        UUID timeLineId = UUID.randomUUID();\n\n        MongoCompoundKey key = new MongoCompoundKey(\"mevivs\", 1, timeLineId);\n\n        String deleteQuery = \"Delete From MongoPrimeUser u where u.tweetBody= :tweetBody\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.setParameter(\"tweetBody\", \"after merge\");\n        q.executeUpdate();\n\n        em.close();\n        em = emf.createEntityManager();\n        MongoPrimeUser result = em.find(MongoPrimeUser.class, key);\n        Assert.assertNull(result);\n        em.close();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        truncateMongo();\n        emf.close();\n        \n    }\n\n    /**\n     * \n     */\n    private void truncateMongo()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        MongoDBClient client = (MongoDBClient) clients.get(\"mongoTest\");\n        if (client != null)\n        {\n            try\n            {\n                Field db = client.getClass().getDeclaredField(\"mongoDb\");\n                if (!db.isAccessible())\n                {\n                    db.setAccessible(true);\n                }\n                DB mongoDB = (DB) db.get(client);\n                mongoDB.dropDatabase();\n            }\n            catch (SecurityException e)\n            {\n                logger.error(\"Error while truncating database\", e);\n            }\n\n            catch (NoSuchFieldException e)\n            {\n                logger.error(\"Error while truncating database\", e);\n            }\n            catch (IllegalArgumentException e)\n            {\n                logger.error(\"Error while truncating database\", e);\n            }\n            catch (IllegalAccessException e)\n            {\n                logger.error(\"Error while truncating database\", e);\n            }\n        }\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/compositeType/MongoCompoundKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * @author vivek.mishra\n */\n@Embeddable\npublic class MongoCompoundKey\n{\n    @Column\n    private String userId;\n\n    @Column\n    private int tweetId;\n\n    @Column\n    private UUID timeLineId;\n\n    /**\n     * \n     */\n    public MongoCompoundKey()\n    {\n    }\n\n    /**\n     * @param userId\n     * @param tweetId\n     * @param timeLineId\n     */\n    public MongoCompoundKey(String userId, int tweetId, UUID timeLineId)\n    {\n        this.userId = userId;\n        this.tweetId = tweetId;\n        this.timeLineId = timeLineId;\n    }\n\n    /**\n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * @return the tweetId\n     */\n    public int getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * @return the timeLineId\n     */\n    public UUID getTimeLineId()\n    {\n        return timeLineId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/compositeType/MongoPrimeUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"User\", schema = \"KunderaExamples@mongoTest\")\npublic class MongoPrimeUser\n{\n\n    @EmbeddedId\n    private MongoCompoundKey key;\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private Date tweetDate;\n\n    public MongoPrimeUser()\n    {\n    }\n\n    public MongoPrimeUser(MongoCompoundKey key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the key\n     */\n    public MongoCompoundKey getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/compositeType/association/UserInfo.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType.association;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.client.crud.compositeType.MongoPrimeUser;\n\n/**\n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"UserInfo\", schema = \"KunderaExamples@mongoTest\")\npublic class UserInfo\n{\n\n    @Id\n    @Column(name = \"userInfo_id\")\n    private String userInfoId;\n\n    @Column(name = \"first_name\")\n    private String firstName;\n\n    @Column(name = \"last_name\")\n    private String lastName;\n\n    @Column(name = \"age\")\n    private int age;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"user_id\")\n    private List<MongoPrimeUser> timeLine;\n\n    /**\n     * \n     */\n    public UserInfo()\n    {\n    }\n\n    /**\n     * @param userInfoId\n     * @param firstName\n     * @param lastName\n     * @param age\n     * @param timeLine\n     */\n    public UserInfo(String userInfoId, String firstName, String lastName, int age, MongoPrimeUser timeLine)\n    {\n        super();\n        this.userInfoId = userInfoId;\n        this.firstName = firstName;\n        this.lastName = lastName;\n        this.age = age;\n        if(this.timeLine == null)\n        {\n            this.timeLine = new ArrayList<MongoPrimeUser>();\n        }\n        \n        this.timeLine.add(timeLine);\n    }\n\n    /**\n     * @return the userInfoId\n     */\n    public String getUserInfoId()\n    {\n        return userInfoId;\n    }\n\n    /**\n     * @return the firstName\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * @return the lastName\n     */\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @return the timeLine\n     */\n    public List<MongoPrimeUser> getTimeLine()\n    {\n        return timeLine;\n    }\n\n    /**\n     * @param firstName\n     *            the firstName to set\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/compositeType/association/UserInfoTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType.association;\n\nimport java.lang.reflect.Field;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.crud.compositeType.MongoCompositeTypeTest;\nimport com.impetus.client.crud.compositeType.MongoCompoundKey;\nimport com.impetus.client.crud.compositeType.MongoPrimeUser;\nimport com.impetus.client.mongodb.MongoDBClient;\nimport com.impetus.kundera.client.Client;\nimport com.mongodb.DB;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class UserInfoTest\n{\n\n    private EntityManagerFactory emf;\n\n    private static final Logger logger = LoggerFactory.getLogger(MongoCompositeTypeTest.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n    }\n\n    @Test\n    public void onCRUD()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Persist\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        MongoCompoundKey key = new MongoCompoundKey(\"mevivs\", 1, timeLineId);\n        MongoPrimeUser timeLine = new MongoPrimeUser(key);\n        timeLine.setTweetBody(\"my first tweet\");\n        timeLine.setTweetDate(currentDate);\n\n        UserInfo userInfo = new UserInfo(\"mevivs_info\", \"Vivek\", \"Mishra\", 31, timeLine);\n        em.persist(userInfo);\n        em.clear();\n\n        // Find\n        UserInfo result = em.find(UserInfo.class, \"mevivs_info\");\n        Assert.assertNotNull(result);\n        Assert.assertEquals(currentDate, result.getTimeLine().get(0).getTweetDate());\n        Assert.assertEquals(timeLineId, result.getTimeLine().get(0).getKey().getTimeLineId());\n        Assert.assertEquals(\"Vivek\", result.getFirstName());\n        Assert.assertEquals(31, result.getAge());\n\n        result.setFirstName(\"Kuldeep\");\n        result.setAge(23);\n\n        em.merge(result);\n\n        em.clear();\n\n        // Find\n        result = null;\n        result = em.find(UserInfo.class, \"mevivs_info\");\n        Assert.assertNotNull(result);\n        Assert.assertEquals(currentDate, result.getTimeLine().get(0).getTweetDate());\n        Assert.assertEquals(timeLineId, result.getTimeLine().get(0).getKey().getTimeLineId());\n        Assert.assertEquals(\"Kuldeep\", result.getFirstName());\n        Assert.assertEquals(23, result.getAge());\n\n        em.remove(result);\n\n        em.clear();\n        result = em.find(UserInfo.class, \"mevivs_info\");\n        Assert.assertNull(result);\n\n    }\n\n    @Test\n    public void onQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Persist\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        MongoCompoundKey key = new MongoCompoundKey(\"mevivs\", 1, timeLineId);\n        MongoPrimeUser timeLine = new MongoPrimeUser(key);\n        timeLine.setTweetBody(\"my first tweet\");\n        timeLine.setTweetDate(new Date());\n\n        UserInfo userInfo = new UserInfo(\"mevivs_info\", \"Vivek\", \"Mishra\", 31, timeLine);\n        em.persist(userInfo);\n\n        em.clear(); // optional,just to clear persistence cache.\n        final String noClause = \"Select u from UserInfo u\";\n\n        final String withClauseOnNoncomposite = \"Select u from UserInfo u where u.age = ?1\";\n\n        // NOSQL Intelligence to teach that query is invalid because partition\n        // key is not present?\n        final String withAllCompositeColClause = \"Select u from UserInfo u where u.userInfoId = :id\";\n\n        // query over 1 composite and 1 non-column\n\n        // query with no clause.\n        Query q = em.createQuery(noClause);\n        List<UserInfo> results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(31, results.get(0).getAge());\n        Assert.assertEquals(\"Vivek\", results.get(0).getFirstName());\n        Assert.assertEquals(\"Mishra\", results.get(0).getLastName());\n        Assert.assertEquals(\"mevivs_info\", results.get(0).getUserInfoId());\n        Assert.assertEquals(currentDate.getTime(), results.get(0).getTimeLine().get(0).getTweetDate().getTime());\n        Assert.assertEquals(timeLineId, results.get(0).getTimeLine().get(0).getKey().getTimeLineId());\n\n        // Query with composite key clause.\n        q = em.createQuery(withClauseOnNoncomposite);\n        q.setParameter(1, 31);\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(31, results.get(0).getAge());\n        Assert.assertEquals(\"Vivek\", results.get(0).getFirstName());\n        Assert.assertEquals(\"Mishra\", results.get(0).getLastName());\n        Assert.assertEquals(\"mevivs_info\", results.get(0).getUserInfoId());\n        Assert.assertEquals(currentDate, results.get(0).getTimeLine().get(0).getTweetDate());\n        Assert.assertEquals(timeLineId, results.get(0).getTimeLine().get(0).getKey().getTimeLineId());\n\n        // Query with composite key clause.\n        q = em.createQuery(withAllCompositeColClause);\n        q.setParameter(\"id\", \"mevivs_info\");\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(31, results.get(0).getAge());\n        Assert.assertEquals(\"Vivek\", results.get(0).getFirstName());\n        Assert.assertEquals(\"Mishra\", results.get(0).getLastName());\n        Assert.assertEquals(\"mevivs_info\", results.get(0).getUserInfoId());\n        Assert.assertEquals(currentDate, results.get(0).getTimeLine().get(0).getTweetDate());\n        Assert.assertEquals(timeLineId, results.get(0).getTimeLine().get(0).getKey().getTimeLineId());\n\n        final String selectiveColumnTweetBodyWithAllCompositeColClause = \"Select u.firstName from UserInfo u where u.userInfoId = :id\";\n        // Query with composite key clause.\n        q = em.createQuery(selectiveColumnTweetBodyWithAllCompositeColClause);\n        q.setParameter(\"id\", \"mevivs_info\");\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(0, results.get(0).getAge());\n        Assert.assertEquals(\"Vivek\", results.get(0).getFirstName());\n        Assert.assertEquals(null, results.get(0).getLastName());\n        Assert.assertEquals(\"mevivs_info\", results.get(0).getUserInfoId());\n\n        final String selectiveColumnTweetDateWithAllCompositeColClause = \"Select u.lastName from UserInfo u where u.userInfoId = :id\";\n        // Query with composite key clause.\n        q = em.createQuery(selectiveColumnTweetDateWithAllCompositeColClause);\n        q.setParameter(\"id\", \"mevivs_info\");\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(0, results.get(0).getAge());\n        Assert.assertEquals(null, results.get(0).getFirstName());\n        Assert.assertEquals(\"Mishra\", results.get(0).getLastName());\n        Assert.assertEquals(\"mevivs_info\", results.get(0).getUserInfoId());\n\n        em.remove(userInfo);\n\n        em.clear();// optional,just to clear persistence cache.\n    }\n\n    @Test\n    public void onNamedQueryTest()\n    {\n        updateNamed();\n        deleteNamed();\n\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Persist\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        MongoCompoundKey key = new MongoCompoundKey(\"mevivs\", 1, timeLineId);\n        MongoPrimeUser timeLine = new MongoPrimeUser(key);\n        timeLine.setTweetBody(\"my first tweet\");\n        timeLine.setTweetDate(currentDate);\n\n        UserInfo userInfo = new UserInfo(\"mevivs_info\", \"Vivek\", \"Mishra\", 31, timeLine);\n        em.persist(userInfo);\n\n        em = emf.createEntityManager();\n\n        String updateQuery = \"Update UserInfo u SET u.firstName=Kuldeep where u.firstName= :beforeUpdate\";\n        Query q = em.createQuery(updateQuery);\n        q.setParameter(\"beforeUpdate\", \"Vivek\");\n        q.executeUpdate();\n\n        UserInfo result = em.find(UserInfo.class, \"mevivs_info\");\n        Assert.assertNotNull(result);\n        Assert.assertEquals(currentDate, result.getTimeLine().get(0).getTweetDate());\n        Assert.assertEquals(timeLineId, result.getTimeLine().get(0).getKey().getTimeLineId());\n        Assert.assertEquals(\"Kuldeep\", result.getFirstName());\n        Assert.assertEquals(31, result.getAge());\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed()\n    {\n        UUID timeLineId = UUID.randomUUID();\n        Date currentDate = new Date();\n        MongoCompoundKey key = new MongoCompoundKey(\"mevivs\", 1, timeLineId);\n\n        String deleteQuery = \"Delete From UserInfo u where u.firstName= :firstName\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.setParameter(\"firstName\", \"Kuldeep\");\n        q.executeUpdate();\n\n        UserInfo result = em.find(UserInfo.class, \"mevivs_info\");\n        Assert.assertNull(result);\n        em.close();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        truncateMongo();\n        emf.close();\n    }\n\n    /**\n     * \n     */\n    private void truncateMongo()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        MongoDBClient client = (MongoDBClient) clients.get(\"mongoTest\");\n        if (client != null)\n        {\n            try\n            {\n                Field db = client.getClass().getDeclaredField(\"mongoDb\");\n                if (!db.isAccessible())\n                {\n                    db.setAccessible(true);\n                }\n                DB mongoDB = (DB) db.get(client);\n                mongoDB.dropDatabase();\n            }\n            catch (SecurityException e)\n            {\n                logger.error(\"Error while truncating db\",e);\n            }\n \n            catch (NoSuchFieldException e)\n            {\n                logger.error(\"Error while truncating db\",e);\n            }\n            catch (IllegalArgumentException e)\n            {\n                logger.error(\"Error while truncating db\",e);\n            }\n            catch (IllegalAccessException e)\n            {\n                logger.error(\"Error while truncating db\",e);\n            }\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/MongoBase.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.lang.reflect.Field;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\n\nimport com.impetus.client.mongodb.MongoDBClient;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.datatypes.datagenerator.DataGenerator;\nimport com.impetus.kundera.datatypes.datagenerator.DataGeneratorFactory;\nimport com.mongodb.DB;\n\npublic abstract class MongoBase\n{\n    public static final boolean RUN_IN_EMBEDDED_MODE = false;\n\n    public static final boolean AUTO_MANAGE_SCHEMA = false;\n\n    protected static final String PERSISTENCE_UNIT = \"MongoDataTypeTest\";\n\n    DataGenerator<?> dataGenerator;\n\n    DataGeneratorFactory factory = new DataGeneratorFactory();\n\n    protected Object getMaxValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.maxValue();\n    }\n\n    protected Object getMinValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.minValue();\n    }\n\n    protected Object getRandomValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.randomValue();\n    }\n\n    protected Object getPartialValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.partialValue();\n    }\n\n    /**\n     * \n     */\n    protected void truncateMongo(EntityManager em, final String persistenceUnit, final String tableName)\n    {\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        MongoDBClient client = (MongoDBClient) clients.get(persistenceUnit);\n        if (client != null)\n        {\n            try\n            {\n                Field db = client.getClass().getDeclaredField(\"mongoDb\");\n                if (!db.isAccessible())\n                {\n                    db.setAccessible(true);\n                }\n                DB mongoDB = (DB) db.get(client);\n                mongoDB.getCollection(tableName).drop();\n            }\n            catch (SecurityException e)\n            {\n                // TODO Auto-generated catch block\n                \n            }\n            catch (NoSuchFieldException e)\n            {\n                // TODO Auto-generated catch block\n                \n            }\n            catch (IllegalArgumentException e)\n            {\n                // TODO Auto-generated catch block\n                \n            }\n            catch (IllegalAccessException e)\n            {\n                // TODO Auto-generated catch block\n                \n            }\n        }\n\n    }\n\n    protected abstract void startCluster();\n\n    protected abstract void stopCluster();\n\n    protected abstract void createSchema();\n\n    protected abstract void dropSchema();\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentEntityDef.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\n\n/**\n * @author vivek.mishra\n * \n */\npublic interface StudentEntityDef\n{\n\n    /**\n     * @return the studentId\n     */\n    long getStudentId();\n\n    /**\n     * @param studentId\n     *            the studentId to set\n     */\n    void setStudentId(long studentId);\n\n    /**\n     * @return the uniqueId\n     */\n    long getUniqueId();\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    void setUniqueId(long uniqueId);\n\n    /**\n     * @return the studentName\n     */\n    String getStudentName();\n\n    /**\n     * @param studentName\n     *            the studentName to set\n     */\n    void setStudentName(String studentName);\n\n    /**\n     * @return the isExceptional\n     */\n    boolean isExceptional();\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    void setExceptional(boolean isExceptional);\n\n    /**\n     * @return the age\n     */\n    int getAge();\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    void setAge(int age);\n\n    /**\n     * @return the semester\n     */\n    char getSemester();\n\n    /**\n     * @param semester\n     *            the semester to set\n     */\n    void setSemester(char semester);\n\n    /**\n     * @return the digitalSignature\n     */\n    byte getDigitalSignature();\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    void setDigitalSignature(byte digitalSignature);\n\n    /**\n     * @return the cgpa\n     */\n    short getCgpa();\n\n    /**\n     * @param cgpa\n     *            the cgpa to set\n     */\n    void setCgpa(short cgpa);\n\n    /**\n     * @return the percentage\n     */\n    float getPercentage();\n\n    /**\n     * @param percentage\n     *            the percentage to set\n     */\n    void setPercentage(float percentage);\n\n    /**\n     * @return the height\n     */\n    double getHeight();\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    void setHeight(double height);\n\n    /**\n     * @return the enrolmentDate\n     */\n    java.util.Date getEnrolmentDate();\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    void setEnrolmentDate(java.util.Date enrolmentDate);\n\n    /**\n     * @return the enrolmentTime\n     */\n    java.util.Date getEnrolmentTime();\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    void setEnrolmentTime(java.util.Date enrolmentTime);\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    java.util.Date getJoiningDateAndTime();\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    void setJoiningDateAndTime(java.util.Date joiningDateAndTime);\n\n    /**\n     * @return the yearsSpent\n     */\n    Integer getYearsSpent();\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    void setYearsSpent(Integer yearsSpent);\n\n    /**\n     * @return the rollNumber\n     */\n    Long getRollNumber();\n\n    /**\n     * @param rollNumber\n     *            the rollNumber to set\n     */\n    void setRollNumber(Long rollNumber);\n\n    /**\n     * @return the monthlyFee\n     */\n    Double getMonthlyFee();\n\n    /**\n     * @param monthlyFee\n     *            the monthlyFee to set\n     */\n    void setMonthlyFee(Double monthlyFee);\n\n    java.sql.Date getSqlDate();\n\n    void setSqlDate(java.sql.Date sqlDate);\n\n    /**\n     * @return the sqlTimestamp\n     */\n    java.sql.Timestamp getSqlTimestamp();\n\n    /**\n     * @param sqlTimestamp\n     *            the sqlTimestamp to set\n     */\n    void setSqlTimestamp(java.sql.Timestamp sqlTimestamp);\n\n    /**\n     * @return the sqlTime\n     */\n    java.sql.Time getSqlTime();\n\n    /**\n     * @param sqlTime\n     *            the sqlTime to set\n     */\n    void setSqlTime(java.sql.Time sqlTime);\n\n    /**\n     * @return the bigInteger\n     */\n    BigInteger getBigInteger();\n\n    /**\n     * @param bigInteger\n     *            the bigInteger to set\n     */\n    void setBigInteger(BigInteger bigInteger);\n\n    /**\n     * @return the bigDecimal\n     */\n    BigDecimal getBigDecimal();\n\n    /**\n     * @param bigDecimal\n     *            the bigDecimal to set\n     */\n    void setBigDecimal(BigDecimal bigDecimal);\n\n    /**\n     * @return the calendar\n     */\n    Calendar getCalendar();\n\n    /**\n     * @param calendar\n     *            the calendar to set\n     */\n    void setCalendar(Calendar calendar);\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongo.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"STUDENT\", schema = \"KunderaExamples@mongoTest\")\n@IndexCollection(columns = { @Index(name = \"uniqueId\"), @Index(name = \"studentName\"), @Index(name = \"age\") })\npublic class StudentMongo implements StudentEntityDef\n{\n    // Primitive Types\n    @Id\n    @Column(name = \"STUDENT_ID\")\n    private long studentId;\n\n    @Column(name = \"UNIQUE_ID\")\n    private long uniqueId;\n\n    @Column(name = \"STUDENT_NAME\")\n    private String studentName;\n\n    @Column(name = \"IS_EXCEPTIONAL\")\n    private boolean isExceptional;\n\n    @Column(name = \"AGE\")\n    private int age;\n\n    @Column(name = \"SEMESTER\")\n    private char semester; // A,B,C,D,E,F for i to vi\n\n    @Column(name = \"DIGITAL_SIGNATURE\")\n    private byte digitalSignature;\n\n    @Column(name = \"CGPA\")\n    private short cgpa; // 1-10\n\n    @Column(name = \"PERCENTAGE\")\n    private float percentage;\n\n    @Column(name = \"HEIGHT\")\n    private double height;\n\n    // Date-time types\n    @Column(name = \"ENROLMENT_DATE\")\n    @Temporal(TemporalType.DATE)\n    private java.util.Date enrolmentDate;\n\n    @Column(name = \"ENROLMENT_TIME\")\n    @Temporal(TemporalType.TIME)\n    private java.util.Date enrolmentTime;\n\n    @Column(name = \"JOINING_DATE_TIME\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private java.util.Date joiningDateAndTime;\n\n    // Wrapper types\n\n    @Column(name = \"YEARS_SPENT\")\n    private Integer yearsSpent;\n\n    @Column(name = \"ROLL_NUMBER\")\n    private Long rollNumber;\n\n    @Column(name = \"MONTHLY_FEE\")\n    private Double monthlyFee;\n\n    @Column(name = \"SQL_DATE\")\n    private java.sql.Date sqlDate;\n\n    @Column(name = \"SQL_TIMESTAMP\")\n    private java.sql.Timestamp sqlTimestamp;\n\n    @Column(name = \"SQL_TIME\")\n    private java.sql.Time sqlTime;\n\n    @Column(name = \"BIG_INT\")\n    private BigInteger bigInteger;\n\n    @Column(name = \"BIG_DECIMAL\")\n    private BigDecimal bigDecimal;\n\n    @Column(name = \"CALENDAR\")\n    private Calendar calendar;\n\n    /**\n     * @return the studentId\n     */\n    public long getStudentId()\n    {\n        return studentId;\n    }\n\n    /**\n     * @param studentId\n     *            the studentId to set\n     */\n    public void setStudentId(long studentId)\n    {\n        this.studentId = studentId;\n    }\n\n    /**\n     * @return the uniqueId\n     */\n    public long getUniqueId()\n    {\n        return uniqueId;\n    }\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    public void setUniqueId(long uniqueId)\n    {\n        this.uniqueId = uniqueId;\n    }\n\n    /**\n     * @return the studentName\n     */\n    public String getStudentName()\n    {\n        return studentName;\n    }\n\n    /**\n     * @param studentName\n     *            the studentName to set\n     */\n    public void setStudentName(String studentName)\n    {\n        this.studentName = studentName;\n    }\n\n    /**\n     * @return the isExceptional\n     */\n    public boolean isExceptional()\n    {\n        return isExceptional;\n    }\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    public void setExceptional(boolean isExceptional)\n    {\n        this.isExceptional = isExceptional;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the semester\n     */\n    public char getSemester()\n    {\n        return semester;\n    }\n\n    /**\n     * @param semester\n     *            the semester to set\n     */\n    public void setSemester(char semester)\n    {\n        this.semester = semester;\n    }\n\n    /**\n     * @return the digitalSignature\n     */\n    public byte getDigitalSignature()\n    {\n        return digitalSignature;\n    }\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    public void setDigitalSignature(byte digitalSignature)\n    {\n        this.digitalSignature = digitalSignature;\n    }\n\n    /**\n     * @return the cgpa\n     */\n    public short getCgpa()\n    {\n        return cgpa;\n    }\n\n    /**\n     * @param cgpa\n     *            the cgpa to set\n     */\n    public void setCgpa(short cgpa)\n    {\n        this.cgpa = cgpa;\n    }\n\n    /**\n     * @return the percentage\n     */\n    public float getPercentage()\n    {\n        return percentage;\n    }\n\n    /**\n     * @param percentage\n     *            the percentage to set\n     */\n    public void setPercentage(float percentage)\n    {\n        this.percentage = percentage;\n    }\n\n    /**\n     * @return the height\n     */\n    public double getHeight()\n    {\n        return height;\n    }\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    public void setHeight(double height)\n    {\n        this.height = height;\n    }\n\n    /**\n     * @return the enrolmentDate\n     */\n    public java.util.Date getEnrolmentDate()\n    {\n        return enrolmentDate;\n    }\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    public void setEnrolmentDate(java.util.Date enrolmentDate)\n    {\n        this.enrolmentDate = enrolmentDate;\n    }\n\n    /**\n     * @return the enrolmentTime\n     */\n    public java.util.Date getEnrolmentTime()\n    {\n        return enrolmentTime;\n    }\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    public void setEnrolmentTime(java.util.Date enrolmentTime)\n    {\n        this.enrolmentTime = enrolmentTime;\n    }\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    public java.util.Date getJoiningDateAndTime()\n    {\n        return joiningDateAndTime;\n    }\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    public void setJoiningDateAndTime(java.util.Date joiningDateAndTime)\n    {\n        this.joiningDateAndTime = joiningDateAndTime;\n    }\n\n    /**\n     * @return the yearsSpent\n     */\n    public Integer getYearsSpent()\n    {\n        return yearsSpent;\n    }\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    public void setYearsSpent(Integer yearsSpent)\n    {\n        this.yearsSpent = yearsSpent;\n    }\n\n    /**\n     * @return the rollNumber\n     */\n    public Long getRollNumber()\n    {\n        return rollNumber;\n    }\n\n    /**\n     * @param rollNumber\n     *            the rollNumber to set\n     */\n    public void setRollNumber(Long rollNumber)\n    {\n        this.rollNumber = rollNumber;\n    }\n\n    /**\n     * @return the monthlyFee\n     */\n    public Double getMonthlyFee()\n    {\n        return monthlyFee;\n    }\n\n    /**\n     * @param monthlyFee\n     *            the monthlyFee to set\n     */\n    public void setMonthlyFee(Double monthlyFee)\n    {\n        this.monthlyFee = monthlyFee;\n    }\n\n    public java.sql.Date getSqlDate()\n    {\n        return sqlDate;\n    }\n\n    public void setSqlDate(java.sql.Date sqlDate)\n    {\n        this.sqlDate = sqlDate;\n    }\n\n    /**\n     * @return the sqlTimestamp\n     */\n    public java.sql.Timestamp getSqlTimestamp()\n    {\n        return sqlTimestamp;\n    }\n\n    /**\n     * @param sqlTimestamp\n     *            the sqlTimestamp to set\n     */\n    public void setSqlTimestamp(java.sql.Timestamp sqlTimestamp)\n    {\n        this.sqlTimestamp = sqlTimestamp;\n    }\n\n    /**\n     * @return the sqlTime\n     */\n    public java.sql.Time getSqlTime()\n    {\n        return sqlTime;\n    }\n\n    /**\n     * @param sqlTime\n     *            the sqlTime to set\n     */\n    public void setSqlTime(java.sql.Time sqlTime)\n    {\n        this.sqlTime = sqlTime;\n    }\n\n    /**\n     * @return the bigInteger\n     */\n    public BigInteger getBigInteger()\n    {\n        return bigInteger;\n    }\n\n    /**\n     * @param bigInteger\n     *            the bigInteger to set\n     */\n    public void setBigInteger(BigInteger bigInteger)\n    {\n        this.bigInteger = bigInteger;\n    }\n\n    /**\n     * @return the bigDecimal\n     */\n    public BigDecimal getBigDecimal()\n    {\n        return bigDecimal;\n    }\n\n    /**\n     * @param bigDecimal\n     *            the bigDecimal to set\n     */\n    public void setBigDecimal(BigDecimal bigDecimal)\n    {\n        this.bigDecimal = bigDecimal;\n    }\n\n    /**\n     * @return the calendar\n     */\n    public Calendar getCalendar()\n    {\n        return calendar;\n    }\n\n    /**\n     * @param calendar\n     *            the calendar to set\n     */\n    public void setCalendar(Calendar calendar)\n    {\n        this.calendar = calendar;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport com.impetus.client.crud.BaseTest;\n\n/**\n * The Class StudentBase.\n * \n * @param <E>\n *            the element type\n */\npublic abstract class StudentMongoBase<E extends StudentEntityDef> extends BaseTest\n{\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\n\n    /** The emf. */\n    protected EntityManagerFactory emf;\n\n    /** The em. */\n    protected EntityManager em;\n\n    // protected String persistenceUnit =\n    // /*\"twissandra,twibase,twingo,picmysql\"*/null;\n\n    /** The student id1. */\n    protected Object studentId1;\n\n    /** The student id2. */\n    protected Object studentId2;\n\n    /** The student id3. */\n    protected Object studentId3;\n\n    /** The enrolment date. */\n    protected Date enrolmentDate = new Date();\n\n    /** The joining date and time. */\n    protected Date joiningDateAndTime = new Date();\n\n    /** The date. */\n    protected long date = new Date().getTime();\n\n    /** The new sql date. */\n    protected java.sql.Date newSqlDate = new java.sql.Date(date);\n\n    /** The enrolment time. */\n    protected Date enrolmentTime = new Date();\n\n    /** The sql time. */\n    protected java.sql.Time sqlTime = new java.sql.Time(date);\n\n    /** The sql timestamp. */\n    protected java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(date);\n\n    /** The big decimal. */\n    protected BigDecimal bigDecimal = new BigDecimal(123456789);\n\n    /** The big integer. */\n    protected BigInteger bigInteger = new BigInteger(\"123456789\");\n\n    /** The number of students. */\n    protected int numberOfStudents = 1000;\n\n    /** The calendar. */\n    protected Calendar calendar = Calendar.getInstance();\n\n    /** The dao. */\n    // StudentDao dao;\n\n    /**\n     * Sets the up internal.\n     * \n     * @param persisntenceUnit\n     *            the new up internal\n     */\n    protected void setupInternal(String persisntenceUnit)\n    {\n        // dao = new StudentDao(persistenceUnit);\n\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startServer();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n\n        studentId1 = new Long(12345677);\n        studentId2 = new Long(12345678);\n        studentId3 = new Long(12345679);\n\n        emf = Persistence.createEntityManagerFactory(persisntenceUnit);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Sets the up internal.\n     * \n     * @param persistenceUnit\n     *            the new up internal\n     */\n    protected void teardownInternal(String persistenceUnit)\n    {\n\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopServer();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            deleteSchema();\n        }\n        if (emf != null)\n        {\n            emf.close();\n        }\n        \n    }\n\n    /**\n     * on insert.\n     * \n     * @param instance\n     *            the instance\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    protected void onInsert(E instance) throws InstantiationException, IllegalAccessException\n    {\n\n        em.persist(prepareData((Long) studentId1, 78575785897L, \"Amresh\", false, 10, 'A', (byte) 5, (short) 8,\n                (float) 61.6, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar,\n                ((E) instance.getClass().newInstance())));\n\n        em.persist(prepareData((Long) studentId2, 78575785898L, \"Amresh\", true, 20, 'C', (byte) 50, (short) 8,\n                (float) 69.6, 163.76765655, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, new BigInteger(\n                        \"1234567810\"), calendar, ((E) instance.getClass().newInstance())));\n\n        em.persist(prepareData((Long) studentId3, 78575785899L, \"Amresh\", true, 15, 'C', (byte) 50, (short) 8,\n                (float) 69.6, 163.76765656, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, new BigInteger(\n                        \"1234567811\"), calendar, ((E) instance.getClass().newInstance())));\n\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param studentId\n     *            the student id\n     * @param uniqueId\n     *            the unique id\n     * @param studentName\n     *            the student name\n     * @param isExceptional\n     *            the is exceptional\n     * @param age\n     *            the age\n     * @param semester\n     *            the semester\n     * @param digitalSignature\n     *            the digital signature\n     * @param cgpa\n     *            the cgpa\n     * @param percentage\n     *            the percentage\n     * @param height\n     *            the height\n     * @param enrolmentDate\n     *            the enrolment date\n     * @param enrolmentTime\n     *            the enrolment time\n     * @param joiningDateAndTime\n     *            the joining date and time\n     * @param yearsSpent\n     *            the years spent\n     * @param rollNumber\n     *            the roll number\n     * @param monthlyFee\n     *            the monthly fee\n     * @param newSqlDate\n     *            the new sql date\n     * @param sqlTime\n     *            the sql time\n     * @param sqlTimestamp\n     *            the sql timestamp\n     * @param bigDecimal\n     *            the big decimal\n     * @param bigInteger\n     *            the big integer\n     * @param calendar\n     *            the calendar\n     * @param o\n     *            the o\n     * @return the person\n     */\n    protected E prepareData(long studentId, long uniqueId, String studentName, boolean isExceptional, int age,\n            char semester, byte digitalSignature, short cgpa, float percentage, double height,\n            java.util.Date enrolmentDate, java.util.Date enrolmentTime, java.util.Date joiningDateAndTime,\n            Integer yearsSpent, Long rollNumber, Double monthlyFee, java.sql.Date newSqlDate, java.sql.Time sqlTime,\n            java.sql.Timestamp sqlTimestamp, BigDecimal bigDecimal, BigInteger bigInteger, Calendar calendar, E o)\n    {\n        o.setStudentId((Long) studentId);\n        o.setUniqueId(uniqueId);\n        o.setStudentName(studentName);\n        o.setExceptional(isExceptional);\n        o.setAge(age);\n        o.setSemester(semester);\n        o.setDigitalSignature(digitalSignature);\n        o.setCgpa(cgpa);\n        o.setPercentage(percentage);\n        o.setHeight(height);\n\n        o.setEnrolmentDate(enrolmentDate);\n        o.setEnrolmentTime(enrolmentTime);\n        o.setJoiningDateAndTime(joiningDateAndTime);\n\n        o.setYearsSpent(yearsSpent);\n        o.setRollNumber(rollNumber);\n        o.setMonthlyFee(monthlyFee);\n        o.setSqlDate(newSqlDate);\n        o.setSqlTime(sqlTime);\n        o.setSqlTimestamp(sqlTimestamp);\n        o.setBigDecimal(bigDecimal);\n        o.setBigInteger(bigInteger);\n        o.setCalendar(calendar);\n        return (E) o;\n    }\n\n    /**\n     * Assert on data types.\n     * \n     * @param s\n     *            the s\n     */\n    protected void assertOnDataTypes(E s)\n    {\n\n        Assert.assertNotNull(s);\n        Assert.assertEquals(((Long) studentId1).longValue(), s.getStudentId());\n        Assert.assertEquals(78575785897L, s.getUniqueId());\n        Assert.assertEquals(\"Amresh\", s.getStudentName());\n        Assert.assertEquals(false, s.isExceptional());\n        Assert.assertEquals(10, s.getAge());\n        Assert.assertEquals('A', s.getSemester());\n        Assert.assertEquals((byte) 5, s.getDigitalSignature());\n        Assert.assertEquals((short) 8, s.getCgpa());\n        Assert.assertEquals((float) 61.6, s.getPercentage());\n        Assert.assertEquals(163.76765654, s.getHeight());\n\n        Assert.assertEquals(enrolmentDate.getDate(), s.getEnrolmentDate().getDate());\n        Assert.assertEquals(enrolmentDate.getMonth(), s.getEnrolmentDate().getMonth());\n        Assert.assertEquals(enrolmentDate.getYear(), s.getEnrolmentDate().getYear());\n\n        Assert.assertEquals(enrolmentTime.getHours(), s.getEnrolmentTime().getHours());\n        Assert.assertEquals(enrolmentTime.getMinutes(), s.getEnrolmentTime().getMinutes());\n        Assert.assertEquals(enrolmentTime.getSeconds(), s.getEnrolmentTime().getSeconds());\n\n        Assert.assertEquals(joiningDateAndTime.getDate(), s.getJoiningDateAndTime().getDate());\n        Assert.assertEquals(joiningDateAndTime.getMonth(), s.getJoiningDateAndTime().getMonth());\n        Assert.assertEquals(joiningDateAndTime.getYear(), s.getJoiningDateAndTime().getYear());\n        Assert.assertEquals(joiningDateAndTime.getHours(), s.getJoiningDateAndTime().getHours());\n        Assert.assertEquals(joiningDateAndTime.getMinutes(), s.getJoiningDateAndTime().getMinutes());\n        Assert.assertEquals(joiningDateAndTime.getSeconds(), s.getJoiningDateAndTime().getSeconds());\n\n        Assert.assertEquals(newSqlDate.getDate(), s.getSqlDate().getDate());\n        Assert.assertEquals(newSqlDate.getMonth(), s.getSqlDate().getMonth());\n        Assert.assertEquals(newSqlDate.getYear(), s.getSqlDate().getYear());\n\n        Assert.assertEquals(sqlTime.getMinutes(), s.getSqlTime().getMinutes());\n        Assert.assertEquals(sqlTime.getSeconds(), s.getSqlTime().getSeconds());\n        Assert.assertEquals(sqlTime.getHours(), s.getSqlTime().getHours());\n\n        Assert.assertEquals(sqlTimestamp.getDate(), s.getSqlTimestamp().getDate());\n        Assert.assertEquals(sqlTimestamp.getMonth(), s.getSqlTimestamp().getMonth());\n        Assert.assertEquals(sqlTimestamp.getYear(), s.getSqlTimestamp().getYear());\n        Assert.assertEquals(sqlTimestamp.getHours(), s.getSqlTimestamp().getHours());\n        Assert.assertEquals(sqlTimestamp.getMinutes(), s.getSqlTimestamp().getMinutes());\n        Assert.assertEquals(sqlTimestamp.getSeconds(), s.getSqlTimestamp().getSeconds());\n\n        Assert.assertEquals(Math.round(bigDecimal.doubleValue()), Math.round(s.getBigDecimal().doubleValue()));\n        Assert.assertEquals(bigInteger, s.getBigInteger());\n\n        Assert.assertEquals(calendar.get(Calendar.YEAR), s.getCalendar().get(Calendar.YEAR));\n        Assert.assertEquals(calendar.get(Calendar.MONTH), s.getCalendar().get(Calendar.MONTH));\n        Assert.assertEquals(calendar.get(Calendar.WEEK_OF_YEAR), s.getCalendar().get(Calendar.WEEK_OF_YEAR));\n        Assert.assertEquals(calendar.get(Calendar.WEEK_OF_MONTH), s.getCalendar().get(Calendar.WEEK_OF_MONTH));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_MONTH), s.getCalendar().get(Calendar.DAY_OF_MONTH));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_WEEK), s.getCalendar().get(Calendar.DAY_OF_WEEK));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH),\n                s.getCalendar().get(Calendar.DAY_OF_WEEK_IN_MONTH));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_YEAR), s.getCalendar().get(Calendar.DAY_OF_YEAR));\n        Assert.assertEquals(calendar.get(Calendar.HOUR), s.getCalendar().get(Calendar.HOUR));\n        Assert.assertEquals(calendar.get(Calendar.HOUR_OF_DAY), s.getCalendar().get(Calendar.HOUR_OF_DAY));\n        Assert.assertEquals(calendar.get(Calendar.AM), s.getCalendar().get(Calendar.AM));\n        Assert.assertEquals(calendar.get(Calendar.PM), s.getCalendar().get(Calendar.PM));\n        Assert.assertEquals(calendar.get(Calendar.AM_PM), s.getCalendar().get(Calendar.AM_PM));\n\n        Assert.assertEquals(new Integer(3), s.getYearsSpent());\n        Assert.assertEquals(new Long(978423946455l), s.getRollNumber());\n        Assert.assertEquals(new Double(135434.89), s.getMonthlyFee());\n\n    }\n\n    abstract void startServer();\n\n    abstract void stopServer();\n\n    abstract void createSchema();\n\n    abstract void deleteSchema();\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoBigDecimalTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoBigDecimal;\n\npublic class StudentMongoBigDecimalTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        em.remove(em.find(StudentMongoBigDecimal.class, getMinValue(BigDecimal.class)));\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of BigDecimal\n        StudentMongoBigDecimal studentMax = new StudentMongoBigDecimal();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((BigDecimal) getMaxValue(BigDecimal.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of BigDecimal\n        StudentMongoBigDecimal studentMin = new StudentMongoBigDecimal();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((BigDecimal) getMinValue(BigDecimal.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of BigDecimal\n        StudentMongoBigDecimal student = new StudentMongoBigDecimal();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((BigDecimal) getRandomValue(BigDecimal.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoBigDecimal studentMax = em.find(StudentMongoBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBigDecimal studentMin = em.find(StudentMongoBigDecimal.class, getMinValue(BigDecimal.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBigDecimal student = em.find(StudentMongoBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoBigDecimal student = em.find(StudentMongoBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBigDecimal newStudent = em.find(StudentMongoBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigDecimal s where s.age = ?1 and s.name > Amresh and s.name <= ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(short.class));\n        q.setParameter(2, getMaxValue(String.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBigDecimal student : students)\n        {\n            Assert.assertEquals(getMinValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigDecimal> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigDecimal s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(BigDecimal.class));\n        q.setParameter(2, getMaxValue(BigDecimal.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigDecimal s where s.name = Kuldeep and s.age > ?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBigDecimal student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigDecimal s where s.name = Kuldeep and s.age > ?1 and s.age <= ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(short.class));\n        q.setParameter(2, getMaxValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBigDecimal student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoBigDecimal studentMax = em.find(StudentMongoBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoBigDecimal s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBigDecimal newStudent = em.find(StudentMongoBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoBigDecimal s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBigDecimal newStudent = em.find(StudentMongoBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigDecimal s where s.name = Amresh and s.age between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(short.class));\n        q.setParameter(2, getMaxValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigDecimal s where s.name = Amresh and s.age > ?1 and s.age < ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(short.class));\n        q.setParameter(2, getMaxValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigDecimal s where s.name = Kuldeep and s.age >= ?1 and s.age <= ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(short.class));\n        q.setParameter(2, getMaxValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigDecimal.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigDecimal s where s.age = ?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, getRandomValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBigDecimal student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigDecimal s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigDecimal.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoBigDecimal s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoBigDecimal> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoBigDecimal student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(BigDecimal.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoBigIntegerTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.math.BigInteger;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoBigInteger;\n\npublic class StudentMongoBigIntegerTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        // EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoBigInteger.class,\n        // getMinValue(BigInteger.class)));\n        // if (AUTO_MANAGE_SCHEMA)\n        // {\n        dropSchema();\n        // }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of BigInteger\n        StudentMongoBigInteger studentMax = new StudentMongoBigInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((BigInteger) getMaxValue(BigInteger.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of BigInteger\n        StudentMongoBigInteger studentMin = new StudentMongoBigInteger();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((BigInteger) getMinValue(BigInteger.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of BigInteger\n        StudentMongoBigInteger student = new StudentMongoBigInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((BigInteger) getRandomValue(BigInteger.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoBigInteger studentMax = em.find(StudentMongoBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBigInteger studentMin = em.find(StudentMongoBigInteger.class, getMinValue(BigInteger.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBigInteger student = em.find(StudentMongoBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoBigInteger student = em.find(StudentMongoBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBigInteger newStudent = em.find(StudentMongoBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigInteger s where s.age = ?1 and s.name > Amresh and s.name <= ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(short.class));\n        q.setParameter(2, getMaxValue(String.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBigInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigInteger> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigInteger s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(BigInteger.class));\n        q.setParameter(2, getMaxValue(BigInteger.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentMongoBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigInteger s where s.name = Kuldeep and s.age > ?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBigInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigInteger s where s.name = Kuldeep and s.age > ?1 and s.age <= ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(short.class));\n        q.setParameter(2, getMaxValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBigInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoBigInteger studentMax = em.find(StudentMongoBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoBigInteger s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBigInteger newStudent = em.find(StudentMongoBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoBigInteger s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.clear();\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBigInteger newStudent = em.find(StudentMongoBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigInteger s where s.name = Amresh and s.age between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(short.class));\n        q.setParameter(2, getMaxValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigInteger s where s.name = Amresh and s.age > ?1 and s.age < ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(short.class));\n        q.setParameter(2, getMaxValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigInteger s where s.name = Kuldeep and s.age >= ?1 and s.age <= ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(short.class));\n        q.setParameter(2, getMaxValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigInteger s where s.age = ?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, getRandomValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBigInteger s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoBigInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoBigInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n        EntityManager em = emf.createEntityManager();\n        truncateMongo(em, PERSISTENCE_UNIT, \"StudentMongoBigInteger\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoBooleanPrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoBooleanPrimitive;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class StudentMongoBooleanPrimitiveTest extends MongoBase\n{\n\n    /**\n     * \n     */\n    private static final String _PERSISTENCEUNIT = \"MongoDataTypeTest\";\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(_PERSISTENCEUNIT);\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        dropSchema();\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of boolean\n        StudentMongoBooleanPrimitive studentMax = new StudentMongoBooleanPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Boolean) getMaxValue(boolean.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of boolean\n        StudentMongoBooleanPrimitive studentMin = new StudentMongoBooleanPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Boolean) getMinValue(boolean.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoBooleanPrimitive studentMax = em.find(StudentMongoBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBooleanPrimitive studentMin = em.find(StudentMongoBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoBooleanPrimitive student = em.find(StudentMongoBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBooleanPrimitive newStudent = em.find(StudentMongoBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanPrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(boolean.class));\n        q.setParameter(2, getMaxValue(boolean.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentMongoBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanPrimitive s where s.name = Kuldeep or s.age > \" + getMinValue(short.class);\n        try\n        {\n            q = em.createQuery(query);\n            students = q.getResultList();\n            Assert.assertNotNull(students);\n            Assert.assertEquals(2, students.size());\n            count = 0;\n            for (StudentMongoBooleanPrimitive student : students)\n            {\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            Assert.assertEquals(2, count);\n            em.close();\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertEquals(\"unsupported clause OR for Mongo\", qhe.getMessage());\n        }\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(boolean.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoBooleanPrimitive studentMax = em.find(StudentMongoBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMinValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoBooleanPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBooleanPrimitive newStudent = em.find(StudentMongoBooleanPrimitive.class, getRandomValue(boolean.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoBooleanPrimitive s SET s.name=Vivek where s.id=true\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBooleanPrimitive newStudent = em.find(StudentMongoBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanPrimitive s where s.name = Kuldeep and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentMongoBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanPrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanPrimitive s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanPrimitive s where s.age = \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoBooleanPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoBooleanPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentMongoBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n        EntityManager em = emf.createEntityManager();\n        truncateMongo(em, _PERSISTENCEUNIT, \"StudentMongoBooleanPrimitive\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoBooleanWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoBooleanWrapper;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class StudentMongoBooleanWrapperTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        List<StudentMongoBooleanWrapper> existingItems =\n              em.createQuery(\"select s from StudentMongoBooleanWrapper s\").getResultList();\n\n        for (StudentMongoBooleanWrapper item : existingItems)\n        {\n            em.remove(item);\n        }\n\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Boolean\n        StudentMongoBooleanWrapper studentMax = new StudentMongoBooleanWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Boolean) getMaxValue(Boolean.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Boolean\n        StudentMongoBooleanWrapper studentMin = new StudentMongoBooleanWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Boolean) getMinValue(Boolean.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoBooleanWrapper studentMax = em.find(StudentMongoBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBooleanWrapper studentMin = em.find(StudentMongoBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        em.close();\n    }\n\n    public void testMerge(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoBooleanWrapper student = em.find(StudentMongoBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBooleanWrapper newStudent = em.find(StudentMongoBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(Boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Boolean.class));\n        q.setParameter(2, getMaxValue(Boolean.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentMongoBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanWrapper s where s.name = Kuldeep or s.age > \" + getMinValue(short.class);\n        try\n        {\n            q = em.createQuery(query);\n            students = q.getResultList();\n            Assert.assertNotNull(students);\n            Assert.assertEquals(2, students.size());\n            count = 0;\n            for (StudentMongoBooleanWrapper student : students)\n            {\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            Assert.assertEquals(2, count);\n            em.close();\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertEquals(\"unsupported clause OR for Mongo\", qhe.getMessage());\n        }\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(Boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(Boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoBooleanWrapper studentMax = em.find(StudentMongoBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMinValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(Boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoBooleanWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBooleanWrapper newStudent = em.find(StudentMongoBooleanWrapper.class, getRandomValue(Boolean.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoBooleanWrapper s SET s.name=Vivek where s.id=true\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBooleanWrapper newStudent = em.find(StudentMongoBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanWrapper s where s.name = Kuldeep and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentMongoBooleanWrapper student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(Boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(Boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanWrapper s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanWrapper s where s.age = \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBooleanWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoBooleanWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoBooleanWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentMongoBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoBytePrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoBytePrimitive;\n\npublic class StudentMongoBytePrimitiveTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoBytePrimitive.class, getMaxValue(byte.class)));\n        em.remove(em.find(StudentMongoBytePrimitive.class, getMinValue(byte.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of byte\n        StudentMongoBytePrimitive studentMax = new StudentMongoBytePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of byte\n        StudentMongoBytePrimitive studentMin = new StudentMongoBytePrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Byte) getMinValue(byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of byte\n        StudentMongoBytePrimitive student = new StudentMongoBytePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoBytePrimitive studentMax = em.find(StudentMongoBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBytePrimitive studentMin = em.find(StudentMongoBytePrimitive.class, getMinValue(byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBytePrimitive student = em.find(StudentMongoBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoBytePrimitive student = em.find(StudentMongoBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBytePrimitive newStudent = em.find(StudentMongoBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBytePrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(byte.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBytePrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBytePrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(byte.class));\n        q.setParameter(2, getMaxValue(byte.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Byte) getMinValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBytePrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBytePrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoBytePrimitive studentMax = em.find(StudentMongoBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoBytePrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBytePrimitive newStudent = em.find(StudentMongoBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoBytePrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoBytePrimitive newStudent = em.find(StudentMongoBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBytePrimitive s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBytePrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBytePrimitive s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBytePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoBytePrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoBytePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoBytePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Byte) getMinValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoByteWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoByteWrapper;\n\npublic class StudentMongoByteWrapperTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoByteWrapper.class, getMaxValue(Byte.class)));\n        em.remove(em.find(StudentMongoByteWrapper.class, getMinValue(Byte.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Byte\n        StudentMongoByteWrapper studentMax = new StudentMongoByteWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(Byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Byte\n        StudentMongoByteWrapper studentMin = new StudentMongoByteWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Byte) getMinValue(Byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Byte\n        StudentMongoByteWrapper student = new StudentMongoByteWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(Byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoByteWrapper studentMax = em.find(StudentMongoByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoByteWrapper studentMin = em.find(StudentMongoByteWrapper.class, getMinValue(Byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoByteWrapper student = em.find(StudentMongoByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoByteWrapper student = em.find(StudentMongoByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoByteWrapper newStudent = em.find(StudentMongoByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoByteWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoByteWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Byte.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoByteWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoByteWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Byte.class));\n        q.setParameter(2, getMaxValue(Byte.class));\n\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Byte.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoByteWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoByteWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoByteWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoByteWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoByteWrapper studentMax = em.find(StudentMongoByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoByteWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoByteWrapper newStudent = em.find(StudentMongoByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoByteWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoByteWrapper newStudent = em.find(StudentMongoByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoByteWrapper s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoByteWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoByteWrapper s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoByteWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoByteWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoByteWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoByteWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Byte.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoCalendarTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.Calendar;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoCalendar;\nimport com.impetus.client.utils.MongoUtils;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class StudentMongoCalendarTest extends MongoBase\n{\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        MongoUtils.dropDatabase(emf, \"MongoDataTypeTest\");\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Calendar\n        StudentMongoCalendar studentMax = new StudentMongoCalendar();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId(((Calendar) getMaxValue(Calendar.class)));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoCalendar studentMax = em.find(StudentMongoCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoCalendar student = em.find(StudentMongoCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoCalendar newStudent = em.find(StudentMongoCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCalendar s where s.age = \" + getMaxValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoCalendar student : students)\n        {\n            Assert.assertEquals(getMaxValue(Calendar.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCalendar> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCalendar s where s.id between \" + getRandomValue(Calendar.class) + \" and \"\n                + getMaxValue(Calendar.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentMongoCalendar student : students)\n        {\n            if (student.getId().equals(getRandomValue(Calendar.class)))\n            {\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Calendar.class)))\n            {\n                Assert.assertEquals(getPartialValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em = null;\n        String query;\n        Query q;\n        try\n        {\n            List<StudentMongoCalendar> students;\n            int count;\n            em = emf.createEntityManager();\n            query = \"Select s From StudentMongoCalendar s where s.name = Kuldeep and s.age > \"\n                    + getPartialValue(short.class);\n            q = em.createQuery(query);\n            students = q.getResultList();\n            Assert.assertNotNull(students);\n            Assert.assertEquals(1, students.size());\n            count = 0;\n            for (StudentMongoCalendar student : students)\n            {\n                Assert.assertEquals(getMaxValue(Calendar.class), student.getId());\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            Assert.assertEquals(1, count);\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertEquals(\"unsupported clause OR for Hbase\", qhe.getMessage());\n        }\n        finally\n        {\n            if (em != null)\n            {\n                em.close();\n            }\n        }\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCalendar s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoCalendar student : students)\n        {\n            Assert.assertEquals(getMaxValue(Calendar.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Calendar\n        StudentMongoCalendar studentMax = new StudentMongoCalendar();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId(((Calendar) getMaxValue(Calendar.class)));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        em.close();\n\n        em = emf.createEntityManager();\n\n        studentMax = em.find(StudentMongoCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoCalendar.class, getMaxValue(Calendar.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoCalendar s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoCalendar newStudent = em.find(StudentMongoCalendar.class, getRandomValue(Calendar.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoCalendar s SET s.name=Vivek where s.name=Kuldeep\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoCalendar newStudent = em.find(StudentMongoCalendar.class, getRandomValue(Calendar.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCalendar> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCalendar s where s.name = Amresh and s.age between \"\n                + getPartialValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCalendar> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCalendar s where s.name = Kuldeep and s.age > \"\n                + getPartialValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCalendar s where s.name = Kuldeep and s.age >= \"\n                + getPartialValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoCalendar student : students)\n        {\n            if (student.getId().equals(getMaxValue(Calendar.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCalendar s where s.age = \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoCalendar student : students)\n        {\n            Assert.assertEquals(getMaxValue(Calendar.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCalendar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCalendar s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoCalendar student : students)\n        {\n            if (student.getId().equals(getMaxValue(Calendar.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoCalendar s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoCalendar> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        int count = 0;\n        for (StudentMongoCalendar student : students)\n        {\n            if (student.getId().equals(((Calendar) getMaxValue(Calendar.class))))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n\n    }\n\n    public void stopCluster()\n    {\n    }\n\n    public void createSchema()\n    {\n\n    }\n\n    public void dropSchema()\n    {\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoCharTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoChar;\n\npublic class StudentMongoCharTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoChar.class, getMaxValue(char.class)));\n        em.remove(em.find(StudentMongoChar.class, getMinValue(char.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of char\n        StudentMongoChar studentMax = new StudentMongoChar();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Character) getMaxValue(char.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of char\n        StudentMongoChar studentMin = new StudentMongoChar();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Character) getMinValue(char.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of char\n        StudentMongoChar student = new StudentMongoChar();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(char.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoChar studentMax = em.find(StudentMongoChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoChar studentMin = em.find(StudentMongoChar.class, getMinValue(char.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoChar student = em.find(StudentMongoChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoChar student = em.find(StudentMongoChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoChar newStudent = em.find(StudentMongoChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoChar s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoChar student : students)\n        {\n            Assert.assertEquals(getMinValue(char.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoChar> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoChar s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(char.class));\n        q.setParameter(2, getMaxValue(char.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Character) getMinValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(char.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoChar s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoChar s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoChar studentMax = em.find(StudentMongoChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoChar.class, getMaxValue(char.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoChar s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoChar newStudent = em.find(StudentMongoChar.class, getRandomValue(char.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoChar s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoChar newStudent = em.find(StudentMongoChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoChar s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoChar s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoChar s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoChar s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoChar s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoChar s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoChar> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Character) getMinValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(char.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoCharacterTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoCharacter;\n\npublic class StudentMongoCharacterTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoCharacter.class,\n        // getMaxValue(Character.class)));\n        em.remove(em.find(StudentMongoCharacter.class, getMinValue(Character.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Character\n        StudentMongoCharacter studentMax = new StudentMongoCharacter();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Character) getMaxValue(Character.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Character\n        StudentMongoCharacter studentMin = new StudentMongoCharacter();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Character) getMinValue(Character.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Character\n        StudentMongoCharacter student = new StudentMongoCharacter();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(Character.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoCharacter studentMax = em.find(StudentMongoCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoCharacter studentMin = em.find(StudentMongoCharacter.class, getMinValue(Character.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoCharacter student = em.find(StudentMongoCharacter.class, getRandomValue(Character.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoCharacter student = em.find(StudentMongoCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoCharacter newStudent = em.find(StudentMongoCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCharacter s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoCharacter student : students)\n        {\n            Assert.assertEquals(getMinValue(Character.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCharacter> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCharacter s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Character.class));\n        q.setParameter(2, getMaxValue(Character.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Character.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCharacter s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoCharacter student : students)\n        {\n            Assert.assertEquals(getMaxValue(Character.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCharacter s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoCharacter student : students)\n        {\n            Assert.assertEquals(getMaxValue(Character.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoCharacter studentMax = em.find(StudentMongoCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoCharacter.class, getMaxValue(Character.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoCharacter s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoCharacter newStudent = em.find(StudentMongoCharacter.class, getRandomValue(Character.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoCharacter s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoCharacter newStudent = em.find(StudentMongoCharacter.class, getRandomValue(Character.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCharacter s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCharacter s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCharacter s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCharacter s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoCharacter s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoCharacter s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoCharacter> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Character.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoDateTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoDate;\n\npublic class StudentMongoDateTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoDate.class, getMaxValue(Date.class)));\n        em.remove(em.find(StudentMongoDate.class, getMinValue(Date.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentMongoDate student = new StudentMongoDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue(Date.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Date\n        StudentMongoDate studentMax = new StudentMongoDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue(Date.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Date\n        StudentMongoDate studentMin = new StudentMongoDate();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Date) getMinValue(Date.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoDate studentMax = em.find(StudentMongoDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDate studentMin = em.find(StudentMongoDate.class, getMinValue(Date.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDate student = em.find(StudentMongoDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoDate student = em.find(StudentMongoDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDate newStudent = em.find(StudentMongoDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDate s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDate student : students)\n        {\n            Assert.assertEquals(getMinValue(Date.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDate> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDate s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Date.class));\n        q.setParameter(2, getMaxValue(Date.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Date.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoDate studentMax = em.find(StudentMongoDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoDate.class, getMaxValue(Date.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoDate s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDate newStudent = em.find(StudentMongoDate.class, getRandomValue(Date.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoDate s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDate newStudent = em.find(StudentMongoDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDate s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDate s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDate s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDate s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoDate s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue(Date.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoDoublePrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoDoublePrimitive;\n\npublic class StudentMongoDoublePrimitiveTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoDoublePrimitive.class,\n        // getMaxValue(double.class)));\n        em.remove(em.find(StudentMongoDoublePrimitive.class, getMinValue(double.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Double\n        StudentMongoDoublePrimitive studentMax = new StudentMongoDoublePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) getMaxValue(Double.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Double\n        StudentMongoDoublePrimitive studentMin = new StudentMongoDoublePrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Double) getMinValue(Double.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Double\n        StudentMongoDoublePrimitive student = new StudentMongoDoublePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoDoublePrimitive studentMax = em.find(StudentMongoDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDoublePrimitive studentMin = em.find(StudentMongoDoublePrimitive.class, getMinValue(Double.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDoublePrimitive student = em.find(StudentMongoDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoDoublePrimitive student = em.find(StudentMongoDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDoublePrimitive newStudent = em.find(StudentMongoDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoublePrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(Double.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoublePrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoublePrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(double.class));\n        q.setParameter(2, getMaxValue(double.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Double) getMinValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoublePrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoublePrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoDoublePrimitive studentMax = em.find(StudentMongoDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoDoublePrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDoublePrimitive newStudent = em.find(StudentMongoDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoDoublePrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDoublePrimitive newStudent = em.find(StudentMongoDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoublePrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoublePrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoublePrimitive s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoublePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoublePrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoDoublePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoDoublePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Double) getMinValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoDoubleWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoDoubleWrapper;\n\npublic class StudentMongoDoubleWrapperTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        dropSchema();\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Double\n        StudentMongoDoubleWrapper studentMax = new StudentMongoDoubleWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) getMaxValue(Double.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Double\n        StudentMongoDoubleWrapper studentMin = new StudentMongoDoubleWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Double) getMinValue(Double.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Double\n        StudentMongoDoubleWrapper student = new StudentMongoDoubleWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoDoubleWrapper studentMax = em.find(StudentMongoDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDoubleWrapper studentMin = em.find(StudentMongoDoubleWrapper.class, getMinValue(Double.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDoubleWrapper student = em.find(StudentMongoDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoDoubleWrapper student = em.find(StudentMongoDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDoubleWrapper newStudent = em.find(StudentMongoDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoubleWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Double.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoubleWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoubleWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Double.class));\n        q.setParameter(2, getMaxValue(Double.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Double.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoubleWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoubleWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoDoubleWrapper studentMax = em.find(StudentMongoDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoDoubleWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDoubleWrapper newStudent = em.find(StudentMongoDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoDoubleWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoDoubleWrapper newStudent = em.find(StudentMongoDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoubleWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoubleWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoubleWrapper s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoubleWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoDoubleWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoDoubleWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoDoubleWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Double.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n        EntityManager em = emf.createEntityManager();\n        truncateMongo(em, PERSISTENCE_UNIT, \"StudentMongoDoubleWrapper\");\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoFloatPrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoFloatPrimitive;\n\npublic class StudentMongoFloatPrimitiveTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoFloatPrimitive.class,\n        // getMaxValue(float.class)));\n        em.remove(em.find(StudentMongoFloatPrimitive.class, getMinValue(float.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of float\n        StudentMongoFloatPrimitive studentMax = new StudentMongoFloatPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Float) getMaxValue(float.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of float\n        StudentMongoFloatPrimitive studentMin = new StudentMongoFloatPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Float) getMinValue(float.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of float\n        StudentMongoFloatPrimitive student = new StudentMongoFloatPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Float) getRandomValue(float.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoFloatPrimitive studentMax = em.find(StudentMongoFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoFloatPrimitive studentMin = em.find(StudentMongoFloatPrimitive.class, getMinValue(float.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoFloatPrimitive student = em.find(StudentMongoFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoFloatPrimitive student = em.find(StudentMongoFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoFloatPrimitive newStudent = em.find(StudentMongoFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(float.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatPrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(float.class));\n        q.setParameter(2, getMaxValue(float.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Float) getMinValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoFloatPrimitive studentMax = em.find(StudentMongoFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoFloatPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoFloatPrimitive newStudent = em.find(StudentMongoFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoFloatPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoFloatPrimitive newStudent = em.find(StudentMongoFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatPrimitive s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatPrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatPrimitive s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoFloatPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoFloatPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Float) getMinValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoFloatWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoFloatWrapper;\n\npublic class StudentMongoFloatWrapperTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoFloatWrapper.class,\n        // getMaxValue(Float.class)));\n        em.remove(em.find(StudentMongoFloatWrapper.class, getMinValue(Float.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Float\n        StudentMongoFloatWrapper studentMax = new StudentMongoFloatWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Float) getMaxValue(Float.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Float\n        StudentMongoFloatWrapper studentMin = new StudentMongoFloatWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Float) getMinValue(Float.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Float\n        StudentMongoFloatWrapper student = new StudentMongoFloatWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Float) getRandomValue(Float.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoFloatWrapper studentMax = em.find(StudentMongoFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoFloatWrapper studentMin = em.find(StudentMongoFloatWrapper.class, getMinValue(Float.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoFloatWrapper student = em.find(StudentMongoFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoFloatWrapper student = em.find(StudentMongoFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoFloatWrapper newStudent = em.find(StudentMongoFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Float.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Float.class));\n        q.setParameter(2, getMaxValue(Float.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Float.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoFloatWrapper studentMax = em.find(StudentMongoFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoFloatWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoFloatWrapper newStudent = em.find(StudentMongoFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoFloatWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoFloatWrapper newStudent = em.find(StudentMongoFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatWrapper s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatWrapper s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoFloatWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoFloatWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoFloatWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Float.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoIntTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoInt;\n\npublic class StudentMongoIntTest extends MongoBase\n{\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoInt.class, getMaxValue(int.class)));\n        // em.remove(em.find(StudentMongoInt.class, getMinValue(int.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of int\n        StudentMongoInt studentMax = new StudentMongoInt();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(int.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of int\n        StudentMongoInt studentMin = new StudentMongoInt();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Integer) getMinValue(int.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of int\n        StudentMongoInt student = new StudentMongoInt();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(int.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoInt studentMax = em.find(StudentMongoInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoInt studentMin = em.find(StudentMongoInt.class, getMinValue(int.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoInt student = em.find(StudentMongoInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoInt student = em.find(StudentMongoInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoInt newStudent = em.find(StudentMongoInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInt s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoInt student : students)\n        {\n            Assert.assertEquals(getMinValue(int.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInt> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInt s where s.id between \" + getMinValue(int.class) + \" and \"\n                + getMaxValue(int.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Integer) getMinValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInt s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInt s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoInt studentMax = em.find(StudentMongoInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoInt.class, getMaxValue(int.class));\n        Assert.assertNull(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n\n        StudentMongoInt studentMin = em.find(StudentMongoInt.class, getMinValue(int.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMin.getName());\n        em.remove(studentMin);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMin = em.find(StudentMongoInt.class, getMinValue(int.class));\n        Assert.assertNull(studentMin);\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoInt s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoInt newStudent = em.find(StudentMongoInt.class, getRandomValue(int.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoInt s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoInt newStudent = em.find(StudentMongoInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInt s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInt s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInt s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInt s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInt s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoInt s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoInt> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Integer) getMinValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoIntegerTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoInteger;\n\npublic class StudentMongoIntegerTest extends MongoBase\n{\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoInteger.class,\n        // getMaxValue(Integer.class)));\n        em.remove(em.find(StudentMongoInteger.class, getMinValue(Integer.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of integer\n        StudentMongoInteger studentMax = new StudentMongoInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(Integer.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of integer\n        StudentMongoInteger studentMin = new StudentMongoInteger();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Integer) getMinValue(Integer.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of integer\n        StudentMongoInteger student = new StudentMongoInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(Integer.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoInteger studentMax = em.find(StudentMongoInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoInteger studentMin = em.find(StudentMongoInteger.class, getMinValue(Integer.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoInteger student = em.find(StudentMongoInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoInteger student = em.find(StudentMongoInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoInteger newStudent = em.find(StudentMongoInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInteger s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(Integer.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInteger> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInteger s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Integer.class));\n        q.setParameter(2, getMaxValue(Integer.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Integer.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInteger s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInteger s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoInteger studentMax = em.find(StudentMongoInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoInteger.class, getMaxValue(Integer.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoInteger s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoInteger newStudent = em.find(StudentMongoInteger.class, getRandomValue(Integer.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoInteger s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoInteger newStudent = em.find(StudentMongoInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInteger s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInteger s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInteger s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInteger s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoInteger s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Integer.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoLongPrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoLongPrimitive;\n\npublic class StudentMongoLongPrimitiveTest extends MongoBase\n{\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoLongPrimitive.class, getMaxValue(long.class)));\n        em.remove(em.find(StudentMongoLongPrimitive.class, getMinValue(long.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of long\n        StudentMongoLongPrimitive studentMax = new StudentMongoLongPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of long\n        StudentMongoLongPrimitive studentMin = new StudentMongoLongPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Long) getMinValue(long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of long\n        StudentMongoLongPrimitive student = new StudentMongoLongPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoLongPrimitive studentMax = em.find(StudentMongoLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoLongPrimitive studentMin = em.find(StudentMongoLongPrimitive.class, getMinValue(long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoLongPrimitive student = em.find(StudentMongoLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoLongPrimitive student = em.find(StudentMongoLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoLongPrimitive newStudent = em.find(StudentMongoLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(long.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongPrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(long.class));\n        q.setParameter(2, getMaxValue(long.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Long) getMinValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoLongPrimitive studentMax = em.find(StudentMongoLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoLongPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoLongPrimitive newStudent = em.find(StudentMongoLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoLongPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoLongPrimitive newStudent = em.find(StudentMongoLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongPrimitive s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongPrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongPrimitive s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoLongPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoLongPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Long) getMinValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoLongWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoLongWrapper;\n\npublic class StudentMongoLongWrapperTest extends MongoBase\n{\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoLongWrapper.class, getMaxValue(Long.class)));\n        em.remove(em.find(StudentMongoLongWrapper.class, getMinValue(Long.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Long\n        StudentMongoLongWrapper studentMax = new StudentMongoLongWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(Long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Long\n        StudentMongoLongWrapper studentMin = new StudentMongoLongWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Long) getMinValue(Long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Long\n        StudentMongoLongWrapper student = new StudentMongoLongWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(Long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoLongWrapper studentMax = em.find(StudentMongoLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoLongWrapper studentMin = em.find(StudentMongoLongWrapper.class, getMinValue(Long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoLongWrapper student = em.find(StudentMongoLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoLongWrapper student = em.find(StudentMongoLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoLongWrapper newStudent = em.find(StudentMongoLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoLongWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Long.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongWrapper s where s.id between \" + getMinValue(Long.class) + \" and \"\n                + getMaxValue(Long.class);\n        // query =\n        // \"Select s From StudentMongoLongWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        // q.setParameter(1, getMinValue(Long.class));\n        // q.setParameter(2, getMaxValue(Long.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Long.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoLongWrapper studentMax = em.find(StudentMongoLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoLongWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoLongWrapper newStudent = em.find(StudentMongoLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoLongWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoLongWrapper newStudent = em.find(StudentMongoLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongWrapper s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongWrapper s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoLongWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoLongWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoLongWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Long.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoShortPrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoShortPrimitive;\n\npublic class StudentMongoShortPrimitiveTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoShortPrimitive.class,\n        // getMaxValue(short.class)));\n        em.remove(em.find(StudentMongoShortPrimitive.class, getMinValue(short.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentMongoShortPrimitive studentMax = new StudentMongoShortPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentMongoShortPrimitive studentMin = new StudentMongoShortPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Short) getMinValue(Short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentMongoShortPrimitive student = new StudentMongoShortPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoShortPrimitive studentMax = em.find(StudentMongoShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoShortPrimitive studentMin = em.find(StudentMongoShortPrimitive.class, getMinValue(Short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoShortPrimitive student = em.find(StudentMongoShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoShortPrimitive student = em.find(StudentMongoShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoShortPrimitive newStudent = em.find(StudentMongoShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(Short.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortPrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(short.class));\n        q.setParameter(2, getMaxValue(short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Short) getMinValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoShortPrimitive studentMax = em.find(StudentMongoShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoShortPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoShortPrimitive newStudent = em.find(StudentMongoShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoShortPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoShortPrimitive newStudent = em.find(StudentMongoShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortPrimitive s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortPrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortPrimitive s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoShortPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoShortPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Short) getMinValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoShortWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoShortWrapper;\n\npublic class StudentMongoShortWrapperTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoShortWrapper.class,\n        // getMaxValue(Short.class)));\n        em.remove(em.find(StudentMongoShortWrapper.class, getMinValue(Short.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentMongoShortWrapper studentMax = new StudentMongoShortWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentMongoShortWrapper studentMin = new StudentMongoShortWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Short) getMinValue(Short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentMongoShortWrapper student = new StudentMongoShortWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoShortWrapper studentMax = em.find(StudentMongoShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoShortWrapper studentMin = em.find(StudentMongoShortWrapper.class, getMinValue(Short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoShortWrapper student = em.find(StudentMongoShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoShortWrapper student = em.find(StudentMongoShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoShortWrapper newStudent = em.find(StudentMongoShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoShortWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Short.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Short.class));\n        q.setParameter(2, getMaxValue(Short.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Short.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoShortWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoShortWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoShortWrapper studentMax = em.find(StudentMongoShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoShortWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoShortWrapper newStudent = em.find(StudentMongoShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoShortWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoShortWrapper newStudent = em.find(StudentMongoShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortWrapper s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortWrapper s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoShortWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoShortWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoShortWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Short.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoSqlDateTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoSqlDate;\n\npublic class StudentMongoSqlDateTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        dropSchema();\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentMongoSqlDate student = new StudentMongoSqlDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue(Date.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Date\n        StudentMongoSqlDate studentMax = new StudentMongoSqlDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue(Date.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Date\n        StudentMongoSqlDate studentMin = new StudentMongoSqlDate();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Date) getMinValue(Date.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoSqlDate studentMax = em.find(StudentMongoSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoSqlDate studentMin = em.find(StudentMongoSqlDate.class, getMinValue(Date.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoSqlDate student = em.find(StudentMongoSqlDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoSqlDate student = em.find(StudentMongoSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoSqlDate newStudent = em.find(StudentMongoSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoSqlDate s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoSqlDate student : students)\n        {\n            Assert.assertEquals(getMinValue(Date.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoSqlDate> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoSqlDate s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Date.class));\n        q.setParameter(2, getMaxValue(Date.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Date.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoSqlDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoSqlDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoSqlDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoSqlDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoSqlDate studentMax = em.find(StudentMongoSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoSqlDate s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoSqlDate newStudent = em.find(StudentMongoSqlDate.class, getRandomValue(Date.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoSqlDate s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoSqlDate newStudent = em.find(StudentMongoSqlDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoSqlDate s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoSqlDate s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoSqlDate s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoSqlDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoSqlDate s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoSqlDate s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoSqlDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue(Date.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n        EntityManager em = emf.createEntityManager();\n        truncateMongo(em, PERSISTENCE_UNIT, \"StudentMongoSqlDate\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoStringTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoString;\n\npublic class StudentMongoStringTest extends MongoBase\n{\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoString.class,\n        // getMaxValue(String.class)));\n        em.remove(em.find(StudentMongoString.class, getMinValue(String.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of String\n        StudentMongoString studentMax = new StudentMongoString();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((String) getMaxValue(String.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of String\n        StudentMongoString studentMin = new StudentMongoString();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((String) getMinValue(String.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of String\n        StudentMongoString student = new StudentMongoString();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((String) getRandomValue(String.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoString studentMax = em.find(StudentMongoString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoString studentMin = em.find(StudentMongoString.class, getMinValue(String.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoString student = em.find(StudentMongoString.class, getRandomValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoString student = em.find(StudentMongoString.class, getMaxValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoString newStudent = em.find(StudentMongoString.class, getMaxValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoString s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoString student : students)\n        {\n            Assert.assertEquals(getMinValue(String.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoString> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoString s where s.id between \" + getMinValue(String.class) + \" and \"\n                + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentMongoString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoString s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoString s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoString studentMax = em.find(StudentMongoString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoString.class, getMaxValue(String.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoString s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoString newStudent = em.find(StudentMongoString.class, getRandomValue(String.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoString s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoString newStudent = em.find(StudentMongoString.class, getRandomValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoString s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoString s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoString s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoString s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoString s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoString s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoString> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(String.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(String.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes;\n\nimport java.math.BigInteger;\nimport java.util.List;\n\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.databene.contiperf.PerfTest;\nimport org.databene.contiperf.junit.ContiPerfRule;\nimport org.databene.contiperf.report.CSVSummaryReportModule;\nimport org.databene.contiperf.report.HtmlReportModule;\nimport org.databene.contiperf.report.ReportModule;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\n\n/**\n * The Class StudentDaoTest.\n * \n * @author Vivek Mishra\n */\npublic class StudentMongoTest extends StudentMongoBase<StudentMongo>\n{\n    String persistenceUnit = \"mongoTest\";\n\n    @Rule\n    public ContiPerfRule i = new ContiPerfRule(new ReportModule[] { new CSVSummaryReportModule(),\n            new HtmlReportModule() });\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setupInternal(persistenceUnit);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        teardownInternal(persistenceUnit);\n    }\n\n    @Test\n    @PerfTest(invocations = 1)\n    public void executeTestsForInsert()\n    {\n        onInsert();\n    }\n\n    @Test\n    @PerfTest(invocations = 1)\n    public void executeTestsForUpdate()\n    {\n        onMerge();\n    }\n\n    /**\n     * Test method for.\n     * \n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     *             {@link com.impetus.kundera.examples.student.StudentDao#saveStudent(com.impetus.kundera.examples.crud.datatype.entities.StudentMongo)}\n     *             .\n     */\n\n    public void onInsert()\n    {\n        try\n        {\n            onInsert(new StudentMongo());\n        }\n        catch (InstantiationException e)\n        {\n\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n\n            Assert.fail(e.getMessage());\n        }\n\n        // find by id.\n        StudentEntityDef s = em.find(StudentMongo.class, studentId1);\n        assertOnDataTypes((StudentMongo) s);\n\n        // // find by name.\n        assertFindByName(em, \"StudentMongo\", StudentMongo.class, \"Amresh\", \"studentName\");\n\n        // find by name and age.\n        assertFindByNameAndAge(em, \"StudentMongo\", StudentMongo.class, \"Amresh\", \"10\", \"studentName\");\n\n        // find by name, age clause\n        assertFindByNameAndAgeGTAndLT(em, \"StudentMongo\", StudentMongo.class, \"Amresh\", \"10\", \"20\", \"studentName\");\n        //\n        // // find by between clause\n        assertFindByNameAndAgeBetween(em, \"StudentMongo\", StudentMongo.class, \"Amresh\", \"10\", \"15\", \"studentName\");\n\n        // find by Range.\n        assertFindByRange(em, \"StudentMongo\", StudentMongo.class, \"12345677\", \"12345678\", \"studentId\");\n\n        // find by without where clause.\n        assertFindWithoutWhereClause(em, \"StudentMongo\", StudentMongo.class);\n\n        // Query on Date.\n        String query = \"Select s from StudentMongo s where s.enrolmentDate =:enrolmentDate\";\n        Query q = em.createQuery(query);\n        q.setParameter(\"enrolmentDate\", enrolmentDate);\n        List<StudentMongo> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n\n        // Query on long.\n        query = \"Select s from StudentMongo s where s.uniqueId =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 78575785897L);\n\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(78575785897L, results.get(0).getUniqueId());\n\n        // Assert on boolean.\n        query = \"Select s from StudentMongo s where s.isExceptional =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, true);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        for (StudentMongo studentMongo : results)\n        {\n            if (studentMongo.getStudentId() == (Long) studentId2)\n            {\n                Assert.assertEquals(20, studentMongo.getAge());\n            }\n            else\n            {\n                Assert.assertEquals(15, studentMongo.getAge());\n            }\n\n        }\n\n        // with false.\n        query = \"Select s from StudentMongo s where s.isExceptional =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, false);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n\n        // query on int.\n\n        query = \"Select s from StudentMongo s where s.age =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 10);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(10, results.get(0).getAge());\n\n        // query on char (semester)\n\n        query = \"Select s from StudentMongo s where s.semester =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 'A');\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(10, results.get(0).getAge());\n        Assert.assertEquals('A', results.get(0).getSemester());\n\n        // query on float (percentage)\n        query = \"Select s from StudentMongo s where s.percentage =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 61.6f);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(61.6f, results.get(0).getPercentage());\n\n        // query on double (height)\n\n        query = \"Select s from StudentMongo s where s.height =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 163.76765654);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(163.76765654, results.get(0).getHeight());\n\n        // query on cgpa.\n        query = \"Select s from StudentMongo s where s.cgpa =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n\n        for (StudentMongo studentMongo : results)\n        {\n            if (studentMongo.getStudentId() == (Long) studentId1)\n            {\n                Assert.assertEquals(10, studentMongo.getAge());\n                Assert.assertEquals(false, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n            }\n            else if (studentMongo.getStudentId() == (Long) studentId2)\n            {\n                Assert.assertEquals(20, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n            }\n            else\n            {\n                Assert.assertEquals(15, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n            }\n\n        }\n\n        // query on yearsSpent.\n        Integer i = new Integer(3);\n        query = \"Select s from StudentMongo s where s.yearsSpent = 3\";\n        q = em.createQuery(query);\n        // q.setParameter(1, new Integer(3));\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        for (StudentMongo studentMongo : results)\n        {\n            if (studentMongo.getStudentId() == (Long) studentId1)\n            {\n                Assert.assertEquals(10, studentMongo.getAge());\n                Assert.assertEquals(false, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n            }\n            else if (studentMongo.getStudentId() == (Long) studentId2)\n            {\n                Assert.assertEquals(20, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n            }\n            else\n            {\n                Assert.assertEquals(15, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n            }\n\n        }\n\n        // query on yearsSpent.\n        query = \"Select s from StudentMongo s where s.yearsSpent =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, new Integer(3));\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        for (StudentMongo studentMongo : results)\n        {\n            if (studentMongo.getStudentId() == (Long) studentId1)\n            {\n                Assert.assertEquals(10, studentMongo.getAge());\n                Assert.assertEquals(false, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n            }\n            else if (studentMongo.getStudentId() == (Long) studentId2)\n            {\n                Assert.assertEquals(20, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n            }\n            else\n            {\n                Assert.assertEquals(15, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n            }\n\n        }\n\n        // query on digitalSignature.\n        query = \"Select s from StudentMongo s where s.digitalSignature =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, (byte) 50);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        for (StudentMongo studentMongo : results)\n        {\n            if (studentMongo.getStudentId() == (Long) studentId2)\n            {\n                Assert.assertEquals(20, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 50, results.get(0).getDigitalSignature());\n            }\n            else\n            {\n                Assert.assertEquals(15, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 50, results.get(0).getDigitalSignature());\n            }\n        }\n\n        // query on cpga and digitalSignature.\n        query = \"Select s from StudentMongo s where s.cgpa =?1 and s.digitalSignature >= ?2 and s.digitalSignature <= ?3\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        q.setParameter(2, (byte) 5);\n        q.setParameter(3, (byte) 50);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        for (StudentMongo studentMongo : results)\n        {\n            if (studentMongo.getStudentId() == (Long) studentId1)\n            {\n                Assert.assertEquals(10, studentMongo.getAge());\n                Assert.assertEquals(false, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n            }\n            else if (studentMongo.getStudentId() == (Long) studentId2)\n            {\n                Assert.assertEquals(20, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n            }\n            else\n            {\n                Assert.assertEquals(15, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n            }\n        }\n\n        // query on cpga and digitalSignature parameter appended with String\n        // .\n        query = \"Select s from StudentMongo s where s.cgpa = 8 and s.digitalSignature >= 5 and s.digitalSignature <= 50\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        for (StudentMongo studentMongo : results)\n        {\n            if (studentMongo.getStudentId() == (Long) studentId1)\n            {\n                Assert.assertEquals(10, studentMongo.getAge());\n                Assert.assertEquals(false, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n            }\n            else if (studentMongo.getStudentId() == (Long) studentId2)\n            {\n                Assert.assertEquals(20, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n            }\n            else\n            {\n                Assert.assertEquals(15, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n            }\n        }\n\n        // query on cpga and digitalSignature.\n        query = \"Select s from StudentMongo s where s.digitalSignature >= ?2 and s.digitalSignature <= ?3 and s.cgpa =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        q.setParameter(2, (byte) 5);\n        q.setParameter(3, (byte) 50);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        for (StudentMongo studentMongo : results)\n        {\n            if (studentMongo.getStudentId() == (Long) studentId1)\n            {\n                Assert.assertEquals(10, studentMongo.getAge());\n                Assert.assertEquals(false, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n            }\n            else if (studentMongo.getStudentId() == (Long) studentId2)\n            {\n                Assert.assertEquals(20, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n            }\n            else\n            {\n                Assert.assertEquals(15, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n            }\n        }\n\n        // query on percentage and height.\n        query = \"Select s from StudentMongo s where s.percentage >= ?2 and s.percentage <= ?3 and s.height =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, 163.76765654);\n        q.setParameter(2, 61.6f);\n        q.setParameter(3, 69.6f);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals(61.6f, results.get(0).getPercentage());\n        Assert.assertEquals(163.76765654, results.get(0).getHeight());\n\n        // query on percentage and height parameter appended in string.\n        query = \"Select s from StudentMongo s where s.percentage >= 61.6 and s.percentage <= 69.6 and s.height = 163.76765654\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals(61.6f, results.get(0).getPercentage());\n        Assert.assertEquals(163.76765654, results.get(0).getHeight());\n\n        // query on cpga and uniqueId.\n        query = \"Select s from StudentMongo s where s.cgpa =?1 and s.uniqueId >= ?2 and s.uniqueId <= ?3\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        q.setParameter(2, 78575785897L);\n        q.setParameter(3, 78575785899L);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        for (StudentMongo studentMongo : results)\n        {\n            if (studentMongo.getStudentId() == (Long) studentId1)\n            {\n                Assert.assertEquals(10, studentMongo.getAge());\n                Assert.assertEquals(false, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n            }\n            else if (studentMongo.getStudentId() == (Long) studentId2)\n            {\n                Assert.assertEquals(20, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n            }\n            else\n            {\n                Assert.assertEquals(15, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n            }\n        }\n\n        for (StudentMongo student : results)\n        {\n            Assert.assertTrue(student.getUniqueId() == 78575785897L || student.getUniqueId() == 78575785898L\n                    || student.getUniqueId() == 78575785899L);\n        }\n\n        // query on cpga and semester.\n        query = \"Select s from StudentMongo s where s.cgpa =?1 and s.semester >= ?2 and s.semester < ?3\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 8);\n        q.setParameter(2, 'A');\n        q.setParameter(3, 'C');\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals((short) 8, results.get(0).getCgpa());\n        Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n        Assert.assertEquals(78575785897L, results.get(0).getUniqueId());\n        Assert.assertEquals(10, results.get(0).getAge());\n\n        // query on cpga and semester with appending in string.\n        query = \"Select s from StudentMongo s where s.cgpa = 8 and s.semester >= A and s.semester <= C\";\n        q = em.createQuery(query);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        for (StudentMongo studentMongo : results)\n        {\n            if (studentMongo.getStudentId() == (Long) studentId1)\n            {\n                Assert.assertEquals(10, studentMongo.getAge());\n                Assert.assertEquals(false, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 5, results.get(0).getDigitalSignature());\n            }\n            else if (studentMongo.getStudentId() == (Long) studentId2)\n            {\n                Assert.assertEquals(20, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n            }\n            else\n            {\n                Assert.assertEquals(15, studentMongo.getAge());\n                Assert.assertEquals(true, studentMongo.isExceptional());\n                Assert.assertEquals(8, studentMongo.getCgpa());\n                Assert.assertEquals(i, studentMongo.getYearsSpent());\n                Assert.assertEquals((byte) 50, results.get(1).getDigitalSignature());\n            }\n        }\n\n        for (StudentMongo student : results)\n        {\n            Assert.assertTrue(student.getUniqueId() == 78575785897L || student.getUniqueId() == 78575785898L\n                    || student.getUniqueId() == 78575785899L);\n        }\n        for (StudentMongo student : results)\n        {\n            Assert.assertTrue(student.getAge() == 15 || student.getAge() == 20 || student.getAge() == 10);\n        }\n\n        // query on invalid cpga and uniqueId.\n        query = \"Select s from StudentMongo s where s.cgpa =?1 and s.uniqueId >= ?2 and s.uniqueId <= ?3\";\n        q = em.createQuery(query);\n        q.setParameter(1, (short) 2);\n        q.setParameter(2, 78575785897L);\n        q.setParameter(3, 78575785899L);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertTrue(results.isEmpty());\n\n        // query on big integer.\n        query = \"Select s from StudentMongo s where s.bigInteger =?1\";\n        q = em.createQuery(query);\n        q.setParameter(1, bigInteger);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(false, results.get(0).isExceptional());\n        Assert.assertEquals(163.76765654, results.get(0).getHeight());\n\n        // invalid.\n        q.setParameter(1, new BigInteger(\"1234567823\"));\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertTrue(results.isEmpty());\n    }\n\n    /**\n     * On merge.\n     */\n    public void onMerge()\n    {\n        em.persist(prepareData((Long) studentId1, 78575785897L, \"Amresh\", true, 10, 'C', (byte) 5, (short) 8,\n                (float) 69.6, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar,\n                new StudentMongo()));\n        StudentMongo s = em.find(StudentMongo.class, studentId1);\n        Assert.assertNotNull(s);\n        Assert.assertEquals(\"Amresh\", s.getStudentName());\n        // modify record.\n        s.setStudentName(\"NewAmresh\");\n        em.merge(s);\n        // emf.close();\n        Query q = em.createQuery(\"Select p from StudentMongo p where p.studentName = NewAmresh\");\n        try\n        {\n            List<StudentMongo> results = q.getResultList();\n            Assert.assertNotNull(results);\n            Assert.assertEquals(1, results.size());\n        }\n        catch (Exception e)\n        {\n            Assert.fail(\"Failure onMerge test\");\n        }\n    }\n\n    @Override\n    void startServer()\n    {\n    }\n\n    @Override\n    void stopServer()\n    {\n    }\n\n    @Override\n    void createSchema()\n    {\n    }\n\n    @Override\n    void deleteSchema()\n    {\n        StudentMongo s1 = em.find(StudentMongo.class, studentId1);\n        StudentMongo s2 = em.find(StudentMongo.class, studentId1);\n        StudentMongo s3 = em.find(StudentMongo.class, studentId1);\n\n        if (s1 != null)\n            em.remove(s1);\n\n        if (s2 != null)\n            em.remove(s2);\n\n        if (s3 != null)\n            em.remove(s3);\n    }\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoTimeTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.Time;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoTime;\n\npublic class StudentMongoTimeTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoTime.class, getMaxValue(Time.class)));\n        em.remove(em.find(StudentMongoTime.class, getMinValue(Time.class)));\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Time\n        StudentMongoTime student = new StudentMongoTime();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Time) getRandomValue(Time.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Time\n        StudentMongoTime studentMax = new StudentMongoTime();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Time) getMaxValue(Time.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Time\n        StudentMongoTime studentMin = new StudentMongoTime();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Time) getMinValue(Time.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoTime studentMax = em.find(StudentMongoTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoTime studentMin = em.find(StudentMongoTime.class, getMinValue(Time.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoTime student = em.find(StudentMongoTime.class, getRandomValue(Time.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoTime student = em.find(StudentMongoTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoTime newStudent = em.find(StudentMongoTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTime s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoTime student : students)\n        {\n            Assert.assertEquals(getMinValue(Time.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTime> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTime s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Time.class));\n        q.setParameter(2, getMaxValue(Time.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Time.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Time.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTime s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoTime student : students)\n        {\n            Assert.assertEquals(getMaxValue(Time.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTime s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoTime student : students)\n        {\n            Assert.assertEquals(getMaxValue(Time.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoTime studentMax = em.find(StudentMongoTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoTime.class, getMaxValue(Time.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoTime s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoTime newStudent = em.find(StudentMongoTime.class, getRandomValue(Time.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String upTimeQuery = \"Update StudentMongoTime s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(upTimeQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoTime newStudent = em.find(StudentMongoTime.class, getRandomValue(Time.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTime s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTime s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTime s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Time.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTime s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTime s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Time.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoTime s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoTime> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoTime student : students)\n        {\n            if (student.getId().equals(getMaxValue(Time.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Time.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Time) getRandomValue(Time.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoTimestampTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.Timestamp;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoTimestamp;\n\npublic class StudentMongoTimestampTest extends MongoBase\n{\n\n    private static final String keyspace = \"KunderaMongoDataType\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startCluster();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        // EntityManager em = emf.createEntityManager();\n        // em.remove(em.find(StudentMongoTimestamp.class,\n        // getMaxValue(Timestamp.class)));\n        // em.remove(em.find(StudentMongoTimestamp.class,\n        // getMinValue(Timestamp.class)));\n        // if (AUTO_MANAGE_SCHEMA)\n        // {\n        dropSchema();\n        // }\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopCluster();\n        }\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Time\n        StudentMongoTimestamp student = new StudentMongoTimestamp();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Timestamp) getRandomValue(Timestamp.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Time\n        StudentMongoTimestamp studentMax = new StudentMongoTimestamp();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Timestamp) getMaxValue(Timestamp.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Timestamp\n        StudentMongoTimestamp studentMin = new StudentMongoTimestamp();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Timestamp) getMinValue(Timestamp.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoTimestamp studentMax = em.find(StudentMongoTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoTimestamp studentMin = em.find(StudentMongoTimestamp.class, getMinValue(Timestamp.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoTimestamp student = em.find(StudentMongoTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoTimestamp student = em.find(StudentMongoTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoTimestamp newStudent = em.find(StudentMongoTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTimestamp s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoTimestamp student : students)\n        {\n            Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTimestamp> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTimestamp s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Timestamp.class));\n        q.setParameter(2, getMaxValue(Timestamp.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTimestamp s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoTimestamp student : students)\n        {\n            Assert.assertEquals(getMaxValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTimestamp s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoTimestamp student : students)\n        {\n            Assert.assertEquals(getMaxValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoTimestamp studentMax = em.find(StudentMongoTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoTimestamp s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoTimestamp newStudent = em.find(StudentMongoTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String upTimeQuery = \"Update StudentMongoTimestamp s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(upTimeQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoTimestamp newStudent = em.find(StudentMongoTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTimestamp s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTimestamp s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTimestamp s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTimestamp s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoTimestamp s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoTimestamp s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoTimestamp> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Timestamp) getRandomValue(Timestamp.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n        EntityManager em = emf.createEntityManager();\n        truncateMongo(em, PERSISTENCE_UNIT, \"StudentMongoTimestamp\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/StudentMongoUUIDTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.util.List;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentMongoUUID;\nimport com.impetus.client.utils.MongoUtils;\n\npublic class StudentMongoUUIDTest extends MongoBase\n{\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"MongoDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n        em.remove(em.find(StudentMongoUUID.class, getMinValue(UUID.class)));\n        MongoUtils.dropDatabase(emf, \"MongoDataTypeTest\");\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of UUID\n        StudentMongoUUID studentMax = new StudentMongoUUID();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((UUID) getMaxValue(UUID.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of UUID\n        StudentMongoUUID studentMin = new StudentMongoUUID();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((UUID) getMinValue(UUID.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of UUID\n        StudentMongoUUID student = new StudentMongoUUID();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((UUID) getRandomValue(UUID.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoUUID studentMax = em.find(StudentMongoUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoUUID studentMin = em.find(StudentMongoUUID.class, getMinValue(UUID.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoUUID student = em.find(StudentMongoUUID.class, getRandomValue(UUID.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentMongoUUID student = em.find(StudentMongoUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoUUID newStudent = em.find(StudentMongoUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoUUID s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoUUID student : students)\n        {\n            Assert.assertEquals(getMinValue(UUID.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoUUID> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoUUID s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(UUID.class));\n        q.setParameter(2, getMaxValue(UUID.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(UUID.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoUUID s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoUUID student : students)\n        {\n            Assert.assertEquals(getMaxValue(UUID.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoUUID s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoUUID student : students)\n        {\n            Assert.assertEquals(getMaxValue(UUID.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentMongoUUID studentMax = em.find(StudentMongoUUID.class, getMaxValue(UUID.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentMongoUUID.class, getMaxValue(UUID.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentMongoUUID s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoUUID newStudent = em.find(StudentMongoUUID.class, getRandomValue(UUID.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentMongoUUID s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentMongoUUID newStudent = em.find(StudentMongoUUID.class, getRandomValue(UUID.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoUUID s where s.name = Amresh and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoUUID s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoUUID s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(UUID.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoUUID s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentMongoUUID student : students)\n        {\n            Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentMongoUUID> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentMongoUUID s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentMongoUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(UUID.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentMongoUUID s \";\n        Query q = em.createQuery(query);\n        List<StudentMongoUUID> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentMongoUUID student : students)\n        {\n            if (student.getId().equals(getMaxValue(UUID.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(UUID.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(UUID.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema()\n    {\n    }\n\n    public void dropSchema()\n    {\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/Collecte.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes.entities;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.CollectionTable;\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\n@Entity\n@Table(name = \"COLLECTE\", schema = \"KunderaExamples@mongoTest\")\npublic class Collecte\n{\n\n    @Id\n    @Column(name = \"COLLECTE_ID\")\n    private String id;\n\n    @Column(name = \"EAN\", nullable = false)\n    private String EAN;\n\n    @Column(name = \"PRODUIT_ID\")\n    private Long idProduit;\n\n    @Temporal(TemporalType.TIMESTAMP)\n    @Column(name = \"dateStatut\")\n    private Date dateStatut;\n\n    @Column(name = \"statut\")\n    private int statut;\n\n    // Element collection, will persist co-located\n    @ElementCollection(fetch = FetchType.LAZY)\n    @CollectionTable(name = \"PHOTOS\")\n    private List<Photoo> photos;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public String getEAN()\n    {\n        return EAN;\n    }\n\n    public void setEAN(String eAN)\n    {\n        EAN = eAN;\n    }\n\n    public Long getIdProduit()\n    {\n        return idProduit;\n    }\n\n    public void setIdProduit(Long idProduit)\n    {\n        this.idProduit = idProduit;\n    }\n\n    public Date getDateStatut()\n    {\n        return dateStatut;\n    }\n\n    public void setDateStatut(Date dateStatut)\n    {\n        this.dateStatut = dateStatut;\n    }\n\n    public int getStatut()\n    {\n        return statut;\n    }\n\n    public void setStatut(int statut)\n    {\n        this.statut = statut;\n    }\n\n    public List<Photoo> getPhotos()\n    {\n        return photos;\n    }\n\n    public void setPhotos(List<Photoo> photos)\n    {\n        this.photos = photos;\n    }\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/Photoo.java",
    "content": "/*******************************************************************************\n *  * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n@Embeddable\npublic class Photoo\n{\n\n    @Column(name = \"NOM_PHOTO\")\n    private String nomPhoto;\n\n    @Column(name = \"MD5\")\n    private String md5;\n\n    @Column(name = \"NOM_FICHIER\")\n    private String nomFichier;\n\n    public String getNomPhoto()\n    {\n        return nomPhoto;\n    }\n\n    public void setNomPhoto(String nomPhoto)\n    {\n        this.nomPhoto = nomPhoto;\n    }\n\n    public String getMd5()\n    {\n        return md5;\n    }\n\n    public void setMd5(String md5)\n    {\n        this.md5 = md5;\n    }\n\n    public String getNomFichier()\n    {\n        return nomFichier;\n    }\n\n    public void setNomFichier(String nomFichier)\n    {\n        this.nomFichier = nomFichier;\n    }\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoBigDecimal.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.math.BigDecimal;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoBigDecimal\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoBigDecimal\n{\n\n    @Id\n    private BigDecimal id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public BigDecimal getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(BigDecimal id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoBigInteger.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.math.BigInteger;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoBigInteger\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoBigInteger\n{\n\n    @Id\n    private BigInteger id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public BigInteger getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(BigInteger id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoBooleanPrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoBooleanPrimitive\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoBooleanPrimitive\n{\n    @Id\n    private boolean id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public boolean getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(boolean id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoBooleanWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoBooleanWrapper\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoBooleanWrapper\n{\n    @Id\n    private Boolean id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Boolean getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Boolean id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoBytePrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoBytePrimitive\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoBytePrimitive\n{\n\n    @Id\n    private byte id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoByteWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoByteWrapper\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoByteWrapper\n{\n\n    @Id\n    private Byte id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoCalendar.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.util.Calendar;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoCalendar\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoCalendar\n{\n\n    @Id\n    private Calendar id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Calendar getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Calendar id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoChar.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoChar\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoChar\n{\n\n    @Id\n    private char id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public char getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(char id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoCharacter.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoCharacter\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoCharacter\n{\n    @Id\n    private Character id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Character getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Character id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoDate.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoDate\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoDate\n{\n\n    @Id\n    private Date id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoDoublePrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoDoublePrimitive\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoDoublePrimitive\n{\n\n    @Id\n    private double id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public double getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoDoubleWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoDoubleWrapper\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoDoubleWrapper\n{\n\n    @Id\n    private Double id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Double getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoFloatPrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoFloatPrimitive\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoFloatPrimitive\n{\n    @Id\n    private float id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public float getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoFloatWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoFloatWrapper\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoFloatWrapper\n{\n\n    @Id\n    private Float id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Float getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoInt.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoInt\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoInt\n{\n\n    @Id\n    private int id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoInteger.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoInteger\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoInteger\n{\n    @Id\n    private Integer id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Integer getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Integer id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoLongPrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoLongPrimitive\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoLongPrimitive\n{\n\n    @Id\n    private long id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public long getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoLongWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoLongWrapper\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoLongWrapper\n{\n\n    @Id\n    private Long id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Long getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoShortPrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoShortPrimitive\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoShortPrimitive\n{\n\n    @Id\n    private short id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public short getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoShortWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoShortWrapper\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoShortWrapper\n{\n\n    @Id\n    private Short id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Short getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoSqlDate.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.sql.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoSqlDate\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoSqlDate\n{\n\n    @Id\n    private Date id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoString.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoString\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoString\n{\n\n    @Id\n    private String id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoTime.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.sql.Time;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoTime\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoTime\n{\n\n    @Id\n    private Time id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Time getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Time id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoTimestamp.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.sql.Timestamp;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoTimestamp\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoTimestamp\n{\n\n    @Id\n    private Timestamp id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Timestamp getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Timestamp id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/datatypes/entities/StudentMongoUUID.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"StudentMongoUUID\", schema = \"KunderaMongoDataType@MongoDataTypeTest\")\npublic class StudentMongoUUID\n{\n\n    @Id\n    private UUID id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public UUID getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(UUID id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/AppUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"User\", schema = \"KunderaExamples@mongoTest\")\npublic class AppUser\n{\n    @Id\n    private String id;\n\n    @Column\n    private List<String> tags;\n\n    @Column\n    private Map<String, String> propertyKeys;\n\n    @Column\n    private Set<String> nickNames;\n\n    @Column\n    protected List<String> friendList;\n\n    @Embedded\n    private PhoneDirectory phoneDirectory;\n\n    public AppUser()\n    {\n        tags = new LinkedList<String>();\n        propertyKeys = new HashMap<String, String>();\n        nickNames = new HashSet<String>();\n        friendList = new LinkedList<String>();\n        tags.add(\"yo\");\n        propertyKeys.put(\"kk\", \"Kuldeep\");\n        nickNames.add(\"kk\");\n        friendList.add(\"xamry\");\n        friendList.add(\"mevivs\");\n    }\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public List<String> getTags()\n    {\n        return tags;\n    }\n\n    public Map<String, String> getPropertyKeys()\n    {\n        return propertyKeys;\n    }\n\n    public Set<String> getNickName()\n    {\n        return nickNames;\n    }\n\n    public List<String> getFriendList()\n    {\n        return friendList;\n    }\n\n    public PhoneDirectory getPhoneDirectory()\n    {\n        return phoneDirectory;\n    }\n\n    public void setPropertyContainer(PhoneDirectory propertyContainer)\n    {\n        this.phoneDirectory = propertyContainer;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/ArticleDetails.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport java.util.Date;\n\n/**\n * The Class ArticleDetails.\n */\n@Entity\n@Table(name = \"ArticleDetails\", schema = \"KunderaExamples@mongoTest\")\npublic class ArticleDetails\n{\n\n    @Id\n    @Column(name = \"details_id\")\n    private String id;\n\n    @Column(name = \"author\")\n    private String author;\n\n    @Column(name = \"intro\")\n    private String intro;\n\n    @Column(name = \"body\")\n    private String body;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(final String id)\n    {\n        this.id = id;\n    }\n\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    public void setAuthor(final String author)\n    {\n        this.author = author;\n    }\n\n    public String getIntro()\n    {\n        return intro;\n    }\n\n    public void setIntro(final String intro)\n    {\n        this.intro = intro;\n    }\n\n    public String getBody()\n    {\n        return body;\n    }\n\n    public void setBody(final String body)\n    {\n        this.body = body;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/ArticleGFS.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Lob;\nimport javax.persistence.Table;\nimport java.util.Date;\n\n/**\n * The Class ArticleGFS.\n */\n@Entity\n@Table(name = \"ArticleGFS\", schema = \"KunderaExamples@mongoTest\")\npublic class ArticleGFS\n{\n\n    @Id\n    @Column(name = \"article_id\")\n    private String articleId;\n\n    @Column(name = \"create_date\", nullable = false)\n    private Date createDate;\n\n    @Column(name = \"display_date\")\n    private Date displayDate;\n\n    @Column(name = \"title\", nullable = false)\n    private String title;\n\n    @Column(name = \"category\")\n    private String category;\n\n    @Column(name = \"priority\")\n    private int priority;\n\n    @Column(name = \"show\")\n    private boolean show;\n\n    @Lob\n    private byte[] data;\n\n    public String getArticleId()\n    {\n        return articleId;\n    }\n\n    public void setArticleId(final String articleId)\n    {\n        this.articleId = articleId;\n    }\n\n    public Date getCreateDate()\n    {\n        return createDate;\n    }\n\n    public void setCreateDate(final Date createDate)\n    {\n        this.createDate = createDate;\n    }\n\n    public Date getDisplayDate()\n    {\n        return displayDate;\n    }\n\n    public void setDisplayDate(final Date displayDate)\n    {\n        this.displayDate = displayDate;\n    }\n\n    public String getTitle()\n    {\n        return title;\n    }\n\n    public void setTitle(final String title)\n    {\n        this.title = title;\n    }\n\n    public String getCategory()\n    {\n        return category;\n    }\n\n    public void setCategory(final String category)\n    {\n        this.category = category;\n    }\n\n    public int getPriority()\n    {\n        return priority;\n    }\n\n    public void setPriority(final int priority)\n    {\n        this.priority = priority;\n    }\n\n    public boolean isShow()\n    {\n        return show;\n    }\n\n    public void setShow(final boolean show)\n    {\n        this.show = show;\n    }\n\n    public byte[] getData()\n    {\n        return data;\n    }\n\n    public void setData(final byte[] data)\n    {\n        this.data = data;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/ArticleMTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class ArticleMTO.\n */\n@Entity\n@Table(name = \"ArticleMTO\", schema = \"KunderaExamples@mongoTest\")\npublic class ArticleMTO\n{\n\n   @Id\n   @Column(name = \"ext_id\")\n   private String id;\n\n   @ManyToOne\n   @JoinColumn(name = \"article_id\")\n   private ArticleMongo article;\n\n   @OneToOne\n   @JoinColumn(name = \"details_id\")\n   private ArticleDetails details;\n\n   @Column(name = \"article_value\")\n   private long value;\n\n   public String getId()\n   {\n      return id;\n   }\n\n   public void setId(final String id)\n   {\n      this.id = id;\n   }\n\n   public ArticleMongo getArticle()\n   {\n      return article;\n   }\n\n   public void setArticle(final ArticleMongo article)\n   {\n      this.article = article;\n   }\n\n   public ArticleDetails getDetails()\n   {\n      return details;\n   }\n\n   public void setDetails(final ArticleDetails details)\n   {\n      this.details = details;\n   }\n\n   public long getValue()\n   {\n      return value;\n   }\n\n   public void setValue(final long value)\n   {\n      this.value = value;\n   }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/ArticleMongo.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport java.util.Date;\n\n/**\n * The Class ArticleMongo.\n */\n@Entity\n@Table(name = \"Article\", schema = \"KunderaExamples@mongoTest\")\npublic class ArticleMongo\n{\n\n    @Id\n    @Column(name = \"article_id\")\n    private String articleId;\n\n    @Column(name = \"create_date\", nullable = false)\n    private Date createDate;\n\n    @Column(name = \"display_date\")\n    private Date displayDate;\n\n    @Column(name = \"title\", nullable = false)\n    private String title;\n\n    @Column(name = \"category\")\n    private String category;\n\n    @Column(name = \"priority\")\n    private int priority;\n\n    @Column(name = \"show\")\n    private boolean show;\n\n    public String getArticleId()\n    {\n        return articleId;\n    }\n\n    public void setArticleId(final String articleId)\n    {\n        this.articleId = articleId;\n    }\n\n    public Date getCreateDate()\n    {\n        return createDate;\n    }\n\n    public void setCreateDate(final Date createDate)\n    {\n        this.createDate = createDate;\n    }\n\n    public Date getDisplayDate()\n    {\n        return displayDate;\n    }\n\n    public void setDisplayDate(final Date displayDate)\n    {\n        this.displayDate = displayDate;\n    }\n\n    public String getTitle()\n    {\n        return title;\n    }\n\n    public void setTitle(final String title)\n    {\n        this.title = title;\n    }\n\n    public String getCategory()\n    {\n        return category;\n    }\n\n    public void setCategory(final String category)\n    {\n        this.category = category;\n    }\n\n    public int getPriority()\n    {\n        return priority;\n    }\n\n    public void setPriority(final int priority)\n    {\n        this.priority = priority;\n    }\n\n    public boolean isShow()\n    {\n        return show;\n    }\n\n    public void setShow(final boolean show)\n    {\n        this.show = show;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/CompositeId.java",
    "content": "/*******************************************************************************\n * * Copyright 2017 Impetus Infotech.\n * *\n * * Licensed under the Apache License, Version 2.0 (the \"License\");\n * * you may not use this file except in compliance with the License.\n * * You may obtain a copy of the License at\n * *\n * * http://www.apache.org/licenses/LICENSE-2.0\n * *\n * * Unless required by applicable law or agreed to in writing, software\n * * distributed under the License is distributed on an \"AS IS\" BASIS,\n * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * * See the License for the specific language governing permissions and\n * * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Basic;\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * The Class CompositeId.\n */\n@Embeddable\npublic class CompositeId\n{\n\n    /** The first name. */\n    @Basic\n    @Column(name = \"first_name\")\n    private String firstName;\n\n    /** The birth date. */\n    @Basic\n    @Column(name = \"birth_date\")\n    private String birthDate;\n\n    /**\n     * Gets the first name.\n     * \n     * @return the first name\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * Sets the first name.\n     * \n     * @param firstName\n     *            the new first name\n     */\n    public void setFirstName(final String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * Gets the birth date.\n     * \n     * @return the birth date\n     */\n    public String getBirthDate()\n    {\n        return birthDate;\n    }\n\n    /**\n     * Sets the birth date.\n     * \n     * @param birthDate\n     *            the new birth date\n     */\n    public void setBirthDate(final String birthDate)\n    {\n        this.birthDate = birthDate;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/CompositeUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2017 Impetus Infotech.\n * *\n * * Licensed under the Apache License, Version 2.0 (the \"License\");\n * * you may not use this file except in compliance with the License.\n * * You may obtain a copy of the License at\n * *\n * * http://www.apache.org/licenses/LICENSE-2.0\n * *\n * * Unless required by applicable law or agreed to in writing, software\n * * distributed under the License is distributed on an \"AS IS\" BASIS,\n * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * * See the License for the specific language governing permissions and\n * * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.*;\n\n/**\n * The Class CompositeUser.\n */\n@Entity\n@Table(name = \"composite_user\")\npublic class CompositeUser\n{\n\n    /** The id. */\n    @EmbeddedId\n    private CompositeId id;\n\n    /** The phone. */\n    @Basic\n    @Column(name = \"phone\")\n    private String phone;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public CompositeId getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the new id\n     */\n    public void setId(final CompositeId id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the phone.\n     * \n     * @return the phone\n     */\n    public String getPhone()\n    {\n        return phone;\n    }\n\n    /**\n     * Sets the phone.\n     * \n     * @param phone\n     *            the new phone\n     */\n    public void setPhone(final String phone)\n    {\n        this.phone = phone;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/Day.java",
    "content": "package com.impetus.client.crud.entities;\n\npublic enum Day\n{\n    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/MongoDBCappedEntity.java",
    "content": "package com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author amresh\n * \n */\n@Entity\n@Table(name = \"MongoDBCappedEntity\", schema = \"KunderaMongoSchemaGeneration@mongoSchemaGenerationTest\")\n@IndexCollection(columns = { @Index(name = \"personName\", type = \"ASC\"),\n        @Index(name = \"age\", type = \"DSC\", min = 100, max = 500) })\npublic class MongoDBCappedEntity\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/MongoToken.java",
    "content": "package com.impetus.client.crud.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"tokens\", schema = \"KunderaExamples@mongoTest\")\npublic class MongoToken\n{\n    @Id\n    @Column(name = \"token_id\")\n    private String tokenId;\n    \n    @Column\n    private String tokenName;\n\n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"client_id\")\n    private MongoTokenClient client;\n\n    public String getId()\n    {\n        return tokenId;\n    }\n\n    public void setId(String id)\n    {\n        this.tokenId = id;\n    }\n\n    public MongoTokenClient getClient()\n    {\n        return client;\n    }\n\n    public void setClient(MongoTokenClient client)\n    {\n        this.client = client;\n    }\n\n    public String getTokenName()\n    {\n        return tokenName;\n    }\n\n    public void setTokenName(String tokenName)\n    {\n        this.tokenName = tokenName;\n    }\n\n    \n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/MongoTokenClient.java",
    "content": "package com.impetus.client.crud.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"client\", schema = \"KunderaExamples@mongoTest\")\npublic class MongoTokenClient\n{\n\n    @Id\n    @Column(name = \"client_id\")\n    private String clientId;\n\n    @Column(name = \"client_name\")\n    private String clientName;\n\n    @OneToMany(mappedBy = \"client\", fetch = FetchType.EAGER)\n    private Set<MongoToken> tokens;\n\n    public String getId()\n    {\n        return clientId;\n    }\n\n    public void setId(String id)\n    {\n        this.clientId = id;\n    }\n\n    public String getClientName()\n    {\n        return clientName;\n    }\n\n    public void setClientName(String clientName)\n    {\n        this.clientName = clientName;\n    }\n\n    public Set<MongoToken> getTokens()\n    {\n        return tokens;\n    }\n\n    public void setTokens(Set<MongoToken> tokens)\n    {\n        this.tokens = tokens;\n    }\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/PersonBatchMongoEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON_BATCH\", schema = \"KunderaMongoDataType@MongoBatchTest\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\npublic class PersonBatchMongoEntity\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"AGEss\")\n    private byte[] a;\n\n    /**\n     * @return the a\n     */\n    public byte[] getA()\n    {\n        return a;\n    }\n\n    /**\n     * @param a\n     *            the a to set\n     */\n    public void setA(byte[] a)\n    {\n        this.a = a;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/PersonMongo.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport java.util.Map;\n\nimport javax.persistence.Column;\nimport javax.persistence.ElementCollection;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.NamedQueries;\nimport javax.persistence.NamedQuery;\nimport javax.persistence.Table;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON\", schema = \"KunderaExamples@mongoTest\")\n@NamedQueries(value = {\n        @NamedQuery(name = \"mongo.named.query\", query = \"Select p from PersonMongo p where p.personName = :name\"),\n        @NamedQuery(name = \"mongo.position.query\", query = \"Select p from PersonMongo p where p.personName = ?1\") })\npublic class PersonMongo\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"DAY_ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    @Column(name = \"MONTH_ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Month month;\n\n    @ElementCollection\n    @Column(name = \"map\")\n    private Map<String, Month> map;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n\n    public Day getDay()\n    {\n        return day;\n    }\n\n    public Month getMonth()\n    {\n        return month;\n    }\n\n    public void setMonth(Month month)\n    {\n        this.month = month;\n    }\n\n    public enum Month\n    {\n        JAN, FEB, MARCH, APRIL, MAY, JUNE;\n    }\n\n    public Map<String, Month> getMap()\n    {\n        return map;\n    }\n\n    public void setMap(Map<String, Month> map)\n    {\n        this.map = map;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/PersonMongoEmptyTableName.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class PersonMongoTableName with empty table name.\n */\n@Entity\n@Table(name = \"\")\npublic class PersonMongoEmptyTableName\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    \n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n   \n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/PersonMongoMTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.client.crud.AddressMongoMTO;\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonMongoMTO\", schema = \"KunderaExamples@mongoTest\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonMongoMTO\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(nullable = false)\n    private AddressMongoMTO address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressMongoMTO getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressMongoMTO address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/PersonMongoNameAnnotation.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity(name=\"PesonMongo\")\n@Table(name = \"PERSON\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\npublic class PersonMongoNameAnnotation\n{\n/*    public static final String UID = \"uid\";\n\n    public static final String EID = \"eid\";\n\n    public static final String FIRST_NAME = \"firstName\";\n\n    public static final String LAST_NAME = \"lastName\";\n\n    public static final String CITY = \"city\";\n\n    public static final String CREATED = \"created\";\n\n    public static final String LAST_MODIFIED = \"lastModified\";*/\n\n    /** The person id. */\n    @Id\n     @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;   \n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the day\n     */\n    public Day getDay()\n    {\n        return day;\n    }\n\n    /**\n     * @param age the age to set\n     */\n    public void setAge(Integer age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @param day the day to set\n     */\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n    \n    \n\n}\n\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/PersonalDetailEmbedded.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Embedded;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Embeddable\npublic class PersonalDetailEmbedded\n{\n    @Column(name=\"PHONENO\")\n    private long phoneNo;\n\n    private String emailId;\n\n    private String address;\n\n    @Embedded\n    private PhoneDirectory phone;\n\n    public String getEmailId()\n    {\n        return emailId;\n    }\n\n    public void setEmailId(String emailId)\n    {\n        this.emailId = emailId;\n    }\n\n    public String getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    public long getPhoneNo()\n    {\n        return phoneNo;\n    }\n\n    public void setPhoneNo(long phoneNo)\n    {\n        this.phoneNo = phoneNo;\n    }\n\n    public PhoneDirectory getPhone()\n    {\n        return phone;\n    }\n\n    public void setPhone(PhoneDirectory phone)\n    {\n        this.phone = phone;\n    }\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/PersonnelEmbedded.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * \n * @author Kuldeep Mishra\n *\n */\n@Table(name = \"PERSONNEL\", schema = \"KunderaExamples@mongoTest\")\n@Entity\npublic class PersonnelEmbedded\n{\n    @Id\n    @Column\n    private int id;\n\n    @Column\n    private String name;\n\n    @Column\n    private int age;\n\n    @Embedded\n    private PersonalDetailEmbedded personalDetail;\n\n    public int getId()\n    {\n        return id;\n    }\n\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public PersonalDetailEmbedded getPersonalDetail()\n    {\n        return personalDetail;\n    }\n\n    public void setPersonalDetail(PersonalDetailEmbedded personalDetail)\n    {\n        this.personalDetail = personalDetail;\n    }\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/PhoneDirectory.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\nimport javax.validation.constraints.Size;\n\n@Embeddable\npublic class PhoneDirectory\n{\n    @Column\n    private String phoneDirectoryName;\n\n    @Column\n    private List<String> contactName;\n\n    @Column\n    @Size(message = \"The size should be at least equal to one but not more than 2\", min = 1, max = 2)\n    private Map<String, String> contactMap;\n\n    @Column\n    private Set<String> contactNumber;\n\n    public PhoneDirectory()\n    {\n        this.contactName = new LinkedList<String>();\n        this.contactMap = new HashMap<String, String>();\n    }\n\n    public PhoneDirectory(String phoneDirectoryName, List<String> contactName, Map<String, String> contactMap,\n            Set<String> contactNumber)\n    {\n        this.contactName = contactName;\n        this.contactMap = contactMap;\n        this.contactNumber = contactNumber;\n        this.phoneDirectoryName = phoneDirectoryName;\n    }\n\n    public String getPhoneDirectoryName()\n    {\n        return phoneDirectoryName;\n    }\n\n    public List<String> getContactName()\n    {\n        return contactName;\n    }\n\n    public Map<String, String> getContactMap()\n    {\n        return contactMap;\n    }\n\n    public Set<String> getContactNumber()\n    {\n        return contactNumber;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/entities/UserInformation.java",
    "content": "package com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"USER\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class UserInformation\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/event/EntityEventDispatcherTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.event;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.PostLoad;\nimport javax.persistence.PostPersist;\nimport javax.persistence.PrePersist;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.event.EntityEventDispatcher;\n\n\n/**\n * Test case for {@link EntityEventDispatcher}\n * \n * @author amresh.singh\n * \n */\npublic class EntityEventDispatcherTest\n{\n\n    private EntityEventDispatcher eventDispatcher;\n\n    private EntityManager em;\n\n    private EntityManagerFactory emf;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        eventDispatcher = new EntityEventDispatcher();\n        \n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        eventDispatcher = null;\n        em.close();\n        emf.close();\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.persistence.event.EntityEventDispatcher#fireEventListeners(com.impetus.kundera.metadata.model.EntityMetadata, java.lang.Object, java.lang.Class)}\n     * .\n     * @throws SecurityException \n     * @throws NoSuchMethodException \n     */\n    @Test\n    public void testExternalFireEventListeners() throws NoSuchMethodException, SecurityException\n    {\n        PersonEventDispatch person = new PersonEventDispatch(\"1\", \"John\", \"Smith\");\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance(), person.getClass());\n        eventDispatcher.fireEventListeners(m, person, PrePersist.class);\n        Assert.assertEquals(\"Amresh\", person.getFirstName());\n        Assert.assertEquals(\"Smith\", person.getLastName());\n        eventDispatcher.fireEventListeners(m, person, PostPersist.class);\n        Assert.assertEquals(\"Amresh\", person.getFirstName());\n        Assert.assertEquals(\"Singh\", person.getLastName());\n        \n        eventDispatcher.fireEventListeners(m, person, PostLoad.class);\n        Assert.assertEquals(\"Amresh\", person.getFirstName());\n        Assert.assertEquals(\"Post Load\", person.getLastName());\n        \n       \n    }\n    \n    /**\n     * Test method for\n     * {@link com.impetus.kundera.persistence.event.EntityEventDispatcher#fireEventListeners(com.impetus.kundera.metadata.model.EntityMetadata, java.lang.Object, java.lang.Class)}\n     * .\n     * @throws SecurityException \n     * @throws NoSuchMethodException \n     */\n    @Test\n    public void testEventListeners() throws NoSuchMethodException, SecurityException\n    {\n        PersonEventDispatch person = new PersonEventDispatch(\"1\", \"John\", \"Smith\");\n        em.persist(person); \n        \n        PersonEventDispatch found = em.find(PersonEventDispatch.class, \"1\");\n        Assert.assertEquals(\"Singh\", found.getLastName());\n        \n       \n    }\n\n  \n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/event/PersonEventDispatch.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2013 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.crud.event;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.EntityListeners;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * The Class PersonnelDTO.\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"person\")\r\n@EntityListeners({ PersonHandler.class })\r\npublic class PersonEventDispatch\r\n{\r\n\r\n    /** The person id. */\r\n    @Id\r\n    private String personId;\r\n\r\n    /** The first name. */\r\n    @Column(name = \"first_name\")\r\n    private String firstName;\r\n\r\n    /** The last name. */\r\n    @Column(name = \"last_name\")\r\n    private String lastName;\r\n\r\n    /**\r\n     * Instantiates a new personnel dto.\r\n     * \r\n     * @param personId\r\n     *            the person id\r\n     * @param firstName\r\n     *            the first name\r\n     * @param lastName\r\n     *            the last name\r\n     */\r\n    public PersonEventDispatch(String personId, String firstName, String lastName)\r\n    {\r\n        this.personId = personId;\r\n        this.firstName = firstName;\r\n        this.lastName = lastName;\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new personnel dto.\r\n     */\r\n    public PersonEventDispatch()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * Gets the person id.\r\n     * \r\n     * @return the personId\r\n     */\r\n    public String getPersonId()\r\n    {\r\n        return personId;\r\n    }\r\n\r\n    /**\r\n     * Sets the person id.\r\n     * \r\n     * @param personId\r\n     *            the personId to set\r\n     */\r\n    public void setPersonId(String personId)\r\n    {\r\n        this.personId = personId;\r\n    }\r\n\r\n    /**\r\n     * Gets the first name.\r\n     * \r\n     * @return the firstName\r\n     */\r\n    public String getFirstName()\r\n    {\r\n        return firstName;\r\n    }\r\n\r\n    /**\r\n     * Sets the first name.\r\n     * \r\n     * @param firstName\r\n     *            the firstName to set\r\n     */\r\n    public void setFirstName(String firstName)\r\n    {\r\n        this.firstName = firstName;\r\n    }\r\n\r\n    /**\r\n     * Gets the last name.\r\n     * \r\n     * @return the lastName\r\n     */\r\n    public String getLastName()\r\n    {\r\n        return lastName;\r\n    }\r\n\r\n    /**\r\n     * Sets the last name.\r\n     * \r\n     * @param lastName\r\n     *            the lastName to set\r\n     */\r\n    public void setLastName(String lastName)\r\n    {\r\n        this.lastName = lastName;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/event/PersonHandler.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.event;\n\nimport javax.persistence.PostLoad;\nimport javax.persistence.PostPersist;\nimport javax.persistence.PrePersist;\n\npublic class PersonHandler\n{\n\n    @PrePersist\n    public void handledPrePersist(PersonEventDispatch user)\n    {\n        user.setFirstName(\"Amresh\");\n    }\n\n    @PostPersist\n    public void handledPostPersist(PersonEventDispatch user)\n    {\n        user.setLastName(\"Singh\");\n    }\n    \n    @PostLoad\n    public void handledPostLoad(PersonEventDispatch user)\n    {\n        if(user != null)\n        {\n            user.setLastName(\"Post Load\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/gfs/GFSUser.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.gfs;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Lob;\nimport javax.persistence.Table;\n\n/**\n * The Class GFSUser.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"USER\", schema = \"GFS@gfs_pu\")\npublic class GFSUser\n{\n\n    /** The user id. */\n    @Id\n    @Column(name = \"USER_ID\")\n    private int userId;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /** The profile pic. */\n    @Lob\n    @Column(name = \"PROFILE_PIC\")\n    private byte[] profilePic;\n\n    /**\n     * Gets the user id.\n     * \n     * @return the user id\n     */\n    public int getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * Sets the user id.\n     * \n     * @param userId\n     *            the new user id\n     */\n    public void setUserId(int userId)\n    {\n        this.userId = userId;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the new name\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * Gets the profile pic.\n     * \n     * @return the profile pic\n     */\n    public byte[] getProfilePic()\n    {\n        return profilePic;\n    }\n\n    /**\n     * Sets the profile pic.\n     * \n     * @param profilePic\n     *            the new profile pic\n     */\n    public void setProfilePic(byte[] profilePic)\n    {\n        this.profilePic = profilePic;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/gfs/GridFSTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.gfs;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.utils.MongoUtils;\n\n/**\n * The Class GridFSTest.\n * \n * @author Devender Yadav\n */\npublic class GridFSTest\n{\n\n    /** The Constant _PU. */\n    private static final String _PU = \"gfs_pu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The profile pic1. */\n    private byte[] profilePic1;\n\n    /** The profile pic2. */\n    private byte[] profilePic2;\n\n    /** The profile pic3. */\n    private byte[] profilePic3;\n\n    /** The profile pic4. */\n    private byte[] profilePic4;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        MongoUtils.dropDatabase(emf, _PU);\n        emf.close();\n    }\n\n    /**\n     * Test CRUD GridFS.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testCRUDGridFS() throws Exception\n    {\n        testInsert();\n        testUpdateNonLobField();\n        testUpdateLobField();\n        testDelete();\n    }\n\n    /**\n     * Test query.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testQuery() throws Exception\n    {\n        profilePic1 = createBinaryData(\"src/test/resources/pic.jpg\", 10);\n        GFSUser user1 = prepareUserObject(1, \"Dev\", profilePic1);\n\n        profilePic2 = createBinaryData(\"src/test/resources/pic.jpg\", 15);\n        GFSUser user2 = prepareUserObject(2, \"PG\", profilePic2);\n\n        profilePic3 = createBinaryData(\"src/test/resources/pic.jpg\", 20);\n        GFSUser user3 = prepareUserObject(3, \"Amit\", profilePic3);\n\n        profilePic4 = createBinaryData(\"src/test/resources/pic.jpg\", 25);\n        GFSUser user4 = prepareUserObject(4, \"Viktor\", profilePic4);\n\n        em.persist(user1);\n        em.persist(user2);\n        em.persist(user3);\n        em.persist(user4);\n\n        em.clear();\n\n        String query = \"SELECT u FROM GFSUser u\";\n        Query qry = em.createQuery(query);\n        List<GFSUser> userList = qry.getResultList();\n        Assert.assertEquals(4, userList.size());\n        assertUsers(userList, true, true, true, true);\n\n        query = \"SELECT u FROM GFSUser u WHERE u.name = 'Dev'\";\n        qry = em.createQuery(query);\n        userList = qry.getResultList();\n        GFSUser user = userList.get(0);\n        Assert.assertEquals(\"Dev\", user.getName());\n        Assert.assertEquals(profilePic1.length, user.getProfilePic().length);\n\n        query = \"SELECT u FROM GFSUser u WHERE u.name = 'Karthik'\";\n        qry = em.createQuery(query);\n        userList = qry.getResultList();\n        Assert.assertEquals(true, userList.isEmpty());\n\n        query = \"SELECT u FROM GFSUser u WHERE u.userId = 2\";\n        qry = em.createQuery(query);\n        userList = qry.getResultList();\n        user = userList.get(0);\n        Assert.assertEquals(\"PG\", user.getName());\n        Assert.assertEquals(profilePic2.length, user.getProfilePic().length);\n\n        query = \"SELECT u FROM GFSUser u WHERE u.userId > 1\";\n        qry = em.createQuery(query);\n        userList = qry.getResultList();\n        Assert.assertEquals(3, userList.size());\n        assertUsers(userList, false, true, true, true);\n\n        query = \"SELECT u FROM GFSUser u WHERE u.userId = 2 and u.name = 'PG'\";\n        qry = em.createQuery(query);\n        userList = qry.getResultList();\n        Assert.assertEquals(1, userList.size());\n        user = userList.get(0);\n        Assert.assertEquals(\"PG\", user.getName());\n        Assert.assertEquals(profilePic2.length, user.getProfilePic().length);\n\n        query = \"SELECT u FROM GFSUser u WHERE u.userId < 3 order by u.name DESC\";\n        qry = em.createQuery(query);\n        userList = qry.getResultList();\n        Assert.assertEquals(2, userList.size());\n        assertUsers(userList, true, true, false, false);\n\n        query = \"SELECT u FROM GFSUser u order by u.name DESC\";\n        qry = em.createQuery(query);\n        qry.setFirstResult(1);\n        qry.setMaxResults(1);\n        userList = qry.getResultList();\n        Assert.assertEquals(1, userList.size());\n        assertUsers(userList, false, true, false, false);\n\n        query = \"SELECT u FROM GFSUser u order by u.name DESC\";\n        qry = em.createQuery(query);\n        qry.setFirstResult(2);\n        qry.setMaxResults(1);\n        userList = qry.getResultList();\n        Assert.assertEquals(1, userList.size());\n        assertUsers(userList, true, false, false, false);\n\n        query = \"SELECT u FROM GFSUser u order by u.name DESC\";\n        qry = em.createQuery(query);\n        qry.setMaxResults(2);\n        userList = qry.getResultList();\n        Assert.assertEquals(2, userList.size());\n        assertUsers(userList, false, true, false, true);\n\n        // remove all users\n        GFSUser u1 = em.find(GFSUser.class, 1);\n        GFSUser u2 = em.find(GFSUser.class, 2);\n        GFSUser u3 = em.find(GFSUser.class, 3);\n        GFSUser u4 = em.find(GFSUser.class, 4);\n        em.clear();\n        em.remove(u1);\n        em.remove(u2);\n        em.remove(u3);\n        em.remove(u4);\n    }\n\n    /**\n     * Test insert.\n     */\n    private void testInsert()\n    {\n        byte[] profilePic = createBinaryData(\"src/test/resources/pic.jpg\", 20);\n        GFSUser user = prepareUserObject(1, \"Dev\", profilePic);\n        em.persist(user);\n\n        em.clear();\n\n        GFSUser u = em.find(GFSUser.class, 1);\n        Assert.assertEquals(\"Dev\", u.getName());\n        Assert.assertEquals(profilePic.length, u.getProfilePic().length);\n    }\n\n    /**\n     * Test update non lob field.\n     */\n    private void testUpdateNonLobField()\n    {\n        GFSUser user = em.find(GFSUser.class, 1);\n        user.setName(\"Devender\");\n        em.merge(user);\n\n        em.clear();\n\n        GFSUser u1 = em.find(GFSUser.class, 1);\n\n        Assert.assertNotNull(u1);\n        Assert.assertEquals(\"Devender\", u1.getName());\n    }\n\n    /**\n     * Test update lob field.\n     */\n    private void testUpdateLobField()\n    {\n        GFSUser user = em.find(GFSUser.class, 1);\n        byte[] profilePic = createBinaryData(\"src/test/resources/pic.jpg\", 15);\n        user.setProfilePic(profilePic);\n\n        em.merge(user);\n\n        em.clear();\n\n        GFSUser u = em.find(GFSUser.class, 1);\n\n        Assert.assertNotNull(u);\n        Assert.assertEquals(\"Devender\", u.getName());\n        Assert.assertEquals(profilePic.length, u.getProfilePic().length);\n    }\n\n    /**\n     * Test delete.\n     */\n    private void testDelete()\n    {\n        GFSUser user = em.find(GFSUser.class, 1);\n        em.remove(user);\n        em.clear();\n        GFSUser u = em.find(GFSUser.class, 1);\n        Assert.assertNull(u);\n    }\n\n    /**\n     * Prepare user object.\n     * \n     * @param userID\n     *            the user id\n     * @param name\n     *            the name\n     * @param profilePic\n     *            the profile pic\n     * @return the GFS user\n     */\n    private GFSUser prepareUserObject(int userID, String name, byte[] profilePic)\n    {\n        GFSUser user = new GFSUser();\n        user.setUserId(userID);\n        user.setName(name);\n        user.setProfilePic(profilePic);\n        return user;\n    }\n\n    /**\n     * Creates the binary data.\n     * \n     * @param locationPath\n     *            the location path\n     * @param multiplicationFactor\n     *            the multiplication factor\n     * @return the byte[]\n     */\n    private byte[] createBinaryData(String locationPath, int multiplicationFactor)\n    {\n        Path path = Paths.get(locationPath);\n        byte[] data = null;\n        try\n        {\n            data = Files.readAllBytes(path);\n        }\n        catch (IOException e)\n        {\n            Assert.fail();\n        }\n\n        byte[] multipliedData = new byte[data.length * multiplicationFactor];\n\n        for (int i = 0; i < multiplicationFactor; i++)\n        {\n            System.arraycopy(data, 0, multipliedData, i * data.length, data.length);\n        }\n\n        return multipliedData;\n    }\n\n    /**\n     * Assert users.\n     * \n     * @param userList\n     *            the user list\n     * @param expectUser1\n     *            expect user1 to be found\n     * @param expectUser2\n     *            expect user2 to be found\n     * @param expectUser3\n     *            expect user3 to be found\n     * @param expectUser4\n     *            expect user4 to be found\n     */\n    private void assertUsers(List<GFSUser> userList, boolean expectUser1, boolean expectUser2, boolean expectUser3,\n            boolean expectUser4)\n    {\n        boolean foundUser1 = false;\n        boolean foundUser2 = false;\n        boolean foundUser3 = false;\n        boolean foundUser4 = false;\n\n        for (GFSUser user : userList)\n        {\n            if (user.getUserId() == 1)\n            {\n                foundUser1 = true;\n                Assert.assertEquals(\"Dev\", user.getName());\n                Assert.assertEquals(profilePic1.length, user.getProfilePic().length);\n            }\n\n            else if (user.getUserId() == 2)\n            {\n                foundUser2 = true;\n                Assert.assertEquals(\"PG\", user.getName());\n                Assert.assertEquals(profilePic2.length, user.getProfilePic().length);\n            }\n\n            else if (user.getUserId() == 3)\n            {\n                foundUser3 = true;\n                Assert.assertEquals(\"Amit\", user.getName());\n                Assert.assertEquals(profilePic3.length, user.getProfilePic().length);\n            }\n\n            else if (user.getUserId() == 4)\n            {\n                foundUser4 = true;\n                Assert.assertEquals(\"Viktor\", user.getName());\n                Assert.assertEquals(profilePic4.length, user.getProfilePic().length);\n            }\n\n            else\n            {\n                Assert.fail();\n            }\n        }\n\n        Assert.assertEquals(expectUser1, foundUser1);\n        Assert.assertEquals(expectUser2, foundUser2);\n        Assert.assertEquals(expectUser3, foundUser3);\n        Assert.assertEquals(expectUser4, foundUser4);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/mappedsuperclass/inheritence/MongoEntityWithoutFieldsTest.java",
    "content": "package com.impetus.client.crud.mappedsuperclass.inheritence;\n\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.mappedsuperclass.EntityWithoutFieldsBase;\n\n/**\n * @author amitkumar\n *\n *\tClass to verify that at least one field in entity class is not mandatory if the \n *\tsuperclass contains all the mandatory fields\n */\npublic class MongoEntityWithoutFieldsTest extends EntityWithoutFieldsBase\n{\n\n\t@Before\n\tpublic void setup()\n\t{\n\t\tpersistenceUnit = \"mongoShowQueryDisabledPU\";\n\t\tsetupInternal();\n\t}\n\t\n\t@Test\n\tpublic void testEntityWithNoFields()\n\t{\n\t\ttestEntityWithNoFieldsBase();\n\t}\n\t\n\t@Test\n\tpublic void testEntityWithNoFields2LevelInheritance()\n\t{\n\t\ttestEntityWithNoFields2LevelInheritanceBase();\n\t}\n\n\t@After\n\tpublic void tearDown()\n\t{\n\t\ttearDownInternal();\n\t}\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/crud/mappedsuperclass/inheritence/MongoMappedSuperClassTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.mappedsuperclass.inheritence;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.MappedSuperclass;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.utils.MongoUtils;\nimport com.impetus.kundera.client.crud.mappedsuperclass.CreditTransaction;\nimport com.impetus.kundera.client.crud.mappedsuperclass.MappedSuperClassBase;\nimport com.impetus.kundera.client.crud.mappedsuperclass.Status;\nimport com.impetus.kundera.client.mongo.mappedsuperclass.Ledger;\n\n\n\n/**\n * @author vivek.mishra junit for {@link MappedSuperclass},\n *         {@link AttributeOverride}, {@link AttributeOverrides}.\n */\npublic class MongoMappedSuperClassTest extends MappedSuperClassBase\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        \n        _PU = \"mongoTest\";\n        setUpInternal();\n    }\n\n    @Test\n    public void test()\n    {\n        assertInternal();\n        \n    }\n    \n    @Test\n    public void testRelation()\n    {\n        CreditTransaction creditTx = new CreditTransaction();\n        creditTx.setTxId(\"credit1\");\n        creditTx.setTxStatus(Status.APPROVED);\n        creditTx.setBankIdentifier(\"sbi\");\n        creditTx.setTransactionDt(new Date());\n        creditTx.setAmount(10);\n        \n        Ledger ledger = new Ledger();\n        ledger.setLedgerId(\"l1\");\n        ledger.setPayee(\"User1\");\n        \n        creditTx.setLedger(ledger);\n        \n//        ledger.setTransaction(creditTx);\n        em.persist(creditTx);\n     \n           \n        em.clear();\n        String creditQuery = \"Select c from CreditTransaction c where c.bankIdentifier = 'sbi'\";\n\n        Query query = em.createQuery(creditQuery);\n\n        List<CreditTransaction> results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"credit1\", results.get(0).getTxId());\n        Assert.assertNotNull(results.get(0).getLedger());\n        \n    \n        em.clear();\n      \n\n    }\n\n    \n    \n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        MongoUtils.dropDatabase(emf, _PU);\n        tearDownInternal();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/esindexer/MongoESAggregationTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n/*\n * author: karthikp.manchala\n */\npackage com.impetus.client.esindexer;\n\nimport javax.persistence.Persistence;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.query.AggregationsBaseTest;\nimport com.impetus.kundera.query.Person;\n\n/**\n * The Class CassandraESAggregationTest.\n * \n * @author karthikp.manchala\n */\npublic class MongoESAggregationTest extends AggregationsBaseTest\n{\n\n    /** The node. */\n    private static Node node = null;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n    }\n\n    /**\n     * Setup.\n     * \n     * @throws InterruptedException\n     *             the interrupted exception\n     */\n    @Before\n    public void setup() throws InterruptedException\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"esIndexerTest\");\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        testAggregation();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (node != null)\n            node.close();\n    }\n\n    /**\n     * Tear down.\n     */\n    @After\n    public void tearDown()\n    {\n        em.remove(em.find(Person.class, \"1\"));\n        em.remove(em.find(Person.class, \"2\"));\n        em.remove(em.find(Person.class, \"3\"));\n        em.remove(em.find(Person.class, \"4\"));\n        em.close();\n        emf.close();\n    }\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/esindexer/MongoESGroupByTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.esindexer;\n\nimport javax.persistence.Persistence;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.query.GroupByBaseTest;\n\n/**\n * The Class CassandraESGroupByTest.\n * \n * @author karthikp.manchala\n * \n */\npublic class MongoESGroupByTest extends GroupByBaseTest\n{\n\n    /** The node. */\n    private static Node node = null;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n\n        emf = Persistence.createEntityManagerFactory(\"esIndexerTest\");\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Test aggregation.\n     */\n    @Test\n    public void test()\n    {\n        testAggregation();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        em.createQuery(\"Delete from Person p\").executeUpdate();\n        waitThread();\n\n        em.close();\n        emf.close();\n\n        if (node != null)\n            node.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/esindexer/MongoESOrderByTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.esindexer;\n\nimport javax.persistence.Persistence;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.query.OrderByBaseTest;\n\n/**\n * The Class CassandraESOrderByTest.\n * \n * @author Amit Kumar\n */\npublic class MongoESOrderByTest extends OrderByBaseTest\n{\n\n    /** The node. */\n    private static Node node = null;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n\n        emf = Persistence.createEntityManagerFactory(\"esIndexerTest\");\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Test Order By.\n     */\n    @Test\n    public void test()\n    {\n        testQuery();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        em.createQuery(\"Delete from Person p\").executeUpdate();\n        waitThread();\n\n        em.close();\n        emf.close();\n\n        if (node != null)\n            node.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/generatedId/MongoGeneratedIdTest.java",
    "content": "package com.impetus.client.generatedId;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.bson.types.ObjectId;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.generatedId.entites.MongoGeneratedIdDefault;\nimport com.impetus.client.generatedId.entites.MongoGeneratedIdStrategyAuto;\nimport com.impetus.client.generatedId.entites.MongoGeneratedIdStrategyIdentity;\nimport com.impetus.client.generatedId.entites.MongoGeneratedIdStrategySequence;\nimport com.impetus.client.generatedId.entites.MongoGeneratedIdStrategyTable;\nimport com.impetus.client.generatedId.entites.MongoGeneratedIdWithOutSequenceGenerator;\nimport com.impetus.client.generatedId.entites.MongoGeneratedIdWithOutTableGenerator;\nimport com.impetus.client.generatedId.entites.MongoGeneratedIdWithSequenceGenerator;\nimport com.impetus.client.generatedId.entites.MongoGeneratedIdWithTableGenerator;\nimport com.impetus.client.mongodb.MongoDBClient;\nimport com.impetus.client.utils.MongoUtils;\nimport com.impetus.kundera.KunderaException;\n\npublic class MongoGeneratedIdTest\n{\n\n    private EntityManagerFactory emf;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n    }\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        MongoUtils.dropDatabase(emf, \"mongoTest\");\n        emf.close();\n    }\n\n    @Test\n    public void testPersist()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        MongoGeneratedIdDefault idDefault = new MongoGeneratedIdDefault();\n        idDefault.setName(\"kuldeep\");\n        try\n        {\n            em.persist(idDefault);\n            List<MongoGeneratedIdDefault> list = em.createQuery(\"Select c from MongoGeneratedIdDefault c\")\n                    .getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"kuldeep\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            idDefault = em.find(MongoGeneratedIdDefault.class, id);\n            Assert.assertNotNull(idDefault);\n            Assert.assertEquals(\"kuldeep\", idDefault.getName());\n        }\n        catch (KunderaException e)\n        {\n            \n            Assert.fail();\n        }\n        MongoGeneratedIdStrategyAuto strategyAuto = new MongoGeneratedIdStrategyAuto();\n        strategyAuto.setName(\"kuldeep\");\n        try\n        {\n            em.persist(strategyAuto);\n            em.clear();\n            List<MongoGeneratedIdStrategyAuto> list = em.createQuery(\"Select c from MongoGeneratedIdStrategyAuto c\")\n                    .getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertTrue(list.get(0).getId() instanceof ObjectId);\n            Assert.assertEquals(\"kuldeep\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            strategyAuto = em.find(MongoGeneratedIdStrategyAuto.class, id);\n            Assert.assertNotNull(strategyAuto);\n            Assert.assertEquals(\"kuldeep\", strategyAuto.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n\n        MongoGeneratedIdStrategyIdentity strategyIdentity = new MongoGeneratedIdStrategyIdentity();\n        strategyIdentity.setName(\"kuldeep\");\n        try\n        {\n            em.persist(strategyIdentity);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.UnsupportedOperationException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.IDENTITY + \" Strategy not supported by this client :\"\n                            + MongoDBClient.class.getName(), e.getMessage());\n        }\n\n        MongoGeneratedIdStrategySequence strategySequence = new MongoGeneratedIdStrategySequence();\n        strategySequence.setName(\"Kuldeep\");\n        try\n        {\n            em.persist(strategySequence);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + MongoDBClient.class.getName(), e.getMessage());\n        }\n\n        MongoGeneratedIdStrategyTable strategyTable = new MongoGeneratedIdStrategyTable();\n        strategyTable.setName(\"KK\");\n        try\n        {\n            em.persist(strategyTable);\n            Assert.fail();\n\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.TABLE + \" Strategy not supported by this client :\"\n                            + MongoDBClient.class.getName(), e.getMessage());\n        }\n\n        MongoGeneratedIdWithOutSequenceGenerator withOutSequenceGenerator = new MongoGeneratedIdWithOutSequenceGenerator();\n        withOutSequenceGenerator.setName(\"Kuldeep Kumar\");\n        try\n        {\n            em.persist(withOutSequenceGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + MongoDBClient.class.getName(), e.getMessage());\n        }\n\n        MongoGeneratedIdWithOutTableGenerator withOutTableGenerator = new MongoGeneratedIdWithOutTableGenerator();\n        withOutTableGenerator.setName(\"Kuldeep Mishra\");\n        try\n        {\n            em.persist(withOutTableGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.TABLE + \" Strategy not supported by this client :\"\n                            + MongoDBClient.class.getName(), e.getMessage());\n        }\n        MongoGeneratedIdWithSequenceGenerator withSequenceGenerator = new MongoGeneratedIdWithSequenceGenerator();\n        withSequenceGenerator.setName(\"Kuldeep Kumar Mishra\");\n        try\n        {\n            em.persist(withSequenceGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.SEQUENCE + \" Strategy not supported by this client :\"\n                            + MongoDBClient.class.getName(), e.getMessage());\n        }\n        MongoGeneratedIdWithTableGenerator withTableGenerator = new MongoGeneratedIdWithTableGenerator();\n        withTableGenerator.setName(\"Kumar Mishra\");\n        try\n        {\n            em.persist(withTableGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.TABLE + \" Strategy not supported by this client :\"\n                            + MongoDBClient.class.getName(), e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/generatedId/entites/MongoGeneratedIdDefault.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"MongoGeneratedIdDefault\", schema = \"KunderaExamples@mongoTest\")\npublic class MongoGeneratedIdDefault\n{\n    @Id\n    @GeneratedValue\n    private String id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/generatedId/entites/MongoGeneratedIdStrategyAuto.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\nimport org.bson.types.ObjectId;\n\n@Entity\n@Table(name = \"MongoGeneratedIdStrategyAuto\", schema = \"KunderaExamples@mongoTest\")\n@TableGenerator(name = \"id_gen\")\npublic class MongoGeneratedIdStrategyAuto\n{\n    @Id\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.AUTO)\n    private ObjectId id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public ObjectId getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(ObjectId id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/generatedId/entites/MongoGeneratedIdStrategyIdentity.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"MongoGeneratedIdStrategyIdentity\", schema = \"KunderaExamples@mongoTest\")\npublic class MongoGeneratedIdStrategyIdentity\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    private String id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/generatedId/entites/MongoGeneratedIdStrategySequence.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"MongoGeneratedIdStrategySequence\", schema = \"KunderaExamples@mongoTest\")\npublic class MongoGeneratedIdStrategySequence\n{\n    @Id\n    @SequenceGenerator(name = \"seq_gen\")\n    @GeneratedValue(generator = \"seq_gen\", strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/generatedId/entites/MongoGeneratedIdStrategyTable.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"MongoGeneratedIdStrategyTable\", schema = \"KunderaExamples@mongoTest\")\n@TableGenerator(name = \"table_gen\")\npublic class MongoGeneratedIdStrategyTable\n{\n\n    @Id\n    @TableGenerator(name = \"table_gen_1\")\n    @GeneratedValue(generator = \"table_gen\", strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/generatedId/entites/MongoGeneratedIdWithOutSequenceGenerator.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"MongoGeneratedIdWithOutSequenceGenerator\", schema = \"KunderaExamples@mongoTest\")\npublic class MongoGeneratedIdWithOutSequenceGenerator\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/generatedId/entites/MongoGeneratedIdWithOutTableGenerator.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"MongoGeneratedIdWithOutTableGenerator\", schema = \"KunderaExamples@mongoTest\")\npublic class MongoGeneratedIdWithOutTableGenerator\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/generatedId/entites/MongoGeneratedIdWithSequenceGenerator.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"MongoGeneratedIdWithSequenceGenerator\", schema = \"KunderaExamples@mongoTest\")\npublic class MongoGeneratedIdWithSequenceGenerator\n{\n    @Id\n    @SequenceGenerator(name = \"id_gen\", allocationSize = 20, initialValue = 80, schema = \"KunderaExamples\", sequenceName = \"newSequence\")\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/generatedId/entites/MongoGeneratedIdWithTableGenerator.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"MongoGeneratedIdWithTableGenerator\", schema = \"KunderaExamples@mongoTest\")\npublic class MongoGeneratedIdWithTableGenerator\n{\n\n    @Id\n    @TableGenerator(name = \"id_gen\", allocationSize = 30, initialValue = 100, schema = \"KunderaExamples\", table = \"kundera\", pkColumnName = \"sequence\", valueColumnName = \"sequenceValue\", pkColumnValue = \"kk\")\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/gis/MongoGISTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.gis;\n\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.databene.contiperf.PerfTest;\nimport org.databene.contiperf.junit.ContiPerfRule;\nimport org.databene.contiperf.report.CSVSummaryReportModule;\nimport org.databene.contiperf.report.HtmlReportModule;\nimport org.databene.contiperf.report.ReportModule;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\n\nimport com.impetus.kundera.gis.SurfaceType;\nimport com.impetus.kundera.gis.geometry.Coordinate;\nimport com.impetus.kundera.gis.geometry.Point;\nimport com.impetus.kundera.gis.geometry.Polygon;\nimport com.vividsolutions.jts.geom.CoordinateSequence;\nimport com.vividsolutions.jts.geom.GeometryFactory;\nimport com.vividsolutions.jts.geom.LinearRing;\n\n/**\n * Test case for GIS\n * \n * @author amresh.singh\n */\n@PerfTest(invocations = 1)\npublic class MongoGISTest\n{\n    String persistenceUnit = \"mongoTest\";\n\n    PersonGISDao dao;\n\n    static Object testParameter;\n\n    @Rule\n    public ContiPerfRule i = new ContiPerfRule(new ReportModule[] { new CSVSummaryReportModule(),\n            new HtmlReportModule() });\n\n    /**\n     * @return the testParameter\n     */\n    public Object getTestParameter()\n    {\n        return testParameter;\n    }\n\n    /**\n     * @param testParameter\n     *            the testParameter to set\n     */\n    public static void setTestParameter(Object testParam)\n    {\n        testParameter = testParam;\n    }\n\n    @Before\n    public void setUp() throws Exception\n    {\n        \n        dao = new PersonGISDao(persistenceUnit);\n    }\n\n    @Test\n    public synchronized void executeTests() throws Exception\n    {\n        addPersons();\n        findPerson();\n\n        // Within Queries\n        findWithinCircle();\n        findWithinTriangle();\n        findWithinPolygon();\n        findWithinRectangle();\n\n        // Near Queries\n        findNear();\n        findNearSphere();\n        findCentreSphere();\n\n        findUsingExactCurrentLocation();\n        findWithinCircleAndName();\n\n        // Update/Delete Queries\n        updateNameWithinCircle();\n        deleteNameWithinCircle();\n\n        updatePerson();\n        removePerson();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        dao.close();\n    }\n\n    private void addPersons()\n    {\n        dao.createEntityManager();\n        for (int i = 0; i < 100; i++)\n        {\n            double x = i % 10;\n            double y = Math.floor(i / 10);\n\n            Person person = new Person();\n            person.setPersonId(i + 1);\n            person.setName(\"Amresh_\" + (i + 1));\n            person.setCurrentLocation(new Point(x, y));\n\n            Vehicle vehicle = new Vehicle();\n            vehicle.setCurrentLocation(new Point(x + 1.0, y + 1.0));\n            vehicle.setPreviousLocation(new Point(x + 2.0, y + 2.0));\n\n            person.setVehicle(vehicle);\n\n            dao.addPerson(person);\n        }\n        dao.closeEntityManager();\n    }\n\n    private void findPerson()\n    {\n        dao.createEntityManager();\n        Person person = dao.findPerson(4);\n\n        Assert.assertNotNull(person);\n        Assert.assertEquals(4, person.getPersonId());\n        Assert.assertEquals(\"Amresh_4\", person.getName());\n\n        Point currentLocation = person.getCurrentLocation();\n        Assert.assertNotNull(currentLocation);\n        Assert.assertEquals(3.0, currentLocation.getX());\n        Assert.assertEquals(0.0, currentLocation.getY());\n\n        Vehicle vehicleLocation = person.getVehicle();\n        Assert.assertNotNull(vehicleLocation);\n        Assert.assertNotNull(vehicleLocation.getCurrentLocation());\n        Assert.assertEquals(4.0, vehicleLocation.getCurrentLocation().getX());\n        Assert.assertEquals(1.0, vehicleLocation.getCurrentLocation().getY());\n        Assert.assertNotNull(vehicleLocation.getPreviousLocation());\n        Assert.assertEquals(5.0, vehicleLocation.getPreviousLocation().getX());\n        Assert.assertEquals(2.0, vehicleLocation.getPreviousLocation().getY());\n\n        dao.closeEntityManager();\n    }\n\n    private void findWithinCircle()\n    {\n        dao.createEntityManager();\n\n        List<Person> persons = dao.findWithinCircle(5.0, 5.0, 2.0, SurfaceType.FLAT);\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 13);\n        dao.closeEntityManager();\n    }\n\n    private void findWithinTriangle()\n    {\n        dao.createEntityManager();\n\n        List<Person> persons = dao.findWithinTriangle(5.0, 5.0, 6.0, 6.0, 7.0, 7.0);\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 3);\n        dao.closeEntityManager();\n    }\n\n    private void findWithinPolygon()\n    {\n        dao.createEntityManager();\n\n        GeometryFactory factory = new GeometryFactory();\n\n        Coordinate[] coordinates = new Coordinate[6];\n        coordinates[0] = new Coordinate(1.0, 1.0);\n        coordinates[1] = new Coordinate(1.0, 2.0);\n        coordinates[2] = new Coordinate(3.0, 4, 0);\n        coordinates[3] = new Coordinate(4.0, 3.0);\n        coordinates[4] = new Coordinate(4.0, 1.0);\n        coordinates[5] = new Coordinate(1.0, 1.0);\n\n        CoordinateSequence points = factory.getCoordinateSequenceFactory().create(coordinates);\n\n        LinearRing shell = new LinearRing(points, factory);\n        LinearRing[] holes = new LinearRing[0];\n        // holes[0] = shell;\n\n        Polygon polygon = new Polygon(shell, holes, factory);\n        List<Person> persons = dao.findWithinPolygon(polygon);\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 11);\n        dao.closeEntityManager();\n\n        dao.createEntityManager();\n\n        holes = new LinearRing[1];\n        holes[0] = shell;\n        polygon = new Polygon(shell, holes, factory);\n        persons = dao.findWithinPolygon(polygon);\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 8);\n        dao.closeEntityManager();\n\n    }\n\n    private void findWithinRectangle()\n    {\n        dao.createEntityManager();\n\n        List<Person> persons = dao.findWithinRectangle(5.0, 5.0, 6.0, 6.0);\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 4);\n        dao.closeEntityManager();\n    }\n\n    private void findNear()\n    {\n        dao.createEntityManager();\n        List<Person> persons = dao.findNear(5.0, 5.0, 2.0, SurfaceType.FLAT);\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 13);\n        dao.closeEntityManager();\n    }\n\n    private void findNearSphere()\n    {\n        dao.createEntityManager();\n        List<Person> persons = dao.findNear(5.0, 5.0, (2.0 * 2.0 * 3.1416 / 360.0), SurfaceType.SPHERICAL);\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 13);\n        dao.closeEntityManager();\n    }\n\n    private void findCentreSphere()\n    {\n        dao.createEntityManager();\n\n        // List<Person> persons = dao.findWithinCircle(5.0, 5.0,\n        // (2.0*2.0*3.1416/360.0), SurfaceType.SPHERICAL);\n        // Assert.assertNotNull(persons);\n        // Assert.assertFalse(persons.isEmpty());\n        // Assert.assertTrue(persons.size() == 13);\n        dao.closeEntityManager();\n    }\n\n    private void findUsingExactCurrentLocation()\n    {\n        dao.createEntityManager();\n\n        List<Person> persons = dao.findUsingCLWithEQ(5.0, 5.0);\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        dao.closeEntityManager();\n    }\n\n    private void findWithinCircleAndName()\n    {\n        dao.createEntityManager();\n\n        List<Person> persons = dao.findWithinCircleAndName(5.0, 5.0, 2.0, SurfaceType.FLAT, \"Amresh_45\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        dao.closeEntityManager();\n    }\n\n    private void updateNameWithinCircle()\n    {\n        dao.createEntityManager();\n\n        int updateCount = dao.updateNameWithinCircle(5.0, 5.0, 0.0, SurfaceType.FLAT);\n        Assert.assertTrue(updateCount == 1);\n\n        dao.createEntityManager();\n        List<Person> persons = dao.findWithinCircle(5.0, 5.0, 0.0, SurfaceType.FLAT);\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        Assert.assertEquals(\"Kuldeep\", persons.get(0).getName());\n        dao.closeEntityManager();\n    }\n\n    private void deleteNameWithinCircle()\n    {\n        dao.createEntityManager();\n\n        int deleteCount = dao.deleteNameWithinCircle(5.0, 5.0, 0.0, SurfaceType.FLAT);\n        Assert.assertTrue(deleteCount == 1);\n        dao.closeEntityManager();\n\n        dao.createEntityManager();\n        List<Person> persons = dao.findWithinCircle(5.0, 5.0, 0.0, SurfaceType.FLAT);\n        Assert.assertNotNull(persons);\n        Assert.assertTrue(persons.isEmpty());\n        dao.closeEntityManager();\n    }\n\n    /**\n     * \n     */\n    private void updatePerson()\n    {\n        dao.createEntityManager();\n        Person person = dao.findPerson(4);\n\n        Assert.assertNotNull(person);\n        Assert.assertEquals(4, person.getPersonId());\n        Assert.assertEquals(\"Amresh_4\", person.getName());\n\n        person.setCurrentLocation(new Point(9.3, 5.8));\n\n        Vehicle vehicle = person.getVehicle();\n        vehicle.setCurrentLocation(new Point(5.67, 11.59));\n        vehicle.setPreviousLocation(new Point(15.67, 21.59));\n\n        person.setVehicle(vehicle);\n\n        dao.mergePerson(person);\n        dao.closeEntityManager();\n        dao.createEntityManager();\n\n        person = dao.findPerson(4);\n\n        Assert.assertNotNull(person);\n        Assert.assertEquals(4, person.getPersonId());\n        Assert.assertEquals(\"Amresh_4\", person.getName());\n        Point currentLocation = person.getCurrentLocation();\n        Assert.assertNotNull(currentLocation);\n        Assert.assertEquals(9.3, currentLocation.getX());\n        Assert.assertEquals(5.8, currentLocation.getY());\n\n        vehicle = person.getVehicle();\n        Assert.assertNotNull(vehicle);\n        Assert.assertNotNull(vehicle.getCurrentLocation());\n        Assert.assertEquals(5.67, vehicle.getCurrentLocation().getX());\n        Assert.assertEquals(11.59, vehicle.getCurrentLocation().getY());\n        Assert.assertNotNull(vehicle.getPreviousLocation());\n        Assert.assertEquals(15.67, vehicle.getPreviousLocation().getX());\n        Assert.assertEquals(21.59, vehicle.getPreviousLocation().getY());\n\n        dao.closeEntityManager();\n\n    }\n\n    /**\n     * \n     */\n    private void removePerson()\n    {\n        dao.createEntityManager();\n        Person person = dao.findPerson(4);\n\n        Assert.assertNotNull(person);\n\n        dao.removePerson(person);\n\n        dao.closeEntityManager();\n        dao.createEntityManager();\n\n        person = dao.findPerson(4);\n\n        Assert.assertNull(person);\n        dao.closeEntityManager();\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/gis/Person.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.gis;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.gis.geometry.Point;\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Person Entity Class\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PERSON_LOCATION\", schema = \"KunderaExamples@mongoTest\")\n@IndexCollection(columns = { @Index(name = \"currentLocation\", type = \"GEO2D\") })\npublic class Person\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private int personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String name;\n\n    @Column(name = \"CURRENT_LOCATION\")\n    private Point currentLocation;\n\n    @Embedded\n    private Vehicle vehicle;\n\n    /**\n     * @return the personId\n     */\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * @param personId\n     *            the personId to set\n     */\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the currentLocation\n     */\n    public Point getCurrentLocation()\n    {\n        return currentLocation;\n    }\n\n    /**\n     * @param currentLocation\n     *            the currentLocation to set\n     */\n    public void setCurrentLocation(Point currentLocation)\n    {\n        this.currentLocation = currentLocation;\n    }\n\n    /**\n     * @return the vehicle\n     */\n    public Vehicle getVehicle()\n    {\n        return vehicle;\n    }\n\n    /**\n     * @param vehicle\n     *            the vehicle to set\n     */\n    public void setVehicle(Vehicle vehicle)\n    {\n        this.vehicle = vehicle;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/gis/PersonGISDao.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.gis;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport com.impetus.client.utils.MongoUtils;\nimport com.impetus.kundera.gis.SurfaceType;\nimport com.impetus.kundera.gis.geometry.Circle;\nimport com.impetus.kundera.gis.geometry.Envelope;\nimport com.impetus.kundera.gis.geometry.Point;\nimport com.impetus.kundera.gis.geometry.Polygon;\nimport com.impetus.kundera.gis.geometry.Triangle;\n\n/**\n * DAO for Geolocation processing for {@link Person} entity\n * \n * @author amresh.singh\n */\npublic class PersonGISDao\n{\n\n    private EntityManager em;\n\n    private EntityManagerFactory emf;\n\n    private String pu;\n\n    public PersonGISDao(String persistenceUnitName)\n    {\n        this.pu = persistenceUnitName;\n        if (emf == null)\n        {\n            try\n            {\n                emf = Persistence.createEntityManagerFactory(persistenceUnitName);\n            }\n            catch (Exception e)\n            {\n                \n            }\n        }\n\n    }\n\n    public void createEntityManager()\n    {\n        if (em == null)\n        {\n            em = emf.createEntityManager();\n        }\n    }\n\n    public void closeEntityManager()\n    {\n        if (em != null)\n        {\n            em.close();\n            em = null;\n        }\n    }\n\n    public void close()\n    {\n        if (emf != null)\n        {\n            MongoUtils.dropDatabase(emf, pu);\n            emf.close();\n        }\n    }\n\n    public void addPerson(Person person)\n    {\n        em.persist(person);\n    }\n\n    public Person findPerson(int personId)\n    {\n        return em.find(Person.class, personId);\n    }\n\n    public List<Person> findWithinCircle(double x, double y, double r, SurfaceType surfaceType)\n    {\n        Circle circle = new Circle(x, y, r);\n        circle.setSurfaceType(surfaceType);\n\n        Query q = em.createQuery(\"Select p from Person p where p.currentLocation IN ?1\");\n        q.setParameter(1, circle);\n        List<Person> persons = q.getResultList();\n        return persons;\n    }\n\n    public List<Person> findWithinTriangle(double x1, double y1, double x2, double y2, double x3, double y3)\n    {\n\n        Triangle triangle = new Triangle(x1, y1, x2, y2, x3, y3);\n\n        Query q = em.createQuery(\"Select p from Person p where p.currentLocation IN :triangle\");\n        q.setParameter(\"triangle\", triangle);\n        List<Person> persons = q.getResultList();\n        return persons;\n    }\n\n    public List<Person> findWithinPolygon(Polygon polygon)\n    {\n        Query q = em.createQuery(\"Select p from Person p where p.currentLocation IN :polygon\");\n        q.setParameter(\"polygon\", polygon);\n        List<Person> persons = q.getResultList();\n        return persons;\n    }\n\n    public List<Person> findWithinRectangle(double x1, double y1, double x2, double y2)\n    {\n        Envelope envelope = new Envelope(x1, x2, y1, y2);\n        Query q = em.createQuery(\"Select p from Person p where p.currentLocation IN :envelope\");\n        q.setParameter(\"envelope\", envelope);\n        List<Person> persons = q.getResultList();\n        return persons;\n    }\n\n    public List<Person> findNear(double x, double y, double maxDistance, SurfaceType surfaceType)\n    {\n        Point point = new Point(x, y);\n        point.setSurfaceType(surfaceType);\n\n        Query q = em\n                .createQuery(\"Select p from Person p where p.currentLocation > :point AND p.currentLocation < :maxDistance\");\n        q.setParameter(\"point\", point);\n        q.setParameter(\"maxDistance\", maxDistance);\n        List<Person> persons = q.getResultList();\n        return persons;\n    }\n\n    public void mergePerson(Person person)\n    {\n        em.merge(person);\n    }\n\n    public void removePerson(Person person)\n    {\n        em.remove(person);\n    }\n\n    /**\n     * @param d\n     * @param e\n     * @return\n     */\n    public List<Person> findUsingCLWithEQ(double x, double y)\n    {\n        Circle circle = new Circle(x, y, 0);\n        circle.setSurfaceType(SurfaceType.FLAT);\n\n        Query q = em.createQuery(\"Select p from Person p where p.currentLocation IN ?1\");\n        q.setParameter(1, circle);\n        List<Person> persons = q.getResultList();\n        return persons;\n    }\n\n    /**\n     * @param d\n     * @param e\n     * @param f\n     * @param flat\n     * @param string\n     * @return\n     */\n    public List<Person> findWithinCircleAndName(double x, double y, double r, SurfaceType surfaceType, String name)\n    {\n\n        Circle circle = new Circle(x, y, r);\n        circle.setSurfaceType(surfaceType);\n\n        Query q = em.createQuery(\"Select p from Person p where p.name = :name and p.currentLocation IN :circle\");\n        q.setParameter(\"name\", name);\n        q.setParameter(\"circle\", circle);\n        List<Person> persons = q.getResultList();\n        return persons;\n\n    }\n\n    /**\n     * @param d\n     * @param e\n     * @param f\n     * @param flat\n     * @return\n     */\n    public int updateNameWithinCircle(double x, double y, double r, SurfaceType surfaceType)\n    {\n        Circle circle = new Circle(x, y, r);\n        circle.setSurfaceType(surfaceType);\n        Query q = em.createQuery(\"Update Person p SET p.name=Kuldeep where p.currentLocation IN ?1\");\n        q.setParameter(1, circle);\n        return q.executeUpdate();\n//        return persons;\n    }\n\n    /**\n     * @param d\n     * @param e\n     * @param f\n     * @param flat\n     * @return\n     */\n    public int deleteNameWithinCircle(double x, double y, double r, SurfaceType surfaceType)\n    {\n        Circle circle = new Circle(x, y, r);\n        circle.setSurfaceType(surfaceType);\n        Query q = em.createQuery(\"Delete From Person p where p.currentLocation IN ?1\");\n        q.setParameter(1, circle);\n        return q.executeUpdate();\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/gis/Vehicle.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.gis;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\nimport com.impetus.kundera.gis.geometry.Point;\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Embeddable\n@IndexCollection(columns = { @Index(name = \"currentLocation\", type = \"GEO2D\"),\n        @Index(name = \"previousLocation\", type = \"GEO2D\") })\npublic class Vehicle\n{\n    @Column(name = \"CURRENT_VEHICLE_LOCATION\")\n    private Point currentLocation;\n\n    @Column(name = \"PREVIOUS_VEHICLE_LOCATION\")\n    private Point previousLocation;\n\n    /**\n     * @return the currentLocation\n     */\n    public Point getCurrentLocation()\n    {\n        return currentLocation;\n    }\n\n    /**\n     * @param currentLocation\n     *            the currentLocation to set\n     */\n    public void setCurrentLocation(Point currentLocation)\n    {\n        this.currentLocation = currentLocation;\n    }\n\n    /**\n     * @return the previousLocation\n     */\n    public Point getPreviousLocation()\n    {\n        return previousLocation;\n    }\n\n    /**\n     * @param previousLocation\n     *            the previousLocation to set\n     */\n    public void setPreviousLocation(Point previousLocation)\n    {\n        this.previousLocation = previousLocation;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/MongoDBAddressConfigurationValidationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2017 Impetus Infotech.\n * *\n * * Licensed under the Apache License, Version 2.0 (the \"License\");\n * * you may not use this file except in compliance with the License.\n * * You may obtain a copy of the License at\n * *\n * * http://www.apache.org/licenses/LICENSE-2.0\n * *\n * * Unless required by applicable law or agreed to in writing, software\n * * distributed under the License is distributed on an \"AS IS\" BASIS,\n * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * * See the License for the specific language governing permissions and\n * * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb;\n\nimport org.junit.Test;\n\n/**\n * Tests the MongoDB client factory configuration validation for node hostnames\n * and ports.\n */\npublic class MongoDBAddressConfigurationValidationTest\n{\n\n    /** The factory. */\n    private final MongoDBClientFactory factory = new MongoDBClientFactory();\n\n    /**\n     * Accepts single host with default port.\n     */\n    @Test\n    public void acceptsSingleHostWithDefaultPort()\n    {\n        factory.onValidation(\"localhost\", \"27017\");\n    }\n\n    /**\n     * Accepts host list with default port.\n     */\n    @Test\n    public void acceptsHostListWithDefaultPort()\n    {\n        factory.onValidation(\"node001,node002\", \"27017\");\n    }\n\n    /**\n     * Accepts host list without default port.\n     */\n    @Test\n    public void acceptsHostListWithoutDefaultPort()\n    {\n        factory.onValidation(\"node001:27001,node002:27002\", null);\n    }\n\n    /**\n     * Fails if any host is missing port without default port.\n     */\n    @Test(expected = IllegalArgumentException.class)\n    public void failsIfAnyHostIsMissingPortWithoutDefaultPort()\n    {\n        factory.onValidation(\"node001:27001,node002\", null);\n    }\n\n    /**\n     * Accepts i pv6 addresses with default port.\n     */\n    @Test\n    public void acceptsIPv6AddressesWithDefaultPort()\n    {\n        factory.onValidation(\"2001:db8:85a3::8a2e:370:7334,2001:db8::12\", \"27099\");\n    }\n\n    /**\n     * Fails with i pv6 addresses without default port.\n     */\n    @Test(expected = IllegalArgumentException.class)\n    public void failsWithIPv6AddressesWithoutDefaultPort()\n    {\n        factory.onValidation(\"2001:db8:85a3::8a2e:370:7334,2001:db8::12\", null);\n    }\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/config/MongoDBPropertyReaderTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb.config;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.StringTokenizer;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.mongodb.MongoDBConstants;\nimport com.impetus.client.mongodb.config.MongoDBPropertyReader.MongoDBSchemaMetadata;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.configure.PersistenceUnitConfiguration;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.mongodb.ReadPreference;\n\n/**\n * @author impadmin\n * \n */\npublic class MongoDBPropertyReaderTest\n{\n\n    private static Logger log = LoggerFactory.getLogger(MongoDBPropertyReaderTest.class);\n\n    private List<Connection> connections = new ArrayList<Connection>();\n\n    private String pu = \"mongoTest\";\n\n    private MongoDBSchemaMetadata dbSchemaMetadata;\n\n    private int timeOut;\n\n    private ReadPreference readPreference;\n\n    private EntityManagerFactory emf;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(pu);\n        new PersistenceUnitConfiguration(null, ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), pu)\n                .configure();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.mongodb.config.MongoDBPropertyReader#read(java.lang.String)}\n     * .\n     */\n    @Test\n    public void testRead()\n    {\n        PropertyReader reader = new MongoDBPropertyReader(null, ((EntityManagerFactoryImpl) emf)\n                .getKunderaMetadataInstance().getApplicationMetadata().getPersistenceUnitMetadata(pu));\n        reader.read(pu);\n        dbSchemaMetadata = MongoDBPropertyReader.msmd;\n\n        Properties properties = new Properties();\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(\n                ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance(), pu);\n        String propertyName = puMetadata != null ? puMetadata\n                .getProperty(PersistenceProperties.KUNDERA_CLIENT_PROPERTY) : null;\n\n        InputStream inStream = propertyName != null ? ClassLoader.getSystemResourceAsStream(propertyName) : null;\n        if (inStream != null)\n        {\n            try\n            {\n                properties.load(inStream);\n                String readPreference = properties.getProperty(MongoDBConstants.READ_PREFERENCE);\n                if (readPreference != null)\n                {\n                    if (readPreference.equalsIgnoreCase(\"primary\"))\n                    {\n                        this.readPreference = ReadPreference.primary();\n                    }\n                    else if (readPreference.equalsIgnoreCase(\"secondary\"))\n                    {\n                        this.readPreference = ReadPreference.secondary();\n                    }\n                    else\n                    {\n                        log.warn(\"Incorrect Read Preference specified. Only primary/ secondary allowed\");\n                    }\n                }\n                timeOut = Integer.parseInt(properties.getProperty(MongoDBConstants.SOCKET_TIMEOUT));\n\n                parseConnectionString(properties.getProperty(MongoDBConstants.CONNECTIONS));\n\n                // Assert.assertEquals(timeOut,\n                // dbSchemaMetadata.getSocketTimeOut());\n                // Assert.assertEquals(this.readPreference,\n                // dbSchemaMetadata.getReadPreference());\n                // Assert.assertEquals(connections.size(),\n                // dbSchemaMetadata.getConnections().size());\n            }\n            catch (NumberFormatException nfe)\n            {\n                log.info(\"time out should be numeric\");\n            }\n            catch (IOException e)\n            {\n                log.info(\"property file not found in class path\");\n            }\n        }\n    }\n\n    private void parseConnectionString(String connectionStr)\n    {\n        String[] tokens = { \"host\", \"port\" };\n        Map<String, String> hostPort = new HashMap<String, String>();\n        // parse connectionStr\n        StringTokenizer connections = new StringTokenizer(connectionStr, \",\");\n        while (connections.hasMoreTokens())\n        {\n            StringTokenizer connection = new StringTokenizer(connections.nextToken(), \":\");\n            int count = 0;\n            while (connection.hasMoreTokens())\n            {\n                hostPort.put(tokens[count++], connection.nextToken());\n            }\n            addConnection(hostPort.get(tokens[0]), hostPort.get(tokens[1]));\n        }\n    }\n\n    private void addConnection(String host, String port)\n    {\n        Connection connection = null;\n        if (host != null && port != null)\n        {\n            connection = new Connection(host, port);\n        }\n        else\n        {\n            // TODO\n            return;\n        }\n\n        if (connection != null && !connections.contains(connection))\n        {\n            connections.add(connection);\n        }\n    }\n\n    private class Connection\n    {\n        private String host;\n\n        private String port;\n\n        public Connection(String host, String port)\n        {\n            this.host = host;\n            this.port = port;\n        }\n\n        /**\n         * @return the host\n         */\n        public String getHost()\n        {\n            return host;\n        }\n\n        /**\n         * @return the port\n         */\n        public String getPort()\n        {\n            return port;\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/config/MongoDBShowQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb.config;\n\nimport static org.junit.Assert.fail;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.FileReader;\nimport java.io.PrintStream;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n/**\n * test case for checking printed queries when kundera.show.query is enabled \n * @author shaheed.hussain\n *\n */\npublic class MongoDBShowQueryTest\n{\n\n    private static final String SHOW_QUERY_ENABLED_PU = \"mongoShowQueryEnabledPU\";\n    private static final String SHOW_QUERY_DISABLED_PU = \"mongoShowQueryDisabledPU\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Map<String, String> puProperties = new HashMap<String, String>();\n\n    private Logger logger = LoggerFactory.getLogger(MongoDBShowQueryTest.class);\n\n    @Before\n    public void setUpBeforeClass() throws Exception\n    {\n      \n        \n        puProperties.put(\"kundera.keyspace\", \"showQueryKeyspace\");\n       \n    }\n\n    @After\n    public void tearDownAfterClass() throws Exception\n    {\n        puProperties = null;\n    }\n\n    /*\n     *testing show.query property when it is disabled\n     */\n    @Test\n    public void testShowQueryDisabled() \n    {\n        emf = Persistence.createEntityManagerFactory(SHOW_QUERY_DISABLED_PU, puProperties);\n        em = emf.createEntityManager();\n        try\n        {\n\n           \n            boolean isFileEmpty=false;\n            BufferedReader br = null;\n            File file = new File(\"showQuery.log\");\n            PrintStream printStream;\n            printStream = new PrintStream(new FileOutputStream(file));\n\n            System.setOut(printStream);\n\n            Query q = em.createQuery(\"Select p.personName from UserInformation p where p.personId = 2\");\n            q.getResultList();\n            System.setOut(printStream);\n\n            q = em.createQuery(\"Select p.personName from UserInformation p where p.personId < 3\");\n            q.getResultList();\n            System.setOut(printStream);\n\n            q = em.createQuery(\"Select p.personName from UserInformation p where p.personId >= 1 and p.personId < 3\");\n            q.getResultList();\n            System.setOut(printStream);\n\n            q = em.createQuery(\"Select p.personName from UserInformation p where p.personId = 1 and p.personName = vivek and p.age >=10 and p.age <= 20\");\n            q.getResultList();\n            System.setOut(printStream);\n\n            br = new BufferedReader(new FileReader(\"showQuery.log\"));\n            isFileEmpty=br.readLine() == null;\n            Assert.assertEquals(isFileEmpty, true);\n            em.close();\n            emf.close();\n\n        }\n        catch (Exception e)\n        {\n            logger.info(e.getMessage());\n        }\n      \n\n    }\n    \n    /*\n     * testing  show.query when it is enabled in persistence unit\n     */\n    @Test\n    public void testShowQuerySetInPU() \n    {\n        emf = Persistence.createEntityManagerFactory(SHOW_QUERY_ENABLED_PU, puProperties);\n        em = emf.createEntityManager();\n        try\n        {\n\n            int i = 0;\n            String expectedQuery[] = new String[4];\n            String actualQuery = null;\n            BufferedReader br = null;\n            File file = new File(\"showQuery.log\");\n            PrintStream printStream;\n            printStream = new PrintStream(new FileOutputStream(file));\n\n            System.setOut(printStream);\n\n            Query q = em.createQuery(\"Select p.personName from UserInformation p where p.personId = 2\");\n            q.getResultList();\n            expectedQuery[0] = \"Find document: { \\\"_id\\\" : \\\"2\\\"}\";\n            System.setOut(printStream);\n\n            q = em.createQuery(\"Select p.personName from UserInformation p where p.personId < 3\");\n            q.getResultList();\n            expectedQuery[1] = \"Find document: { \\\"_id\\\" : { \\\"$lt\\\" : \\\"3\\\"}}\";\n            System.setOut(printStream);\n\n            q = em.createQuery(\"Select p.personName from UserInformation p where p.personId >= 1 and p.personId < 3\");\n            q.getResultList();\n            expectedQuery[2] = \"Find document: { \\\"_id\\\" : { \\\"$gte\\\" : \\\"1\\\" , \\\"$lt\\\" : \\\"3\\\"}}\";\n            System.setOut(printStream);\n\n            q = em.createQuery(\"Select p.personName from UserInformation p where p.personId = 1 and p.personName = vivek and p.age >=10 and p.age <= 20\");\n            q.getResultList();\n            expectedQuery[3] = \"Find document: { \\\"_id\\\" : \\\"1\\\" , \\\"PERSON_NAME\\\" : \\\"vivek\\\" , \\\"AGE\\\" : { \\\"$gte\\\" : 10 , \\\"$lte\\\" : 20}}\";\n            System.setOut(printStream);\n\n            br = new BufferedReader(new FileReader(\"showQuery.log\"));\n            actualQuery = br.readLine();\n            if(actualQuery==null)\n                fail(\"failed as file is empty\");\n           \n            while (actualQuery  != null)\n            {\n                \n                Assert.assertEquals(expectedQuery[i++], actualQuery);\n                actualQuery = br.readLine();\n            }\n            em.close();\n            emf.close();\n        }\n        catch (Exception e)\n        {\n            logger.info(e.getMessage());\n        }\n\n    }\n    \n    /*\n     * testing kunera.show.query property when it is enabled at external properties level\n     */\n    @Test\n    public void testShowQuerySetInPropertyMap() \n    {\n        puProperties.put(\"kundera.show.query\",\"true\");\n        emf = Persistence.createEntityManagerFactory(SHOW_QUERY_DISABLED_PU, puProperties);\n        em = emf.createEntityManager();\n        try\n        {\n\n            int i = 0;\n            String expectedQuery[] = new String[4];\n            String actualQuery = null;\n            BufferedReader br = null;\n            File file = new File(\"showQuery.log\");\n            PrintStream printStream;\n            printStream = new PrintStream(new FileOutputStream(file));\n\n            System.setOut(printStream);\n\n            Query q = em.createQuery(\"Select p.personName from UserInformation p where p.personId = 2\");\n            q.getResultList();\n            expectedQuery[0] = \"Find document: { \\\"_id\\\" : \\\"2\\\"}\";\n            System.setOut(printStream);\n\n            q = em.createQuery(\"Select p.personName from UserInformation p where p.personId < 3\");\n            q.getResultList();\n            expectedQuery[1] = \"Find document: { \\\"_id\\\" : { \\\"$lt\\\" : \\\"3\\\"}}\";\n            System.setOut(printStream);\n\n            q = em.createQuery(\"Select p.personName from UserInformation p where p.personId >= 1 and p.personId < 3\");\n            q.getResultList();\n            expectedQuery[2] = \"Find document: { \\\"_id\\\" : { \\\"$gte\\\" : \\\"1\\\" , \\\"$lt\\\" : \\\"3\\\"}}\";\n            System.setOut(printStream);\n\n            q = em.createQuery(\"Select p.personName from UserInformation p where p.personId = 1 and p.personName = vivek and p.age >=10 and p.age <= 20\");\n            q.getResultList();\n            expectedQuery[3] = \"Find document: { \\\"_id\\\" : \\\"1\\\" , \\\"PERSON_NAME\\\" : \\\"vivek\\\" , \\\"AGE\\\" : { \\\"$gte\\\" : 10 , \\\"$lte\\\" : 20}}\";\n            System.setOut(printStream);\n\n            br = new BufferedReader(new FileReader(\"showQuery.log\"));\n            \n            actualQuery = br.readLine();\n            if(actualQuery==null)\n                fail(\"failed as file is empty\");\n           \n            while (actualQuery  != null)\n            {\n                \n                Assert.assertEquals(expectedQuery[i++], actualQuery);\n                actualQuery = br.readLine();\n            }\n            em.close();\n            emf.close();\n        }\n        catch (Exception e)\n        {\n            logger.info(e.getMessage());\n        }\n\n    }\n    \n    \n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/config/MongoUser.java",
    "content": "/**\n * \n */\npackage com.impetus.client.mongodb.config;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"MongoUser\", schema = \"KunderaExamples@mongoTest\")\npublic class MongoUser\n{\n\n    @Id\n    private String name;\n\n    @Column\n    private int age;\n\n    @Column\n    private String address;\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/config/MongoUserTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.mongodb.config;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class MongoUserTest\n{\n\n    /**\n     * \n     */\n    private static final String _PU = \"mongoTest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Map<String, String> puProperties = new HashMap<String, String>();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        puProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n        puProperties.put(\"kundera.keyspace\", \"KunderaMongoKeyspace\");\n        emf = Persistence.createEntityManagerFactory(_PU, puProperties);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        puProperties = null;\n    }\n\n    @Test\n    public void test()\n    {\n        MongoUser u = new MongoUser();\n        u.setName(\"kuldeep\");\n        u.setAge(24);\n        u.setAddress(\"gzb\");\n        em.persist(u);\n\n        em.clear();\n\n        MongoUser user = em.find(MongoUser.class, \"kuldeep\");\n        Assert.assertNotNull(user);\n        Assert.assertEquals(24, user.getAge());\n        Assert.assertEquals(\"gzb\", user.getAddress());\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/config/OperationLevelPropertiesTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.mongodb.config;\n\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.PersonMongo;\nimport com.impetus.client.mongodb.MongoDBClient;\nimport com.impetus.client.mongodb.MongoDBClientProperties;\nimport com.impetus.kundera.client.Client;\nimport com.mongodb.DBEncoder;\nimport com.mongodb.DefaultDBEncoder;\nimport com.mongodb.LazyDBEncoder;\nimport com.mongodb.WriteConcern;\n\n/**\n * Test case for properties set on operation level in MongoDBClient\n * \n * @author amresh.singh\n */\npublic class OperationLevelPropertiesTest\n{\n    String persistenceUnit = \"mongoTest\";\n\n    EntityManagerFactory emf;\n\n    EntityManager em;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        em = emf.createEntityManager();\n        \n        em.getDelegate();\n        \n    }\n\n    @Test\n    public void executeTest()\n    {\n        // Get properties from client\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        MongoDBClient client = (MongoDBClient) clients.get(persistenceUnit);\n\n        // Check default values\n        WriteConcern wc = client.getWriteConcern();\n        DBEncoder encoder = client.getEncoder();\n        Assert.assertNotNull(wc);\n        Assert.assertFalse(wc.getFsync());\n        Assert.assertEquals(1, wc.getW());\n        Assert.assertEquals(0, wc.getWtimeout());\n        Assert.assertNotNull(encoder);\n        Assert.assertTrue(encoder instanceof DefaultDBEncoder);\n        \n        // Set parameters into EM\n        // (See http://api.mongodb.org/java/2.6/com/mongodb/WriteConcern.html)\n        WriteConcern wcNew = new WriteConcern(1, 300, true);\n        DBEncoder encoderNew = new LazyDBEncoder();\n        em.setProperty(MongoDBClientProperties.WRITE_CONCERN, wcNew);\n        em.setProperty(MongoDBClientProperties.BATCH_SIZE, 5);\n       \n\n        // Check Modified values\n        WriteConcern wcModified = client.getWriteConcern();\n        DBEncoder encoderModified = client.getEncoder();\n        Assert.assertNotNull(wcModified);\n        Assert.assertTrue(wcModified.getFsync());\n        Assert.assertEquals(1, wcModified.getW());\n        Assert.assertEquals(300, wcModified.getWtimeout());\n        Assert.assertNotNull(encoderModified);\n        Assert.assertEquals(5, client.getBatchSize());\n        // Assert.assertTrue(encoderModified instanceof LazyDBEncoder);\n        em.clear();\n        \n        em.setProperty(MongoDBClientProperties.BATCH_SIZE,\"\"+ 2);\n        Assert.assertEquals(2, client.getBatchSize());\n        \n        em.clear();\n        // Write Entity to database\n        PersonMongo person = new PersonMongo();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"Amresh\");\n        person.setAge(31);\n        em.persist(person);\n        \n        PersonMongo person1 = new PersonMongo();\n        person1.setPersonId(\"2\");\n        person1.setPersonName(\"Chhavi\");\n        person1.setAge(31);\n        em.persist(person1);\n\n        // Find entity from database\n        PersonMongo p = em.find(PersonMongo.class, \"1\");\n        Assert.assertNotNull(p);\n\n        // Delete entity from database\n        em.remove(p);\n\n    }\n    \n   \n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/index/Book.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb.index;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Book.\n * \n * @author devender.yadav\n */\n@Entity\n@IndexCollection(columns = { @Index(name = \"category\", type = \"unique\") })\npublic class Book\n{\n\n    /** The id. */\n    @Id\n    private String id;\n\n    /** The title. */\n    @Column\n    private String title;\n\n    /** The category. */\n    @Column\n    private String category;\n\n    /** The num pages. */\n    @Column\n    private int numPages;\n\n    /**\n     * Instantiates a new book.\n     */\n    public Book()\n    {\n\n    }\n\n    /**\n     * Instantiates a new book.\n     * \n     * @param id\n     *            the id\n     * @param title\n     *            the title\n     * @param category\n     *            the category\n     * @param numPages\n     *            the num pages\n     */\n    public Book(String id, String title, String category, int numPages)\n    {\n        this.id = id;\n        this.title = title;\n        this.category = category;\n        this.numPages = numPages;\n    }\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the new id\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the title.\n     * \n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * Sets the title.\n     * \n     * @param title\n     *            the new title\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * Gets the category.\n     * \n     * @return the category\n     */\n    public String getCategory()\n    {\n        return category;\n    }\n\n    /**\n     * Sets the category.\n     * \n     * @param category\n     *            the new category\n     */\n    public void setCategory(String category)\n    {\n        this.category = category;\n    }\n\n    /**\n     * Gets the num pages.\n     * \n     * @return the num pages\n     */\n    public int getNumPages()\n    {\n        return numPages;\n    }\n\n    /**\n     * Sets the num pages.\n     * \n     * @param number\n     *            the new num pages\n     */\n    public void setNumPages(int number)\n    {\n        this.numPages = number;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/index/IndexTypeTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb.index;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * @author amresh.singh\n *\n */\npublic class IndexTypeTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    /**\n     * Test method for {@link com.impetus.client.mongodb.index.IndexType#findByValue(com.impetus.client.mongodb.index.IndexType)}.\n     */\n    @Test\n    public void testFindByValue()\n    {     \n        Assert.assertEquals(\"1\", IndexType.findByValue(IndexType.ASC));\n        Assert.assertEquals(\"-1\", IndexType.findByValue(IndexType.DSC));\n        Assert.assertEquals(\"2D\", IndexType.findByValue(IndexType.GEO2D));        \n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/index/UniqueIndexTest.java",
    "content": "package com.impetus.client.mongodb.index;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.utils.MongoUtils;\n\n/**\n * The Class UniqueIndexTest.\n * \n * @author devender.yadav\n */\npublic class UniqueIndexTest\n{\n\n    /** The Constant _PU. */\n    private static final String PU = \"mongo_pu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test CRUD GridFS.\n     * \n     * @throws Exception\n     *             the exceptiono\n     */\n    @Test\n    public void testInsert() throws Exception\n    {\n        Book book1 = new Book(\"1\", \"title1\", \"cat1\", 100);\n        Book book2 = new Book(\"2\", \"title2\", \"cat2\", 200);\n        Book book3 = new Book(\"3\", \"title3\", \"cat2\", 200);\n\n        try\n        {\n            em.clear();\n            em.persist(book1);\n\n            Book book = em.find(Book.class, \"1\");\n            Assert.assertNotNull(book);\n            Assert.assertEquals(\"title1\", book.getTitle());\n            Assert.assertEquals(\"cat1\", book.getCategory());\n            Assert.assertEquals(100, book.getNumPages());\n\n            em.clear();\n            em.persist(book2);\n\n            book = em.find(Book.class, \"2\");\n            Assert.assertNotNull(book);\n            Assert.assertEquals(\"title2\", book.getTitle());\n            Assert.assertEquals(\"cat2\", book.getCategory());\n            Assert.assertEquals(200, book.getNumPages());\n\n            em.clear();\n            em.persist(book3);\n            Assert.fail();\n        }\n        catch (Exception ex)\n        {\n            Book b = em.find(Book.class, \"3\");\n            Assert.assertNull(b);\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        MongoUtils.dropDatabase(emf, PU);\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/schemamanager/Location.java",
    "content": "package com.impetus.client.mongodb.schemamanager;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\nimport com.impetus.kundera.gis.geometry.Point;\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Embeddable\n@IndexCollection(columns = { @Index(name = \"currentLocation\", type = \"GEO2D\", min = -100, max = 500),\n        @Index(name = \"previousLocation\", type = \"GEO2D\", min = 100, max = 400) })\npublic class Location\n{\n    @Column(name = \"CURRENT_LOCATION\")\n    private Point currentLocation;\n\n    @Column(name = \"PREVIOUS_LOCATION\")\n    private Point previousLocation;\n\n    /**\n     * @return the currentLocation\n     */\n    public Point getCurrentLocation()\n    {\n        return currentLocation;\n    }\n\n    /**\n     * @param currentLocation\n     *            the currentLocation to set\n     */\n    public void setCurrentLocation(Point currentLocation)\n    {\n        this.currentLocation = currentLocation;\n    }\n\n    /**\n     * @return the previousLocation\n     */\n    public Point getPreviousLocation()\n    {\n        return previousLocation;\n    }\n\n    /**\n     * @param previousLocation\n     *            the previousLocation to set\n     */\n    public void setPreviousLocation(Point previousLocation)\n    {\n        this.previousLocation = previousLocation;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/schemamanager/MongoDBEmbeddedEntity.java",
    "content": "package com.impetus.client.mongodb.schemamanager;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"MongoDBEmbeddedEntity\", schema = \"KunderaMongoSchemaGeneration@mongoSchemaGenerationTest\")\n@IndexCollection(columns = { @Index(name = \"personName\", type = \"ASC\"),\n        @Index(name = \"age\", type = \"DSC\", min = 100, max = 500),\n        @Index(name = \"currentLocation\", type = \"GEO2D\", min = -100, max = 500) })\npublic class MongoDBEmbeddedEntity\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Embedded\n    private Location location;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    public Location getLocation()\n    {\n        return location;\n    }\n\n    public void setLocation(Location location)\n    {\n        this.location = location;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/schemamanager/MongoDBEntitySimple.java",
    "content": "/**\n * \n */\npackage com.impetus.client.mongodb.schemamanager;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.gis.geometry.Point;\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"MongoDBEntitySimple\", schema = \"KunderaMongoSchemaGeneration@mongoSchemaGenerationTest\")\n@IndexCollection(columns = { @Index(name = \"personName\", type = \"ASC\"),\n        @Index(name = \"age\", type = \"DSC\", min = 100, max = 500),\n        @Index(name = \"currentLocation\", type = \"GEO2D\", min = -100, max = 500) })\npublic class MongoDBEntitySimple\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"CURRENT_LOCATION\")\n    private Point currentLocation;\n\n    @Column(name = \"PREVIOUS_LOCATION\")\n    private Point previousLocation;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the currentLocation\n     */\n    public Point getCurrentLocation()\n    {\n        return currentLocation;\n    }\n\n    /**\n     * @param currentLocation\n     *            the currentLocation to set\n     */\n    public void setCurrentLocation(Point currentLocation)\n    {\n        this.currentLocation = currentLocation;\n    }\n\n    /**\n     * @return the previousLocation\n     */\n    public Point getPreviousLocation()\n    {\n        return previousLocation;\n    }\n\n    /**\n     * @param previousLocation\n     *            the previousLocation to set\n     */\n    public void setPreviousLocation(Point previousLocation)\n    {\n        this.previousLocation = previousLocation;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/schemamanager/MongoDBSchemaManagerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb.schemamanager;\n\nimport java.lang.reflect.Field;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.mongodb.MongoDBClient;\nimport com.impetus.client.mongodb.MongoDBClientFactory;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientResolver;\nimport com.mongodb.BasicDBObject;\nimport com.mongodb.DB;\nimport com.mongodb.DBCollection;\nimport com.mongodb.DBObject;\nimport com.mongodb.ReadPreference;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class MongoDBSchemaManagerTest\n{\n    private DB db;\n\n    private String persistenceUnit = \"mongoSchemaGenerationTest\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        truncateMongo();\n    }\n\n    @Test\n    public void testValidate()\n    {\n\n        try\n        {\n            Map props = new HashMap();\n            props.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"validate\");\n            emf = Persistence.createEntityManagerFactory(persistenceUnit, props);\n            Assert.fail(\"Schema generation exception should have been thrown since schema doesn't exist\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertNotNull(e);\n        }\n    }\n\n    @Test\n    public void testUpdate()\n    {\n\n        Map props = new HashMap();\n        props.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"update\");\n\n        emf = Persistence.createEntityManagerFactory(persistenceUnit, props);\n        em = emf.createEntityManager();\n\n        getDB();\n\n        DBCollection collection = db.getCollection(\"MongoDBEntitySimple\");\n        Assert.assertEquals(ReadPreference.primary(), collection.getReadPreference());\n        Assert.assertNotNull(collection.getIndexInfo());\n        Assert.assertEquals(4, collection.getIndexInfo().size());\n        int count = 0;\n        for (DBObject dbObject : collection.getIndexInfo())\n        {\n\n            if (dbObject.get(\"name\").equals(\"_id_\"))\n            {\n                Assert.assertTrue(dbObject.get(\"key\").equals(new BasicDBObject(\"_id\", 1)));\n                count++;\n            }\n            else if (dbObject.get(\"name\").equals(\"PERSON_NAME_1\"))\n            {\n                Assert.assertEquals(new Double(Integer.MIN_VALUE), dbObject.get(\"min\"));\n                Assert.assertEquals(new Double(Integer.MAX_VALUE), dbObject.get(\"max\"));\n                Assert.assertTrue(dbObject.get(\"key\").equals(new BasicDBObject(\"PERSON_NAME\", 1)));\n                count++;\n            }\n            else if (dbObject.get(\"name\").equals(\"AGE_-1\"))\n            {\n                Assert.assertEquals(new Double(100.0), dbObject.get(\"min\"));\n                Assert.assertEquals(new Double(500.0), dbObject.get(\"max\"));\n                Assert.assertTrue(dbObject.get(\"key\").equals(new BasicDBObject(\"AGE\", -1)));\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(new Double(-100), dbObject.get(\"min\"));\n                Assert.assertEquals(new Double(500), dbObject.get(\"max\"));\n                Assert.assertTrue(dbObject.get(\"key\").equals(new BasicDBObject(\"CURRENT_LOCATION\", \"2d\")));\n                count++;\n            }\n        }\n        Assert.assertEquals(4, count);\n\n        collection = db.getCollection(\"GFS_BOOK.files\");\n        Assert.assertEquals(ReadPreference.primary(), collection.getReadPreference());\n        Assert.assertNotNull(collection.getIndexInfo());\n\n        collection = db.getCollection(\"GFS_BOOK.chunks\");\n        Assert.assertEquals(ReadPreference.primary(), collection.getReadPreference());\n        Assert.assertNotNull(collection.getIndexInfo());\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.mongodb.schemamanager.MongoDBSchemaManager#create(java.util.List)}\n     * .\n     */\n    @Test\n    public void testCreate()\n    {\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        em = emf.createEntityManager();\n        getDB();\n\n        DBCollection collection = db.getCollection(\"MongoDBEntitySimple\");\n        Assert.assertEquals(ReadPreference.primary(), collection.getReadPreference());\n        Assert.assertNotNull(collection.getIndexInfo());\n        Assert.assertEquals(4, collection.getIndexInfo().size());\n        int count = 0;\n        for (DBObject dbObject : collection.getIndexInfo())\n        {\n\n            if (dbObject.get(\"name\").equals(\"_id_\"))\n            {\n                Assert.assertTrue(dbObject.get(\"key\").equals(new BasicDBObject(\"_id\", 1)));\n                count++;\n            }\n            else if (dbObject.get(\"name\").equals(\"PERSON_NAME_1\"))\n            {\n                Assert.assertEquals(new Double(Integer.MIN_VALUE), dbObject.get(\"min\"));\n                Assert.assertEquals(new Double(Integer.MAX_VALUE), dbObject.get(\"max\"));\n                Assert.assertTrue(dbObject.get(\"key\").equals(new BasicDBObject(\"PERSON_NAME\", 1)));\n                count++;\n            }\n            else if (dbObject.get(\"name\").equals(\"AGE_-1\"))\n            {\n                Assert.assertEquals(new Double(100), dbObject.get(\"min\"));\n                Assert.assertEquals(new Double(500), dbObject.get(\"max\"));\n                Assert.assertTrue(dbObject.get(\"key\").equals(new BasicDBObject(\"AGE\", -1)));\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(new Double(-100), dbObject.get(\"min\"));\n                Assert.assertEquals(new Double(500), dbObject.get(\"max\"));\n                Assert.assertTrue(dbObject.get(\"key\").equals(new BasicDBObject(\"CURRENT_LOCATION\", \"2d\")));\n                count++;\n            }\n        }\n        Assert.assertEquals(4, count);\n\n        collection = db.getCollection(\"GFS_BOOK.files\");\n        Assert.assertEquals(ReadPreference.primary(), collection.getReadPreference());\n        Assert.assertNotNull(collection.getIndexInfo());\n\n        collection = db.getCollection(\"GFS_BOOK.chunks\");\n        Assert.assertEquals(ReadPreference.primary(), collection.getReadPreference());\n        Assert.assertNotNull(collection.getIndexInfo());\n    }\n\n    @Test\n    public void testCreateIndexesOnEmbedded()\n    {\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        em = emf.createEntityManager();\n        getDB();\n\n        DBCollection collection = db.getCollection(\"MongoDBEmbeddedEntity\");\n        Assert.assertEquals(ReadPreference.primary(), collection.getReadPreference());\n        Assert.assertNotNull(collection.getIndexInfo());\n        Assert.assertEquals(5, collection.getIndexInfo().size());\n        int count = 0;\n        for (DBObject dbObject : collection.getIndexInfo())\n        {\n\n            if (dbObject.get(\"name\").equals(\"_id_\"))\n            {\n                Assert.assertTrue(dbObject.get(\"key\").equals(new BasicDBObject(\"_id\", 1)));\n                count++;\n            }\n            else if (dbObject.get(\"name\").equals(\"PERSON_NAME_1\"))\n            {\n                Assert.assertEquals(new Double(Integer.MIN_VALUE), dbObject.get(\"min\"));\n                Assert.assertEquals(new Double(Integer.MAX_VALUE), dbObject.get(\"max\"));\n                Assert.assertTrue(dbObject.get(\"key\").equals(new BasicDBObject(\"PERSON_NAME\", 1)));\n                count++;\n            }\n            else if (dbObject.get(\"name\").equals(\"AGE_-1\"))\n            {\n                Assert.assertEquals(new Double(100), dbObject.get(\"min\"));\n                Assert.assertEquals(new Double(500), dbObject.get(\"max\"));\n                Assert.assertTrue(dbObject.get(\"key\").equals(new BasicDBObject(\"AGE\", -1)));\n                count++;\n            }\n            else if (dbObject.get(\"name\").equals(\"location.CURRENT_LOCATION_2d\"))\n            {\n                Assert.assertEquals(new Double(-100), dbObject.get(\"min\"));\n                Assert.assertEquals(new Double(500), dbObject.get(\"max\"));\n                Assert.assertTrue(dbObject.get(\"key\").equals(new BasicDBObject(\"location.CURRENT_LOCATION\", \"2d\")));\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(new Double(100), dbObject.get(\"min\"));\n                Assert.assertEquals(new Double(400), dbObject.get(\"max\"));\n                Assert.assertTrue(dbObject.get(\"key\").equals(new BasicDBObject(\"location.PREVIOUS_LOCATION\", \"2d\")));\n                count++;\n            }\n        }\n        Assert.assertEquals(5, count);\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.mongodb.schemamanager.MongoDBSchemaManager#dropSchema()}\n     * .\n     */\n    @Test\n    public void testDropSchema()\n    {\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n        em = emf.createEntityManager();\n        getDB();\n\n        MongoDBClientFactory clientFactory = (MongoDBClientFactory) ClientResolver.getClientFactory(persistenceUnit);\n        clientFactory.getSchemaManager(null).dropSchema();\n        DBCollection collection = db.getCollection(\"MongoDBEntitySimple\");\n        Assert.assertTrue(collection.getIndexInfo().isEmpty());\n        Assert.assertEquals(0, collection.getCount());\n        collection = db.getCollection(\"GFS_BOOK.files\");\n        Assert.assertTrue(collection.getIndexInfo().isEmpty());\n        Assert.assertEquals(0, collection.getCount());\n        collection = db.getCollection(\"GFS_BOOK.chunks\");\n        Assert.assertTrue(collection.getIndexInfo().isEmpty());\n        Assert.assertEquals(0, collection.getCount());\n    }\n\n    /**\n     * \n     */\n    private void truncateMongo()\n    {\n\n        if (db != null)\n        {\n            db.dropDatabase();\n        }\n    }\n\n    /**\n     * \n     */\n    private void getDB()\n    {\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        MongoDBClient client = (MongoDBClient) clients.get(persistenceUnit);\n        if (client != null)\n        {\n            try\n            {\n                Field mongodb = client.getClass().getDeclaredField(\"mongoDb\");\n                if (!mongodb.isAccessible())\n                {\n                    mongodb.setAccessible(true);\n                }\n                db = (DB) mongodb.get(client);\n            }\n\n            catch (SecurityException e)\n            {\n                Assert.fail(e.getMessage());\n            }\n            catch (NoSuchFieldException e)\n            {\n                Assert.fail(e.getMessage());\n            }\n            catch (IllegalArgumentException e)\n            {\n                Assert.fail(e.getMessage());\n            }\n            catch (IllegalAccessException e)\n            {\n                Assert.fail(e.getMessage());\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/schemamanager/MongoGFSBookEntity.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.mongodb.schemamanager;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Lob;\nimport javax.persistence.Table;\n\n/**\n * The Class MongoGFSBookEntity.\n * \n * @author Devender Yadav\n */\n@Entity\n@Table(name = \"GFS_BOOK\", schema = \"KunderaMongoSchemaGeneration@mongoSchemaGenerationTest\")\npublic class MongoGFSBookEntity\n{\n\n    /** The id. */\n    @Id\n    private String id;\n\n    /** The title. */\n    @Column\n    private String title;\n\n    /** The pdf file. */\n    @Lob\n    private byte[] pdfFile;\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the new id\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the title.\n     * \n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * Sets the title.\n     * \n     * @param title\n     *            the new title\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * Gets the pdf file.\n     * \n     * @return the pdf file\n     */\n    public byte[] getPdfFile()\n    {\n        return pdfFile;\n    }\n\n    /**\n     * Sets the pdf file.\n     * \n     * @param pdfFile\n     *            the new pdf file\n     */\n    public void setPdfFile(byte[] pdfFile)\n    {\n        this.pdfFile = pdfFile;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/validator/BookEntity.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.mongodb.validator;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Devender Yadav\n * \n */\n@Entity\n@Table(name = \"BOOK_ENTITY\", schema = \"KunderaExamples@mongoTest\")\npublic class BookEntity\n{\n\n    @Id\n    @Column(name = \"ID\")\n    private int bookId;\n\n    @Column(name = \"TITLE\")\n    private String title;\n\n    @Column(name = \"AUTHOR\")\n    private String author;\n\n    @Column(name = \"PAGES\")\n    private int pages;\n\n    protected BookEntity()\n    {\n    }\n\n    public int getBookId()\n    {\n        return bookId;\n    }\n\n    public void setBookId(int bookId)\n    {\n        this.bookId = bookId;\n    }\n\n    public String getTitle()\n    {\n        return title;\n    }\n\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    public int getPages()\n    {\n        return pages;\n    }\n\n    public void setPages(int pages)\n    {\n        this.pages = pages;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/mongodb/validator/ConstructorValidationTest.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.mongodb.validator;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\n/**\n * @author Devender Yadav\n * \n */\npublic class ConstructorValidationTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    @Test\n    public void validConstructorTest() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"mongoTest\");\n        em = emf.createEntityManager();\n        BookEntity book = new BookEntity();\n        book.setBookId(1);\n        book.setTitle(\"The Complete Reference\");\n        book.setAuthor(\"Herbert Schildt\");\n        book.setPages(500);\n\n        em.persist(book);\n\n        em.clear();\n\n        BookEntity book1 = em.find(BookEntity.class, 1);\n\n        Assert.assertNotNull(book1);\n        Assert.assertEquals(1, book1.getBookId());\n        Assert.assertEquals(\"The Complete Reference\", book1.getTitle());\n        Assert.assertEquals(\"Herbert Schildt\", book1.getAuthor());\n        Assert.assertEquals(500, book1.getPages());\n\n        em.remove(book1);\n\n        BookEntity book2 = em.find(BookEntity.class, 1);\n        Assert.assertNull(book2);\n\n        em.close();\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/twitter/TwingoTest.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter;\r\n\r\nimport org.databene.contiperf.PerfTest;\r\nimport org.databene.contiperf.junit.ContiPerfRule;\r\nimport org.databene.contiperf.report.CSVSummaryReportModule;\r\nimport org.databene.contiperf.report.HtmlReportModule;\r\nimport org.databene.contiperf.report.ReportModule;\r\nimport org.junit.Rule;\r\nimport org.junit.Test;\r\n\r\nimport com.impetus.client.twitter.dao.Twitter;\r\n\r\n/**\r\n * Test case for MongoDB.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class TwingoTest extends TwitterTestBaseMongo\r\n{\r\n\r\n    /** The user id1. */\r\n    String userId1;\r\n\r\n    /** The user id2. */\r\n    String userId2;\r\n\r\n    /** The twitter. */\r\n    Twitter twitter;\r\n\r\n    @Rule\r\n    public ContiPerfRule i = new ContiPerfRule(new ReportModule[] { new CSVSummaryReportModule(),\r\n            new HtmlReportModule() });\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see junit.framework.TestCase#setUp()\r\n     */\r\n    @Override\r\n    protected void setUp() throws Exception\r\n    {\r\n        setUpInternal(\"mongoTest\");\r\n    }\r\n\r\n    /**\r\n     * Test on execute.\r\n     */\r\n\r\n    @Test\r\n    @PerfTest(invocations = 10)\r\n    public void testOnExecute()\r\n    {\r\n        executeTestSuite();\r\n    }\r\n\r\n    @Override\r\n    protected void tearDown() throws Exception\r\n    {\r\n        tearDownInternal();\r\n    }\r\n\r\n    @Override\r\n    void createSchema()\r\n    {\r\n        // No need to create schema, it will be created automatically\r\n    }\r\n\r\n    @Override\r\n    void startServer()\r\n    {\r\n        // Currently no embedded server\r\n    }\r\n\r\n    @Override\r\n    void stopServer()\r\n    {\r\n        // Currently no embedded server\r\n    }\r\n\r\n    @Override\r\n    void deleteSchema()\r\n    {\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/twitter/TwitterTestBaseMongo.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter;\r\n\r\nimport java.util.List;\r\n\r\nimport junit.framework.TestCase;\r\n\r\nimport org.junit.Assert;\r\n\r\nimport com.impetus.client.twitter.dao.Twitter;\r\nimport com.impetus.client.twitter.dao.TwitterService;\r\nimport com.impetus.client.twitter.entities.ExternalLinkMongo;\r\nimport com.impetus.client.twitter.entities.PersonalDetailMongo;\r\nimport com.impetus.client.twitter.entities.PreferenceMongo;\r\nimport com.impetus.client.twitter.entities.TweetMongo;\r\nimport com.impetus.client.twitter.entities.UserMongo;\r\n\r\n/**\r\n * Test case for MongoDB.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic abstract class TwitterTestBaseMongo extends TestCase\r\n{\r\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\r\n\r\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\r\n\r\n    /** The user id1. */\r\n    String userId1;\r\n\r\n    /** The user id2. */\r\n    String userId2;\r\n\r\n    /** The twitter. */\r\n    protected Twitter twitter;\r\n\r\n    /**\r\n     * Sets the up internal.\r\n     * \r\n     * @param persistenceUnitName\r\n     *            the new up internal\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    protected void setUpInternal(String persistenceUnitName) throws Exception\r\n    {\r\n        userId1 = \"0001\";\r\n        userId2 = \"0002\";\r\n\r\n        // Start Cassandra Server\r\n        if (RUN_IN_EMBEDDED_MODE)\r\n        {\r\n            startServer();\r\n        }\r\n\r\n        twitter = new TwitterService(persistenceUnitName);\r\n\r\n        // Create Schema\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            createSchema();\r\n        }\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see junit.framework.TestCase#tearDown()\r\n     */\r\n    /**\r\n     * Tear down internal.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    protected void tearDownInternal() throws Exception\r\n    {\r\n        if (twitter != null)\r\n        {\r\n            twitter.close();\r\n        }\r\n\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            deleteSchema();\r\n        }\r\n\r\n        // Stop Server\r\n        if (RUN_IN_EMBEDDED_MODE)\r\n        {\r\n            stopServer();\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Execute suite.\r\n     */\r\n    protected void executeTestSuite()\r\n    {\r\n        // Insert, Find and Update\r\n        addAllUserInfo();\r\n        getUserById();\r\n        updateUser();\r\n\r\n        // Queries\r\n        getAllUsers();\r\n        getAllTweets();\r\n\r\n        // Remove Users\r\n        removeUser();\r\n\r\n    }\r\n\r\n    protected void addAllUserInfo()\r\n    {\r\n        UserMongo user1 = buildUser1();\r\n        UserMongo user2 = buildUser2();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addUser(user1);\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addUser(user2);\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    protected void getUserById()\r\n    {\r\n        twitter.createEntityManager();\r\n        UserMongo user1 = twitter.findUserById(userId1);\r\n        assertUser1(user1);\r\n\r\n        UserMongo user2 = twitter.findUserById(userId2);\r\n        assertUser2(user2);\r\n\r\n    }\r\n\r\n    protected void updateUser()\r\n    {\r\n        twitter.createEntityManager();\r\n        UserMongo user1 = twitter.findUserById(userId1);\r\n        assertUser1(user1);\r\n\r\n        user1.setPersonalDetail(new PersonalDetailMongo(\"Vivek\", \"unknown\", \"Married\"));\r\n        user1.addTweet(new TweetMongo(\"My Third Tweet\", \"iPhone\"));\r\n        twitter.mergeUser(user1);\r\n\r\n        UserMongo user1AfterMerge = twitter.findUserById(userId1);\r\n\r\n        assertUpdatedUser1(user1AfterMerge);\r\n\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    protected void removeUser()\r\n    {\r\n        twitter.createEntityManager();\r\n        UserMongo user1 = twitter.findUserById(userId1);\r\n        // TODO: this needs to uncomment only after fixing update issue on\r\n        // associations\r\n        // assertUpdatedUser1(user1);\r\n\r\n        twitter.removeUser(user1);\r\n\r\n        UserMongo user1AfterRemoval = twitter.findUserById(userId1);\r\n        Assert.assertNull(user1AfterRemoval);\r\n\r\n        UserMongo user2 = twitter.findUserById(userId2);\r\n        // TODO: this needs to uncomment only after fixing update issue on\r\n        // associations\r\n        // assertUpdatedUser1(user1);\r\n\r\n        twitter.removeUser(user2);\r\n\r\n        UserMongo user2AfterRemoval = twitter.findUserById(userId2);\r\n        Assert.assertNull(user2AfterRemoval);\r\n\r\n        twitter.closeEntityManager();\r\n\r\n    }\r\n\r\n    protected void getAllUsers()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<UserMongo> users = twitter.getAllUsers();\r\n        Assert.assertNotNull(users);\r\n        Assert.assertFalse(users.isEmpty());\r\n        Assert.assertEquals(2, users.size());\r\n\r\n        for (UserMongo u : users)\r\n        {\r\n            Assert.assertNotNull(u);\r\n            if (u.getUserId().equals(userId1))\r\n            {\r\n                // TODO: this needs to uncomment only after fixing update issue\r\n                // on associations\r\n                // assertUpdatedUser1(u);\r\n            }\r\n            else if (u.getUserId().equals(userId2))\r\n            {\r\n                // assertUser2(u);\r\n            }\r\n        }\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Adds the users.\r\n     */\r\n    protected void addUsers()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addUser(userId1, \"Amresh\", \"password1\", \"married\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addUser(userId2, \"Saurabh\", \"password2\", \"single\");\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Save preference.\r\n     */\r\n    protected void savePreference()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.savePreference(userId1, new PreferenceMongo(\"P1\", \"Motif\", \"2\"));\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.savePreference(userId2, new PreferenceMongo(\"P2\", \"High Contrast\", \"3\"));\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Adds the external links.\r\n     */\r\n    protected void addExternalLinks()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId1, \"L1\", \"Facebook\", \"http://facebook.com/coolnerd\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId1, \"L2\", \"LinkedIn\", \"http://linkedin.com/in/devilmate\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId2, \"L3\", \"GooglePlus\", \"http://plus.google.com/inviteme\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId2, \"L4\", \"Yahoo\", \"http://yahoo.com/profiles/itsmeamry\");\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Adds the tweets.\r\n     */\r\n    protected void addTweets()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId1, \"Here is my first tweet\", \"Web\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId1, \"Second Tweet from me\", \"Mobile\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId2, \"Saurabh tweets for the first time\", \"Phone\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId2, \"Another tweet from Saurabh\", \"text\");\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * User1 follows user2.\r\n     */\r\n    protected void user1FollowsUser2()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.startFollowing(userId1, userId2);\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * User1 adds user2 as follower.\r\n     */\r\n    protected void user1AddsUser2AsFollower()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addFollower(userId1, userId2);\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Gets the all tweets.\r\n     * \r\n     * @return the all tweets\r\n     */\r\n    protected void getAllTweets()\r\n    {\r\n        twitter.createEntityManager();\r\n\r\n        List<TweetMongo> tweetsUser1 = twitter.getAllTweets(userId1);\r\n        List<TweetMongo> tweetsUser2 = twitter.getAllTweets(userId2);\r\n\r\n        twitter.closeEntityManager();\r\n\r\n        assertNotNull(tweetsUser1);\r\n        assertNotNull(tweetsUser2);\r\n\r\n        assertFalse(tweetsUser1.isEmpty());\r\n        assertFalse(tweetsUser2.isEmpty());\r\n\r\n        // TODO : uncomment\r\n        assertEquals(3, tweetsUser1.size());\r\n        // assertEquals(2, tweetsUser1.size());\r\n        assertEquals(2, tweetsUser2.size());\r\n    }\r\n\r\n    /**\r\n     * Gets the tweets by body.\r\n     * \r\n     * @return the tweets by body\r\n     */\r\n    public void getTweetsByBody()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<TweetMongo> user1Tweet = twitter.findTweetByBody(\"Here\");\r\n        List<TweetMongo> user2Tweet = twitter.findTweetByBody(\"Saurabh\");\r\n\r\n        twitter.closeEntityManager();\r\n\r\n        assertNotNull(user1Tweet);\r\n        assertNotNull(user2Tweet);\r\n        assertEquals(1, user1Tweet.size());\r\n        assertEquals(1, user2Tweet.size());\r\n    }\r\n\r\n    /**\r\n     * Gets the tweet by device.\r\n     * \r\n     * @return the tweet by device\r\n     */\r\n    public void getTweetsByDevice()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<TweetMongo> webTweets = twitter.findTweetByDevice(\"Web\");\r\n        List<TweetMongo> mobileTweets = twitter.findTweetByDevice(\"Mobile\");\r\n\r\n        twitter.closeEntityManager();\r\n\r\n        assertNotNull(webTweets);\r\n        assertNotNull(mobileTweets);\r\n        assertEquals(1, webTweets.size());\r\n        assertEquals(1, mobileTweets.size());\r\n\r\n    }\r\n\r\n    /**\r\n     * Gets the all followers.\r\n     * \r\n     * @return the all followers\r\n     */\r\n    protected void getAllFollowers()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<UserMongo> follower1 = twitter.getFollowers(userId1);\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        List<UserMongo> follower2 = twitter.getFollowers(userId2);\r\n        twitter.closeEntityManager();\r\n\r\n        assertNull(follower1);\r\n        assertNotNull(follower2);\r\n    }\r\n\r\n    /**\r\n     * @return\r\n     */\r\n    private UserMongo buildUser1()\r\n    {\r\n        UserMongo user1 = new UserMongo(userId1, \"Amresh\", \"password1\", \"married\");\r\n\r\n        user1.setPreference(new PreferenceMongo(\"P1\", \"Motif\", \"2\"));\r\n\r\n        user1.addExternalLink(new ExternalLinkMongo(\"L1\", \"Facebook\", \"http://facebook.com/coolnerd\"));\r\n        user1.addExternalLink(new ExternalLinkMongo(\"L2\", \"LinkedIn\", \"http://linkedin.com/in/devilmate\"));\r\n\r\n        user1.addTweet(new TweetMongo(\"Here is my first tweet\", \"Web\"));\r\n        user1.addTweet(new TweetMongo(\"Second Tweet from me\", \"Mobile\"));\r\n        return user1;\r\n    }\r\n\r\n    /**\r\n     * @return\r\n     */\r\n    private UserMongo buildUser2()\r\n    {\r\n        UserMongo user2 = new UserMongo(userId2, \"Saurabh\", \"password2\", \"single\");\r\n\r\n        user2.setPreference(new PreferenceMongo(\"P2\", \"High Contrast\", \"3\"));\r\n\r\n        user2.addExternalLink(new ExternalLinkMongo(\"L3\", \"GooglePlus\", \"http://plus.google.com/inviteme\"));\r\n        user2.addExternalLink(new ExternalLinkMongo(\"L4\", \"Yahoo\", \"http://yahoo.com/profiles/itsmeamry\"));\r\n\r\n        user2.addTweet(new TweetMongo(\"Saurabh tweets for the first time\", \"Phone\"));\r\n        user2.addTweet(new TweetMongo(\"Another tweet from Saurabh\", \"text\"));\r\n        return user2;\r\n    }\r\n\r\n    private void assertUser1(UserMongo user1)\r\n    {\r\n        Assert.assertNotNull(user1);\r\n        Assert.assertEquals(userId1, user1.getUserId());\r\n        Assert.assertNotNull(user1.getPersonalDetail());\r\n        Assert.assertEquals(\"Amresh\", user1.getPersonalDetail().getName());\r\n        Assert.assertNotNull(user1.getPreference());\r\n        Assert.assertEquals(\"2\", user1.getPreference().getPrivacyLevel());\r\n        Assert.assertNotNull(user1.getTweets());\r\n        Assert.assertFalse(user1.getTweets().isEmpty());\r\n        Assert.assertEquals(2, user1.getTweets().size());\r\n        Assert.assertNotNull(user1.getExternalLinks());\r\n        Assert.assertFalse(user1.getExternalLinks().isEmpty());\r\n        Assert.assertEquals(2, user1.getExternalLinks().size());\r\n    }\r\n\r\n    private void assertUser2(UserMongo user2)\r\n    {\r\n        Assert.assertNotNull(user2);\r\n        Assert.assertEquals(userId2, user2.getUserId());\r\n        Assert.assertNotNull(user2.getPersonalDetail());\r\n        Assert.assertEquals(\"Saurabh\", user2.getPersonalDetail().getName());\r\n        Assert.assertNotNull(user2.getPreference());\r\n        Assert.assertEquals(\"3\", user2.getPreference().getPrivacyLevel());\r\n        Assert.assertNotNull(user2.getTweets());\r\n        Assert.assertFalse(user2.getTweets().isEmpty());\r\n        Assert.assertEquals(2, user2.getTweets().size());\r\n        Assert.assertNotNull(user2.getExternalLinks());\r\n        Assert.assertFalse(user2.getExternalLinks().isEmpty());\r\n        Assert.assertEquals(2, user2.getExternalLinks().size());\r\n    }\r\n\r\n    private void assertUpdatedUser1(UserMongo user1)\r\n    {\r\n        Assert.assertNotNull(user1);\r\n        Assert.assertEquals(userId1, user1.getUserId());\r\n        Assert.assertNotNull(user1.getPersonalDetail());\r\n        Assert.assertEquals(\"Vivek\", user1.getPersonalDetail().getName());\r\n        Assert.assertEquals(\"unknown\", user1.getPersonalDetail().getPassword());\r\n        Assert.assertNotNull(user1.getPreference());\r\n        Assert.assertEquals(\"2\", user1.getPreference().getPrivacyLevel());\r\n        Assert.assertNotNull(user1.getTweets());\r\n        Assert.assertFalse(user1.getTweets().isEmpty());\r\n        Assert.assertEquals(3, user1.getTweets().size());\r\n        Assert.assertNotNull(user1.getExternalLinks());\r\n        Assert.assertFalse(user1.getExternalLinks().isEmpty());\r\n        Assert.assertEquals(2, user1.getExternalLinks().size());\r\n    }\r\n\r\n    abstract void startServer();\r\n\r\n    abstract void stopServer();\r\n\r\n    abstract void deleteSchema();\r\n\r\n    abstract void createSchema();\r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/twitter/dao/SuperDao.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.dao;\r\n\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Persistence;\r\n\r\n/**\r\n * The Class SuperDao.\r\n * \r\n * @author impetus\r\n */\r\npublic class SuperDao\r\n{\r\n\r\n    /**\r\n     * Inits the.\r\n     * \r\n     * @param persistenceUnitName\r\n     *            the persistence unit name\r\n     * @return the entity manager\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    protected EntityManagerFactory createEntityManagerFactory(String persistenceUnitName)\r\n    {\r\n        return Persistence.createEntityManagerFactory(persistenceUnitName);\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/twitter/dao/Twitter.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.dao;\r\n\r\nimport java.util.List;\r\n\r\nimport com.impetus.client.twitter.entities.PreferenceMongo;\r\nimport com.impetus.client.twitter.entities.TweetMongo;\r\nimport com.impetus.client.twitter.entities.UserMongo;\r\n\r\n/**\r\n * Single window application for Twitter application. Contains methods for\r\n * performing CRUD operations on users and their tweets.\r\n */\r\npublic interface Twitter\r\n{\r\n\r\n    void addUser(UserMongo user);\r\n\r\n    /**\r\n     * Registers a new user with Twitter application\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param name\r\n     *            the name\r\n     * @param password\r\n     *            the password\r\n     * @param relationshipStatus\r\n     *            the relationship status\r\n     */\r\n    void addUser(String userId, String name, String password, String relationshipStatus);\r\n\r\n    /**\r\n     * Save preference for a given user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param preference\r\n     *            the preference\r\n     */\r\n    void savePreference(String userId, PreferenceMongo preference);\r\n\r\n    /**\r\n     * Adds an external link for the given user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param linkType\r\n     *            the link type\r\n     * @param linkAddress\r\n     *            the link address\r\n     */\r\n    void addExternalLink(String userId, String linkId, String linkType, String linkAddress);\r\n\r\n    /**\r\n     * Adds a new tweet for a user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param tweetBody\r\n     *            the tweet body\r\n     * @param device\r\n     *            the device\r\n     */\r\n    void addTweet(String userId, String tweetBody, String device);\r\n\r\n    /**\r\n     * Makes User whose row key is <code>userId</code> follow a user whose row\r\n     * key is <code>friendUserId</code>\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param friendUserId\r\n     *            the friend user id\r\n     */\r\n    void startFollowing(String userId, String friendUserId);\r\n\r\n    /**\r\n     * Adds the follower whose row key is <code>followerUserId</code> to User\r\n     * whose row key is <code>userId</code>\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param followerUserId\r\n     *            the follower user id\r\n     */\r\n    void addFollower(String userId, String followerUserId);\r\n\r\n    UserMongo findUserById(String userId);\r\n\r\n    void removeUser(UserMongo user);\r\n\r\n    void mergeUser(UserMongo user);\r\n\r\n    /**\r\n     * Retrieves all tweets for a given user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @return the all tweets\r\n     */\r\n    List<UserMongo> getAllUsers();\r\n\r\n    List<TweetMongo> getAllTweets(String userId);\r\n\r\n    /**\r\n     * Returns a list of followers for a given user.\r\n     * \r\n     * @param userId\r\n     *            user id\r\n     * @return list of all followers.\r\n     */\r\n    List<UserMongo> getFollowers(String userId);\r\n\r\n    /**\r\n     * Find tweet by tweet body.\r\n     * \r\n     * @param tweetBody\r\n     *            the tweet body\r\n     * @return the list\r\n     */\r\n    List<TweetMongo> findTweetByBody(String tweetBody);\r\n\r\n    /**\r\n     * Find tweet by device.\r\n     * \r\n     * @param deviceName\r\n     *            the device name\r\n     * @return the list\r\n     */\r\n    List<TweetMongo> findTweetByDevice(String deviceName);\r\n\r\n    /**\r\n     * Close.\r\n     */\r\n    void close();\r\n\r\n    void createEntityManager();\r\n\r\n    void closeEntityManager();\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/twitter/dao/TwitterService.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.dao;\r\n\r\nimport java.util.List;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Query;\r\n\r\nimport com.impetus.client.twitter.entities.ExternalLinkMongo;\r\nimport com.impetus.client.twitter.entities.PreferenceMongo;\r\nimport com.impetus.client.twitter.entities.TweetMongo;\r\nimport com.impetus.client.twitter.entities.UserMongo;\r\nimport com.impetus.client.utils.MongoUtils;\r\n\r\n/**\r\n * Data access object class for implementation of twitter.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class TwitterService extends SuperDao implements Twitter\r\n{\r\n    private EntityManager em;\r\n\r\n    private EntityManagerFactory emf;\r\n\r\n    private String pu;\r\n\r\n    public TwitterService(String persistenceUnitName)\r\n    {\r\n        this.pu = persistenceUnitName;\r\n        if (emf == null)\r\n        {\r\n            try\r\n            {\r\n                emf = createEntityManagerFactory(persistenceUnitName);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                \r\n            }\r\n        }\r\n\r\n    }\r\n\r\n    @Override\r\n    public void createEntityManager()\r\n    {\r\n        if (em == null)\r\n        {\r\n            em = emf.createEntityManager();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void closeEntityManager()\r\n    {\r\n        if (em != null)\r\n        {\r\n            em.close();\r\n            em = null;\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void close()\r\n    {\r\n        if (emf != null)\r\n        {\r\n            MongoUtils.dropDatabase(emf, pu);\r\n            emf.close();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void addUser(UserMongo user)\r\n    {\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void addUser(String userId, String name, String password, String relationshipStatus)\r\n    {\r\n        UserMongo user = new UserMongo(userId, name, password, relationshipStatus);\r\n        em.persist(user);\r\n\r\n    }\r\n\r\n    @Override\r\n    public void savePreference(String userId, PreferenceMongo preference)\r\n    {\r\n\r\n        UserMongo user = em.find(UserMongo.class, userId);\r\n        user.setPreference(preference);\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void addExternalLink(String userId, String linkId, String linkType, String linkAddress)\r\n    {\r\n        UserMongo user = em.find(UserMongo.class, userId);\r\n        user.addExternalLink(new ExternalLinkMongo(linkId, linkType, linkAddress));\r\n\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void addTweet(String userId, String tweetBody, String device)\r\n    {\r\n        UserMongo user = em.find(UserMongo.class, userId);\r\n        user.addTweet(new TweetMongo(tweetBody, device));\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void startFollowing(String userId, String friendUserId)\r\n    {\r\n        UserMongo user = em.find(UserMongo.class, userId);\r\n        UserMongo friend = em.find(UserMongo.class, friendUserId);\r\n\r\n        user.addFriend(friend);\r\n        em.persist(user);\r\n\r\n        friend.addFollower(user);\r\n        em.persist(friend);\r\n    }\r\n\r\n    @Override\r\n    public void addFollower(String userId, String followerUserId)\r\n    {\r\n        UserMongo user = em.find(UserMongo.class, userId);\r\n        UserMongo follower = em.find(UserMongo.class, followerUserId);\r\n\r\n        user.addFollower(follower);\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public UserMongo findUserById(String userId)\r\n    {\r\n        UserMongo user = em.find(UserMongo.class, userId);\r\n        return user;\r\n    }\r\n\r\n    @Override\r\n    public void removeUser(UserMongo user)\r\n    {\r\n        em.remove(user);\r\n    }\r\n\r\n    @Override\r\n    public void mergeUser(UserMongo user)\r\n    {\r\n        em.merge(user);\r\n    }\r\n\r\n    @Override\r\n    public List<UserMongo> getAllUsers()\r\n    {\r\n\r\n        Query q = em.createQuery(\"select u from UserMongo u\");\r\n\r\n        List<UserMongo> users = q.getResultList();\r\n\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<TweetMongo> getAllTweets(String userId)\r\n    {\r\n        Query q = em.createQuery(\"select u from UserMongo u where u.userId =:userId\");\r\n        q.setParameter(\"userId\", userId);\r\n        List<UserMongo> users = q.getResultList();\r\n        if (users == null || users.isEmpty())\r\n        {\r\n            return null;\r\n        }\r\n        else\r\n        {\r\n            return users.get(0).getTweets();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public List<UserMongo> getFollowers(String userId)\r\n    {\r\n        Query q = em.createQuery(\"select u from UserMongo u where u.userId =:userId\");\r\n        q.setParameter(\"userId\", userId);\r\n        List<UserMongo> users = q.getResultList();\r\n        if (users == null || users.isEmpty())\r\n        {\r\n            return null;\r\n        }\r\n        return users.get(0).getFollowers();\r\n    }\r\n\r\n    @Override\r\n    public List<TweetMongo> findTweetByBody(String tweetBody)\r\n    {\r\n        Query q = em.createQuery(\"select u.tweet_body from UserMongo u where u.tweet_body like :body\");\r\n        q.setParameter(\"body\", tweetBody);\r\n        List<TweetMongo> tweets = q.getResultList();\r\n        return tweets;\r\n    }\r\n\r\n    @Override\r\n    public List<TweetMongo> findTweetByDevice(String deviceName)\r\n    {\r\n        Query q = em.createQuery(\"select u.tweeted_from from UserMongo u where u.tweeted_from like :device\");\r\n        q.setParameter(\"device\", deviceName);\r\n        List<TweetMongo> tweets = q.getResultList();\r\n        return tweets;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/twitter/entities/ExternalLinkMongo.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.twitter.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class for user's External link details\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"EXTERNAL_LINK\", schema = \"KunderaExamples@mongoTest\")\npublic class ExternalLinkMongo\n{\n\n    @Id\n    @Column(name = \"EXT_LINK_ID\")\n    private String extLinkId;\n\n    @Column(name = \"LINK_TYPE\")\n    private String linkType;\n\n    @Column(name = \"LINK_ADDRESS\")\n    private String linkAddress;\n\n    public ExternalLinkMongo()\n    {\n    }\n\n    public ExternalLinkMongo(String extLinkId, String type, String address)\n    {\n        this.extLinkId = extLinkId;\n        this.linkType = type;\n        this.linkAddress = address;\n    }\n\n    /**\n     * @return the extLinkId\n     */\n    public String getExtLinkId()\n    {\n        return extLinkId;\n    }\n\n    /**\n     * @param extLinkId\n     *            the extLinkId to set\n     */\n    public void setExtLinkId(String extLinkId)\n    {\n        this.extLinkId = extLinkId;\n    }\n\n    /**\n     * @return the linkType\n     */\n    public String getLinkType()\n    {\n        return linkType;\n    }\n\n    /**\n     * @param linkType\n     *            the linkType to set\n     */\n    public void setLinkType(String linkType)\n    {\n        this.linkType = linkType;\n    }\n\n    /**\n     * @return the linkAddress\n     */\n    public String getLinkAddress()\n    {\n        return linkAddress;\n    }\n\n    /**\n     * @param linkAddress\n     *            the linkAddress to set\n     */\n    public void setLinkAddress(String linkAddress)\n    {\n        this.linkAddress = linkAddress;\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/twitter/entities/PersonalDetailMongo.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\nimport com.impetus.client.twitter.utils.ExampleUtilsMongo;\r\n\r\n/**\r\n * Entity class for user's personal details\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\npublic class PersonalDetailMongo\r\n{\r\n    @Column(name = \"personal_detail_id\")\r\n    private String personalDetailId;\r\n\r\n    @Column(name = \"name\")\r\n    private String name;\r\n\r\n    @Column(name = \"password\")\r\n    private String password;\r\n\r\n    @Column(name = \"rel_status\")\r\n    private String relationshipStatus;\r\n\r\n    public PersonalDetailMongo()\r\n    {\r\n\r\n    }\r\n\r\n    public PersonalDetailMongo(String name, String password, String relationshipStatus)\r\n    {\r\n        setPersonalDetailId(ExampleUtilsMongo.getUniqueId());\r\n        setName(name);\r\n        setPassword(password);\r\n        setRelationshipStatus(relationshipStatus);\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetailId\r\n     */\r\n    public String getPersonalDetailId()\r\n    {\r\n        return personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetailId\r\n     *            the personalDetailId to set\r\n     */\r\n    public void setPersonalDetailId(String personalDetailId)\r\n    {\r\n        this.personalDetailId = personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @return the name\r\n     */\r\n    public String getName()\r\n    {\r\n        return name;\r\n    }\r\n\r\n    /**\r\n     * @param name\r\n     *            the name to set\r\n     */\r\n    public void setName(String name)\r\n    {\r\n        this.name = name;\r\n    }\r\n\r\n    /**\r\n     * @return the password\r\n     */\r\n    public String getPassword()\r\n    {\r\n        return password;\r\n    }\r\n\r\n    /**\r\n     * @param password\r\n     *            the password to set\r\n     */\r\n    public void setPassword(String password)\r\n    {\r\n        this.password = password;\r\n    }\r\n\r\n    /**\r\n     * @return the relationshipStatus\r\n     */\r\n    public String getRelationshipStatus()\r\n    {\r\n        return relationshipStatus;\r\n    }\r\n\r\n    /**\r\n     * @param relationshipStatus\r\n     *            the relationshipStatus to set\r\n     */\r\n    public void setRelationshipStatus(String relationshipStatus)\r\n    {\r\n        this.relationshipStatus = relationshipStatus;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/twitter/entities/PreferenceMongo.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * Entity class for User Preferences\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"PREFERENCE\", schema = \"KunderaExamples@mongoTest\")\r\npublic class PreferenceMongo\r\n{\r\n    @Id\r\n    @Column(name = \"PREFERENCE_ID\")\r\n    String preferenceId;\r\n\r\n    @Column(name = \"WEBSITE_THEME\")\r\n    String websiteTheme;\r\n\r\n    @Column(name = \"PRIVACY_LEVEL\")\r\n    String privacyLevel; // 1, 2, 3\r\n\r\n    public PreferenceMongo()\r\n    {\r\n\r\n    }\r\n\r\n    public PreferenceMongo(String preferenceId, String theme, String privacyLevel)\r\n    {\r\n        this.preferenceId = preferenceId;\r\n        this.websiteTheme = theme;\r\n        this.privacyLevel = privacyLevel;\r\n    }\r\n\r\n    /**\r\n     * @return the preferenceId\r\n     */\r\n    public String getPreferenceId()\r\n    {\r\n        return preferenceId;\r\n    }\r\n\r\n    /**\r\n     * @param preferenceId\r\n     *            the preferenceId to set\r\n     */\r\n    public void setPreferenceId(String preferenceId)\r\n    {\r\n        this.preferenceId = preferenceId;\r\n    }\r\n\r\n    /**\r\n     * @return the websiteTheme\r\n     */\r\n    public String getWebsiteTheme()\r\n    {\r\n        return websiteTheme;\r\n    }\r\n\r\n    /**\r\n     * @param websiteTheme\r\n     *            the websiteTheme to set\r\n     */\r\n    public void setWebsiteTheme(String websiteTheme)\r\n    {\r\n        this.websiteTheme = websiteTheme;\r\n    }\r\n\r\n    /**\r\n     * @return the privacyLevel\r\n     */\r\n    public String getPrivacyLevel()\r\n    {\r\n        return privacyLevel;\r\n    }\r\n\r\n    /**\r\n     * @param privacyLevel\r\n     *            the privacyLevel to set\r\n     */\r\n    public void setPrivacyLevel(String privacyLevel)\r\n    {\r\n        this.privacyLevel = privacyLevel;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/twitter/entities/RoleMongo.java",
    "content": "package com.impetus.client.twitter.entities;\n\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"Rol\", schema = \"KunderaExamples@mongoTest\")\npublic class RoleMongo\n{\n\n    @Id\n    @Column\n    private Integer rolId;\n\n    @Column\n    private String name;\n\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY, mappedBy = \"userRol\")\n    private List<User> segUsuarioList;\n\n    public RoleMongo()\n    {\n\n    }\n\n    /**\n     * @return the rolId\n     */\n    public Integer getRolId()\n    {\n        return rolId;\n    }\n\n    /**\n     * @param rolId\n     *            the rolId to set\n     */\n    public void setRolId(Integer rolId)\n    {\n        this.rolId = rolId;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the segUsuarioList\n     */\n    public List<User> getSegUsuarioList()\n    {\n        return segUsuarioList;\n    }\n\n    /**\n     * @param segUsuarioList\n     *            the segUsuarioList to set\n     */\n    public void setSegUsuarioList(List<User> segUsuarioList)\n    {\n        this.segUsuarioList = segUsuarioList;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/twitter/entities/TweetMongo.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\nimport com.impetus.client.twitter.utils.ExampleUtilsMongo;\r\n\r\n/**\r\n * Class for Tweets\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\npublic class TweetMongo\r\n{\r\n\r\n    @Column(name = \"tweet_id\")\r\n    private String tweetId;\r\n\r\n    @Column(name = \"tweet_body\")\r\n    private String body;\r\n\r\n    @Column(name = \"tweeted_from\")\r\n    private String device;\r\n\r\n    // private long timestamp;\r\n\r\n    public TweetMongo(String body, String device)\r\n    {\r\n        this.tweetId = ExampleUtilsMongo.getUniqueId();\r\n        this.body = body;\r\n        this.device = device;\r\n        // this.timestamp = ExampleUtils.getCurrentTimestamp();\r\n    }\r\n\r\n    public TweetMongo()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * @return the tweetId\r\n     */\r\n    public String getTweetId()\r\n    {\r\n        return tweetId;\r\n    }\r\n\r\n    /**\r\n     * @param tweetId\r\n     *            the tweetId to set\r\n     */\r\n    public void setTweetId(String tweetId)\r\n    {\r\n        this.tweetId = tweetId;\r\n    }\r\n\r\n    /**\r\n     * @return the body\r\n     */\r\n    public String getBody()\r\n    {\r\n        return body;\r\n    }\r\n\r\n    /**\r\n     * @param body\r\n     *            the body to set\r\n     */\r\n    public void setBody(String body)\r\n    {\r\n        this.body = body;\r\n    }\r\n\r\n    /**\r\n     * @return the device\r\n     */\r\n    public String getDevice()\r\n    {\r\n        return device;\r\n    }\r\n\r\n    /**\r\n     * @param device\r\n     *            the device to set\r\n     */\r\n    public void setDevice(String device)\r\n    {\r\n        this.device = device;\r\n    }\r\n\r\n    /*    *//**\r\n     * @return the timestamp\r\n     */\r\n    /*\r\n     * public long getTimestamp() { return timestamp; }\r\n     *//**\r\n     * @param timestamp\r\n     *            the timestamp to set\r\n     */\r\n    /*\r\n     * public void setTimestamp(long timestamp) { this.timestamp = timestamp; }\r\n     */\r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/twitter/entities/User.java",
    "content": "package com.impetus.client.twitter.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"User\", schema = \"KunderaExamples@mongoTest\")\npublic class User\n{\n    @Id\n    @Column\n    private Integer userId;\n\n    @Column\n    private String name;\n\n    @Column\n    private String email;\n\n    @Column\n    private Integer age;\n\n    @Column\n    private String lastName;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"rolId\")\n    private RoleMongo userRol;\n\n    /**\n     * \n     */\n    public User()\n    {\n    }\n\n    /**\n     * @return the userId\n     */\n    public Integer getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * @param userId\n     *            the userId to set\n     */\n    public void setUserId(Integer userId)\n    {\n        this.userId = userId;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the email\n     */\n    public String getEmail()\n    {\n        return email;\n    }\n\n    /**\n     * @param email\n     *            the email to set\n     */\n    public void setEmail(String email)\n    {\n        this.email = email;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(Integer age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the lastName\n     */\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    /**\n     * @param lastName\n     *            the lastName to set\n     */\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n    /**\n     * @return the userRol\n     */\n    public RoleMongo getUserRol()\n    {\n        return userRol;\n    }\n\n    /**\n     * @param userRol\n     *            the userRol to set\n     */\n    public void setUserRol(RoleMongo userRol)\n    {\n        this.userRol = userRol;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/twitter/entities/UserMongo.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.CollectionTable;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.ElementCollection;\r\nimport javax.persistence.Embedded;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.OneToOne;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * @author impetus\r\n * \r\n */\r\n@Entity\r\n@Table(name = \"USER\", schema = \"KunderaExamples@mongoTest\")\r\npublic class UserMongo\r\n{\r\n\r\n    @Id\r\n    @Column(name = \"USER_ID\")\r\n    private String userId;\r\n\r\n    // Embedded object, will persist co-located\r\n    @Embedded\r\n    private PersonalDetailMongo personalDetail;\r\n\r\n    // Element collection, will persist co-located\r\n    @ElementCollection\r\n    @CollectionTable(name = \"tweeted\")\r\n    private List<TweetMongo> tweets;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"FRIEND_ID\")\r\n    private List<UserMongo> friends; // List of users whom I follow\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"FOLLOWER_ID\")\r\n    private List<UserMongo> followers; // List of users who are following me\r\n\r\n    // One-to-one, will be persisted separately\r\n    @OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"PREFERENCE_ID\")\r\n    private PreferenceMongo preference;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"USER_ID\")\r\n    private Set<ExternalLinkMongo> externalLinks;\r\n\r\n    public UserMongo()\r\n    {\r\n\r\n    }\r\n\r\n    public UserMongo(String userId, String name, String password, String relationshipStatus)\r\n    {\r\n        PersonalDetailMongo pd = new PersonalDetailMongo(name, password, relationshipStatus);\r\n        setUserId(userId);\r\n        setPersonalDetail(pd);\r\n    }\r\n\r\n    /**\r\n     * @return the userId\r\n     */\r\n    public String getUserId()\r\n    {\r\n        return userId;\r\n    }\r\n\r\n    /**\r\n     * @param userId\r\n     *            the userId to set\r\n     */\r\n    public void setUserId(String userId)\r\n    {\r\n        this.userId = userId;\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetail\r\n     */\r\n    public PersonalDetailMongo getPersonalDetail()\r\n    {\r\n        return personalDetail;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetail\r\n     *            the personalDetail to set\r\n     */\r\n    public void setPersonalDetail(PersonalDetailMongo personalDetail)\r\n    {\r\n        this.personalDetail = personalDetail;\r\n    }\r\n\r\n    /**\r\n     * @return the tweets\r\n     */\r\n    public List<TweetMongo> getTweets()\r\n    {\r\n        return tweets;\r\n    }\r\n\r\n    /**\r\n     * @param tweets\r\n     *            the tweets to set\r\n     */\r\n    public void addTweet(TweetMongo tweet)\r\n    {\r\n        if (this.tweets == null || this.tweets.isEmpty())\r\n        {\r\n            this.tweets = new ArrayList<TweetMongo>();\r\n        }\r\n        this.tweets.add(tweet);\r\n    }\r\n\r\n    /**\r\n     * @return the preference\r\n     */\r\n    public PreferenceMongo getPreference()\r\n    {\r\n        return preference;\r\n    }\r\n\r\n    /**\r\n     * @param preference\r\n     *            the preference to set\r\n     */\r\n    public void setPreference(PreferenceMongo preference)\r\n    {\r\n        this.preference = preference;\r\n    }\r\n\r\n    /**\r\n     * @return the externalLinks\r\n     */\r\n    public Set<ExternalLinkMongo> getExternalLinks()\r\n    {\r\n        return externalLinks;\r\n    }\r\n\r\n    /**\r\n     * @param imDetails\r\n     *            the imDetails to set\r\n     */\r\n    public void addExternalLink(ExternalLinkMongo externalLink)\r\n    {\r\n        if (this.externalLinks == null || this.externalLinks.isEmpty())\r\n        {\r\n            this.externalLinks = new HashSet<ExternalLinkMongo>();\r\n        }\r\n\r\n        this.externalLinks.add(externalLink);\r\n    }\r\n\r\n    /**\r\n     * @return the friends\r\n     */\r\n    public List<UserMongo> getFriends()\r\n    {\r\n        return friends;\r\n    }\r\n\r\n    /**\r\n     * @param friends\r\n     *            the friends to set\r\n     */\r\n    public void addFriend(UserMongo friend)\r\n    {\r\n        if (this.friends == null || this.friends.isEmpty())\r\n        {\r\n            this.friends = new ArrayList<UserMongo>();\r\n        }\r\n        this.friends.add(friend);\r\n    }\r\n\r\n    /**\r\n     * @return the followers\r\n     */\r\n    public List<UserMongo> getFollowers()\r\n    {\r\n        return followers;\r\n    }\r\n\r\n    /**\r\n     * @param followers\r\n     *            the followers to set\r\n     */\r\n    public void addFollower(UserMongo follower)\r\n    {\r\n        if (this.followers == null || this.followers.isEmpty())\r\n        {\r\n            this.followers = new ArrayList<UserMongo>();\r\n        }\r\n\r\n        this.followers.add(follower);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/twitter/utils/ExampleUtilsMongo.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.utils;\r\n\r\nimport java.util.Date;\r\nimport java.util.UUID;\r\n\r\n/**\r\n * Class for utility methods\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class ExampleUtilsMongo\r\n{\r\n    public static String getUniqueId()\r\n    {\r\n        return UUID.randomUUID().toString();\r\n    }\r\n\r\n    public static long getCurrentTimestamp()\r\n    {\r\n        return new Date().getTime();\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/client/utils/MongoUtils.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.utils;\n\nimport java.lang.reflect.Field;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.mongodb.MongoDBClient;\nimport com.impetus.kundera.client.Client;\nimport com.mongodb.DB;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class MongoUtils\n{\n\n    private static final Logger logger = LoggerFactory.getLogger(MongoUtils.class);\n\n    /**\n     * \n     */\n    public static void dropDatabase(EntityManagerFactory emf, String pu)\n    {\n        EntityManager em = null;\n        Map<String, Client> clients = null;\n        MongoDBClient client = null;\n        if (emf != null)\n            em = emf.createEntityManager();\n\n        if (em != null)\n            clients = (Map<String, Client>) em.getDelegate();\n        if (clients != null)\n            client = (MongoDBClient) clients.get(pu);\n        if (client != null)\n        {\n            try\n            {\n                Field db = client.getClass().getDeclaredField(\"mongoDb\");\n                if (!db.isAccessible())\n                {\n                    db.setAccessible(true);\n                }\n                DB mongoDB = (DB) db.get(client);\n                mongoDB.dropDatabase();\n            }\n            catch (SecurityException e)\n            {\n                logger.error(\"Error while truncating db\",e);\n            }\n\n            catch (NoSuchFieldException e)\n            {\n                logger.error(\"Error while truncating db\",e);\n            }\n            catch (IllegalArgumentException e)\n            {\n                logger.error(\"Error while truncating db\",e);\n            }\n            catch (IllegalAccessException e)\n            {\n                logger.error(\"Error while truncating db\",e);\n            }\n        }\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/crud/inheritence/AbstractClassEventEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.inheritence;\n\nimport java.io.Serializable;\n\nimport javax.persistence.DiscriminatorColumn;\nimport javax.persistence.DiscriminatorType;\nimport javax.persistence.Entity;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.PostPersist;\nimport javax.persistence.Table;\n\n/**\n * Abstract entity class.\n * @author chhavi.gangwal\n *\n */\n@Entity\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@Table(name = \"abstract_entity_event\")\n@DiscriminatorColumn(name = \"type\", length = 64, discriminatorType = DiscriminatorType.STRING)\npublic abstract class AbstractClassEventEntity extends MappedSuperClassEventEntity implements Serializable\n{\n    \n    private String secondLevelEntityType;\n    \n    @PostPersist\n    public void  abstractClassCounter()\n    {\n        invocationCounter--;\n    }\n\n    \n    public String getsecondLevelEntityType()\n    {\n        return secondLevelEntityType;\n    }\n\n    public void setsecondLevelEntityType(String secondLevelEntityType)\n    {\n        this.secondLevelEntityType = secondLevelEntityType;\n    }\n    \n   \n\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/crud/inheritence/AbstractEntityEventListenerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.inheritence;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.persistence.event.EntityEventDispatcher;\n\n/**\n * Test case for {@link AbstractEntityEventListenerTest}\n * \n * @author chhavi.gangwal\n * \n */\npublic class AbstractEntityEventListenerTest\n{\n\n    private EntityEventDispatcher eventDispatcher;\n\n    private EntityManager em;\n\n    private EntityManagerFactory emf;\n\n    private static String _PU = \"mongoTest\";\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        eventDispatcher = new EntityEventDispatcher();\n        \n        emf = Persistence.createEntityManagerFactory(_PU);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        eventDispatcher = null;\n        em.close();\n        emf.close();\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.persistence.event.EntityEventDispatcher#fireEventListeners(com.impetus.kundera.metadata.model.EntityMetadata, java.lang.Object, java.lang.Class)}\n     * .\n     * \n     * @throws SecurityException\n     * @throws NoSuchMethodException\n     */\n    @Test\n    public void testEventListeners() throws NoSuchMethodException, SecurityException\n    {\n        EventEntity entity = new EventEntity();\n        entity.setId(10L);\n        em.persist(entity);\n\n        // +2 for @PrePersist -1 for @PostPersist\n        Assert.assertEquals(1, entity.invocationCounter);\n        \n        EventEntity found = em.find(EventEntity.class, 10L);\n        found.setEntityType(\"Updated\");\n        found.invocationCounter = 0;\n        em.merge(found);\n\n        found = em.find(EventEntity.class, 10L);\n\n        // +1 for @PreUpdate +1 for @PostUpdate\n        Assert.assertEquals(2, entity.invocationCounter);\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/crud/inheritence/EventEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.inheritence;\n\n\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.PostUpdate;\nimport javax.persistence.PreUpdate;\n/**\n  * \n * @author chhavi.gangwal\n * \n */\n@Entity\n@DiscriminatorValue(\"event_entity\")\npublic class EventEntity extends AbstractClassEventEntity\n{\n    @Column(name = \"entityType\")\n    private String entityType;\n    \n   \n    @PreUpdate\n    public void  preUpdateEntityCOunter()\n    {\n        this.invocationCounter++;\n    }\n    \n    @PostUpdate\n    public void  postUpdateEntityCOunter()\n    {\n        this.invocationCounter++;\n    }\n    \n    public String getEntityType()\n    {\n        return entityType;\n    }\n\n    public void setEntityType(String entityType)\n    {\n        this.entityType = entityType;\n    }\n    \n   \n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/crud/inheritence/FacebookProfile.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.DiscriminatorValue;\r\nimport javax.persistence.Entity;\r\n\r\n/**\r\n * Facebook profile entity\r\n * \r\n * @author vivek.mishra\r\n * \r\n */\r\n@Entity\r\n@DiscriminatorValue(\"fb\")\r\npublic class FacebookProfile extends SocialProfile\r\n{\r\n    // protected static final String TYPE = \"twitter\";\r\n\r\n    // @Id\r\n    // // @GeneratedValue\r\n    // @Column(name = \"guid\", updatable = false, nullable = false)\r\n    // private String id;\r\n\r\n    @Column(name = \"facebook_id\", updatable = false)\r\n    private String facebookId;\r\n\r\n    @Column(name = \"facebook_user\", length = 128)\r\n    private String facebookUser;\r\n\r\n    public String getFacebookId()\r\n    {\r\n        return facebookId;\r\n    }\r\n\r\n    public void setFacebookId(String facebookId)\r\n    {\r\n        this.facebookId = facebookId;\r\n    }\r\n\r\n    public String getFacebookUser()\r\n    {\r\n        return facebookUser;\r\n    }\r\n\r\n    public void setFacebookUser(String facebookUser)\r\n    {\r\n        this.facebookUser = facebookUser;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/crud/inheritence/GuidDomainObject.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\nimport javax.persistence.Id;\r\nimport javax.persistence.MappedSuperclass;\r\n\r\n\r\n\r\n/**\r\n * Abstract mapped super class.\r\n * \r\n * @author vivek.mishra\r\n *\r\n */\r\n@MappedSuperclass\r\nabstract public class GuidDomainObject \r\n{\r\n   /* @Id\r\n    @GeneratedValue\r\n    @Column(name = \"guid\", updatable = false, nullable = false)\r\n    private String id;*/\r\n    \r\n    @Id\r\n//    @TableGenerator(name = \"AEntity_id_generatorStrategy\", table = \"SequenceEntity\", allocationSize = 1000)\r\n//    @GeneratedValue(strategy = GenerationType.TABLE, generator = \"AEntity_id_generatorStrategy\")\r\n    private Long id;\r\n\r\n    public Long getId()\r\n    {\r\n        return id;\r\n    }\r\n\r\n    public void setId(Long id)\r\n    {\r\n        this.id = id;\r\n    }\r\n\r\n    \r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/crud/inheritence/InheritenceDomainTest.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Persistence;\r\nimport javax.persistence.Query;\r\n\r\nimport junit.framework.Assert;\r\n\r\nimport org.junit.After;\r\nimport org.junit.AfterClass;\r\nimport org.junit.BeforeClass;\r\nimport org.junit.Test;\r\n\r\nimport com.impetus.client.utils.MongoUtils;\r\n\r\n/**\r\n * Junit test case.\r\n * @author vivek.mishra\r\n *\r\n */\r\npublic class InheritenceDomainTest\r\n{\r\n\r\n    protected static String _PU = \"mongoTest\";\r\n\r\n    /** The emf. */\r\n    protected static EntityManagerFactory emf;\r\n\r\n    /** The em. */\r\n    protected static EntityManager em;\r\n\r\n    \r\n    @BeforeClass\r\n    public static void setUpBeforeClass() throws Exception\r\n    {\r\n        \r\n        \r\n        emf = Persistence.createEntityManagerFactory(_PU);\r\n        em = emf.createEntityManager();\r\n    }\r\n\r\n    @Test\r\n    public void testRelation()\r\n    {\r\n\r\n        List<SocialProfile> profiles = new ArrayList<SocialProfile>();\r\n\r\n        FacebookProfile fbprofile = new FacebookProfile();\r\n        fbprofile.setId(103l);\r\n        fbprofile.setFacebookId(\"fb1\");\r\n        fbprofile.setFacebookUser(\"facebook\");\r\n        fbprofile.setuserType(\"dumbo\");\r\n\r\n        profiles.add(fbprofile);\r\n\r\n        TwitterProfile twprofile1 = new TwitterProfile();\r\n        twprofile1.setTwitterId(\"2\");\r\n        twprofile1.setTwitterName(\"test2\");\r\n        twprofile1.setId(102l);\r\n        profiles.add(twprofile1);\r\n        twprofile1.setuserType(\"dumbo\");\r\n        \r\n        UserAccount uacc = new UserAccount();\r\n\r\n        uacc.setId(101l);\r\n        uacc.setDispName(\"Test\");\r\n        uacc.setSocialProfiles(profiles);\r\n\r\n        twprofile1.setuserAccount(uacc);\r\n        fbprofile.setuserAccount(uacc);\r\n\r\n        em.getTransaction().begin();\r\n        em.persist(uacc);\r\n        em.getTransaction().commit();\r\n        \r\n        //TODOO: Stack over flow error.\r\n//        em.persist(fbprofile);\r\n//        em.persist(twprofile1);\r\n        em.clear();\r\n\r\n        String uaQuery = \"Select ua from UserAccount ua\";\r\n\r\n        Query q = em.createQuery(uaQuery);\r\n        List<UserAccount> results = q.getResultList();\r\n\r\n\r\n        Assert.assertEquals(1, results.size());\r\n        Assert.assertEquals(\"Test\", results.get(0).getDispName());\r\n         Assert.assertEquals(2, results.get(0).getSocialProfiles().size());\r\n\r\n        em.clear();\r\n\r\n    }\r\n\r\n    @Test\r\n    public void testAbstractEntity()\r\n    {\r\n        FacebookProfile fbprofile = new FacebookProfile();\r\n        fbprofile.setId(Long.MIN_VALUE);\r\n        fbprofile.setFacebookId(\"fb1\");\r\n        fbprofile.setFacebookUser(\"facebook\");\r\n        fbprofile.setuserType(\"dumbo\");\r\n\r\n        em.persist(fbprofile);\r\n        \r\n        \r\n        TwitterProfile twprofile = new TwitterProfile();\r\n        twprofile.setTwitterId(\"2\");\r\n        twprofile.setTwitterName(\"test2\");\r\n        twprofile.setId(Long.MAX_VALUE);\r\n        twprofile.setuserType(\"dumbo\");\r\n        \r\n        em.persist(twprofile);\r\n        \r\n        SocialProfile facebookProfile = em.find(SocialProfile.class,Long.MIN_VALUE);\r\n        Assert.assertNotNull(facebookProfile);\r\n        Assert.assertTrue(facebookProfile.getClass().isAssignableFrom(FacebookProfile.class));\r\n        \r\n        SocialProfile twitterProfile = em.find(SocialProfile.class,Long.MAX_VALUE);\r\n        Assert.assertNotNull(twitterProfile);\r\n        Assert.assertTrue(twitterProfile.getClass().isAssignableFrom(TwitterProfile.class));\r\n        \r\n        String queryStr = \"Select s from SocialProfile s\";\r\n        \r\n        Query query = em.createQuery(queryStr);\r\n        \r\n        List<SocialProfile> socialProfiles = query.getResultList();\r\n        \r\n        Assert.assertFalse(socialProfiles.isEmpty());\r\n        Assert.assertEquals(2, socialProfiles.size());\r\n        Assert.assertFalse(socialProfiles.get(0).getClass().getSimpleName().equals(socialProfiles.get(1).getClass().getSimpleName()));\r\n    }\r\n    \r\n    /**\r\n     * Tear down.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n     @After\r\n    public void tearDown() throws Exception\r\n    {\r\n        MongoUtils.dropDatabase(emf, _PU);\r\n    }\r\n\r\n     @AfterClass\r\n     public static void tearDownAfterClass()\r\n     {\r\n         if(em != null)\r\n         {\r\n             em.close();\r\n             em=null;\r\n         }\r\n         if(emf != null)\r\n         {\r\n             emf.close();\r\n             emf=null;\r\n         }\r\n         \r\n         \r\n     }\r\n}\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/crud/inheritence/MappedSuperClassEventEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.inheritence;\n\n\nimport javax.persistence.Id;\nimport javax.persistence.MappedSuperclass;\nimport javax.persistence.PrePersist;\n\n\n/**\n  * \n * @author chhavi.gangwal\n * \n */\n@MappedSuperclass\nabstract public class MappedSuperClassEventEntity\n{\n    @Id\n    public Long id;\n    \n    \n    protected static int invocationCounter = 0;\n    \n    public MappedSuperClassEventEntity(){\n        \n    }\n    \n    @PrePersist\n    public void  mappedSuperClassCounter()\n    {\n        invocationCounter = invocationCounter + 2;\n    }\n\n    public Long getId()\n    {\n        return id;\n    }\n\n    public void setId(Long id)\n    {\n        this.id = id;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/crud/inheritence/SocialProfile.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.client.crud.inheritence;\n\nimport java.io.Serializable;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorColumn;\nimport javax.persistence.DiscriminatorType;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * Abstract entity class.\n * @author vivek.mishra\n *\n */\n@Entity\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@Table(name = \"social_profile\")\n@DiscriminatorColumn(name = \"type\", length = 64, discriminatorType = DiscriminatorType.STRING)\npublic abstract class SocialProfile extends GuidDomainObject implements Serializable\n{\n    @Column(name = \"userType\")\n    private String userType;\n\n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"user_account_id\")\n    private UserAccount account;\n    \n    public String getuserType()\n    {\n        return userType;\n    }\n\n    public void setuserType(String userType)\n    {\n        this.userType = userType;\n    }\n    \n    public UserAccount getuserAccount()\n    {\n        return account;\n    }\n\n    public void setuserAccount(UserAccount account)\n    {\n        this.account = account;\n    }\n\n}"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/crud/inheritence/TwitterProfile.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.DiscriminatorValue;\r\nimport javax.persistence.Entity;\r\n\r\n/**\r\n * Twitter profile entity.\r\n * @author vivek.mishra\r\n *\r\n */\r\n@Entity\r\n@DiscriminatorValue(\"twitter\")\r\npublic class TwitterProfile extends SocialProfile\r\n{\r\n   // protected static final String TYPE = \"twitter\";\r\n\r\n//    @Id\r\n////    @GeneratedValue\r\n//    @Column(name = \"guid\", updatable = false, nullable = false)\r\n//    private String id;\r\n\r\n    @Column(name = \"twitter_id\", updatable = false)\r\n    private String twitterId;\r\n\r\n    @Column(name = \"twitter_user\", length = 128)\r\n    private String twitterUser;\r\n    \r\n    public String getTwitterId()\r\n    {\r\n        return twitterId;\r\n    }\r\n\r\n    public void setTwitterId(String twitterId)\r\n    {\r\n        this.twitterId = twitterId;\r\n    }\r\n    \r\n    public String getTwitterName()\r\n    {\r\n        return twitterUser;\r\n    }\r\n\r\n    public void setTwitterName(String twitterUser)\r\n    {\r\n        this.twitterUser = twitterUser;\r\n    }\r\n\r\n\r\n}  \r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/crud/inheritence/UserAccount.java",
    "content": "/**\r\n * Copyright 2013 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.client.crud.inheritence;\r\n\r\n\r\nimport java.util.List;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.Table;\r\n\r\n\r\n/**\r\n * User account entity.\r\n * @author vivek.mishra\r\n *\r\n */\r\n@Entity\r\n@Table(name = \"user_account\")\r\npublic class UserAccount extends GuidDomainObject\r\n{\r\n    /*@EmbeddedId\r\n    private ProfileType key;\r\n    \r\n    public ProfileType getId()\r\n    {\r\n        return key;\r\n    }\r\n\r\n    public void setId(ProfileType key)\r\n    {\r\n        this.key = key;\r\n    }\r\n    \r\n    */\r\n    @Column(name = \"display_name\", length = 128)\r\n    private String displayName = null;\r\n\r\n    @Column(name = \"email\", length = 128, unique = true)\r\n    private String email = null;\r\n\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER,mappedBy = \"account\")\r\n    private List<SocialProfile> profiles;\r\n    \r\n    public String getDispName()\r\n    {\r\n        return displayName;\r\n    }\r\n\r\n    public void setDispName(String displayName)\r\n    {\r\n        this.displayName = displayName;\r\n    }\r\n    \r\n    public String getEmail()\r\n    {\r\n        return email;\r\n    }\r\n\r\n    public void setEmail(String email)\r\n    {\r\n        this.email = email;\r\n    }\r\n    \r\n    public List<SocialProfile> getSocialProfiles()\r\n    {\r\n        return profiles;\r\n    }\r\n\r\n    public void setSocialProfiles(List<SocialProfile> profiles)\r\n    {\r\n        this.profiles = profiles;\r\n    }\r\n} \r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/CreditTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.client.mongo.mappedsuperclass.Transaction;\n\n/**\n * @author vivek.mishra\n * Credit transaction extends {@link Transaction}\n *\n */\n\n@Entity\n@Table(name = \"TRNX_CREDIT\")\n@DiscriminatorValue(value = \"CREDIT\")\n@AttributeOverride(name=\"bankIdentifier\",column= @Column(name=\"CREDIT_BANK_IDENT\"))\npublic class CreditTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public CreditTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/DebitTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\n\nimport com.impetus.kundera.client.mongo.mappedsuperclass.Transaction;\n\n/**\n * @author vivek.mishra\n * Debit transaction extends {@link Transaction}\n *\n */\n@Entity\n@DiscriminatorValue(value=\"DEBIT\")\n\n@AttributeOverrides(value = { @AttributeOverride(name = \"txId\", column = @Column(name = \"DEBIT_ID\")),\n        @AttributeOverride(name = \"bankIdentifier\", column = @Column(name = \"DEBIT_BANK_IDENT\")),\n        @AttributeOverride(name = \"transactionDt\", column = @Column(name = \"TX_DT\")) })\n\npublic class DebitTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public DebitTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/mongo/MongoDBConfigurationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2017 Impetus Infotech.\n * *\n * * Licensed under the Apache License, Version 2.0 (the \"License\");\n * * you may not use this file except in compliance with the License.\n * * You may obtain a copy of the License at\n * *\n * * http://www.apache.org/licenses/LICENSE-2.0\n * *\n * * Unless required by applicable law or agreed to in writing, software\n * * distributed under the License is distributed on an \"AS IS\" BASIS,\n * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * * See the License for the specific language governing permissions and\n * * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.mongo;\n\nimport com.impetus.client.crud.BaseTest;\nimport com.impetus.client.mongodb.MongoDBClientFactory;\nimport com.impetus.client.mongodb.MongoDBConstants;\nimport com.mongodb.DBDecoder;\nimport com.mongodb.DBDecoderFactory;\nimport com.mongodb.DBEncoder;\nimport com.mongodb.DBEncoderFactory;\nimport com.mongodb.LazyDBDecoder;\nimport com.mongodb.MongoClientOptions;\nimport com.mongodb.WriteConcern;\nimport junit.framework.Assert;\nimport org.junit.Test;\n\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLSocketFactory;\nimport javax.net.ssl.TrustManager;\nimport javax.net.ssl.X509TrustManager;\nimport java.security.SecureRandom;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Properties;\n\n/**\n * Tests various configuration options for the MongoDB client factory.\n */\npublic class MongoDBConfigurationTest extends BaseTest\n{\n\n    /**\n     * Tests configuration from the external 'kundera.client.property' file\n     */\n    @Test\n    public void testConfigurationFromClientProperties()\n    {\n        Properties clientProperties = buildProperties(kv(MongoDBConstants.SAFE, \"false\"));\n\n        MongoClientOptions options = buildOptions(clientProperties, null);\n\n        Assert.assertEquals(WriteConcern.NORMAL, options.getWriteConcern());\n\n        clientProperties = buildProperties(kv(MongoDBConstants.W, \"0\"), kv(MongoDBConstants.W_TIME_OUT, \"1000\"),\n                kv(MongoDBConstants.FSYNC, \"true\"), kv(MongoDBConstants.J, \"false\"));\n\n        options = buildOptions(clientProperties, null);\n\n        WriteConcern wc = options.getWriteConcern();\n        Assert.assertEquals(0, wc.getW());\n        Assert.assertEquals(1000, wc.getWtimeout());\n        Assert.assertEquals(true, wc.getFsync());\n        Assert.assertEquals(false, wc.getJ());\n\n        clientProperties = buildProperties(kv(MongoDBConstants.DB_DECODER_FACTORY, \"com.mongodb.LazyDBDecoder.FACTORY\"));\n\n        options = buildOptions(clientProperties, null);\n\n        Assert.assertEquals(LazyDBDecoder.FACTORY, options.getDbDecoderFactory());\n\n        clientProperties = buildProperties(kv(MongoDBConstants.DB_DECODER_FACTORY,\n                \"com.impetus.kundera.client.mongo.MongoDBConfigurationTest$TestDBDecoderFactory\"));\n\n        options = buildOptions(clientProperties, null);\n\n        Assert.assertEquals(TestDBDecoderFactory.class, options.getDbDecoderFactory().getClass());\n\n        clientProperties = buildProperties(kv(MongoDBConstants.DB_ENCODER_FACTORY,\n                \"com.impetus.kundera.client.mongo.MongoDBConfigurationTest$TestDBEncoderFactory\"));\n\n        options = buildOptions(clientProperties, null);\n\n        Assert.assertEquals(TestDBEncoderFactory.class, options.getDbEncoderFactory().getClass());\n\n        clientProperties = buildProperties(kv(MongoDBConstants.SOCKET_FACTORY,\n                \"com.impetus.kundera.client.mongo.MongoDBConfigurationTest.INSECURE_SSL_SOCKET_FACTORY\"));\n\n        options = buildOptions(clientProperties, null);\n\n        Assert.assertEquals(INSECURE_SSL_SOCKET_FACTORY, options.getSocketFactory());\n\n        clientProperties = buildProperties(kv(MongoDBConstants.SOCKET_FACTORY,\n                \"javax.net.ssl.SSLSocketFactory.getDefault()\"));\n\n        options = buildOptions(clientProperties, null);\n\n        Assert.assertEquals(SSLSocketFactory.getDefault().getClass(), options.getSocketFactory().getClass());\n\n        clientProperties = buildProperties(kv(MongoDBConstants.AUTO_CONNECT_RETRY, \"true\"));\n\n        options = buildOptions(clientProperties, null);\n\n//        Assert.assertTrue(options.isAutoConnectRetry());\n\n        clientProperties = buildProperties(kv(MongoDBConstants.MAX_AUTO_CONNECT_RETRY, \"12\"));\n\n        options = buildOptions(clientProperties, null);\n\n//        Assert.assertEquals(12L, options.getMaxAutoConnectRetryTime());\n\n        clientProperties = buildProperties(kv(MongoDBConstants.CONNECTION_PER_HOST, \"7\"));\n\n        options = buildOptions(clientProperties, null);\n\n        Assert.assertEquals(7, options.getConnectionsPerHost());\n\n        clientProperties = buildProperties(kv(MongoDBConstants.CONNECT_TIME_OUT, \"32\"));\n\n        options = buildOptions(clientProperties, null);\n\n        Assert.assertEquals(32, options.getConnectTimeout());\n\n        clientProperties = buildProperties(kv(MongoDBConstants.MAX_WAIT_TIME, \"41\"));\n\n        options = buildOptions(clientProperties, null);\n\n        Assert.assertEquals(41, options.getMaxWaitTime());\n\n        clientProperties = buildProperties(kv(MongoDBConstants.TABCM, \"3\"));\n\n        options = buildOptions(clientProperties, null);\n\n        Assert.assertEquals(3, options.getThreadsAllowedToBlockForConnectionMultiplier());\n    }\n\n    /**\n     * Tests configuration from external properties.\n     */\n    @Test\n    public void testConfigurationFromExternalProperties()\n    {\n        Map<String, String> externalProperties = buildExternalProperties(kv(MongoDBConstants.SAFE, \"false\"));\n\n        MongoClientOptions options = buildOptions(null, externalProperties);\n\n        Assert.assertEquals(WriteConcern.NORMAL, options.getWriteConcern());\n\n        externalProperties = buildExternalProperties(kv(MongoDBConstants.W, \"0\"),\n                kv(MongoDBConstants.W_TIME_OUT, \"1000\"), kv(MongoDBConstants.FSYNC, \"true\"),\n                kv(MongoDBConstants.J, \"false\"));\n\n        options = buildOptions(null, externalProperties);\n\n        WriteConcern wc = options.getWriteConcern();\n        Assert.assertEquals(0, wc.getW());\n        Assert.assertEquals(1000, wc.getWtimeout());\n        Assert.assertEquals(true, wc.getFsync());\n        Assert.assertEquals(false, wc.getJ());\n\n        externalProperties = buildExternalProperties(kv(MongoDBConstants.DB_DECODER_FACTORY,\n                \"com.mongodb.LazyDBDecoder.FACTORY\"));\n\n        options = buildOptions(null, externalProperties);\n\n        Assert.assertEquals(LazyDBDecoder.FACTORY, options.getDbDecoderFactory());\n\n        externalProperties = buildExternalProperties(kv(MongoDBConstants.DB_DECODER_FACTORY,\n                \"com.impetus.kundera.client.mongo.MongoDBConfigurationTest$TestDBDecoderFactory\"));\n\n        options = buildOptions(null, externalProperties);\n\n        Assert.assertEquals(TestDBDecoderFactory.class, options.getDbDecoderFactory().getClass());\n\n        externalProperties = buildExternalProperties(kv(MongoDBConstants.DB_ENCODER_FACTORY,\n                \"com.impetus.kundera.client.mongo.MongoDBConfigurationTest$TestDBEncoderFactory\"));\n\n        options = buildOptions(null, externalProperties);\n\n        Assert.assertEquals(TestDBEncoderFactory.class, options.getDbEncoderFactory().getClass());\n\n        externalProperties = buildExternalProperties(kv(MongoDBConstants.SOCKET_FACTORY,\n                \"com.impetus.kundera.client.mongo.MongoDBConfigurationTest.INSECURE_SSL_SOCKET_FACTORY\"));\n\n        options = buildOptions(null, externalProperties);\n\n        Assert.assertEquals(INSECURE_SSL_SOCKET_FACTORY, options.getSocketFactory());\n\n        externalProperties = buildExternalProperties(kv(MongoDBConstants.SOCKET_FACTORY,\n                \"javax.net.ssl.SSLSocketFactory.getDefault()\"));\n\n        options = buildOptions(null, externalProperties);\n\n        Assert.assertEquals(SSLSocketFactory.getDefault().getClass(), options.getSocketFactory().getClass());\n\n        externalProperties = buildExternalProperties(kv(MongoDBConstants.AUTO_CONNECT_RETRY, \"true\"));\n\n        options = buildOptions(null, externalProperties);\n\n//        Assert.assertTrue(options.isAutoConnectRetry());\n\n        externalProperties = buildExternalProperties(kv(MongoDBConstants.MAX_AUTO_CONNECT_RETRY, \"12\"));\n\n        options = buildOptions(null, externalProperties);\n\n//        Assert.assertEquals(12L, options.getMaxAutoConnectRetryTime());\n\n        externalProperties = buildExternalProperties(kv(MongoDBConstants.CONNECTION_PER_HOST, \"7\"));\n\n        options = buildOptions(null, externalProperties);\n\n        Assert.assertEquals(7, options.getConnectionsPerHost());\n\n        externalProperties = buildExternalProperties(kv(MongoDBConstants.CONNECT_TIME_OUT, \"32\"));\n\n        options = buildOptions(null, externalProperties);\n\n        Assert.assertEquals(32, options.getConnectTimeout());\n\n        externalProperties = buildExternalProperties(kv(MongoDBConstants.MAX_WAIT_TIME, \"41\"));\n\n        options = buildOptions(null, externalProperties);\n\n        Assert.assertEquals(41, options.getMaxWaitTime());\n\n        externalProperties = buildExternalProperties(kv(MongoDBConstants.TABCM, \"3\"));\n\n        options = buildOptions(null, externalProperties);\n\n        Assert.assertEquals(3, options.getThreadsAllowedToBlockForConnectionMultiplier());\n    }\n\n    /**\n     * Builds the options.\n     * \n     * @param clientProperties\n     *            the client properties\n     * @param externalProperties\n     *            the external properties\n     * @return the mongo client options\n     */\n    private MongoClientOptions buildOptions(Properties clientProperties, Map<String, ?> externalProperties)\n    {\n        return new MongoDBClientFactory.PopulateMongoOptions(clientProperties, externalProperties).prepareBuilder()\n                .build();\n    }\n\n    /**\n     * Builds the properties.\n     * \n     * @param keyValuePairs\n     *            the key value pairs\n     * @return the properties\n     */\n    private static Properties buildProperties(final KeyValue... keyValuePairs)\n    {\n        Properties properties = new Properties();\n        for (KeyValue item : keyValuePairs)\n        {\n            properties.put(item.getKey(), item.getValue());\n        }\n        return properties;\n    }\n\n    /**\n     * Builds the external properties.\n     * \n     * @param keyValuePairs\n     *            the key value pairs\n     * @return the map\n     */\n    private static Map<String, String> buildExternalProperties(final KeyValue... keyValuePairs)\n    {\n        Map<String, String> properties = new HashMap<String, String>();\n        for (KeyValue item : keyValuePairs)\n        {\n            properties.put(item.getKey(), item.getValue());\n        }\n        return properties;\n    }\n\n    /**\n     * Kv.\n     * \n     * @param key\n     *            the key\n     * @param value\n     *            the value\n     * @return the key value\n     */\n    private static KeyValue kv(String key, String value)\n    {\n        return new KeyValue(key, value);\n    }\n\n    /**\n     * The Class KeyValue.\n     */\n    private static class KeyValue\n    {\n\n        /** The key. */\n        private final String key;\n\n        /** The value. */\n        private final String value;\n\n        /**\n         * Instantiates a new key value.\n         * \n         * @param key\n         *            the key\n         * @param value\n         *            the value\n         */\n        public KeyValue(final String key, final String value)\n        {\n            this.key = key;\n            this.value = value;\n        }\n\n        /**\n         * Gets the key.\n         * \n         * @return the key\n         */\n        public String getKey()\n        {\n            return key;\n        }\n\n        /**\n         * Gets the value.\n         * \n         * @return the value\n         */\n        public String getValue()\n        {\n            return value;\n        }\n    }\n\n    /**\n     * A factory for creating TestDBDecoder objects.\n     */\n    public static class TestDBDecoderFactory implements DBDecoderFactory\n    {\n\n        /*\n         * (non-Javadoc)\n         * \n         * @see com.mongodb.DBDecoderFactory#create()\n         */\n        @Override\n        public DBDecoder create()\n        {\n            return null; // dummy\n        }\n    }\n\n    /**\n     * A factory for creating TestDBEncoder objects.\n     */\n    public static class TestDBEncoderFactory implements DBEncoderFactory\n    {\n\n        /*\n         * (non-Javadoc)\n         * \n         * @see com.mongodb.DBEncoderFactory#create()\n         */\n        @Override\n        public DBEncoder create()\n        {\n            return null; // dummy\n        }\n    }\n\n    /** The Constant INSECURE_SSL_SOCKET_FACTORY. */\n    public static final SSLSocketFactory INSECURE_SSL_SOCKET_FACTORY;\n\n    static\n    {\n        try\n        {\n            final SSLContext sslContext = SSLContext.getInstance(\"TLS\");\n            sslContext.init(null, new TrustManager[] { new X509TrustManager()\n            {\n                public void checkClientTrusted(final X509Certificate[] x509Certificates, final String s)\n                        throws CertificateException\n                {\n                }\n\n                public void checkServerTrusted(final X509Certificate[] x509Certificates, final String s)\n                        throws CertificateException\n                {\n                }\n\n                public X509Certificate[] getAcceptedIssuers()\n                {\n                    return new X509Certificate[0];\n                }\n            } }, new SecureRandom());\n\n            INSECURE_SSL_SOCKET_FACTORY = sslContext.getSocketFactory();\n        }\n        catch (Exception ex)\n        {\n            throw new AssertionError(\"Unexpected error\", ex);\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/mongo/mappedsuperclass/Ledger.java",
    "content": "package com.impetus.kundera.client.mongo.mappedsuperclass;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\n\n\n@Entity\npublic class Ledger\n{\n    @Id\n    private String ledgerId;\n    \n    @Column\n    private Integer balance;\n\n    @Column\n    private String user;\n    \n    @OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    private Transaction trans;\n    \n    public Ledger()\n    {\n        \n    }\n    \n    public String getLedgerId()\n    {\n        return ledgerId;\n    }\n\n    public void setLedgerId(String ledgerId)\n    {\n        this.ledgerId = ledgerId;\n    }\n\n    \n    public Integer getBalanace()\n    {\n        return balance;\n    }\n\n    public void setBalanace(Integer balance)\n    {\n        this.balance = balance;\n    }\n\n    public String getPayee()\n    {\n        return user;\n    }\n\n    public void setPayee(String user)\n    {\n        this.user = user;\n    }\n    \n    public Transaction getTransaction()\n    {\n        return trans;\n    }\n\n    public void setTransaction(Transaction trans)\n    {\n        this.trans = trans;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/java/com/impetus/kundera/client/mongo/mappedsuperclass/Transaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.mongo.mappedsuperclass;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorColumn;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.client.crud.mappedsuperclass.AbstractTransaction;\n\n\n\n/**\n * @author vivek.mishra\n * Transaction concrete entity\n *\n */\n@Entity\n@Table(name = \"TRNX\")\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@DiscriminatorColumn(name = \"tx_type\")\npublic class Transaction extends AbstractTransaction\n{\n    \n    @Column\n    private String bankIdentifier;\n    \n    @OneToOne(cascade = { CascadeType.ALL },fetch = FetchType.EAGER)\n    private Ledger ledger;\n\n    public String getBankIdentifier()\n    {\n        return bankIdentifier;\n    }\n\n    public void setBankIdentifier(String bankIdentifier)\n    {\n        this.bankIdentifier = bankIdentifier;\n    }\n    \n    public Ledger getLedger()\n    {\n        return ledger;\n    }\n\n    public void setLedger(Ledger ledger)\n    {\n        this.ledger = ledger;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-mongo/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\t<!-- Persistence Units for Twitter application -->\n\n\t<persistence-unit name=\"mongoTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"lucene\" /> -->\n\t\t\t<!-- <property name=\"kundera.client.property\" value=\"kundera-mongo.properties\" \n\t\t\t\t/> -->\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"gfs_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.crud.gfs.GFSUser</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"GFS\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"mongo_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.mongodb.index.Book</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaIndexTest\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"validAuthenticationMongoPu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaAuthTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t\t<property name=\"kundera.username\" value=\"kunderaUser\" />\n\t\t\t<property name=\"kundera.password\" value=\"kunderapassword\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"validAuthenticationMongoPuAdminDb\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"admin\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t\t<property name=\"kundera.username\" value=\"admin\" />\n\t\t\t<property name=\"kundera.password\" value=\"password\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"invalidAuthenticationMongoPu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaAuthTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t\t<property name=\"kundera.username\" value=\"kunderaUser\" />\n\t\t\t<property name=\"kundera.password\" value=\"invalid\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"MongoDataTypeTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaMongoDataType\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<!-- <property name=\"kundera.ddl.auto.prepare\" value=\"create-drop\"/> -->\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"MongoBatchTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaMongoDataType\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<!-- <property name=\"kundera.ddl.auto.prepare\" value=\"create-drop\"/> -->\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t\t<property name=\"kundera.batch.size\" value=\"5\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"mongoSchemaGenerationTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaMongoSchemaGeneration\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create-drop\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaMongoTest.xml\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"mongoShowQueryEnabledPU\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.crud.entities.UserInformation</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"showQueryKeyspace\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create-drop\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t\t<property name=\"kundera.show.query\" value=\"true\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"mongoShowQueryDisabledPU\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.crud.entities.UserInformation</class>\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileHandset</class>\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileManufacturer</class>\n\t\t<class>com.impetus.kundera.client.crud.associations.MobileOperatingSystem</class>\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.Person</class>\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.PersonChild</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"showQueryKeyspace\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create-drop\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"esIndexerTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n<!-- \t\t<class>com.impetus.client.esindexer.PersonESIndexerCassandra</class> -->\n<!-- \t\t<class>com.impetus.client.esindexer.PersonESIndexerCassandraUUID</class> -->\n\t\t<class>com.impetus.kundera.query.Person</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t\t<property name=\"kundera.indexer.class\" value=\"com.impetus.client.es.index.ESIndexer\" />\n\n\t\t</properties>\n\t</persistence-unit>\n\n</persistence>\n"
  },
  {
    "path": "src/kundera-mongo/src/test/resources/META-INF/persistence_2_0.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!-- persistence.xml schema -->\r\n<xsd:schema targetNamespace=\"http://java.sun.com/xml/ns/persistence\" \r\n  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\r\n  xmlns:persistence=\"http://java.sun.com/xml/ns/persistence\"\r\n  elementFormDefault=\"qualified\" \r\n  attributeFormDefault=\"unqualified\" \r\n  version=\"2.0\">\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n      @(#)persistence_2_0.xsd  1.0  October 1 2009\r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n\r\n  Copyright (c) 2008, 2009 Sun Microsystems. All rights reserved. \r\n  \r\n  This program and the accompanying materials are made available under the \r\n  terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 \r\n  which accompanies this distribution. \r\n  The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html\r\n  and the Eclipse Distribution License is available at \r\n  http://www.eclipse.org/org/documents/edl-v10.php.\r\n  \r\n  Contributors:\r\n      Linda DeMichiel - Java Persistence 2.0, Version 2.0 (October 1, 2009)\r\n      Specification available from http://jcp.org/en/jsr/detail?id=317\r\n \r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n   <xsd:annotation>\r\n     <xsd:documentation><![CDATA[\r\n\r\n     This is the XML Schema for the persistence configuration file.\r\n     The file must be named \"META-INF/persistence.xml\" in the \r\n     persistence archive.\r\n\r\n     Persistence configuration files must indicate\r\n     the persistence schema by using the persistence namespace:\r\n\r\n     http://java.sun.com/xml/ns/persistence\r\n\r\n     and indicate the version of the schema by\r\n     using the version element as shown below:\r\n\r\n      <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n        xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n          http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\"\r\n        version=\"2.0\">\r\n          ...\r\n      </persistence>\r\n\r\n    ]]></xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:simpleType name=\"versionType\">\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:pattern value=\"[0-9]+(\\.[0-9]+)*\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:element name=\"persistence\">\r\n    <xsd:complexType>\r\n      <xsd:sequence>\r\n\r\n        <!-- **************************************************** -->\r\n\r\n        <xsd:element name=\"persistence-unit\" \r\n                     minOccurs=\"1\" maxOccurs=\"unbounded\">\r\n          <xsd:complexType>\r\n            <xsd:annotation>\r\n              <xsd:documentation>\r\n\r\n                Configuration of a persistence unit.\r\n\r\n              </xsd:documentation>\r\n            </xsd:annotation>\r\n            <xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"description\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Description of this persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"provider\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Provider class that supplies EntityManagers for this \r\n                    persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of the JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"non-jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of a non-JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"mapping-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    File containing mapping information. Loaded as a resource \r\n                    by the persistence provider.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jar-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Jar file that is to be scanned for managed classes. \r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"class\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Managed class to be included in the persistence unit and\r\n                    to scan for annotations.  It should be annotated \r\n                    with either @Entity, @Embeddable or @MappedSuperclass.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"exclude-unlisted-classes\" type=\"xsd:boolean\" \r\n                           default=\"true\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    When set to true then only listed classes and jars will \r\n                    be scanned for persistent classes, otherwise the \r\n                    enclosing jar or directory will also be scanned. \r\n                    Not applicable to Java SE persistence units.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"shared-cache-mode\" \r\n                           type=\"persistence:persistence-unit-caching-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Defines whether caching is enabled for the \r\n                    persistence unit if caching is supported by the\r\n                    persistence provider. When set to ALL, all entities \r\n                    will be cached. When set to NONE, no entities will\r\n                    be cached. When set to ENABLE_SELECTIVE, only entities\r\n                    specified as cacheable will be cached. When set to\r\n                    DISABLE_SELECTIVE, entities specified as not cacheable\r\n                    will not be cached. When not specified or when set to\r\n                    UNSPECIFIED, provider defaults may apply.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"validation-mode\" \r\n                           type=\"persistence:persistence-unit-validation-mode-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The validation mode to be used for the persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"properties\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    A list of standard and vendor-specific properties \r\n                    and hints.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n                <xsd:complexType>\r\n                  <xsd:sequence>\r\n                    <xsd:element name=\"property\" \r\n                                 minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                      <xsd:annotation>\r\n                        <xsd:documentation>\r\n                          A name-value pair.\r\n                        </xsd:documentation>\r\n                      </xsd:annotation>\r\n                      <xsd:complexType>\r\n                        <xsd:attribute name=\"name\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                        <xsd:attribute name=\"value\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                      </xsd:complexType>\r\n                    </xsd:element>\r\n                  </xsd:sequence>\r\n                </xsd:complexType>\r\n              </xsd:element>\r\n\r\n            </xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Name used in code to reference this persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"transaction-type\" \r\n                           type=\"persistence:persistence-unit-transaction-type\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Type of transactions used by EntityManagers from this \r\n                  persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n          </xsd:complexType>\r\n        </xsd:element>\r\n      </xsd:sequence>\r\n      <xsd:attribute name=\"version\" type=\"persistence:versionType\" \r\n                     fixed=\"2.0\" use=\"required\"/>\r\n    </xsd:complexType>\r\n  </xsd:element>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-transaction-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum PersistenceUnitTransactionType {JTA, RESOURCE_LOCAL};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"JTA\"/>\r\n      <xsd:enumeration value=\"RESOURCE_LOCAL\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-caching-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum SharedCacheMode { ALL, NONE, ENABLE_SELECTIVE, DISABLE_SELECTIVE, UNSPECIFIED};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"ALL\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n      <xsd:enumeration value=\"ENABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"DISABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"UNSPECIFIED\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-validation-mode-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum ValidationMode { AUTO, CALLBACK, NONE};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"AUTO\"/>\r\n      <xsd:enumeration value=\"CALLBACK\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n</xsd:schema>\r\n"
  },
  {
    "path": "src/kundera-mongo/src/test/resources/esindexer.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<indexerProperties>\n\t<nodes>\n\t\t<node>\n\t\t\t<properties>\n\t\t\t\t<property name=\"host\" value=\"localhost\" />\n\t\t\t\t<property name=\"port\" value=\"9300\" />\n\t\t\t</properties>\n\t\t</node>\n\t</nodes>\n</indexerProperties>"
  },
  {
    "path": "src/kundera-mongo/src/test/resources/kundera-mongo.properties",
    "content": "mongodb.servers=192.168.145.67:27017,192.168.145.118:27017,192.168.145.54:27017\nread.preference=primary\nsocket.timeout=1000000"
  },
  {
    "path": "src/kundera-mongo/src/test/resources/kunderaMongoTest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>mongo</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"read.preference\" value=\"primary\"></property>\n\t\t\t\t\t<property name=\"socket.timeout\" value=\"100000\"></property>\n\t\t\t\t</properties>\n\t\t\t\t<servers>\n\t\t\t\t\t<server>\n\t\t\t\t\t\t<host>localhost\n\t\t\t\t\t\t</host>\n\t\t\t\t\t\t<port>27017</port>\n\t\t\t\t\t</server>\n\t\t\t\t</servers>\n\t\t\t</connection>\n\t\t\t<schemas>\n\t\t\t\t<schema>\n\t\t\t\t\t<name>KunderaMongoSchemaGeneration</name>\n\t\t\t\t\t<tables>\n\t\t\t\t\t\t<table>\n\t\t\t\t\t\t\t<name>MongoDBCappedEntity</name>\n\t\t\t\t\t\t\t<properties>\n\t\t\t\t\t\t\t\t<property name=\"capped\" value=\"true\"></property>\n\t\t\t\t\t\t\t\t<property name=\"size\" value=\"10240\"></property>\n\t\t\t\t\t\t\t\t<property name=\"max\" value=\"10\"></property>\n\t\t\t\t\t\t\t</properties>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</tables>\n\t\t\t\t</schema>\n\t\t\t</schemas>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "src/kundera-mongo/src/test/resources/log4j.properties",
    "content": "log4j.rootLogger=WARN, DRFA, CONSOLE\r\n\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n"
  },
  {
    "path": "src/kundera-neo4j/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<groupId>com.impetus</groupId>\n\t\t<artifactId>kundera</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-neo4j</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-neo4j</name>\n\t<url>http://maven.apache.org</url>\n\n\t<!-- <repositories> <repository> <id>neo4j-release-repository</id> <name>Neo4j \n\t\tMaven 2 release repository</name> <url>http://m2.neo4j.org/releases</url> \n\t\t<releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> \n\t\t</snapshots> </repository> <repository> <id>neo4j-snapshot-repository</id> \n\t\t<name>Neo4j Maven 2 snapshot repository</name> <url>http://m2.neo4j.org/snapshots</url> \n\t\t<snapshots> <enabled>true</enabled> </snapshots> <releases> <enabled>false</enabled> \n\t\t</releases> </repository> </repositories> -->\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<!-- Kundera Dependencies -->\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.apache.lucene</groupId>\n\t\t\t<artifactId>lucene-core</artifactId>\n\t\t\t<!-- <version>3.5.0</version> -->\n\t\t\t<version>3.5.0</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.lucene</groupId>\n\t\t\t<artifactId>lucene-queryparser</artifactId>\n\t\t\t<version>3.5.0</version>\n\t\t\t<scope>compile</scope>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<artifactId>jakarta-regexp</artifactId>\n\t\t\t\t\t<groupId>jakarta-regexp</groupId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t\t<!-- Neo4J Libraries -->\n\t\t<dependency>\n\t\t\t<groupId>org.neo4j</groupId>\n\t\t\t<artifactId>neo4j</artifactId>\n\t\t\t<version>1.8.1</version>\n\t\t</dependency>\n\t\t<!-- Jersey - REST Libraries -->\n\t\t<dependency>\n\t\t\t<groupId>com.sun.jersey</groupId>\n\t\t\t<artifactId>jersey-client</artifactId>\n\t\t\t<version>1.12</version>\n\t\t</dependency>\n\t</dependencies>\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<!-- <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> \n\t\t\t\t<configuration> The destination file for the code coverage report has to \n\t\t\t\tbe set to the same value in the parent pom and in each module pom. Then JaCoCo \n\t\t\t\twill add up information in the same report, so that, it will give the cross-module \n\t\t\t\tcode coverage. <destFile>${project.basedir}/../target/jacoco-it.exec</destFile> \n\t\t\t\t</configuration> <executions> <execution> <id>post-test</id> <configuration> \n\t\t\t\t<skip>true</skip> </configuration> </execution> </executions> </plugin> -->\n\n\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/GraphEntityMapper.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j;\n\nimport java.lang.reflect.Field;\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.StringTokenizer;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.neo4j.graphdb.GraphDatabaseService;\nimport org.neo4j.graphdb.Node;\nimport org.neo4j.graphdb.NotFoundException;\nimport org.neo4j.graphdb.Relationship;\nimport org.neo4j.graphdb.index.Index;\nimport org.neo4j.graphdb.index.IndexHits;\nimport org.neo4j.graphdb.index.ReadableIndex;\nimport org.neo4j.graphdb.index.UniqueFactory;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.neo4j.index.Neo4JIndexManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * Responsible for converting Neo4J graph (nodes+relationships) into JPA\n * entities and vice versa\n * \n * @author amresh.singh\n */\npublic final class GraphEntityMapper\n{\n    /** Separator between constituents of composite key */\n    private static final String COMPOSITE_KEY_SEPARATOR = \"$CKS$\";\n\n    private static final String PROXY_NODE_TYPE_KEY = \"$NODE_TYPE$\";\n\n    private static final String PROXY_NODE_VALUE = \"$PROXY_NODE$\";\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(GraphEntityMapper.class);\n\n    private Neo4JIndexManager indexer;\n\n    private KunderaMetadata kunderaMetadata;\n\n    public GraphEntityMapper(Neo4JIndexManager indexer, final KunderaMetadata kunderaMetadata)\n    {\n        this.indexer = indexer;\n        this.kunderaMetadata = kunderaMetadata;\n    }\n\n    /**\n     * Fetches(and converts) {@link Node} instance from Entity object If it's a\n     * update operation, node is searched and attributes populated Otherwise\n     * Node is created into database (replacing any existing node) with\n     * attributes populated\n     * \n     * @param id\n     * \n     */\n    public Node getNodeFromEntity(Object entity, Object key, GraphDatabaseService graphDb, EntityMetadata m,\n            boolean isUpdate)\n    {\n\n        // Construct top level node first, making sure unique ID in the index\n        Node node = null;\n        if (!isUpdate)\n        {\n            node = getOrCreateNodeWithUniqueFactory(entity, key, m, graphDb);\n        }\n        else\n        {\n\n            node = searchNode(key, m, graphDb, true);\n        }\n\n        if (node != null)\n        {\n            populateNodeProperties(entity, m, node);\n        }\n\n        return node;\n    }\n\n    /**\n     * Create \"Proxy\" nodes into Neo4J. Proxy nodes are defined as nodes in\n     * Neo4J that refer to a record in some other database. They cater to\n     * polyglot persistence cases.\n     */\n    public Node createProxyNode(Object sourceNodeId, Object targetNodeId, GraphDatabaseService graphDb,\n            EntityMetadata sourceEntityMetadata, EntityMetadata targetEntityMetadata)\n    {\n\n        String sourceNodeIdColumnName = ((AbstractAttribute) sourceEntityMetadata.getIdAttribute()).getJPAColumnName();\n        String targetNodeIdColumnName = ((AbstractAttribute) targetEntityMetadata.getIdAttribute()).getJPAColumnName();\n\n        Node node = graphDb.createNode();\n        node.setProperty(PROXY_NODE_TYPE_KEY, PROXY_NODE_VALUE);\n        node.setProperty(sourceNodeIdColumnName, sourceNodeId);\n        node.setProperty(targetNodeIdColumnName, targetNodeId);\n        return node;\n    }\n\n    /**\n     * \n     * Converts a {@link Node} instance to entity object\n     */\n    public Object getEntityFromNode(Node node, EntityMetadata m)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n        // Iterate over, entity attributes\n        Set<Attribute> attributes = entityType.getSingularAttributes();\n\n        Object entity = null;\n\n        try\n        {\n            // entity = m.getEntityClazz().newInstance();\n\n            for (Attribute attribute : attributes)\n            {\n                Field field = (Field) attribute.getJavaMember();\n                String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n\n                // Set Entity level properties\n                if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())\n                        && m.getIdAttribute().getJavaType().equals(field.getType()))\n                {\n                    Object idValue = deserializeIdAttributeValue(m, (String) node.getProperty(columnName));\n                    if (idValue != null)\n                    {\n                        entity = initialize(m, entity);\n                        PropertyAccessorHelper.set(entity, field, idValue);\n                    }\n                }\n                else if (!attribute.isCollection() && !attribute.isAssociation()\n                        && !((AbstractAttribute) m.getIdAttribute()).getJPAColumnName().equals(columnName))\n                {\n                    Object columnValue = node.getProperty(columnName, null);\n                    if (columnValue != null)\n                    {\n                        entity = initialize(m, entity);\n                        PropertyAccessorHelper.set(entity, field, fromNeo4JObject(columnValue, field));\n                    }\n                }\n            }\n\n            if (entity != null && !metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n            {\n                Object rowKey = node.getProperty(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName());\n                if (rowKey != null)\n                {\n                    PropertyAccessorHelper.setId(entity, m,\n                            fromNeo4JObject(rowKey, (Field) m.getIdAttribute().getJavaMember()));\n                }\n            }\n        }\n        catch (NotFoundException e)\n        {\n            log.info(e.getMessage());\n            return null;\n        }\n\n        return entity;\n    }\n\n    /**\n     * \n     * Converts a {@link Relationship} object to corresponding entity object\n     */\n    public Object getEntityFromRelationship(Relationship relationship, EntityMetadata topLevelEntityMetadata,\n            Relation relation)\n    {\n        EntityMetadata relationshipEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                relation.getMapKeyJoinClass());\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                relationshipEntityMetadata.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(relationshipEntityMetadata.getEntityClazz());\n\n        // Iterate over, entity attributes\n        Set<Attribute> attributes = entityType.getSingularAttributes();\n\n        Object entity = null;\n\n        try\n        {\n            // entity =\n            // relationshipEntityMetadata.getEntityClazz().newInstance();\n\n            for (Attribute attribute : attributes)\n            {\n                Field field = (Field) attribute.getJavaMember();\n                String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n\n                // Set Entity level properties\n                if (metaModel.isEmbeddable(relationshipEntityMetadata.getIdAttribute().getBindableJavaType())\n                        && relationshipEntityMetadata.getIdAttribute().getJavaType().equals(field.getType()))\n                {\n                    Object idValue = deserializeIdAttributeValue(relationshipEntityMetadata,\n                            (String) relationship.getProperty(columnName));\n                    if (idValue != null)\n                    {\n                        entity = initialize(relationshipEntityMetadata, entity);\n                        PropertyAccessorHelper.set(entity, field, idValue);\n                    }\n                }\n                else if (!attribute.isCollection() && !attribute.isAssociation()\n                        && !field.getType().equals(topLevelEntityMetadata.getEntityClazz())\n                        && !field.getType().equals(relation.getTargetEntity()))\n                {\n                    Object value = relationship.getProperty(columnName, null);\n                    if (value != null)\n                    {\n                        entity = initialize(relationshipEntityMetadata, entity);\n                        PropertyAccessorHelper.set(entity, field, fromNeo4JObject(value, field));\n                    }\n                }\n            }\n\n            if (entity != null\n                    && !metaModel.isEmbeddable(relationshipEntityMetadata.getIdAttribute().getBindableJavaType()))\n            {\n                Object rowKey = relationship.getProperty(((AbstractAttribute) relationshipEntityMetadata\n                        .getIdAttribute()).getJPAColumnName());\n                if (rowKey != null)\n                {\n                    PropertyAccessorHelper\n                            .setId(entity,\n                                    relationshipEntityMetadata,\n                                    fromNeo4JObject(rowKey, (Field) relationshipEntityMetadata.getIdAttribute()\n                                            .getJavaMember()));\n                }\n            }\n        }\n        catch (NotFoundException e)\n        {\n            log.info(e.getMessage());\n            return null;\n        }\n\n        return entity;\n    }\n\n    /**\n     * Creates a Map containing all properties (and their values) for a given\n     * entity\n     * \n     * @param entity\n     * @param m\n     * @return\n     */\n    public Map<String, Object> createNodeProperties(Object entity, EntityMetadata m)\n    {\n        Map<String, Object> props = new HashMap<String, Object>();\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n        // Iterate over entity attributes\n        Set<Attribute> attributes = entityType.getSingularAttributes();\n        for (Attribute attribute : attributes)\n        {\n            Field field = (Field) attribute.getJavaMember();\n\n            // Set Node level properties\n            if (!attribute.isCollection() && !attribute.isAssociation())\n            {\n\n                String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                Object value = PropertyAccessorHelper.getObject(entity, field);\n                if (value != null)\n                {\n                    props.put(columnName, toNeo4JProperty(value));\n                }\n            }\n        }\n        return props;\n    }\n\n    /**\n     * Populates Node properties from Entity object\n     * \n     * @param entity\n     * @param m\n     * @param node\n     */\n    private void populateNodeProperties(Object entity, EntityMetadata m, Node node)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n        // Iterate over entity attributes\n        Set<Attribute> attributes = entityType.getSingularAttributes();\n        for (Attribute attribute : attributes)\n        {\n            Field field = (Field) attribute.getJavaMember();\n\n            // Set Node level properties\n            if (!attribute.isCollection() && !attribute.isAssociation() && !((SingularAttribute) attribute).isId())\n            {\n                String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                Object value = PropertyAccessorHelper.getObject(entity, field);\n                if (value != null)\n                {\n                    node.setProperty(columnName, toNeo4JProperty(value));\n                }\n            }\n        }\n    }\n\n    /**\n     * Populates a {@link Relationship} with attributes of a given relationship\n     * entity object <code>relationshipObj</code>\n     * \n     * @param entityMetadata\n     * @param targetNodeMetadata\n     * @param relationship\n     * @param relationshipObj\n     */\n    public void populateRelationshipProperties(EntityMetadata entityMetadata, EntityMetadata targetNodeMetadata,\n            Relationship relationship, Object relationshipObj)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(relationshipObj.getClass());\n\n        Set<Attribute> attributes = entityType.getSingularAttributes();\n        for (Attribute attribute : attributes)\n        {\n            Field f = (Field) attribute.getJavaMember();\n            if (!f.getType().equals(entityMetadata.getEntityClazz())\n                    && !f.getType().equals(targetNodeMetadata.getEntityClazz()))\n            {\n                EntityMetadata relMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                        relationshipObj.getClass());\n                String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                if (metaModel.isEmbeddable(relMetadata.getIdAttribute().getBindableJavaType())\n                        && ((SingularAttribute) attribute).isId())\n                {\n                    // Populate Embedded attribute value into relationship\n                    Object id = PropertyAccessorHelper.getId(relationshipObj, relMetadata);\n                    Object serializedIdValue = serializeIdAttributeValue(relMetadata, metaModel, id);\n                    relationship.setProperty(columnName, serializedIdValue);\n\n                    // Populate attributes of embedded fields into relationship\n                    Set<Attribute> embeddableAttributes = metaModel.embeddable(\n                            relMetadata.getIdAttribute().getBindableJavaType()).getSingularAttributes();\n                    for (Attribute embeddableAttribute : embeddableAttributes)\n                    {\n                        String embeddedColumn = ((AbstractAttribute) embeddableAttribute).getJPAColumnName();\n                        if (embeddedColumn == null)\n                            embeddedColumn = embeddableAttribute.getName();\n                        Object value = PropertyAccessorHelper\n                                .getObject(id, (Field) embeddableAttribute.getJavaMember());\n\n                        if (value != null)\n                            relationship.setProperty(embeddedColumn, value);\n                    }\n                }\n                else\n                {\n                    Object value = PropertyAccessorHelper.getObject(relationshipObj, f);\n                    relationship.setProperty(columnName, toNeo4JProperty(value));\n                }\n\n            }\n        }\n\n    }\n\n    /**\n     * Creates a Map containing all properties (and their values) for a given\n     * relationship entity\n     * \n     * @param entityMetadata\n     * @param targetEntityMetadata\n     * @param relationshipProperties\n     * @param relationshipEntity\n     */\n    public Map<String, Object> createRelationshipProperties(EntityMetadata entityMetadata,\n            EntityMetadata targetEntityMetadata, Object relationshipEntity)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(relationshipEntity.getClass());\n        Map<String, Object> relationshipProperties = new HashMap<String, Object>();\n\n        Set<Attribute> attributes = entityType.getSingularAttributes();\n        for (Attribute attribute : attributes)\n        {\n            Field f = (Field) attribute.getJavaMember();\n            if (!f.getType().equals(entityMetadata.getEntityClazz())\n                    && !f.getType().equals(targetEntityMetadata.getEntityClazz()))\n            {\n                String relPropertyName = ((AbstractAttribute) attribute).getJPAColumnName();\n                Object value = PropertyAccessorHelper.getObject(relationshipEntity, f);\n                relationshipProperties.put(relPropertyName, toNeo4JProperty(value));\n            }\n        }\n        return relationshipProperties;\n    }\n\n    /**\n     * \n     * Gets (if available) or creates a node for the given entity\n     */\n    private Node getOrCreateNodeWithUniqueFactory(final Object entity, final Object id, final EntityMetadata m,\n            GraphDatabaseService graphDb)\n    {\n        final String idColumnName = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n        final MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        final String idUniqueValue = serializeIdAttributeValue(m, metaModel, id);\n\n        UniqueFactory<Node> factory = new UniqueFactory.UniqueNodeFactory(graphDb, m.getIndexName())\n        {\n            /**\n             * Initialize ID attribute\n             */\n            @Override\n            protected void initialize(Node created, Map<String, Object> properties)\n            {\n                // Set Embeddable ID attribute\n                if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n                {\n                    // Populate embedded field value in serialized format\n                    created.setProperty(idColumnName, idUniqueValue);\n\n                    // Populated all other attributes of embedded into this node\n                    Set<Attribute> embeddableAttributes = metaModel\n                            .embeddable(m.getIdAttribute().getBindableJavaType()).getSingularAttributes();\n                    for (Attribute attribute : embeddableAttributes)\n                    {\n                        String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                        if (columnName == null)\n                            columnName = attribute.getName();\n                        Object value = PropertyAccessorHelper.getObject(id, (Field) attribute.getJavaMember());\n\n                        if (value != null)\n                            created.setProperty(columnName, value);\n                    }\n                }\n                else\n                {\n                    created.setProperty(idColumnName, properties.get(idColumnName));\n                }\n\n            }\n        };\n\n        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n        {\n            return factory.getOrCreate(idColumnName, idUniqueValue);\n        }\n        else\n        {\n            return factory.getOrCreate(idColumnName, id);\n        }\n\n    }\n\n    /**\n     * Prepares ID column value for embedded IDs by combining its attributes\n     * \n     * @param m\n     * @param id\n     * @param metaModel\n     * @return\n     */\n    private String serializeIdAttributeValue(final EntityMetadata m, MetamodelImpl metaModel, Object id)\n    {\n        if (!metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n        {\n            return null;\n        }\n\n        Class<?> embeddableClass = m.getIdAttribute().getBindableJavaType();\n        String idUniqueValue = \"\";\n\n        for (Field embeddedField : embeddableClass.getDeclaredFields())\n        {\n            if (!ReflectUtils.isTransientOrStatic(embeddedField))\n            {\n\n                Object value = PropertyAccessorHelper.getObject(id, embeddedField);\n                if (value != null && !StringUtils.isEmpty(value.toString()))\n                    idUniqueValue = idUniqueValue + value + COMPOSITE_KEY_SEPARATOR;\n            }\n        }\n\n        if (idUniqueValue.endsWith(COMPOSITE_KEY_SEPARATOR))\n            idUniqueValue = idUniqueValue.substring(0, idUniqueValue.length() - COMPOSITE_KEY_SEPARATOR.length());\n        return idUniqueValue;\n    }\n\n    /**\n     * Prepares Embedded ID field from value prepared via\n     * serializeIdAttributeValue method.\n     */\n    private Object deserializeIdAttributeValue(final EntityMetadata m, String idValue)\n    {\n        if (idValue == null)\n        {\n            return null;\n        }\n        Class<?> embeddableClass = m.getIdAttribute().getBindableJavaType();\n        Object embeddedObject = embeddedObject = KunderaCoreUtils.createNewInstance(embeddableClass);\n        List<String> tokens = new ArrayList<String>();\n        StringTokenizer st = new StringTokenizer((String) idValue, COMPOSITE_KEY_SEPARATOR);\n        while (st.hasMoreTokens())\n        {\n            tokens.add((String) st.nextElement());\n        }\n\n        int count = 0;\n        for (Field embeddedField : embeddableClass.getDeclaredFields())\n        {\n            if (!ReflectUtils.isTransientOrStatic(embeddedField))\n            {\n                if (count < tokens.size())\n                {\n                    String value = tokens.get(count++);\n                    PropertyAccessorHelper.set(embeddedObject, embeddedField, value);\n                }\n            }\n        }\n        return embeddedObject;\n    }\n\n    /**\n     * Gets (if available) or creates a relationship for the given entity\n     */\n    private Relationship getOrCreateRelationshipWithUniqueFactory(Object entity, EntityMetadata m,\n            GraphDatabaseService graphDb)\n    {\n        Object id = PropertyAccessorHelper.getObject(entity, (Field) m.getIdAttribute().getJavaMember());\n        final String idFieldName = m.getIdAttribute().getName();\n\n        UniqueFactory<Relationship> factory = new UniqueFactory.UniqueRelationshipFactory(graphDb, m.getIndexName())\n        {\n\n            @Override\n            protected Relationship create(Map<String, Object> paramMap)\n            {\n                return null;\n            }\n\n            @Override\n            protected void initialize(Relationship relationship, Map<String, Object> properties)\n            {\n                relationship.setProperty(idFieldName, properties.get(idFieldName));\n            }\n        };\n\n        return factory.getOrCreate(idFieldName, id);\n    }\n\n    /**\n     * Converts a given field value to an object that is Neo4J compatible\n     * \n     * @param source\n     * @return\n     */\n    public Object toNeo4JProperty(Object source)\n    {\n        if (source instanceof BigDecimal || source instanceof BigInteger)\n        {\n            return source.toString();\n        }\n        else if ((source instanceof Calendar) || (source instanceof GregorianCalendar))\n        {\n            return PropertyAccessorHelper.fromSourceToTargetClass(String.class, Date.class,\n                    ((Calendar) source).getTime());\n        }\n        if (source instanceof Date)\n        {\n            Class<?> sourceClass = source.getClass();\n            return PropertyAccessorHelper.fromSourceToTargetClass(String.class, sourceClass, source);\n        }\n        return source;\n    }\n\n    /**\n     * Converts a property stored in Neo4J (nodes or relationship) to\n     * corresponding entity field value\n     */\n    public Object fromNeo4JObject(Object source, Field field)\n    {\n        Class<?> targetClass = field.getType();\n\n        if (targetClass.isAssignableFrom(BigDecimal.class) || targetClass.isAssignableFrom(BigInteger.class))\n        {\n            return PropertyAccessorHelper.fromSourceToTargetClass(field.getType(), source.getClass(), source);\n        }\n        else if (targetClass.isAssignableFrom(Calendar.class) || targetClass.isAssignableFrom(GregorianCalendar.class))\n        {\n            Date d = (Date) PropertyAccessorHelper.fromSourceToTargetClass(Date.class, source.getClass(), source);\n            Calendar cal = Calendar.getInstance();\n            cal.setTime(d);\n            return cal;\n        }\n        else if (targetClass.isAssignableFrom(Date.class))\n        {\n            return PropertyAccessorHelper.fromSourceToTargetClass(field.getType(), source.getClass(), source);\n        }\n        else\n        {\n            return source;\n        }\n\n    }\n\n    /**\n     * Searches a node from the database for a given key\n     */\n    public Node searchNode(Object key, EntityMetadata m, GraphDatabaseService graphDb, boolean skipProxy)\n    {\n        Node node = null;\n        String idColumnName = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n\n        final MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n        {\n            key = serializeIdAttributeValue(m, metaModel, key);\n        }\n\n        if (indexer.isNodeAutoIndexingEnabled(graphDb))\n        {\n            // Get the Node auto index\n            ReadableIndex<Node> autoNodeIndex = graphDb.index().getNodeAutoIndexer().getAutoIndex();\n            IndexHits<Node> nodesFound = autoNodeIndex.get(idColumnName, key);\n            node = getMatchingNodeFromIndexHits(nodesFound, skipProxy);\n        }\n        else\n        {\n            // Searching within manually created indexes\n            Index<Node> nodeIndex = graphDb.index().forNodes(m.getIndexName());\n            IndexHits<Node> nodesFound = nodeIndex.get(idColumnName, key);\n            node = getMatchingNodeFromIndexHits(nodesFound, skipProxy);\n        }\n\n        return node;\n    }\n\n    /**\n     * Fetches first Non-proxy node from Index Hits\n     * \n     * @param skipProxy\n     * @param nodesFound\n     * @return\n     */\n    protected Node getMatchingNodeFromIndexHits(IndexHits<Node> nodesFound, boolean skipProxy)\n    {\n        Node node = null;\n        try\n        {\n            if (nodesFound == null || nodesFound.size() == 0 || !nodesFound.hasNext())\n            {\n                return null;\n            }\n            else\n            {\n                if (skipProxy)\n                    node = getNonProxyNode(nodesFound);\n                else\n                    node = nodesFound.next();\n            }\n        }\n        finally\n        {\n            nodesFound.close();\n        }\n        return node;\n    }\n\n    /**\n     * Fetches Non-proxy nodes from index hits\n     */\n    private Node getNonProxyNode(IndexHits<Node> nodesFound)\n    {\n        Node node = null;\n        if (nodesFound.hasNext())\n        {\n            node = nodesFound.next();\n        }\n        else\n        {\n            return null;\n        }\n\n        try\n        {\n            Object proxyNodeProperty = node.getProperty(PROXY_NODE_TYPE_KEY);\n        }\n        catch (NotFoundException e)\n        {\n            return node;\n        }\n        catch (IllegalStateException e)\n        {\n            return node;\n        }\n        return getNonProxyNode(nodesFound);\n    }\n\n    /**\n     * \n     * @param m\n     * @param entity\n     * @param id\n     * @return\n     */\n    private Object initialize(EntityMetadata m, Object entity)\n    {\n        try\n        {\n            if (entity == null)\n            {\n                entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());\n            }\n\n            return entity;\n        }\n        catch (Exception e)\n        {\n            throw new PersistenceException(\"Error occured while instantiating entity, Caused by : \", e);\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/Neo4JClient.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport javax.persistence.GenerationType;\nimport javax.persistence.PersistenceException;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.neo4j.graphdb.Direction;\nimport org.neo4j.graphdb.DynamicRelationshipType;\nimport org.neo4j.graphdb.GraphDatabaseService;\nimport org.neo4j.graphdb.Node;\nimport org.neo4j.graphdb.NotInTransactionException;\nimport org.neo4j.graphdb.Relationship;\nimport org.neo4j.graphdb.index.Index;\nimport org.neo4j.graphdb.index.IndexHits;\nimport org.neo4j.graphdb.index.ReadableIndex;\nimport org.neo4j.unsafe.batchinsert.BatchInserter;\nimport org.neo4j.unsafe.batchinsert.BatchInserterIndexProvider;\nimport org.neo4j.unsafe.batchinsert.BatchInserters;\nimport org.neo4j.unsafe.batchinsert.LuceneBatchInserterIndexProvider;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.neo4j.config.Neo4JPropertyReader;\nimport com.impetus.client.neo4j.config.Neo4JPropertyReader.Neo4JSchemaMetadata;\nimport com.impetus.client.neo4j.index.Neo4JIndexManager;\nimport com.impetus.client.neo4j.query.Neo4JQuery;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.lifecycle.states.RemovedState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.KunderaTransactionException;\nimport com.impetus.kundera.persistence.TransactionBinder;\nimport com.impetus.kundera.persistence.TransactionResource;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * Implementation of {@link Client} using Neo4J Native Java driver (see Embedded\n * Java driver at http://www.neo4j.org/develop/drivers)\n * \n * @author amresh.singh\n */\npublic class Neo4JClient extends Neo4JClientBase implements Client<Neo4JQuery>, TransactionBinder, Batcher\n{\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(Neo4JClient.class);\n\n    /**\n     * Reference to Neo4J client factory.\n     */\n    private Neo4JClientFactory factory;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /** The mapper. */\n    private GraphEntityMapper mapper;\n\n    /** The resource. */\n    private TransactionResource resource;\n\n    /** The indexer. */\n    private Neo4JIndexManager indexer;\n\n    /**\n     * Instantiates a new neo4 j client.\n     * \n     * @param factory\n     *            the factory\n     * @param puProperties\n     *            the pu properties\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    Neo4JClient(final Neo4JClientFactory factory, Map<String, Object> puProperties, String persistenceUnit,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata, puProperties, persistenceUnit);\n        this.factory = factory;\n        reader = new Neo4JEntityReader(kunderaMetadata);\n        indexer = new Neo4JIndexManager();\n        mapper = new GraphEntityMapper(indexer, kunderaMetadata);\n        populateBatchSize(persistenceUnit, puProperties);\n        this.clientMetadata = factory.getClientMetadata();\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientPropertiesSetter#populateClientProperties\n     * (com.impetus.kundera.client.Client, java.util.Map)\n     */\n    @Override\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        // All client properties currently are those that are specified in\n        // neo4j.properties (or custom XML configuration file according to\n        // Kundera format)\n        // No custom property currently defined by Kundera, leaving empty\n        if (log.isDebugEnabled())\n            log.debug(\"No custom property to set for Neo4J\");\n        for (String key : properties.keySet())\n        {\n            Object value = properties.get(key);\n            if (key.equals(PersistenceProperties.KUNDERA_BATCH_SIZE) && value instanceof Integer)\n            {\n                Integer batchSize = (Integer) value;\n                ((Neo4JClient) client).setBatchSize(batchSize);\n            }\n        }\n    }\n\n    /**\n     * Finds an entity from graph database.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param key\n     *            the key\n     * @return the object\n     */\n    @Override\n    public Object find(Class entityClass, Object key)\n    {\n        GraphDatabaseService graphDb = null;\n        if (resource != null)\n        {\n            graphDb = getConnection();\n        }\n\n        if (graphDb == null)\n            graphDb = factory.getConnection();\n\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n\n        Object entity = null;\n        Node node = mapper.searchNode(key, m, graphDb, true);\n\n        if (node != null && !((Neo4JTransaction) resource).containsNodeId(node.getId()))\n\n        {\n            entity = getEntityWithAssociationFromNode(m, node);\n        }\n\n        return entity;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.String[], java.lang.Object[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)\n    {\n        List entities = new ArrayList<E>();\n        for (Object key : keys)\n        {\n            entities.add(find(entityClass, key));\n        }\n        return entities;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n        throw new UnsupportedOperationException(\"Embedded attributes not supported in Neo4J as of now\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    @Override\n    public void close()\n    {\n        // Closure is internally handled by Neo4J\n    }\n\n    /**\n     * Deletes an entity from database.\n     * \n     * @param entity\n     *            the entity\n     * @param key\n     *            the key\n     */\n    @Override\n    public void delete(Object entity, Object key)\n    {\n        // All Modifying Neo4J operations must be executed within a transaction\n        checkActiveTransaction();\n\n        GraphDatabaseService graphDb = getConnection();\n\n        // Find Node for this particular entity\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        Node node = mapper.searchNode(key, m, graphDb, true);\n        if (node != null)\n        {\n            // Remove this particular node, if not already deleted in current\n            // transaction\n            if (!((Neo4JTransaction) resource).containsNodeId(node.getId()))\n            {\n                node.delete();\n\n                // Manually remove node index if applicable\n                indexer.deleteNodeIndex(m, graphDb, node);\n\n                // Remove all relationship edges attached to this node\n                // (otherwise an\n                // exception is thrown)\n                for (Relationship relationship : node.getRelationships())\n                {\n                    relationship.delete();\n\n                    // Manually remove relationship index if applicable\n                    indexer.deleteRelationshipIndex(m, graphDb, relationship);\n                }\n\n                ((Neo4JTransaction) resource).addNodeId(node.getId());\n            }\n        }\n        else\n        {\n            if (log.isDebugEnabled())\n                log.debug(\"Entity to be deleted doesn't exist in graph. Doing nothing\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera\n     * .persistence.context.jointable.JoinTableData)\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        throw new UnsupportedOperationException(\"Join Table not supported for Neo4J as of now\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,\n            Object pKeyColumnValue, Class columnJavaType)\n    {\n        throw new UnsupportedOperationException(\"Operation not supported for Neo4J\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n        throw new UnsupportedOperationException(\"Operation not supported for Neo4J\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    @Override\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n        throw new UnsupportedOperationException(\"Operation not supported for Neo4J\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n        throw new UnsupportedOperationException(\"Operation not supported for Neo4J\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<Neo4JQuery> getQueryImplementor()\n    {\n        return Neo4JQuery.class;\n    }\n\n    /**\n     * Writes an entity to database.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @param id\n     *            the id\n     * @param rlHolders\n     *            the rl holders\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n        if (log.isDebugEnabled())\n            log.debug(\"Persisting \" + entity);\n\n        // All Modifying Neo4J operations must be executed within a transaction\n        checkActiveTransaction();\n\n        GraphDatabaseService graphDb = getConnection();\n\n        try\n        {\n\n            // Top level node\n            Node node = mapper.getNodeFromEntity(entity, id, graphDb, entityMetadata, isUpdate);\n\n            if (node != null)\n            {\n                MetamodelImpl metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                        getPersistenceUnit());\n\n                ((Neo4JTransaction) resource).addProcessedNode(id, node);\n\n                if (!rlHolders.isEmpty())\n                {\n                    for (RelationHolder rh : rlHolders)\n                    {\n                        // Search Node (to be connected to ) in Neo4J graph\n                        EntityMetadata targetNodeMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                                rh.getRelationValue().getClass());\n                        Object targetNodeKey = PropertyAccessorHelper.getId(rh.getRelationValue(), targetNodeMetadata);\n                        // Node targetNode = mapper.searchNode(targetNodeKey,\n                        // targetNodeMetadata, graphDb);\n\n                        Node targetNode = null; // Target node connected through\n                                                // relationship\n\n                        /**\n                         * If Relationship is with an entity in Neo4J, Target\n                         * node must already have been created Get a handle of\n                         * it from processed nodes and add edges to it. Else, if\n                         * relationship is with an entity in a database other\n                         * than Neo4J, create a \"Proxy Node\" that points to a\n                         * row in other database. This proxy node contains key\n                         * equal to primary key of row in other database.\n                         * */\n\n                        if (isEntityForNeo4J(targetNodeMetadata))\n                        {\n                            targetNode = ((Neo4JTransaction) resource).getProcessedNode(targetNodeKey);\n                        }\n                        else\n                        {\n                            // Create Proxy nodes for insert requests\n                            if (!isUpdate)\n                            {\n                                targetNode = mapper.createProxyNode(id, targetNodeKey, graphDb, entityMetadata,\n                                        targetNodeMetadata);\n                            }\n                        }\n\n                        if (targetNode != null)\n                        {\n                            // Join this node (source node) to target node via\n                            // relationship\n                            DynamicRelationshipType relType = DynamicRelationshipType.withName(rh.getRelationName());\n                            Relationship relationship = node.createRelationshipTo(targetNode, relType);\n\n                            // Populate relationship's own properties into it\n                            Object relationshipObj = rh.getRelationVia();\n                            if (relationshipObj != null)\n                            {\n                                mapper.populateRelationshipProperties(entityMetadata, targetNodeMetadata, relationship,\n                                        relationshipObj);\n\n                                // After relationship creation, manually index\n                                // it if desired\n                                EntityMetadata relationMetadata = KunderaMetadataManager.getEntityMetadata(\n                                        kunderaMetadata, relationshipObj.getClass());\n                                if (!isUpdate)\n                                {\n                                    indexer.indexRelationship(relationMetadata, graphDb, relationship, metamodel);\n                                }\n                                else\n                                {\n                                    indexer.updateRelationshipIndex(relationMetadata, graphDb, relationship, metamodel);\n                                }\n\n                            }\n                        }\n\n                    }\n                }\n\n                // After node creation, manually index this node, if desired\n                if (!isUpdate)\n                {\n                    indexer.indexNode(entityMetadata, graphDb, node, metamodel);\n                }\n                else\n                {\n                    indexer.updateNodeIndex(entityMetadata, graphDb, node, metamodel);\n                }\n            }\n\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while persisting entity \" + entity + \", Caused by: \", e);\n            throw new PersistenceException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.api.Batcher#addBatch(com.impetus.kundera\n     * .graph.Node)\n     */\n    @Override\n    public void addBatch(com.impetus.kundera.graph.Node node)\n    {\n        if (node != null)\n        {\n            nodes.add(node);\n        }\n        if (batchSize > 0 && batchSize == nodes.size())\n        {\n            executeBatch();\n            nodes.clear();\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#executeBatch()\n     */\n    @Override\n    public int executeBatch()\n    {\n        if (batchSize > 0)\n        {\n            boolean nodeAutoIndexingEnabled = indexer.isNodeAutoIndexingEnabled(factory.getConnection());\n            boolean relationshipAutoIndexingEnabled = indexer\n                    .isRelationshipAutoIndexingEnabled(factory.getConnection());\n\n            BatchInserter inserter = getBatchInserter();\n            BatchInserterIndexProvider indexProvider = new LuceneBatchInserterIndexProvider(inserter);\n\n            if (inserter == null)\n            {\n                log.error(\"Unable to create instance of BatchInserter. Opertion will fail\");\n                throw new PersistenceException(\"Unable to create instance of BatchInserter. Opertion will fail\");\n            }\n\n            if (resource != null && resource.isActive())\n            {\n                log.error(\"Batch Insertion MUST not be executed in a transaction\");\n                throw new PersistenceException(\"Batch Insertion MUST not be executed in a transaction\");\n            }\n\n            Map<Object, Long> pkToNodeIdMap = new HashMap<Object, Long>();\n            for (com.impetus.kundera.graph.Node graphNode : nodes)\n            {\n                if (graphNode.isDirty())\n                {\n                    graphNode.handlePreEvent();\n                    // Delete can not be executed in batch, deleting normally\n                    if (graphNode.isInState(RemovedState.class))\n                    {\n                        delete(graphNode.getData(), graphNode.getEntityId());\n                    }\n                    else if (graphNode.isUpdate())\n                    {\n                        // Neo4J allows only batch insertion, follow usual path\n                        // for normal updates\n                        persist(graphNode);\n                    }\n                    else\n                    {\n                        // Insert node\n                        Object entity = graphNode.getData();\n                        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n                        Object pk = PropertyAccessorHelper.getId(entity, m);\n                        Map<String, Object> nodeProperties = mapper.createNodeProperties(entity, m);\n                        long nodeId = inserter.createNode(nodeProperties);\n                        pkToNodeIdMap.put(pk, nodeId);\n\n                        // Index Node\n                        indexer.indexNodeUsingBatchIndexer(indexProvider, m, nodeId, nodeProperties,\n                                nodeAutoIndexingEnabled);\n\n                        // Insert relationships for this particular node\n                        if (!getRelationHolders(graphNode).isEmpty())\n                        {\n                            for (RelationHolder rh : getRelationHolders(graphNode))\n                            {\n                                // Search Node (to be connected to ) in Neo4J\n                                // graph\n                                EntityMetadata targetNodeMetadata = KunderaMetadataManager.getEntityMetadata(\n                                        kunderaMetadata, rh.getRelationValue().getClass());\n                                Object targetNodeKey = PropertyAccessorHelper.getId(rh.getRelationValue(),\n                                        targetNodeMetadata);\n                                Long targetNodeId = pkToNodeIdMap.get(targetNodeKey);\n\n                                if (targetNodeId != null)\n                                {\n                                    /**\n                                     * Join this node (source node) to target\n                                     * node via relationship\n                                     */\n                                    // Relationship Type\n                                    DynamicRelationshipType relType = DynamicRelationshipType.withName(rh\n                                            .getRelationName());\n\n                                    // Relationship Properties\n                                    Map<String, Object> relationshipProperties = null;\n                                    Object relationshipObj = rh.getRelationVia();\n                                    if (relationshipObj != null)\n                                    {\n                                        EntityMetadata relationMetadata = KunderaMetadataManager.getEntityMetadata(\n                                                kunderaMetadata, relationshipObj.getClass());\n\n                                        relationshipProperties = mapper.createRelationshipProperties(m,\n                                                targetNodeMetadata, relationshipObj);\n\n                                        // Finally insert relationship\n                                        long relationshipId = inserter.createRelationship(nodeId, targetNodeId,\n                                                relType, relationshipProperties);\n\n                                        // Index this relationship\n                                        indexer.indexRelationshipUsingBatchIndexer(indexProvider, relationMetadata,\n                                                relationshipId, relationshipProperties, relationshipAutoIndexingEnabled);\n                                    }\n\n                                }\n                            }\n                        }\n                    }\n                    graphNode.handlePostEvent();\n                }\n            }\n\n            // Shutdown Batch inserter\n            indexProvider.shutdown();\n            inserter.shutdown();\n\n            // Restore Graph Database service\n            factory.setConnection((GraphDatabaseService) factory.createPoolOrConnection());\n\n            return pkToNodeIdMap.size();\n        }\n        else\n        {\n            return 0;\n        }\n\n    }\n\n    /**\n     * Populates relationship entities into original entity.\n     * \n     * @param m\n     *            the m\n     * @param entity\n     *            the entity\n     * @param relationMap\n     *            the relation map\n     * @param node\n     *            the node\n     * @param nodeIdToEntityMap\n     *            the node id to entity map\n     */\n    private void populateRelations(EntityMetadata m, Object entity, Map<String, Object> relationMap, Node node,\n            Map<Long, Object> nodeIdToEntityMap)\n    {\n        // Populate all relationship entities that are in Neo4J\n        for (Relation relation : m.getRelations())\n        {\n            if (relation != null)\n            {\n                Class<?> targetEntityClass = relation.getTargetEntity();\n                EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                        targetEntityClass);\n                Field property = relation.getProperty();\n                if (relation.getPropertyType().isAssignableFrom(Map.class))\n                {\n                    Map<Object, Object> targetEntitiesMap = new HashMap<Object, Object>();\n\n                    // If relationship entity is stored into Neo4J, fetch it\n                    // immediately\n                    if (isEntityForNeo4J(targetEntityMetadata))\n                    {\n\n                        for (Relationship relationship : node.getRelationships(Direction.OUTGOING,\n                                DynamicRelationshipType.withName(relation.getJoinColumnName(kunderaMetadata))))\n                        {\n                            if (relationship == null)\n                            {\n                                continue;\n                            }\n\n                            // Target Entity\n                            Node endNode = relationship.getEndNode();\n                            if (endNode == null)\n                            {\n                                continue;\n                            }\n                            Object targetEntity = nodeIdToEntityMap.get(endNode.getId());\n                            if (targetEntity == null)\n                            {\n                                targetEntity = mapper.getEntityFromNode(endNode, targetEntityMetadata);\n                            }\n\n                            // Relationship Entity\n                            Object relationshipEntity = mapper.getEntityFromRelationship(relationship, m, relation);\n\n                            // If this relationship is bidirectional, put source\n                            // entity into Map field for target entity\n                            Field bidirectionalField = relation.getBiDirectionalField();\n                            Map<Object, Object> sourceEntitiesMap = new HashMap<Object, Object>();\n                            if (bidirectionalField != null)\n                            {\n                                for (Relationship incomingRelationship : endNode.getRelationships(Direction.INCOMING,\n                                        DynamicRelationshipType.withName(relation.getJoinColumnName(kunderaMetadata))))\n                                {\n                                    Node startNode = incomingRelationship.getStartNode();\n                                    Object sourceEntity = nodeIdToEntityMap.get(startNode.getId());\n                                    if (sourceEntity == null)\n                                    {\n                                        sourceEntity = mapper.getEntityFromNode(startNode, m);\n                                        nodeIdToEntityMap.put(startNode.getId(), sourceEntity);\n                                    }\n                                    sourceEntitiesMap.put(relationshipEntity, sourceEntity);\n                                }\n                                PropertyAccessorHelper.set(targetEntity, bidirectionalField, sourceEntitiesMap);\n                            }\n\n                            // Set references to Target and owning entity in\n                            // relationship entity\n                            Class<?> relationshipClass = relation.getMapKeyJoinClass();\n                            for (Field f : relationshipClass.getDeclaredFields())\n                            {\n                                if (!ReflectUtils.isTransientOrStatic(f))\n                                {\n\n                                    if (f.getType().equals(m.getEntityClazz()))\n                                    {\n                                        PropertyAccessorHelper.set(relationshipEntity, f, entity);\n                                    }\n                                    else if (f.getType().equals(targetEntityClass))\n                                    {\n                                        PropertyAccessorHelper.set(relationshipEntity, f, targetEntity);\n                                    }\n                                }\n                            }\n                            targetEntitiesMap.put(relationshipEntity, targetEntity);\n                        }\n\n                        PropertyAccessorHelper.set(entity, property, targetEntitiesMap);\n                    }\n\n                    /**\n                     * If relationship entity is stored in a database other than\n                     * Neo4J foreign keys are stored in \"Proxy Nodes\", retrieve\n                     * these foreign keys and set into EnhanceEntity\n                     */\n                    else\n                    {\n\n                        for (Relationship relationship : node.getRelationships(Direction.OUTGOING,\n                                DynamicRelationshipType.withName(relation.getJoinColumnName(kunderaMetadata))))\n                        {\n                            Node proxyNode = relationship.getEndNode();\n\n                            String targetEntityIdColumnName = ((AbstractAttribute) targetEntityMetadata\n                                    .getIdAttribute()).getJPAColumnName();\n                            Object targetObjectId = proxyNode.getProperty(targetEntityIdColumnName);\n                            Object relationshipEntity = mapper.getEntityFromRelationship(relationship, m, relation);\n\n                            targetEntitiesMap.put(targetObjectId, relationshipEntity);\n                        }\n\n                        relationMap.put(relation.getJoinColumnName(kunderaMetadata), targetEntitiesMap);\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * Returns instance of {@link BatchInserter}.\n     * \n     * @return the batch inserter\n     */\n    protected BatchInserter getBatchInserter()\n    {\n        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(\n                getPersistenceUnit());\n        Properties props = puMetadata.getProperties();\n\n        // Datastore file path\n        String datastoreFilePath = (String) props.get(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);\n        if (StringUtils.isEmpty(datastoreFilePath))\n        {\n            throw new PersistenceException(\n                    \"For Neo4J, it's mandatory to specify kundera.datastore.file.path property in persistence.xml\");\n        }\n\n        // Shut down Graph DB, at a time only one service may have lock on DB\n        // file\n        if (factory.getConnection() != null)\n        {\n            factory.getConnection().shutdown();\n        }\n\n        BatchInserter inserter = null;\n\n        // Create Batch inserter with configuration if specified\n        Neo4JSchemaMetadata nsmd = Neo4JPropertyReader.nsmd;\n        ClientProperties cp = nsmd != null ? nsmd.getClientProperties() : null;\n        if (cp != null)\n        {\n            DataStore dataStore = nsmd != null ? nsmd.getDataStore() : null;\n            Properties properties = dataStore != null && dataStore.getConnection() != null ? dataStore.getConnection()\n                    .getProperties() : null;\n\n            if (properties != null)\n            {\n                Map<String, String> config = new HashMap<String, String>((Map) properties);\n                inserter = BatchInserters.inserter(datastoreFilePath, config);\n            }\n        }\n\n        // Create Batch inserter without configuration if not provided\n        if (inserter == null)\n        {\n            inserter = BatchInserters.inserter(datastoreFilePath);\n        }\n        return inserter;\n    }\n\n    /**\n     * Binds Transaction resource to this client.\n     * \n     * @param resource\n     *            the resource\n     */\n    @Override\n    public void bind(TransactionResource resource)\n    {\n        if (resource != null && resource instanceof Neo4JTransaction)\n        {\n            ((Neo4JTransaction) resource).setGraphDb(factory.getConnection());\n            this.resource = resource;\n        }\n        else\n        {\n            throw new KunderaTransactionException(\"Invalid transaction resource provided:\" + resource\n                    + \" Should have been an instance of :\" + Neo4JTransaction.class);\n        }\n    }\n\n    /**\n     * Execute lucene query.\n     * \n     * @param m\n     *            the m\n     * @param luceneQuery\n     *            the lucene query\n     * @return the list\n     */\n    public List<Object> executeLuceneQuery(EntityMetadata m, String luceneQuery)\n    {\n        log.info(\"Executing Lucene Query on Neo4J:\" + luceneQuery);\n\n        GraphDatabaseService graphDb = getConnection();\n        List<Object> entities = new ArrayList<Object>();\n\n        if (!indexer.isNodeAutoIndexingEnabled(graphDb) && m.isIndexable())\n        {\n            Index<Node> nodeIndex = graphDb.index().forNodes(m.getIndexName());\n\n            IndexHits<Node> hits = nodeIndex.query(luceneQuery);\n            addEntityFromIndexHits(m, entities, hits);\n        }\n        else\n        {\n\n            ReadableIndex<Node> autoNodeIndex = graphDb.index().getNodeAutoIndexer().getAutoIndex();\n            IndexHits<Node> hits = autoNodeIndex.query(luceneQuery);\n            addEntityFromIndexHits(m, entities, hits);\n\n        }\n        return entities;\n    }\n\n    /**\n     * Adds the entity from index hits.\n     * \n     * @param m\n     *            the m\n     * @param entities\n     *            the entities\n     * @param hits\n     *            the hits\n     */\n    protected void addEntityFromIndexHits(EntityMetadata m, List<Object> entities, IndexHits<Node> hits)\n    {\n        for (Node node : hits)\n        {\n            if (node != null)\n            {\n                Object entity = getEntityWithAssociationFromNode(m, node);\n                if (entity != null)\n                {\n\n                    entities.add(entity);\n\n                }\n            }\n        }\n    }\n\n    /**\n     * Gets the entity with association from node.\n     * \n     * @param m\n     *            the m\n     * @param node\n     *            the node\n     * @return the entity with association from node\n     */\n    private Object getEntityWithAssociationFromNode(EntityMetadata m, Node node)\n    {\n        Map<String, Object> relationMap = new HashMap<String, Object>();\n\n        /**\n         * Map containing Node ID as key and Entity object as value. Helps cache\n         * entity objects found earlier for faster lookup and prevents repeated\n         * processing\n         */\n        Map<Long, Object> nodeIdToEntityMap = new HashMap<Long, Object>();\n\n        Object entity = mapper.getEntityFromNode(node, m);\n\n        nodeIdToEntityMap.put(node.getId(), entity);\n        populateRelations(m, entity, relationMap, node, nodeIdToEntityMap);\n\n        nodeIdToEntityMap.clear();\n\n        if (!relationMap.isEmpty() && entity != null)\n        {\n            return new EnhanceEntity(entity, PropertyAccessorHelper.getId(entity, m), relationMap);\n        }\n        else\n        {\n            return entity;\n        }\n\n    }\n\n    /**\n     * Checks whether there is an active transaction within this client Batch\n     * operations are run without any transaction boundary hence this check is\n     * not applicable for them All Modifying Neo4J operations must be executed\n     * within a transaction.\n     */\n    private void checkActiveTransaction()\n    {\n        if (batchSize == 0 && (resource == null || !resource.isActive()))\n        {\n            throw new NotInTransactionException(\"All Modifying Neo4J operations must be executed within a transaction\");\n        }\n    }\n\n    /**\n     * Gets the connection.\n     * \n     * @return the connection\n     */\n    public GraphDatabaseService getConnection()\n    {\n        if (resource != null)\n        {\n            return ((Neo4JTransaction) resource).getGraphDb();\n        }\n        else\n        {\n            return factory.getConnection();\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        throw new UnsupportedOperationException(GenerationType.class.getSimpleName()\n                + \" Strategies not supported by this client : Neo4JClient\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/Neo4JClientBase.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * Base class for all Neo4J clients\n * \n * @author amresh.singh\n */\npublic abstract class Neo4JClientBase extends ClientBase implements ClientPropertiesSetter\n{\n    private static Logger log = LoggerFactory.getLogger(Neo4JClientBase.class);\n\n    /** Batch size. */\n    protected int batchSize;\n\n    /** list of nodes for batch processing. */\n    protected List<Node> nodes = new ArrayList<Node>();\n\n    Neo4JClientBase(KunderaMetadata kunderaMetadata, Map<String, Object> puProperties, String persistenceUnit)\n    {\n        super(kunderaMetadata, puProperties, persistenceUnit);\n    }\n\n    protected boolean isEntityForNeo4J(EntityMetadata entityMetadata)\n    {\n        String persistenceUnit = entityMetadata.getPersistenceUnit();\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\n                persistenceUnit);\n        String clientFactory = puMetadata.getProperty(PersistenceProperties.KUNDERA_CLIENT_FACTORY);\n        if (clientFactory.indexOf(\"com.impetus.client.neo4j\") >= 0)\n        {\n            return true;\n        }\n        return false;\n    }\n\n    /**\n     * @param persistenceUnit\n     * @param puProperties\n     */\n    protected void populateBatchSize(String persistenceUnit, Map<String, Object> puProperties)\n    {\n        String batch_Size = puProperties != null ? (String) puProperties.get(PersistenceProperties.KUNDERA_BATCH_SIZE)\n                : null;\n        if (batch_Size != null)\n        {\n            setBatchSize(Integer.valueOf(batch_Size));\n        }\n        else\n        {\n            PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\n                    persistenceUnit);\n            setBatchSize(puMetadata.getBatchSize());\n        }\n    }\n\n    void setBatchSize(int batch_Size)\n    {\n        this.batchSize = batch_Size;\n    }\n\n    public int getBatchSize()\n    {\n        return batchSize;\n    }\n\n    public void clear()\n    {\n        if (nodes != null)\n        {\n            nodes.clear();\n            nodes = new ArrayList<Node>();\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/Neo4JClientFactory.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.neo4j.graphdb.GraphDatabaseService;\nimport org.neo4j.graphdb.factory.GraphDatabaseBuilder;\nimport org.neo4j.graphdb.factory.GraphDatabaseFactory;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.neo4j.config.Neo4JPropertyReader;\nimport com.impetus.client.neo4j.config.Neo4JPropertyReader.Neo4JSchemaMetadata;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.PersistenceUnitConfigurationException;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * Factory of Neo4J client(s)\n * \n * @author amresh.singh\n */\npublic class Neo4JClientFactory extends GenericClientFactory\n{\n\n    /** The logger. */\n    private static Logger log = LoggerFactory.getLogger(Neo4JClientFactory.class);\n\n    @Override\n    public void initialize(Map<String, Object> puProperties)\n    {\n        initializePropertyReader();\n        setExternalProperties(puProperties);\n    }\n\n    /**\n     * Create Neo4J Embedded Graph DB instance, that acts as a Neo4J connection\n     * repository for Neo4J If a Neo4j specfic client properties file is\n     * specified in persistence.xml, it initializes DB instance with those\n     * properties. Other DB instance is initialized with default properties.\n     */\n    @Override\n    protected Object createPoolOrConnection()\n    {\n        if (log.isInfoEnabled())\n            log.info(\"Initializing Neo4J database connection...\");\n\n        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(\n                getPersistenceUnit());\n\n        Properties props = puMetadata.getProperties();\n        \n        String datastoreFilePath = null;\n        if (externalProperties != null)\n        {\n            datastoreFilePath = (String) externalProperties.get(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);\n        }\n        if (StringUtils.isBlank(datastoreFilePath))\n        {\n            datastoreFilePath = (String) props.get(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);\n        }\n        \n        if (StringUtils.isBlank(datastoreFilePath))\n        {\n            throw new PersistenceUnitConfigurationException(\n                    \"For Neo4J, it's mandatory to specify kundera.datastore.file.path property in persistence.xml\");\n        }\n\n        Neo4JSchemaMetadata nsmd = Neo4JPropertyReader.nsmd;\n        ClientProperties cp = nsmd != null ? nsmd.getClientProperties() : null;\n\n        GraphDatabaseService graphDb = (GraphDatabaseService) getConnectionPoolOrConnection();\n\n        if (cp != null && graphDb == null)\n        {\n            DataStore dataStore = nsmd != null ? nsmd.getDataStore() : null;\n\n            Properties properties = dataStore != null && dataStore.getConnection() != null ? dataStore.getConnection()\n                    .getProperties() : null;\n\n            if (properties != null)\n            {\n                Map<String, String> config = new HashMap<String, String>((Map) properties);\n\n                GraphDatabaseBuilder builder = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(datastoreFilePath);\n                builder.setConfig(config);\n\n                graphDb = builder.newGraphDatabase();\n                // registerShutdownHook(graphDb);\n            }\n        }\n\n        if (graphDb == null)\n        {\n            graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(datastoreFilePath);\n            // registerShutdownHook(graphDb);\n        }\n\n        return graphDb;\n    }\n\n    @Override\n    protected Client instantiateClient(String persistenceUnit)\n    {\n        return new Neo4JClient(this, externalProperties, persistenceUnit, kunderaMetadata);\n    }\n\n    @Override\n    public boolean isThreadSafe()\n    {\n        return true;\n    }\n\n    @Override\n    public SchemaManager getSchemaManager(Map<String, Object> puProperties)\n    {\n        log.info(\"No schema manager implementation available (required) for Neo4J.\");\n        return null;\n    }\n\n    @Override\n    public void destroy()\n    {\n        this.externalProperties = null;\n        ((GraphDatabaseService) getConnectionPoolOrConnection()).shutdown();\n        // Not required for multithreaded clients\n    }\n\n    /**\n     * Retrieves {@link GraphDatabaseService} instance\n     * \n     * @return\n     */\n    GraphDatabaseService getConnection()\n    {\n        return (GraphDatabaseService) getConnectionPoolOrConnection();\n    }\n\n    void setConnection(GraphDatabaseService graphDb)\n    {\n        setConnectionPoolOrConnection(graphDb);\n    }\n\n    /**\n     * \n     */\n    private void initializePropertyReader()\n    {\n        if (propertyReader == null)\n        {\n            propertyReader = new Neo4JPropertyReader(externalProperties, kunderaMetadata.getApplicationMetadata()\n                    .getPersistenceUnitMetadata(getPersistenceUnit()));\n            propertyReader.read(getPersistenceUnit());\n        }\n    }\n\n    /**\n     * @param puProperties\n     */\n    protected void setExternalProperties(Map<String, Object> puProperties)\n    {\n        if (puProperties != null)\n        {\n            this.externalProperties = puProperties;\n        }\n    }\n\n    /**\n     * Registers a shutdown hook for the Neo4j instance so that it shuts down\n     * nicely when the VM exits (even if you \"Ctrl-C\" the running example before\n     * it's completed) The EmbeddedGraphDatabase instance can be shared among\n     * multiple threads. Note however that you can’t create multiple instances\n     * pointing to the same database.\n     * \n     * @param graphDb\n     */\n    /*\n     * private static void registerShutdownHook(final GraphDatabaseService\n     * graphDb) { Runtime.getRuntime().addShutdownHook(new Thread() {\n     * \n     * @Override public void run() { graphDb.shutdown(); } }); }\n     */\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n        throw new UnsupportedOperationException(\"Load balancing feature is not supported in \"\n                + this.getClass().getSimpleName());\n    }\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/Neo4JEntityReader.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j;\n\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * Entity Reader for Neo4J\n * \n * @author amresh.singh\n */\npublic class Neo4JEntityReader extends AbstractEntityReader implements EntityReader\n{\n\n    public Neo4JEntityReader(final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    public Neo4JEntityReader(KunderaQuery kunderaQuery, final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n        this.kunderaQuery = kunderaQuery;\n    }\n\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        return super.findById(primaryKey, m, client);\n    }\n\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        throw new UnsupportedOperationException(\"Method supported not required for Neo4J\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/Neo4JTransaction.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.neo4j.graphdb.GraphDatabaseService;\nimport org.neo4j.graphdb.Node;\nimport org.neo4j.graphdb.Transaction;\n\nimport com.impetus.kundera.persistence.TransactionResource;\n\n/**\n * Defines transaction boundaries for Neo4J client, in case user opts for\n * transaction support (kundera.transaction.resource)\n * \n * @author amresh.singh\n */\npublic class Neo4JTransaction implements TransactionResource\n{\n    /** Whether this transaction is currently in progress */\n    private boolean isTransactionInProgress;\n\n    /** IDs of nodes participating in this transaction */\n    private List<Long> nodeIds;\n\n    private Map<Object, Node> processedNodes;\n\n    /**\n     * Instance of {@link GraphDatabaseService} from which this transaction was\n     * spawned\n     */\n    GraphDatabaseService graphDb = null;\n\n    /** Neo4J Transaction instance */\n    Transaction tx = null;\n\n    @Override\n    public void onBegin()\n    {\n        if (graphDb != null && !isTransactionInProgress)\n        {\n            tx = graphDb.beginTx();\n            nodeIds = new ArrayList<Long>();\n            processedNodes = new HashMap<Object, Node>();\n        }\n\n        isTransactionInProgress = true;\n    }\n\n    @Override\n    public void onCommit()\n    {\n        if (tx != null && isTransactionInProgress)\n        {\n            tx.success();\n            tx.finish();\n            nodeIds.clear();\n            processedNodes.clear();\n        }\n\n        isTransactionInProgress = false;\n    }\n\n    @Override\n    public void onRollback()\n    {\n        if (tx != null && isTransactionInProgress)\n        {\n            tx.failure();\n            tx.finish();\n            nodeIds.clear();\n            processedNodes.clear();\n        }\n\n        tx = null;\n        isTransactionInProgress = false;\n    }\n\n    @Override\n    public void onFlush()\n    {\n        onCommit();\n    }\n\n    @Override\n    public Response prepare()\n    {\n        return Response.YES;\n    }\n\n    @Override\n    public boolean isActive()\n    {\n        return isTransactionInProgress;\n    }\n\n    /**\n     * @return the graphDb\n     */\n    public GraphDatabaseService getGraphDb()\n    {\n        return graphDb;\n    }\n\n    /**\n     * @param graphDb\n     *            the graphDb to set\n     */\n    public void setGraphDb(GraphDatabaseService graphDb)\n    {\n        this.graphDb = graphDb;\n    }\n\n    /**\n     * @param nodeIds\n     *            the nodeIds to set\n     */\n    public void addNodeId(Long nodeId)\n    {\n        if (nodeIds == null)\n        {\n            nodeIds = new ArrayList<Long>();\n        }\n        nodeIds.add(nodeId);\n    }\n\n    public boolean containsNodeId(Long nodeId)\n    {\n        if (nodeIds == null)\n            return false;\n\n        return nodeIds.contains(nodeId);\n    }\n\n    /**\n     * @return the processedNodes\n     */\n    public Node getProcessedNode(Object key)\n    {\n        if (processedNodes == null || processedNodes.isEmpty())\n        {\n            return null;\n        }\n        return processedNodes.get(key);\n    }\n\n    /**\n     * @param processedNodes\n     *            the processedNodes to set\n     */\n    public void addProcessedNode(Object key, Node processedNode)\n    {\n        if (processedNodes == null)\n        {\n            processedNodes = new HashMap<Object, Node>();\n        }\n        processedNodes.put(key, processedNode);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/config/Neo4JPropertyReader.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.config;\n\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * XML Property reader for Neo4J specific configuration\n * \n * @author amresh.singh\n */\npublic class Neo4JPropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n\n    /** log instance */\n    private static Logger log = LoggerFactory.getLogger(Neo4JPropertyReader.class);\n\n    /** Neo4J schema metadata instance */\n    public static Neo4JSchemaMetadata nsmd;\n\n    public Neo4JPropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        nsmd = new Neo4JSchemaMetadata();\n    }\n\n    /**\n     * Sets Client properties from XML configuration file into\n     * {@link Neo4JSchemaMetadata}\n     */\n    @Override\n    protected void onXml(ClientProperties cp)\n    {\n        if (cp != null)\n        {\n            nsmd.setClientProperties(cp);\n        }\n    }\n\n    /**\n     * Holds property related to Neo4J specific configuration file\n     * \n     * @author Amresh\n     * \n     */\n    public class Neo4JSchemaMetadata\n    {\n        private static final String NEO4J_DATASTORE = \"neo4j\";\n\n        private ClientProperties clientProperties;\n\n        public Neo4JSchemaMetadata()\n        {\n\n        }\n\n        /**\n         * @return the clientProperties\n         */\n        public ClientProperties getClientProperties()\n        {\n            return clientProperties;\n        }\n\n        /**\n         * @param clientProperties\n         *            the clientProperties to set\n         */\n        private void setClientProperties(ClientProperties clientProperties)\n        {\n            this.clientProperties = clientProperties;\n        }\n\n        /**\n         * Returns datastore instance for given {@link ClientProperties} for\n         * Neo4j\n         * \n         * @return\n         */\n        public DataStore getDataStore()\n        {\n            if (getClientProperties() != null && getClientProperties().getDatastores() != null)\n            {\n                for (DataStore dataStore : getClientProperties().getDatastores())\n                {\n                    if (dataStore.getName() != null && dataStore.getName().trim().equalsIgnoreCase(NEO4J_DATASTORE))\n                    {\n                        return dataStore;\n                    }\n                }\n            }\n            return null;\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/index/Neo4JIndexManager.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.index;\n\nimport java.lang.reflect.Field;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.metamodel.Attribute;\n\nimport org.neo4j.graphdb.GraphDatabaseService;\nimport org.neo4j.graphdb.Node;\nimport org.neo4j.graphdb.Relationship;\nimport org.neo4j.graphdb.index.Index;\nimport org.neo4j.helpers.collection.MapUtil;\nimport org.neo4j.unsafe.batchinsert.BatchInserterIndex;\nimport org.neo4j.unsafe.batchinsert.BatchInserterIndexProvider;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\n\n/**\n * Provides functionalities specific to Auto/ Manual Indexing\n * \n * @author amresh.singh\n */\npublic class Neo4JIndexManager\n{\n    // Auto-Indexing related methods\n    public boolean isNodeAutoIndexingEnabled(GraphDatabaseService graphDb)\n    {\n        return graphDb.index().getNodeAutoIndexer().isEnabled();\n    }\n\n    public boolean isRelationshipAutoIndexingEnabled(GraphDatabaseService graphDb)\n    {\n        return graphDb.index().getRelationshipAutoIndexer().isEnabled();\n    }\n\n    public Set<String> getNodeIndexedProperties(GraphDatabaseService graphDb)\n    {\n        return graphDb.index().getNodeAutoIndexer().getAutoIndexedProperties();\n    }\n\n    public Set<String> getRelationsipIndexedProperties(GraphDatabaseService graphDb)\n    {\n        return graphDb.index().getRelationshipAutoIndexer().getAutoIndexedProperties();\n    }\n\n    protected boolean isEntityForNeo4J(EntityMetadata entityMetadata, PersistenceUnitMetadata puMetadata)\n    {\n        String clientFactory = puMetadata.getProperty(PersistenceProperties.KUNDERA_CLIENT_FACTORY);\n        if (clientFactory.indexOf(\"com.impetus.client.neo4j\") >= 0)\n        {\n            return true;\n        }\n        return false;\n    }\n\n    /**************** Manual Indexing related methods *********************/\n\n    /**\n     * If node auto-indexing is disabled,manually index this Node\n     * \n     * @param entityMetadata\n     * @param graphDb\n     * @param autoIndexing\n     * @param node\n     */\n    public void indexNode(EntityMetadata entityMetadata, GraphDatabaseService graphDb, Node node, MetamodelImpl metaModel)\n    {\n        if (!isNodeAutoIndexingEnabled(graphDb) && entityMetadata.isIndexable())\n        {\n            Index<Node> nodeIndex = graphDb.index().forNodes(entityMetadata.getIndexName());\n            addNodeIndex(entityMetadata, node, nodeIndex, metaModel);\n        }\n    }\n\n    /**\n     * If relationship auto-indexing is disabled, manually index this\n     * relationship\n     * \n     * @param entityMetadata\n     * @param graphDb\n     * @param autoIndexing\n     * @param node\n     */\n    public void indexRelationship(EntityMetadata entityMetadata, GraphDatabaseService graphDb, Relationship relationship, MetamodelImpl metaModel)\n    {\n        if (!isRelationshipAutoIndexingEnabled(graphDb) && entityMetadata.isIndexable())\n        {\n            Index<Relationship> relationshipIndex = graphDb.index().forRelationships(entityMetadata.getIndexName());\n            addRelationshipIndex(entityMetadata, relationship, relationshipIndex, metaModel);\n        }\n    }\n\n    public void indexNodeUsingBatchIndexer(BatchInserterIndexProvider indexProvider, EntityMetadata entityMetadata,\n            long nodeId, Map<String, Object> nodeProperties, boolean nodeAutoIndexingEnabled)\n    {\n        BatchInserterIndex nodeIndex = null;\n\n        if (!nodeAutoIndexingEnabled && entityMetadata.isIndexable())\n        {\n            nodeIndex = indexProvider.nodeIndex(entityMetadata.getIndexName(), MapUtil.stringMap(\"type\", \"exact\"));\n\n        }\n        else\n        {\n            nodeIndex = indexProvider.nodeIndex(\"node_auto_index\", MapUtil.stringMap(\"type\", \"exact\"));\n        }\n\n        if (nodeIndex != null)\n            nodeIndex.add(nodeId, nodeProperties);\n    }\n\n    public void indexRelationshipUsingBatchIndexer(BatchInserterIndexProvider indexProvider,\n            EntityMetadata entityMetadata, long relationshipId, Map<String, Object> relationshipProperties,\n            boolean relationshipAutoIndexingEnabled)\n    {\n        BatchInserterIndex relationshipIndex = null;\n\n        if (!relationshipAutoIndexingEnabled && entityMetadata.isIndexable())\n        {\n            relationshipIndex = indexProvider.relationshipIndex(entityMetadata.getIndexName(),\n                    MapUtil.stringMap(\"type\", \"exact\"));\n        }\n        else\n        {\n            relationshipIndex = indexProvider.relationshipIndex(\"relationship_auto_index\",\n                    MapUtil.stringMap(\"type\", \"exact\"));\n        }\n\n        if (relationshipIndex != null)\n            relationshipIndex.add(relationshipId, relationshipProperties);\n    }\n\n    /**\n     * If node auto-indexing is disabled, Update index for this node manually\n     * \n     * @param entityMetadata\n     * @param graphDb\n     * @param autoIndexing\n     * @param node\n     */\n    public void updateNodeIndex(EntityMetadata entityMetadata, GraphDatabaseService graphDb, Node node, MetamodelImpl metaModel)\n    {\n        if (!isNodeAutoIndexingEnabled(graphDb) && entityMetadata.isIndexable())\n        {\n            Index<Node> nodeIndex = graphDb.index().forNodes(entityMetadata.getIndexName());\n\n            // Remove all exiting node entries from Index\n            nodeIndex.remove(node);\n\n            // Recreate fresh index on this node\n            addNodeIndex(entityMetadata, node, nodeIndex, metaModel);\n        }\n\n    }\n\n    /**\n     * If relationship auto-indexing is disabled, Update index for this\n     * relationship manually\n     * \n     * @param entityMetadata\n     * @param graphDb\n     * @param autoIndexing\n     * @param node\n     */\n    public void updateRelationshipIndex(EntityMetadata entityMetadata, GraphDatabaseService graphDb,\n            Relationship relationship, MetamodelImpl metaModel)\n    {\n        if (!isRelationshipAutoIndexingEnabled(graphDb) && entityMetadata.isIndexable())\n        {\n            Index<Relationship> relationshipIndex = graphDb.index().forRelationships(entityMetadata.getIndexName());\n\n            // Remove all existing relationship entries from Index\n            relationshipIndex.remove(relationship);\n\n            // Recreate fresh index on this relationship\n            addRelationshipIndex(entityMetadata, relationship, relationshipIndex, metaModel);\n        }\n    }\n\n    /**\n     * Deletes a {@link Node} from manually created index if auto-indexing is\n     * disabled\n     * \n     * @param entityMetadata\n     * @param graphDb\n     * @param node\n     */\n    public void deleteNodeIndex(EntityMetadata entityMetadata, GraphDatabaseService graphDb, Node node)\n    {\n        if (!isNodeAutoIndexingEnabled(graphDb) && entityMetadata.isIndexable())\n        {\n            Index<Node> nodeIndex = graphDb.index().forNodes(entityMetadata.getIndexName());\n            nodeIndex.remove(node);\n        }\n    }\n\n    /**\n     * Deletes a {@link Relationship} from manually created index if\n     * auto-indexing is disabled\n     * \n     * @param entityMetadata\n     * @param graphDb\n     * @param relationship\n     */\n    public void deleteRelationshipIndex(EntityMetadata entityMetadata, GraphDatabaseService graphDb,\n            Relationship relationship)\n    {\n        if (!isRelationshipAutoIndexingEnabled(graphDb) && entityMetadata.isIndexable())\n        {\n            Index<Relationship> relationshipIndex = graphDb.index().forRelationships(entityMetadata.getIndexName());\n            relationshipIndex.remove(relationship);\n        }\n    }\n\n    /**\n     * Adds Node Index for all singular attributes (including ID) of a given\n     * entity\n     * \n     * @param entityMetadata\n     * @param node\n     * @param metaModel\n     * @param nodeIndex\n     */\n    private void addNodeIndex(EntityMetadata entityMetadata, Node node, Index<Node> nodeIndex, MetamodelImpl metaModel)\n    {\n//        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n//                entityMetadata.getPersistenceUnit());\n\n        // ID attribute has to be indexed necessarily\n        String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();\n        nodeIndex.add(node, idColumnName, node.getProperty(idColumnName));\n\n        // Index all other fields, for whom indexing is enabled\n        for (Attribute attribute : metaModel.entity(entityMetadata.getEntityClazz()).getSingularAttributes())\n        {\n            Field field = (Field) attribute.getJavaMember();\n            if (!attribute.isCollection() && !attribute.isAssociation()\n                    && entityMetadata.getIndexProperties().keySet().contains(field.getName()))\n            {\n                String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                nodeIndex.add(node, columnName, node.getProperty(columnName));\n            }\n        }\n    }\n\n    /**\n     * Adds Relationship Index for all singular attributes (including ID) of a\n     * given relationship entity\n     * \n     * @param entityMetadata\n     * @param graphDb\n     * @param relationship\n     */\n    private void addRelationshipIndex(EntityMetadata entityMetadata, Relationship relationship,\n            Index<Relationship> relationshipIndex, MetamodelImpl metaModel)\n    {\n//        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n//                entityMetadata.getPersistenceUnit());\n\n        // ID attribute has to be indexed first\n        String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();\n        relationshipIndex.add(relationship, idColumnName, relationship.getProperty(idColumnName));\n\n        // Index all other fields, for whom indexing is enabled\n        for (Attribute attribute : metaModel.entity(entityMetadata.getEntityClazz()).getSingularAttributes())\n        {\n            Field field = (Field) attribute.getJavaMember();\n            if (!attribute.isCollection() && !attribute.isAssociation()\n                    && entityMetadata.getIndexProperties().keySet().contains(field.getName()))\n            {\n                String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                relationshipIndex.add(relationship, columnName, relationship.getProperty(columnName));\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/query/Neo4JLuceneQuery.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.query;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.impetus.client.neo4j.Neo4JClient;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\n\n/**\n * Lucene implementation of {@link Neo4JNativeQuery}\n * \n * @author amresh.singh\n */\npublic class Neo4JLuceneQuery implements Neo4JNativeQuery\n{\n\n    @Override\n    public List<Object> executeNativeQuery(String nativeQuery, Neo4JClient client, EntityMetadata m)\n    {\n        List<Object> entities = new ArrayList<Object>();\n\n        entities = client.executeLuceneQuery(m, nativeQuery);\n\n        return entities;\n    }\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/query/Neo4JNativeQuery.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.query;\n\nimport java.util.List;\n\nimport com.impetus.client.neo4j.Neo4JClient;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\n\n/**\n * Interface for Neo4J Native queries\n * \n * @author amresh.singh\n */\npublic interface Neo4JNativeQuery\n{\n\n    public List<Object> executeNativeQuery(String nativeQuery, Neo4JClient client, EntityMetadata m);\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/query/Neo4JNativeQueryFactory.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.query;\n\nimport com.impetus.kundera.query.QueryHandlerException;\n\n/**\n * factory for {@link Neo4JNativeQuery}\n * \n * @author amresh.singh\n */\npublic class Neo4JNativeQueryFactory\n{\n    public static Neo4JNativeQuery getNativeQueryImplementation(Neo4JQueryType queryType)\n    {\n        if (queryType.equals(Neo4JQueryType.LUCENE))\n        {\n            return new Neo4JLuceneQuery();\n        }\n        /*\n         * else if (queryType.equals(Neo4JQueryType.CYPHER)) { return new\n         * Neo4JCypherQuery(); }\n         */\n        /*\n         * else if (queryType.equals(Neo4JQueryType.GREMLIN)) {\n         * \n         * }\n         */\n        else\n        {\n            throw new QueryHandlerException(\"Invalid Query Type:\" + queryType\n                    + \".Can't determine and implementation for running this type for native query for Neo4J\");\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/query/Neo4JQuery.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.query;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport com.impetus.client.neo4j.Neo4JClient;\nimport com.impetus.client.neo4j.Neo4JEntityReader;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.query.QueryImpl;\n\n/**\n * Neo4J Query Implementor\n * \n * @author amresh.singh\n */\npublic class Neo4JQuery extends QueryImpl\n{\n    private static final String NATIVE_QUERY_TYPE = \"native.query.type\";\n\n    Neo4JQueryType queryType;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /**\n     * @param query\n     * @param persistenceDelegator\n     */\n    public Neo4JQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n        if (getHints().containsKey(NATIVE_QUERY_TYPE))\n        {\n            queryType = (Neo4JQueryType) getHints().get(NATIVE_QUERY_TYPE);\n        }\n        else\n        {\n            queryType = Neo4JQueryType.LUCENE;\n        }\n\n    }\n\n    @Override\n    protected List<Object> populateEntities(EntityMetadata m, Client client)\n    {\n        // One implementation for entities with or without relations\n        return recursivelyPopulateEntities(m, client);\n    }\n\n    @Override\n    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n        List<Object> entities = new ArrayList<Object>();\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\n\n        String query = appMetadata.getQuery(getJPAQuery());\n        boolean isNative = kunderaQuery.isNative()/*\n                                                   * query == null ? true :\n                                                   * appMetadata\n                                                   * .isNative(getJPAQuery())\n                                                   */;\n\n        if (isNative)\n        {\n            String nativeQuery = query != null ? query : getJPAQuery();\n            Neo4JNativeQuery nativeQueryImpl = Neo4JNativeQueryFactory.getNativeQueryImplementation(queryType);\n            entities = nativeQueryImpl.executeNativeQuery(nativeQuery, (Neo4JClient) client, m);\n        }\n        else\n        {\n            String luceneQuery = getLuceneQuery(kunderaQuery);\n            entities = ((Neo4JClient) client).executeLuceneQuery(m, luceneQuery);\n        }\n        return setRelationEntities(entities, client, m);\n    }\n\n    @Override\n    protected EntityReader getReader()\n    {\n        if (reader == null)\n        {\n            reader = new Neo4JEntityReader(kunderaQuery, kunderaMetadata);\n        }\n        return reader;\n    }\n\n    @Override\n    protected int onExecuteUpdate()\n    {\n        return onUpdateDeleteEvent();\n    }\n\n    private String getLuceneQuery(KunderaQuery kunderaQuery)\n    {\n        StringBuffer sb = new StringBuffer();\n\n        if (kunderaQuery.getFilterClauseQueue().isEmpty())\n        {\n            // Select All query if filter clause is empty\n            String idColumnName = ((AbstractAttribute) kunderaQuery.getEntityMetadata().getIdAttribute())\n                    .getJPAColumnName();\n            sb.append(idColumnName).append(\":\").append(\"*\");\n        }\n        else\n        {\n            for (Object object : kunderaQuery.getFilterClauseQueue())\n            {\n                if (object instanceof FilterClause)\n                {\n                    boolean appended = false;\n                    FilterClause filter = (FilterClause) object;\n                    // property\n                    sb.append(filter.getProperty());\n\n                    // joiner\n                    String appender = \"\";\n                    String condition = filter.getCondition().trim();\n                    if (condition.equals(\"=\"))\n                    {\n                        sb.append(\":\");\n                    }\n                    else if (condition.equalsIgnoreCase(\"like\"))\n                    {\n                        sb.append(\":\");\n                        appender = \"*\";\n                    }\n                    else if (condition.equalsIgnoreCase(\">\"))\n                    {\n                        // TODO: Amresh need to look for \"String.class\"\n                        // parameter.\n                        sb.append(appendRange(filter.getValue().get(0).toString(), false, true, String.class));\n                        appended = true;\n                    }\n                    else if (condition.equalsIgnoreCase(\">=\"))\n                    {\n                        sb.append(appendRange(filter.getValue().get(0).toString(), true, true, String.class));\n                        appended = true;\n                    }\n                    else if (condition.equalsIgnoreCase(\"<\"))\n                    {\n                        sb.append(appendRange(filter.getValue().get(0).toString(), false, false, String.class));\n                        appended = true;\n                    }\n                    else if (condition.equalsIgnoreCase(\"<=\"))\n                    {\n                        sb.append(appendRange(filter.getValue().get(0).toString(), true, false, String.class));\n                        appended = true;\n                    }\n                    else if (condition.equalsIgnoreCase(\"in\"))\n                    {\n                        sb.append(\":\");\n                        List<Object> items = filter.getValue();\n                        Object firstItem = items.get(0);\n                        if (firstItem.getClass().isArray())\n                        {\n                            items = Arrays.asList((Object[]) firstItem);\n                        }\n                        if (items.size() > 1)\n                        {\n                            sb.append(\"(\");\n                            for (Object item : items)\n                            {\n                                sb.append(\"\\\"\" + item.toString() + \"\\\" \");\n                            }\n                            sb.append(\")\");\n                        }\n                        else\n                        {\n                            sb.append(\"(\").append(items.get(0).toString().replaceAll(\"[,]\", \"\").replaceAll(\"[']\", \"\\\"\")).append(\")\");\n                        }\n                        appended = true;\n                    }\n                    // value. if not already appended.\n                    if (!appended)\n                    {\n                        if (appender.equals(\"\") && filter.getValue() != null\n                                && filter.getValue().get(0).toString().contains(\" \"))\n                        {\n                            sb.append(\"\\\"\");\n                            sb.append(filter.getValue().get(0).toString());\n                            sb.append(\"\\\"\");\n                        }\n                        else\n                        {\n                            sb.append(filter.getValue().get(0));\n                            sb.append(appender);\n                        }\n\n                    }\n                }\n                else\n                {\n                    sb.append(\" \" + object + \" \");\n                }\n            }\n        }\n\n        return sb.toString();\n    }\n\n    @Override\n    public void close()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    @Override\n    public Iterator iterate()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /**\n     * Append range.\n     * \n     * @param value\n     *            the value\n     * @param inclusive\n     *            the inclusive\n     * @param isGreaterThan\n     *            the is greater than\n     * @return the string\n     */\n    protected String appendRange(String value, boolean inclusive, boolean isGreaterThan, Class clazz)\n    {\n        String appender = \" \";\n        StringBuilder sb = new StringBuilder();\n        sb.append(\":\");\n        sb.append(inclusive ? \"[\" : \"{\");\n        sb.append(isGreaterThan ? value : \"*\");\n        sb.append(appender);\n        sb.append(\"TO\");\n        sb.append(appender);\n        if (clazz.isAssignableFrom(int.class) || clazz.isAssignableFrom(Integer.class)\n                || clazz.isAssignableFrom(short.class) || clazz.isAssignableFrom(long.class)\n                || clazz.isAssignableFrom(Long.class) || clazz.isAssignableFrom(float.class)\n                || clazz.isAssignableFrom(Float.class) || clazz.isAssignableFrom(BigDecimal.class)\n                || clazz.isAssignableFrom(BigInteger.class) || clazz.isAssignableFrom(Double.class)\n                || clazz.isAssignableFrom(double.class))\n        {\n            sb.append(isGreaterThan ? \"*\" : value);\n\n        }\n        else\n        {\n            sb.append(isGreaterThan ? \"null\" : value);\n        }\n\n        // sb.append(isGreaterThan ? \"null\" : value);\n\n        sb.append(inclusive ? \"]\" : \"}\");\n        return sb.toString();\n    }\n\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/main/java/com/impetus/client/neo4j/query/Neo4JQueryType.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.query;\n\n/**\n * Enum for different native query types supported in Neo4J Currently, only\n * Lucene is supported, rest are for future use.\n * \n * @author amresh.singh\n */\npublic enum Neo4JQueryType\n{\n    LUCENE, CYPHER, GREMLIN\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/GraphEntityMapperTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j;\n\nimport java.io.File;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.neo4j.graphdb.DynamicRelationshipType;\nimport org.neo4j.graphdb.GraphDatabaseService;\nimport org.neo4j.graphdb.Node;\nimport org.neo4j.graphdb.Relationship;\nimport org.neo4j.graphdb.Transaction;\nimport org.neo4j.kernel.impl.util.FileUtils;\n\nimport com.impetus.client.neo4j.imdb.Actor;\nimport com.impetus.client.neo4j.imdb.Movie;\nimport com.impetus.client.neo4j.imdb.Role;\nimport com.impetus.client.neo4j.index.Neo4JIndexManager;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * Test case for {@link GraphEntityMapper}\n * \n * @author amresh.singh\n */\npublic class GraphEntityMapperTest\n{\n    static EntityManagerFactory emf;\n\n    static EntityManager em;\n\n    static Neo4JClient client;\n\n    GraphEntityMapper mapper;\n\n    GraphDatabaseService graphDb;\n\n    final static String PU = \"imdb\";\n\n    private static KunderaMetadata kunderaMetadata;\n    /**\n     * @throws java.lang.Exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n        \n        kunderaMetadata = ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance();\n        \n        em = emf.createEntityManager();\n        \n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        client = (Neo4JClient) clients.get(PU);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata, PU);\n        String datastoreFilePath = puMetadata.getProperty(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);\n\n        em.close();\n        emf.close();\n\n        if (datastoreFilePath != null)\n            FileUtils.deleteRecursively(new File(datastoreFilePath));\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        mapper = new GraphEntityMapper(new Neo4JIndexManager(), kunderaMetadata);\n        graphDb = client.getConnection();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        mapper = null;\n        graphDb = null;\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.GraphEntityMapper#getNodeFromEntity(java.lang.Object, Object, org.neo4j.graphdb.GraphDatabaseService, com.impetus.kundera.metadata.model.EntityMetadata, boolean)}\n     * .\n     */\n    @Test\n    public void testGetNodeFromEntity()\n    {\n        Actor actor = new Actor();\n        actor.setId(1);\n        actor.setName(\"Keenu Reeves\");\n\n        Transaction tx = graphDb.beginTx();\n        Node node = mapper.getNodeFromEntity(actor, 1, graphDb, KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Actor.class),\n                false);\n        Assert.assertNotNull(node);\n        Assert.assertEquals(1, node.getProperty(\"ACTOR_ID\"));\n        Assert.assertEquals(\"Keenu Reeves\", node.getProperty(\"ACTOR_NAME\"));\n\n        node.delete();\n\n        tx.success();\n        tx.finish();\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.GraphEntityMapper#createProxyNode(java.lang.Object, java.lang.Object, org.neo4j.graphdb.GraphDatabaseService, com.impetus.kundera.metadata.model.EntityMetadata, com.impetus.kundera.metadata.model.EntityMetadata)}\n     * .\n     */\n    @Test\n    public void testCreateProxyNode()\n    {\n        EntityMetadata sourceM = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Actor.class);\n        EntityMetadata targetM = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Movie.class);\n\n        Transaction tx = graphDb.beginTx();\n        Node proxyNode = mapper.createProxyNode(1, \"A\", graphDb, sourceM, targetM);\n\n        Assert.assertNotNull(proxyNode);\n        Assert.assertEquals(1, proxyNode.getProperty(\"ACTOR_ID\"));\n        Assert.assertEquals(\"A\", proxyNode.getProperty(\"MOVIE_ID\"));\n        Assert.assertEquals(\"$PROXY_NODE$\", proxyNode.getProperty(\"$NODE_TYPE$\"));\n\n        proxyNode.delete();\n        tx.success();\n        tx.finish();\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.GraphEntityMapper#getEntityFromNode(org.neo4j.graphdb.Node, com.impetus.kundera.metadata.model.EntityMetadata)}\n     * .\n     */\n    @Test\n    public void testGetEntityFromNode()\n    {\n        Transaction tx = graphDb.beginTx();\n        Node node = graphDb.createNode();\n        node.setProperty(\"ACTOR_ID\", 1);\n        node.setProperty(\"ACTOR_NAME\", \"Amresh Singh\");\n\n        Actor actor = (Actor) mapper.getEntityFromNode(node, KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Actor.class));\n\n        Assert.assertNotNull(actor);\n        Assert.assertEquals(1, actor.getId());\n        Assert.assertEquals(\"Amresh Singh\", actor.getName());\n\n        node.delete();\n        tx.success();\n        tx.finish();\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.GraphEntityMapper#getEntityFromRelationship(org.neo4j.graphdb.Relationship, com.impetus.kundera.metadata.model.EntityMetadata, com.impetus.kundera.metadata.model.Relation)}\n     * .\n     */\n    @Test\n    public void testGetEntityFromRelationship()\n    {\n        Transaction tx = graphDb.beginTx();\n        Node sourceNode = graphDb.createNode();\n        sourceNode.setProperty(\"ACTOR_ID\", 1);\n        sourceNode.setProperty(\"ACTOR_NAME\", \"Amresh Singh\");\n\n        Node targetNode = graphDb.createNode();\n        targetNode.setProperty(\"MOVIE_ID\", \"M1\");\n        targetNode.setProperty(\"TITLE\", \"Matrix Reloaded\");\n        targetNode.setProperty(\"YEAR\", 1999);\n\n        Relationship rel = sourceNode.createRelationshipTo(targetNode, DynamicRelationshipType.withName(\"ACTS_IN\"));\n        rel.setProperty(\"ROLE_NAME\", \"Neo\");\n        rel.setProperty(\"ROLE_TYPE\", \"Lead Actor\");\n\n        Role role = (Role) mapper.getEntityFromRelationship(rel, KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Actor.class),\n                KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Actor.class).getRelation(\"movies\"));\n\n        Assert.assertNotNull(role);\n        Assert.assertEquals(\"Neo\", role.getRoleName());\n        Assert.assertEquals(\"Lead Actor\", role.getRoleType());\n\n        rel.delete();\n        sourceNode.delete();\n        targetNode.delete();\n\n        tx.success();\n        tx.finish();\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.GraphEntityMapper#createNodeProperties(java.lang.Object, com.impetus.kundera.metadata.model.EntityMetadata)}\n     * .\n     */\n    @Test\n    public void testCreateNodeProperties()\n    {\n        Actor actor = new Actor();\n        actor.setId(1);\n        actor.setName(\"Keenu Reeves\");\n\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Actor.class);\n\n        Map<String, Object> props = mapper.createNodeProperties(actor, m);\n        Assert.assertNotNull(props);\n        Assert.assertFalse(props.isEmpty());\n        Assert.assertEquals(1, props.get(\"ACTOR_ID\"));\n        Assert.assertEquals(\"Keenu Reeves\", props.get(\"ACTOR_NAME\"));\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.GraphEntityMapper#populateRelationshipProperties(com.impetus.kundera.metadata.model.EntityMetadata, com.impetus.kundera.metadata.model.EntityMetadata, org.neo4j.graphdb.Relationship, java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testPopulateRelationshipProperties()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.GraphEntityMapper#createRelationshipProperties(com.impetus.kundera.metadata.model.EntityMetadata, com.impetus.kundera.metadata.model.EntityMetadata, java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testCreateRelationshipProperties()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.GraphEntityMapper#toNeo4JProperty(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testToNeo4JProperty()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.GraphEntityMapper#fromNeo4JObject(java.lang.Object, java.lang.reflect.Field)}\n     * .\n     */\n    @Test\n    public void testFromNeo4JObject()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.GraphEntityMapper#searchNode(java.lang.Object, com.impetus.kundera.metadata.model.EntityMetadata, org.neo4j.graphdb.GraphDatabaseService, boolean)}\n     * .\n     */\n    @Test\n    public void testSearchNode()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.GraphEntityMapper#getMatchingNodeFromIndexHits(org.neo4j.graphdb.index.IndexHits, boolean)}\n     * .\n     */\n    @Test\n    public void testGetMatchingNodeFromIndexHits()\n    {\n\n    }\n\n}"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/Neo4JClientFactoryTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.lang.reflect.Field;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.neo4j.kernel.EmbeddedGraphDatabase;\nimport org.neo4j.kernel.impl.util.FileUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.ClientResolver;\nimport com.impetus.kundera.loader.ClientFactory;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * Test case for {@link Neo4JClientFactory}\n * \n * @author amresh.singh\n */\npublic class Neo4JClientFactoryTest\n{\n\n    /** The Constant REDIS_PU. */\n    private static final String persistenceUnit = \"imdb\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(Neo4JClientFactoryTest.class);\n\n    /**\n     * Setup.\n     */\n    @Before\n    public void setup()\n    {\n        emf = Persistence.createEntityManagerFactory(persistenceUnit);\n    }\n\n    /**\n     * Test connection.\n     */\n    @Test\n    public void testConnection()\n    {\n        logger.info(\"On test connection\");\n\n        ClientFactory clientFactory = ClientResolver.getClientFactory(persistenceUnit);\n        Assert.assertNotNull(clientFactory);\n        Assert.assertEquals(Neo4JClientFactory.class, clientFactory.getClass());\n        Field connectionField;\n        try\n        {\n            String field_name = \"connectionPoolOrConnection\";\n            connectionField = ((Neo4JClientFactory) clientFactory).getClass().getSuperclass()\n                    .getDeclaredField(field_name);\n\n            if (!connectionField.isAccessible())\n            {\n                connectionField.setAccessible(true);\n            }\n\n            Object connectionObj = connectionField.get(clientFactory);\n\n            Assert.assertNotNull(connectionObj);\n            Assert.assertTrue(connectionObj instanceof EmbeddedGraphDatabase);\n\n        }\n        catch (SecurityException e)\n        {\n            logger.error(e.getMessage());\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            logger.error(e.getMessage());\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalArgumentException e)\n        {\n            logger.error(e.getMessage());\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            logger.error(e.getMessage());\n            Assert.fail(e.getMessage());\n        }\n\n    }\n\n    /**\n     * Tear down.\n     * @throws IOException \n     */\n    @After\n    public void tearDown() throws IOException\n    {\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance(), persistenceUnit);\n        String datastoreFilePath = puMetadata.getProperty(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);\n\n        emf.close();\n\n        if (datastoreFilePath != null)\n            FileUtils.deleteRecursively(new File(datastoreFilePath));\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/Neo4JClientTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.neo4j;\n\nimport java.io.File;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.neo4j.kernel.impl.util.FileUtils;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * @author amresh\n * \n */\npublic class Neo4JClientTest\n{\n    static EntityManagerFactory emf;\n\n    static EntityManager em;\n\n    static Neo4JClient client;\n\n    GraphEntityMapper mapper;\n\n    final static String PU = \"imdb\";\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n        em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        client = (Neo4JClient) clients.get(PU);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance(), PU);\n        String datastoreFilePath = puMetadata.getProperty(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);\n\n        em.close();\n        emf.close();\n\n       if (datastoreFilePath != null)\n            FileUtils.deleteRecursively(new File(datastoreFilePath));\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#onPersist(com.impetus.kundera.metadata.model.EntityMetadata, java.lang.Object, java.lang.Object, java.util.List)}\n     * .\n     */\n    @Test\n    public void testOnPersist()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#find(java.lang.Class, java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testFindClassObject()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#findAll(java.lang.Class, String[], java.lang.Object[])}\n     * .\n     */\n    @Test\n    public void testFindAll()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#delete(java.lang.Object, java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testDelete()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#persistJoinTable(com.impetus.kundera.persistence.context.jointable.JoinTableData)}\n     * .\n     */\n    @Test\n    public void testPersistJoinTable()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#getColumnsById(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testGetColumnsById()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#findIdsByColumn(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Object, java.lang.Class)}\n     * .\n     */\n    @Test\n    public void testFindIdsByColumn()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#deleteByColumn(java.lang.String, java.lang.String, java.lang.String, java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testDeleteByColumn()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#findByRelation(java.lang.String, java.lang.Object, java.lang.Class)}\n     * .\n     */\n    @Test\n    public void testFindByRelation()\n    {\n\n    }\n\n    /**\n     * Test method for {@link com.impetus.client.neo4j.Neo4JClient#getReader()}.\n     */\n    @Test\n    public void testGetReader()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#getQueryImplementor()}.\n     */\n    @Test\n    public void testGetQueryImplementor()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#addBatch(com.impetus.kundera.graph.Node)}\n     * .\n     */\n    @Test\n    public void testAddBatch()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#executeBatch()}.\n     */\n    @Test\n    public void testExecuteBatch()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#getBatchInserter()}.\n     */\n    @Test\n    public void testGetBatchInserter()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#bind(com.impetus.kundera.persistence.TransactionResource)}\n     * .\n     */\n    @Test\n    public void testBind()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#executeLuceneQuery(com.impetus.kundera.metadata.model.EntityMetadata, java.lang.String)}\n     * .\n     */\n    @Test\n    public void testExecuteLuceneQuery()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClient#getConnection()}.\n     */\n    @Test\n    public void testGetConnection()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClientBase#isEntityForNeo4J(com.impetus.kundera.metadata.model.EntityMetadata)}\n     * .\n     */\n    @Test\n    public void testIsEntityForNeo4J()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClientBase#populateBatchSize(java.lang.String, java.util.Map)}\n     * .\n     */\n    @Test\n    public void testPopulateBatchSize()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.neo4j.Neo4JClientBase#getBatchSize()}.\n     */\n    @Test\n    public void testGetBatchSize()\n    {\n\n    }\n\n    /**\n     * Test method for {@link com.impetus.client.neo4j.Neo4JClientBase#clear()}.\n     */\n    @Test\n    public void testClear()\n    {\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/Actor.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.MapKeyJoinColumn;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Actor Node Entity class\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table\n// Ignored for Neo4J\n@IndexCollection(columns = { @Index(name = \"name\", type = \"KEYS\") })\npublic class Actor\n{\n    @Id\n    @Column(name = \"ACTOR_ID\")\n    private int id;\n\n    @Column(name = \"ACTOR_NAME\")\n    private String name;\n\n    public Actor()\n    {\n    }\n\n    public Actor(int actorId, String actorName)\n    {\n        this.id = actorId;\n        this.name = actorName;\n    }\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)    \n    @MapKeyJoinColumn(name = \"ACTS_IN\")\n    private Map<Role, Movie> movies;\n\n    public void addMovie(Role role, Movie movie)\n    {\n        if (movies == null)\n            movies = new HashMap<Role, Movie>();\n        movies.put(role, movie);\n    }\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the movies\n     */\n    public Map<Role, Movie> getMovies()\n    {\n        return movies;\n    }\n\n    /**\n     * @param movies\n     *            the movies to set\n     */\n    public void setMovies(Map<Role, Movie> movies)\n    {\n        this.movies = movies;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/ActorWithMultipleRelation.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.MapKeyJoinColumn;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Actor Node Entity class\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table\n// Ignored for Neo4J\n@IndexCollection(columns = { @Index(name = \"name\", type = \"KEYS\") })\npublic class ActorWithMultipleRelation\n{\n    @Id\n    @Column(name = \"ACTOR_ID\")\n    private int id;\n\n    @Column(name = \"ACTOR_NAME\")\n    private String name;\n\n    public ActorWithMultipleRelation()\n    {\n    }\n\n    public ActorWithMultipleRelation(int actorId, String actorName)\n    {\n        this.id = actorId;\n        this.name = actorName;\n    }\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @MapKeyJoinColumn(name = \"ACTS_IN\")\n    private Map<NewRole, LatestMovie> latestActedMovies;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @MapKeyJoinColumn(name = \"ACTS_IN_FAV\")\n    private Map<OldRole, ArchivedMovie> oldActedMovies;\n\n    public void addLatestMovie(NewRole role, LatestMovie movie)\n    {\n        if (latestActedMovies == null)\n        {\n            latestActedMovies = new HashMap<NewRole, LatestMovie>();\n        }\n        latestActedMovies.put(role, movie);\n    }\n\n    public void addArchivedMovie(OldRole role, ArchivedMovie movie)\n    {\n        if (oldActedMovies == null)\n        {\n            oldActedMovies = new HashMap<OldRole, ArchivedMovie>();\n        }\n        oldActedMovies.put(role, movie);\n    }\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the latestMovies\n     */\n    public Map<NewRole, LatestMovie> getLatestMovies()\n    {\n        return latestActedMovies;\n    }\n\n    /**\n     * @param latestMovies\n     *            the actedMovies to set\n     */\n    public void setLatestMovies(Map<NewRole, LatestMovie> latestMovies)\n    {\n        this.latestActedMovies = latestMovies;\n    }\n\n    /**\n     * @return the archivedMovies\n     */\n    public Map<OldRole, ArchivedMovie> getArchivedMovies()\n    {\n        return oldActedMovies;\n    }\n\n    /**\n     * @param archivedMovies\n     *            the favouriteMovies to set\n     */\n    public void setArchivedMovies(Map<OldRole, ArchivedMovie> archivedMovies)\n    {\n        this.oldActedMovies = archivedMovies;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/ActorWithMultipleRelationTest.java",
    "content": "package com.impetus.client.neo4j.imdb;\n\nimport java.io.File;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.neo4j.kernel.impl.util.FileUtils;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * @author impadmin\n * \n */\npublic class ActorWithMultipleRelationTest\n{\n    private static final String IMDB_PU = \"imdb\";\n\n    private EntityManagerFactory emf;\n\n    private KunderaMetadata kunderaMetadata;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(IMDB_PU);\n        kunderaMetadata = ((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager\n                .getPersistenceUnitMetadata(kunderaMetadata, IMDB_PU);\n        String datastoreFilePath = puMetadata.getProperty(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);\n        emf.close();\n        if (datastoreFilePath != null)\n        {\n            FileUtils.deleteRecursively(new File(datastoreFilePath));\n        }\n    }\n\n    @Test\n    public void test()\n    {\n        // Actors\n        ActorWithMultipleRelation actor = new ActorWithMultipleRelation(1, \"Tom Cruise\");\n\n        // Latest Movies\n        LatestMovie latestMovie1 = new LatestMovie(\"l1\", \"Mission:Impossible Ghost Protocol\", 2011);\n        LatestMovie latestMovie2 = new LatestMovie(\"l2\", \"Jack Reacher\", 2012);\n\n        // New Roles\n        NewRole newRole1 = new NewRole(\"Ethan Hunt\", \"Lead Actor\");\n        newRole1.setActor(actor);\n        newRole1.setMovie(latestMovie1);\n\n        NewRole newRole2 = new NewRole(\"Jack Reacher\", \"Lead Actor\");\n        newRole2.setActor(actor);\n        newRole2.setMovie(latestMovie2);\n\n        // Relationships\n        actor.addLatestMovie(newRole1, latestMovie1);\n        actor.addLatestMovie(newRole2, latestMovie2);\n\n        // latestMovie1.addActor(newRole1, actor);\n\n        EntityManager em = emf.createEntityManager();\n\n        em.getTransaction().begin();\n        em.persist(actor);\n        em.getTransaction().commit();\n        em.clear();\n\n        ActorWithMultipleRelation result = em.find(ActorWithMultipleRelation.class, 1);\n        Assert.assertNotNull(result);\n        Assert.assertNotNull(result.getName());\n        Assert.assertNotNull(result.getId());\n        Assert.assertNotNull(result.getLatestMovies());\n        Assert.assertFalse(result.getLatestMovies().isEmpty());\n        \n        Assert.assertNotNull(result.getLatestMovies().get(newRole1));\n        Assert.assertEquals(\"Mission:Impossible Ghost Protocol\", result.getLatestMovies().get(newRole1).getTitle());\n        Assert.assertEquals(\"l1\", result.getLatestMovies().get(newRole1).getId());\n        Assert.assertEquals(2011, result.getLatestMovies().get(newRole1).getYear());\n\n        Assert.assertNotNull(result.getLatestMovies().get(newRole2));\n        Assert.assertEquals(\"Jack Reacher\", result.getLatestMovies().get(newRole2).getTitle());\n        Assert.assertEquals(\"l2\", result.getLatestMovies().get(newRole2).getId());\n        Assert.assertEquals(2012, result.getLatestMovies().get(newRole2).getYear());\n        \n        Assert.assertNotNull(result.getArchivedMovies());\n        Assert.assertTrue(result.getArchivedMovies().isEmpty());\n\n        List<ActorWithMultipleRelation> results = em.createQuery(\"Select a from ActorWithMultipleRelation a\")\n                .getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertNotNull(results.get(0));\n\n        result = results.get(0);\n\n        Assert.assertNotNull(result.getName());\n        Assert.assertNotNull(result.getId());\n        Assert.assertNotNull(result.getLatestMovies());\n        Assert.assertFalse(result.getLatestMovies().isEmpty());\n\n        Assert.assertNotNull(result.getLatestMovies().get(newRole1));\n        Assert.assertEquals(\"Mission:Impossible Ghost Protocol\", result.getLatestMovies().get(newRole1).getTitle());\n        Assert.assertEquals(\"l1\", result.getLatestMovies().get(newRole1).getId());\n        Assert.assertEquals(2011, result.getLatestMovies().get(newRole1).getYear());\n\n        Assert.assertNotNull(result.getLatestMovies().get(newRole2));\n        Assert.assertEquals(\"Jack Reacher\", result.getLatestMovies().get(newRole2).getTitle());\n        Assert.assertEquals(\"l2\", result.getLatestMovies().get(newRole2).getId());\n        Assert.assertEquals(2012, result.getLatestMovies().get(newRole2).getYear());\n\n        Assert.assertNotNull(result.getArchivedMovies());\n        Assert.assertTrue(result.getArchivedMovies().isEmpty());\n\n        // Remove\n        em.getTransaction().begin();\n        em.remove(result);\n        em.getTransaction().commit();\n        result = em.find(ActorWithMultipleRelation.class, 1);\n        Assert.assertNull(result);\n\n        // Adding one more relationship to actor.\n        // Latest Movies\n        ArchivedMovie archivedMovie1 = new ArchivedMovie(\"a1\", \"Top Gun\", 1986);\n        ArchivedMovie archivedMovie2 = new ArchivedMovie(\"a2\", \"A Few Good Men\", 1992);\n\n        // New Roles\n        OldRole oldRole1 = new OldRole(\"LT Pete 'Maverick' Mitchell\", \"Lead Actor\");\n        oldRole1.setActor(actor);\n        oldRole1.setMovie(archivedMovie1);\n\n        OldRole oldRole2 = new OldRole(\"Daniel Kaffee\", \"Lead Actor\");\n        oldRole2.setActor(actor);\n        oldRole2.setMovie(archivedMovie2);\n\n        // Relationships\n        actor.addArchivedMovie(oldRole1, archivedMovie1);\n        actor.addArchivedMovie(oldRole2, archivedMovie2);\n\n        // archivedMovie2.addActor(oldRole1, actor);\n\n        em.getTransaction().begin();\n        em.persist(actor);\n        em.getTransaction().commit();\n        em.clear();\n\n        result = em.find(ActorWithMultipleRelation.class, 1);\n        Assert.assertNotNull(result);\n        Assert.assertNotNull(result.getName());\n        Assert.assertNotNull(result.getId());\n        Assert.assertNotNull(result.getLatestMovies());\n        Assert.assertFalse(result.getLatestMovies().isEmpty());\n\n        Assert.assertNotNull(result.getLatestMovies().get(newRole1));\n        Assert.assertEquals(\"Mission:Impossible Ghost Protocol\", result.getLatestMovies().get(newRole1).getTitle());\n        Assert.assertEquals(\"l1\", result.getLatestMovies().get(newRole1).getId());\n        Assert.assertEquals(2011, result.getLatestMovies().get(newRole1).getYear());\n\n        Assert.assertNotNull(result.getLatestMovies().get(newRole2));\n        Assert.assertEquals(\"Jack Reacher\", result.getLatestMovies().get(newRole2).getTitle());\n        Assert.assertEquals(\"l2\", result.getLatestMovies().get(newRole2).getId());\n        Assert.assertEquals(2012, result.getLatestMovies().get(newRole2).getYear());\n\n        Assert.assertNotNull(result.getArchivedMovies());\n        Assert.assertFalse(result.getArchivedMovies().isEmpty());\n\n        Assert.assertNotNull(result.getArchivedMovies().get(oldRole1));\n        Assert.assertEquals(\"Top Gun\", result.getArchivedMovies().get(oldRole1).getTitle());\n        Assert.assertEquals(\"a1\", result.getArchivedMovies().get(oldRole1).getId());\n        Assert.assertEquals(1986, result.getArchivedMovies().get(oldRole1).getYear());\n\n        Assert.assertNotNull(result.getArchivedMovies().get(oldRole2));\n        Assert.assertEquals(\"A Few Good Men\", result.getArchivedMovies().get(oldRole2).getTitle());\n        Assert.assertEquals(\"a2\", result.getArchivedMovies().get(oldRole2).getId());\n        Assert.assertEquals(1992, result.getArchivedMovies().get(oldRole2).getYear());\n\n\n        results = em.createQuery(\"Select a from ActorWithMultipleRelation a\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertNotNull(results.get(0));\n\n        result = results.get(0);\n\n        Assert.assertNotNull(result.getName());\n        Assert.assertNotNull(result.getId());\n        Assert.assertNotNull(result.getLatestMovies());\n        Assert.assertFalse(result.getLatestMovies().isEmpty());\n        Assert.assertNotNull(result.getLatestMovies().get(newRole1));\n        Assert.assertEquals(\"Mission:Impossible Ghost Protocol\", result.getLatestMovies().get(newRole1).getTitle());\n        Assert.assertEquals(\"l1\", result.getLatestMovies().get(newRole1).getId());\n        Assert.assertEquals(2011, result.getLatestMovies().get(newRole1).getYear());\n\n        Assert.assertNotNull(result.getLatestMovies().get(newRole2));\n        Assert.assertEquals(\"Jack Reacher\", result.getLatestMovies().get(newRole2).getTitle());\n        Assert.assertEquals(\"l2\", result.getLatestMovies().get(newRole2).getId());\n        Assert.assertEquals(2012, result.getLatestMovies().get(newRole2).getYear());\n\n        Assert.assertNotNull(result.getArchivedMovies());\n        Assert.assertFalse(result.getArchivedMovies().isEmpty());\n\n        Assert.assertNotNull(result.getArchivedMovies().get(oldRole1));\n        Assert.assertEquals(\"Top Gun\", result.getArchivedMovies().get(oldRole1).getTitle());\n        Assert.assertEquals(\"a1\", result.getArchivedMovies().get(oldRole1).getId());\n        Assert.assertEquals(1986, result.getArchivedMovies().get(oldRole1).getYear());\n\n        Assert.assertNotNull(result.getArchivedMovies().get(oldRole2));\n        Assert.assertEquals(\"A Few Good Men\", result.getArchivedMovies().get(oldRole2).getTitle());\n        Assert.assertEquals(\"a2\", result.getArchivedMovies().get(oldRole2).getId());\n        Assert.assertEquals(1992, result.getArchivedMovies().get(oldRole2).getYear());\n\n        // Remove\n        em.getTransaction().begin();\n        em.remove(result);\n        em.getTransaction().commit();\n        result = em.find(ActorWithMultipleRelation.class, 1);\n        Assert.assertNull(result);\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/ArchivedMovie.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Movie Node entity class\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table\n@IndexCollection(columns = { @Index(name = \"title\", type = \"KEYS\"), @Index(name = \"year\", type = \"KEYS\") })\npublic class ArchivedMovie\n{\n    @Id\n    @Column(name = \"MOVIE_ID\")\n    private String id;\n\n    @Column(name = \"TITLE\")\n    private String title;\n\n    @Column(name = \"YEAR\")\n    private int year;\n\n    @ManyToMany(fetch = FetchType.LAZY, mappedBy = \"movies\")\n    private Map<OldRole, ActorWithMultipleRelation> actors;\n\n    public ArchivedMovie()\n    {\n    }\n\n    public ArchivedMovie(String id, String title, int year)\n    {\n        this.id = id;\n        this.title = title;\n        this.year = year;\n    }\n\n    public void addActor(OldRole role, ActorWithMultipleRelation actor)\n    {\n        if (actors == null)\n            actors = new HashMap<OldRole, ActorWithMultipleRelation>();\n        actors.put(role, actor);\n    }\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * @param title\n     *            the title to set\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * @return the year\n     */\n    public int getYear()\n    {\n        return year;\n    }\n\n    /**\n     * @param year\n     *            the year to set\n     */\n    public void setYear(int year)\n    {\n        this.year = year;\n    }\n\n    /**\n     * @return the actors\n     */\n    public Map<OldRole, ActorWithMultipleRelation> getActors()\n    {\n        return actors;\n    }\n\n    /**\n     * @param actors\n     *            the actors to set\n     */\n    public void setActors(Map<OldRole, ActorWithMultipleRelation> actors)\n    {\n        this.actors = actors;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/IMDBBatchInsertionTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.neo4j.kernel.impl.util.FileUtils;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * Test case demonstrating batch insertion in Neo4J\n * \n * @author amresh.singh\n */\npublic class IMDBBatchInsertionTest\n{\n    private static final String IMDB_BATCH_PU = \"imdbBatch\";\n\n    EntityManagerFactory emf;\n\n    EntityManager em;\n\n    final int n = 4; // Number of actors\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        Map properties = new HashMap();\n        properties.put(PersistenceProperties.KUNDERA_BATCH_SIZE, \"5\");\n        emf = Persistence.createEntityManagerFactory(IMDB_BATCH_PU, properties);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance(), IMDB_BATCH_PU);\n        String datastoreFilePath = puMetadata.getProperty(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);\n\n        em.close();\n        \n        emf.close();\n\n        if (datastoreFilePath != null)\n            FileUtils.deleteRecursively(new File(datastoreFilePath));\n    }\n\n    @Test\n    public void batchTest()\n    {\n\n        List<Actor> actors = prepareData(n);\n\n        for (Actor actor : actors)\n        {\n            if (actor != null)\n            {\n                em.persist(actor);\n            }\n        }\n    }\n\n    /**\n     * n = number of Actors\n     * \n     * @param n\n     * @return\n     */\n    private List<Actor> prepareData(int n)\n    {\n        List<Actor> actors = new ArrayList<Actor>();\n        actors.add(0, null);\n        List<Movie> movies = new ArrayList<Movie>();\n        movies.add(0, null);\n        List<Role> roles = new ArrayList<Role>();\n        roles.add(0, null);\n\n        for (int i = 1; i <= (n + 1); i++)\n        {\n            Movie movie = new Movie(\"\" + i, \"Movie \" + i, (2000 + i));\n            movies.add(i, movie);\n        }\n\n        for (int i = 1; i <= 2 * n; i++)\n        {\n            Role role = new Role(\"Role \" + i, \"Role Type \" + i);\n            roles.add(i, role);\n        }\n\n        for (int i = 1; i <= n; i++)\n        {\n            Actor actor = new Actor(i, \"Actor \" + i);\n            actors.add(i, actor);\n\n        }\n\n        for (int i = 1; i <= n; i++)\n        {\n            Actor actor = actors.get(i);\n            actor.addMovie(roles.get(2 * i - 1), movies.get(i));\n            actor.addMovie(roles.get(2 * i), movies.get(i + 1));\n\n            if (i == 1)\n            {\n                movies.get(i).addActor(roles.get(i), actor);\n            }\n            else\n            {\n                movies.get(i).addActor(roles.get(2 * i - 2), actors.get(i - 1));\n                movies.get(i).addActor(roles.get(2 * i - 1), actors.get(i));\n            }\n        }\n        movies.get(n + 1).addActor(roles.get(2 * n), actors.get(n));\n\n        return actors;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/IMDBCRUDTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * Test case using IMDB example for CRUD Demonstrates M-2-M Association between\n * two entitites using Map\n * \n * @author amresh.singh\n */\npublic class IMDBCRUDTest extends IMDBTestBase\n{\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        init();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        clean();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        // CRUD\n        insert();\n        find();\n        merge();\n        delete();\n    }\n\n    private void insert()\n    {\n        populateActors();\n\n        em.getTransaction().begin();\n\n        em.persist(actor1);\n        em.persist(actor2);\n\n        em.getTransaction().commit();\n\n    }\n\n    private void find()\n    {\n        // Find actor by ID\n        em.clear();\n\n        Actor actor1 = em.find(Actor.class, 1);\n        Actor actor2 = em.find(Actor.class, 2);\n\n        assertActors(actor1, actor2);\n\n    }\n\n    private void merge()\n    {\n        Actor actor1 = em.find(Actor.class, 1);\n        Actor actor2 = em.find(Actor.class, 2);\n\n        assertActors(actor1, actor2);\n\n        actor1.setName(\"Amresh\");\n        actor2.setName(\"Amir\");\n\n        em.getTransaction().begin();\n        em.merge(actor1);\n        em.merge(actor2);\n        em.getTransaction().commit();\n\n        em.clear();\n\n        Actor actor1AfterMerge = em.find(Actor.class, 1);\n        Actor actor2AfterMerge = em.find(Actor.class, 2);\n\n        assertUpdatedActors(actor1AfterMerge, actor2AfterMerge);\n\n    }\n\n    private void delete()\n    {\n        em.clear();\n        Actor actor1 = em.find(Actor.class, 1);\n        Actor actor2 = em.find(Actor.class, 2);\n        assertUpdatedActors(actor1, actor2);\n\n        em.getTransaction().begin();\n        em.remove(actor1);\n        em.remove(actor2);\n        em.getTransaction().commit();\n\n        em.clear(); // clear cache\n        Actor actor1AfterDeletion = em.find(Actor.class, 1);\n        Actor actor2AfterDeletion = em.find(Actor.class, 2);\n\n        Assert.assertNull(actor1AfterDeletion);\n        Assert.assertNull(actor2AfterDeletion);\n\n        Movie movie1AfterDeletion = em.find(Movie.class, \"m1\");\n        Movie movie2AfterDeletion = em.find(Movie.class, \"m2\");\n        Movie movie3AfterDeletion = em.find(Movie.class, \"m3\");\n\n        Assert.assertNull(movie1AfterDeletion);\n        Assert.assertNull(movie2AfterDeletion);\n        Assert.assertNull(movie3AfterDeletion);\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/IMDBJPAQueriesTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * * Test case using IMDB example for JPA Queries Demonstrates M-2-M Association\n * between two entitites using Map\n * \n * @author amresh.singh\n */\npublic class IMDBJPAQueriesTest extends IMDBTestBase\n{\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        init();\n\n        // Prepare and insert data\n        populateActors();\n        em.getTransaction().begin();\n        em.persist(actor1);\n        em.persist(actor2);\n        em.getTransaction().commit();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        // Delete inserted records\n        Actor actor1 = em.find(Actor.class, 1);\n        Actor actor2 = em.find(Actor.class, 2);\n\n        if (actor1 != null && actor2 != null)\n        {\n            em.getTransaction().begin();\n            em.remove(actor1);\n            em.remove(actor2);\n            em.getTransaction().commit();\n        }\n\n        clean();\n    }\n\n    @Test\n    public void testJPAQueries()\n    {\n        // Select Queries\n        findAllActors();\n        findActorByID();\n        findActorByName();\n        findActorByIDAndName();\n        findActorUsingInClause();\n        findActorWithMatchingName();\n        findActorWithinGivenIdRange();\n        findSelectedFields();\n        findMoviesBetweenAPeriod();\n        findMoviesGreaterThanLessThanYear();\n        findMoviesUsingIdOrTitle();\n        findMoviesUsingIdOrTitleOrYear();\n        // Delete Queries\n        deleteAllActors();\n\n    }\n\n    private void findAllActors()\n    {\n        Query query = em.createQuery(\"select a from Actor a\");\n        List<Actor> actors = query.getResultList();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(2, actors.size());\n    }\n\n    private void findActorByID()\n    {\n        Query query = em.createQuery(\"select a from Actor a where a.id = :id\");\n        query.setParameter(\"id\", 2);\n        List<Actor> actors = query.getResultList();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(1, actors.size());\n        assertActor2(actors.get(0));\n    }\n\n    private void findActorByName()\n    {\n        Query query = em.createQuery(\"select a from Actor a where a.name=:name\");\n        query.setParameter(\"name\", \"Tom Cruise\");\n        List<Actor> actors = query.getResultList();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(1, actors.size());\n        assertActor1(actors.get(0));\n    }\n\n    private void findActorByIDAndName()\n    {\n        // Positive scenario\n        Query query = em.createQuery(\"select a from Actor a where a.id=:id AND a.name=:name\");\n        query.setParameter(\"id\", 1);\n        query.setParameter(\"name\", \"Tom Cruise\");\n        List<Actor> actors = query.getResultList();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(1, actors.size());\n        assertActor1(actors.get(0));\n\n        // Negative scenario\n        query = em.createQuery(\"select a from Actor a where a.id=:id AND a.name=:name\");\n        query.setParameter(\"id\", 2);\n        query.setParameter(\"name\", \"Tom Cruise\");\n        actors = query.getResultList();\n        Assert.assertTrue(actors == null || actors.isEmpty());\n    }\n\n    private void findActorUsingInClause() {\n        \tQuery query = em.createQuery(\"select a from Actor a where a.name in ('Tom Cruise','Emmanuelle Béart')\");\n        \tList<Actor> actors = query.getResultList();\n        \tAssert.assertNotNull(actors);\n            Assert.assertFalse(actors.isEmpty());\n            Assert.assertEquals(2, actors.size());\n            \n            query = em.createQuery(\"select a from Actor a where a.name in ('Tom Cruise','Brad Pitt')\");\n        \tactors = query.getResultList();\n        \tAssert.assertNotNull(actors);\n            Assert.assertFalse(actors.isEmpty());\n            Assert.assertEquals(1, actors.size());\n            \n            query = em.createQuery(\"select a from Actor a where a.name in :names\");\n            List<String> names = new ArrayList<String>();\n            names.add(\"Tom Cruise\");\n            names.add(\"Brad Pitt\");\n            query.setParameter(\"names\", names);\n        \tactors = query.getResultList();\n        \tAssert.assertNotNull(actors);\n            Assert.assertFalse(actors.isEmpty());\n            Assert.assertEquals(1, actors.size());\n    \t\t\n            query = em.createQuery(\"select a from Actor a where a.name in :names\");\n            String[] namesArray = new String[]{\"Tom Cruise\",\"Brad Pitt\"};\n            query.setParameter(\"names\", namesArray);\n        \tactors = query.getResultList();\n        \tAssert.assertNotNull(actors);\n            Assert.assertFalse(actors.isEmpty());\n            Assert.assertEquals(1, actors.size());\n    \t}\n\n    private void findActorWithMatchingName()\n    {\n        Query query = em.createQuery(\"select a from Actor a where a.name like :name\");\n        query.setParameter(\"name\", \"Emma\");\n        List<Actor> actors = query.getResultList();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(1, actors.size());\n        assertActor2(actors.get(0));\n    }\n\n    private void findActorWithinGivenIdRange()\n    {\n        Query query = em.createQuery(\"select a from Actor a where a.id between :min AND :max\");\n        query.setParameter(\"min\", 1);\n        query.setParameter(\"max\", 2);\n        List<Actor> actors = query.getResultList();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(2, actors.size());\n        // assertActor2(actors.get(0));\n    }\n\n    private void findMoviesBetweenAPeriod()\n    {\n        // Between\n        Query query = em.createQuery(\"select m from Movie m where m.year between :start AND :end\");\n        query.setParameter(\"start\", 1990);\n        query.setParameter(\"end\", 2006);\n        List<Movie> movies = query.getResultList();\n        Assert.assertNotNull(movies);\n        Assert.assertFalse(movies.isEmpty());\n        Assert.assertEquals(2, movies.size());\n\n    }\n\n    private void findMoviesGreaterThanLessThanYear()\n    {\n        // Greater-than/ Less Than\n        Query query = em.createQuery(\"select m from Movie m where m.year >= :start AND m.year <= :end\");\n        query.setParameter(\"start\", 2005);\n        query.setParameter(\"end\", 2010);\n        List<Movie> movies = query.getResultList();\n        Assert.assertNotNull(movies);\n        Assert.assertFalse(movies.isEmpty());\n        Assert.assertEquals(2, movies.size());\n    }\n\n    private void findSelectedFields()\n    {\n        Query query = em.createQuery(\"select a.name from Actor a\");\n        List<Actor> actors = query.getResultList();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(2, actors.size());\n\n        for (Actor actor : actors)\n        {\n            Assert.assertNotNull(actor);\n            Assert.assertNotNull(actor.getId());\n            Assert.assertNotNull(actor.getName());\n        }\n    }\n\n    private void findMoviesUsingIdOrTitle()\n    {\n        Query query = em.createQuery(\"select m from Movie m where m.id = :movieId OR m.title like :title\");\n        query.setParameter(\"movieId\", \"m1\");\n        query.setParameter(\"title\", \"Miss\");\n        List<Movie> movies = query.getResultList();\n        Assert.assertNotNull(movies);\n        Assert.assertFalse(movies.isEmpty());\n        Assert.assertEquals(2, movies.size());\n\n        for (Movie movie : movies)\n        {\n            Assert.assertNotNull(movie);\n            Assert.assertTrue(movie.getId().equals(\"m1\") || movie.getId().equals(\"m2\"));\n        }\n    }\n\n    private void findMoviesUsingIdOrTitleOrYear()\n    {\n        Query query = em\n                .createQuery(\"select m from Movie m where m.id = :movieId OR m.title like :title OR m.year = :year\");\n        query.setParameter(\"movieId\", \"m1\");\n        query.setParameter(\"title\", \"Miss\");\n        query.setParameter(\"year\", 2009);\n        List<Movie> movies = query.getResultList();\n        Assert.assertNotNull(movies);\n        Assert.assertFalse(movies.isEmpty());\n        Assert.assertEquals(3, movies.size());\n\n        for (Movie movie : movies)\n        {\n            Assert.assertNotNull(movie);\n            Assert.assertTrue(movie.getId().equals(\"m1\") || movie.getId().equals(\"m2\") || movie.getId().equals(\"m3\"));\n        }\n    }\n\n    private void deleteAllActors()\n    {\n        em.getTransaction().begin();\n        Query query = em.createQuery(\"delete from Actor a\");\n        int deleteCount = query.executeUpdate();\n        em.getTransaction().commit();\n        Assert.assertEquals(2, deleteCount);\n\n        // Check whether all records have been deleted\n        query = em.createQuery(\"select a from Actor a\");\n        List<Actor> actors = query.getResultList();\n        Assert.assertTrue(actors == null || actors.isEmpty());\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/IMDBMapMetamodelTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport javax.persistence.metamodel.Metamodel;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\n\n/**\n * Test case for validating correctness of Metamodel for Map data type\n * \n * @author amresh.singh\n */\npublic class IMDBMapMetamodelTest extends IMDBTestBase\n{\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        init();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        clean();\n    }\n\n    @Test\n    public void testMetamodel()\n    {\n        EntityMetadata m1 = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Actor.class);\n        Assert.assertNotNull(m1);\n        Assert.assertEquals(Actor.class, m1.getEntityClazz());\n        Assert.assertEquals(Role.class, m1.getRelation(\"movies\").getMapKeyJoinClass());\n        Assert.assertEquals(Movie.class, m1.getRelation(\"movies\").getTargetEntity());\n        Assert.assertEquals(\"ACTS_IN\", m1.getRelation(\"movies\").getJoinColumnName(kunderaMetadata));\n\n        EntityMetadata m2 = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Movie.class);\n        Assert.assertNotNull(m2);\n        Assert.assertEquals(Movie.class, m2.getEntityClazz());\n        Assert.assertEquals(Role.class, m2.getRelation(\"actors\").getMapKeyJoinClass());\n        Assert.assertEquals(Actor.class, m2.getRelation(\"actors\").getTargetEntity());\n        Assert.assertNotNull(m2.getRelation(\"actors\").getJoinColumnName(kunderaMetadata));\n        Assert.assertEquals(m2.getRelation(\"actors\").getJoinColumnName(kunderaMetadata),\"actors\");\n\n        EntityMetadata m3 = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, Role.class);\n        Assert.assertNotNull(m3);\n        Assert.assertEquals(Role.class, m3.getEntityClazz());\n\n        Metamodel mm = KunderaMetadataManager.getMetamodel(kunderaMetadata, \"imdb\");\n        Assert.assertNotNull(mm);\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/IMDBNativeLuceneQueryTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport java.util.List;\n\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * Unit test case for Native queries (Lucene)\n * \n * @author amresh.singh\n */\npublic class IMDBNativeLuceneQueryTest extends IMDBTestBase\n{\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        init();\n\n        // Prepare and insert data\n        populateActors();\n        em.getTransaction().begin();\n        em.persist(actor1);\n        em.persist(actor2);\n        em.getTransaction().commit();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        // Delete inserted records\n        Actor actor1 = em.find(Actor.class, 1);\n        Actor actor2 = em.find(Actor.class, 2);\n\n        if (actor1 != null && actor2 != null)\n        {\n            em.getTransaction().begin();\n            em.remove(actor1);\n            em.remove(actor2);\n            em.getTransaction().commit();\n        }\n\n        clean();\n    }\n\n    @Test\n    public void testLuceneQueries()\n    {\n        // Select Queries\n        findAllActors();\n        findActorByID();\n        findActorByName();\n        findActorByIDAndName();\n        findActorWithMatchingName();\n        findActorWithinGivenIdRange();\n        findMoviesBetweenAPeriod();\n        findMoviesGreaterThanLessThanYear();\n        findMoviesUsingIdOrTitle();\n        findMoviesUsingIdOrTitleOrYear();\n\n    }\n\n    private void findAllActors()\n    {\n        Query query = em.createNativeQuery(\"ACTOR_ID:*\", Actor.class);\n        List<Actor> actors = query.getResultList();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(2, actors.size());\n    }\n\n    private void findActorByID()\n    {\n        Query query = em.createNativeQuery(\"ACTOR_ID:2\", Actor.class);\n        List<Actor> actors = query.getResultList();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(1, actors.size());\n        assertActor2(actors.get(0));\n    }\n\n    private void findActorByName()\n    {\n        Query query = em.createNativeQuery(\"ACTOR_NAME:\\\"Tom Cruise\\\"\", Actor.class);\n        List<Actor> actors = query.getResultList();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(1, actors.size());\n        assertActor1(actors.get(0));\n    }\n\n    private void findActorByIDAndName()\n    {\n        // Positive scenario\n        Query query = em.createNativeQuery(\"ACTOR_ID:1 AND ACTOR_NAME:\\\"Tom Cruise\\\"\", Actor.class);\n        List<Actor> actors = query.getResultList();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(1, actors.size());\n        assertActor1(actors.get(0));\n\n        // Negative scenario\n        query = em.createNativeQuery(\"ACTOR_ID:2 AND ACTOR_NAME:\\\"Tom Cruise\\\"\", Actor.class);\n        actors = query.getResultList();\n        Assert.assertTrue(actors == null || actors.isEmpty());\n    }\n\n    private void findActorWithMatchingName()\n    {\n        Query query = em.createNativeQuery(\"ACTOR_NAME:Emma*\", Actor.class);\n        List<Actor> actors = query.getResultList();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(1, actors.size());\n        assertActor2(actors.get(0));\n    }\n\n    private void findActorWithinGivenIdRange()\n    {\n        // Records are inclusive of range boundaries\n        Query query = em.createNativeQuery(\"ACTOR_ID:[1 TO 2]\", Actor.class);\n        List<Actor> actors = query.getResultList();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(2, actors.size());\n    }\n\n    private void findMoviesBetweenAPeriod()\n    {\n        // Between\n        // Records are exclusive of range boundaries\n        Query query = em.createNativeQuery(\"YEAR:{1989 TO 2007}\", Movie.class);\n        List<Movie> movies = query.getResultList();\n        Assert.assertNotNull(movies);\n        Assert.assertFalse(movies.isEmpty());\n        Assert.assertEquals(2, movies.size());\n\n    }\n\n    private void findMoviesGreaterThanLessThanYear()\n    {\n        // Greater-than/ Less Than\n        Query query = em.createNativeQuery(\"YEAR:[2005 TO 2010]\", Movie.class);\n        List<Movie> movies = query.getResultList();\n        Assert.assertNotNull(movies);\n        Assert.assertFalse(movies.isEmpty());\n        Assert.assertEquals(2, movies.size());\n    }\n\n    private void findMoviesUsingIdOrTitle()\n    {\n        Query query = em.createNativeQuery(\"MOVIE_ID:m1 OR TITLE:Miss*\", Movie.class);\n        List<Movie> movies = query.getResultList();\n        Assert.assertNotNull(movies);\n        Assert.assertFalse(movies.isEmpty());\n        Assert.assertEquals(2, movies.size());\n\n        for (Movie movie : movies)\n        {\n            Assert.assertNotNull(movie);\n            Assert.assertTrue(movie.getId().equals(\"m1\") || movie.getId().equals(\"m2\"));\n        }\n    }\n\n    private void findMoviesUsingIdOrTitleOrYear()\n    {\n        Query query = em.createNativeQuery(\"MOVIE_ID:m1 OR TITLE:Miss* OR YEAR:2009\", Movie.class);\n        List<Movie> movies = query.getResultList();\n        Assert.assertNotNull(movies);\n        Assert.assertFalse(movies.isEmpty());\n        Assert.assertEquals(3, movies.size());\n\n        for (Movie movie : movies)\n        {\n            Assert.assertNotNull(movie);\n            Assert.assertTrue(movie.getId().equals(\"m1\") || movie.getId().equals(\"m2\") || movie.getId().equals(\"m3\"));\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/IMDBTestBase.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.Assert;\nimport org.neo4j.kernel.impl.util.FileUtils;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * Base class for All IMDB Tests\n * \n * @author amresh.singh\n */\npublic class IMDBTestBase\n{\n    protected Actor actor1;\n\n    protected Actor actor2;\n\n    protected static EntityManagerFactory emf;\n\n    protected EntityManager em;\n\n    protected static final String IMDB_PU = \"imdb\";\n\n    protected KunderaMetadata kunderaMetadata;\n\n    /**\n     * @param actor1\n     * @param actor2\n     */\n    protected void assertActors(Actor actor1, Actor actor2)\n    {\n        assertActor1(actor1);\n        assertActor2(actor2);\n    }\n\n    /**\n     * @param actor2\n     */\n    protected void assertActor2(Actor actor2)\n    {\n        Assert.assertNotNull(actor2);\n        Assert.assertEquals(2, actor2.getId());\n        Assert.assertEquals(\"Emmanuelle Béart\", actor2.getName());\n        Map<Role, Movie> movies2 = actor2.getMovies();\n        Assert.assertFalse(movies2 == null || movies2.isEmpty());\n        Assert.assertEquals(2, movies2.size());\n        for (Role role : movies2.keySet())\n        {\n            Assert.assertNotNull(role);\n            Movie movie = movies2.get(role);\n            Assert.assertNotNull(movie);\n            Assert.assertTrue(movie.getActors() != null && !movie.getActors().isEmpty());\n        }\n    }\n\n    /**\n     * @param actor1\n     */\n    protected void assertActor1(Actor actor1)\n    {\n        Assert.assertNotNull(actor1);\n        Assert.assertEquals(1, actor1.getId());\n        Assert.assertEquals(\"Tom Cruise\", actor1.getName());\n        Map<Role, Movie> movies1 = actor1.getMovies();\n        Assert.assertFalse(movies1 == null || movies1.isEmpty());\n        Assert.assertEquals(2, movies1.size());\n        for (Role role : movies1.keySet())\n        {\n            Assert.assertNotNull(role);\n            Movie movie = movies1.get(role);\n            Assert.assertNotNull(movie);\n            Assert.assertTrue(movie.getActors() != null && !movie.getActors().isEmpty());\n        }\n    }\n\n    /**\n     * @param actor1\n     * @param actor2\n     */\n    protected void assertUpdatedActors(Actor actor1, Actor actor2)\n    {\n        assertUpdatedActor1(actor1);\n        assertUpdatedActor2(actor2);\n    }\n\n    /**\n     * @param actor2\n     */\n    protected void assertUpdatedActor2(Actor actor2)\n    {\n        Assert.assertNotNull(actor2);\n        Assert.assertEquals(2, actor2.getId());\n        Assert.assertEquals(\"Amir\", actor2.getName());\n        Map<Role, Movie> movies2 = actor2.getMovies();\n        Assert.assertFalse(movies2 == null || movies2.isEmpty());\n        Assert.assertEquals(2, movies2.size());\n        for (Role role : movies2.keySet())\n        {\n            Assert.assertNotNull(role);\n            Movie movie = movies2.get(role);\n            Assert.assertNotNull(movie);\n            Assert.assertTrue(movie.getActors() != null && !movie.getActors().isEmpty());\n        }\n    }\n\n    /**\n     * @param actor1\n     */\n    protected void assertUpdatedActor1(Actor actor1)\n    {\n        Assert.assertNotNull(actor1);\n        Assert.assertEquals(1, actor1.getId());\n        Assert.assertEquals(\"Amresh\", actor1.getName());\n        Map<Role, Movie> movies1 = actor1.getMovies();\n        Assert.assertFalse(movies1 == null || movies1.isEmpty());\n        Assert.assertEquals(2, movies1.size());\n        for (Role role : movies1.keySet())\n        {\n            Assert.assertNotNull(role);\n            Movie movie = movies1.get(role);\n            Assert.assertNotNull(movie);\n            Assert.assertTrue(movie.getActors() != null && !movie.getActors().isEmpty());\n        }\n    }\n\n    protected void populateActors()\n    {\n        // Actors\n        actor1 = new Actor(1, \"Tom Cruise\");\n        actor2 = new Actor(2, \"Emmanuelle Béart\");\n\n        // Movies\n        Movie movie1 = new Movie(\"m1\", \"War of the Worlds\", 2005);\n        Movie movie2 = new Movie(\"m2\", \"Mission Impossible\", 1996);\n        Movie movie3 = new Movie(\"m3\", \"Hell\", 2009);\n\n        // Roles\n        Role role1 = new Role(\"Ray Ferrier\", \"Lead Actor\");\n        role1.setActor(actor1);\n        role1.setMovie(movie1);\n        Role role2 = new Role(\"Ethan Hunt\", \"Lead Actor\");\n        role2.setActor(actor1);\n        role2.setMovie(movie2);\n        Role role3 = new Role(\"Claire Phelps\", \"Lead Actress\");\n        role3.setActor(actor2);\n        role1.setMovie(movie2);\n        Role role4 = new Role(\"Sophie\", \"Supporting Actress\");\n        role4.setActor(actor2);\n        role1.setMovie(movie3);\n\n        // Relationships\n        actor1.addMovie(role1, movie1);\n        actor1.addMovie(role2, movie2);\n        actor2.addMovie(role3, movie2);\n        actor2.addMovie(role4, movie3);\n\n        movie1.addActor(role1, actor1);\n        movie2.addActor(role2, actor1);\n        movie2.addActor(role3, actor2);\n        movie3.addActor(role4, actor2);\n    }\n\n    protected void init()\n    {\n        emf = Persistence.createEntityManagerFactory(IMDB_PU);\n        kunderaMetadata = ((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance();\n        em = emf.createEntityManager();\n    }\n\n    protected void clean() throws IOException\n    {\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager\n                .getPersistenceUnitMetadata(kunderaMetadata, IMDB_PU);\n        String datastoreFilePath = puMetadata.getProperty(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);\n\n        em.close();\n        emf.close();\n\n        if (datastoreFilePath != null)\n            FileUtils.deleteRecursively(new File(datastoreFilePath));\n    }\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/IMDBTransactionTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * Test case for validating transaction handling provided by Kundera for Neo4J\n * \n * @author amresh.singh\n */\npublic class IMDBTransactionTest extends IMDBTestBase\n{\n\n\n    /*    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(IMDB_PU);\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata, IMDB_PU);\n        String datastoreFilePath = puMetadata.getProperty(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);\n        FileUtils.deleteRecursively(new File(datastoreFilePath));\n//        emf.close();\n    }*/\n\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        init();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n        em.getTransaction().begin();\n        em.remove(actor1);\n        em.remove(actor2);\n        em.getTransaction().commit();\n\n//        em.close();\n        clean();\n    }\n\n    @Test\n    public void withTransaction()\n    {\n        try\n        {\n            /** Prepare data */\n            // Actors\n            populateActors();\n\n            /** Insert records */\n            em.getTransaction().begin();\n            em.persist(actor1);\n            em.persist(actor2);\n            em.getTransaction().commit();\n\n            /** Find records (Doesn't need transaction) */\n            Actor actor11 = em.find(Actor.class, 1);\n            Actor actor22 = em.find(Actor.class, 2);\n            assertActors(actor11, actor22);\n\n            /** Update records */\n            em.clear();\n            actor1.setName(\"Amresh\");\n            actor2.setName(\"Amir\");\n            em.getTransaction().begin();\n            em.merge(actor1);\n            em.merge(actor2);\n            em.getTransaction().commit();\n            em.clear();\n            Actor actor1AfterMerge = em.find(Actor.class, 1);\n            Actor actor2AfterMerge = em.find(Actor.class, 2);\n            assertUpdatedActors(actor1AfterMerge, actor2AfterMerge);\n\n            /** Delete records */\n//            em.clear();\n            em.getTransaction().begin();\n            em.remove(actor11);\n            em.getTransaction().commit();\n            em.getTransaction().begin();\n            em.remove(actor22);\n            em.getTransaction().commit();\n            em.clear(); // clear cache\n            Actor actor1AfterDeletion = em.find(Actor.class, 1);\n            Actor actor2AfterDeletion = em.find(Actor.class, 2);\n            Assert.assertNull(actor1AfterDeletion);\n            Assert.assertNull(actor2AfterDeletion);\n\n        }\n        catch (Exception e)\n        {\n            Assert.fail(e.getMessage());\n        }\n\n    }\n\n    @Test\n    public void withoutTransaction()\n    {\n        /** Prepare data */\n        populateActors();\n\n        /** Insert records without a transaction */\n        try\n        {\n            em.persist(actor1);\n            em.persist(actor2);\n            Assert.fail();\n        }\n        catch (Exception e)\n        {\n            Assert.assertTrue(e.getMessage().toString().indexOf(\"transaction\") >= 0);\n        }\n\n        /** Find records */\n        em.clear();\n        Actor actor11 = em.find(Actor.class, 1);\n        Actor actor22 = em.find(Actor.class, 2);\n        Assert.assertNull(actor11);\n        Assert.assertNull(actor22);\n\n    }\n\n    @Test\n    public void rollbackBehavior()\n    {\n        populateActors();\n\n        em.getTransaction().begin();\n        em.persist(actor1);\n        em.persist(actor2);\n        em.getTransaction().rollback();\n\n        em.clear();\n        Actor actor11 = em.find(Actor.class, 1);\n        Actor actor22 = em.find(Actor.class, 2);\n        Assert.assertNull(actor11);\n        Assert.assertNull(actor22);\n    }\n\n    @Test\n    public void rollbackBehaviorOnException()\n    {\n        populateActors();\n\n        try\n        {\n            em.getTransaction().begin();\n            em.persist(actor1);\n            em.persist(actor2);\n            em.getTransaction().commit();\n\n            em.getTransaction().begin();\n            actor1.setName(\"Amresh\");\n            actor2.setName(\"Amir\");\n            em.merge(actor1);\n            em.merge(actor2);\n            em.merge(null);\n            em.getTransaction().commit();\n        }\n        catch (Exception e)\n        {\n            em.clear();\n            Actor actor11 = em.find(Actor.class, 1);\n            Actor actor22 = em.find(Actor.class, 2);\n            Assert.assertNotNull(actor11);\n            Assert.assertNotNull(actor22);\n            Assert.assertNotSame(\"Amresh\", actor11.getName());\n            Assert.assertNotSame(\"Amir\", actor22.getName());\n\n        }\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/LatestMovie.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Movie Node entity class\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table\n@IndexCollection(columns = { @Index(name = \"title\", type = \"KEYS\"), @Index(name = \"year\", type = \"KEYS\") })\npublic class LatestMovie\n{\n    @Id\n    @Column(name = \"MOVIE_ID\")\n    private String id;\n\n    @Column(name = \"TITLE\")\n    private String title;\n\n    @Column(name = \"YEAR\")\n    private int year;\n\n    @ManyToMany(fetch = FetchType.LAZY, mappedBy = \"movies\")\n    private Map<NewRole, ActorWithMultipleRelation> actors;\n\n    public LatestMovie()\n    {\n    }\n\n    public LatestMovie(String id, String title, int year)\n    {\n        this.id = id;\n        this.title = title;\n        this.year = year;\n    }\n\n    public void addActor(NewRole role, ActorWithMultipleRelation actor)\n    {\n        if (actors == null)\n            actors = new HashMap<NewRole, ActorWithMultipleRelation>();\n        actors.put(role, actor);\n    }\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * @param title\n     *            the title to set\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * @return the year\n     */\n    public int getYear()\n    {\n        return year;\n    }\n\n    /**\n     * @param year\n     *            the year to set\n     */\n    public void setYear(int year)\n    {\n        this.year = year;\n    }\n\n    /**\n     * @return the actors\n     */\n    public Map<NewRole, ActorWithMultipleRelation> getActors()\n    {\n        return actors;\n    }\n\n    /**\n     * @param actors\n     *            the actors to set\n     */\n    public void setActors(Map<NewRole, ActorWithMultipleRelation> actors)\n    {\n        this.actors = actors;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/Movie.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Movie Node entity class\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table\n@IndexCollection(columns = { @Index(name = \"title\", type = \"KEYS\"), @Index(name = \"year\", type = \"KEYS\") })\npublic class Movie\n{\n    @Id\n    @Column(name = \"MOVIE_ID\")\n    private String id;\n\n    @Column(name = \"TITLE\")\n    private String title;\n\n    @Column(name = \"YEAR\")\n    private int year;\n\n    @ManyToMany(fetch = FetchType.LAZY, mappedBy = \"movies\")\n    private Map<Role, Actor> actors;\n\n    public Movie()\n    {\n    }\n\n    public Movie(String id, String title, int year)\n    {\n        this.id = id;\n        this.title = title;\n        this.year = year;\n    }\n\n    public void addActor(Role role, Actor actor)\n    {\n        if (actors == null)\n            actors = new HashMap<Role, Actor>();\n        actors.put(role, actor);\n    }\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * @param title\n     *            the title to set\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * @return the year\n     */\n    public int getYear()\n    {\n        return year;\n    }\n\n    /**\n     * @param year\n     *            the year to set\n     */\n    public void setYear(int year)\n    {\n        this.year = year;\n    }\n\n    /**\n     * @return the actors\n     */\n    public Map<Role, Actor> getActors()\n    {\n        return actors;\n    }\n\n    /**\n     * @param actors\n     *            the actors to set\n     */\n    public void setActors(Map<Role, Actor> actors)\n    {\n        this.actors = actors;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/NewRole.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Role Relationship entity class\n * \n * @author amresh.singh\n */\n@Entity\n@Table\n@IndexCollection(columns = { @Index(name = \"roleType\", type = \"KEYS\") })\npublic class NewRole\n{\n    @Id\n    @Column(name = \"ROLE_NAME\")\n    private String roleName;\n\n    @Column(name = \"ROLE_TYPE\")\n    private String roleType;\n\n    @OneToOne\n    private ActorWithMultipleRelation actor;\n\n    @OneToOne\n    private LatestMovie movie;\n\n    public NewRole()\n    {\n    }\n\n    public NewRole(String roleName, String roleType)\n    {\n        this.roleName = roleName;\n        this.roleType = roleType;\n    }\n\n    /**\n     * @return the roleName\n     */\n    public String getRoleName()\n    {\n        return roleName;\n    }\n\n    /**\n     * @param roleName\n     *            the roleName to set\n     */\n    public void setRoleName(String roleName)\n    {\n        this.roleName = roleName;\n    }\n\n    /**\n     * @return the roleType\n     */\n    public String getRoleType()\n    {\n        return roleType;\n    }\n\n    /**\n     * @param roleType\n     *            the roleType to set\n     */\n    public void setRoleType(String roleType)\n    {\n        this.roleType = roleType;\n    }\n\n    /**\n     * @return the actor\n     */\n    public ActorWithMultipleRelation getActor()\n    {\n        return actor;\n    }\n\n    /**\n     * @param actor\n     *            the actor to set\n     */\n    public void setActor(ActorWithMultipleRelation actor)\n    {\n        this.actor = actor;\n    }\n\n    /**\n     * @return the movie\n     */\n    public LatestMovie getMovie()\n    {\n        return movie;\n    }\n\n    /**\n     * @param movie\n     *            the movie to set\n     */\n    public void setMovie(LatestMovie movie)\n    {\n        this.movie = movie;\n    }\n\n    public boolean equals(Object o)\n    {\n        if (!(o instanceof NewRole))\n        {\n            return false;\n        }\n\n        NewRole that = (NewRole) o;\n\n        return (this.roleName == that.roleName || this.roleName.equals(that.roleName))\n                && (this.roleType == that.roleType || this.roleType.equals(that.roleType));\n\n    }\n\n    public int hashCode()\n    {\n        int h1 = (roleName == null) ? 0 : roleName.hashCode();\n        int h2 = (roleType == null) ? 0 : roleType.hashCode();\n        return h1 + 31 * h2;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/OldRole.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Role Relationship entity class\n * \n * @author amresh.singh\n */\n@Entity\n@Table\n@IndexCollection(columns = { @Index(name = \"roleType\", type = \"KEYS\") })\npublic class OldRole\n{\n    @Id\n    @Column(name = \"ROLE_NAME\")\n    private String roleName;\n\n    @Column(name = \"ROLE_TYPE\")\n    private String roleType;\n\n    @OneToOne\n    private ActorWithMultipleRelation actor;\n\n    @OneToOne\n    private ArchivedMovie movie;\n\n    public OldRole()\n    {\n    }\n\n    public OldRole(String roleName, String roleType)\n    {\n        this.roleName = roleName;\n        this.roleType = roleType;\n    }\n\n    /**\n     * @return the roleName\n     */\n    public String getRoleName()\n    {\n        return roleName;\n    }\n\n    /**\n     * @param roleName\n     *            the roleName to set\n     */\n    public void setRoleName(String roleName)\n    {\n        this.roleName = roleName;\n    }\n\n    /**\n     * @return the roleType\n     */\n    public String getRoleType()\n    {\n        return roleType;\n    }\n\n    /**\n     * @param roleType\n     *            the roleType to set\n     */\n    public void setRoleType(String roleType)\n    {\n        this.roleType = roleType;\n    }\n\n    /**\n     * @return the actor\n     */\n    public ActorWithMultipleRelation getActor()\n    {\n        return actor;\n    }\n\n    /**\n     * @param actor\n     *            the actor to set\n     */\n    public void setActor(ActorWithMultipleRelation actor)\n    {\n        this.actor = actor;\n    }\n\n    /**\n     * @return the movie\n     */\n    public ArchivedMovie getMovie()\n    {\n        return movie;\n    }\n\n    /**\n     * @param movie\n     *            the movie to set\n     */\n    public void setMovie(ArchivedMovie movie)\n    {\n        this.movie = movie;\n    }\n\n    public boolean equals(Object o)\n    {\n        if (!(o instanceof OldRole))\n        {\n            return false;\n        }\n\n        OldRole that = (OldRole) o;\n\n        return (this.roleName == that.roleName || this.roleName.equals(that.roleName))\n                && (this.roleType == that.roleType || this.roleType.equals(that.roleType));\n\n    }\n\n    public int hashCode()\n    {\n        int h1 = (roleName == null) ? 0 : roleName.hashCode();\n        int h2 = (roleType == null) ? 0 : roleType.hashCode();\n        return h1 + 31 * h2;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/Role.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Role Relationship entity class\n * \n * @author amresh.singh\n */\n@Entity\n@Table\n@IndexCollection(columns = { @Index(name = \"roleType\", type = \"KEYS\") })\npublic class Role\n{\n    @Id\n    @Column(name = \"ROLE_NAME\")\n    private String roleName;\n\n    @Column(name = \"ROLE_TYPE\")\n    private String roleType;\n\n    @OneToOne\n    private Actor actor;\n\n    @OneToOne\n    private Movie movie;\n\n    public Role()\n    {\n    }\n\n    public Role(String roleName, String roleType)\n    {\n        this.roleName = roleName;\n        this.roleType = roleType;\n    }\n\n    /**\n     * @return the roleName\n     */\n    public String getRoleName()\n    {\n        return roleName;\n    }\n\n    /**\n     * @param roleName\n     *            the roleName to set\n     */\n    public void setRoleName(String roleName)\n    {\n        this.roleName = roleName;\n    }\n\n    /**\n     * @return the roleType\n     */\n    public String getRoleType()\n    {\n        return roleType;\n    }\n\n    /**\n     * @param roleType\n     *            the roleType to set\n     */\n    public void setRoleType(String roleType)\n    {\n        this.roleType = roleType;\n    }\n\n    /**\n     * @return the actor\n     */\n    public Actor getActor()\n    {\n        return actor;\n    }\n\n    /**\n     * @param actor\n     *            the actor to set\n     */\n    public void setActor(Actor actor)\n    {\n        this.actor = actor;\n    }\n\n    /**\n     * @return the movie\n     */\n    public Movie getMovie()\n    {\n        return movie;\n    }\n\n    /**\n     * @param movie\n     *            the movie to set\n     */\n    public void setMovie(Movie movie)\n    {\n        this.movie = movie;\n    }\n\n    public boolean equals(Object o)\n    {\n        if (!(o instanceof Role))\n        {\n            return false;\n        }\n\n        Role that = (Role) o;\n\n        return (this.roleName == that.roleName || this.roleName.equals(that.roleName))\n                && (this.roleType == that.roleType || this.roleType.equals(that.roleType));\n\n    }\n\n    public int hashCode()\n    {\n        int h1 = (roleName == null) ? 0 : roleName.hashCode();\n        int h2 = (roleType == null) ? 0 : roleType.hashCode();\n        return h1 + 31 * h2;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/SimpleCRUDTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.neo4j.imdb;\n\nimport java.io.File;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.neo4j.kernel.impl.util.FileUtils;\n\n/**\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class SimpleCRUDTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private static final String IMDB_PU = \"neo4jTest\";\n\n    private String datastoreFilePath = \"target/newpath.db\";\n\n    @Before\n    public void setup() throws Exception\n    {\n        Map<String, String> propertyMap = new HashMap<String, String>();\n        propertyMap.put(\"kundera.datastore.file.path\", datastoreFilePath);\n\n        emf = Persistence.createEntityManagerFactory(IMDB_PU, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    // @Test\n    public void testDummy()\n    {\n\n    }\n\n    @Test\n    public void should_save_entity() throws Exception\n    {\n        Actor actor = new Actor();\n        actor.setId(1);\n        actor.setName(\"Tom cruise\");\n\n        em.getTransaction().begin();\n\n        em.persist(actor);\n\n        em.getTransaction().commit();\n\n        em.clear();\n\n        Actor foundActor = em.find(Actor.class, 1);\n        Assert.assertNotNull(foundActor);\n        Assert.assertEquals(\"Tom cruise\", foundActor.getName());\n        Assert.assertEquals(1, foundActor.getId());\n\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n\n        if (datastoreFilePath != null)\n        {\n            FileUtils.deleteRecursively(new File(datastoreFilePath));\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/composite/ActorComposite.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb.composite;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.MapKeyJoinColumn;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Actor Node Entity class\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table\n// Ignored for Neo4J\n@IndexCollection(columns = { @Index(name = \"name\", type = \"KEYS\") })\npublic class ActorComposite\n{\n    @EmbeddedId\n    private ActorId actorId;\n\n    @Column(name = \"ACTOR_NAME\")\n    private String name;\n\n    public ActorComposite()\n    {\n    }\n\n    public ActorComposite(ActorId actorId, String actorName)\n    {\n        this.actorId = actorId;\n        this.name = actorName;\n    }\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @MapKeyJoinColumn(name = \"ACTS_IN\")\n    private Map<RoleComposite, MovieComposite> movies;\n\n    public void addMovie(RoleComposite role, MovieComposite movie)\n    {\n        if (movies == null)\n            movies = new HashMap<RoleComposite, MovieComposite>();\n        movies.put(role, movie);\n    }\n\n    /**\n     * @return the actorId\n     */\n    public ActorId getActorId()\n    {\n        return actorId;\n    }\n\n    /**\n     * @param actorId\n     *            the actorId to set\n     */\n    public void setActorId(ActorId actorId)\n    {\n        this.actorId = actorId;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the movies\n     */\n    public Map<RoleComposite, MovieComposite> getMovies()\n    {\n        return movies;\n    }\n\n    /**\n     * @param movies\n     *            the movies to set\n     */\n    public void setMovies(Map<RoleComposite, MovieComposite> movies)\n    {\n        this.movies = movies;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/composite/ActorId.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb.composite;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * Class Holding Identity attributes for actors\n * \n * @author amresh.singh\n */\n@Embeddable\npublic class ActorId\n{\n    @Column(name = \"ACTOR_ID_PREFIX\")\n    private String prefix;\n\n    @Column(name = \"ACTOR_ID_SUFFIX\")\n    private int suffix;\n\n    public ActorId()\n    {\n    }\n\n    /**\n     * @param prefix\n     * @param suffix\n     */\n    public ActorId(String prefix, int suffix)\n    {\n        super();\n        this.prefix = prefix;\n        this.suffix = suffix;\n    }\n\n    /**\n     * @return the prefix\n     */\n    public String getPrefix()\n    {\n        return prefix;\n    }\n\n    /**\n     * @param prefix\n     *            the prefix to set\n     */\n    public void setPrefix(String prefix)\n    {\n        this.prefix = prefix;\n    }\n\n    /**\n     * @return the suffix\n     */\n    public int getSuffix()\n    {\n        return suffix;\n    }\n\n    /**\n     * @param suffix\n     *            the suffix to set\n     */\n    public void setSuffix(int suffix)\n    {\n        this.suffix = suffix;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/composite/IMDBCompositeKeyTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb.composite;\n\nimport java.io.File;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.neo4j.kernel.impl.util.FileUtils;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * Test case for entities that hold composite keys\n * \n * @author amresh.singh\n */\npublic class IMDBCompositeKeyTest\n{\n\n    EntityManagerFactory emf;\n\n    EntityManager em;\n\n    private static final String IMDB_PU = \"imdb\";\n\n    ActorComposite actor1;\n\n    ActorComposite actor2;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        \n        emf = Persistence.createEntityManagerFactory(IMDB_PU);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance(), IMDB_PU);\n        String datastoreFilePath = puMetadata.getProperty(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);\n\n        em.close();\n        emf.close();\n\n        if (datastoreFilePath != null)\n            FileUtils.deleteRecursively(new File(datastoreFilePath));\n\n    }\n\n    @Test\n    public void testCompositeKeys()\n    {\n        insert();\n        findById();\n        merge();\n        delete();\n    }\n\n    /**\n     * \n     */\n    public void insert()\n    {\n        prepareData();\n        em.getTransaction().begin();\n        em.persist(actor1);\n        em.persist(actor2);\n        em.getTransaction().commit();\n    }\n\n    private void findById()\n    {\n        // Find actor by ID\n        em.clear();\n        ActorComposite actor1 = em.find(ActorComposite.class, new ActorId(\"A\", 1));\n        ActorComposite actor2 = em.find(ActorComposite.class, new ActorId(\"A\", 2));\n\n        assertActors(actor1, actor2);\n    }\n\n    private void merge()\n    {\n        em.clear();\n        ActorComposite actor1 = em.find(ActorComposite.class, new ActorId(\"A\", 1));\n        ActorComposite actor2 = em.find(ActorComposite.class, new ActorId(\"A\", 2));\n        assertActors(actor1, actor2);\n\n        actor1.setName(\"Amresh\");\n        actor2.setName(\"Amir\");\n\n        em.getTransaction().begin();\n        em.merge(actor1);\n        em.merge(actor2);\n        em.getTransaction().commit();\n\n        em.clear();\n\n        ActorComposite actor1AfterMerge = em.find(ActorComposite.class, new ActorId(\"A\", 1));\n        ActorComposite actor2AfterMerge = em.find(ActorComposite.class, new ActorId(\"A\", 2));\n\n        assertUpdatedActors(actor1AfterMerge, actor2AfterMerge);\n    }\n\n    private void delete()\n    {\n        em.clear();\n        ActorComposite actor1 = em.find(ActorComposite.class, new ActorId(\"A\", 1));\n        ActorComposite actor2 = em.find(ActorComposite.class, new ActorId(\"A\", 2));\n\n        em.getTransaction().begin();\n        em.remove(actor1);\n        em.remove(actor2);\n        em.getTransaction().commit();\n\n        em.clear();\n        ActorComposite actor1AfterDeletion = em.find(ActorComposite.class, new ActorId(\"A\", 1));\n        ActorComposite actor2AfterDeletion = em.find(ActorComposite.class, new ActorId(\"A\", 2));\n        Assert.assertNull(actor1AfterDeletion);\n        Assert.assertNull(actor2AfterDeletion);\n    }\n\n    private void prepareData()\n    {\n        // Actors\n        actor1 = new ActorComposite(new ActorId(\"A\", 1), \"Tom Cruise\");\n        actor2 = new ActorComposite(new ActorId(\"A\", 2), \"Emmanuelle Béart\");\n\n        // Movies\n        MovieComposite movie1 = new MovieComposite(new MovieId('U', 11111111L), \"War of the Worlds\", 2005);\n        MovieComposite movie2 = new MovieComposite(new MovieId('U', 22222222L), \"Mission Impossible\", 1996);\n        MovieComposite movie3 = new MovieComposite(new MovieId('A', 33333333L), \"Hell\", 2005);\n\n        // Roles\n        RoleComposite role1 = new RoleComposite(new RoleId(\"Ray\", \"Ferrier\"), \"Lead Actor\");\n        role1.setActor(actor1);\n        role1.setMovie(movie1);\n        RoleComposite role2 = new RoleComposite(new RoleId(\"Ethan\", \"Hunt\"), \"Lead Actor\");\n        role2.setActor(actor1);\n        role2.setMovie(movie2);\n        RoleComposite role3 = new RoleComposite(new RoleId(\"Claire\", \"Phelps\"), \"Lead Actress\");\n        role3.setActor(actor2);\n        role1.setMovie(movie2);\n        RoleComposite role4 = new RoleComposite(new RoleId(\"Sophie\", \"\"), \"Supporting Actress\");\n        role4.setActor(actor2);\n        role1.setMovie(movie3);\n\n        // Relationships\n        actor1.addMovie(role1, movie1);\n        actor1.addMovie(role2, movie2);\n        actor2.addMovie(role3, movie2);\n        actor2.addMovie(role4, movie3);\n\n        movie1.addActor(role1, actor1);\n        movie2.addActor(role2, actor1);\n        movie2.addActor(role3, actor2);\n        movie3.addActor(role4, actor2);\n    }\n\n    private void assertActors(ActorComposite actor1, ActorComposite actor2)\n    {\n        Assert.assertNotNull(actor1);\n        Assert.assertEquals(\"A\", actor1.getActorId().getPrefix());\n        Assert.assertEquals(1, actor1.getActorId().getSuffix());\n        Assert.assertEquals(\"Tom Cruise\", actor1.getName());\n        Map<RoleComposite, MovieComposite> movies1 = actor1.getMovies();\n        Assert.assertFalse(movies1 == null || movies1.isEmpty());\n        Assert.assertEquals(2, movies1.size());\n\n        Assert.assertNotNull(actor2);\n        Assert.assertEquals(\"A\", actor2.getActorId().getPrefix());\n        Assert.assertEquals(2, actor2.getActorId().getSuffix());\n        Assert.assertEquals(\"Emmanuelle Béart\", actor2.getName());\n        Map<RoleComposite, MovieComposite> movies2 = actor2.getMovies();\n        Assert.assertFalse(movies2 == null || movies2.isEmpty());\n        Assert.assertEquals(2, movies2.size());\n    }\n\n    private void assertUpdatedActors(ActorComposite actor1, ActorComposite actor2)\n    {\n        Assert.assertNotNull(actor1);\n        Assert.assertEquals(\"A\", actor1.getActorId().getPrefix());\n        Assert.assertEquals(1, actor1.getActorId().getSuffix());\n        Assert.assertEquals(\"Amresh\", actor1.getName());\n        Map<RoleComposite, MovieComposite> movies1 = actor1.getMovies();\n        Assert.assertFalse(movies1 == null || movies1.isEmpty());\n        Assert.assertEquals(2, movies1.size());\n\n        Assert.assertNotNull(actor2);\n        Assert.assertEquals(\"A\", actor2.getActorId().getPrefix());\n        Assert.assertEquals(2, actor2.getActorId().getSuffix());\n        Assert.assertEquals(\"Amir\", actor2.getName());\n        Map<RoleComposite, MovieComposite> movies2 = actor2.getMovies();\n        Assert.assertFalse(movies2 == null || movies2.isEmpty());\n        Assert.assertEquals(2, movies2.size());\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/composite/MovieComposite.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb.composite;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Movie Node entity class\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table\n@IndexCollection(columns = { @Index(name = \"title\", type = \"KEYS\"), @Index(name = \"year\", type = \"KEYS\") })\npublic class MovieComposite\n{\n    @EmbeddedId\n    private MovieId movieId;\n\n    @Column(name = \"TITLE\")\n    private String title;\n\n    @Column(name = \"YEAR\")\n    private int year;\n\n    @ManyToMany(fetch = FetchType.LAZY, mappedBy = \"movies\")\n    private Map<RoleComposite, ActorComposite> actors;\n\n    public MovieComposite()\n    {\n    }\n\n    public MovieComposite(MovieId id, String title, int year)\n    {\n        this.movieId = id;\n        this.title = title;\n        this.year = year;\n    }\n\n    public void addActor(RoleComposite role, ActorComposite actor)\n    {\n        if (actors == null)\n            actors = new HashMap<RoleComposite, ActorComposite>();\n        actors.put(role, actor);\n    }\n\n    /**\n     * @return the movieId\n     */\n    public MovieId getMovieId()\n    {\n        return movieId;\n    }\n\n    /**\n     * @param movieId\n     *            the movieId to set\n     */\n    public void setMovieId(MovieId movieId)\n    {\n        this.movieId = movieId;\n    }\n\n    /**\n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * @param title\n     *            the title to set\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * @return the year\n     */\n    public int getYear()\n    {\n        return year;\n    }\n\n    /**\n     * @param year\n     *            the year to set\n     */\n    public void setYear(int year)\n    {\n        this.year = year;\n    }\n\n    /**\n     * @return the actors\n     */\n    public Map<RoleComposite, ActorComposite> getActors()\n    {\n        return actors;\n    }\n\n    /**\n     * @param actors\n     *            the actors to set\n     */\n    public void setActors(Map<RoleComposite, ActorComposite> actors)\n    {\n        this.actors = actors;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/composite/MovieId.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb.composite;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * Class Holding Identity attributes for movies\n * \n * @author amresh.singh\n */\n@Embeddable\npublic class MovieId\n{\n    @Column(name = \"CERTIFICATION\")\n    private char certification;\n\n    @Column(name = \"SERIAL_NUMBER\")\n    private long serialNumber;\n\n    public MovieId()\n    {\n    }\n\n    /**\n     * @param certification\n     * @param serialNumber\n     */\n    public MovieId(char certification, long serialNumber)\n    {\n        super();\n        this.certification = certification;\n        this.serialNumber = serialNumber;\n    }\n\n    /**\n     * @return the certification\n     */\n    public char getCertification()\n    {\n        return certification;\n    }\n\n    /**\n     * @param certification\n     *            the certification to set\n     */\n    public void setCertification(char certification)\n    {\n        this.certification = certification;\n    }\n\n    /**\n     * @return the serialNumber\n     */\n    public long getSerialNumber()\n    {\n        return serialNumber;\n    }\n\n    /**\n     * @param serialNumber\n     *            the serialNumber to set\n     */\n    public void setSerialNumber(long serialNumber)\n    {\n        this.serialNumber = serialNumber;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/composite/RoleComposite.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb.composite;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Role Relationship entity class\n * \n * @author amresh.singh\n */\n@Entity\n@Table\n@IndexCollection(columns = { @Index(name = \"roleType\", type = \"KEYS\") })\npublic class RoleComposite\n{\n    @EmbeddedId\n    private RoleId roleId;\n\n    @Column(name = \"ROLE_TYPE\")\n    private String roleType;\n\n    @OneToOne\n    private ActorComposite actor;\n\n    @OneToOne\n    private MovieComposite movie;\n\n    public RoleComposite()\n    {\n    }\n\n    public RoleComposite(RoleId id, String roleType)\n    {\n        this.roleId = id;\n        this.roleType = roleType;\n    }\n\n    /**\n     * @return the roleId\n     */\n    public RoleId getRoleId()\n    {\n        return roleId;\n    }\n\n    /**\n     * @param roleId\n     *            the roleId to set\n     */\n    public void setRoleId(RoleId roleId)\n    {\n        this.roleId = roleId;\n    }\n\n    /**\n     * @return the roleType\n     */\n    public String getRoleType()\n    {\n        return roleType;\n    }\n\n    /**\n     * @param roleType\n     *            the roleType to set\n     */\n    public void setRoleType(String roleType)\n    {\n        this.roleType = roleType;\n    }\n\n    /**\n     * @return the actor\n     */\n    public ActorComposite getActor()\n    {\n        return actor;\n    }\n\n    /**\n     * @param actor\n     *            the actor to set\n     */\n    public void setActor(ActorComposite actor)\n    {\n        this.actor = actor;\n    }\n\n    /**\n     * @return the movie\n     */\n    public MovieComposite getMovie()\n    {\n        return movie;\n    }\n\n    /**\n     * @param movie\n     *            the movie to set\n     */\n    public void setMovie(MovieComposite movie)\n    {\n        this.movie = movie;\n    }\n\n    public boolean equals(Object o)\n    {\n        if (!(o instanceof RoleComposite))\n        {\n            return false;\n        }\n\n        RoleComposite that = (RoleComposite) o;\n\n        return (this.roleId == that.roleId || this.roleId.equals(that.roleId))\n                && (this.roleType == that.roleType || this.roleType.equals(that.roleType));\n\n    }\n\n    public int hashCode()\n    {\n        int h1 = (roleId == null) ? 0 : roleId.hashCode();\n        int h2 = (roleType == null) ? 0 : roleType.hashCode();\n        return h1 + 31 * h2;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/composite/RoleId.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb.composite;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * Class Holding Identity attributes for roles\n * \n * @author amresh.singh\n */\n@Embeddable\npublic class RoleId\n{\n    @Column(name = \"FIRST_NAME\")\n    private String firstName;\n\n    @Column(name = \"LAST_NAME\")\n    private String lastName;\n\n    public RoleId()\n    {\n    }\n\n    /**\n     * @param firstName\n     * @param lastName\n     */\n    public RoleId(String firstName, String lastName)\n    {\n        super();\n        this.firstName = firstName;\n        this.lastName = lastName;\n    }\n\n    /**\n     * @return the firstName\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * @param firstName\n     *            the firstName to set\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * @return the lastName\n     */\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    /**\n     * @param lastName\n     *            the lastName to set\n     */\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n    public boolean equals(Object o)\n    {\n        if (!(o instanceof RoleId))\n        {\n            return false;\n        }\n\n        RoleId that = (RoleId) o;\n\n        return (this.firstName == that.firstName || this.firstName.equals(that.firstName))\n                && (this.lastName == that.lastName || this.lastName.equals(that.lastName));\n    }\n\n    public int hashCode()\n    {\n        int h1 = (firstName == null) ? 0 : firstName.hashCode();\n        int h2 = (lastName == null) ? 0 : lastName.hashCode();\n        return h1 + 31 * h2;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/datatype/ActorAllDataType.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb.datatype;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.MapKeyJoinColumn;\nimport javax.persistence.Table;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Entity Class for Actor\n * \n * @author amresh.singh\n */\n@Entity\n@Table\n// Ignored for Neo4J\n@IndexCollection(columns = { @Index(name = \"name\", type = \"KEYS\") })\npublic class ActorAllDataType\n{\n    @Id\n    @Column(name = \"ACTOR_ID\")\n    private int id;\n\n    @Column(name = \"ACTOR_NAME\")\n    private String name;\n\n    @Column(name = \"DEPARTMENT_ID\")\n    private long departmentId;\n\n    @Column(name = \"IS_EXCEPTIONAL\")\n    private boolean isExceptional;\n\n    @Column(name = \"GRADE\")\n    private char grade; // A,B,C,D,E,F for i to vi\n\n    @Column(name = \"DIGITAL_SIGNATURE\")\n    private byte digitalSignature;\n\n    @Column(name = \"RATING\")\n    private short rating; // 1-10\n\n    @Column(name = \"COMPLIANCE\")\n    private float compliance;\n\n    @Column(name = \"HEIGHT\")\n    private double height;\n\n    // Date-time types\n    @Column(name = \"ENROLMENT_DATE\")\n    @Temporal(TemporalType.DATE)\n    private java.util.Date enrolmentDate;\n\n    @Column(name = \"ENROLMENT_TIME\")\n    @Temporal(TemporalType.TIME)\n    private java.util.Date enrolmentTime;\n\n    @Column(name = \"JOINING_DATE_TIME\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private java.util.Date joiningDateAndTime;\n\n    // Wrapper types\n    @Column(name = \"YEARS_SPENT\")\n    private Integer yearsSpent;\n\n    @Column(name = \"UNIQUE_ID\")\n    private Long uniqueId;\n\n    @Column(name = \"MONTHLY_SALARY\")\n    private Double monthlySalary;\n\n    @Column(name = \"JOB_ATTEMPTS\")\n    private BigInteger jobAttempts;\n\n    @Column(name = \"ACCUMULATED_WEALTH\")\n    private BigDecimal accumulatedWealth;\n\n    @Column(name = \"GRADUATION_DAY\")\n    private Calendar graduationDay;\n\n    public ActorAllDataType()\n    {\n    }\n\n    public ActorAllDataType(int id, String name, long departmentId, boolean isExceptional, char grade,\n            byte digitalSignature, short rating, float compliance, double height, Date enrolmentDate,\n            Date enrolmentTime, Date joiningDateAndTime, Integer yearsSpent, Long uniqueId, Double monthlySalary,\n            BigInteger jobAttempts, BigDecimal accumulatedWealth, Calendar graduationDay)\n    {\n\n        super();\n        this.id = id;\n        this.name = name;\n        this.departmentId = departmentId;\n        this.isExceptional = isExceptional;\n        this.grade = grade;\n        this.digitalSignature = digitalSignature;\n        this.rating = rating;\n        this.compliance = compliance;\n        this.height = height;\n        this.enrolmentDate = enrolmentDate;\n        this.enrolmentTime = enrolmentTime;\n        this.joiningDateAndTime = joiningDateAndTime;\n        this.yearsSpent = yearsSpent;\n        this.uniqueId = uniqueId;\n        this.monthlySalary = monthlySalary;\n        this.jobAttempts = jobAttempts;\n        this.accumulatedWealth = accumulatedWealth;\n        this.graduationDay = graduationDay;\n    }\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @MapKeyJoinColumn(name = \"ACTS_IN\")\n    private Map<RoleAllDataType, MovieAllDataType> movies;\n\n    public void addMovie(RoleAllDataType role, MovieAllDataType movie)\n    {\n        if (movies == null)\n            movies = new HashMap<RoleAllDataType, MovieAllDataType>();\n        movies.put(role, movie);\n    }\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the departmentId\n     */\n    public long getDepartmentId()\n    {\n        return departmentId;\n    }\n\n    /**\n     * @param departmentId\n     *            the departmentId to set\n     */\n    public void setDepartmentId(long departmentId)\n    {\n        this.departmentId = departmentId;\n    }\n\n    /**\n     * @return the isExceptional\n     */\n    public boolean isExceptional()\n    {\n        return isExceptional;\n    }\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    public void setExceptional(boolean isExceptional)\n    {\n        this.isExceptional = isExceptional;\n    }\n\n    /**\n     * @return the grade\n     */\n    public char getGrade()\n    {\n        return grade;\n    }\n\n    /**\n     * @param grade\n     *            the grade to set\n     */\n    public void setGrade(char grade)\n    {\n        this.grade = grade;\n    }\n\n    /**\n     * @return the digitalSignature\n     */\n    public byte getDigitalSignature()\n    {\n        return digitalSignature;\n    }\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    public void setDigitalSignature(byte digitalSignature)\n    {\n        this.digitalSignature = digitalSignature;\n    }\n\n    /**\n     * @return the rating\n     */\n    public short getRating()\n    {\n        return rating;\n    }\n\n    /**\n     * @param rating\n     *            the rating to set\n     */\n    public void setRating(short rating)\n    {\n        this.rating = rating;\n    }\n\n    /**\n     * @return the compliance\n     */\n    public float getCompliance()\n    {\n        return compliance;\n    }\n\n    /**\n     * @param compliance\n     *            the compliance to set\n     */\n    public void setCompliance(float compliance)\n    {\n        this.compliance = compliance;\n    }\n\n    /**\n     * @return the height\n     */\n    public double getHeight()\n    {\n        return height;\n    }\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    public void setHeight(double height)\n    {\n        this.height = height;\n    }\n\n    /**\n     * @return the enrolmentDate\n     */\n    public java.util.Date getEnrolmentDate()\n    {\n        return enrolmentDate;\n    }\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    public void setEnrolmentDate(java.util.Date enrolmentDate)\n    {\n        this.enrolmentDate = enrolmentDate;\n    }\n\n    /**\n     * @return the enrolmentTime\n     */\n    public java.util.Date getEnrolmentTime()\n    {\n        return enrolmentTime;\n    }\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    public void setEnrolmentTime(java.util.Date enrolmentTime)\n    {\n        this.enrolmentTime = enrolmentTime;\n    }\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    public java.util.Date getJoiningDateAndTime()\n    {\n        return joiningDateAndTime;\n    }\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    public void setJoiningDateAndTime(java.util.Date joiningDateAndTime)\n    {\n        this.joiningDateAndTime = joiningDateAndTime;\n    }\n\n    /**\n     * @return the yearsSpent\n     */\n    public Integer getYearsSpent()\n    {\n        return yearsSpent;\n    }\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    public void setYearsSpent(Integer yearsSpent)\n    {\n        this.yearsSpent = yearsSpent;\n    }\n\n    /**\n     * @return the uniqueId\n     */\n    public Long getUniqueId()\n    {\n        return uniqueId;\n    }\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    public void setUniqueId(Long uniqueId)\n    {\n        this.uniqueId = uniqueId;\n    }\n\n    /**\n     * @return the monthlySalary\n     */\n    public Double getMonthlySalary()\n    {\n        return monthlySalary;\n    }\n\n    /**\n     * @param monthlySalary\n     *            the monthlySalary to set\n     */\n    public void setMonthlySalary(Double monthlySalary)\n    {\n        this.monthlySalary = monthlySalary;\n    }\n\n    /**\n     * @return the jobAttempts\n     */\n    public BigInteger getJobAttempts()\n    {\n        return jobAttempts;\n    }\n\n    /**\n     * @param jobAttempts\n     *            the jobAttempts to set\n     */\n    public void setJobAttempts(BigInteger jobAttempts)\n    {\n        this.jobAttempts = jobAttempts;\n    }\n\n    /**\n     * @return the accumulatedWealth\n     */\n    public BigDecimal getAccumulatedWealth()\n    {\n        return accumulatedWealth;\n    }\n\n    /**\n     * @param accumulatedWealth\n     *            the accumulatedWealth to set\n     */\n    public void setAccumulatedWealth(BigDecimal accumulatedWealth)\n    {\n        this.accumulatedWealth = accumulatedWealth;\n    }\n\n    /**\n     * @return the graduationDay\n     */\n    public Calendar getGraduationDay()\n    {\n        return graduationDay;\n    }\n\n    /**\n     * @param graduationDay\n     *            the graduationDay to set\n     */\n    public void setGraduationDay(Calendar graduationDay)\n    {\n        this.graduationDay = graduationDay;\n    }\n\n    /**\n     * @return the movies\n     */\n    public Map<RoleAllDataType, MovieAllDataType> getMovies()\n    {\n        return movies;\n    }\n\n    /**\n     * @param movies\n     *            the movies to set\n     */\n    public void setMovies(Map<RoleAllDataType, MovieAllDataType> movies)\n    {\n        this.movies = movies;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/datatype/IMDBAllDataTypeTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb.datatype;\n\nimport java.io.File;\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.neo4j.kernel.impl.util.FileUtils;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\n\n/**\n * Test case\n * \n * @author amresh.singh\n */\npublic class IMDBAllDataTypeTest\n{\n    EntityManagerFactory emf;\n\n    EntityManager em;\n\n    Calendar cal = Calendar.getInstance();\n\n    ActorAllDataType actor1;\n\n    ActorAllDataType actor2;\n\n    private static final String IMDB_PU = \"imdb\";\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(IMDB_PU);\n        em = emf.createEntityManager();\n\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        // Delete inserted records\n        ActorAllDataType actor1 = em.find(ActorAllDataType.class, 1);\n        ActorAllDataType actor2 = em.find(ActorAllDataType.class, 2);\n\n        if (actor1 != null && actor2 != null)\n        {\n            em.getTransaction().begin();\n            em.remove(actor1);\n            em.remove(actor2);\n            em.getTransaction().commit();\n        }\n\n        MovieAllDataType movie1 = em.find(MovieAllDataType.class, \"m1\");\n        MovieAllDataType movie2 = em.find(MovieAllDataType.class, \"m2\");\n        MovieAllDataType movie3 = em.find(MovieAllDataType.class, \"m3\");\n\n        if (movie1 != null)\n        {\n            em.getTransaction().begin();\n            em.remove(movie1);\n            em.getTransaction().commit();\n        }\n\n        if (movie2 != null)\n        {\n            em.getTransaction().begin();\n            em.remove(movie2);\n            em.getTransaction().commit();\n        }\n\n        if (movie3 != null)\n        {\n            em.getTransaction().begin();\n            em.remove(movie3);\n            em.getTransaction().commit();\n        }\n\n        PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(((EntityManagerFactoryImpl)emf).getKunderaMetadataInstance(), IMDB_PU);\n        String datastoreFilePath = puMetadata.getProperty(PersistenceProperties.KUNDERA_DATASTORE_FILE_PATH);\n\n        em.close();\n        emf.close();\n        if (datastoreFilePath != null)\n            FileUtils.deleteRecursively(new File(datastoreFilePath));\n\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        insert();\n        findById();\n        delete();\n    }\n\n    private void insert()\n    {\n        prepareData();\n\n        em.getTransaction().begin();\n        em.persist(actor1);\n        em.persist(actor2);\n        em.getTransaction().commit();\n    }\n\n    private void findById()\n    {\n        // Find actor by ID\n        em.clear();\n        ActorAllDataType actor1 = em.find(ActorAllDataType.class, 1);\n        ActorAllDataType actor2 = em.find(ActorAllDataType.class, 2);\n\n        assertActors(actor1, actor2);\n    }\n\n    private void delete()\n    {\n        ActorAllDataType actor1 = em.find(ActorAllDataType.class, 1);\n        ActorAllDataType actor2 = em.find(ActorAllDataType.class, 2);\n\n        em.getTransaction().begin();\n        em.remove(actor1);\n        em.remove(actor2);\n        em.getTransaction().commit();\n\n        em.clear();\n        ActorAllDataType actor11 = em.find(ActorAllDataType.class, 1);\n        ActorAllDataType actor22 = em.find(ActorAllDataType.class, 2);\n        Assert.assertNull(actor11);\n        Assert.assertNull(actor22);\n    }\n\n    private void assertActors(ActorAllDataType actor1, ActorAllDataType actor2)\n    {\n        Assert.assertNotNull(actor1);\n        Assert.assertEquals(1, actor1.getId());\n        Assert.assertEquals(\"Tom Cruise\", actor1.getName());\n        Assert.assertEquals(23456789l, actor1.getDepartmentId());\n        Assert.assertEquals(true, actor1.isExceptional());\n        Assert.assertEquals('C', actor1.getGrade());\n        Assert.assertEquals((byte) 8, actor1.getDigitalSignature());\n        Assert.assertEquals((short) 5, actor1.getRating());\n        Assert.assertEquals((float) 10.0, actor1.getCompliance(), 0.0);\n        Assert.assertEquals(163.12, actor1.getHeight(), 0.0);\n        Assert.assertEquals(new Date(Long.parseLong(\"1351667541111\")), actor1.getEnrolmentDate());\n        Assert.assertEquals(new Date(Long.parseLong(\"1351667542222\")), actor1.getEnrolmentTime());\n        Assert.assertEquals(new Date(Long.parseLong(\"1351667543333\")), actor1.getJoiningDateAndTime());\n        Assert.assertEquals(new Integer(2), actor1.getYearsSpent());\n        Assert.assertEquals(new Long(3634521523423L), actor1.getUniqueId());\n        Assert.assertEquals(new Double(7.23452342343), actor1.getMonthlySalary());\n        Assert.assertEquals(new BigInteger(\"123456789\"), actor1.getJobAttempts());\n        Assert.assertEquals(new BigDecimal(123456789), actor1.getAccumulatedWealth());\n        Assert.assertEquals(cal, actor1.getGraduationDay());\n\n        Map<RoleAllDataType, MovieAllDataType> movies1 = actor1.getMovies();\n        Assert.assertFalse(movies1 == null || movies1.isEmpty());\n        Assert.assertEquals(2, movies1.size());\n        for (RoleAllDataType role : movies1.keySet())\n        {\n            Assert.assertNotNull(role);\n            Assert.assertNotNull(role.getActor());\n            Assert.assertNotNull(role.getMovie());\n            Assert.assertNotNull(movies1.get(role));\n        }\n\n        Assert.assertNotNull(actor2);\n        Assert.assertEquals(2, actor2.getId());\n        Assert.assertEquals(\"Emmanuelle Béart\", actor2.getName());\n        Assert.assertEquals(23456790l, actor2.getDepartmentId());\n        Assert.assertEquals(false, actor2.isExceptional());\n        Assert.assertEquals('D', actor2.getGrade());\n        Assert.assertEquals((byte) 9, actor2.getDigitalSignature());\n        Assert.assertEquals((short) 6, actor2.getRating());\n        Assert.assertEquals((float) 11.3, actor2.getCompliance(), 0.0);\n        Assert.assertEquals(161.99, actor2.getHeight(), 0.0);\n        Assert.assertEquals(new Date(Long.parseLong(\"1351667544444\")), actor2.getEnrolmentDate());\n        Assert.assertEquals(new Date(Long.parseLong(\"1351667545555\")), actor2.getEnrolmentTime());\n        Assert.assertEquals(new Date(Long.parseLong(\"1351667546666\")), actor2.getJoiningDateAndTime());\n        Assert.assertEquals(new Integer(3), actor2.getYearsSpent());\n        Assert.assertEquals(new Long(3634521523453L), actor2.getUniqueId());\n        Assert.assertEquals(new Double(8.23452342343), actor2.getMonthlySalary());\n        Assert.assertEquals(new BigInteger(\"123456790\"), actor2.getJobAttempts());\n        Assert.assertEquals(new BigDecimal(123456790), actor2.getAccumulatedWealth());\n        Assert.assertEquals(cal, actor2.getGraduationDay());\n\n        Map<RoleAllDataType, MovieAllDataType> movies2 = actor2.getMovies();\n        Assert.assertFalse(movies2 == null || movies2.isEmpty());\n        Assert.assertEquals(2, movies2.size());\n\n        for (RoleAllDataType role : movies2.keySet())\n        {\n            Assert.assertNotNull(role);\n            Assert.assertNotNull(role.getActor());\n            Assert.assertNotNull(role.getMovie());\n            Assert.assertNotNull(movies2.get(role));\n        }\n    }\n\n    private void prepareData()\n    {\n        actor1 = new ActorAllDataType(1, \"Tom Cruise\", 23456789l, true, 'C', (byte) 8, (short) 5, (float) 10.0, 163.12,\n                new Date(Long.parseLong(\"1351667541111\")), new Date(Long.parseLong(\"1351667542222\")), new Date(\n                        Long.parseLong(\"1351667543333\")), 2, new Long(3634521523423L), new Double(7.23452342343),\n                new BigInteger(\"123456789\"), new BigDecimal(123456789), cal);\n\n        actor2 = new ActorAllDataType(2, \"Emmanuelle Béart\", 23456790l, false, 'D', (byte) 9, (short) 6, (float) 11.3,\n                161.99, new Date(Long.parseLong(\"1351667544444\")), new Date(Long.parseLong(\"1351667545555\")), new Date(\n                        Long.parseLong(\"1351667546666\")), 3, new Long(3634521523453L), new Double(8.23452342343),\n                new BigInteger(\"123456790\"), new BigDecimal(123456790), cal);\n\n        // Movies\n        MovieAllDataType movie1 = new MovieAllDataType(\"m1\", \"War of the Worlds\", 2005);\n        MovieAllDataType movie2 = new MovieAllDataType(\"m2\", \"Mission Impossible\", 1996);\n        MovieAllDataType movie3 = new MovieAllDataType(\"m3\", \"Hell\", 2005);\n\n        // Roles\n        RoleAllDataType role1 = new RoleAllDataType(\"Ray Ferrier\", \"Lead Actor\", 1, 354354354l, true, 'A', (byte) 8,\n                (short) 5, 3.7f, 6.5, new Date(Long.parseLong(\"1351667541111\")), new Date(\n                        Long.parseLong(\"1351667542222\")), new Date(Long.parseLong(\"1351667543333\")), 1, 98682342343l,\n                6.7, new BigInteger(\"1111111111111\"), new BigDecimal(1234567890), cal);\n        role1.setActor(actor1);\n        role1.setMovie(movie1);\n\n        RoleAllDataType role2 = new RoleAllDataType(\"Ethan Hunt\", \"Lead Actor\", 2, 354354355l, false, 'B', (byte) 9,\n                (short) 6, 3.8f, 6.8, new Date(Long.parseLong(\"1351667544444\")), new Date(\n                        Long.parseLong(\"1351667545555\")), new Date(Long.parseLong(\"1351667546666\")), 2, 98682342344l,\n                6.8, new BigInteger(\"22222222222222\"), new BigDecimal(1234567891), cal);\n        role2.setActor(actor1);\n        role2.setMovie(movie2);\n\n        RoleAllDataType role3 = new RoleAllDataType(\"Claire Phelps\", \"Lead Actress\", 3, 354354356l, true, 'C',\n                (byte) 10, (short) 7, 3.9f, 6.9, new Date(Long.parseLong(\"1351667547777\")), new Date(\n                        Long.parseLong(\"1351667548888\")), new Date(Long.parseLong(\"1351667549999\")), 3, 98682342345l,\n                6.9, new BigInteger(\"3333333333333\"), new BigDecimal(1234567892), cal);\n        role3.setActor(actor2);\n        role1.setMovie(movie2);\n\n        RoleAllDataType role4 = new RoleAllDataType(\"Sophie\", \"Supporting Actress\", 4, 354354357l, false, 'D',\n                (byte) 11, (short) 5, 3.7f, 7.0, new Date(Long.parseLong(\"1351667551111\")), new Date(\n                        Long.parseLong(\"1351667552222\")), new Date(Long.parseLong(\"1351667553333\")), 4, 98682342346l,\n                7.0, new BigInteger(\"4444444444444\"), new BigDecimal(1234567893), cal);\n        role4.setActor(actor2);\n        role1.setMovie(movie3);\n\n        // Relationships\n        actor1.addMovie(role1, movie1);\n        actor1.addMovie(role2, movie2);\n        actor2.addMovie(role3, movie2);\n        actor2.addMovie(role4, movie3);\n\n        movie1.addActor(role1, actor1);\n        movie2.addActor(role2, actor1);\n        movie2.addActor(role3, actor2);\n        movie3.addActor(role4, actor2);\n    }\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/datatype/MovieAllDataType.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb.datatype;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Movie entity containing all data type fields\n * \n * @author amresh.singh\n */\n@Entity\n@Table\n@IndexCollection(columns = { @Index(name = \"title\", type = \"KEYS\"), @Index(name = \"year\", type = \"KEYS\") })\npublic class MovieAllDataType\n{\n    @Id\n    @Column(name = \"MOVIE_ID\")\n    private String id;\n\n    @Column(name = \"TITLE\")\n    private String title;\n\n    @Column(name = \"YEAR\")\n    private int year;\n\n    @ManyToMany(fetch = FetchType.LAZY, mappedBy = \"movies\")\n    private Map<RoleAllDataType, ActorAllDataType> actors;\n\n    public MovieAllDataType()\n    {\n    }\n\n    public MovieAllDataType(String id, String title, int year)\n    {\n        super();\n        this.id = id;\n        this.title = title;\n        this.year = year;\n    }\n\n    public void addActor(RoleAllDataType role, ActorAllDataType actor)\n    {\n        if (actors == null)\n            actors = new HashMap<RoleAllDataType, ActorAllDataType>();\n        actors.put(role, actor);\n    }\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * @param title\n     *            the title to set\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * @return the year\n     */\n    public int getYear()\n    {\n        return year;\n    }\n\n    /**\n     * @param year\n     *            the year to set\n     */\n    public void setYear(int year)\n    {\n        this.year = year;\n    }\n\n    /**\n     * @return the actors\n     */\n    public Map<RoleAllDataType, ActorAllDataType> getActors()\n    {\n        return actors;\n    }\n\n    /**\n     * @param actors\n     *            the actors to set\n     */\n    public void setActors(Map<RoleAllDataType, ActorAllDataType> actors)\n    {\n        this.actors = actors;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/java/com/impetus/client/neo4j/imdb/datatype/RoleAllDataType.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.neo4j.imdb.datatype;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Role Entity containing all data types\n * \n * @author amresh.singh\n */\n@Entity\n@Table\n@IndexCollection(columns = { @Index(name = \"roleType\", type = \"KEYS\") })\npublic class RoleAllDataType\n{\n    @Id\n    @Column(name = \"ROLE_NAME\")\n    private String roleName;\n\n    @Column(name = \"ROLE_TYPE\")\n    private String roleType;\n\n    @Column(name = \"ROLE_CODE\")\n    private int roleCode;\n\n    @Column(name = \"ROLE_LOCATION_ID\")\n    private long roleLocationId;\n\n    @Column(name = \"IS_EXCEPTIONAL\")\n    private boolean isExceptional;\n\n    @Column(name = \"GRADE\")\n    private char grade; // A,B,C,D,E,F for i to vi\n\n    @Column(name = \"DIGITAL_SIGNATURE\")\n    private byte digitalSignature;\n\n    @Column(name = \"RATING\")\n    private short rating; // 1-10\n\n    @Column(name = \"COMPLIANCE\")\n    private float compliance;\n\n    @Column(name = \"IMDB_RATING\")\n    private double imdbRating;\n\n    // Date-time types\n    @Column(name = \"ROLE_START_DATE\")\n    @Temporal(TemporalType.DATE)\n    private java.util.Date roleStartDate;\n\n    @Column(name = \"ROLE_START_TIME\")\n    @Temporal(TemporalType.TIME)\n    private java.util.Date roleStartTime;\n\n    @Column(name = \"SCRIPT_READ_TIME\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private java.util.Date scriptReadTime;\n\n    // Wrapper types\n    @Column(name = \"YEARS_SPENT\")\n    private Integer yearsSpent;\n\n    @Column(name = \"UNIQUE_ID\")\n    private Long uniqueId;\n\n    @Column(name = \"REMUNERATION\")\n    private Double remuneration;\n\n    @Column(name = \"REHEARSAL_ATTEMPTS\")\n    private BigInteger rehearsalAttempts;\n\n    @Column(name = \"TO_BE_PAID_FOR_ROLE\")\n    private BigDecimal toBePaidForRole;\n\n    @Column(name = \"GRADUATION_DAY\")\n    private Calendar graduationDay;\n\n    @OneToOne\n    private ActorAllDataType actor;\n\n    @OneToOne\n    private MovieAllDataType movie;\n\n    public RoleAllDataType()\n    {\n\n    }\n\n    public RoleAllDataType(String roleName, String roleType, int roleCode, long roleLocationId, boolean isExceptional,\n            char grade, byte digitalSignature, short rating, float compliance, double imdbRating, Date roleStartDate,\n            Date roleStartTime, Date scriptReadTime, Integer yearsSpent, Long uniqueId, Double remuneration,\n            BigInteger rehearsalAttempts, BigDecimal toBePaidForRole, Calendar graduationDay)\n    {\n        super();\n        this.roleName = roleName;\n        this.roleType = roleType;\n        this.roleCode = roleCode;\n        this.roleLocationId = roleLocationId;\n        this.isExceptional = isExceptional;\n        this.grade = grade;\n        this.digitalSignature = digitalSignature;\n        this.rating = rating;\n        this.compliance = compliance;\n        this.imdbRating = imdbRating;\n        this.roleStartDate = roleStartDate;\n        this.roleStartTime = roleStartTime;\n        this.scriptReadTime = scriptReadTime;\n        this.yearsSpent = yearsSpent;\n        this.uniqueId = uniqueId;\n        this.remuneration = remuneration;\n        this.rehearsalAttempts = rehearsalAttempts;\n        this.toBePaidForRole = toBePaidForRole;\n        this.graduationDay = graduationDay;\n    }\n\n    /**\n     * @return the roleName\n     */\n    public String getRoleName()\n    {\n        return roleName;\n    }\n\n    /**\n     * @param roleName\n     *            the roleName to set\n     */\n    public void setRoleName(String roleName)\n    {\n        this.roleName = roleName;\n    }\n\n    /**\n     * @return the roleType\n     */\n    public String getRoleType()\n    {\n        return roleType;\n    }\n\n    /**\n     * @param roleType\n     *            the roleType to set\n     */\n    public void setRoleType(String roleType)\n    {\n        this.roleType = roleType;\n    }\n\n    /**\n     * @return the roleCode\n     */\n    public int getRoleCode()\n    {\n        return roleCode;\n    }\n\n    /**\n     * @param roleCode\n     *            the roleCode to set\n     */\n    public void setRoleCode(int roleCode)\n    {\n        this.roleCode = roleCode;\n    }\n\n    /**\n     * @return the roleLocationId\n     */\n    public long getRoleLocationId()\n    {\n        return roleLocationId;\n    }\n\n    /**\n     * @param roleLocationId\n     *            the roleLocationId to set\n     */\n    public void setRoleLocationId(long roleLocationId)\n    {\n        this.roleLocationId = roleLocationId;\n    }\n\n    /**\n     * @return the isExceptional\n     */\n    public boolean isExceptional()\n    {\n        return isExceptional;\n    }\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    public void setExceptional(boolean isExceptional)\n    {\n        this.isExceptional = isExceptional;\n    }\n\n    /**\n     * @return the grade\n     */\n    public char getGrade()\n    {\n        return grade;\n    }\n\n    /**\n     * @param grade\n     *            the grade to set\n     */\n    public void setGrade(char grade)\n    {\n        this.grade = grade;\n    }\n\n    /**\n     * @return the digitalSignature\n     */\n    public byte getDigitalSignature()\n    {\n        return digitalSignature;\n    }\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    public void setDigitalSignature(byte digitalSignature)\n    {\n        this.digitalSignature = digitalSignature;\n    }\n\n    /**\n     * @return the rating\n     */\n    public short getRating()\n    {\n        return rating;\n    }\n\n    /**\n     * @param rating\n     *            the rating to set\n     */\n    public void setRating(short rating)\n    {\n        this.rating = rating;\n    }\n\n    /**\n     * @return the compliance\n     */\n    public float getCompliance()\n    {\n        return compliance;\n    }\n\n    /**\n     * @param compliance\n     *            the compliance to set\n     */\n    public void setCompliance(float compliance)\n    {\n        this.compliance = compliance;\n    }\n\n    /**\n     * @return the imdbRating\n     */\n    public double getImdbRating()\n    {\n        return imdbRating;\n    }\n\n    /**\n     * @param imdbRating\n     *            the imdbRating to set\n     */\n    public void setImdbRating(double imdbRating)\n    {\n        this.imdbRating = imdbRating;\n    }\n\n    /**\n     * @return the roleStartDate\n     */\n    public java.util.Date getRoleStartDate()\n    {\n        return roleStartDate;\n    }\n\n    /**\n     * @param roleStartDate\n     *            the roleStartDate to set\n     */\n    public void setRoleStartDate(java.util.Date roleStartDate)\n    {\n        this.roleStartDate = roleStartDate;\n    }\n\n    /**\n     * @return the roleStartTime\n     */\n    public java.util.Date getRoleStartTime()\n    {\n        return roleStartTime;\n    }\n\n    /**\n     * @param roleStartTime\n     *            the roleStartTime to set\n     */\n    public void setRoleStartTime(java.util.Date roleStartTime)\n    {\n        this.roleStartTime = roleStartTime;\n    }\n\n    /**\n     * @return the scriptReadTime\n     */\n    public java.util.Date getScriptReadTime()\n    {\n        return scriptReadTime;\n    }\n\n    /**\n     * @param scriptReadTime\n     *            the scriptReadTime to set\n     */\n    public void setScriptReadTime(java.util.Date scriptReadTime)\n    {\n        this.scriptReadTime = scriptReadTime;\n    }\n\n    /**\n     * @return the yearsSpent\n     */\n    public Integer getYearsSpent()\n    {\n        return yearsSpent;\n    }\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    public void setYearsSpent(Integer yearsSpent)\n    {\n        this.yearsSpent = yearsSpent;\n    }\n\n    /**\n     * @return the uniqueId\n     */\n    public Long getUniqueId()\n    {\n        return uniqueId;\n    }\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    public void setUniqueId(Long uniqueId)\n    {\n        this.uniqueId = uniqueId;\n    }\n\n    /**\n     * @return the remuneration\n     */\n    public Double getRemuneration()\n    {\n        return remuneration;\n    }\n\n    /**\n     * @param remuneration\n     *            the remuneration to set\n     */\n    public void setRemuneration(Double remuneration)\n    {\n        this.remuneration = remuneration;\n    }\n\n    /**\n     * @return the rehearsalAttempts\n     */\n    public BigInteger getRehearsalAttempts()\n    {\n        return rehearsalAttempts;\n    }\n\n    /**\n     * @param rehearsalAttempts\n     *            the rehearsalAttempts to set\n     */\n    public void setRehearsalAttempts(BigInteger rehearsalAttempts)\n    {\n        this.rehearsalAttempts = rehearsalAttempts;\n    }\n\n    /**\n     * @return the toBePaidForRole\n     */\n    public BigDecimal getToBePaidForRole()\n    {\n        return toBePaidForRole;\n    }\n\n    /**\n     * @param toBePaidForRole\n     *            the toBePaidForRole to set\n     */\n    public void setToBePaidForRole(BigDecimal toBePaidForRole)\n    {\n        this.toBePaidForRole = toBePaidForRole;\n    }\n\n    /**\n     * @return the graduationDay\n     */\n    public Calendar getGraduationDay()\n    {\n        return graduationDay;\n    }\n\n    /**\n     * @param graduationDay\n     *            the graduationDay to set\n     */\n    public void setGraduationDay(Calendar graduationDay)\n    {\n        this.graduationDay = graduationDay;\n    }\n\n    /**\n     * @return the actor\n     */\n    public ActorAllDataType getActor()\n    {\n        return actor;\n    }\n\n    /**\n     * @param actor\n     *            the actor to set\n     */\n    public void setActor(ActorAllDataType actor)\n    {\n        this.actor = actor;\n    }\n\n    /**\n     * @return the movie\n     */\n    public MovieAllDataType getMovie()\n    {\n        return movie;\n    }\n\n    /**\n     * @param movie\n     *            the movie to set\n     */\n    public void setMovie(MovieAllDataType movie)\n    {\n        this.movie = movie;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\t<!-- Persistence Units for IMDB application -->\n\t<persistence-unit name=\"imdb\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.neo4j.imdb.Actor</class>\n\t\t<class>com.impetus.client.neo4j.imdb.Movie</class>\n\t\t<class>com.impetus.client.neo4j.imdb.Role</class>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"7474\" />\n\t\t\t<property name=\"kundera.datastore.file.path\" value=\"target/imdb.db\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"neo4j\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.neo4j.Neo4JClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaNeo4JTest.xml\" />\n\t\t\t<property name=\"kundera.transaction.resource.class\" value=\"com.impetus.client.neo4j.Neo4JTransaction\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"imdbBatch\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"7474\" />\n\t\t\t<property name=\"kundera.datastore.file.path\" value=\"target/imdbBatch.db\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"neo4j\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.neo4j.Neo4JClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaNeo4JTest.xml\" />\n\t\t\t<property name=\"kundera.transaction.resource.class\" value=\"com.impetus.client.neo4j.Neo4JTransaction\" />\n\t\t\t<property name=\"kundera.batch.size\" value=\"5\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"neo4jTest\">\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"7474\" />\n\t\t\t<property name=\"kundera.datastore.file.path\" value=\"target/neo4jTest.db\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"neo4j\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.neo4j.Neo4JClientFactory\" />\n\t\t\t<!-- <property name=\"kundera.client.property\" value=\"kunderaNeo4JTest.xml\" /> -->\n\t\t\t<property name=\"kundera.transaction.resource.class\" value=\"com.impetus.client.neo4j.Neo4JTransaction\" />\n\t\t</properties>\n\t</persistence-unit>\n</persistence>\n\n"
  },
  {
    "path": "src/kundera-neo4j/src/test/resources/kunderaNeo4JTest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>neo4j</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\n\t\t\t\t\t<!-- Native queries would be assumed to be this one, can't be overidden at operation level -->\n\t\t\t\t\t<property name=\"default_native_query_language\" value=\"lucene\"></property>\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t<property name=\"all_stores_total_mapped_memory_size\" value=\"500M\"></property>\n\t\t\t\t\t<property name=\"allow_store_upgrade\" value=\"false\"></property>\n\t\t\t\t\t<property name=\"array_block_size\" value=\"120\"></property>\n\t\t\t\t\t<property name=\"backup_slave\" value=\"false\"></property>\n\t\t\t\t\t<property name=\"cache_type\" value=\"soft\"></property>\n\t\t\t\t\t<property name=\"cypher_parser_version\" value=\"1.8\"></property>\n\t\t\t\t\t<property name=\"dump_configuration\" value=\"false\"></property>\n\t\t\t\t\t<!--<property name=\"forced_kernel_id\" value=\"\"></property>-->\n\t\t\t\t\t<property name=\"gc_monitor_threshold\" value=\"200ms\"></property>\n\t\t\t\t\t<property name=\"gc_monitor_wait_time\" value=\"100ms\"></property>\n\t\t\t\t\t<property name=\"gcr_cache_min_log_interval\" value=\"60s\"></property>\n\t\t\t\t\t<property name=\"grab_file_lock\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"intercept_committing_transactions\" value=\"false\"></property>\n\t\t\t\t\t<property name=\"intercept_deserialized_transactions\" value=\"false\"></property>\n\t\t\t\t\t<property name=\"keep_logical_logs\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"log_mapped_memory_stats\" value=\"false\"></property>\n\t\t\t\t\t<property name=\"log_mapped_memory_stats_filename\" value=\"mapped_memory_stats.log\"></property>\n\t\t\t\t\t<property name=\"log_mapped_memory_stats_interval\" value=\"1000000\"></property>\n\t\t\t\t\t<property name=\"logging.threshold_for_rotation\" value=\"104857600\"></property>\n\t\t\t\t\t<property name=\"logical_log\" value=\"nioneo_logical.log\"></property>\n\t\t\t\t\t<property name=\"lucene_searcher_cache_size\" value=\"2147483647\"></property>\n\t\t\t\t\t<property name=\"lucene_writer_cache_size\" value=\"2147483647\"></property>\n\t\t\t\t\t<property name=\"mapped_memory_page_size\" value=\"1M\"></property>\n\t\t\t\t\t<property name=\"neo_store\" value=\"neostore\"></property>\n\t\t\t\t\t<property name=\"neostore.nodestore.db.mapped_memory\" value=\"20M\"></property>\n\t\t\t\t\t<property name=\"neostore.propertystore.db.arrays.mapped_memory\" value=\"130M\"></property>\n\t\t\t\t\t<property name=\"neostore.propertystore.db.index.keys.mapped_memory\" value=\"1M\"></property>\n\t\t\t\t\t<property name=\"neostore.propertystore.db.index.mapped_memory\" value=\"1M\"></property>\n\t\t\t\t\t<property name=\"neostore.propertystore.db.mapped_memory\" value=\"90M\"></property>\n\t\t\t\t\t<property name=\"neostore.propertystore.db.strings.mapped_memory\" value=\"130M\"></property>\n\t\t\t\t\t<property name=\"neostore.relationshipstore.db.mapped_memory\" value=\"100M\"></property>\n\t\t\t\t\t\n\t\t\t\t\t<!--Controls the auto indexing feature for nodes. Setting to false shuts it down,\n\t\t\t\t\t while true enables it by default for properties listed in the node_keys_indexable setting.  -->\n\t\t\t\t\t<property name=\"node_auto_indexing\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"node_cache_array_fraction\" value=\"1.0\"></property>\n\t\t\t\t\t<!--<property name=\"node_cache_size\" value=\"\"></property>-->\n\t\t\t\t\t<property name=\"node_keys_indexable\" value=\"ACTOR_ID,ACTOR_NAME,ACTOR_ID_PREFIX,ACTOR_ID_SUFFIX,MOVIE_ID,TITLE,YEAR,CERTIFICATION,SERIAL_NUMBER,actorId,movieId\"></property>\n\t\t\t\t\t<property name=\"query_cache_size\" value=\"100\"></property>\n\t\t\t\t\t<property name=\"read_only\" value=\"false\"></property>\n\t\t\t\t\t<property name=\"rebuild_idgenerators_fast\" value=\"false\"></property>\n\t\t\t\t\t\n\t\t\t\t\t<!-- Controls the auto indexing feature for relationships. Setting to false shuts it down,\n\t\t\t\t\t while true enables it by default for properties listed in the relationship_keys_indexable setting. -->\n\t\t\t\t\t<property name=\"relationship_auto_indexing\" value=\"true\"></property>\n\t\t\t\t\t<property name=\"relationship_cache_array_fraction\" value=\"1.0\"></property>\n\t\t\t\t\t<!-- <property name=\"relationship_cache_size\" value=\"\"></property> -->\n\t\t\t\t\t<property name=\"relationship_keys_indexable\" value=\"ROLE_NAME,ROLE_TYPE,roleId\"></property>\n\t\t\t\t\t<property name=\"remote_logging_enabled\" value=\"false\"></property>\n\t\t\t\t\t<property name=\"remote_logging_host\" value=\"127.0.0.1\"></property>\n\t\t\t\t\t<property name=\"remote_logging_port\" value=\"4560\"></property>\n\t\t\t\t\t\n\t\t\t\t\t<!-- The directory where the database files are located. -->\n\t\t\t\t\t<!--<property name=\"store_dir\" value=\"\"></property>-->\n\t\t\t\t\t<property name=\"string_block_size\" value=\"120\"></property>\n\t\t\t\t\t<!--<property name=\"tx_manager_impl\" value=\"\"></property>-->\n\t\t\t\t\t<!--<property name=\"use_memory_mapped_buffers\" value=\"\"></property>-->\t\t\t\t\t\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "src/kundera-oracle-nosql/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus</groupId>\n\t\t<artifactId>kundera</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-oracle-nosql</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-oracle-nosql</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t</properties>\n\n\n\t<!-- Dependencies -->\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.oracle.kv</groupId>\n\t\t\t<artifactId>oracle-nosql-client</artifactId>\n\t\t\t<version>3.2.5</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.5</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.eclipse.jetty</groupId>\n\t\t\t<artifactId>jetty-util</artifactId>\n\t\t\t<version>7.4.0.v20110414</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.eclipse.jetty</groupId>\n\t\t\t<artifactId>jetty-server</artifactId>\n\t\t\t<version>7.4.0.v20110414</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.eclipse.jetty</groupId>\n\t\t\t<artifactId>jetty-webapp</artifactId>\n\t\t\t<version>7.4.0.v20110414</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.avro</groupId>\n\t\t\t<artifactId>avro</artifactId>\n\t\t\t<version>1.7.6</version>\n\t\t</dependency>\n\t\t<!-- elastic search dependency -->\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-elastic-search</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-surefire-plugin</artifactId>\n\t\t\t\t<version>2.7.2</version>\n\t\t\t</plugin>\n\t\t\t<!-- <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> \n\t\t\t\t<configuration> The destination file for the code coverage report has to \n\t\t\t\tbe set to the same value in the parent pom and in each module pom. Then JaCoCo \n\t\t\t\twill add up information in the same report, so that, it will give the cross-module \n\t\t\t\tcode coverage. <destFile>${project.basedir}/../target/jacoco-it.exec</destFile> \n\t\t\t\t</configuration> <executions> <execution> <id>post-test</id> <configuration> \n\t\t\t\t<skip>true</skip> </configuration> </execution> </executions> </plugin> -->\n\t\t</plugins>\n\t</build>\n\n</project>\n\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/NoSqlDBUtils.java",
    "content": "package com.impetus.client.oraclenosql;\n\nimport java.lang.reflect.Field;\nimport java.util.Date;\n\nimport javax.persistence.PersistenceException;\n\nimport oracle.kv.table.FieldDef;\nimport oracle.kv.table.FieldValue;\nimport oracle.kv.table.RecordValue;\n\nimport com.impetus.kundera.property.PropertyAccessorHelper;\n\npublic final class NoSqlDBUtils\n{\n\n    static void add(final FieldDef fieldMetadata, RecordValue row, Object value, final String fieldName)\n    {\n        if (fieldMetadata != null)\n        {\n            switch (fieldMetadata.getType())\n            {\n            case STRING:\n                \n                if(value != null)\n                row.put(fieldName, value.toString());\n                \n                break;\n\n            case INTEGER:\n                row.put(fieldName, (Integer) value);\n                break;\n\n            case LONG:\n                if (value != null && value.getClass().isAssignableFrom(Date.class))\n                {\n                    row.put(fieldName, ((Date) value).getTime());\n                } else if (value != null && value.getClass().isAssignableFrom(java.sql.Date.class))\n                {\n                    row.put(fieldName, ((java.sql.Date) value).getTime());\n                } else if(value != null && value.getClass().isAssignableFrom(java.sql.Timestamp.class))\n                {\n                    row.put(fieldName, ((java.sql.Timestamp) value).getTime());\n                } else if(value != null && value.getClass().isAssignableFrom(java.sql.Time.class))\n                {\n                    row.put(fieldName, ((java.sql.Time) value).getTime());\n                }\n                else\n                {\n                    row.put(fieldName, (Long) value);\n                }\n\n                break;\n\n            case MAP:\n\n                // MapValue mapValue = row.putMap(fieldName);\n                // mapValue.\n\n                break;\n\n            case RECORD:\n                throw new UnsupportedOperationException(\n                        \"Support for FIXED_BINARY field type is not available with Kundera\");\n\n            case FIXED_BINARY:\n                throw new UnsupportedOperationException(\n                        \"Support for FIXED_BINARY field type is not available with Kundera\");\n\n            case DOUBLE:\n                row.put(fieldName, (Double) value);\n                break;\n\n            case FLOAT:\n                row.put(fieldName, (Float) value);\n                break;\n            /*\n             * case DATE: row.put(fieldName, ((Date) value).getTime()); break;\n             */\n            case BOOLEAN:\n                row.put(fieldName, (Boolean) value);\n                break;\n\n            case BINARY:\n                if(value != null)\n                row.put(fieldName, PropertyAccessorHelper.getBytes(value));\n                break;\n\n            case ARRAY:\n                // TODO::\n                throw new UnsupportedOperationException(\n                        \"Support for FIXED_BINARY field type is not available with Kundera\");\n\n            default:\n                throw new UnsupportedOperationException(\"Invalid field type: \" + fieldMetadata.getType() + \" provided!\");\n            }\n        }\n        else\n        {\n            throw new PersistenceException(\"Invalid field \" + fieldName + \" provided!\");\n        }\n\n    }\n\n    static void get(final FieldDef fieldMetadata, FieldValue value, Object entity, final Field field)\n    {\n        if (fieldMetadata != null && !value.isNull())\n        {\n            switch (fieldMetadata.getType())\n            {\n            case STRING:\n                \n                    PropertyAccessorHelper.set(entity, field, value.asString().get());\n                break;\n\n            case INTEGER:\n                    PropertyAccessorHelper.set(entity, field, value.asInteger().get());\n                break;\n\n            case LONG:\n                    if (field.getType().isAssignableFrom(Date.class))\n                    {\n                        PropertyAccessorHelper.set(entity, field, new Date(value.asLong().get()));\n                    }\n                    else if (field.getType().isAssignableFrom(java.sql.Date.class))\n                    {\n                        PropertyAccessorHelper.set(entity, field, new java.sql.Date(value.asLong().get()));\n                    }\n                    else if (field.getType().isAssignableFrom(java.sql.Timestamp.class))\n                    {\n                        PropertyAccessorHelper.set(entity, field, new java.sql.Timestamp(value.asLong().get()));\n                    }\n                    else if (field.getType().isAssignableFrom(java.sql.Time.class))\n                    {\n                        PropertyAccessorHelper.set(entity, field, new java.sql.Time(value.asLong().get()));\n                    }\n                    else\n                    {\n                        PropertyAccessorHelper.set(entity, field, value.asLong().get());\n                    }\n                break;\n\n            case MAP:\n\n                // MapValue mapValue = row.putMap(fieldName);\n                // mapValue.\n\n                break;\n\n            case RECORD:\n                throw new UnsupportedOperationException(\n                        \"Support for FIXED_BINARY field type is not available with Kundera\");\n\n            case FIXED_BINARY:\n                throw new UnsupportedOperationException(\n                        \"Support for FIXED_BINARY field type is not available with Kundera\");\n\n            case DOUBLE:\n                    PropertyAccessorHelper.set(entity, field, value.asDouble().get());\n                break;\n\n            case FLOAT:\n                    PropertyAccessorHelper.set(entity, field, value.asFloat().get());\n                break;\n            /*\n             * case DATE: PropertyAccessorHelper.set(entity, field, new\n             * Date(value.asDate().getMilliseconds())); break;\n             */\n            case BOOLEAN:\n                    PropertyAccessorHelper.set(entity, field, value.asBoolean().get());\n                break;\n\n            case BINARY:\n                    PropertyAccessorHelper.set(entity, field, value.asBinary().get());\n                break;\n\n            case ARRAY:\n                // TODO::\n                throw new UnsupportedOperationException(\n                        \"Support for FIXED_BINARY field type is not available with Kundera\");\n\n            default:\n                throw new UnsupportedOperationException(\"Invalid field type: \" + fieldMetadata.getType() + \" provided!\");\n            }\n        }\n        else if(fieldMetadata == null)\n        {\n            throw new PersistenceException(\"Invalid field \" + field.getName() + \" provided!\");\n        }\n\n    }\n\n    static Object get(final FieldDef fieldMetadata, FieldValue value, final Field field)\n    {\n        Object retValue = null;\n        if (fieldMetadata != null && !value.isNull())\n        {\n            switch (fieldMetadata.getType())\n            {\n            case STRING:\n                \n                retValue = value.asString().get();\n                break;\n\n            case INTEGER:\n                retValue = value.asInteger().get();\n                break;\n\n            case LONG:\n\n                retValue = value.asLong().get();\n\n                if ( field != null && field.getType().isAssignableFrom(Date.class))\n                {\n                    retValue = new Date((Long) retValue);\n                }else if (field != null && field.getType().isAssignableFrom(java.sql.Date.class))\n                {\n                    retValue = new java.sql.Date((Long) retValue);\n                }\n                else if(field != null && field.getType().isAssignableFrom(java.sql.Timestamp.class))\n                {\n                    retValue = new java.sql.Timestamp((Long) retValue);\n                } else if(field != null && field.getType().isAssignableFrom(java.sql.Time.class))\n                {\n                    retValue = new java.sql.Time((Long) retValue);\n                }\n                break;\n\n            case MAP:\n\n                // MapValue mapValue = row.putMap(fieldName);\n                // mapValue.\n\n                break;\n\n            case RECORD:\n                throw new UnsupportedOperationException(\n                        \"Support for FIXED_BINARY field type is not available with Kundera\");\n\n            case FIXED_BINARY:\n                throw new UnsupportedOperationException(\n                        \"Support for FIXED_BINARY field type is not available with Kundera\");\n\n            case DOUBLE:\n                retValue = value.asDouble().get();\n                break;\n\n            /*\n             * case DATE: retValue = new Date(value.asDate().getMilliseconds());\n             * break;\n             */\n            case BOOLEAN:\n                retValue = value.asBoolean().get();\n                break;\n\n            case BINARY:\n                retValue = value.asBinary().get();\n\n                break;\n\n            case ARRAY:\n                // TODO::\n                throw new UnsupportedOperationException(\n                        \"Support for FIXED_BINARY field type is not available with Kundera\");\n\n            default:\n                throw new UnsupportedOperationException(\"Invalid field type: \" + fieldMetadata.getType() + \" provided!\");\n            }\n        }\n        else if(fieldMetadata == null)\n        {\n            throw new PersistenceException(\"Invalid field \" + field.getName() + \" provided!\");\n        }\n\n        return retValue;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/OracleNOSQLConstants.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql;\n\nimport java.util.concurrent.TimeUnit;\n\nimport oracle.kv.Consistency;\nimport oracle.kv.Durability;\n\n/**\n * Constants used in OracleNoSQL implementation of Kundera\n * \n * @author amresh.singh\n */\npublic interface OracleNOSQLConstants\n{\n    /** LOB Constants */\n    public static final int DEFAULT_WRITE_TIMEOUT_SECONDS = 5;\n\n    public static final Durability DEFAULT_DURABILITY = Durability.COMMIT_WRITE_NO_SYNC;\n\n    public static final TimeUnit DEFAULT_TIME_UNIT = TimeUnit.SECONDS;\n\n    public static final Consistency DEFAULT_CONSISTENCY = Consistency.NONE_REQUIRED;\n\n    public static final String LOB_SUFFIX = \".lob\";\n\n    public static final int OUTPUT_BUFFER_SIZE = 1024;\n\n    public static final String SECONDARY_INDEX_SUFFIX = \"_idx\";\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/OracleNoSQLClient.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.StringTokenizer;\nimport java.util.concurrent.TimeUnit;\n\nimport javax.persistence.GenerationType;\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport oracle.kv.Consistency;\nimport oracle.kv.Durability;\nimport oracle.kv.DurabilityException;\nimport oracle.kv.FaultException;\nimport oracle.kv.KVStore;\nimport oracle.kv.Key;\nimport oracle.kv.impl.api.table.TableImpl;\nimport oracle.kv.table.FieldDef;\nimport oracle.kv.table.FieldValue;\nimport oracle.kv.table.Index;\nimport oracle.kv.table.IndexKey;\nimport oracle.kv.table.PrimaryKey;\nimport oracle.kv.table.RecordValue;\nimport oracle.kv.table.ReturnRow.Choice;\nimport oracle.kv.table.Row;\nimport oracle.kv.table.Table;\nimport oracle.kv.table.TableAPI;\nimport oracle.kv.table.TableOpExecutionException;\nimport oracle.kv.table.TableOperation;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.oraclenosql.config.OracleNoSQLClientProperties;\nimport com.impetus.client.oraclenosql.query.OracleNoSQLQuery;\nimport com.impetus.client.oraclenosql.query.OracleNoSQLQueryInterpreter;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.lifecycle.states.RemovedState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.Relation.ForeignKey;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.query.QueryHandlerException;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * Implementation of {@link Client} interface for Oracle NoSQL database.\n * \n * @author vivek.mishra\n */\npublic class OracleNoSQLClient extends ClientBase implements Client<OracleNoSQLQuery>, Batcher, ClientPropertiesSetter\n{\n\n    /** The Constant SEPERATOR. */\n    private static final String SEPERATOR = \"_\";\n\n    private static final String JOIN_TABLE_PRIMARY_KEY_NAME = \"key\";\n\n    /** The kvstore db. */\n    private KVStore kvStore;\n\n    /** The factory. */\n    private OracleNoSQLClientFactory factory;\n\n    /** The handler. */\n    private OracleNoSQLDataHandler handler;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /** list of nodes for batch processing. */\n    private List<Node> nodes = new ArrayList<Node>();\n\n    /** batch size. */\n    private int batchSize;\n\n    // Configuration Parameter\n    /** The timeout. */\n    private int timeout = OracleNOSQLConstants.DEFAULT_WRITE_TIMEOUT_SECONDS;\n\n    /** The durability. */\n    private Durability durability = OracleNOSQLConstants.DEFAULT_DURABILITY;\n\n    /** The time unit. */\n    private TimeUnit timeUnit = OracleNOSQLConstants.DEFAULT_TIME_UNIT;\n\n    /** The consistency. */\n    private Consistency consistency = OracleNOSQLConstants.DEFAULT_CONSISTENCY;\n\n    /** The table api. */\n    private TableAPI tableAPI;\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(OracleNoSQLClient.class);\n\n    /**\n     * Instantiates a new oracle no sqldb client.\n     * \n     * @param factory\n     *            the factory\n     * @param reader\n     *            the reader\n     * @param indexManager\n     *            the index manager\n     * @param kvStore\n     *            the kv store\n     * @param puProperties\n     *            the pu properties\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    OracleNoSQLClient(final OracleNoSQLClientFactory factory, EntityReader reader, IndexManager indexManager,\n            final KVStore kvStore, Map<String, Object> puProperties, String persistenceUnit,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata, puProperties, persistenceUnit);\n        this.factory = factory;\n        this.kvStore = kvStore;\n        // this.handler = new OracleNoSQLDataHandler(this, kvStore,\n        // persistenceUnit);\n        this.reader = reader;\n        this.indexManager = indexManager;\n        this.clientMetadata = factory.getClientMetadata();\n        this.tableAPI = kvStore.getTableAPI();\n        setBatchSize(persistenceUnit, puProperties);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.Object)\n     */\n\n    @Override\n    public Object find(Class entityClass, Object key)\n    {\n        return find(entityClass, key, null);\n    }\n\n    /**\n     * Find by id.\n     * \n     * @param entityClass\n     *            entity class\n     * @param key\n     *            primary key\n     * @param columnsToSelect\n     *            columns to select\n     * @return the object\n     */\n    private Object find(Class entityClass, Object key, List<String> columnsToSelect)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,\n                entityMetadata.getPersistenceUnit());\n\n        String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();\n        Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());\n\n        PrimaryKey rowKey = schemaTable.createPrimaryKey();\n        if (metamodel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n        {\n            readEmbeddable(key, columnsToSelect, entityMetadata, metamodel, schemaTable, rowKey,\n                    entityMetadata.getIdAttribute());\n        }\n        else\n        {\n            if (eligibleToFetch(columnsToSelect, idColumnName))\n            {\n                NoSqlDBUtils.add(schemaTable.getField(idColumnName), rowKey, key, idColumnName);\n            }\n        }\n        KunderaCoreUtils.printQuery(\"Fetch data from \" + entityMetadata.getTableName() + \" for PK \" + key, showQuery);\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"Fetching data from \" + entityMetadata.getTableName() + \" for PK \" + key);\n        }\n\n        // Object entity = null;\n        List entities = new ArrayList();\n        Map<String, Object> relationMap = initialize(entityMetadata);\n\n        try\n        {\n            Iterator<Row> rowsIter = tableAPI.tableIterator(rowKey, null, null);\n            // iterator and build entity\n            entities = scrollAndPopulate(key, entityMetadata, metamodel, schemaTable, rowsIter, relationMap,\n                    columnsToSelect);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while finding data for Key \" + key + \", Caused By :\" + e + \".\");\n            throw new PersistenceException(e);\n        }\n\n        return entities.isEmpty() ? null : entities.get(0);\n    }\n\n    /**\n     * Read embeddable.\n     * \n     * @param key\n     *            the key\n     * @param columnsToSelect\n     *            the columns to select\n     * @param entityMetadata\n     *            the entity metadata\n     * @param metamodel\n     *            the metamodel\n     * @param schemaTable\n     *            the schema table\n     * @param value\n     *            the value\n     * @param attribute\n     *            the attribute\n     */\n    private void readEmbeddable(Object key, List<String> columnsToSelect, EntityMetadata entityMetadata,\n            MetamodelImpl metamodel, Table schemaTable, RecordValue value, Attribute attribute)\n    {\n        EmbeddableType embeddableId = metamodel.embeddable(((AbstractAttribute) attribute).getBindableJavaType());\n        Set<Attribute> embeddedAttributes = embeddableId.getAttributes();\n\n        for (Attribute embeddedAttrib : embeddedAttributes)\n        {\n            String columnName = ((AbstractAttribute) embeddedAttrib).getJPAColumnName();\n            Object embeddedColumn = PropertyAccessorHelper.getObject(key, (Field) embeddedAttrib.getJavaMember());\n\n            // either null or empty or contains that column\n            if (eligibleToFetch(columnsToSelect, columnName))\n            {\n                NoSqlDBUtils.add(schemaTable.getField(columnName), value, embeddedColumn, columnName);\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    @Override\n    public void close()\n    {\n        this.handler = null;\n        this.reader = null;\n\n        nodes.clear();\n    }\n\n    /**\n     * Delete by primary key.\n     * \n     * @param entity\n     *            the entity\n     * @param pKey\n     *            the key\n     */\n    @Override\n    public void delete(Object entity, Object pKey)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,\n                entityMetadata.getPersistenceUnit());\n\n        String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();\n\n        Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());\n\n        PrimaryKey key = schemaTable.createPrimaryKey();\n\n        if (metamodel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n        {\n            EmbeddableType embeddableId = metamodel.embeddable(entityMetadata.getIdAttribute().getBindableJavaType());\n            Set<Attribute> embeddedAttributes = embeddableId.getAttributes();\n\n            for (Attribute embeddedAttrib : embeddedAttributes)\n            {\n                String columnName = ((AbstractAttribute) embeddedAttrib).getJPAColumnName();\n                Object embeddedColumn = PropertyAccessorHelper.getObject(pKey, (Field) embeddedAttrib.getJavaMember());\n\n                NoSqlDBUtils.add(schemaTable.getField(columnName), key, embeddedColumn, columnName);\n            }\n        }\n        else\n        {\n            NoSqlDBUtils.add(schemaTable.getField(idColumnName), key, pKey, idColumnName);\n        }\n\n        tableAPI.delete(key, null, null);\n        KunderaCoreUtils.printQuery(\"Delete data from \" + entityMetadata.getTableName() + \" for PK \" + pKey, showQuery);\n    }\n\n    /**\n     * On persist.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @param id\n     *            the id\n     * @param rlHolders\n     *            the rl holders\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n        KunderaCoreUtils.printQuery(\n                \"Persist data into \" + entityMetadata.getSchema() + \".\" + entityMetadata.getTableName() + \" for \" + id,\n                showQuery);\n        Row row = createRow(entityMetadata, entity, id, rlHolders);\n        // TODO:: handle case for putDate??????\n\n        tableAPI.put(row, null, null);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera\n     * .persistence.context.jointable.JoinTableData)\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        String joinTableName = joinTableData.getJoinTableName();\n        String joinColumnName = joinTableData.getJoinColumnName();\n        String invJoinColumnName = joinTableData.getInverseJoinColumnName();\n        Map<Key, List<TableOperation>> operations = new HashMap<Key, List<TableOperation>>();\n\n        Table schemaTable = tableAPI.getTable(joinTableName);\n        Row row = schemaTable.createRow();\n\n        // String primaryKey = joinColumnName + SEPERATOR + invJoinColumnName;\n\n        KunderaCoreUtils.printQuery(\"Persist Join Table:\" + joinTableName, showQuery);\n        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();\n\n        try\n        {\n            for (Object pk : joinTableRecords.keySet())\n            {\n                // here pk is join column name and it's values would become\n                // inverse join columns\n\n                NoSqlDBUtils.add(schemaTable.getField(joinColumnName), row, pk, joinColumnName);\n                Set<Object> values = joinTableRecords.get(pk);\n                for (Object childId : values)\n                {\n                    // what if join or inverse join column is null? Not handling\n                    // as ideally it should be handled in core itself!\n\n                    NoSqlDBUtils.add(schemaTable.getField(invJoinColumnName), row, childId, invJoinColumnName);\n\n                    NoSqlDBUtils.add(schemaTable.getField(JOIN_TABLE_PRIMARY_KEY_NAME), row,\n                            pk.toString() + SEPERATOR + childId.toString(), JOIN_TABLE_PRIMARY_KEY_NAME);\n\n                    addOps(operations, schemaTable, row);\n                }\n            }\n\n            execute(operations);\n        }\n        finally\n        {\n            operations.clear();\n            operations = null;\n        }\n    }\n\n    /**\n     * Adds the ops.\n     * \n     * @param operations\n     *            the operations\n     * @param schemaTable\n     *            the schema table\n     * @param row\n     *            the row\n     */\n    private void addOps(Map<Key, List<TableOperation>> operations, Table schemaTable, Row row)\n    {\n        Key key = ((TableImpl) schemaTable).createKey(row, false);\n\n        TableOperation ops = tableAPI.getTableOperationFactory().createPut(row, Choice.NONE, true);\n\n        if (operations.containsKey(key))\n        {\n            operations.get(key).add(ops);\n\n        }\n        else\n        {\n            List<TableOperation> operation = new ArrayList<TableOperation>();\n            operation.add(ops);\n            operations.put(key, operation);\n        }\n    }\n\n    /**\n     * Execute.\n     * \n     * @param batches\n     *            the batches\n     */\n    private void execute(Map<Key, List<TableOperation>> batches)\n    {\n        if (batches != null && !batches.isEmpty())\n        {\n            try\n            {\n                for (List<TableOperation> batch : batches.values())\n                {\n                    tableAPI.execute(batch, null);\n                }\n            }\n            catch (DurabilityException e)\n            {\n                log.error(\"Error while executing operations in OracleNOSQL, Caused by:\" + e + \".\");\n                throw new PersistenceException(\"Error while Persisting data using batch\", e);\n            }\n            catch (TableOpExecutionException e)\n            {\n                log.error(\"Error while executing operations in OracleNOSQL, Caused by:\" + e + \".\");\n                throw new PersistenceException(\"Error while Persisting data using batch\", e);\n            }\n            catch (FaultException e)\n            {\n                log.error(\"Error while executing operations in OracleNOSQL, Caused by:\" + e + \".\");\n                throw new PersistenceException(\"Error while Persisting data using batch\", e);\n            }\n            finally\n            {\n                batches.clear();\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.String[], java.lang.Object[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)\n    {\n        List<E> results = new ArrayList<E>();\n\n        if (columnsToSelect == null)\n        {\n            columnsToSelect = new String[0];\n        }\n\n        if (keys == null)\n        {\n            EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n            MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,\n                    entityMetadata.getPersistenceUnit());\n\n            EntityType entityType = metamodel.entity(entityMetadata.getEntityClazz());\n\n            Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());\n            // KunderaCoreUtils.showQuery(\"Get all records for \" +\n            // entityMetadata.getTableName(), showQuery);\n            Iterator<Row> rowsIter = tableAPI.tableIterator(schemaTable.createPrimaryKey(), null, null);\n\n            Map<String, Object> relationMap = initialize(entityMetadata);\n\n            try\n            {\n                results = scrollAndPopulate(null, entityMetadata, metamodel, schemaTable, rowsIter, relationMap,\n                        Arrays.asList(columnsToSelect));\n            }\n            catch (Exception e)\n            {\n                log.error(\"Error while finding records , Caused By :\" + e + \".\");\n                throw new PersistenceException(e);\n            }\n        }\n        else\n        {\n\n            for (Object key : keys)\n            {\n                results.add((E) find(entityClass, key, Arrays.asList(columnsToSelect)));\n            }\n        }\n\n        return results;\n    }\n\n    /**\n     * On JPQL query execution.\n     * \n     * @param <E>\n     *            the element type\n     * @param entityClass\n     *            entity class.\n     * @param interpreter\n     *            query interpreter\n     * @param primaryKeys\n     *            set of primary keys. Empty if\n     * @return the list\n     */\n    public <E> List<E> executeQuery(Class<E> entityClass, OracleNoSQLQueryInterpreter interpreter,\n            Set<Object> primaryKeys)\n    {\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n        MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,\n                entityMetadata.getPersistenceUnit());\n\n        EntityType entityType = metamodel.entity(entityMetadata.getEntityClazz());\n\n        List<E> results = new ArrayList<E>();\n\n        if (interpreter.getClauseQueue().isEmpty()) // Select all query\n        {\n            // Select Query with where clause (requires search within inverted\n            // index)\n            return findAll(entityClass, interpreter.getSelectColumns(), null);\n        }\n        else if (interpreter.isFindById() && interpreter.getClauseQueue().size() == 1)\n        {\n            Object value = null;\n            Object clause = interpreter.getClauseQueue().peek();\n            if (clause.getClass().isAssignableFrom(FilterClause.class))\n            {\n                value = interpreter.getRowKey();\n            }\n            else\n            {\n                throw new QueryHandlerException(\n                        \"Query with multiple AND/OR clause is not supported with oracle nosql db\");\n            }\n            if (value != null)\n            {\n                Object output = find(entityClass, value, Arrays.asList(interpreter.getSelectColumns()));\n                if (output != null)\n                {\n                    results.add((E) output);\n                }\n            }\n        }\n        else if (interpreter.getClauseQueue().size() >= 1) // query over index\n        // keys.\n        {\n            return onIndexSearch(interpreter, entityMetadata, metamodel, results,\n                    Arrays.asList(interpreter.getSelectColumns()));\n        }\n        return results;\n\n        // throw new\n        // UnsupportedOperationException(\"Query with where clause is not yet\n        // supported\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n        throw new UnsupportedOperationException(\"This operation is not supported for OracleNoSQL.\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,\n            Object pKeyColumnValue, Class columnJavaType)\n    {\n        // search using index on pkey column\n        List<E> foreignKeys = new ArrayList<E>();\n\n        Table schemaTable = tableAPI.getTable(tableName);\n        Index index = schemaTable.getIndex(pKeyColumnName);\n        IndexKey indexKey = index.createIndexKey();\n\n        // StringBuilder indexNamebuilder = new StringBuilder();\n        NoSqlDBUtils.add(schemaTable.getField(pKeyColumnName), indexKey, pKeyColumnValue, pKeyColumnName);\n        KunderaCoreUtils.printQuery(\n                \"Get columns by id from:\" + tableName + \" for column:\" + columnName + \" where value:\" + pKeyColumnValue,\n                showQuery);\n        Iterator<Row> rowsIter = tableAPI.tableIterator(indexKey, null, null);\n\n        while (rowsIter.hasNext())\n        {\n            Row row = rowsIter.next();\n            FieldDef fieldMetadata = schemaTable.getField(columnName);\n            FieldValue value = row.get(columnName);\n            foreignKeys.add((E) NoSqlDBUtils.get(fieldMetadata, value, null));\n        }\n\n        return foreignKeys;\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n        return getColumnsById(schemaName, tableName, columnName, pKeyName, columnValue, entityClazz).toArray();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    @Override\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n        Table schemaTable = tableAPI.getTable(tableName);\n        List<String> primaryKeys = schemaTable.getPrimaryKey();\n\n        Object[] foundRecords = findIdsByColumn(schemaName, tableName, primaryKeys.get(0), columnName, columnValue,\n                null);\n        KunderaCoreUtils.printQuery(\"Delete columns by id from:\" + tableName, showQuery);\n        if (foundRecords != null)\n        {\n            for (Object key : foundRecords)\n            {\n                PrimaryKey primaryKey = schemaTable.createPrimaryKey();\n                NoSqlDBUtils.add(schemaTable.getField(primaryKeys.get(0)), primaryKey, key, primaryKeys.get(0));\n                KunderaCoreUtils.printQuery(\"  Delete for id:\" + key, showQuery);\n                tableAPI.delete(primaryKey, null, null);\n            }\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    /**\n     * Find by relational column name and value.\n     * \n     * @param colName\n     *            the col name\n     * @param colValue\n     *            the col value\n     * @param entityClazz\n     *            the entity clazz\n     * @return the list\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n        // find by relational value !\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n        MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,\n                entityMetadata.getPersistenceUnit());\n\n        EntityType entityType = metamodel.entity(entityMetadata.getEntityClazz());\n\n        Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());\n\n        Iterator<Row> rowsIter = null;\n        if (schemaTable.getPrimaryKey().contains(colName))\n        {\n            PrimaryKey rowKey = schemaTable.createPrimaryKey();\n            NoSqlDBUtils.add(schemaTable.getField(colName), rowKey, colValue, colName);\n            rowsIter = tableAPI.tableIterator(rowKey, null, null);\n        }\n        else\n        {\n            Index index = schemaTable.getIndex(colName);\n            IndexKey indexKey = index.createIndexKey();\n            NoSqlDBUtils.add(schemaTable.getField(colName), indexKey, colValue, colName);\n            rowsIter = tableAPI.tableIterator(indexKey, null, null);\n        }\n\n        try\n        {\n            Map<String, Object> relationMap = initialize(entityMetadata);\n\n            return scrollAndPopulate(null, entityMetadata, metamodel, schemaTable, rowsIter, relationMap, null);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while finding data for Key \" + colName + \", Caused By :\" + e + \".\");\n            throw new PersistenceException(e);\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<OracleNoSQLQuery> getQueryImplementor()\n    {\n        return OracleNoSQLQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.api.Batcher#addBatch(com.impetus.kundera\n     * .graph.Node)\n     */\n    @Override\n    public void addBatch(Node node)\n    {\n        if (node != null)\n        {\n            nodes.add(node);\n        }\n        onBatchLimit();\n    }\n\n    /**\n     * Gets the handler.\n     * \n     * @return the handler\n     */\n    public OracleNoSQLDataHandler getHandler()\n    {\n        return handler;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#executeBatch()\n     */\n    @Override\n    public int executeBatch()\n    {\n\n        Map<Key, List<TableOperation>> operations = new HashMap<Key, List<TableOperation>>();\n        for (Node node : nodes)\n        {\n            if (node.isDirty())\n            {\n                node.handlePreEvent();\n                // delete can not be executed in batch\n                if (node.isInState(RemovedState.class))\n                {\n                    delete(node.getData(), node.getEntityId());\n                }\n                else\n                {\n                    EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                            node.getDataClass());\n                    List<RelationHolder> relationHolders = getRelationHolders(node);\n                    // KunderaCoreUtils.showQuery(\"Execute batch for\" +\n                    // metadata.getSchema() + \".\" + metadata.getTableName(),\n                    // showQuery);\n                    Row row = createRow(metadata, node.getData(), node.getEntityId(), relationHolders);\n\n                    Table schemaTable = tableAPI.getTable(metadata.getTableName());\n\n                    addOps(operations, schemaTable, row);\n                }\n                node.handlePostEvent();\n            }\n        }\n\n        execute(operations);\n        return nodes.size();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#getBatchSize()\n     */\n    @Override\n    public int getBatchSize()\n    {\n        return batchSize;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#clear()\n     */\n    @Override\n    public void clear()\n    {\n        if (nodes != null)\n        {\n            nodes.clear();\n            nodes = new ArrayList<Node>();\n        }\n    }\n\n    /**\n     * Check on batch limit.\n     */\n    private void onBatchLimit()\n    {\n        if (batchSize > 0 && batchSize == nodes.size())\n        {\n            executeBatch();\n            nodes.clear();\n        }\n    }\n\n    /**\n     * Sets the batch size.\n     * \n     * @param persistenceUnit\n     *            the persistence unit\n     * @param puProperties\n     *            the pu properties\n     */\n    private void setBatchSize(String persistenceUnit, Map<String, Object> puProperties)\n    {\n        String batch_Size = null;\n        if (puProperties != null)\n        {\n            batch_Size = puProperties != null ? (String) puProperties.get(PersistenceProperties.KUNDERA_BATCH_SIZE)\n                    : null;\n            if (batch_Size != null)\n            {\n                setBatchSize(Integer.valueOf(batch_Size));\n            }\n        }\n        else if (batch_Size == null)\n        {\n            PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\n                    persistenceUnit);\n            setBatchSize(puMetadata.getBatchSize());\n        }\n    }\n\n    /**\n     * Sets the batch size.\n     * \n     * @param batch_Size\n     *            the new batch size\n     */\n    public void setBatchSize(int batch_Size)\n    {\n        this.batchSize = batch_Size;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientPropertiesSetter#\n     * populateClientProperties (com.impetus.kundera.client.Client,\n     * java.util.Map)\n     */\n    @Override\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n\n        new OracleNoSQLClientProperties().populateClientProperties(client, properties);\n    }\n\n    /**\n     * Sets the timeout.\n     * \n     * @param timeout\n     *            the timeout to set\n     */\n    public void setTimeout(int timeout)\n    {\n        this.timeout = timeout;\n    }\n\n    /**\n     * Sets the durability.\n     * \n     * @param durability\n     *            the durability to set\n     */\n    public void setDurability(Durability durability)\n    {\n        this.durability = durability;\n    }\n\n    /**\n     * Sets the time unit.\n     * \n     * @param timeUnit\n     *            the timeUnit to set\n     */\n    public void setTimeUnit(TimeUnit timeUnit)\n    {\n        this.timeUnit = timeUnit;\n    }\n\n    /**\n     * Sets the consistency.\n     * \n     * @param consistency\n     *            the consistency to set\n     */\n    public void setConsistency(Consistency consistency)\n    {\n        this.consistency = consistency;\n    }\n\n    /**\n     * Gets the timeout.\n     * \n     * @return the timeout\n     */\n    public int getTimeout()\n    {\n        return timeout;\n    }\n\n    /**\n     * Gets the durability.\n     * \n     * @return the durability\n     */\n    public Durability getDurability()\n    {\n        return durability;\n    }\n\n    /**\n     * Gets the time unit.\n     * \n     * @return the timeUnit\n     */\n    public TimeUnit getTimeUnit()\n    {\n        return timeUnit;\n    }\n\n    /**\n     * Gets the consistency.\n     * \n     * @return the consistency\n     */\n    public Consistency getConsistency()\n    {\n        return consistency;\n    }\n\n    /**\n     * Iterate and store attributes.\n     * \n     * @param entity\n     *            JPA entity.\n     * @param metamodel\n     *            JPA meta model.\n     * @param row\n     *            kv row.\n     * @param attributes\n     *            JPA attributes.\n     * @param schemaTable\n     *            the schema table\n     * @param metadata\n     *            the metadata\n     */\n    private void process(Object entity, MetamodelImpl metamodel, Row row, Set<Attribute> attributes, Table schemaTable,\n            EntityMetadata metadata)\n    {\n\n        for (Attribute attribute : attributes)\n        {\n            // by pass association.\n            if (!attribute.isAssociation())\n            {\n                // in case of embeddable id.\n                if (attribute.equals(metadata.getIdAttribute())\n                        && metamodel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType()))\n                {\n                    processEmbeddableAttribute(entity, metamodel, row, schemaTable, metadata, attribute);\n                }\n                else\n                {\n                    if (metamodel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType()))\n                    {\n                        processEmbeddableAttribute(entity, metamodel, row, schemaTable, metadata, attribute);\n                    }\n                    else\n                    {\n                        setField(row, schemaTable, entity, attribute);\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * Process embeddable attribute.\n     * \n     * @param entity\n     *            the entity\n     * @param metamodel\n     *            the metamodel\n     * @param row\n     *            the row\n     * @param schemaTable\n     *            the schema table\n     * @param metadata\n     *            the metadata\n     * @param attribute\n     *            the attribute\n     */\n    private void processEmbeddableAttribute(Object entity, MetamodelImpl metamodel, Row row, Table schemaTable,\n            EntityMetadata metadata, Attribute attribute)\n    {\n        // process on embeddables.\n        EmbeddableType embeddable = metamodel.embeddable(((AbstractAttribute) attribute).getBindableJavaType());\n        Set<Attribute> embeddedAttributes = embeddable.getAttributes();\n        Object embeddedObject = PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());\n\n        for (Attribute embeddedAttrib : embeddedAttributes)\n        {\n            setField(row, schemaTable, embeddedObject, embeddedAttrib);\n        }\n    }\n\n    /**\n     * Process relational attributes.\n     * \n     * @param rlHolders\n     *            relation holders\n     * @param row\n     *            kv row object\n     * @param schemaTable\n     *            the schema table\n     */\n    private void onRelationalAttributes(List<RelationHolder> rlHolders, Row row, Table schemaTable)\n    {\n        // Iterate over relations\n        if (rlHolders != null && !rlHolders.isEmpty())\n        {\n            for (RelationHolder rh : rlHolders)\n            {\n                String relationName = rh.getRelationName();\n                Object valueObj = rh.getRelationValue();\n\n                if (!StringUtils.isEmpty(relationName) && valueObj != null)\n                {\n                    if (valueObj != null)\n                    {\n                        NoSqlDBUtils.add(schemaTable.getField(relationName), row, valueObj, relationName);\n                        KunderaCoreUtils.printQuery(\n                                \"Add relation: relation name:\" + relationName + \"relation value:\" + valueObj,\n                                showQuery);\n                    }\n                }\n            }\n        }\n    }\n\n    /**\n     * Process discriminator columns.\n     * \n     * @param row\n     *            kv row object.\n     * @param entityType\n     *            metamodel attribute.\n     * @param schemaTable\n     *            the schema table\n     */\n    private void addDiscriminatorColumn(Row row, EntityType entityType, Table schemaTable)\n    {\n        String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n        String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();\n\n        // No need to check for empty or blank, as considering it as valid name\n        // for nosql!\n        if (discrColumn != null && discrValue != null)\n        {\n            // Key\n            // Key key = Key.createKey(majorKeyComponent, discrColumn);\n\n            byte[] valueInBytes = PropertyAccessorHelper.getBytes(discrValue);\n            NoSqlDBUtils.add(schemaTable.getField(discrColumn), row, discrValue, discrColumn);\n\n        }\n    }\n\n    /**\n     * setter field.\n     * \n     * @param row\n     *            the row\n     * @param schemaTable\n     *            the schema table\n     * @param embeddedObject\n     *            the embedded object\n     * @param embeddedAttrib\n     *            the embedded attrib\n     */\n    private void setField(Row row, Table schemaTable, Object embeddedObject, Attribute embeddedAttrib)\n    {\n        Field field = (Field) embeddedAttrib.getJavaMember();\n        FieldDef fieldDef = schemaTable.getField(((AbstractAttribute) embeddedAttrib).getJPAColumnName());\n\n        Object valueObj = PropertyAccessorHelper.getObject(embeddedObject, field);\n\n        if (valueObj != null)\n            NoSqlDBUtils.add(fieldDef, row, valueObj, ((AbstractAttribute) embeddedAttrib).getJPAColumnName());\n\n    }\n\n    /**\n     * Populate id.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param schemaTable\n     *            the schema table\n     * @param entity\n     *            the entity\n     * @param row\n     *            the row\n     */\n    private void populateId(EntityMetadata entityMetadata, Table schemaTable, Object entity, Row row)\n    {\n        FieldDef fieldMetadata;\n        FieldValue value;\n        String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();\n\n        fieldMetadata = schemaTable.getField(idColumnName);\n\n        value = row.get(idColumnName);\n\n        NoSqlDBUtils.get(fieldMetadata, value, entity, (Field) entityMetadata.getIdAttribute().getJavaMember());\n    }\n\n    /**\n     * On embeddable id.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param metaModel\n     *            the meta model\n     * @param schemaTable\n     *            the schema table\n     * @param entity\n     *            the entity\n     * @param row\n     *            the row\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    private void onEmbeddableId(EntityMetadata entityMetadata, MetamodelImpl metaModel, Table schemaTable,\n            Object entity, Row row) throws InstantiationException, IllegalAccessException\n    {\n        FieldDef fieldMetadata;\n        FieldValue value;\n        EmbeddableType embeddableType = metaModel.embeddable(entityMetadata.getIdAttribute().getBindableJavaType());\n        Set<Attribute> embeddedAttributes = embeddableType.getAttributes();\n\n        Object embeddedObject = entityMetadata.getIdAttribute().getBindableJavaType().newInstance();\n        for (Attribute attrib : embeddedAttributes)\n        {\n\n            String columnName = ((AbstractAttribute) attrib).getJPAColumnName();\n\n            fieldMetadata = schemaTable.getField(columnName);\n            value = row.get(columnName);\n            NoSqlDBUtils.get(fieldMetadata, value, embeddedObject, (Field) attrib.getJavaMember());\n        }\n\n        PropertyAccessorHelper.set(entity, (Field) entityMetadata.getIdAttribute().getJavaMember(), embeddedObject);\n    }\n\n    /**\n     * Initialize.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @return the map\n     */\n    private Map<String, Object> initialize(EntityMetadata entityMetadata)\n    {\n        Map<String, Object> relationMap = null;\n        if (entityMetadata.getRelationNames() != null && !entityMetadata.getRelationNames().isEmpty())\n        {\n            relationMap = new HashMap<String, Object>();\n        }\n        return relationMap;\n    }\n\n    /**\n     * Scroll and populate.\n     * \n     * @param key\n     *            the key\n     * @param entityMetadata\n     *            the entity metadata\n     * @param metaModel\n     *            the meta model\n     * @param schemaTable\n     *            the schema table\n     * @param rowsIter\n     *            the rows iter\n     * @param relationMap\n     *            the relation map\n     * @param columnsToSelect\n     *            the columns to select\n     * @return the list\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    private List scrollAndPopulate(Object key, EntityMetadata entityMetadata, MetamodelImpl metaModel,\n            Table schemaTable, Iterator<Row> rowsIter, Map<String, Object> relationMap, List<String> columnsToSelect)\n                    throws InstantiationException, IllegalAccessException\n    {\n        List results = new ArrayList();\n        Object entity = null;\n        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n        // here\n        while (rowsIter.hasNext())\n        {\n            relationMap = new HashMap<String, Object>();\n            entity = initializeEntity(key, entityMetadata);\n\n            Row row = rowsIter.next();\n\n            List<String> fields = row.getTable().getFields();\n            FieldDef fieldMetadata = null;\n            FieldValue value = null;\n            String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();\n            if (/* eligibleToFetch(columnsToSelect, idColumnName) && */!metaModel\n                    .isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n            {\n                populateId(entityMetadata, schemaTable, entity, row);\n            }\n            else\n            {\n                onEmbeddableId(entityMetadata, metaModel, schemaTable, entity, row);\n            }\n\n            Iterator<String> fieldIter = fields.iterator();\n\n            Set<Attribute> attributes = entityType.getAttributes();\n            for (Attribute attribute : attributes)\n            {\n                String jpaColumnName = ((AbstractAttribute) attribute).getJPAColumnName();\n                if (eligibleToFetch(columnsToSelect, jpaColumnName)\n                        && !attribute.getName().equals(entityMetadata.getIdAttribute().getName()))\n                {\n                    if (metaModel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType()))\n                    {\n                        // readEmbeddable(value, columnsToSelect,\n                        // entityMetadata, metaModel, schemaTable, value,\n                        // attribute);\n                        EmbeddableType embeddableId = metaModel\n                                .embeddable(((AbstractAttribute) attribute).getBindableJavaType());\n                        Set<Attribute> embeddedAttributes = embeddableId.getAttributes();\n                        Object embeddedObject = ((AbstractAttribute) attribute).getBindableJavaType().newInstance();\n                        for (Attribute embeddedAttrib : embeddedAttributes)\n                        {\n                            String embeddedColumnName = ((AbstractAttribute) embeddedAttrib).getJPAColumnName();\n\n                            fieldMetadata = schemaTable.getField(embeddedColumnName);\n                            value = row.get(embeddedColumnName);\n                            NoSqlDBUtils.get(fieldMetadata, value, embeddedObject,\n                                    (Field) embeddedAttrib.getJavaMember());\n                        }\n                        PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), embeddedObject);\n\n                    }\n                    else\n                    {\n                        fieldMetadata = schemaTable.getField(jpaColumnName);\n                        value = row.get(jpaColumnName);\n\n                        if (!attribute.isAssociation() && value != null)\n                        {\n                            NoSqlDBUtils.get(fieldMetadata, value, entity, (Field) attribute.getJavaMember());\n                        }\n                        else if (attribute.isAssociation() && value != null)\n                        {\n                            Relation relation = entityMetadata.getRelation(attribute.getName());\n\n                            if (relation != null)\n                            {\n                                EntityMetadata associationMetadata = KunderaMetadataManager\n                                        .getEntityMetadata(kunderaMetadata, relation.getTargetEntity());\n                                if (!relation.getType().equals(ForeignKey.MANY_TO_MANY))\n                                {\n                                    relationMap.put(jpaColumnName, NoSqlDBUtils.get(fieldMetadata, value,\n                                            (Field) associationMetadata.getIdAttribute().getJavaMember()));\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n\n            if (entity != null)\n            {\n                results.add(\n                        relationMap.isEmpty() ? entity\n                                : new EnhanceEntity(entity,\n                                        key != null ? key : PropertyAccessorHelper.getId(entity, entityMetadata),\n                                        relationMap));\n            }\n        }\n        return results;\n    }\n\n    /**\n     * Initialize entity.\n     * \n     * @param key\n     *            the key\n     * @param entityMetadata\n     *            the entity metadata\n     * @return the object\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    private Object initializeEntity(Object key, EntityMetadata entityMetadata)\n            throws InstantiationException, IllegalAccessException\n    {\n        Object entity = null;\n        entity = entityMetadata.getEntityClazz().newInstance();\n        if (key != null)\n        {\n            PropertyAccessorHelper.setId(entity, entityMetadata, key);\n        }\n        return entity;\n    }\n\n    /**\n     * On index search.\n     * \n     * @param <E>\n     *            the element type\n     * @param interpreter\n     *            the interpreter\n     * @param entityMetadata\n     *            the entity metadata\n     * @param metamodel\n     *            the metamodel\n     * @param results\n     *            the results\n     * @param columnsToSelect\n     *            the columns to select\n     * @return the list\n     */\n    private <E> List<E> onIndexSearch(OracleNoSQLQueryInterpreter interpreter, EntityMetadata entityMetadata,\n            MetamodelImpl metamodel, List<E> results, List<String> columnsToSelect)\n    {\n        Map<String, List> indexes = new HashMap<String, List>();\n        StringBuilder indexNamebuilder = new StringBuilder();\n\n        for (Object clause : interpreter.getClauseQueue())\n        {\n            if (clause.getClass().isAssignableFrom(FilterClause.class))\n            {\n                String fieldName = null;\n\n                String clauseName = ((FilterClause) clause).getProperty();\n                StringTokenizer stringTokenizer = new StringTokenizer(clauseName, \".\");\n                // if need to select embedded columns\n                if (stringTokenizer.countTokens() > 1)\n                {\n                    fieldName = stringTokenizer.nextToken();\n                }\n\n                fieldName = stringTokenizer.nextToken();\n                Object value = ((FilterClause) clause).getValue();\n                if (!indexes.containsKey(fieldName))\n                {\n                    indexNamebuilder.append(fieldName);\n                    indexNamebuilder.append(\",\");\n                }\n                indexes.put(fieldName, (List) value);\n            }\n            else\n            {\n                if (clause.toString().equalsIgnoreCase(\"OR\"))\n                {\n                    throw new QueryHandlerException(\"OR clause is not supported with oracle nosql db\");\n                }\n            }\n        }\n\n        // prepare index name and value.\n        Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());\n        String indexKeyName = indexNamebuilder.deleteCharAt(indexNamebuilder.length() - 1).toString();\n        Index index = schemaTable.getIndex(entityMetadata.getIndexProperties().get(indexKeyName).getName());\n        IndexKey indexKey = index.createIndexKey();\n\n        // StringBuilder indexNamebuilder = new StringBuilder();\n        for (String indexName : indexes.keySet())\n        {\n            NoSqlDBUtils.add(schemaTable.getField(indexName), indexKey, indexes.get(indexName).get(0), indexName);\n        }\n\n        Iterator<Row> rowsIter = tableAPI.tableIterator(indexKey, null, null);\n\n        Map<String, Object> relationMap = initialize(entityMetadata);\n\n        try\n        {\n            results = scrollAndPopulate(null, entityMetadata, metamodel, schemaTable, rowsIter, relationMap,\n                    columnsToSelect);\n            KunderaCoreUtils.printQueryWithFilterClause(interpreter.getClauseQueue(), entityMetadata.getTableName());\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while finding records , Caused By :\" + e + \".\");\n            throw new PersistenceException(e);\n        }\n\n        return results;\n    }\n\n    /**\n     * Creates the row.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @param id\n     *            the id\n     * @param rlHolders\n     *            the rl holders\n     * @return the row\n     */\n    private Row createRow(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n        String schema = entityMetadata.getSchema(); // Irrelevant for this\n        // datastore\n        String table = entityMetadata.getTableName();\n\n        MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,\n                entityMetadata.getPersistenceUnit());\n\n        Table schemaTable = null;\n\n        try\n        {\n            schemaTable = tableAPI.getTable(table);\n\n            if (schemaTable == null)\n            {\n                log.error(\"No table found for \" + table);\n                throw new KunderaException(\"No table found for \" + table);\n            }\n        }\n        catch (FaultException ex)\n        {\n            log.error(\"Error while getting table \" + table + \". Caused By: \", ex);\n            throw new KunderaException(\"Error while getting table \" + table + \". Caused By: \", ex);\n        }\n\n        Row row = schemaTable.createRow();\n\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"Persisting data into \" + schema + \".\" + table + \" for \" + id);\n        }\n\n        EntityType entityType = metamodel.entity(entityMetadata.getEntityClazz());\n\n        Set<Attribute> attributes = entityType.getAttributes();\n\n        // process entity attributes.\n        process(entity, metamodel, row, attributes, schemaTable, entityMetadata);\n        // on relational attributes.\n        onRelationalAttributes(rlHolders, row, schemaTable);\n        // add discriminator column(if present)\n        addDiscriminatorColumn(row, entityType, schemaTable);\n        return row;\n    }\n\n    /**\n     * Eligible to fetch.\n     * \n     * @param columnsToSelect\n     *            the columns to select\n     * @param columnName\n     *            the column name\n     * @return true, if successful\n     */\n    private boolean eligibleToFetch(List<String> columnsToSelect, String columnName)\n    {\n        return (columnsToSelect != null && !columnsToSelect.isEmpty() && columnsToSelect.contains(columnName))\n                || (columnsToSelect == null || columnsToSelect.isEmpty());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        throw new UnsupportedOperationException(\n                GenerationType.class.getSimpleName() + \" Strategies not supported by this client : OracleNoSQLClient\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/OracleNoSQLClientFactory.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql;\n\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport oracle.kv.AuthenticationFailureException;\nimport oracle.kv.KVStore;\nimport oracle.kv.KVStoreConfig;\nimport oracle.kv.KVStoreFactory;\nimport oracle.kv.PasswordCredentials;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.oraclenosql.config.OracleNoSQLPropertyReader;\nimport com.impetus.client.oraclenosql.index.OracleNoSQLInvertedIndexer;\nimport com.impetus.client.oraclenosql.schemamanager.OracleNoSQLSchemaManager;\nimport com.impetus.client.oraclenosql.server.OracleNoSQLHostConfiguration;\nimport com.impetus.client.oraclenosql.server.OracleNoSQLHost;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.index.Indexer;\nimport com.impetus.kundera.loader.ClientFactory;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.service.Host;\nimport com.impetus.kundera.service.HostConfiguration;\n\n/**\n * {@link ClientFactory} implementation for Oracle NOSQL database\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLClientFactory extends GenericClientFactory\n{\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(OracleNoSQLClientFactory.class);\n\n    private HostConfiguration configuration;\n\n    /** The kvstore db. */\n    private KVStore kvStore;\n\n    @Override\n    public SchemaManager getSchemaManager(Map<String, Object> puProperties)\n    {\n        if (schemaManager == null)\n        {\n            initializePropertyReader();\n            setExternalProperties(puProperties);\n            schemaManager = new OracleNoSQLSchemaManager(OracleNoSQLClientFactory.class.getName(), puProperties,\n                    kunderaMetadata);\n        }\n        return schemaManager;\n    }\n\n    @Override\n    public void initialize(Map<String, Object> puProperties)\n    {\n        initializePropertyReader();\n        setExternalProperties(puProperties);\n        configuration = new OracleNoSQLHostConfiguration(externalProperties, OracleNoSQLPropertyReader.osmd,\n                getPersistenceUnit(), kunderaMetadata);\n        reader = new OracleNoSQLEntityReader(kunderaMetadata);\n    }\n\n    @Override\n    protected Client instantiateClient(String persistenceUnit)\n    {\n        String indexerClass = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(getPersistenceUnit())\n                .getProperties().getProperty(PersistenceProperties.KUNDERA_INDEXER_CLASS);\n\n        Client client = new OracleNoSQLClient(this, reader, indexManager, kvStore, externalProperties,\n                getPersistenceUnit(), kunderaMetadata);\n        populateIndexer(indexerClass, client);\n\n        return client;\n    }\n\n    @Override\n    public boolean isThreadSafe()\n    {\n        return false;\n    }\n\n    @Override\n    public void destroy()\n    {\n        indexManager.close();\n        if (schemaManager != null)\n        {\n            getSchemaManager(externalProperties).dropSchema();\n        }\n        schemaManager = null;\n        externalProperties = null;\n\n        if (kvStore != null)\n        {\n            logger.info(\"Closing connection to kvStore.\");\n            kvStore.close();\n            logger.info(\"Closed connection to kvStore.\");\n        }\n        else\n        {\n            logger.warn(\"Can't close connection to kvStore, it was already disconnected\");\n        }\n    }\n\n    @Override\n    protected Object createPoolOrConnection()\n    {\n        kvStore = getConnection();\n\n        return kvStore;\n    }\n\n    /**\n     * Populates {@link Indexer} into {@link IndexManager}\n     * \n     * @param indexerClass\n     * @param client\n     */\n    private void populateIndexer(String indexerClass, Client client)\n    {\n        if (indexerClass != null && indexerClass.equals(OracleNoSQLInvertedIndexer.class.getName()))\n        {\n            ((OracleNoSQLInvertedIndexer) indexManager.getIndexer()).setKvStore(kvStore);\n            ((OracleNoSQLInvertedIndexer) indexManager.getIndexer()).setHandler(((OracleNoSQLClient) client)\n                    .getHandler());\n        }\n    }\n\n    private void initializePropertyReader()\n    {\n        if (propertyReader == null)\n        {\n            propertyReader = new OracleNoSQLPropertyReader(externalProperties, kunderaMetadata.getApplicationMetadata()\n                    .getPersistenceUnitMetadata(getPersistenceUnit()));\n            propertyReader.read(getPersistenceUnit());\n        }\n    }\n\n    /**\n     * Gets the connection.\n     * \n     * @return the connection\n     */\n    private KVStore getConnection()\n    {\n\n        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(getPersistenceUnit());\n\n        Properties props = persistenceUnitMetadata.getProperties();\n        String hostName = null;\n        String defaultPort = null;\n        String storeName = null;\n        String poolSize = null;\n        String userName = null;\n        String password = null;\n        \n\n        if (externalProperties != null)\n        {\n            hostName = (String) externalProperties.get(PersistenceProperties.KUNDERA_NODES);\n            defaultPort = (String) externalProperties.get(PersistenceProperties.KUNDERA_PORT);\n            storeName = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);\n            poolSize = (String) externalProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE);\n            userName = (String) externalProperties.get(PersistenceProperties.KUNDERA_USERNAME);\n            password = (String) externalProperties.get(PersistenceProperties.KUNDERA_PASSWORD);\n        }\n\n        if (hostName == null)\n        {\n            hostName = (String) props.get(PersistenceProperties.KUNDERA_NODES);\n        }\n        if (defaultPort == null)\n        {\n            defaultPort = (String) props.get(PersistenceProperties.KUNDERA_PORT);\n        }\n        // keyspace is keystore\n        if (storeName == null)\n        {\n            storeName = (String) props.get(PersistenceProperties.KUNDERA_KEYSPACE);\n        }\n        if (poolSize == null)\n        {\n            poolSize = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE);\n        }\n        String[] hosts = new String[configuration.getHosts().size()];\n        int count = 0;\n\n        for (Host host : configuration.getHosts())\n        {\n            hosts[count] = host.getHost() + \":\" + host.getPort();\n            count++;\n        }\n        \n        KVStoreConfig kconfig = new KVStoreConfig(storeName, hosts);\n        try\n        {\n\n            if (!((OracleNoSQLHostConfiguration)configuration).getSecurityProps().isEmpty())\n            {\n                \n                kconfig.setSecurityProperties(((OracleNoSQLHostConfiguration)configuration).getSecurityProps());\n                \n            }\n            \n            if (userName != null && password != null)\n            {\n                return KVStoreFactory\n                        .getStore(kconfig, new PasswordCredentials(userName, password.toCharArray()), null);\n            }\n        }\n        catch (AuthenticationFailureException afe)\n        {\n            /*\n             * Could potentially retry the login, possibly with different\n             * credentials, but in this simple example, we just fail the\n             * attempt.\n             */\n            throw new KunderaException(\"Could not authorize the client connection \" + afe.getMessage());\n\n        }\n\n        return KVStoreFactory.getStore(kconfig);\n    }\n\n\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n        throw new UnsupportedOperationException(\"Load balancing feature is not supported in \"\n                + this.getClass().getSimpleName());\n    }\n}"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/OracleNoSQLDataHandler.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql;\n\n/**\n * Utility class for handling read/ write of data from/ to Oracle NoSQL database\n * @author amresh.singh\n */\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.util.List;\n\nimport javax.persistence.PersistenceException;\n\nimport oracle.kv.DurabilityException;\nimport oracle.kv.FaultException;\nimport oracle.kv.KVStore;\nimport oracle.kv.Key;\nimport oracle.kv.KeyValueVersion;\nimport oracle.kv.Operation;\nimport oracle.kv.OperationExecutionException;\nimport oracle.kv.Version;\nimport oracle.kv.lob.InputStreamVersion;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.Client;\n\n/**\n * Provides utility methods for handling data held in Oracle NoSQL KVstore.\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLDataHandler\n{\n    /** The client. */\n    private OracleNoSQLClient client;\n\n    private KVStore kvStore;\n\n    /** The persistence unit. */\n    private String persistenceUnit;\n\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(OracleNoSQLDataHandler.class);\n\n    /**\n     * Instantiates a new mongo db data handler.\n     * \n     * @param client\n     *            the client\n     * @param persistenceUnit\n     *            the persistence unit\n     */\n    public OracleNoSQLDataHandler(Client client, KVStore kvStore, String persistenceUnit)\n    {\n        super();\n        this.client = (OracleNoSQLClient) client;\n        this.kvStore = kvStore;\n        this.persistenceUnit = persistenceUnit;\n    }\n\n    public void execute(List<Operation> operations)\n    {\n        if (operations != null && !operations.isEmpty())\n        {\n            try\n            {\n                kvStore.execute(operations);\n            }\n            catch (DurabilityException e)\n            {\n                log.error(\"Error while executing operations\",e);\n                throw new PersistenceException(\"Error while Persisting data using batch. Caused by: \" + e + \".\");\n            }\n            catch (OperationExecutionException e)\n            {\n                log.error(\"Error while executing operations\",e);\n                throw new PersistenceException(\"Error while Persisting data using batch. Caused by: \" + e + \".\");\n            }\n            catch (FaultException e)\n            {\n                log.error(\"Error while executing operations\",e);\n                throw new PersistenceException(\"Error while Persisting data using batch. Caused by: \" + e + \".\");\n            }\n            finally\n            {\n                operations.clear();\n            }\n        }\n    }\n\n    /**\n     * @param keyValueVersion\n     * @param fileName\n     * @return\n     * @throws FileNotFoundException\n     * @throws IOException\n     */\n    public File getLOBFile(KeyValueVersion keyValueVersion, String fileName) throws FileNotFoundException, IOException\n    {\n        InputStreamVersion istreamVersion = kvStore.getLOB(keyValueVersion.getKey(), client.getConsistency(),\n                client.getTimeout(), client.getTimeUnit());\n        InputStream is = istreamVersion.getInputStream();\n\n        File lobFile = new File(fileName);\n        OutputStream os = new FileOutputStream(lobFile);\n        int read = 0;\n        byte[] bytes = new byte[OracleNOSQLConstants.OUTPUT_BUFFER_SIZE];\n        while ((read = is.read(bytes)) != -1)\n        {\n            os.write(bytes, 0, read);\n        }\n        return lobFile;\n    }\n\n    /**\n     * @param minorKey\n     * @return\n     */\n    public String removeLOBSuffix(String minorKey)\n    {\n        if (minorKey == null)\n            return minorKey;\n\n        if (minorKey.endsWith(OracleNOSQLConstants.LOB_SUFFIX))\n        {\n            minorKey = minorKey.substring(0, minorKey.length() - OracleNOSQLConstants.LOB_SUFFIX.length());\n        }\n        return minorKey;\n    }\n\n    /**\n     * Saves LOB file to Oracle KV Store\n     * \n     * @param key\n     * @param lobFile\n     */\n    public void saveLOBFile(Key key, File lobFile)\n    {\n        try\n        {\n            FileInputStream fis = new FileInputStream(lobFile);\n            Version version = kvStore.putLOB(key, fis, client.getDurability(), client.getTimeout(),\n                    client.getTimeUnit());\n        }\n        catch (FileNotFoundException e)\n        {\n            log.warn(\"Unable to find file \" + lobFile + \". This is being omitted, Caused by:\" + e + \".\");\n        }\n        catch (IOException e)\n        {\n            log.warn(\"IOException while writing file \" + lobFile + \". This is being omitted. Caused by:\" + e + \".\");\n        }\n    }\n\n}"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/OracleNoSQLEntityReader.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql;\n\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * Implementation of {@link EntityReader} for Oracle NoSQL database\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLEntityReader extends AbstractEntityReader implements EntityReader\n{\n    public OracleNoSQLEntityReader(final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    public OracleNoSQLEntityReader(KunderaQuery kunderaQuery, final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n        this.kunderaQuery = kunderaQuery;\n    }\n\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        throw new UnsupportedOperationException(\"Method supported not required for Oracle NOSql\");\n    }\n\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        return super.findById(primaryKey, m, client);\n    }\n\n}"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/config/OracleNoSQLClientProperties.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.config;\n\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\nimport oracle.kv.Consistency;\nimport oracle.kv.Durability;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.oraclenosql.OracleNoSQLClient;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\n\n/**\n * OracleNoSQL implementation of {@link ClientPropertiesSetter}\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLClientProperties\n{\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(OracleNoSQLClientProperties.class);\n\n    private static final String WRITE_TIMEOUT = \"write.timeout\";\n\n    private static final String DURABILITY = \"durability\";\n\n    private static final String TIME_UNIT = \"time.unit\";\n\n    private static final String CONSISTENCY = \"consistency\";\n\n    private OracleNoSQLClient oracleNoSQLClient;\n\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        this.oracleNoSQLClient = (OracleNoSQLClient) client;\n\n        if (properties != null)\n        {\n            for (String key : properties.keySet())\n            {\n                Object value = properties.get(key);\n                if (checkNull(key, value))\n                {\n                    if (key.equals(WRITE_TIMEOUT))\n                    {\n                        setTimeOut(value);\n                    }\n                    else if (key.equals(DURABILITY) && value instanceof Durability)\n                    {\n                        this.oracleNoSQLClient.setDurability((Durability) value);\n                    }\n                    else if (key.equals(TIME_UNIT))\n                    {\n                        setTimeUnit(value);\n                    }\n                    else if (key.equals(CONSISTENCY) && value instanceof Consistency)\n                    {\n                        this.oracleNoSQLClient.setConsistency((Consistency) value);\n                    }\n                    else if (key.equals(PersistenceProperties.KUNDERA_BATCH_SIZE))\n                    {\n                        setBatchSize(value);\n                    }\n                    // Add more properties as needed\n                }\n            }\n        }\n    }\n\n    /**\n     * set time out\n     */\n    private void setTimeOut(Object value)\n    {\n        if (value instanceof Integer)\n        {\n            this.oracleNoSQLClient.setTimeout((Integer) value);\n        }\n        else if (value instanceof String)\n        {\n            this.oracleNoSQLClient.setTimeout(Integer.valueOf((String) value));\n        }\n    }\n\n    /**\n     * set time unit\n     */\n    private void setTimeUnit(Object value)\n    {\n        if (value instanceof TimeUnit)\n        {\n            this.oracleNoSQLClient.setTimeUnit((TimeUnit) value);\n        }\n        else if (value instanceof String)\n        {\n            this.oracleNoSQLClient.setTimeUnit(TimeUnit.valueOf((String) value));\n        }\n    }\n\n    /**\n     * set batch size\n     */\n    private void setBatchSize(Object value)\n    {\n        if (value instanceof Integer)\n        {\n            this.oracleNoSQLClient.setBatchSize((Integer) value);\n        }\n        else if (value instanceof String)\n        {\n            this.oracleNoSQLClient.setBatchSize(Integer.valueOf((String) value));\n        }\n    }\n\n    /**\n     * check key value map not null\n     */\n    private boolean checkNull(String key, Object value)\n    {\n        return key != null && value != null;\n    }\n\n}"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/config/OracleNoSQLPropertyReader.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.config;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection.Server;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * XML Property reader for OracleNoSQL specific configuration\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLPropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n    /** log instance */\n    private static Logger log = LoggerFactory.getLogger(OracleNoSQLPropertyReader.class);\n\n    /** OracleNoSQL schema metadata instance */\n    public static OracleNoSQLSchemaMetadata osmd;\n\n    public OracleNoSQLPropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        osmd = new OracleNoSQLSchemaMetadata();\n    }\n\n    /**\n     * Sets Client properties from XML configuration file into\n     * {@link OracleNoSQLSchemaMetadata}\n     */\n    @Override\n    protected void onXml(ClientProperties cp)\n    {\n        if (cp != null)\n        {\n            osmd.setClientProperties(cp);\n        }\n    }\n\n    /**\n     * Holds property related to OracleNoSQL specific configuration file\n     * \n     * @author Amresh\n     * \n     */\n    public class OracleNoSQLSchemaMetadata\n    {\n        private static final String ORACLE_NOSQL_DATASTORE = \"oraclenosql\";\n\n        private ClientProperties clientProperties;\n\n        public OracleNoSQLSchemaMetadata()\n        {\n\n        }\n\n        /**\n         * @return the clientProperties\n         */\n        public ClientProperties getClientProperties()\n        {\n            return clientProperties;\n        }\n\n        /**\n         * @param clientProperties\n         *            the clientProperties to set\n         */\n        private void setClientProperties(ClientProperties clientProperties)\n        {\n            this.clientProperties = clientProperties;\n        }\n\n        /**\n         * Returns datastore instance for given {@link ClientProperties} for\n         * OracleNoSQL\n         * \n         * @return\n         */\n        public DataStore getDataStore()\n        {\n            if (getClientProperties() != null && getClientProperties().getDatastores() != null)\n            {\n                for (DataStore dataStore : getClientProperties().getDatastores())\n                {\n                    if (dataStore.getName() != null && dataStore.getName().trim().equalsIgnoreCase(ORACLE_NOSQL_DATASTORE))\n                    {\n                        return dataStore;\n                    }\n                }\n            }\n            return null;\n        }\n        \n        public Properties getConnectionProperties()\n        {\n            DataStore ds = getDataStore();\n            Properties properties = new Properties();\n            if (ds != null)\n            {\n                if (ds.getConnection() != null)\n                {\n                    properties = ds.getConnection().getProperties();\n                    return properties != null ? properties : new Properties();\n                }\n                if (log.isWarnEnabled())\n                {\n                    log.warn(\"No connection properties found, returning none.\");\n                }\n            }\n            return properties;\n        }\n\n        public List<Server> getConnectionServers()\n        {\n            DataStore ds = getDataStore();\n            List<Server> servers = new ArrayList<Server>();\n            if (ds != null && ds.getConnection() != null)\n            {\n                servers = ds.getConnection().getServers();\n                return servers;\n            }\n            return servers;\n        }\n    }\n\n}"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/index/OracleNoSQLInvertedIndexer.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.index;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Queue;\nimport java.util.Set;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\n\nimport oracle.kv.Direction;\nimport oracle.kv.KVStore;\nimport oracle.kv.Key;\nimport oracle.kv.KeyRange;\nimport oracle.kv.KeyValueVersion;\nimport oracle.kv.Value;\n\nimport com.impetus.client.oraclenosql.OracleNOSQLConstants;\nimport com.impetus.client.oraclenosql.OracleNoSQLDataHandler;\nimport com.impetus.client.oraclenosql.query.OracleNoSQLQueryInterpreter;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.index.Indexer;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessor;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\n\n/**\n * Inverted Index implementation of {@link Indexer}\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLInvertedIndexer implements Indexer\n{\n\n    private KVStore kvStore;\n\n    private OracleNoSQLDataHandler handler;\n\n    @Override\n    public void index(Class entityClazz, EntityMetadata m, Map<String, Object> values, Object entityId,\n            final Class parentClazz)\n    {\n        String idColumnName = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n        Object id = values.get(idColumnName);\n\n        for (String column : values.keySet())\n        {\n            Object valueObject = values.get(column);\n\n            List<String> majorKeyComponents = new ArrayList<String>();\n            majorKeyComponents.add(getIndexTableName(m));\n            majorKeyComponents.add(column);\n            majorKeyComponents.add(PropertyAccessorHelper.getString(valueObject));\n\n            String minorKey = PropertyAccessorHelper.getString(id);\n\n            Key key = Key.createKey(majorKeyComponents, minorKey);\n            byte[] valueByteArray = PropertyAccessorHelper.getBytes(id);\n\n            kvStore.put(key, Value.createValue(valueByteArray));\n        }\n    }\n\n    @Override\n    public Map<String, Object> search(Class<?> clazz, EntityMetadata m, String luceneQuery, int start, int count)\n    {\n        throw new UnsupportedOperationException(\"This method is not supported for OracleNoSQL.\");\n    }\n\n    @Override\n    public Map<String, Object> search(String query, Class<?> parentClass, EntityMetadata parentMetadata,\n            Class<?> childClass, EntityMetadata childMetadata, Object entityId, int start, int count)\n    {\n        String secIndexName = getIndexTableName(childMetadata);\n        String parentIdColumnName = ((AbstractAttribute) parentMetadata.getIdAttribute()).getJPAColumnName();\n        String childIdColumnName = ((AbstractAttribute) childMetadata.getIdAttribute()).getJPAColumnName();\n        String id = PropertyAccessorHelper.getString(entityId);\n\n        List<String> majorComponents = new ArrayList<String>();\n        majorComponents.add(secIndexName);\n        majorComponents.add(parentIdColumnName);\n        majorComponents.add(id);\n\n        Key majorKeyToFind = Key.createKey(majorComponents);\n\n        Iterator<KeyValueVersion> iterator = kvStore.multiGetIterator(Direction.FORWARD, 0, majorKeyToFind, null, null);\n\n        Map<String, Object> results = new HashMap<String, Object>();\n\n        while (iterator.hasNext())\n        {\n            KeyValueVersion keyValueVersion = iterator.next();\n            String minorKey = keyValueVersion.getKey().getMinorPath().get(0);\n\n            PropertyAccessor accessor = PropertyAccessorFactory\n                    .getPropertyAccessor(childMetadata.getIdAttribute().getBindableJavaType());\n\n            byte[] idByteArr = keyValueVersion.getValue().getValue();\n            Object keyObj = accessor.fromBytes(childMetadata.getIdAttribute().getBindableJavaType(), idByteArr);\n\n            results.put(childIdColumnName + \"|\" + minorKey, keyObj);\n        }\n\n        return results;\n    }\n\n    public <E> Set<E> executeQuery(OracleNoSQLQueryInterpreter interpreter, Class<?> entityClass,\n            EntityMetadata entityMetadata)\n    {\n        String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();\n        String secIndexName = getIndexTableName(entityMetadata);\n\n        Set<Object> results = new HashSet<Object>();\n        Set<Object> foundKeys = new HashSet<Object>();\n        String interClauseOperator = null;\n\n        Queue filterClauseQueue = interpreter.getClauseQueue();\n\n        for (Object clause : filterClauseQueue)\n        {\n            if (clause instanceof FilterClause)\n            {\n                foundKeys = new HashSet<Object>();\n\n                String columnName = ((FilterClause) clause).getProperty();\n                String condition = ((FilterClause) clause).getCondition();\n                Object value = ((FilterClause) clause).getValue();\n\n                if (columnName.equals(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName())\n                        && condition.equals(\"=\"))\n                {\n                    Object idValue = PropertyAccessorHelper.fromSourceToTargetClass(\n                            entityMetadata.getIdAttribute().getJavaType(), String.class, value);\n                    foundKeys.add(idValue);\n                }\n                else\n                {\n                    List<String> majorComponents = new ArrayList<String>();\n                    majorComponents.add(secIndexName);\n                    majorComponents.add(columnName);\n\n                    KeyRange range = null;\n                    Iterator<KeyValueVersion> iterator = null;\n\n                    if (condition.equals(\"=\"))\n                    {\n                        majorComponents.add(PropertyAccessorHelper.getString(value));\n                        Key majorKeyToFind = Key.createKey(majorComponents);\n                        iterator = kvStore.multiGetIterator(Direction.FORWARD, 0, majorKeyToFind, range, null);\n                    }\n                    else if (condition.equals(\">\"))\n                    {\n                        range = new KeyRange(value.toString(), false, null, true);\n                        Key majorKeyToFind = Key.createKey(majorComponents);\n                        iterator = kvStore.storeIterator(Direction.UNORDERED, 0, majorKeyToFind, range, null);\n                    }\n                    else if (condition.equals(\"<\"))\n                    {\n                        range = new KeyRange(null, true, value.toString(), false);\n                        Key majorKeyToFind = Key.createKey(majorComponents);\n                        iterator = kvStore.storeIterator(Direction.UNORDERED, 0, majorKeyToFind, range, null);\n                    }\n                    else if (condition.equals(\">=\"))\n                    {\n                        range = new KeyRange(value.toString(), true, null, true);\n                        Key majorKeyToFind = Key.createKey(majorComponents);\n                        iterator = kvStore.storeIterator(Direction.UNORDERED, 0, majorKeyToFind, range, null);\n                    }\n                    else if (condition.equals(\"<=\"))\n                    {\n                        range = new KeyRange(null, true, value.toString(), true);\n                        Key majorKeyToFind = Key.createKey(majorComponents);\n                        iterator = kvStore.storeIterator(Direction.UNORDERED, 0, majorKeyToFind, range, null);\n                    }\n\n                    while (iterator.hasNext())\n                    {\n                        KeyValueVersion keyValueVersion = iterator.next();\n                        String minorKey = keyValueVersion.getKey().getMinorPath().get(0);\n\n                        PropertyAccessor accessor = PropertyAccessorFactory\n                                .getPropertyAccessor(entityMetadata.getIdAttribute().getBindableJavaType());\n\n                        byte[] idByteArr = keyValueVersion.getValue().getValue();\n                        Object keyObj = accessor.fromBytes(entityMetadata.getIdAttribute().getBindableJavaType(),\n                                idByteArr);\n\n                        foundKeys.add(keyObj);\n                    }\n\n                }\n            }\n            else if (clause instanceof String)\n            {\n                interClauseOperator = clause.toString().trim();\n            }\n\n            addToResults(results, foundKeys, interClauseOperator);\n        }\n\n        return (Set<E>) results;\n\n    }\n\n    @Override\n    public void unIndex(Class entityClazz, Object entity, EntityMetadata entityMetadata, MetamodelImpl metamodel)\n    {\n        String indexTableName = getIndexTableName(entityMetadata);\n\n        // byte[] id = PropertyAccessorHelper.get(entity,\n        // (Field)entityMetadata.getIdAttribute().getJavaMember());\n        Object id = PropertyAccessorHelper.getId(entity, entityMetadata);\n        EntityType entityType = metamodel.entity(entityMetadata.getEntityClazz());\n        Set<Attribute> attributes = entityType.getSingularAttributes();\n\n        for (Attribute attribute : attributes)\n        {\n            Class fieldJavaType = ((AbstractAttribute) attribute).getBindableJavaType();\n\n            if (!attribute.isAssociation() && !metamodel.isEmbeddable(fieldJavaType))\n            {\n                String columnName = ((AbstractAttribute) attribute).getJPAColumnName();\n\n                List<String> majorComponents = new ArrayList<String>();\n                majorComponents.add(indexTableName);\n                majorComponents.add(columnName);\n\n                Key key = Key.createKey(majorComponents);\n                Iterator<KeyValueVersion> iterator = kvStore.storeIterator(Direction.UNORDERED, 0, key, null, null);\n\n                while (iterator.hasNext())\n                {\n                    KeyValueVersion keyValueVersion = iterator.next();\n                    Key keytoDelete = keyValueVersion.getKey();\n                    byte[] value = keyValueVersion.getValue().getValue();\n                    Object valueObject = PropertyAccessorHelper.getObject(\n                            ((AbstractAttribute) entityMetadata.getIdAttribute()).getBindableJavaType(), value);\n\n                    if (valueObject.equals(id))\n                    {\n                        // Delete this key\n                        kvStore.multiDelete(keytoDelete, null, null);\n                    }\n                }\n            }\n        }\n\n    }\n\n    @Override\n    public void close()\n    {\n    }\n\n    private void addToResults(Set results, Set resultsToAdd, String operation)\n    {\n        if (resultsToAdd == null || resultsToAdd.isEmpty())\n        {\n            return;\n        }\n\n        if (operation == null)\n        {\n            results.addAll(resultsToAdd);\n        }\n        else if (operation.equalsIgnoreCase(\"OR\"))\n        {\n            results.addAll(resultsToAdd);\n        }\n        else if (operation.equalsIgnoreCase(\"AND\"))\n        {\n            if (results.isEmpty())\n            {\n                results.addAll(resultsToAdd);\n            }\n            else\n            {\n                results.retainAll(resultsToAdd);\n            }\n        }\n\n        resultsToAdd.clear();\n    }\n\n    /**\n     * @return the kvStore\n     */\n    public KVStore getKvStore()\n    {\n        return kvStore;\n    }\n\n    /**\n     * @param kvStore\n     *            the kvStore to set\n     */\n    public void setKvStore(KVStore kvStore)\n    {\n        this.kvStore = kvStore;\n    }\n\n    /**\n     * @param handler\n     *            the handler to set\n     */\n    public void setHandler(OracleNoSQLDataHandler handler)\n    {\n        this.handler = handler;\n    }\n\n    /**\n     * @param entityMetadata\n     * @return\n     */\n    protected String getIndexTableName(EntityMetadata entityMetadata)\n    {\n        return entityMetadata.getIndexName() + OracleNOSQLConstants.SECONDARY_INDEX_SUFFIX;\n    }\n\n    @Override\n    public Map<String, Object> search(KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery,\n            PersistenceDelegator persistenceDelegator, EntityMetadata m, int firstResult, int maxResults)\n    {\n        throw new KunderaException(\"Unsupported Method\");\n    }\n}"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/query/OracleNoSQLQuery.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.query;\n\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Queue;\nimport java.util.Set;\n\nimport javax.persistence.Query;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.oraclenosql.OracleNoSQLClient;\nimport com.impetus.client.oraclenosql.OracleNoSQLEntityReader;\nimport com.impetus.client.oraclenosql.index.OracleNoSQLInvertedIndexer;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.query.QueryImpl;\n\n/**\n * Implementation of {@link Query} for Oracle NoSQL database\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLQuery extends QueryImpl\n{\n    private static Logger log = LoggerFactory.getLogger(OracleNoSQLQuery.class);\n\n    public OracleNoSQLQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n    }\n\n    @Override\n    protected List<Object> populateEntities(EntityMetadata m, Client client)\n    {\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"Populating entities for JPA query on OracleNOSQL\");\n        }\n\n        OracleNoSQLQueryInterpreter interpreter = translateQuery(getKunderaQuery().getFilterClauseQueue(), m);\n\n        ClientMetadata clientMetadata = ((ClientBase) client).getClientMetadata();\n\n        if (!MetadataUtils.useSecondryIndex(clientMetadata)\n                && !(clientMetadata.getIndexImplementor() != null && clientMetadata.getIndexImplementor().equals(\n                        OracleNoSQLInvertedIndexer.class.getName())))\n        {\n            return populateUsingLucene(m, client, null, interpreter.getSelectColumns());\n        }\n        else\n        {\n            return (List<Object>) ((OracleNoSQLClient) client).executeQuery(m.getEntityClazz(), interpreter,\n                    null);\n        }\n    }\n\n    @Override\n    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n        List<Object> ls = new ArrayList<Object>();\n        ls = populateEntities(m, client);\n\n        return setRelationEntities(ls, client, m);\n    }\n\n    @Override\n    protected EntityReader getReader()\n    {\n        return new OracleNoSQLEntityReader(kunderaQuery, kunderaMetadata);\n    }\n\n    @Override\n    protected int onExecuteUpdate()\n    {\n        return onUpdateDeleteEvent();\n    }\n\n    private OracleNoSQLQueryInterpreter translateQuery(Queue clauseQueue, EntityMetadata entityMetadata)\n    {\n        OracleNoSQLQueryInterpreter interpreter = new OracleNoSQLQueryInterpreter(getColumns(getKunderaQuery()\n                .getResult(), entityMetadata));\n        interpreter.setClauseQueue(clauseQueue);\n\n        String operatorWithIdClause = null;\n        boolean idClauseFound = false;\n        for (Object clause : clauseQueue)\n        {\n            if (clause.getClass().isAssignableFrom(FilterClause.class) && !idClauseFound)\n            {\n                String columnName = ((FilterClause) clause).getProperty();\n                SingularAttribute idAttribute = entityMetadata.getIdAttribute();\n                if (columnName.equals(((AbstractAttribute) idAttribute).getJPAColumnName()))\n                {\n                    interpreter.setFindById(true);\n                    // To convert rowkey string to object.\n                    // With 2.11 onwards Filter clause values has been changed\n                    // to collection of values. other than IN or sub query\n                    // doing get(0) here.\n                    Object keyObj = PropertyAccessorHelper.fromSourceToTargetClass(((AbstractAttribute) idAttribute)\n                            .getBindableJavaType(), (((FilterClause) clause).getValue().get(0)).getClass(),\n                            ((FilterClause) clause).getValue().get(0));\n\n                    interpreter.setRowKey(keyObj);\n                    idClauseFound = true;\n                }\n            }\n            else if (clause instanceof String)\n            {\n                operatorWithIdClause = clause.toString().trim();\n            }\n\n            if (idClauseFound && operatorWithIdClause != null)\n            {\n                break;\n            }\n        }\n\n        interpreter.setOperatorWithRowKey(operatorWithIdClause);\n\n        return interpreter;\n    }\n\n    @Override\n    public void close()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    @Override\n    public Iterator iterate()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n        OracleNoSQLQueryInterpreter interpreter = translateQuery(getKunderaQuery().getFilterClauseQueue(), m);\n        return ((OracleNoSQLClient) client).executeQuery(m.getEntityClazz(), interpreter, null);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/query/OracleNoSQLQueryInterpreter.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.query;\n\nimport java.util.Queue;\n\n/**\n * Interprets JPA query and holds conditions to pass on to client\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLQueryInterpreter\n{\n\n    // Select columns\n    private String[] selectColumns;\n\n    private boolean isFindById;\n\n    private Object rowKey;\n\n    private String operatorWithRowKey;\n\n    private Queue clauseQueue;\n\n    /**\n     * Default constructor\n     */\n    public OracleNoSQLQueryInterpreter(String[] selectColumns)\n    {\n        this.selectColumns = selectColumns;\n    }\n\n    /**\n     * @return the clauseQueue\n     */\n    public Queue getClauseQueue()\n    {\n        return clauseQueue;\n    }\n\n    /**\n     * @param clauseQueue\n     *            the clauseQueue to set\n     */\n    public void setClauseQueue(Queue clauseQueue)\n    {\n        this.clauseQueue = clauseQueue;\n    }\n\n    /**\n     * @return the selectColumns\n     */\n    public String[] getSelectColumns()\n    {\n        return selectColumns;\n    }\n\n    /**\n     * @param selectColumns\n     *            the selectColumns to set\n     */\n    public void setSelectColumns(String[] selectColumns)\n    {\n        this.selectColumns = selectColumns;\n    }\n\n    /**\n     * @return the isFindById\n     */\n    public boolean isFindById()\n    {\n        return isFindById;\n    }\n\n    /**\n     * @param isFindById\n     *            the isFindById to set\n     */\n    public void setFindById(boolean isFindById)\n    {\n        this.isFindById = isFindById;\n    }\n\n    /**\n     * @return the rowKey\n     */\n    public Object getRowKey()\n    {\n        return rowKey;\n    }\n\n    /**\n     * @param rowKey\n     *            the rowKey to set\n     */\n    public void setRowKey(Object rowKey)\n    {\n        this.rowKey = rowKey;\n    }\n\n    /**\n     * @return the operatorWithRowKey\n     */\n    public String getOperatorWithRowKey()\n    {\n        return operatorWithRowKey;\n    }\n\n    /**\n     * @param operatorWithRowKey\n     *            the operatorWithRowKey to set\n     */\n    public void setOperatorWithRowKey(String operatorWithRowKey)\n    {\n        this.operatorWithRowKey = operatorWithRowKey;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/schemamanager/OracleNoSQLSchemaManager.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.schemamanager;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport javax.persistence.Embeddable;\n\nimport oracle.kv.FaultException;\nimport oracle.kv.KVSecurityConstants;\nimport oracle.kv.KVStore;\nimport oracle.kv.KVStoreConfig;\nimport oracle.kv.KVStoreFactory;\nimport oracle.kv.PasswordCredentials;\nimport oracle.kv.table.StatementResult;\nimport oracle.kv.table.Table;\nimport oracle.kv.table.TableAPI;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.configure.schema.ColumnInfo;\nimport com.impetus.kundera.configure.schema.EmbeddedColumnInfo;\nimport com.impetus.kundera.configure.schema.IndexInfo;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.configure.schema.TableInfo;\nimport com.impetus.kundera.configure.schema.api.AbstractSchemaManager;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\n\n/**\n * The Class OracleNoSQLSchemaManager.\n * \n * @author devender.yadav\n * \n */\npublic class OracleNoSQLSchemaManager extends AbstractSchemaManager implements SchemaManager\n{\n\n    /** The Constant logger. */\n    private static final Logger logger = LoggerFactory.getLogger(OracleNoSQLSchemaManager.class);\n\n    /** The kv store. */\n    private KVStore kvStore;\n\n    /** The table api. */\n    private TableAPI tableAPI;\n\n    private Properties securityProps = new Properties();\n\n    /**\n     * Instantiates a new oracle no sql schema manager.\n     * \n     * @param clientFactory\n     *            the client factory\n     * @param externalProperties\n     *            the external properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public OracleNoSQLSchemaManager(String clientFactory, Map<String, Object> externalProperties,\n            KunderaMetadata kunderaMetadata)\n    {\n        super(clientFactory, externalProperties, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.SchemaManager#validateEntity\n     * (java.lang.Class)\n     */\n    @Override\n    public boolean validateEntity(Class clazz)\n    {\n        return true;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.AbstractSchemaManager#\n     * exportSchema (java.lang.String, java.util.List)\n     */\n    @Override\n    public void exportSchema(String persistenceUnit, List<TableInfo> puToSchemaCol)\n    {\n        super.exportSchema(persistenceUnit, puToSchemaCol);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.SchemaManager#dropSchema()\n     */\n    @Override\n    public void dropSchema()\n    {\n        // dropping all the tables in the Oracle NoSQL store\n        if (operation != null && operation.equalsIgnoreCase(\"create-drop\"))\n        {\n            for (TableInfo tableInfo : tableInfos)\n            {\n                try\n                {\n                    StatementResult result = tableAPI.executeSync(\"DROP TABLE IF EXISTS \" + tableInfo.getTableName());\n                    if (!result.isSuccessful())\n                    {\n                        throw new SchemaGenerationException(\"Unable to DROP TABLE \" + tableInfo.getTableName());\n                    }\n                }\n                catch (IllegalArgumentException e)\n                {\n                    logger.error(\"Invalid DROP TABLE Statement. Caused By: \", e);\n                    throw new SchemaGenerationException(e, \"Invalid DROP TABLE Statement. Caused By: \");\n                }\n                catch (FaultException e)\n                {\n                    logger.error(\"DROP TABLE Statement couldn't be executed. Caused By: \", e);\n                    throw new SchemaGenerationException(e, \"Invalid DROP TABLE Statement is executed. Caused By: \");\n                }\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.AbstractSchemaManager#\n     * initiateClient ()\n     */\n    @Override\n    protected boolean initiateClient()\n    {\n        String[] hostsList = new String[hosts.length];\n        int count = 0;\n        for (String host : hosts)\n        {\n            if (host == null || !StringUtils.isNumeric(port) || port.isEmpty())\n            {\n                logger.error(\"Host or port should not be null / port should be numeric\");\n                throw new IllegalArgumentException(\"Host or port should not be null / port should be numeric\");\n            }\n            hostsList[count] = host + \":\" + port;\n            count++;\n        }\n        KVStoreConfig kconfig = new KVStoreConfig(databaseName, hostsList);\n        if (!securityProps.isEmpty())\n        {\n\n            kconfig.setSecurityProperties(securityProps);\n\n        }\n\n        try\n        {\n            if (userName != null && password != null)\n            {\n                kvStore = KVStoreFactory.getStore(kconfig, new PasswordCredentials(userName, password.toCharArray()),\n                        null);\n            }\n            else\n            {\n                kvStore = KVStoreFactory.getStore(kconfig);\n            }\n\n            tableAPI = kvStore.getTableAPI();\n        }\n        catch (FaultException e)\n        {\n            logger.error(\"Unable to get KVStore. Caused by \", e);\n            throw new KunderaException(\"Unable to get KVStore. Caused by \", e);\n        }\n\n        return true;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#validate\n     * (java.util.List)\n     */\n    @Override\n    protected void validate(List<TableInfo> tableInfos)\n    {\n        for (TableInfo tableInfo : tableInfos)\n        {\n            try\n            {\n                if (tableAPI.getTable(tableInfo.getTableName()) == null)\n                {\n                    logger.error(\"No table found for \" + tableInfo.getTableName());\n                    throw new SchemaGenerationException(\"No table found for \" + tableInfo.getTableName());\n                }\n            }\n            catch (FaultException e)\n            {\n                logger.error(\"Error while getting table \" + tableInfo.getTableName() + \". Caused By: \", e);\n                throw new SchemaGenerationException(e, \"Error while getting table \" + tableInfo.getTableName()\n                        + \". Caused By: \");\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#update\n     * (java.util.List)\n     */\n    @Override\n    protected void update(List<TableInfo> tableInfos)\n    {\n        StatementResult result = null;\n        String statement = null;\n        for (TableInfo tableInfo : tableInfos)\n        {\n            try\n            {\n                Table table = tableAPI.getTable(tableInfo.getTableName());\n                if (table == null)\n                {\n                    statement = buildCreateDDLQuery(tableInfo);\n                    result = tableAPI.executeSync(statement);\n                    if (!result.isSuccessful())\n                    {\n                        throw new SchemaGenerationException(\"Unable to CREATE TABLE \" + tableInfo.getTableName());\n                    }\n                }\n                else\n                {\n                    List<ColumnInfo> columnInfos = tableInfo.getColumnMetadatas();\n                    Map<String, String> newColumns = new HashMap<String, String>();\n                    for (ColumnInfo column : columnInfos)\n                    {\n                        if (table.getField(column.getColumnName()) == null)\n                        {\n                            newColumns.put(column.getColumnName(), column.getType().getSimpleName());\n                        }\n                    }\n\n                    List<EmbeddedColumnInfo> embeddedColumnInfos = tableInfo.getEmbeddedColumnMetadatas();\n                    for (EmbeddedColumnInfo embeddedColumnInfo : embeddedColumnInfos)\n                    {\n                        for (ColumnInfo column : embeddedColumnInfo.getColumns())\n                        {\n                            if (table.getField(column.getColumnName()) == null)\n                            {\n                                newColumns.put(column.getColumnName(), column.getType().getSimpleName());\n                            }\n                        }\n                    }\n                    if (!newColumns.isEmpty())\n                    {\n                        statement = buildAlterDDLQuery(tableInfo, newColumns);\n                        result = tableAPI.executeSync(statement);\n\n                        if (!result.isSuccessful())\n                        {\n                            throw new SchemaGenerationException(\"Unable to ALTER TABLE \" + tableInfo.getTableName());\n                        }\n                    }\n                }\n                createIndexOnTable(tableInfo);\n            }\n            catch (IllegalArgumentException e)\n            {\n                logger.error(\"Invalid Statement. Caused By: \", e);\n                throw new SchemaGenerationException(e, \"Invalid Statement. Caused By: \");\n            }\n            catch (FaultException e)\n            {\n                logger.error(\"Statement couldn't be executed. Caused By: \", e);\n                throw new SchemaGenerationException(e, \"Statement couldn't be executed. Caused By: \");\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#create\n     * (java.util.List)\n     */\n    @Override\n    protected void create(List<TableInfo> tableInfos)\n    {\n        StatementResult result = null;\n        String statement = null;\n\n        for (TableInfo tableInfo : tableInfos)\n        {\n            try\n            {\n                result = tableAPI.executeSync(\"DROP TABLE IF EXISTS \" + tableInfo.getTableName());\n                if (!result.isSuccessful())\n                {\n                    throw new SchemaGenerationException(\"Unable to DROP TABLE \" + tableInfo.getTableName());\n                }\n                statement = buildCreateDDLQuery(tableInfo);\n                result = tableAPI.executeSync(statement);\n                if (!result.isSuccessful())\n                {\n                    throw new SchemaGenerationException(\"Unable to CREATE TABLE \" + tableInfo.getTableName());\n                }\n                createIndexOnTable(tableInfo);\n            }\n            catch (IllegalArgumentException e)\n            {\n                logger.error(\"Invalid Statement. Caused By: \", e);\n                throw new SchemaGenerationException(e, \"Invalid Statement. Caused By: \");\n            }\n            catch (FaultException e)\n            {\n                logger.error(\"Statement couldn't be executed. Caused By: \", e);\n                throw new SchemaGenerationException(e, \"Statement couldn't be executed. Caused By: \");\n            }\n        }\n    }\n\n    /**\n     * Creates the index on table.\n     * \n     * @param tableInfo\n     *            the table info\n     */\n    private void createIndexOnTable(TableInfo tableInfo)\n    {\n\n        List<IndexInfo> indexColumns = tableInfo.getColumnsToBeIndexed();\n        for (IndexInfo indexInfo : indexColumns)\n        {\n            if (indexInfo.getIndexType() != null && indexInfo.getIndexType().toLowerCase().equals(Constants.COMPOSITE))\n            {\n                String[] columnNames = indexInfo.getColumnName().split(Constants.COMMA);\n                createIndex(tableInfo.getTableName(), indexInfo.getIndexName(), columnNames);\n            }\n            else\n            {\n                createIndex(tableInfo.getTableName(), indexInfo.getIndexName(), indexInfo.getColumnName());\n            }\n        }\n    }\n\n    /**\n     * Creates the index.\n     * \n     * @param tableName\n     *            the table name\n     * @param indexName\n     *            the index name\n     * @param fieldName\n     *            the field name\n     */\n    private void createIndex(String tableName, String indexName, String... fieldNames)\n    {\n        StringBuilder builder = new StringBuilder();\n        builder.append(\"CREATE INDEX IF NOT EXISTS \");\n        builder.append(indexName);\n        builder.append(\" ON \");\n        builder.append(tableName);\n        builder.append(Constants.OPEN_ROUND_BRACKET);\n        for (String fieldName : fieldNames)\n        {\n            builder.append(fieldName);\n            builder.append(Constants.COMMA);\n        }\n        builder.deleteCharAt(builder.length() - 1);\n        builder.append(Constants.CLOSE_ROUND_BRACKET);\n        StatementResult result = tableAPI.executeSync(builder.toString());\n        if (!result.isSuccessful())\n        {\n            throw new SchemaGenerationException(\"Unable to CREATE Index with Index Name [\" + indexName\n                    + \"] for table [\" + tableName + \"]\");\n        }\n    }\n\n    /**\n     * Builds the create ddl query.\n     * \n     * @param tableInfo\n     *            the table info\n     * @return the string\n     */\n    private String buildCreateDDLQuery(TableInfo tableInfo)\n    {\n        String statement;\n        boolean flag = false;\n        StringBuilder compoundKeys = null;\n        StringBuilder builder = new StringBuilder();\n        builder.append(\"CREATE TABLE \");\n        builder.append(tableInfo.getTableName());\n        builder.append(Constants.OPEN_ROUND_BRACKET);\n\n        if (!tableInfo.getTableIdType().isAnnotationPresent(Embeddable.class))\n        {\n            builder.append(tableInfo.getIdColumnName());\n            builder.append(Constants.SPACE);\n            String idType = tableInfo.getTableIdType().getSimpleName().toLowerCase();\n            builder.append(OracleNoSQLValidationClassMapper.getValidIdType(idType));\n            builder.append(Constants.COMMA);\n        }\n\n        for (ColumnInfo columnInfo : tableInfo.getColumnMetadatas())\n        {\n            builder.append(columnInfo.getColumnName());\n            builder.append(Constants.SPACE);\n            String coulmnType = columnInfo.getType().getSimpleName().toLowerCase();\n            builder.append(OracleNoSQLValidationClassMapper.getValidType(coulmnType));\n            builder.append(Constants.COMMA);\n        }\n        for (EmbeddedColumnInfo embeddedColumnInfo : tableInfo.getEmbeddedColumnMetadatas())\n        {\n            if (tableInfo.getIdColumnName().equals(embeddedColumnInfo.getEmbeddedColumnName()))\n            {\n                compoundKeys = new StringBuilder();\n                flag = true;\n            }\n            for (ColumnInfo columnInfo : embeddedColumnInfo.getColumns())\n            {\n                builder.append(columnInfo.getColumnName());\n                builder.append(Constants.SPACE);\n                String coulmnType = columnInfo.getType().getSimpleName().toLowerCase();\n                builder.append(OracleNoSQLValidationClassMapper.getValidType(coulmnType));\n                builder.append(Constants.COMMA);\n                if (flag)\n                {\n                    compoundKeys.append(columnInfo.getColumnName());\n                    compoundKeys.append(Constants.COMMA);\n                }\n            }\n            flag = false;\n        }\n\n        builder.append(\"PRIMARY KEY\");\n        builder.append(Constants.OPEN_ROUND_BRACKET);\n\n        if (!tableInfo.getTableIdType().isAnnotationPresent(Embeddable.class))\n        {\n            builder.append(tableInfo.getIdColumnName());\n        }\n        else\n        {\n            compoundKeys.deleteCharAt(compoundKeys.length() - 1);\n            builder.append(compoundKeys.toString());\n        }\n\n        builder.append(Constants.CLOSE_ROUND_BRACKET);\n        builder.append(Constants.CLOSE_ROUND_BRACKET);\n\n        statement = builder.toString();\n        return statement;\n    }\n\n    /**\n     * Builds the alter ddl query.\n     * \n     * @param tableInfo\n     *            the table info\n     * @param newColumns\n     *            the new columns\n     * @return the string\n     */\n    private String buildAlterDDLQuery(TableInfo tableInfo, Map<String, String> newColumns)\n    {\n        String statement;\n        StringBuilder builder = new StringBuilder();\n        builder.append(\"ALTER TABLE \");\n        builder.append(tableInfo.getTableName());\n        builder.append(Constants.OPEN_ROUND_BRACKET);\n\n        for (Map.Entry<String, String> entry : newColumns.entrySet())\n        {\n            builder.append(\"ADD \");\n            builder.append(entry.getKey());\n            builder.append(Constants.SPACE);\n            String coulmnType = entry.getValue().toLowerCase();\n            builder.append(OracleNoSQLValidationClassMapper.getValidType(coulmnType));\n            builder.append(Constants.COMMA);\n        }\n\n        builder.deleteCharAt(builder.length() - 1);\n        builder.append(Constants.CLOSE_ROUND_BRACKET);\n        statement = builder.toString();\n        return statement;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.AbstractSchemaManager#\n     * create_drop (java.util.List)\n     */\n    @Override\n    protected void create_drop(List<TableInfo> tableInfos)\n    {\n        create(tableInfos);\n    }\n\n    /**\n     * @param secProps\n     * @param connectionProperties\n     */\n    private void setSecurityProps()\n    {\n        if (externalProperties.containsKey(KVSecurityConstants.TRANSPORT_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.TRANSPORT_PROPERTY,\n                    externalProperties.get(KVSecurityConstants.TRANSPORT_PROPERTY));\n        }\n\n        if (externalProperties.containsKey(KVSecurityConstants.SSL_TRUSTSTORE_TYPE_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.SSL_TRUSTSTORE_TYPE_PROPERTY,\n                    externalProperties.get(KVSecurityConstants.SSL_TRUSTSTORE_TYPE_PROPERTY));\n        }\n        if (externalProperties.containsKey(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY,\n                    externalProperties.get(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY));\n        }\n        if (externalProperties.containsKey(KVSecurityConstants.SSL_PROTOCOLS_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.SSL_PROTOCOLS_PROPERTY,\n                    externalProperties.get(KVSecurityConstants.SSL_PROTOCOLS_PROPERTY));\n        }\n        if (externalProperties.containsKey(KVSecurityConstants.SSL_HOSTNAME_VERIFIER_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.SSL_HOSTNAME_VERIFIER_PROPERTY,\n                    externalProperties.get(KVSecurityConstants.SSL_HOSTNAME_VERIFIER_PROPERTY));\n        }\n        if (externalProperties.containsKey(KVSecurityConstants.SSL_CIPHER_SUITES_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.SSL_CIPHER_SUITES_PROPERTY,\n                    externalProperties.get(KVSecurityConstants.SSL_CIPHER_SUITES_PROPERTY));\n        }\n        if (externalProperties.containsKey(KVSecurityConstants.SECURITY_FILE_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.SECURITY_FILE_PROPERTY,\n                    externalProperties.get(KVSecurityConstants.SECURITY_FILE_PROPERTY));\n        }\n\n        if (externalProperties.containsKey(KVSecurityConstants.AUTH_WALLET_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.AUTH_WALLET_PROPERTY,\n                    externalProperties.get(KVSecurityConstants.AUTH_WALLET_PROPERTY));\n        }\n        if (externalProperties.containsKey(KVSecurityConstants.AUTH_USERNAME_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.AUTH_USERNAME_PROPERTY,\n                    externalProperties.get(KVSecurityConstants.AUTH_USERNAME_PROPERTY));\n        }\n        if (externalProperties.containsKey(KVSecurityConstants.AUTH_PWDFILE_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.AUTH_PWDFILE_PROPERTY,\n                    externalProperties.get(KVSecurityConstants.AUTH_PWDFILE_PROPERTY));\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/schemamanager/OracleNoSQLValidationClassMapper.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.schemamanager;\n\nimport java.util.HashMap;\n\nimport com.impetus.kundera.KunderaException;\n\n/**\n * The Class OracleNoSQLValidationClassMapper.\n * \n * @author devender.yadav\n */\npublic class OracleNoSQLValidationClassMapper\n{\n\n    /** The Constant validationClassMapper. */\n    private final static HashMap<String, String> validationClassMapper = new HashMap<String, String>();\n    \n    /** The Constant validationClassMapperforId. */\n    private final static HashMap<String, String> validationClassMapperforId = new HashMap<String, String>();\n\n    static\n    {\n        validationClassMapper.put(\"int\", \"integer\");\n        validationClassMapper.put(\"integer\", \"integer\");\n        validationClassMapper.put(\"byte\", \"binary\");\n        validationClassMapper.put(\"short\", \"binary\");\n        validationClassMapper.put(\"bigdecimal\", \"binary\");\n        validationClassMapper.put(\"biginteger\", \"binary\");\n        validationClassMapper.put(\"date\", \"binary\");\n        validationClassMapper.put(\"calendar\", \"binary\");\n        validationClassMapper.put(\"char\", \"string\");\n        validationClassMapper.put(\"character\", \"string\");\n        validationClassMapper.put(\"long\", \"long\");\n        validationClassMapper.put(\"string\", \"string\");\n        validationClassMapper.put(\"boolean\", \"boolean\");\n        validationClassMapper.put(\"float\", \"float\");\n        validationClassMapper.put(\"double\", \"double\");\n        validationClassMapper.put(\"file\", \"binary\");\n        validationClassMapper.put(\"byte[]\", \"binary\");\n        \n        validationClassMapperforId.put(\"int\", \"integer\");\n        validationClassMapperforId.put(\"integer\", \"integer\");\n        validationClassMapperforId.put(\"date\", \"long\");\n        validationClassMapperforId.put(\"char\", \"string\");\n        validationClassMapperforId.put(\"character\", \"string\");\n        validationClassMapperforId.put(\"long\", \"long\");\n        validationClassMapperforId.put(\"string\", \"string\");\n        validationClassMapperforId.put(\"float\", \"float\");\n        validationClassMapperforId.put(\"double\", \"double\");\n    }\n\n    /**\n     * Gets the valid type.\n     * \n     * @param type\n     *            the type\n     * @return the valid type\n     */\n    public static String getValidType(String type)\n    {\n        return (validationClassMapper.get(type) == null) ? \"binary\" : validationClassMapper.get(type);\n    }\n    \n    /**\n     * Gets the valid Id type.\n     * \n     * @param type\n     *            the type\n     * @return the valid Id type\n     */\n    public static String getValidIdType(String type)\n    {\n    \tif(validationClassMapperforId.get(type) == null){\n    \t\tthrow new KunderaException(\"ID of type: \"+type+\" is not supported for Kundera Oracle NOSQL.\");\n    \t}\n        return  validationClassMapperforId.get(type);\n    }\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/server/OracleNoSQLHost.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.server;\n\nimport java.util.Properties;\n\nimport org.apache.commons.lang.builder.HashCodeBuilder;\n\nimport com.impetus.kundera.service.Host;\n\n/**\n * Cassandra Host configuration.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class OracleNoSQLHost implements Host\n{\n\n    public static final int DEFAULT_PORT = 5000;\n\n    private String host;\n\n    private int port;\n\n    private String userName;\n\n    private String password;\n    \n   \n\n    \n    public OracleNoSQLHost(String host)\n    {\n        this.host = host;\n        this.port = DEFAULT_PORT;\n    }\n\n    public OracleNoSQLHost(String host, int port)\n    {\n        this.host = host;\n        this.port = port;\n    }\n\n    @Override\n    public String getHost()\n    {\n        return host;\n    }\n\n    @Override\n    public int getPort()\n    {\n        return port;\n    }\n\n    @Override\n    public boolean equals(Object obj)\n    {\n        if (!(obj instanceof OracleNoSQLHost))\n        {\n            return false;\n        }\n        OracleNoSQLHost other = (OracleNoSQLHost) obj;\n        return other.host.equals(this.host) && other.port == this.port;\n    }\n\n    @Override\n    public int hashCode()\n    {\n        StringBuilder builder = new StringBuilder(host);\n        builder.append(port);\n        return HashCodeBuilder.reflectionHashCode(builder);\n    }\n\n    @Override\n    public String toString()\n    {\n        StringBuilder builder = new StringBuilder(host);\n        builder.append(\":\");\n        builder.append(port);\n        return builder.toString();\n    }\n\n\n\n\n    @Override\n    public String getUser()\n    {\n        return this.userName;\n    }\n\n    @Override\n    public String getPassword()\n    {\n        return this.password;\n    }\n\n    public void setUserName(String userName)\n    {\n        this.userName = userName;\n    }\n\n    public void setPassword(String password)\n    {\n        this.password = password;\n    }\n\n    @Override\n    public int getMaxTotal()\n    {\n        \n        return 0;\n    }\n\n    @Override\n    public int getMaxActive()\n    {\n        \n        return 0;\n    }\n\n    @Override\n    public int getMaxIdle()\n    {\n       \n        return 0;\n    }\n\n    @Override\n    public int getMinIdle()\n    {\n       \n        return 0;\n    }\n\n    @Override\n    public boolean isRetryHost()\n    {\n      \n        return false;\n    }\n\n \n  \n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/server/OracleNoSQLHostConfiguration.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.oraclenosql.server;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.concurrent.CopyOnWriteArrayList;\n\nimport oracle.kv.KVSecurityConstants;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.oraclenosql.config.OracleNoSQLPropertyReader.OracleNoSQLSchemaMetadata;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection.Server;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.service.Host;\nimport com.impetus.kundera.service.HostConfiguration;\n\n/**\n * Holds host configuration for cassandra specific settings.\n * \n * @author Kuldeep.Mishra\n * \n */\npublic class OracleNoSQLHostConfiguration extends HostConfiguration\n{\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(OracleNoSQLHostConfiguration.class);\n    \n    private Properties securityProps =  new Properties();\n\n   \n\n    public OracleNoSQLHostConfiguration(Map externalProperties, OracleNoSQLSchemaMetadata csmd, String persistenceUnit,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(externalProperties, csmd != null ? csmd.getConnectionServers() : new ArrayList<Server>(),\n                persistenceUnit, kunderaMetadata);\n\n        connectionProperties.putAll(csmd.getConnectionProperties());\n        \n        setSecurityProps(); \n\n    }\n\n    protected void buildHosts(List<Server> servers, List<Host> hostsList)\n    {\n        List<OracleNoSQLHost> oracleNoSQLHosts = new CopyOnWriteArrayList<OracleNoSQLHost>();\n\n        for (Server server : servers)\n        {\n            String host = server.getHost().trim();\n            String portAsString = server.getPort().trim();\n            onValidation(host, portAsString);\n            Properties serverProperties = server.getProperties();\n            OracleNoSQLHost oracleNoSQLHost = new OracleNoSQLHost(host, Integer.parseInt(portAsString));\n            setConfig(oracleNoSQLHost, null, serverProperties);\n            oracleNoSQLHosts.add(oracleNoSQLHost);\n            hostsList.add(oracleNoSQLHost);\n        }\n\n    }\n\n    protected void buildHosts(String hosts, String portAsString, List<Host> hostsList)\n    {\n        String[] hostVals = hosts.split(\",\");\n        List<OracleNoSQLHost> oracleNoSqlHosts = new CopyOnWriteArrayList<OracleNoSQLHost>();\n        for (int x = 0; x < hostVals.length; x++)\n        {\n            String host = hostVals[x].trim();\n            portAsString = portAsString.trim();\n            onValidation(host, portAsString);\n            int port = Integer.parseInt(portAsString);\n            OracleNoSQLHost oracleNoSQLHost = port == OracleNoSQLHost.DEFAULT_PORT ? new OracleNoSQLHost(host)\n                    : new OracleNoSQLHost(host, port);\n            setConfig(oracleNoSQLHost, persistenceUnitMetadata.getProperties(), externalProperties);\n            oracleNoSqlHosts.add(oracleNoSQLHost);\n            hostsList.add(oracleNoSQLHost);\n        }\n    }\n\n    @Override\n    protected void setConfig(Host host, Properties props, Map externalProperties)\n    {\n        OracleNoSQLHost oracleNoSQLHost = (OracleNoSQLHost) host;\n        String userName = null;\n        String password = null;\n               \n        if (externalProperties != null)\n        {\n            connectionProperties.putAll(externalProperties);\n            userName = (String) connectionProperties.get(PersistenceProperties.KUNDERA_USERNAME);\n            password = (String) connectionProperties.get(PersistenceProperties.KUNDERA_PASSWORD);\n             \n        }\n\n        if (props != null)\n        {\n \n            if (userName == null)\n            {\n                userName = props.getProperty(PersistenceProperties.KUNDERA_USERNAME);\n                password = props.getProperty(PersistenceProperties.KUNDERA_PASSWORD);\n            }\n        }\n        try\n        {\n\n            oracleNoSQLHost.setUserName(userName);\n            oracleNoSQLHost.setPassword(password);\n            \n\n        }\n        catch (NumberFormatException e)\n        {\n            logger.warn(\"Some Connection pool related property couldn't be parsed. Default pool policy would be used\");\n        }\n    }\n\n    /**\n     * @param secProps\n     * @param connectionProperties \n     */\n    private void setSecurityProps()\n    {\n        if (connectionProperties.containsKey(KVSecurityConstants.TRANSPORT_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.TRANSPORT_PROPERTY,\n                    connectionProperties.get(KVSecurityConstants.TRANSPORT_PROPERTY));\n        }\n\n        if (connectionProperties.containsKey(KVSecurityConstants.SSL_TRUSTSTORE_TYPE_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.SSL_TRUSTSTORE_TYPE_PROPERTY,\n                    connectionProperties.get(KVSecurityConstants.SSL_TRUSTSTORE_TYPE_PROPERTY));\n        }\n        if (connectionProperties.containsKey(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY,\n                    connectionProperties.get(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY));\n        }\n        if (connectionProperties.containsKey(KVSecurityConstants.SSL_PROTOCOLS_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.SSL_PROTOCOLS_PROPERTY,\n                    connectionProperties.get(KVSecurityConstants.SSL_PROTOCOLS_PROPERTY));\n        }\n        if (connectionProperties.containsKey(KVSecurityConstants.SSL_HOSTNAME_VERIFIER_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.SSL_HOSTNAME_VERIFIER_PROPERTY,\n                    connectionProperties.get(KVSecurityConstants.SSL_HOSTNAME_VERIFIER_PROPERTY));\n        }\n        if (connectionProperties.containsKey(KVSecurityConstants.SSL_CIPHER_SUITES_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.SSL_CIPHER_SUITES_PROPERTY,\n                    connectionProperties.get(KVSecurityConstants.SSL_CIPHER_SUITES_PROPERTY));\n        }\n        if (connectionProperties.containsKey(KVSecurityConstants.SECURITY_FILE_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.SECURITY_FILE_PROPERTY,\n                    connectionProperties.get(KVSecurityConstants.SECURITY_FILE_PROPERTY));\n        }\n\n        if (connectionProperties.containsKey(KVSecurityConstants.AUTH_WALLET_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.AUTH_WALLET_PROPERTY,\n                    connectionProperties.get(KVSecurityConstants.AUTH_WALLET_PROPERTY));\n        }\n        if (connectionProperties.containsKey(KVSecurityConstants.AUTH_USERNAME_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.AUTH_USERNAME_PROPERTY,\n                    connectionProperties.get(KVSecurityConstants.AUTH_USERNAME_PROPERTY));\n        }\n        if (connectionProperties.containsKey(KVSecurityConstants.AUTH_PWDFILE_PROPERTY))\n        {\n            securityProps.put(KVSecurityConstants.AUTH_PWDFILE_PROPERTY,\n                    connectionProperties.get(KVSecurityConstants.AUTH_PWDFILE_PROPERTY));\n        }\n        \n        \n    }\n\n    /**\n     * \n     * @return Host array\n     */\n    public List<Host> getOracleNoSQLHosts()\n    {\n        return hostsList;\n    }\n    \n    /**\n     * @return the secProps\n     */\n    public Properties getSecurityProps()\n    {\n        return securityProps;\n    }\n\n    /**\n     * \n     * @param host\n     * @param port\n     * @return CassandraHosts\n     */\n    public OracleNoSQLHost getOracleNoSQLHost(String host, int port)\n    {\n        for (Host oraclenoSqlHost : hostsList)\n        {\n            if (((OracleNoSQLHost) oraclenoSqlHost).equals(new OracleNoSQLHost(host, port)))\n            {\n                return (OracleNoSQLHost) oraclenoSqlHost;\n            }\n        }\n        return null;\n    }\n}"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/OracleEntityTransactionTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql;\n\nimport java.io.IOException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport javax.servlet.UnavailableException;\nimport javax.xml.registry.InvalidRequestException;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.entities.PersonKVStore;\n\n/**\n * The Class EntityTransactionTest.\n * \n * @author vivek.mishra\n */\npublic class OracleEntityTransactionTest\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"twikvstore\");\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * On rollback.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onRollback() throws IOException\n    {\n\n        em.getTransaction().begin();\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        // roll back.\n        em.getTransaction().rollback();\n\n        em.getTransaction().begin();\n\n        PersonKVStore p = findById(PersonKVStore.class, \"1\", em);\n        Assert.assertNull(p);\n\n        // on commit.\n        em.getTransaction().commit();\n\n        // Still no record should be flushed as already rollback!\n        p = findById(PersonKVStore.class, \"1\", em);\n        Assert.assertNull(p);\n    }\n\n    /**\n     * On commit.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onCommit() throws IOException\n    {\n\n        em.getTransaction().begin();\n\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        // on commit.\n        em.getTransaction().commit();\n\n        PersonKVStore p = findById(PersonKVStore.class, \"1\", em);\n        Assert.assertNotNull(p);\n\n        em.getTransaction().begin();\n\n        ((PersonKVStore) p2).setPersonName(\"rollback\");\n        em.merge(p2);\n\n        // roll back, should roll back person name for p2!\n        em.getTransaction().rollback();\n\n        p = findById(PersonKVStore.class, \"1\", em);\n        Assert.assertNotNull(p);\n\n        p = findById(PersonKVStore.class, \"2\", em);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertNotSame(\"rollback\", p.getPersonName());\n\n    }\n\n    /**\n     * Rollback on error.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void rollbackOnError() throws IOException\n    {\n        PersonKVStore p = null;\n        try\n        {\n            Object p1 = prepareData(\"1\", 10);\n            Object p2 = prepareData(\"2\", 20);\n            em.persist(p1);\n            em.persist(p2);\n\n            p = findById(PersonKVStore.class, \"1\", em);\n            Assert.assertNotNull(p);\n\n            Object p3 = prepareData(\"3\", 15);\n            em.persist(p3);\n\n            // Assert on rollback on error.\n            ((PersonKVStore) p2).setPersonName(\"rollback\");\n            em.merge(p2);\n            em.merge(null);\n\n            // As this is a runtime exception so rollback should happen and\n            // delete out commited data.\n        }\n        catch (Exception ex)\n        {\n\n            p = findById(PersonKVStore.class, \"1\", em);\n            Assert.assertNull(p);\n\n            p = findById(PersonKVStore.class, \"2\", em);\n            Assert.assertNull(p);\n\n            p = findById(PersonKVStore.class, \"3\", em);\n            Assert.assertNull(p);\n        }\n        em.clear();\n        // persist with 1 em\n        EntityManager em1 = emf.createEntityManager();\n        // em1.setFlushMode(FlushModeType.COMMIT);\n        em1.getTransaction().begin();\n        Object p3 = prepareData(\"4\", 15);\n        em1.persist(p3);\n        em1.getTransaction().commit();\n\n        try\n        {\n            // remove with another em with auto flush.\n            EntityManager em2 = emf.createEntityManager();\n            PersonKVStore person = em2.find(PersonKVStore.class, \"4\");\n            em2.remove(person);\n            em2.merge(null);\n        }\n        catch (Exception ex)\n        {\n            // Deleted records cannot be rolled back in cassandra!\n            // em1.clear();\n\n            p = findById(PersonKVStore.class, \"4\", em1);\n            Assert.assertNotNull(p);\n            Assert.assertEquals(\"vivek\", p.getPersonName());\n\n        }\n    }\n\n    /**\n     * Roll back with multi transactions.\n     */\n    @Test\n    public void rollBackWithMultiTransactions()\n    {\n        EntityManager em1 = emf.createEntityManager();\n        // em1.setFlushMode(FlushModeType.COMMIT);\n\n        // Begin transaction.\n        em1.getTransaction().begin();\n        Object p1 = prepareData(\"11\", 10);\n        em1.persist(p1);\n\n        // commit p1.\n        em1.getTransaction().commit();\n\n        // another em instance\n        EntityManager em2 = emf.createEntityManager();\n        // em2.setFlushMode(FlushModeType.COMMIT);\n\n        // begin transaction.\n        em2.getTransaction().begin();\n        PersonKVStore found = em2.find(PersonKVStore.class, \"11\");\n        found.setPersonName(\"merged\");\n        em2.merge(found);\n\n        // commit p1 after modification.\n        em2.getTransaction().commit();\n\n        // open another entity manager.\n        EntityManager em3 = emf.createEntityManager();\n        found = em3.find(PersonKVStore.class, \"11\");\n        found.setPersonName(\"lastemerge\");\n        try\n        {\n            em3.merge(found);\n            em3.merge(null);\n        }\n        catch (Exception ex)\n        {\n            PersonKVStore finalFound = em2.find(PersonKVStore.class, \"11\");\n            Assert.assertNotNull(finalFound);\n            Assert.assertEquals(\"merged\", finalFound.getPersonName());\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        // Delete by query.\n        String deleteQuery = \"Delete from PersonKVStore p\";\n        Query query = em.createQuery(deleteQuery);\n        int updateCount = query.executeUpdate();\n        em.close();\n        emf.close();\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param rowKey\n     *            the row key\n     * @param age\n     *            the age\n     * @return the person\n     */\n    private PersonKVStore prepareData(String rowKey, int age)\n    {\n        PersonKVStore o = new PersonKVStore();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age);\n        return o;\n    }\n\n    /**\n     * Find by id.\n     * \n     * @param <E>\n     *            the element type\n     * @param clazz\n     *            the clazz\n     * @param rowKey\n     *            the row key\n     * @param em\n     *            the em\n     * @return the e\n     */\n    private <E extends Object> E findById(Class<E> clazz, Object rowKey, EntityManager em)\n    {\n        return em.find(clazz, rowKey);\n    }\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/OracleNoSQLAssociationTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql;\n\nimport static org.junit.Assert.assertNotNull;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.entities.AddressOTOOracleNoSQL;\nimport com.impetus.client.oraclenosql.entities.PersonOTOOracleNoSQL;\n\n/**\n * Test case for association between two entities in OracleNoSQL\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLAssociationTest\n{\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"twikvstore\");\n        em = emf.createEntityManager();\n    }\n\n    @After\n    public void tearDown()\n    {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void executeTest()\n    {\n        // Insert records\n        persistPerson(\"1\", \"person1\", 10, new AddressOTOOracleNoSQL(1.1, \"Address 1\"));\n        persistPerson(\"2\", \"person2\", 20, new AddressOTOOracleNoSQL(2.2, \"Address 2\"));\n        persistPerson(\"3\", \"person3\", 30, new AddressOTOOracleNoSQL(3.3, \"Address 3\"));\n        persistPerson(\"4\", \"person4\", 40, new AddressOTOOracleNoSQL(4.4, \"Address 4\"));\n\n        // Find Records\n        em.clear();\n        PersonOTOOracleNoSQL p11 = findById(\"1\");\n        Assert.assertNotNull(p11);\n        Assert.assertEquals(\"person1\", p11.getPersonName());\n        Assert.assertEquals(new Integer(10), p11.getAge());\n        Assert.assertNotNull(p11.getAddress());\n        Assert.assertEquals(new Double(1.1), p11.getAddress().getAddressId());\n        Assert.assertEquals(\"Address 1\", p11.getAddress().getStreet());\n\n        PersonOTOOracleNoSQL p22 = findById(\"2\");\n        Assert.assertNotNull(p22);\n        Assert.assertEquals(\"person2\", p22.getPersonName());\n        Assert.assertEquals(new Integer(20), p22.getAge());\n        Assert.assertNotNull(p22.getAddress());\n        Assert.assertEquals(new Double(2.2), p22.getAddress().getAddressId());\n        Assert.assertEquals(\"Address 2\", p22.getAddress().getStreet());\n\n        PersonOTOOracleNoSQL p33 = findById(\"3\");\n        Assert.assertNotNull(p33);\n        Assert.assertEquals(\"person3\", p33.getPersonName());\n        Assert.assertEquals(new Integer(30), p33.getAge());\n        Assert.assertNotNull(p33.getAddress());\n        Assert.assertEquals(new Double(3.3), p33.getAddress().getAddressId());\n        Assert.assertEquals(\"Address 3\", p33.getAddress().getStreet());\n\n        PersonOTOOracleNoSQL p44 = findById(\"4\");\n        assertNotNull(p44);\n        Assert.assertEquals(\"person4\", p44.getPersonName());\n        Assert.assertEquals(new Integer(40), p44.getAge());\n        Assert.assertNotNull(p44.getAddress());\n        Assert.assertEquals(new Double(4.4), p44.getAddress().getAddressId());\n        Assert.assertEquals(\"Address 4\", p44.getAddress().getStreet());\n\n        PersonOTOOracleNoSQL p55 = findById(\"5\"); // Invalid records\n        Assert.assertNull(p55);\n\n        // Update records\n        p11.setPersonName(\"person11\");\n        p11.setAge(100);\n        p11.getAddress().setStreet(\"Address 11\");\n        updatePerson(p11);\n        p22.setPersonName(\"person22\");\n        p22.setAge(200);\n        p22.getAddress().setStreet(\"Address 22\");\n        updatePerson(p22);\n        p33.setPersonName(\"person33\");\n        p33.setAge(300);\n        p33.getAddress().setStreet(\"Address 33\");\n        updatePerson(p33);\n        p44.setPersonName(\"person44\");\n        p44.setAge(400);\n        p44.getAddress().setStreet(\"Address 44\");\n        updatePerson(p44);\n        em.clear();\n        p11 = findById(\"1\");\n        Assert.assertNotNull(p11);\n        Assert.assertEquals(\"person11\", p11.getPersonName());\n        Assert.assertEquals(new Integer(100), p11.getAge());\n        Assert.assertEquals(\"Address 11\", p11.getAddress().getStreet());\n\n        p22 = findById(\"2\");\n        assertNotNull(p22);\n        Assert.assertEquals(\"person22\", p22.getPersonName());\n        Assert.assertEquals(new Integer(200), p22.getAge());\n        Assert.assertEquals(\"Address 22\", p22.getAddress().getStreet());\n\n        p33 = findById(\"3\");\n        assertNotNull(p33);\n        Assert.assertEquals(\"person33\", p33.getPersonName());\n        Assert.assertEquals(new Integer(300), p33.getAge());\n        Assert.assertEquals(\"Address 33\", p33.getAddress().getStreet());\n\n        p44 = findById(\"4\");\n        Assert.assertNotNull(p44);\n        Assert.assertEquals(\"person44\", p44.getPersonName());\n        Assert.assertEquals(new Integer(400), p44.getAge());\n        Assert.assertEquals(\"Address 44\", p44.getAddress().getStreet());\n\n        // Delete Records\n        deletePerson(p11);\n        deletePerson(p22);\n        deletePerson(p33);\n        deletePerson(p44);\n\n        em.clear();\n        Assert.assertNull(findById(\"1\"));\n        Assert.assertNull(findById(\"2\"));\n        Assert.assertNull(findById(\"3\"));\n        Assert.assertNull(findById(\"4\"));\n\n    }\n\n    protected void persistPerson(String personId, String personName, int age, AddressOTOOracleNoSQL address)\n    {\n        Object p = preparePerson(personId, age, personName, address);\n        em.persist(p);\n    }\n\n    protected PersonOTOOracleNoSQL findById(Object personId)\n    {\n        return em.find(PersonOTOOracleNoSQL.class, personId);\n    }\n\n    protected void updatePerson(PersonOTOOracleNoSQL person)\n    {\n        em.merge(person);\n    }\n\n    protected void deletePerson(PersonOTOOracleNoSQL person)\n    {\n        em.remove(person);\n    }\n\n    protected PersonOTOOracleNoSQL preparePerson(String rowKey, int age, String name, AddressOTOOracleNoSQL address)\n    {\n        PersonOTOOracleNoSQL person = new PersonOTOOracleNoSQL();\n        person.setPersonId(rowKey);\n        person.setPersonName(name);\n        person.setAge(age);\n        person.setAddress(address);\n        return person;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/OracleNoSQLClientFactoryTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql;\n\nimport java.lang.reflect.Field;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.ClientResolver;\nimport com.impetus.kundera.loader.ClientFactory;\n\n/**\n * Test case for {@link OracleNoSQLClientFactory_legacy}\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLClientFactoryTest\n{\n    /** The Constant REDIS_PU. */\n    private static final String PU = \"twikvstore\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(OracleNoSQLClientFactoryTest.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.client.oraclenosql.OracleNoSQLClientFactory_legacy#createPoolOrConnection()}\n     * .\n     */\n    @Test\n    public void testConnection()\n    {\n        logger.info(\"On test connection\");\n\n        ClientFactory clientFactory = ClientResolver.getClientFactory(PU);\n        Assert.assertNotNull(clientFactory);\n        Assert.assertEquals(OracleNoSQLClientFactory.class, clientFactory.getClass());\n        Field connectionField;\n        try\n        {\n            String field_name = \"connectionPoolOrConnection\";\n            connectionField = ((OracleNoSQLClientFactory) clientFactory).getClass().getSuperclass()\n                    .getDeclaredField(field_name);\n\n            if (!connectionField.isAccessible())\n            {\n                connectionField.setAccessible(true);\n            }\n\n            Object connectionObj = connectionField.get(clientFactory);\n\n            Assert.assertNotNull(connectionObj);\n\n        }\n        catch (SecurityException e)\n        {\n            logger.error(e.getMessage());\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            logger.error(e.getMessage());\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalArgumentException e)\n        {\n            logger.error(e.getMessage());\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            logger.error(e.getMessage());\n            Assert.fail(e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/OracleNoSQLClientTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.oraclenosql.entities.PersonOTOOracleNoSQL;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData.OPERATION;\n\nimport oracle.kv.KVStore;\nimport oracle.kv.KVStoreConfig;\nimport oracle.kv.KVStoreFactory;\nimport oracle.kv.table.TableAPI;\n\n/**\n * Test case for {@link OracleNoSQLClient_Leagacy}\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLClientTest\n{\n\n    /** The Constant REDIS_PU. */\n    private static final String PU = \"twikvstore\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(OracleNoSQLClient.class);\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        createJoinTableInDatabase();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n    }\n\n    @Test\n    public void testPersistJoinTableData()\n    {\n\n        final String schemaName = \"KunderaTests\";\n        final String tableName = \"PERSON_ADDRESS\";\n        final String joinColumn = \"PERSON_ID\";\n        final String inverseJoinColumn = \"ADDRESS_ID\";\n\n        JoinTableData joinTableData = new JoinTableData(OPERATION.INSERT, schemaName, tableName, joinColumn,\n                inverseJoinColumn, PersonOTOOracleNoSQL.class);\n\n        String joinKey1 = \"JK1\";\n        Integer joinKey2 = new Integer(2);\n\n        Integer inverseJoinKey1 = new Integer(1);\n        Double inverseJoinKey2 = new Double(2.2);\n        String inverseJoinKey3 = \"IJK3\";\n\n        Set inverseJoinKeysFor1 = new HashSet();\n        inverseJoinKeysFor1.add(inverseJoinKey1);\n        inverseJoinKeysFor1.add(inverseJoinKey2);\n\n        Set inverseJoinKeysFor2 = new HashSet();\n        inverseJoinKeysFor2.add(inverseJoinKey2);\n        inverseJoinKeysFor2.add(inverseJoinKey3);\n\n        joinTableData.addJoinTableRecord(joinKey1, inverseJoinKeysFor1);\n        joinTableData.addJoinTableRecord(joinKey2, inverseJoinKeysFor2);\n\n        EntityManager em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        OracleNoSQLClient client = (OracleNoSQLClient) clients.get(PU);\n        client.persistJoinTable(joinTableData);\n\n        List<String> columns = client.getColumnsById(schemaName, tableName, joinColumn, inverseJoinColumn, joinKey1,\n                String.class);\n\n        Assert.assertNotNull(columns);\n        Assert.assertEquals(true, !columns.isEmpty());\n        Assert.assertEquals(2, columns.size());\n        Assert.assertEquals(true, columns.contains(inverseJoinKey1.toString()));\n        Assert.assertEquals(true, columns.contains(inverseJoinKey2.toString()));\n\n        Object[] ids = client.findIdsByColumn(schemaName, tableName, joinColumn, inverseJoinColumn, inverseJoinKey2,\n                PersonOTOOracleNoSQL.class);\n        Assert.assertNotNull(ids);\n        Assert.assertTrue(ids.length == 2);\n\n        client.deleteByColumn(schemaName, tableName, inverseJoinColumn, inverseJoinKey1);\n        client.deleteByColumn(schemaName, tableName, inverseJoinColumn, inverseJoinKey2);\n\n        columns = client.getColumnsById(schemaName, tableName, joinColumn, inverseJoinColumn, joinKey1, String.class);\n\n        Assert.assertTrue(columns.isEmpty());\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        dropJoinTableInDatabase();\n    }\n\n    private static void createJoinTableInDatabase()\n    {\n        KVStore kvStore = KVStoreFactory.getStore(new KVStoreConfig(\"OracleNoSqlTests\", \"localhost:5000\"));\n        TableAPI tableAPI = kvStore.getTableAPI();\n        tableAPI.executeSync(\n                \"CREATE TABLE PERSON_ADDRESS (key STRING, PERSON_ID STRING,ADDRESS_ID STRING,PRIMARY KEY (key))\");\n        tableAPI.executeSync(\"CREATE INDEX IF NOT EXISTS PERSON_ID ON PERSON_ADDRESS(PERSON_ID)\");\n        tableAPI.executeSync(\"CREATE INDEX IF NOT EXISTS ADDRESS_ID ON PERSON_ADDRESS(ADDRESS_ID)\");\n        kvStore.close();\n\n    }\n\n    private static void dropJoinTableInDatabase()\n    {\n        KVStore kvStore = KVStoreFactory.getStore(new KVStoreConfig(\"OracleNoSqlTests\", \"localhost:5000\"));\n        TableAPI tableAPI = kvStore.getTableAPI();\n        tableAPI.executeSync(\" DROP TABLE IF EXISTS PERSON_ADDRESS\");\n        tableAPI.executeSync(\"DROP INDEX IF EXISTS PERSON_ID ON PERSON_ADDRESS\");\n        tableAPI.executeSync(\"DROP INDEX IF EXISTS ADDRESS_ID ON PERSON_ADDRESS\");\n        kvStore.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/OracleNoSQLEmbeddableTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.entities.Office;\nimport com.impetus.client.oraclenosql.entities.PersonEmbeddedKVStore;\n\n/**\n * Test case for CRUD and query operations on an entity that contains one\n * embeddable attribute\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLEmbeddableTest extends OracleNoSQLTestBase\n{\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown()\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void executeCRUDTest()\n    {\n\n        // Insert records\n        persistPerson(\"1\", \"person1\", 10, new Office(1, \"Company1\", \"Location 1\"));\n        persistPerson(\"2\", \"person2\", 20, new Office(2, \"Company2\", \"Location 2\"));\n        persistPerson(\"3\", \"person3\", 30, new Office(3, \"Company3\", \"Location 3\"));\n        persistPerson(\"4\", \"person4\", 40, new Office(4, \"Company4\", \"Location 4\"));\n\n        // Find Records\n        clearEm();\n        PersonEmbeddedKVStore p11 = findById(\"1\");\n        assertNotNull(p11);\n        assertEquals(\"person1\", p11.getPersonName());\n        assertEquals(10, p11.getAge());\n        Assert.assertNotNull(p11.getOffice());\n        Assert.assertEquals(1, p11.getOffice().getOfficeId());\n        Assert.assertEquals(\"Company1\", p11.getOffice().getCompanyName());\n        Assert.assertEquals(\"Location 1\", p11.getOffice().getLocation());\n\n        PersonEmbeddedKVStore p22 = findById(\"2\");\n        assertNotNull(p22);\n        assertEquals(\"person2\", p22.getPersonName());\n        assertEquals(20, p22.getAge());\n        Assert.assertNotNull(p22.getOffice());\n        Assert.assertEquals(2, p22.getOffice().getOfficeId());\n        Assert.assertEquals(\"Company2\", p22.getOffice().getCompanyName());\n        Assert.assertEquals(\"Location 2\", p22.getOffice().getLocation());\n\n        PersonEmbeddedKVStore p33 = findById(\"3\");\n        assertNotNull(p33);\n        assertEquals(\"person3\", p33.getPersonName());\n        assertEquals(30, p33.getAge());\n        Assert.assertNotNull(p33.getOffice());\n        Assert.assertEquals(3, p33.getOffice().getOfficeId());\n        Assert.assertEquals(\"Company3\", p33.getOffice().getCompanyName());\n        Assert.assertEquals(\"Location 3\", p33.getOffice().getLocation());\n\n        PersonEmbeddedKVStore p44 = findById(\"4\");\n        assertNotNull(p44);\n        assertEquals(\"person4\", p44.getPersonName());\n        assertEquals(40, p44.getAge());\n        Assert.assertNotNull(p44.getOffice());\n        Assert.assertEquals(4, p44.getOffice().getOfficeId());\n        Assert.assertEquals(\"Company4\", p44.getOffice().getCompanyName());\n        Assert.assertEquals(\"Location 4\", p44.getOffice().getLocation());\n\n        PersonEmbeddedKVStore p55 = findById(\"5\"); // Invalid records\n        Assert.assertNull(p55);\n\n        // Update records\n        p11.setPersonName(\"person11\");\n        p11.setAge(100);\n        p11.getOffice().setCompanyName(\"Company11\");\n        updatePerson(p11);\n        p22.setPersonName(\"person22\");\n        p22.setAge(200);\n        p22.getOffice().setCompanyName(\"Company22\");\n        updatePerson(p22);\n        p33.setPersonName(\"person33\");\n        p33.setAge(300);\n        p33.getOffice().setCompanyName(\"Company33\");\n        updatePerson(p33);\n        p44.setPersonName(\"person44\");\n        p44.setAge(400);\n        p44.getOffice().setCompanyName(\"Company44\");\n        updatePerson(p44);\n        clearEm();\n        p11 = findById(\"1\");\n        assertNotNull(p11);\n        assertEquals(\"person11\", p11.getPersonName());\n        assertEquals(100, p11.getAge());\n        Assert.assertEquals(\"Company11\", p11.getOffice().getCompanyName());\n\n        p22 = findById(\"2\");\n        assertNotNull(p22);\n        assertEquals(\"person22\", p22.getPersonName());\n        assertEquals(200, p22.getAge());\n        Assert.assertEquals(\"Company22\", p22.getOffice().getCompanyName());\n\n        p33 = findById(\"3\");\n        assertNotNull(p33);\n        assertEquals(\"person33\", p33.getPersonName());\n        assertEquals(300, p33.getAge());\n        Assert.assertEquals(\"Company33\", p33.getOffice().getCompanyName());\n\n        p44 = findById(\"4\");\n        assertNotNull(p44);\n        assertEquals(\"person44\", p44.getPersonName());\n        assertEquals(400, p44.getAge());\n        Assert.assertEquals(\"Company44\", p44.getOffice().getCompanyName());\n\n        // Delete Records\n        deletePerson(p11);\n        deletePerson(p22);\n        deletePerson(p33);\n        deletePerson(p44);\n\n        clearEm();\n        Assert.assertNull(findById(\"1\"));\n        Assert.assertNull(findById(\"2\"));\n        Assert.assertNull(findById(\"3\"));\n        Assert.assertNull(findById(\"4\"));\n\n    }\n\n    @Test\n    public void executeJPAQueriesTest()\n    {\n        // Insert records\n        persistPerson(\"1\", \"person1\", 10, new Office(1, \"Company1\", \"Location 1\"));\n        persistPerson(\"2\", \"person2\", 20, new Office(2, \"Company2\", \"Location 2\"));\n        persistPerson(\"3\", \"person3\", 30, new Office(3, \"Company3\", \"Location 3\"));\n        persistPerson(\"4\", \"person4\", 40, new Office(4, \"Company4\", \"Location 4\"));\n\n        // Select query, without where clause\n        clearEm();\n        String findWithOutWhereClause = \"Select p from PersonEmbeddedKVStore p\";\n        List<PersonEmbeddedKVStore> results = executeSelectQuery(findWithOutWhereClause);\n        Assert.assertEquals(4, results.size());\n\n        // Select query with where clause on single non-ID column\n        clearEm();\n        String findByName = \"Select p from PersonEmbeddedKVStore p where p.personName=:personName\";\n        Map<Object, Object> params = new HashMap<Object, Object>();\n        params.put(\"personName\", \"person1\");\n        results = executeSelectQuery(findByName, params);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"1\", results.get(0).getPersonId());\n        Assert.assertEquals(\"person1\", results.get(0).getPersonName());\n        Assert.assertEquals(10, results.get(0).getAge());\n\n        clearEm();\n        // Select query with where clause on ID column\n        String findById = \"Select p from PersonEmbeddedKVStore p where p.personId=:personId\";\n        params = new HashMap<Object, Object>();\n        params.put(\"personId\", \"2\");\n        results = executeSelectQuery(findById, params);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"2\", results.get(0).getPersonId());\n        Assert.assertEquals(\"person2\", results.get(0).getPersonName());\n        Assert.assertEquals(20, results.get(0).getAge());\n\n        clearEm();\n        // Select query with where clause on ID column and non-ID column with\n        // AND operator\n        String findByIdAndAge = \"Select p from PersonEmbeddedKVStore p where p.personId=:personId AND p.age=:age\";\n        params = new HashMap<Object, Object>();\n        params.put(\"personId\", \"3\");\n        params.put(\"age\", 30);\n        results = executeSelectQuery(findByIdAndAge, params);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"3\", results.get(0).getPersonId());\n        Assert.assertEquals(\"person3\", results.get(0).getPersonName());\n        Assert.assertEquals(30, results.get(0).getAge());\n\n        clearEm();\n        // Select query with where clause on ID column and non-ID column with\n        // AND operator (no record)\n        params = new HashMap<Object, Object>();\n        params.put(\"personId\", \"1\");\n        params.put(\"age\", 30);\n        results = executeSelectQuery(findByIdAndAge, params);\n        Assert.assertEquals(0, results.size());\n\n        // OR queries and numeric searches are not supported for Lucene as of\n        // now, and hence are not to be\n        // tested in that case\n        if (!isLuceneIndexingEnabled())\n        {\n\n            clearEm();\n            // Select query with where clause on ID column and non-ID column\n            // with OR\n            // operator\n/*            findByIdAndAge = \"Select p from PersonEmbeddedKVStore p where p.personId=:personId OR p.age=:age\";\n            params = new HashMap<Object, Object>();\n            params.put(\"personId\", \"1\");\n            params.put(\"age\", 30);\n            results = executeSelectQuery(findByIdAndAge, params);\n            Assert.assertEquals(2, results.size());\n\n            clearEm();\n            // Select query with where clause on ID column and non-ID column\n            // (greater than operator) with OR operator\n            findByIdAndAge = \"Select p from PersonEmbeddedKVStore p where p.personId=:personId OR p.age >:age\";\n            params = new HashMap<Object, Object>();\n            params.put(\"personId\", \"1\");\n            params.put(\"age\", 20);\n            results = executeSelectQuery(findByIdAndAge, params);\n            Assert.assertEquals(3, results.size());\n\n            clearEm();\n            // Select query with where clause on non-ID column (with comparison)\n            // with AND operator\n            findByIdAndAge = \"Select p from PersonEmbeddedKVStore p where p.age>=:min AND p.age<=:max\";\n            params = new HashMap<Object, Object>();\n            params.put(\"min\", 20);\n            params.put(\"max\", 30);\n            results = executeSelectQuery(findByIdAndAge, params);\n            Assert.assertEquals(2, results.size());\n\n            clearEm();\n            // Select query with where clause on non-ID column (with comparison)\n            // with AND operator\n            findByIdAndAge = \"Select p from PersonEmbeddedKVStore p where p.age<=:start AND p.age>:end\";\n            params = new HashMap<Object, Object>();\n            params.put(\"start\", 40);\n            params.put(\"end\", 15);\n            results = executeSelectQuery(findByIdAndAge, params);\n            Assert.assertEquals(3, results.size());\n\n            clearEm();\n            // Select query with where clause on non-ID column (with comparison)\n            // with OR operator\n            findByIdAndAge = \"Select p from PersonEmbeddedKVStore p where p.age>:min OR p.age<=:max\";\n            params = new HashMap<Object, Object>();\n            params.put(\"min\", 30);\n            params.put(\"max\", 20);\n            results = executeSelectQuery(findByIdAndAge, params);\n            Assert.assertEquals(3, results.size());\n\n            clearEm();\n            // Select query with where clause on non-ID column (with comparison)\n            // with OR operator\n            String findAgeByBetween = \"Select p from PersonEmbeddedKVStore p where p.age between :min AND :max\";\n            params = new HashMap<Object, Object>();\n            params.put(\"min\", 20);\n            params.put(\"max\", 40);\n            results = executeSelectQuery(findAgeByBetween, params);\n            Assert.assertEquals(3, results.size());\n\n            clearEm();\n            // Select query with where clause on non-ID column (with comparison)\n            // with OR operator\n            String findPersonIdBetween = \"Select p from PersonEmbeddedKVStore p where p.personId between :min AND :max\";\n            params = new HashMap<Object, Object>();\n            params.put(\"min\", \"2\");\n            params.put(\"max\", \"4\");\n            results = executeSelectQuery(findPersonIdBetween, params);\n            Assert.assertEquals(3, results.size());\n*/        }\n\n        clearEm();\n        // Search over selective column\n        String findSelective = \"Select p.age from PersonEmbeddedKVStore p\";\n        results = executeSelectQuery(findSelective);\n        Assert.assertEquals(4, results.size());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNotNull(results.get(0).getAge());\n\n        clearEm();\n        // Search over column within embeddable\n        String findByCompanyName = \"Select p from PersonEmbeddedKVStore p where p.office.companyName=:companyName\";\n        params = new HashMap<Object, Object>();\n        params.put(\"companyName\", \"Company3\");\n        results = executeSelectQuery(findByCompanyName, params);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"3\", results.get(0).getPersonId());\n        Assert.assertEquals(\"person3\", results.get(0).getPersonName());\n        Assert.assertEquals(30, results.get(0).getAge());\n        Assert.assertEquals(3, results.get(0).getOffice().getOfficeId());\n        Assert.assertEquals(\"Company3\", results.get(0).getOffice().getCompanyName());\n        Assert.assertEquals(\"Location 3\", results.get(0).getOffice().getLocation());\n\n        // Delete by query.\n        String deleteQuery = \"Delete from PersonEmbeddedKVStore p\";\n        int updateCount = executeDMLQuery(deleteQuery);\n        Assert.assertEquals(4, updateCount);\n\n        clearEm();\n        Assert.assertEquals(null, findById(\"1\"));\n        Assert.assertEquals(null, findById(\"2\"));\n        Assert.assertEquals(null, findById(\"3\"));\n        Assert.assertEquals(null, findById(\"4\"));\n\n    }\n\n    protected void persistPerson(String personId, String personName, int age, Office office)\n    {\n        Object p = preparePerson(personId, age, personName, office);\n        persist(p);\n    }\n\n    protected PersonEmbeddedKVStore preparePerson(String rowKey, int age, String name, Office office)\n    {\n        PersonEmbeddedKVStore person = new PersonEmbeddedKVStore();\n        person.setPersonId(rowKey);\n        person.setPersonName(name);\n        person.setAge(age);\n        person.setOffice(office);\n        return person;\n    }\n\n    protected PersonEmbeddedKVStore findById(Object personId)\n    {\n        return (PersonEmbeddedKVStore) find(PersonEmbeddedKVStore.class, personId);\n    }\n\n    protected void updatePerson(PersonEmbeddedKVStore person)\n    {\n        update(person);\n    }\n\n    protected void deletePerson(PersonEmbeddedKVStore person)\n    {\n        delete(person);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/OracleNoSQLLOBTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql;\n\nimport java.io.File;\nimport java.util.concurrent.TimeUnit;\n\nimport oracle.kv.Consistency;\nimport oracle.kv.Durability;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.entities.UserProfile;\n\n/**\n * Test case for read and write on Large Objects (LOBs)\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLLOBTest extends OracleNoSQLTestBase\n{\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n\n        setEmProperty(\"write.timeout\", 10);\n        setEmProperty(\"durability\", Durability.COMMIT_WRITE_NO_SYNC);\n        setEmProperty(\"time.unit\", TimeUnit.SECONDS);\n        setEmProperty(\"consistency\", Consistency.NONE_REQUIRED);\n    }\n\n    @After\n    public void tearDown()\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void executeLOBTest()\n    {\n        // Save Record\n        File file = new File(\"src/test/resources/nature.jpg\");\n        long fileSize = file.getTotalSpace();\n        UserProfile userProfile = new UserProfile(1, \"Amresh\", file);\n        persist(userProfile);\n\n        // Find Record\n        clearEm();\n        UserProfile up = (UserProfile) find(UserProfile.class, 1);\n        Assert.assertNotNull(up);\n        Assert.assertEquals(1, up.getUserId());\n        Assert.assertEquals(\"Amresh\", up.getUserName());\n        Assert.assertEquals(fileSize, up.getProfilePicture().getTotalSpace());\n\n        // Delete Record\n        clearEm();\n        delete(up);\n        Assert.assertNull(find(UserProfile.class, 1));\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/OracleNoSQLMinorKeyAllDataTypeTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.entities.PersonOracleNoSQLAllDataType;\n\n/**\n * Test case for validating correct persistence for all supported data types\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLMinorKeyAllDataTypeTest\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    Calendar cal1;\n\n    Calendar cal2;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"twikvstore\");\n        em = emf.createEntityManager();\n        cal1 = Calendar.getInstance();\n        cal2 = Calendar.getInstance();\n\n        cal1.setTime(new Date(1344079067777l));\n        cal2.setTime(new Date(1344079068888l));\n    }\n\n    @After\n    public void tearDown()\n    {\n        em.close();\n        emf.close();\n   }\n\n    @Test\n    public void executeTest()\n    {\n        PersonOracleNoSQLAllDataType person1 = buildPerson1();\n        PersonOracleNoSQLAllDataType person2 = buildPerson2();\n\n        // Insert Records\n        persistPerson(person1);\n        persistPerson(person2);\n\n        // Find Records\n        em.clear();\n        PersonOracleNoSQLAllDataType p1 = findById(1234567l);\n        PersonOracleNoSQLAllDataType p2 = findById(1234568l);\n        assertPerson1(p1);\n        assertPerson2(p2);\n\n        // Delete records\n        em.remove(p1);\n        em.remove(p2);\n        em.clear();\n        Assert.assertNull(findById(1234567l));\n        Assert.assertNull(findById(1234568l));\n\n    }\n\n    protected void persistPerson(PersonOracleNoSQLAllDataType p)\n    {\n        em.persist(p);\n    }\n\n    protected PersonOracleNoSQLAllDataType findById(Object personId)\n    {\n        return em.find(PersonOracleNoSQLAllDataType.class, personId);\n    }\n\n    protected void updatePerson(PersonOracleNoSQLAllDataType person)\n    {\n        em.merge(person);\n    }\n\n    protected void deletePerson(PersonOracleNoSQLAllDataType person)\n    {\n        em.remove(person);\n    }\n\n    private PersonOracleNoSQLAllDataType buildPerson1()\n    {\n\n        PersonOracleNoSQLAllDataType person = new PersonOracleNoSQLAllDataType(1234567l, \"Labs\", false, 31, 'C',\n                (byte) 8, (short) 5, (float) 10.0, 163.12, new Date(Long.parseLong(\"1344079065781\")), new Date(\n                        Long.parseLong(\"1344079067623\")), new Date(Long.parseLong(\"1344079069105\")), 2, new Long(\n                        3634521523423L), new Double(0.23452342343), new java.sql.Date(new Date(\n                        Long.parseLong(\"1344079061111\")).getTime()), new java.sql.Time(new Date(\n                        Long.parseLong(\"1344079062222\")).getTime()), new java.sql.Timestamp(new Date(\n                        Long.parseLong(\"13440790653333\")).getTime()), new BigInteger(\"123456789\"), new BigDecimal(\n                        123456789), cal1);\n        return person;\n    }\n\n    private void assertPerson1(PersonOracleNoSQLAllDataType p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1234567l, p.getPersonId());\n        Assert.assertEquals(\"Labs\", p.getPersonName());\n        Assert.assertEquals(false, p.isExceptional());\n        Assert.assertEquals(31, p.getAge());\n        Assert.assertEquals('C', p.getGrade());\n        Assert.assertEquals((byte) 8, p.getDigitalSignature());\n        Assert.assertEquals((short) 5, p.getRating());\n        Assert.assertEquals((float) 10.0, p.getCompliance(), 0.0);\n        Assert.assertEquals(163.12, p.getHeight(), 0.0);\n        Assert.assertEquals(new Date(Long.parseLong(\"1344079065781\")), p.getEnrolmentDate());\n        Assert.assertEquals(new Date(Long.parseLong(\"1344079067623\")), p.getEnrolmentTime());\n        Assert.assertEquals(new Date(Long.parseLong(\"1344079069105\")), p.getJoiningDateAndTime());\n        Assert.assertEquals(new Integer(2), p.getYearsSpent());\n        Assert.assertEquals(new Long(3634521523423L), p.getUniqueId());\n        Assert.assertEquals(new Double(0.23452342343), p.getMonthlySalary());\n        Assert.assertEquals(new java.sql.Date(new Date(Long.parseLong(\"1344079061111\")).getTime()), p.getBirthday());\n        Assert.assertEquals(new java.util.Date(new Date(Long.parseLong(\"1344079062222\")).getTime()), p.getBirthtime());\n        Assert.assertEquals(new java.util.Date(new Date(Long.parseLong(\"13440790653333\")).getTime()),\n                p.getAnniversary());\n        Assert.assertEquals(new BigInteger(\"123456789\"), p.getJobAttempts());\n        Assert.assertEquals(new BigDecimal(123456789), p.getAccumulatedWealth());\n        Assert.assertEquals(cal1, p.getGraduationDay());\n    }\n\n    private PersonOracleNoSQLAllDataType buildPerson2()\n    {\n\n        PersonOracleNoSQLAllDataType person = new PersonOracleNoSQLAllDataType(1234568l, \"ODC\", true, 32, 'A',\n                (byte) 10, (short) 8, (float) 9.80, 323.3, new Date(Long.parseLong(\"1344079063412\")), new Date(\n                        Long.parseLong(\"1344079068266\")), new Date(Long.parseLong(\"1344079061078\")), 5, new Long(\n                        25423452343L), new Double(0.76452343), new java.sql.Date(new Date(\n                        Long.parseLong(\"1344079064444\")).getTime()), new java.sql.Time(new Date(\n                        Long.parseLong(\"1344079065555\")).getTime()), new java.sql.Timestamp(new Date(\n                        Long.parseLong(\"1344079066666\")).getTime()), new BigInteger(\"123456790\"), new BigDecimal(\n                        123456790), cal2);\n        return person;\n    }\n\n    private void assertPerson2(PersonOracleNoSQLAllDataType p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1234568l, p.getPersonId());\n        Assert.assertEquals(\"ODC\", p.getPersonName());\n        Assert.assertEquals(true, p.isExceptional());\n        Assert.assertEquals(32, p.getAge());\n        Assert.assertEquals('A', p.getGrade());\n        Assert.assertEquals((byte) 10, p.getDigitalSignature());\n        Assert.assertEquals((short) 8, p.getRating());\n        Assert.assertEquals((float) 9.80, p.getCompliance(), 0.0);\n        Assert.assertEquals(323.3, p.getHeight(), 0.0);\n        Assert.assertEquals(new Date(Long.parseLong(\"1344079063412\")), p.getEnrolmentDate());\n        Assert.assertEquals(new Date(Long.parseLong(\"1344079068266\")), p.getEnrolmentTime());\n        Assert.assertEquals(new Date(Long.parseLong(\"1344079061078\")), p.getJoiningDateAndTime());\n        Assert.assertEquals(new Integer(5), p.getYearsSpent());\n        Assert.assertEquals(new Long(25423452343L), p.getUniqueId());\n        Assert.assertEquals(new Double(0.76452343), p.getMonthlySalary());\n        Assert.assertEquals(new java.util.Date(new Date(Long.parseLong(\"1344079064444\")).getTime()), p.getBirthday());\n        Assert.assertEquals(new java.util.Date(new Date(Long.parseLong(\"1344079065555\")).getTime()), p.getBirthtime());\n        Assert.assertEquals(new java.util.Date(new Date(Long.parseLong(\"1344079066666\")).getTime()),\n                p.getAnniversary());\n        Assert.assertEquals(new BigInteger(\"123456790\"), p.getJobAttempts());\n        Assert.assertEquals(new BigDecimal(123456790), p.getAccumulatedWealth());\n        Assert.assertEquals(cal2, p.getGraduationDay());\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/OracleNoSQLPropertySetterTest.java",
    "content": "package com.impetus.client.oraclenosql;\n\n/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\nimport oracle.kv.Consistency;\nimport oracle.kv.Durability;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\n\n/**\n * Test case for {@link OracleNoSQLClient_Leagacy}\n * \n * @author Chhavi Gangwal\n */\npublic class OracleNoSQLPropertySetterTest\n{\n\n    /** The Constant REDIS_PU. */\n    private static final String PU = \"twikvstore\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    EntityManager em;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(OracleNoSQLClient.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n        em = emf.createEntityManager();\n\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n   }\n\n    @Test\n    public void testProperties()\n    {\n\n        // Get properties from client\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        OracleNoSQLClient client = (OracleNoSQLClient) clients.get(PU);\n\n        // Check default values\n        Durability du = client.getDurability();\n        Consistency consist = client.getConsistency();\n        TimeUnit tu = client.getTimeUnit();\n        Assert.assertNotNull(du);\n        Assert.assertNotNull(consist);\n        Assert.assertNotNull(tu);\n        Assert.assertTrue(du instanceof Durability);\n\n        // Set parameters into EM\n        em.setProperty(\"write.timeout\", 5);\n        em.setProperty(\"durability\", Durability.COMMIT_NO_SYNC);\n        em.setProperty(\"time.unit\", TimeUnit.HOURS);\n        em.setProperty(\"consistency\", Consistency.ABSOLUTE);\n        em.setProperty(PersistenceProperties.KUNDERA_BATCH_SIZE, 5);\n\n        Assert.assertEquals(5, client.getBatchSize());\n        Assert.assertEquals(5, client.getTimeout());\n        Assert.assertEquals(TimeUnit.HOURS, client.getTimeUnit());\n        Assert.assertEquals(Consistency.ABSOLUTE, client.getConsistency());\n        Assert.assertEquals(Durability.COMMIT_NO_SYNC, client.getDurability());\n\n        em.clear();\n\n        // Set parameters into EMas string\n        em.setProperty(\"write.timeout\", \"10\");\n        em.setProperty(PersistenceProperties.KUNDERA_BATCH_SIZE, \"10\");\n        em.setProperty(\"time.unit\", \"\" + TimeUnit.HOURS);\n\n        Assert.assertEquals(10, client.getTimeout());\n        Assert.assertEquals(TimeUnit.HOURS, client.getTimeUnit());\n        Assert.assertEquals(10, client.getBatchSize());\n    }\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/OracleNoSQLSingleEntityTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.entities.PersonKVStore;\n\n/**\n * Test case for CRUD and Queries on a single entity\n * \n * @author amresh.singh\n */\n\npublic class OracleNoSQLSingleEntityTest extends OracleNoSQLTestBase\n{\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown()\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void executeCRUDTest()\n    {\n        // Insert records\n        persistPerson(\"1\", \"person1\", 10);\n        persistPerson(\"2\", \"person2\", 20);\n        persistPerson(\"3\", \"person3\", 30);\n        persistPerson(\"4\", \"person4\", 40);\n\n        // Find Records\n        clearEm();\n        PersonKVStore p11 = findById(\"1\");\n        assertNotNull(p11);\n        assertEquals(\"person1\", p11.getPersonName());\n        assertEquals(10, p11.getAge());\n\n        PersonKVStore p22 = findById(\"2\");\n        assertNotNull(p22);\n        assertEquals(\"person2\", p22.getPersonName());\n        assertEquals(20, p22.getAge());\n\n        PersonKVStore p33 = findById(\"3\");\n        assertNotNull(p33);\n        assertEquals(\"person3\", p33.getPersonName());\n        assertEquals(30, p33.getAge());\n\n        PersonKVStore p44 = findById(\"4\");\n        assertNotNull(p44);\n        assertEquals(\"person4\", p44.getPersonName());\n        assertEquals(40, p44.getAge());\n\n        PersonKVStore p55 = findById(\"5\"); // Invalid records\n        Assert.assertNull(p55);\n\n        // Update records\n        p11.setPersonName(\"person11\");\n        p11.setAge(100);\n        updatePerson(p11);\n        p22.setPersonName(\"person22\");\n        p22.setAge(200);\n        updatePerson(p22);\n        p33.setPersonName(\"person33\");\n        p33.setAge(300);\n        updatePerson(p33);\n        p44.setPersonName(\"person44\");\n        p44.setAge(400);\n        updatePerson(p44);\n        clearEm();\n        p11 = findById(\"1\");\n        assertNotNull(p11);\n        assertEquals(\"person11\", p11.getPersonName());\n        assertEquals(100, p11.getAge());\n\n        p22 = findById(\"2\");\n        assertNotNull(p22);\n        assertEquals(\"person22\", p22.getPersonName());\n        assertEquals(200, p22.getAge());\n\n        p33 = findById(\"3\");\n        assertNotNull(p33);\n        assertEquals(\"person33\", p33.getPersonName());\n        assertEquals(300, p33.getAge());\n\n        p44 = findById(\"4\");\n        assertNotNull(p44);\n        assertEquals(\"person44\", p44.getPersonName());\n        assertEquals(400, p44.getAge());\n\n        // Delete Records\n        deletePerson(p11);\n        deletePerson(p22);\n        deletePerson(p33);\n        deletePerson(p44);\n\n        clearEm();\n        Assert.assertNull(findById(\"1\"));\n        Assert.assertNull(findById(\"2\"));\n        Assert.assertNull(findById(\"3\"));\n        Assert.assertNull(findById(\"4\"));\n\n    }\n\n    @Test\n    public void executeJPAQueriesTest()\n    {\n        // Insert records\n        persistPerson(\"1\", \"person1\", 10);\n        persistPerson(\"2\", \"person2\", 20);\n        persistPerson(\"3\", \"person3\", 30);\n        persistPerson(\"4\", \"person4\", 40);\n\n        clearEm();\n        // Select query, without where clause\n        String findWithOutWhereClause = \"Select p from PersonKVStore p\";\n        List<PersonKVStore> results = executeSelectQuery(findWithOutWhereClause);\n        Assert.assertEquals(4, results.size());\n\n        clearEm();\n        // Select query with where clause on single non-ID column\n        String findByName = \"Select p from PersonKVStore p where p.personName=:personName\";\n        Map<Object, Object> params = new HashMap<Object, Object>();\n        params.put(\"personName\", \"person1\");\n        results = executeSelectQuery(findByName, params);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"1\", results.get(0).getPersonId());\n        Assert.assertEquals(\"person1\", results.get(0).getPersonName());\n        Assert.assertEquals(10, results.get(0).getAge());\n\n        clearEm();\n        // Select query with where clause on ID column\n        String findById = \"Select p from PersonKVStore p where p.personId=:personId\";\n        params = new HashMap<Object, Object>();\n        params.put(\"personId\", \"2\");\n        results = executeSelectQuery(findById, params);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"2\", results.get(0).getPersonId());\n        Assert.assertEquals(\"person2\", results.get(0).getPersonName());\n        Assert.assertEquals(20, results.get(0).getAge());\n\n        clearEm();\n        // Select query with where clause on ID column and non-ID column with\n        // AND operator\n        String findByIdAndAge = \"Select p from PersonKVStore p where p.personId=:personId AND p.age=:age\";\n        params = new HashMap<Object, Object>();\n        params.put(\"personId\", \"3\");\n        params.put(\"age\", 30);\n        results = executeSelectQuery(findByIdAndAge, params);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"3\", results.get(0).getPersonId());\n        Assert.assertEquals(\"person3\", results.get(0).getPersonName());\n        Assert.assertEquals(30, results.get(0).getAge());\n\n        clearEm();\n        // Select query with where clause on ID column and non-ID column with\n        // AND operator (no record)\n        params = new HashMap<Object, Object>();\n        params.put(\"personId\", \"1\");\n        params.put(\"age\", 30);\n        results = executeSelectQuery(findByIdAndAge, params);\n        Assert.assertEquals(0, results.size());\n\n        // OR queries and numeric searches are not supported for Lucene as of\n        // now, and hence are not to be\n        // tested in that case\n        if (!isLuceneIndexingEnabled())\n        {\n            clearEm();\n            \n            // OR, AND WITH LT,GT,LTE AND GTE ARE NOT SUPPORTED.\n            \n            // Select query with where clause on ID column and non-ID column\n            // with OR operator\n/*            findByIdAndAge = \"Select p from PersonKVStore p where p.personId=:personId OR p.age=:age\";\n            params = new HashMap<Object, Object>();\n            params.put(\"personId\", \"1\");\n            params.put(\"age\", 30);\n            results = executeSelectQuery(findByIdAndAge, params);\n            Assert.assertEquals(2, results.size());\n\n            clearEm();\n            // Select query with where clause on ID column and non-ID column\n            // (greater than operator) with OR operator\n            findByIdAndAge = \"Select p from PersonKVStore p where p.personId=:personId OR p.age >:age\";\n            params = new HashMap<Object, Object>();\n            params.put(\"personId\", \"1\");\n            params.put(\"age\", 20);\n            results = executeSelectQuery(findByIdAndAge, params);\n            Assert.assertEquals(3, results.size());\n\n            clearEm();\n            // Select query with where clause on non-ID column (with comparison)\n            // with OR operator\n            String findByAgeOR = \"Select p from PersonKVStore p where p.age>:min OR p.age<=:max\";\n            params = new HashMap<Object, Object>();\n            params.put(\"min\", 30);\n            params.put(\"max\", 20);\n            results = executeSelectQuery(findByAgeOR, params);\n            Assert.assertEquals(3, results.size());\n\n            clearEm();\n*/            // Select query with where clause on non-ID column (with comparison)\n            // with AND operator\n/*            String findByAge = \"Select p from PersonKVStore p where p.age>=:min AND p.age<=:max\";\n            params = new HashMap<Object, Object>();\n            params.put(\"min\", 20);\n            params.put(\"max\", 30);\n            results = executeSelectQuery(findByAge, params);\n            Assert.assertEquals(2, results.size());\n\n            clearEm();\n            // Select query with where clause on non-ID column (with comparison)\n            // with AND operator\n            String findByAgeLTGT = \"Select p from PersonKVStore p where p.age<=:start AND p.age>:end\";\n            params = new HashMap<Object, Object>();\n            params.put(\"start\", 40);\n            params.put(\"end\", 15);\n            results = executeSelectQuery(findByAgeLTGT, params);\n            Assert.assertEquals(3, results.size());\n\n            clearEm();\n            // Select query with where clause on non-ID column (with comparison)\n            // with OR operator\n            String findAgeByBetween = \"Select p from PersonKVStore p where p.age between :min AND :max\";\n            params = new HashMap<Object, Object>();\n            params.put(\"min\", 20);\n            params.put(\"max\", 40);\n            results = executeSelectQuery(findAgeByBetween, params);\n            Assert.assertEquals(3, results.size());\n\n            clearEm();\n            // Select query with where clause on non-ID column (with comparison)\n            // with OR operator\n            String findPersonIdBetween = \"Select p from PersonKVStore p where p.personId between :min AND :max\";\n            params = new HashMap<Object, Object>();\n            params.put(\"min\", \"2\");\n            params.put(\"max\", \"4\");\n            results = executeSelectQuery(findPersonIdBetween, params);\n            Assert.assertEquals(3, results.size());\n*/\n        }\n\n        clearEm();\n        String findSelective = \"Select p.age from PersonKVStore p\";\n        results = executeSelectQuery(findSelective);\n        Assert.assertEquals(4, results.size());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNotNull(results.get(0).getAge());\n\n        // Named Query\n        clearEm();\n        params = new HashMap<Object, Object>();\n        params.put(\"age\", 30);\n        results = executeNamedQuery(\"findByAge\", params);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"3\", results.get(0).getPersonId());\n        Assert.assertEquals(\"person3\", results.get(0).getPersonName());\n        Assert.assertEquals(30, results.get(0).getAge());\n\n        clearEm();\n        params = new HashMap<Object, Object>();\n        params.put(1, \"person3\");\n        results = executeNamedQuery(\"findByName\", params);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"3\", results.get(0).getPersonId());\n        Assert.assertEquals(\"person3\", results.get(0).getPersonName());\n        Assert.assertEquals(30, results.get(0).getAge());\n\n        // Delete by query.\n        String deleteQuery = \"Delete from PersonKVStore p\";\n        int updateCount = executeDMLQuery(deleteQuery);\n        Assert.assertEquals(4, updateCount);\n\n        clearEm();\n        Assert.assertEquals(null, findById(\"1\"));\n        Assert.assertEquals(null, findById(\"2\"));\n        Assert.assertEquals(null, findById(\"3\"));\n        Assert.assertEquals(null, findById(\"4\"));\n    }\n\n    protected void persistPerson(String personId, String personName, int age)\n    {\n        Object p = preparePerson(personId, age, personName);\n        persist(p);\n    }\n\n    protected PersonKVStore preparePerson(String rowKey, int age, String name)\n    {\n        PersonKVStore person = new PersonKVStore();\n        person.setPersonId(rowKey);\n        person.setPersonName(name);\n        person.setAge(age);\n        return person;\n    }\n\n    protected PersonKVStore findById(Object personId)\n    {\n        return (PersonKVStore) find(PersonKVStore.class, personId);\n    }\n\n    protected void updatePerson(PersonKVStore person)\n    {\n        update(person);\n    }\n\n    protected <E extends Object> void assertFindByNameAndAge(EntityManager em, String clazz, E e, String name,\n            String minVal, String fieldName)\n    {\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name + \" and p.AGE = \"\n                + minVal);\n        List<E> results = q.getResultList();\n        assertNotNull(results);\n        assertTrue(!results.isEmpty());\n        assertEquals(1, results.size());\n    }\n\n    protected <E extends Object> void assertFindByName(EntityManager em, String clazz, E e, String name,\n            String fieldName)\n    {\n\n        String query = \"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name;\n        // // find by name.\n        Query q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        assertNotNull(results);\n        assertTrue(!results.isEmpty());\n        assertEquals(2, results.size());\n\n    }\n\n    protected <E extends Object> void assertFindByNameAndAgeGTAndLT(EntityManager em, String clazz, E e, String name,\n            String minVal, String maxVal, String fieldName)\n    {\n        // // // find by name, age clause\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = \" + name + \" and p.AGE > \"\n                + minVal + \" and p.AGE < \" + maxVal);\n        List<E> results = q.getResultList();\n        assertNotNull(results);\n        // assertTrue(!results.isEmpty());\n        assertEquals(2, results.size());\n    }\n\n    protected void deletePerson(PersonKVStore person)\n    {\n        delete(person);\n    }\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/OracleNoSQLTestBase.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.apache.commons.lang.StringUtils;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\n\n\n/**\n * Base class for all test cases\n * \n * @author amresh.singh\n */\npublic class OracleNoSQLTestBase\n{\n\n    private static final String PERSISTENCE_UNIT = \"twikvstore\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    protected void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        em = emf.createEntityManager();\n    }\n\n    protected void tearDown()\n    {\n        em.close();\n        emf.close();\n    }\n\n    protected void clearEm()\n    {\n        em.clear();\n    }\n\n    protected void setEmProperty(String key, Object value)\n    {\n        em.setProperty(key, value);\n    }\n\n    protected void persist(Object entity)\n    {\n        em.persist(entity);\n    }\n\n    protected Object find(Class<?> entityClass, Object id)\n    {\n        return em.find(entityClass, id);\n    }\n\n    protected void update(Object entity)\n    {\n        em.merge(entity);\n    }\n\n    protected void delete(Object entity)\n    {\n        em.remove(entity);\n    }\n\n    protected List executeSelectQuery(String jpaQuery)\n    {\n        Query query = em.createQuery(jpaQuery);\n        return query.getResultList();\n    }\n\n    protected List executeSelectQuery(String jpaQuery, Map<Object, Object> params)\n    {\n        Query query = em.createQuery(jpaQuery);\n        setParams(params, query);\n        return query.getResultList();\n    }\n\n    protected int executeDMLQuery(String jpaQuery)\n    {\n        Query query = em.createQuery(jpaQuery);\n        int updateCount = query.executeUpdate();\n        return updateCount;\n    }\n\n    protected List executeNamedQuery(String namedQuery, Map<Object, Object> params)\n    {\n        Query query = em.createNamedQuery(namedQuery);\n        setParams(params, query);\n        return query.getResultList();\n    }\n\n    protected void begingTx()\n    {\n        em.getTransaction().begin();\n    }\n\n    protected void commitTx()\n    {\n        em.getTransaction().commit();\n    }\n\n    protected void rollbackTx()\n    {\n        em.getTransaction().rollback();\n    }\n\n    /**\n     * @param params\n     * @param query\n     */\n    private void setParams(Map<Object, Object> params, Query query)\n    {\n        if (params != null && !params.isEmpty())\n        {\n            for (Object param : params.keySet())\n            {\n                if (param instanceof Integer)\n                {\n                    query.setParameter(((Integer) param).intValue(), params.get(param));\n                }\n                else if (param instanceof String)\n                {\n                    query.setParameter((String) param, params.get(param));\n                }\n            }\n\n        }\n    }\n\n    protected boolean isLuceneIndexingEnabled()\n    {\n        if (emf != null)\n        {\n           Map<String,Client> clients = (Map<String, Client>) em.getDelegate();\n           \n           OracleNoSQLClient client = (OracleNoSQLClient) clients.get(PERSISTENCE_UNIT);\n           \n           ClientMetadata clientMetadata = ((ClientBase)client).getClientMetadata() ;\n            String luceneDirectory = clientMetadata.getLuceneIndexDir();\n            if (!StringUtils.isEmpty(luceneDirectory))\n            {\n                return true;\n            }\n        }\n        return false;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/OracleNosqlShowQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql;\n\nimport static org.junit.Assert.fail;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.FileReader;\nimport java.io.PrintStream;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * test case for checking printed queries when kundera.show.query is enabled\n * \n * @author shaheed.hussain\n * \n */\n\npublic class OracleNosqlShowQueryTest extends OracleNoSQLTestBase\n{\n\n    private static final String SHOW_QUERY_ENABLED_PU = \"oracleNosqlShowQueryEnabledPU\";\n\n    private static final String SHOW_QUERY_DISABLED_PU = \"oracleNosqlShowQueryDisabledPU\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Map<String, String> puProperties = new HashMap<String, String>();\n\n    private Logger logger = LoggerFactory.getLogger(OracleNosqlShowQueryTest.class);\n\n    @Before\n    public void setUpBeforeClass() throws Exception\n    {\n        //puProperties.put(\"kundera.show.query\", \"true\");\n\n    }\n\n    @After\n    public void tearDownAfterClass() throws Exception\n    {\n        em.close();\n        emf.close();\n        puProperties = null;\n    }\n\n    /*\n     * testing  show.query when it is enabled in persistence unit\n     */\n    @Test\n    public void testShowQuerySetInPU()\n    {\n        emf = Persistence.createEntityManagerFactory(SHOW_QUERY_ENABLED_PU, puProperties);\n        em = emf.createEntityManager();\n        try\n        {\n\n            int i = 0;\n            String expectedQuery[] = new String[3];\n            String actualQuery = null;\n            BufferedReader br = null;\n            File file = new File(\"showQuery.log\");\n            PrintStream printStream;\n\n            printStream = new PrintStream(new FileOutputStream(file));\n            System.setOut(printStream);\n            \n\n            Query findQuery = em.createQuery(\"Select p from UserInformation p where p.id=\\\"PK_1\\\"\");\n            findQuery.getResultList();\n            expectedQuery[0] = \"Fetch data from UserInformation for PK PK_1\";\n            System.setOut(printStream);\n\n            // and query is not supported in oracle nosql\n            findQuery = em.createQuery(\"Select p from UserInformation p where p.id=Shahid\");\n            findQuery.getResultList();\n            expectedQuery[1] = \"Fetch data from UserInformation for PK Shahid\";\n            System.setOut(printStream);\n\n            br = new BufferedReader(new FileReader(\"showQuery.log\"));\n            actualQuery = br.readLine();\n            if (actualQuery == null)\n                fail(\"failed as file is empty\");\n\n            while (actualQuery != null)\n            {\n                Assert.assertEquals(expectedQuery[i++], actualQuery);\n                actualQuery = br.readLine();\n            }\n            \n        }\n        catch (Exception e)\n        {\n            logger.info(e.getMessage());\n        }\n\n    }\n\n    /*\n     *testing show.query property when it is disabled\n     */\n    @Test\n    public void testShowQueryDisabled()\n    {\n        emf = Persistence.createEntityManagerFactory(SHOW_QUERY_DISABLED_PU, puProperties);\n        em = emf.createEntityManager();\n\n        try\n        {\n            boolean isFileEmpty = false;\n            BufferedReader br = null;\n            File file = new File(\"showQuery.log\");\n            PrintStream printStream;\n\n            printStream = new PrintStream(new FileOutputStream(file));\n            System.setOut(printStream);\n            Query findQuery = em.createQuery(\"Select p from UserInformation p\");\n            findQuery.getResultList();\n\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select p from UserInformation p where p.id=\\\"PK_1\\\"\");\n            findQuery.getResultList();\n            System.setOut(printStream);\n\n            // and query is not supported in oracle nosql\n            findQuery = em.createQuery(\"Select p from UserInformation p where p.id=\\\"Shahid\\\"\");\n            findQuery.getResultList();\n            System.setOut(printStream);\n\n            br = new BufferedReader(new FileReader(\"showQuery.log\"));\n            isFileEmpty = br.readLine() == null;\n            Assert.assertEquals(isFileEmpty, true);\n            \n        }\n        catch (Exception e)\n        {\n            logger.info(e.getMessage());\n        }\n\n    }\n\n    /*\n     * testing kunera.show.query property when it is enabled at external properties level\n     */\n    @Test\n    public void testShowQueryPropertySetInPropertyMap()\n    {\n        puProperties.put(\"kundera.show.query\", \"true\");\n        emf = Persistence.createEntityManagerFactory(SHOW_QUERY_DISABLED_PU, puProperties);\n        em = emf.createEntityManager();\n        try\n        {\n\n            int i = 0;\n            String expectedQuery[] = new String[3];\n            String actualQuery = null;\n            BufferedReader br = null;\n            File file = new File(\"showQuery.log\");\n            PrintStream printStream;\n\n            printStream = new PrintStream(new FileOutputStream(file));\n            System.setOut(printStream);\n            \n\n            Query findQuery = em.createQuery(\"Select p from UserInformation p where p.id=\\\"PK_1\\\"\");\n            findQuery.getResultList();\n            expectedQuery[0] = \"Fetch data from UserInformation for PK PK_1\";\n            System.setOut(printStream);\n            \n\n            // and query is not supported in oracle nosql\n            findQuery = em.createQuery(\"Select p from UserInformation p where p.id=\\\"Shahid\\\"\");\n            findQuery.getResultList();\n            expectedQuery[1] = \"Fetch data from UserInformation for PK Shahid\";\n            System.setOut(printStream);\n\n            br = new BufferedReader(new FileReader(\"showQuery.log\"));\n            actualQuery = br.readLine();\n            if (actualQuery == null)\n                fail(\"failed as file is empty\");\n\n            while (actualQuery != null)\n            {\n\n                Assert.assertEquals(expectedQuery[i++], actualQuery);\n                actualQuery = br.readLine();\n            }\n            \n        }\n        catch (Exception e)\n        {\n            logger.info(e.getMessage());\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/batch/AddressBatchOracleNosql.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.batch;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Entity class for batch operation\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ADDRESS_BATCH\", schema = \"OracleNoSqlTests@oracleNosqlBatchTestSizeTwenty\")\n@IndexCollection(columns = { @Index(name = \"STREET\") })\npublic class AddressBatchOracleNosql\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    /** The person name. */\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * @return the addressId\n     */\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    /**\n     * @param addressId\n     *            the addressId to set\n     */\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * @param street\n     *            the street to set\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/batch/OracleNosqlBatchProcessorMixedTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.batch;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * Test case for more than one entities persisted in the same batch\n * \n * @author amresh.singh\n */\npublic class OracleNosqlBatchProcessorMixedTest\n{\n    private static final String PERSISTENCE_UNIT = \"oracleNosqlBatchTestSizeTwenty\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    private List<PersonBatchOracleNosql> allPersons;\n\n    private List<AddressBatchOracleNosql> allAddresses;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void onBatch()\n    {\n        List<PersonBatchOracleNosql> persons = preparePersonData(11);\n        List<AddressBatchOracleNosql> addresses = prepareAddressData(11);\n\n        // Insert Persons\n        for (PersonBatchOracleNosql person : persons)\n        {\n            em.persist(person);\n        }\n\n        // Insert Addresses\n        for (AddressBatchOracleNosql address : addresses)\n        {\n            em.persist(address);\n        }\n\n        // flush all on close.\n        // explicit flush on close\n        em.clear();\n        em.close();\n\n        em = emf.createEntityManager();\n\n        // Query on Persons\n        String personsQueryStr = \" Select p from PersonBatchOracleNosql p\";\n        Query personsQuery = em.createQuery(personsQueryStr);\n        allPersons = personsQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(11, allPersons.size());\n\n        // Query on Addresses\n        String addressQueryStr = \" Select a from AddressBatchOracleNosql a\";\n        Query addressQuery = em.createQuery(addressQueryStr);\n        allAddresses = addressQuery.getResultList();\n        Assert.assertNotNull(allAddresses);\n        Assert.assertEquals(11, allAddresses.size());\n\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        for (PersonBatchOracleNosql entity : allPersons)\n        {\n            em.remove(entity);\n        }\n        for (AddressBatchOracleNosql entity : allAddresses)\n        {\n            em.remove(entity);\n        }\n        em.close();\n        emf.close();\n    }\n\n    private List<PersonBatchOracleNosql> preparePersonData(Integer noOfRecords)\n    {\n        List<PersonBatchOracleNosql> persons = new ArrayList<PersonBatchOracleNosql>();\n        for (int i = 1; i <= noOfRecords; i++)\n        {\n            PersonBatchOracleNosql o = new PersonBatchOracleNosql();\n            o.setPersonId(i + \"\");\n            o.setPersonName(\"Name \" + i);\n            o.setAge(10);\n            persons.add(o);\n        }\n        return persons;\n    }\n\n    private List<AddressBatchOracleNosql> prepareAddressData(Integer noOfRecords)\n    {\n        List<AddressBatchOracleNosql> addresses = new ArrayList<AddressBatchOracleNosql>();\n        for (int i = 1; i <= noOfRecords; i++)\n        {\n            AddressBatchOracleNosql o = new AddressBatchOracleNosql();\n            o.setAddressId(i + \"\");\n            o.setStreet(\"My Street \" + i);\n            addresses.add(o);\n        }\n        return addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/batch/OracleNosqlBatchProcessorTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.batch;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.persistence.api.Batcher;\n\n/**\n * Batch processing test case for oracle-kv.\n * \n * @author vivek.mishra\n * \n */\npublic class OracleNosqlBatchProcessorTest\n{\n    /**\n     * \n     */\n    private static final String PERSISTENCE_UNIT = \"oracleNosqlBatchTest\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    protected boolean AUTO_MANAGE_SCHEMA = true;\n\n    protected boolean USE_CQL = false;\n\n    protected Map propertyMap = null;\n\n    private List<PersonBatchOracleNosqlEntity> results;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        if (propertyMap == null)\n        {\n            propertyMap = new HashMap();\n            propertyMap.put(\"kundera.batch.size\", \"5\");\n        }\n        emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void onBatch()\n    {\n        int counter = 0;\n        List<PersonBatchOracleNosqlEntity> rows = prepareData(10);\n        for (PersonBatchOracleNosqlEntity entity : rows)\n        {\n            em.persist(entity);\n\n            // check for implicit flush.\n            if (++counter == 5)\n            {\n                Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n\n                Batcher client = (Batcher) clients.get(PERSISTENCE_UNIT);\n                Assert.assertEquals(5, client.getBatchSize());\n                em.clear();\n                for (int i = 0; i < 5; i++)\n                {\n\n                    // assert on each batch size record\n                    Assert.assertNotNull(em.find(PersonBatchOracleNosqlEntity.class, rows.get(i).getPersonId()));\n\n                    // as batch size is 5.\n                    Assert.assertNull(em.find(PersonBatchOracleNosqlEntity.class, rows.get(6).getPersonId()));\n                }\n                // means implicit flush must happen\n            }\n        }\n\n        // flush all on close.\n        // explicit flush on close\n        em.clear();\n        em.close();\n\n        em = emf.createEntityManager();\n\n        String sql = \" Select p from PersonBatchOracleNosqlEntity p\";\n        Query query = em.createQuery(sql);\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(10, results.size());\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n        for (PersonBatchOracleNosqlEntity entity : results)\n        {\n            em.remove(entity);\n        }\n        em.close();\n        emf.close();\n    }\n\n    private List<PersonBatchOracleNosqlEntity> prepareData(Integer noOfRecords)\n    {\n        List<PersonBatchOracleNosqlEntity> persons = new ArrayList<PersonBatchOracleNosqlEntity>();\n        for (int i = 1; i <= noOfRecords; i++)\n        {\n            PersonBatchOracleNosqlEntity o = new PersonBatchOracleNosqlEntity();\n            o.setPersonId(i + \"\");\n            o.setPersonName(\"vivek\" + i);\n            o.setAge(10);\n            persons.add(o);\n        }\n\n        return persons;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/batch/PersonBatchOracleNosql.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.batch;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Entity class for Person in Batch operation\n * \n * @author amresh.singh\n */\n@Entity\n@Table(name = \"PERSON_BATCH\", schema = \"OracleNoSqlTests@oracleNosqlBatchTestSizeTwenty\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\npublic class PersonBatchOracleNosql\n{\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"AGEss\")\n    private byte[] a;\n\n    /**\n     * @return the a\n     */\n    public byte[] getA()\n    {\n        return a;\n    }\n\n    /**\n     * @param a\n     *            the a to set\n     */\n    public void setA(byte[] a)\n    {\n        this.a = a;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/batch/PersonBatchOracleNosqlEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.batch;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON_BATCH\", schema = \"OracleNoSqlTests@oracleNosqlBatchTest\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\npublic class PersonBatchOracleNosqlEntity\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"AGEss\")\n    private byte[] a;\n\n    /**\n     * @return the a\n     */\n    public byte[] getA()\n    {\n        return a;\n    }\n\n    /**\n     * @param a\n     *            the a to set\n     */\n    public void setA(byte[] a)\n    {\n        this.a = a;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/crud/OracleNoSqlESAggregationTest.java",
    "content": "package com.impetus.client.oraclenosql.crud;\r\n\r\nimport java.util.List;\r\n\r\nimport javax.persistence.Persistence;\r\n\r\nimport org.elasticsearch.common.settings.Settings;\r\nimport org.elasticsearch.common.settings.Settings.Builder;\r\nimport org.elasticsearch.node.Node;\r\nimport org.elasticsearch.node.NodeBuilder;\r\nimport org.junit.After;\r\nimport org.junit.AfterClass;\r\nimport org.junit.Before;\r\nimport org.junit.BeforeClass;\r\nimport org.junit.Test;\r\n\r\nimport com.impetus.kundera.client.query.AggregationsBaseTest;\r\nimport com.impetus.kundera.query.Person;\r\n\r\nimport junit.framework.Assert;\r\n\r\n/**\r\n * The Class OracleNoSqlESAggregationTest.\r\n * \r\n * @author karthikp.manchala\r\n */\r\npublic class OracleNoSqlESAggregationTest extends AggregationsBaseTest\r\n{\r\n    /** The node. */\r\n    private static Node node = null;\r\n\r\n    /**\r\n     * Sets the up before class.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    @BeforeClass\r\n    public static void setUpBeforeClass() throws Exception\r\n    {\r\n        if (!checkIfServerRunning())\r\n        {\r\n            Builder builder = Settings.settingsBuilder();\r\n            builder.put(\"path.home\", \"target/data\");\r\n            node = new NodeBuilder().settings(builder).node();\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Setup.\r\n     * \r\n     * @throws InterruptedException\r\n     *             the interrupted exception\r\n     */\r\n    @Before\r\n    public void setup() throws InterruptedException\r\n    {\r\n\r\n        emf = Persistence.createEntityManagerFactory(\"ESkvstore\");\r\n        em = emf.createEntityManager();\r\n        init();\r\n    }\r\n    \r\n    @Test\r\n    public void aggregationTest(){\r\n        testAggregation();\r\n    }\r\n    \r\n    @Test\r\n    public void indexDeletionTest() throws Exception\r\n    {\r\n        Thread.sleep(1000);\r\n        String query = \"Select min(p.salary) from Person p\";\r\n        List resultList = em.createQuery(query).getResultList();\r\n        Assert.assertEquals(1, resultList.size());\r\n        Assert.assertEquals(100.0, resultList.get(0));\r\n        \r\n        Person person = em.find(Person.class, \"1\");\r\n        em.remove(person);\r\n        Thread.sleep(1000);\r\n        query = \"Select min(p.salary) from Person p\";\r\n        resultList = em.createQuery(query).getResultList();\r\n        Assert.assertEquals(1, resultList.size());\r\n        Assert.assertEquals(200.0, resultList.get(0));\r\n        \r\n        Person person2 = em.find(Person.class, \"2\");\r\n        em.remove(person2);\r\n        Thread.sleep(1000);\r\n        query = \"Select min(p.salary) from Person p\";\r\n        resultList = em.createQuery(query).getResultList();\r\n        Assert.assertEquals(1, resultList.size());\r\n        Assert.assertEquals(300.0, resultList.get(0));\r\n        \r\n        em.persist(person);\r\n        em.persist(person2);\r\n    }\r\n\r\n\r\n    /**\r\n     * Tear down after class.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    @AfterClass\r\n    public static void tearDownAfterClass() throws Exception\r\n    {\r\n        if (node != null)\r\n            node.close();\r\n    }\r\n\r\n    /**\r\n     * Tear down.\r\n     */\r\n    @After\r\n    public void tearDown()\r\n    {\r\n        em.remove(em.find(Person.class, \"1\"));\r\n        em.remove(em.find(Person.class, \"2\"));\r\n        em.remove(em.find(Person.class, \"3\"));\r\n        em.remove(em.find(Person.class, \"4\"));\r\n        em.close();\r\n        emf.close();\r\n    }\r\n}"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/crud/OracleNoSqlESGroupByTest.java",
    "content": "package com.impetus.client.oraclenosql.crud;\r\n\r\nimport javax.persistence.Persistence;\r\n\r\nimport org.elasticsearch.common.settings.Settings;\r\nimport org.elasticsearch.common.settings.Settings.Builder;\r\nimport org.elasticsearch.node.Node;\r\nimport org.elasticsearch.node.NodeBuilder;\r\nimport org.junit.AfterClass;\r\nimport org.junit.BeforeClass;\r\nimport org.junit.Test;\r\n\r\nimport com.impetus.kundera.client.query.GroupByBaseTest;\r\n\r\n/**\r\n * The Class OracleNoSqlESGroupByTest.\r\n * \r\n * @author karthikp.manchala\r\n */\r\npublic class OracleNoSqlESGroupByTest extends GroupByBaseTest\r\n{\r\n    /** The node. */\r\n    private static Node node = null;\r\n\r\n    /**\r\n     * Sets the up before class.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    @BeforeClass\r\n    public static void setUpBeforeClass() throws Exception\r\n    {\r\n        if (!checkIfServerRunning())\r\n        {\r\n            Builder builder = Settings.settingsBuilder();\r\n            builder.put(\"path.home\", \"target/data\");\r\n            node = new NodeBuilder().settings(builder).node();\r\n        }\r\n\r\n        emf = Persistence.createEntityManagerFactory(\"ESkvstore\");\r\n        em = emf.createEntityManager();\r\n        init();\r\n    }\r\n\r\n    /**\r\n     * Test aggregation.\r\n     */\r\n    @Test\r\n    public void test()\r\n    {\r\n        testAggregation();\r\n    }\r\n\r\n    /**\r\n     * Tear down after class.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    @AfterClass\r\n    public static void tearDownAfterClass() throws Exception\r\n    {\r\n        em.createQuery(\"Delete from Person p\").executeUpdate();\r\n        waitThread();\r\n\r\n        em.close();\r\n        emf.close();\r\n\r\n        if (node != null)\r\n            node.close();\r\n    }\r\n}"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/crud/OracleNoSqlLuceneTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.crud;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.entities.PersonOracleNoSql;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * \n * @author shaheed.hussain\n * \n */\npublic class OracleNoSqlLuceneTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    @Before\n    public void setUp()\n    {\n        Map<String, String> propertyMap = new HashMap<String, String>();\n        propertyMap.put(\"index.home.dir\", \"./lucene\");\n        emf = Persistence.createEntityManagerFactory(\"twikvstore\", propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void luceneTest()\n    {\n        persistPerson(\"1\", \"person1\", 10);\n        persistPerson(\"2\", \"person2\", 20);\n        persistPerson(\"3\", \"person3\", 30);\n        persistPerson(\"4\", \"person4\", 40);\n\n        clearEm();\n        // Select query, without where clause\n        String findWithOutWhereClause = \"Select p from PersonOracleNoSql p\";\n        List<PersonOracleNoSql> results = executeSelectQuery(findWithOutWhereClause);\n        Assert.assertEquals(4, results.size());\n\n        clearEm();\n        String findSelective = \"Select p.age from PersonOracleNoSql p\";\n        results = executeSelectQuery(findSelective);\n        Assert.assertEquals(4, results.size());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNotNull(results.get(0).getAge());\n\n        clearEm();\n        // Select query with where clause on single non-ID column\n        String findByName = \"Select p.personId from PersonOracleNoSql p where p.personName='person1'\";\n        results = executeSelectQuery(findByName);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"1\", results.get(0).getPersonId());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNull(results.get(0).getAge());\n\n        clearEm();\n        // Select query with where clause on ID column\n        String findById = \"Select p from PersonOracleNoSql p where p.personId=2\";\n        results = executeSelectQuery(findById);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"2\", results.get(0).getPersonId());\n        Assert.assertEquals(\"person2\", results.get(0).getPersonName());\n        Assert.assertEquals(20, results.get(0).getAge().intValue());\n\n        String find = \"Select p from PersonOracleNoSql p where p.personName='person4' and p.age>30\";\n        results = executeSelectQuery(find);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"4\", results.get(0).getPersonId());\n        Assert.assertEquals(\"person4\", results.get(0).getPersonName());\n        Assert.assertEquals(40, results.get(0).getAge().intValue());\n\n        String findMultipleColumns = \"Select p.personId,p.age from PersonOracleNoSql p where p.personName='person3'\";\n        results = executeSelectQuery(findMultipleColumns);\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"3\", results.get(0).getPersonId());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertEquals(30, results.get(0).getAge().intValue());\n        \n        \n        // Delete by query.\n        String deleteQuery = \"Delete from PersonOracleNoSql p\";\n        Query query = em.createQuery(deleteQuery);\n        int updateCount = query.executeUpdate();\n        Assert.assertEquals(4, updateCount);\n    }\n\n    private void persistPerson(String personId, String personName, int age)\n    {\n        PersonOracleNoSql p = preparePerson(personId, age, personName);\n        em.persist(p);\n    }\n\n    private PersonOracleNoSql preparePerson(String rowKey, int age, String name)\n    {\n        PersonOracleNoSql person = new PersonOracleNoSql();\n        person.setPersonId(rowKey);\n        person.setPersonName(name);\n        person.setAge(age);\n        return person;\n    }\n\n    protected void clearEm()\n    {\n        em.clear();\n    }\n\n    protected List<PersonOracleNoSql> executeSelectQuery(String jpaQuery)\n    {\n        Query query = em.createQuery(jpaQuery);\n        return query.getResultList();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        LuceneCleanupUtilities.cleanLuceneDirectory(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance()\n                .getApplicationMetadata().getPersistenceUnitMetadata(\"twikvstore\"));\n        em.close();\n        emf.close();\n    }\n    \n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/crud/OracleNoSqlMTMTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.crud;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.entities.AddressOracleNoSqlMTM;\nimport com.impetus.client.oraclenosql.entities.PersonOracleNoSqlMTM;\n\n\n/**\n * @author vivek.mishra\n * \n */\npublic class OracleNoSqlMTMTest {\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception {\n        emf = Persistence.createEntityManagerFactory(\"twikvstore\");\n        em = getNewEM();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void testCRUD() {\n        AddressOracleNoSqlMTM address1 = new AddressOracleNoSqlMTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"sector 11\");\n\n        AddressOracleNoSqlMTM address2 = new AddressOracleNoSqlMTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"sector 12\");\n\n        AddressOracleNoSqlMTM address3 = new AddressOracleNoSqlMTM();\n        address3.setAddressId(\"c\");\n        address3.setStreet(\"sector 13\");\n\n        Set<AddressOracleNoSqlMTM> addresses1 = new HashSet<AddressOracleNoSqlMTM>();\n        addresses1.add(address1);\n        addresses1.add(address2);\n\n        Set<AddressOracleNoSqlMTM> addresses2 = new HashSet<AddressOracleNoSqlMTM>();\n        addresses2.add(address2);\n        addresses2.add(address3);\n\n        PersonOracleNoSqlMTM person1 = new PersonOracleNoSqlMTM();\n        person1.setPersonId(\"1\");\n        person1.setPersonName(\"Kuldeep\");\n\n        PersonOracleNoSqlMTM person2 = new PersonOracleNoSqlMTM();\n        person2.setPersonId(\"2\");\n        person2.setPersonName(\"vivek\");\n\n        person1.setAddresses(addresses1);\n        person2.setAddresses(addresses2);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        em = getNewEM();\n\n        PersonOracleNoSqlMTM foundPerson1 = em.find(PersonOracleNoSqlMTM.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson1.getPersonName());\n\n        int counter = 0;\n        for (AddressOracleNoSqlMTM address : foundPerson1.getAddresses()) {\n            if (address.getAddressId().equals(\"a\")) {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            } else {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        PersonOracleNoSqlMTM foundPerson2 = em.find(PersonOracleNoSqlMTM.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddresses());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vivek\", foundPerson2.getPersonName());\n\n        counter = 0;\n        for (AddressOracleNoSqlMTM address : foundPerson2.getAddresses()) {\n            if (address.getAddressId().equals(\"b\")) {\n                counter++;\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n            } else {\n                Assert.assertEquals(\"c\", address.getAddressId());\n                Assert.assertEquals(\"sector 13\", address.getStreet());\n                counter++;\n            }\n        }\n\n        foundPerson1.setPersonName(\"KK\");\n\n        foundPerson2.setPersonName(\"vives\");\n\n        em.merge(foundPerson1);\n        em.merge(foundPerson2);\n\n        em = getNewEM();\n\n        foundPerson1 = em.find(PersonOracleNoSqlMTM.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson1.getPersonName());\n\n        counter = 0;\n        for (AddressOracleNoSqlMTM address : foundPerson1.getAddresses()) {\n            if (address.getAddressId().equals(\"a\")) {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            } else {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        foundPerson2 = em.find(PersonOracleNoSqlMTM.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddresses());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vives\", foundPerson2.getPersonName());\n\n        counter = 0;\n        for (AddressOracleNoSqlMTM address : foundPerson2.getAddresses()) {\n            if (address.getAddressId().equals(\"b\")) {\n                counter++;\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n            } else {\n                Assert.assertEquals(\"c\", address.getAddressId());\n                Assert.assertEquals(\"sector 13\", address.getStreet());\n                counter++;\n            }\n        }\n\n        em.remove(foundPerson1);\n        em.remove(foundPerson2);\n\n        foundPerson1 = em.find(PersonOracleNoSqlMTM.class, \"1\");\n        foundPerson2 = em.find(PersonOracleNoSqlMTM.class, \"2\");\n\n        Assert.assertNull(foundPerson1);\n        Assert.assertNull(foundPerson2);\n    }\n\n    @Test\n    public void testQuery() {\n        AddressOracleNoSqlMTM address1 = new AddressOracleNoSqlMTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"sector 11\");\n\n        AddressOracleNoSqlMTM address2 = new AddressOracleNoSqlMTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"sector 12\");\n\n        AddressOracleNoSqlMTM address3 = new AddressOracleNoSqlMTM();\n        address3.setAddressId(\"c\");\n        address3.setStreet(\"sector 13\");\n\n        Set<AddressOracleNoSqlMTM> addresses1 = new HashSet<AddressOracleNoSqlMTM>();\n        addresses1.add(address1);\n        addresses1.add(address2);\n\n        Set<AddressOracleNoSqlMTM> addresses2 = new HashSet<AddressOracleNoSqlMTM>();\n        addresses2.add(address2);\n        addresses2.add(address3);\n\n        PersonOracleNoSqlMTM person1 = new PersonOracleNoSqlMTM();\n        person1.setPersonId(\"1\");\n        person1.setPersonName(\"Kuldeep\");\n\n        PersonOracleNoSqlMTM person2 = new PersonOracleNoSqlMTM();\n        person2.setPersonId(\"2\");\n        person2.setPersonName(\"vivek\");\n\n        person1.setAddresses(addresses1);\n        person2.setAddresses(addresses2);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        em = getNewEM();\n\n        String personsQueryStr = \" Select p from PersonOracleNoSqlMTM p\";\n        Query personsQuery = em.createQuery(personsQueryStr);\n        List<PersonOracleNoSqlMTM> allPersons = personsQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        for (PersonOracleNoSqlMTM foundPerson : allPersons) {\n            Assert.assertNotNull(foundPerson);\n            Assert.assertNotNull(foundPerson.getAddresses());\n            Assert.assertEquals(2, foundPerson.getAddresses().size());\n            \n            if (foundPerson.getPersonId().equals(\"1\")) {\n\n                \n                Assert.assertEquals(\"1\", foundPerson.getPersonId());\n                Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n\n                for (AddressOracleNoSqlMTM address : foundPerson.getAddresses()) {\n                    if (address.getAddressId().equals(\"a\")) {\n\n                        Assert.assertEquals(\"sector 11\", address.getStreet());\n                    } else {\n                        Assert.assertEquals(\"b\", address.getAddressId());\n                        Assert.assertEquals(\"sector 12\", address.getStreet());\n\n                    }\n                }\n            } else if (foundPerson.getPersonId().equals(\"2\")) {\n\n  \n                Assert.assertEquals(\"2\", foundPerson.getPersonId());\n                Assert.assertEquals(\"vivek\", foundPerson.getPersonName());\n\n                for (AddressOracleNoSqlMTM address : foundPerson.getAddresses()) {\n                    if (address.getAddressId().equals(\"b\")) {\n\n                        Assert.assertEquals(\"sector 12\", address.getStreet());\n                    } else {\n                        Assert.assertEquals(\"c\", address.getAddressId());\n                        Assert.assertEquals(\"sector 13\", address.getStreet());\n\n                    }\n                }\n            }\n          \n        }\n        em.remove(allPersons.get(0));\n        em.remove(allPersons.get(1));\n        PersonOracleNoSqlMTM  foundPerson1 = em.find(PersonOracleNoSqlMTM.class, allPersons.get(0).getPersonId());\n        PersonOracleNoSqlMTM  foundPerson2 = em.find(PersonOracleNoSqlMTM.class, allPersons.get(1).getPersonId());\n        Assert.assertNull(foundPerson1);\n        Assert.assertNull(foundPerson2);\n\n    }\n\n    private EntityManager getNewEM() {\n        if (em != null && em.isOpen()) {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/crud/OracleNoSqlMTOTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.crud;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.entities.AddressOracleNoSqlMTO;\nimport com.impetus.client.oraclenosql.entities.PersonOracleNoSqlMTO;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class OracleNoSqlMTOTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"twikvstore\");\n        em = getNewEM();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        AddressOracleNoSqlMTO address = new AddressOracleNoSqlMTO();\n        address.setAddressId(\"a\");\n        address.setStreet(\"sector 11\");\n\n        PersonOracleNoSqlMTO person1 = new PersonOracleNoSqlMTO();\n        person1.setPersonId(\"1\");\n        person1.setPersonName(\"Kuldeep\");\n\n        PersonOracleNoSqlMTO person2 = new PersonOracleNoSqlMTO();\n        person2.setPersonId(\"2\");\n        person2.setPersonName(\"vivek\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        em = getNewEM();\n\n        PersonOracleNoSqlMTO foundPerson1 = em.find(PersonOracleNoSqlMTO.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddress());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson1.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson1.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson1.getAddress().getStreet());\n\n        PersonOracleNoSqlMTO foundPerson2 = em.find(PersonOracleNoSqlMTO.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddress());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vivek\", foundPerson2.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson2.getAddress().getStreet());\n\n        foundPerson1.setPersonName(\"KK\");\n\n        foundPerson2.setPersonName(\"vives\");\n\n        em.merge(foundPerson1);\n        em.merge(foundPerson2);\n\n        em = getNewEM();\n\n        foundPerson1 = em.find(PersonOracleNoSqlMTO.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddress());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson1.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson1.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson1.getAddress().getStreet());\n\n        foundPerson2 = em.find(PersonOracleNoSqlMTO.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddress());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vives\", foundPerson2.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson2.getAddress().getStreet());\n\n        em.remove(foundPerson1);\n        em.remove(foundPerson2);\n\n        foundPerson1 = em.find(PersonOracleNoSqlMTO.class, \"1\");\n        foundPerson2 = em.find(PersonOracleNoSqlMTO.class, \"2\");\n\n        Assert.assertNull(foundPerson1);\n        Assert.assertNull(foundPerson2);\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/crud/OracleNoSqlOTMTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.crud;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.entities.AddressOracleNoSqlOTM;\nimport com.impetus.client.oraclenosql.entities.PersonOracleNoSqlOTM;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class OracleNoSqlOTMTest {\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception {\n        emf = Persistence.createEntityManagerFactory(\"twikvstore\");\n        em = getNewEM();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void testCRUD() {\n        AddressOracleNoSqlOTM address1 = new AddressOracleNoSqlOTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"sector 11\");\n\n        AddressOracleNoSqlOTM address2 = new AddressOracleNoSqlOTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"sector 12\");\n\n        Set<AddressOracleNoSqlOTM> addresses = new HashSet<AddressOracleNoSqlOTM>();\n        addresses.add(address1);\n        addresses.add(address2);\n\n        PersonOracleNoSqlOTM person = new PersonOracleNoSqlOTM();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"Kuldeep\");\n        person.setAddresses(addresses);\n\n        em.persist(person);\n\n        em = getNewEM();\n\n        PersonOracleNoSqlOTM foundPerson = em.find(PersonOracleNoSqlOTM.class, \"1\");\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n\n        int counter = 0;\n        for (AddressOracleNoSqlOTM address : foundPerson.getAddresses()) {\n            if (address.getAddressId().equals(\"a\")) {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            } else {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        Assert.assertEquals(2, counter);\n\n        foundPerson.setPersonName(\"KK\");\n\n        em.merge(foundPerson);\n\n        em = getNewEM();\n\n        foundPerson = em.find(PersonOracleNoSqlOTM.class, \"1\");\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson.getPersonName());\n\n        counter = 0;\n        for (AddressOracleNoSqlOTM address : foundPerson.getAddresses()) {\n            if (address.getAddressId().equals(\"a\")) {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            } else {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        Assert.assertEquals(2, counter);\n\n        em.remove(foundPerson);\n\n        foundPerson = em.find(PersonOracleNoSqlOTM.class, \"1\");\n        Assert.assertNull(foundPerson);\n    }\n\n    @Test\n    public void testQuery() {\n        AddressOracleNoSqlOTM address1 = new AddressOracleNoSqlOTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"sector 11\");\n\n        AddressOracleNoSqlOTM address2 = new AddressOracleNoSqlOTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"sector 12\");\n\n        Set<AddressOracleNoSqlOTM> addresses = new HashSet<AddressOracleNoSqlOTM>();\n        addresses.add(address1);\n        addresses.add(address2);\n\n        PersonOracleNoSqlOTM person = new PersonOracleNoSqlOTM();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"Kuldeep\");\n        person.setAddresses(addresses);\n\n        em.persist(person);\n\n        AddressOracleNoSqlOTM address1a = new AddressOracleNoSqlOTM();\n        address1a.setAddressId(\"a1\");\n        address1a.setStreet(\"sector 11a\");\n\n        AddressOracleNoSqlOTM address2b = new AddressOracleNoSqlOTM();\n        address2b.setAddressId(\"b1\");\n        address2b.setStreet(\"sector 12b\");\n\n        Set<AddressOracleNoSqlOTM> addresses1 = new HashSet<AddressOracleNoSqlOTM>();\n        addresses1.add(address1a);\n        addresses1.add(address2b);\n\n        PersonOracleNoSqlOTM person1 = new PersonOracleNoSqlOTM();\n        person1.setPersonId(\"2\");\n        person1.setPersonName(\"KK\");\n        person1.setAddresses(addresses1);\n\n        em.persist(person1);\n\n        em = getNewEM();\n\n        String personsQueryStr = \" Select p from PersonOracleNoSqlOTM p\";\n        Query personsQuery = em.createQuery(personsQueryStr);\n        List<PersonOracleNoSqlOTM> allPersons = personsQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        Assert.assertEquals(2, allPersons.size());\n\n        for (PersonOracleNoSqlOTM foundPerson : allPersons) {\n\n            Assert.assertNotNull(foundPerson);\n            Assert.assertEquals(2, foundPerson.getAddresses().size());\n            Assert.assertNotNull(foundPerson.getAddresses());\n            if (foundPerson.getPersonId().equals(\"1\")) {\n\n                Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n\n                for (AddressOracleNoSqlOTM address : foundPerson.getAddresses()) {\n                    if (address.getAddressId().equals(\"a\")) {\n\n                        Assert.assertEquals(\"sector 11\", address.getStreet());\n                    } else {\n                        Assert.assertEquals(\"b\", address.getAddressId());\n                        Assert.assertEquals(\"sector 12\", address.getStreet());\n\n                    }\n                }\n            } else if (foundPerson.getPersonId().equals(\"2\")) {\n                Assert.assertEquals(\"KK\", foundPerson.getPersonName());\n\n                for (AddressOracleNoSqlOTM address : foundPerson.getAddresses()) {\n                    if (address.getAddressId().equals(\"a1\")) {\n\n                        Assert.assertEquals(\"sector 11a\", address.getStreet());\n                    } else {\n                        Assert.assertEquals(\"b1\", address.getAddressId());\n                        Assert.assertEquals(\"sector 12b\", address.getStreet());\n\n                    }\n                }\n            }\n            em.remove(foundPerson);\n\n            foundPerson = em.find(PersonOracleNoSqlOTM.class, foundPerson.getPersonId());\n            Assert.assertNull(foundPerson);\n        }\n\n    }\n\n    private EntityManager getNewEM() {\n        if (em != null && em.isOpen()) {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/crud/OracleNoSqlOTOTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.crud;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.entities.AddressOracleNoSqlOTO;\nimport com.impetus.client.oraclenosql.entities.PersonOracleNoSqlOTO;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class OracleNoSqlOTOTest {\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception {\n        emf = Persistence.createEntityManagerFactory(\"twikvstore\");\n        em = getNewEM();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void testCRUD() {\n        AddressOracleNoSqlOTO address = new AddressOracleNoSqlOTO();\n        address.setAddressId(\"a\");\n        address.setStreet(\"sector 11\");\n\n        PersonOracleNoSqlOTO person = new PersonOracleNoSqlOTO();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"Kuldeep\");\n        person.setAddress(address);\n\n        em.persist(person);\n\n        em = getNewEM();\n\n        PersonOracleNoSqlOTO foundPerson = em.find(PersonOracleNoSqlOTO.class, \"1\");\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddress());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson.getAddress().getStreet());\n\n        foundPerson.setPersonName(\"KK\");\n        foundPerson.getAddress().setStreet(\"sector 12\");\n\n        em.merge(foundPerson);\n\n        em = getNewEM();\n\n        foundPerson = em.find(PersonOracleNoSqlOTO.class, \"1\");\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddress());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 12\", foundPerson.getAddress().getStreet());\n\n        em.remove(foundPerson);\n        foundPerson = em.find(PersonOracleNoSqlOTO.class, \"1\");\n        Assert.assertNull(foundPerson);\n\n    }\n\n    @Test\n    public void testQuery() {\n        AddressOracleNoSqlOTO address = new AddressOracleNoSqlOTO();\n        address.setAddressId(\"a\");\n        address.setStreet(\"sector 11\");\n\n        AddressOracleNoSqlOTO address1 = new AddressOracleNoSqlOTO();\n        address1.setAddressId(\"a1\");\n        address1.setStreet(\"sector 12\");\n\n        PersonOracleNoSqlOTO person = new PersonOracleNoSqlOTO();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"Kuldeep\");\n        person.setAddress(address);\n\n        PersonOracleNoSqlOTO person1 = new PersonOracleNoSqlOTO();\n        person1.setPersonId(\"2\");\n        person1.setPersonName(\"KK\");\n        person1.setAddress(address1);\n        em.persist(person1);\n\n        em.persist(person);\n\n        em = getNewEM();\n\n        em = getNewEM();\n\n        // Query on Persons\n        String personsQueryStr = \" Select p from PersonOracleNoSqlOTO p\";\n        Query personsQuery = em.createQuery(personsQueryStr);\n        List<PersonOracleNoSqlOTO> allPersons = personsQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n\n        for (PersonOracleNoSqlOTO foundPerson : allPersons) {\n            Assert.assertNotNull(foundPerson);\n            Assert.assertNotNull(foundPerson.getAddress());\n            if (foundPerson.getPersonId().equals(\"1\")) {\n                \n                Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n                Assert.assertEquals(\"a\", foundPerson.getAddress().getAddressId());\n                Assert.assertEquals(\"sector 11\", foundPerson.getAddress().getStreet());\n                \n            } else if (foundPerson.getPersonId().equals(\"2\")) {\n                \n                Assert.assertEquals(\"KK\", foundPerson.getPersonName());\n                Assert.assertEquals(\"a1\", foundPerson.getAddress().getAddressId());\n                Assert.assertEquals(\"sector 12\", foundPerson.getAddress().getStreet());\n                \n            }\n            em.remove(foundPerson);\n            foundPerson = em.find(PersonOracleNoSqlOTO.class, foundPerson.getPersonId());\n            Assert.assertNull(foundPerson);\n        }\n\n    }\n\n    private EntityManager getNewEM() {\n        if (em != null && em.isOpen()) {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n}"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/entities/StudentOracleNoSQLChar.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.entities;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"StudentOracleNoSQLChar\", schema = \"OracleNoSqlTests@oracleNosqlDataTypeTest\")\npublic class StudentOracleNoSQLChar implements Serializable\n{\n\n    @Id\n    private char id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public char getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(char id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/entities/StudentOracleNoSQLCharacter.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.entities;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"StudentOracleNoSQLCharacter\", schema = \"OracleNoSqlTests@oracleNosqlDataTypeTest\")\npublic class StudentOracleNoSQLCharacter implements Serializable\n{\n    @Id\n    private Character id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Character getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Character id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/entities/StudentOracleNoSQLDate.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.entities;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"StudentOracleNoSQLDate\", schema = \"OracleNoSqlTests@oracleNosqlDataTypeTest\")\npublic class StudentOracleNoSQLDate implements Serializable\n{\n\n    @Id\n    private Date id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/entities/StudentOracleNoSQLDoublePrimitive.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.entities;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"StudentOracleNoSQLDoublePrimitiv\", schema = \"OracleNoSqlTests@oracleNosqlDataTypeTest\")\npublic class StudentOracleNoSQLDoublePrimitive implements Serializable\n{\n\n    @Id\n    private double id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public double getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/entities/StudentOracleNoSQLDoubleWrapper.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.entities;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"StudentOracleNoSQLDoubleWrapper\", schema = \"OracleNoSqlTests@oracleNosqlDataTypeTest\")\npublic class StudentOracleNoSQLDoubleWrapper implements Serializable\n{\n\n    @Id\n    private Double id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Double getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/entities/StudentOracleNoSQLFloatPrimitive.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.entities;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"StudentOracleNoSQLFloatPrimitive\", schema = \"OracleNoSqlTests@oracleNosqlDataTypeTest\")\npublic class StudentOracleNoSQLFloatPrimitive implements Serializable\n{\n    @Id\n    private float id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public float getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/entities/StudentOracleNoSQLFloatWrapper.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.entities;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"StudentOracleNoSQLFloatWrapper\", schema = \"OracleNoSqlTests@oracleNosqlDataTypeTest\")\npublic class StudentOracleNoSQLFloatWrapper implements Serializable\n{\n\n    @Id\n    private Float id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Float getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/entities/StudentOracleNoSQLInt.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.entities;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"StudentOracleNoSQLInt\", schema = \"OracleNoSqlTests@oracleNosqlDataTypeTest\")\npublic class StudentOracleNoSQLInt implements Serializable\n{\n\n    @Id\n    private int id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/entities/StudentOracleNoSQLInteger.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.entities;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"StudentOracleNoSQLInteger\", schema = \"OracleNoSqlTests@oracleNosqlDataTypeTest\")\npublic class StudentOracleNoSQLInteger implements Serializable\n{\n    @Id\n    private Integer id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Integer getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Integer id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/entities/StudentOracleNoSQLLongPrimitive.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.entities;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"StudentOracleNoSQLLongPrimitive\", schema = \"OracleNoSqlTests@oracleNosqlDataTypeTest\")\npublic class StudentOracleNoSQLLongPrimitive implements Serializable\n{\n\n    @Id\n    private long id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public long getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/entities/StudentOracleNoSQLLongWrapper.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.entities;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"StudentOracleNoSQLLongWrapper\", schema = \"OracleNoSqlTests@oracleNosqlDataTypeTest\")\npublic class StudentOracleNoSQLLongWrapper implements Serializable\n{\n\n    @Id\n    private Long id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Long getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/entities/StudentOracleNoSQLSqlDate.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.entities;\n\nimport java.io.Serializable;\nimport java.sql.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"StudentOracleNoSQLSqlDate\", schema = \"OracleNoSqlTests@oracleNosqlDataTypeTest\")\npublic class StudentOracleNoSQLSqlDate implements Serializable\n{\n\n    @Id\n    private Date id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/entities/StudentOracleNoSQLString.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.entities;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"StudentOracleNoSQLString\", schema = \"OracleNoSqlTests@oracleNosqlDataTypeTest\")\npublic class StudentOracleNoSQLString implements Serializable\n{\n\n    @Id\n    private String id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/OracleNoSQLBase.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport com.impetus.kundera.datatypes.datagenerator.DataGenerator;\nimport com.impetus.kundera.datatypes.datagenerator.DataGeneratorFactory;\n\n/**\n * @author vivek.mishra\n *\n */\npublic abstract class OracleNoSQLBase\n{\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\n\n    DataGenerator<?> dataGenerator;\n\n    DataGeneratorFactory factory = new DataGeneratorFactory();\n\n    protected Object getMaxValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.maxValue();\n    }\n\n    protected Object getMinValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.minValue();\n    }\n\n    protected Object getRandomValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.randomValue();\n    }\n\n    protected Object getPartialValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.partialValue();\n    }\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/StudentOracleNoSQLCharTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLChar;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class StudentOracleNoSQLCharTest extends OracleNoSQLBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"oracleNosqlDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of char\n        StudentOracleNoSQLChar studentMax = new StudentOracleNoSQLChar();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Character) getMaxValue(char.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of char\n        StudentOracleNoSQLChar studentMin = new StudentOracleNoSQLChar();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Character) getMinValue(char.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of char\n        StudentOracleNoSQLChar student = new StudentOracleNoSQLChar();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(char.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLChar studentMax = em.find(StudentOracleNoSQLChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLChar studentMin = em.find(StudentOracleNoSQLChar.class, getMinValue(char.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLChar student = em.find(StudentOracleNoSQLChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentOracleNoSQLChar student = em.find(StudentOracleNoSQLChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLChar newStudent = em.find(StudentOracleNoSQLChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLChar student : students)\n        {\n            Assert.assertEquals(getMinValue(char.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLChar> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(char.class));\n        q.setParameter(2, getMaxValue(char.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Character) getMinValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(char.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLChar studentMax = em.find(StudentOracleNoSQLChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentOracleNoSQLChar.class, getMaxValue(char.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLChar s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLChar newStudent = em.find(StudentOracleNoSQLChar.class, getRandomValue(char.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLChar s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLChar newStudent = em.find(StudentOracleNoSQLChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLChar s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLChar s \";\n        Query q = em.createQuery(query);\n        List<StudentOracleNoSQLChar> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Character) getMinValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(char.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/StudentOracleNoSQLCharacterTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLCharacter;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class StudentOracleNoSQLCharacterTest extends OracleNoSQLBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"oracleNosqlDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Character\n        StudentOracleNoSQLCharacter studentMax = new StudentOracleNoSQLCharacter();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Character) getMaxValue(Character.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Character\n        StudentOracleNoSQLCharacter studentMin = new StudentOracleNoSQLCharacter();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Character) getMinValue(Character.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Character\n        StudentOracleNoSQLCharacter student = new StudentOracleNoSQLCharacter();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(Character.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLCharacter studentMax = em.find(StudentOracleNoSQLCharacter.class,\n                getMaxValue(Character.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLCharacter studentMin = em.find(StudentOracleNoSQLCharacter.class,\n                getMinValue(Character.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLCharacter student = em.find(StudentOracleNoSQLCharacter.class,\n                getRandomValue(Character.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentOracleNoSQLCharacter student = em.find(StudentOracleNoSQLCharacter.class, getMaxValue(Character.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLCharacter newStudent = em.find(StudentOracleNoSQLCharacter.class,\n                getMaxValue(Character.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLCharacter student : students)\n        {\n            Assert.assertEquals(getMinValue(Character.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLCharacter> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Character.class));\n        q.setParameter(2, getMaxValue(Character.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Character.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLCharacter student : students)\n        {\n            Assert.assertEquals(getMaxValue(Character.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLCharacter student : students)\n        {\n            Assert.assertEquals(getMaxValue(Character.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLCharacter studentMax = em.find(StudentOracleNoSQLCharacter.class,\n                getMaxValue(Character.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentOracleNoSQLCharacter.class, getMaxValue(Character.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLCharacter s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLCharacter newStudent = em.find(StudentOracleNoSQLCharacter.class,\n                getRandomValue(Character.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLCharacter s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLCharacter newStudent = em.find(StudentOracleNoSQLCharacter.class,\n                getRandomValue(Character.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLCharacter s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLCharacter s \";\n        Query q = em.createQuery(query);\n        List<StudentOracleNoSQLCharacter> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLCharacter student : students)\n        {\n            if (student.getId().equals(getMaxValue(Character.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Character.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/StudentOracleNoSQLDateTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLDate;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class StudentOracleNoSQLDateTest extends OracleNoSQLBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"oracleNosqlDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentOracleNoSQLDate student = new StudentOracleNoSQLDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue(Date.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Date\n        StudentOracleNoSQLDate studentMax = new StudentOracleNoSQLDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue(Date.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Date\n        StudentOracleNoSQLDate studentMin = new StudentOracleNoSQLDate();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Date) getMinValue(Date.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.clear();\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLDate studentMax = em.find(StudentOracleNoSQLDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDate studentMin = em.find(StudentOracleNoSQLDate.class, getMinValue(Date.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDate student = em.find(StudentOracleNoSQLDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentOracleNoSQLDate student = em.find(StudentOracleNoSQLDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDate newStudent = em.find(StudentOracleNoSQLDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDate student : students)\n        {\n            Assert.assertEquals(getMinValue(Date.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDate> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.id between ?1  and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Date.class));\n        q.setParameter(2, getMaxValue(Date.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Date.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLDate studentMax = em.find(StudentOracleNoSQLDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentOracleNoSQLDate.class, getMaxValue(Date.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLDate s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDate newStudent = em.find(StudentOracleNoSQLDate.class, getRandomValue(Date.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLDate s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDate newStudent = em.find(StudentOracleNoSQLDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDate s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLDate s \";\n        Query q = em.createQuery(query);\n        List<StudentOracleNoSQLDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue(Date.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/StudentOracleNoSQLDoublePrimitiveTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLDoublePrimitive;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class StudentOracleNoSQLDoublePrimitiveTest extends OracleNoSQLBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"oracleNosqlDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Double\n        StudentOracleNoSQLDoublePrimitive studentMax = new StudentOracleNoSQLDoublePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) getMaxValue(Double.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Double\n        StudentOracleNoSQLDoublePrimitive studentMin = new StudentOracleNoSQLDoublePrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Double) getMinValue(Double.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Double\n        StudentOracleNoSQLDoublePrimitive student = new StudentOracleNoSQLDoublePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLDoublePrimitive studentMax = em.find(StudentOracleNoSQLDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDoublePrimitive studentMin = em.find(StudentOracleNoSQLDoublePrimitive.class, getMinValue(Double.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDoublePrimitive student = em.find(StudentOracleNoSQLDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentOracleNoSQLDoublePrimitive student = em.find(StudentOracleNoSQLDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDoublePrimitive newStudent = em.find(StudentOracleNoSQLDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(Double.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoublePrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(double.class));\n        q.setParameter(2, getMaxValue(double.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Double) getMinValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLDoublePrimitive studentMax = em.find(StudentOracleNoSQLDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentOracleNoSQLDoublePrimitive.class, getMaxValue(Double.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLDoublePrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDoublePrimitive newStudent = em.find(StudentOracleNoSQLDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLDoublePrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDoublePrimitive newStudent = em.find(StudentOracleNoSQLDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoublePrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLDoublePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentOracleNoSQLDoublePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) getMaxValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Double) getMinValue(Double.class)).doubleValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/StudentOracleNoSQLDoubleWrapperTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLDoubleWrapper;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class StudentOracleNoSQLDoubleWrapperTest extends OracleNoSQLBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"oracleNosqlDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Double\n        StudentOracleNoSQLDoubleWrapper studentMax = new StudentOracleNoSQLDoubleWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) getMaxValue(Double.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Double\n        StudentOracleNoSQLDoubleWrapper studentMin = new StudentOracleNoSQLDoubleWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Double) getMinValue(Double.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Double\n        StudentOracleNoSQLDoubleWrapper student = new StudentOracleNoSQLDoubleWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLDoubleWrapper studentMax = em.find(StudentOracleNoSQLDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDoubleWrapper studentMin = em.find(StudentOracleNoSQLDoubleWrapper.class, getMinValue(Double.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDoubleWrapper student = em.find(StudentOracleNoSQLDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentOracleNoSQLDoubleWrapper student = em.find(StudentOracleNoSQLDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDoubleWrapper newStudent = em.find(StudentOracleNoSQLDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Double.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoubleWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Double.class));\n        q.setParameter(2, getMaxValue(Double.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Double.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Double.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLDoubleWrapper studentMax = em.find(StudentOracleNoSQLDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentOracleNoSQLDoubleWrapper.class, getMaxValue(Double.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLDoubleWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDoubleWrapper newStudent = em.find(StudentOracleNoSQLDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLDoubleWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLDoubleWrapper newStudent = em.find(StudentOracleNoSQLDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLDoubleWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Double.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLDoubleWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentOracleNoSQLDoubleWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLDoubleWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Double.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Double.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/StudentOracleNoSQLFloatPrimitiveTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLFloatPrimitive;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class StudentOracleNoSQLFloatPrimitiveTest extends OracleNoSQLBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"oracleNosqlDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of float\n        StudentOracleNoSQLFloatPrimitive studentMax = new StudentOracleNoSQLFloatPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Float) getMaxValue(float.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of float\n        StudentOracleNoSQLFloatPrimitive studentMin = new StudentOracleNoSQLFloatPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Float) getMinValue(float.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of float\n        StudentOracleNoSQLFloatPrimitive student = new StudentOracleNoSQLFloatPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Float) getRandomValue(float.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLFloatPrimitive studentMax = em.find(StudentOracleNoSQLFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLFloatPrimitive studentMin = em.find(StudentOracleNoSQLFloatPrimitive.class, getMinValue(float.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLFloatPrimitive student = em.find(StudentOracleNoSQLFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentOracleNoSQLFloatPrimitive student = em.find(StudentOracleNoSQLFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLFloatPrimitive newStudent = em.find(StudentOracleNoSQLFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(float.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.id between \" + getMinValue(float.class) + \" and \"\n                + getMaxValue(float.class);\n        // query =\n        // \"Select s From StudentOracleNoSQLFloatPrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        // q.setParameter(1, getMinValue(float.class));\n        // q.setParameter(2, getMaxValue(float.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Float) getMinValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLFloatPrimitive studentMax = em.find(StudentOracleNoSQLFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentOracleNoSQLFloatPrimitive.class, getMaxValue(float.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLFloatPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLFloatPrimitive newStudent = em.find(StudentOracleNoSQLFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLFloatPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLFloatPrimitive newStudent = em.find(StudentOracleNoSQLFloatPrimitive.class, getRandomValue(float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLFloatPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentOracleNoSQLFloatPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLFloatPrimitive student : students)\n        {\n            if (student.getId() == ((Float) getMaxValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Float) getMinValue(float.class)).floatValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/StudentOracleNoSQLFloatWrapperTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLFloatWrapper;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class StudentOracleNoSQLFloatWrapperTest extends OracleNoSQLBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"oracleNosqlDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Float\n        StudentOracleNoSQLFloatWrapper studentMax = new StudentOracleNoSQLFloatWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Float) getMaxValue(Float.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Float\n        StudentOracleNoSQLFloatWrapper studentMin = new StudentOracleNoSQLFloatWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Float) getMinValue(Float.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Float\n        StudentOracleNoSQLFloatWrapper student = new StudentOracleNoSQLFloatWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Float) getRandomValue(Float.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLFloatWrapper studentMax = em.find(StudentOracleNoSQLFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLFloatWrapper studentMin = em.find(StudentOracleNoSQLFloatWrapper.class, getMinValue(Float.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLFloatWrapper student = em.find(StudentOracleNoSQLFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentOracleNoSQLFloatWrapper student = em.find(StudentOracleNoSQLFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLFloatWrapper newStudent = em.find(StudentOracleNoSQLFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Float.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Float.class));\n        q.setParameter(2, getMaxValue(Float.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Float.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Float.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLFloatWrapper studentMax = em.find(StudentOracleNoSQLFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentOracleNoSQLFloatWrapper.class, getMaxValue(Float.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLFloatWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLFloatWrapper newStudent = em.find(StudentOracleNoSQLFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLFloatWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLFloatWrapper newStudent = em.find(StudentOracleNoSQLFloatWrapper.class, getRandomValue(Float.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Float.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLFloatWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLFloatWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Float.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLFloatWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentOracleNoSQLFloatWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLFloatWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Float.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Float.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Float.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/StudentOracleNoSQLIntTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLInt;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class StudentOracleNoSQLIntTest extends OracleNoSQLBase\n{\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"oracleNosqlDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of int\n        StudentOracleNoSQLInt studentMax = new StudentOracleNoSQLInt();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(int.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of int\n        StudentOracleNoSQLInt studentMin = new StudentOracleNoSQLInt();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Integer) getMinValue(int.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of int\n        StudentOracleNoSQLInt student = new StudentOracleNoSQLInt();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(int.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLInt studentMax = em.find(StudentOracleNoSQLInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLInt studentMin = em.find(StudentOracleNoSQLInt.class, getMinValue(int.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLInt student = em.find(StudentOracleNoSQLInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentOracleNoSQLInt student = em.find(StudentOracleNoSQLInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLInt newStudent = em.find(StudentOracleNoSQLInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInt student : students)\n        {\n            Assert.assertEquals(getMinValue(int.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInt> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.id between \" + getMinValue(int.class) + \" and \"\n                + getMaxValue(int.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Integer) getMinValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLInt studentMax = em.find(StudentOracleNoSQLInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentOracleNoSQLInt.class, getMaxValue(int.class));\n        Assert.assertNull(studentMax);\n        testPersist(useSameEm);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLInt s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLInt newStudent = em.find(StudentOracleNoSQLInt.class, getRandomValue(int.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLInt s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLInt newStudent = em.find(StudentOracleNoSQLInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInt s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLInt s \";\n        Query q = em.createQuery(query);\n        List<StudentOracleNoSQLInt> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Integer) getMinValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/StudentOracleNoSQLIntegerTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLInteger;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class StudentOracleNoSQLIntegerTest extends OracleNoSQLBase\n{\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"oracleNosqlDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of integer\n        StudentOracleNoSQLInteger studentMax = new StudentOracleNoSQLInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(Integer.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of integer\n        StudentOracleNoSQLInteger studentMin = new StudentOracleNoSQLInteger();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Integer) getMinValue(Integer.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of integer\n        StudentOracleNoSQLInteger student = new StudentOracleNoSQLInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(Integer.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLInteger studentMax = em.find(StudentOracleNoSQLInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLInteger studentMin = em.find(StudentOracleNoSQLInteger.class, getMinValue(Integer.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLInteger student = em.find(StudentOracleNoSQLInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentOracleNoSQLInteger student = em.find(StudentOracleNoSQLInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLInteger newStudent = em.find(StudentOracleNoSQLInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(Integer.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInteger> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Integer.class));\n        q.setParameter(2, getMaxValue(Integer.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Integer.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLInteger studentMax = em.find(StudentOracleNoSQLInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentOracleNoSQLInteger.class, getMaxValue(Integer.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLInteger s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLInteger newStudent = em.find(StudentOracleNoSQLInteger.class, getRandomValue(Integer.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLInteger s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLInteger newStudent = em.find(StudentOracleNoSQLInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLInteger s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentOracleNoSQLInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Integer.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/StudentOracleNoSQLLongPrimitiveTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLLongPrimitive;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class StudentOracleNoSQLLongPrimitiveTest extends OracleNoSQLBase\n{\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"oracleNosqlDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of long\n        StudentOracleNoSQLLongPrimitive studentMax = new StudentOracleNoSQLLongPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of long\n        StudentOracleNoSQLLongPrimitive studentMin = new StudentOracleNoSQLLongPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Long) getMinValue(long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of long\n        StudentOracleNoSQLLongPrimitive student = new StudentOracleNoSQLLongPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLLongPrimitive studentMax = em.find(StudentOracleNoSQLLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLLongPrimitive studentMin = em.find(StudentOracleNoSQLLongPrimitive.class, getMinValue(long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLLongPrimitive student = em.find(StudentOracleNoSQLLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentOracleNoSQLLongPrimitive student = em.find(StudentOracleNoSQLLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLLongPrimitive newStudent = em.find(StudentOracleNoSQLLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(long.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.id between \" + getMinValue(long.class) + \" and \"\n                + getMaxValue(long.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Long) getMinValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLLongPrimitive studentMax = em.find(StudentOracleNoSQLLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentOracleNoSQLLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLLongPrimitive s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLLongPrimitive newStudent = em.find(StudentOracleNoSQLLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLLongPrimitive s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLLongPrimitive newStudent = em.find(StudentOracleNoSQLLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongPrimitive s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLLongPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentOracleNoSQLLongPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Long) getMinValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/StudentOracleNoSQLLongWrapperTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLLongWrapper;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class StudentOracleNoSQLLongWrapperTest extends OracleNoSQLBase\n{\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"oracleNosqlDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert min value of Long\n        StudentOracleNoSQLLongWrapper studentMin = new StudentOracleNoSQLLongWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Long) getMinValue(Long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Long\n        StudentOracleNoSQLLongWrapper student = new StudentOracleNoSQLLongWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(Long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Long\n        StudentOracleNoSQLLongWrapper studentMax = new StudentOracleNoSQLLongWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(Long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLLongWrapper studentMax = em.find(StudentOracleNoSQLLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLLongWrapper studentMin = em.find(StudentOracleNoSQLLongWrapper.class, getMinValue(Long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLLongWrapper student = em.find(StudentOracleNoSQLLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentOracleNoSQLLongWrapper student = em.find(StudentOracleNoSQLLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLLongWrapper newStudent = em.find(StudentOracleNoSQLLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Long.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Long.class));\n        q.setParameter(2, getMaxValue(Long.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Long.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLLongWrapper studentMax = em.find(StudentOracleNoSQLLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentOracleNoSQLLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLLongWrapper s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLLongWrapper newStudent = em.find(StudentOracleNoSQLLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLLongWrapper s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLLongWrapper newStudent = em.find(StudentOracleNoSQLLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLLongWrapper s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLLongWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentOracleNoSQLLongWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Long.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/StudentOracleNoSQLSqlDateTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport java.sql.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLSqlDate;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class StudentOracleNoSQLSqlDateTest extends OracleNoSQLBase\n{\n\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"oracleNosqlDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentOracleNoSQLSqlDate student = new StudentOracleNoSQLSqlDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue(Date.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Date\n        StudentOracleNoSQLSqlDate studentMax = new StudentOracleNoSQLSqlDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue(Date.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Date\n        StudentOracleNoSQLSqlDate studentMin = new StudentOracleNoSQLSqlDate();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Date) getMinValue(Date.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLSqlDate studentMax = em.find(StudentOracleNoSQLSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLSqlDate studentMin = em.find(StudentOracleNoSQLSqlDate.class, getMinValue(Date.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLSqlDate student = em.find(StudentOracleNoSQLSqlDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentOracleNoSQLSqlDate student = em.find(StudentOracleNoSQLSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLSqlDate newStudent = em.find(StudentOracleNoSQLSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLSqlDate student : students)\n        {\n            Assert.assertEquals(getMinValue(Date.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLSqlDate> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.id between \" + getMinValue(Date.class) + \" and \"\n                + getMaxValue(Date.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Date.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLSqlDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLSqlDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLSqlDate studentMax = em.find(StudentOracleNoSQLSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentOracleNoSQLSqlDate.class, getMaxValue(Date.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLSqlDate s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLSqlDate newStudent = em.find(StudentOracleNoSQLSqlDate.class, getRandomValue(Date.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLSqlDate s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLSqlDate newStudent = em.find(StudentOracleNoSQLSqlDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLSqlDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLSqlDate s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLSqlDate s \";\n        Query q = em.createQuery(query);\n        List<StudentOracleNoSQLSqlDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue(Date.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/datatypes/tests/StudentOracleNoSQLStringTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.datatypes.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLString;\n\n/**\n * @author vivek.mishra\n *\n */\npublic class StudentOracleNoSQLStringTest extends OracleNoSQLBase\n{\n    private static final String keyspace = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"oracleNosqlDataTypeTest\");\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        // testFindByQuery(true);\n        // testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        // testFindByQuery(false);\n        // testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of String\n        StudentOracleNoSQLString studentMax = new StudentOracleNoSQLString();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((String) getMaxValue(String.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of String\n        StudentOracleNoSQLString studentMin = new StudentOracleNoSQLString();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((String) getMinValue(String.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of String\n        StudentOracleNoSQLString student = new StudentOracleNoSQLString();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((String) getRandomValue(String.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLString studentMax = em.find(StudentOracleNoSQLString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLString studentMin = em.find(StudentOracleNoSQLString.class, getMinValue(String.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLString student = em.find(StudentOracleNoSQLString.class, getRandomValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentOracleNoSQLString student = em.find(StudentOracleNoSQLString.class, getMaxValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLString newStudent = em.find(StudentOracleNoSQLString.class, getMaxValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLString student : students)\n        {\n            Assert.assertEquals(getMinValue(String.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLString> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.id between \" + getMinValue(String.class) + \" and \"\n                + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.name = Kuldeep and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentOracleNoSQLString studentMax = em.find(StudentOracleNoSQLString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentOracleNoSQLString.class, getMaxValue(String.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentOracleNoSQLString s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLString newStudent = em.find(StudentOracleNoSQLString.class, getRandomValue(String.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentOracleNoSQLString s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentOracleNoSQLString newStudent = em.find(StudentOracleNoSQLString.class, getRandomValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.name = Amresh and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.name = Kuldeep and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentOracleNoSQLString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentOracleNoSQLString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentOracleNoSQLString s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentOracleNoSQLString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentOracleNoSQLString s \";\n        Query q = em.createQuery(query);\n        List<StudentOracleNoSQLString> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentOracleNoSQLString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(String.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(String.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/AddressOTOOracleNoSQL.java",
    "content": "package com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"ADDRESS_OTO\", schema = \"OracleNoSqlTests@twikvstore\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressOTOOracleNoSQL\n{\n\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private Double addressId;\n\n    @Column(name = \"street\")\n    private String street;\n\n    public AddressOTOOracleNoSQL()\n    {\n\n    }\n\n    public AddressOTOOracleNoSQL(Double addressId, String address)\n    {\n        this.addressId = addressId;\n        this.street = address;\n    }\n\n    public AddressOTOOracleNoSQL(Double addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    /**\n     * @return the street\n     */\n    public String getStreet()\n    {\n        return street;\n    }\n\n    /**\n     * @param street\n     *            the street to set\n     */\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    /**\n     * @param addressId\n     *            the addressId to set\n     */\n    public void setAddressId(Double addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public Double getAddressId()\n    {\n        return addressId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/AddressOracleNoSqlMTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"AddressOracleNoSqlMTM\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressOracleNoSqlMTM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/AddressOracleNoSqlMTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"AddressOracleNoSqlMTO\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressOracleNoSqlMTO\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/AddressOracleNoSqlOTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"AddressOracleNoSqlOTM\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressOracleNoSqlOTM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/AddressOracleNoSqlOTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"AddressOracleNoSqlOTO\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressOracleNoSqlOTO\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/Month.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\npublic enum Month\n{\n    JAN, FEB, MARCH, APRIL, MAY, JUNE;\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/Office.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Office Embeddable object\n * \n * @author amresh.singh\n */\n@Embeddable\n@IndexCollection(columns = { @Index(indexName = \"officeId\", name = \"officeId\"),\n        @Index(indexName = \"companyName\", name = \"companyName\"), @Index(indexName = \"location\", name = \"location\") })\npublic class Office\n{\n    @Column\n    private int officeId;\n\n    @Column\n    private String companyName;\n\n    @Column\n    private String location;\n\n    public Office()\n    {\n\n    }\n\n    public Office(int officeId, String companyName, String location)\n    {\n        this.officeId = officeId;\n        this.companyName = companyName;\n        this.location = location;\n    }\n\n    /**\n     * @return the officeId\n     */\n    public int getOfficeId()\n    {\n        return officeId;\n    }\n\n    /**\n     * @param officeId\n     *            the officeId to set\n     */\n    public void setOfficeId(int officeId)\n    {\n        this.officeId = officeId;\n    }\n\n    /**\n     * @return the companyName\n     */\n    public String getCompanyName()\n    {\n        return companyName;\n    }\n\n    /**\n     * @param companyName\n     *            the companyName to set\n     */\n    public void setCompanyName(String companyName)\n    {\n        this.companyName = companyName;\n    }\n\n    /**\n     * @return the location\n     */\n    public String getLocation()\n    {\n        return location;\n    }\n\n    /**\n     * @param location\n     *            the location to set\n     */\n    public void setLocation(String location)\n    {\n        this.location = location;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/OracleNoSqlAddressJTAEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"ADDRESS\")\npublic class OracleNoSqlAddressJTAEntity\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * \n     */\n    public OracleNoSqlAddressJTAEntity()\n    {\n    }\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/OracleNoSqlCompoundKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * @author vivek.mishra\n */\n@Embeddable\npublic class OracleNoSqlCompoundKey\n{\n    @Column\n    private String user_Id;\n\n    @Column\n    private int tweetId;\n\n    @Column\n    private String timeLineId;\n\n    /**\n     * \n     */\n    public OracleNoSqlCompoundKey()\n    {\n    }\n\n    /**\n     * @param userId\n     * @param tweetId\n     * @param timeLineId\n     */\n    public OracleNoSqlCompoundKey(String userId, int tweetId, String timeLineId)\n    {\n       this.user_Id = userId;\n        this.tweetId = tweetId;\n        this.timeLineId = timeLineId;\n    }\n\n    /**\n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return user_Id;\n    }\n\n    /**\n     * @return the tweetId\n     */\n    public int getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * @return the timeLineId\n     */\n    public String getTimeLineId()\n    {\n        return timeLineId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/OracleNoSqlEmbeddedUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class OracleNoSqlEmbeddedUser.\n * \n * @author vivek.mishra\n */\n\n@Entity\n@Table(name = \"Embedded_User\")\npublic class OracleNoSqlEmbeddedUser\n{\n\n    /** The user id. */\n    @Id\n    private String userId;\n\n    /** The embeddable. */\n    @Embedded\n    private OracleNoSqlCompoundKey embeddable;\n\n    /** The tweet body. */\n    @Column\n    private String tweetBody;\n\n    /** The tweet date. */\n    @Column\n    private Date tweetDate;\n\n    /**\n     * Instantiates a new redis embedded user.\n     */\n    public OracleNoSqlEmbeddedUser()\n    {\n    }\n\n    /**\n     * Instantiates a new redis embedded user.\n     * \n     * @param userId\n     *            the user id\n     */\n    public OracleNoSqlEmbeddedUser(String userId)\n    {\n        this.userId = userId;\n    }\n\n    /**\n     * Gets the tweet body.\n     * \n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * Gets the tweet date.\n     * \n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * Sets the tweet body.\n     * \n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * Sets the tweet date.\n     * \n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n    /**\n     * Gets the user id.\n     * \n     * @return the user id\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * Gets the embeddable.\n     * \n     * @return the embeddable\n     */\n    public OracleNoSqlCompoundKey getEmbeddable()\n    {\n        return embeddable;\n    }\n\n    /**\n     * Sets the embeddable.\n     * \n     * @param embeddable\n     *            the new embeddable\n     */\n    public void setEmbeddable(OracleNoSqlCompoundKey embeddable)\n    {\n        this.embeddable = embeddable;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/OracleNoSqlPersonJTAEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"PERSONNEL\")\npublic class OracleNoSqlPersonJTAEntity\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private OracleNoSqlAddressJTAEntity address;\n\n    /**\n     * \n     */\n    public OracleNoSqlPersonJTAEntity()\n    {\n    }\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public OracleNoSqlAddressJTAEntity getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(OracleNoSqlAddressJTAEntity address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/OracleNoSqlPrimeUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n */\n\n@Entity\n@Table(name = \"User\")\n\n@IndexCollection(columns = {\n        @Index(indexName = \"user_tweet_timeline\", name = \"key.user_Id,key.tweetId,key.timeLineId\", type = \"composite\"),\n        @Index(indexName = \"user_tweet\", name = \"key.user_Id,key.tweetId\", type = \"composite\") })\npublic class OracleNoSqlPrimeUser\n{\n\n    @EmbeddedId\n    private OracleNoSqlCompoundKey key;\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private Date tweetDate;\n\n    public OracleNoSqlPrimeUser()\n    {\n    }\n\n    public OracleNoSqlPrimeUser(OracleNoSqlCompoundKey key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the key\n     */\n    public OracleNoSqlCompoundKey getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/OracleNoSqlToken.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"tokens\")\n@IndexCollection(columns = { @Index(name = \"tokenName\") })\npublic class OracleNoSqlToken\n{\n    @Id\n    @Column(name = \"token_id\")\n    private String id;\n\n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"client_id\")\n    private OracleNoSqlTokenClient client;\n\n    @Column\n    private String tokenName;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public OracleNoSqlTokenClient getClient()\n    {\n        return client;\n    }\n\n    public void setClient(OracleNoSqlTokenClient client)\n    {\n        this.client = client;\n    }\n\n    public String getTokenName()\n    {\n        return tokenName;\n    }\n\n    public void setTokenName(String tokenName)\n    {\n        this.tokenName = tokenName;\n    }\n\n}"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/OracleNoSqlTokenClient.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"client\")\npublic class OracleNoSqlTokenClient\n{\n\n    @Id\n    @Column(name = \"client_id\")\n    private String id;\n\n    @Column(name = \"client_name\")\n    private String clientName;\n\n    @OneToMany(mappedBy = \"client\", fetch = FetchType.EAGER)\n    private Set<OracleNoSqlToken> tokens;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public String getClientName()\n    {\n        return clientName;\n    }\n\n    public void setClientName(String clientName)\n    {\n        this.clientName = clientName;\n    }\n\n    public Set<OracleNoSqlToken> getTokens()\n    {\n        return tokens;\n    }\n\n    public void setTokens(Set<OracleNoSqlToken> tokens)\n    {\n        this.tokens = tokens;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/PersonEmbeddedKVStore.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Person entity with one embedded attribute\n * \n * @author amresh.singh\n */\n@Entity\n@Table(name = \"PERSON_EMBEDDED\", schema = \"OracleNoSqlTests@twikvstore\")\n@IndexCollection(columns = { @Index(indexName = \"compositeIdx\", name = \"personId,age\", type = \"composite\"),\n        @Index(indexName = \"personName\", name = \"personName\"), @Index(indexName = \"age\", name = \"age\"),\n        @Index(indexName = \"officeId\", name = \"office.officeId\",type = \"composite\"),\n        @Index(indexName = \"companyName\", name = \"office.companyName\",type = \"composite\"),\n        @Index(indexName = \"location\", name = \"office.location\",type = \"composite\") })\npublic class PersonEmbeddedKVStore\n{\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Embedded\n    private Office office;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the office\n     */\n    public Office getOffice()\n    {\n        return office;\n    }\n\n    /**\n     * @param office\n     *            the office to set\n     */\n    public void setOffice(Office office)\n    {\n        this.office = office;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(Integer age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/PersonKVStore.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.NamedQueries;\nimport javax.persistence.NamedQuery;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * \ntable create -name PERSON\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nadd-field -type integer -name AGE\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PERSON -wait\n */\n\n/**\n * Entity class for Person\n * \n * @author amresh.singh\n */\n@Entity\n@Table(name = \"PERSON_KV_STORE\", schema = \"OracleNoSqlTests@twikvstore\")\n@IndexCollection(columns = { @Index(indexName = \"personName\", name = \"personName\"),\n        @Index(indexName = \"age\", name = \"age\"),\n        @Index(indexName = \"personId_age\", name = \"personId,age\", type = \"composite\") })\n@NamedQueries(value = { @NamedQuery(name = \"findByAge\", query = \"Select p from PersonKVStore p where p.age=:age\"),\n        @NamedQuery(name = \"findByName\", query = \"Select p from PersonKVStore p where p.personName = ?1\") })\npublic class PersonKVStore\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/PersonOTOOracleNoSQL.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Person.\n * @author vivek.mishra\n */\n@Entity\n@Table(name = \"PERSON_OTO\", schema = \"OracleNoSqlTests@twikvstore\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\npublic class PersonOTOOracleNoSQL\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressOTOOracleNoSQL address;\n\n    public PersonOTOOracleNoSQL()\n    {\n\n    }\n\n    public PersonOTOOracleNoSQL(String personId, String personName, Integer age, AddressOTOOracleNoSQL address)\n    {\n        this.personId = personId;\n        this.personName = personName;\n        this.age = age;\n        this.address = address;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public AddressOTOOracleNoSQL getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressOTOOracleNoSQL address)\n    {\n        this.address = address;\n    }\n\n    public void setAge(Integer age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/PersonOracleNoSQLAllDataType.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.sql.Time;\nimport java.sql.Timestamp;\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\n/**\n * The Class Person.\n */\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"PERSON_ALL_DATA_TYPE\", schema = \"OracleNoSqlTests@twikvstore\")\npublic class PersonOracleNoSQLAllDataType\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private long personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @Column(name = \"IS_EXCEPTIONAL\")\n    private boolean isExceptional;\n\n    @Column(name = \"AGE\")\n    private int age;\n\n    @Column(name = \"GRADE\")\n    private char grade; // A,B,C,D,E,F for i to vi\n\n    @Column(name = \"DIGITAL_SIGNATURE\")\n    private byte digitalSignature;\n\n    @Column(name = \"RATING\")\n    private short rating; // 1-10\n\n    @Column(name = \"COMPLIANCE\")\n    private float compliance;\n\n    @Column(name = \"HEIGHT\")\n    private double height;\n\n    // Date-time types\n    @Column(name = \"ENROLMENT_DATE\")\n    @Temporal(TemporalType.DATE)\n    private java.util.Date enrolmentDate;\n\n    @Column(name = \"ENROLMENT_TIME\")\n    @Temporal(TemporalType.TIME)\n    private java.util.Date enrolmentTime;\n\n    @Column(name = \"JOINING_DATE_TIME\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private java.util.Date joiningDateAndTime;\n\n    // Wrapper types\n    @Column(name = \"YEARS_SPENT\")\n    private Integer yearsSpent;\n\n    @Column(name = \"UNIQUE_ID\")\n    private Long uniqueId;\n\n    @Column(name = \"MONTHLY_SALARY\")\n    private Double monthlySalary;\n\n    @Column(name = \"BIRTH_DAY\")\n    private java.util.Date birthday;\n\n    @Column(name = \"BIRTH_TIME\")\n    private java.util.Date birthtime;\n\n    @Column(name = \"ANNIVERSARY\")\n    private java.util.Date anniversary;\n\n    @Column(name = \"JOB_ATTEMPTS\")\n    private BigInteger jobAttempts;\n\n    @Column(name = \"ACCUMULATED_WEALTH\")\n    private BigDecimal accumulatedWealth;\n\n    @Column(name = \"GRADUATION_DAY\")\n    private Calendar graduationDay;\n\n    public PersonOracleNoSQLAllDataType()\n    {\n    }\n\n    public PersonOracleNoSQLAllDataType(long personId, String personName, boolean isExceptional, int age, char grade,\n            byte digitalSignature, short rating, float compliance, double height, Date enrolmentDate,\n            Date enrolmentTime, Date joiningDateAndTime, Integer yearsSpent, Long uniqueId, Double monthlySalary,\n            java.sql.Date birthday, Time birthtime, Timestamp anniversary, BigInteger jobAttempts,\n            BigDecimal accumulatedWealth, Calendar graduationDay)\n    {\n        this.personId = personId;\n        this.personName = personName;\n        this.isExceptional = isExceptional;\n        this.age = age;\n        this.grade = grade;\n        this.digitalSignature = digitalSignature;\n        this.rating = rating;\n        this.compliance = compliance;\n        this.height = height;\n        this.enrolmentDate = enrolmentDate;\n        this.enrolmentTime = enrolmentTime;\n        this.joiningDateAndTime = joiningDateAndTime;\n        this.yearsSpent = yearsSpent;\n        this.uniqueId = uniqueId;\n        this.monthlySalary = monthlySalary;\n        this.birthday = birthday;\n        this.birthtime = birthtime;\n        this.anniversary = anniversary;\n        this.jobAttempts = jobAttempts;\n        this.accumulatedWealth = accumulatedWealth;\n        this.graduationDay = graduationDay;\n    }\n\n    /**\n     * @return the personId\n     */\n    public long getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * @param personId\n     *            the personId to set\n     */\n    public void setPersonId(long personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the personName\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * @param personName\n     *            the personName to set\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * @return the isExceptional\n     */\n    public boolean isExceptional()\n    {\n        return isExceptional;\n    }\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    public void setExceptional(boolean isExceptional)\n    {\n        this.isExceptional = isExceptional;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the grade\n     */\n    public char getGrade()\n    {\n        return grade;\n    }\n\n    /**\n     * @param grade\n     *            the grade to set\n     */\n    public void setGrade(char grade)\n    {\n        this.grade = grade;\n    }\n\n    /**\n     * @return the digitalSignature\n     */\n    public byte getDigitalSignature()\n    {\n        return digitalSignature;\n    }\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    public void setDigitalSignature(byte digitalSignature)\n    {\n        this.digitalSignature = digitalSignature;\n    }\n\n    /**\n     * @return the rating\n     */\n    public short getRating()\n    {\n        return rating;\n    }\n\n    /**\n     * @param rating\n     *            the rating to set\n     */\n    public void setRating(short rating)\n    {\n        this.rating = rating;\n    }\n\n    /**\n     * @return the compliance\n     */\n    public float getCompliance()\n    {\n        return compliance;\n    }\n\n    /**\n     * @param compliance\n     *            the compliance to set\n     */\n    public void setCompliance(float compliance)\n    {\n        this.compliance = compliance;\n    }\n\n    /**\n     * @return the height\n     */\n    public double getHeight()\n    {\n        return height;\n    }\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    public void setHeight(double height)\n    {\n        this.height = height;\n    }\n\n    /**\n     * @return the enrolmentDate\n     */\n    public java.util.Date getEnrolmentDate()\n    {\n        return enrolmentDate;\n    }\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    public void setEnrolmentDate(java.util.Date enrolmentDate)\n    {\n        this.enrolmentDate = enrolmentDate;\n    }\n\n    /**\n     * @return the enrolmentTime\n     */\n    public java.util.Date getEnrolmentTime()\n    {\n        return enrolmentTime;\n    }\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    public void setEnrolmentTime(java.util.Date enrolmentTime)\n    {\n        this.enrolmentTime = enrolmentTime;\n    }\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    public java.util.Date getJoiningDateAndTime()\n    {\n        return joiningDateAndTime;\n    }\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    public void setJoiningDateAndTime(java.util.Date joiningDateAndTime)\n    {\n        this.joiningDateAndTime = joiningDateAndTime;\n    }\n\n    /**\n     * @return the yearsSpent\n     */\n    public Integer getYearsSpent()\n    {\n        return yearsSpent;\n    }\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    public void setYearsSpent(Integer yearsSpent)\n    {\n        this.yearsSpent = yearsSpent;\n    }\n\n    /**\n     * @return the uniqueId\n     */\n    public Long getUniqueId()\n    {\n        return uniqueId;\n    }\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    public void setUniqueId(Long uniqueId)\n    {\n        this.uniqueId = uniqueId;\n    }\n\n    /**\n     * @return the monthlySalary\n     */\n    public Double getMonthlySalary()\n    {\n        return monthlySalary;\n    }\n\n    /**\n     * @param monthlySalary\n     *            the monthlySalary to set\n     */\n    public void setMonthlySalary(Double monthlySalary)\n    {\n        this.monthlySalary = monthlySalary;\n    }\n\n    /**\n     * @return the birthday\n     */\n    public java.util.Date getBirthday()\n    {\n        return birthday;\n    }\n\n    /**\n     * @param birthday\n     *            the birthday to set\n     */\n    public void setBirthday(java.sql.Date birthday)\n    {\n        this.birthday = birthday;\n    }\n\n    /**\n     * @return the birthtime\n     */\n    public java.util.Date getBirthtime()\n    {\n        return birthtime;\n    }\n\n    /**\n     * @param birthtime\n     *            the birthtime to set\n     */\n    public void setBirthtime(java.util.Date birthtime)\n    {\n        this.birthtime = birthtime;\n    }\n\n    /**\n     * @return the anniversary\n     */\n    public java.util.Date getAnniversary()\n    {\n        return anniversary;\n    }\n\n    /**\n     * @param anniversary\n     *            the anniversary to set\n     */\n    public void setAnniversary(java.util.Date anniversary)\n    {\n        this.anniversary = anniversary;\n    }\n\n    /**\n     * @return the jobAttempts\n     */\n    public BigInteger getJobAttempts()\n    {\n        return jobAttempts;\n    }\n\n    /**\n     * @param jobAttempts\n     *            the jobAttempts to set\n     */\n    public void setJobAttempts(BigInteger jobAttempts)\n    {\n        this.jobAttempts = jobAttempts;\n    }\n\n    /**\n     * @return the accumulatedWealth\n     */\n    public BigDecimal getAccumulatedWealth()\n    {\n        return accumulatedWealth;\n    }\n\n    /**\n     * @param accumulatedWealth\n     *            the accumulatedWealth to set\n     */\n    public void setAccumulatedWealth(BigDecimal accumulatedWealth)\n    {\n        this.accumulatedWealth = accumulatedWealth;\n    }\n\n    /**\n     * @return the graduationDay\n     */\n    public Calendar getGraduationDay()\n    {\n        return graduationDay;\n    }\n\n    /**\n     * @param graduationDay\n     *            the graduationDay to set\n     */\n    public void setGraduationDay(Calendar graduationDay)\n    {\n        this.graduationDay = graduationDay;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/PersonOracleNoSql.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Person.\n * @author vivek.mishra\n */\n@Entity\n@Table(name = \"PERSON_ORACLE_NOSQL\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\") })\npublic class PersonOracleNoSql\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"DAY_ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    @Column(name = \"MONTH_ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Month month;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public Day getDay()\n    {\n        return day;\n    }\n\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n\n    public Month getMonth()\n    {\n        return month;\n    }\n\n    public void setMonth(Month month)\n    {\n        this.month = month;\n    }\n\n    public enum Day\n    {\n        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/PersonOracleNoSqlMTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"PersonOracleNoSqlMTM\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonOracleNoSqlMTM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"PERSONNEL_ADDRESS\", schema = \"OracleNoSqlTests\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Set<AddressOracleNoSqlMTM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressOracleNoSqlMTM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressOracleNoSqlMTM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/PersonOracleNoSqlMTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"PersonOracleNoSqlMTO\")\npublic class PersonOracleNoSqlMTO\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressOracleNoSqlMTO address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressOracleNoSqlMTO getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressOracleNoSqlMTO address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/PersonOracleNoSqlOTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"PersonOracleNoSqlOTM\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonOracleNoSqlOTM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<AddressOracleNoSqlOTM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressOracleNoSqlOTM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressOracleNoSqlOTM> addresses)\n    {\n        this.addresses = addresses;\n    }\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/PersonOracleNoSqlOTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n *\n */\n@Entity\n@Table(name = \"PersonOracleNoSqlOTO\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonOracleNoSqlOTO\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressOracleNoSqlOTO address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressOracleNoSqlOTO getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressOracleNoSqlOTO address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/UserInformation.java",
    "content": "package com.impetus.client.oraclenosql.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"UserInformation\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class UserInformation\n{\n    @Id\n    private String id;\n\n    @Column\n    private String name;\n\n    @Column\n    private int age;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/entities/UserProfile.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.oraclenosql.entities;\n\nimport java.io.File;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * \ntable create -name USER_PROFILE\nadd-field -type integer -name USER_ID\nadd-field -type string -name USER_NAME\nadd-field -type binary -name PROFILE_PICTURE\nprimary-key -field USER_ID\nexit\nplan add-table -name USER_PROFILE -wait\n\n */\n\n/**\n * UserProfile entity class\n * \n * @author amresh.singh\n */\n@Entity\n@Table(name = \"USER_PROFILE\", schema = \"OracleNoSqlTests@twikvstore\")\n@IndexCollection(columns = { @Index(name = \"userName\") })\npublic class UserProfile\n{\n    @Id\n    @Column(name = \"USER_ID\")\n    private int userId;\n\n    @Column(name = \"USER_NAME\")\n    private String userName;\n\n    @Column(name = \"PROFILE_PICTURE\")\n    private File profilePicture;\n\n    public UserProfile()\n    {\n\n    }\n\n    public UserProfile(int userId, String userName, File profilePicture)\n    {\n        super();\n        this.userId = userId;\n        this.userName = userName;\n        this.profilePicture = profilePicture;\n    }\n\n    /**\n     * @return the userId\n     */\n    public int getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * @param userId\n     *            the userId to set\n     */\n    public void setUserId(int userId)\n    {\n        this.userId = userId;\n    }\n\n    /**\n     * @return the userName\n     */\n    public String getUserName()\n    {\n        return userName;\n    }\n\n    /**\n     * @param userName\n     *            the userName to set\n     */\n    public void setUserName(String userName)\n    {\n        this.userName = userName;\n    }\n\n    /**\n     * @return the profilePicture\n     */\n    public File getProfilePicture()\n    {\n        return profilePicture;\n    }\n\n    /**\n     * @param profilePicture\n     *            the profilePicture to set\n     */\n    public void setProfilePicture(File profilePicture)\n    {\n        this.profilePicture = profilePicture;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/schemamanager/OracleNoSQLSchemaGenerationTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.schemamanager;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport oracle.kv.KVStore;\nimport oracle.kv.KVStoreConfig;\nimport oracle.kv.KVStoreFactory;\nimport oracle.kv.table.Table;\nimport oracle.kv.table.TableAPI;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\n\n/**\n * The Class OracleNoSQLSchemaGenerationTest.\n * \n * @author devender.yadav\n * \n */\npublic class OracleNoSQLSchemaGenerationTest\n{\n\n    /** The Constant _PU. */\n    private static final String _PU = \"oracleNosqlSchemaGeneration\";\n\n    /** The Constant STORE_NAME. */\n    private static final String STORE_NAME = \"OracleNoSqlTests\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The kv store. */\n    private static KVStore kvStore;\n\n    /** The table api. */\n    private static TableAPI tableAPI;\n\n    /** The property map. */\n    private Map<String, String> propertyMap = new HashMap<String, String>();\n\n    /**\n     * Sets the upbefore class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpbeforeClass() throws Exception\n    {\n        kvStore = KVStoreFactory.getStore(new KVStoreConfig(STORE_NAME, \"localhost:5000\"));\n        tableAPI = kvStore.getTableAPI();\n        tableAPI.executeSync(\"DROP TABLE IF EXISTS ONS_USER\");\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        tableAPI.executeSync(\"DROP TABLE IF EXISTS ONS_USER\");\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        kvStore.close();\n    }\n\n    /**\n     * Test create.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testCreate() throws Exception\n    {\n        Table table = tableAPI.getTable(\"ONS_USER\");\n        Assert.assertNull(table);\n\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n\n        table = tableAPI.getTable(\"ONS_USER\");\n        Assert.assertNotNull(table);\n        List<String> list = table.getFields();\n        Assert.assertTrue(!list.isEmpty());\n        Assert.assertNotNull(table.getIndexes());\n    }\n\n    /**\n     * Test create drop.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testCreateDrop() throws Exception\n    {\n        Table table = tableAPI.getTable(\"ONS_USER\");\n        Assert.assertNull(table);\n\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create-drop\");\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n\n        table = tableAPI.getTable(\"ONS_USER\");\n        Assert.assertNotNull(table);\n        List<String> list = table.getFields();\n        Assert.assertTrue(!list.isEmpty());\n        Assert.assertNotNull(table.getIndexes());\n    }\n\n    /**\n     * Test update.\n     */\n    @Test\n    public void testUpdate()\n    {\n        Table table = tableAPI.getTable(\"ONS_USER\");\n        Assert.assertNull(table);\n\n        tableAPI.executeSync(\"CREATE TABLE ONS_USER(userId string, name string, age string, PRIMARY KEY(userId))\");\n        table = tableAPI.getTable(\"ONS_USER\");\n        Assert.assertNotNull(table);\n        List<String> list = table.getFields();\n\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"update\");\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n        table = tableAPI.getTable(\"ONS_USER\");\n        Assert.assertNotNull(table);\n        List<String> updatedList = table.getFields();\n        Assert.assertNotSame(list.size(), updatedList.size());\n        Assert.assertNotNull(table.getIndexes());\n    }\n\n    /**\n     * Test validate.\n     */\n    @Test\n    public void testValidate()\n    {\n        Table table = tableAPI.getTable(\"ONS_USER\");\n        Assert.assertNull(table);\n\n        try\n        {\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"validate\");\n            emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n            Assert.fail(\"SchemaGenerationException must be thrown as there is no entity with name ONS_USER\");\n        }\n        catch (Exception e)\n        {\n            Assert.assertNotNull(e);\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/schemamanager/OracleNoSQLUser.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.schemamanager;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class OracleNoSQLUser.\n * \n * @author devender.yadav\n */\n@Entity\n@Table(name = \"ONS_USER\")\n@IndexCollection(columns = { @Index(indexName = \"name\", name = \"name\"),\n        @Index(indexName = \"age\", name = \"age\")\n        ,@Index(indexName = \"email\", name = \"details.email\", type = \"composite\"),\n        @Index(indexName = \"address\", name = \"details.address\", type = \"composite\")\n})\npublic class OracleNoSQLUser\n{\n    /** The user id. */\n    @Id\n    @Column(name = \"userId\")\n    private int userId;\n\n    /** The name. */\n    @Column(name = \"NAME\")\n    private String name;\n\n    /** The age. */\n    @Column(name = \"age\")\n    private int age;\n\n    @Embedded\n    private UserDetails details;\n\n    /**\n     * Gets the user id.\n     * \n     * @return the user id\n     */\n    public int getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * Sets the user id.\n     * \n     * @param userId\n     *            the new user id\n     */\n    public void setUserId(int userId)\n    {\n        this.userId = userId;\n    }\n\n    /**\n     * Gets the name.\n     * \n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * Sets the name.\n     * \n     * @param name\n     *            the new name\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the details.\n     * \n     * @return the details\n     */\n    public UserDetails getDetails()\n    {\n        return details;\n    }\n\n    public void setDetails(UserDetails details)\n    {\n        this.details = details;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/schemamanager/OracleNoSQSchemaOperationTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.schemamanager;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\n\n/**\n * The Class OracleNoSQSchemaOperationTest.\n * \n * @author devender.yadav\n */\npublic class OracleNoSQSchemaOperationTest\n{\n    /** The Constant _PU. */\n    private static final String _PU = \"oracleNosqlSchemaGeneration\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The property map. */\n    private static Map<String, String> propertyMap = new HashMap<String, String>();\n\n    /** The true. */\n    private boolean T = true;\n\n    /** The false. */\n    private boolean F = false;\n\n    /**\n     * Sets the upbefore class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpbeforeClass() throws Exception\n    {\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create\");\n        emf = Persistence.createEntityManagerFactory(_PU, propertyMap);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test crud.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testCrud() throws Exception\n    {\n        OracleNoSQLUser user1 = createUser(1, \"dev\", 23, \"dev@abc.com\", \"noida\");\n        em.persist(user1);\n\n        em.clear();\n        OracleNoSQLUser user = em.find(OracleNoSQLUser.class, 1);\n        validateUser1(user);\n\n        user.setName(\"devender\");\n        em.merge(user);\n\n        em.clear();\n        OracleNoSQLUser u = em.find(OracleNoSQLUser.class, 1);\n        Assert.assertNotNull(u);\n        Assert.assertEquals(\"devender\", user.getName());\n\n        em.remove(user);\n\n        em.clear();\n        u = em.find(OracleNoSQLUser.class, 1);\n        Assert.assertNull(u);\n    }\n\n    /**\n     * Test query.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testQuery() throws Exception\n    {\n        OracleNoSQLUser user1 = createUser(1, \"dev\", 23, \"dev@abc.com\", \"noida\");\n        OracleNoSQLUser user2 = createUser(2, \"karthik\", 22, \"karthik@abc.com\", \"indore\");\n        OracleNoSQLUser user3 = createUser(3, \"pg\", 24, \"pg@abc.com\", \"blore\");\n\n        em.persist(user1);\n        em.persist(user2);\n        em.persist(user3);\n\n        List<OracleNoSQLUser> users = em.createQuery(\"select u from OracleNoSQLUser u\").getResultList();\n        Assert.assertNotNull(users);\n        Assert.assertEquals(3, users.size());\n        assertResults(users, T, T, T);\n\n        users = em.createQuery(\"select u from OracleNoSQLUser u where u.userId = 1\").getResultList();\n        Assert.assertNotNull(users);\n        Assert.assertEquals(1, users.size());\n        assertResults(users, T, F, F);\n\n        users = em.createQuery(\"select u from OracleNoSQLUser u where u.name = 'pg'\").getResultList();\n        Assert.assertNotNull(users);\n        Assert.assertEquals(1, users.size());\n        assertResults(users, F, F, T);\n\n        users = em.createQuery(\"select u from OracleNoSQLUser u where u.details.email = 'dev@abc.com'\").getResultList();\n        Assert.assertNotNull(users);\n        Assert.assertEquals(1, users.size());\n        assertResults(users, T, F, F);\n\n        em.remove(user1);\n        em.remove(user2);\n        em.remove(user3);\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n    }\n\n    /**\n     * Creates the user.\n     * \n     * @param id\n     *            the id\n     * @param name\n     *            the name\n     * @param age\n     *            the age\n     * @param email\n     *            the email\n     * @param address\n     *            the address\n     * @return the oracle no sql user\n     */\n    private OracleNoSQLUser createUser(int id, String name, int age, String email, String address)\n    {\n        OracleNoSQLUser user = new OracleNoSQLUser();\n        user.setUserId(id);\n        user.setName(name);\n        user.setAge(age);\n        UserDetails details = new UserDetails();\n        details.setEmail(email);\n        details.setAddress(address);\n        user.setDetails(details);\n        return user;\n    }\n\n    /**\n     * Removes the user.\n     */\n    private void removeUser()\n    {\n        OracleNoSQLUser user = em.find(OracleNoSQLUser.class, 1);\n        if (user != null)\n        {\n            em.remove(user);\n        }\n        user = em.find(OracleNoSQLUser.class, 2);\n        if (user != null)\n        {\n            em.remove(user);\n        }\n        user = em.find(OracleNoSQLUser.class, 3);\n        if (user != null)\n        {\n            em.remove(user);\n        }\n\n    }\n\n    /**\n     * Assert results.\n     * \n     * @param results\n     *            the results\n     * @param foundUser1\n     *            the found user1\n     * @param foundUser2\n     *            the found user2\n     * @param foundUser3\n     *            the found user3\n     */\n    private void assertResults(List<OracleNoSQLUser> results, boolean foundUser1, boolean foundUser2, boolean foundUser3)\n    {\n        for (OracleNoSQLUser User : results)\n        {\n            switch (User.getUserId())\n            {\n            case 1:\n                if (foundUser1)\n                    validateUser1(User);\n                else\n                    Assert.fail();\n                break;\n            case 2:\n                if (foundUser2)\n                    validateUser2(User);\n                else\n                    Assert.fail();\n                break;\n            case 3:\n                if (foundUser3)\n                    validateUser3(User);\n                else\n                    Assert.fail();\n                break;\n            }\n        }\n    }\n\n    /**\n     * Validate user1.\n     * \n     * @param user\n     *            the user\n     */\n    private void validateUser1(OracleNoSQLUser user)\n    {\n        Assert.assertNotNull(user);\n        Assert.assertEquals(\"dev\", user.getName());\n        Assert.assertEquals(23, user.getAge());\n        Assert.assertEquals(\"dev@abc.com\", user.getDetails().getEmail());\n        Assert.assertEquals(\"noida\", user.getDetails().getAddress());\n    }\n\n    /**\n     * Validate user2.\n     * \n     * @param user\n     *            the user\n     */\n    private void validateUser2(OracleNoSQLUser user)\n    {\n        Assert.assertNotNull(user);\n        Assert.assertEquals(\"karthik\", user.getName());\n        Assert.assertEquals(22, user.getAge());\n        Assert.assertEquals(\"karthik@abc.com\", user.getDetails().getEmail());\n        Assert.assertEquals(\"indore\", user.getDetails().getAddress());\n\n    }\n\n    /**\n     * Validate user3.\n     * \n     * @param user\n     *            the user\n     */\n    private void validateUser3(OracleNoSQLUser user)\n    {\n        Assert.assertNotNull(user);\n        Assert.assertEquals(\"pg\", user.getName());\n        Assert.assertEquals(24, user.getAge());\n        Assert.assertEquals(\"pg@abc.com\", user.getDetails().getEmail());\n        Assert.assertEquals(\"blore\", user.getDetails().getAddress());\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/client/oraclenosql/schemamanager/UserDetails.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.oraclenosql.schemamanager;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class UserDetails.\n * \n * @author devender.yadav\n */\n@Embeddable\n@IndexCollection(columns = { @Index(indexName = \"email\", name = \"email\"),\n        @Index(indexName = \"address\", name = \"address\") })\npublic class UserDetails\n{\n\n    /** The email. */\n    @Column(name = \"email\")\n    private String email;\n\n    /** The address. */\n    @Column(name = \"address\")\n    private String address;\n\n    /**\n     * Gets the email.\n     * \n     * @return the email\n     */\n    public String getEmail()\n    {\n        return email;\n    }\n\n    /**\n     * Sets the email.\n     * \n     * @param email\n     *            the new email\n     */\n    public void setEmail(String email)\n    {\n        this.email = email;\n    }\n\n    /**\n     * Gets the address.\n     * \n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * Sets the address.\n     * \n     * @param address\n     *            the new address\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/CreditTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n * Credit transaction extends {@link Transaction}\n *\n */\n\n@Entity\n@Table(name = \"TRNX_CREDIT\")\n@DiscriminatorValue(value = \"credit\")\n@AttributeOverride(name=\"bankIdentifier\",column= @Column(name=\"CREDIT_BANK_IDENT\"))\n@IndexCollection(columns = { @Index(name = \"bankIdentifier\"), @Index(name = \"tx_type\") })\npublic class CreditTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public CreditTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/DebitTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n * Debit transaction extends {@link Transaction}\n *\n */\n@Entity\n@DiscriminatorValue(value=\"debit\")\n\n@AttributeOverrides(value = { @AttributeOverride(name = \"txId\", column = @Column(name = \"DEBIT_ID\")),\n        @AttributeOverride(name = \"bankIdentifier\", column = @Column(name = \"DEBIT_BANK_IDENT\")),\n        @AttributeOverride(name = \"transactionDt\", column = @Column(name = \"TX_DT\")) })\n\n@IndexCollection(columns = { @Index(name = \"bankIdentifier\"), @Index(name = \"tx_type\") })\npublic class DebitTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public DebitTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\t<!-- Persistence Units for KV store application -->\n\t<persistence-unit name=\"twikvstore\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"5000\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.OracleNoSQLClientFactory\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"OracleNoSqlTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.client\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \n\t\t\t\t/> -->\t\t\t<!-- <property name=\"index.home.dir\" value=\"./lucene\"/> -->\n\t\t\t<!-- <property name=\"kundera.indexer.class\" value=\"com.impetus.client.oraclenosql.index.OracleNoSQLInvertedIndexer\" \n\t\t\t\t/> -->\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"oracleNosqlDataTypeTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLChar</class>\n\t\t<class>com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLCharacter</class>\n\t\t<class>com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLDate</class>\n\t\t<class>com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLDoublePrimitive</class>\n\t\t<class>com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLDoubleWrapper</class>\n\t\t<class>com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLFloatPrimitive</class>\n\t\t<class>com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLFloatWrapper</class>\n\t\t<class>com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLInt</class>\n\t\t<class>com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLInteger</class>\n\t\t<class>com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLLongPrimitive</class>\n\t\t<class>com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLLongWrapper</class>\n\t\t<class>com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLSqlDate</class>\n\t\t<class>com.impetus.client.oraclenosql.datatypes.entities.StudentOracleNoSQLString</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"5000\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.OracleNoSQLClientFactory\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"OracleNoSqlTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.client\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"oracleNosqlSchemaGeneration\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.oraclenosql.schemamanager.OracleNoSQLUser</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"5000\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.OracleNoSQLClientFactory\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"OracleNoSqlTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.client\" value=\"kvstore\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"oracleNosqlBatchTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.oraclenosql.batch.PersonBatchOracleNosqlEntity</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"5000\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.OracleNoSQLClientFactory\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"OracleNoSqlTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.client\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.cache.provider.class\"\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"./lucene\"/> -->\n\t\t\t<property name=\"kundera.indexer.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.index.OracleNoSQLInvertedIndexer\" />\n\t\t\t<property name=\"kundera.batch.size\" value=\"5\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"oracleNosqlBatchTestSizeTwenty\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.oraclenosql.batch.AddressBatchOracleNosql</class>\n\t\t<class>com.impetus.client.oraclenosql.batch.PersonBatchOracleNosql</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"5000\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.OracleNoSQLClientFactory\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"OracleNoSqlTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.client\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.cache.provider.class\"\n\t\t\t\tvalue=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" />\n\t\t\t<property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" />\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"./lucene\"/> -->\n\t\t\t<property name=\"kundera.indexer.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.index.OracleNoSQLInvertedIndexer\" />\n\t\t\t<property name=\"kundera.batch.size\" value=\"20\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"oracleNosqlShowQueryEnabledPU\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.oraclenosql.entities.UserInformation</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"5000\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.OracleNoSQLClientFactory\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"OracleNoSqlTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.client\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.show.query\" value=\"true\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"oracleNosqlShowQueryDisabledPU\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.client.oraclenosql.entities.UserInformation</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost,Impetus-N178Cent\" />\n\t\t\t<property name=\"kundera.port\" value=\"5000\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.OracleNoSQLClientFactory\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"OracleNoSqlTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.client\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"ESkvstore\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.query.Person</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"5000\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.OracleNoSQLClientFactory\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"OracleNoSqlTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.client\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.indexer.class\" value=\"com.impetus.client.es.index.ESIndexer\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\n\t\t</properties>\n\t</persistence-unit>\n\n</persistence>\n\n\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/resources/esindexer.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<indexerProperties>\n\t<nodes>\n\t\t<node>\n\t\t\t<properties>\n\t\t\t\t<property name=\"host\" value=\"localhost\" />\n\t\t\t\t<property name=\"port\" value=\"9300\" />\n\t\t\t</properties>\n\t\t</node>\n\t</nodes>\n</indexerProperties>"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/resources/kvstoreSecurityConfig.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>oraclenosql</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t  <property name=\"oracle.kv.security\"\n\t\t\t\t\t\tvalue=\"/home/impadmin/oracle/client.txt\" />\n\t\t\t\t</properties>\n\t\t\t\t<servers>\n\t\t\t\t\t<server>\n\t\t\t\t\t\t<host>localhost</host>\n\t\t\t\t\t\t<port>5000</port>\n\t\t\t\t\t</server>\n\t\t\t\t\t<server>\n\t\t\t\t\t\t<host>192.168.145.21</host>\n\t\t\t\t\t\t<port>5000</port>\n\t\t\t\t\t</server>\n\t\t\t\t</servers>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>\n"
  },
  {
    "path": "src/kundera-oracle-nosql/src/test/resources/oraclenosql_script",
    "content": "table create -name PERSON_ALL_DATA_TYPE\nadd-field -type Long -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nadd-field -type boolean -name IS_EXCEPTIONAL\nadd-field -type integer -name AGE\nadd-field -type BINARY -name DIGITAL_SIGNATURE\nadd-field -type BINARY -name RATING\nadd-field -type float -name COMPLIANCE\nadd-field -type double -name HEIGHT\nadd-field -type string -name GRADE\nadd-field -type BINARY -name ENROLMENT_DATE\nadd-field -type BINARY -name ENROLMENT_TIME\nadd-field -type BINARY -name JOINING_DATE_TIME\nadd-field -type integer -name YEARS_SPENT\nadd-field -type Long -name UNIQUE_ID\nadd-field -type Long -name BIRTH_DAY\nadd-field -type double -name MONTHLY_SALARY\nadd-field -type BINARY -name BIRTH_TIME\nadd-field -type BINARY -name ANNIVERSARY\nadd-field -type BINARY -name JOB_ATTEMPTS\nadd-field -type BINARY -name ACCUMULATED_WEALTH\nadd-field -type BINARY -name GRADUATION_DAY\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PERSON_ALL_DATA_TYPE -wait\n\ntable create -name PERSON\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nadd-field -type integer -name AGE\nadd-field -type double -name SALARY\nadd-field -type string -name ENUM\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PERSON -wait\nplan add-index -name age -table PERSON -field AGE -wait\nplan add-index -name personName -table PERSON -field PERSON_NAME -wait\nplan add-index -name personId_age -table PERSON -field PERSON_ID -field AGE -wait\nplan add-index -name salary -table PERSON -field SALARY -wait\n\ntable create -name PERSON_KV_STORE\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nadd-field -type integer -name AGE\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PERSON_KV_STORE -wait\nplan add-index -name age -table PERSON_KV_STORE -field AGE -wait\nplan add-index -name personName -table PERSON_KV_STORE -field PERSON_NAME -wait\nplan add-index -name personId_age -table PERSON_KV_STORE -field PERSON_ID -field AGE -wait\n\ntable create -name USER_PROFILE\nadd-field -type integer -name USER_ID\nadd-field -type string -name USER_NAME\nadd-field -type binary -name PROFILE_PICTURE\nprimary-key -field USER_ID\nexit\nplan add-table -name USER_PROFILE -wait\n\ntable create -name PERSON_OTO\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nadd-field -type integer -name AGE\nadd-field -type double -name ADDRESS_ID\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PERSON_OTO -wait\n\ntable create -name ADDRESS_OTO\nadd-field -type string -name street\nadd-field -type double -name ADDRESS_ID\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name ADDRESS_OTO -wait\n\ntable create -name PersonOracleNoSqlMTO\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nadd-field -type string -name ADDRESS_ID\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonOracleNoSqlMTO -wait\n\ntable create -name AddressOracleNoSqlMTO\nadd-field -type string -name ADDRESS_ID\nprimary-key -field ADDRESS_ID\nadd-field -type string -name STREET\nexit\nplan add-table -name AddressOracleNoSqlMTO -wait\n\ntable create -name AddressOracleNoSqlOTM\nadd-field -type string -name STREET\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name PERSON_ID\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name AddressOracleNoSqlOTM -wait\nplan add-index -name PERSON_ID -table AddressOracleNoSqlOTM -field PERSON_ID -wait\n\ntable create -name PersonOracleNoSqlOTM\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonOracleNoSqlOTM -wait\n\ntable create -name PersonOracleNoSqlOTO\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nadd-field -type string -name ADDRESS_ID\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonOracleNoSqlOTO -wait\n\ntable create -name AddressOracleNoSqlOTO\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name AddressOracleNoSqlOTO -wait\n\ntable create -name StudentOracleNoSQLFloatPrimitive\nadd-field -type float -name id\nadd-field -type binary -name AGE\nadd-field -type string -name NAME\nprimary-key -field id\nexit\nplan add-table -name StudentOracleNoSQLFloatPrimitive -wait\n\ntable create -name StudentOracleNoSQLLongPrimitive\nadd-field -type long -name id\nadd-field -type binary -name AGE\nadd-field -type string -name NAME\nprimary-key -field id\nexit\nplan add-table -name StudentOracleNoSQLLongPrimitive -wait\n\ntable create -name StudentOracleNoSQLSqlDate\nadd-field -type long -name id\nadd-field -type binary -name AGE\nadd-field -type string -name NAME\nprimary-key -field id\nexit\nplan add-table -name StudentOracleNoSQLSqlDate -wait\n\ntable create -name StudentOracleNoSQLFloatWrapper\nadd-field -type float -name id\nadd-field -type binary -name AGE\nadd-field -type string -name NAME\nprimary-key -field id\nexit\nplan add-table -name StudentOracleNoSQLFloatWrapper -wait\n\ntable create -name StudentOracleNoSQLDoublePrimitiv\nadd-field -type double -name id\nadd-field -type binary -name AGE\nadd-field -type string -name NAME\nprimary-key -field id\nexit\nplan add-table -name StudentOracleNoSQLDoublePrimitiv -wait\n\ntable create -name StudentOracleNoSQLString\nadd-field -type string -name id\nadd-field -type binary -name AGE\nadd-field -type string -name NAME\nprimary-key -field id\nexit\nplan add-table -name StudentOracleNoSQLString -wait\n\ntable create -name StudentOracleNoSQLInt\nadd-field -type integer -name id\nadd-field -type string -name NAME\nadd-field -type binary -name AGE\nprimary-key -field id\nexit\nplan add-table -name StudentOracleNoSQLInt -wait\n\ntable create -name StudentOracleNoSQLDoubleWrapper\nadd-field -type double -name id\nadd-field -type binary -name AGE\nadd-field -type string -name NAME\nprimary-key -field id\nexit\nplan add-table -name StudentOracleNoSQLDoubleWrapper -wait\n\ntable create -name StudentOracleNoSQLLongWrapper\nadd-field -type long -name id\nadd-field -type binary -name AGE\nadd-field -type string -name NAME\nprimary-key -field id\nexit\nplan add-table -name StudentOracleNoSQLLongWrapper -wait\n\ntable create -name StudentOracleNoSQLInteger\nadd-field -type integer -name id\nadd-field -type binary -name AGE\nadd-field -type string -name NAME\nprimary-key -field id\nexit\nplan add-table -name StudentOracleNoSQLInteger -wait\n\ntable create -name StudentOracleNoSQLDate\nadd-field -type long -name id\nadd-field -type binary -name AGE\nadd-field -type string -name NAME\nprimary-key -field id\nexit\nplan add-table -name StudentOracleNoSQLDate -wait\n\ntable create -name StudentOracleNoSQLCharacter\nadd-field -type string -name id\nadd-field -type binary -name AGE\nadd-field -type string -name NAME\nprimary-key -field id\nexit\nplan add-table -name StudentOracleNoSQLCharacter -wait\n\ntable create -name StudentOracleNoSQLChar\nadd-field -type string -name id\nadd-field -type binary -name AGE\nadd-field -type string -name NAME\nprimary-key -field id\nexit\nplan add-table -name StudentOracleNoSQLChar -wait\n\ntable create -name User\nadd-field -type string -name user_Id\nadd-field -type integer -name tweetId\nadd-field -type string -name timeLineId\nadd-field -type string -name tweetBody\nadd-field -type long -name tweetDate\nprimary-key -field user_Id -field tweetId -field timeLineId\nexit\nplan add-table -name User -wait\nplan add-index -name user_tweet -table User -field user_Id -field tweetId -wait\nplan add-index -name user_tweet_timeline -table User -field user_Id -field tweetId -field timeLineId -wait\n\ntable create -name PERSON_BATCH\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nadd-field -type integer -name AGE\nadd-field -type binary -name AGEss\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PERSON_BATCH -wait\n\ntable create -name ADDRESS_BATCH\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name ADDRESS_BATCH -wait\n\ntable create -name PersonOracleNoSqlMTM\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonOracleNoSqlMTM -wait\n\ntable create -name AddressOracleNoSqlMTM\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name AddressOracleNoSqlMTM -wait\n\ntable create -name PERSONNEL_ADDRESS\nadd-field -type string -name key\nadd-field -type string -name PERSON_ID\nadd-field -type string -name ADDRESS_ID\nprimary-key -field key\nexit\nplan add-table -name PERSONNEL_ADDRESS -wait\nplan add-index -name PERSON_ID -table PERSONNEL_ADDRESS -field PERSON_ID -wait\nplan add-index -name ADDRESS_ID -table PERSONNEL_ADDRESS -field ADDRESS_ID -wait\n\ntable create -name PERSON_ADDRESS\nadd-field -type string -name key\nadd-field -type string -name PERSON_ID\nadd-field -type string -name ADDRESS_ID\nprimary-key -field key\nexit\nplan add-table -name PERSON_ADDRESS -wait\nplan add-index -name PERSON_ID -table PERSON_ADDRESS -field PERSON_ID -wait\nplan add-index -name ADDRESS_ID -table PERSON_ADDRESS -field ADDRESS_ID -wait\n\ntable create -name UserInformation\nadd-field -type integer -name age\nadd-field -type string -name name\nadd-field -type string -name id\nprimary-key -field id\nexit\nplan add-table -name UserInformation -wait\n\ntable create -name PERSON_EMBEDDED\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nadd-field -type integer -name AGE\nadd-field -type integer -name officeId\nadd-field -type string -name companyName\nadd-field -type string -name location\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PERSON_EMBEDDED -wait\nplan add-index -name officeId -table PERSON_EMBEDDED -field officeId -wait\nplan add-index -name companyName -table PERSON_EMBEDDED -field companyName -wait\nplan add-index -name location -table PERSON_EMBEDDED -field location -wait\nplan add-index -name age -table PERSON_EMBEDDED -field AGE -wait\nplan add-index -name personName -table PERSON_EMBEDDED -field PERSON_NAME -wait\nplan add-index -name compositeIdx -table PERSON_EMBEDDED -field PERSON_ID -field AGE -wait"
  },
  {
    "path": "src/kundera-rdbms/pom.xml",
    "content": "<?xml version=\"1.0\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<artifactId>kundera</artifactId>\n\t\t<groupId>com.impetus</groupId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-rdbms</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-rdbms</name>\n\t<url>http://maven.apache.org</url>\n\n\t<dependencies>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.hibernate</groupId>\n\t\t\t<artifactId>hibernate-core</artifactId>\n\t\t\t<version>5.2.5.Final</version>\n\t\t</dependency>\n\t\t<!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> \n\t\t\t<version>4.1.7.Final</version> </dependency> -->\n\t\t<dependency>\n\t\t\t<groupId>org.hibernate</groupId>\n\t\t\t<artifactId>hibernate-validator</artifactId>\n\t\t\t<version>5.3.4.Final</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>mysql</groupId>\n\t\t\t<artifactId>mysql-connector-java</artifactId>\n\t\t\t<version>5.1.6</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.hibernate</groupId>\n\t\t\t<artifactId>hibernate-c3p0</artifactId>\n\t\t\t<version>5.2.5.Final</version>\n\t\t</dependency>\n\t\t<!-- <dependency> <groupId>hsqldb</groupId> <artifactId>hsqldb</artifactId> \n\t\t\t<version>1.8.0.7</version> <scope>test</scope> </dependency> -->\n\t\t<dependency>\n\t\t\t<groupId>org.hsqldb</groupId>\n\t\t\t<artifactId>hsqldb</artifactId>\n\t\t\t<version>2.3.4</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t</properties>\n\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<!-- <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> \n\t\t\t\t<configuration> The destination file for the code coverage report has to \n\t\t\t\tbe set to the same value in the parent pom and in each module pom. Then JaCoCo \n\t\t\t\twill add up information in the same report, so that, it will give the cross-module \n\t\t\t\tcode coverage. <destFile>${project.basedir}/../target/jacoco-it.exec</destFile> \n\t\t\t\t</configuration> <executions> <execution> <id>post-test</id> <configuration> \n\t\t\t\t<skip>true</skip> </configuration> </execution> </executions> </plugin> -->\n\n\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "src/kundera-rdbms/src/main/java/com/impetus/client/rdbms/HibernateClient.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rdbms;\n\nimport java.io.Serializable;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.GenerationType;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.OneToMany;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Parameter;\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.hibernate.Criteria;\nimport org.hibernate.HibernateException;\nimport org.hibernate.Query;\nimport org.hibernate.SQLQuery;\nimport org.hibernate.Session;\nimport org.hibernate.StatelessSession;\nimport org.hibernate.Transaction;\nimport org.hibernate.criterion.Restrictions;\nimport org.hibernate.internal.StatelessSessionImpl;\nimport org.hibernate.transform.AliasToEntityMapResultTransformer;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.rdbms.query.RDBMSQuery;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.Relation;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.EntityReaderException;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessor;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.proxy.ProxyHelper;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class HibernateClient.\n * \n * @author vivek.mishra\n */\npublic class HibernateClient extends ClientBase implements Client<RDBMSQuery>\n{\n\n    /** The client factory. */\n    private RDBMSClientFactory clientFactory;\n\n    /** The s. */\n    private StatelessSession s;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /** The Constant log. */\n    private static final Logger log = LoggerFactory.getLogger(HibernateClient.class);\n\n    /**\n     * Instantiates a new hibernate client.\n     * \n     * @param persistenceUnit\n     *            the persistence unit\n     * @param indexManager\n     *            the index manager\n     * @param reader\n     *            the reader\n     * @param clientFactory\n     *            the client factory\n     * @param externalProperties\n     *            the external properties\n     * @param clientMetadata\n     *            the client metadata\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public HibernateClient(final String persistenceUnit, IndexManager indexManager, EntityReader reader,\n            RDBMSClientFactory clientFactory, Map<String, Object> externalProperties,\n            final ClientMetadata clientMetadata, final KunderaMetadata kunderaMetadata)\n    {\n\n        super(kunderaMetadata, externalProperties, persistenceUnit);\n        this.clientFactory = clientFactory;\n        // TODO . once we clear this persistenceUnit stuff we need to simply\n        // modify this to have a properties or even pass an EMF!\n        this.indexManager = indexManager;\n        this.reader = reader;\n        this.clientMetadata = clientMetadata;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    @Override\n    public void close()\n    {\n        this.indexManager.flush();\n        if (s != null)\n        {\n            s.close();\n            s = null;\n        }\n        externalProperties = null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    public void delete(Object entity, Object pKey)\n    {\n        s = getStatelessSession();\n        Transaction tx = null;\n        tx = onBegin();\n        s.delete(entity);\n        onCommit(tx);\n\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,\n                metadata.getPersistenceUnit());\n        if (!MetadataUtils.useSecondryIndex(getClientMetadata()))\n        {\n            getIndexManager().remove(metadata, entity, pKey);\n        }\n    }\n\n    /**\n     * On begin.\n     * \n     * @return the transaction\n     */\n    private Transaction onBegin()\n    {\n        Transaction tx;\n        if (((StatelessSessionImpl) s).getTransactionCoordinator().isTransactionActive())\n        {\n            tx = ((StatelessSessionImpl) s).getTransaction();\n        }\n        else\n        {\n            tx = s.beginTransaction();\n        }\n        return tx;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.String)\n     */\n    @Override\n    public Object find(Class clazz, Object key)\n    {\n        s = getStatelessSession();\n\n        Object result = null;\n        try\n        {\n            result = s.get(clazz, (Serializable) key);\n        }\n        catch (ClassCastException ccex)\n        {\n            log.error(\"Class can not be serializable, Caused by {}.\", ccex);\n            throw new KunderaException(ccex);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while finding, Caused by {}. \", e);\n            throw new KunderaException(e);\n        }\n        return result;\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.String[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClazz, String[] columnsToSelect, Object... arg1)\n    {\n        // TODO: Vivek correct it. unfortunately i need to open a new session\n        // for each finder to avoid lazy loading.\n        Session s = getSession();\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, getPersistenceUnit(),\n                entityClazz);\n\n        Object[] pKeys = getDataType(entityMetadata, arg1);\n        String id = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();\n\n        Criteria c = s.createCriteria(entityClazz);\n\n        c.add(Restrictions.in(id, pKeys));\n\n        return c.list();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.metadata\n     * .model.EntityMetadata, java.lang.Object, java.lang.Object,\n     * java.util.List)\n     */\n    @Override\n    protected void onPersist(EntityMetadata metadata, Object entity, Object id, List<RelationHolder> relationHolders)\n    {\n        boolean proxyRemoved = removeKunderaProxies(metadata, entity, relationHolders);\n\n        Transaction tx = null;\n\n        s = getStatelessSession();\n        tx = onBegin();\n        try\n        {\n            if (!isUpdate)\n            {\n                id = s.insert(entity);\n\n                // Update foreign Keys\n                updateForeignKeys(metadata, id, relationHolders);\n                onCommit(tx);/* tx.commit(); */\n            }\n            else\n            {\n                s.update(entity);\n\n                if (proxyRemoved)\n                {\n                    updateForeignKeys(metadata, id, relationHolders);\n                }\n\n                onCommit(tx);\n            }\n        }\n        // TODO: Bad code, get rid of these exceptions, currently necessary for\n        // handling many to one case\n        catch (org.hibernate.exception.ConstraintViolationException e)\n        {\n            s.update(entity);\n            log.info(e.getMessage());\n            onCommit(tx);\n            // tx.commit();\n        }\n        catch (HibernateException e)\n        {\n            log.error(\"Error while persisting object of {}, Caused by {}.\", metadata.getEntityClazz(), e);\n            throw new PersistenceException(e);\n        }\n    }\n\n    /**\n     * On commit.\n     * \n     * @param tx\n     *            the tx\n     */\n    private void onCommit(Transaction tx)\n    {\n        if (tx.isActive())\n        {\n            tx.commit();\n        }\n    }\n\n    /**\n     * Inserts records into JoinTable.\n     * \n     * @param joinTableData\n     *            the join table data\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        String schemaName = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, joinTableData.getEntityClass())\n                .getSchema();\n        String joinTableName = joinTableData.getJoinTableName();\n        String joinColumnName = joinTableData.getJoinColumnName();\n        String invJoinColumnName = joinTableData.getInverseJoinColumnName();\n\n        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();\n\n        for (Object key : joinTableRecords.keySet())\n        {\n            Set<Object> values = joinTableRecords.get(key);\n            insertRecordInJoinTable(schemaName, joinTableName, joinColumnName, invJoinColumnName, key, values);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String joinTableName, String joinColumnName,\n            String inverseJoinColumnName, Object parentId, Class columnJavaType)\n    {\n        StringBuffer sqlQuery = new StringBuffer();\n        sqlQuery.append(\"SELECT \").append(inverseJoinColumnName).append(\" FROM \")\n                .append(getFromClause(schemaName, joinTableName)).append(\" WHERE \").append(joinColumnName).append(\"='\")\n                .append(parentId).append(\"'\");\n\n        Session s = getSession();\n\n        SQLQuery query = s.createSQLQuery(sqlQuery.toString());\n\n        List<E> foreignKeys = new ArrayList<E>();\n\n        foreignKeys = query.list();\n\n        return foreignKeys;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n        String childIdStr = (String) columnValue;\n        StringBuffer sqlQuery = new StringBuffer();\n        sqlQuery.append(\"SELECT \").append(pKeyName).append(\" FROM \").append(getFromClause(schemaName, tableName))\n                .append(\" WHERE \").append(columnName).append(\"='\").append(childIdStr).append(\"'\");\n\n        Session s = getSession();\n\n        SQLQuery query = s.createSQLQuery(sqlQuery.toString());\n\n        List<Object> primaryKeys = new ArrayList<Object>();\n\n        primaryKeys = query.list();\n\n        if (primaryKeys != null && !primaryKeys.isEmpty())\n        {\n            return primaryKeys.toArray(new Object[0]);\n        }\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.Object)\n     */\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n        StringBuffer query = new StringBuffer();\n\n        query.append(\"DELETE FROM \").append(getFromClause(schemaName, tableName)).append(\" WHERE \").append(columnName)\n                .append(\"=\").append(\"'\").append(columnValue).append(\"'\");\n\n        StatelessSession s = getStatelessSession();\n\n        Transaction tx = onBegin();\n        onNativeUpdate(query.toString(), null);\n        onCommit(tx);\n\n    }\n\n    /**\n     * Insert record in join table.\n     * \n     * @param schemaName\n     *            the schema name\n     * @param joinTableName\n     *            the join table name\n     * @param joinColumnName\n     *            the join column name\n     * @param inverseJoinColumnName\n     *            the inverse join column name\n     * @param parentId\n     *            the parent id\n     * @param childrenIds\n     *            the children ids\n     */\n    private void insertRecordInJoinTable(String schemaName, String joinTableName, String joinColumnName,\n            String inverseJoinColumnName, Object parentId, Set<Object> childrenIds)\n    {\n        s = getStatelessSession();\n        Transaction tx = onBegin();\n        for (Object childId : childrenIds)\n        {\n            StringBuffer query = new StringBuffer();\n\n            // write an update query\n            Object[] existingRowIds = findIdsByColumn(schemaName, joinTableName, joinColumnName, inverseJoinColumnName,\n                    (String) childId, null);\n\n            boolean joinTableRecordsExists = false;\n            if (existingRowIds != null && existingRowIds.length > 0)\n            {\n                for (Object o : existingRowIds)\n                {\n                    if (o.toString().equals(parentId.toString()))\n                    {\n                        joinTableRecordsExists = true;\n                        break;\n                    }\n                }\n            }\n\n            if (!joinTableRecordsExists)\n            {\n                query.append(\"INSERT INTO \").append(getFromClause(schemaName, joinTableName)).append(\"(\")\n                        .append(joinColumnName).append(\",\").append(inverseJoinColumnName).append(\")\")\n                        .append(\" VALUES('\").append(parentId).append(\"','\").append(childId).append(\"')\");\n\n                s.createSQLQuery(query.toString()).executeUpdate();\n            }\n        }\n        onCommit(tx);\n        // tx.commit();\n    }\n\n    /**\n     * Gets the session instance.\n     * \n     * @return the session instance\n     */\n    private StatelessSession getStatelessSession()\n    {\n        return s != null ? s : clientFactory.getStatelessSession();\n    }\n\n    /**\n     * Gets the session instance.\n     * \n     * @return the session instance\n     */\n    private Session getSession()\n    {\n        return clientFactory.getSession();\n    }\n\n    /**\n     * Find.\n     * \n     * @param nativeQuery\n     *            the native fquery\n     * @param relations\n     *            the relations\n     * @param m\n     *            the m\n     * @return the list\n     */\n    public List find(String nativeQuery, List<String> relations, EntityMetadata m)\n    {\n        List entities = new ArrayList();\n\n        s = getStatelessSession();\n\n        SQLQuery q = s.createSQLQuery(nativeQuery);\n        q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);\n\n        List result = q.list();\n\n        try\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n\n            EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n            List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();\n            for (Object o : result)\n            {\n                Map<String, Object> relationValue = null;\n                Object entity = null;\n                EntityMetadata subEntityMetadata = null;\n                if (!subManagedType.isEmpty())\n                {\n                    for (AbstractManagedType subEntity : subManagedType)\n                    {\n                        String discColumn = subEntity.getDiscriminatorColumn();\n                        String disColValue = subEntity.getDiscriminatorValue();\n                        Object value = ((Map<String, Object>) o).get(discColumn);\n                        if (value != null && value.toString().equals(disColValue))\n                        {\n                            subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                                    subEntity.getJavaType());\n                            break;\n                        }\n                    }\n                    entity = instantiateEntity(subEntityMetadata.getEntityClazz(), entity);\n                    relationValue = HibernateUtils.getTranslatedObject(kunderaMetadata, entity,\n                            (Map<String, Object>) o, m);\n\n                }\n                else\n                {\n                    entity = instantiateEntity(m.getEntityClazz(), entity);\n                    relationValue = HibernateUtils.getTranslatedObject(kunderaMetadata, entity,\n                            (Map<String, Object>) o, m);\n                }\n\n                if (relationValue != null && !relationValue.isEmpty())\n                {\n                    entity = new EnhanceEntity(entity, PropertyAccessorHelper.getId(entity, m), relationValue);\n                }\n                entities.add(entity);\n            }\n            return entities;\n        }\n        catch (Exception e)\n        {\n            if (e.getMessage().equals(\"Can not be translated into entity.\"))\n            {\n                return result;\n            }\n            throw new EntityReaderException(e);\n        }\n    }\n\n    /**\n     * Find.\n     * \n     * @param query\n     *            the native fquery\n     * @param parameterMap\n     *            the parameter map\n     * @param maxResult \n     * @param firstResult \n     * @return the list\n     */\n    public List findByQuery(String query, Map<Parameter, Object> parameterMap, int firstResult, int maxResult)\n    {\n        s = getStatelessSession();\n\n        Query q = s.createQuery(query);\n        q.setFirstResult(firstResult);\n        q.setMaxResults(maxResult);\n\n        setParameters(parameterMap, q);\n\n        return q.list();\n    }\n\n    /**\n     * On native update.\n     * \n     * @param query\n     *            the query\n     * @param parameterMap\n     *            the parameter map\n     * @return the int\n     */\n    public int onNativeUpdate(String query, Map<Parameter, Object> parameterMap)\n    {\n        s = getStatelessSession();\n\n        Query q = s.createSQLQuery(query);\n        setParameters(parameterMap, q);\n\n        // Transaction tx = s.getTransaction() == null ? s.beginTransaction():\n        // s.getTransaction();\n\n        // tx.begin();\n        int i = q.executeUpdate();\n\n        // tx.commit();\n\n        return i;\n    }\n\n    /**\n     * Find.\n     * \n     * @param query\n     *            the native fquery\n     * @param parameterMap\n     *            the parameter map\n     * @param maxResult \n     * @param firstResult \n     * @return the list\n     */\n    public int onExecuteUpdate(String query, Map<Parameter, Object> parameterMap, int firstResult, int maxResult)\n    {\n        s = getStatelessSession();\n\n        Query q = s.createQuery(query);\n        \n        q.setFirstResult(firstResult);\n        q.setMaxResults(maxResult);\n        \n        setParameters(parameterMap, q);\n\n        Transaction tx = onBegin();\n\n        int i = q.executeUpdate();\n\n        onCommit(tx);\n        // tx.commit();\n\n        return i;\n    }\n\n    /**\n     * Gets the query instance.\n     * \n     * @param nativeQuery\n     *            the native query\n     * @param m\n     *            the m\n     * @return the query instance\n     */\n    public SQLQuery getQueryInstance(String nativeQuery, EntityMetadata m)\n    {\n        s = getStatelessSession();\n\n        SQLQuery q = s.createSQLQuery(nativeQuery).addEntity(m.getEntityClazz());\n\n        List<String> relations = m.getRelationNames();\n        if (relations != null)\n        {\n            for (String r : relations)\n            {\n                Relation rel = m.getRelation(m.getFieldName(r));\n                String name = MetadataUtils.getMappedName(m, m.getRelation(r), kunderaMetadata);\n                if (!((AbstractAttribute) m.getIdAttribute()).getJPAColumnName().equalsIgnoreCase(\n                        name != null ? name : r)\n                        && rel != null\n                        && !rel.getProperty().isAnnotationPresent(ManyToMany.class)\n                        && !rel.getProperty().isAnnotationPresent(OneToMany.class)\n                        && (rel.getProperty().isAnnotationPresent(OneToOne.class)\n                                && StringUtils.isBlank(rel.getMappedBy()) || rel.getProperty().isAnnotationPresent(\n                                ManyToOne.class)))\n                {\n                    q.addScalar(name != null ? name : r);\n                }\n            }\n        }\n        return q;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.String,\n     * java.lang.String, com.impetus.kundera.metadata.model.EntityMetadata)\n     */\n    public List findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n        String tableName = m.getTableName();\n\n        // Suffixing the UNDERSCORE instead of prefix as Oracle 11g complains\n        // about invalid characters error while executing the request.\n        StringBuilder queryBuilder = new StringBuilder(\"Select \");\n\n        queryBuilder.append(\"* \");\n        queryBuilder.append(\"From \");\n        queryBuilder.append(getFromClause(m.getSchema(), tableName));\n        queryBuilder.append(\" \");\n\n        queryBuilder.append(\" Where \");\n        queryBuilder.append(colName);\n        queryBuilder.append(\" = \");\n        queryBuilder.append(\"'\");\n        queryBuilder.append(colValue);\n        queryBuilder.append(\"'\");\n        s = getStatelessSession();\n\n        List results = find(queryBuilder.toString(), m.getRelationNames(), m);\n        return populateEnhanceEntities(m, m.getRelationNames(), results);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<RDBMSQuery> getQueryImplementor()\n    {\n        return RDBMSQuery.class;\n    }\n\n    /**\n     * Gets the data type.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param arg1\n     *            the arg1\n     * @return the data type\n     * @throws PropertyAccessException\n     *             the property access exception\n     */\n    private Object[] getDataType(EntityMetadata entityMetadata, Object... arg1) throws PropertyAccessException\n    {\n        Field idField = (Field) entityMetadata.getIdAttribute().getJavaMember();\n        PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor(idField);\n\n        Object[] pKeys = new Object[arg1.length];\n        int cnt = 0;\n        for (Object r : arg1)\n        {\n            pKeys[cnt++] = accessor.fromString(idField.getClass(), r.toString());\n        }\n        return pKeys;\n    }\n\n    /**\n     * Gets the from clause.\n     * \n     * @param schemaName\n     *            the schema name\n     * @param tableName\n     *            the table name\n     * @return the from clause\n     */\n    private String getFromClause(String schemaName, String tableName)\n    {\n        String clause = tableName;\n        if (schemaName != null && !schemaName.isEmpty())\n        {\n            clause = schemaName + \".\" + tableName;\n        }\n        return clause;\n    }\n\n    /**\n     * Updates foreign keys into master table.\n     * \n     * @param metadata\n     *            the metadata\n     * @param id\n     *            the id\n     * @param relationHolders\n     *            the relation holders\n     */\n    private void updateForeignKeys(EntityMetadata metadata, Object id, List<RelationHolder> relationHolders)\n    {\n        for (RelationHolder rh : relationHolders)\n        {\n            String linkName = rh.getRelationName();\n            Object linkValue = rh.getRelationValue();\n            if (linkName != null && linkValue != null)\n            {\n\n                // String fieldName = metadata.getFieldName(linkName);\n\n                String clause = getFromClause(metadata.getSchema(), metadata.getTableName());\n                // String updateSql = \"Update \" +\n                // metadata.getEntityClazz().getSimpleName() + \" SET \" +\n                // fieldName + \"= '\" + linkValue + \"' WHERE \"\n                // + ((AbstractAttribute) metadata.getIdAttribute()).getName() +\n                // \" = '\" + id + \"'\";\n\n                String updateSql = \"Update \" + clause + \" SET \" + linkName + \"= '\" + linkValue + \"' WHERE \"\n                        + ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName() + \" = '\" + id + \"'\";\n\n                onNativeUpdate(updateSql, null);\n            }\n        }\n    }\n\n    /**\n     * Removes the kundera proxies.\n     * \n     * @param metadata\n     *            the metadata\n     * @param entity\n     *            the entity\n     * @param relationHolders\n     *            the relation holders\n     * @return true, if successful\n     */\n    private boolean removeKunderaProxies(EntityMetadata metadata, Object entity, List<RelationHolder> relationHolders)\n    {\n        boolean proxyRemoved = false;\n\n        for (Relation relation : metadata.getRelations())\n        {\n            if (relation != null && relation.isUnary())\n            {\n                Object relationObject = PropertyAccessorHelper.getObject(entity, relation.getProperty());\n                if (relationObject != null && ProxyHelper.isKunderaProxy(relationObject))\n                {\n                    EntityMetadata relMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                            relation.getTargetEntity());\n                    Method idAccessorMethod = relMetadata.getReadIdentifierMethod();\n                    Object foreignKey = null;\n                    try\n                    {\n                        foreignKey = idAccessorMethod.invoke(relationObject, new Object[] {});\n                    }\n                    catch (IllegalArgumentException e)\n                    {\n                        log.error(\"Error while Fetching relationship value of {}, Caused by {}.\",\n                                metadata.getEntityClazz(), e);\n                    }\n                    catch (IllegalAccessException e)\n                    {\n                        log.error(\"Error while Fetching relationship value of {}, Caused by {}.\",\n                                metadata.getEntityClazz(), e);\n                    }\n                    catch (InvocationTargetException e)\n                    {\n                        log.error(\"Error while Fetching relationship value of {}, Caused by {}.\",\n                                metadata.getEntityClazz(), e);\n                    }\n\n                    if (foreignKey != null)\n                    {\n                        relationObject = null;\n                        PropertyAccessorHelper.set(entity, relation.getProperty(), relationObject);\n                        relationHolders\n                                .add(new RelationHolder(relation.getJoinColumnName(kunderaMetadata), foreignKey));\n                        proxyRemoved = true;\n                    }\n                }\n            }\n        }\n        return proxyRemoved;\n    }\n\n    /**\n     * Populate enhance entities.\n     * \n     * @param m\n     *            the m\n     * @param relationNames\n     *            the relation names\n     * @param result\n     *            the result\n     * @return the list\n     */\n    private List<EnhanceEntity> populateEnhanceEntities(EntityMetadata m, List<String> relationNames, List result)\n    {\n\n        List<EnhanceEntity> ls = null;\n        if (!result.isEmpty())\n        {\n            ls = new ArrayList<EnhanceEntity>(result.size());\n            for (Object o : result)\n            {\n                EnhanceEntity entity = null;\n                if (!o.getClass().isAssignableFrom(EnhanceEntity.class))\n                {\n                    entity = new EnhanceEntity(o, PropertyAccessorHelper.getId(o, m), null);\n                }\n                else\n                {\n                    entity = (EnhanceEntity) o;\n                }\n                ls.add(entity);\n            }\n        }\n        return ls;\n    }\n\n    /**\n     * Instantiate entity.\n     * \n     * @param entityClass\n     *            the entity class\n     * @param entity\n     *            the entity\n     * @return the object\n     */\n    private Object instantiateEntity(Class entityClass, Object entity)\n    {\n        try\n        {\n            if (entity == null)\n            {\n                return entityClass.newInstance();\n            }\n            return entity;\n        }\n        catch (InstantiationException e)\n        {\n            log.error(\"Error while instantiating \" + entityClass + \", Caused by: \", e);\n        }\n        catch (IllegalAccessException e)\n        {\n            log.error(\"Error while instantiating \" + entityClass + \", Caused by: \", e);\n        }\n        return null;\n    }\n\n    /**\n     * Sets the parameters.\n     * \n     * @param parameterMap\n     *            the parameter map\n     * @param q\n     *            the q\n     */\n    private void setParameters(Map<Parameter, Object> parameterMap, Query q)\n    {\n        if (parameterMap != null && !parameterMap.isEmpty())\n        {\n            for (Parameter parameter : parameterMap.keySet())\n            {\n                Object paramObject = parameterMap.get(parameter);\n                if (parameter.getName() != null)\n                {\n                    if (paramObject instanceof Collection)\n                    {\n                        q.setParameterList(parameter.getName(), (Collection) paramObject);\n                    }\n                    else\n                    {\n                        q.setParameter(parameter.getName(), paramObject);\n                    }\n                }\n                else if (parameter.getPosition() != null)\n                {\n                    if (paramObject instanceof Collection)\n                    {\n                        q.setParameterList(Integer.toString(parameter.getPosition()), (Collection) paramObject);\n                    }\n                    else\n                    {\n                        q.setParameter(Integer.toString(parameter.getPosition()), paramObject);\n                    }\n                }\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        throw new UnsupportedOperationException(GenerationType.class.getSimpleName()\n                + \" Strategies not supported by this client : HibernateClient\");\n    }\n\n}"
  },
  {
    "path": "src/kundera-rdbms/src/main/java/com/impetus/client/rdbms/HibernateUtils.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rdbms;\n\nimport java.lang.reflect.Field;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.Metamodel;\n\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.attributes.AttributeType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReaderException;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.property.accessor.EnumAccessor;\n\n/**\n * The Class HibernateUtils.\n * \n * @author vivek.mishra\n */\npublic final class HibernateUtils\n{\n\n    /**\n     * Gets the properties.\n     * \n     * @param persistenceUnit\n     *            the persistence unit\n     * @return the properties\n     */\n    static final Properties getProperties(final KunderaMetadata kunderaMetadata, final String persistenceUnit)\n    {\n        PersistenceUnitMetadata persistenceUnitMetadatata = kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(persistenceUnit);\n        Properties props = persistenceUnitMetadatata.getProperties();\n        return props;\n    }\n\n    static final URL getPersistenceUnitUrl(final KunderaMetadata kunderaMetadata, final String persistenceUnit)\n    {\n        PersistenceUnitMetadata persistenceUnitMetadatata = kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(persistenceUnit);\n        return persistenceUnitMetadatata != null ? persistenceUnitMetadatata.getMappedUrl() : null;\n    }\n\n    /**\n     * \n     * @param entity\n     * @param valueMap\n     * @param m\n     * @return\n     */\n    static Map<String, Object> getTranslatedObject(final KunderaMetadata kunderaMetadata, Object entity, Map<String, Object> valueMap, EntityMetadata m)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n        String idColumnName = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();\n        Object rowKey = valueMap.get(idColumnName) == null ? valueMap.get(idColumnName.toUpperCase()) == null ? valueMap\n                .get(idColumnName.toLowerCase()) : valueMap.get(idColumnName.toUpperCase())\n                : valueMap.get(idColumnName);\n\n        Map<String, Object> relationValue = new HashMap<String, Object>();\n\n        if (valueMap != null && (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()) || rowKey != null))\n        {\n            try\n            {\n                if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))\n                {\n                    EmbeddableType embeddable = metaModel.embeddable(m.getIdAttribute().getBindableJavaType());\n                    Iterator<Attribute> iter = embeddable.getAttributes().iterator();\n                    Object compoundKey = m.getIdAttribute().getBindableJavaType().newInstance();\n                    while (iter.hasNext())\n                    {\n                        Attribute attr = iter.next();\n                        AbstractAttribute compositeAbstractAttrib = (AbstractAttribute) attr;\n                        Object value = valueMap.get(compositeAbstractAttrib.getJPAColumnName()) == null ? valueMap\n                                .get(compositeAbstractAttrib.getJPAColumnName().toUpperCase()) == null ? valueMap\n                                .get(compositeAbstractAttrib.getJPAColumnName().toLowerCase()) : valueMap\n                                .get(compositeAbstractAttrib.getJPAColumnName().toUpperCase()) : valueMap\n                                .get(compositeAbstractAttrib.getJPAColumnName());\n                        setFieldValue(compoundKey, value, attr);\n                    }\n                    PropertyAccessorHelper.setId(entity, m, compoundKey);\n                }\n                else\n                {\n                    setId(entity, rowKey, m);\n                }\n\n                Set<Attribute> columns = entityType.getAttributes();\n\n                for (Attribute column : columns)\n                {\n                    if (!column.equals(m.getIdAttribute()))\n                    {\n                        String jpaColumnName = ((AbstractAttribute) column).getJPAColumnName();\n\n                        Class javaType = ((AbstractAttribute) column).getBindableJavaType();\n                        if (metaModel.isEmbeddable(javaType))\n                        {\n                            onViaEmbeddable(column, entity, metaModel, valueMap);\n                        }\n                        else if (!column.isAssociation())\n                        {\n                            Object valueObject = valueMap.get(jpaColumnName) == null ? valueMap.get(jpaColumnName\n                                    .toUpperCase()) == null ? valueMap.get(jpaColumnName.toLowerCase()) : valueMap\n                                    .get(jpaColumnName.toUpperCase()) : valueMap.get(jpaColumnName);\n                            if (valueObject != null && AttributeType.getType(javaType).equals(AttributeType.ENUM))\n                            {\n                                EnumAccessor accessor = new EnumAccessor();\n                                valueObject = accessor.fromString(javaType, valueObject.toString());\n                                setFieldValue(entity, valueObject, column);\n                            }\n                            else if(valueObject != null)\n                            {\n                                setFieldValue(entity, valueObject, column);\n                            }\n                        }\n                        else if (m.getRelationNames() != null)\n                        {\n                            if (m.getRelationNames().contains(jpaColumnName) && !jpaColumnName.equals(idColumnName))\n                            {\n                                Object colValue = valueMap.get(jpaColumnName) == null ? valueMap.get(jpaColumnName\n                                        .toUpperCase()) == null ? valueMap.get(jpaColumnName.toLowerCase()) : valueMap\n                                                .get(jpaColumnName.toUpperCase()) : valueMap.get(jpaColumnName);\n                                if (colValue != null)\n                                {\n                                    relationValue.put(jpaColumnName, colValue);\n                                }\n                            }\n                        }\n                    }\n                }\n                return relationValue;\n            }\n            catch (Exception ex)\n            {\n                throw new EntityReaderException(ex);\n            }\n        }\n        throw new EntityReaderException(\"Can not be translated into entity.\");\n    }\n\n    /**\n     * @param entityType\n     * @param column\n     * @param m\n     * @param entity\n     * @param embeddable\n     * @param valueMap\n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     */\n    private static void onViaEmbeddable(Attribute column, Object entity, Metamodel metamodel,\n            Map<String, Object> valueMap) throws InstantiationException, IllegalAccessException\n    {\n        EmbeddableType embeddable = metamodel.embeddable(((AbstractAttribute) column).getBindableJavaType());\n        Field embeddedField = (Field) column.getJavaMember();\n        Object embeddedDocumentObject = null;\n\n        if (column.isCollection())\n        {\n            Class embeddedObjectClass = PropertyAccessorHelper.getGenericClass(embeddedField);\n\n            embeddedDocumentObject = valueMap.get(((AbstractAttribute) column).getJPAColumnName());\n\n            if (embeddedDocumentObject != null)\n            {\n                Collection embeddedCollection = getCollectionFromDocumentList(metamodel,\n                        (List<Map<String, Object>>) embeddedDocumentObject, embeddedField.getType(),\n                        embeddedObjectClass, embeddable.getAttributes());\n                PropertyAccessorHelper.set(entity, embeddedField, embeddedCollection);\n            }\n        }\n        else\n        {\n            Object obj = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());\n            if (obj == null)\n            {\n                obj = ((AbstractAttribute) column).getBindableJavaType().newInstance();\n            }\n            embeddedDocumentObject = valueMap.get(((AbstractAttribute) column).getJPAColumnName());\n            if(embeddedDocumentObject != null)\n            PropertyAccessorHelper.set(\n                    entity,\n                    embeddedField,\n                    getObjectFromDocument(metamodel, (Map<String, Object>) embeddedDocumentObject,\n                            embeddable.getAttributes(), obj));\n        }\n    }\n\n    /**\n     * Creates a collection of <code>embeddedObjectClass</code> instances\n     * wherein each element is java object representation of MongoDB document\n     * object contained in <code>documentList</code>. Field names are determined\n     * from <code>columns</code>.\n     * \n     * @param documentList\n     *            the document list\n     * @param embeddedCollectionClass\n     *            the embedded collection class\n     * @param embeddedObjectClass\n     *            the embedded object class\n     * @param columns\n     *            the columns\n     * @param metamodel\n     * @return the collection from document list\n     */\n    private static Collection<?> getCollectionFromDocumentList(Metamodel metamodel,\n            List<Map<String, Object>> documentList, Class embeddedCollectionClass, Class embeddedObjectClass,\n            Set<Attribute> columns)\n    {\n        Collection<Object> embeddedCollection = null;\n        if (embeddedCollectionClass.equals(Set.class))\n        {\n            embeddedCollection = new HashSet<Object>();\n        }\n        else if (embeddedCollectionClass.equals(List.class))\n        {\n            embeddedCollection = new ArrayList<Object>();\n        }\n        else\n        {\n            throw new PersistenceException(\"Invalid collection class \" + embeddedCollectionClass\n                    + \"; only Set and List allowed\");\n        }\n\n        for (Map<String, Object> dbObj : documentList)\n        {\n            try\n            {\n                Object obj = embeddedObjectClass.newInstance();\n                embeddedCollection.add(getObjectFromDocument(metamodel, dbObj, columns, obj));\n            }\n            catch (InstantiationException e)\n            {\n                throw new PersistenceException(e);\n            }\n            catch (IllegalAccessException e)\n            {\n                throw new PersistenceException(e);\n            }\n        }\n        return embeddedCollection;\n    }\n\n    /**\n     * Creates an instance of <code>clazz</code> and populates fields fetched\n     * from MongoDB document object. Field names are determined from\n     * <code>columns</code>\n     * \n     * @param documentObj\n     *            the document obj\n     * @param clazz\n     *            the clazz\n     * @param columns\n     *            the columns\n     * @return the object from document\n     * @throws IllegalAccessException\n     * @throws InstantiationException\n     */\n    private static Object getObjectFromDocument(Metamodel metamodel, Map<String, Object> documentObj,\n            Set<Attribute> columns, Object obj) throws InstantiationException, IllegalAccessException\n    {\n        for (Attribute column : columns)\n        {\n            Object value = documentObj.get(((AbstractAttribute) column).getJPAColumnName());\n\n            if (((MetamodelImpl) metamodel).isEmbeddable(((AbstractAttribute) column).getBindableJavaType()))\n            {\n                onViaEmbeddable(column, obj, metamodel, (Map<String, Object>) value);\n            }\n            else\n            {\n                setFieldValue(obj, value, column);\n            }\n        }\n        return obj;\n    }\n\n    private static void setFieldValue(Object entity, Object value, Attribute column)\n    {\n        value = PropertyAccessorHelper.fromSourceToTargetClass(column.getJavaType(), value.getClass(), value);\n        PropertyAccessorHelper.set(entity, (Field) column.getJavaMember(), value);\n    }\n\n    private static void setId(Object entity, Object value, EntityMetadata m)\n    {\n        value = PropertyAccessorHelper.fromSourceToTargetClass(m.getIdAttribute().getJavaType(), value.getClass(),\n                value);\n        PropertyAccessorHelper.setId(entity, m, value);\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/main/java/com/impetus/client/rdbms/RDBMSClientFactory.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rdbms;\n\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.PersistenceException;\n\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.StatelessSession;\nimport org.hibernate.boot.registry.StandardServiceRegistryBuilder;\nimport org.hibernate.cfg.Configuration;\nimport org.hibernate.service.ServiceRegistry;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.rdbms.query.RDBMSEntityReader;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\n\n/**\n * A factory for creating RDBMSClient objects.\n * \n * @author vivek.mishra\n */\npublic class RDBMSClientFactory extends GenericClientFactory\n{\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(RDBMSClientFactory.class);\n\n    /** The conf. */\n    private Configuration conf;\n\n    /** The sf. */\n    private SessionFactory sf;\n\n    private ServiceRegistry serviceRegistry;\n\n    @Override\n    public void destroy()\n    {\n        unload();\n\n        if (sf != null && !sf.isClosed())\n        {\n            sf.close();\n            sf = null;\n        }\n        indexManager.close();\n        externalProperties = null;\n    }\n\n    @Override\n    public void initialize(Map<String, Object> externalProperty)\n    {\n        reader = new RDBMSEntityReader(kunderaMetadata);\n        ((RDBMSEntityReader) reader).setFilter(\"where\");\n        setExternalProperties(externalProperty);\n    }\n\n    @Override\n    protected Object createPoolOrConnection()\n    {\n\n        getConfigurationObject();\n        Set<String> pus = kunderaMetadata.getApplicationMetadata().getMetamodelMap().keySet();\n\n        Map<String, Collection<Class<?>>> classes = new HashMap<String, Collection<Class<?>>>();\n\n        for (String pu : pus)\n        {\n            classes.put(pu,\n                    /* Collection<Class<?>> classes = */((MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                            .getMetamodel(pu)).getEntityNameToClassMap().values());\n        }\n        // to keep hibernate happy! As in our case all scanned classes are not\n        // meant for rdbms, so initally i have set depth to zero!\n        conf.setProperty(\"hibernate.max_fetch_depth\", \"0\");\n\n        if (externalProperties != null && !externalProperties.isEmpty())\n        {\n            for (String key : externalProperties.keySet())\n            {\n                Object value = externalProperties.get(key);\n                if (value instanceof String)\n                {\n                    conf.setProperty(key, (String) value);\n                }\n            }\n        }\n\n        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();\n\n        Iterator<Collection<Class<?>>> iter = classes.values().iterator();\n\n        while (iter.hasNext())\n        {\n            for (Class<?> c : iter.next())\n            {\n                conf.addAnnotatedClass(c);\n            }\n        }\n        sf = conf.buildSessionFactory(serviceRegistry);\n\n        String schemaProperty = conf.getProperty(\"hibernate.hbm2ddl.auto\");\n        if (schemaProperty != null && (schemaProperty.equals(\"create\") || schemaProperty.equals(\"create-drop\")))\n        {\n            synchronized (sf)\n            {\n                for (String pu : pus)\n                {\n                    StatelessSession session = sf.openStatelessSession();\n                    if (!pu.equals(getPersistenceUnit()))\n                    {\n                        Collection<Class<?>> collection = classes.get(pu);\n                        for (Class clazz : collection)\n                        {\n                            EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n                            try\n                            {\n                                session.createSQLQuery(\"Drop table \" + metadata.getTableName()).executeUpdate();\n                            }\n                            catch (Exception e)\n                            {\n                                // ignore such drops.\n                            }\n                        }\n                    }\n\n                }\n            }\n        }\n\n        return sf;\n    }\n\n    @Override\n    protected Client instantiateClient(String persistenceUnit)\n    {\n        return new HibernateClient(getPersistenceUnit(), indexManager, reader, this, externalProperties,\n                clientMetadata, kunderaMetadata);\n    }\n\n    @Override\n    public boolean isThreadSafe()\n    {\n        return true;\n    }\n\n    @Override\n    public SchemaManager getSchemaManager(Map<String, Object> puProperties)\n    {\n        return null;\n    }\n\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n        throw new UnsupportedOperationException(\"Load balancing feature is not supported in \"\n                + this.getClass().getSimpleName());\n    }\n\n    /**\n     * Returns configuration object.\n     */\n    private void getConfigurationObject()\n    {\n        RDBMSPropertyReader reader = new RDBMSPropertyReader(externalProperties, kunderaMetadata\n                .getApplicationMetadata().getPersistenceUnitMetadata(getPersistenceUnit()));\n        this.conf = reader.load(getPersistenceUnit());\n    }\n\n    Session getSession()\n    {\n        if (sf != null)\n        {\n            return sf.openSession();\n        }\n        throw new PersistenceException(\"Session factory is not initialized\");\n    }\n\n    StatelessSession getStatelessSession()\n    {\n        if (sf != null)\n        {\n            return sf.openStatelessSession();\n        }\n        throw new PersistenceException(\"Session factory is not initialized\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/main/java/com/impetus/client/rdbms/RDBMSPropertyReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rdbms;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.hibernate.cfg.Configuration;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * @author vivek.mishra\n * \n *         Implementation class to read external property configuration. Extends\n *         {@link AbstractPropertyReader}(future purpose), though none of method\n *         is supported.\n */\npublic class RDBMSPropertyReader extends AbstractPropertyReader\n{\n\n    /** The log instance. */\n    private static final Logger log = LoggerFactory.getLogger(RDBMSPropertyReader.class);\n\n    public RDBMSPropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n    }\n\n    /**\n     * Reads property file which is given in persistence unit\n     * \n     * @param pu\n     */\n\n    public Configuration load(String pu)\n    {\n        Configuration conf = new Configuration().addProperties(puMetadata.getProperties());\n        String propertyFileName = externalProperties != null ? (String) externalProperties\n                .get(PersistenceProperties.KUNDERA_CLIENT_PROPERTY) : null;\n        if (propertyFileName == null)\n        {\n            propertyFileName = puMetadata != null ? puMetadata\n                    .getProperty(PersistenceProperties.KUNDERA_CLIENT_PROPERTY) : null;\n        }\n        if (propertyFileName != null)\n        {\n            PropertyType fileType = PropertyType.value(propertyFileName);\n\n            switch (fileType)\n            {\n            case xml:\n                conf.configure(propertyFileName);\n                break;\n\n            case properties:\n                Properties props = new Properties();\n\n                InputStream ioStream = puMetadata.getClassLoader().getResourceAsStream(propertyFileName);\n                if (ioStream == null)\n                {\n                    propertyFileName = KunderaCoreUtils.resolvePath(propertyFileName);\n                    try\n                    {\n                        ioStream = new FileInputStream(new File(propertyFileName));\n                    }\n                    catch (FileNotFoundException e)\n                    {\n                        log.warn(\"File {} not found, Caused by \", propertyFileName);\n                    }\n                }\n                try\n                {\n                    if (ioStream != null)\n                    {\n                        props.load(ioStream);\n                    }\n                }\n                catch (IOException e)\n                {\n                    log.error(\"Skipping as error occurred while loading property file {}, Cause by : {}.\",\n                            propertyFileName, e);\n                }\n\n                conf.addProperties(props);\n                break;\n\n            default:\n                log.error(\"Unsupported type{} for file{}, skipping load of properties.\", fileType, propertyFileName);\n                break;\n            }\n        }\n\n        return conf;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.AbstractPropertyReader#onXml(com.impetus\n     * .kundera.configure.ClientProperties)\n     */\n    @Override\n    protected void onXml(ClientProperties cp)\n    {\n        throw new UnsupportedOperationException(\"Unsupported, support added with read() method\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/main/java/com/impetus/client/rdbms/query/RDBMSEntityReader.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.rdbms.query;\r\n\r\nimport java.lang.reflect.Field;\r\nimport java.sql.Date;\r\nimport java.util.ArrayList;\r\nimport java.util.Collection;\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Queue;\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.ManyToMany;\r\nimport javax.persistence.ManyToOne;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.OneToOne;\r\nimport javax.persistence.PersistenceException;\r\nimport javax.persistence.Transient;\r\nimport javax.persistence.metamodel.Attribute;\r\nimport javax.persistence.metamodel.EmbeddableType;\r\nimport javax.persistence.metamodel.EntityType;\r\nimport javax.persistence.metamodel.Metamodel;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.client.rdbms.HibernateClient;\r\nimport com.impetus.kundera.client.Client;\r\nimport com.impetus.kundera.client.ClientBase;\r\nimport com.impetus.kundera.client.EnhanceEntity;\r\nimport com.impetus.kundera.metadata.MetadataUtils;\r\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\r\nimport com.impetus.kundera.metadata.model.Relation;\r\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\r\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\r\nimport com.impetus.kundera.persistence.AbstractEntityReader;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\r\nimport com.impetus.kundera.persistence.EntityReader;\r\nimport com.impetus.kundera.property.PropertyAccessorHelper;\r\nimport com.impetus.kundera.query.KunderaQuery;\r\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\r\nimport com.impetus.kundera.query.QueryHandlerException;\r\n\r\n/**\r\n * The Class RDBMSEntityReader.\r\n * \r\n * @author vivek.mishra\r\n */\r\npublic class RDBMSEntityReader extends AbstractEntityReader implements EntityReader\r\n{\r\n\r\n    /** the log used by this class. */\r\n    private static Logger log = LoggerFactory.getLogger(RDBMSEntityReader.class);\r\n\r\n    /** The conditions. */\r\n    private Queue conditions;\r\n\r\n    /** The filter. */\r\n    private String filter;\r\n\r\n    /** The jpa query. */\r\n    private String jpaQuery;\r\n\r\n    /**\r\n     * Instantiates a new rDBMS entity reader.\r\n     * \r\n     * @param luceneQuery\r\n     *            the lucene query\r\n     * @param query\r\n     *            the query\r\n     */\r\n    public RDBMSEntityReader(String query, KunderaQuery kunderaQuery, final KunderaMetadata kunderaMetadata)\r\n    {\r\n        super(kunderaMetadata);\r\n        this.jpaQuery = query;\r\n        this.kunderaQuery = kunderaQuery;\r\n    }\r\n\r\n    /**\r\n     * Instantiates a new rDBMS entity reader.\r\n     */\r\n    public RDBMSEntityReader(final KunderaMetadata kunderaMetadata)\r\n    {\r\n        super(kunderaMetadata);\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.persistence.EntityReader#populateRelation(com.impetus\r\n     * .kundera.metadata.model.EntityMetadata, java.util.List, boolean,\r\n     * com.impetus.kundera.client.Client)\r\n     */\r\n    @Override\r\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\r\n    {\r\n        // TODO: maxresults to be taken care after work on pagination.\r\n\r\n        List<EnhanceEntity> ls = null;\r\n        List<String> relationNames = m.getRelationNames();\r\n        boolean isParent = m.isParent();\r\n        if (!isParent)\r\n        {\r\n            // if it is not a parent.\r\n            String sqlQuery = null;\r\n            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))\r\n            {\r\n                sqlQuery = getSqlQueryFromJPA(m, relationNames, null);\r\n            }\r\n            else\r\n            {\r\n                // prepare lucene query and find.\r\n                Set<String> rSet = fetchDataFromLucene(m.getEntityClazz(), client);\r\n                if (rSet != null && !rSet.isEmpty())\r\n                {\r\n                    filter = \"WHERE\";\r\n                }\r\n                sqlQuery = getSqlQueryFromJPA(m, relationNames, rSet);\r\n            }\r\n            // call client with relation name list and convert to sql query.\r\n\r\n            ls = populateEnhanceEntities(m, relationNames, client, sqlQuery);\r\n        }\r\n        else\r\n        {\r\n            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))\r\n            {\r\n                try\r\n                {\r\n                    List entities = ((HibernateClient) client).find(getSqlQueryFromJPA(m, relationNames, null),\r\n                            new ArrayList<String>(), m);\r\n                    ls = new ArrayList<EnhanceEntity>(entities.size());\r\n                    ls = transform(m, ls, entities);\r\n                }\r\n                catch (Exception e)\r\n                {\r\n                    log.error(\"Error while executing handleAssociation for RDBMS, Caused by {}.\", e);\r\n                    throw new QueryHandlerException(e);\r\n                }\r\n            }\r\n            else\r\n            {\r\n                ls = onAssociationUsingLucene(m, client, ls);\r\n            }\r\n        }\r\n\r\n        return ls;\r\n    }\r\n\r\n    /**\r\n     * Populate enhance entities.\r\n     * \r\n     * @param m\r\n     *            the m\r\n     * @param relationNames\r\n     *            the relation names\r\n     * @param client\r\n     *            the client\r\n     * @param sqlQuery\r\n     *            the sql query\r\n     * @return the list\r\n     */\r\n    private List<EnhanceEntity> populateEnhanceEntities(EntityMetadata m, List<String> relationNames, Client client,\r\n            String sqlQuery)\r\n    {\r\n        List<EnhanceEntity> ls = null;\r\n        List result = ((HibernateClient) client).find(sqlQuery, relationNames, m);\r\n\r\n        if (!result.isEmpty())\r\n        {\r\n            ls = new ArrayList<EnhanceEntity>(result.size());\r\n            for (Object o : result)\r\n            {\r\n                EnhanceEntity entity = null;\r\n                if (!o.getClass().isAssignableFrom(EnhanceEntity.class))\r\n                {\r\n                    entity = new EnhanceEntity(o, getId(o, m), null);\r\n                }\r\n                else\r\n                {\r\n                    entity = (EnhanceEntity) o;\r\n                }\r\n                ls.add(entity);\r\n            }\r\n        }\r\n        return ls;\r\n    }\r\n\r\n    /**\r\n     * Gets the sql query from jpa.\r\n     * \r\n     * @param entityMetadata\r\n     *            the entity metadata\r\n     * @param relations\r\n     *            the relations\r\n     * @param primaryKeys\r\n     *            the primary keys\r\n     * @return the sql query from jpa\r\n     */\r\n    public String getSqlQueryFromJPA(EntityMetadata entityMetadata, List<String> relations, Set<String> primaryKeys)\r\n    {\r\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\r\n        Metamodel metaModel = appMetadata.getMetamodel(entityMetadata.getPersistenceUnit());\r\n\r\n        if (jpaQuery != null)\r\n        {\r\n            String query = appMetadata.getQuery(jpaQuery);\r\n            boolean isNative = kunderaQuery != null ? kunderaQuery.isNative() : false;\r\n\r\n            if (isNative)\r\n            {\r\n                return query != null ? query : jpaQuery;\r\n            }\r\n        }\r\n\r\n        // Suffixing the UNDERSCORE instead of prefix as Oracle 11g complains\r\n        // about invalid characters error while executing the request.\r\n        String aliasName = entityMetadata.getTableName() + \"_\";\r\n\r\n        StringBuilder queryBuilder = new StringBuilder(\"Select \");\r\n\r\n        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\r\n        Set<Attribute> attributes = entityType.getAttributes();\r\n        for (Attribute field : attributes)\r\n        {\r\n            if (!field.isAssociation() && !field.isCollection()\r\n                    && !((Field) field.getJavaMember()).isAnnotationPresent(ManyToMany.class)\r\n                    && !((Field) field.getJavaMember()).isAnnotationPresent(Transient.class)\r\n                    && !((MetamodelImpl) metaModel).isEmbeddable(((AbstractAttribute) field).getBindableJavaType()))\r\n            {\r\n                queryBuilder.append(aliasName);\r\n                queryBuilder.append(\".\");\r\n                queryBuilder.append(((AbstractAttribute) field).getJPAColumnName());\r\n                queryBuilder.append(\", \");\r\n            }\r\n        }\r\n\r\n        // Handle embedded columns, add them to list.\r\n        Map<String, EmbeddableType> embeddedColumns = ((MetamodelImpl) metaModel).getEmbeddables(entityMetadata\r\n                .getEntityClazz());\r\n        for (EmbeddableType embeddedCol : embeddedColumns.values())\r\n        {\r\n            Set<Attribute> embeddedAttributes = embeddedCol.getAttributes();\r\n            for (Attribute column : embeddedAttributes)\r\n            {\r\n                queryBuilder.append(aliasName);\r\n                queryBuilder.append(\".\");\r\n                queryBuilder.append(((AbstractAttribute) column).getJPAColumnName());\r\n                queryBuilder.append(\", \");\r\n            }\r\n        }\r\n\r\n        if (relations != null)\r\n        {\r\n            for (String relation : relations)\r\n            {\r\n                Relation rel = entityMetadata.getRelation(entityMetadata.getFieldName(relation));\r\n                String r = MetadataUtils.getMappedName(entityMetadata, rel, kunderaMetadata);\r\n                if (!((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName().equalsIgnoreCase(\r\n                        r != null ? r : relation)\r\n                        && rel != null\r\n                        && !rel.getProperty().isAnnotationPresent(ManyToMany.class)\r\n                        && !rel.getProperty().isAnnotationPresent(OneToMany.class)\r\n                        && (rel.getProperty().isAnnotationPresent(OneToOne.class)\r\n                                && StringUtils.isBlank(rel.getMappedBy()) || rel.getProperty().isAnnotationPresent(\r\n                                ManyToOne.class)))\r\n                {\r\n                    queryBuilder.append(aliasName);\r\n                    queryBuilder.append(\".\");\r\n                    queryBuilder.append(r != null ? r : relation);\r\n                    queryBuilder.append(\", \");\r\n                }\r\n            }\r\n        }\r\n\r\n        // Remove last \",\"\r\n        queryBuilder.deleteCharAt(queryBuilder.lastIndexOf(\",\"));\r\n\r\n        queryBuilder.append(\" From \");\r\n        if (entityMetadata.getSchema() != null && !entityMetadata.getSchema().isEmpty())\r\n        {\r\n            queryBuilder.append(entityMetadata.getSchema() + \".\");\r\n        }\r\n        queryBuilder.append(entityMetadata.getTableName());\r\n        queryBuilder.append(\" \");\r\n        queryBuilder.append(aliasName);\r\n        // add conditions\r\n        if (filter != null)\r\n        {\r\n            queryBuilder.append(\" Where \");\r\n        }\r\n\r\n        // Append conditions\r\n        onCondition(entityMetadata, (MetamodelImpl) metaModel, primaryKeys, aliasName, queryBuilder, entityType);\r\n\r\n        return queryBuilder.toString();\r\n    }\r\n\r\n    /**\r\n     * \r\n     * @param entityMetadata\r\n     * @param primaryKeys\r\n     * @param aliasName\r\n     * @param queryBuilder\r\n     * @param entityType\r\n     */\r\n    private void onCondition(EntityMetadata entityMetadata, MetamodelImpl metamodel, Set<String> primaryKeys,\r\n            String aliasName, StringBuilder queryBuilder, EntityType entityType)\r\n    {\r\n        if (primaryKeys == null)\r\n        {\r\n            for (Object o : conditions)\r\n            {\r\n                if (o instanceof FilterClause)\r\n                {\r\n                    FilterClause clause = ((FilterClause) o);\r\n                    Object value = clause.getValue().get(0);\r\n                    String propertyName = clause.getProperty();\r\n                    String condition = clause.getCondition();\r\n\r\n                    if (StringUtils.contains(propertyName, '.'))\r\n                    {\r\n                        int indexOf = propertyName.indexOf(\".\");\r\n                        String jpaColumnName = propertyName.substring(0, indexOf);\r\n                        String embeddedColumnName = propertyName.substring(indexOf + 1, propertyName.length());\r\n                        String fieldName = entityMetadata.getFieldName(jpaColumnName);\r\n                        Attribute attribute = entityType.getAttribute(fieldName);\r\n                        EmbeddableType embeddedType = metamodel.embeddable(((AbstractAttribute) attribute)\r\n                                .getBindableJavaType());\r\n                        Attribute embeddedAttribute = embeddedType.getAttribute(embeddedColumnName);\r\n\r\n                        addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition, fieldName,\r\n                                embeddedAttribute);\r\n                    }\r\n                    else\r\n                    {\r\n                        String fieldName = entityMetadata.getFieldName(propertyName);\r\n                        Attribute attribute = entityType.getAttribute(fieldName);\r\n                        if (metamodel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType()))\r\n                        {\r\n                            EmbeddableType embeddedType = metamodel.embeddable(((AbstractAttribute) attribute)\r\n                                    .getBindableJavaType());\r\n                            Set<Attribute> attributes = embeddedType.getAttributes();\r\n                            for (Attribute embeddedAttribute : attributes)\r\n                            {\r\n                                Object embeddedAttributevalue = PropertyAccessorHelper.getObject(value,\r\n                                        (Field) embeddedAttribute.getJavaMember());\r\n                                addClause(entityMetadata, aliasName, queryBuilder, entityType, embeddedAttributevalue,\r\n                                        condition, propertyName, embeddedAttribute);\r\n                                queryBuilder.append(\" and \");\r\n                            }\r\n\r\n                            queryBuilder.delete(queryBuilder.lastIndexOf(\"and\"), queryBuilder.lastIndexOf(\"and\") + 3);\r\n                        }\r\n                        else if (((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName().equals(\r\n                                propertyName))\r\n                        {\r\n                            addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition,\r\n                                    propertyName, entityMetadata.getIdAttribute());\r\n                        }\r\n                        else\r\n                        {\r\n                            addClause(entityMetadata, aliasName, queryBuilder, entityType, value, condition,\r\n                                    propertyName, attribute);\r\n                        }\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    queryBuilder.append(\" \");\r\n                    queryBuilder.append(o);\r\n                    queryBuilder.append(\" \");\r\n                }\r\n            }\r\n        }\r\n        else\r\n        {\r\n            queryBuilder.append(aliasName);\r\n            queryBuilder.append(\".\");\r\n            queryBuilder.append(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName());\r\n            queryBuilder.append(\" \");\r\n            queryBuilder.append(\"IN(\");\r\n            int count = 0;\r\n            Attribute col = entityMetadata.getIdAttribute();\r\n            boolean isString = isStringProperty(entityType, col);\r\n            for (String key : primaryKeys)\r\n            {\r\n                appendStringPrefix(queryBuilder, isString);\r\n                queryBuilder.append(key);\r\n                appendStringPrefix(queryBuilder, isString);\r\n                if (++count != primaryKeys.size())\r\n                {\r\n                    queryBuilder.append(\",\");\r\n                }\r\n                else\r\n                {\r\n                    queryBuilder.append(\")\");\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * \r\n     * @param entityMetadata\r\n     * @param aliasName\r\n     * @param queryBuilder\r\n     * @param entityType\r\n     * @param value\r\n     * @param condition\r\n     * @param propertyName\r\n     * @param attribute\r\n     */\r\n    private void addClause(EntityMetadata entityMetadata, String aliasName, StringBuilder queryBuilder,\r\n            EntityType entityType, Object value, String condition, String propertyName, Attribute attribute)\r\n    {\r\n        boolean isString = isStringProperty(entityType, attribute);\r\n\r\n        // queryBuilder.append(aliasName);\r\n        // queryBuilder.append(\".\");\r\n        queryBuilder.append(StringUtils.replace(((AbstractAttribute) attribute).getJPAColumnName(), aliasName,\r\n                aliasName));\r\n\r\n        queryBuilder.append(\" \");\r\n        queryBuilder.append(condition);\r\n\r\n        if (condition.equalsIgnoreCase(\"like\"))\r\n        {\r\n            queryBuilder.append(\"%\");\r\n        }\r\n        queryBuilder.append(\" \");\r\n        if (condition.equalsIgnoreCase(\"IN\"))\r\n        {\r\n            buildINClause(queryBuilder, value, isString);\r\n        }\r\n        else\r\n        {\r\n            appendStringPrefix(queryBuilder, isString);\r\n            queryBuilder.append(value);\r\n            appendStringPrefix(queryBuilder, isString);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * \r\n     * @param queryBuilder\r\n     * @param value\r\n     * @param isString\r\n     */\r\n    private void buildINClause(StringBuilder queryBuilder, Object value, boolean isString)\r\n    {\r\n        if (List.class.isAssignableFrom(value.getClass()) || Set.class.isAssignableFrom(value.getClass()))\r\n        {\r\n            queryBuilder.append(\" (\");\r\n            Collection collection = ((Collection) value);\r\n            for (Object obj : collection)\r\n            {\r\n                if (isString)\r\n                {\r\n                    appendStringPrefix(queryBuilder, isString);\r\n                }\r\n                queryBuilder.append(obj.toString());\r\n                if (isString)\r\n                {\r\n                    appendStringPrefix(queryBuilder, isString);\r\n                }\r\n                queryBuilder.append(\",\");\r\n            }\r\n            if (!collection.isEmpty())\r\n            {\r\n                queryBuilder.deleteCharAt(queryBuilder.lastIndexOf(\",\"));\r\n            }\r\n            queryBuilder.append(\")\");\r\n        }\r\n        else\r\n        {\r\n            queryBuilder.append(value.toString());\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Append string prefix.\r\n     * \r\n     * @param queryBuilder\r\n     *            the query builder\r\n     * @param isString\r\n     *            the is string\r\n     */\r\n    private void appendStringPrefix(StringBuilder queryBuilder, boolean isString)\r\n    {\r\n        if (isString)\r\n        {\r\n            queryBuilder.append(\"'\");\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Sets the conditions.\r\n     * \r\n     * @param q\r\n     *            the new conditions\r\n     */\r\n    public void setConditions(Queue q)\r\n    {\r\n        this.conditions = q;\r\n    }\r\n\r\n    /**\r\n     * Sets the filter.\r\n     * \r\n     * @param filter\r\n     *            the new filter\r\n     */\r\n    public void setFilter(String filter)\r\n    {\r\n        this.filter = filter;\r\n    }\r\n\r\n    /**\r\n     * Populate relations.\r\n     * \r\n     * @param relations\r\n     *            the relations\r\n     * @param o\r\n     *            the o\r\n     * @return the map\r\n     */\r\n    private Map<String, Object> populateRelations(List<String> relations, Object[] o)\r\n    {\r\n        Map<String, Object> relationVal = new HashMap<String, Object>(relations.size());\r\n        int counter = 1;\r\n        for (String r : relations)\r\n        {\r\n            relationVal.put(r, o[counter++]);\r\n        }\r\n        return relationVal;\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see\r\n     * com.impetus.kundera.persistence.EntityReader#findById(java.lang.Object,\r\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.util.List,\r\n     * com.impetus.kundera.client.Client)\r\n     */\r\n    @Override\r\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\r\n    {\r\n        List<String> relationNames = m.getRelationNames();\r\n        if (relationNames != null && !relationNames.isEmpty())\r\n        {\r\n            Set<String> keys = new HashSet<String>(1);\r\n            keys.add(primaryKey.toString());\r\n            String query = getSqlQueryFromJPA(m, relationNames, keys);\r\n            List<EnhanceEntity> results = populateEnhanceEntities(m, relationNames, client, query);\r\n            return results != null && !results.isEmpty() ? results.get(0) : null;\r\n        }\r\n        else\r\n        {\r\n            Object o;\r\n            try\r\n            {\r\n                o = client.find(m.getEntityClazz(), primaryKey);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                throw new PersistenceException(e);\r\n            }\r\n            return o != null ? new EnhanceEntity(o, getId(o, m), null) : null;\r\n        }\r\n\r\n        // return super.findById(primaryKey, m, client);\r\n    }\r\n\r\n    /**\r\n     * Checks if is string property.\r\n     * \r\n     * @param m\r\n     *            the m\r\n     * @param fieldName\r\n     *            the field name\r\n     * @return true, if is string property\r\n     */\r\n    private boolean isStringProperty(EntityType entityType, Attribute attribute)\r\n    {\r\n        String discriminatorColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\r\n\r\n        if (attribute.getName().equals(discriminatorColumn))\r\n        {\r\n            return true;\r\n        }\r\n\r\n        return attribute != null ? ((AbstractAttribute) attribute).getBindableJavaType().isAssignableFrom(String.class)\r\n                || ((AbstractAttribute) attribute).getBindableJavaType().isAssignableFrom(Character.class)\r\n                || ((AbstractAttribute) attribute).getBindableJavaType().isAssignableFrom(char.class)\r\n                || ((AbstractAttribute) attribute).getBindableJavaType().isAssignableFrom(Date.class)\r\n                || ((AbstractAttribute) attribute).getBindableJavaType().isAssignableFrom(java.util.Date.class) : false;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-rdbms/src/main/java/com/impetus/client/rdbms/query/RDBMSQuery.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rdbms.query;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.Parameter;\nimport javax.persistence.Query;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.rdbms.HibernateClient;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.QueryHandlerException;\nimport com.impetus.kundera.query.QueryImpl;\nimport com.impetus.kundera.utils.ReflectUtils;\n\n/**\n * The Class RDBMSQuery.\n * \n * @author vivek.mishra\n */\npublic class RDBMSQuery extends QueryImpl\n{\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(RDBMSQuery.class);\n\n    /** The reader. */\n    private RDBMSEntityReader reader;\n\n    /**\n     * Instantiates a new RDBMS query.\n     * \n     * @param query\n     *            the query\n     * @param kunderaQuery\n     *            the kundera query\n     * @param persistenceDelegator\n     *            the persistence delegator\n     * @param persistenceUnits\n     *            the persistence units\n     */\n    public RDBMSQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n    }\n\n    @Override\n    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n        // retrieve\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"On handleAssociation() retrieve associations \");\n        }\n\n        initializeReader();\n\n        List<EnhanceEntity> ls = getReader().populateRelation(m, client, this.maxResult);\n\n        return setRelationEntities(ls, client, m);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    protected List<Object> populateEntities(EntityMetadata m, Client client)\n    {\n        if (log.isDebugEnabled())\n        {\n            log.debug(\"on start of fetching non associated entities\");\n        }\n        List<Object> result = new ArrayList<Object>();\n\n        initializeReader();\n\n        try\n        {\n            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))\n            {\n                List<String> relations = new ArrayList<String>();\n                if (kunderaQuery.isNative())\n                {\n                    return ((HibernateClient) client).find(getJPAQuery(), relations, m);\n\n                }\n                else\n                {\n                    return ((HibernateClient) client).findByQuery(getJPAQuery(), getParamaters(), firstResult, maxResult);\n\n                }\n            }\n            else\n            {\n                return populateUsingLucene(m, client, result, null);\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error during query execution, Caused by: {}.\", e);\n            throw new QueryHandlerException(e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#getReader()\n     */\n    @Override\n    protected RDBMSEntityReader getReader()\n    {\n        if (reader == null)\n        {\n            reader = new RDBMSEntityReader(getJPAQuery(), kunderaQuery, kunderaMetadata);\n        }\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()\n     */\n    @Override\n    protected int onExecuteUpdate()\n    {\n        EntityMetadata m = getEntityMetadata();\n\n        Client client = persistenceDelegeator.getClient(m);\n        return ((HibernateClient) client).onExecuteUpdate(getJPAQuery(), getParamaters(), firstResult, maxResult);\n    }\n\n    /**\n     * Initializes reader with conditions and filter in case for JPA/Named query\n     * only!\n     * \n     */\n    private void initializeReader()\n    {\n        boolean isNative = kunderaQuery.isNative();\n\n        if (!isNative)\n        {\n            getReader().setConditions(getKunderaQuery().getFilterClauseQueue());\n\n            getReader().setFilter(getKunderaQuery().getFilter());\n        }\n    }\n\n    @Override\n    public void close()\n    {\n        this.reader = null;\n    }\n\n    @Override\n    public Iterator iterate()\n    {\n        if (kunderaQuery.isNative())\n        {\n            throw new UnsupportedOperationException(\"Iteration not supported over native queries\");\n        }\n\n        initializeReader();\n        EntityMetadata m = getEntityMetadata();\n        Client client = persistenceDelegeator.getClient(m);\n        return new ResultIterator((HibernateClient) client, m, persistenceDelegeator,\n                getFetchSize() != null ? getFetchSize() : this.maxResult,\n                ((RDBMSEntityReader) getReader()).getSqlQueryFromJPA(m, m.getRelationNames(), null));\n    }\n\n    /**\n     * Gets the column list.\n     * \n     * @param m\n     *            the m\n     * @param results\n     *            the results\n     * @return the column list\n     */\n    List<String> getColumnList(EntityMetadata m, String[] results, EmbeddableType compoundKey)\n    {\n        List<String> columns = new ArrayList<String>();\n        if (results != null && results.length > 0)\n        {\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n            EntityType entity = metaModel.entity(m.getEntityClazz());\n\n            for (int i = 1; i < results.length; i++)\n            {\n                if (results[i] != null)\n                {\n                    Attribute attribute = entity.getAttribute(results[i]);\n\n                    if (attribute == null)\n                    {\n                        throw new QueryHandlerException(\"column type is null for: \" + results);\n                    }\n                    else if (m.getIdAttribute().equals(attribute) && compoundKey != null)\n                    {\n                        Field[] fields = m.getIdAttribute().getBindableJavaType().getDeclaredFields();\n                        for (Field field : fields)\n                        {\n                            if (!ReflectUtils.isTransientOrStatic(field))\n                            {\n                                Attribute compositeColumn = compoundKey.getAttribute(field.getName());\n                                columns.add(((AbstractAttribute) compositeColumn).getJPAColumnName());\n                            }\n                        }\n                    }\n                    else\n                    {\n                        columns.add(((AbstractAttribute) attribute).getJPAColumnName());\n                    }\n                }\n            }\n            return columns;\n        }\n\n        if (log.isInfoEnabled())\n        {\n            log.info(\"No record found, returning null.\");\n        }\n        return null;\n    }\n\n    private Map<Parameter, Object> getParamaters()\n    {\n        Map<Parameter, Object> parameterMap = new HashMap<Parameter, Object>();\n\n        if (getKunderaQuery().getParameters() == null || getKunderaQuery().getParameters().isEmpty())\n        {\n            return parameterMap;\n        }\n\n        for (Parameter parameter : getKunderaQuery().getParameters())\n        {\n            parameterMap.put(parameter, getKunderaQuery().getClauseValue(parameter));\n        }\n        return parameterMap;\n    }\n\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n        return ((HibernateClient) client).findByQuery(getJPAQuery(), getParamaters(), firstResult, maxResult);\n    }\n    \n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#setFirstResult(int)\n     */\n    @Override\n    public Query setFirstResult(int firstResult)\n    {\n        return super.setFirstResult(firstResult);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#setMaxResults(int)\n     */\n    @Override\n    public Query setMaxResults(int maxResult)\n    {\n        return super.setMaxResults(maxResult);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/main/java/com/impetus/client/rdbms/query/ResultIterator.java",
    "content": "/**\n * Copyright 2014 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.rdbms.query;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport javax.persistence.PersistenceException;\n\nimport org.hibernate.SQLQuery;\n\nimport com.impetus.client.rdbms.HibernateClient;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.IResultIterator;\n\n/**\n * @author kuldeep.mishra .\n * \n *         Implementation of RDBMS result iteration.\n * \n * @param <E>\n */\nclass ResultIterator<E> implements IResultIterator<E>\n{\n    private EntityMetadata m;\n\n    private HibernateClient client;\n\n    private int fetchSize;\n\n    private PersistenceDelegator persistenceDelegator;\n\n    private SQLQuery sqlQuery;\n\n    private List result;\n\n    private int firstResultIndex;\n\n    private int maxResultIndex;\n\n    ResultIterator(HibernateClient client, EntityMetadata m, PersistenceDelegator pd, int fetchSize, String query)\n    {\n        this.m = m;\n        this.client = client;\n        this.fetchSize = fetchSize;\n        this.maxResultIndex = fetchSize;\n        this.persistenceDelegator = pd;\n        this.sqlQuery = client.getQueryInstance(query, m);\n    }\n\n    @Override\n    public boolean hasNext()\n    {\n        if (firstResultIndex < maxResultIndex)\n        {\n            // TODO:namedquery, JPQL, HQL => iterate, native => then don't\n\n            result = sqlQuery.setFirstResult(firstResultIndex++).setMaxResults(1).list();\n        }\n\n        return result != null && !result.isEmpty() && fetchSize != 0;\n    }\n\n    @Override\n    public E next()\n    {\n        if (result == null || result.isEmpty() || fetchSize == 0)\n        {\n            throw new NoSuchElementException(\"Nothing to scroll further for: \" + m.getEntityClazz());\n        }\n\n        fetchSize--;\n\n        Object nextResult = result.get(0);\n\n        result = null;\n\n        Class clazz = m.getEntityClazz();\n        E entity = null;\n        entity = instantiateEntity(clazz, entity);\n\n        boolean noRelationFound = true;\n        if (!nextResult.getClass().isAssignableFrom(clazz))\n        {\n            entity = (E) ((Object[]) nextResult)[0];\n            noRelationFound = false;\n        }\n        else\n        {\n            entity = (E) nextResult;\n        }\n\n        Object id = PropertyAccessorHelper.getId(entity, m);\n        entity = (E) new EnhanceEntity(entity, id, noRelationFound ? null : populateRelations(m.getRelationNames(),\n                (Object[]) nextResult));\n\n        if (!m.isRelationViaJoinTable() && (m.getRelationNames() == null || (m.getRelationNames().isEmpty())))\n        {\n            return entity;\n        }\n        else\n        {\n            List<EnhanceEntity> ls = new ArrayList<EnhanceEntity>();\n            ls.add((EnhanceEntity) entity);\n            return setRelationEntities(ls.get(0), client, m);\n        }\n    }\n\n    /**\n     * \n     * @param entityClazz\n     * @param entity\n     * @return\n     */\n    private E instantiateEntity(Class<?> entityClazz, Object entity)\n    {\n        try\n        {\n            if (entity == null)\n            {\n                return (E) entityClazz.newInstance();\n            }\n            return (E) entity;\n        }\n        catch (InstantiationException e)\n        {\n            throw new PersistenceException(\"Error while instantiating entity \" + entityClazz + \".\", e);\n        }\n        catch (IllegalAccessException e)\n        {\n            throw new PersistenceException(\"Error while instantiating entity \" + entityClazz + \".\", e);\n        }\n    }\n\n    @Override\n    public void remove()\n    {\n        throw new UnsupportedOperationException(\"Remove method is not supported over pagination\");\n    }\n\n    @Override\n    public List<E> next(int chunkSize)\n    {\n        throw new UnsupportedOperationException(\"Fetch in chunks is not yet supported\");\n    }\n\n    /**\n     * \n     * @param enhanceEntity\n     * @param client\n     * @param m\n     * @return\n     */\n    private E setRelationEntities(Object enhanceEntity, Client client, EntityMetadata m)\n    {\n        // Enhance entities can contain or may not contain relation.\n        // if it contain a relation means it is a child\n        // if it does not then it means it is a parent.\n        E result = null;\n        if (enhanceEntity != null)\n        {\n            if (!(enhanceEntity instanceof EnhanceEntity))\n            {\n                enhanceEntity = new EnhanceEntity(enhanceEntity, PropertyAccessorHelper.getId(enhanceEntity, m), null);\n            }\n            EnhanceEntity ee = (EnhanceEntity) enhanceEntity;\n\n            result = (E) client.getReader().recursivelyFindEntities(ee.getEntity(), ee.getRelations(), m,\n                    persistenceDelegator, false, new HashMap<Object, Object>());\n        }\n        return result;\n    }\n\n    /**\n     * Populate relations.\n     * \n     * @param relations\n     *            the relations\n     * @param o\n     *            the o\n     * @return the map\n     */\n    private Map<String, Object> populateRelations(List<String> relations, Object[] o)\n    {\n        Map<String, Object> relationVal = new HashMap<String, Object>(relations.size());\n        int counter = 1;\n        for (String r : relations)\n        {\n            relationVal.put(r, o[counter++]);\n        }\n        return relationVal;\n    }\n}"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/BaseTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport com.impetus.client.crud.entities.PersonRDBMS;\n\n/**\n * The Class BaseTest.\n * \n * @author vivek.mishra\n */\npublic abstract class BaseTest\n{\n    /**\n     * Prepare rdbms instance.\n     * \n     * @param rowKey\n     *            the row key\n     * @param age\n     *            the age\n     * @return the person rdbms\n     */\n    protected PersonRDBMS prepareRDBMSInstance(String rowKey, int age)\n    {\n        PersonRDBMS o = new PersonRDBMS();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age);\n        return o;\n    }\n\n    /**\n     * Find by id.\n     * \n     * @param <E>\n     *            the element type\n     * @param clazz\n     *            the clazz\n     * @param rowKey\n     *            the row key\n     * @param em\n     *            the em\n     * @return the e\n     */\n    protected <E extends Object> E findById(Class<E> clazz, Object rowKey, EntityManager em)\n    {\n        return em.find(clazz, rowKey);\n    }\n\n    /**\n     * Assert find by name.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByName(EntityManager em, String clazz, E e, String name,\n            String fieldName)\n    {\n\n        String query = \"Select p from \" + clazz + \" p where p.\" + fieldName + \" = '\" + name +\"'\";\n        // // find by name.\n        Query q = em.createQuery(query);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n\n    }\n\n    /**\n     * Assert find by name and age.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param minVal\n     *            the min val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByNameAndAge(EntityManager em, String clazz, E e, String name,\n            String minVal, String fieldName)\n    {\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = '\" + name + \"' and p.age > \"\n                + minVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n    }\n\n    /**\n     * Assert find by name and age gt and lt.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param minVal\n     *            the min val\n     * @param maxVal\n     *            the max val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByNameAndAgeGTAndLT(EntityManager em, String clazz, E e, String name,\n            String minVal, String maxVal, String fieldName)\n    {\n        // // // find by name, age clause\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = '\" + name + \"' and p.age > \"\n                + minVal + \" and p.age < \" + maxVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(1, results.size());\n    }\n\n    /**\n     * Assert find by name and age between.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param name\n     *            the name\n     * @param minVal\n     *            the min val\n     * @param maxVal\n     *            the max val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByNameAndAgeBetween(EntityManager em, String clazz, E e, String name,\n            String minVal, String maxVal, String fieldName)\n    {\n        // // find by between clause\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = '\" + name\n                + \"' and p.age between \" + minVal + \" and \" + maxVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n\n    }\n\n    /**\n     * Assert find by range.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param minVal\n     *            the min val\n     * @param maxVal\n     *            the max val\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertFindByRange(EntityManager em, String clazz, E e, String minVal,\n            String maxVal, String fieldName)\n\n    {\n        // find by Range.\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" Between \" + minVal + \" and \"\n                + maxVal);\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n    }\n\n    /**\n     * Assert find without where clause.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     */\n    protected <E extends Object> void assertFindWithoutWhereClause(EntityManager em, String clazz, E e)\n    {\n        // find by without where clause.\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p\");\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(3, results.size());\n    }\n\n    /**\n     * Assert on merge.\n     * \n     * @param <E>\n     *            the element type\n     * @param em\n     *            the em\n     * @param clazz\n     *            the clazz\n     * @param e\n     *            the e\n     * @param oldName\n     *            the old name\n     * @param newName\n     *            the new name\n     * @param fieldName\n     *            the field name\n     */\n    protected <E extends Object> void assertOnMerge(EntityManager em, String clazz, E e, String oldName,\n            String newName, String fieldName)\n    {\n        Query q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = '\" + oldName+\"'\");\n        List<E> results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n\n        q = em.createQuery(\"Select p from \" + clazz + \" p where p.\" + fieldName + \" = '\" + newName+\"'\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotSame(oldName, getPersonName(e, results.get(0)));\n        Assert.assertEquals(newName, getPersonName(e, results.get(0)));\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @param <E>\n     *            the element type\n     * @param e\n     *            the e\n     * @param result\n     *            the result\n     * @return the person name\n     */\n    private <E extends Object> String getPersonName(E e, Object result)\n    {\n\n        throw new RuntimeException(\"Support for \" + e + \"is not yet supported\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/PersonRdbmsTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.math.BigInteger;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.PersonRDBMS;\n\npublic class PersonRdbmsTest extends BaseTest\n{\n\n    private static final String SCHEMA = \"testdb\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    private Map<Object, Object> col;\n\n    private RDBMSCli cli;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"testHibernate\");\n        em = emf.createEntityManager();\n        col = new java.util.HashMap<Object, Object>();\n    }\n\n    @Test\n    public void onInsertRdbms() throws Exception\n    {\n        try\n        {\n            cli = new RDBMSCli(SCHEMA);\n            cli.createSchema(SCHEMA);\n            cli.update(\"CREATE TABLE TESTDB.PERSON (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), AGE INTEGER)\");\n        }\n        catch (Exception e)\n        {\n\n            cli.update(\"DELETE FROM TESTDB.PERSON\");\n            cli.update(\"DROP TABLE TESTDB.PERSON\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.PERSON (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), AGE INTEGER)\");\n            // nothing\n            // do\n        }\n\n        Object p1 = prepareRDBMSInstance(\"1\", 10);\n        Object p2 = prepareRDBMSInstance(\"2\", 20);\n        Object p3 = prepareRDBMSInstance(\"3\", 15);\n\n        Query findQuery = em.createQuery(\"Select p from PersonRDBMS p\");\n        List<PersonRDBMS> allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = em.createQuery(\"Select p from PersonRDBMS p where p.personName = 'vivek'\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = em.createQuery(\"Select p.age from PersonRDBMS p where p.personName = 'vivek'\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        em.close();\n        // emf.close();\n        // emf = Persistence.createEntityManagerFactory(\"testHibernate\");\n\n        em = emf.createEntityManager();\n\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        PersonRDBMS personRDBMS = findById(PersonRDBMS.class, \"1\", em);\n        Assert.assertNotNull(personRDBMS);\n        Assert.assertEquals(\"vivek\", personRDBMS.getPersonName());\n        assertFindWithoutWhereClause(em, \"PersonRDBMS\", PersonRDBMS.class);\n        assertFindByName(em, \"PersonRDBMS\", PersonRDBMS.class, \"vivek\", \"personName\");\n        assertFindByNameAndAge(em, \"PersonRDBMS\", PersonRDBMS.class, \"vivek\", \"10\", \"personName\");\n        assertFindByNameAndAgeGTAndLT(em, \"PersonRDBMS\", PersonRDBMS.class, \"vivek\", \"10\", \"20\", \"personName\");\n        assertFindByNameAndAgeBetween(em, \"PersonRDBMS\", PersonRDBMS.class, \"vivek\", \"10\", \"15\", \"personName\");\n        assertFindByRange(em, \"PersonRDBMS\", PersonRDBMS.class, \"1\", \"2\", \"personId\");\n        \n        //test Pagination\n        testPagination();\n\n        // Test IN clause.\n        testINClause();\n\n        // Test Native queries.\n        testNativeQuery();\n        \n    }\n\n    private void testPagination()\n    {\n        Query findQuery = em.createQuery(\"Select p from PersonRDBMS p\");\n        findQuery.setFirstResult(1);\n        findQuery.setMaxResults(2);\n        List<PersonRDBMS> allPersons = findQuery.getResultList();\n        Assert.assertEquals(2, allPersons.size());\n        Assert.assertEquals(\"2\", allPersons.get(0).getPersonId());\n        Assert.assertEquals(\"3\", allPersons.get(1).getPersonId());\n        \n        //extremes\n        findQuery.setFirstResult(5);\n        findQuery.setMaxResults(10);\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n    }\n\n    private void testINClause()\n    {\n        Query findQuery;\n        List<PersonRDBMS> allPersons;\n        findQuery = em.createQuery(\"Select p from PersonRDBMS p where p.personName IN :nameList\");\n        List<String> nameList = new ArrayList<String>();\n        nameList.add(\"vivek\");\n        nameList.add(\"kk\");\n\n        findQuery.setParameter(\"nameList\", nameList);\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(3, allPersons.size());\n\n        findQuery = em.createQuery(\"Select p from PersonRDBMS p where p.personName IN ?1\");\n        findQuery.setParameter(1, nameList);\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(3, allPersons.size());\n\n        em.close();\n\n        em = emf.createEntityManager();\n\n        try\n        {\n            findQuery = em.createQuery(\"Select p from PersonRDBMS p where p.personName IN :nameList\");\n            findQuery.setParameter(\"nameList\", new ArrayList<String>());\n            allPersons = findQuery.getResultList();\n            Assert.fail();\n        }\n        catch (Exception e)\n        {\n            Assert.assertEquals(\n                    \"javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not prepare statement\",\n                    e.getMessage());\n        }\n        findQuery = em.createQuery(\"Select p from PersonRDBMS p where p.personName IN ('vivek', 'kk')\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(3, allPersons.size());\n\n        findQuery = em.createQuery(\"Select p from PersonRDBMS p where p.age IN :ageList\");\n        List<Integer> ageList = new ArrayList<Integer>();\n        ageList.add(10);\n        ageList.add(25);\n        findQuery.setParameter(\"ageList\", ageList);\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(1, allPersons.size());\n\n        em.close();\n\n        em = emf.createEntityManager();\n\n        findQuery = em.createQuery(\"Select p from PersonRDBMS p where p.age IN (10 , 20)\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(2, allPersons.size());\n\n    }\n\n    private void testNativeQuery()\n    {\n\n        Query findQuery;\n        List<PersonRDBMS> allPersons;\n        findQuery = em.createNativeQuery(\"Select * from testdb.PERSON where PERSON_NAME IN ('vivek' , 'kk')\",\n                PersonRDBMS.class);\n\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(3, allPersons.size());\n\n        findQuery = em.createNativeQuery(\"Select * from testdb.PERSON where AGE IN (10, 25)\", PersonRDBMS.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(1, allPersons.size());\n\n        findQuery = em.createNativeQuery(\"Select count(*) from testdb.PERSON\", PersonRDBMS.class);\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertEquals(1, allPersons.size());\n        Assert.assertTrue(allPersons.get(0) instanceof Map);\n        Assert.assertTrue(((Map<String, Object>) allPersons.get(0)).get(\"C1\") != null);\n        Assert.assertTrue(((Map<String, Object>) allPersons.get(0)).get(\"C1\") instanceof BigInteger);\n        Assert.assertTrue(((BigInteger) ((Map<String, Object>) allPersons.get(0)).get(\"C1\")).intValue() == 3);\n    }\n\n    // @Test\n    public void onMergeRdbms()\n    {\n        Object p1 = prepareRDBMSInstance(\"1\", 10);\n        Object p2 = prepareRDBMSInstance(\"2\", 20);\n        Object p3 = prepareRDBMSInstance(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        PersonRDBMS personRDBMS = findById(PersonRDBMS.class, \"1\", em);\n        Assert.assertNotNull(personRDBMS);\n        Assert.assertEquals(\"vivek\", personRDBMS.getPersonName());\n        personRDBMS.setPersonName(\"Newvivek\");\n\n        em.merge(personRDBMS);\n        assertOnMerge(em, \"PersonRDBMS\", PersonRDBMS.class, \"vivek\", \"newvivek\", \"personName\");\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        for (Object val : col.values())\n        {\n            em.remove(val);\n        }\n        em.close();\n        emf.close();\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.PERSON\");\n            cli.update(\"DROP TABLE TESTDB.PERSON\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n        // cli.dropSchema(\"TESTDB\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/RDBMSCli.java",
    "content": "/* Copyright (c) 2001-2005, The HSQL Development Group\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * Neither the name of the HSQL Development Group nor the names of its\n * contributors may be used to endorse or promote products derived from this\n * software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\npackage com.impetus.client.crud;\n\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.ResultSetMetaData;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Title: Testdb Description: simple hello world db example of a standalone\n * persistent db application\n * \n * every time it runs it adds four more rows to sample_table it does a query and\n * prints the results to standard out\n * \n * Author: Karl Meissner karl@meissnersd.com\n */\n\npublic class RDBMSCli\n{\n    static Connection conn; // our connnection to the db - presist for life of\n                            // program\n    /** The Constant logger. */\n    private static final Logger logger = LoggerFactory.getLogger(RDBMSCli.class);\n\n    // we dont want this garbage collected until we are done\n    public RDBMSCli(String db_file_name_prefix) throws Exception\n    { // note more general exception\n\n        // Load the HSQL Database Engine JDBC driver\n        // hsqldb.jar should be in the class path or made part of the current\n        // jar\n        Class.forName(\"org.hsqldb.jdbcDriver\");\n\n        // connect to the database. This will load the db files and start the\n        // database if it is not alread running.\n        // db_file_name_prefix is used to open or create files that hold the\n        // state\n        // of the db.\n        // It can contain directory names relative to the\n        // current working directory\n        conn = DriverManager.getConnection(\"jdbc:hsqldb:mem:\" + db_file_name_prefix, // filenames\n                \"sa\", // username\n                \"\"); // password\n        \n        conn.setAutoCommit(true);\n        \n//        conn.setClientInfo(\"hsqldb.write_delay\", \"false\");\n    }\n\n    public void shutdown() throws SQLException\n    {\n\n        Statement st = conn.createStatement();\n\n        // db writes out to files and performs clean shuts down\n        // otherwise there will be an unclean shutdown\n        // when program ends\n        st.execute(\"SHUTDOWN\");\n        closeConnection();\n    }\n\n    /**\n     * @throws SQLException\n     */\n    public void closeConnection() throws SQLException\n    {\n        if (conn != null)\n        {\n            conn.close(); // if there are no other open connection\n            conn = null;\n        }\n    }\n\n    // use for SQL command SELECT\n    public synchronized static void query(String expression) throws SQLException\n    {\n\n        Statement st = null;\n        ResultSet rs = null;\n\n        st = conn.createStatement(); // statement objects can be reused with\n\n        // repeated calls to execute but we\n        // choose to make a new one each time\n        rs = st.executeQuery(expression); // run the query\n\n        // do something with the result set.\n        dump(rs);\n        st.close(); // NOTE!! if you close a statement the associated ResultSet\n                    // is\n\n        // closed too\n        // so you should copy the contents to some other object.\n        // the result set is invalidated also if you recycle an Statement\n        // and try to execute some other query before the result set has been\n        // completely examined.\n    }\n\n    // use for SQL commands CREATE, DROP, INSERT and UPDATE\n    public synchronized void update(String expression) throws SQLException\n    {\n\n        Statement st = null;\n\n        st = conn.createStatement(); // statements\n\n        int i = st.executeUpdate(expression); // run the query\n\n        if (i == -1)\n        {\n            System.out.println(\"db error : \" + expression);\n        }\n        st.close();\n    } // void update()\n\n    public static void dump(ResultSet rs) throws SQLException\n    {\n\n        // the order of the rows in a cursor\n        // are implementation dependent unless you use the SQL ORDER statement\n        ResultSetMetaData meta = rs.getMetaData();\n        int colmax = meta.getColumnCount();\n        int i;\n        Object o = null;\n\n        // the result set is a cursor into the data. You can only\n        // point to one row at a time\n        // assume we are pointing to BEFORE the first row\n        // rs.next() points to next row and returns true\n        // or false if there is no next row, which breaks the loop\n        for (; rs.next();)\n        {\n            for (i = 0; i < colmax; ++i)\n            {\n                o = rs.getObject(i + 1); // Is SQL the first column is indexed\n\n                // with 1 not 0\n            }\n        }\n    } // void dump( ResultSet rs )\n\n    public void createSchema(final String schemaName) throws SQLException\n    {\n        try\n        {\n            String sql = \"CREATE schema \" + schemaName + \" AUTHORIZATION DBA\";\n            update(sql);\n        }\n        catch (Exception e)\n        {\n            // do nothing..\n        }\n        // update(\"set \" + schemaName);\n    }\n\n    public void dropSchema(final String schemaName) throws SQLException\n    {\n        String sql = \"drop schema \" + schemaName;\n        update(sql);        \n    }\n\n    public static void main(String[] args)\n    {\n\n        RDBMSCli db = null;\n\n        try\n        {\n            db = new RDBMSCli(\"testdb\");\n        }\n        catch (Exception ex1)\n        {\n        \tlogger.warn(ex1.getMessage());\n            return;\n        }\n        // bye bye }\n\n        try\n        {\n            \n            // make an empty table // // by declaring the id column IDENTITY,\n            // the db\n            // will automatically // generate unique values for new rows- useful\n            // for row\n            // keys\n            db.update(\"CREATE schema testdb AUTHORIZATION DBA\");\n            db.update(\"CREATE TABLE sample_table ( id INTEGER IDENTITY, str_col VARCHAR(256), num_col INTEGER)\");\n        }\n        catch (SQLException ex2)\n        {\n        \tlogger.warn(ex2.getMessage());\n\n            // ignore //ex2.printStackTrace(); // second time we run program //\n            // should\n            /*\n             * throw execption since table // already there // // this will have\n             * no effect on the db\n             */}\n\n        try\n        {\n\n            // add some rows - will create duplicates if run more then once //\n            // the id\n            // column is automatically generated\n            db.update(\"INSERT INTO sample_table(str_col,num_col) VALUES('Ford', 100)\");\n            db.update(\"INSERT INTO sample_table(str_col,num_col) VALUES('Toyota', 200)\");\n            db.update(\"INSERT INTO sample_table(str_col,num_col) VALUES('Honda', 300)\");\n            db.update(\"INSERT INTO sample_table(str_col,num_col) VALUES('GM', 400)\");\n\n            // do a query\n            // db.query(\"SELECT * FROM sample_table WHERE num_col < 250\");\n\n            // at end of program db.shutdown(); }\n        }\n        catch (SQLException ex3)\n        {\n        \tlogger.warn(ex3.getMessage());\n        }\n    } // main()\n} // class Testdb\n\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/RDBMSMTMEagerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.sql.SQLException;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.AddressRDBMSMTM;\nimport com.impetus.client.crud.entities.PersonEagerRDBMSMTM;\n\n/**\n * @author impadmin\n * \n */\npublic class RDBMSMTMEagerTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private RDBMSCli cli;\n\n    private static final String SCHEMA = \"testdb\";\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"testHibernate\");\n        em = getNewEM();\n        createSchema();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        dropSchema();\n    }\n\n    @Test\n    public void testDummy()\n    {\n        Assert.assertTrue(\"Enable testCRUD while EagerFetching in rdbms get fixed.\", true);\n\n    }\n\n    // @Test\n    public void testCRUD()\n    {\n        // TODO Eager fetching not working.\n\n        AddressRDBMSMTM address1 = new AddressRDBMSMTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"sector 11\");\n\n        AddressRDBMSMTM address2 = new AddressRDBMSMTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"sector 12\");\n\n        AddressRDBMSMTM address3 = new AddressRDBMSMTM();\n        address3.setAddressId(\"c\");\n        address3.setStreet(\"sector 13\");\n\n        Set<AddressRDBMSMTM> addresses1 = new HashSet<AddressRDBMSMTM>();\n        addresses1.add(address1);\n        addresses1.add(address2);\n\n        Set<AddressRDBMSMTM> addresses2 = new HashSet<AddressRDBMSMTM>();\n        addresses2.add(address2);\n        addresses2.add(address3);\n\n        PersonEagerRDBMSMTM person1 = new PersonEagerRDBMSMTM();\n        person1.setPersonId(\"1\");\n        person1.setPersonName(\"Kuldeep\");\n\n        PersonEagerRDBMSMTM person2 = new PersonEagerRDBMSMTM();\n        person2.setPersonId(\"2\");\n        person2.setPersonName(\"vivek\");\n\n        person1.setAddresses(addresses1);\n        person2.setAddresses(addresses2);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        em = getNewEM();\n\n        PersonEagerRDBMSMTM foundPerson1 = em.find(PersonEagerRDBMSMTM.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson1.getPersonName());\n\n        int counter = 0;\n        for (AddressRDBMSMTM address : foundPerson1.getAddresses())\n        {\n            if (address.getAddressId().equals(\"a\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        PersonEagerRDBMSMTM foundPerson2 = em.find(PersonEagerRDBMSMTM.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddresses());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vivek\", foundPerson2.getPersonName());\n\n        counter = 0;\n        for (AddressRDBMSMTM address : foundPerson2.getAddresses())\n        {\n            if (address.getAddressId().equals(\"b\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"c\", address.getAddressId());\n                Assert.assertEquals(\"sector 13\", address.getStreet());\n                counter++;\n            }\n        }\n\n        foundPerson1.setPersonName(\"KK\");\n\n        foundPerson2.setPersonName(\"vives\");\n\n        em.merge(foundPerson1);\n        em.merge(foundPerson2);\n\n        em = getNewEM();\n\n        foundPerson1 = em.find(PersonEagerRDBMSMTM.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson1.getPersonName());\n\n        counter = 0;\n        for (AddressRDBMSMTM address : foundPerson1.getAddresses())\n        {\n            if (address.getAddressId().equals(\"a\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        foundPerson2 = em.find(PersonEagerRDBMSMTM.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddresses());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vives\", foundPerson2.getPersonName());\n\n        counter = 0;\n        for (AddressRDBMSMTM address : foundPerson2.getAddresses())\n        {\n            if (address.getAddressId().equals(\"b\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"c\", address.getAddressId());\n                Assert.assertEquals(\"sector 13\", address.getStreet());\n                counter++;\n            }\n        }\n\n        em.remove(foundPerson1);\n        em.remove(foundPerson2);\n\n        foundPerson1 = em.find(PersonEagerRDBMSMTM.class, \"1\");\n        foundPerson2 = em.find(PersonEagerRDBMSMTM.class, \"2\");\n\n        Assert.assertNull(foundPerson1);\n        Assert.assertNull(foundPerson2);\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n\n    private void createSchema() throws SQLException\n    {\n        try\n        {\n            cli = new RDBMSCli(SCHEMA);\n            cli.createSchema(SCHEMA);\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))\");\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL_ADDRESS (ADDRESS_ID VARCHAR(9), PERSON_ID VARCHAR(9))\");\n        }\n        catch (Exception e)\n        {\n\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL_ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL_ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.PERSON (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))\");\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL_ADDRESS (ADDRESS_ID VARCHAR(9), PERSON_ID VARCHAR(9))\");\n            // nothing\n            // do\n        }\n    }\n\n    private void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL_ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL_ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/RDBMSMTMLazyTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.sql.SQLException;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.AddressRDBMSMTM;\nimport com.impetus.client.crud.entities.PersonLazyRDBMSMTM;\n\n/**\n * @author impadmin\n * \n */\npublic class RDBMSMTMLazyTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private RDBMSCli cli;\n\n    private static final String SCHEMA = \"testdb\";\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"testHibernate\");\n        em = getNewEM();\n        createSchema();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        dropSchema();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        AddressRDBMSMTM address1 = new AddressRDBMSMTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"sector 11\");\n\n        AddressRDBMSMTM address2 = new AddressRDBMSMTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"sector 12\");\n\n        AddressRDBMSMTM address3 = new AddressRDBMSMTM();\n        address3.setAddressId(\"c\");\n        address3.setStreet(\"sector 13\");\n\n        Set<AddressRDBMSMTM> addresses1 = new HashSet<AddressRDBMSMTM>();\n        addresses1.add(address1);\n        addresses1.add(address2);\n\n        Set<AddressRDBMSMTM> addresses2 = new HashSet<AddressRDBMSMTM>();\n        addresses2.add(address2);\n        addresses2.add(address3);\n\n        PersonLazyRDBMSMTM person1 = new PersonLazyRDBMSMTM();\n        person1.setPersonId(\"1\");\n        person1.setPersonName(\"Kuldeep\");\n\n        PersonLazyRDBMSMTM person2 = new PersonLazyRDBMSMTM();\n        person2.setPersonId(\"2\");\n        person2.setPersonName(\"vivek\");\n\n        person1.setAddresses(addresses1);\n        person2.setAddresses(addresses2);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        em = getNewEM();\n\n        PersonLazyRDBMSMTM foundPerson1 = em.find(PersonLazyRDBMSMTM.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson1.getPersonName());\n\n        int counter = 0;\n        for (AddressRDBMSMTM address : foundPerson1.getAddresses())\n        {\n            if (address.getAddressId().equals(\"a\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        PersonLazyRDBMSMTM foundPerson2 = em.find(PersonLazyRDBMSMTM.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddresses());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vivek\", foundPerson2.getPersonName());\n\n        counter = 0;\n        for (AddressRDBMSMTM address : foundPerson2.getAddresses())\n        {\n            if (address.getAddressId().equals(\"b\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"c\", address.getAddressId());\n                Assert.assertEquals(\"sector 13\", address.getStreet());\n                counter++;\n            }\n        }\n\n        foundPerson1.setPersonName(\"KK\");\n\n        foundPerson2.setPersonName(\"vives\");\n\n        em.merge(foundPerson1);\n        em.merge(foundPerson2);\n\n        em = getNewEM();\n\n        foundPerson1 = em.find(PersonLazyRDBMSMTM.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson1.getPersonName());\n\n        counter = 0;\n        for (AddressRDBMSMTM address : foundPerson1.getAddresses())\n        {\n            if (address.getAddressId().equals(\"a\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        foundPerson2 = em.find(PersonLazyRDBMSMTM.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddresses());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vives\", foundPerson2.getPersonName());\n\n        counter = 0;\n        for (AddressRDBMSMTM address : foundPerson2.getAddresses())\n        {\n            if (address.getAddressId().equals(\"b\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"c\", address.getAddressId());\n                Assert.assertEquals(\"sector 13\", address.getStreet());\n                counter++;\n            }\n        }\n\n        em.remove(foundPerson1);\n        em.remove(foundPerson2);\n\n        foundPerson1 = em.find(PersonLazyRDBMSMTM.class, \"1\");\n        foundPerson2 = em.find(PersonLazyRDBMSMTM.class, \"2\");\n\n        Assert.assertNull(foundPerson1);\n        Assert.assertNull(foundPerson2);\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n\n    private void createSchema() throws SQLException\n    {\n        try\n        {\n            cli = new RDBMSCli(SCHEMA);\n            cli.createSchema(SCHEMA);\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))\");\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL_ADDRESS (ADDRESS_ID VARCHAR(9), PERSON_ID VARCHAR(9))\");\n        }\n        catch (Exception e)\n        {\n            \n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL_ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL_ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.PERSON (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))\");\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL_ADDRESS (ADDRESS_ID VARCHAR(9), PERSON_ID VARCHAR(9))\");\n            // nothing\n            // do\n        }\n    }\n\n    private void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL_ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL_ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/RDBMSMTOEagerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.sql.SQLException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.AddressRDBMSMTO;\nimport com.impetus.client.crud.entities.PersonEagerRDBMSMTO;\n\npublic class RDBMSMTOEagerTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private RDBMSCli cli;\n\n    private static final String SCHEMA = \"testdb\";\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"testHibernate\");\n        em = getNewEM();\n        createSchema();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        dropSchema();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        AddressRDBMSMTO address = new AddressRDBMSMTO();\n        address.setAddressId(\"a\");\n        address.setStreet(\"sector 11\");\n\n        PersonEagerRDBMSMTO person1 = new PersonEagerRDBMSMTO();\n        person1.setPersonId(\"1\");\n        person1.setPersonName(\"Kuldeep\");\n\n        PersonEagerRDBMSMTO person2 = new PersonEagerRDBMSMTO();\n        person2.setPersonId(\"2\");\n        person2.setPersonName(\"vivek\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        em = getNewEM();\n\n        PersonEagerRDBMSMTO foundPerson1 = em.find(PersonEagerRDBMSMTO.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddress());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson1.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson1.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson1.getAddress().getStreet());\n\n        PersonEagerRDBMSMTO foundPerson2 = em.find(PersonEagerRDBMSMTO.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddress());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vivek\", foundPerson2.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson2.getAddress().getStreet());\n\n        foundPerson1.setPersonName(\"KK\");\n\n        foundPerson2.setPersonName(\"vives\");\n\n        em.merge(foundPerson1);\n        em.merge(foundPerson2);\n\n        em = getNewEM();\n\n        foundPerson1 = em.find(PersonEagerRDBMSMTO.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddress());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson1.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson1.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson1.getAddress().getStreet());\n\n        foundPerson2 = em.find(PersonEagerRDBMSMTO.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddress());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vives\", foundPerson2.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson2.getAddress().getStreet());\n\n        em.remove(foundPerson1);\n        em.remove(foundPerson2);\n\n        foundPerson1 = em.find(PersonEagerRDBMSMTO.class, \"1\");\n        foundPerson2 = em.find(PersonEagerRDBMSMTO.class, \"2\");\n        \n        Assert.assertNull(foundPerson1);\n        Assert.assertNull(foundPerson2);\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n    private void createSchema() throws SQLException\n    {\n        try\n        {\n            cli = new RDBMSCli(SCHEMA);\n            cli.createSchema(SCHEMA);\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(9))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n        catch (Exception e)\n        {\n            \n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(9))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))\");\n            // nothing\n            // do\n        }\n    }\n\n    private void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/RDBMSMTOLazyTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.AddressRDBMSMTO;\nimport com.impetus.client.crud.entities.PersonLazyRDBMSMTO;\n\npublic class RDBMSMTOLazyTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private RDBMSCli cli;\n\n    private static final String SCHEMA = \"testdb\";\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"testHibernate\");\n        em = getNewEM();\n        createSchema();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        dropSchema();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        AddressRDBMSMTO address = new AddressRDBMSMTO();\n        address.setAddressId(\"a\");\n        address.setStreet(\"sector 11\");\n\n        PersonLazyRDBMSMTO person1 = new PersonLazyRDBMSMTO();\n        person1.setPersonId(\"1\");\n        person1.setPersonName(\"Kuldeep\");\n\n        PersonLazyRDBMSMTO person2 = new PersonLazyRDBMSMTO();\n        person2.setPersonId(\"2\");\n        person2.setPersonName(\"vivek\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        em = getNewEM();\n\n        PersonLazyRDBMSMTO foundPerson1 = em.find(PersonLazyRDBMSMTO.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddress());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson1.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson1.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson1.getAddress().getStreet());\n\n        PersonLazyRDBMSMTO foundPerson2 = em.find(PersonLazyRDBMSMTO.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddress());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vivek\", foundPerson2.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson2.getAddress().getStreet());\n\n        foundPerson1.setPersonName(\"KK\");\n\n        foundPerson2.setPersonName(\"vives\");\n\n        em.merge(foundPerson1);\n        em.merge(foundPerson2);\n\n        em = getNewEM();\n\n        foundPerson1 = em.find(PersonLazyRDBMSMTO.class, \"1\");\n        Assert.assertNotNull(foundPerson1);\n        Assert.assertNotNull(foundPerson1.getAddress());\n        Assert.assertEquals(\"1\", foundPerson1.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson1.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson1.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson1.getAddress().getStreet());\n\n        foundPerson2 = em.find(PersonLazyRDBMSMTO.class, \"2\");\n        Assert.assertNotNull(foundPerson2);\n        Assert.assertNotNull(foundPerson2.getAddress());\n        Assert.assertEquals(\"2\", foundPerson2.getPersonId());\n        Assert.assertEquals(\"vives\", foundPerson2.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson2.getAddress().getStreet());\n\n        List<PersonLazyRDBMSMTO> results = em.createQuery(\"select p from PersonLazyRDBMSMTO p\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(2, results.size());\n\n        for (PersonLazyRDBMSMTO personLazyRDBMSMTO : results)\n        {\n            Assert.assertNotNull(personLazyRDBMSMTO);\n\n            if (personLazyRDBMSMTO.getPersonId().equals(\"1\"))\n            {\n                Assert.assertEquals(\"KK\", personLazyRDBMSMTO.getPersonName());\n            }\n            else\n            {\n                Assert.assertEquals(\"2\", personLazyRDBMSMTO.getPersonId());\n                Assert.assertEquals(\"vives\", personLazyRDBMSMTO.getPersonName());\n            }\n            Assert.assertNotNull(personLazyRDBMSMTO.getAddress());\n            Assert.assertEquals(\"a\", personLazyRDBMSMTO.getAddress().getAddressId());\n            Assert.assertEquals(\"sector 11\", personLazyRDBMSMTO.getAddress().getStreet());\n        }\n\n        results = em.createQuery(\"select p from PersonLazyRDBMSMTO p where p.personId = '1'\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertFalse(results.isEmpty());\n        Assert.assertEquals(1, results.size());\n        \n        PersonLazyRDBMSMTO personLazyRDBMSMTO = results.get(0);\n\n        Assert.assertNotNull(personLazyRDBMSMTO);\n        Assert.assertEquals(\"KK\", personLazyRDBMSMTO.getPersonName());\n        Assert.assertNotNull(personLazyRDBMSMTO.getAddress());\n        Assert.assertEquals(\"a\", personLazyRDBMSMTO.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", personLazyRDBMSMTO.getAddress().getStreet());\n\n        em.remove(foundPerson1);\n        em.remove(foundPerson2);\n\n        foundPerson1 = em.find(PersonLazyRDBMSMTO.class, \"1\");\n        foundPerson2 = em.find(PersonLazyRDBMSMTO.class, \"2\");\n\n        Assert.assertNull(foundPerson1);\n        Assert.assertNull(foundPerson2);\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n\n    private void createSchema() throws SQLException\n    {\n        try\n        {\n            cli = new RDBMSCli(SCHEMA);\n            cli.createSchema(SCHEMA);\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(9))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n        catch (Exception e)\n        {\n\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(9))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))\");\n            // nothing\n            // do\n        }\n    }\n\n    private void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/RDBMSMappedSuperClassTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.sql.SQLException;\n\nimport javax.persistence.MappedSuperclass;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.crud.mappedsuperclass.MappedSuperClassBase;\n\n/**\n * @author vivek.mishra Junit for {@link MappedSuperclass} in RDBMS\n * \n */\npublic class RDBMSMappedSuperClassTest extends MappedSuperClassBase\n{\n\n    private RDBMSCli cli;\n\n    private static final String SCHEMA = \"testdb\";\n\n    @Before\n    public void setUp() throws Exception\n    {\n        createSchema();\n        _PU = \"mappedPu\";\n        setUpInternal();\n    }\n\n    @Test\n    public void test() throws Exception\n    {\n        cli = new RDBMSCli(\"testdb\");\n        cli.createSchema(\"testdb\");\n\n        assertInternal(true);\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        // // Delete by query.\n        String deleteQuery = \"Delete from RDBMSCreditTransaction p\";\n\n        Query query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n\n        deleteQuery = \"Delete from RDBMSDebitTransaction p\";\n\n        query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n\n        tearDownInternal();\n        \n        dropSchema();\n\n    }\n\n    private void createSchema() throws SQLException\n    {\n        try\n        {\n            cli = new RDBMSCli(SCHEMA);\n            cli.createSchema(SCHEMA);\n            cli.update(\"CREATE TABLE TESTDB.TRNX_CREDIT (txId VARCHAR(255) PRIMARY KEY, amount int, txStatus VARCHAR(255), tx_type VARCHAR(255), CREDIT_BANK_IDENT VARCHAR(255), transactionDt date)\");\n            cli.update(\"CREATE TABLE TESTDB.DebitTransaction (DEBIT_ID VARCHAR(255) PRIMARY KEY, amount int, DEBIT_BANK_IDENT VARCHAR(256), txStatus VARCHAR(255), TX_DT date, tx_type VARCHAR(255))\");\n        }\n        catch (Exception e)\n        {\n\n            cli.update(\"DELETE FROM TESTDB.TRNX_CREDIT\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.TRNX_CREDIT\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.TRNX_CREDIT (txId VARCHAR(255) PRIMARY KEY, amount int, txStatus VARCHAR(255), tx_type VARCHAR(255), CREDIT_BANK_IDENT VARCHAR(255), transactionDt date)\");\n            cli.update(\"CREATE TABLE TESTDB.DebitTransaction (DEBIT_ID VARCHAR(255) PRIMARY KEY, amount int, DEBIT_BANK_IDENT VARCHAR(256), txStatus VARCHAR(255), TX_DT date, tx_type VARCHAR(255))\");\n            // nothing\n            // do\n        }\n    }\n\n    private void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.TRNX_CREDIT\");\n            cli.update(\"DELETE FROM TESTDB.DebitTransaction\");\n            cli.update(\"DROP TABLE TESTDB.TRNX_CREDIT\");\n            cli.update(\"DROP TABLE TESTDB.DebitTransaction\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/RDBMSOTMEagerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.sql.SQLException;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.AddressRDBMSOTM;\nimport com.impetus.client.crud.entities.PersonEagerRDBMSOTM;\n\n/**\n * @author impadmin\n * \n */\npublic class RDBMSOTMEagerTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private RDBMSCli cli;\n\n    private static final String SCHEMA = \"testdb\";\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"testHibernate\");\n        em = getNewEM();\n        createSchema();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        dropSchema();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        AddressRDBMSOTM address1 = new AddressRDBMSOTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"sector 11\");\n\n        AddressRDBMSOTM address2 = new AddressRDBMSOTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"sector 12\");\n\n        Set<AddressRDBMSOTM> addresses = new HashSet<AddressRDBMSOTM>();\n        addresses.add(address1);\n        addresses.add(address2);\n\n        PersonEagerRDBMSOTM person = new PersonEagerRDBMSOTM();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"Kuldeep\");\n        person.setAddresses(addresses);\n\n        em.persist(person);\n\n        em = getNewEM();\n\n        PersonEagerRDBMSOTM foundPerson = em.find(PersonEagerRDBMSOTM.class, \"1\");\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n\n        int counter = 0;\n        for (AddressRDBMSOTM address : foundPerson.getAddresses())\n        {\n            if (address.getAddressId().equals(\"a\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        Assert.assertEquals(2, counter);\n\n        foundPerson.setPersonName(\"KK\");\n\n        em.merge(foundPerson);\n\n        em = getNewEM();\n\n        foundPerson = em.find(PersonEagerRDBMSOTM.class, \"1\");\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson.getPersonName());\n\n        counter = 0;\n        for (AddressRDBMSOTM address : foundPerson.getAddresses())\n        {\n            if (address.getAddressId().equals(\"a\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        Assert.assertEquals(2, counter);\n\n        em.remove(foundPerson);\n\n        foundPerson = em.find(PersonEagerRDBMSOTM.class, \"1\");\n        Assert.assertNull(foundPerson);\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n    private void createSchema() throws SQLException\n    {\n        try\n        {\n            cli = new RDBMSCli(SCHEMA);\n            cli.createSchema(SCHEMA);\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256), PERSON_ID VARCHAR(9))\");\n        }\n        catch (Exception e)\n        {\n            \n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256), PERSON_ID VARCHAR(9))\");\n            // nothing\n            // do\n        }\n    }\n\n    private void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/RDBMSOTMLazyTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.sql.SQLException;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.AddressRDBMSOTM;\nimport com.impetus.client.crud.entities.PersonLazyRDBMSOTM;\n\n/**\n * @author impadmin\n * \n */\npublic class RDBMSOTMLazyTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private RDBMSCli cli;\n\n    private static final String SCHEMA = \"testdb\";\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"testHibernate\");\n        em = getNewEM();\n        createSchema();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        dropSchema();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        AddressRDBMSOTM address1 = new AddressRDBMSOTM();\n        address1.setAddressId(\"a\");\n        address1.setStreet(\"sector 11\");\n\n        AddressRDBMSOTM address2 = new AddressRDBMSOTM();\n        address2.setAddressId(\"b\");\n        address2.setStreet(\"sector 12\");\n\n        Set<AddressRDBMSOTM> addresses = new HashSet<AddressRDBMSOTM>();\n        addresses.add(address1);\n        addresses.add(address2);\n\n        PersonLazyRDBMSOTM person = new PersonLazyRDBMSOTM();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"Kuldeep\");\n        person.setAddresses(addresses);\n\n        em.persist(person);\n\n        em = getNewEM();\n\n        PersonLazyRDBMSOTM foundPerson = em.find(PersonLazyRDBMSOTM.class, \"1\");\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n\n        int counter = 0;\n        for (AddressRDBMSOTM address : foundPerson.getAddresses())\n        {\n            if (address.getAddressId().equals(\"a\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        Assert.assertEquals(2, counter);\n\n\n        List<PersonLazyRDBMSOTM> persons = em.createQuery(\"Select p from PersonLazyRDBMSOTM p\").getResultList();\n        \n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        \n        foundPerson.setPersonName(\"KK\");\n\n        em.merge(foundPerson);\n\n        em = getNewEM();\n\n        foundPerson = em.find(PersonLazyRDBMSOTM.class, \"1\");\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddresses());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson.getPersonName());\n\n        counter = 0;\n        for (AddressRDBMSOTM address : foundPerson.getAddresses())\n        {\n            if (address.getAddressId().equals(\"a\"))\n            {\n                counter++;\n                Assert.assertEquals(\"sector 11\", address.getStreet());\n            }\n            else\n            {\n                Assert.assertEquals(\"b\", address.getAddressId());\n                Assert.assertEquals(\"sector 12\", address.getStreet());\n                counter++;\n            }\n        }\n\n        Assert.assertEquals(2, counter);\n\n        em.remove(foundPerson);\n\n        foundPerson = em.find(PersonLazyRDBMSOTM.class, \"1\");\n        Assert.assertNull(foundPerson);\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n\n    private void createSchema() throws SQLException\n    {\n        try\n        {\n            cli = new RDBMSCli(SCHEMA);\n            cli.createSchema(SCHEMA);\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256), PERSON_ID VARCHAR(9))\");\n        }\n        catch (Exception e)\n        {\n            \n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256), PERSON_ID VARCHAR(9))\");\n            // nothing\n            // do\n        }\n    }\n\n    private void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/RDBMSOTOEagerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.sql.SQLException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.AddressRDBMSOTO;\nimport com.impetus.client.crud.entities.PersonEagerRDBMSOTO;\n\npublic class RDBMSOTOEagerTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private RDBMSCli cli;\n\n    private static final String SCHEMA = \"testdb\";\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"testHibernate\");\n        em = getNewEM();\n        createSchema();\n    }\n\n\n    @Test\n    public void testCRUD()\n    {\n        AddressRDBMSOTO address = new AddressRDBMSOTO();\n        address.setAddressId(\"a\");\n        address.setStreet(\"sector 11\");\n\n        PersonEagerRDBMSOTO person = new PersonEagerRDBMSOTO();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"Kuldeep\");\n        person.setAddress(address);\n\n        em.persist(person);\n\n        em = getNewEM();\n\n        PersonEagerRDBMSOTO foundPerson = em.find(PersonEagerRDBMSOTO.class, \"1\");\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddress());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson.getAddress().getStreet());\n\n        foundPerson.setPersonName(\"KK\");\n        foundPerson.getAddress().setStreet(\"sector 12\");\n\n        em.merge(foundPerson);\n\n        em = getNewEM();\n\n        foundPerson = em.find(PersonEagerRDBMSOTO.class, \"1\");\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddress());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 12\", foundPerson.getAddress().getStreet());\n\n        em.remove(foundPerson);\n        foundPerson = em.find(PersonEagerRDBMSOTO.class, \"1\");\n        Assert.assertNull(foundPerson);\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n    \n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        dropSchema();\n    }\n    \n    private void createSchema() throws SQLException\n    {\n        try\n        {\n            cli = new RDBMSCli(SCHEMA);\n            cli.createSchema(SCHEMA);\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(9))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(9))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))\");\n            // nothing\n            // do\n        }\n    }\n\n    private void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/RDBMSOTOLazyTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.sql.SQLException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.AddressRDBMSOTO;\nimport com.impetus.client.crud.entities.PersonLazyRDBMSOTO;\n\npublic class RDBMSOTOLazyTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private RDBMSCli cli;\n\n    private static final String SCHEMA = \"testdb\";\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"testHibernate\");\n        em = getNewEM();\n        createSchema();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        AddressRDBMSOTO address = new AddressRDBMSOTO();\n        address.setAddressId(\"a\");\n        address.setStreet(\"sector 11\");\n\n        PersonLazyRDBMSOTO person = new PersonLazyRDBMSOTO();\n        person.setPersonId(\"1\");\n        person.setPersonName(\"Kuldeep\");\n        person.setAddress(address);\n\n        em.persist(person);\n\n        em = getNewEM();\n\n        PersonLazyRDBMSOTO foundPerson = em.find(PersonLazyRDBMSOTO.class, \"1\");\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddress());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"Kuldeep\", foundPerson.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 11\", foundPerson.getAddress().getStreet());\n\n        foundPerson.setPersonName(\"KK\");\n        foundPerson.getAddress().setStreet(\"sector 12\");\n\n        em.merge(foundPerson);\n\n        em = getNewEM();\n\n        foundPerson = em.find(PersonLazyRDBMSOTO.class, \"1\");\n        Assert.assertNotNull(foundPerson);\n        Assert.assertNotNull(foundPerson.getAddress());\n        Assert.assertEquals(\"1\", foundPerson.getPersonId());\n        Assert.assertEquals(\"KK\", foundPerson.getPersonName());\n        Assert.assertEquals(\"a\", foundPerson.getAddress().getAddressId());\n        Assert.assertEquals(\"sector 12\", foundPerson.getAddress().getStreet());\n\n        em.remove(foundPerson);\n        foundPerson = em.find(PersonLazyRDBMSOTO.class, \"1\");\n        Assert.assertNull(foundPerson);\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        return em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        dropSchema();\n    }\n\n    private void createSchema() throws SQLException\n    {\n        try\n        {\n            cli = new RDBMSCli(SCHEMA);\n            cli.createSchema(SCHEMA);\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(9))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n        catch (Exception e)\n        {\n            \n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.PERSONNEL (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(9))\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESS (ADDRESS_ID VARCHAR(9) PRIMARY KEY, STREET VARCHAR(256))\");\n            // nothing\n            // do\n        }\n    }\n\n    private void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.PERSONNEL\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESS\");\n            cli.update(\"DROP TABLE TESTDB.PERSONNEL\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESS\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/RdbmsLuceneTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud;\n\nimport java.sql.SQLException;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.PersonRDBMS;\n\npublic class RdbmsLuceneTest extends BaseTest\n{\n\n    private static final String SCHEMA = \"testdb\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    private Map<Object, Object> col;\n\n    private RDBMSCli cli;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        Map<String,String> propertyMap = new HashMap<String,String>();\n        propertyMap.put(\"index.home.dir\", \"lucene\");\n        emf = Persistence.createEntityManagerFactory(\"testHibernate\",propertyMap);\n        em = emf.createEntityManager();\n        col = new java.util.HashMap<Object, Object>();\n    }\n\n    @Test\n    public void test() throws SQLException\n    {\n        try\n        {\n            cli = new RDBMSCli(SCHEMA);\n            cli.createSchema(SCHEMA);\n            cli.update(\"CREATE TABLE TESTDB.PERSON (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), AGE INTEGER)\");\n        }\n        catch (Exception e)\n        {\n\n            cli.update(\"DELETE FROM TESTDB.PERSON\");\n            cli.update(\"DROP TABLE TESTDB.PERSON\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.PERSON (PERSON_ID VARCHAR(9) PRIMARY KEY, PERSON_NAME VARCHAR(256), AGE INTEGER)\");\n        }\n\n        Object p1 = prepareRDBMSInstance(\"1\", 10);\n        Object p2 = prepareRDBMSInstance(\"2\", 20);\n        Object p3 = prepareRDBMSInstance(\"3\", 15);\n\n        Query findQuery = em.createQuery(\"Select p from PersonRDBMS p\");\n        List<PersonRDBMS> allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = em.createQuery(\"Select p from PersonRDBMS p where p.personName = 'vivek'\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        findQuery = em.createQuery(\"Select p.age from PersonRDBMS p where p.personName = 'vivek'\");\n        allPersons = findQuery.getResultList();\n        Assert.assertNotNull(allPersons);\n        Assert.assertTrue(allPersons.isEmpty());\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        em.close();\n    \n        em = emf.createEntityManager();\n\n        col.put(\"1\", p1);\n        col.put(\"2\", p2);\n        col.put(\"3\", p3);\n        PersonRDBMS personRDBMS = findById(PersonRDBMS.class, \"1\", em);\n        Assert.assertNotNull(personRDBMS);\n        Assert.assertEquals(\"vivek\", personRDBMS.getPersonName());\n        assertFindWithoutWhereClause(em, \"PersonRDBMS\", PersonRDBMS.class);\n        assertFindByName(em, \"PersonRDBMS\", PersonRDBMS.class, \"vivek\", \"personName\");\n        assertFindByNameAndAge(em, \"PersonRDBMS\", PersonRDBMS.class, \"vivek\", \"10\", \"personName\");\n        assertFindByNameAndAgeGTAndLT(em, \"PersonRDBMS\", PersonRDBMS.class, \"vivek\", \"10\", \"20\", \"personName\");\n        assertFindByNameAndAgeBetween(em, \"PersonRDBMS\", PersonRDBMS.class, \"vivek\", \"10\", \"15\", \"personName\");\n        assertFindByRange(em, \"PersonRDBMS\", PersonRDBMS.class, \"1\", \"2\", \"personId\");\n\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        for (Object val : col.values())\n        {\n            em.remove(val);\n        }\n        em.close();\n        emf.close();\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.PERSON\");\n            cli.update(\"DROP TABLE TESTDB.PERSON\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n    \n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/ResultIteratorTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.crud;\n\nimport java.sql.SQLException;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.entities.PersonRDBMS;\nimport com.impetus.client.crud.entities.RDBMSToken;\nimport com.impetus.client.crud.entities.RDBMSTokenClient;\nimport com.impetus.kundera.query.IResultIterator;\nimport com.impetus.kundera.query.Query;\n\n/**\n * @author kuldeep.mishra junit for {@link IResultIterator}.\n */\npublic class ResultIteratorTest extends BaseTest\n{\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    private RDBMSCli cli;\n\n    private static final String SCHEMA = \"testdb\";\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        createSchema();\n        \n        emf = Persistence.createEntityManagerFactory(\"testHibernate\");\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testScroll() throws Exception\n    {\n        onScroll();\n    }\n\n    @Test\n    public void testScrollAssociation() throws Exception\n    {\n        assertOnTokenScroll();\n    }\n\n    private void assertOnTokenScroll()\n    {\n        RDBMSTokenClient client = new RDBMSTokenClient();\n        client.setClientName(\"tokenClient1\");\n        client.setId(\"tokenClientId\");\n\n        RDBMSToken token1 = new RDBMSToken();\n        token1.setId(\"RdbmsTokenId1\");\n        token1.setTokenName(\"tokenName1\");\n        token1.setClient(client);\n\n        RDBMSToken token2 = new RDBMSToken();\n        token2.setId(\"tokenId2\");\n        token2.setTokenName(\"tokenName2\");\n        token2.setClient(client);\n\n        em.persist(token1);\n        em.persist(token2);\n\n        String queryWithoutClause = \"Select t from RDBMSToken t\";\n        assertOnTokenScroll(queryWithoutClause, 2);\n\n        String queryWithClause = \"Select t from RDBMSToken t where t.tokenName='tokenName1'\";\n\n        assertOnTokenScroll(queryWithClause, 1);\n\n        // TODO:: Need to discuss , this should be working with token\n        // support. Special scenario.\n        String queryWithIdClause = \"Select t from RDBMSToken t where t.tokenId = 'RDBMSTokenId1'\";\n        //        assertOnTokenScroll(queryWithIdClause, 1);\n\n    }\n\n    private void assertOnTokenScroll(String queryClause, int expected)\n    {\n        Query query = (Query) em.createQuery(queryClause, RDBMSToken.class);\n\n        int count = 0;\n        Iterator<RDBMSToken> tokens = query.iterate();\n        while (tokens.hasNext())\n        {\n            RDBMSToken token = tokens.next();\n            Assert.assertNotNull(token);\n            RDBMSTokenClient client = token.getClient();\n            Assert.assertNotNull(client);\n            Assert.assertEquals(\"tokenClient1\", client.getClientName());\n            // Assert.assertEquals(2, client.getTokens().size());\n            count++;\n        }\n\n        Assert.assertTrue(count > 0);\n        Assert.assertTrue(count == expected);\n    }\n\n    private void onScroll()\n    {\n        Object p1 = prepareRDBMSInstance(\"1\", 10);\n        Object p2 = prepareRDBMSInstance(\"2\", 20);\n        Object p3 = prepareRDBMSInstance(\"3\", 15);\n\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        em.flush();\n        em.clear();\n        final String queryWithoutClause = \"Select p from PersonRDBMS p\";\n\n        assertOnScroll(queryWithoutClause, 3);\n\n        final String queryWithClause = \"Select p from PersonRDBMS p where p.personName = vivek\";\n\n        assertOnScroll(queryWithClause, 3);\n\n        final String queryWithAndClause = \"Select p from PersonRDBMS p where p.personName = vivek and p.age = 15\";\n\n        assertOnScroll(queryWithAndClause, 1);\n\n        final String queryWithLTClause = \"Select p from PersonRDBMS p where p.personName = vivek and p.age < 15\";\n\n        assertOnScroll(queryWithLTClause, 1);\n\n        final String queryWithGTClause = \"Select p from PersonRDBMS p where p.personName = vivek and p.age >= 15\";\n\n        assertOnScroll(queryWithGTClause, 2);\n\n        final String queryWithLTGTClause = \"Select p from PersonRDBMS p where p.personName = vivek and p.age > 10 and p.age < 20\";\n\n        assertOnScroll(queryWithLTGTClause, 1);\n\n        final String queryWithLTGTEClause = \"Select p from PersonRDBMS p where p.personName = vivek and p.age >= 10 and p.age < 20\";\n\n        assertOnScroll(queryWithLTGTEClause, 2);\n\n        String queryWithIdClause = \"Select p from PersonRDBMS p where p.personId = '2' \";\n        assertOnScroll(queryWithIdClause, 1);\n    }\n\n    private void assertOnScroll(final String queryWithoutClause, int expectedCount)\n    {\n        Query query = (Query) em.createQuery(queryWithoutClause, PersonRDBMS.class);\n\n        assertOnFetch(query, 0, expectedCount);\n        assertOnFetch(query, 2, expectedCount); // less records\n\n        assertOnFetch(query, 4, expectedCount); // more fetch size than\n                                                // available in db.\n        assertOnFetch(query, 3, expectedCount); // more fetch size than\n                                                // available in db.\n\n        assertOnFetch(query, null, expectedCount); // set to null;\n\n    }\n\n    private void assertOnFetch(Query query, Integer fetchSize, int available)\n    {\n        query.setFetchSize(fetchSize);\n        int counter = 0;\n        Iterator<PersonRDBMS> iter = query.iterate();\n\n        while (iter.hasNext())\n        {\n            Assert.assertNotNull(iter.next());\n            counter++;\n        }\n\n        Assert.assertEquals(counter, fetchSize == null || available < fetchSize ? available : fetchSize);\n        try\n        {\n            iter.next();\n            Assert.fail();\n        }\n        catch (NoSuchElementException nsex)\n        {\n            Assert.assertNotNull(nsex.getMessage());\n        }\n    }\n\n    @After\n    public void tearDown()\n    {\n        em.close();\n        emf.close();\n        dropSchema();\n    }\n\n    private void createSchema() throws SQLException\n    {\n        try\n        {\n            cli = new RDBMSCli(SCHEMA);\n            cli.createSchema(SCHEMA);\n            cli.update(\"CREATE MEMORY TABLE TESTDB.PERSON (PERSON_ID VARCHAR(90) PRIMARY KEY, PERSON_NAME VARCHAR(256), AGE INTEGER)\");\n            cli.update(\"CREATE MEMORY TABLE TESTDB.TOKENS (TOKEN_ID VARCHAR(90) PRIMARY KEY, TOKEN_NAME VARCHAR(256), CLIENT_ID VARCHAR(256))\");\n            cli.update(\"CREATE MEMORY TABLE TESTDB.CLIENT (CLIENT_ID VARCHAR(90) PRIMARY KEY, CLIENT_NAME VARCHAR(256))\");\n        }\n        catch (Exception e)\n        {\n\n            cli.update(\"DELETE FROM TESTDB.PERSON\");\n            cli.update(\"DROP TABLE TESTDB.PERSON\");\n            cli.update(\"DELETE FROM TESTDB.TOKENS\");\n            cli.update(\"DROP TABLE TESTDB.TOKENS\");\n            cli.update(\"DELETE FROM TESTDB.CLIENT\");\n            cli.update(\"DROP TABLE TESTDB.CLIENT\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE MEMORY TABLE TESTDB.PERSON (PERSON_ID VARCHAR(90) PRIMARY KEY, PERSON_NAME VARCHAR(256), AGE INTEGER)\");\n            cli.update(\"CREATE MEMORY TABLE TESTDB.TOKENS (TOKEN_ID VARCHAR(90) PRIMARY KEY, TOKEN_NAME VARCHAR(256), CLIENT_ID VARCHAR(256))\");\n            cli.update(\"CREATE MEMORY TABLE TESTDB.CLIENT (CLIENT_ID VARCHAR(90) PRIMARY KEY, CLIENT_NAME VARCHAR(256))\");\n            // nothing\n            // do\n        }\n    }\n\n    private void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.PERSON\");\n            cli.update(\"DROP TABLE TESTDB.PERSON\");\n            cli.update(\"DELETE FROM TESTDB.tokens\");\n            cli.update(\"DROP TABLE TESTDB.tokens\");\n            cli.update(\"DELETE FROM TESTDB.client\");\n            cli.update(\"DROP TABLE TESTDB.client\");\n\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n            cli.shutdown();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/compositeType/RdbmsCompositeTypeTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.sql.SQLException;\nimport java.util.List;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.RDBMSCli;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class RdbmsCompositeTypeTest\n{\n    private EntityManagerFactory emf;\n\n    private RDBMSCli cli;\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        cli = new RDBMSCli(\"TESTDB\");\n        cli.createSchema(\"TESTDB\");\n        createSchema();\n        emf = null;\n        emf = Persistence.createEntityManagerFactory(\"testHibernate\");\n    }\n\n    /**\n     * CRUD over Compound primary Key.\n     */\n    @Test\n    public synchronized void onCRUD()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        RdbmsCompoundKey key = new RdbmsCompoundKey(\"mevivs\", 1, timeLineId.toString());\n        RdbmsPrimeUser user = new RdbmsPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setUserName(\"kk\");\n        em.persist(user);\n\n        em.close(); // optional,just to clear persistence cache.\n\n        em = emf.createEntityManager();\n        RdbmsPrimeUser result = em.find(RdbmsPrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"my first tweet\", result.getTweetBody());\n        Assert.assertEquals(timeLineId.toString(), result.getKey().getTimeLineId());\n        Assert.assertEquals(\"kk\", result.getUserName());\n\n        em.clear();// optional,just to clear persistence cache.\n\n        user.setTweetBody(\"After merge\");\n        em.merge(user);\n\n        em.close();// optional,just to clear persistence cache.\n\n        em = emf.createEntityManager();\n        result = em.find(RdbmsPrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"After merge\", result.getTweetBody());\n        Assert.assertEquals(timeLineId.toString(), result.getKey().getTimeLineId());\n        Assert.assertEquals(\"kk\", result.getUserName());\n\n        // deleting composite\n        em.remove(result);\n\n        em.close();// optional,just to clear persistence cache.\n\n        em = emf.createEntityManager();\n        result = em.find(RdbmsPrimeUser.class, key);\n        Assert.assertNull(result);\n    }\n\n    @Test\n    public synchronized void onQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n        RdbmsCompoundKey key = new RdbmsCompoundKey(\"mevivs\", 1, timeLineId.toString());\n        RdbmsPrimeUser user = new RdbmsPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setUserName(\"kk\");\n        em.persist(user);\n\n        em.close(); // optional,just to clear persistence cache.\n        em = emf.createEntityManager();\n        final String noClause = \"Select u from RdbmsPrimeUser u\";\n\n        final String withFirstCompositeColClause = \"Select u from RdbmsPrimeUser u where u.key.userId = :userId\";\n\n        final String withClauseOnNoncomposite = \"Select u from RdbmsPrimeUser u where u.userName = ?1\";\n\n        final String withSecondCompositeColClause = \"Select u from RdbmsPrimeUser u where u.key.tweetId = :tweetId\";\n        final String withBothCompositeColClause = \"Select u from RdbmsPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId\";\n        final String withAllCompositeColClause = \"Select u from RdbmsPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId = :timeLineId\";\n        final String withLastCompositeColGTClause = \"Select u from RdbmsPrimeUser u where u.key.userId = :userId and u.key.tweetId = :tweetId and u.key.timeLineId >= :timeLineId\";\n\n        // query with no clause.\n        Query q = em.createQuery(noClause);\n        List<RdbmsPrimeUser> results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withFirstCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withClauseOnNoncomposite);\n        q.setParameter(1, \"kk\");\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withSecondCompositeColClause);\n        q.setParameter(\"tweetId\", 1);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withBothCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withAllCompositeColClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId.toString());\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        // Query with composite key clause.\n        q = em.createQuery(withLastCompositeColGTClause);\n        q.setParameter(\"userId\", \"mevivs\");\n        q.setParameter(\"tweetId\", 1);\n        q.setParameter(\"timeLineId\", timeLineId.toString());\n        results = q.getResultList();\n        Assert.assertEquals(1, results.size());\n\n        final String withCompositeKeyClause = \"Select u from RdbmsPrimeUser u where u.key = :key\";\n        // Query with composite key clause.\n        q = em.createQuery(withCompositeKeyClause);\n        q.setParameter(\"key\", key);\n        results = q.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n\n        em.remove(user);\n\n        em.clear();// optional,just to clear persistence cache.\n    }\n\n    @Test\n    public synchronized void onNamedQueryTest()\n    {\n        updateNamed();\n        deleteNamed();\n\n    }\n\n    /**\n     * Update by Named Query.\n     * \n     * @return\n     */\n    private void updateNamed()\n    {\n        EntityManager em = emf.createEntityManager();\n\n        UUID timeLineId = UUID.randomUUID();\n\n        RdbmsCompoundKey key = new RdbmsCompoundKey(\"mevivs\", 1, timeLineId.toString());\n        RdbmsPrimeUser user = new RdbmsPrimeUser(key);\n        user.setTweetBody(\"my first tweet\");\n        user.setUserName(\"kk\");\n        em.persist(user);\n\n        em.close();\n\n        em = emf.createEntityManager();\n\n        String updateQuery = \"Update RdbmsPrimeUser u SET u.tweetBody='after merge' where u.tweetBody= :beforeUpdate\";\n        Query q = em.createQuery(updateQuery);\n        q.setParameter(\"beforeUpdate\", \"my first tweet\");\n        q.executeUpdate();\n        em.close();\n        em = emf.createEntityManager();\n\n        RdbmsPrimeUser result = em.find(RdbmsPrimeUser.class, key);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(\"after merge\", result.getTweetBody());\n        Assert.assertEquals(timeLineId.toString(), result.getKey().getTimeLineId());\n        Assert.assertEquals(\"kk\", result.getUserName());\n        em.close();\n    }\n\n    /**\n     * delete by Named Query.\n     */\n    private void deleteNamed()\n    {\n        UUID timeLineId = UUID.randomUUID();\n\n        RdbmsCompoundKey key = new RdbmsCompoundKey(\"mevivs\", 1, timeLineId.toString());\n\n        String deleteQuery = \"Delete From RdbmsPrimeUser u where u.tweetBody= :tweetBody\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.setParameter(\"tweetBody\", \"after merge\");\n        q.executeUpdate();\n\n        em.close();\n        em = emf.createEntityManager();\n        RdbmsPrimeUser result = em.find(RdbmsPrimeUser.class, key);\n        Assert.assertNull(result);\n        em.close();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n        \n        dropSchema();\n    }\n    \n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.USER (tweetBody VARCHAR(255), userName VARCHAR(255), tweetId INTEGER, userId VARCHAR(255), timeLineId VARCHAR(255)) \");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.USER\");\n            cli.update(\"DROP TABLE TESTDB.USER\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.USER (tweetBody VARCHAR(255), userName VARCHAR(255), tweetId INTEGER, userId VARCHAR(255), timeLineId VARCHAR(255)) \");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.USER\");\n            cli.update(\"DROP TABLE TESTDB.USER\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/compositeType/RdbmsCompoundKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * @author vivek.mishra\n */\n@Embeddable\npublic class RdbmsCompoundKey implements Serializable\n{\n    /**\n     * \n     */\n    private static final long serialVersionUID = 1L;\n\n    @Column\n    private String userId;\n\n    @Column\n    private int tweetId;\n\n    @Column\n    private String timeLineId;\n\n    /**\n     * \n     */\n    public RdbmsCompoundKey()\n    {\n    }\n\n    /**\n     * @param userId\n     * @param tweetId\n     * @param timeLineId\n     */\n    public RdbmsCompoundKey(String userId, int tweetId, String timeLineId)\n    {\n        this.userId = userId;\n        this.tweetId = tweetId;\n        this.timeLineId = timeLineId;\n    }\n\n    /**\n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * @return the tweetId\n     */\n    public int getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * @return the timeLineId\n     */\n    public String getTimeLineId()\n    {\n        return timeLineId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/compositeType/RdbmsPrimeUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.compositeType;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"User\", schema = \"TESTDB\")\npublic class RdbmsPrimeUser\n{\n\n    @EmbeddedId\n    private RdbmsCompoundKey key;\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private String userName;\n\n    public RdbmsPrimeUser()\n    {\n    }\n\n    public RdbmsPrimeUser(RdbmsCompoundKey key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the key\n     */\n    public RdbmsCompoundKey getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    public String getUserName()\n    {\n        return userName;\n    }\n\n    public void setUserName(String userName)\n    {\n        this.userName = userName;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/RdbmsBase.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\n\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport com.impetus.client.crud.RDBMSCli;\nimport com.impetus.kundera.datatypes.datagenerator.DataGenerator;\nimport com.impetus.kundera.datatypes.datagenerator.DataGeneratorFactory;\n\npublic abstract class RdbmsBase\n{\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\n\n    protected EntityManagerFactory emf;\n\n    protected RDBMSCli cli;\n\n    protected void setUp() throws Exception\n    {\n        cli = new RDBMSCli(\"TESTDB\");\n        cli.createSchema(\"TESTDB\");\n\n        \n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n        emf = Persistence.createEntityManagerFactory(\"RdbmsDataTypeTest\");\n    }\n\n    protected void tearDown() throws Exception\n    {\n        emf.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            dropSchema();\n        }\n    }\n\n    DataGenerator<?> dataGenerator;\n\n    DataGeneratorFactory factory = new DataGeneratorFactory();\n\n    protected Object getMaxValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.maxValue();\n    }\n\n    protected Object getMinValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.minValue();\n    }\n\n    protected Object getRandomValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.randomValue();\n    }\n\n    protected Object getPartialValue(Class<?> clazz)\n    {\n        dataGenerator = factory.getDataGenerator(clazz);\n        return dataGenerator.partialValue();\n    }\n\n    protected abstract void createSchema() throws SQLException;\n\n    protected abstract void dropSchema();\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport com.impetus.client.crud.BaseTest;\n\n/**\n * The Class StudentBase.\n * \n * @param <E>\n *            the element type\n */\npublic abstract class StudentBase<E extends StudentEntityDef> extends BaseTest\n{\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\n\n    /** The emf. */\n    protected EntityManagerFactory emf;\n\n    /** The em. */\n    protected EntityManager em;\n\n    // protected String persistenceUnit =\n    // /*\"twissandra,twibase,twingo,picmysql\"*/null;\n\n    /** The student id1. */\n    protected Object studentId1;\n\n    /** The student id2. */\n    protected Object studentId2;\n\n    /** The student id3. */\n    protected Object studentId3;\n    \n    /** The date. */\n//    protected long date =  new Date(2014+1980,03,01).getTime(); /*System.currentTimeMillis();*/\n    \n    /** The enrolment date. */\n    protected Date enrolmentDate = new Date();\n\n    /** The joining date and time. */\n    protected Date joiningDateAndTime = new Date();\n    /** The new sql date. */\n    protected java.sql.Date newSqlDate = new java.sql.Date(enrolmentDate.getTime());\n\n    /** The enrolment time. */\n    protected Date enrolmentTime = new Date();\n\n    /** The sql time. */\n    protected java.sql.Time sqlTime = new java.sql.Time(5,32,45);\n\n    /** The sql timestamp. */\n    protected java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(sqlTime.getTime());\n\n    /** The big decimal. */\n    protected BigDecimal bigDecimal = new BigDecimal(123456789);\n\n    /** The big integer. */\n    protected BigInteger bigInteger = new BigInteger(\"123456789\");\n\n    /** The number of students. */\n    protected int numberOfStudents = 1000;\n\n    /** The calendar. */\n    protected Calendar calendar = Calendar.getInstance();\n\n    /** The dao. */\n    // StudentDao dao;\n\n    /**\n     * Sets the up internal.\n     * \n     * @param persisntenceUnit\n     *            the new up internal\n     */\n    protected void setupInternal(String persisntenceUnit)\n    {\n        // dao = new StudentDao(persistenceUnit);\n\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            startServer();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createSchema();\n        }\n\n        studentId1 = new Long(12345677);\n        studentId2 = new Long(12345678);\n        studentId3 = new Long(12345679);\n\n        emf = Persistence.createEntityManagerFactory(persisntenceUnit);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Sets the up internal.\n     * \n     * @param persistenceUnit\n     *            the new up internal\n     */\n    protected void teardownInternal(String persistenceUnit)\n    {\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            deleteSchema();\n        }\n\n        if (em != null)\n        {\n            em.close();\n        }\n        if (emf != null)\n        {\n            emf.close();\n        }\n\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            stopServer();\n        }\n\n    }\n\n    /**\n     * on insert.\n     * \n     * @param instance\n     *            the instance\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    protected void onInsert(E instance) throws InstantiationException, IllegalAccessException\n    {\n\n        em.persist(prepareData((Long) studentId1, 78575785897L, \"Amresh\", true, 10, 'C', (byte) 5, (short) 8,\n                (float) 69.6, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar,\n                ((E) instance.getClass().newInstance())));\n\n        em.persist(prepareData((Long) studentId2, 78575785897L, \"Amresh\", true, 20, 'C', (byte) 5, (short) 8,\n                (float) 69.6, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar,\n                ((E) instance.getClass().newInstance())));\n\n        em.persist(prepareData((Long) studentId3, 78575785897L, \"Amresh\", true, 15, 'C', (byte) 5, (short) 8,\n                (float) 69.6, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar,\n                ((E) instance.getClass().newInstance())));\n\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param studentId\n     *            the student id\n     * @param uniqueId\n     *            the unique id\n     * @param studentName\n     *            the student name\n     * @param isExceptional\n     *            the is exceptional\n     * @param age\n     *            the age\n     * @param semester\n     *            the semester\n     * @param digitalSignature\n     *            the digital signature\n     * @param cgpa\n     *            the cgpa\n     * @param percentage\n     *            the percentage\n     * @param height\n     *            the height\n     * @param enrolmentDate\n     *            the enrolment date\n     * @param enrolmentTime\n     *            the enrolment time\n     * @param joiningDateAndTime\n     *            the joining date and time\n     * @param yearsSpent\n     *            the years spent\n     * @param rollNumber\n     *            the roll number\n     * @param monthlyFee\n     *            the monthly fee\n     * @param newSqlDate\n     *            the new sql date\n     * @param sqlTime\n     *            the sql time\n     * @param sqlTimestamp\n     *            the sql timestamp\n     * @param bigDecimal\n     *            the big decimal\n     * @param bigInteger\n     *            the big integer\n     * @param calendar\n     *            the calendar\n     * @param o\n     *            the o\n     * @return the person\n     */\n    protected E prepareData(long studentId, long uniqueId, String studentName, boolean isExceptional, int age,\n            char semester, byte digitalSignature, short cgpa, float percentage, double height,\n            java.util.Date enrolmentDate, java.util.Date enrolmentTime, java.util.Date joiningDateAndTime,\n            Integer yearsSpent, Long rollNumber, Double monthlyFee, java.sql.Date newSqlDate, java.sql.Time sqlTime,\n            java.sql.Timestamp sqlTimestamp, BigDecimal bigDecimal, BigInteger bigInteger, Calendar calendar, E o)\n    {\n        o.setStudentId((Long) studentId);\n        o.setUniqueId(78575785897L);\n        o.setStudentName(studentName);\n        o.setExceptional(isExceptional);\n        o.setAge(age);\n        o.setSemester(semester);\n        o.setDigitalSignature(digitalSignature);\n        o.setCgpa(cgpa);\n        o.setPercentage(percentage);\n        o.setHeight(height);\n\n        o.setEnrolmentDate(enrolmentDate);\n        o.setEnrolmentTime(enrolmentTime);\n        o.setJoiningDateAndTime(joiningDateAndTime);\n\n        o.setYearsSpent(yearsSpent);\n        o.setRollNumber(rollNumber);\n        o.setMonthlyFee(monthlyFee);\n        o.setSqlDate(newSqlDate);\n        o.setSqlTime(sqlTime);\n        o.setSqlTimestamp(sqlTimestamp);\n        o.setBigDecimal(bigDecimal);\n        o.setBigInteger(bigInteger);\n        o.setCalendar(calendar);\n        return (E) o;\n    }\n\n    /**\n     * Assert on data types.\n     * \n     * @param s\n     *            the s\n     */\n    protected void assertOnDataTypes(E s)\n    {\n\n        Assert.assertNotNull(s);\n        Assert.assertEquals(((Long) studentId1).longValue(), s.getStudentId());\n        Assert.assertEquals(78575785897L, s.getUniqueId());\n        Assert.assertEquals(\"Amresh\", s.getStudentName());\n        Assert.assertEquals(true, s.isExceptional());\n        Assert.assertEquals(10, s.getAge());\n        Assert.assertEquals('C', s.getSemester());\n        Assert.assertEquals((byte) 5, s.getDigitalSignature());\n        Assert.assertEquals((short) 8, s.getCgpa());\n        Assert.assertEquals((float) 69.6, s.getPercentage());\n        Assert.assertEquals(163.76765654, s.getHeight());\n\n        Assert.assertEquals(enrolmentDate.getDate(), s.getEnrolmentDate().getDate());\n        Assert.assertEquals(enrolmentDate.getMonth(), s.getEnrolmentDate().getMonth());\n        Assert.assertEquals(enrolmentDate.getYear(), s.getEnrolmentDate().getYear());\n\n        Assert.assertEquals(enrolmentTime.getHours(), s.getEnrolmentTime().getHours());\n        Assert.assertEquals(enrolmentTime.getMinutes(), s.getEnrolmentTime().getMinutes());\n        Assert.assertEquals(enrolmentTime.getSeconds(), s.getEnrolmentTime().getSeconds());\n\n        Assert.assertEquals(joiningDateAndTime.getDate(), s.getJoiningDateAndTime().getDate());\n        Assert.assertEquals(joiningDateAndTime.getMonth(), s.getJoiningDateAndTime().getMonth());\n        Assert.assertEquals(joiningDateAndTime.getYear(), s.getJoiningDateAndTime().getYear());\n        Assert.assertEquals(joiningDateAndTime.getHours(), s.getJoiningDateAndTime().getHours());\n        Assert.assertEquals(joiningDateAndTime.getMinutes(), s.getJoiningDateAndTime().getMinutes());\n        Assert.assertEquals(joiningDateAndTime.getSeconds(), s.getJoiningDateAndTime().getSeconds());\n\n        Assert.assertEquals(newSqlDate.getDate(), s.getSqlDate().getDate());\n        Assert.assertEquals(newSqlDate.getMonth(), s.getSqlDate().getMonth());\n        Assert.assertEquals(newSqlDate.getYear(), s.getSqlDate().getYear());\n\n        Assert.assertEquals(sqlTime.getMinutes(), s.getSqlTime().getMinutes());\n        Assert.assertEquals(sqlTime.getSeconds(), s.getSqlTime().getSeconds());\n        Assert.assertEquals(sqlTime.getHours(), s.getSqlTime().getHours());\n\n        Assert.assertEquals(sqlTimestamp.getDate(), s.getSqlTimestamp().getDate());\n        Assert.assertEquals(sqlTimestamp.getMonth(), s.getSqlTimestamp().getMonth());\n        Assert.assertEquals(sqlTimestamp.getYear(), s.getSqlTimestamp().getYear());\n        Assert.assertEquals(sqlTimestamp.getHours(), s.getSqlTimestamp().getHours());\n        Assert.assertEquals(sqlTimestamp.getMinutes(), s.getSqlTimestamp().getMinutes());\n        Assert.assertEquals(sqlTimestamp.getSeconds(), s.getSqlTimestamp().getSeconds());\n\n        Assert.assertEquals(Math.round(bigDecimal.doubleValue()), Math.round(s.getBigDecimal().doubleValue()));\n        Assert.assertEquals(bigInteger, s.getBigInteger());\n\n        Assert.assertEquals(calendar.get(Calendar.YEAR), s.getCalendar().get(Calendar.YEAR));\n        Assert.assertEquals(calendar.get(Calendar.MONTH), s.getCalendar().get(Calendar.MONTH));\n        Assert.assertEquals(calendar.get(Calendar.WEEK_OF_YEAR), s.getCalendar().get(Calendar.WEEK_OF_YEAR));\n        Assert.assertEquals(calendar.get(Calendar.WEEK_OF_MONTH), s.getCalendar().get(Calendar.WEEK_OF_MONTH));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_MONTH), s.getCalendar().get(Calendar.DAY_OF_MONTH));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_WEEK), s.getCalendar().get(Calendar.DAY_OF_WEEK));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH),\n                s.getCalendar().get(Calendar.DAY_OF_WEEK_IN_MONTH));\n        Assert.assertEquals(calendar.get(Calendar.DAY_OF_YEAR), s.getCalendar().get(Calendar.DAY_OF_YEAR));\n        Assert.assertEquals(calendar.get(Calendar.HOUR), s.getCalendar().get(Calendar.HOUR));\n        Assert.assertEquals(calendar.get(Calendar.HOUR_OF_DAY), s.getCalendar().get(Calendar.HOUR_OF_DAY));\n        Assert.assertEquals(calendar.get(Calendar.AM), s.getCalendar().get(Calendar.AM));\n        Assert.assertEquals(calendar.get(Calendar.PM), s.getCalendar().get(Calendar.PM));\n        Assert.assertEquals(calendar.get(Calendar.AM_PM), s.getCalendar().get(Calendar.AM_PM));\n\n        Assert.assertEquals(new Integer(3), s.getYearsSpent());\n        Assert.assertEquals(new Long(978423946455l), s.getRollNumber());\n        Assert.assertEquals(new Double(135434.89), s.getMonthlyFee());\n\n    }\n\n    abstract void startServer();\n\n    abstract void stopServer();\n\n    abstract void createSchema();\n\n    abstract void deleteSchema();\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentEntityDef.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\n\n/**\n * @author vivek.mishra\n * \n */\npublic interface StudentEntityDef\n{\n\n    /**\n     * @return the studentId\n     */\n    long getStudentId();\n\n    /**\n     * @param studentId\n     *            the studentId to set\n     */\n    void setStudentId(long studentId);\n\n    /**\n     * @return the uniqueId\n     */\n    long getUniqueId();\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    void setUniqueId(long uniqueId);\n\n    /**\n     * @return the studentName\n     */\n    String getStudentName();\n\n    /**\n     * @param studentName\n     *            the studentName to set\n     */\n    void setStudentName(String studentName);\n\n    /**\n     * @return the isExceptional\n     */\n    boolean isExceptional();\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    void setExceptional(boolean isExceptional);\n\n    /**\n     * @return the age\n     */\n    int getAge();\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    void setAge(int age);\n\n    /**\n     * @return the semester\n     */\n    char getSemester();\n\n    /**\n     * @param semester\n     *            the semester to set\n     */\n    void setSemester(char semester);\n\n    /**\n     * @return the digitalSignature\n     */\n    byte getDigitalSignature();\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    void setDigitalSignature(byte digitalSignature);\n\n    /**\n     * @return the cgpa\n     */\n    short getCgpa();\n\n    /**\n     * @param cgpa\n     *            the cgpa to set\n     */\n    void setCgpa(short cgpa);\n\n    /**\n     * @return the percentage\n     */\n    float getPercentage();\n\n    /**\n     * @param percentage\n     *            the percentage to set\n     */\n    void setPercentage(float percentage);\n\n    /**\n     * @return the height\n     */\n    double getHeight();\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    void setHeight(double height);\n\n    /**\n     * @return the enrolmentDate\n     */\n    java.util.Date getEnrolmentDate();\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    void setEnrolmentDate(java.util.Date enrolmentDate);\n\n    /**\n     * @return the enrolmentTime\n     */\n    java.util.Date getEnrolmentTime();\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    void setEnrolmentTime(java.util.Date enrolmentTime);\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    java.util.Date getJoiningDateAndTime();\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    void setJoiningDateAndTime(java.util.Date joiningDateAndTime);\n\n    /**\n     * @return the yearsSpent\n     */\n    Integer getYearsSpent();\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    void setYearsSpent(Integer yearsSpent);\n\n    /**\n     * @return the rollNumber\n     */\n    Long getRollNumber();\n\n    /**\n     * @param rollNumber\n     *            the rollNumber to set\n     */\n    void setRollNumber(Long rollNumber);\n\n    /**\n     * @return the monthlyFee\n     */\n    Double getMonthlyFee();\n\n    /**\n     * @param monthlyFee\n     *            the monthlyFee to set\n     */\n    void setMonthlyFee(Double monthlyFee);\n\n    java.sql.Date getSqlDate();\n\n    void setSqlDate(java.sql.Date sqlDate);\n\n    /**\n     * @return the sqlTimestamp\n     */\n    java.sql.Timestamp getSqlTimestamp();\n\n    /**\n     * @param sqlTimestamp\n     *            the sqlTimestamp to set\n     */\n    void setSqlTimestamp(java.sql.Timestamp sqlTimestamp);\n\n    /**\n     * @return the sqlTime\n     */\n    java.sql.Time getSqlTime();\n\n    /**\n     * @param sqlTime\n     *            the sqlTime to set\n     */\n    void setSqlTime(java.sql.Time sqlTime);\n\n    /**\n     * @return the bigInteger\n     */\n    BigInteger getBigInteger();\n\n    /**\n     * @param bigInteger\n     *            the bigInteger to set\n     */\n    void setBigInteger(BigInteger bigInteger);\n\n    /**\n     * @return the bigDecimal\n     */\n    BigDecimal getBigDecimal();\n\n    /**\n     * @param bigDecimal\n     *            the bigDecimal to set\n     */\n    void setBigDecimal(BigDecimal bigDecimal);\n\n    /**\n     * @return the calendar\n     */\n    Calendar getCalendar();\n\n    /**\n     * @param calendar\n     *            the calendar to set\n     */\n    void setCalendar(Calendar calendar);\n\n}"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbms.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\n@Entity\n@Table(name = \"STUDENT\", schema = \"testdb\")\npublic class StudentRdbms implements StudentEntityDef\n{\n    // Primitive Types\n    @Id\n    @Column(name = \"STUDENT_ID\")\n    private long studentId;\n\n    @Column(name = \"UNIQUE_ID\")\n    private long uniqueId;\n\n    @Column(name = \"STUDENT_NAME\")\n    private String studentName;\n\n    @Column(name = \"IS_EXCEPTIONAL\")\n    private boolean isExceptional;\n\n    @Column(name = \"AGE\")\n    private int age;\n\n    @Column(name = \"SEMESTER\")\n    private char semester; // A,B,C,D,E,F for i to vi\n\n    @Column(name = \"DIGITAL_SIGNATURE\")\n    private byte digitalSignature;\n\n    @Column(name = \"CGPA\")\n    private short cgpa; // 1-10\n\n    @Column(name = \"PERCENTAGE\")\n    private float percentage;\n\n    @Column(name = \"HEIGHT\")\n    private double height;\n\n    // Date-time types\n    @Column(name = \"ENROLMENT_DATE\")\n    @Temporal(TemporalType.DATE)\n    private java.util.Date enrolmentDate;\n\n    @Column(name = \"ENROLMENT_TIME\")\n    @Temporal(TemporalType.TIME)\n    private java.util.Date enrolmentTime;\n\n    @Column(name = \"JOINING_DATE_TIME\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private java.util.Date joiningDateAndTime;\n\n    // Wrapper types\n\n    @Column(name = \"YEARS_SPENT\")\n    private Integer yearsSpent;\n\n    @Column(name = \"ROLL_NUMBER\")\n    private Long rollNumber;\n\n    @Column(name = \"MONTHLY_FEE\")\n    private Double monthlyFee;\n\n    @Column(name = \"SQL_DATE\")\n    private java.sql.Date sqlDate;\n\n    @Column(name = \"SQL_TIMESTAMP\")\n    private java.sql.Timestamp sqlTimestamp;\n\n    @Column(name = \"SQL_TIME\")\n    private java.sql.Time sqlTime;\n\n    @Column(name = \"BIG_INT\")\n    private BigInteger bigInteger;\n\n    @Column(name = \"BIG_DECIMAL\")\n    private BigDecimal bigDecimal;\n\n    @Column(name = \"CALENDAR\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private Calendar calendar;\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getStudentId()\n     */\n    @Override\n    public long getStudentId()\n    {\n        return studentId;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setStudentId\n     * (long)\n     */\n    @Override\n    public void setStudentId(long studentId)\n    {\n        this.studentId = studentId;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getUniqueId()\n     */\n    @Override\n    public long getUniqueId()\n    {\n        return uniqueId;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setUniqueId\n     * (long)\n     */\n    @Override\n    public void setUniqueId(long uniqueId)\n    {\n        this.uniqueId = uniqueId;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getStudentName\n     * ()\n     */\n    @Override\n    public String getStudentName()\n    {\n        return studentName;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setStudentName\n     * (java.lang.String)\n     */\n    @Override\n    public void setStudentName(String studentName)\n    {\n        this.studentName = studentName;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#isExceptional\n     * ()\n     */\n    @Override\n    public boolean isExceptional()\n    {\n        return isExceptional;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setExceptional\n     * (boolean)\n     */\n    @Override\n    public void setExceptional(boolean isExceptional)\n    {\n        this.isExceptional = isExceptional;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.examples.crud.student.StudentEntityDef#getAge()\n     */\n    @Override\n    public int getAge()\n    {\n        return age;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setAge(int)\n     */\n    @Override\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getSemester()\n     */\n    @Override\n    public char getSemester()\n    {\n        return semester;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setSemester\n     * (char)\n     */\n    @Override\n    public void setSemester(char semester)\n    {\n        this.semester = semester;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.examples.crud.student.StudentEntityDef#\n     * getDigitalSignature()\n     */\n    @Override\n    public byte getDigitalSignature()\n    {\n        return digitalSignature;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.examples.crud.student.StudentEntityDef#\n     * setDigitalSignature(byte)\n     */\n    @Override\n    public void setDigitalSignature(byte digitalSignature)\n    {\n        this.digitalSignature = digitalSignature;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.examples.crud.student.StudentEntityDef#getCgpa()\n     */\n    @Override\n    public short getCgpa()\n    {\n        return cgpa;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setCgpa(short)\n     */\n    @Override\n    public void setCgpa(short cgpa)\n    {\n        this.cgpa = cgpa;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getPercentage\n     * ()\n     */\n    @Override\n    public float getPercentage()\n    {\n        return percentage;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setPercentage\n     * (float)\n     */\n    @Override\n    public void setPercentage(float percentage)\n    {\n        this.percentage = percentage;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getHeight()\n     */\n    @Override\n    public double getHeight()\n    {\n        return height;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setHeight(\n     * double)\n     */\n    @Override\n    public void setHeight(double height)\n    {\n        this.height = height;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getEnrolmentDate\n     * ()\n     */\n    @Override\n    public java.util.Date getEnrolmentDate()\n    {\n        return enrolmentDate;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setEnrolmentDate\n     * (java.util.Date)\n     */\n    @Override\n    public void setEnrolmentDate(java.util.Date enrolmentDate)\n    {\n        this.enrolmentDate = enrolmentDate;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getEnrolmentTime\n     * ()\n     */\n    @Override\n    public java.util.Date getEnrolmentTime()\n    {\n        return enrolmentTime;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setEnrolmentTime\n     * (java.util.Date)\n     */\n    @Override\n    public void setEnrolmentTime(java.util.Date enrolmentTime)\n    {\n        this.enrolmentTime = enrolmentTime;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.examples.crud.student.StudentEntityDef#\n     * getJoiningDateAndTime()\n     */\n    @Override\n    public java.util.Date getJoiningDateAndTime()\n    {\n        return joiningDateAndTime;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.examples.crud.student.StudentEntityDef#\n     * setJoiningDateAndTime(java.util.Date)\n     */\n    @Override\n    public void setJoiningDateAndTime(java.util.Date joiningDateAndTime)\n    {\n        this.joiningDateAndTime = joiningDateAndTime;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getYearsSpent\n     * ()\n     */\n    @Override\n    public Integer getYearsSpent()\n    {\n        return yearsSpent;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setYearsSpent\n     * (java.lang.Integer)\n     */\n    @Override\n    public void setYearsSpent(Integer yearsSpent)\n    {\n        this.yearsSpent = yearsSpent;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getRollNumber\n     * ()\n     */\n    @Override\n    public Long getRollNumber()\n    {\n        return rollNumber;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setRollNumber\n     * (java.lang.Long)\n     */\n    @Override\n    public void setRollNumber(Long rollNumber)\n    {\n        this.rollNumber = rollNumber;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getMonthlyFee\n     * ()\n     */\n    @Override\n    public Double getMonthlyFee()\n    {\n        return monthlyFee;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setMonthlyFee\n     * (java.lang.Double)\n     */\n    @Override\n    public void setMonthlyFee(Double monthlyFee)\n    {\n        this.monthlyFee = monthlyFee;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getSqlDate()\n     */\n    @Override\n    public java.sql.Date getSqlDate()\n    {\n        return sqlDate;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setSqlDate\n     * (java.sql.Date)\n     */\n    @Override\n    public void setSqlDate(java.sql.Date sqlDate)\n    {\n        this.sqlDate = sqlDate;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getSqlTimestamp\n     * ()\n     */\n    @Override\n    public java.sql.Timestamp getSqlTimestamp()\n    {\n        return sqlTimestamp;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setSqlTimestamp\n     * (java.sql.Timestamp)\n     */\n    @Override\n    public void setSqlTimestamp(java.sql.Timestamp sqlTimestamp)\n    {\n        this.sqlTimestamp = sqlTimestamp;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getSqlTime()\n     */\n    @Override\n    public java.sql.Time getSqlTime()\n    {\n        return sqlTime;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setSqlTime\n     * (java.sql.Time)\n     */\n    @Override\n    public void setSqlTime(java.sql.Time sqlTime)\n    {\n        this.sqlTime = sqlTime;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getBigInteger\n     * ()\n     */\n    @Override\n    public BigInteger getBigInteger()\n    {\n        return bigInteger;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setBigInteger\n     * (java.math.BigInteger)\n     */\n    @Override\n    public void setBigInteger(BigInteger bigInteger)\n    {\n        this.bigInteger = bigInteger;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getBigDecimal\n     * ()\n     */\n    @Override\n    public BigDecimal getBigDecimal()\n    {\n        return bigDecimal;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setBigDecimal\n     * (java.math.BigDecimal)\n     */\n    @Override\n    public void setBigDecimal(BigDecimal bigDecimal)\n    {\n        this.bigDecimal = bigDecimal;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#getCalendar()\n     */\n    @Override\n    public Calendar getCalendar()\n    {\n        return calendar;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.examples.crud.student.StudentEntityDef#setCalendar\n     * (java.util.Calendar)\n     */\n    @Override\n    public void setCalendar(Calendar calendar)\n    {\n        this.calendar = calendar;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsBigDecimalTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.math.BigDecimal;\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentBigDecimal;\n\npublic class StudentRdbmsBigDecimalTest extends RdbmsBase\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of BigDecimal\n        StudentBigDecimal studentMax = new StudentBigDecimal();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setStudentId((BigDecimal) getMaxValue(BigDecimal.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of BigDecimal\n        StudentBigDecimal studentMin = new StudentBigDecimal();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setStudentId((BigDecimal) getMinValue(BigDecimal.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of BigDecimal\n        StudentBigDecimal student = new StudentBigDecimal();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setStudentId((BigDecimal) getRandomValue(BigDecimal.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBigDecimal studentMax = em.find(StudentBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigDecimal studentMin = em.find(StudentBigDecimal.class, getMinValue(BigDecimal.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigDecimal student = em.find(StudentBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentBigDecimal student = em.find(StudentBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigDecimal newStudent = em.find(StudentBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            Assert.assertEquals(getMinValue(BigDecimal.class), student.getStudentId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(BigDecimal.class));\n        q.setParameter(2, getMaxValue(BigDecimal.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            if (student.getStudentId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getStudentId().equals(getMinValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigDecimal.class), student.getStudentId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigDecimal.class), student.getStudentId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBigDecimal studentMax = em.find(StudentBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentBigDecimal.class, getMaxValue(BigDecimal.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentBigDecimal s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigDecimal newStudent = em.find(StudentBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentBigDecimal s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigDecimal newStudent = em.find(StudentBigDecimal.class, getRandomValue(BigDecimal.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.name = 'Amresh' and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            Assert.assertEquals(((BigDecimal) getRandomValue(BigDecimal.class)).intValue(), student.getStudentId()\n                    .intValue());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            Assert.assertEquals(((BigDecimal) getRandomValue(BigDecimal.class)).intValue(), student.getStudentId()\n                    .intValue());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.name = 'Kuldeep' and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            if (student.getStudentId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigDecimal.class), student.getStudentId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            Assert.assertEquals(((BigDecimal) getRandomValue(BigDecimal.class)).intValue(), student.getStudentId()\n                    .intValue());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigDecimal> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigDecimal s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            if (student.getStudentId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigDecimal.class), student.getStudentId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentBigDecimal s \";\n        Query q = em.createQuery(query);\n        List<StudentBigDecimal> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentBigDecimal student : students)\n        {\n            if (student.getStudentId().equals(getMaxValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getStudentId().equals(getMinValue(BigDecimal.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((BigDecimal) getRandomValue(BigDecimal.class)).intValue(), student.getStudentId()\n                        .intValue());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE TESTDB.StudentBigDecimal (STUDENT_ID DECIMAL(19,2) PRIMARY KEY, NAME VARCHAR(255), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentBigDecimal\");\n            cli.update(\"DROP TABLE TESTDB.StudentBigDecimal\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentBigDecimal (STUDENT_ID DECIMAL(19,2) PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentBigDecimal\");\n            cli.update(\"DROP TABLE TESTDB.StudentBigDecimal\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsBigIntegerTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.math.BigInteger;\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentBigInteger;\n\npublic class StudentRdbmsBigIntegerTest extends RdbmsBase\n{\n\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQuery(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of BigInteger\n        StudentBigInteger studentMax = new StudentBigInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((BigInteger) getMaxValue(BigInteger.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of BigInteger\n        StudentBigInteger studentMin = new StudentBigInteger();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((BigInteger) getMinValue(BigInteger.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of BigInteger\n        StudentBigInteger student = new StudentBigInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((BigInteger) getRandomValue(BigInteger.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBigInteger studentMax = em\n                .find(StudentBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigInteger studentMin = em\n                .find(StudentBigInteger.class, getMinValue(BigInteger.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigInteger student = em\n                .find(StudentBigInteger.class, getRandomValue(BigInteger.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentBigInteger student = em.find(StudentBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigInteger newStudent = em\n                .find(StudentBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) + \"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(BigInteger.class));\n        q.setParameter(2, getMaxValue(BigInteger.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.name = 'Kuldeep' and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.name = 'Kuldeep' and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(useSameEm);\n        deleteNamed(useSameEm);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBigInteger studentMax = em\n                .find(StudentBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentBigInteger.class, getMaxValue(BigInteger.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentBigInteger s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigInteger newStudent = em.find(StudentBigInteger.class,\n                getRandomValue(BigInteger.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentBigInteger s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBigInteger newStudent = em.find(StudentBigInteger.class,\n                getRandomValue(BigInteger.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.name = 'Amresh' and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.name = 'Kuldeep' and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBigInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBigInteger s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentBigInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentBigInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentBigInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(BigInteger.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(BigInteger.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {}\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentBigInteger (id BIGINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentBigInteger\");\n            cli.update(\"DROP TABLE TESTDB.StudentBigInteger\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentBigInteger (id BIGINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentBigInteger\");\n            cli.update(\"DROP TABLE TESTDB.StudentBigInteger\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsBooleanPrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentBooleanPrimitive;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class StudentRdbmsBooleanPrimitiveTest extends RdbmsBase\n{\n\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of boolean\n        StudentBooleanPrimitive studentMax = new StudentBooleanPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Boolean) getMaxValue(boolean.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of boolean\n        StudentBooleanPrimitive studentMin = new StudentBooleanPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Boolean) getMinValue(boolean.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBooleanPrimitive studentMax = em.find(StudentBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanPrimitive studentMin = em.find(StudentBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentBooleanPrimitive student = em.find(StudentBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanPrimitive newStudent = em.find(StudentBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) +\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(boolean.class));\n        q.setParameter(2, getMaxValue(boolean.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.name = 'Kuldeep' or s.age > \" + getMinValue(short.class);\n        try\n        {\n            q = em.createQuery(query);\n            students = q.getResultList();\n            Assert.assertNotNull(students);\n            Assert.assertEquals(2, students.size());\n            count = 0;\n            for (StudentBooleanPrimitive student : students)\n            {\n                if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n                {\n                    Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                    Assert.assertEquals(\"Kuldeep\", student.getName());\n                    count++;\n                }\n                else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n                {\n                    Assert.assertEquals(getMinValue(short.class), student.getAge());\n                    Assert.assertEquals(getMinValue(String.class), student.getName());\n                    count++;\n                }\n            }\n            Assert.assertEquals(2, count);\n            em.close();\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertEquals(\"unsupported clause OR for cassandra\", qhe.getMessage());\n        }\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.name = 'Kuldeep' and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(boolean.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBooleanPrimitive studentMax = em.find(StudentBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMinValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentBooleanPrimitive.class, getMinValue(boolean.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentBooleanPrimitive s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanPrimitive newStudent = em.find(StudentBooleanPrimitive.class, getRandomValue(boolean.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentBooleanPrimitive s SET s.name='Vivek' where s.id=true\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanPrimitive newStudent = em.find(StudentBooleanPrimitive.class, getMaxValue(boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.name = 'Kuldeep' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.name = 'Kuldeep' and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.age = \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanPrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentBooleanPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentBooleanPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBooleanPrimitive student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentBooleanPrimitive (id BOOLEAN PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentBooleanPrimitive\");\n            cli.update(\"DROP TABLE TESTDB.StudentBooleanPrimitive\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentBooleanPrimitive (id BOOLEAN PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentBooleanPrimitive\");\n            cli.update(\"DROP TABLE TESTDB.StudentBooleanPrimitive\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsBooleanWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentBooleanWrapper;\nimport com.impetus.kundera.query.QueryHandlerException;\n\npublic class StudentRdbmsBooleanWrapperTest extends RdbmsBase\n{\n\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Boolean\n        StudentBooleanWrapper studentMax = new StudentBooleanWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Boolean) getMaxValue(Boolean.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Boolean\n        StudentBooleanWrapper studentMin = new StudentBooleanWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Boolean) getMinValue(Boolean.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBooleanWrapper studentMax = em.find(StudentBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanWrapper studentMin = em.find(StudentBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        em.close();\n    }\n\n    public void testMerge(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentBooleanWrapper student = em.find(StudentBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanWrapper newStudent = em.find(StudentBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(Boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) +\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Boolean.class));\n        q.setParameter(2, getMaxValue(Boolean.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.name = 'Kuldeep' or s.age > \" + getMinValue(short.class);\n        try\n        {\n            q = em.createQuery(query);\n            students = q.getResultList();\n            Assert.assertNotNull(students);\n            Assert.assertEquals(2, students.size());\n            count = 0;\n            for (StudentBooleanWrapper student : students)\n            {\n                if (student.getId() == ((Boolean) getMaxValue(boolean.class)).booleanValue())\n                {\n                    Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                    Assert.assertEquals(\"Kuldeep\", student.getName());\n                    count++;\n                }\n                else if (student.getId() == ((Boolean) getMinValue(boolean.class)).booleanValue())\n                {\n                    Assert.assertEquals(getMinValue(short.class), student.getAge());\n                    Assert.assertEquals(getMinValue(String.class), student.getName());\n                    count++;\n                }}\n            Assert.assertEquals(2, count);\n            em.close();\n        }\n        catch (QueryHandlerException qhe)\n        {\n            Assert.assertEquals(\"unsupported clause OR for cassandra\", qhe.getMessage());\n        }\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.name = 'Kuldeep' and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(Boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(Boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBooleanWrapper studentMax = em.find(StudentBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMinValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentBooleanWrapper.class, getMinValue(Boolean.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(Boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentBooleanWrapper s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanWrapper newStudent = em.find(StudentBooleanWrapper.class, getRandomValue(Boolean.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(Boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentBooleanWrapper s SET s.name='Vivek' where s.id=true\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBooleanWrapper newStudent = em.find(StudentBooleanWrapper.class, getMaxValue(Boolean.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.name = 'Kuldeep' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            if (student.getId() == ((Boolean) getMaxValue(Boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Boolean) getMinValue(Boolean.class)).booleanValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertTrue(students.isEmpty());\n\n        em.close();\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.name = 'Kuldeep' and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.age = \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBooleanWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBooleanWrapper s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Boolean.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentBooleanWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentBooleanWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentBooleanWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Boolean.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentBooleanWrapper (id BOOLEAN PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentBooleanWrapper\");\n            cli.update(\"DROP TABLE TESTDB.StudentBooleanWrapper\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentBooleanWrapper (id BOOLEAN PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentBooleanWrapper\");\n            cli.update(\"DROP TABLE TESTDB.StudentBooleanWrapper\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsBytePrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentBytePrimitive;\n\npublic class StudentRdbmsBytePrimitiveTest extends RdbmsBase\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of byte\n        StudentBytePrimitive studentMax = new StudentBytePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of byte\n        StudentBytePrimitive studentMin = new StudentBytePrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Byte) getMinValue(byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of byte\n        StudentBytePrimitive student = new StudentBytePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBytePrimitive studentMax = em.find(StudentBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBytePrimitive studentMin = em.find(StudentBytePrimitive.class, getMinValue(byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBytePrimitive student = em.find(StudentBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentBytePrimitive student = em.find(StudentBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBytePrimitive newStudent = em.find(StudentBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) +\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(byte.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(byte.class));\n        q.setParameter(2, getMaxValue(byte.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Byte) getMinValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentBytePrimitive studentMax = em.find(StudentBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentBytePrimitive.class, getMaxValue(byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentBytePrimitive s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBytePrimitive newStudent = em.find(StudentBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentBytePrimitive s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentBytePrimitive newStudent = em.find(StudentBytePrimitive.class, getRandomValue(byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.name = 'Kuldeep' and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentBytePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentBytePrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentBytePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentBytePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentBytePrimitive student : students)\n        {\n            if (student.getId() == ((Byte) getMaxValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Byte) getMinValue(byte.class)).byteValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentBytePrimitive (id TINYINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentBytePrimitive\");\n            cli.update(\"DROP TABLE TESTDB.StudentBytePrimitive\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentBytePrimitive (id TINYINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentBytePrimitive\");\n            cli.update(\"DROP TABLE TESTDB.StudentBytePrimitive\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsByteWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentByteWrapper;\n\npublic class StudentRdbmsByteWrapperTest extends RdbmsBase\n{\n\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Byte\n        StudentByteWrapper studentMax = new StudentByteWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Byte) getMaxValue(Byte.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Byte\n        StudentByteWrapper studentMin = new StudentByteWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Byte) getMinValue(Byte.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Byte\n        StudentByteWrapper student = new StudentByteWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Byte) getRandomValue(Byte.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentByteWrapper studentMax = em.find(StudentByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentByteWrapper studentMin = em.find(StudentByteWrapper.class, getMinValue(Byte.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentByteWrapper student = em.find(StudentByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentByteWrapper student = em.find(StudentByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentByteWrapper newStudent = em.find(StudentByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Byte.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.id between \" + getMinValue(Byte.class) + \" and \"\n                + getMaxValue(Byte.class);\n        // query =\n        // \"Select s From StudentByteWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        // q.setParameter(1, getMinValue(Byte.class));\n        // q.setParameter(2, getMaxValue(Byte.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Byte.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Byte.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentByteWrapper studentMax = em.find(StudentByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentByteWrapper.class, getMaxValue(Byte.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentByteWrapper s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentByteWrapper newStudent = em.find(StudentByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentByteWrapper s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentByteWrapper newStudent = em.find(StudentByteWrapper.class, getRandomValue(Byte.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.name = 'Kuldeep' and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentByteWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentByteWrapper s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Byte.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentByteWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentByteWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentByteWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Byte.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Byte.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Byte.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentByteWrapper (id TINYINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentByteWrapper\");\n            cli.update(\"DROP TABLE TESTDB.StudentByteWrapper\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentByteWrapper (id TINYINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentByteWrapper\");\n            cli.update(\"DROP TABLE TESTDB.StudentByteWrapper\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsCharTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentChar;\n\npublic class StudentRdbmsCharTest extends RdbmsBase\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of char\n        StudentChar studentMax = new StudentChar();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Character) getMaxValue(char.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of char\n        StudentChar studentMin = new StudentChar();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Character) getMinValue(char.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of char\n        StudentChar student = new StudentChar();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(char.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentChar studentMax = em.find(StudentChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentChar studentMin = em.find(StudentChar.class, getMinValue(char.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentChar student = em.find(StudentChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentChar student = em.find(StudentChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentChar newStudent = em.find(StudentChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            Assert.assertEquals(getMinValue(char.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getRandomValue(Character.class));\n        q.setParameter(2, getMaxValue(char.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentChar student : students)\n        {\n            if (student.getId() == (Character)getMaxValue(Character.class))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            Assert.assertEquals(getMaxValue(char.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentChar studentMax = em.find(StudentChar.class, getMaxValue(char.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentChar.class, getMaxValue(char.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentChar s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentChar newStudent = em.find(StudentChar.class, getRandomValue(char.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentChar s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentChar newStudent = em.find(StudentChar.class, getRandomValue(char.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.name = 'Amresh' and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.name = 'Kuldeep' and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            Assert.assertEquals(getRandomValue(char.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentChar> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentChar s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(char.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentChar s \";\n        Query q = em.createQuery(query);\n        List<StudentChar> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentChar student : students)\n        {\n            if (student.getId() == ((Character) getMaxValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Character) getMinValue(char.class)).charValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(char.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentChar (id VARCHAR(255) PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentChar\");\n            cli.update(\"DROP TABLE TESTDB.StudentChar\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentChar (id VARCHAR(255) PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentChar\");\n            cli.update(\"DROP TABLE TESTDB.StudentChar\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsCharacterTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentCharacter;\n\npublic class StudentRdbmsCharacterTest extends RdbmsBase\n{\n    private Character maxValue = (Character) getMaxValue(Character.class);\n    \n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Character\n        StudentCharacter studentMax = new StudentCharacter();\n        studentMax.setAge((Short) getMaxValue(short.class));        \n        studentMax.setId((Character) maxValue);\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Character\n        StudentCharacter studentMin = new StudentCharacter();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Character) getMinValue(Character.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Character\n        StudentCharacter student = new StudentCharacter();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Character) getRandomValue(Character.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCharacter studentMax = em.find(StudentCharacter.class, maxValue);\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCharacter studentMin = em.find(StudentCharacter.class, getMinValue(Character.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCharacter student = em.find(StudentCharacter.class, getRandomValue(Character.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentCharacter student = em.find(StudentCharacter.class, maxValue);\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCharacter newStudent = em.find(StudentCharacter.class, maxValue);\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            Assert.assertEquals(getMinValue(Character.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getRandomValue(Character.class));\n        q.setParameter(2, maxValue);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentCharacter student : students)\n        {\n            if (student.getId().equals(maxValue))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            Assert.assertEquals(maxValue, student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            Assert.assertEquals(maxValue, student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentCharacter studentMax = em.find(StudentCharacter.class, maxValue);\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentCharacter.class, maxValue);\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentCharacter s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCharacter newStudent = em.find(StudentCharacter.class, getRandomValue(Character.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentCharacter s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentCharacter newStudent = em.find(StudentCharacter.class, getRandomValue(Character.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.name = 'Amresh' and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.name = 'Kuldeep' and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            if (student.getId().equals(maxValue))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            Assert.assertEquals(getRandomValue(Character.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentCharacter> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentCharacter s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentCharacter student : students)\n        {\n            if (student.getId().equals(maxValue))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Character.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentCharacter s \";\n        Query q = em.createQuery(query);\n        List<StudentCharacter> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentCharacter student : students)\n        {\n            if (student.getId().equals(maxValue))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Character.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Character.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentCharacter (id VARCHAR(255) PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentCharacter\");\n            cli.update(\"DROP TABLE TESTDB.StudentCharacter\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentCharacter (id VARCHAR(255) PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentCharacter\");\n            cli.update(\"DROP TABLE TESTDB.StudentCharacter\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsDateTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentDate;\n\npublic class StudentRdbmsDateTest extends RdbmsBase\n{\n\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        // TODO : uncomment once date issue fixed.\n//        testPersist(true);\n//        testFindById(true);\n//        testMerge(true);\n//        testFindByQuery(true);\n//        testNamedQueryUseSameEm(true);\n//        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n//        TODO : uncomment once date issue fixed.\n//        testPersist(false);\n//        testFindById(false);\n//        testMerge(false);\n//        testFindByQuery(false);\n//        testNamedQuery(false);\n//        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentDate student = new StudentDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue(Date.class));\n        student.setName((String) getRandomValue(String.class));\n\n        // Insert max value of Date\n        StudentDate studentMax = new StudentDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue(Date.class));\n        studentMax.setName((String) getMaxValue(String.class));\n\n        // Insert min value of Date\n        StudentDate studentMin = new StudentDate();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Date) getMinValue(Date.class));\n        studentMin.setName((String) getMinValue(String.class));\n\n        em.persist(student);\n        em.persist(studentMax);\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentDate studentMax = em.find(StudentDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDate studentMin = em.find(StudentDate.class, getMinValue(Date.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDate student = em.find(StudentDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentDate student = em.find(StudentDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDate newStudent = em.find(StudentDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > Amresh and s.name <= \" + getMaxValue(String.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            Assert.assertEquals(getMinValue(Date.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.id between ?1  and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Date.class));\n        q.setParameter(2, getMaxValue(Date.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Date.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Date.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.name = Kuldeep and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            Assert.assertEquals(getMaxValue(Date.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentDate studentMax = em.find(StudentDate.class, getMaxValue(Date.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentDate.class, getMaxValue(Date.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentDate s where s.name=Vivek\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDate newStudent = em.find(StudentDate.class, getRandomValue(Date.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentDate s SET s.name=Vivek where s.name=Amresh\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDate newStudent = em.find(StudentDate.class, getRandomValue(Date.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.name = Amresh and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.name = Amresh and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.name = Kuldeep and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            Assert.assertEquals(getRandomValue(Date.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDate s where s.name = Kuldeep\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentDate student : students)\n        {\n            if (student.getId().equals(getMaxValue(Date.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Date.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentDate s \";\n        Query q = em.createQuery(query);\n        List<StudentDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentDate student : students)\n        {\n            if (student.getId().getDate() == ((Date)getMaxValue(Date.class)).getDate())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().getDate() == ((Date)getMinValue(Date.class)).getDate())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue(Date.class)).getDate(), student.getId().getDate());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentDate (id DATE PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentDate\");\n            cli.update(\"DROP TABLE TESTDB.StudentDate\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentDate (id DATE PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentDate\");\n            cli.update(\"DROP TABLE TESTDB.StudentDate\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n   \n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsDoublePrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentDoublePrimitive;\n\npublic class StudentRdbmsDoublePrimitiveTest extends RdbmsBase\n{\n\n    private Double maxValue = (double) Float.MAX_VALUE;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Double\n        StudentDoublePrimitive student = new StudentDoublePrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        \n        // Insert min value of Double\n        StudentDoublePrimitive studentMin = new StudentDoublePrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Double) getMinValue());\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert max value of Double\n        StudentDoublePrimitive studentMax = new StudentDoublePrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) maxValue);\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n        em.close();\n    }\n\n    private Object getMinValue()\n    {\n        return -1232.123;\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentDoublePrimitive studentMax = em.find(StudentDoublePrimitive.class, maxValue);\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoublePrimitive studentMin = em.find(StudentDoublePrimitive.class, getMinValue());\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoublePrimitive student = em.find(StudentDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentDoublePrimitive student = em.find(StudentDoublePrimitive.class, maxValue);\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoublePrimitive newStudent = em.find(StudentDoublePrimitive.class, maxValue);\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) +\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue());\n        q.setParameter(2, maxValue);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) maxValue).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Double) getMinValue()).doubleValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            Assert.assertEquals(maxValue, student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            Assert.assertEquals(maxValue, student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentDoublePrimitive studentMax = em.find(StudentDoublePrimitive.class, maxValue);\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentDoublePrimitive.class, maxValue);\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentDoublePrimitive s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoublePrimitive newStudent = em.find(StudentDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentDoublePrimitive s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoublePrimitive newStudent = em.find(StudentDoublePrimitive.class, getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.name = 'Kuldeep' and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) maxValue).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoublePrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoublePrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            if (student.getId() == ((Double) maxValue).doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentDoublePrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentDoublePrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentDoublePrimitive student : students)\n        {\n            if (student.getId() == maxValue.doubleValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Double) getMinValue()).doubleValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentDoublePrimitive (id DOUBLE PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentDoublePrimitive\");\n            cli.update(\"DROP TABLE TESTDB.StudentDoublePrimitive\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentDoublePrimitive (id DOUBLE PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentDoublePrimitive\");\n            cli.update(\"DROP TABLE TESTDB.StudentDoublePrimitive\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsDoubleWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentDoubleWrapper;\n\npublic class StudentRdbmsDoubleWrapperTest extends RdbmsBase\n{\n\n    private Double maxValue = (double) Float.MAX_VALUE;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    private Object getMinValue()\n    {\n        return -1232.123;\n    }\n    \n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Double\n        StudentDoubleWrapper studentMax = new StudentDoubleWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Double) maxValue);\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Double\n        StudentDoubleWrapper studentMin = new StudentDoubleWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Double) getMinValue());\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Double\n        StudentDoubleWrapper student = new StudentDoubleWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Double) getRandomValue(Double.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentDoubleWrapper studentMax = em.find(StudentDoubleWrapper.class, maxValue);\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoubleWrapper studentMin = em.find(StudentDoubleWrapper.class, getMinValue());\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoubleWrapper student = em.find(StudentDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentDoubleWrapper student = em.find(StudentDoubleWrapper.class, maxValue);\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoubleWrapper newStudent = em.find(StudentDoubleWrapper.class, maxValue);\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class) +\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue());\n        q.setParameter(2, maxValue);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            if (student.getId().equals(maxValue))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue()))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            Assert.assertEquals(maxValue, student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            Assert.assertEquals(maxValue, student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentDoubleWrapper studentMax = em.find(StudentDoubleWrapper.class, maxValue);\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentDoubleWrapper.class, maxValue);\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentDoubleWrapper s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoubleWrapper newStudent = em.find(StudentDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentDoubleWrapper s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentDoubleWrapper newStudent = em.find(StudentDoubleWrapper.class, getRandomValue(Double.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.name = 'Kuldeep' and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            if (student.getId().equals(maxValue))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Double.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentDoubleWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentDoubleWrapper s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            if (student.getId().equals(maxValue))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentDoubleWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentDoubleWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentDoubleWrapper student : students)\n        {\n            if (student.getId().equals(maxValue))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue()))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Double.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentDoubleWrapper (id DOUBLE PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentDoubleWrapper\");\n            cli.update(\"DROP TABLE TESTDB.StudentDoubleWrapper\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentDoubleWrapper (id DOUBLE PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentDoubleWrapper\");\n            cli.update(\"DROP TABLE TESTDB.StudentDoubleWrapper\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsIntTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentInt;\n\npublic class StudentRdbmsIntTest extends RdbmsBase\n{\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of int\n        StudentInt studentMax = new StudentInt();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(int.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of int\n        StudentInt studentMin = new StudentInt();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Integer) getMinValue(int.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of int\n        StudentInt student = new StudentInt();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(int.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentInt studentMax = em.find(StudentInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInt studentMin = em.find(StudentInt.class, getMinValue(int.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInt student = em.find(StudentInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentInt student = em.find(StudentInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInt newStudent = em.find(StudentInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            Assert.assertEquals(getMinValue(int.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.id between \" + getMinValue(int.class) + \" and \"\n                + getMaxValue(int.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Integer) getMinValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            Assert.assertEquals(getMaxValue(int.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentInt studentMax = em.find(StudentInt.class, getMaxValue(int.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentInt.class, getMaxValue(int.class));\n        Assert.assertNull(studentMax);\n        testPersist(useSameEm);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentInt s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInt newStudent = em.find(StudentInt.class, getRandomValue(int.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentInt s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInt newStudent = em.find(StudentInt.class, getRandomValue(int.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.name = 'Kuldeep' and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            Assert.assertEquals(getRandomValue(int.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInt> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInt s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(int.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentInt s \";\n        Query q = em.createQuery(query);\n        List<StudentInt> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentInt student : students)\n        {\n            if (student.getId() == ((Integer) getMaxValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Integer) getMinValue(int.class)).intValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(int.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentInt (id INTEGER PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentInt\");\n            cli.update(\"DROP TABLE TESTDB.StudentInt\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentInt (id INTEGER PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentInt\");\n            cli.update(\"DROP TABLE TESTDB.StudentInt\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsIntegerTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentInteger;\n\npublic class StudentRdbmsIntegerTest extends RdbmsBase\n{\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of integer\n        StudentInteger studentMax = new StudentInteger();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Integer) getMaxValue(Integer.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of integer\n        StudentInteger studentMin = new StudentInteger();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Integer) getMinValue(Integer.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of integer\n        StudentInteger student = new StudentInteger();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Integer) getRandomValue(Integer.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentInteger studentMax = em.find(StudentInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInteger studentMin = em.find(StudentInteger.class, getMinValue(Integer.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInteger student = em.find(StudentInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentInteger student = em.find(StudentInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInteger newStudent = em.find(StudentInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            Assert.assertEquals(getMinValue(Integer.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Integer.class));\n        q.setParameter(2, getMaxValue(Integer.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Integer.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.name = 'Kuldeep' and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.name = 'Kuldeep' and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            Assert.assertEquals(getMaxValue(Integer.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentInteger studentMax = em.find(StudentInteger.class, getMaxValue(Integer.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentInteger.class, getMaxValue(Integer.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentInteger s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInteger newStudent = em.find(StudentInteger.class, getRandomValue(Integer.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentInteger s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentInteger newStudent = em.find(StudentInteger.class, getRandomValue(Integer.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.name = 'Kuldeep' and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentInteger> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentInteger s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Integer.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentInteger s \";\n        Query q = em.createQuery(query);\n        List<StudentInteger> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentInteger student : students)\n        {\n            if (student.getId().equals(getMaxValue(Integer.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Integer.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Integer.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE TESTDB.StudentInteger (id INTEGER PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentInteger\");\n            cli.update(\"DROP TABLE TESTDB.StudentInteger\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentInteger (id INTEGER PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentInteger\");\n            cli.update(\"DROP TABLE TESTDB.StudentInteger\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsLongPrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentLongPrimitive;\n\npublic class StudentRdbmsLongPrimitiveTest extends RdbmsBase\n{\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of long\n        StudentLongPrimitive studentMax = new StudentLongPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of long\n        StudentLongPrimitive studentMin = new StudentLongPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Long) getMinValue(long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of long\n        StudentLongPrimitive student = new StudentLongPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentLongPrimitive studentMax = em.find(StudentLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongPrimitive studentMin = em.find(StudentLongPrimitive.class, getMinValue(long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongPrimitive student = em.find(StudentLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentLongPrimitive student = em.find(StudentLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongPrimitive newStudent = em.find(StudentLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(long.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.id between \" + getMinValue(long.class) + \" and \"\n                + getMaxValue(long.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Long) getMinValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentLongPrimitive studentMax = em.find(StudentLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentLongPrimitive.class, getMaxValue(long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentLongPrimitive s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongPrimitive newStudent = em.find(StudentLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentLongPrimitive s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongPrimitive newStudent = em.find(StudentLongPrimitive.class, getRandomValue(long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.name = 'Kuldeep' and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongPrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentLongPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentLongPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentLongPrimitive student : students)\n        {\n            if (student.getId() == ((Long) getMaxValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Long) getMinValue(long.class)).longValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentLongPrimitive (id BIGINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentLongPrimitive\");\n            cli.update(\"DROP TABLE TESTDB.StudentLongPrimitive\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentLongPrimitive (id BIGINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentLongPrimitive\");\n            cli.update(\"DROP TABLE TESTDB.StudentLongPrimitive\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsLongWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentLongWrapper;\n\npublic class StudentRdbmsLongWrapperTest extends RdbmsBase\n{\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert min value of Long\n        StudentLongWrapper studentMin = new StudentLongWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Long) getMinValue(Long.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Long\n        StudentLongWrapper student = new StudentLongWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Long) getRandomValue(Long.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Long\n        StudentLongWrapper studentMax = new StudentLongWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Long) getMaxValue(Long.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentLongWrapper studentMax = em.find(StudentLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongWrapper studentMin = em.find(StudentLongWrapper.class, getMinValue(Long.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongWrapper student = em.find(StudentLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentLongWrapper student = em.find(StudentLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongWrapper newStudent = em.find(StudentLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Long.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.id between ?1 and ?2\";\n        q = em.createQuery(query);\n        q.setParameter(1, getMinValue(Long.class));\n        q.setParameter(2, getMaxValue(Long.class));\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Long.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Long.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentLongWrapper studentMax = em.find(StudentLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentLongWrapper.class, getMaxValue(Long.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentLongWrapper s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongWrapper newStudent = em.find(StudentLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentLongWrapper s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentLongWrapper newStudent = em.find(StudentLongWrapper.class, getRandomValue(Long.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.name = 'Kuldeep' and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Long.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentLongWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentLongWrapper s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Long.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentLongWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentLongWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentLongWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Long.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Long.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Long.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentLongWrapper (id BIGINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentLongWrapper\");\n            cli.update(\"DROP TABLE TESTDB.StudentLongWrapper\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentLongWrapper (id BIGINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentLongWrapper\");\n            cli.update(\"DROP TABLE TESTDB.StudentLongWrapper\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsShortPrimitiveTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentShortPrimitive;\n\npublic class StudentRdbmsShortPrimitiveTest extends RdbmsBase\n{\n\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentShortPrimitive studentMax = new StudentShortPrimitive();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentShortPrimitive studentMin = new StudentShortPrimitive();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Short) getMinValue(Short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentShortPrimitive student = new StudentShortPrimitive();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentShortPrimitive studentMax = em.find(StudentShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortPrimitive studentMin = em.find(StudentShortPrimitive.class, getMinValue(Short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortPrimitive student = em.find(StudentShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentShortPrimitive student = em.find(StudentShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortPrimitive newStudent = em.find(StudentShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMinValue(Short.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.id between \" + getMinValue(Short.class) + \" and \"\n                + getMaxValue(Short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Short) getMinValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentShortPrimitive studentMax = em.find(StudentShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentShortPrimitive.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentShortPrimitive s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortPrimitive newStudent = em.find(StudentShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentShortPrimitive s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortPrimitive newStudent = em.find(StudentShortPrimitive.class, getRandomValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.name = 'Kuldeep' and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortPrimitive> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortPrimitive s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentShortPrimitive s \";\n        Query q = em.createQuery(query);\n        List<StudentShortPrimitive> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentShortPrimitive student : students)\n        {\n            if (student.getId() == ((Short) getMaxValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId() == ((Short) getMinValue(Short.class)).shortValue())\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentShortPrimitive (id SMALLINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentShortPrimitive\");\n            cli.update(\"DROP TABLE TESTDB.StudentShortPrimitive\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentShortPrimitive (id SMALLINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentShortPrimitive\");\n            cli.update(\"DROP TABLE TESTDB.StudentShortPrimitive\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsShortWrapperTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentShortWrapper;\n\npublic class StudentRdbmsShortWrapperTest extends RdbmsBase\n{\n\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of Short\n        StudentShortWrapper studentMax = new StudentShortWrapper();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Short) getMaxValue(Short.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Short\n        StudentShortWrapper studentMin = new StudentShortWrapper();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Short) getMinValue(Short.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of Short\n        StudentShortWrapper student = new StudentShortWrapper();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Short) getRandomValue(Short.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentShortWrapper studentMax = em.find(StudentShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortWrapper studentMin = em.find(StudentShortWrapper.class, getMinValue(Short.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortWrapper student = em.find(StudentShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentShortWrapper student = em.find(StudentShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortWrapper newStudent = em.find(StudentShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            Assert.assertEquals(getMinValue(Short.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.id between \" + getMinValue(Short.class) + \" and \"\n                + getMaxValue(Short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Short.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            Assert.assertEquals(getMaxValue(Short.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentShortWrapper studentMax = em.find(StudentShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentShortWrapper.class, getMaxValue(Short.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentShortWrapper s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortWrapper newStudent = em.find(StudentShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentShortWrapper s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentShortWrapper newStudent = em.find(StudentShortWrapper.class, getRandomValue(Short.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.name = 'Kuldeep' and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            Assert.assertEquals(getRandomValue(Short.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentShortWrapper> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentShortWrapper s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Short.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentShortWrapper s \";\n        Query q = em.createQuery(query);\n        List<StudentShortWrapper> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentShortWrapper student : students)\n        {\n            if (student.getId().equals(getMaxValue(Short.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Short.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Short.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentShortWrapper (id SMALLINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentShortWrapper\");\n            cli.update(\"DROP TABLE TESTDB.StudentShortWrapper\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentShortWrapper (id SMALLINT PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentShortWrapper\");\n            cli.update(\"DROP TABLE TESTDB.StudentShortWrapper\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsSqlDateTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.Date;\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentSqlDate;\n\npublic class StudentRdbmsSqlDateTest extends RdbmsBase\n{\n    private static final Date DATE = new Date(System.currentTimeMillis());\n    \n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Date\n        StudentSqlDate student = new StudentSqlDate();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Date) getRandomValue());\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Date\n        StudentSqlDate studentMax = new StudentSqlDate();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Date) getMaxValue());\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Date\n        StudentSqlDate studentMin = new StudentSqlDate();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Date) getMinValue());\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    private Object getMinValue()\n    {\n        return new Date(1970, 1, 1);\n    }\n\n    private Object getRandomValue()\n    {\n        return DATE;\n    }\n\n    private Object getMaxValue()\n    {\n        return new Date(2100, 1, 1);\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentSqlDate studentMax = em.find(StudentSqlDate.class, getMaxValue());\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentSqlDate studentMin = em.find(StudentSqlDate.class, getMinValue());\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentSqlDate student = em.find(StudentSqlDate.class, getRandomValue());\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentSqlDate student = em.find(StudentSqlDate.class, getMaxValue());\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentSqlDate newStudent = em.find(StudentSqlDate.class, getMaxValue());\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            Assert.assertEquals(getMinValue(), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.id between \" + getMinValue() + \" and \" + getMaxValue();\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue()))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue()).getDate(), student.getId().getDate());\n                Assert.assertEquals(((Date) getRandomValue()).getYear(), student.getId().getYear());\n                Assert.assertEquals(((Date) getRandomValue()).getMonth(), student.getId().getMonth());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            Assert.assertEquals(((Date) getMaxValue()).getDate(), student.getId().getDate());\n            Assert.assertEquals(((Date) getMaxValue()).getYear(), student.getId().getYear());\n            Assert.assertEquals(((Date) getMaxValue()).getMonth(), student.getId().getMonth());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            Assert.assertEquals(((Date) getMaxValue()).getDate(), student.getId().getDate());\n            Assert.assertEquals(((Date) getMaxValue()).getYear(), student.getId().getYear());\n            Assert.assertEquals(((Date) getMaxValue()).getMonth(), student.getId().getMonth());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentSqlDate studentMax = em.find(StudentSqlDate.class, getMaxValue());\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentSqlDate.class, getMaxValue());\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentSqlDate s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentSqlDate newStudent = em.find(StudentSqlDate.class, getRandomValue());\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentSqlDate s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentSqlDate newStudent = em.find(StudentSqlDate.class, getRandomValue());\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.name = 'Amresh' and s.age between \" + getMinValue(short.class)\n                + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            Assert.assertEquals(((Date) getRandomValue()).getDate(), student.getId().getDate());\n            Assert.assertEquals(((Date) getRandomValue()).getYear(), student.getId().getYear());\n            Assert.assertEquals(((Date) getRandomValue()).getMonth(), student.getId().getMonth());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            Assert.assertEquals(((Date) getRandomValue()).getDate(), student.getId().getDate());\n            Assert.assertEquals(((Date) getRandomValue()).getYear(), student.getId().getYear());\n            Assert.assertEquals(((Date) getRandomValue()).getMonth(), student.getId().getMonth());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.name = 'Kuldeep' and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getMinValue()).getDate(), student.getId().getDate());\n                Assert.assertEquals(((Date) getMinValue()).getYear(), student.getId().getYear());\n                Assert.assertEquals(((Date) getMinValue()).getMonth(), student.getId().getMonth());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            Assert.assertEquals(((Date) getRandomValue()).getDate(), student.getId().getDate());\n            Assert.assertEquals(((Date) getRandomValue()).getYear(), student.getId().getYear());\n            Assert.assertEquals(((Date) getRandomValue()).getMonth(), student.getId().getMonth());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentSqlDate> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentSqlDate s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getMinValue()).getDate(), student.getId().getDate());\n                Assert.assertEquals(((Date) getMinValue()).getYear(), student.getId().getYear());\n                Assert.assertEquals(((Date) getMinValue()).getMonth(), student.getId().getMonth());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentSqlDate s \";\n        Query q = em.createQuery(query);\n        List<StudentSqlDate> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentSqlDate student : students)\n        {\n            if (student.getId().equals(getMaxValue()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue()))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Date) getRandomValue()).getDate(), student.getId().getDate());\n                Assert.assertEquals(((Date) getRandomValue()).getYear(), student.getId().getYear());\n                Assert.assertEquals(((Date) getRandomValue()).getMonth(), student.getId().getMonth());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentSqlDate (id DATE PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentSqlDate\");\n            cli.update(\"DROP TABLE TESTDB.StudentSqlDate\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentSqlDate (id DATE PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentSqlDate\");\n            cli.update(\"DROP TABLE TESTDB.StudentSqlDate\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsStringTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentString;\n\npublic class StudentRdbmsStringTest extends RdbmsBase\n{\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert max value of String\n        StudentString studentMax = new StudentString();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((String) getMaxValue(String.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of String\n        StudentString studentMin = new StudentString();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((String) getMinValue(String.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        // Insert random value of String\n        StudentString student = new StudentString();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((String) getRandomValue(String.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentString studentMax = em.find(StudentString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentString studentMin = em.find(StudentString.class, getMinValue(String.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentString student = em.find(StudentString.class, getRandomValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentString student = em.find(StudentString.class, getMaxValue(String.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentString newStudent = em.find(StudentString.class, getMaxValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            Assert.assertEquals(getMinValue(String.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.id between '\" + getMinValue(String.class) + \"' and '\"\n                + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        int count = 0;\n        for (StudentString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            Assert.assertEquals(getMaxValue(String.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentString studentMax = em.find(StudentString.class, getMaxValue(String.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentString.class, getMaxValue(String.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentString s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentString newStudent = em.find(StudentString.class, getRandomValue(String.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String updateQuery = \"Update StudentString s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(updateQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentString newStudent = em.find(StudentString.class, getRandomValue(String.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.name = 'Kuldeep' and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            Assert.assertEquals(getRandomValue(String.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentString> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentString s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(String.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentString s \";\n        Query q = em.createQuery(query);\n        List<StudentString> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentString student : students)\n        {\n            if (student.getId().equals(getMaxValue(String.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(String.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(String.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentString (STUDENT_ID VARCHAR(255) PRIMARY KEY, NAME VARCHAR(255), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentString\");\n            cli.update(\"DROP TABLE TESTDB.StudentString\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentString (STUDENT_ID VARCHAR(255) PRIMARY KEY, NAME VARCHAR(255), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentString\");\n            cli.update(\"DROP TABLE TESTDB.StudentString\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.RDBMSCli;\n\n/**\n * The Class StudentDaoTest.\n * \n * @author Vivek Mishra\n */\npublic class StudentRdbmsTest extends StudentBase<StudentRdbms>\n{\n    String persistenceUnit = \"testHibernate\";\n\n    private RDBMSCli cli;\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        cli = new RDBMSCli(\"testdb\");\n        cli.createSchema(\"testdb\");\n        // cli.update(\"USE testdb\");\n        cli.update(\"CREATE TABLE TESTDB.STUDENT (STUDENT_ID BIGINT PRIMARY KEY,UNIQUE_ID BIGINT, STUDENT_NAME VARCHAR(256), AGE SMALLINT,IS_EXCEPTIONAL BOOLEAN,SEMESTER VARCHAR(4),DIGITAL_SIGNATURE TINYINT,CGPA SMALLINT,\"\n                + \"PERCENTAGE DECIMAL(10,8),HEIGHT DECIMAL(11,8) ,ENROLMENT_DATE DATE,ENROLMENT_TIME TIME,JOINING_DATE_TIME TIMESTAMP,YEARS_SPENT INTEGER,ROLL_NUMBER BIGINT\"\n                + \",MONTHLY_FEE DOUBLE,SQL_DATE DATE,SQL_TIMESTAMP TIMESTAMP , SQL_TIME TIME,BIG_INT BIGINT,BIG_DECIMAL DECIMAL,CALENDAR TIMESTAMP)\");\n\n        setupInternal(persistenceUnit);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        teardownInternal(persistenceUnit);\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.STUDENT\");\n            cli.update(\"DROP TABLE TESTDB.STUDENT\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (SQLException e)\n        {\n            // do nothing..weird!!\n        }\n        // cli.dropSchema(\"TESTDB\");\n        \n    }\n\n    @SuppressWarnings(\"deprecation\")\n    @Test\n    public void executeTests()\n    {\n        onInsert();\n        // onMerge();\n    }\n\n    /**\n     * Test method for.\n     * \n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     *             {@link com.impetus.kundera.examples.student.StudentDao#saveStudent(com.impetus.kundera.examples.crud.datatype.entities.StudentRdbms)}\n     *             .\n     */\n\n    public void onInsert()\n    {\n        try\n        {\n            onInsert(new StudentRdbms());\n            em.clear();\n        }\n        catch (InstantiationException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n\n        // find by id.\n        StudentEntityDef s = em.find(StudentRdbms.class, studentId1);\n        assertOnDataTypes((StudentRdbms) s);\n        em.clear();\n\n        // // find by name.\n        assertFindByName(em, \"StudentRdbms\", StudentRdbms.class, \"Amresh\", \"studentName\");\n\n        // find by name and age.\n        assertFindByNameAndAge(em, \"StudentRdbms\", StudentRdbms.class, \"Amresh\", \"10\", \"studentName\");\n\n        // find by name, age clause\n        assertFindByNameAndAgeGTAndLT(em, \"StudentRdbms\", StudentRdbms.class, \"Amresh\", \"10\", \"20\", \"studentName\");\n        //\n        // // find by between clause\n        assertFindByNameAndAgeBetween(em, \"StudentRdbms\", StudentRdbms.class, \"Amresh\", \"10\", \"15\", \"studentName\");\n\n        // find by Range.\n        assertFindByRange(em, \"StudentRdbms\", StudentRdbms.class, \"12345677\", \"12345678\", \"studentId\");\n\n        // find by without where clause.\n        assertFindWithoutWhereClause(em, \"StudentRdbms\", StudentRdbms.class);\n    }\n\n    /**\n     * On merge.\n     */\n    public void onMerge()\n    {\n        em.persist(prepareData((Long) studentId1, 78575785897L, \"Amresh\", true, 10, 'C', (byte) 5, (short) 8,\n                (float) 69.6, 163.76765654, enrolmentDate, enrolmentTime, joiningDateAndTime, new Integer(3), new Long(\n                        978423946455l), 135434.89, newSqlDate, sqlTime, sqlTimestamp, bigDecimal, bigInteger, calendar,\n                new StudentRdbms()));\n        StudentRdbms s = em.find(StudentRdbms.class, studentId1);\n        Assert.assertNotNull(s);\n        Assert.assertEquals(\"Amresh\", s.getStudentName());\n        // modify record.\n        s.setStudentName(\"NewAmresh\");\n        em.merge(s);\n        // emf.close();\n        // assertOnMerge(em, \"StudentRdbms\", StudentRdbms.class, \"Amresh\",\n        // \"NewAmresh\",\"STUDENT_NAME\");\n    }\n\n    @Override\n    void startServer()\n    {\n    }\n\n    @Override\n    void stopServer()\n    {\n    }\n\n    @Override\n    void createSchema()\n    {\n    }\n\n    @Override\n    void deleteSchema()\n    {\n        em.remove(em.find(StudentRdbms.class, studentId1));\n        em.remove(em.find(StudentRdbms.class, studentId2));\n        em.remove(em.find(StudentRdbms.class, studentId3));\n    }\n\n}"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsTimeTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.sql.Time;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentTime;\n\npublic class StudentRdbmsTimeTest extends RdbmsBase\n{\n\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Time\n        StudentTime student = new StudentTime();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Time) getRandomValue(Time.class));\n        student.setName((String) getRandomValue(String.class));\n\n        // Insert max value of Time\n        StudentTime studentMax = new StudentTime();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Time) getMaxValue(Time.class));\n        studentMax.setName((String) getMaxValue(String.class));\n\n        // Insert min value of Time\n        StudentTime studentMin = new StudentTime();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Time) getMinValue(Time.class));\n        studentMin.setName((String) getMinValue(String.class));\n\n        em.persist(student);\n        em.persist(studentMax);\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentTime studentMax = em.find(StudentTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTime studentMin = em.find(StudentTime.class, getMinValue(Time.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTime student = em.find(StudentTime.class, getRandomValue(Time.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentTime student = em.find(StudentTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTime newStudent = em.find(StudentTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            Assert.assertEquals(getMinValue(Time.class).toString(), student.getId().toString());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.id between \" + getMinValue(Time.class) + \" and \"\n                + getMaxValue(Time.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentTime student : students)\n        {\n            if (student.getId().toString().equals(getMaxValue(Time.class).toString()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().toString().equals(getMinValue(Time.class).toString()))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Time.class).toString(), student.getId().toString());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            Assert.assertEquals(getMaxValue(Time.class).toString(), student.getId().toString());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.name = 'Kuldeep' and s.age > \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            Assert.assertEquals(getMaxValue(Time.class).toString(), student.getId().toString());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentTime studentMax = em.find(StudentTime.class, getMaxValue(Time.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentTime.class, getMaxValue(Time.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentTime s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTime newStudent = em.find(StudentTime.class, getRandomValue(Time.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String upTimeQuery = \"Update StudentTime s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(upTimeQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTime newStudent = em.find(StudentTime.class, getRandomValue(Time.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class).toString(), student.getId().toString());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.name = 'Amresh' and s.age > \" + getMinValue(short.class)\n                + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class).toString(), student.getId().toString());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.name = 'Kuldeep' and s.age >= \" + getMinValue(short.class)\n                + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            if (student.getId().toString().equals(getMaxValue(Time.class).toString()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Time.class).toString(), student.getId().toString());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            Assert.assertEquals(getRandomValue(Time.class).toString(), student.getId().toString());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTime> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTime s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentTime student : students)\n        {\n            if (student.getId().toString().equals(getMaxValue(Time.class).toString()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Time.class).toString(), student.getId().toString());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentTime s \";\n        Query q = em.createQuery(query);\n        List<StudentTime> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentTime student : students)\n        {\n            if (student.getId().toString().equals(getMaxValue(Time.class).toString()))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().toString().equals(getMinValue(Time.class).toString()))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Time) getRandomValue(Time.class)).toString(), student.getId().toString());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentTime (id TIME PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentTime\");\n            cli.update(\"DROP TABLE TESTDB.StudentTime\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentTime (id TIME PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentTime\");\n            cli.update(\"DROP TABLE TESTDB.StudentTime\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/StudentRdbmsTimestampTest.java",
    "content": "package com.impetus.client.crud.datatypes;\n\nimport java.sql.SQLException;\nimport java.sql.Timestamp;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.datatypes.entities.StudentTimestamp;\n\npublic class StudentRdbmsTimestampTest extends RdbmsBase\n{\n\n    \n\n    @Before\n    public void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void testExecuteUseSameEm()\n    {\n        testPersist(true);\n        testFindById(true);\n        testMerge(true);\n        testFindByQuery(true);\n        testNamedQueryUseSameEm(true);\n        testDelete(true);\n    }\n\n    @Test\n    public void testExecute()\n    {\n        testPersist(false);\n        testFindById(false);\n        testMerge(false);\n        testFindByQuery(false);\n        testNamedQuery(false);\n        testDelete(false);\n    }\n\n    public void testPersist(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Insert random value of Time\n        StudentTimestamp student = new StudentTimestamp();\n        student.setAge((Short) getRandomValue(short.class));\n        student.setId((Timestamp) getRandomValue(Timestamp.class));\n        student.setName((String) getRandomValue(String.class));\n        em.persist(student);\n\n        // Insert max value of Time\n        StudentTimestamp studentMax = new StudentTimestamp();\n        studentMax.setAge((Short) getMaxValue(short.class));\n        studentMax.setId((Timestamp) getMaxValue(Timestamp.class));\n        studentMax.setName((String) getMaxValue(String.class));\n        em.persist(studentMax);\n\n        // Insert min value of Timestamp\n        StudentTimestamp studentMin = new StudentTimestamp();\n        studentMin.setAge((Short) getMinValue(short.class));\n        studentMin.setId((Timestamp) getMinValue(Timestamp.class));\n        studentMin.setName((String) getMinValue(String.class));\n        em.persist(studentMin);\n\n        em.close();\n    }\n\n    public void testFindById(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentTimestamp studentMax = em.find(StudentTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(getMaxValue(String.class), studentMax.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTimestamp studentMin = em.find(StudentTimestamp.class, getMinValue(Timestamp.class));\n        Assert.assertNotNull(studentMin);\n        Assert.assertEquals(getMinValue(short.class), studentMin.getAge());\n        Assert.assertEquals(getMinValue(String.class), studentMin.getName());\n\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTimestamp student = em.find(StudentTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getRandomValue(short.class), student.getAge());\n        Assert.assertEquals(getRandomValue(String.class), student.getName());\n        em.close();\n    }\n\n    public void testMerge(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        StudentTimestamp student = em.find(StudentTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(student);\n        Assert.assertEquals(getMaxValue(short.class), student.getAge());\n        Assert.assertEquals(getMaxValue(String.class), student.getName());\n\n        student.setName(\"Kuldeep\");\n        em.merge(student);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTimestamp newStudent = em.find(StudentTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getMaxValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Kuldeep\", newStudent.getName());\n    }\n\n    public void testFindByQuery(boolean useSameEm)\n    {\n        findAllQuery();\n        findByName();\n        findByAge();\n        findByNameAndAgeGTAndLT();\n        findByNameAndAgeGTEQAndLTEQ();\n        findByNameAndAgeGTAndLTEQ();\n        findByNameAndAgeWithOrClause();\n        findByAgeAndNameGTAndLT();\n        findByNameAndAGEBetween();\n        // findByRange();\n    }\n\n    private void findByAgeAndNameGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.age = \" + getMinValue(short.class)\n                + \" and s.name > 'Amresh' and s.name <= '\" + getMaxValue(String.class)+\"'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMinValue(short.class), student.getAge());\n            Assert.assertEquals(getMinValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByRange()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.id between \" + getMinValue(Timestamp.class)\n                + \" and \" + getMaxValue(Timestamp.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeWithOrClause()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.name = 'Kuldeep' and s.age > \"\n                + getMinValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            Assert.assertEquals(getMaxValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLTEQ()\n    {\n\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.name = 'Kuldeep' and s.age > \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            Assert.assertEquals(getMaxValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getMaxValue(short.class), student.getAge());\n            Assert.assertEquals(\"Kuldeep\", student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    public void testNamedQueryUseSameEm(boolean useSameEm)\n    {\n        updateNamed(true);\n        deleteNamed(true);\n    }\n\n    public void testNamedQuery(boolean useSameEm)\n    {\n        updateNamed(false);\n        deleteNamed(false);\n    }\n\n    public void testDelete(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n\n        StudentTimestamp studentMax = em.find(StudentTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNotNull(studentMax);\n        Assert.assertEquals(getMaxValue(short.class), studentMax.getAge());\n        Assert.assertEquals(\"Kuldeep\", studentMax.getName());\n        em.remove(studentMax);\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        studentMax = em.find(StudentTimestamp.class, getMaxValue(Timestamp.class));\n        Assert.assertNull(studentMax);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void deleteNamed(boolean useSameEm)\n    {\n\n        String deleteQuery = \"Delete From StudentTimestamp s where s.name='Vivek'\";\n        EntityManager em = emf.createEntityManager();\n        Query q = em.createQuery(deleteQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTimestamp newStudent = em\n                .find(StudentTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNull(newStudent);\n        em.close();\n    }\n\n    /**\n     * @return\n     */\n\n    private void updateNamed(boolean useSameEm)\n    {\n        EntityManager em = emf.createEntityManager();\n        String upTimeQuery = \"Update StudentTimestamp s SET s.name='Vivek' where s.name='Amresh'\";\n        Query q = em.createQuery(upTimeQuery);\n        q.executeUpdate();\n        if (!useSameEm)\n        {\n            em.close();\n            em = emf.createEntityManager();\n        }\n        StudentTimestamp newStudent = em\n                .find(StudentTimestamp.class, getRandomValue(Timestamp.class));\n        Assert.assertNotNull(newStudent);\n        Assert.assertEquals(getRandomValue(short.class), newStudent.getAge());\n        Assert.assertEquals(\"Vivek\", newStudent.getName());\n        em.close();\n    }\n\n    private void findByNameAndAGEBetween()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.name = 'Amresh' and s.age between \"\n                + getMinValue(short.class) + \" and \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    private void findByNameAndAgeGTAndLT()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.name = 'Amresh' and s.age > \"\n                + getMinValue(short.class) + \" and s.age < \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n\n    }\n\n    private void findByNameAndAgeGTEQAndLTEQ()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.name = 'Kuldeep' and s.age >= \"\n                + getMinValue(short.class) + \" and s.age <= \" + getMaxValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n\n    }\n\n    private void findByAge()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.age = \" + getRandomValue(short.class);\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(1, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            Assert.assertEquals(getRandomValue(Timestamp.class), student.getId());\n            Assert.assertEquals(getRandomValue(short.class), student.getAge());\n            Assert.assertEquals(getRandomValue(String.class), student.getName());\n            count++;\n        }\n        Assert.assertEquals(1, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findByName()\n    {\n        EntityManager em;\n        String query;\n        Query q;\n        List<StudentTimestamp> students;\n        int count;\n        em = emf.createEntityManager();\n        query = \"Select s From StudentTimestamp s where s.name = 'Kuldeep'\";\n        q = em.createQuery(query);\n        students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(2, students.size());\n        count = 0;\n        for (StudentTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(getMinValue(Timestamp.class), student.getId());\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(2, count);\n        em.close();\n    }\n\n    /**\n     * \n     */\n    private void findAllQuery()\n    {\n        EntityManager em = emf.createEntityManager();\n        // Selet all query.\n        String query = \"Select s From StudentTimestamp s \";\n        Query q = em.createQuery(query);\n        List<StudentTimestamp> students = q.getResultList();\n        Assert.assertNotNull(students);\n        Assert.assertEquals(3, students.size());\n        int count = 0;\n        for (StudentTimestamp student : students)\n        {\n            if (student.getId().equals(getMaxValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMaxValue(short.class), student.getAge());\n                Assert.assertEquals(\"Kuldeep\", student.getName());\n                count++;\n            }\n            else if (student.getId().equals(getMinValue(Timestamp.class)))\n            {\n                Assert.assertEquals(getMinValue(short.class), student.getAge());\n                Assert.assertEquals(getMinValue(String.class), student.getName());\n                count++;\n            }\n            else\n            {\n                Assert.assertEquals(((Timestamp) getRandomValue(Timestamp.class)).getTime(), student.getId().getTime());\n                Assert.assertEquals(getRandomValue(short.class), student.getAge());\n                Assert.assertEquals(getRandomValue(String.class), student.getName());\n                count++;\n            }\n        }\n        Assert.assertEquals(3, count);\n        em.close();\n    }\n\n    public void startCluster()\n    {\n    \t\n    }\n\n    public void stopCluster()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    public void createSchema() throws SQLException\n    {\n        try\n        {\n            cli.createSchema(\"testdb\");\n            cli.update(\"CREATE TABLE TESTDB.StudentTimestamp (id TIMESTAMP PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentTimestamp\");\n            cli.update(\"DROP TABLE TESTDB.StudentTimestamp\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.update(\"CREATE TABLE TESTDB.StudentTimestamp (id TIMESTAMP PRIMARY KEY, NAME VARCHAR(256), AGE SMALLINT)\");\n        }\n    }\n\n    public void dropSchema()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.StudentTimestamp\");\n            cli.update(\"DROP TABLE TESTDB.StudentTimestamp\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (Exception e)\n        {\n            // Nothing to do\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentBigDecimal.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.math.BigDecimal;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentBigDecimal\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentBigDecimal\n{\n\n    @Id\n    @Column(name = \"STUDENT_ID\")\n    private BigDecimal studentId;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public BigDecimal getStudentId()\n    {\n        return studentId;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setStudentId(BigDecimal studentId)\n    {\n        this.studentId = studentId;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentBigInteger.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.math.BigInteger;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentBigInteger\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentBigInteger {\n\n\t@Id\n\tprivate BigInteger id;\n\n\t@Column(name = \"AGE\")\n\tprivate short age;\n\n\t@Column(name = \"NAME\")\n\tprivate String name;\n\n\t/**\n\t * @return the id\n\t */\n\tpublic BigInteger getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * @param id\n\t *            the id to set\n\t */\n\tpublic void setId(BigInteger id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * @return the age\n\t */\n\tpublic short getAge() {\n\t\treturn age;\n\t}\n\n\t/**\n\t * @param age\n\t *            the age to set\n\t */\n\tpublic void setAge(short age) {\n\t\tthis.age = age;\n\t}\n\n\t/**\n\t * @return the name\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * @param name\n\t *            the name to set\n\t */\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentBooleanPrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentBooleanPrimitive\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentBooleanPrimitive\n{\n    @Id\n    private boolean id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public boolean getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(boolean id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentBooleanWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentBooleanWrapper\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentBooleanWrapper\n{\n    @Id\n    private Boolean id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Boolean getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Boolean id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentBytePrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentBytePrimitive\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentBytePrimitive\n{\n\n    @Id\n    private byte id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentByteWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentByteWrapper\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentByteWrapper\n{\n\n    @Id\n    private Byte id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Byte getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Byte id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentCalendar.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.util.Calendar;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentCalendar\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentCalendar\n{\n\n    @Id\n    private Calendar id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Calendar getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Calendar id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentChar.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentChar\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentChar\n{\n\n    @Id\n    private char id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public char getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(char id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentCharacter.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentCharacter\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentCharacter\n{\n    @Id\n    private Character id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Character getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Character id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentDate.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentDate\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentDate\n{\n\n    @Id\n//    @Temporal(TemporalType.DATE)\n    private Date id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentDoublePrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentDoublePrimitive\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentDoublePrimitive\n{\n\n    @Id\n    private double id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public double getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentDoubleWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentDoubleWrapper\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentDoubleWrapper\n{\n\n    @Id\n    private Double id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Double getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Double id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentFloatPrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentFloatPrimitive\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentFloatPrimitive\n{\n    @Id\n    private float id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public float getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentFloatWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentFloatWrapper\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentFloatWrapper\n{\n\n    @Id\n    private Float id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Float getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Float id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentInt.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentInt\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentInt\n{\n\n    @Id\n    private int id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentInteger.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentInteger\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentInteger\n{\n    @Id\n    private Integer id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Integer getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Integer id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentLongPrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentLongPrimitive\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentLongPrimitive\n{\n\n    @Id\n    private long id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public long getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentLongWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentLongWrapper\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentLongWrapper\n{\n\n    @Id\n    private Long id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Long getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Long id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentShortPrimitive.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentShortPrimitive\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentShortPrimitive\n{\n\n    @Id\n    private short id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public short getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentShortWrapper.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentShortWrapper\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentShortWrapper\n{\n\n    @Id\n    private Short id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Short getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Short id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentSqlDate.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.sql.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentSqlDate\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentSqlDate\n{\n\n    @Id\n    private Date id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Date getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Date id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentString.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentString\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentString\n{\n\n    @Id\n    @Column(name = \"STUDENT_ID\")\n    private String id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentTime.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.sql.Time;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentTime\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentTime\n{\n\n    @Id\n    private Time id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Time getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Time id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentTimestamp.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.sql.Timestamp;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentTimestamp\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentTimestamp\n{\n\n    @Id\n    private Timestamp id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public Timestamp getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(Timestamp id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/datatypes/entities/StudentUUID.java",
    "content": "package com.impetus.client.crud.datatypes.entities;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"StudentUUID\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"age\"), @Index(name = \"name\") })\npublic class StudentUUID\n{\n\n    @Id\n    private UUID id;\n\n    @Column(name = \"AGE\")\n    private short age;\n\n    @Column(name = \"NAME\")\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public UUID getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(UUID id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the age\n     */\n    public short getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(short age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/AddressRDBMSMTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressRDBMSMTM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/AddressRDBMSMTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressRDBMSMTO\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/AddressRDBMSOTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressRDBMSOTM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/AddressRDBMSOTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"ADDRESS\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressRDBMSOTO\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/PersonEagerRDBMSMTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSONNEL\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonEagerRDBMSMTM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @JoinTable(name = \"PERSONNEL_ADDRESS\", schema = \"KunderaTests\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Set<AddressRDBMSMTM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressRDBMSMTM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressRDBMSMTM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/PersonEagerRDBMSMTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSONNEL\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonEagerRDBMSMTO\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressRDBMSMTO address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressRDBMSMTO getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressRDBMSMTO address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/PersonEagerRDBMSOTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSONNEL\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonEagerRDBMSOTM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<AddressRDBMSOTM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressRDBMSOTM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressRDBMSOTM> addresses)\n    {\n        this.addresses = addresses;\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/PersonEagerRDBMSOTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSONNEL\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonEagerRDBMSOTO\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressRDBMSOTO address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressRDBMSOTO getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressRDBMSOTO address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/PersonLazyRDBMSMTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSONNEL\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonLazyRDBMSMTM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"PERSONNEL_ADDRESS\", schema = \"testdb\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Set<AddressRDBMSMTM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressRDBMSMTM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressRDBMSMTM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/PersonLazyRDBMSMTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSONNEL\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonLazyRDBMSMTO\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressRDBMSMTO address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressRDBMSMTO getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressRDBMSMTO address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/PersonLazyRDBMSOTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSONNEL\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonLazyRDBMSOTM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<AddressRDBMSOTM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<AddressRDBMSOTM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<AddressRDBMSOTM> addresses)\n    {\n        this.addresses = addresses;\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/PersonLazyRDBMSOTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PERSONNEL\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonLazyRDBMSOTO\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressRDBMSOTO address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public AddressRDBMSOTO getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressRDBMSOTO address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/PersonRDBMS.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n// TODO: Auto-generated Javadoc\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON\", schema = \"TESTDB\")\n@IndexCollection(columns = { @Index(name = \"personName\"),@Index(name = \"age\") })\npublic class PersonRDBMS\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/RDBMSToken.java",
    "content": "package com.impetus.client.crud.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"TOKENS\", schema = \"TESTDB\")\npublic class RDBMSToken\n{\n    @Id\n    @Column(name = \"TOKEN_ID\")\n    private String tokenId;\n\n    @Column(name = \"TOKEN_NAME\")\n    private String tokenName;\n\n    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"client_id\")\n    private RDBMSTokenClient client;\n\n    public String getId()\n    {\n        return tokenId;\n    }\n\n    public void setId(String id)\n    {\n        this.tokenId = id;\n    }\n\n    public RDBMSTokenClient getClient()\n    {\n        return client;\n    }\n\n    public void setClient(RDBMSTokenClient client)\n    {\n        this.client = client;\n    }\n\n    public String getTokenName()\n    {\n        return tokenName;\n    }\n\n    public void setTokenName(String tokenName)\n    {\n        this.tokenName = tokenName;\n    }\n\n}"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/entities/RDBMSTokenClient.java",
    "content": "package com.impetus.client.crud.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"CLIENT\", schema = \"TESTDB\")\npublic class RDBMSTokenClient\n{\n\n    @Id\n    @Column(name = \"CLIENT_ID\")\n    private String clientId;\n\n    @Column(name = \"CLIENT_NAME\")\n    private String clientName;\n\n//    @OneToMany(mappedBy = \"client\", fetch = FetchType.LAZY)\n//    private Set<RDBMSToken> tokens;\n\n    public String getId()\n    {\n        return clientId;\n    }\n\n    public void setId(String id)\n    {\n        this.clientId = id;\n    }\n\n    public String getClientName()\n    {\n        return clientName;\n    }\n\n    public void setClientName(String clientName)\n    {\n        this.clientName = clientName;\n    }\n\n//    public Set<RDBMSToken> getTokens()\n//    {\n//        return tokens;\n//    }\n//\n//    public void setTokens(Set<RDBMSToken> tokens)\n//    {\n//        this.tokens = tokens;\n//    }\n}"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/generatedId/AddressGeneratedId.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.generatedId;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"AddressGeneratedId\", schema = \"testdb\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressGeneratedId\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    @GeneratedValue()\n    private int addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public int getAddressId()\n    {\n        return addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public void setAddressId(int addressId)\n    {\n        this.addressId = addressId;\n    }\n    \n}"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/generatedId/GeneratedIdTest.java",
    "content": "/**\n * \n */\npackage com.impetus.client.crud.generatedId;\n\nimport java.sql.SQLException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.RDBMSCli;\n\n/**\n * @author impadmin\n * \n */\npublic class GeneratedIdTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private RDBMSCli cli;\n\n    /**\n     * \n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        createTables();\n        emf = Persistence.createEntityManagerFactory(\"testHibernate\");\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        cli.update(\"DELETE FROM TESTDB.UserGeneratedId\");\n        cli.update(\"DROP TABLE TESTDB.UserGeneratedId\");\n        cli.update(\"DELETE FROM TESTDB.AddressGeneratedId\");\n        cli.update(\"DROP TABLE TESTDB.AddressGeneratedId\");\n        cli.dropSchema(\"TESTDB\");\n        em.close();\n        emf.close();\n        \n        try\n        {\n            cli.update(\"DELETE FROM TESTDB.USERGENERATEDID\");\n            cli.update(\"DROP TABLE TESTDB.USERGENERATEDID\");\n            cli.update(\"DELETE FROM TESTDB.ADDRESSGENERATEDID\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESSGENERATEDID\");\n            cli.update(\"DROP SCHEMA TESTDB\");\n            cli.closeConnection();\n        }\n        catch (SQLException e)\n        {\n            // do nothing..weird!!\n        }\n    }\n\n    @Test\n    public void test()\n    {\n        AddressGeneratedId address = new AddressGeneratedId();\n        address.setStreet(\"sector 20, G Block\");\n        // address.setAddressId(99);\n\n        UserGeneratedId user = new UserGeneratedId();\n        // user.setPersonId(17);\n        user.setAddress(address);\n        user.setPersonName(\"Kuldeep\");\n\n        em.persist(user);\n\n        em.clear();\n\n        List<UserGeneratedId> result = em.createQuery(\"Select u from UserGeneratedId u\").getResultList();\n        Assert.assertNotNull(result);\n        Assert.assertEquals(1, result.size());\n        Assert.assertNotNull(result.get(0).getAddress());\n        Assert.assertEquals(\"sector 20, G Block\", result.get(0).getAddress().getStreet());\n        Assert.assertEquals(\"Kuldeep\", result.get(0).getPersonName());\n    }\n\n    private void createTables() throws SQLException\n    {\n\n        try\n        {\n            cli = new RDBMSCli(\"testdb\");\n            cli.createSchema(\"testdb\");\n        }\n        catch (Exception e)\n        {\n\n        }\n        try\n        {\n            cli.update(\"CREATE SEQUENCE HIBERNATE_SEQUENCE START WITH 1 INCREMENT BY 1\");\n            cli.update(\"CREATE TABLE TESTDB.USERGENERATEDID (PERSON_ID INT GENERATED BY DEFAULT AS IDENTITY (START WITH 1), PERSON_NAME VARCHAR(256), ADDRESS_ID INTEGER)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.USERGENERATEDID\");\n            cli.update(\"DROP TABLE TESTDB.USERGENERATEDID\");\n            cli.update(\"CREATE TABLE TESTDB.USERGENERATEDID (PERSON_ID INT  GENERATED BY DEFAULT AS IDENTITY (START WITH 1), PERSON_NAME VARCHAR(256), ADDRESS_ID INTEGER)\");\n        }\n        try\n        {\n            cli.update(\"CREATE TABLE TESTDB.ADDRESSGENERATEDID (ADDRESS_ID INTEGER  GENERATED BY DEFAULT AS IDENTITY (START WITH 1), STREET VARCHAR(256))\");\n\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM TESTDB.ADDRESSGENERATEDID\");\n            cli.update(\"DROP TABLE TESTDB.ADDRESSGENERATEDID\");\n            cli.update(\"CREATE TABLE TESTDB.ADDRESSGENERATEDID (ADDRESS_ID INTEGER  GENERATED BY DEFAULT AS IDENTITY (START WITH 1), STREET VARCHAR(256))\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/generatedId/UserGeneratedId.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.generatedId;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"UserGeneratedId\", schema = \"testdb\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class UserGeneratedId\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    @GeneratedValue()\n    private int personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressGeneratedId address;\n\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public AddressGeneratedId getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressGeneratedId address)\n    {\n        this.address = address;\n    }\n\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/crud/mappedsuperclass/inheritence/RdbmsEntityWithoutFieldsTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.crud.mappedsuperclass.inheritence;\n\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.mappedsuperclass.EntityWithoutFieldsBase;\n\n/**\n * @author amitkumar\n *\n *\tClass to verify that at least one field in entity class is not mandatory if the \n *\tsuperclass contains all the mandatory fields\n */\npublic class RdbmsEntityWithoutFieldsTest extends EntityWithoutFieldsBase\n{\n\n\t@Before\n\tpublic void setup()\n\t{\n\t\tpersistenceUnit = \"RdbmsMappedSUTest\";\n\t\tsetupInternal();\n\t}\n\t\n\t@Test\n\tpublic void testEntityWithNoFields()\n\t{\n\t\ttestEntityWithNoFieldsBase();\n\t}\n\t\n\t@Test\n\tpublic void testEntityWithNoFields2LevelInheritance()\n\t{\n\t\ttestEntityWithNoFields2LevelInheritanceBase();\n\t}\n\n\t@After\n\tpublic void tearDown()\n\t{\n\t\ttearDownInternal();\n\t}\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/twitter/TweetRDBMSTest.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter;\r\n\r\nimport org.junit.Test;\r\n\r\nimport com.impetus.client.twitter.dao.Twitter;\r\n\r\n/**\r\n * Test case for MongoDB.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class TweetRDBMSTest extends TwitterTestBaseRDBMS\r\n{\r\n\r\n    /** The user id1. */\r\n    String userId1;\r\n\r\n    /** The user id2. */\r\n    String userId2;\r\n\r\n    /** The twitter. */\r\n    Twitter twitter;\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see junit.framework.TestCase#setUp()\r\n     */\r\n    @Override\r\n    protected void setUp() throws Exception\r\n    {\r\n        setUpInternal(\"testHibernate\");\r\n    }\r\n\r\n    /**\r\n     * Test on execute.\r\n     */\r\n\r\n    @Test\r\n    public void testOnExecute()\r\n    {\r\n//        executeTestSuite();\r\n    }\r\n\r\n    @Override\r\n    protected void tearDown() throws Exception\r\n    {\r\n        tearDownInternal();\r\n    }\r\n\r\n    @Override\r\n    void createSchema()\r\n    {\r\n        // No need to create schema, it will be created automatically\r\n    }\r\n\r\n    @Override\r\n    void startServer()\r\n    {\r\n        // Currently no embedded server\r\n    }\r\n\r\n    @Override\r\n    void stopServer()\r\n    {\r\n        // Currently no embedded server\r\n    }\r\n\r\n    @Override\r\n    void deleteSchema()\r\n    {\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/twitter/TwitterTestBaseRDBMS.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter;\r\n\r\nimport java.util.List;\r\n\r\nimport junit.framework.TestCase;\r\n\r\nimport org.junit.Assert;\r\n\r\nimport com.impetus.client.twitter.dao.Twitter;\r\nimport com.impetus.client.twitter.dao.TwitterService;\r\nimport com.impetus.client.twitter.entities.ExternalLinkRDBMS;\r\nimport com.impetus.client.twitter.entities.PersonalDetailRDBMS;\r\nimport com.impetus.client.twitter.entities.PreferenceRDBMS;\r\nimport com.impetus.client.twitter.entities.TweetRDBMS;\r\nimport com.impetus.client.twitter.entities.UserRDBMS;\r\n\r\n/**\r\n * Test case for MongoDB.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic abstract class TwitterTestBaseRDBMS extends TestCase\r\n{\r\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\r\n\r\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\r\n\r\n    /** The user id1. */\r\n    String userId1;\r\n\r\n    /** The user id2. */\r\n    String userId2;\r\n\r\n    /** The twitter. */\r\n    protected Twitter twitter;\r\n\r\n    /**\r\n     * Sets the up internal.\r\n     * \r\n     * @param persistenceUnitName\r\n     *            the new up internal\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    protected void setUpInternal(String persistenceUnitName) throws Exception\r\n    {\r\n        userId1 = \"0001\";\r\n        userId2 = \"0002\";\r\n\r\n        // Start Cassandra Server\r\n        if (RUN_IN_EMBEDDED_MODE)\r\n        {\r\n            startServer();\r\n        }\r\n\r\n        twitter = new TwitterService(persistenceUnitName);\r\n\r\n        // Create Schema\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            createSchema();\r\n        }\r\n    }\r\n\r\n    /*\r\n     * (non-Javadoc)\r\n     * \r\n     * @see junit.framework.TestCase#tearDown()\r\n     */\r\n    /**\r\n     * Tear down internal.\r\n     * \r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    protected void tearDownInternal() throws Exception\r\n    {\r\n        if (twitter != null)\r\n        {\r\n            twitter.close();\r\n        }\r\n\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            deleteSchema();\r\n        }\r\n\r\n        // Stop Server\r\n        if (RUN_IN_EMBEDDED_MODE)\r\n        {\r\n            stopServer();\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Execute suite.\r\n     */\r\n    protected void executeTestSuite()\r\n    {\r\n        // Insert, Find and Update\r\n        addAllUserInfo();\r\n        getUserById();\r\n        updateUser();\r\n\r\n        // Queries\r\n        getAllUsers();\r\n        getAllTweets();\r\n\r\n        // Remove Users\r\n        removeUser();\r\n\r\n    }\r\n\r\n    protected void addAllUserInfo()\r\n    {\r\n        UserRDBMS user1 = buildUser1();\r\n        UserRDBMS user2 = buildUser2();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addUser(user1);\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addUser(user2);\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    protected void getUserById()\r\n    {\r\n        twitter.createEntityManager();\r\n        UserRDBMS user1 = twitter.findUserById(userId1);\r\n        assertUser1(user1);\r\n\r\n        UserRDBMS user2 = twitter.findUserById(userId2);\r\n        assertUser2(user2);\r\n\r\n    }\r\n\r\n    protected void updateUser()\r\n    {\r\n        twitter.createEntityManager();\r\n        UserRDBMS user1 = twitter.findUserById(userId1);\r\n        assertUser1(user1);\r\n\r\n        user1.setPersonalDetail(new PersonalDetailRDBMS(\"Vivek\", \"unknown\", \"Married\"));\r\n        user1.addTweet(new TweetRDBMS(\"My Third Tweet\", \"iPhone\"));\r\n        twitter.mergeUser(user1);\r\n\r\n        UserRDBMS user1AfterMerge = twitter.findUserById(userId1);\r\n\r\n        assertUpdatedUser1(user1AfterMerge);\r\n\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    protected void removeUser()\r\n    {\r\n        twitter.createEntityManager();\r\n        UserRDBMS user1 = twitter.findUserById(userId1);\r\n        // TODO: this needs to uncomment only after fixing update issue on\r\n        // associations\r\n        // assertUpdatedUser1(user1);\r\n\r\n        twitter.removeUser(user1);\r\n\r\n        UserRDBMS user1AfterRemoval = twitter.findUserById(userId1);\r\n        Assert.assertNull(user1AfterRemoval);\r\n\r\n        UserRDBMS user2 = twitter.findUserById(userId2);\r\n        // TODO: this needs to uncomment only after fixing update issue on\r\n        // associations\r\n        // assertUpdatedUser1(user1);\r\n\r\n        twitter.removeUser(user2);\r\n\r\n        UserRDBMS user2AfterRemoval = twitter.findUserById(userId2);\r\n        Assert.assertNull(user2AfterRemoval);\r\n\r\n        twitter.closeEntityManager();\r\n\r\n    }\r\n\r\n    protected void getAllUsers()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<UserRDBMS> users = twitter.getAllUsers();\r\n        Assert.assertNotNull(users);\r\n        Assert.assertFalse(users.isEmpty());\r\n        Assert.assertEquals(2, users.size());\r\n\r\n        for (UserRDBMS u : users)\r\n        {\r\n            Assert.assertNotNull(u);\r\n            if (u.getUserId().equals(userId1))\r\n            {\r\n                // TODO: this needs to uncomment only after fixing update issue\r\n                // on associations\r\n                // assertUpdatedUser1(u);\r\n            }\r\n            else if (u.getUserId().equals(userId2))\r\n            {\r\n                // assertUser2(u);\r\n            }\r\n        }\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Adds the users.\r\n     */\r\n    protected void addUsers()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addUser(userId1, \"Amresh\", \"password1\", \"married\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addUser(userId2, \"Saurabh\", \"password2\", \"single\");\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Save preference.\r\n     */\r\n    protected void savePreference()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.savePreference(userId1, new PreferenceRDBMS(\"P1\", \"Motif\", \"2\"));\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.savePreference(userId2, new PreferenceRDBMS(\"P2\", \"High Contrast\", \"3\"));\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Adds the external links.\r\n     */\r\n    protected void addExternalLinks()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId1, \"L1\", \"Facebook\", \"http://facebook.com/coolnerd\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId1, \"L2\", \"LinkedIn\", \"http://linkedin.com/in/devilmate\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId2, \"L3\", \"GooglePlus\", \"http://plus.google.com/inviteme\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addExternalLink(userId2, \"L4\", \"Yahoo\", \"http://yahoo.com/profiles/itsmeamry\");\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Adds the tweets.\r\n     */\r\n    protected void addTweets()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId1, \"Here is my first tweet\", \"Web\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId1, \"Second Tweet from me\", \"Mobile\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId2, \"Saurabh tweets for the first time\", \"Phone\");\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        twitter.addTweet(userId2, \"Another tweet from Saurabh\", \"text\");\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * User1 follows user2.\r\n     */\r\n    protected void user1FollowsUser2()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.startFollowing(userId1, userId2);\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * User1 adds user2 as follower.\r\n     */\r\n    protected void user1AddsUser2AsFollower()\r\n    {\r\n        twitter.createEntityManager();\r\n        twitter.addFollower(userId1, userId2);\r\n        twitter.closeEntityManager();\r\n    }\r\n\r\n    /**\r\n     * Gets the all tweets.\r\n     * \r\n     * @return the all tweets\r\n     */\r\n    protected void getAllTweets()\r\n    {\r\n        twitter.createEntityManager();\r\n\r\n        List<TweetRDBMS> tweetsUser1 = twitter.getAllTweets(userId1);\r\n        List<TweetRDBMS> tweetsUser2 = twitter.getAllTweets(userId2);\r\n\r\n        twitter.closeEntityManager();\r\n\r\n        assertNotNull(tweetsUser1);\r\n        assertNotNull(tweetsUser2);\r\n\r\n        assertFalse(tweetsUser1.isEmpty());\r\n        assertFalse(tweetsUser2.isEmpty());\r\n\r\n        // TODO : uncomment\r\n        assertEquals(3, tweetsUser1.size());\r\n        // assertEquals(2, tweetsUser1.size());\r\n        assertEquals(2, tweetsUser2.size());\r\n    }\r\n\r\n    /**\r\n     * Gets the tweets by body.\r\n     * \r\n     * @return the tweets by body\r\n     */\r\n    public void getTweetsByBody()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<TweetRDBMS> user1Tweet = twitter.findTweetByBody(\"Here\");\r\n        List<TweetRDBMS> user2Tweet = twitter.findTweetByBody(\"Saurabh\");\r\n\r\n        twitter.closeEntityManager();\r\n\r\n        assertNotNull(user1Tweet);\r\n        assertNotNull(user2Tweet);\r\n        assertEquals(1, user1Tweet.size());\r\n        assertEquals(1, user2Tweet.size());\r\n    }\r\n\r\n    /**\r\n     * Gets the tweet by device.\r\n     * \r\n     * @return the tweet by device\r\n     */\r\n    public void getTweetsByDevice()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<TweetRDBMS> webTweets = twitter.findTweetByDevice(\"Web\");\r\n        List<TweetRDBMS> mobileTweets = twitter.findTweetByDevice(\"Mobile\");\r\n\r\n        twitter.closeEntityManager();\r\n\r\n        assertNotNull(webTweets);\r\n        assertNotNull(mobileTweets);\r\n        assertEquals(1, webTweets.size());\r\n        assertEquals(1, mobileTweets.size());\r\n\r\n    }\r\n\r\n    /**\r\n     * Gets the all followers.\r\n     * \r\n     * @return the all followers\r\n     */\r\n    protected void getAllFollowers()\r\n    {\r\n        twitter.createEntityManager();\r\n        List<UserRDBMS> follower1 = twitter.getFollowers(userId1);\r\n        twitter.closeEntityManager();\r\n\r\n        twitter.createEntityManager();\r\n        List<UserRDBMS> follower2 = twitter.getFollowers(userId2);\r\n        twitter.closeEntityManager();\r\n\r\n        assertNull(follower1);\r\n        assertNotNull(follower2);\r\n    }\r\n\r\n    /**\r\n     * @return\r\n     */\r\n    private UserRDBMS buildUser1()\r\n    {\r\n        UserRDBMS user1 = new UserRDBMS(userId1, \"Amresh\", \"password1\", \"married\");\r\n\r\n        user1.setPreference(new PreferenceRDBMS(\"P1\", \"Motif\", \"2\"));\r\n\r\n        user1.addExternalLink(new ExternalLinkRDBMS(\"L1\", \"Facebook\", \"http://facebook.com/coolnerd\"));\r\n        user1.addExternalLink(new ExternalLinkRDBMS(\"L2\", \"LinkedIn\", \"http://linkedin.com/in/devilmate\"));\r\n\r\n        user1.addTweet(new TweetRDBMS(\"Here is my first tweet\", \"Web\"));\r\n        user1.addTweet(new TweetRDBMS(\"Second Tweet from me\", \"Mobile\"));\r\n        return user1;\r\n    }\r\n\r\n    /**\r\n     * @return\r\n     */\r\n    private UserRDBMS buildUser2()\r\n    {\r\n        UserRDBMS user2 = new UserRDBMS(userId2, \"Saurabh\", \"password2\", \"single\");\r\n\r\n        user2.setPreference(new PreferenceRDBMS(\"P2\", \"High Contrast\", \"3\"));\r\n\r\n        user2.addExternalLink(new ExternalLinkRDBMS(\"L3\", \"GooglePlus\", \"http://plus.google.com/inviteme\"));\r\n        user2.addExternalLink(new ExternalLinkRDBMS(\"L4\", \"Yahoo\", \"http://yahoo.com/profiles/itsmeamry\"));\r\n\r\n        user2.addTweet(new TweetRDBMS(\"Saurabh tweets for the first time\", \"Phone\"));\r\n        user2.addTweet(new TweetRDBMS(\"Another tweet from Saurabh\", \"text\"));\r\n        return user2;\r\n    }\r\n\r\n    private void assertUser1(UserRDBMS user1)\r\n    {\r\n        Assert.assertNotNull(user1);\r\n        Assert.assertEquals(userId1, user1.getUserId());\r\n        Assert.assertNotNull(user1.getPersonalDetail());\r\n        Assert.assertEquals(\"Amresh\", user1.getPersonalDetail().getName());\r\n        Assert.assertNotNull(user1.getPreference());\r\n        Assert.assertEquals(\"2\", user1.getPreference().getPrivacyLevel());\r\n        Assert.assertNotNull(user1.getTweets());\r\n        Assert.assertFalse(user1.getTweets().isEmpty());\r\n        Assert.assertEquals(2, user1.getTweets().size());\r\n        Assert.assertNotNull(user1.getExternalLinks());\r\n        Assert.assertFalse(user1.getExternalLinks().isEmpty());\r\n        Assert.assertEquals(2, user1.getExternalLinks().size());\r\n    }\r\n\r\n    private void assertUser2(UserRDBMS user2)\r\n    {\r\n        Assert.assertNotNull(user2);\r\n        Assert.assertEquals(userId2, user2.getUserId());\r\n        Assert.assertNotNull(user2.getPersonalDetail());\r\n        Assert.assertEquals(\"Saurabh\", user2.getPersonalDetail().getName());\r\n        Assert.assertNotNull(user2.getPreference());\r\n        Assert.assertEquals(\"3\", user2.getPreference().getPrivacyLevel());\r\n        Assert.assertNotNull(user2.getTweets());\r\n        Assert.assertFalse(user2.getTweets().isEmpty());\r\n        Assert.assertEquals(2, user2.getTweets().size());\r\n        Assert.assertNotNull(user2.getExternalLinks());\r\n        Assert.assertFalse(user2.getExternalLinks().isEmpty());\r\n        Assert.assertEquals(2, user2.getExternalLinks().size());\r\n    }\r\n\r\n    private void assertUpdatedUser1(UserRDBMS user1)\r\n    {\r\n        Assert.assertNotNull(user1);\r\n        Assert.assertEquals(userId1, user1.getUserId());\r\n        Assert.assertNotNull(user1.getPersonalDetail());\r\n        Assert.assertEquals(\"Vivek\", user1.getPersonalDetail().getName());\r\n        Assert.assertEquals(\"unknown\", user1.getPersonalDetail().getPassword());\r\n        Assert.assertNotNull(user1.getPreference());\r\n        Assert.assertEquals(\"2\", user1.getPreference().getPrivacyLevel());\r\n        Assert.assertNotNull(user1.getTweets());\r\n        Assert.assertFalse(user1.getTweets().isEmpty());\r\n        Assert.assertEquals(3, user1.getTweets().size());\r\n        Assert.assertNotNull(user1.getExternalLinks());\r\n        Assert.assertFalse(user1.getExternalLinks().isEmpty());\r\n        Assert.assertEquals(2, user1.getExternalLinks().size());\r\n    }\r\n\r\n    abstract void startServer();\r\n\r\n    abstract void stopServer();\r\n\r\n    abstract void deleteSchema();\r\n\r\n    abstract void createSchema();\r\n}\r\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/twitter/dao/SuperDao.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.dao;\r\n\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Persistence;\r\n\r\n/**\r\n * The Class SuperDao.\r\n * \r\n * @author impetus\r\n */\r\npublic class SuperDao\r\n{\r\n\r\n    /**\r\n     * Inits the.\r\n     * \r\n     * @param persistenceUnitName\r\n     *            the persistence unit name\r\n     * @return the entity manager\r\n     * @throws Exception\r\n     *             the exception\r\n     */\r\n    protected EntityManagerFactory createEntityManagerFactory(String persistenceUnitName)\r\n    {\r\n        return Persistence.createEntityManagerFactory(persistenceUnitName);\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/twitter/dao/Twitter.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.dao;\r\n\r\nimport java.util.List;\r\n\r\nimport com.impetus.client.twitter.entities.PreferenceRDBMS;\r\nimport com.impetus.client.twitter.entities.TweetRDBMS;\r\nimport com.impetus.client.twitter.entities.UserRDBMS;\r\n\r\n/**\r\n * Single window application for Twitter application. Contains methods for\r\n * performing CRUD operations on users and their tweets.\r\n */\r\npublic interface Twitter\r\n{\r\n\r\n    void addUser(UserRDBMS user);\r\n\r\n    /**\r\n     * Registers a new user with Twitter application\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param name\r\n     *            the name\r\n     * @param password\r\n     *            the password\r\n     * @param relationshipStatus\r\n     *            the relationship status\r\n     */\r\n    void addUser(String userId, String name, String password, String relationshipStatus);\r\n\r\n    /**\r\n     * Save preference for a given user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param preference\r\n     *            the preference\r\n     */\r\n    void savePreference(String userId, PreferenceRDBMS preference);\r\n\r\n    /**\r\n     * Adds an external link for the given user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param linkType\r\n     *            the link type\r\n     * @param linkAddress\r\n     *            the link address\r\n     */\r\n    void addExternalLink(String userId, String linkId, String linkType, String linkAddress);\r\n\r\n    /**\r\n     * Adds a new tweet for a user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param tweetBody\r\n     *            the tweet body\r\n     * @param device\r\n     *            the device\r\n     */\r\n    void addTweet(String userId, String tweetBody, String device);\r\n\r\n    /**\r\n     * Makes User whose row key is <code>userId</code> follow a user whose row\r\n     * key is <code>friendUserId</code>\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param friendUserId\r\n     *            the friend user id\r\n     */\r\n    void startFollowing(String userId, String friendUserId);\r\n\r\n    /**\r\n     * Adds the follower whose row key is <code>followerUserId</code> to User\r\n     * whose row key is <code>userId</code>\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @param followerUserId\r\n     *            the follower user id\r\n     */\r\n    void addFollower(String userId, String followerUserId);\r\n\r\n    UserRDBMS findUserById(String userId);\r\n\r\n    void removeUser(UserRDBMS user);\r\n\r\n    void mergeUser(UserRDBMS user);\r\n\r\n    /**\r\n     * Retrieves all tweets for a given user\r\n     * \r\n     * @param userId\r\n     *            the user id\r\n     * @return the all tweets\r\n     */\r\n    List<UserRDBMS> getAllUsers();\r\n\r\n    List<TweetRDBMS> getAllTweets(String userId);\r\n\r\n    /**\r\n     * Returns a list of followers for a given user.\r\n     * \r\n     * @param userId\r\n     *            user id\r\n     * @return list of all followers.\r\n     */\r\n    List<UserRDBMS> getFollowers(String userId);\r\n\r\n    /**\r\n     * Find tweet by tweet body.\r\n     * \r\n     * @param tweetBody\r\n     *            the tweet body\r\n     * @return the list\r\n     */\r\n    List<TweetRDBMS> findTweetByBody(String tweetBody);\r\n\r\n    /**\r\n     * Find tweet by device.\r\n     * \r\n     * @param deviceName\r\n     *            the device name\r\n     * @return the list\r\n     */\r\n    List<TweetRDBMS> findTweetByDevice(String deviceName);\r\n\r\n    /**\r\n     * Close.\r\n     */\r\n    void close();\r\n\r\n    void createEntityManager();\r\n\r\n    void closeEntityManager();\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/twitter/dao/TwitterService.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.dao;\r\n\r\nimport java.util.List;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Query;\r\n\r\nimport com.impetus.client.twitter.entities.ExternalLinkRDBMS;\r\nimport com.impetus.client.twitter.entities.PreferenceRDBMS;\r\nimport com.impetus.client.twitter.entities.TweetRDBMS;\r\nimport com.impetus.client.twitter.entities.UserRDBMS;\r\n\r\n/**\r\n * Data access object class for implementation of twitter.\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class TwitterService extends SuperDao implements Twitter\r\n{\r\n    private EntityManager em;\r\n\r\n    private EntityManagerFactory emf;\r\n\r\n    private String pu;\r\n\r\n    public TwitterService(String persistenceUnitName)\r\n    {\r\n        this.pu = persistenceUnitName;\r\n        if (emf == null)\r\n        {\r\n            try\r\n            {\r\n                emf = createEntityManagerFactory(persistenceUnitName);\r\n            }\r\n            catch (Exception e)\r\n            {\r\n                \r\n            }\r\n        }\r\n\r\n    }\r\n\r\n    @Override\r\n    public void createEntityManager()\r\n    {\r\n        if (em == null)\r\n        {\r\n            em = emf.createEntityManager();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void closeEntityManager()\r\n    {\r\n        if (em != null)\r\n        {\r\n            em.close();\r\n            em = null;\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void close()\r\n    {\r\n        if (emf != null)\r\n        {\r\n            emf.close();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void addUser(UserRDBMS user)\r\n    {\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void addUser(String userId, String name, String password, String relationshipStatus)\r\n    {\r\n        UserRDBMS user = new UserRDBMS(userId, name, password, relationshipStatus);\r\n        em.persist(user);\r\n\r\n    }\r\n\r\n    @Override\r\n    public void savePreference(String userId, PreferenceRDBMS preference)\r\n    {\r\n\r\n        UserRDBMS user = em.find(UserRDBMS.class, userId);\r\n        user.setPreference(preference);\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void addExternalLink(String userId, String linkId, String linkType, String linkAddress)\r\n    {\r\n        UserRDBMS user = em.find(UserRDBMS.class, userId);\r\n        user.addExternalLink(new ExternalLinkRDBMS(linkId, linkType, linkAddress));\r\n\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void addTweet(String userId, String tweetBody, String device)\r\n    {\r\n        UserRDBMS user = em.find(UserRDBMS.class, userId);\r\n        user.addTweet(new TweetRDBMS(tweetBody, device));\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public void startFollowing(String userId, String friendUserId)\r\n    {\r\n        UserRDBMS user = em.find(UserRDBMS.class, userId);\r\n        UserRDBMS friend = em.find(UserRDBMS.class, friendUserId);\r\n\r\n        user.addFriend(friend);\r\n        em.persist(user);\r\n\r\n        friend.addFollower(user);\r\n        em.persist(friend);\r\n    }\r\n\r\n    @Override\r\n    public void addFollower(String userId, String followerUserId)\r\n    {\r\n        UserRDBMS user = em.find(UserRDBMS.class, userId);\r\n        UserRDBMS follower = em.find(UserRDBMS.class, followerUserId);\r\n\r\n        user.addFollower(follower);\r\n        em.persist(user);\r\n    }\r\n\r\n    @Override\r\n    public UserRDBMS findUserById(String userId)\r\n    {\r\n        UserRDBMS user = em.find(UserRDBMS.class, userId);\r\n        return user;\r\n    }\r\n\r\n    @Override\r\n    public void removeUser(UserRDBMS user)\r\n    {\r\n        em.remove(user);\r\n    }\r\n\r\n    @Override\r\n    public void mergeUser(UserRDBMS user)\r\n    {\r\n        em.merge(user);\r\n    }\r\n\r\n    @Override\r\n    public List<UserRDBMS> getAllUsers()\r\n    {\r\n\r\n        Query q = em.createQuery(\"select u from UserRDBMS u\");\r\n\r\n        List<UserRDBMS> users = q.getResultList();\r\n\r\n        return users;\r\n    }\r\n\r\n    @Override\r\n    public List<TweetRDBMS> getAllTweets(String userId)\r\n    {\r\n        Query q = em.createQuery(\"select u from UserRDBMS u where u.userId =:userId\");\r\n        q.setParameter(\"userId\", userId);\r\n        List<UserRDBMS> users = q.getResultList();\r\n        if (users == null || users.isEmpty())\r\n        {\r\n            return null;\r\n        }\r\n        else\r\n        {\r\n            return users.get(0).getTweets();\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public List<UserRDBMS> getFollowers(String userId)\r\n    {\r\n        Query q = em.createQuery(\"select u from UserRDBMS u where u.userId =:userId\");\r\n        q.setParameter(\"userId\", userId);\r\n        List<UserRDBMS> users = q.getResultList();\r\n        if (users == null || users.isEmpty())\r\n        {\r\n            return null;\r\n        }\r\n        return users.get(0).getFollowers();\r\n    }\r\n\r\n    @Override\r\n    public List<TweetRDBMS> findTweetByBody(String tweetBody)\r\n    {\r\n        Query q = em.createQuery(\"select u.tweet_body from UserRDBMS u where u.tweet_body like :body\");\r\n        q.setParameter(\"body\", tweetBody);\r\n        List<TweetRDBMS> tweets = q.getResultList();\r\n        return tweets;\r\n    }\r\n\r\n    @Override\r\n    public List<TweetRDBMS> findTweetByDevice(String deviceName)\r\n    {\r\n        Query q = em.createQuery(\"select u.tweeted_from from UserRDBMS u where u.tweeted_from like :device\");\r\n        q.setParameter(\"device\", deviceName);\r\n        List<TweetRDBMS> tweets = q.getResultList();\r\n        return tweets;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/twitter/entities/ExternalLinkRDBMS.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.twitter.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class for user's External link details\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"EXTERNAL_LINK\")\npublic class ExternalLinkRDBMS\n{\n\n    @Id\n    @Column(name = \"EXT_LINK_ID\")\n    private String extLinkId;\n\n    @Column(name = \"LINK_TYPE\")\n    private String linkType;\n\n    @Column(name = \"LINK_ADDRESS\")\n    private String linkAddress;\n\n    public ExternalLinkRDBMS()\n    {\n    }\n\n    public ExternalLinkRDBMS(String extLinkId, String type, String address)\n    {\n        this.extLinkId = extLinkId;\n        this.linkType = type;\n        this.linkAddress = address;\n    }\n\n    /**\n     * @return the extLinkId\n     */\n    public String getExtLinkId()\n    {\n        return extLinkId;\n    }\n\n    /**\n     * @param extLinkId\n     *            the extLinkId to set\n     */\n    public void setExtLinkId(String extLinkId)\n    {\n        this.extLinkId = extLinkId;\n    }\n\n    /**\n     * @return the linkType\n     */\n    public String getLinkType()\n    {\n        return linkType;\n    }\n\n    /**\n     * @param linkType\n     *            the linkType to set\n     */\n    public void setLinkType(String linkType)\n    {\n        this.linkType = linkType;\n    }\n\n    /**\n     * @return the linkAddress\n     */\n    public String getLinkAddress()\n    {\n        return linkAddress;\n    }\n\n    /**\n     * @param linkAddress\n     *            the linkAddress to set\n     */\n    public void setLinkAddress(String linkAddress)\n    {\n        this.linkAddress = linkAddress;\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/twitter/entities/PersonalDetailRDBMS.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\nimport com.impetus.client.twitter.utils.ExampleUtilsMongo;\r\n\r\n/**\r\n * Entity class for user's personal details\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\npublic class PersonalDetailRDBMS\r\n{\r\n    @Column(name = \"personal_detail_id\")\r\n    private String personalDetailId;\r\n\r\n    @Column(name = \"name\")\r\n    private String name;\r\n\r\n    @Column(name = \"password\")\r\n    private String password;\r\n\r\n    @Column(name = \"rel_status\")\r\n    private String relationshipStatus;\r\n\r\n    public PersonalDetailRDBMS()\r\n    {\r\n\r\n    }\r\n\r\n    public PersonalDetailRDBMS(String name, String password, String relationshipStatus)\r\n    {\r\n        setPersonalDetailId(ExampleUtilsMongo.getUniqueId());\r\n        setName(name);\r\n        setPassword(password);\r\n        setRelationshipStatus(relationshipStatus);\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetailId\r\n     */\r\n    public String getPersonalDetailId()\r\n    {\r\n        return personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetailId\r\n     *            the personalDetailId to set\r\n     */\r\n    public void setPersonalDetailId(String personalDetailId)\r\n    {\r\n        this.personalDetailId = personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @return the name\r\n     */\r\n    public String getName()\r\n    {\r\n        return name;\r\n    }\r\n\r\n    /**\r\n     * @param name\r\n     *            the name to set\r\n     */\r\n    public void setName(String name)\r\n    {\r\n        this.name = name;\r\n    }\r\n\r\n    /**\r\n     * @return the password\r\n     */\r\n    public String getPassword()\r\n    {\r\n        return password;\r\n    }\r\n\r\n    /**\r\n     * @param password\r\n     *            the password to set\r\n     */\r\n    public void setPassword(String password)\r\n    {\r\n        this.password = password;\r\n    }\r\n\r\n    /**\r\n     * @return the relationshipStatus\r\n     */\r\n    public String getRelationshipStatus()\r\n    {\r\n        return relationshipStatus;\r\n    }\r\n\r\n    /**\r\n     * @param relationshipStatus\r\n     *            the relationshipStatus to set\r\n     */\r\n    public void setRelationshipStatus(String relationshipStatus)\r\n    {\r\n        this.relationshipStatus = relationshipStatus;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/twitter/entities/PreferenceRDBMS.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * Entity class for User Preferences\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"PREFERENCE\")\r\npublic class PreferenceRDBMS\r\n{\r\n    @Id\r\n    @Column(name = \"PREFERENCE_ID\")\r\n    String preferenceId;\r\n\r\n    @Column(name = \"WEBSITE_THEME\")\r\n    String websiteTheme;\r\n\r\n    @Column(name = \"PRIVACY_LEVEL\")\r\n    String privacyLevel; // 1, 2, 3\r\n\r\n    public PreferenceRDBMS()\r\n    {\r\n\r\n    }\r\n\r\n    public PreferenceRDBMS(String preferenceId, String theme, String privacyLevel)\r\n    {\r\n        this.preferenceId = preferenceId;\r\n        this.websiteTheme = theme;\r\n        this.privacyLevel = privacyLevel;\r\n    }\r\n\r\n    /**\r\n     * @return the preferenceId\r\n     */\r\n    public String getPreferenceId()\r\n    {\r\n        return preferenceId;\r\n    }\r\n\r\n    /**\r\n     * @param preferenceId\r\n     *            the preferenceId to set\r\n     */\r\n    public void setPreferenceId(String preferenceId)\r\n    {\r\n        this.preferenceId = preferenceId;\r\n    }\r\n\r\n    /**\r\n     * @return the websiteTheme\r\n     */\r\n    public String getWebsiteTheme()\r\n    {\r\n        return websiteTheme;\r\n    }\r\n\r\n    /**\r\n     * @param websiteTheme\r\n     *            the websiteTheme to set\r\n     */\r\n    public void setWebsiteTheme(String websiteTheme)\r\n    {\r\n        this.websiteTheme = websiteTheme;\r\n    }\r\n\r\n    /**\r\n     * @return the privacyLevel\r\n     */\r\n    public String getPrivacyLevel()\r\n    {\r\n        return privacyLevel;\r\n    }\r\n\r\n    /**\r\n     * @param privacyLevel\r\n     *            the privacyLevel to set\r\n     */\r\n    public void setPrivacyLevel(String privacyLevel)\r\n    {\r\n        this.privacyLevel = privacyLevel;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/twitter/entities/TweetRDBMS.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\nimport com.impetus.client.twitter.utils.ExampleUtilsMongo;\r\n\r\n/**\r\n * Class for Tweets\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\npublic class TweetRDBMS\r\n{\r\n\r\n    @Column(name = \"tweet_id\")\r\n    private String tweetId;\r\n\r\n    @Column(name = \"tweet_body\")\r\n    private String body;\r\n\r\n    @Column(name = \"tweeted_from\")\r\n    private String device;\r\n\r\n    // private long timestamp;\r\n\r\n    public TweetRDBMS(String body, String device)\r\n    {\r\n        this.tweetId = ExampleUtilsMongo.getUniqueId();\r\n        this.body = body;\r\n        this.device = device;\r\n        // this.timestamp = ExampleUtils.getCurrentTimestamp();\r\n    }\r\n\r\n    public TweetRDBMS()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * @return the tweetId\r\n     */\r\n    public String getTweetId()\r\n    {\r\n        return tweetId;\r\n    }\r\n\r\n    /**\r\n     * @param tweetId\r\n     *            the tweetId to set\r\n     */\r\n    public void setTweetId(String tweetId)\r\n    {\r\n        this.tweetId = tweetId;\r\n    }\r\n\r\n    /**\r\n     * @return the body\r\n     */\r\n    public String getBody()\r\n    {\r\n        return body;\r\n    }\r\n\r\n    /**\r\n     * @param body\r\n     *            the body to set\r\n     */\r\n    public void setBody(String body)\r\n    {\r\n        this.body = body;\r\n    }\r\n\r\n    /**\r\n     * @return the device\r\n     */\r\n    public String getDevice()\r\n    {\r\n        return device;\r\n    }\r\n\r\n    /**\r\n     * @param device\r\n     *            the device to set\r\n     */\r\n    public void setDevice(String device)\r\n    {\r\n        this.device = device;\r\n    }\r\n\r\n    /*    *//**\r\n     * @return the timestamp\r\n     */\r\n    /*\r\n     * public long getTimestamp() { return timestamp; }\r\n     *//**\r\n     * @param timestamp\r\n     *            the timestamp to set\r\n     */\r\n    /*\r\n     * public void setTimestamp(long timestamp) { this.timestamp = timestamp; }\r\n     */\r\n}\r\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/twitter/entities/UserRDBMS.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.entities;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.CollectionTable;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.ElementCollection;\r\nimport javax.persistence.Embedded;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.OneToOne;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * @author impetus\r\n * \r\n */\r\n@Entity\r\n@Table(name = \"UserRDBMS\")\r\npublic class UserRDBMS\r\n{\r\n\r\n    @Id\r\n    @Column(name = \"USER_ID\")\r\n    private String userId;\r\n\r\n    // Embedded object, will persist co-located\r\n    @Embedded\r\n    private PersonalDetailRDBMS personalDetail;\r\n\r\n    // Element collection, will persist co-located\r\n    @ElementCollection\r\n    @CollectionTable(name = \"tweeted\")\r\n    private List<TweetRDBMS> tweets;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)\r\n    @JoinColumn(name = \"FRIEND_ID\")\r\n    private List<UserRDBMS> friends; // List of users whom I follow\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)\r\n    @JoinColumn(name = \"FOLLOWER_ID\")\r\n    private List<UserRDBMS> followers; // List of users who are following me\r\n\r\n    // One-to-one, will be persisted separately\r\n    @OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)\r\n    @JoinColumn(name = \"PREFERENCE_ID\")\r\n    private PreferenceRDBMS preference;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)\r\n    @JoinColumn(name = \"USER_ID\")\r\n    private Set<ExternalLinkRDBMS> externalLinks;\r\n\r\n    public UserRDBMS()\r\n    {\r\n\r\n    }\r\n\r\n    public UserRDBMS(String userId, String name, String password, String relationshipStatus)\r\n    {\r\n        PersonalDetailRDBMS pd = new PersonalDetailRDBMS(name, password, relationshipStatus);\r\n        setUserId(userId);\r\n        setPersonalDetail(pd);\r\n    }\r\n\r\n    /**\r\n     * @return the userId\r\n     */\r\n    public String getUserId()\r\n    {\r\n        return userId;\r\n    }\r\n\r\n    /**\r\n     * @param userId\r\n     *            the userId to set\r\n     */\r\n    public void setUserId(String userId)\r\n    {\r\n        this.userId = userId;\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetail\r\n     */\r\n    public PersonalDetailRDBMS getPersonalDetail()\r\n    {\r\n        return personalDetail;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetail\r\n     *            the personalDetail to set\r\n     */\r\n    public void setPersonalDetail(PersonalDetailRDBMS personalDetail)\r\n    {\r\n        this.personalDetail = personalDetail;\r\n    }\r\n\r\n    /**\r\n     * @return the tweets\r\n     */\r\n    public List<TweetRDBMS> getTweets()\r\n    {\r\n        return tweets;\r\n    }\r\n\r\n    /**\r\n     * @param tweets\r\n     *            the tweets to set\r\n     */\r\n    public void addTweet(TweetRDBMS tweet)\r\n    {\r\n        if (this.tweets == null || this.tweets.isEmpty())\r\n        {\r\n            this.tweets = new ArrayList<TweetRDBMS>();\r\n        }\r\n        this.tweets.add(tweet);\r\n    }\r\n\r\n    /**\r\n     * @return the preference\r\n     */\r\n    public PreferenceRDBMS getPreference()\r\n    {\r\n        return preference;\r\n    }\r\n\r\n    /**\r\n     * @param preference\r\n     *            the preference to set\r\n     */\r\n    public void setPreference(PreferenceRDBMS preference)\r\n    {\r\n        this.preference = preference;\r\n    }\r\n\r\n    /**\r\n     * @return the externalLinks\r\n     */\r\n    public Set<ExternalLinkRDBMS> getExternalLinks()\r\n    {\r\n        return externalLinks;\r\n    }\r\n\r\n    /**\r\n     * @param imDetails\r\n     *            the imDetails to set\r\n     */\r\n    public void addExternalLink(ExternalLinkRDBMS externalLink)\r\n    {\r\n        if (this.externalLinks == null || this.externalLinks.isEmpty())\r\n        {\r\n            this.externalLinks = new HashSet<ExternalLinkRDBMS>();\r\n        }\r\n\r\n        this.externalLinks.add(externalLink);\r\n    }\r\n\r\n    /**\r\n     * @return the friends\r\n     */\r\n    public List<UserRDBMS> getFriends()\r\n    {\r\n        return friends;\r\n    }\r\n\r\n    /**\r\n     * @param friends\r\n     *            the friends to set\r\n     */\r\n    public void addFriend(UserRDBMS friend)\r\n    {\r\n        if (this.friends == null || this.friends.isEmpty())\r\n        {\r\n            this.friends = new ArrayList<UserRDBMS>();\r\n        }\r\n        this.friends.add(friend);\r\n    }\r\n\r\n    /**\r\n     * @return the followers\r\n     */\r\n    public List<UserRDBMS> getFollowers()\r\n    {\r\n        return followers;\r\n    }\r\n\r\n    /**\r\n     * @param followers\r\n     *            the followers to set\r\n     */\r\n    public void addFollower(UserRDBMS follower)\r\n    {\r\n        if (this.followers == null || this.followers.isEmpty())\r\n        {\r\n            this.followers = new ArrayList<UserRDBMS>();\r\n        }\r\n\r\n        this.followers.add(follower);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/client/twitter/utils/ExampleUtilsMongo.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.twitter.utils;\r\n\r\nimport java.util.Date;\r\nimport java.util.UUID;\r\n\r\n/**\r\n * Class for utility methods\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class ExampleUtilsMongo\r\n{\r\n    public static String getUniqueId()\r\n    {\r\n        return UUID.randomUUID().toString();\r\n    }\r\n\r\n    public static long getCurrentTimestamp()\r\n    {\r\n        return new Date().getTime();\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/AbstractTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Id;\nimport javax.persistence.MappedSuperclass;\n\n/**\n * @author vivek.mishra\n * Transaction {@link MappedSuperclass}\n */\n\n@MappedSuperclass\npublic class AbstractTransaction\n{\n\n    @Id\n    private String txId;\n    \n    @Column\n    private Date transactionDt;\n\n    public Date getTransactionDt()\n    {\n        return transactionDt;\n    }\n\n    public void setTransactionDt(Date transactionDt)\n    {\n        this.transactionDt = transactionDt;\n    }\n\n    public String getTxId()\n    {\n        return txId;\n    }\n\n    public void setTxId(String txId)\n    {\n        this.txId = txId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/MappedSuperClassBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.MappedSuperclass;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * @author vivek.mishra junit for {@link MappedSuperclass},\n *         {@link AttributeOverride}, {@link AttributeOverrides}.\n */\npublic abstract class MappedSuperClassBase\n{\n\n    /** log for this class. */\n    private static Logger log = LoggerFactory.getLogger(MappedSuperClassBase.class);\n\n    protected String _PU = \"corePu\";\n\n    /** The emf. */\n    protected static EntityManagerFactory emf;\n\n    /** The em. */\n    protected static EntityManager em;\n\n    protected void setUpInternal() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(_PU);\n        em = emf.createEntityManager();\n    }\n\n    protected void assertInternal()\n    {\n        assertInternal(false);\n    }\n\n    protected void assertInternal(boolean wait)\n    {\n        RDBMSCreditTransaction creditTx = new RDBMSCreditTransaction();\n        creditTx.setTxId(\"credit1\");\n        creditTx.setTxStatus(Status.APPROVED);\n        creditTx.setBankIdentifier(\"sbi\");\n        creditTx.setTransactionDt(new Date());\n        creditTx.setAmount(10);\n        em.persist(creditTx);\n\n        waitThread(wait);\n\n        RDBMSDebitTransaction debitTx = new RDBMSDebitTransaction();\n        debitTx.setTxId(\"debit1\");\n        debitTx.setTxStatus(Status.PENDING);\n        debitTx.setTransactionDt(new Date());\n        debitTx.setBankIdentifier(\"sbi\");\n        debitTx.setAmount(-10);\n        em.persist(debitTx);\n\n        waitThread(wait);\n        em.clear();\n        String creditQuery = \"Select c from RDBMSCreditTransaction c where c.bankIdentifier = 'sbi'\";\n\n        Query query = em.createQuery(creditQuery);\n\n        List<RDBMSCreditTransaction> results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"credit1\", results.get(0).getTxId());\n\n        em.clear();\n        String debitQuery = \"Select d from RDBMSDebitTransaction d where d.bankIdentifier = 'sbi'\";\n\n        query = em.createQuery(debitQuery);\n\n        List<RDBMSDebitTransaction> debitResults = query.getResultList();\n        Assert.assertEquals(1, debitResults.size());\n        Assert.assertEquals(\"debit1\", debitResults.get(0).getTxId());\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    protected void tearDownInternal() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n\n        if (em != null)\n        {\n            em.close();\n        }\n\n        \n    }\n\n    private void waitThread(boolean toWait)\n    {\n        if (toWait)\n        {\n            try\n            {\n                Thread.sleep(2000);\n            }\n            catch (InterruptedException e)\n            {\n                log.error(\"Error while thread interruption, {}\", e);\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/RDBMSCreditTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * Credit transaction extends {@link Transaction}\n *\n */\n\n@Entity\n@Table(name = \"TRNX_CREDIT\", schema = \"TESTDB\")\n@DiscriminatorValue(value = \"CREDIT\")\n@AttributeOverride(name=\"bankIdentifier\",column= @Column(name=\"CREDIT_BANK_IDENT\"))\npublic class RDBMSCreditTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public RDBMSCreditTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/RDBMSDebitTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra Debit transaction extends {@link Transaction}\n * \n */\n@Entity\n@DiscriminatorValue(value = \"DEBIT\")\n@AttributeOverrides(value = { @AttributeOverride(name = \"txId\", column = @Column(name = \"DEBIT_ID\")),\n        @AttributeOverride(name = \"bankIdentifier\", column = @Column(name = \"DEBIT_BANK_IDENT\")),\n        @AttributeOverride(name = \"transactionDt\", column = @Column(name = \"TX_DT\")) })\n@Table(name = \"DebitTransaction\", schema = \"TESTDB\")\npublic class RDBMSDebitTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public RDBMSDebitTransaction()\n    {\n\n    }\n\n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/Status.java",
    "content": "package com.impetus.kundera.client.crud.mappedsuperclass;\n\npublic enum Status\n{\n    APPROVED,PENDING\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/Transaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorColumn;\nimport javax.persistence.Id;\nimport javax.persistence.Inheritance;\nimport javax.persistence.InheritanceType;\nimport javax.persistence.MappedSuperclass;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * Transaction {@link MappedSuperclass}\n *\n */\n@MappedSuperclass\n@Table(name = \"TRNX\")\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@DiscriminatorColumn(name = \"tx_type\")\npublic class Transaction \n{\n\n    @Id\n    private String txId;\n    \n    @Column\n    private String bankIdentifier;\n\n    \n    @Column\n    private Date transactionDt;\n\n    public Date getTransactionDt()\n    {\n        return transactionDt;\n    }\n\n    public void setTransactionDt(Date transactionDt)\n    {\n        this.transactionDt = transactionDt;\n    }\n\n\n\n    public String getTxId()\n    {\n        return txId;\n    }\n\n    public void setTxId(String txId)\n    {\n        this.txId = txId;\n    }\n\n    public String getBankIdentifier()\n    {\n        return bankIdentifier;\n    }\n\n    public void setBankIdentifier(String bankIdentifier)\n    {\n        this.bankIdentifier = bankIdentifier;\n    }\n\n\n}\n"
  },
  {
    "path": "src/kundera-rdbms/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"testHibernate\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.client.Player</class>\r\n\t\t<class>com.impetus.client.onetoone.OTONPerson</class>\r\n\t\t<class>com.impetus.client.onetoone.OTONSPerson</class>\r\n\t\t<class>com.impetus.client.onetomany.OTMNPerson</class>\r\n\t\t<class>com.impetus.client.onetomany.bi.OTMBNPerson</class>\r\n\t\t<class>com.impetus.client.manytoone.MTONPerson</class>\r\n\t\t<class>com.impetus.client.manytomany.MTMNPerson</class>\r\n\t\t<class>com.impetus.client.onetoone.OTOAddress</class>\r\n\t\t<class>com.impetus.client.onetoone.OTOSAddress</class>\r\n\t\t<class>com.impetus.client.onetomany.OTMAddress</class>\r\n\t\t<class>com.impetus.client.onetomany.bi.OTMBAddress</class>\r\n\t\t<class>com.impetus.client.manytoone.MTOAddress</class>\r\n\t\t<class>com.impetus.client.manytomany.MTMAddress</class>\r\n\t\t<!-- <class>com.impetus.client.crud.PersonRDBMS</class> <class>com.impetus.client.crud.datatypes.StudentRdbms</class> \r\n\t\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes> -->\r\n\t\t<properties>\r\n\t\t\t<!-- <property name=\"hibernate.hbm2ddl.auto\" value=\"create-drop\" /> -->\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.rdbms.RDBMSClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.keyspace\" value=\"testdb\" /> -->\t\t\t<!-- DO NOT delete these -->\r\n\t\t\t<!-- <property name=\"current_session_context_class\" value=\"thread\" /> -->\r\n\t\t\t<!-- <property name=\"hibernate.show_sql\" value=\"true\" /> -->\r\n\t\t\t<!-- <property name=\"hibernate.format_sql\" value=\"true\" /> <property name=\"hibernate.connection.driver_class\" \r\n\t\t\t\tvalue=\"org.hsqldb.jdbcDriver\" /> <property name=\"hibernate.connection.url\" \r\n\t\t\t\tvalue=\"jdbc:hsqldb:mem:TESTDB\" /> <property name=\"hibernate.connection.username\" \r\n\t\t\t\tvalue=\"sa\" /> <property name=\"hibernate.connection.password\" value=\"\" /> \r\n\t\t\t\t<property name=\"hibernate.connection.pool_size\" value=\"10\" /> <property name=\"hibernate.connection.autocommit\" \r\n\t\t\t\tvalue=\"true\" /> <property name=\"hibernate.dialect\" value=\"org.hibernate.dialect.HSQLDialect\" \r\n\t\t\t\t/> -->\r\n\t\t\t<!-- <property name=\"hibernate.max_fetch_depth\" value=\"0\" /> <property \r\n\t\t\t\tname=\"hibernate.show_sql\" value=\"true\" /> <property name=\"hibernate.format_sql\" \r\n\t\t\t\tvalue=\"true\" /> <property name=\"hibernate.dialect\" value=\"org.hibernate.dialect.MySQL5Dialect\" \r\n\t\t\t\t/> <property name=\"hibernate.connection.driver_class\" value=\"com.mysql.jdbc.Driver\" \r\n\t\t\t\t/> <property name=\"hibernate.connection.url\" value=\"jdbc:mysql://localhost:3306/testdb\" \r\n\t\t\t\t/> <property name=\"hibernate.connection.username\" value=\"root\" /> <property \r\n\t\t\t\tname=\"hibernate.connection.password\" value=\"impetus\" /> <property name=\"hibernate.c3p0.min_size\" \r\n\t\t\t\tvalue=\"10\" /> <property name=\"hibernate.c3p0.max_size\" value=\"100\" /> <property \r\n\t\t\t\tname=\"hibernate.c3p0.timeout\" value=\"300\" /> <property name=\"hibernate.c3p0.max_statements\" \r\n\t\t\t\tvalue=\"50\" /> <property name=\"hibernate.c3p0.idle_test_period\" value=\"3000\" \r\n\t\t\t\t/> <property name=\"hibernate.hbm2ddl.auto\" value=\"update\" /> <property name=\"current_session_context_class\" \r\n\t\t\t\tvalue=\"thread\" /> -->\r\n\t\t\t<!-- <property name=\"hibernate.connection.provider_class\" value=\"org.hibernate.connection.C3P0ConnectionProvider\" \r\n\t\t\t\t/> -->\r\n\t\t\t<!-- <property name=\"hibernate.show_sql\" value=\"true\" /> <property name=\"hibernate.format_sql\" \r\n\t\t\t\tvalue=\"true\" /> -->\t\t\t<!-- <property name=\"hibernate.hbm2ddl.auto\" value=\"create-drop\" /> -->\r\n\t\t\t<property name=\"kundera.client.property\" value=\"hibernate.properties\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"mappedPu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.rdbms.RDBMSClientFactory\" />\r\n\t\t\t<!-- <property name=\"hibernate.hbm2ddl.auto\" value=\"create-drop\" /> -->\r\n\t\t\t<property name=\"hibernate.max_fetch_depth\" value=\"0\" />\r\n\t\t\t<!-- <property name=\"hibernate.show_sql\" value=\"true\" /> <property name=\"hibernate.format_sql\" \r\n\t\t\t\tvalue=\"true\" /> -->\r\n\t\t\t<property name=\"kundera.client.property\" value=\"hibernate.properties\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"RdbmsDataTypeTest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentString</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentInt</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentBigInteger</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentBigDecimal</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentBytePrimitive</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentByteWrapper</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentInteger</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentFloatPrimitive</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentFloatWrapper</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentDoublePrimitive</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentDoubleWrapper</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentChar</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentCharacter</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentLongPrimitive</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentLongWrapper</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentShortPrimitive</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentShortWrapper</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentSqlDate</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentTimestamp</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentTime</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentUUID</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentDate</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentCalendar</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentBooleanPrimitive</class>\r\n\t\t<class>com.impetus.client.crud.datatypes.entities.StudentBooleanWrapper</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.rdbms.RDBMSClientFactory\" />\r\n\t\t\t<!-- <property name=\"hibernate.hbm2ddl.auto\" value=\"create-drop\" />\r\n\t\t\t<property name=\"hibernate.max_fetch_depth\" value=\"0\" /> -->\r\n\t\t\t<property name=\"kundera.client.property\" value=\"hibernate.properties\" />\r\n\t\t\t<!-- <property name=\"kundera.keyspace\" value=\"KunderaTests\" /> -->\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\t\r\n\t<persistence-unit name=\"RdbmsMappedSUTest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.Person</class>\r\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.PersonChild</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.rdbms.RDBMSClientFactory\" />\r\n\t\t\t<property name=\"hibernate.hbm2ddl.auto\" value=\"create-drop\" />\r\n\t\t\t<!-- <property name=\"hibernate.max_fetch_depth\" value=\"0\" /> -->\r\n\t\t\t<property name=\"kundera.client.property\" value=\"hibernate.properties\" />\r\n\t\t\t<!-- <property name=\"kundera.keyspace\" value=\"KunderaTests\" /> -->\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n</persistence>"
  },
  {
    "path": "src/kundera-rdbms/src/test/resources/hibernate.properties",
    "content": " hibernate.connection.driver_class=org.hsqldb.jdbcDriver\n hibernate.connection.url=jdbc:hsqldb:mem:TESTDB\n hibernate.connection.username=sa\n hibernate.connection.password=\n hibernate.dialect = org.hibernate.dialect.HSQLDialect\n hibernate.connection.pool_size=10\n hibernate.connection.autocommit=true\n# hibernate.show_sql=true\n hibernate.max_fetch_depth=0\n# hibernate.hbm2ddl.auto=create\n \n# hibernate.dialect = org.hibernate.dialect.MySQL5Dialect\n# hibernate.connection.url=jdbc:mysql://localhost:3306/KunderaTests\n# hibernate.connection.driver_class=com.mysql.jdbc.Driver\n# hibernate.connection.username=root\n# hibernate.connection.password=impetus\n# hibernate.c3p0.min_size=5\n# hibernate.c3p0.max_size=10\n# hibernate.c3p0.timeout=30000\n# hibernate.c3p0.max_statements=50\n# hibernate.hbm2ddl.auto=create"
  },
  {
    "path": "src/kundera-rdbms/src/test/resources/log4j.properties",
    "content": "log4j.rootLogger=INFO, DRFA, CONSOLE\r\n\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n"
  },
  {
    "path": "src/kundera-redis/pom.xml",
    "content": "<?xml version=\"1.0\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<artifactId>kundera</artifactId>\n\t\t<groupId>com.impetus</groupId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-redis</artifactId>\n\t<name>kundera-redis</name>\n\t<url>http://maven.apache.org</url>\n\t<dependencies>\n\t\t<!-- Kundera dependencies -->\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-elastic-search</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\n\t\t<!-- JEDIS dependencies -->\n\t\t<dependency>\n\t\t\t<groupId>org.apache.commons</groupId>\n\t\t\t<artifactId>commons-pool2</artifactId>\n\t\t\t<version>2.3</version>\n\t\t\t<scope>compile</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>redis.clients</groupId>\n\t\t\t<artifactId>jedis</artifactId>\n\t\t\t<version>2.8.0</version>\n\t\t\t<scope>compile</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<!-- contiperf dependency should not be here -->\n\t\t<dependency>\n\t\t\t<groupId>org.databene</groupId>\n\t\t\t<artifactId>contiperf</artifactId>\n\t\t\t<version>2.2.0</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t</properties>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<!-- <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> \n\t\t\t\t<configuration> The destination file for the code coverage report has to \n\t\t\t\tbe set to the same value in the parent pom and in each module pom. Then JaCoCo \n\t\t\t\twill add up information in the same report, so that, it will give the cross-module \n\t\t\t\tcode coverage. <destFile>${project.basedir}/../target/jacoco-it.exec</destFile> \n\t\t\t\t</configuration> <executions> <execution> <id>post-test</id> <configuration> \n\t\t\t\t<skip>true</skip> </configuration> </execution> </executions> </plugin> -->\n\n\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n\n</project>\n"
  },
  {
    "path": "src/kundera-redis/src/main/java/com/impetus/client/redis/RedisClient.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.redis;\n\nimport java.io.UnsupportedEncodingException;\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.StringTokenizer;\n\nimport javax.persistence.PersistenceException;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EmbeddableType;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport redis.clients.jedis.Jedis;\nimport redis.clients.jedis.Pipeline;\nimport redis.clients.jedis.Response;\nimport redis.clients.jedis.Transaction;\nimport redis.clients.jedis.exceptions.JedisConnectionException;\n\nimport com.impetus.client.redis.RedisQueryInterpreter.Clause;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.generator.SequenceGenerator;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.index.Indexer;\nimport com.impetus.kundera.lifecycle.states.RemovedState;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.metadata.model.SequenceGeneratorDiscriptor;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.KunderaTransactionException;\nimport com.impetus.kundera.persistence.TransactionBinder;\nimport com.impetus.kundera.persistence.TransactionResource;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessorFactory;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.property.accessor.ObjectAccessor;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * Redis client implementation for REDIS.\n * \n * @author vivek.mishra\n */\npublic class RedisClient extends ClientBase implements Client<RedisQuery>, Batcher, ClientPropertiesSetter,\n        TransactionBinder\n{\n    /**\n     * Reference to redis client factory.\n     */\n    RedisClientFactory factory;\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /** The settings. */\n    private Map<String, Object> settings;\n\n    /** list of nodes for batch processing. */\n    private List<Node> nodes = new ArrayList<Node>();\n\n    /** The resource. */\n    private TransactionResource resource;\n\n    /** batch size. */\n    private int batchSize;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(RedisClient.class);\n\n    /** The Constant COMPOSITE_KEY_SEPERATOR. */\n    private static final String COMPOSITE_KEY_SEPERATOR = \"\\001\";\n\n    /** The connection. */\n    private Jedis connection;\n\n    /**\n     * Instantiates a new redis client.\n     * \n     * @param factory\n     *            the factory\n     * @param puProperties\n     *            the pu properties\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    RedisClient(final RedisClientFactory factory, final Map<String, Object> puProperties, final String persistenceUnit,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata, puProperties, persistenceUnit);\n        this.factory = factory;\n        this.reader = new RedisEntityReader(kunderaMetadata);\n        this.indexManager = factory.getIndexManager();\n        initializeIndexer();\n        this.clientMetadata = factory.getClientMetadata();\n        setBatchSize(persistenceUnit, factory.getOverridenProperties());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.metadata\n     * .model.EntityMetadata, java.lang.Object, java.lang.Object,\n     * java.util.List)\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n        Object connection = getConnection();\n        // Create a hashset and populate data into it\n        //\n\n        Pipeline pipeLine = null;\n        try\n        {\n            if (isBoundTransaction())\n            {\n                pipeLine = ((Jedis) connection).pipelined();\n                onPersist(entityMetadata, entity, id, rlHolders, pipeLine);\n            }\n            else\n            {\n                onPersist(entityMetadata, entity, id, rlHolders, connection);\n            }\n        }\n        finally\n        {\n            //\n            if (pipeLine != null)\n            {\n                pipeLine.sync(); // send I/O.. as persist call. so no need to\n                                 // read\n            } // response?\n\n            onCleanup(connection);\n        }\n\n    }\n\n    /**\n     * Gets the double.\n     * \n     * @param valueAsStr\n     *            the value as str\n     * @return the double\n     */\n    private double getDouble(String valueAsStr)\n    {\n        return StringUtils.isNumeric(valueAsStr) ? Double.parseDouble(valueAsStr) : Double\n                .parseDouble(((Integer) valueAsStr.hashCode()).toString());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.Object)\n     */\n    @Override\n    public Object find(Class entityClass, Object key)\n    {\n        Object result = null;\n        Object connection = getConnection();\n        try\n        {\n            result = fetch(entityClass, key, connection, null);\n        }\n        catch (InstantiationException e)\n        {\n            logger.error(\"Error during find by key:\", e);\n            throw new PersistenceException(e);\n        }\n        catch (IllegalAccessException e)\n        {\n            logger.error(\"Error during find by key:\", e);\n            throw new PersistenceException(e);\n        }\n        finally\n        {\n            onCleanup(connection);\n        }\n\n        return result;\n    }\n\n    /**\n     * Retrieves entity instance of given class,row key and specific fields.\n     * \n     * @param clazz\n     *            entity class\n     * @param key\n     *            row key\n     * @param connection\n     *            connection instance.\n     * @param fields\n     *            fields.\n     * @return entity instance.\n     * @throws InstantiationException\n     *             throws in case of runtime exception\n     * @throws IllegalAccessException\n     *             throws in case of runtime exception\n     */\n    private Object fetch(Class clazz, Object key, Object connection, byte[][] fields) throws InstantiationException,\n            IllegalAccessException\n    {\n        Object result = null;\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n\n        String rowKey = null;\n        if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n        {\n            if(key instanceof String && ((String) key).indexOf(COMPOSITE_KEY_SEPERATOR)>0){\n                rowKey = (String) key;\n            }\n            else{\n            rowKey = KunderaCoreUtils.prepareCompositeKey(entityMetadata, key);\n            }\n        }\n        else\n        {\n            ObjectAccessor accessor = new ObjectAccessor();\n\n            rowKey = accessor.toString(key);\n        }\n\n        String hashKey = getHashKey(entityMetadata.getTableName(), rowKey);\n        KunderaCoreUtils\n                .printQuery(\"Fetch data from \" + entityMetadata.getTableName() + \" for PK \" + rowKey, showQuery);\n        try\n        {\n            Map<byte[], byte[]> columns = new HashMap<byte[], byte[]>();\n\n            // IF it is for selective columns\n            if (fields != null)\n            {\n                List<byte[]> fieldValues = null;\n                if (resource != null && resource.isActive())\n                {\n                    Response response = ((Transaction) connection).hmget(getEncodedBytes(hashKey), fields);\n                    // ((Transaction) connection).exec();\n                    ((RedisTransaction) resource).onExecute(((Transaction) connection));\n\n                    fieldValues = (List<byte[]>) response.get();\n                    connection = getConnection();\n\n                }\n                else\n                {\n                    fieldValues = ((Jedis) connection).hmget(getEncodedBytes(hashKey), fields);\n                }\n\n                if (fieldValues != null && !fieldValues.isEmpty())\n                {\n                    for (int i = 0; i < fields.length; i++)\n                    {\n                        if (fieldValues.get(i) != null)\n                        {\n                            columns.put(fields[i], fieldValues.get(i));\n                        }\n                    }\n                }\n            }\n            else\n            {\n                columns = getColumns(connection, hashKey, columns);\n            }\n            // Map<byte[], byte[]>\n            result = unwrap(entityMetadata, columns, key);\n        }\n        catch (JedisConnectionException jedex)\n        {\n            // Jedis is throwing runtime exception in case of no result\n            // found!!!!\n            return null;\n        }\n\n        return result;\n    }\n\n    /**\n     * Gets the columns.\n     * \n     * @param connection\n     *            the connection\n     * @param hashKey\n     *            the hash key\n     * @param columns\n     *            the columns\n     * @return the columns\n     */\n    private Map<byte[], byte[]> getColumns(Object connection, String hashKey, Map<byte[], byte[]> columns)\n    {\n        if (resource != null && resource.isActive())\n        {\n            // Why transaction API returns response in byte[] format/?\n            Response response = ((Transaction) connection).hgetAll(getEncodedBytes(hashKey));\n            ((RedisTransaction) resource).onExecute(((Transaction) connection));\n            // ((Transaction) connection).exec();\n            Map<String, String> cols = (Map<String, String>) response.get();\n            connection = getConnection();\n\n            if (cols != null)\n            {\n                for (String name : cols.keySet())\n                {\n                    columns.put(getEncodedBytes(name), getEncodedBytes(cols.get(name)));\n                }\n            }\n        }\n        else\n        {\n            columns = ((Jedis) connection).hgetAll(getEncodedBytes(hashKey));\n        }\n        return columns;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.Object[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)\n    {\n        Object connection = getConnection();\n        List results = new ArrayList();\n        try\n        {\n            for (Object key : keys)\n            {\n                Object result = fetch(entityClass, key, connection, null);\n                if (result != null)\n                {\n                    results.add(result);\n                }\n            }\n        }\n        catch (InstantiationException e)\n        {\n            logger.error(\"Error during find by key:\", e);\n            throw new PersistenceException(e);\n        }\n        catch (IllegalAccessException e)\n        {\n            logger.error(\"Error during find by key:\", e);\n            throw new PersistenceException(e);\n        }\n        return results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n        throw new UnsupportedOperationException(\"Method not supported!\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    @Override\n    public void close()\n    {\n        if (settings != null)\n        {\n            settings.clear();\n            settings = null;\n        }\n\n        if (connection != null)\n        {\n            connection.disconnect();\n            connection = null;\n        }\n\n        reader = null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    public void delete(Object entity, Object pKey)\n    {\n        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        Object connection = getConnection();\n        Pipeline pipeLine = null;\n        try\n        {\n            if (isBoundTransaction())\n            {\n                pipeLine = ((Jedis) connection).pipelined();\n                onDelete(entity, pKey, pipeLine);\n            }\n            else\n            {\n                onDelete(entity, pKey, connection);\n            }\n            getIndexManager().remove(metadata, entity, pKey);\n        }\n        finally\n        {\n            if (pipeLine != null)\n            {\n                pipeLine.sync();\n            }\n            onCleanup(connection);\n        }\n    }\n\n    /**\n     * On delete relation.\n     * \n     * @param connection\n     *            connection instance.\n     * @param entityMetadata\n     *            entity metadata.\n     * @param rowKey\n     *            row key.\n     */\n    private void deleteRelation(Object connection, EntityMetadata entityMetadata, String rowKey)\n    {\n        List<String> relations = entityMetadata.getRelationNames();\n\n        if (relations != null)\n        {\n            for (String relation : relations)\n            {\n                if (resource != null && resource.isActive())\n                {\n                    ((Transaction) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey), relation);\n\n                }\n                else\n                {\n                    ((Pipeline) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey), relation);\n\n                }\n            }\n\n        }\n        /*\n         * Response<Map<String, String>> fields = null; if (resource != null &&\n         * resource.isActive()) { fields = ((Transaction)\n         * connection).hgetAll(getHashKey(entityMetadata.getTableName(),\n         * rowKey)); if (connection != null) { ((Pipeline) connection).sync(); }\n         * for (String field : fields.get().keySet()) { ((Transaction)\n         * connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey),\n         * field); } } else { fields = ((Pipeline)\n         * connection).hgetAll(getHashKey(entityMetadata.getTableName(),\n         * rowKey)); if (connection != null) { ((Pipeline) connection).sync(); }\n         * for (String field : fields.get().keySet()) { ((Pipeline)\n         * connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey),\n         * field); } }\n         */\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera\n     * .persistence.context.jointable.JoinTableData)\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        String tableName = joinTableData.getJoinTableName();\n        String inverseJoinColumn = joinTableData.getInverseJoinColumnName();\n        String joinColumn = joinTableData.getJoinColumnName();\n\n        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();\n        Object connection = null;\n        Pipeline pipeline = null;\n        /**\n         * Example: join table : PERSON_ADDRESS join column : PERSON_ID (1_p)\n         * inverse join column : ADDRESS_ID (1_a) store in REDIS:\n         * PERSON_ADDRESS:1_p_1_a PERSON_ID 1_p ADDRESS_ID 1_a\n         */\n        // String rowKey =\n        try\n        {\n            connection = getConnection();\n            if (isBoundTransaction())\n            {\n                pipeline = ((Jedis) connection).pipelined();\n            }\n            Set<Object> joinKeys = joinTableRecords.keySet();\n\n            for (Object joinKey : joinKeys)\n            {\n                String joinKeyAsStr = PropertyAccessorHelper.getString(joinKey);\n\n                Set<Object> inverseKeys = joinTableRecords.get(joinKey);\n\n                for (Object inverseKey : inverseKeys)\n                {\n                    Map<byte[], byte[]> redisFields = new HashMap<byte[], byte[]>(1);\n                    String inverseJoinKeyAsStr = PropertyAccessorHelper.getString(inverseKey);\n                    String redisKey = getHashKey(tableName, joinKeyAsStr + \"_\" + inverseJoinKeyAsStr);\n                    redisFields.put(getEncodedBytes(joinColumn), getEncodedBytes(joinKeyAsStr)); // put\n                                                                                                 // join\n                                                                                                 // column\n                                                                                                 // field.\n                    redisFields.put(getEncodedBytes(inverseJoinColumn), getEncodedBytes(inverseJoinKeyAsStr)); // put\n                                                                                                               // inverse\n                                                                                                               // join\n                                                                                                               // column\n                                                                                                               // field\n\n                    // add to hash table.\n\n                    if (resource != null && resource.isActive())\n                    {\n                        ((Transaction) connection).hmset(getEncodedBytes(redisKey), redisFields);\n                        // add index\n                        ((Transaction) connection).zadd(getHashKey(tableName, inverseJoinKeyAsStr),\n                                getDouble(inverseJoinKeyAsStr), redisKey);\n                        ((Transaction) connection).zadd(getHashKey(tableName, joinKeyAsStr), getDouble(joinKeyAsStr),\n                                redisKey);\n\n                    }\n                    else\n                    {\n                        ((Jedis) connection).hmset(getEncodedBytes(redisKey), redisFields);\n                        // add index\n                        ((Jedis) connection).zadd(getHashKey(tableName, inverseJoinKeyAsStr),\n                                getDouble(inverseJoinKeyAsStr), redisKey);\n                        ((Jedis) connection).zadd(getHashKey(tableName, joinKeyAsStr), getDouble(joinKeyAsStr),\n                                redisKey);\n\n                    }\n                    redisFields.clear();\n                }\n\n            }\n            KunderaCoreUtils.printQuery(\"Persist Join Table:\" + tableName, showQuery);\n        }\n        finally\n        {\n            if (pipeline != null)\n            {\n                pipeline.sync();\n            }\n            onCleanup(connection);\n        }\n\n    }\n\n    /**\n     * Returns collection of column values for given join table. TODO: Method is\n     * very much tightly coupled with Join table implementation and does not\n     * serve purpose as it is meant for.\n     * \n     * @param <E>\n     *            the element type\n     * @param schemaName\n     *            the schema name\n     * @param tableName\n     *            the table name\n     * @param pKeyColumnName\n     *            the key column name\n     * @param columnName\n     *            the column name\n     * @param pKeyColumnValue\n     *            the key column value\n     * @param columnJavaType\n     *            the column java type\n     * @return the columns by id\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,\n            Object pKeyColumnValue, Class columnJavaType)\n    {\n        Object connection = null;\n\n        List results = new ArrayList();\n\n        try\n        {\n            connection = getConnection();\n\n            String valueAsStr = PropertyAccessorHelper.getString(pKeyColumnValue);\n\n            Double score = getDouble(valueAsStr);\n\n            Set<String> resultKeys = null;\n            if (resource != null && resource.isActive())\n            {\n                Response response = ((Transaction) connection).zrangeByScore(getHashKey(tableName, valueAsStr), score,\n                        score);\n                // ((Transaction) connection).exec();\n                ((RedisTransaction) resource).onExecute(((Transaction) connection));\n\n                // ((Transaction)\n                // connection).zrangeByScore(getHashKey(tableName, valueAsStr),\n                // score, score);\n                resultKeys = (Set<String>) response.get();\n\n            }\n            else\n            {\n                resultKeys = ((Jedis) connection).zrangeByScore(getHashKey(tableName, valueAsStr), score, score);\n            }\n\n            results = fetchColumn(columnName, connection, results, resultKeys);\n\n            // return connection.hmget(getEncodedBytes(redisKey),\n            // getEncodedBytes(columnName));\n            KunderaCoreUtils.printQuery(\"Get columns by id from:\" + tableName + \" for column:\" + columnName\n                    + \" where value:\" + pKeyColumnValue, showQuery);\n            return results;\n        }\n        finally\n        {\n            onCleanup(connection);\n        }\n    }\n\n    /**\n     * Fetch column.\n     * \n     * @param columnName\n     *            the column name\n     * @param connection\n     *            the connection\n     * @param results\n     *            the results\n     * @param resultKeys\n     *            the result keys\n     * @return the list\n     */\n    private List fetchColumn(String columnName, Object connection, List results, Set<String> resultKeys)\n    {\n        for (String hashKey : resultKeys)\n        {\n            List columnValues = null;\n            if (resource != null && resource.isActive())\n            {\n                Response response = ((Transaction) connection).hmget(hashKey, columnName);\n                // ((Transaction) connection).exec();\n                ((RedisTransaction) resource).onExecute(((Transaction) connection));\n\n                columnValues = (List) response.get();\n            }\n            else\n            {\n                columnValues = ((Jedis) connection).hmget(hashKey, columnName);\n            }\n\n            if (columnValues != null && !columnValues.isEmpty())\n            {\n                results.addAll(columnValues); // Currently returning list of\n                                              // string as known issue\n                                              // with\n                                              // joint table concept!\n            }\n\n        }\n\n        return results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n        Object connection = null;\n\n        try\n        {\n            connection = getConnection();\n            String valueAsStr = PropertyAccessorHelper.getString(columnValue);\n\n            Set<String> results = null;\n\n            if (resource != null && resource.isActive())\n            {\n                Response response = ((Transaction) connection).zrangeByScore(getHashKey(tableName, valueAsStr),\n                        getDouble(valueAsStr), getDouble(valueAsStr));\n                // ((Transaction) connection).exec();\n                ((RedisTransaction) resource).onExecute(((Transaction) connection));\n\n                results = (Set<String>) response.get();\n            }\n            else\n            {\n                results = ((Jedis) connection).zrangeByScore(getHashKey(tableName, valueAsStr), getDouble(valueAsStr),\n                        getDouble(valueAsStr));\n\n            }\n\n            List returnResults = new ArrayList();\n            returnResults = fetchColumn(pKeyName, connection, returnResults, results);\n            if (returnResults != null)\n            {\n\n                return returnResults.toArray(new Object[0]);\n            }\n\n        }\n        finally\n        {\n            onCleanup(connection);\n        }\n\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    @Override\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n        Object connection = null;\n        Pipeline pipeLine = null;\n        try\n        {\n\n            connection = getConnection();\n\n            if (isBoundTransaction())\n            {\n                pipeLine = ((Jedis) connection).pipelined();\n            }\n\n            String valueAsStr = PropertyAccessorHelper.getString(columnValue);\n            Double score = getDouble(valueAsStr);\n            Set<String> results = null;\n            if (resource != null && resource.isActive())\n            {\n                Response response = ((Transaction) connection).zrangeByScore(getHashKey(tableName, valueAsStr), score,\n                        score);\n                // ((Transaction) connection).exec();\n                ((RedisTransaction) resource).onExecute(((Transaction) connection));\n\n                results = (Set<String>) response.get();\n            }\n            else\n            {\n                results = ((Jedis) connection).zrangeByScore(getHashKey(tableName, valueAsStr), score, score);\n            }\n            // Set<String> results =\n            // connection.zrangeByScore(getHashKey(tableName, valueAsStr),\n            // score, score);\n\n            if (results != null)\n            {\n                for (String rowKey : results)\n                {\n                    // byte[] hashKey = getEncodedBytes(getHashKey(tableName,\n                    // rowKey));\n\n                    Map<byte[], byte[]> columns = null;\n                    columns = getColumns(connection, rowKey, columns);\n\n                    for (byte[] column : columns.keySet()) // delete each\n                                                           // column(e.g.\n                    // field)\n                    {\n                        // connection.get(key)\n                        String colName = PropertyAccessorFactory.STRING.fromBytes(String.class, columns.get(column));\n\n                        if (resource != null && resource.isActive())\n                        {\n                            ((Transaction) connection).hdel(getEncodedBytes(rowKey), column); // delete\n                            // record\n                            ((Transaction) connection).zrem(getHashKey(tableName, colName), rowKey); // delete\n                            // inverted\n                            // index.\n\n                        }\n                        else\n                        {\n                            ((Jedis) connection).hdel(getEncodedBytes(rowKey), column); // delete\n                            // record\n                            ((Jedis) connection).zrem(getHashKey(tableName, colName), rowKey); // delete\n                            // inverted\n                            // index.\n\n                        }\n                    }\n                }\n\n            }\n        }\n        finally\n        {\n            if (pipeLine != null)\n            {\n                pipeLine.sync();\n            }\n            onCleanup(connection);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n        Object[] ids = findIdsByColumn(entityMetadata.getTableName(), colName, colValue);\n        List<Object> resultSet = new ArrayList<Object>();\n        if (ids != null)\n        {\n            // just to insure uniqueness.\n\n            for (Object id : new HashSet(Arrays.asList(ids)))\n            {\n                resultSet.add(find(entityClazz, id));\n            }\n        }\n\n        return resultSet;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<RedisQuery> getQueryImplementor()\n    {\n        return RedisQuery.class;\n    }\n\n    /**\n     * To supply configurations for jedis connection.\n     * \n     * @param configurations\n     *            the configurations\n     */\n    public void setConfig(Map<String, Object> configurations)\n    {\n        this.settings = configurations;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.api.Batcher#addBatch(com.impetus.kundera\n     * .graph.Node)\n     */\n    @Override\n    public void addBatch(Node node)\n    {\n        if (node != null)\n        {\n            nodes.add(node);\n        }\n\n        onBatchLimit();\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#executeBatch()\n     */\n    @Override\n    public int executeBatch()\n    {\n        Object connection = getConnection();\n        // Create a hashset and populate data into it\n        Pipeline pipeLine = null;\n        if (isBoundTransaction())\n        {\n            pipeLine = ((Jedis) connection).pipelined();\n        }\n        try\n        {\n            for (Node node : nodes)\n            {\n                if (node.isDirty())\n                {\n                    node.handlePreEvent();\n                    // delete can not be executed in batch\n                    if (node.isInState(RemovedState.class))\n                    {\n                        onDelete(node.getData(), node.getEntityId(), pipeLine != null ? pipeLine : connection);\n                    }\n                    else\n                    {\n\n                        List<RelationHolder> relationHolders = getRelationHolders(node);\n                        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                                node.getDataClass());\n\n                        onPersist(metadata, node.getData(), node.getEntityId(), relationHolders,\n                                pipeLine != null ? pipeLine : connection);\n                    }\n                    node.handlePostEvent();\n                }\n            }\n        }\n        finally\n        {\n            //\n            if (pipeLine != null)\n            {\n                pipeLine.sync(); // send I/O.. as persist call. so no need to\n                                 // read\n                // response?\n            }\n            onCleanup(connection);\n        }\n\n        return nodes.size();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#getBatchSize()\n     */\n    @Override\n    public int getBatchSize()\n    {\n        return batchSize;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.api.Batcher#clear()\n     */\n    @Override\n    public void clear()\n    {\n        if (nodes != null)\n        {\n            nodes.clear();\n            nodes = new ArrayList<Node>();\n        }\n    }\n\n    /**\n     * Find ids by column.\n     * \n     * @param tableName\n     *            the table name\n     * @param columnName\n     *            the column name\n     * @param columnValue\n     *            the column value\n     * @return the object[]\n     */\n    private Object[] findIdsByColumn(String tableName, String columnName, Object columnValue)\n    {\n        Object connection = null;\n\n        try\n        {\n            connection = getConnection();\n            String valueAsStr = PropertyAccessorHelper.getString(columnValue);\n\n            Set<String> results = null;\n\n            if (resource != null && resource.isActive())\n            {\n                Response response = ((Transaction) connection).zrangeByScore(getHashKey(tableName, columnName),\n                        getDouble(valueAsStr), getDouble(valueAsStr));\n                // ((Transaction) connection).exec();\n                ((RedisTransaction) resource).onExecute(((Transaction) connection));\n\n                results = (Set<String>) response.get();\n            }\n            else\n            {\n                results = ((Jedis) connection).zrangeByScore(getHashKey(tableName, columnName), getDouble(valueAsStr),\n                        getDouble(valueAsStr));\n\n            }\n            if (results != null)\n            {\n                return results.toArray(new Object[0]);\n            }\n\n        }\n        finally\n        {\n            onCleanup(connection);\n        }\n\n        return null;\n    }\n\n    /**\n     * Check on batch limit.\n     */\n    private void onBatchLimit()\n    {\n        if (batchSize > 0 && batchSize == nodes.size())\n        {\n            executeBatch();\n            nodes.clear();\n        }\n    }\n\n    /**\n     * Attribute wrapper.\n     * \n     * @author vivek.mishra\n     * \n     */\n    class AttributeWrapper\n    {\n\n        /** The columns. */\n        private Map<byte[], byte[]> columns;\n\n        /** The indexes. */\n        private Map<String, Double> indexes;\n\n        /**\n         * Instantiates a new attribute wrapper.\n         */\n        private AttributeWrapper()\n        {\n            columns = new HashMap<byte[], byte[]>();\n\n            indexes = new HashMap<String, Double>();\n        }\n\n        /**\n         * Instantiates a new attribute wrapper.\n         * \n         * @param size\n         *            the size\n         */\n        AttributeWrapper(int size)\n        {\n            columns = new HashMap<byte[], byte[]>(size);\n\n            indexes = new HashMap<String, Double>(size);\n        }\n\n        /**\n         * Adds the column.\n         * \n         * @param key\n         *            the key\n         * @param value\n         *            the value\n         */\n        private void addColumn(byte[] key, byte[] value)\n        {\n            columns.put(key, value);\n        }\n\n        /**\n         * Adds the index.\n         * \n         * @param key\n         *            the key\n         * @param score\n         *            the score\n         */\n        private void addIndex(String key, Double score)\n        {\n            indexes.put(key, score);\n        }\n\n        /**\n         * Gets the columns.\n         * \n         * @return the columns\n         */\n        Map<byte[], byte[]> getColumns()\n        {\n            return columns;\n        }\n\n        /**\n         * Gets the indexes.\n         * \n         * @return the indexes\n         */\n        Map getIndexes()\n        {\n            return indexes;\n        }\n\n    }\n\n    /**\n     * Returns hash key.\n     * \n     * @param tableName\n     *            table name\n     * @param rowKey\n     *            row key\n     * @return concatenated hash key\n     */\n    private String getHashKey(final String tableName, final String rowKey)\n    {\n        StringBuilder builder = new StringBuilder(tableName);\n        builder.append(\":\");\n        builder.append(rowKey);\n        return builder.toString();\n    }\n\n    /**\n     * Returns encoded bytes.\n     * \n     * @param name\n     *            field name.\n     * @return encoded byte array.\n     */\n    byte[] getEncodedBytes(final String name)\n    {\n        try\n        {\n            if (name != null)\n            {\n                return name.getBytes(Constants.CHARSET_UTF8);\n            }\n        }\n        catch (UnsupportedEncodingException e)\n        {\n            logger.error(\"Error during persist, Caused by:\", e);\n            throw new PersistenceException(e);\n        }\n\n        return null;\n    }\n\n    /**\n     * Add inverted index in sorted set.\n     * \n     * @param connection\n     *            redis connection instance\n     * @param wrapper\n     *            attribute wrapper.\n     * @param rowKey\n     *            row key to be stor\n     * @param metadata\n     *            the metadata\n     */\n    private void addIndex(final Object connection, final AttributeWrapper wrapper, final String rowKey,\n            final EntityMetadata metadata)\n    {\n\n        Indexer indexer = indexManager.getIndexer();\n\n        if (indexer != null && indexer.getClass().getSimpleName().equals(\"RedisIndexer\"))\n        {\n            // Add row key to list(Required for wild search over table).\n            wrapper.addIndex(\n                    getHashKey(metadata.getTableName(),\n                            ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName()), getDouble(rowKey));\n\n            // Add row-key as inverted index as well needed for multiple clause\n            // search with key and non row key.\n            wrapper.addIndex(\n                    getHashKey(metadata.getTableName(),\n                            getHashKey(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName(), rowKey)),\n                    getDouble(rowKey));\n\n            indexer.index(metadata.getEntityClazz(), metadata, wrapper.getIndexes(), rowKey, null);\n        }\n    }\n\n    /**\n     * Deletes inverted indexes from redis.\n     * \n     * @param connection\n     *            redis instance.\n     * @param wrapper\n     *            attribute wrapper\n     * @param member\n     *            sorted set member name.\n     */\n\n    private void unIndex(final Object connection, final AttributeWrapper wrapper, final String member)\n    {\n        Set<String> keys = wrapper.getIndexes().keySet();\n        for (String key : keys)\n        {\n            if (resource != null && resource.isActive())\n            {\n                ((Transaction) connection).zrem(key, member);\n\n            }\n            else\n            {\n                ((Pipeline) connection).zrem(key, member);\n\n            }\n        }\n    }\n\n    /**\n     * On release connection.\n     * \n     * @param connection\n     *            redis connection instance.\n     */\n    private void onCleanup(Object connection)\n    {\n        // if not running within transaction boundary\n        if (this.connection != null)\n        {\n            if (settings != null)\n            {\n                ((Jedis) connection).configResetStat();\n            }\n            factory.releaseConnection((Jedis) this.connection);\n        }\n\n        this.connection = null;\n    }\n\n    /*    *//**\n     * Prepares composite key as a redis key.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @return redis key\n     */\n    /*\n     * private String prepareCompositeKey(final EntityMetadata m, final\n     * MetamodelImpl metaModel, final Object compositeKey) { // EmbeddableType\n     * keyObject = //\n     * metaModel.embeddable(m.getIdAttribute().getBindableJavaType());\n     * \n     * Field[] fields =\n     * m.getIdAttribute().getBindableJavaType().getDeclaredFields();\n     * \n     * StringBuilder stringBuilder = new StringBuilder(); for (Field f : fields)\n     * { if (!ReflectUtils.isTransientOrStatic(f)) { // Attribute\n     * compositeColumn = // keyObject.getAttribute(f.getName()); try { String\n     * fieldValue = PropertyAccessorHelper.getString(compositeKey, f); // field\n     * // value stringBuilder.append(fieldValue);\n     * stringBuilder.append(COMPOSITE_KEY_SEPERATOR); } catch\n     * (IllegalArgumentException e) {\n     * logger.error(\"Error during persist, Caused by:\", e); throw new\n     * PersistenceException(e); } } }\n     * \n     * if (stringBuilder.length() > 0) {\n     * stringBuilder.deleteCharAt(stringBuilder\n     * .lastIndexOf(COMPOSITE_KEY_SEPERATOR)); } return\n     * stringBuilder.toString(); }\n     */\n    /**\n     * Wraps entity attributes into byte[] and return instance of attribute\n     * wrapper.\n     * \n     * @param entityMetadata\n     * @param entity\n     * @return\n     */\n    private AttributeWrapper wrap(EntityMetadata entityMetadata, Object entity)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n\n        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n        Set<Attribute> attributes = entityType.getAttributes();\n\n        // attributes can be null??? i guess NO\n        AttributeWrapper wrapper = new AttributeWrapper(attributes.size());\n\n        List<String> relationNames = entityMetadata.getRelationNames();\n\n        // PropertyAccessorHelper.get(entity,\n        for (Attribute attr : attributes)\n        {\n            if (/* !entityMetadata.getIdAttribute().equals(attr) && */!attr.isAssociation())\n            {\n                if (metaModel.isEmbeddable(((AbstractAttribute) attr).getBindableJavaType()))\n                {\n                    EmbeddableType embeddableAttribute = metaModel.embeddable(((AbstractAttribute) attr)\n                            .getBindableJavaType());\n\n                    Object embeddedObject = PropertyAccessorHelper.getObject(entity, (Field) attr.getJavaMember());\n\n                    Set<Attribute> embeddedAttributes = embeddableAttribute.getAttributes();\n\n                    for (Attribute attrib : embeddedAttributes)\n                    {\n                        addToWrapper(entityMetadata, wrapper, embeddedObject, attrib, attr);\n                    }\n\n                }\n                else\n                {\n                    addToWrapper(entityMetadata, wrapper, entity, attr);\n                }\n            }\n            else if (attributes.size() == 1) // means it is only a key! weird\n                                             // but possible negative\n                                             // scenario\n            {\n                byte[] value = PropertyAccessorHelper.get(entity, (Field) attr.getJavaMember());\n                byte[] name;\n                name = getEncodedBytes(((AbstractAttribute) attr).getJPAColumnName());\n\n                // add column name as key and value as value\n                wrapper.addColumn(name, value);\n\n            }\n        }\n\n        return wrapper;\n    }\n\n    /**\n     * Adds field to wrapper.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param wrapper\n     *            the wrapper\n     * @param resultedObject\n     *            the resulted object\n     * @param attrib\n     *            the attrib\n     */\n    private void addToWrapper(EntityMetadata entityMetadata, AttributeWrapper wrapper, Object resultedObject,\n            Attribute attrib)\n    {\n        addToWrapper(entityMetadata, wrapper, resultedObject, attrib, null);\n    }\n\n    /**\n     * Wraps entity attributes into redis format byte[].\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param wrapper\n     *            the wrapper\n     * @param embeddedObject\n     *            the embedded object\n     * @param attrib\n     *            the attrib\n     * @param embeddedAttrib\n     *            the embedded attrib\n     */\n    private void addToWrapper(EntityMetadata entityMetadata, AttributeWrapper wrapper, Object embeddedObject,\n            Attribute attrib, Attribute embeddedAttrib)\n    {\n        if (embeddedObject == null)\n        {\n            return;\n        }\n        \n        byte[] value = PropertyAccessorHelper.get(embeddedObject, (Field) attrib.getJavaMember());\n        byte[] name;\n        if (value != null)\n        {\n            if (embeddedAttrib == null)\n            {\n                name = getEncodedBytes(((AbstractAttribute) attrib).getJPAColumnName());\n            }\n            else\n            {\n                name = getEncodedBytes(getHashKey(embeddedAttrib.getName(),\n                        ((AbstractAttribute) attrib).getJPAColumnName()));\n            }\n            // add column name as key and value as value\n            wrapper.addColumn(name, value);\n            // // {tablename:columnname,hashcode} for value\n\n            // selective indexing.\n            if (entityMetadata.getIndexProperties().containsKey(((AbstractAttribute) attrib).getJPAColumnName()))\n            {\n                String valueAsStr = PropertyAccessorHelper.getString(embeddedObject, (Field) attrib.getJavaMember());\n                wrapper.addIndex(\n                        getHashKey(entityMetadata.getTableName(), ((AbstractAttribute) attrib).getJPAColumnName()),\n                        getDouble(valueAsStr));\n\n                wrapper.addIndex(\n                        getHashKey(entityMetadata.getTableName(),\n                                getHashKey(((AbstractAttribute) attrib).getJPAColumnName(), valueAsStr)),\n                        getDouble(valueAsStr));\n            }\n        }\n    }\n\n    /**\n     * Unwraps redis results into entity.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param results\n     *            the results\n     * @param key\n     *            the key\n     * @return the object\n     * @throws InstantiationException\n     *             the instantiation exception\n     * @throws IllegalAccessException\n     *             the illegal access exception\n     */\n    private Object unwrap(EntityMetadata entityMetadata, Map<byte[], byte[]> results, Object key)\n            throws InstantiationException, IllegalAccessException\n    {\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n\n        List<String> relationNames = entityMetadata.getRelationNames();\n        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n\n        Map<String, Object> relations = new HashMap<String, Object>();\n        Object entity = null;\n\n        // Set<Attribute> attributes = entityType.getAttributes();\n\n        Set<byte[]> columnNames = results.keySet();\n        for (byte[] nameInByte : columnNames)\n        {\n            if (entity == null)\n            {\n                entity = KunderaCoreUtils.createNewInstance(entityMetadata.getEntityClazz());\n            }\n\n            String columnName = PropertyAccessorFactory.STRING.fromBytes(String.class, nameInByte);\n\n            byte[] value = results.get(nameInByte);\n            String discriminatorColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n\n            if (columnName != null && !columnName.equals(discriminatorColumn))\n            {\n                String fieldName = entityMetadata.getFieldName(columnName);\n\n                if (fieldName != null)\n                {\n                    Attribute attribute = entityType.getAttribute(fieldName);\n\n                    if (relationNames != null && relationNames.contains(columnName))\n                    {\n                        Field field = (Field) attribute.getJavaMember();\n                        EntityMetadata associationMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,\n                                ((AbstractAttribute) attribute).getBindableJavaType());\n                        relations.put(columnName, PropertyAccessorHelper.getObject(associationMetadata.getIdAttribute()\n                                .getBindableJavaType(), value));\n                    }\n                    else\n                    {\n                        PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), value);\n                    }\n                }\n                else\n                {\n                    // means it might be an embeddable field, if not simply omit\n                    // this field.\n\n                    if (StringUtils.contains(columnName, \":\"))\n                    {\n                        StringTokenizer tokenizer = new StringTokenizer(columnName, \":\");\n                        while (tokenizer.hasMoreTokens())\n                        {\n                            String embeddedFieldName = tokenizer.nextToken();\n                            String embeddedColumnName = tokenizer.nextToken();\n\n                            Map<String, EmbeddableType> embeddables = metaModel.getEmbeddables(entityMetadata\n                                    .getEntityClazz());\n\n                            EmbeddableType embeddableAttribute = embeddables.get(embeddedFieldName);\n                            \n                            AbstractAttribute attrib = null;\n                            Iterator itr = embeddableAttribute.getAttributes().iterator();\n                            while (itr.hasNext())\n                            {\n                                attrib = (AbstractAttribute) itr.next();\n                                if (attrib.getJPAColumnName().equals(embeddedColumnName))\n                                {\n                                    break;\n                                }\n                            }\n\n                            Object embeddedObject = PropertyAccessorHelper.getObject(entity, (Field) entityType\n                                    .getAttribute(embeddedFieldName).getJavaMember());\n\n                            if (embeddedObject == null)\n                            {\n                                embeddedObject = KunderaCoreUtils.createNewInstance(((AbstractAttribute) entityType\n                                        .getAttribute(embeddedFieldName)).getBindableJavaType());\n\n                                PropertyAccessorHelper.set(entity, (Field) entityType.getAttribute(embeddedFieldName)\n                                        .getJavaMember(), embeddedObject);\n                            }\n\n                            PropertyAccessorHelper.set(embeddedObject, (Field) attrib.getJavaMember(), value);\n                            // PropertyAccessorHelper.\n\n                        }\n                    }\n                    // It might be a case of embeddable attribute.\n\n                }\n            }\n\n        }\n\n        if (entity != null)\n        {\n            Class javaType = entityMetadata.getIdAttribute().getBindableJavaType();\n\n            if (!metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())\n                    && key.getClass().isAssignableFrom(String.class) && !key.getClass().equals(javaType))\n            {\n                key = PropertyAccessorFactory.getPropertyAccessor(javaType).fromString(javaType, key.toString());\n            }\n//            PropertyAccessorHelper.set(entity, (Field) entityMetadata.getIdAttribute().getJavaMember(), key);\n        }\n        if (!relations.isEmpty())\n        {\n            return new EnhanceEntity(entity, key, relations);\n        }\n\n        return entity;\n    }\n\n    /**\n     * On execute query.\n     * \n     * @param queryParameter\n     *            the query parameter\n     * @param entityClazz\n     *            the entity clazz\n     * @return the list\n     */\n    List onExecuteQuery(RedisQueryInterpreter queryParameter, Class entityClazz)\n    {\n        /**\n         * Find a list of id's and then call findById for each!\n         */\n        Object connection = null;\n        List<Object> results = new ArrayList<Object>();\n        try\n        {\n            connection = getConnection();\n            Set<String> rowKeys = new HashSet<String>();\n            EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);\n            String printQuery = null;\n\n            if (showQuery)\n            {\n                printQuery = \"Fetching primary key from \" + entityMetadata.getTableName() + \" corresponding to \";\n            }\n\n            if (queryParameter.getClause() != null && !queryParameter.isByRange())\n            {\n                String destStore = entityClazz.getSimpleName() + System.currentTimeMillis();\n\n                Map<String, Object> fieldSets = queryParameter.getFields();\n\n                Set<String> keySets = new HashSet<String>(fieldSets.size());\n                // byte[][] keys = new byte[][fieldSets.size()];\n                for (String column : fieldSets.keySet())\n                {\n                    String valueAsStr = PropertyAccessorHelper.getString(fieldSets.get(column));\n                    String key = getHashKey(entityMetadata.getTableName(), getHashKey(column, valueAsStr));\n                    keySets.add(key);\n                    if (showQuery)\n                    {\n                        printQuery = printQuery + key + \" and \";\n                    }\n                }\n\n                if (showQuery)\n                {\n                    printQuery = printQuery.substring(0, printQuery.lastIndexOf(\" and \"));\n                }\n\n                if (queryParameter.getClause().equals(Clause.INTERSECT))\n                {\n                    KunderaCoreUtils.printQuery(printQuery, showQuery);\n\n                    if (resource != null && resource.isActive())\n                    {\n                        ((Transaction) connection).zinterstore(destStore, keySets.toArray(new String[] {}));\n                    }\n                    else\n                    {\n                        ((Jedis) connection).zinterstore(destStore, keySets.toArray(new String[] {}));\n                    }\n                }\n                else\n                {\n                    if (showQuery)\n                    {\n                        KunderaCoreUtils.printQuery(printQuery.replaceAll(\"and\", \"or\"), showQuery);\n                    }\n\n                    if (resource != null && resource.isActive())\n                    {\n                        ((Transaction) connection).zunionstore(destStore, keySets.toArray(new String[] {}));\n                    }\n                    else\n                    {\n                        ((Jedis) connection).zunionstore(destStore, keySets.toArray(new String[] {}));\n                    }\n                }\n\n                if (resource != null && resource.isActive())\n                {\n                    Response response = ((Transaction) connection).zrange(destStore, 0, -1);\n                    // ((Transaction) connection).exec();\n                    ((RedisTransaction) resource).onExecute(((Transaction) connection));\n\n                    rowKeys = (Set<String>) response.get();\n                    // connection = reInitialize(connection, rowKeys);\n                    //\n                    // ((Transaction) connection).del(destStore);\n\n                }\n                else\n                {\n                    rowKeys = ((Jedis) connection).zrange(destStore, 0, -1);\n                    ((Jedis) connection).del(destStore);\n                }\n\n                // delete intermediate store after find.\n                //\n                // means it is a query over sorted set.\n            }\n            else if (queryParameter.isByRange())\n            {\n                // means query over a single sorted set with range\n                Map<String, Double> minimum = queryParameter.getMin();\n                Map<String, Double> maximum = queryParameter.getMax();\n\n                String column = minimum.keySet().iterator().next();\n                KunderaCoreUtils.printQuery(printQuery + column + \" between \" + minimum + \" and \" + maximum, showQuery);\n                if (resource != null && resource.isActive())\n                {\n                    Response response = ((Transaction) connection)\n                            .zrangeByScore(getHashKey(entityMetadata.getTableName(), column), minimum.get(column),\n                                    maximum.get(column));\n                    // ((Transaction) connection).exec();\n                    ((RedisTransaction) resource).onExecute(((Transaction) connection));\n\n                    rowKeys = (Set<String>) response.get();\n                    // connection = reInitialize(connection, rowKeys);\n                }\n                else\n                {\n                    rowKeys = ((Jedis) connection).zrangeByScore(getHashKey(entityMetadata.getTableName(), column),\n                            minimum.get(column), maximum.get(column));\n                }\n            }\n            else if (queryParameter.isById())\n            {\n                Map<String, Object> fieldSets = queryParameter.getFields();\n\n                results = findAllColumns(entityClazz, (queryParameter.getColumns() != null ? queryParameter\n                        .getColumns().toArray(new byte[][] {}) : null), fieldSets.values().toArray());\n                return results;\n            }\n            else if (queryParameter.getFields() != null)\n            {\n                Set<String> columns = queryParameter.getFields().keySet();\n\n                for (String column : columns)\n                {\n                    // ideally it will always be 1 value in map, else it will go\n                    // it queryParameter.getClause() will not be null!\n                    Double value = getDouble(PropertyAccessorHelper.getString(queryParameter.getFields().get(column)));\n                    if (resource != null && resource.isActive())\n                    {\n                        Response response = ((Transaction) connection).zrangeByScore(\n                                getHashKey(entityMetadata.getTableName(), column), value, value);\n                        // ((Transaction) connection).exec();\n                        ((RedisTransaction) resource).onExecute(((Transaction) connection));\n\n                        rowKeys = (Set<String>) response.get();\n                        // connection = reInitialize(connection, rowKeys);\n\n                    }\n                    else\n                    {\n                        rowKeys = ((Jedis) connection).zrangeByScore(getHashKey(entityMetadata.getTableName(), column),\n                                value, value);\n                    }\n                }\n            }\n            else\n            {\n                if (resource != null && resource.isActive())\n                {\n                    Response response = ((Transaction) connection).zrange(\n                            getHashKey(entityMetadata.getTableName(),\n                                    ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), 0, -1);\n                    // resource.onCommit()\n                    // ((Transaction) connection).exec();\n                    ((RedisTransaction) resource).onExecute(((Transaction) connection));\n\n                    rowKeys = new HashSet<String>((Collection<? extends String>) response.get());\n                }\n                else\n                {\n                    rowKeys = new HashSet<String>(((Jedis) connection).zrange(\n                            getHashKey(entityMetadata.getTableName(),\n                                    ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), 0, -1));\n                }\n            }\n\n            for (String k : rowKeys)\n            {\n                connection = reInitialize(connection, rowKeys);\n                Object record = fetch(entityClazz, k, connection, (queryParameter.getColumns() != null ? queryParameter\n                        .getColumns().toArray(new byte[][] {}) : null));\n                if (record != null)\n                {\n                    results.add(record);\n                }\n            }\n\n        }\n        catch (InstantiationException e)\n        {\n            logger.error(\"Error during persist, Caused by:\", e);\n            throw new PersistenceException(e);\n        }\n        catch (IllegalAccessException e)\n        {\n            logger.error(\"Error during persist, Caused by:\", e);\n            throw new PersistenceException(e);\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Error during persist, Caused by:\", e);\n            throw new PersistenceException(e);\n        }\n        finally\n        {\n            onCleanup(connection);\n\n        }\n\n        return results;\n    }\n\n    /**\n     * Re initialize.\n     * \n     * @param connection\n     *            the connection\n     * @param rowKeys\n     *            the row keys\n     * @return the object\n     */\n    private Object reInitialize(Object connection, Set<String> rowKeys)\n    {\n        /*\n         * if(!rowKeys.isEmpty()) {\n         */\n        connection = getConnection();\n        // }\n        return connection;\n    }\n\n    /**\n     * Find all columns.\n     * \n     * @param <E>\n     *            the element type\n     * @param entityClass\n     *            the entity class\n     * @param columns\n     *            the columns\n     * @param keys\n     *            the keys\n     * @return the list\n     */\n    private <E> List<E> findAllColumns(Class<E> entityClass, byte[][] columns, Object... keys)\n    {\n        Object connection = getConnection();\n        // connection.co\n        List results = new ArrayList();\n        try\n        {\n            for (Object key : keys)\n            {\n                Object result = fetch(entityClass, key, connection, columns);\n                if (result != null)\n                {\n                    results.add(result);\n                }\n            }\n        }\n        catch (InstantiationException e)\n        {\n            logger.error(\"Error during find by key:\", e);\n            throw new PersistenceException(e);\n        }\n        catch (IllegalAccessException e)\n        {\n            logger.error(\"Error during find by key:\", e);\n            throw new PersistenceException(e);\n        }\n        return results;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientPropertiesSetter#populateClientProperties\n     * (com.impetus.kundera.client.Client, java.util.Map)\n     */\n    @Override\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        setConfig(properties);\n        for (String key : properties.keySet())\n        {\n            Object value = properties.get(key);\n            if (key.equals(PersistenceProperties.KUNDERA_BATCH_SIZE) && value instanceof Integer)\n            {\n                Integer batchSize = (Integer) value;\n                ((RedisClient) client).setBatchSize(batchSize);\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.TransactionBinder#bind(com.impetus.kundera\n     * .persistence.TransactionResource)\n     */\n    @Override\n    public void bind(TransactionResource resource)\n    {\n        // Not checking for type of TransactionRes\n        if (resource != null && resource instanceof RedisTransaction)\n        {\n            this.resource = resource;\n        }\n        else\n        {\n            throw new KunderaTransactionException(\"Invalid transaction resource provided:\" + resource\n                    + \" Should have been an instance of :\" + RedisTransaction.class);\n        }\n    }\n\n    /**\n     * Returns jedis connection.\n     * \n     * @return jedis resource.\n     */\n    private Object getConnection()\n    {\n        /*\n         * Jedis connection = factory.getConnection();\n         * \n         * // If resource is not null means a transaction in progress.\n         * \n         * if (settings != null) { for (String key : settings.keySet()) {\n         * connection.configSet(key, settings.get(key).toString()); } }\n         * \n         * if (resource != null && resource.isActive()) { return\n         * ((RedisTransaction) resource).bindResource(connection); } else {\n         * return connection; } if (resource == null || (resource != null &&\n         * !resource.isActive()))\n         */\n        // means either transaction resource is not bound or it is not active,\n        // but connection has already by initialized\n        if (isBoundTransaction() && this.connection != null)\n        {\n            return this.connection;\n        }\n\n        // if running within transaction boundary.\n        if (resource != null && resource.isActive())\n        {\n            // no need to get a connection from pool, as nested MULTI is not yet\n            // supported.\n            if (((RedisTransaction) resource).isResourceBound())\n            {\n                return ((RedisTransaction) resource).getResource();\n            }\n            else\n            {\n                Jedis conn = getAndSetConnection();\n                return ((RedisTransaction) resource).bindResource(conn);\n            }\n\n        }\n        else\n        {\n            Jedis conn = getAndSetConnection();\n            return conn;\n        }\n    }\n\n    /**\n     * Gets the and set connection.\n     * \n     * @return the and set connection\n     */\n    private Jedis getAndSetConnection()\n    {\n        Jedis conn = factory.getConnection();\n        this.connection = conn;\n        // If resource is not null means a transaction in progress.\n\n        if (settings != null)\n        {\n            for (String key : settings.keySet())\n            {\n                conn.configSet(key, settings.get(key).toString());\n            }\n        }\n        return conn;\n    }\n\n    /**\n     * Sets the batch size.\n     * \n     * @param persistenceUnit\n     *            the persistence unit\n     * @param puProperties\n     *            the pu properties\n     */\n    private void setBatchSize(String persistenceUnit, Map<String, Object> puProperties)\n    {\n        String batch_Size = null;\n        if (puProperties != null)\n        {\n            batch_Size = puProperties != null ? (String) puProperties.get(PersistenceProperties.KUNDERA_BATCH_SIZE)\n                    : null;\n            if (batch_Size != null)\n            {\n                setBatchSize(Integer.valueOf(batch_Size));\n            }\n        }\n        else if (batch_Size == null)\n        {\n            PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,\n                    persistenceUnit);\n            setBatchSize(puMetadata.getBatchSize());\n        }\n    }\n\n    /**\n     * Sets the batch size.\n     * \n     * @param batch_Size\n     *            the new batch size\n     */\n    private void setBatchSize(int batch_Size)\n    {\n        this.batchSize = batch_Size;\n    }\n\n    /**\n     * On persist.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @param id\n     *            the id\n     * @param rlHolders\n     *            the rl holders\n     * @param connection\n     *            the connection\n     */\n    private void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders,\n            Object connection)\n    {\n        // first open a pipeline\n        AttributeWrapper wrapper = wrap(entityMetadata, entity);\n\n        // add relations.\n\n        if (rlHolders != null)\n        {\n            for (RelationHolder relation : rlHolders)\n            {\n                String name = relation.getRelationName();\n                Object value = relation.getRelationValue();\n                byte[] valueInBytes = PropertyAccessorHelper.getBytes(value);\n                byte[] nameInBytes = getEncodedBytes(name);\n                String valueAsStr = PropertyAccessorHelper.getString(value);\n                wrapper.addColumn(nameInBytes, valueInBytes);\n                wrapper.addIndex(getHashKey(entityMetadata.getTableName(), name), getDouble(valueAsStr));\n\n                // this index is required to work for UNION/INTERSECT\n                // support.\n\n                wrapper.addIndex(getHashKey(entityMetadata.getTableName(), getHashKey(name, valueAsStr)),\n                        getDouble(valueAsStr));\n            }\n        }\n\n        // prepareCompositeKey\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n\n        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());\n        String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();\n        String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();\n\n        // No need to check for empty or blank, as considering it as valid name\n        // for nosql!\n        if (discrColumn != null && discrValue != null)\n        {\n            byte[] valueInBytes = PropertyAccessorHelper.getBytes(discrValue);\n            byte[] nameInBytes = getEncodedBytes(discrColumn);\n            wrapper.addColumn(nameInBytes, valueInBytes);\n            wrapper.addIndex(getHashKey(entityMetadata.getTableName(), discrColumn), getDouble(discrValue));\n            wrapper.addIndex(getHashKey(entityMetadata.getTableName(), getHashKey(discrColumn, discrValue)),\n                    getDouble(discrValue));\n        }\n\n        String rowKey = null;\n        if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n        {\n            rowKey = KunderaCoreUtils.prepareCompositeKey(entityMetadata, id);\n        }\n        else\n        {\n            ObjectAccessor accessor = new ObjectAccessor();\n            rowKey = accessor.toString(id);\n            // rowKey = /*PropertyAccessorHelper.getString(entity, (Field)\n            // entityMetadata.getIdAttribute().getJavaMember())*/ ;\n        }\n\n        String hashKey = getHashKey(entityMetadata.getTableName(), rowKey);\n\n        if (resource != null && resource.isActive())\n        {\n            ((Transaction) connection).hmset(getEncodedBytes(hashKey), wrapper.getColumns());\n        }\n        else\n        {\n            ((Pipeline) connection).hmset(getEncodedBytes(hashKey), wrapper.getColumns());\n        }\n\n        // Add inverted indexes for column based search.\n\n        // // Add row key to list(Required for wild search over table).\n        //\n        // wrapper.addIndex(getHashKey(entityMetadata.getTableName(),\n        // ((AbstractAttribute)\n        // entityMetadata.getIdAttribute()).getJPAColumnName()),\n        // getDouble(rowKey));\n        //\n        // // Add row-key as inverted index as well needed for multiple clause\n        // // search with key and non row key.\n        // wrapper.addIndex(getHashKey(\n        // entityMetadata.getTableName(),\n        // getHashKey(((AbstractAttribute)\n        // entityMetadata.getIdAttribute()).getJPAColumnName(), rowKey)),\n        // getDouble(rowKey));\n        KunderaCoreUtils.printQuery(\n                \"Persist data into \" + entityMetadata.getSchema() + \".\" + entityMetadata.getTableName()\n                        + \" for primary key \" + rowKey, showQuery);\n        addIndex(connection, wrapper, rowKey, entityMetadata);\n\n    }\n\n    /**\n     * On delete.\n     * \n     * @param entity\n     *            the entity\n     * @param pKey\n     *            the key\n     * @param connection\n     *            the connection\n     */\n    private void onDelete(Object entity, Object pKey, Object connection)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        AttributeWrapper wrapper = wrap(entityMetadata, entity);\n\n        Set<byte[]> columnNames = wrapper.columns.keySet();\n\n        String rowKey = null;\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                entityMetadata.getPersistenceUnit());\n\n        if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))\n        {\n            rowKey = KunderaCoreUtils.prepareCompositeKey(entityMetadata, pKey);\n        }\n        else\n        {\n            rowKey = PropertyAccessorHelper.getString(entity, (Field) entityMetadata.getIdAttribute().getJavaMember());\n        }\n\n        for (byte[] name : columnNames)\n        {\n            if (resource != null && resource.isActive())\n            {\n                ((Transaction) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey),\n                        PropertyAccessorFactory.STRING.fromBytes(String.class, name));\n\n            }\n            else\n            {\n                ((Pipeline) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey),\n                        PropertyAccessorFactory.STRING.fromBytes(String.class, name));\n\n            }\n        }\n\n        // Delete relation values.\n\n        deleteRelation(connection, entityMetadata, rowKey);\n\n        // Delete inverted indexes.\n        unIndex(connection, wrapper, rowKey);\n\n        if (resource != null && resource.isActive())\n        {\n            ((Transaction) connection).zrem(\n                    getHashKey(entityMetadata.getTableName(),\n                            ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), rowKey);\n\n        }\n        else\n        {\n            ((Pipeline) connection).zrem(\n                    getHashKey(entityMetadata.getTableName(),\n                            ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), rowKey);\n\n        }\n        KunderaCoreUtils.printQuery(\"Delete data from:\" + entityMetadata.getTableName() + \"for primary key: \" + rowKey,\n                showQuery);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientBase#indexNode(com.impetus.kundera.graph\n     * .Node, com.impetus.kundera.metadata.model.EntityMetadata)\n     */\n    @Override\n    protected void indexNode(Node node, EntityMetadata entityMetadata)\n    {\n        // Do nothing as\n        if (this.indexManager.getIndexer() != null\n                && !this.indexManager.getIndexer().getClass().getSimpleName().equals(\"RedisIndexer\"))\n        {\n            super.indexNode(node, entityMetadata);\n        }\n    }\n\n    /**\n     * Initialize indexer.\n     */\n    private void initializeIndexer()\n    {\n        if (this.indexManager.getIndexer() != null\n                && this.indexManager.getIndexer().getClass().getSimpleName().equals(\"RedisIndexer\"))\n        {\n            ((RedisIndexer) this.indexManager.getIndexer()).assignConnection(getConnection());\n        }\n    }\n\n    /**\n     * Checks if is bound transaction.\n     * \n     * @return true, if is bound transaction\n     */\n    private boolean isBoundTransaction()\n    {\n        return resource == null || (resource != null && !resource.isActive());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        return (Generator) KunderaCoreUtils.createNewInstance(RedisIdGenerator.class);\n    }\n\n}"
  },
  {
    "path": "src/kundera-redis/src/main/java/com/impetus/client/redis/RedisClientFactory.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.redis;\n\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport redis.clients.jedis.Jedis;\nimport redis.clients.jedis.JedisPool;\nimport redis.clients.jedis.JedisPoolConfig;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * Default client factory implementation for REDIS <a>redis.io</a>\n * \n * @author vivek.mishra\n */\npublic class RedisClientFactory extends GenericClientFactory\n{\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(RedisClientFactory.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.GenericClientFactory#initialize()\n     */\n    /**\n     * Initialize redis client factory.\n     */\n    @Override\n    public void initialize(Map<String, Object> externalProperty)\n    {\n        setExternalProperties(externalProperty);\n        initializePropertyReader();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#createPoolOrConnection()\n     */\n    @Override\n    protected Object createPoolOrConnection()\n    {\n        logger.info(\"Initializing Redis connection pool\");\n\n        final byte WHEN_EXHAUSTED_FAIL = 0;\n\n        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(\n                getPersistenceUnit());\n\n        Properties props = puMetadata.getProperties();\n        String contactNode = null;\n        String defaultPort = null;\n        String password = null;\n        String maxActivePerNode = null;\n        String maxIdlePerNode = null;\n        String minIdlePerNode = null;\n        String maxTotal = null;\n        String txTimeOut = null;\n\n        if (externalProperties != null)\n        {\n            contactNode = (String) externalProperties.get(PersistenceProperties.KUNDERA_NODES);\n            defaultPort = (String) externalProperties.get(PersistenceProperties.KUNDERA_PORT);\n            password = (String) externalProperties.get(PersistenceProperties.KUNDERA_PASSWORD);\n            maxActivePerNode = (String) externalProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE);\n            maxIdlePerNode = (String) externalProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_IDLE);\n            minIdlePerNode = (String) externalProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MIN_IDLE);\n            maxTotal = (String) externalProperties.get(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_TOTAL);\n            txTimeOut = (String) externalProperties.get(PersistenceProperties.KUNDERA_TRANSACTION_TIMEOUT);\n        }\n\n        if (contactNode == null)\n        {\n            contactNode = RedisPropertyReader.rsmd.getHost() != null ? RedisPropertyReader.rsmd.getHost()\n                    : (String) props.get(PersistenceProperties.KUNDERA_NODES);\n        }\n\n        if (defaultPort == null)\n        {\n            defaultPort = RedisPropertyReader.rsmd.getPort() != null ? RedisPropertyReader.rsmd.getPort()\n                    : (String) props.get(PersistenceProperties.KUNDERA_PORT);\n        }\n\n        if (password == null)\n        {\n            password = RedisPropertyReader.rsmd.getPassword() != null ? RedisPropertyReader.rsmd.getPassword()\n                    : (String) props.get(PersistenceProperties.KUNDERA_PASSWORD);\n        }\n\n        if (maxActivePerNode == null)\n        {\n            maxActivePerNode = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_ACTIVE);\n        }\n\n        if (maxIdlePerNode == null)\n        {\n            maxIdlePerNode = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_IDLE);\n        }\n\n        if (minIdlePerNode == null)\n        {\n            minIdlePerNode = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MIN_IDLE);\n        }\n\n        if (maxTotal == null)\n        {\n            maxTotal = props.getProperty(PersistenceProperties.KUNDERA_POOL_SIZE_MAX_TOTAL);\n        }\n\n        if (txTimeOut == null)\n        {\n            txTimeOut = props.getProperty(PersistenceProperties.KUNDERA_TRANSACTION_TIMEOUT);\n        }\n\n        JedisPoolConfig poolConfig = onPoolConfig(WHEN_EXHAUSTED_FAIL, maxActivePerNode, maxIdlePerNode,\n                minIdlePerNode, maxTotal);\n        \n\n        JedisPool pool = null;\n        onValidation(contactNode, defaultPort);\n\n        if (poolConfig != null)\n        {\n            if (password != null)\n            {\n                pool = new JedisPool(poolConfig, contactNode, Integer.parseInt(defaultPort), txTimeOut != null\n                        && StringUtils.isNumeric(txTimeOut) ? Integer.parseInt(txTimeOut) : -1, password);\n            }\n            else\n            {\n                pool = new JedisPool(poolConfig, contactNode, Integer.parseInt(defaultPort), txTimeOut != null\n                        && StringUtils.isNumeric(txTimeOut) ? Integer.parseInt(txTimeOut) : -1);\n            }\n\n            return pool;\n            \n        }\n        else\n        {\n            // Jedis connection = new Jedis(contactNode,\n            // Integer.valueOf(defaultPort));\n\n            // if (password != null)\n            // {\n            // // connection.auth(password);\n            // }\n            // connection.connect();\n            // Connection to made available at the time of getConnection(). YCSB\n            // performance fixes and ideally it is needed at that time only.\n            // No need to cache it at factory level as needed to managed within\n            // entity manager boundary!\n            return null;\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#instantiateClient(java\n     * .lang.String)\n     */\n    @Override\n    protected Client<RedisQuery> instantiateClient(String persistenceUnit)\n    {\n        logger.info(\"instantiating client instance\");\n        return new RedisClient(this, externalProperties, persistenceUnit, kunderaMetadata);\n    }\n\n    Map<String, Object> getOverridenProperties()\n    {\n        return this.externalProperties;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.ClientFactory#getSchemaManager()\n     */\n    @Override\n    public SchemaManager getSchemaManager(Map<String, Object> externalProperty)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.ClientLifeCycleManager#destroy()\n     */\n    @Override\n    public void destroy()\n    {\n        // if(logger.isDebugEnabled())\n        logger.info(\"on close destroying connection pool\");\n\n        if (getConnectionPoolOrConnection() != null && getConnectionPoolOrConnection() instanceof JedisPool)\n        {\n            ((JedisPool) getConnectionPoolOrConnection()).destroy();\n        }\n        else if (getConnectionPoolOrConnection() != null && getConnectionPoolOrConnection() instanceof Jedis)\n        {\n            ((Jedis) getConnectionPoolOrConnection()).disconnect();\n        }\n\n    }\n\n    /**\n     * Retrieving connection from connection pool.\n     * \n     * @return returns jedis instance.\n     */\n    Jedis getConnection()\n    {\n        if (logger.isDebugEnabled())\n            logger.info(\"borrowing connection from pool\");\n        Object poolOrConnection = getConnectionPoolOrConnection();\n        if (poolOrConnection != null && poolOrConnection instanceof JedisPool)\n        {\n\n            Jedis connection = ((JedisPool) getConnectionPoolOrConnection()).getResource();\n            connection.getClient().setTimeoutInfinite();\n            Map props = RedisPropertyReader.rsmd.getProperties();\n\n            // set external xml properties.\n            if (props != null)\n            {\n                // props.\n                for (Object key : props.keySet())\n                {\n                    connection.configSet(key.toString(), props.get(key).toString());\n                }\n            }\n            return connection;\n            \n        }\n        else\n        {\n            PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(\n                    getPersistenceUnit());\n\n            Properties props = puMetadata.getProperties();\n            String contactNode = null;\n            String defaultPort = null;\n            String password = null;\n            if (externalProperties != null)\n            {\n                contactNode = (String) externalProperties.get(PersistenceProperties.KUNDERA_NODES);\n                defaultPort = (String) externalProperties.get(PersistenceProperties.KUNDERA_PORT);\n                password = (String) externalProperties.get(PersistenceProperties.KUNDERA_PASSWORD);\n            }\n\n            if (contactNode == null)\n            {\n                contactNode = RedisPropertyReader.rsmd.getHost() != null ? RedisPropertyReader.rsmd.getHost()\n                        : (String) props.get(PersistenceProperties.KUNDERA_NODES);\n            }\n            if (defaultPort == null)\n            {\n                defaultPort = RedisPropertyReader.rsmd.getPort() != null ? RedisPropertyReader.rsmd.getPort()\n                        : (String) props.get(PersistenceProperties.KUNDERA_PORT);\n            }\n            if (password == null)\n            {\n                password = RedisPropertyReader.rsmd.getPassword() != null ? RedisPropertyReader.rsmd.getPassword()\n                        : (String) props.get(PersistenceProperties.KUNDERA_PASSWORD);\n            }\n            if (defaultPort == null || !StringUtils.isNumeric(defaultPort))\n            {\n                throw new RuntimeException(\"Invalid port provided: \" + defaultPort);\n            }\n            Jedis connection = new Jedis(contactNode, Integer.parseInt(defaultPort));\n\n            if (password != null)\n            {\n                connection.auth(password);\n            }\n            connection.connect();\n            return connection;\n        }\n    }\n\n    /**\n     * Release/return connection to pool.\n     * \n     * @param res\n     *            jedis resource\n     */\n    void releaseConnection(Jedis res)\n    {\n        if (logger.isDebugEnabled())\n            logger.info(\"releasing connection from pool\");\n        Object poolOrConnection = getConnectionPoolOrConnection();\n        if (poolOrConnection instanceof JedisPool)\n        {\n            ((JedisPool) poolOrConnection).returnResource(res);\n        }\n    }\n\n    IndexManager getIndexManager()\n    {\n        return indexManager;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.GenericClientFactory#isThreadSafe()\n     */\n    @Override\n    public boolean isThreadSafe()\n    {\n\n        return false;\n    }\n\n    /*\n     * On pool config event.\n     */\n    private JedisPoolConfig onPoolConfig(final byte WHEN_EXHAUSTED_FAIL, String maxActivePerNode,\n            String maxIdlePerNode, String minIdlePerNode, String maxTotal)\n    {\n        if (!StringUtils.isBlank(maxActivePerNode) && StringUtils.isNumeric(maxActivePerNode))\n        {\n            logger.info(\"configuring connection pool\");\n\n            JedisPoolConfig poolConfig = new JedisPoolConfig();\n\n            if (maxTotal != null && StringUtils.isNumeric(maxTotal))\n            {\n                poolConfig.setMaxTotal(Integer.valueOf(maxTotal));\n            }\n            if (maxIdlePerNode != null && StringUtils.isNumeric(maxIdlePerNode))\n            {\n                poolConfig.setMaxIdle(Integer.valueOf(maxIdlePerNode));\n            }\n            if (minIdlePerNode != null && StringUtils.isNumeric(minIdlePerNode))\n            {\n                poolConfig.setMinIdle(Integer.parseInt(minIdlePerNode));\n            }\n            if (maxActivePerNode != null && StringUtils.isNumeric(maxActivePerNode))\n            {\n                //poolConfig.setWhenExhaustedAction(WHEN_EXHAUSTED_FAIL);\n                poolConfig.setBlockWhenExhausted(true);\n            }\n            return poolConfig;\n        }\n\n        return null;\n    }\n\n    /**\n     * \n     */\n    private void initializePropertyReader()\n    {\n        if (propertyReader == null)\n        {\n            propertyReader = new RedisPropertyReader(externalProperties, kunderaMetadata.getApplicationMetadata()\n                    .getPersistenceUnitMetadata(getPersistenceUnit()));\n            propertyReader.read(getPersistenceUnit());\n        }\n    }\n\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n        throw new UnsupportedOperationException(\"Load balancing feature is not supported in \"\n                + this.getClass().getSimpleName());\n    }\n}"
  },
  {
    "path": "src/kundera-redis/src/main/java/com/impetus/client/redis/RedisEntityReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.redis;\n\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * Implementation for {@link EntityReader} interface.\n * \n * @author vivek.mishra\n */\npublic class RedisEntityReader extends AbstractEntityReader implements EntityReader\n{\n\n    public RedisEntityReader(final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    public RedisEntityReader(KunderaQuery kunderaQuery, final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n        this.kunderaQuery = kunderaQuery;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#populateRelation(com.impetus\n     * .kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        // TODO Auto-generated method stub\n        throw new UnsupportedOperationException(\"Method supported not required for Redis\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#findById(java.lang.String,\n     * com.impetus.kundera.metadata.model.EntityMetadata, java.util.List,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        return super.findById(primaryKey, m, client);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/main/java/com/impetus/client/redis/RedisIdGenerator.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.redis;\n\nimport redis.clients.jedis.Jedis;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.generator.SequenceGenerator;\nimport com.impetus.kundera.metadata.model.SequenceGeneratorDiscriptor;\n\n/**\n * The Class RedisIdGenerator.\n * \n * @author: karthikp.manchala\n */\npublic class RedisIdGenerator implements SequenceGenerator\n{\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.generator.SequenceGenerator#generate(com.impetus.\n     * kundera.metadata.model.SequenceGeneratorDiscriptor,\n     * com.impetus.kundera.client.Client, java.lang.Object)\n     */\n    @Override\n    public Object generate(SequenceGeneratorDiscriptor discriptor, Client<?> client, String dataType)\n    {\n        Jedis jedis = ((RedisClient) client).factory.getConnection();\n\n        Long latestCount = jedis.incr(((RedisClient) client).getEncodedBytes(discriptor.getSequenceName()));\n        if (latestCount == 1)\n        {\n            return discriptor.getInitialValue();\n        }\n        else\n        {\n            return (latestCount - 1) * discriptor.getAllocationSize();\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/main/java/com/impetus/client/redis/RedisIndexer.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.impetus.client.redis;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport redis.clients.jedis.Jedis;\nimport redis.clients.jedis.Pipeline;\nimport redis.clients.jedis.Transaction;\n\nimport com.impetus.client.redis.RedisClient.AttributeWrapper;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.index.Indexer;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.KunderaQuery;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class RedisIndexer implements Indexer\n{\n\n    private Object pipeLineOrConnection;\n\n    private static Logger logger = LoggerFactory.getLogger(RedisIndexer.class);\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.index.Indexer#index(java.lang.Class,\n     * java.util.Map, java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public void index(Class entityClazz, EntityMetadata m, Map<String, Object> values, Object parentId,\n            Class parentClazz)\n    {\n        Set<String> indexNames = values.keySet();\n        for (String idx_Name : indexNames)\n        {\n            Double value = (Double) values.get(idx_Name);\n            Pipeline pipeLine = null;\n            try\n            {\n                if (this.pipeLineOrConnection.getClass().isAssignableFrom(Jedis.class))\n                {\n                    pipeLine = ((Jedis) this.pipeLineOrConnection).pipelined();\n                    pipeLine.zadd(idx_Name, value, parentId.toString());\n                    // pipeLine.sync();\n                }\n                else\n                {\n                    ((Transaction) this.pipeLineOrConnection).zadd(idx_Name, value, parentId.toString());\n                }\n            }\n            finally\n            {\n                if (pipeLine != null)\n                {\n                    pipeLine.sync();\n                }\n            }\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.index.Indexer#search(java.lang.Class,\n     * java.lang.String, int, int)\n     */\n    @Override\n    public Map<String, Object> search(Class<?> clazz, EntityMetadata m, String queryString, int start, int count)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.index.Indexer#search(java.lang.String,\n     * java.lang.Class, java.lang.Class, java.lang.Object, int, int)\n     */\n    @Override\n    public Map<String, Object> search(String query, Class<?> parentClass, EntityMetadata parentMetadata,\n            Class<?> childClass, EntityMetadata childMetadata, Object entityId, int start, int count)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.index.Indexer#unIndex(java.lang.Class,\n     * java.lang.Object)\n     */\n    @Override\n    public void unIndex(Class entityClazz, Object entity, EntityMetadata metadata, MetamodelImpl metamodel)\n    {\n        // we need not implement this method for Redis because\n        // redis automatically removes indexes while performing delete\n        logger.warn(\"Removing index is implicitly managed by RedisClient's unindex method\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.index.Indexer#close()\n     */\n    @Override\n    public void close()\n    {\n    }\n\n    void assignConnection(Object connection)\n    {\n        this.pipeLineOrConnection = connection;\n    }\n\n    private void unIndex(final AttributeWrapper wrapper, final String member)\n    {\n        Set<String> keys = wrapper.getIndexes().keySet();\n\n        // keys\n        for (String key : keys)\n        {\n            if (this.pipeLineOrConnection.getClass().isAssignableFrom(Transaction.class))\n            {\n                ((Transaction) this.pipeLineOrConnection).zrem(key, member);\n\n            }\n            else\n            {\n                ((Pipeline) this.pipeLineOrConnection).zrem(key, member);\n\n            }\n        }\n    }\n\n    @Override\n    public Map<String, Object> search(KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery,\n            PersistenceDelegator persistenceDelegator, EntityMetadata m, int firstResult, int maxResults)\n    {\n        throw new KunderaException(\"Unsupported Method\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-redis/src/main/java/com/impetus/client/redis/RedisPropertyReader.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.redis;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * Property reader responsible for: a) Reads property file (xml or .properties)\n * \n * @author vivek.mishra\n * \n */\npublic class RedisPropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n\n    /** log instance */\n    private static Logger log = LoggerFactory.getLogger(RedisPropertyReader.class);\n\n    /** MongoDB schema metadata instance */\n    public static RedisSchemaMetadata rsmd;\n\n    public RedisPropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        rsmd = new RedisSchemaMetadata();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.AbstractPropertyReader#onXml(com.impetus\n     * .kundera.configure.ClientProperties)\n     */\n    @Override\n    protected void onXml(ClientProperties cp)\n    {\n\n        if (cp != null)\n        {\n            rsmd.setClientProperties(cp);\n        }\n\n    }\n\n    public class RedisSchemaMetadata\n    {\n        private static final String PORT = \"port\";\n\n        private static final String HOST = \"host\";\n\n        private ClientProperties clientProperties;\n\n        private HashMap<String, String> properties = new HashMap<String, String>();\n\n        private String host;\n\n        private String port;\n\n        public RedisSchemaMetadata()\n        {\n\n        }\n\n        /**\n         * @param clientProperties\n         *            the clientProperties to set\n         */\n        private void setClientProperties(ClientProperties clientProperties)\n        {\n            this.clientProperties = clientProperties;\n            properties = initializeProperties();\n            this.host = properties.get(HOST);\n            this.port = properties.get(PORT);\n        }\n\n        public Map<String, String> getProperties()\n        {\n            properties.remove(HOST);\n            properties.remove(PORT);\n            return (Map<String, String>) Collections.unmodifiableMap(properties);\n        }\n\n        public String getHost()\n        {\n            return host;\n        }\n\n        public String getPort()\n        {\n            return port;\n        }\n\n        public String getPassword()\n        {\n            return properties.get(\"requirepass\");\n        }\n\n        private HashMap<String, String> initializeProperties()\n        {\n            if (clientProperties != null && clientProperties.getDatastores() != null)\n            {\n                for (DataStore dataStore : clientProperties.getDatastores())\n                {\n                    if (dataStore.getName() != null && dataStore.getName().trim().equalsIgnoreCase(\"redis\"))\n                    {\n                        return new HashMap(dataStore.getConnection().getProperties());\n                    }\n                }\n            }\n\n            return null;\n        }\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-redis/src/main/java/com/impetus/client/redis/RedisQuery.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.s\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.redis;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Queue;\nimport java.util.Set;\n\nimport javax.persistence.Query;\n\nimport com.impetus.client.redis.RedisQueryInterpreter.Clause;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.MetadataUtils;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQuery.FilterClause;\nimport com.impetus.kundera.query.QueryHandlerException;\nimport com.impetus.kundera.query.QueryImpl;\n\n/**\n * Redis query interface implements <code> {@link Query} </code> and extends\n * <code> {@link QueryImpl}</code>\n * \n * @author vivek.mishra\n */\npublic class RedisQuery extends QueryImpl\n{\n\n    public RedisQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List<Object> populateEntities(EntityMetadata entityMetadata, Client client)\n    {\n        /**\n         * Multiple clause: like two columns with and cluase For multiple\n         * andTranslate jpa clause into temp store based on clause if it is for\n         * multiple data set. and fetch from there and then finally delete that\n         * temp storage. Query translator will translate queries into key value\n         */\n\n        /**\n         * Limitations: 1) Multiple AND/OR clause not possible 2) Only equal\n         * clause possible with AND/OR clause.\n         * \n         */\n\n        Set<Object> results = new LinkedHashSet<Object>();\n\n        ClientMetadata clientMetadata = ((ClientBase) client).getClientMetadata();\n\n        if (!MetadataUtils.useSecondryIndex(clientMetadata)\n                && !(clientMetadata.getIndexImplementor() != null && clientMetadata.getIndexImplementor().equals(\n                        RedisIndexer.class.getName())))\n        {\n            results.addAll(populateUsingLucene(entityMetadata, client, null,\n                    getColumns(getKunderaQuery().getResult(), entityMetadata)));\n        }\n        else\n        {\n            RedisQueryInterpreter interpreter = onTranslation(getKunderaQuery().getFilterClauseQueue(), entityMetadata);\n            results.addAll((List<Object>) ((RedisClient) client).onExecuteQuery(interpreter,\n                    entityMetadata.getEntityClazz()));\n        }\n\n        List<Object> output = new ArrayList<Object>();\n        output.addAll(results);\n\n        return output;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#recursivelyPopulateEntities(com.impetus\n     * .kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n        List<EnhanceEntity> ls = new ArrayList<EnhanceEntity>();\n        RedisQueryInterpreter interpreter = onTranslation(getKunderaQuery().getFilterClauseQueue(), m);\n        ls = ((RedisClient) client).onExecuteQuery(interpreter, m.getEntityClazz());\n        return setRelationEntities(ls, client, m);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#getReader()\n     */\n    @Override\n    protected EntityReader getReader()\n    {\n        // TODO Auto-generated method stub\n        // WHY is it required!!!\n        return new RedisEntityReader(kunderaQuery, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()\n     */\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()\n     */\n    @Override\n    protected int onExecuteUpdate()\n    {\n        return onUpdateDeleteEvent();\n    }\n\n    private RedisQueryInterpreter onTranslation(Queue clauseQueue, EntityMetadata entityMetadata)\n    {\n        RedisQueryInterpreter interpreter = new RedisQueryInterpreter(getColumns(getKunderaQuery().getResult(),\n                entityMetadata));\n\n        // If there is no clause present, means we might need to scan complete\n        // table.\n        /**\n         * TODOOOO: Create a sorted set with table name. and add row key as\n         * score and value on persist. delete it out as well on delete call.\n         */\n        for (Object clause : clauseQueue)\n        {\n            \n            if (clause.toString().trim().equalsIgnoreCase(\"(\") || clause.toString().trim().equalsIgnoreCase(\")\"))\n            {\n                // nested/multiple AND/OR not supported in Redis\n                continue;\n            }\n            \n            if (clause.getClass().isAssignableFrom(FilterClause.class))\n            {\n                Object value = ((FilterClause) clause).getValue().get(0);\n                String condition = ((FilterClause) clause).getCondition();\n                String columnName = ((FilterClause) clause).getProperty();\n\n                if (columnName.equals(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()))\n                {\n                    interpreter.setById(true);\n                }\n\n                if (condition.equals(\"=\"))\n                {\n                    interpreter.setFieldName(columnName);\n                    interpreter.setValue(value);\n                }\n                // TODO:: this is not possible. REDIS does not provide a way for\n                // this even for numeric values, reason: it includes boundary\n                // values by default.\n                /*\n                 * else if (condition.equals(\">\")) {\n                 * interpreter.setMin(columnName,value); // these can only work\n                 * for // numeric values.\n                 * \n                 * } else if (condition.equals(\"<\")) {\n                 * interpreter.setMax(columnName,value); // these can only work\n                 * for // numeric values.\n                 * \n                 * }\n                 */else if (condition.equals(\">=\"))\n                {\n                    validateClause(interpreter, condition, columnName);\n                    interpreter.setMin(columnName, value);\n                    if (interpreter.getMax() == null)\n                    {\n                        interpreter.setMax(columnName, -1D);\n                    }\n                    // interp\n                }\n                else if (condition.equals(\"<=\"))\n                {\n                    validateClause(interpreter, condition, columnName);\n                    interpreter.setMax(columnName, value);\n                    if (interpreter.getMin() == null)\n                    {\n                        interpreter.setMin(columnName, 0D);\n                    }\n                }\n                else if (interpreter.getClause() != null)\n                {\n                    throw new QueryHandlerException(\"Condition:\" + condition\n                            + \" not supported for REDIS with nested AND/OR Clause.\");\n                }\n                else\n                {\n                    throw new QueryHandlerException(\"Condition:\" + condition + \" not supported for REDIS\");\n                }\n            }\n            else\n            {\n\n                String opr = clause.toString().trim();\n\n                if (interpreter.getClause() == null)\n                {\n                    if (opr.equalsIgnoreCase(\"AND\"))\n                    {\n                        interpreter.setClause(Clause.INTERSECT);\n                    }\n                    else if (opr.equalsIgnoreCase(\"OR\"))\n                    {\n                        interpreter.setClause(Clause.UNION);\n                    }\n                    else\n                    {\n                        throw new QueryHandlerException(\"Invalid intra clause:\" + opr + \" not supported for REDIS\");\n                    }\n\n                }\n                else if (RedisQueryInterpreter.getMappedClause(opr) == null)\n                {\n                    throw new QueryHandlerException(\"Invalid intra clause:\" + opr + \" not supported for REDIS\");\n                }\n                else if (interpreter.getClause() != null\n                        && !interpreter.getClause().equals(RedisQueryInterpreter.getMappedClause(opr)))\n                {\n                    throw new QueryHandlerException(\"Multiple combination of AND/OR clause not supported for REDIS\");\n                }\n                // it is a case of \"AND\", \"OR\" clause\n            }\n        }\n\n        return interpreter;\n    }\n\n    private void validateClause(RedisQueryInterpreter interpreter, String condition, String columnName)\n    {\n        if (interpreter.getClause() != null)\n        {\n            if (interpreter.getFieldName() != null && !interpreter.getFieldName().equals(columnName))\n            {\n                throw new QueryHandlerException(\n                        \"Nested AND/OR clause is not supported for different set of fields for condition:\" + condition);\n            }\n        }\n\n        interpreter.setFieldName(columnName);\n    }\n\n    @Override\n    public void close()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    @Override\n    public Iterator iterate()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n\n        RedisQueryInterpreter interpreter = onTranslation(getKunderaQuery().getFilterClauseQueue(), m);\n        return ((RedisClient) client).onExecuteQuery(interpreter, m.getEntityClazz());\n\n    }\n\n}"
  },
  {
    "path": "src/kundera-redis/src/main/java/com/impetus/client/redis/RedisQueryInterpreter.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.redis;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.commons.lang.StringUtils;\n\nimport com.impetus.kundera.property.PropertyAccessorHelper;\n\n/**\n * Query interpreter responsible for: <li>Determine if it is a query by id.</li>\n * <li>holds value and clause(UNION or INTERSECT REDIS clause for sorted set)</li>\n * \n * @author vivek.mishra\n * \n */\nclass RedisQueryInterpreter\n{\n\n    private boolean isById;\n\n    private Map<String, Double> min;\n\n    private Map<String, Double> max;\n\n    private Clause clause;\n\n    private Object value;\n\n    private String fieldName;\n\n    private Map<String, Object> fields;\n\n    private String[] columns;\n\n    private static Map<String, Clause> clauseMapper = new HashMap<String, Clause>();\n    static\n    {\n        clauseMapper.put(\"AND\", Clause.INTERSECT);\n        clauseMapper.put(\"OR\", Clause.UNION);\n    }\n\n    enum Clause\n    {\n        UNION, INTERSECT;\n    }\n\n    static Clause getMappedClause(String intraClause)\n    {\n        return clauseMapper.get(intraClause);\n    }\n\n    /**\n     * Default constructor\n     */\n    public RedisQueryInterpreter(String[] columns)\n    {\n        this.columns = columns;\n    }\n\n    boolean isById()\n    {\n        return isById;\n    }\n\n    void setById(boolean isById)\n    {\n        this.isById = isById;\n    }\n\n    Clause getClause()\n    {\n        return clause;\n    }\n\n    void setClause(Clause clause)\n    {\n        this.clause = clause;\n    }\n\n    boolean isByRange()\n    {\n        return min != null || max != null;\n    }\n\n    Object getValue()\n    {\n        return value;\n    }\n\n    void setValue(Object value)\n    {\n        this.value = value;\n        if (this.fields != null)\n        {\n            fields.put(fieldName, value);\n        }\n    }\n\n    Map<String, Double> getMin()\n    {\n        return min;\n    }\n\n    void setMin(String field, Object fieldValue)\n    {\n        this.min = new HashMap<String, Double>(1);\n        this.min.put(\n                field,\n                !StringUtils.isNumeric(fieldValue.toString()) ? Double.valueOf(PropertyAccessorHelper.getString(\n                        fieldValue).hashCode()) : Double.valueOf(fieldValue.toString()));\n    }\n\n    Map<String, Double> getMax()\n    {\n        return max;\n    }\n\n    void setMax(String field, Object fieldValue)\n    {\n        this.max = new HashMap<String, Double>(1);\n        this.max.put(\n                field,\n                !StringUtils.isNumeric(fieldValue.toString()) ? Double.valueOf(PropertyAccessorHelper.getString(\n                        fieldValue).hashCode()) : Double.valueOf(fieldValue.toString()));\n    }\n\n    String getFieldName()\n    {\n        return fieldName;\n    }\n\n    void setFieldName(String fieldName)\n    {\n        this.fieldName = fieldName;\n        if (fields == null)\n        {\n            fields = new HashMap<String, Object>(2);\n        }\n        fields.put(fieldName, null);\n    }\n\n    Map<String, Object> getFields()\n    {\n        return fields;\n    }\n\n    List<byte[]> getColumns()\n    {\n        if (columns != null && columns.length > 0)\n        {\n            // byte[] fields = new byte[columns.length][1];\n            List<byte[]> fields = new ArrayList<byte[]>(columns.length);\n            for (int i = 0; i < columns.length; i++)\n            {\n                if (columns[i] != null /* && columns[i].indexOf(\".\") >= 0 */)\n                {\n                    byte[] f = PropertyAccessorHelper.getBytes(columns[i]);\n                    fields.add(f);\n                }\n            }\n\n            return fields.isEmpty() ? null : fields;\n        }\n\n        return null;\n    }\n    \n    String[] getSelectedColumns(){\n    \n    return columns;\n    }\n\n}"
  },
  {
    "path": "src/kundera-redis/src/main/java/com/impetus/client/redis/RedisTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client.redis;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport redis.clients.jedis.Jedis;\nimport redis.clients.jedis.Transaction;\n\nimport com.impetus.kundera.persistence.TransactionResource;\n\n/**\n * Defines transaction boundaries for redis client, if user opted for\n * transaction support(kundera.transaction.resource)\n * \n * @author vivek\n * \n */\npublic class RedisTransaction implements TransactionResource\n{\n\n    private List<Transaction> resources = new ArrayList<Transaction>();\n\n    private boolean isTransactionInProgress;\n\n    /**\n     * Default constructor\n     */\n    public RedisTransaction()\n    {\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.TransactionResource#onBegin()\n     */\n    @Override\n    public void onBegin()\n    {\n        isTransactionInProgress = true;\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.TransactionResource#onCommit()\n     */\n    @Override\n    public void onCommit()\n    {\n        for (Transaction resource : resources)\n        {\n            resource.exec();\n        }\n        isTransactionInProgress = false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.TransactionResource#onRollback()\n     */\n    @Override\n    public void onRollback()\n    {\n        for (Transaction resource : resources)\n        {\n            resource.discard();\n        }\n\n        resources.clear();\n        resources = new ArrayList<Transaction>();\n        isTransactionInProgress = false;\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.TransactionResource#onFlush()\n     */\n    @Override\n    public void onFlush()\n    {\n        onCommit();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.TransactionResource#prepare()\n     */\n    @Override\n    public Response prepare()\n    {\n        return Response.YES;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.persistence.TransactionResource#isActive()\n     */\n    @Override\n    public boolean isActive()\n    {\n        return isTransactionInProgress;\n    }\n\n    Transaction bindResource(Jedis resource)\n    {\n        Transaction tx = null;\n        // Multi not supported.\n\n        /*\n         * if (resources.isEmpty()) {\n         */\n        tx = resource.multi();\n        resources.add(tx);\n        /*\n         * } else { // tx = resource.multi(); // resources.add(tx); tx =\n         * resources.get(0); }\n         */return tx;\n    }\n\n    Transaction getResource()\n    {\n        return resources.get(0);\n    }\n\n    boolean isResourceBound()\n    {\n        return !resources.isEmpty();\n    }\n\n    synchronized void onExecute(Transaction tx)\n    {\n        tx.exec();\n        resources.remove(tx);\n    }\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisAssociationTest.java",
    "content": "package com.impetus.client;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.entities.AddressOTORedis;\nimport com.impetus.client.entities.PersonOTORedis;\n\npublic class RedisAssociationTest\n{\n\n    private static final String ROW_KEY = \"1\";\n\n    /** The Constant REDIS_PU. */\n    private static final String REDIS_PU = \"redis_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(RedisAssociationTest.class);\n\n    @Before\n    public void setUp()\n    {\n        // \n        emf = Persistence.createEntityManagerFactory(REDIS_PU);\n    }\n\n    @Test\n    public void testCrud()\n    {\n        logger.info(\"On crud over association \");\n        EntityManager em = emf.createEntityManager();\n\n        PersonOTORedis person = new PersonOTORedis(ROW_KEY);\n        person.setAge(32);\n        person.setPersonName(\"vivek\");\n        AddressOTORedis address = new AddressOTORedis(12.23);\n        address.setAddress(\"india\");\n        person.setAddress(address);\n        em.persist(person);\n\n        em.clear();\n        PersonOTORedis p = em.find(PersonOTORedis.class, ROW_KEY);\n\n        // Assertions.\n        Assert.assertNotNull(p);\n        Assert.assertEquals(person.getPersonId(), p.getPersonId());\n        Assert.assertNotNull(p.getAddress());\n        Assert.assertEquals(person.getAddress().getAddress(), p.getAddress().getAddress());\n\n        // Remove\n        em.remove(p);\n\n        em.clear(); // clear cache\n        Assert.assertNull(em.find(AddressOTORedis.class, 12.23));\n    }\n\n    @After\n    public void tearDown()\n    {\n        logger.info(\"on tear down\");\n        emf.close();\n    }\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisAssociationTestMTM.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.entities.AddressMTMRedis;\nimport com.impetus.client.entities.PersonMTMRedis;\n\npublic class RedisAssociationTestMTM\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"redis_pu\");\n        em = getNewEM();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void testCrud()\n    {\n\n        AddressMTMRedis address1 = getAddress(101.0, \"NCR\");\n        AddressMTMRedis address2 = getAddress(109.0, \"Delhi\");\n        AddressMTMRedis address3 = getAddress(145.0, \"Gurgaon\");\n\n        Set<AddressMTMRedis> addresses1 = new HashSet<AddressMTMRedis>();\n        addresses1.add(address1);\n        addresses1.add(address2);\n\n        Set<AddressMTMRedis> addresses2 = new HashSet<AddressMTMRedis>();\n        addresses2.add(address2);\n        addresses2.add(address3);\n\n        PersonMTMRedis person1 = getPerson(\"1\", \"User1\", 20, addresses1);\n        PersonMTMRedis person2 = getPerson(\"2\", \"User2\", 40, addresses2);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        PersonMTMRedis resultPerson1 = em.find(PersonMTMRedis.class, \"1\");\n        PersonMTMRedis resultPerson2 = em.find(PersonMTMRedis.class, \"2\");\n\n        notNullCheck(resultPerson1, resultPerson2);\n        Assert.assertEquals(\"1\", resultPerson1.getPersonId());\n        Assert.assertEquals(\"User1\", resultPerson1.getPersonName());\n        Assert.assertEquals(20, resultPerson1.getAge().intValue());\n\n        Assert.assertEquals(\"2\", resultPerson2.getPersonId());\n        Assert.assertEquals(\"User2\", resultPerson2.getPersonName());\n        Assert.assertEquals(40, resultPerson2.getAge().intValue());\n\n        Assert.assertEquals(2, resultPerson1.getAddress().size());\n        Assert.assertEquals(2, resultPerson2.getAddress().size());\n\n        for (AddressMTMRedis address : resultPerson1.getAddress())\n        {\n            if (address.getAddressId().equals(101.0))\n            {\n                Assert.assertEquals(\"NCR\", address.getAddress());\n            }\n            else\n            {\n                Assert.assertEquals(109.0, address.getAddressId());\n                Assert.assertEquals(\"Delhi\", address.getAddress());\n            }\n        }\n\n        for (AddressMTMRedis address : resultPerson2.getAddress())\n        {\n            if (address.getAddressId().equals(109.0))\n            {\n                Assert.assertEquals(\"Delhi\", address.getAddress());\n            }\n            else\n            {\n                Assert.assertEquals(145.0, address.getAddressId());\n                Assert.assertEquals(\"Gurgaon\", address.getAddress());\n            }\n        }\n\n        em.clear();\n        address1.setAddress(\"Agra\");\n        address2.setAddress(\"Mathura\");\n        person1.setPersonName(\"User3\");\n\n        em.merge(person1);\n        em = getNewEM();\n\n        resultPerson1 = em.find(PersonMTMRedis.class, \"1\");\n        resultPerson2 = em.find(PersonMTMRedis.class, \"2\");\n\n        notNullCheck(resultPerson1, resultPerson2);\n        Assert.assertEquals(\"1\", resultPerson1.getPersonId());\n        Assert.assertEquals(\"User3\", resultPerson1.getPersonName());\n        Assert.assertEquals(20, resultPerson1.getAge().intValue());\n\n        for (AddressMTMRedis address : resultPerson1.getAddress())\n        {\n            if (address.getAddressId().equals(101.0))\n            {\n                Assert.assertEquals(\"Agra\", address.getAddress());\n            }\n            else\n            {\n                Assert.assertEquals(109.0, address.getAddressId());\n                Assert.assertEquals(\"Mathura\", address.getAddress());\n            }\n        }\n\n        for (AddressMTMRedis address : resultPerson2.getAddress())\n        {\n            if (address.getAddressId().equals(109.0))\n            {\n                Assert.assertEquals(\"Mathura\", address.getAddress());\n            }\n            else\n            {\n                Assert.assertEquals(145.0, address.getAddressId());\n                Assert.assertEquals(\"Gurgaon\", address.getAddress());\n            }\n        }\n\n        em.remove(resultPerson1);\n        em.remove(resultPerson2);\n\n        Assert.assertNull(em.find(PersonMTMRedis.class, \"1\"));\n        Assert.assertNull(em.find(PersonMTMRedis.class, \"2\"));\n        Assert.assertNull(em.find(AddressMTMRedis.class, 101.0));\n        Assert.assertNull(em.find(AddressMTMRedis.class, 109.0));\n        Assert.assertNull(em.find(AddressMTMRedis.class, 145.0));\n    }\n\n    @Test\n    public void testQuery()\n    {\n\n        AddressMTMRedis address1 = getAddress(101.0, \"NCR\");\n        AddressMTMRedis address2 = getAddress(109.0, \"Delhi\");\n        AddressMTMRedis address3 = getAddress(145.0, \"Gurgaon\");\n\n        Set<AddressMTMRedis> addresses1 = new HashSet<AddressMTMRedis>();\n        addresses1.add(address1);\n        addresses1.add(address2);\n\n        Set<AddressMTMRedis> addresses2 = new HashSet<AddressMTMRedis>();\n        addresses2.add(address2);\n        addresses2.add(address3);\n\n        PersonMTMRedis person1 = getPerson(\"1\", \"User1\", 20, addresses1);\n        PersonMTMRedis person2 = getPerson(\"2\", \"User2\", 40, addresses2);\n\n        em.persist(person1);\n        em.persist(person2);\n\n        Query query = em.createQuery(\"Select e from PersonMTMRedis e\");\n        List<PersonMTMRedis> queryResult = query.getResultList();\n\n        Assert.assertEquals(2, queryResult.size());\n\n        PersonMTMRedis resultPerson1 = queryResult.get(1);\n        PersonMTMRedis resultPerson2 = queryResult.get(0);\n\n        notNullCheck(resultPerson1, resultPerson2);\n        Assert.assertEquals(\"1\", resultPerson1.getPersonId());\n        Assert.assertEquals(\"User1\", resultPerson1.getPersonName());\n        Assert.assertEquals(20, resultPerson1.getAge().intValue());\n\n        Assert.assertEquals(\"2\", resultPerson2.getPersonId());\n        Assert.assertEquals(\"User2\", resultPerson2.getPersonName());\n        Assert.assertEquals(40, resultPerson2.getAge().intValue());\n\n        Assert.assertEquals(2, resultPerson1.getAddress().size());\n        Assert.assertEquals(2, resultPerson2.getAddress().size());\n\n        for (AddressMTMRedis address : resultPerson1.getAddress())\n        {\n            if (address.getAddressId().equals(101.0))\n            {\n                Assert.assertEquals(\"NCR\", address.getAddress());\n            }\n            else\n            {\n                Assert.assertEquals(109.0, address.getAddressId());\n                Assert.assertEquals(\"Delhi\", address.getAddress());\n            }\n        }\n\n        for (AddressMTMRedis address : resultPerson2.getAddress())\n        {\n            if (address.getAddressId().equals(109.0))\n            {\n                Assert.assertEquals(\"Delhi\", address.getAddress());\n            }\n            else\n            {\n                Assert.assertEquals(145.0, address.getAddressId());\n                Assert.assertEquals(\"Gurgaon\", address.getAddress());\n            }\n        }\n\n        em.clear();\n        address1.setAddress(\"Agra\");\n        address2.setAddress(\"Mathura\");\n        person1.setPersonName(\"User3\");\n\n        em.merge(person1);\n        em = getNewEM();\n\n        query = em.createQuery(\"Select e from PersonMTMRedis e\");\n        queryResult = query.getResultList();\n\n        Assert.assertEquals(2, queryResult.size());\n\n        if (queryResult.get(0).getPersonId().equals(1))\n        {\n            resultPerson1 = queryResult.get(0);\n            resultPerson2 = queryResult.get(1);\n        }\n        else\n        {\n            resultPerson1 = queryResult.get(1);\n            resultPerson2 = queryResult.get(0);\n        }\n\n        notNullCheck(resultPerson1, resultPerson2);\n\n        Assert.assertEquals(\"1\", resultPerson1.getPersonId());\n        Assert.assertEquals(\"User3\", resultPerson1.getPersonName());\n        Assert.assertEquals(20, resultPerson1.getAge().intValue());\n\n        for (AddressMTMRedis address : resultPerson1.getAddress())\n        {\n            if (address.getAddressId().equals(101.0))\n            {\n                Assert.assertEquals(\"Agra\", address.getAddress());\n            }\n            else\n            {\n                Assert.assertEquals(109.0, address.getAddressId());\n                Assert.assertEquals(\"Mathura\", address.getAddress());\n            }\n        }\n\n        for (AddressMTMRedis address : resultPerson2.getAddress())\n        {\n            if (address.getAddressId().equals(109.0))\n            {\n                Assert.assertEquals(\"Mathura\", address.getAddress());\n            }\n            else\n            {\n                Assert.assertEquals(145.0, address.getAddressId());\n                Assert.assertEquals(\"Gurgaon\", address.getAddress());\n            }\n        }\n\n        em.remove(resultPerson1);\n        em.remove(resultPerson2);\n\n        Assert.assertNull(em.find(PersonMTMRedis.class, \"1\"));\n        Assert.assertNull(em.find(PersonMTMRedis.class, \"2\"));\n        Assert.assertNull(em.find(AddressMTMRedis.class, 101.0));\n        Assert.assertNull(em.find(AddressMTMRedis.class, 109.0));\n        Assert.assertNull(em.find(AddressMTMRedis.class, 145.0));\n    }\n\n    private boolean notNullCheck(PersonMTMRedis resultPerson1, PersonMTMRedis resultPerson2)\n    {\n\n        Assert.assertNotNull(resultPerson1);\n        Assert.assertNotNull(resultPerson2);\n        Assert.assertNotNull(resultPerson1.getAddress());\n        Assert.assertNotNull(resultPerson2.getAddress());\n\n        return true;\n    }\n\n    private PersonMTMRedis getPerson(String personId, String personName, int age, Set<AddressMTMRedis> address)\n    {\n\n        PersonMTMRedis person = new PersonMTMRedis(personId);\n        person.setAge(age);\n        person.setPersonName(personName);\n        person.setAddress(address);\n\n        return person;\n    }\n\n    private AddressMTMRedis getAddress(Double addressId, String personAddress)\n    {\n\n        AddressMTMRedis address = new AddressMTMRedis(addressId);\n        address.setAddress(personAddress);\n        return address;\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        // Delete by query.\n        Query query = em.createQuery(\"Delete from PersonMTMRedis p\");\n        int updateCount = query.executeUpdate();\n        return em = emf.createEntityManager();\n    }\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisAssociationTestMTO.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.entities.AddressMTORedis;\nimport com.impetus.client.entities.PersonMTORedis;\n\npublic class RedisAssociationTestMTO\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"redis_pu\");\n        em = getNewEM();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void testCrud()\n    {\n\n        AddressMTORedis address = new AddressMTORedis(100.0);\n        address.setAddress(\"Gr. Noida\");\n\n        PersonMTORedis person1 = getPerson(\"1\", \"User1\", 20, address);\n        PersonMTORedis person2 = getPerson(\"2\", \"User2\", 40, address);\n        em.persist(person1);\n        em.persist(person2);\n\n        PersonMTORedis resultPerson1 = em.find(PersonMTORedis.class, \"1\");\n        PersonMTORedis resultPerson2 = em.find(PersonMTORedis.class, \"2\");\n\n        notNullCheck(resultPerson1, resultPerson2);\n        Assert.assertEquals(\"1\", resultPerson1.getPersonId());\n        Assert.assertEquals(\"User1\", resultPerson1.getPersonName());\n        Assert.assertEquals(20, resultPerson1.getAge().intValue());\n\n        Assert.assertEquals(\"2\", resultPerson2.getPersonId());\n        Assert.assertEquals(\"User2\", resultPerson2.getPersonName());\n        Assert.assertEquals(40, resultPerson2.getAge().intValue());\n\n        Assert.assertEquals(100.0, resultPerson1.getAddress().getAddressId());\n        Assert.assertEquals(\"Gr. Noida\", resultPerson1.getAddress().getAddress());\n        Assert.assertEquals(100.0, resultPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"Gr. Noida\", resultPerson2.getAddress().getAddress());\n\n        em.clear();\n        address.setAddress(\"NCR\");\n        person1.setPersonName(\"User3\");\n        person1.setAddress(address);\n\n        em.merge(person1);\n        em = getNewEM();\n\n        resultPerson1 = em.find(PersonMTORedis.class, \"1\");\n        resultPerson2 = em.find(PersonMTORedis.class, \"2\");\n\n        notNullCheck(resultPerson1, resultPerson2);\n        Assert.assertEquals(\"1\", resultPerson1.getPersonId());\n        Assert.assertEquals(\"User3\", resultPerson1.getPersonName());\n        Assert.assertEquals(20, resultPerson1.getAge().intValue());\n\n        Assert.assertEquals(100.0, resultPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"NCR\", resultPerson2.getAddress().getAddress());\n\n        em.remove(resultPerson1);\n        em.remove(resultPerson2);\n\n        Assert.assertNull(em.find(PersonMTORedis.class, \"1\"));\n        Assert.assertNull(em.find(PersonMTORedis.class, \"2\"));\n        // Assert.assertNull(em.find(AddressMTORedis.class, 100.0));\n    }\n\n    @Test\n    public void testQuery()\n    {\n\n        AddressMTORedis address = new AddressMTORedis(100.0);\n        address.setAddress(\"Gr. Noida\");\n\n        PersonMTORedis person1 = getPerson(\"1\", \"User1\", 20, address);\n        PersonMTORedis person2 = getPerson(\"2\", \"User2\", 40, address);\n        em.persist(person1);\n        em.persist(person2);\n\n        Query query = em.createQuery(\"Select e from PersonMTORedis e\");\n        List<PersonMTORedis> queryResult = query.getResultList();\n\n        Assert.assertEquals(2, queryResult.size());\n        PersonMTORedis resultPerson1 = queryResult.get(0);\n        PersonMTORedis resultPerson2 = queryResult.get(1);\n\n        notNullCheck(resultPerson1, resultPerson2);\n        for (PersonMTORedis resultPerson : queryResult)\n        {\n\n            if (resultPerson.getPersonId().equals(\"1\"))\n            {\n                Assert.assertEquals(\"User1\", resultPerson.getPersonName());\n                Assert.assertEquals(20, resultPerson.getAge().intValue());\n            }\n            else\n            {\n                Assert.assertEquals(\"2\", resultPerson.getPersonId());\n                Assert.assertEquals(\"User2\", resultPerson.getPersonName());\n                Assert.assertEquals(40, resultPerson.getAge().intValue());\n            }\n        }\n\n        Assert.assertEquals(100.0, resultPerson1.getAddress().getAddressId());\n        Assert.assertEquals(\"Gr. Noida\", resultPerson1.getAddress().getAddress());\n        Assert.assertEquals(100.0, resultPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"Gr. Noida\", resultPerson2.getAddress().getAddress());\n\n        em.clear();\n        address.setAddress(\"NCR\");\n        person1.setPersonName(\"User3\");\n        person1.setAddress(address);\n\n        em.merge(person1);\n        em = getNewEM();\n\n        query = em.createQuery(\"Select e from PersonMTORedis e\");\n        queryResult = query.getResultList();\n\n        Assert.assertEquals(2, queryResult.size());\n        resultPerson1 = queryResult.get(0);\n        resultPerson2 = queryResult.get(1);\n\n        notNullCheck(resultPerson1, resultPerson2);\n        for (PersonMTORedis resultPerson : queryResult)\n        {\n\n            if (resultPerson.getPersonId().equals(\"1\"))\n            {\n                Assert.assertEquals(\"User3\", resultPerson.getPersonName());\n                Assert.assertEquals(20, resultPerson.getAge().intValue());\n            }\n            else\n            {\n                Assert.assertEquals(\"2\", resultPerson.getPersonId());\n                Assert.assertEquals(\"User2\", resultPerson.getPersonName());\n                Assert.assertEquals(40, resultPerson.getAge().intValue());\n            }\n        }\n\n        Assert.assertEquals(100.0, resultPerson2.getAddress().getAddressId());\n        Assert.assertEquals(\"NCR\", resultPerson2.getAddress().getAddress());\n\n        em.remove(resultPerson1);\n        em.remove(resultPerson2);\n\n        Assert.assertNull(em.find(PersonMTORedis.class, \"1\"));\n        Assert.assertNull(em.find(PersonMTORedis.class, \"2\"));\n        // Assert.assertNull(em.find(AddressMTORedis.class, 100.0));\n    }\n\n    private boolean notNullCheck(PersonMTORedis resultPerson1, PersonMTORedis resultPerson2)\n    {\n\n        Assert.assertNotNull(resultPerson1);\n        Assert.assertNotNull(resultPerson2);\n        Assert.assertNotNull(resultPerson1.getAddress());\n        Assert.assertNotNull(resultPerson2.getAddress());\n\n        return true;\n    }\n\n    private PersonMTORedis getPerson(String personId, String personName, int age, AddressMTORedis address)\n    {\n\n        PersonMTORedis person = new PersonMTORedis(personId);\n        person.setAge(age);\n        person.setPersonName(personName);\n        person.setAddress(address);\n\n        return person;\n    }\n\n    private EntityManager getNewEM()\n    {\n        if (em != null && em.isOpen())\n        {\n            em.close();\n        }\n        // Delete by query.\n        Query query = em.createQuery(\"Delete from PersonMTORedis p\");\n        int updateCount = query.executeUpdate();\n        return em = emf.createEntityManager();\n    }\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisClientFactoryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client;\n\nimport java.lang.reflect.Field;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport redis.clients.jedis.Jedis;\nimport com.impetus.client.redis.RedisClient;\nimport com.impetus.client.redis.RedisClientFactory;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientResolver;\nimport com.impetus.kundera.loader.ClientFactory;\nimport com.impetus.kundera.persistence.api.Batcher;\n\n/**\n * The Class RedisClientFactoryTest. Junit for {@link RedisClientFactory}\n */\npublic class RedisClientFactoryTest\n{\n\n    /** The Constant REDIS_PU. */\n    private static final String REDIS_PU = \"redisClientFactoryTest_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(RedisClientFactoryTest.class);\n\n    /**\n     * Setup.\n     */\n    @Before\n    public void setup()\n    {\n        Map<String, String> properties = new HashMap<String, String>(1);\n        properties.put(\"kundera.transaction.timeout\", \"20000\");\n        properties.put(\"kundera.pool.size.max.active\", \"10\");\n        properties.put(\"kundera.nodes\", \"localhost\");\n        properties.put(\"kundera.port\", \"6379\");\n        properties.put(\"kundera.batch.size\", \"5\");\n        emf = Persistence.createEntityManagerFactory(REDIS_PU, properties);\n    }\n\n    /**\n     * Test connection.\n     */\n    @Test\n    public void testConnection()\n    {\n        logger.info(\"On test connection\");\n\n        ClientFactory clientFactory = ClientResolver.getClientFactory(REDIS_PU);\n        Assert.assertNotNull(clientFactory);\n        Assert.assertEquals(RedisClientFactory.class, clientFactory.getClass());\n        Field connectionField;\n        try\n        {\n            String field_name = \"connectionPoolOrConnection\";\n            \n            connectionField = ((RedisClientFactory) clientFactory).getClass().getSuperclass()\n                    .getDeclaredField(field_name);\n\n            if (!connectionField.isAccessible())\n            {\n                connectionField.setAccessible(true);\n            }\n\n            Object connectionObj = connectionField.get(clientFactory);\n           \n            EntityManager em = emf.createEntityManager();\n            Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n            RedisClient redisClient = (RedisClient) clients.get(REDIS_PU);\n            Assert.assertEquals(5, ((Batcher) redisClient).getBatchSize());\n            Field field=redisClient.getClass().getDeclaredField(\"connection\");\n            field.setAccessible(true);\n            Jedis connection=(Jedis) field.get(redisClient);\n            Assert.assertEquals(6379, connection.getClient().getPort());\n            Assert.assertEquals(\"localhost\", connection.getClient().getHost());\n            Assert.assertEquals(20000, connection.getClient().getConnectionTimeout());\n            \n            Assert.assertNotNull(connectionObj);\n\n        }\n        catch (SecurityException e)\n        {\n            logger.error(e.getMessage());\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            logger.error(e.getMessage());\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalArgumentException e)\n        {\n            logger.error(e.getMessage());\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            logger.error(e.getMessage());\n            Assert.fail(e.getMessage());\n        }\n       \n    }\n\n    /**\n     * Tear down.\n     */\n    @After\n    public void tearDown()\n    {\n        emf.close();\n    }\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisClientTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.databene.contiperf.PerfTest;\nimport org.databene.contiperf.junit.ContiPerfRule;\nimport org.databene.contiperf.report.CSVSummaryReportModule;\nimport org.databene.contiperf.report.HtmlReportModule;\nimport org.databene.contiperf.report.ReportModule;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.entities.Month;\nimport com.impetus.client.entities.PersonRedis;\nimport com.impetus.client.entities.PersonRedis.Day;\nimport com.impetus.client.redis.RedisClient;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.graph.Node;\nimport com.impetus.kundera.lifecycle.states.TransientState;\nimport com.impetus.kundera.persistence.api.Batcher;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData.OPERATION;\n\n/**\n * Junit for {@link RedisClient}.\n * \n * @author vivek.mishra\n */\n\npublic class RedisClientTest\n{\n\n    private static final String ROW_KEY = \"1\";\n\n    /** The Constant REDIS_PU. */\n    private static final String REDIS_PU = \"redis_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(RedisClientTest.class);\n\n    @Rule\n    public ContiPerfRule i = new ContiPerfRule(new ReportModule[] { new CSVSummaryReportModule(),\n            new HtmlReportModule() });\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(REDIS_PU);\n    }\n\n    @Test\n    @PerfTest(invocations = 10)\n    public void testCRUD()\n    {\n        logger.info(\"On testInsert\");\n        EntityManager em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        RedisClient client = (RedisClient) clients.get(REDIS_PU);\n        onInsert(client);\n        onUpdate(client);\n        onDelete(client);\n        em.close();\n    }\n\n    @Test\n    public void testCRUDWithBatch()\n    {\n        \n        Map<String, String> batchProperty = new HashMap<String, String>(1);\n        batchProperty.put(PersistenceProperties.KUNDERA_BATCH_SIZE, \"5\");\n        EntityManagerFactory emf = Persistence.createEntityManagerFactory(REDIS_PU, batchProperty);\n        EntityManager em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        RedisClient client = (RedisClient) clients.get(REDIS_PU);\n        Assert.assertEquals(5, ((Batcher) client).getBatchSize());\n\n        final String originalName = \"vivek\";\n\n        for (int i = 0; i < 9; i++)\n        {\n            PersonRedis object = new PersonRedis();\n            object.setAge(32);\n            object.setPersonId(ROW_KEY + i);\n            object.setPersonName(originalName);\n            em.persist(object);\n\n            if (i >= 5)\n            {\n                PersonRedis result = (PersonRedis) client.find(PersonRedis.class, ROW_KEY + i);\n                Assert.assertNull(result);\n            }\n            else if (i > 0 && i % 4 == 0)\n            {\n                PersonRedis result = (PersonRedis) client.find(PersonRedis.class, ROW_KEY + i);\n                Assert.assertNotNull(result);\n                Assert.assertEquals(result.getPersonId(), object.getPersonId());\n                Assert.assertEquals(result.getAge(), object.getAge());\n                Assert.assertEquals(result.getPersonName(), object.getPersonName());\n            }\n        }\n        em.flush();\n        em.clear();\n        em.close();\n        em = null;\n\n//        emf.close();\n        //\n        // emf = null;\n        // batchProperty.put(PersistenceProperties.KUNDERA_BATCH_SIZE, null);\n        // emf = Persistence.createEntityManagerFactory(REDIS_PU,\n        // batchProperty);\n\n    }\n\n    @Test\n    public void testPersistJoinTableData()\n    {\n        final String schemaName = \"redis\";\n        final String tableName = \"redisjointable\";\n        final String joinColumn = \"joincolumn\";\n        final String inverseJoinColumn = \"inverseJoinColumnName\";\n\n        JoinTableData joinTableData = new JoinTableData(OPERATION.INSERT, \"redis\", \"redisjointable\", \"joincolumn\",\n                \"inverseJoinColumnName\", null);\n\n        UUID joinKey = UUID.randomUUID();\n\n        Integer inverseJoinKey1 = new Integer(10);\n        Double inverseJoinKey2 = new Double(12.23);\n        Set inverseJoinKeys = new HashSet();\n        inverseJoinKeys.add(inverseJoinKey1);\n        inverseJoinKeys.add(inverseJoinKey2);\n\n        joinTableData.addJoinTableRecord(joinKey, inverseJoinKeys);\n\n        EntityManager em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        RedisClient client = (RedisClient) clients.get(REDIS_PU);\n        client.persistJoinTable(joinTableData);\n\n        List<String> columns = client.getColumnsById(schemaName, tableName, joinColumn, inverseJoinColumn, joinKey,\n                String.class);\n\n        Assert.assertNotNull(columns);\n        Assert.assertEquals(true, !columns.isEmpty());\n        Assert.assertEquals(2, columns.size());\n        Assert.assertEquals(true, columns.contains(inverseJoinKey1.toString()));\n        Assert.assertEquals(true, columns.contains(inverseJoinKey2.toString()));\n\n        client.deleteByColumn(schemaName, tableName, inverseJoinColumn, inverseJoinKey1);\n        client.deleteByColumn(schemaName, tableName, inverseJoinColumn, inverseJoinKey2);\n\n        columns = client.getColumnsById(schemaName, tableName, joinColumn, inverseJoinColumn, joinKey, String.class);\n\n        Assert.assertTrue(columns.isEmpty());\n\n    }\n\n    /**\n     * Assertions on delete.\n     * \n     * @param client\n     *            Redis client instance.\n     */\n    private void onUpdate(RedisClient client)\n    {\n        PersonRedis result = (PersonRedis) client.find(PersonRedis.class, ROW_KEY);\n        Assert.assertNotNull(result);\n\n        String updatedName = \"Updated\";\n        result.setPersonName(updatedName);\n        result.setAge(33);\n        Assert.assertNotNull(result);\n        Assert.assertEquals(result.getAge(), new Integer(33));\n        Assert.assertEquals(result.getPersonName(), updatedName);\n    }\n\n    /**\n     * Assertions on delete.\n     * \n     * @param client\n     *            Redis client instance.\n     */\n    private void onDelete(RedisClient client)\n    {\n        PersonRedis result = (PersonRedis) client.find(PersonRedis.class, ROW_KEY);\n        Assert.assertNotNull(result);\n        client.delete(result, ROW_KEY);\n        result = (PersonRedis) client.find(PersonRedis.class, ROW_KEY);\n        Assert.assertNull(result);\n    }\n\n    /**\n     * Assertions on insert.\n     * \n     * @param client\n     *            Redis client instance.\n     */\n    private void onInsert(RedisClient client)\n    {\n        // RedisClient client = (RedisClient) clients.get(REDIS_PU);\n        final String nodeId = \"node1\";\n        final String originalName = \"vivek\";\n        PersonRedis object = new PersonRedis();\n        object.setAge(32);\n        object.setPersonId(ROW_KEY);\n        object.setPersonName(originalName);\n        object.setDay(Day.TUESDAY);\n        object.setMonth(Month.JAN);\n\n        Node node = new Node(nodeId, PersonRedis.class, new TransientState(), null, ROW_KEY, null);\n        node.setData(object);\n        client.persist(node);\n\n        PersonRedis result = (PersonRedis) client.find(PersonRedis.class, ROW_KEY);\n\n        Assert.assertNotNull(result);\n        Assert.assertEquals(result.getPersonId(), object.getPersonId());\n        Assert.assertEquals(result.getAge(), object.getAge());\n        Assert.assertEquals(result.getPersonName(), object.getPersonName());\n        Assert.assertEquals(result.getDay(), object.getDay());\n        Assert.assertEquals(result.getMonth(), object.getMonth());\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        EntityManager em = emf.createEntityManager();\n\n        // Delete by query.\n        String deleteQuery = \"Delete from PersonRedis p\";\n        Query query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n\n        em.close();\n\n        emf.close();\n        emf = null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisCompositeKeyTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.entities.RedisCompoundKey;\nimport com.impetus.client.entities.RedisPrimeUser;\n\nimport junit.framework.Assert;\n\n/**\n * The Class RedisCompositeKeyTest.\n */\npublic class RedisCompositeKeyTest\n{\n\n    /** The Constant REDIS_PU. */\n    private static final String REDIS_PU = \"redis_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(REDIS_PU);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test operations.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @Test\n    public void testOperations() throws Exception\n    {\n        testInsert();\n        testQuery();\n        testDelete();\n    }\n\n    /**\n     * Test insert.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    public void testInsert() throws Exception\n    {\n        RedisCompoundKey compoundKey1 = new RedisCompoundKey(\"1\", 101, UUID.randomUUID());\n        RedisPrimeUser user1 = new RedisPrimeUser(compoundKey1);\n        user1.setTweetBody(\"My tweet 1\");\n        user1.setTweetDate(new Date());\n        em.persist(user1);\n\n        RedisCompoundKey compoundKey2 = new RedisCompoundKey(\"2\", 102, UUID.randomUUID());\n        RedisPrimeUser user2 = new RedisPrimeUser(compoundKey2);\n        user2.setTweetBody(\"My tweet 2\");\n        user2.setTweetDate(new Date());\n        em.persist(user2);\n\n        RedisCompoundKey compoundKey3 = new RedisCompoundKey(\"3\", 103, UUID.randomUUID());\n        RedisPrimeUser user3 = new RedisPrimeUser(compoundKey3);\n        user3.setTweetBody(\"My tweet 3\");\n        user3.setTweetDate(new Date());\n        em.persist(user3);\n\n        em.clear();\n\n        RedisPrimeUser user = em.find(RedisPrimeUser.class, compoundKey1);\n        Assert.assertNotNull(user);\n        Assert.assertNotNull(user.getKey());\n        Assert.assertEquals(\"1\", user.getKey().getUserId());\n        Assert.assertEquals(101, user.getKey().getTweetId());\n        Assert.assertEquals(\"My tweet 1\", user.getTweetBody());\n\n    }\n\n    /**\n     * Test query.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    public void testQuery() throws Exception\n    {\n        RedisPrimeUser user = null;\n        List<RedisPrimeUser> users = em.createQuery(\"select u from RedisPrimeUser u\").getResultList();\n        Assert.assertEquals(3, users.size());\n\n        users = em.createQuery(\"select u from RedisPrimeUser u where u.tweetBody='My tweet 2'\").getResultList();\n        Assert.assertEquals(1, users.size());\n        Assert.assertNotNull(users.get(0));\n        user = users.get(0);\n        Assert.assertEquals(\"2\", user.getKey().getUserId());\n        Assert.assertEquals(102, user.getKey().getTweetId());\n        Assert.assertEquals(\"My tweet 2\", user.getTweetBody());\n    }\n\n    /**\n     * Test delete.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    public void testDelete() throws Exception\n    {\n        String deleteQuery = \"Delete from RedisPrimeUser p\";\n        em.createQuery(deleteQuery).executeUpdate();\n\n        List<RedisPrimeUser> users = em.createQuery(\"select u from RedisPrimeUser u\").getResultList();\n        Assert.assertTrue(users.isEmpty());\n    }\n\n    /**\n     * Tear down.\n     *\n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        String deleteQuery = \"Delete from RedisPrimeUser p\";\n        em.createQuery(deleteQuery).executeUpdate();\n\n        if (em != null)\n        {\n            em.close();\n        }\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n}"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisESAggregationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client;\n\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.query.AggregationsBaseTest;\n\n/**\n * The Class RedisESAggregationTest.\n * \n * @author karthikp.manchala\n */\npublic class RedisESAggregationTest extends AggregationsBaseTest\n{\n\n    /** The Constant REDIS_PU. */\n    private static final String REDIS_PU = \"redisElasticSearch_pu\";\n\n    /** The node. */\n    private static Node node = null;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        Builder builder = Settings.settingsBuilder();\n        builder.put(\"path.home\", \"target/data\");\n        node = new NodeBuilder().settings(builder).node();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        testAggregation();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        node.close();\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(REDIS_PU);\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n        String deleteQuery = \"Delete from Person p\";\n        Query query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n        em.flush();\n        em.clear();\n        emf.close();\n    }\n}"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisESGroupByTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client;\n\nimport javax.persistence.Persistence;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.query.GroupByBaseTest;\n\n/**\n * The Class RedisESGroupByTest.\n * \n * @author karthikp.manchala\n */\npublic class RedisESGroupByTest extends GroupByBaseTest\n{\n\n    /** The Constant REDIS_PU. */\n    private static final String REDIS_PU = \"redisElasticSearch_pu\";\n\n    /** The node. */\n    private static Node node = null;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n\n        emf = Persistence.createEntityManagerFactory(REDIS_PU);\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Test aggregation.\n     */\n    @Test\n    public void test()\n    {\n        testAggregation();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        em.createQuery(\"Delete from Person p\").executeUpdate();\n        waitThread();\n\n        em.close();\n        emf.close();\n\n        if (node != null)\n            node.close();\n    }\n}"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisESIndexerTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.entities.Month;\nimport com.impetus.client.entities.PersonRedis;\nimport com.impetus.client.entities.PersonRedis.Day;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\nimport junit.framework.Assert;\n\n/**\n * The Class RedisESIndexerTest.\n * \n * @author Amit Kumar\n */\npublic class RedisESIndexerTest\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /** The Constant REDIS_PU. */\n    private static final String REDIS_PU = \"redisElasticSearch_pu\";\n\n    /** The Constant ROW_KEY. */\n    private static final String ROW_KEY = \"1\";\n\n    /** The node. */\n    private static Node node = null;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(RedisESIndexerTest.class);\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        Builder builder = Settings.settingsBuilder();\n        builder.put(\"path.home\", \"target/data\");\n        node = new NodeBuilder().settings(builder).node();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        node.close();\n        LuceneCleanupUtilities.cleanDir(\"target/data\");\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        emf = Persistence.createEntityManagerFactory(REDIS_PU);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n        purge();\n        emf.close();\n    }\n\n    /**\n     * Crud test with es.\n     */\n    @Test\n    public void crudTestWithES()\n    {\n\n        logger.info(\"Crud tests for ES\");\n        PersonRedis person2 = preparePerson(\"Amit\", \"2\", 40);\n\n        // Persist records\n        em.persist(person2);\n\n        waitThread(10);\n\n        PersonRedis fetchPerson = em.find(PersonRedis.class, \"2\");\n        // Assertion for fetching objects\n        Assert.assertEquals(\"2\", fetchPerson.getPersonId());\n        Assert.assertEquals(\"Amit\", fetchPerson.getPersonName());\n        Assert.assertEquals(40, fetchPerson.getAge().intValue());\n\n        fetchPerson.setAge(50);\n        em.merge(fetchPerson);\n\n        fetchPerson = em.find(PersonRedis.class, \"2\");\n        // Assertion for merge\n        Assert.assertEquals(\"2\", fetchPerson.getPersonId());\n        Assert.assertEquals(\"Amit\", fetchPerson.getPersonName());\n        Assert.assertEquals(50, fetchPerson.getAge().intValue());\n\n        em.remove(fetchPerson);\n        // Assertion for remove\n        fetchPerson = null;\n        fetchPerson = em.find(PersonRedis.class, \"2\");\n        Assert.assertNull(fetchPerson);\n\n    }\n\n    /**\n     * Test like.\n     */\n    @Test\n    // Need to enable the support\n    public void testLike()\n    {\n        PersonRedis person = preparePerson(\"Amit\", ROW_KEY, 32);\n        em.persist(person);\n        person = preparePerson(\"Devender\", ROW_KEY + 1, 34);\n        em.persist(person);\n        waitThread(5);\n\n        Query query;\n        List<PersonRedis> results;\n        // find by key.\n        String findById = \"Select p from PersonRedis p where p.personName like 'mit'\";\n        query = em.createQuery(findById);\n        // query.setParameter(\"personId\", ROW_KEY);\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"Amit\", results.get(0).getPersonName());\n    }\n\n    /**\n     * Query testwith es.\n     */\n    @Test\n    public void QueryTestwithES()\n    {\n\n        logger.info(\"Query tests for ES\");\n        Query query;\n        List<PersonRedis> results;\n\n        // persist record.\n        PersonRedis person = preparePerson(\"Amit\", ROW_KEY, 32);\n        em.persist(person);\n        person = preparePerson(\"Amit\", ROW_KEY + 1, 34);\n        em.persist(person);\n        person = preparePerson(\"Amit\", ROW_KEY + 3, 29);\n        em.persist(person);\n\n        waitThread(10);\n\n        testFindWithOutWhereClause();\n\n        testFindById();\n\n        testFindByNonRowKey();\n\n        testFindByRowAndNonRowKey();\n\n        testFindByBetweenOverNonRowKey();\n\n        testFindByBetweenOverRowKey();\n\n        testFindByGTELTEClauseNonRowKey();\n\n        testFindParticularColumn();\n\n        testFindByIdGTELTE();\n\n        testInvalidDifferentClause();\n\n        testSelectSpecificColumn();\n\n        testORClause();\n\n        testMultipleORClause();\n\n        testDelete();\n    }\n\n    @Test\n    public void indexDeletionTest() throws Exception\n    {\n        // persist record.\n        em.persist(preparePerson(\"Amit\", \"1\", 20));\n        em.persist(preparePerson(\"Amit\", \"2\", 30));\n        em.persist(preparePerson(\"Amit\", \"3\", 40));\n        em.persist(preparePerson(\"Amit\", \"4\", 50));\n        Thread.sleep(1000);\n\n        String query = \"Select min(p.age) from PersonRedis p\";\n        List resultList = em.createQuery(query).getResultList();\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(20.0, resultList.get(0));\n\n        PersonRedis person = em.find(PersonRedis.class, \"1\");\n        em.remove(person);\n        Thread.sleep(1000);\n        query = \"Select min(p.age) from PersonRedis p\";\n        resultList = em.createQuery(query).getResultList();\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(30.0, resultList.get(0));\n\n        person = em.find(PersonRedis.class, \"2\");\n        em.remove(person);\n        Thread.sleep(1000);\n        query = \"Select min(p.age) from PersonRedis p\";\n        resultList = em.createQuery(query).getResultList();\n        Assert.assertEquals(1, resultList.size());\n        Assert.assertEquals(40.0, resultList.get(0));\n    }\n\n    /**\n     * Test delete.\n     */\n    private void testDelete()\n    {\n        Query query;\n        List<PersonRedis> results;\n\n        // Delete by query.\n        String deleteQuery = \"Delete from PersonRedis p\";\n        query = em.createQuery(deleteQuery);\n        int updateCount = query.executeUpdate();\n        Assert.assertEquals(3, updateCount);\n\n        // Search all after delete.\n        String findWithOutWhereClause = \"Select p from PersonRedis p\";\n        query = em.createQuery(findWithOutWhereClause);\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertTrue(results.size() == 0);\n    }\n\n    /**\n     * Test multiple or clause.\n     */\n    private void testMultipleORClause()\n    {\n        Query query;\n        List<PersonRedis> results;\n        String findByIdMoreOrAge = \"Select p from PersonRedis p where p.personId=:personId OR p.age=:age OR p.personName=:personName\";\n        query = em.createQuery(findByIdMoreOrAge);\n        query.setParameter(\"personId\", ROW_KEY);\n        query.setParameter(\"age\", 29);\n        query.setParameter(\"personName\", \"amit\");\n\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n    }\n\n    /**\n     * Test or clause.\n     */\n    private void testORClause()\n    {\n        Query query;\n        List<PersonRedis> results;\n        // Find by key and now row key\n        String findByIdOrAge = \"Select p from PersonRedis p where p.personId=:personId OR p.age=:age\";\n        query = em.createQuery(findByIdOrAge);\n        query.setParameter(\"personId\", ROW_KEY);\n        query.setParameter(\"age\", 29);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        boolean isPresent = false;\n        for (PersonRedis r : results)\n        {\n            if (r.getAge().equals(29) && !r.getPersonId().equals(ROW_KEY))\n            {\n                isPresent = true;\n                break;\n            }\n        }\n\n        Assert.assertTrue(isPresent);\n    }\n\n    /**\n     * Test select specific column.\n     */\n    private void testSelectSpecificColumn()\n    {\n        Query query;\n        List<PersonRedis> results;\n        String findSelective = \"Select p.age from PersonRedis p\";\n        query = em.createQuery(findSelective);\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNotNull(results.get(0).getAge());\n    }\n\n    /**\n     * Test invalid different clause.\n     */\n    private void testInvalidDifferentClause()\n    {\n        Query query;\n        String invalidDifferentClause = \"Select p from PersonRedis p where p.personId=:personId AND p.age >=:age\";\n        query = em.createQuery(invalidDifferentClause);\n        query.setParameter(\"personId\", ROW_KEY);\n        query.setParameter(\"age\", 32);\n        List<PersonRedis> results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNotNull(results.get(0).getPersonName());\n        Assert.assertNotNull(results.get(0).getAge());\n\n    }\n\n    /**\n     * Test find particular column.\n     */\n    private void testFindParticularColumn()\n    {\n        Query query;\n        List<PersonRedis> results;\n        String q = \"select p.personId from PersonRedis p\";\n        query = em.createQuery(q);\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNull(results.get(0).getAge());\n    }\n\n    /**\n     * Find by greater than and less than clause over non row key.\n     */\n    private void testFindByGTELTEClauseNonRowKey()\n    {\n        Query query;\n        List<PersonRedis> results;\n        // Find by greater than and less than clause over non row key\n        String findAgeByGTELTEClause = \"Select p from PersonRedis p where p.age <=:max AND p.age>=:min\";\n        query = em.createQuery(findAgeByGTELTEClause);\n        query.setParameter(\"min\", 32);\n        query.setParameter(\"max\", 35);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(\"Amit\", results.get(0).getPersonName());\n    }\n\n    /**\n     * Between clause over rowkey.\n     */\n    private void testFindByBetweenOverRowKey()\n    {\n        Query query;\n        List<PersonRedis> results;\n        // Between clause over rowkey\n        String findIdByBetween = \"Select p from PersonRedis p where p.personId between :min AND :max\";\n        query = em.createQuery(findIdByBetween);\n        query.setParameter(\"min\", ROW_KEY);\n        query.setParameter(\"max\", ROW_KEY + 1);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(\"Amit\", results.get(0).getPersonName());\n    }\n\n    /**\n     * find by between over non rowkey.\n     */\n    private void testFindByBetweenOverNonRowKey()\n    {\n        Query query;\n        List<PersonRedis> results;\n        // find by between over non rowkey\n        String findAgeByBetween = \"Select p from PersonRedis p where p.age between :min AND :max\";\n        query = em.createQuery(findAgeByBetween);\n        query.setParameter(\"min\", 32);\n        query.setParameter(\"max\", 35);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(\"Amit\", results.get(0).getPersonName());\n    }\n\n    /**\n     * Test find by row and non row key.\n     */\n    private void testFindByRowAndNonRowKey()\n    {\n        Query query;\n        List<PersonRedis> results;\n        // Find by key and now row key\n        String findByIdAndAge = \"Select p from PersonRedis p where p.personId=:personId AND p.age=:age\";\n        query = em.createQuery(findByIdAndAge);\n        query.setParameter(\"personId\", ROW_KEY);\n        query.setParameter(\"age\", 32);\n\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"Amit\", results.get(0).getPersonName());\n    }\n\n    /**\n     * Find by now row key.\n     */\n    private void testFindByNonRowKey()\n    {\n        Query query;\n        List<PersonRedis> results;\n        // Find by now row key\n        String findByAge = \"Select p from PersonRedis p where p.age=:age\";\n        query = em.createQuery(findByAge);\n        query.setParameter(\"age\", 32);\n\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"Amit\", results.get(0).getPersonName());\n        Assert.assertEquals(ROW_KEY, results.get(0).getPersonId());\n    }\n\n    /**\n     * find by key.\n     */\n    private void testFindById()\n    {\n        Query query;\n        List<PersonRedis> results;\n        // find by key.\n        String findById = \"Select p from PersonRedis p where p.personId=:personId\";\n        query = em.createQuery(findById);\n        query.setParameter(\"personId\", ROW_KEY);\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"Amit\", results.get(0).getPersonName());\n    }\n\n    /**\n     * Find without where clause.\n     */\n    private void testFindWithOutWhereClause()\n    {\n        // Find without where clause.\n        String findWithOutWhereClause = \"Select p from PersonRedis p\";\n        Query query = em.createQuery(findWithOutWhereClause);\n        List<PersonRedis> results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n    }\n\n    /**\n     * Find id by greater than and less than clause over non row key.\n     */\n    private void testFindByIdGTELTE()\n    {\n        Query query;\n        List<PersonRedis> results;\n        // Find id by greater than and less than clause over non row key\n        String findIdByGTELTEClause = \"Select p from PersonRedis p where p.age <=:max AND p.age>=:min\";\n        query = em.createQuery(findIdByGTELTEClause);\n        query.setParameter(\"min\", 32);\n        query.setParameter(\"max\", 35);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNotNull(results.get(0).getPersonName());\n        Assert.assertNotNull(results.get(0).getAge());\n    }\n\n    /**\n     * Wait thread.\n     * \n     * @param i\n     *            the i\n     */\n    private void waitThread(int i)\n    {\n\n        try\n        {\n            Thread.sleep(i * 1000);\n\n        }\n        catch (InterruptedException e)\n        {\n\n            logger.info(\"Wait thread interrupted.\");\n        }\n\n    }\n\n    /**\n     * Delete by query.\n     */\n    private void purge()\n    {\n        // Delete by query.\n        String deleteQuery = \"Delete from PersonRedis p\";\n        Query query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n        em.clear();\n        query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n        em.flush();\n        em.clear();\n    }\n\n    /**\n     * Prepare person.\n     * \n     * @param rowId\n     *            the row id\n     * @param age\n     *            the age\n     * @return the person redis\n     */\n    private PersonRedis preparePerson(String pname, String rowId, int age)\n    {\n\n        PersonRedis o = new PersonRedis();\n        o.setPersonId(rowId);\n        o.setPersonName(pname);\n        o.setAge(age);\n        o.setDay(Day.MONDAY);\n        o.setMonth(Month.MARCH);\n        return o;\n    }\n\n}"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisESOrderByTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client;\n\nimport javax.persistence.Persistence;\n\nimport org.elasticsearch.common.settings.Settings;\nimport org.elasticsearch.common.settings.Settings.Builder;\nimport org.elasticsearch.node.Node;\nimport org.elasticsearch.node.NodeBuilder;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.query.OrderByBaseTest;\n\n/**\n * @author Amit Kumar\n * \n */\npublic class RedisESOrderByTest extends OrderByBaseTest\n{\n    /** The Constant REDIS_PU. */\n    private static final String REDIS_PU = \"redisElasticSearch_pu\";\n\n    /** The node. */\n    private static Node node = null;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n        if (!checkIfServerRunning())\n        {\n            Builder builder = Settings.settingsBuilder();\n            builder.put(\"path.home\", \"target/data\");\n            node = new NodeBuilder().settings(builder).node();\n        }\n\n        emf = Persistence.createEntityManagerFactory(REDIS_PU);\n        em = emf.createEntityManager();\n        init();\n    }\n\n    /**\n     * Test Order By.\n     */\n    @Test\n    public void test()\n    {\n        testQuery();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        em.createQuery(\"Delete from Person p\").executeUpdate();\n        waitThread();\n\n        em.close();\n        emf.close();\n\n        if (node != null)\n            node.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisEmbeddableTest.java",
    "content": "package com.impetus.client;\n\nimport java.util.Date;\nimport java.util.UUID;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.entities.RedisCompoundKey;\nimport com.impetus.client.entities.RedisEmbeddedUser;\n\n/**\n * The Class RedisEmbeddableTest.\n */\npublic class RedisEmbeddableTest\n{\n\n    /** The Constant REDIS_PU. */\n    private static final String REDIS_PU = \"redis_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(RedisCompositeKeyTest.class);\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(REDIS_PU);\n    }\n\n    /**\n     * Test crud.\n     */\n    @Test\n    public void testCRUD()\n    {\n        logger.info(\"On testCRUD\");\n        EntityManager em = emf.createEntityManager();\n        final String userId = \"1\";\n        final int tweetId = 12;\n        final UUID timeLineId = UUID.randomUUID();\n        final Date tweetDate = new Date();\n        RedisCompoundKey embeddable = new RedisCompoundKey(userId, tweetId, timeLineId);\n        RedisEmbeddedUser user = new RedisEmbeddedUser(userId);\n        user.setTweetBody(\"My tweet\");\n        user.setTweetDate(tweetDate);\n        user.setEmbeddable(embeddable);\n        em.persist(user);\n\n        em.clear(); // clear cache.\n\n        RedisEmbeddedUser found = em.find(RedisEmbeddedUser.class, userId);\n        Assert.assertNotNull(found);\n        Assert.assertNotNull(found.getUserId());\n        Assert.assertEquals(userId, found.getEmbeddable().getUserId());\n        Assert.assertEquals(tweetDate, found.getTweetDate());\n        em.remove(found);\n\n        em.clear(); // clear cache.\n\n        found = em.find(RedisEmbeddedUser.class, userId);\n        Assert.assertNull(found);\n        em.close();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisLuceneTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.entities.Month;\nimport com.impetus.client.entities.PersonRedis;\nimport com.impetus.client.entities.PersonRedis.Day;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.utils.LuceneCleanupUtilities;\n\n/**\n * @author Amit Kumar\n * \n */\npublic class RedisLuceneTest\n{\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /** The Constant REDIS_PU. */\n    private static final String REDIS_PU = \"redis_pu\";\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(RedisESIndexerTest.class);\n\n    /** The property map. */\n    protected Map<String, String> propertyMap = new HashMap<String, String>();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        propertyMap.put(\"index.home.dir\", \"./lucene\");\n        emf = Persistence.createEntityManagerFactory(\"redisLucene_pu\", propertyMap);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n        LuceneCleanupUtilities.cleanDir(\"./lucene\");\n        LuceneCleanupUtilities.cleanLuceneDirectory(((EntityManagerFactoryImpl) emf).getKunderaMetadataInstance()\n                .getApplicationMetadata().getPersistenceUnitMetadata(\"redisLucene_pu\"));\n        // Delete by query.\n        String deleteQuery = \"Delete from PersonRedis p\";\n        Query query = em.createQuery(deleteQuery);\n        int updateCount = query.executeUpdate();\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void crudTestWithLucene()\n    {\n\n        logger.info(\"Crud tests for Lucene\");\n\n        PersonRedis person1 = preparePerson(\"101\", 20);\n        PersonRedis person2 = preparePerson(\"102\", 40);\n        PersonRedis person3 = preparePerson(\"103\", 60);\n\n        // Persist records\n        em.persist(person1);\n        em.persist(person2);\n        em.persist(person3);\n\n        PersonRedis fetchPerson = em.find(PersonRedis.class, \"102\");\n        // Assertion for fetching objects\n        Assert.assertEquals(\"102\", fetchPerson.getPersonId());\n        Assert.assertEquals(\"Amit\", fetchPerson.getPersonName());\n        Assert.assertEquals(40, fetchPerson.getAge().intValue());\n\n        fetchPerson.setAge(50);\n        em.merge(fetchPerson);\n\n        fetchPerson = em.find(PersonRedis.class, \"102\");\n        // Assertion for merge\n        Assert.assertEquals(\"102\", fetchPerson.getPersonId());\n        Assert.assertEquals(\"Amit\", fetchPerson.getPersonName());\n        Assert.assertEquals(50, fetchPerson.getAge().intValue());\n\n        em.remove(fetchPerson);\n        // Assertion for remove\n        fetchPerson = null;\n        fetchPerson = em.find(PersonRedis.class, \"102\");\n        Assert.assertNull(fetchPerson);\n\n        em.remove(em.find(PersonRedis.class, \"101\"));\n        em.remove(em.find(PersonRedis.class, \"103\"));\n    }\n\n    @Test\n    public void queryTestWithLucene()\n    {\n        init();\n        em.clear();\n\n        String qry = \"Select p.personName, p.age from PersonRedis p where p.personId = 1 and p.age = 10\";\n        Query q = em.createQuery(qry);\n        List<PersonRedis> persons = q.getResultList();\n        assertNotNull(persons);\n        assertEquals(1, persons.size());\n        assertNull(persons.get(0).getMonth());\n        assertNull(persons.get(0).getDay());\n        assertEquals(10, persons.get(0).getAge().intValue());\n        assertEquals(\"Amit\", persons.get(0).getPersonName());\n\n        qry = \"Select p.personName from PersonRedis p where p.age=20\";\n        q = em.createQuery(qry);\n        persons = q.getResultList();\n        assertNotNull(persons);\n        assertEquals(1, persons.size());\n        assertNull(persons.get(0).getMonth());\n        assertNull(persons.get(0).getDay());\n        assertNull(persons.get(0).getAge());\n        assertEquals(\"Amit\", persons.get(0).getPersonName());\n\n        qry = \"Select p.age from PersonRedis p where p.personId = 2\";\n        q = em.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        assertNull(persons.get(0).getMonth());\n        assertNull(persons.get(0).getDay());\n        assertNull(persons.get(0).getPersonName());\n        assertEquals(20, persons.get(0).getAge().intValue());\n\n        qry = \"Select p from PersonRedis p\";\n        q = em.createQuery(qry);\n        persons = q.getResultList();\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(3, persons.size());\n\n        testFindByGreaterThan();\n\n        testFindByLessThan();\n\n        testFindByBetweenOverNonRowKey();\n\n        qry = \"Update PersonRedis p set p.personName= 'Amit Kumar' where p.age = 20\";\n        q = em.createQuery(qry);\n        int updateCount = q.executeUpdate();\n\n        Assert.assertEquals(1, updateCount);\n\n        qry = \"Select p from PersonRedis p where p.age = 20\";\n        q = em.createQuery(qry);\n        persons = q.getResultList();\n\n        Assert.assertNotNull(persons);\n        Assert.assertEquals(1, persons.size());\n        assertEquals(\"Amit Kumar\", persons.get(0).getPersonName());\n        assertEquals(20, persons.get(0).getAge().intValue());\n\n        qry = \"delete from PersonRedis p where p.age = 20\";\n        q = em.createQuery(qry);\n        int count = q.executeUpdate();\n\n        Assert.assertEquals(1, count);\n        assertNull(em.find(PersonRedis.class, \"2\"));\n    }\n\n    /**\n     * find by Greater than over rowkey.\n     */\n    private void testFindByGreaterThan()\n    {\n        Query query;\n        List<PersonRedis> results;\n        String findAgeByBetween = \"Select p from PersonRedis p where p.age > 17\";\n        query = em.createQuery(findAgeByBetween);\n\n        results = query.getResultList();\n\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"2\", results.get(0).getPersonId());\n        Assert.assertEquals(\"Amit\", results.get(0).getPersonName());\n        Assert.assertEquals(20, results.get(0).getAge().intValue());\n    }\n\n    /**\n     * find by less than over rowkey.\n     */\n    private void testFindByLessThan()\n    {\n        Query query;\n        List<PersonRedis> results;\n        String findAgeByBetween = \"Select p from PersonRedis p where p.age < 12\";\n        query = em.createQuery(findAgeByBetween);\n\n        results = query.getResultList();\n\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"1\", results.get(0).getPersonId());\n        Assert.assertEquals(\"Amit\", results.get(0).getPersonName());\n        Assert.assertEquals(10, results.get(0).getAge().intValue());\n    }\n\n    /**\n     * find by between over non rowkey.\n     */\n    private void testFindByBetweenOverNonRowKey()\n    {\n        Query query;\n        List<PersonRedis> results;\n        String findAgeByBetween = \"Select p from PersonRedis p where p.age between :min AND :max\";\n        query = em.createQuery(findAgeByBetween);\n        query.setParameter(\"min\", 10);\n        query.setParameter(\"max\", 19);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(\"Amit\", results.get(0).getPersonName());\n    }\n\n    private void init()\n    {\n        Object p1 = preparePerson(\"1\", 10);\n        Object p2 = preparePerson(\"2\", 20);\n        Object p3 = preparePerson(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n    }\n\n    private PersonRedis preparePerson(String rowId, int age)\n    {\n\n        PersonRedis o = new PersonRedis();\n        o.setPersonId(rowId);\n        o.setPersonName(\"Amit\");\n        o.setAge(age);\n        o.setDay(Day.MONDAY);\n        o.setMonth(Month.MARCH);\n        return o;\n    }\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisMappedSuperClassTest.java",
    "content": "package com.impetus.client;\n\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.crud.mappedsuperclass.MappedSuperClassBase;\n\npublic class RedisMappedSuperClassTest extends MappedSuperClassBase\n{\n\n    @Before\n    public void setUp() throws Exception\n    {\n        _PU = \"redis_pu\";\n        setUpInternal();\n    }\n    \n    @Test\n    public void test()\n    {\n        assertInternal(true);\n    }\n\n    \n    @After\n    public void tearDown() throws Exception\n    {\n        // Delete by query.\n        String deleteQuery = \"Delete from CreditTransaction p\";\n        \n        Query query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n\n        deleteQuery = \"Delete from DebitTransaction p\";\n        \n        query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n\n        tearDownInternal();\n        \n\n    }\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\n\npackage com.impetus.client;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.entities.PersonRedis;\nimport com.impetus.kundera.query.QueryHandlerException;\n\n/**\n * @author vivek\n * \n */\npublic class RedisQueryTest\n{\n\n    private static final String ROW_KEY = \"1\";\n\n    /** The Constant REDIS_PU. */\n    private static final String REDIS_PU = \"redis_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n    \n    /** The em. */\n    private EntityManager em;\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(RedisQueryTest.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(REDIS_PU);\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testPopulateEntites()\n    {\n        logger.info(\"On testPopulateEntities\");\n\n        \n        purge();\n\n        final String originalName = \"vivek\";\n\n        // persist record.\n        PersonRedis object = new PersonRedis();\n        object.setAge(32);\n        object.setPersonId(ROW_KEY);\n        object.setPersonName(originalName);\n\n        em.persist(object);\n\n        object.setAge(34);\n        object.setPersonId(ROW_KEY + 1);\n        object.setPersonName(originalName);\n\n        em.persist(object);\n\n        object.setAge(29);\n        object.setPersonId(ROW_KEY + 3);\n        object.setPersonName(originalName);\n\n        em.persist(object);\n\n        // Find without where clause.\n        String findWithOutWhereClause = \"Select p from PersonRedis p\";\n        Query query = em.createQuery(findWithOutWhereClause);\n        List<PersonRedis> results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n\n        // find by key.\n        String findById = \"Select p from PersonRedis p where p.personId=:personId\";\n        query = em.createQuery(findById);\n        query.setParameter(\"personId\", ROW_KEY);\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n\n        // Find by key and now row key\n        String findByAge = \"Select p from PersonRedis p where p.age=:age\";\n        query = em.createQuery(findByAge);\n        query.setParameter(\"age\", 32);\n\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n        Assert.assertEquals(ROW_KEY, results.get(0).getPersonId());\n\n        // Find by key and now row key\n        String findByIdAndAge = \"Select p from PersonRedis p where p.personId=:personId AND p.age=:age\";\n        query = em.createQuery(findByIdAndAge);\n        query.setParameter(\"personId\", ROW_KEY);\n        query.setParameter(\"age\", 32);\n\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n\n        // find by between over non rowkey\n        String findAgeByBetween = \"Select p from PersonRedis p where p.age between :min AND :max\";\n        query = em.createQuery(findAgeByBetween);\n        query.setParameter(\"min\", 32);\n        query.setParameter(\"max\", 35);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n\n        // Between clause over rowkey\n        String findIdByBetween = \"Select p from PersonRedis p where p.personId between :min AND :max\";\n        query = em.createQuery(findIdByBetween);\n        query.setParameter(\"min\", ROW_KEY);\n        query.setParameter(\"max\", ROW_KEY + 1);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n\n        // Find by greater than and less than clause over non row key\n        String findAgeByGTELTEClause = \"Select p from PersonRedis p where p.age <=:max AND p.age>=:min\";\n        query = em.createQuery(findAgeByGTELTEClause);\n        query.setParameter(\"min\", 32);\n        query.setParameter(\"max\", 35);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n\n        String q = \"select p.personId from PersonRedis p\";\n        query = em.createQuery(q);\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNull(results.get(0).getAge());\n\n        // Find id by greater than and less than clause over non row key\n        String findIdByGTELTEClause = \"Select p from PersonRedis p where p.age <=:max AND p.age>=:min\";\n        query = em.createQuery(findIdByGTELTEClause);\n        query.setParameter(\"min\", 32);\n        query.setParameter(\"max\", 35);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertNotNull(results.get(0).getPersonId());\n        Assert.assertNotNull(results.get(0).getPersonName());\n        Assert.assertNotNull(results.get(0).getAge());\n\n        // Invalid scenario.\n        try\n        {\n            String invalidDifferentClause = \"Select p from PersonRedis p where p.personId=:personId AND p.age >=:age\";\n            query = em.createQuery(invalidDifferentClause);\n            query.setParameter(\"personId\", ROW_KEY);\n            query.setParameter(\"age\", 32);\n            query.getResultList();\n            Assert.fail(\"Must have thrown query handler exception!\");\n        }\n\n        catch (QueryHandlerException qhex)\n        {\n            Assert.assertNotNull(qhex);\n        }\n\n        // More than TWO AND clause\n        // OR Clause\n\n        // Find without where clause on SELECTIVE COLUMN\n        // TODOOOOOOOOOOOOOOOOOOOOOOO.\n        String findSelective = \"Select p.age from PersonRedis p\";\n        query = em.createQuery(findSelective);\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        Assert.assertNull(results.get(0).getPersonName());\n        Assert.assertNotNull(results.get(0).getAge());\n\n        // Find by key and now row key\n        String findByIdOrAge = \"Select p from PersonRedis p where p.personId=:personId OR p.age=:age\";\n        query = em.createQuery(findByIdOrAge);\n        query.setParameter(\"personId\", ROW_KEY);\n        query.setParameter(\"age\", 29);\n\n        results = query.getResultList();\n        Assert.assertEquals(2, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n        boolean isPresent = false;\n        for (PersonRedis r : results)\n        {\n            if (r.getAge().equals(29) && !r.getPersonId().equals(ROW_KEY))\n            {\n                isPresent = true;\n                break;\n            }\n        }\n\n        Assert.assertTrue(isPresent);\n\n        String findByIdMoreOrAge = \"Select p from PersonRedis p where p.personId=:personId OR p.age=:age OR p.personName=:personName\";\n        query = em.createQuery(findByIdMoreOrAge);\n        query.setParameter(\"personId\", ROW_KEY);\n        query.setParameter(\"age\", 29);\n        query.setParameter(\"personName\", originalName);\n\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        Assert.assertEquals(originalName, results.get(0).getPersonName());\n\n        // TODOOOO: selective column search\n\n        // Delete by query.\n        String deleteQuery = \"Delete from PersonRedis p\";\n        query = em.createQuery(deleteQuery);\n        int updateCount = query.executeUpdate();\n\n        Assert.assertEquals(3, updateCount);\n\n        // Search all after delete.\n        findWithOutWhereClause = \"Select p from PersonRedis p\";\n        query = em.createQuery(findWithOutWhereClause);\n        results = query.getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertTrue(results.isEmpty());\n    }\n\n    private void purge()\n    {\n        // Delete by query.\n        String deleteQuery = \"Delete from PersonRedis p\";\n        Query query = em.createQuery(deleteQuery);\n        int updateCount = query.executeUpdate();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        purge();\n        em.close();\n        emf.close();\n        emf = null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisShowQueryTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client;\n\nimport static org.junit.Assert.fail;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.FileReader;\nimport java.io.PrintStream;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * \n * @author shaheed.hussain\n *\n */\npublic class RedisShowQueryTest\n{\n\n    private static final String REDIS_PU = \"redis_pu\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Map<String, String> puProperties = new HashMap<String, String>();\n\n    private Logger logger = LoggerFactory.getLogger(RedisShowQueryTest.class);\n\n    private File file = null;\n\n    @After\n    public void tearDown() throws Exception\n    {\n        file.delete();\n        em.close();\n        emf.close();\n        puProperties = null;\n    }\n\n    /*\n     * testing show.query property when it is disabled\n     */\n    @Test\n    public void testShowQueryDisabled()\n    {\n        emf = Persistence.createEntityManagerFactory(REDIS_PU);\n        em = emf.createEntityManager();\n\n        try\n        {\n            boolean isFileEmpty = false;\n            BufferedReader br = null;\n            file = new File(\"showQuery.log\");\n            PrintStream printStream;\n\n            printStream = new PrintStream(new FileOutputStream(file));\n            System.setOut(printStream);\n            Query findQuery = em.createQuery(\"Select s from UserInformation s\");\n            findQuery.getResultList();\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select p from UserInformation p where p.id=\\\"PK_1\\\"\");\n            findQuery.getResultList();\n            System.setOut(printStream);\n\n            // and query is not supported in oracle nosql\n            findQuery = em.createQuery(\"Select p from UserInformation p where p.id=\\\"Shahid\\\"\");\n            findQuery.getResultList();\n            System.setOut(printStream);\n\n            br = new BufferedReader(new FileReader(\"showQuery.log\"));\n            isFileEmpty = br.readLine() == null;\n            Assert.assertEquals(isFileEmpty, true);\n\n        }\n        catch (Exception e)\n        {\n            logger.info(e.getMessage());\n        }\n\n    }\n\n    /*\n     * testing kunera.show.query property when it is enabled\n     */\n    @Test\n    public void testShowQueryEnabled()\n    {\n        puProperties.put(\"kundera.show.query\", \"true\");\n        emf = Persistence.createEntityManagerFactory(REDIS_PU, puProperties);\n        em = emf.createEntityManager();\n        try\n        {\n\n            int i = 0;\n            String expectedQuery[] = new String[3];\n            String actualQuery = null;\n            BufferedReader br = null;\n            file = new File(\"showQuery.log\");\n            PrintStream printStream;\n\n            printStream = new PrintStream(new FileOutputStream(file));\n            System.setOut(printStream);\n\n            Query findQuery = em.createQuery(\"Select p from UserInformation p where p.id=PK_1\");\n            findQuery.getResultList();\n            expectedQuery[0] = \"Fetch data from UserInformation for PK PK_1\";\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select p from UserInformation p where p.id=Shahid\");\n            findQuery.getResultList();\n            expectedQuery[1] = \"Fetch data from UserInformation for PK Shahid\";\n            System.setOut(printStream);\n\n            findQuery = em.createQuery(\"Select p from UserInformation p where p.age between 32 and 35\");\n            findQuery.getResultList();\n            System.setOut(printStream);\n            expectedQuery[2] = \"Fetching primary key from UserInformation corresponding to age between {age=32.0} and {age=35.0}\";\n\n            br = new BufferedReader(new FileReader(\"showQuery.log\"));\n            actualQuery = br.readLine();\n            if (actualQuery == null)\n                fail(\"failed as file is empty\");\n\n            while (actualQuery != null)\n            {\n                Assert.assertEquals(expectedQuery[i++], actualQuery);\n                actualQuery = br.readLine();\n            }\n        }\n        catch (Exception e)\n        {\n            logger.info(e.getMessage());\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/RedisTransactionTest.java",
    "content": "package com.impetus.client;\n\nimport java.io.IOException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport javax.xml.registry.InvalidRequestException;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.entities.PersonRedis;\n\npublic class RedisTransactionTest\n{\n\n    private static final String ROW_KEY = \"1\";\n\n    /** The Constant REDIS_PU. */\n    private static final String REDIS_PU = \"redis_pu\";\n\n    /** The emf. */\n    private EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(RedisTransactionTest.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(REDIS_PU);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * On rollback.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onRollback() throws Exception\n    {\n        purge();\n        em.getTransaction().begin();\n\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        // roll back.\n        em.getTransaction().rollback();\n        PersonRedis p = em.find(PersonRedis.class, \"1\");\n        Assert.assertNull(p);\n\n        // on commit.\n\n        // Still no record should be flushed as already rollback!\n        p = em.find(PersonRedis.class, \"1\");\n        Assert.assertNull(p);\n    }\n\n    /**\n     * On commit.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void onCommit() throws Exception\n    {\n        purge();\n        // em.setFlushMode(FlushModeType.COMMIT);\n\n        em.getTransaction().begin();\n\n        Object p1 = prepareData(\"1\", 10);\n        Object p2 = prepareData(\"2\", 20);\n        Object p3 = prepareData(\"3\", 15);\n        em.persist(p1);\n        em.persist(p2);\n        em.persist(p3);\n\n        // on commit.\n        em.getTransaction().commit();\n\n        em.getTransaction().begin();\n\n        PersonRedis p = em.find(PersonRedis.class, \"1\");\n        Assert.assertNotNull(p);\n\n        ((PersonRedis) p2).setPersonName(\"rollback\");\n        em.merge(p2);\n\n        // roll back, should roll back person name for p2!\n        em.getTransaction().rollback();\n\n        p = em.find(PersonRedis.class, \"1\");\n        Assert.assertNotNull(p);\n\n        p = em.find(PersonRedis.class, \"2\");\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertNotSame(\"rollback\", p.getPersonName());\n\n        em.getTransaction().begin();\n        em.getTransaction().commit();\n    }\n\n    /**\n     * Rollback on error.\n     * \n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    @Test\n    public void rollbackOnError() throws Exception\n    {\n        purge();\n        PersonRedis p = null;\n        try\n        {\n            Object p1 = prepareData(\"1\", 10);\n            Object p2 = prepareData(\"2\", 20);\n            em.persist(p1);\n            em.persist(p2);\n\n            p = em.find(PersonRedis.class, \"1\");\n            Assert.assertNotNull(p);\n\n            Object p3 = prepareData(\"3\", 15);\n            em.persist(p3);\n\n            // Assert on rollback on error.\n            ((PersonRedis) p2).setPersonName(\"rollback\");\n            em.merge(p2);\n            em.merge(null);\n\n            // As this is a runtime exception so rollback should happen and\n            // delete out commited data.\n        }\n        catch (Exception ex)\n        {\n            em.clear();\n            p = em.find(PersonRedis.class, \"1\");\n            Assert.assertNull(p);\n\n            p = em.find(PersonRedis.class, \"2\");\n            Assert.assertNull(p);\n\n            p = em.find(PersonRedis.class, \"3\");\n            Assert.assertNull(p);\n        }\n        em.clear();\n        // persist with 1 em\n        EntityManager em1 = emf.createEntityManager();\n        // em1.setFlushMode(FlushModeType.COMMIT);\n        em1.getTransaction().begin();\n        Object p3 = prepareData(\"4\", 15);\n        em1.persist(p3);\n        em1.getTransaction().commit();\n\n        try\n        {\n            // remove with another em with auto flush.\n            EntityManager em2 = emf.createEntityManager();\n            PersonRedis person = em2.find(PersonRedis.class, \"4\");\n            em2.remove(person);\n            em2.merge(null);\n        }\n        catch (Exception ex)\n        {\n            em1.clear();\n            p = em.find(PersonRedis.class, \"4\");\n            Assert.assertNotNull(p);\n            Assert.assertEquals(\"vivek\", p.getPersonName());\n\n        }\n    }\n\n    /**\n     * Roll back with multi transactions.\n     */\n    @Test\n    public void rollBackWithMultiTransactions()\n    {\n        purge();\n        EntityManager em1 = emf.createEntityManager();\n        // em1.setFlushMode(FlushModeType.COMMIT);\n\n        // Begin transaction.\n        em1.getTransaction().begin();\n        Object p1 = prepareData(\"11\", 10);\n        em1.persist(p1);\n\n        // commit p1.\n        em1.getTransaction().commit();\n\n        // another em instance\n        EntityManager em2 = emf.createEntityManager();\n        // em2.setFlushMode(FlushModeType.COMMIT);\n\n        // begin transaction.\n        PersonRedis found = em2.find(PersonRedis.class, \"11\");\n\n        em2.getTransaction().begin();\n        found.setPersonName(\"merged\");\n        em2.merge(found);\n\n        // // commit p1 after modification.\n        em2.getTransaction().commit();\n\n        // open another entity manager.\n        EntityManager em3 = emf.createEntityManager();\n        found = em3.find(PersonRedis.class, \"11\");\n        found.setPersonName(\"lastemerge\");\n        try\n        {\n            em3.merge(found);\n            em3.merge(null);\n        }\n        catch (Exception ex)\n        {\n            PersonRedis finalFound = em2.find(PersonRedis.class, \"11\");\n            Assert.assertNotNull(finalFound);\n            Assert.assertEquals(\"merged\", finalFound.getPersonName());\n        }\n    }\n\n    /**\n     * Prepare data.\n     * \n     * @param rowKey\n     *            the row key\n     * @param age\n     *            the age\n     * @return the person\n     */\n    private PersonRedis prepareData(String rowKey, int age)\n    {\n        PersonRedis o = new PersonRedis();\n        o.setPersonId(rowKey);\n        o.setPersonName(\"vivek\");\n        o.setAge(age);\n        return o;\n    }\n    \n    private void purge()\n    {\n        // Delete by query.\n        String deleteQuery = \"Delete from PersonRedis p\";\n        Query query = em.createQuery(deleteQuery);\n        int updateCount = query.executeUpdate();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        \n        purge();\n\n        em.close();\n        emf.close();\n        emf = null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/entities/AddressMTMRedis.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n\n@Entity\n@Table(name=\"AddressMTM\", schema=\"RedisK@redis_pu\")\npublic class AddressMTMRedis {\n\n\n\t@Id\n\t@Column(name=\"ADDRESS_ID\")\n\tprivate Double addressId;\n\n\t@Column(name=\"address\")\n\tprivate String address;\n\n\tpublic  AddressMTMRedis() {\n\n\t}\n\n\tpublic  AddressMTMRedis(Double addId) {\n\n\t\tthis.addressId=addId;\n\t}\n\n\tpublic Double getAddressId() {\n\t\treturn addressId;\n\t}\n\n\tpublic void setAddressId(Double addressId) {\n\t\tthis.addressId = addressId;\n\t}\n\n\tpublic String getAddress() {\n\t\treturn address;\n\t}\n\n\tpublic void setAddress(String address) {\n\t\tthis.address = address;\n\t}\n}"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/entities/AddressMTORedis.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n\n@Entity\n@Table(name=\"AddressMTO\", schema=\"RedisK@redis_pu\")\npublic class AddressMTORedis {\n\n\n\t@Id\n\t@Column(name=\"ADDRESS_ID\")\n\tprivate Double addressId;\n\n\t@Column(name=\"address\")\n\tprivate String address;\n\n\tpublic  AddressMTORedis() {\n\n\t}\n\n\tpublic  AddressMTORedis(Double addId) {\n\n\t\tthis.addressId=addId;\n\t}\n\n\tpublic Double getAddressId() {\n\t\treturn addressId;\n\t}\n\n\tpublic void setAddressId(Double addressId) {\n\t\tthis.addressId = addressId;\n\t}\n\n\tpublic String getAddress() {\n\t\treturn address;\n\t}\n\n\tpublic void setAddress(String address) {\n\t\tthis.address = address;\n\t}\n}"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/entities/AddressOTORedis.java",
    "content": "package com.impetus.client.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"Address\", schema = \"RedisK@redis_pu\")\npublic class AddressOTORedis\n{\n\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private Double addressId;\n\n    public AddressOTORedis()\n    {\n\n    }\n\n    public AddressOTORedis(Double addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    @Column(name = \"address\")\n    private String address;\n\n    public String getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    public Double getAddressId()\n    {\n        return addressId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/entities/Month.java",
    "content": "package com.impetus.client.entities;\n\npublic enum Month\n{\n    JAN, FEB, MARCH, APRIL, MAY, JUNE;\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/entities/PersonMTMRedis.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name=\"PERSONMTM\",schema=\"RedisK@redis_pu\")\npublic class PersonMTMRedis {\n\n\t@Id\n\t@Column(name = \"PERSON_ID\")\n\tprivate String personId;\n\n\t/** The person name. */\n\t@Column(name = \"PERSON_NAME\")\n\tprivate String personName;\n\n\t/** The age. */\n\t@Column(name = \"AGE\")\n\tprivate Integer age;\n\n\t@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n\t@JoinTable(name = \"ADDRESS_ID\", schema = \"RedisK\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n\tprivate Set<AddressMTMRedis> address;\n\n\tpublic PersonMTMRedis(String personId)\n\t{\n\t\tthis.personId = personId;\n\t}\n\n\tpublic PersonMTMRedis()\n\t{\n\n\t}\n\n\t/**\n\t * Gets the person id.\n\t * \n\t * @return the person id\n\t */\n\tpublic String getPersonId()\n\t{\n\t\treturn personId;\n\t}\n\n\t/**\n\t * Gets the person name.\n\t * \n\t * @return the person name\n\t */\n\tpublic String getPersonName()\n\t{\n\t\treturn personName;\n\t}\n\n\t/**\n\t * Sets the person name.\n\t * \n\t * @param personName\n\t *            the new person name\n\t */\n\tpublic void setPersonName(String personName)\n\t{\n\t\tthis.personName = personName;\n\t}\n\n\t/**\n\t * Sets the person id.\n\t * \n\t * @param personId\n\t *            the new person id\n\t */\n\tpublic void setPersonId(String personId)\n\t{\n\t\tthis.personId = personId;\n\t}\n\n\t/**\n\t * @return the age\n\t */\n\tpublic Integer getAge()\n\t{\n\t\treturn age;\n\t}\n\n\t/**\n\t * @param age\n\t *            the age to set\n\t */\n\tpublic void setAge(int age)\n\t{\n\t\tthis.age = age;\n\t}\n\n\tpublic Set<AddressMTMRedis> getAddress()\n\t{\n\t\treturn address;\n\t}\n\n\tpublic void setAddress(Set<AddressMTMRedis> address)\n\t{\n\t\tthis.address = address;\n\t}\n\n\tpublic void setAge(Integer age)\n\t{\n\t\tthis.age = age;\n\t}\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/entities/PersonMTORedis.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name=\"PERSONMTO\",schema=\"RedisK@redis_pu\")\npublic class PersonMTORedis {\n\n\t@Id\n\t@Column(name = \"PERSON_ID\")\n\tprivate String personId;\n\n\t/** The person name. */\n\t@Column(name = \"PERSON_NAME\")\n\tprivate String personName;\n\n\t/** The age. */\n\t@Column(name = \"AGE\")\n\tprivate Integer age;\n\n\t@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n\t@JoinColumn(name = \"ADDRESS_ID\")\n\tprivate AddressMTORedis address;\n\n\tpublic PersonMTORedis(String personId)\n\t{\n\t\tthis.personId = personId;\n\t}\n\n\tpublic PersonMTORedis()\n\t{\n\n\t}\n\n\t/**\n\t * Gets the person id.\n\t * \n\t * @return the person id\n\t */\n\tpublic String getPersonId()\n\t{\n\t\treturn personId;\n\t}\n\n\t/**\n\t * Gets the person name.\n\t * \n\t * @return the person name\n\t */\n\tpublic String getPersonName()\n\t{\n\t\treturn personName;\n\t}\n\n\t/**\n\t * Sets the person name.\n\t * \n\t * @param personName\n\t *            the new person name\n\t */\n\tpublic void setPersonName(String personName)\n\t{\n\t\tthis.personName = personName;\n\t}\n\n\t/**\n\t * Sets the person id.\n\t * \n\t * @param personId\n\t *            the new person id\n\t */\n\tpublic void setPersonId(String personId)\n\t{\n\t\tthis.personId = personId;\n\t}\n\n\t/**\n\t * @return the age\n\t */\n\tpublic Integer getAge()\n\t{\n\t\treturn age;\n\t}\n\n\t/**\n\t * @param age\n\t *            the age to set\n\t */\n\tpublic void setAge(int age)\n\t{\n\t\tthis.age = age;\n\t}\n\n\tpublic AddressMTORedis getAddress()\n\t{\n\t\treturn address;\n\t}\n\n\tpublic void setAddress(AddressMTORedis address)\n\t{\n\t\tthis.address = address;\n\t}\n\n\tpublic void setAge(Integer age)\n\t{\n\t\tthis.age = age;\n\t}\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/entities/PersonOTORedis.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON\", schema = \"RedisK@redis_pu\")\npublic class PersonOTORedis\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressOTORedis address;\n\n    public PersonOTORedis(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public PersonOTORedis()\n    {\n\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public AddressOTORedis getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressOTORedis address)\n    {\n        this.address = address;\n    }\n\n    public void setAge(Integer age)\n    {\n        this.age = age;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/entities/PersonRedis.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Person.\n */\n@Entity\n@Table(name = \"PERSON_REDIS\")\n@IndexCollection(columns={@Index(name=\"personName\"),@Index(name=\"age\")})\npublic class PersonRedis\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n\n    @Column(name = \"ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Day day;\n\n    @Column(name = \"MONTH_ENUM\")\n    @Enumerated(EnumType.STRING)\n    private Month month;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public Integer getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    public Day getDay()\n    {\n        return day;\n    }\n\n    public void setDay(Day day)\n    {\n        this.day = day;\n    }\n\n    public Month getMonth()\n    {\n        return month;\n    }\n\n    public void setMonth(Month month)\n    {\n        this.month = month;\n    }\n\n    public enum Day\n    {\n        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/entities/RedisCompoundKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.entities;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\n\n/**\n * @author vivek.mishra\n */\n@Embeddable\npublic class RedisCompoundKey\n{\n    @Column\n    private String userId;\n\n    @Column\n    private int tweetId;\n\n    @Column\n    private UUID timeLineId;\n\n    /**\n     * \n     */\n    public RedisCompoundKey()\n    {\n    }\n\n    /**\n     * @param userId\n     * @param tweetId\n     * @param timeLineId\n     */\n    public RedisCompoundKey(String userId, int tweetId, UUID timeLineId)\n    {\n        this.userId = userId;\n        this.tweetId = tweetId;\n        this.timeLineId = timeLineId;\n    }\n\n    /**\n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * @return the tweetId\n     */\n    public int getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * @return the timeLineId\n     */\n    public UUID getTimeLineId()\n    {\n        return timeLineId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/entities/RedisEmbeddedUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class RedisEmbeddedUser.\n * \n * @author vivek.mishra\n */\n\n@Entity\n@Table(name = \"User\", schema = \"RedisK@redis_pu\")\npublic class RedisEmbeddedUser\n{\n\n    /** The user id. */\n    @Id\n    private String userId;\n\n    /** The embeddable. */\n    @Embedded\n    private RedisCompoundKey embeddable;\n\n    /** The tweet body. */\n    @Column\n    private String tweetBody;\n\n    /** The tweet date. */\n    @Column\n    private Date tweetDate;\n\n    /**\n     * Instantiates a new redis embedded user.\n     */\n    public RedisEmbeddedUser()\n    {\n    }\n\n    /**\n     * Instantiates a new redis embedded user.\n     * \n     * @param userId\n     *            the user id\n     */\n    public RedisEmbeddedUser(String userId)\n    {\n        this.userId = userId;\n    }\n\n    /**\n     * Gets the tweet body.\n     * \n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * Gets the tweet date.\n     * \n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * Sets the tweet body.\n     * \n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * Sets the tweet date.\n     * \n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n    /**\n     * Gets the user id.\n     * \n     * @return the user id\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * Gets the embeddable.\n     * \n     * @return the embeddable\n     */\n    public RedisCompoundKey getEmbeddable()\n    {\n        return embeddable;\n    }\n\n    /**\n     * Sets the embeddable.\n     * \n     * @param embeddable\n     *            the new embeddable\n     */\n    public void setEmbeddable(RedisCompoundKey embeddable)\n    {\n        this.embeddable = embeddable;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/entities/RedisPrimeUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.entities;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"User\", schema = \"RedisK@redis_pu\")\n@IndexCollection(columns={@Index(name=\"tweetBody\")})\npublic class RedisPrimeUser\n{\n\n    @EmbeddedId\n    private RedisCompoundKey key;\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private Date tweetDate;\n\n    public RedisPrimeUser()\n    {\n    }\n\n    public RedisPrimeUser(RedisCompoundKey key)\n    {\n        this.key = key;\n    }\n\n    /**\n     * @return the key\n     */\n    public RedisCompoundKey getKey()\n    {\n        return key;\n    }\n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/entities/UserInformation.java",
    "content": "package com.impetus.client.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"UserInformation\")\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"age\") })\npublic class UserInformation\n{\n    @Id\n    private String id;\n\n    @Column\n    private String name;\n\n    @Column\n    private int age;\n\n    public String getId()\n    {\n        return id;\n    }\n\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    public String getName()\n    {\n        return name;\n    }\n\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    public int getAge()\n    {\n        return age;\n    }\n\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n}\n\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/generatedId/RedisGeneratedIdTest.java",
    "content": "package com.impetus.client.generatedId;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.generatedId.entites.RedisGeneratedIdDefault;\nimport com.impetus.client.generatedId.entites.RedisGeneratedIdStrategyAuto;\nimport com.impetus.client.generatedId.entites.RedisGeneratedIdStrategyIdentity;\nimport com.impetus.client.generatedId.entites.RedisGeneratedIdStrategySequence;\nimport com.impetus.client.generatedId.entites.RedisGeneratedIdStrategyTable;\nimport com.impetus.client.generatedId.entites.RedisGeneratedIdWithOutSequenceGenerator;\nimport com.impetus.client.generatedId.entites.RedisGeneratedIdWithOutTableGenerator;\nimport com.impetus.client.generatedId.entites.RedisGeneratedIdWithSequenceGenerator;\nimport com.impetus.client.generatedId.entites.RedisGeneratedIdWithTableGenerator;\nimport com.impetus.client.redis.RedisClient;\nimport com.impetus.kundera.KunderaException;\n\npublic class RedisGeneratedIdTest\n{\n\n    private EntityManagerFactory emf;\n    \n    private EntityManager em;\n\n    @BeforeClass\n    public static void setUpBeforeClass() throws Exception\n    {\n    }\n\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n    }\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"redis_pu\");\n        em = emf.createEntityManager();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    { \n\n        purge();\n\n        em.close();\n\n        emf.close();\n    }\n\n    /**\n     * \n     */\n    private void purge()\n    {\n        // Delete by query.\n        String deleteQuery = \"Delete from RedisGeneratedIdStrategySequence r\";\n        Query query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n\n        deleteQuery = \"Delete from RedisGeneratedIdWithOutSequenceGenerator r\";\n        query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n\n        deleteQuery = \"Delete from RedisGeneratedIdWithSequenceGenerator r\";\n        query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n    }\n\n    @Test\n    public void testPersist()\n    {\n        purge();\n        RedisGeneratedIdDefault idDefault = new RedisGeneratedIdDefault();\n        idDefault.setName(\"kuldeep\");\n        try\n        {\n            em.persist(idDefault);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                    + GenerationType.AUTO + \" Strategy not supported by this client :\" + RedisClient.class.getName(),\n                    e.getMessage());\n        }\n        RedisGeneratedIdStrategyAuto strategyAuto = new RedisGeneratedIdStrategyAuto();\n        strategyAuto.setName(\"kuldeep\");\n        em.clear();\n        try\n        {\n            em.persist(strategyAuto);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                    + GenerationType.AUTO + \" Strategy not supported by this client :\" + RedisClient.class.getName(),\n                    e.getMessage());\n        }\n        em.clear();\n        RedisGeneratedIdStrategyIdentity strategyIdentity = new RedisGeneratedIdStrategyIdentity();\n        strategyIdentity.setName(\"kuldeep\");\n        try\n        {\n            em.persist(strategyIdentity);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\n                    \"java.lang.UnsupportedOperationException: \" + GenerationType.class.getSimpleName() + \".\"\n                            + GenerationType.IDENTITY + \" Strategy not supported by this client :\"\n                            + RedisClient.class.getName(), e.getMessage());\n        }\n        em.clear();\n        RedisGeneratedIdStrategySequence strategySequence = new RedisGeneratedIdStrategySequence();\n        strategySequence.setName(\"Kuldeep\");\n        try\n        {\n            em.persist(strategySequence);\n            List<RedisGeneratedIdStrategySequence> list = em.createQuery(\n                    \"Select c from RedisGeneratedIdStrategySequence c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"Kuldeep\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            strategySequence = em.find(RedisGeneratedIdStrategySequence.class, id);\n            Assert.assertNotNull(strategySequence);\n            Assert.assertEquals(\"Kuldeep\", strategySequence.getName());\n        }\n        catch (KunderaException e)\n        {\n            \n            Assert.fail();\n        }\n        em.clear();\n        RedisGeneratedIdStrategyTable strategyTable = new RedisGeneratedIdStrategyTable();\n        strategyTable.setName(\"KK\");\n        try\n        {\n            em.persist(strategyTable);\n            Assert.fail();\n\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                    + GenerationType.TABLE + \" Strategy not supported by this client :\" + RedisClient.class.getName(),\n                    e.getMessage());\n        }\n        em.clear();\n        RedisGeneratedIdWithOutSequenceGenerator withOutSequenceGenerator = new RedisGeneratedIdWithOutSequenceGenerator();\n        withOutSequenceGenerator.setName(\"Kuldeep Kumar\");\n        try\n        {\n            em.persist(withOutSequenceGenerator);\n            List<RedisGeneratedIdWithOutSequenceGenerator> list = em.createQuery(\n                    \"Select c from RedisGeneratedIdWithOutSequenceGenerator c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"Kuldeep Kumar\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            withOutSequenceGenerator = em.find(RedisGeneratedIdWithOutSequenceGenerator.class, id);\n            Assert.assertNotNull(withOutSequenceGenerator);\n            Assert.assertEquals(\"Kuldeep Kumar\", withOutSequenceGenerator.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n        em.clear();\n        RedisGeneratedIdWithOutTableGenerator withOutTableGenerator = new RedisGeneratedIdWithOutTableGenerator();\n        withOutTableGenerator.setName(\"Kuldeep Mishra\");\n        try\n        {\n            em.persist(withOutTableGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                    + GenerationType.TABLE + \" Strategy not supported by this client :\" + RedisClient.class.getName(),\n                    e.getMessage());\n        }\n        em.clear();\n        RedisGeneratedIdWithSequenceGenerator withSequenceGenerator = new RedisGeneratedIdWithSequenceGenerator();\n        withSequenceGenerator.setName(\"Kuldeep Kumar Mishra\");\n        try\n        {\n            em.persist(withSequenceGenerator);\n            List<RedisGeneratedIdWithSequenceGenerator> list = em.createQuery(\n                    \"Select c from RedisGeneratedIdWithSequenceGenerator c\").getResultList();\n            Assert.assertNotNull(list);\n            Assert.assertEquals(1, list.size());\n            Assert.assertEquals(\"Kuldeep Kumar Mishra\", list.get(0).getName());\n            Object id = list.get(0).getId();\n            em.clear();\n            withSequenceGenerator = em.find(RedisGeneratedIdWithSequenceGenerator.class, id);\n            Assert.assertNotNull(withSequenceGenerator);\n            Assert.assertEquals(\"Kuldeep Kumar Mishra\", withSequenceGenerator.getName());\n        }\n        catch (KunderaException e)\n        {\n            Assert.fail();\n        }\n        em.clear();\n        RedisGeneratedIdWithTableGenerator withTableGenerator = new RedisGeneratedIdWithTableGenerator();\n        withTableGenerator.setName(\"Kumar Mishra\");\n        try\n        {\n            em.persist(withTableGenerator);\n            Assert.fail();\n        }\n        catch (KunderaException e)\n        {\n            Assert.assertEquals(\"java.lang.IllegalArgumentException: \" + GenerationType.class.getSimpleName() + \".\"\n                    + GenerationType.TABLE + \" Strategy not supported by this client :\" + RedisClient.class.getName(),\n                    e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/generatedId/entites/RedisGeneratedIdDefault.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"RedisGeneratedIdDefault\", schema = \"RedisK@redis_pu\")\npublic class RedisGeneratedIdDefault\n{\n    @Id\n    @GeneratedValue\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/generatedId/entites/RedisGeneratedIdStrategyAuto.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"RedisGeneratedIdStrategyAuto\", schema = \"RedisK@redis_pu\")\n@TableGenerator(name = \"id_gen\")\npublic class RedisGeneratedIdStrategyAuto\n{\n    @Id\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.AUTO)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/generatedId/entites/RedisGeneratedIdStrategyIdentity.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"RedisGeneratedIdStrategyIdentity\", schema = \"RedisK@redis_pu\")\npublic class RedisGeneratedIdStrategyIdentity\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.IDENTITY)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/generatedId/entites/RedisGeneratedIdStrategySequence.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"RedisGeneratedIdStrategySequence\", schema = \"RedisK@redis_pu\")\npublic class RedisGeneratedIdStrategySequence\n{\n    @Id\n    @SequenceGenerator(name = \"seq_gen\")\n    @GeneratedValue(generator = \"seq_gen\", strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/generatedId/entites/RedisGeneratedIdStrategyTable.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"RedisGeneratedIdStrategyTable\", schema = \"RedisK@redis_pu\")\n@TableGenerator(name = \"table_gen\")\npublic class RedisGeneratedIdStrategyTable\n{\n\n    @Id\n    @TableGenerator(name = \"table_gen_1\")\n    @GeneratedValue(generator = \"table_gen\", strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/generatedId/entites/RedisGeneratedIdWithOutSequenceGenerator.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"RedisGeneratedIdWithOutSequenceGenerator\", schema = \"RedisK@redis_pu\")\npublic class RedisGeneratedIdWithOutSequenceGenerator\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/generatedId/entites/RedisGeneratedIdWithOutTableGenerator.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"RedisGeneratedIdWithOutTableGenerator\", schema = \"RedisK@redis_pu\")\npublic class RedisGeneratedIdWithOutTableGenerator\n{\n\n    @Id\n    @GeneratedValue(strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/generatedId/entites/RedisGeneratedIdWithSequenceGenerator.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.SequenceGenerator;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"RedisGeneratedIdWithSequenceGenerator\", schema = \"RedisK@redis_pu\")\npublic class RedisGeneratedIdWithSequenceGenerator\n{\n    @Id\n    @SequenceGenerator(name = \"id_gen\", allocationSize = 20, initialValue = 80, schema = \"RedisK\", sequenceName = \"newSequence\")\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.SEQUENCE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/generatedId/entites/RedisGeneratedIdWithTableGenerator.java",
    "content": "package com.impetus.client.generatedId.entites;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.TableGenerator;\n\n@Entity\n@Table(name = \"RedisGeneratedIdWithTableGenerator\", schema = \"RedisK@redis_pu\")\npublic class RedisGeneratedIdWithTableGenerator\n{\n\n    @Id\n    @TableGenerator(name = \"id_gen\", allocationSize = 30, initialValue = 100, schema = \"RedisK\", table = \"kundera\", pkColumnName = \"sequence\", valueColumnName = \"sequenceValue\", pkColumnValue = \"kk\")\n    @GeneratedValue(generator = \"id_gen\", strategy = GenerationType.TABLE)\n    private int id;\n\n    @Column\n    private String name;\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/validation/BookEntity.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.validation;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Devender Yadav\n * \n */\n@Entity\n@Table(name = \"BOOK_ENTITY\", schema = \"RedisK@redis_pu\")\npublic class BookEntity\n{\n\n    @Id\n    @Column(name = \"ID\")\n    private int bookId;\n\n    @Column(name = \"TITLE\")\n    private String title;\n\n    @Column(name = \"AUTHOR\")\n    private String author;\n\n    @Column(name = \"PAGES\")\n    private int pages;\n\n    protected BookEntity()\n    {\n    }\n\n    public int getBookId()\n    {\n        return bookId;\n    }\n\n    public void setBookId(int bookId)\n    {\n        this.bookId = bookId;\n    }\n\n    public String getTitle()\n    {\n        return title;\n    }\n\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    public int getPages()\n    {\n        return pages;\n    }\n\n    public void setPages(int pages)\n    {\n        this.pages = pages;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/client/validation/ConstructorValidationTest.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.validation;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.Test;\n\n/**\n * @author Devender Yadav\n * \n */\npublic class ConstructorValidationTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    @Test\n    public void validConstructorTest() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(\"redis_pu\");\n        em = emf.createEntityManager();\n        BookEntity book = new BookEntity();\n        book.setBookId(1);\n        book.setTitle(\"The Complete Reference\");\n        book.setAuthor(\"Herbert Schildt\");\n        book.setPages(500);\n\n        em.persist(book);\n\n        em.clear();\n\n        BookEntity book1 = em.find(BookEntity.class, 1);\n\n        Assert.assertNotNull(book1);\n        Assert.assertEquals(1, book1.getBookId());\n        Assert.assertEquals(\"The Complete Reference\", book1.getTitle());\n        Assert.assertEquals(\"Herbert Schildt\", book1.getAuthor());\n        Assert.assertEquals(500, book1.getPages());\n\n        em.remove(book1);\n\n        BookEntity book2 = em.find(BookEntity.class, 1);\n        Assert.assertNull(book2);\n\n        em.close();\n        emf.close();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/CreditTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n * Credit transaction extends {@link Transaction}\n *\n */\n\n@Entity\n@Table(name = \"TRNX_CREDIT\")\n@DiscriminatorValue(value = \"credit\")\n@AttributeOverride(name=\"bankIdentifier\",column= @Column(name=\"CREDIT_BANK_IDENT\"))\n@IndexCollection(columns={@Index(name=\"bankIdentifier\")})\npublic class CreditTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public CreditTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/kundera/client/crud/mappedsuperclass/DebitTransaction.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.crud.mappedsuperclass;\n\nimport javax.persistence.AttributeOverride;\nimport javax.persistence.AttributeOverrides;\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.EnumType;\nimport javax.persistence.Enumerated;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * @author vivek.mishra\n * Debit transaction extends {@link Transaction}\n *\n */\n@Entity\n@DiscriminatorValue(value=\"debit\")\n\n@AttributeOverrides(value = { @AttributeOverride(name = \"txId\", column = @Column(name = \"DEBIT_ID\")),\n        @AttributeOverride(name = \"bankIdentifier\", column = @Column(name = \"DEBIT_BANK_IDENT\")),\n        @AttributeOverride(name = \"transactionDt\", column = @Column(name = \"TX_DT\")) })\n@IndexCollection(columns={@Index(name=\"bankIdentifier\")})\npublic class DebitTransaction extends Transaction\n{\n\n    @Column\n    private Integer amount;\n\n    @Column\n    @Enumerated(EnumType.STRING)\n    private Status txStatus;\n\n    public DebitTransaction()\n    {\n        \n    }\n    \n    public Integer getAmount()\n    {\n        return amount;\n    }\n\n    public void setAmount(Integer amount)\n    {\n        this.amount = amount;\n    }\n\n    public Status getTxStatus()\n    {\n        return txStatus;\n    }\n\n    public void setTxStatus(Status txStatus)\n    {\n        this.txStatus = txStatus;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/java/com/impetus/kundera/client/mappedsuperclass/inheritance/RedisEntityWithoutFieldsTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.client.mappedsuperclass.inheritance;\n\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.metadata.mappedsuperclass.EntityWithoutFieldsTest;\n\n/**\n * @author amitkumar\n *\n *\tClass to verify that at least one field in entity class is not mandatory if the \n *\tsuperclass contains all the mandatory fields\n */\npublic class RedisEntityWithoutFieldsTest extends EntityWithoutFieldsTest{\n\n\t@Before\n\tpublic void setup()\n\t{\n\t\tpersistenceUnit = \"redisMappedSuperClass_pu\";\n\t\tsetupInternal();\n\t}\n\t\n\t@Test\n\tpublic void testEntityWithNoFields()\n\t{\n\t\ttestEntityWithNoFieldsBase();\n\t}\n\t\n\t@Test\n\tpublic void testEntityWithNoFields2LevelInheritance()\n\t{\n\t\ttestEntityWithNoFields2LevelInheritanceBase();\n\t}\n\n\t@After\n\tpublic void tearDown()\n\t{\n                em.createQuery(\"Delete from Person p\").executeUpdate();\n\t\ttearDownInternal();\n\t}\n}\n"
  },
  {
    "path": "src/kundera-redis/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\n\t<persistence-unit name=\"redis_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\n\t\t\t<property name=\"kundera.port\" value=\"6379\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"RedisK\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"redis\" />\n\t\t\t<property name=\"kundera.client\" value=\"redis\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.redis.RedisClientFactory\" />\n\t\t\t<property name=\"kundera.password\" value=\"Kundera@123\" />\n\t\t\t<!-- <property name=\"kundera.transaction.timeout\" value=\"30\" /> -->\n\t\t\t<!-- <property name=\"kundera.pool.size.max.active\" value=\"10\" /> -->\n\t\t\t<property name=\"kundera.client.property\" value=\"RedisTest.xml\" />\n\t\t\t<property name=\"kundera.transaction.resource.class\" value=\"com.impetus.client.redis.RedisTransaction\" />\n\t\t\t<property name=\"kundera.indexer.class\" value=\"com.impetus.client.redis.RedisIndexer\" />\n\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"redisClientFactoryTest_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\n\t\t\t<property name=\"kundera.port\" value=\"5000\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"RedisK\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"redis\" />\n\t\t\t<property name=\"kundera.client\" value=\"redis\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.redis.RedisClientFactory\" />\n\t\t\t<property name=\"kundera.password\" value=\"Kundera@123\" />\n\t\t\t<!-- <property name=\"kundera.transaction.timeout\" value=\"30\" /> -->\n\t\t\t<property name=\"kundera.pool.size.max.active\" value=\"5\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"RedisTest.xml\" />\n\t\t\t<property name=\"kundera.transaction.resource.class\" value=\"com.impetus.client.redis.RedisTransaction\" />\n\t\t\t<property name=\"kundera.indexer.class\" value=\"com.impetus.client.redis.RedisIndexer\" />\n\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"redisElasticSearch_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.query.Person</class>\n\t\t<class>com.impetus.client.entities.PersonRedis</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\n\t\t\t<property name=\"kundera.port\" value=\"6379\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"RedisKES\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"redis\" />\n\t\t\t<property name=\"kundera.client\" value=\"redis\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.redis.RedisClientFactory\" />\n\t\t\t<property name=\"kundera.password\" value=\"Kundera@123\" />\n\t\t\t<property name=\"kundera.transaction.resource.class\" value=\"com.impetus.client.redis.RedisTransaction\" />\n\t\t\t<property name=\"kundera.indexer.class\" value=\"com.impetus.client.es.index.ESIndexer\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"redisLucene_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"6379\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"RedisKLucene\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"redis\" />\n\t\t\t<property name=\"kundera.client\" value=\"redis\" />\n\t\t\t<property name=\"kundera.password\" value=\"Kundera@123\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.redis.RedisClientFactory\" />\n\t\t\t<property name=\"kundera.transaction.resource.class\" value=\"com.impetus.client.redis.RedisTransaction\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"redisMappedSuperClass_pu\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.Person</class>\n\t\t<class>com.impetus.kundera.metadata.mappedsuperclass.PersonChild</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\n\t\t\t<property name=\"kundera.port\" value=\"6379\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"RedisK\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"redis\" />\n\t\t\t<property name=\"kundera.client\" value=\"redis\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.redis.RedisClientFactory\" />\n\t\t\t<property name=\"kundera.password\" value=\"Kundera@123\" />\n\t\t\t<!-- <property name=\"kundera.transaction.timeout\" value=\"30\" /> -->\n\t\t\t<!-- <property name=\"kundera.pool.size.max.active\" value=\"10\" /> -->\n\t\t\t<!-- <property name=\"kundera.client.property\" value=\"RedisTest.xml\" /> -->\n\t\t\t<property name=\"kundera.transaction.resource.class\" value=\"com.impetus.client.redis.RedisTransaction\" />\n\t\t\t<property name=\"kundera.indexer.class\" value=\"com.impetus.client.redis.RedisIndexer\" />\n\n\n\t\t</properties>\n\t</persistence-unit>\n\n</persistence>"
  },
  {
    "path": "src/kundera-redis/src/test/resources/RedisTest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>redis</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"port\" value=\"6379\"></property>\n\t\t\t\t\t<property name=\"host\" value=\"localhost\"></property>\n\t\t\t\t\t<!-- <property name=\"timeout\" value=\"300\"></property> -->\n\t\t\t\t\t<property name=\"dbfilename\" value=\"kunderadump.rdb\"></property>\n\t\t\t\t\t<property name=\"requirepass\" value=\"Kundera@123\"></property>\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>\n"
  },
  {
    "path": "src/kundera-redis/src/test/resources/esindexer.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<indexerProperties>\n\t<nodes>\n\t\t<node>\n\t\t\t<properties>\n\t\t\t\t<property name=\"host\" value=\"localhost\" />\n\t\t\t\t<property name=\"port\" value=\"9300\" />\n\t\t\t</properties>\n\t\t</node>\n\t</nodes>\n</indexerProperties>\n"
  },
  {
    "path": "src/kundera-rest/pom.xml",
    "content": "<?xml version=\"1.0\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<artifactId>kundera</artifactId>\n\t\t<groupId>com.impetus</groupId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-rest</artifactId>\n\t<name>kundera-rest</name>\n\t<url>http://maven.apache.org</url>\n\n\t<dependencies>\n\t\t<!-- JAX-RS Libraries -->\n\t\t<dependency>\n\t\t\t<groupId>com.sun.jersey</groupId>\n\t\t\t<artifactId>jersey-server</artifactId>\n\t\t\t<version>1.18.1</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.sun.jersey</groupId>\n\t\t\t<artifactId>jersey-core</artifactId>\n\t\t\t<version>1.18.1</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.sun.jersey</groupId>\n\t\t\t<artifactId>jersey-servlet</artifactId>\n\t\t\t<version>1.18.1</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.sun.jersey</groupId>\n\t\t\t<artifactId>jersey-json</artifactId>\n\t\t\t<version>1.18.1</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.fasterxml.jackson.core</groupId>\n\t\t\t<artifactId>jackson-annotations</artifactId>\n\t\t\t<version>2.4.4</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.fasterxml.jackson.core</groupId>\n\t\t\t<artifactId>jackson-core</artifactId>\n\t\t\t<version>2.4.4</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.fasterxml.jackson.core</groupId>\n\t\t\t<artifactId>jackson-databind</artifactId>\n\t\t\t<version>2.4.4</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.fasterxml.jackson.module</groupId>\n\t\t\t<artifactId>jackson-module-jsonSchema</artifactId>\n\t\t\t<version>2.4.4</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.fasterxml.jackson.dataformat</groupId>\n\t\t\t<artifactId>jackson-dataformat-xml</artifactId>\n\t\t\t<version>2.4.4</version>\n\t\t</dependency>\n\n\n\t\t<!-- Unit Testing libraries -->\n\t\t<dependency>\n\t\t\t<groupId>com.sun.jersey.jersey-test-framework</groupId>\n\t\t\t<artifactId>jersey-test-framework-grizzly</artifactId>\n\t\t\t<version>1.9.1</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<!-- contiperf dependency should not be here -->\n\t\t<dependency>\n\t\t\t<groupId>org.databene</groupId>\n\t\t\t<artifactId>contiperf</artifactId>\n\t\t\t<version>2.2.0</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>javax.ws.rs</groupId>\n\t\t\t\t\t<artifactId>javax.ws.rs-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>javax</groupId>\n\t\t\t\t\t<artifactId>javaee-web-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.glassfish</groupId>\n\t\t\t\t\t<artifactId>javax.faces</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>javax.jws</groupId>\n\t\t\t\t\t<artifactId>jsr181-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>javax.xml.ws</groupId>\n\t\t\t\t\t<artifactId>jaxws-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-mongo</artifactId>\n\t\t\t<version>${project.version}</version>\n\n\t\t</dependency>\n\t</dependencies>\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<!-- <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> \n\t\t\t\t<configuration> The destination file for the code coverage report has to \n\t\t\t\tbe set to the same value in the parent pom and in each module pom. Then JaCoCo \n\t\t\t\twill add up information in the same report, so that, it will give the cross-module \n\t\t\t\tcode coverage. <destFile>${project.basedir}/../target/jacoco-it.exec</destFile> \n\t\t\t\t</configuration> <executions> <execution> <id>post-test</id> <configuration> \n\t\t\t\t<skip>true</skip> </configuration> </execution> </executions> </plugin> -->\n\n\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/common/Constants.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.common;\r\n\r\n/**\r\n * Holds constants\r\n * \r\n * @author amresh.singh\r\n */\r\npublic interface Constants\r\n{\r\n    public static final String KUNDERA_API_PATH = \"kundera/api\";\r\n\r\n    public static final String KUNDERA_REST_RESOURCES_PACKAGE = \"com.impetus.kundera.rest.resources\";\r\n\r\n    /** Token prefixes */\r\n    public static final String APPLICATION_TOKEN_PREFIX = \"AT\";\r\n\r\n    public static final String SESSION_TOKEN_PREFIX = \"ST\";\r\n\r\n    /** Header Names */\r\n    public static final String APPLICATION_TOKEN_HEADER_NAME = \"x-at\";\r\n\r\n    public static final String SESSION_TOKEN_HEADER_NAME = \"x-st\";\r\n\r\n    /** Resources */\r\n    public static final String APPLICATION_RESOURCE_PATH = \"/application\";\r\n\r\n    public static final String SESSION_RESOURCE_PATH = \"/session\";\r\n    \r\n    public static final String TRANSACTION_RESOURCE_PATH = \"/tx\";\r\n\r\n    public static final String CRUD_RESOURCE_PATH = \"/crud\";\r\n\r\n    public static final String JPA_QUERY_RESOURCE_PATH = \"/query/jpa\";\r\n\r\n    public static final String NATIVE_QUERY_RESOURCE_PATH = \"/query/native/\";\r\n\r\n    public static final String META_DATA_RESOURCE_PATH = \"/metadata\";\r\n\r\n    public static final String NAMED_QUERY_ALL = \"all\";\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/common/EntityUtils.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.rest.common;\r\n\r\nimport java.io.IOException;\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\nimport java.util.StringTokenizer;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.Parameter;\r\nimport javax.persistence.Query;\r\nimport javax.ws.rs.HttpMethod;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\nimport org.codehaus.jackson.JsonParseException;\r\nimport org.codehaus.jackson.map.JsonMappingException;\r\nimport org.codehaus.jackson.map.ObjectMapper;\r\nimport org.codehaus.jackson.type.TypeReference;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\r\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\r\nimport com.impetus.kundera.property.PropertyAccessor;\r\nimport com.impetus.kundera.property.PropertyAccessorFactory;\r\nimport com.impetus.kundera.query.KunderaQuery;\r\nimport com.impetus.kundera.query.QueryImpl;\r\n\r\n/**\r\n * Utility methods for handling entities passed in REST request\r\n * \r\n * @author amresh\r\n * \r\n */\r\npublic class EntityUtils {\r\n\r\n    public static Map<String, String> httpMethods = new HashMap<String, String>();\r\n\r\n    private static Logger log = LoggerFactory.getLogger(EntityUtils.class);\r\n\r\n    static {\r\n        httpMethods.put(HttpMethod.GET, \"SELECT\");\r\n        httpMethods.put(HttpMethod.POST, \"INSERT\");\r\n        httpMethods.put(HttpMethod.PUT, \"UPDATE\");\r\n        httpMethods.put(HttpMethod.DELETE, \"DELETE\");\r\n    }\r\n\r\n    /**\r\n     * @param entityClassName\r\n     * @param em\r\n     * @return\r\n     */\r\n    public static AbstractManagedType getEntityManagedType(String entityClassName, EntityManager em) {\r\n        MetamodelImpl metamodel = (MetamodelImpl) em.getEntityManagerFactory().getMetamodel();\r\n        Class<?> entityClass = metamodel.getEntityClass(entityClassName);\r\n        EntityMetadata entityMetadata = metamodel.getEntityMetadata(entityClass);\r\n        AbstractManagedType managedType = (AbstractManagedType) metamodel.entity(entityMetadata.getEntityClazz());\r\n        return managedType;\r\n    }\r\n\r\n    /**\r\n     * @param entityClassName\r\n     * @param em\r\n     * @return\r\n     */\r\n    public static Class<?> getEntityClass(String entityClassName, EntityManager em) {\r\n        MetamodelImpl metamodel = (MetamodelImpl) em.getEntityManagerFactory().getMetamodel();\r\n        Class<?> entityClass = metamodel.getEntityClass(entityClassName);\r\n        return entityClass;\r\n    }\r\n\r\n    /**\r\n     * @param entityClassName\r\n     * @param em\r\n     * @return\r\n     */\r\n    public static EntityMetadata getEntityMetaData(String entityClassName, EntityManager em) {\r\n        MetamodelImpl metamodel = (MetamodelImpl) em.getEntityManagerFactory().getMetamodel();\r\n        Class<?> entityClass = metamodel.getEntityClass(entityClassName);\r\n\r\n        return metamodel.getEntityMetadata(entityClass);\r\n    }\r\n\r\n    public static String getQueryPart(String fullQueryString) {\r\n        if (fullQueryString.contains(\"?\")) {\r\n            return fullQueryString.substring(0, fullQueryString.indexOf(\"?\"));\r\n        } else {\r\n            return fullQueryString;\r\n        }\r\n    }\r\n\r\n    public static String getParameterPart(String fullQueryString) {\r\n        if (fullQueryString.contains(\"?\")) {\r\n            return fullQueryString.substring(fullQueryString.indexOf(\"?\") + 1, fullQueryString.length());\r\n        } else {\r\n            return \"\";\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @param queryString\r\n     * @param q\r\n     * @param em\r\n     */\r\n    public static void setObjectQueryParameters(String queryString, String parameterString, Query q, EntityManager em,\r\n        String mediaType) {\r\n        MetamodelImpl metamodel = (MetamodelImpl) em.getEntityManagerFactory().getMetamodel();\r\n\r\n        if (parameterString == null || parameterString.isEmpty()) {\r\n            return;\r\n        }\r\n\r\n        Map<String, String> paramsMap = new HashMap<String, String>();\r\n        ObjectMapper mapper = new ObjectMapper();\r\n\r\n        try {\r\n            paramsMap = mapper.readValue(parameterString, new TypeReference<HashMap<String, String>>() {\r\n            });\r\n            KunderaQuery kq = ((QueryImpl) q).getKunderaQuery();\r\n            Set<Parameter<?>> parameters = kq.getParameters();\r\n            for (String paramName : paramsMap.keySet()) {\r\n                String value = paramsMap.get(paramName);\r\n\r\n                if (paramName.equalsIgnoreCase(\"firstResult\")) {\r\n                    q.setFirstResult(Integer.parseInt(value));\r\n\r\n                } else if (paramName.equalsIgnoreCase(\"maxResult\")) {\r\n                    q.setMaxResults(Integer.parseInt(value));\r\n\r\n                } else if (StringUtils.isNumeric(paramName)) {\r\n                    for (Parameter param : parameters) {\r\n                        if (param.getPosition() == Integer.parseInt(paramName)) {\r\n\r\n                            Class<?> paramClass = param.getParameterType();\r\n                            Object paramValue = null;\r\n                            if (metamodel.isEmbeddable(paramClass)) {\r\n                                paramValue =\r\n                                    JAXBUtils.toObject(StreamUtils.toInputStream(value), paramClass, mediaType);\r\n\r\n                            } else {\r\n                                PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);\r\n                                paramValue = accessor.fromString(paramClass, value);\r\n                            }\r\n\r\n                            q.setParameter(Integer.parseInt(paramName), paramValue);\r\n                            break;\r\n                        }\r\n                    }\r\n                } else {\r\n                    for (Parameter param : parameters) {\r\n                        if (param.getName().equals(paramName)) {\r\n\r\n                            Class<?> paramClass = param.getParameterType();\r\n                            Object paramValue = null;\r\n\r\n                            if (metamodel.isEmbeddable(paramClass)) {\r\n                                paramValue =\r\n                                    JAXBUtils.toObject(StreamUtils.toInputStream(value), paramClass, mediaType);\r\n\r\n                            } else {\r\n                                PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);\r\n                                paramValue = accessor.fromString(paramClass, value);\r\n                            }\r\n                            q.setParameter(paramName, paramValue);\r\n                            break;\r\n                        }\r\n                    }\r\n\r\n                }\r\n            }\r\n\r\n        } catch (JsonParseException e) {\r\n            log.error(e.getMessage());\r\n        } catch (JsonMappingException e) {\r\n            log.error(e.getMessage());\r\n        } catch (IOException e) {\r\n            log.error(e.getMessage());\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @param queryString\r\n     * @param q\r\n     */\r\n    public static void setQueryParameters(String queryString, String parameterString, Query q) {\r\n        Map<String, String> paramsMap = new HashMap<String, String>();\r\n\r\n        StringTokenizer st = new StringTokenizer(parameterString, \"&\");\r\n        while (st.hasMoreTokens()) {\r\n            String element = st.nextToken();\r\n            paramsMap.put(element.substring(0, element.indexOf(\"=\")),\r\n                element.substring(element.indexOf(\"=\") + 1, element.length()));\r\n        }\r\n        KunderaQuery kq = ((QueryImpl) q).getKunderaQuery();\r\n        Set<Parameter<?>> parameters = kq.getParameters();\r\n        for (String paramName : paramsMap.keySet()) {\r\n            String value = paramsMap.get(paramName);\r\n            if (paramName.equalsIgnoreCase(\"firstResult\")) {\r\n                q.setFirstResult(Integer.parseInt(value));\r\n            } else if (paramName.equalsIgnoreCase(\"maxResult\")) {\r\n                q.setMaxResults(Integer.parseInt(value));\r\n            } else if (StringUtils.isNumeric(paramName)) {\r\n                for (Parameter param : parameters) {\r\n                    if (param.getPosition() == Integer.parseInt(paramName)) {\r\n                        Class<?> paramClass = param.getParameterType();\r\n                        PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);\r\n                        Object paramValue = accessor.fromString(paramClass, value);\r\n                        q.setParameter(Integer.parseInt(paramName), paramValue);\r\n                        break;\r\n                    }\r\n                }\r\n            } else {\r\n                for (Parameter param : parameters) {\r\n                    if (param.getName().equals(paramName)) {\r\n                        Class<?> paramClass = param.getParameterType();\r\n                        PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);\r\n                        Object paramValue = accessor.fromString(paramClass, value);\r\n                        q.setParameter(paramName, paramValue);\r\n\r\n                        break;\r\n                    }\r\n                }\r\n\r\n            }\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @param queryString\r\n     * @param q\r\n     */\r\n    public static void setQueryParameters(String queryString, HashMap<String, String> paramsMap, Query q) {\r\n        KunderaQuery kq = ((QueryImpl) q).getKunderaQuery();\r\n        Set<Parameter<?>> parameters = kq.getParameters();\r\n        for (String paramName : paramsMap.keySet()) {\r\n            String value = paramsMap.get(paramName);\r\n\r\n            if (StringUtils.isNumeric(paramName)) {\r\n                for (Parameter param : parameters) {\r\n                    if (param.getPosition() == Integer.parseInt(paramName)) {\r\n                        Class<?> paramClass = param.getParameterType();\r\n                        PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);\r\n                        Object paramValue = accessor.fromString(paramClass, value);\r\n                        q.setParameter(Integer.parseInt(paramName), paramValue);\r\n                        break;\r\n                    }\r\n                }\r\n            } else {\r\n                for (Parameter param : parameters) {\r\n                    if (param.getName().equals(paramName)) {\r\n                        Class<?> paramClass = param.getParameterType();\r\n                        PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);\r\n                        Object paramValue = accessor.fromString(paramClass, value);\r\n                        if (paramName.equalsIgnoreCase(\"firstResult\")) {\r\n                            q.setFirstResult(Integer.parseInt((String) paramValue));\r\n                        } else if (paramName.equalsIgnoreCase(\"maxResult\")) {\r\n                            q.setMaxResults(Integer.parseInt((String) paramValue));\r\n                        } else {\r\n                            q.setParameter(paramName, paramValue);\r\n                        }\r\n                        break;\r\n                    }\r\n                }\r\n\r\n            }\r\n        }\r\n    }\r\n\r\n    public static boolean isValidQuery(String queryString, String httpMethod) {\r\n        if (queryString == null || httpMethod == null) {\r\n            return false;\r\n        }\r\n        queryString = queryString.trim();\r\n        if (queryString.length() < 6)\r\n            return false;\r\n        String firstKeyword = queryString.substring(0, 6);\r\n        String allowedKeyword = httpMethods.get(httpMethod);\r\n\r\n        if (allowedKeyword != null && firstKeyword.equalsIgnoreCase(allowedKeyword)) {\r\n            return true;\r\n        } else {\r\n            return false;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/common/JAXBUtils.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.common;\r\n\r\nimport java.io.ByteArrayOutputStream;\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.util.ArrayList;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.ws.rs.core.MediaType;\r\nimport javax.xml.bind.JAXBContext;\r\nimport javax.xml.bind.JAXBException;\r\nimport javax.xml.bind.SchemaOutputResolver;\r\nimport javax.xml.transform.Result;\r\nimport javax.xml.transform.stream.StreamResult;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.fasterxml.jackson.core.JsonParseException;\r\nimport com.fasterxml.jackson.core.JsonProcessingException;\r\nimport com.fasterxml.jackson.databind.JsonMappingException;\r\nimport com.fasterxml.jackson.databind.ObjectMapper;\r\nimport com.fasterxml.jackson.dataformat.xml.XmlMapper;\r\nimport com.fasterxml.jackson.module.jsonSchema.JsonSchema;\r\nimport com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper;\r\n\r\n/**\r\n * Utility for converting objects into XML and vice versa\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class JAXBUtils {\r\n    private static Logger log = LoggerFactory.getLogger(JAXBUtils.class);\r\n\r\n    private static Map<Class<?>, String> schemaMap;\r\n\r\n    public final static ObjectMapper mapper;\r\n    private final static XmlMapper xmlMapper;\r\n    static {\r\n        mapper = new ObjectMapper();\r\n        xmlMapper = new XmlMapper();\r\n    }\r\n\r\n    /**\r\n     * Converts <code>InputStream</code> to Object using JAXB\r\n     * \r\n     * @param str\r\n     * @param objectClass\r\n     * @return\r\n     */\r\n    public static Object toObject(InputStream is, Class<?> objectClass, String mediaType) {\r\n        Object output = null;\r\n\r\n        try {\r\n            output = objectClass.newInstance();\r\n\r\n            if (MediaType.APPLICATION_XML.equals(mediaType)) {\r\n\r\n                output = xmlMapper.readValue(is, objectClass);\r\n\r\n            } else if (MediaType.APPLICATION_JSON.equals(mediaType)) {\r\n\r\n                output = mapper.readValue(is, objectClass);\r\n\r\n            }\r\n        } catch (InstantiationException e) {\r\n            log.warn(\"Error while converting String to Object using JAXB:\" + e.getMessage());\r\n            return null;\r\n        } catch (IllegalAccessException e) {\r\n            log.warn(\"Error while converting String to Object using JAXB:\" + e.getMessage());\r\n            return null;\r\n        } catch (JsonParseException e) {\r\n            log.error(e.getMessage());\r\n        } catch (JsonMappingException e) {\r\n            log.error(e.getMessage());\r\n        } catch (IOException e) {\r\n            log.error(e.getMessage());\r\n        }\r\n        return output;\r\n    }\r\n\r\n    /**\r\n     * Converts <code>InputStream</code> to Object using JAXB\r\n     * \r\n     * @param str\r\n     * @param objectClass\r\n     * @return\r\n     */\r\n    public static Object toObject(String data, Class<?> objectClass, String mediaType) {\r\n        Object output = null;\r\n\r\n        try {\r\n            output = objectClass.newInstance();\r\n\r\n            if (MediaType.APPLICATION_XML.equals(mediaType)) {\r\n                output = xmlMapper.readValue(data, objectClass);\r\n\r\n            } else if (MediaType.APPLICATION_JSON.equals(mediaType)) {\r\n                if (MediaType.APPLICATION_JSON.equals(mediaType)) {\r\n                    output = mapper.readValue(data, objectClass);\r\n                }\r\n                return output;\r\n            }\r\n        } catch (InstantiationException e) {\r\n            log.warn(\"Error while converting String to Object using JAXB:\" + e.getMessage());\r\n            return null;\r\n        } catch (IllegalAccessException e) {\r\n            log.warn(\"Error while converting String to Object using JAXB:\" + e.getMessage());\r\n            return null;\r\n        } catch (JsonParseException e) {\r\n            log.error(e.getMessage());\r\n        } catch (JsonMappingException e) {\r\n            log.error(e.getMessage());\r\n        } catch (IOException e) {\r\n            log.error(e.getMessage());\r\n        }\r\n        return output;\r\n    }\r\n\r\n    public static String toString(Object object, String mediaType) {\r\n        try {\r\n            if (MediaType.APPLICATION_XML.equals(mediaType)) {\r\n                return xmlMapper.writeValueAsString(object);\r\n\r\n            } else if (MediaType.APPLICATION_JSON.equals(mediaType)) {\r\n                return mapper.writeValueAsString(object);\r\n            }\r\n\r\n        } catch (JsonProcessingException e) {\r\n            log.error(e.getMessage());\r\n        }\r\n        return null;\r\n    }\r\n\r\n    /**\r\n     * @param objectClass\r\n     * @param mediaType\r\n     * @return\r\n     */\r\n    public static String getSchema(Class<?> objectClass, String mediaType) {\r\n        try {\r\n\r\n            if (mediaType == MediaType.APPLICATION_JSON) {\r\n\r\n                String schemaDef = null;\r\n\r\n                if (schemaMap == null) {\r\n                    schemaMap = new HashMap<Class<?>, String>();\r\n                }\r\n                if (schemaMap.containsKey(objectClass)) {\r\n                    schemaDef = schemaMap.get(objectClass);\r\n\r\n                } else {\r\n\r\n                    ObjectMapper objectMapper = new ObjectMapper();\r\n                    SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();\r\n                    objectMapper.acceptJsonFormatVisitor(objectClass, visitor);\r\n                    JsonSchema schema = visitor.finalSchema();\r\n                    schemaDef = objectMapper.writeValueAsString(schema);\r\n                    schemaMap.put(objectClass, schemaDef);\r\n                }\r\n\r\n                return schemaDef;\r\n\r\n            } else if (mediaType == MediaType.APPLICATION_XML) {\r\n                JAXBContext jc = JAXBContext.newInstance(objectClass);\r\n                // generate the schemas\r\n                final ArrayList<ByteArrayOutputStream> schemaStreams = new ArrayList<ByteArrayOutputStream>();\r\n                jc.generateSchema(new SchemaOutputResolver() {\r\n                    @Override\r\n                    public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {\r\n                        ByteArrayOutputStream out = new ByteArrayOutputStream();\r\n                        schemaStreams.add(out);\r\n                        StreamResult streamResult = new StreamResult(out);\r\n                        streamResult.setSystemId(\"\");\r\n                        return streamResult;\r\n                    }\r\n                });\r\n\r\n                // convert to a list of string\r\n                List<String> schemas = new ArrayList<String>();\r\n                for (ByteArrayOutputStream os : schemaStreams) {\r\n                    schemas.add(os.toString());\r\n\r\n                }\r\n\r\n                return schemaStreams.get(0).toString();\r\n\r\n            }\r\n\r\n        } catch (JAXBException e) {\r\n            log.error(\"Error during translation, Caused by:\" + e.getMessage() + \", returning null\");\r\n            return null;\r\n        } catch (IOException e) {\r\n            log.error(\"Error during translation, Caused by:\" + e.getMessage() + \", returning null\");\r\n        }\r\n        return null;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/common/ResponseBuilder.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2014 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.rest.common;\r\n\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\n\r\n/**\r\n * Utility methods for handling entities passed in REST request\r\n * \r\n * @author chhavi.gangwal\r\n * \r\n */\r\npublic class ResponseBuilder {\r\n\r\n    public static Map<String, String> httpMethods = new HashMap<String, String>();\r\n\r\n    private static Logger log = LoggerFactory.getLogger(ResponseBuilder.class);\r\n\r\n    /**\r\n     * @param entityClassName\r\n     * @param em\r\n     * @return\r\n     */\r\n    public static String buildOutput(Class<?> entityClass, EntityMetadata entityMetadata, Object output) {\r\n        StringBuilder sb = new StringBuilder(\"'\");\r\n        sb.append(\"{\\\"\").append(entityClass.getSimpleName().toLowerCase()).append(\"\\\":\").append(output)\r\n            .append(\",\\\"entityClassName\\\":\\\"\").append(entityMetadata.getEntityClazz().getSimpleName())\r\n            .append(\"\\\",\\\"id\\\":\\\"\" + entityMetadata.getIdAttribute().getName()).append(\"\\\"}\").append(\"'\");\r\n        return sb.toString();\r\n    }\r\n    \r\n \r\n    /**\r\n     * @param output\r\n     * @param literal\r\n     * @return\r\n     */\r\n    public static String buildOutput(String output, String literal) {\r\n        StringBuilder sb = new StringBuilder(literal);\r\n        sb.append(output).append(literal);\r\n        return sb.toString();\r\n    }\r\n\r\n\r\n   \r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/common/ResponseCode.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.common;\r\n\r\n/**\r\n * Constants for REST responses\r\n * \r\n * @author amresh.singh\r\n */\r\npublic interface ResponseCode\r\n{\r\n    public static final String DELETE_AT_SUCCESS = \"APPLICATION_TOKEN_DELETE_SUCCESS\";\r\n\r\n    public static final String DELETE_AT_FAILED = \"APPLICATION_TOKEN_DELETE_FAILED\";\r\n\r\n    public static final String DELETE_ST_SUCCESS = \"SESSION_TOKEN_DELETE_SUCCESS\";\r\n\r\n    public static final String DELETE_ST_FAILED = \"SESSION_TOKEN_DELETE_FAILED\";\r\n\r\n    public static final String GET_ST_FAILED = \"SESSION_TOKEN_ GET_FAILED\";\r\n\r\n    public static final String PUT_ST_FAILED = \"SESSION_TOKEN_PUT_FAILED\";\r\n\r\n    public static final String PUT_ST_SUCCESS = \"SESSION_TOKEN_PUT_SUCCESS\";\r\n\r\n    public static final String GET_TX_SUCCESS = \"GET_TX_SUCCESS\";\r\n\r\n    public static final String GET_TX_FAILED = \"GET_TX_FAILED\";\r\n\r\n    public static final String POST_TX_SUCCESS = \"POST_TX_SUCCESS\";\r\n\r\n    public static final String POST_TX_FAILED = \"POST_TX_FAILED\";\r\n\r\n    public static final String DELETE_TX_SUCCESS = \"DELETE_TX_SUCCESS\";\r\n\r\n    public static final String DELETE_TX_FAILED = \"DELETE_TX_FAILED\";\r\n    \r\n    public static final String CLEAR_ST_SUCCESS = \"SESSION_TOKEN_CLEAR_SUCCESS\";\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/common/StreamUtils.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.rest.common;\n\nimport java.io.BufferedReader;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\n\n/**\n * Utilities for converting InputStream to various forms and vice versa\n * \n * @author amresh.singh\n */\npublic class StreamUtils\n{\n\n    /**\n     * Converts Input stream to String\n     * \n     * @param is\n     * @return\n     * @throws IOException\n     */\n    public static String toString(InputStream is)\n    {\n        String output = new String();\n        try\n        {\n            BufferedReader br = new BufferedReader(new InputStreamReader(is));\n            for (String line = br.readLine(); line != null; line = br.readLine())\n                output += line;\n        }\n        catch (IOException e)\n        {\n            return null;\n        }\n        return output;\n    }\n\n    /**\n     * Converts String to Input Stream\n     * \n     * @param s\n     * @return\n     */\n    public static InputStream toInputStream(String s)\n    {\n        InputStream is = new ByteArrayInputStream(s.getBytes());\n        return is;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/common/TokenUtils.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.rest.common;\n\nimport java.util.UUID;\n\n/**\n * Utility class for generating tokens\n * \n * @author amresh.singh\n */\npublic class TokenUtils\n{\n    /**\n     * Generates Application Token\n     * \n     * @return\n     */\n    public static String generateApplicationToken()\n    {\n        return Constants.APPLICATION_TOKEN_PREFIX + \"_\" + UUID.randomUUID();\n    }\n\n    /**\n     * Generates Session Token\n     * \n     * @return\n     */\n    public static String generateSessionToken()\n    {\n        return Constants.SESSION_TOKEN_PREFIX + \"_\" + UUID.randomUUID();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/converters/CollectionConverter.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.rest.converters;\r\n\r\nimport java.io.IOException;\r\nimport java.util.Collection;\r\nimport javax.ws.rs.core.MediaType;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.fasterxml.jackson.core.JsonParseException;\r\nimport com.fasterxml.jackson.databind.JsonMappingException;\r\nimport com.impetus.kundera.rest.common.JAXBUtils;\r\nimport com.impetus.kundera.rest.common.StreamUtils;\r\n\r\n/**\r\n * Converts a Collection object to XML/ JSON representation and vice-versa\r\n * \r\n * @author amresh\r\n * \r\n */\r\npublic class CollectionConverter\r\n{\r\n    private static Logger log = LoggerFactory.getLogger(CollectionConverter.class);\r\n\r\n    /**\r\n     * Converts a collection of <code>genericClass</code> objects to String\r\n     * representation\r\n     * \r\n     * @param input\r\n     * @param genericClass\r\n     * @param mediaType\r\n     * @return\r\n     */\r\n    public static String toString(Collection<?> input, Class<?> genericClass, String mediaType)\r\n    {\r\n        if (MediaType.APPLICATION_XML.equals(mediaType))\r\n        {\r\n            StringBuilder sb = new StringBuilder(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" standalone=\\\"yes\\\"?>\")\r\n                    .append(\"<\").append(genericClass.getSimpleName().toLowerCase()).append(\"s>\");\r\n            for (Object obj : input)\r\n            {\r\n                if (obj != null)\r\n                {\r\n                    String s = JAXBUtils.toString(obj, mediaType);\r\n\r\n                    if (s.startsWith(\"<?xml\"))\r\n                    {\r\n                        s = s.substring(s.indexOf(\">\") + 1, s.length());\r\n                    }\r\n                    sb.append(s);\r\n                }\r\n            }\r\n            sb.append(\"<\").append(genericClass.getSimpleName().toLowerCase()).append(\"s>\");\r\n            return sb.toString();\r\n        }\r\n        else if (MediaType.APPLICATION_JSON.equals(mediaType))\r\n        {\r\n        \t\r\n            int i = 0;\r\n            StringBuilder sb = new StringBuilder(\"[\");\r\n            for (Object obj : input)\r\n            {\r\n                if (obj != null)\r\n                {\r\n                    String s = JAXBUtils.toString(obj, mediaType);\r\n                    i++;\r\n                    sb.append(s);\r\n                    if(i < input.size()) {\r\n                        sb.append(\",\");\r\n                    }\r\n                }\r\n                \r\n            }\r\n            sb.append(\"]\");\r\n            return sb.toString();\r\n        }\r\n\r\n        return null;\r\n    }\r\n\r\n    /**\r\n     * Converts a String representation to collection of\r\n     * <code>genericClass</code> objects\r\n     * \r\n     * @param input\r\n     * @param collectionClass\r\n     * @param genericClass\r\n     * @param mediaType\r\n     * @return\r\n     */\r\n    public static Collection toCollection(String input, Class<?> collectionClass, Class<?> genericClass,\r\n            String mediaType)\r\n    {\r\n\r\n        try\r\n        {\r\n            if (MediaType.APPLICATION_XML.equals(mediaType))\r\n            {\r\n                Collection c = (Collection) collectionClass.newInstance();\r\n                if (input.startsWith(\"<?xml\"))\r\n                {\r\n                    input = input.substring(input.indexOf(\">\") + 1, input.length());\r\n                }\r\n\r\n                input = input.replaceAll(\"<\" + genericClass.getSimpleName().toLowerCase() + \"s>\", \"\");\r\n\r\n                while (!input.equals(\"\"))\r\n                {\r\n                    int i = input.indexOf(\"</\" + genericClass.getSimpleName().toLowerCase() + \">\");\r\n                    String s = input.substring(0, i + 3 + genericClass.getSimpleName().length());\r\n                    input = input.substring(i + 3 + genericClass.getSimpleName().length(), input.length());\r\n                    Object o = JAXBUtils.toObject(StreamUtils.toInputStream(s), genericClass, mediaType);\r\n                    c.add(o);\r\n                }\r\n                return c;\r\n\r\n            }\r\n            else if (MediaType.APPLICATION_JSON.equals(mediaType))\r\n            {\r\n                \r\n                    return  JAXBUtils.mapper.readValue(input, JAXBUtils.mapper.getTypeFactory()\r\n                                        .constructCollectionType((Class<? extends Collection>) collectionClass, genericClass));\r\n               \r\n                \r\n            }\r\n            return null;\r\n        }\r\n        catch (InstantiationException e)\r\n        {\r\n            log.error(\"Error during translation, Caused by:\" + e.getMessage() + \", returning null\");\r\n            return null;\r\n        }\r\n        catch (IllegalAccessException e)\r\n        {\r\n            log.error(\"Error during translation, Caused by:\" + e.getMessage() + \", returning null\");\r\n            return null;\r\n        } catch (JsonParseException e) {\r\n            log.error(\"Error during translation, Caused by:\" + e.getMessage() + \", returning null\");\r\n            return null;\r\n        } catch (JsonMappingException e) {\r\n            log.error(\"Error during translation, Caused by:\" + e.getMessage() + \", returning null\");\r\n            return null;\r\n        } catch (IOException e) {\r\n            log.error(\"Error during translation, Caused by:\" + e.getMessage() + \", returning null\");\r\n            return null;\r\n        }\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/converters/ListMessageBodyProvider.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.rest.converters;\n\nimport java.io.BufferedWriter;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport java.io.OutputStreamWriter;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Type;\nimport java.util.ArrayList;\nimport java.util.Iterator;\n\nimport javax.ws.rs.WebApplicationException;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.MultivaluedMap;\nimport javax.ws.rs.ext.MessageBodyWriter;\n\n/**\n * @author amresh\n * \n */\npublic class ListMessageBodyProvider implements MessageBodyWriter<ArrayList<Object>>\n{\n\n    @Override\n    public boolean isWriteable(Class<?> paramClass, Type paramType, Annotation[] paramArrayOfAnnotation,\n            MediaType paramMediaType)\n    {\n        return true;\n    }\n\n    @Override\n    public long getSize(ArrayList<Object> paramT, Class<?> paramClass, Type paramType,\n            Annotation[] paramArrayOfAnnotation, MediaType paramMediaType)\n    {\n        return -1;\n    }\n\n    @Override\n    public void writeTo(ArrayList<Object> paramT, Class<?> paramClass, Type paramType,\n            Annotation[] paramArrayOfAnnotation, MediaType paramMediaType,\n            MultivaluedMap<String, Object> paramMultivaluedMap, OutputStream paramOutputStream) throws IOException,\n            WebApplicationException\n    {\n        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(paramOutputStream));\n        String ts = null;\n        Iterator<Object> i = paramT.iterator();\n        while (i.hasNext())\n        {\n            ts += i.next().toString();\n        }\n        bw.write(ts);\n        bw.flush();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/dto/QueryResult.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.rest.dto;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * Wrapper for query results\n * \n * @author amresh\n */\n\n@XmlRootElement\npublic class QueryResult\n{\n    private List list;\n\n    /**\n     * @return the list\n     */\n    public List getList()\n    {\n        if (list == null)\n        {\n            list = new ArrayList();\n        }\n        return list;\n    }\n\n    /**\n     * @param list\n     *            the list to set\n     */\n    public void setList(List list)\n    {\n        this.list = list;\n    }\n}\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/dto/Schema.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.rest.dto;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * Holds schema information\n * \n * @author amresh.singh\n */\n\n@XmlRootElement\npublic class Schema\n{\n    private String schemaName;\n\n    private List<Table> tables;\n\n    /**\n     * @return the schemaName\n     */\n    public String getSchemaName()\n    {\n        return schemaName;\n    }\n\n    /**\n     * @param schemaName\n     *            the schemaName to set\n     */\n    public void setSchemaName(String schemaName)\n    {\n        this.schemaName = schemaName;\n    }\n\n    /**\n     * @return the tables\n     */\n    public List<Table> getTables()\n    {\n        return tables;\n    }\n\n    /**\n     * @param tables\n     *            the tables to set\n     */\n    public void setTables(List<Table> tables)\n    {\n        this.tables = tables;\n    }\n\n    public void addTable(Table table)\n    {\n        if (tables == null)\n        {\n            tables = new ArrayList<Table>();\n        }\n        tables.add(table);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/dto/SchemaMetadata.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.rest.dto;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * Holds List of schema information\n * \n * @author amresh\n * \n */\n\n@XmlRootElement\npublic class SchemaMetadata\n{\n    private List<Schema> schemaList;\n\n    /**\n     * @return the schemaList\n     */\n    public List<Schema> getSchemaList()\n    {\n        return schemaList;\n    }\n\n    /**\n     * @param schemaList\n     *            the schemaList to set\n     */\n    public void setSchemaList(List<Schema> schemaList)\n    {\n        this.schemaList = schemaList;\n    }\n\n    public void addSchema(Schema schema)\n    {\n        if (schemaList == null)\n        {\n            schemaList = new ArrayList<Schema>();\n        }\n        schemaList.add(schema);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/dto/Table.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.rest.dto;\n\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * Holds Table information\n * \n * @author amresh.singh\n */\n\n@XmlRootElement\npublic class Table\n{\n    private String tableName;\n\n    private String entityClassName;\n    \n    private String simpleEntityClassName;\n\n    public String getSimpleEntityClassName() {\n\t\treturn simpleEntityClassName;\n\t}\n\n\tpublic void setSimpleEntityClassName(String simpleEntityClassName) {\n\t\tthis.simpleEntityClassName = simpleEntityClassName;\n\t}\n\n\t/**\n     * @return the tableName\n     */\n    public String getTableName()\n    {\n        return tableName;\n    }\n\n    /**\n     * @param tableName\n     *            the tableName to set\n     */\n    public void setTableName(String tableName)\n    {\n        this.tableName = tableName;\n    }\n\n    /**\n     * @return the entityClassName\n     */\n    public String getEntityClassName()\n    {\n        return entityClassName;\n    }\n\n    /**\n     * @param entityClassName\n     *            the entityClassName to set\n     */\n    public void setEntityClassName(String entityClassName)\n    {\n        this.entityClassName = entityClassName;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/repository/EMFRepository.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.rest.repository;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManagerFactory;\n\n/**\n * Repository for holding Application Tokens and {@link EntityManagerFactory}\n * \n * @author amresh.singh\n */\npublic class EMFRepository\n{\n\n    /** The Constant INSTANCE. */\n    public static final EMFRepository INSTANCE = new EMFRepository();\n\n    private Map<String, EntityManagerFactory> emfMap;\n\n    /**\n     * @return the emfMap\n     */\n    public Map<String, EntityManagerFactory> getEmfMap()\n    {\n        return emfMap;\n    }\n\n    /**\n     * Retrieves EMF\n     * \n     * @param applicationToken\n     * @return\n     */\n    public EntityManagerFactory getEMF(String applicationToken)\n    {\n        if (emfMap == null)\n        {\n            return null;\n        }\n        else\n        {\n            return emfMap.get(applicationToken);\n        }\n    }\n\n    /**\n     * @param emfMap\n     *            the emfMap to set\n     */\n    public void setEmfMap(Map<String, EntityManagerFactory> emfMap)\n    {\n        this.emfMap = emfMap;\n    }\n\n    /**\n     * @param emfMap\n     *            the emfMap to set\n     */\n    public void addEmf(String applicationToken, EntityManagerFactory emf)\n    {\n        if (emfMap == null)\n        {\n            emfMap = new HashMap<String, EntityManagerFactory>();\n        }\n        emfMap.put(applicationToken, emf);\n    }\n\n    /**\n     * Removes EMF\n     * \n     * @param applicationToken\n     */\n    public void removeEMF(String applicationToken)\n    {\n        if (emfMap != null)\n        {\n            EntityManagerFactory emf = emfMap.get(applicationToken);\n            if (emf != null)\n            {\n                emf.close();\n            }\n            emfMap.remove(applicationToken);\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/repository/EMRepository.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.rest.repository;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\n\n/**\n * Repository for holding Session Tokens and {@link EntityManager}\n * \n * @author amresh.singh\n */\npublic class EMRepository\n{\n\n    /** The Constant INSTANCE. */\n    public static final EMRepository INSTANCE = new EMRepository();\n\n    private Map<String, EntityManager> emMap;\n\n    /**\n     * @return the emMap\n     */\n    public Map<String, EntityManager> getEmMap()\n    {\n        return emMap;\n    }\n\n    /**\n     * Retrieves EM\n     * \n     * @param sessionToken\n     * @return\n     */\n    public EntityManager getEM(String sessionToken)\n    {\n        if (emMap == null)\n        {\n            return null;\n        }\n        else\n        {\n            return emMap.get(sessionToken);\n        }\n    }\n\n    /**\n     * @param emMap\n     *            the emMap to set\n     */\n    public void setEmMap(Map<String, EntityManager> emMap)\n    {\n        this.emMap = emMap;\n    }\n\n    /**\n     * Adds EM\n     * \n     * @param sessionToken\n     * @param em\n     */\n    public void addEm(String sessionToken, EntityManager em)\n    {\n        if (emMap == null)\n        {\n            emMap = new HashMap<String, EntityManager>();\n        }\n        emMap.put(sessionToken, em);\n    }\n\n    /**\n     * Removes EM\n     * \n     * @param sessionToken\n     */\n    public void removeEm(String sessionToken)\n    {\n        if (emMap != null)\n        {\n            EntityManager em = emMap.get(sessionToken);\n            if (em != null)\n            {\n                em.close();\n            }\n            emMap.remove(sessionToken);\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/resources/ApplicationResource.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.resources;\r\n\r\nimport java.io.IOException;\r\nimport java.util.HashMap;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Persistence;\r\nimport javax.ws.rs.DELETE;\r\nimport javax.ws.rs.HeaderParam;\r\nimport javax.ws.rs.POST;\r\nimport javax.ws.rs.Path;\r\nimport javax.ws.rs.PathParam;\r\nimport javax.ws.rs.Produces;\r\nimport javax.ws.rs.core.Context;\r\nimport javax.ws.rs.core.HttpHeaders;\r\nimport javax.ws.rs.core.MediaType;\r\nimport javax.ws.rs.core.Response;\r\n\r\nimport org.codehaus.jackson.JsonParseException;\r\nimport org.codehaus.jackson.map.JsonMappingException;\r\nimport org.codehaus.jackson.map.ObjectMapper;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.rest.common.Constants;\r\nimport com.impetus.kundera.rest.common.ResponseCode;\r\nimport com.impetus.kundera.rest.common.ResponseBuilder;\r\nimport com.impetus.kundera.rest.common.TokenUtils;\r\nimport com.impetus.kundera.rest.repository.EMFRepository;\r\n\r\n/**\r\n * Application Token Resource\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Path(\"/\" + Constants.KUNDERA_API_PATH + Constants.APPLICATION_RESOURCE_PATH)\r\npublic class ApplicationResource {\r\n\tprivate static Logger log = LoggerFactory\r\n\t\t\t.getLogger(ApplicationResource.class);\r\n\r\n\t/**\r\n\t * Handler for GET method requests for this resource Generates Application\r\n\t * token and returns, creates and puts EMF into repository\r\n\t * \r\n\t * @param persistenceUnits\r\n\t * @return\r\n\t */\r\n\r\n\t@POST\r\n\t@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n\t@Path(\"/{persistenceUnits}\")\r\n\tpublic Response getApplicationToken(\r\n\t\t\t@PathParam(\"persistenceUnits\") String persistenceUnits,\r\n\t\t\t@Context HttpHeaders headers, String externalProperties) {\r\n\t    String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n\t\tmediaType = mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON;\r\n\t\tif (log.isDebugEnabled())\r\n\t\t\tlog.debug(\"GET Persistence Unit(s):\" + persistenceUnits);\r\n\t\tEntityManagerFactory emf = null;\r\n\t\tif (externalProperties != null && !externalProperties.isEmpty()) {\r\n\t\t\t\r\n\t\t\ttry {\r\n\t\t\t\tif (persistenceUnits.contains(\",\")) {\r\n\t\t\t\t\tMap<String, Map<String, String>> puProperties = new HashMap<String, Map<String, String>>();\r\n\t\t\t\t\tpuProperties = new ObjectMapper().readValue(externalProperties,\r\n\t\t\t\t\t\t\tpuProperties.getClass());\r\n\t\t\t\t\temf = Persistence\r\n\t\t\t\t\t\t\t.createEntityManagerFactory(persistenceUnits,\r\n\t\t\t\t\t\t\t\t\tpuProperties);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tMap<String, Object> puProperties = new HashMap<String, Object>();\r\n\t\t\t\t\tpuProperties = new ObjectMapper().readValue(externalProperties,\r\n\t\t\t\t\t\t\tpuProperties.getClass());\r\n\t\t\t\t\temf = Persistence\r\n\t\t\t\t\t\t\t.createEntityManagerFactory(persistenceUnits,\r\n\t\t\t\t\t\t\t\t\tpuProperties);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\r\n\t\t\t} catch (JsonParseException e) {\r\n\t\t\t\tlog.error(e.getMessage());\r\n\t\t\t} catch (JsonMappingException e) {\r\n\t\t\t\tlog.error(e.getMessage());\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\tlog.error(e.getMessage());\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\t emf = Persistence\r\n\t\t\t\t\t.createEntityManagerFactory(persistenceUnits);\r\n\t\t}\r\n\t\tif (emf == null) {\r\n\t\t\tlog.warn(\"Invalid emf\");\r\n\t\t\treturn Response.serverError().build();// ResponseCode.DELETE_AT_FAILED;\r\n\r\n\t\t}\r\n\t\tString applicationToken = TokenUtils.generateApplicationToken();\r\n\r\n\t\tEMFRepository.INSTANCE.addEmf(applicationToken, emf);\r\n\t\t//applicationToken = \"\\\"\" + applicationToken + \"\\\"\";\r\n\t\treturn Response.ok(ResponseBuilder.buildOutput(applicationToken, \"\\\"\"), mediaType).build();\r\n\t}\r\n\r\n\t/**\r\n\t * Handler for DELETE method requests for this resource Closes EMF and\r\n\t * removes application token along with from repository\r\n\t * \r\n\t * @param id\r\n\t * @return\r\n\t */\r\n\t@DELETE\r\n\t@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n\tpublic Response closeApplication(\r\n\t\t\t@HeaderParam(Constants.APPLICATION_TOKEN_HEADER_NAME) String applicationToken,\r\n\t\t\t@Context HttpHeaders headers) {\r\n\t    String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n\t\tmediaType = mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON;\r\n\t\tif (log.isDebugEnabled())\r\n\t\t\tlog.debug(\"DELETE: Application Token:\" + applicationToken);\r\n\r\n\t\tEntityManagerFactory emf = EMFRepository.INSTANCE\r\n\t\t\t\t.getEMF(applicationToken);\r\n\t\tif (emf == null) {\r\n\t\t\tlog.warn(\"DELETE: Application Token:\" + applicationToken\r\n\t\t\t\t\t+ \" doesn't exist and hence can't be closed\");\r\n\t\t\treturn Response.serverError().build();// ResponseCode.DELETE_AT_FAILED;\r\n\r\n\t\t}\r\n\r\n\t\tEMFRepository.INSTANCE.removeEMF(applicationToken);\r\n\t\treturn Response.ok(new String(ResponseCode.DELETE_AT_SUCCESS),\r\n\t\t\t\tmediaType).build();\r\n\t}\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/resources/CRUDResource.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.resources;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.metamodel.EmbeddableType;\r\nimport javax.ws.rs.DELETE;\r\nimport javax.ws.rs.GET;\r\nimport javax.ws.rs.HeaderParam;\r\nimport javax.ws.rs.POST;\r\nimport javax.ws.rs.PUT;\r\nimport javax.ws.rs.Path;\r\nimport javax.ws.rs.PathParam;\r\nimport javax.ws.rs.Produces;\r\nimport javax.ws.rs.core.Context;\r\nimport javax.ws.rs.core.HttpHeaders;\r\nimport javax.ws.rs.core.MediaType;\r\nimport javax.ws.rs.core.Response;\r\nimport javax.ws.rs.core.UriInfo;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.fasterxml.jackson.databind.ObjectMapper;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\r\nimport com.impetus.kundera.rest.common.Constants;\r\nimport com.impetus.kundera.rest.common.EntityUtils;\r\nimport com.impetus.kundera.rest.common.JAXBUtils;\r\nimport com.impetus.kundera.rest.common.ResponseBuilder;\r\nimport com.impetus.kundera.rest.repository.EMRepository;\r\n\r\n/**\r\n * REST resource for CRUD operations\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Path(\"/\" + Constants.KUNDERA_API_PATH + Constants.CRUD_RESOURCE_PATH + \"/{entityClass}\")\r\npublic class CRUDResource {\r\n    /** log for this class. */\r\n    private static Logger log = LoggerFactory.getLogger(CRUDResource.class);\r\n\r\n\r\n    /**\r\n     * Handler for POST method requests for this resource Inserts an entity into datastore\r\n     * \r\n     * @param sessionToken\r\n     * @param entityClassName\r\n     * @param in\r\n     * @return\r\n     */\r\n    @POST\r\n    // @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    public Response insert(@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken,\r\n        @PathParam(\"entityClass\") String entityClassName, String input, @Context HttpHeaders headers) {\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n\r\n        mediaType =\r\n            mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML\r\n                : MediaType.APPLICATION_JSON;\r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        input = input.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n\r\n        if (log.isDebugEnabled()) {\r\n            log.debug(\"POST: SessionToken: \" + sessionToken);\r\n            log.debug(\"POST: entityClass: \" + entityClassName);\r\n        }\r\n\r\n        try {\r\n            EntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n            Class<?> entityClass = EntityUtils.getEntityClass(entityClassName, em);\r\n\r\n            if (log.isDebugEnabled())\r\n                log.debug(\"POST: entityClass\" + entityClass);\r\n\r\n            if (log.isDebugEnabled())\r\n                log.debug(\"POST: Media Type:\" + mediaType);\r\n\r\n            log.debug(\"Entity Data\" + input);\r\n\r\n            Object entity = JAXBUtils.toObject(input, entityClass, mediaType);\r\n\r\n            log.debug(\"Entity Data\" + entity);\r\n            em.persist(entity);\r\n\r\n        } catch (Exception e) {\r\n            log.error(e.getMessage());\r\n            return Response.serverError().build();\r\n        }\r\n\r\n        return Response.ok(\"Record persisted\", mediaType).build();\r\n    }\r\n\r\n    /**\r\n     * Handler for GET method requests for this resource Finds an entity from datastore\r\n     * \r\n     * @param sessionToken\r\n     * @param entityClassName\r\n     * @param id\r\n     * @return\r\n     */\r\n    @GET\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Path(\"/{id}\")\r\n    public Response find(@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken,\r\n        @PathParam(\"entityClass\") String entityClassName, @PathParam(\"id\") String id, @Context HttpHeaders headers) {\r\n\r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n        mediaType =\r\n            mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML\r\n                : MediaType.APPLICATION_JSON;\r\n        log.debug(\"GET: sessionToken:\" + sessionToken);\r\n        log.debug(\"GET: entityClass:\" + entityClassName);\r\n        log.debug(\"GET: ID:\" + id);\r\n\r\n        Object entity = null;\r\n        Class<?> entityClass;\r\n        EntityMetadata entityMetadata = null;\r\n        try {\r\n            EntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n            entityClass = EntityUtils.getEntityClass(entityClassName, em);\r\n            entityMetadata = EntityUtils.getEntityMetaData(entityClass.getSimpleName(), em);\r\n            log.debug(\"GET: entityClass\" + entityClass);\r\n            MetamodelImpl metaModel = (MetamodelImpl) em.getEntityManagerFactory().getMetamodel();\r\n            EmbeddableType keyObj = null;\r\n            Object key = null;\r\n            id = java.net.URLDecoder.decode(id, \"UTF-8\");\r\n            if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())) {\r\n                keyObj = metaModel.embeddable(entityMetadata.getIdAttribute().getBindableJavaType());\r\n                key = JAXBUtils.toObject(id, keyObj.getJavaType(), mediaType);\r\n            } else {\r\n                ObjectMapper mapper = new ObjectMapper();\r\n                key = mapper.convertValue(id, entityMetadata.getIdAttribute().getBindableJavaType());\r\n            }\r\n            \r\n            entity = em.find(entityClass, key);\r\n        } catch (Exception e) {\r\n            log.error(e.getMessage());\r\n            return Response.serverError().build();\r\n        }\r\n\r\n        log.debug(\"GET: \" + entity);\r\n\r\n        if (entity == null) {\r\n            return Response.noContent().build();\r\n        }\r\n        String output = JAXBUtils.toString(entity, mediaType);\r\n        if (mediaType.equalsIgnoreCase(MediaType.APPLICATION_JSON)) {\r\n            return Response.ok(ResponseBuilder.buildOutput(entityClass, entityMetadata, output), mediaType).build();\r\n        } else {\r\n            return Response.ok(output.toString(), mediaType).build();\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Handler for PUT method requests for this resource Updates an entity into datastore\r\n     * \r\n     * @param sessionToken\r\n     * @param entityClassName\r\n     * @param in\r\n     * @return\r\n     */\r\n    @PUT\r\n    // @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    public Response update(@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken,\r\n        @PathParam(\"entityClass\") String entityClassName, String input, @Context HttpHeaders headers) {\r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        input = input.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n\r\n        log.debug(\"PUT: sessionToken:\" + sessionToken);\r\n        log.debug(\"PUT: entityClassName:\" + entityClassName);\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n        mediaType =\r\n            mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML\r\n                : MediaType.APPLICATION_JSON;\r\n\r\n        log.debug(\"POST: Media Type:\" + mediaType);\r\n\r\n        Object output;\r\n        Class<?> entityClass;\r\n        Object entity;\r\n        EntityMetadata entityMetadata = null;\r\n        try {\r\n            EntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n            entityClass = EntityUtils.getEntityClass(entityClassName, em);\r\n            log.debug(\"PUT: entityClass: \" + entityClass);\r\n            entityMetadata = EntityUtils.getEntityMetaData(entityClass.getSimpleName(), em);\r\n\r\n            entity = JAXBUtils.toObject(input, entityClass, mediaType);\r\n            output = em.merge(entity);\r\n        } catch (Exception e) {\r\n            log.error(e.getMessage());\r\n            return Response.serverError().build();\r\n        }\r\n\r\n        if (output == null) {\r\n            return Response.notModified().build();\r\n        }\r\n        output = JAXBUtils.toString(output, mediaType);\r\n        if (mediaType.equalsIgnoreCase(MediaType.APPLICATION_JSON)) {\r\n            return Response.ok(ResponseBuilder.buildOutput(entityClass, entityMetadata, output), mediaType).build();\r\n        } else {\r\n            return Response.ok(output.toString(), mediaType).build();\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Handler for DELETE method requests for this resource Deletes an entity from datastore\r\n     * \r\n     * @param sessionToken\r\n     * @param entityClassName\r\n     * @param id\r\n     * @return\r\n     */\r\n    @DELETE\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Path(\"/delete/{id}\")\r\n    public Response delete(@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken,\r\n        @PathParam(\"entityClass\") String entityClassName, @PathParam(\"id\") String id, @Context HttpHeaders headers) {\r\n\r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n        mediaType =\r\n            mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML\r\n                : MediaType.APPLICATION_JSON;\r\n        log.debug(\"DELETE: sessionToken:\" + sessionToken);\r\n        log.debug(\"DELETE: entityClass Name:\" + entityClassName);\r\n        log.debug(\"DELETE: ID:\" + id);\r\n\r\n        try {\r\n            EntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n            Class<?> entityClass = EntityUtils.getEntityClass(entityClassName, em);\r\n            log.debug(\"DELETE: entityClass\" + entityClass);\r\n            EntityMetadata entityMetadata = EntityUtils.getEntityMetaData(entityClass.getSimpleName(), em);\r\n            MetamodelImpl metaModel = (MetamodelImpl) em.getEntityManagerFactory().getMetamodel();\r\n            EmbeddableType keyObj = null;\r\n            Object key = null;\r\n            id = java.net.URLDecoder.decode(id, \"UTF-8\");\r\n            if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())) {\r\n                keyObj = metaModel.embeddable(entityMetadata.getIdAttribute().getBindableJavaType());\r\n                key = JAXBUtils.toObject(id, keyObj.getJavaType(), mediaType);\r\n            } else {\r\n                ObjectMapper mapper = new ObjectMapper();\r\n                key = mapper.convertValue(id, entityMetadata.getIdAttribute().getBindableJavaType());\r\n            }\r\n\r\n            Object entity = em.find(entityClass, key);\r\n            em.remove(entity);\r\n        } catch (Exception e) {\r\n            log.error(e.getMessage());\r\n            return Response.serverError().build();\r\n        }\r\n\r\n        return Response.ok(new String(\"Deleted Successfully\"), mediaType).build();\r\n\r\n    }\r\n\r\n}"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/resources/JPAQueryResource.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.rest.resources;\r\n\r\nimport java.util.List;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.Query;\r\nimport javax.ws.rs.DELETE;\r\nimport javax.ws.rs.GET;\r\nimport javax.ws.rs.HttpMethod;\r\nimport javax.ws.rs.POST;\r\nimport javax.ws.rs.PUT;\r\nimport javax.ws.rs.Path;\r\nimport javax.ws.rs.Produces;\r\nimport javax.ws.rs.core.Context;\r\nimport javax.ws.rs.core.HttpHeaders;\r\nimport javax.ws.rs.core.MediaType;\r\nimport javax.ws.rs.core.Response;\r\nimport javax.ws.rs.core.UriInfo;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.query.QueryImpl;\r\nimport com.impetus.kundera.rest.common.Constants;\r\nimport com.impetus.kundera.rest.common.EntityUtils;\r\nimport com.impetus.kundera.rest.common.ResponseBuilder;\r\nimport com.impetus.kundera.rest.converters.CollectionConverter;\r\nimport com.impetus.kundera.rest.repository.EMRepository;\r\n\r\n/**\r\n * REST based resource for JPA queries\r\n * \r\n * @author amresh\r\n * \r\n */\r\n\r\n@Path(\"/\" + Constants.KUNDERA_API_PATH + Constants.JPA_QUERY_RESOURCE_PATH)\r\npublic class JPAQueryResource {\r\n\r\n    private static Logger log = LoggerFactory.getLogger(JPAQueryResource.class);\r\n\r\n    /**\r\n     * Handler for GET method requests for this resource. Retrieves all entities for a given table from datasource that\r\n     * match after running named query. If named query=All, it returns all records.\r\n     * \r\n     * @param sessionToken\r\n     * @param entityClassName\r\n     * @param id\r\n     * @return\r\n     */\r\n\r\n    @GET\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Path(\"/{entityClass}/{namedQueryName}\")\r\n    public Response executeNamedQuery(@Context HttpHeaders headers, @Context UriInfo info) {\r\n\r\n        String entityClassName = info.getPathParameters().getFirst(\"entityClass\");\r\n        String namedQueryName = info.getPathParameters().getFirst(\"namedQueryName\");\r\n        String params = info.getRequestUri().getQuery();\r\n        String sessionToken = headers.getRequestHeader(Constants.SESSION_TOKEN_HEADER_NAME).get(0);\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n        mediaType =\r\n            mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML\r\n                : MediaType.APPLICATION_JSON;\r\n\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET: sessionToken:\" + sessionToken + \", entityClass:\" + entityClassName + \", Named Query:\"\r\n                + namedQueryName + \", Media Type:\" + mediaType);\r\n\r\n        List result = null;\r\n        Class<?> entityClass = null;\r\n        EntityMetadata entityMetadata = null;\r\n        try {\r\n            sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n            EntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n            entityClass = EntityUtils.getEntityClass(entityClassName, em);\r\n            entityMetadata = EntityUtils.getEntityMetaData(entityClass.getSimpleName(), em);\r\n\r\n            if (log.isDebugEnabled())\r\n                log.debug(\"GET: entityClass\" + entityClass);\r\n\r\n            if (Constants.NAMED_QUERY_ALL.equalsIgnoreCase(namedQueryName)) {\r\n                String alias = entityClassName.substring(0, 1).toLowerCase();\r\n\r\n                StringBuilder sb =\r\n                    new StringBuilder().append(\"SELECT \").append(alias).append(\" FROM \").append(entityClassName)\r\n                        .append(\" \").append(alias);\r\n\r\n                Query q = em.createQuery(sb.toString());\r\n                result = q.getResultList();\r\n            } else {\r\n                String queryPart = EntityUtils.getQueryPart(namedQueryName);\r\n                String paramPart = params != null ? params : EntityUtils.getParameterPart(namedQueryName);\r\n\r\n                Query q = em.createNamedQuery(queryPart);\r\n                if (q == null) {\r\n                    return Response.serverError().build();\r\n                }\r\n\r\n                boolean isDeleteOrUpdateQuery = ((QueryImpl) q).getKunderaQuery().isDeleteUpdate();\r\n                if (isDeleteOrUpdateQuery) {\r\n                    log.error(\"Incorrect HTTP method GET for query:\" + queryPart);\r\n                    return Response.noContent().build();\r\n                }\r\n\r\n                EntityUtils.setQueryParameters(queryPart, paramPart, q);\r\n\r\n                result = q.getResultList();\r\n            }\r\n\r\n        } catch (Exception e) {\r\n            log.error(e.getMessage());\r\n            return Response.serverError().build();\r\n        }\r\n\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET: Result of \" + namedQueryName + \" Query : \" + result);\r\n\r\n        if (result == null) {\r\n            return Response.noContent().build();\r\n        }\r\n\r\n        String output = CollectionConverter.toString(result, entityClass, mediaType);\r\n        if (mediaType.equalsIgnoreCase(MediaType.APPLICATION_JSON)) {\r\n            return Response.ok(ResponseBuilder.buildOutput(entityClass, entityMetadata, output), mediaType).build();\r\n        } else {\r\n            return Response.ok(output.toString(), mediaType).build();\r\n        }\r\n\r\n    }\r\n\r\n    /**\r\n     * Handler for GET method requests for this resource Retrieves records from datasource for a given select JPA query\r\n     * \r\n     * @param sessionToken\r\n     * @param entityClassName\r\n     * @param id\r\n     * @return\r\n     */\r\n\r\n    @POST\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Path(\"/{jpaQuery}\")\r\n    public Response executeSelectJPAQuery(@Context HttpHeaders headers, @Context UriInfo info, String parameters) {\r\n        String jpaQuery = info.getPathParameters().getFirst(\"jpaQuery\");\r\n        String params = info.getRequestUri().getQuery();\r\n\r\n        String sessionToken = headers.getRequestHeader(Constants.SESSION_TOKEN_HEADER_NAME).get(0);\r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n        mediaType =\r\n            mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML\r\n                : MediaType.APPLICATION_JSON;\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET: sessionToken:\" + sessionToken + \", jpaQuery:\" + jpaQuery + \", Media Type:\" + mediaType);\r\n\r\n        if (!EntityUtils.isValidQuery(jpaQuery, HttpMethod.GET)) {\r\n            log.error(\"Incorrect HTTP method GET for query:\" + jpaQuery);\r\n            return Response.noContent().build();\r\n        }\r\n\r\n        List result = null;\r\n        Query q = null;\r\n        EntityMetadata entityMetadata = null;\r\n        EntityManager em = null;\r\n        try {\r\n            em = EMRepository.INSTANCE.getEM(sessionToken);\r\n\r\n            String queryPart = EntityUtils.getQueryPart(jpaQuery);\r\n            String paramPart = params != null ? params : EntityUtils.getParameterPart(jpaQuery);\r\n\r\n            q = em.createQuery(queryPart);\r\n            if (q == null) {\r\n                return Response.serverError().build();\r\n            }\r\n\r\n            EntityUtils.setQueryParameters(queryPart, paramPart, q);\r\n            EntityUtils.setObjectQueryParameters(queryPart, parameters, q, em, mediaType);\r\n\r\n            result = q.getResultList();\r\n        } catch (Exception e) {\r\n            log.error(e.getMessage());\r\n            return Response.serverError().build();\r\n        }\r\n\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET: Result for JPA Query: \" + result);\r\n\r\n        if (result == null) {\r\n            return Response.noContent().build();\r\n        }\r\n\r\n        Class<?> genericClass = ((QueryImpl) q).getKunderaQuery().getEntityClass();\r\n        entityMetadata = EntityUtils.getEntityMetaData(genericClass.getSimpleName(), em);\r\n        String output = CollectionConverter.toString(result, genericClass, mediaType);\r\n        if (mediaType.equalsIgnoreCase(MediaType.APPLICATION_JSON)) {\r\n            return Response.ok(ResponseBuilder.buildOutput(genericClass, entityMetadata, output), mediaType).build();\r\n          \r\n        } else {\r\n            return Response.ok(output.toString(), mediaType).build();\r\n        }\r\n\r\n    }\r\n\r\n    /**\r\n     * Handler for PUT method requests for this resource Retrieves records from datasource for a given UPDATE JPA query\r\n     * \r\n     * @param sessionToken\r\n     * @param entityClassName\r\n     * @param id\r\n     * @return\r\n     */\r\n    @PUT\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Path(\"/{jpaQuery}\")\r\n    public Response executeUpdateJPAQuery(@Context HttpHeaders headers, @Context UriInfo info, String parameters) {\r\n        String jpaQuery = info.getPathParameters().getFirst(\"jpaQuery\");\r\n        String params = info.getRequestUri().getQuery();\r\n        String sessionToken = headers.getRequestHeader(Constants.SESSION_TOKEN_HEADER_NAME).get(0);\r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n        mediaType =\r\n            mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML\r\n                : MediaType.APPLICATION_JSON;\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET: sessionToken:\" + sessionToken + \", jpaQuery:\" + jpaQuery + \", Media Type:\" + mediaType);\r\n\r\n        if (!EntityUtils.isValidQuery(jpaQuery, HttpMethod.PUT)) {\r\n            log.error(\"Incorrect HTTP method POST for query:\" + jpaQuery);\r\n            return Response.noContent().build();\r\n        }\r\n\r\n        int result = executeWrite(jpaQuery, params, sessionToken, parameters, mediaType);\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET: Result for JPA Query: \" + result);\r\n\r\n        if (result < 0) {\r\n            return Response.noContent().build();\r\n        }\r\n\r\n        return Response.ok(result, mediaType).build();\r\n    }\r\n\r\n    /**\r\n     * Handler for DELETE method requests for this resource Retrieves records from datasource for a given UPDATE JPA\r\n     * query\r\n     * \r\n     * @param sessionToken\r\n     * @param entityClassName\r\n     * @param id\r\n     * @return\r\n     */\r\n    @DELETE\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Path(\"/{jpaQuery}\")\r\n    public Response executeDeleteJPAQuery(@Context HttpHeaders headers, @Context UriInfo info, String parameters) {\r\n        String jpaQuery = info.getPathParameters().getFirst(\"jpaQuery\");\r\n        String params = info.getRequestUri().getQuery();\r\n        String sessionToken = headers.getRequestHeader(Constants.SESSION_TOKEN_HEADER_NAME).get(0);\r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n        mediaType =\r\n            mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML\r\n                : MediaType.APPLICATION_JSON;\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET: sessionToken:\" + sessionToken + \", jpaQuery:\" + jpaQuery + \", Media Type:\" + mediaType);\r\n\r\n        if (!EntityUtils.isValidQuery(jpaQuery, HttpMethod.DELETE)) {\r\n            log.error(\"Incorrect HTTP method POST for query:\" + jpaQuery);\r\n            return Response.noContent().build();\r\n        }\r\n\r\n        int result = executeWrite(jpaQuery, params, sessionToken, parameters, mediaType);\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET: Result for JPA Query: \" + result);\r\n\r\n        if (result < 0) {\r\n            return Response.noContent().build();\r\n        }\r\n\r\n        return Response.ok(result, mediaType).build();\r\n    }\r\n\r\n    private int executeWrite(String jpaQuery, String params, String sessionToken, String parameters, String mediaType) {\r\n        int result = -1;\r\n        Query q = null;\r\n        try {\r\n            EntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n\r\n            String queryPart = EntityUtils.getQueryPart(jpaQuery);\r\n            String paramPart = params != null ? params : EntityUtils.getParameterPart(jpaQuery);\r\n\r\n            q = em.createQuery(queryPart);\r\n\r\n            if (q != null) {\r\n                EntityUtils.setQueryParameters(queryPart, paramPart, q);\r\n                EntityUtils.setObjectQueryParameters(queryPart, parameters, q, em, mediaType);\r\n                result = q.executeUpdate();\r\n            }\r\n        } catch (Exception e) {\r\n            log.error(e.getMessage());\r\n        }\r\n        return result;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/resources/MetadataResource.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.resources;\r\n\r\nimport java.io.IOException;\r\nimport java.util.Map;\r\nimport java.util.StringTokenizer;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.ws.rs.GET;\r\nimport javax.ws.rs.HeaderParam;\r\nimport javax.ws.rs.POST;\r\nimport javax.ws.rs.Path;\r\nimport javax.ws.rs.PathParam;\r\nimport javax.ws.rs.Produces;\r\nimport javax.ws.rs.core.Context;\r\nimport javax.ws.rs.core.HttpHeaders;\r\nimport javax.ws.rs.core.MediaType;\r\nimport javax.ws.rs.core.Response;\r\n\r\nimport org.codehaus.jackson.JsonGenerationException;\r\nimport org.codehaus.jackson.map.JsonMappingException;\r\nimport org.codehaus.jackson.map.ObjectMapper;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\r\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\r\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\r\nimport com.impetus.kundera.rest.common.Constants;\r\nimport com.impetus.kundera.rest.common.EntityUtils;\r\nimport com.impetus.kundera.rest.common.JAXBUtils;\r\nimport com.impetus.kundera.rest.common.ResponseBuilder;\r\nimport com.impetus.kundera.rest.dto.Schema;\r\nimport com.impetus.kundera.rest.dto.SchemaMetadata;\r\nimport com.impetus.kundera.rest.dto.Table;\r\nimport com.impetus.kundera.rest.repository.EMRepository;\r\n\r\n/**\r\n * REST Resource for Meta data related operations\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Path(\"/\" + Constants.KUNDERA_API_PATH + Constants.META_DATA_RESOURCE_PATH)\r\npublic class MetadataResource {\r\n    private static Logger log = LoggerFactory.getLogger(MetadataResource.class);\r\n\r\n    /**\r\n     * Handler for GET requests. Returns schema List and related metadata for the given list of persistence units.\r\n     * \r\n     * @param persistenceUnits\r\n     * @return\r\n     */\r\n    @GET\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Path(\"/schemaList/{persistenceUnits}\")\r\n    public Response getSchemaList(@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken,\r\n        @PathParam(\"persistenceUnits\") String persistenceUnits, @Context HttpHeaders headers) {\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET: Persistence Units:\" + persistenceUnits);\r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n\r\n        EntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n        StringTokenizer st = new StringTokenizer(persistenceUnits, \",\");\r\n        EntityManagerFactoryImpl emfImpl = (EntityManagerFactoryImpl) em.getEntityManagerFactory();\r\n\r\n        SchemaMetadata schemaMetadata = new SchemaMetadata();\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n        mediaType =\r\n            mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML\r\n                : MediaType.APPLICATION_JSON;\r\n        while (st.hasMoreTokens()) {\r\n\r\n            String persistenceUnit = st.nextToken();\r\n            PersistenceUnitMetadata puMetadata =\r\n                emfImpl.getKunderaMetadataInstance().getApplicationMetadata()\r\n                    .getPersistenceUnitMetadata(persistenceUnit);\r\n            String schemaStr = puMetadata.getProperty(\"kundera.keyspace\");\r\n\r\n            if (schemaStr != null) {\r\n                Schema schema = new Schema();\r\n                schema.setSchemaName(schemaStr);\r\n\r\n                \r\n                MetamodelImpl metamodel = (MetamodelImpl) em.getEntityManagerFactory().getMetamodel();\r\n                Map<String, EntityMetadata> metamodelMap = metamodel.getEntityMetadataMap();\r\n\r\n                for (String clazz : metamodelMap.keySet()) {\r\n                    EntityMetadata m = metamodelMap.get(clazz);\r\n                    Table table = new Table();\r\n                    table.setEntityClassName(clazz);\r\n                    table.setTableName(m.getTableName());\r\n                    table.setSimpleEntityClassName(m.getEntityClazz().getSimpleName());\r\n\r\n                    schema.addTable(table);\r\n                }\r\n                schemaMetadata.addSchema(schema);\r\n            }\r\n        }\r\n\r\n        if (schemaMetadata.getSchemaList().isEmpty()) {\r\n            if (log.isDebugEnabled())\r\n                log.warn(\"GET: getSchemaList: Can't find Schema for PUs \" + persistenceUnits);\r\n            return Response.noContent().build();\r\n        } else {\r\n            if (mediaType.equalsIgnoreCase(MediaType.APPLICATION_JSON)) {\r\n                ObjectMapper mapper = new ObjectMapper();\r\n                String output = null;\r\n\r\n                try {\r\n                    output = mapper.writeValueAsString(schemaMetadata);\r\n                } catch (JsonGenerationException e) {\r\n                    log.error(e.getMessage());\r\n                } catch (JsonMappingException e) {\r\n                    log.error(e.getMessage());\r\n                } catch (IOException e) {\r\n                    log.error(e.getMessage());\r\n                }\r\n\r\n          \r\n\r\n                return Response.ok(ResponseBuilder.buildOutput(output, \"'\"), mediaType).build();\r\n            } else {\r\n                return Response.ok(schemaMetadata, mediaType).build();\r\n            }\r\n        }\r\n\r\n    }\r\n\r\n    /**\r\n     * Handler for GET requests. Returns schema List and related metadata for the given list of persistence units.\r\n     * \r\n     * @param persistenceUnits\r\n     * @return\r\n     */\r\n    @POST\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Path(\"/{entityClass}\")\r\n    public Response getEntityModel(@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken,\r\n        @PathParam(\"entityClass\") String entityClassName, @Context HttpHeaders headers) {\r\n        Class<?> entityClass;\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n        mediaType =\r\n            mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML\r\n                : MediaType.APPLICATION_JSON;\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET: Persistence Units:\" + entityClassName);\r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        try {\r\n            EntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n            entityClass = EntityUtils.getEntityClass(entityClassName, em);\r\n\r\n            String output = JAXBUtils.getSchema(entityClass, mediaType);\r\n\r\n            return Response.ok(ResponseBuilder.buildOutput(output, \"'\"), mediaType).build();\r\n        } catch (Exception e) {\r\n            log.error(e.getMessage());\r\n            return Response.serverError().build();\r\n        }\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/resources/NativeQueryResource.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.resources;\r\n\r\nimport java.io.IOException;\r\nimport java.net.URLDecoder;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.Query;\r\nimport javax.ws.rs.GET;\r\nimport javax.ws.rs.POST;\r\nimport javax.ws.rs.PUT;\r\nimport javax.ws.rs.Path;\r\nimport javax.ws.rs.Produces;\r\nimport javax.ws.rs.core.Context;\r\nimport javax.ws.rs.core.HttpHeaders;\r\nimport javax.ws.rs.core.MediaType;\r\nimport javax.ws.rs.core.Response;\r\nimport javax.ws.rs.core.UriInfo;\r\n\r\nimport org.apache.cassandra.thrift.Column;\r\nimport org.codehaus.jackson.JsonGenerationException;\r\nimport org.codehaus.jackson.map.JsonMappingException;\r\nimport org.codehaus.jackson.map.ObjectMapper;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.client.Client;\r\nimport com.impetus.kundera.metadata.model.EntityMetadata;\r\nimport com.impetus.kundera.property.PropertyAccessorHelper;\r\nimport com.impetus.kundera.rest.common.Constants;\r\nimport com.impetus.kundera.rest.common.EntityUtils;\r\nimport com.impetus.kundera.rest.common.ResponseBuilder;\r\nimport com.impetus.kundera.rest.converters.CollectionConverter;\r\nimport com.impetus.kundera.rest.repository.EMRepository;\r\n\r\n/**\r\n * REST based resource for Native Queries\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Path(\"/\" + Constants.KUNDERA_API_PATH + Constants.NATIVE_QUERY_RESOURCE_PATH)\r\npublic class NativeQueryResource {\r\n    private static Logger log = LoggerFactory.getLogger(NativeQueryResource.class);\r\n\r\n    /**\r\n     * Executes Native Query and returns resposne\r\n     * \r\n     * @param headers\r\n     * @param info\r\n     * @return\r\n     */\r\n    @POST\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Path(\"/{entityClassName}\")\r\n    public Response executeNativeQuery(@Context HttpHeaders headers, @Context UriInfo info, String query) {\r\n\r\n        String sessionToken = headers.getRequestHeader(Constants.SESSION_TOKEN_HEADER_NAME).get(0);\r\n\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n        mediaType =\r\n            mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML\r\n                : MediaType.APPLICATION_JSON;\r\n        String entityClassName = info.getPathParameters().getFirst(\"entityClassName\");\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET:: Session Token:\" + sessionToken + \", Entity Class Name:\" + entityClassName\r\n                + \", Native Query:\" + query + \", Media Type:\" + mediaType);\r\n\r\n        List result = null;\r\n        Class<?> entityClass = null;\r\n        EntityMetadata entityMetadata = null;\r\n        Query q;\r\n\r\n        try {\r\n            query = URLDecoder.decode(query, \"UTF-8\");\r\n            sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n            EntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n\r\n            entityClass = EntityUtils.getEntityClass(entityClassName, em);\r\n            entityMetadata = EntityUtils.getEntityMetaData(entityClass.getSimpleName(), em);\r\n            if (log.isDebugEnabled())\r\n                log.debug(\"GET: entityClass\" + entityClass);\r\n            q = em.createNativeQuery(query, entityClass);\r\n            result = q.getResultList();\r\n            result = onNativeCassResults(result, entityMetadata, em);\r\n        } catch (Exception e) {\r\n            log.error(e.getMessage());\r\n            return Response.serverError().build();\r\n        }\r\n\r\n        if (result == null) {\r\n            return Response.noContent().build();\r\n        }\r\n\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET: Media Type:\" + mediaType);\r\n       \r\n    \r\n        String output = CollectionConverter.toString(result, entityClass, mediaType);\r\n        if (mediaType.equalsIgnoreCase(MediaType.APPLICATION_JSON)) {\r\n            return Response.ok(ResponseBuilder.buildOutput(entityClass, entityMetadata, output), mediaType).build();\r\n        } else {\r\n            return Response.ok(output.toString(), mediaType).build();\r\n        }\r\n\r\n    }\r\n\r\n    /**\r\n     * @param result\r\n     * @param entityMetadata\r\n     * @param em\r\n     * @return\r\n     */\r\n    private List onNativeCassResults(List result, EntityMetadata entityMetadata, EntityManager em) {\r\n        Map<String, Client<Query>> clients = (Map<String, Client<Query>>) em.getDelegate();\r\n        Client client = clients.get(entityMetadata.getPersistenceUnit());\r\n        if((client.getClass().getSimpleName().equals(\"ThriftClient\") || client.getClass().getSimpleName().equals(\"PelopsClient\")\r\n                        || client.getClass().getSimpleName().equals(\"DSClient\"))\r\n                        && Column.class.equals(result.get(0).getClass())) {\r\n            int count = 0;\r\n            for(Object column : result) {\r\n                Map<Object, Object> valueMap = new HashMap<Object, Object>();\r\n                valueMap.put(PropertyAccessorHelper.getObject(String.class, ((Column) column).getName()), PropertyAccessorHelper.getObject(Long.class, ((Column) column).getValue()));\r\n                result.set(count, valueMap);\r\n                count ++;\r\n            }\r\n                      \r\n           \r\n        }\r\n        return result;\r\n    }\r\n\r\n    /**\r\n     * Executes Native script and returns responsne\r\n     * \r\n     * @param headers\r\n     * @param info\r\n     * @return\r\n     */\r\n    @PUT\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Path(\"/{persistenceUnit}\")\r\n    public Response executeNativeScript(@Context HttpHeaders headers, @Context UriInfo info, String script) {\r\n\r\n        String sessionToken = headers.getRequestHeader(Constants.SESSION_TOKEN_HEADER_NAME).get(0);\r\n        String persistenceUnit = info.getPathParameters().getFirst(\"persistenceUnit\");\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n        mediaType =\r\n            mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML\r\n                : MediaType.APPLICATION_JSON;\r\n\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET:: Session Token:\" + sessionToken + \", Native Script:\" + script + \", Media Type:\" + mediaType);\r\n\r\n        Object result = null;\r\n\r\n        try {\r\n            script = URLDecoder.decode(script, \"UTF-8\");\r\n            sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n            EntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n\r\n            Map<String, Client<Query>> clients = (Map<String, Client<Query>>) em.getDelegate();\r\n            Client client = clients.get(persistenceUnit);\r\n\r\n            result = client.executeScript(script);\r\n\r\n        } catch (Exception e) {\r\n            log.error(e.getMessage());\r\n            return Response.serverError().build();\r\n        }\r\n\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET: Media Type:\" + mediaType);\r\n\r\n        if (result == null) {\r\n            return Response.noContent().build();\r\n        } else {\r\n            if (mediaType.equalsIgnoreCase(MediaType.APPLICATION_JSON)) {\r\n                ObjectMapper mapper = new ObjectMapper();\r\n                String output = null;\r\n\r\n                try {\r\n                    output = mapper.writeValueAsString(result);\r\n                } catch (JsonGenerationException e) {\r\n                    log.error(e.getMessage());\r\n                } catch (JsonMappingException e) {\r\n                    log.error(e.getMessage());\r\n                } catch (IOException e) {\r\n                    log.error(e.getMessage());\r\n                }\r\n                return Response.ok(ResponseBuilder.buildOutput(output, \"'\"), mediaType).build();\r\n            } else {\r\n                return Response.ok(result, mediaType).build();\r\n            }\r\n        }\r\n\r\n    }\r\n\r\n    /************** Named Native Queries **************************/\r\n\r\n    /**\r\n     * Executes named native queries and returns response\r\n     * \r\n     * @param headers\r\n     * @param info\r\n     * @return\r\n     */\r\n\r\n    @GET\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Path(\"/{entityClass}/{namedNativeQueryName}\")\r\n    public Response executeNamedNativeQuery(@Context HttpHeaders headers, @Context UriInfo info) {\r\n\r\n        String entityClassName = info.getPathParameters().getFirst(\"entityClass\");\r\n        String namedNativeQueryName = info.getPathParameters().getFirst(\"namedNativeQueryName\");\r\n        String sessionToken = headers.getRequestHeader(Constants.SESSION_TOKEN_HEADER_NAME).get(0);\r\n\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n        mediaType =\r\n            mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML\r\n                : MediaType.APPLICATION_JSON;\r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"GET:: Session Token:\" + sessionToken + \", Entity Class Name:\" + entityClassName\r\n                + \", Named Native Query:\" + namedNativeQueryName + \", Media Type:\" + mediaType);\r\n\r\n        Class<?> entityClass = null;\r\n        List result = null;\r\n        EntityMetadata entityMetadata = null;\r\n        try {\r\n            EntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n\r\n            entityClass = EntityUtils.getEntityClass(entityClassName, em);\r\n            entityMetadata = EntityUtils.getEntityMetaData(entityClass.getSimpleName(), em);\r\n            if (log.isDebugEnabled())\r\n                log.debug(\"GET: entityClass\" + entityClass);\r\n            Query q = em.createNamedQuery(namedNativeQueryName);\r\n            result = q.getResultList();\r\n        } catch (Exception e) {\r\n            log.error(e.getMessage(), e);\r\n            return Response.serverError().build();\r\n        }\r\n\r\n        if (result == null) {\r\n            return Response.noContent().build();\r\n        }\r\n\r\n        String output = CollectionConverter.toString(result, entityClass, mediaType);\r\n        if (mediaType.equalsIgnoreCase(MediaType.APPLICATION_JSON)) {\r\n            return Response.ok(ResponseBuilder.buildOutput(entityClass, entityMetadata, output), mediaType).build();\r\n        } else {\r\n            return Response.ok(output.toString(), mediaType).build();\r\n        }\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/resources/SessionResource.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.resources;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.ws.rs.Consumes;\r\nimport javax.ws.rs.DELETE;\r\nimport javax.ws.rs.GET;\r\nimport javax.ws.rs.HeaderParam;\r\nimport javax.ws.rs.POST;\r\nimport javax.ws.rs.PUT;\r\nimport javax.ws.rs.Path;\r\nimport javax.ws.rs.Produces;\r\nimport javax.ws.rs.core.Context;\r\nimport javax.ws.rs.core.HttpHeaders;\r\nimport javax.ws.rs.core.MediaType;\r\nimport javax.ws.rs.core.Response;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.rest.common.Constants;\r\nimport com.impetus.kundera.rest.common.ResponseCode;\r\nimport com.impetus.kundera.rest.common.ResponseBuilder;\r\nimport com.impetus.kundera.rest.common.TokenUtils;\r\nimport com.impetus.kundera.rest.repository.EMFRepository;\r\nimport com.impetus.kundera.rest.repository.EMRepository;\r\n\r\n/**\r\n * Session Token REST Resource\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Path(\"/\" + Constants.KUNDERA_API_PATH + Constants.SESSION_RESOURCE_PATH)\r\npublic class SessionResource {\r\n\tprivate static Logger log = LoggerFactory.getLogger(SessionResource.class);\r\n\r\n\t/**\r\n\t * Handler for GET method requests for this resource Generates Session token\r\n\t * and returns, creates and puts EM into repository\r\n\t * \r\n\t * @param applicationToken\r\n\t * @return\r\n\t */\r\n\r\n\t@GET\r\n\t@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n\t@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n\tpublic Response getSessionToken(\r\n\t\t\t@HeaderParam(Constants.APPLICATION_TOKEN_HEADER_NAME) String applicationToken,\r\n\t\t\t@Context HttpHeaders headers) {\r\n\t\tif (log.isDebugEnabled())\r\n\t\t\tlog.debug(\"GET: Application Token:\" + applicationToken);\r\n\t\tString mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n\t\tmediaType = mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON;\r\n\t\tEntityManagerFactory emf = EMFRepository.INSTANCE\r\n\t\t\t\t.getEMF(applicationToken);\r\n\r\n\t\tif (emf == null) {\r\n\t\t\tif (log.isDebugEnabled())\r\n\t\t\t\tlog.warn(\"GET: Application Token:\" + applicationToken\r\n\t\t\t\t\t\t+ \" doesn't exist and hence Session can't be created\");\r\n\t\t\treturn Response.serverError().build();\r\n\t\t}\r\n\r\n\t\tString sessionToken = TokenUtils.generateSessionToken();\r\n\t\tEntityManager em = emf.createEntityManager();\r\n\r\n\t\tEMRepository.INSTANCE.addEm(sessionToken, em);\r\n\t\t//sessionToken = \"\\\"\"+sessionToken+\"\\\"\";\r\n\t\treturn Response.ok(ResponseBuilder.buildOutput(sessionToken, \"\\\"\"), mediaType).build();\r\n\t}\r\n\r\n\t/**\r\n\t * Handler for GET method requests for this resource Generates Session token\r\n\t * and returns, creates and puts EM into repository\r\n\t * \r\n\t * @param applicationToken\r\n\t * @return\r\n\t */\r\n\t@PUT\r\n\t@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n\t@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n\tpublic Response flush(\r\n\t\t\t@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken,\r\n\t\t\t@Context HttpHeaders headers) {\r\n\t\tif (log.isDebugEnabled())\r\n\t\t\tlog.debug(\"PUT: Session Token:\" + sessionToken);\r\n\t\tString mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n\t\tmediaType = mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON;\r\n\t\tEntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n\r\n\t\tif (em == null) {\r\n\t\t\tif (log.isDebugEnabled())\r\n\t\t\t\tlog.warn(\"PUT: Session Token:\" + sessionToken\r\n\t\t\t\t\t\t+ \" doesn't exist and hence can't be deleted\");\r\n\t\t\treturn Response.serverError().build();\r\n\t\t}\r\n\r\n\t\ttry {\r\n\t\t\tem.flush();\r\n\t\t} catch (Exception e) {\r\n\t\t\tlog.error(\"PUT: Failed: \" + e.getMessage());\r\n\t\t\tResponse.serverError().build();\r\n\t\t}\r\n\r\n\t\treturn Response.ok(new String(ResponseCode.PUT_ST_SUCCESS), mediaType)\r\n\t\t\t\t.build();\r\n\t}\r\n\t\r\n\t/**\r\n     * Handler for POST method requests for this resource clears em\r\n     * \r\n     * @param sessionToken\r\n     * @return\r\n     */\r\n    @POST\r\n    @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n    public Response clear(\r\n            @HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken,\r\n            @Context HttpHeaders headers) {\r\n        if (log.isDebugEnabled())\r\n            log.debug(\"PUT: Session Token:\" + sessionToken);\r\n        String mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n        mediaType = mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON;\r\n        EntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n\r\n        if (em == null) {\r\n            if (log.isDebugEnabled())\r\n                log.warn(\"PUT: Session Token:\" + sessionToken\r\n                        + \" doesn't exist and hence can't be cleared\");\r\n            return Response.serverError().build();\r\n        }\r\n\r\n        try {\r\n            em.clear();\r\n        } catch (Exception e) {\r\n            log.error(\"PUT: Failed: \" + e.getMessage());\r\n            Response.serverError().build();\r\n        }\r\n\r\n        return Response.ok(new String(ResponseCode.CLEAR_ST_SUCCESS), mediaType)\r\n                .build();\r\n    }\r\n\r\n\t/**\r\n\t * Handler for DELETE method requests for this resource Closes EM and\r\n\t * removes session token alongwith from repository\r\n\t * \r\n\t * @param id\r\n\t * @return\r\n\t */\r\n\t@DELETE\r\n\t@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n\t@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })\r\n\tpublic Response deleteSession(\r\n\t\t\t@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken,\r\n\t\t\t@Context HttpHeaders headers) {\r\n\r\n\t\tif (log.isDebugEnabled())\r\n\t\t\tlog.debug(\"DELETE: Session Token:\" + sessionToken);\r\n\t\tString mediaType = headers != null && headers.getRequestHeaders().containsKey(\"Content-type\")? headers.getRequestHeader(\"Content-type\").get(0) : MediaType.APPLICATION_JSON;\r\n\t\tmediaType = mediaType.equalsIgnoreCase(MediaType.APPLICATION_XML) ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON;\r\n\t\tEntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n\t\tif (em == null) {\r\n\t\t\tif (log.isDebugEnabled())\r\n\t\t\t\tlog.warn(\"DELETE: Session Token:\" + sessionToken\r\n\t\t\t\t\t\t+ \" doesn't exist and hence can't be deleted\");\r\n\r\n\t\t\tResponse.serverError().build();\r\n\t\t}\r\n\r\n\t\tEMRepository.INSTANCE.removeEm(sessionToken);\r\n\t\treturn Response.ok(new String(ResponseCode.DELETE_ST_SUCCESS),\r\n\t\t\t\tmediaType).build();\r\n\r\n\t}\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/main/java/com/impetus/kundera/rest/resources/TransactionResource.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.resources;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.ws.rs.Consumes;\r\nimport javax.ws.rs.DELETE;\r\nimport javax.ws.rs.GET;\r\nimport javax.ws.rs.HeaderParam;\r\nimport javax.ws.rs.POST;\r\nimport javax.ws.rs.Path;\r\nimport javax.ws.rs.Produces;\r\nimport javax.ws.rs.core.MediaType;\r\n\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.rest.common.Constants;\r\nimport com.impetus.kundera.rest.common.ResponseCode;\r\nimport com.impetus.kundera.rest.repository.EMRepository;\r\n\r\n/**\r\n * REST resource for entity transactions\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Path(\"/\" + Constants.KUNDERA_API_PATH + Constants.TRANSACTION_RESOURCE_PATH)\r\npublic class TransactionResource {\r\n\tprivate static Logger log = LoggerFactory\r\n\t\t\t.getLogger(TransactionResource.class);\r\n\r\n\t/**\r\n\t * Handler for GET method requests for this resource Begins a fresh\r\n\t * transaction for given session\r\n\t * \r\n\t * @return\r\n\t */\r\n\t@GET\r\n\t@Produces(MediaType.TEXT_PLAIN)\r\n\tpublic String begin(\r\n\t\t\t@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken) {\r\n\t\tif (log.isDebugEnabled())\r\n\t\t\tlog.debug(\"GET: Session Token:\" + sessionToken);\r\n\r\n\t\tEntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n\t\tif (em == null) {\r\n\t\t\tif (log.isDebugEnabled())\r\n\t\t\t\tlog.warn(\"GET: Session Token:\" + sessionToken\r\n\t\t\t\t\t\t+ \" doesn't exist and transaction failed to begin\");\r\n\t\t\treturn ResponseCode.GET_TX_FAILED;\r\n\t\t}\r\n\r\n\t\ttry {\r\n\t\t\tem.getTransaction().begin();\r\n\t\t} catch (Exception e) {\r\n\t\t\tlog.error(\"GET: Failed: \" + e.getMessage());\r\n\t\t\treturn ResponseCode.GET_TX_FAILED;\r\n\t\t}\r\n\t\treturn ResponseCode.GET_TX_SUCCESS;\r\n\t}\r\n\r\n\t/**\r\n\t * Handler for POST method requests for this resource Commits transaction\r\n\t * for the given session\r\n\t * \r\n\t * @param applicationToken\r\n\t * @return\r\n\t */\r\n\t@POST\r\n\t@Consumes(MediaType.TEXT_PLAIN)\r\n\tpublic String commit(\r\n\t\t\t@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken) {\r\n\t\tif (log.isDebugEnabled())\r\n\t\t\tlog.debug(\"POST: Session Token:\" + sessionToken);\r\n\r\n\t\tEntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n\t\tif (em == null) {\r\n\t\t\tif (log.isDebugEnabled())\r\n\t\t\t\tlog.warn(\"POST: Session Token:\"\r\n\t\t\t\t\t\t+ sessionToken\r\n\t\t\t\t\t\t+ \" doesn't exist and transaction could not be commited\");\r\n\t\t\treturn ResponseCode.POST_TX_FAILED;\r\n\t\t}\r\n\r\n\t\ttry {\r\n\t\t\tem.getTransaction().commit();\r\n\t\t} catch (Exception e) {\r\n\t\t\tlog.error(\"POST: Failed: \" + e.getMessage());\r\n\t\t\treturn ResponseCode.POST_TX_FAILED;\r\n\t\t}\r\n\t\treturn ResponseCode.POST_TX_SUCCESS;\r\n\t}\r\n\r\n\t/**\r\n\t * Handler for DELETE method requests for this resource Rolls back\r\n\t * transaction for the given session\r\n\t * \r\n\t * @return\r\n\t */\r\n\t@DELETE\r\n\t@Consumes(MediaType.TEXT_PLAIN)\r\n\tpublic String rollback(\r\n\t\t\t@HeaderParam(Constants.SESSION_TOKEN_HEADER_NAME) String sessionToken) {\r\n\t\tif (log.isDebugEnabled())\r\n\t\t\tlog.debug(\"DELETE: Session Token:\" + sessionToken);\r\n\r\n\t\tEntityManager em = EMRepository.INSTANCE.getEM(sessionToken);\r\n\t\tif (em == null) {\r\n\t\t\tif (log.isDebugEnabled())\r\n\t\t\t\tlog.warn(\"DELETE: Session Token:\"\r\n\t\t\t\t\t\t+ sessionToken\r\n\t\t\t\t\t\t+ \" doesn't exist and transaction could not be rolled back\");\r\n\t\t\treturn ResponseCode.DELETE_TX_FAILED;\r\n\r\n\t\t}\r\n\r\n\t\ttry {\r\n\t\t\tem.getTransaction().rollback();\r\n\t\t} catch (Exception e) {\r\n\t\t\tlog.error(\"DELETE: Failed: \" + e.getMessage());\r\n\t\t\treturn ResponseCode.DELETE_TX_FAILED;\r\n\t\t}\r\n\r\n\t\treturn ResponseCode.DELETE_TX_SUCCESS;\r\n\t}\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/main/resources/log4j.properties",
    "content": "log4j.rootLogger=WARN, DRFA, CONSOLE\r\n\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera-rest.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/Book.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.rest.common;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.NamedNativeQueries;\nimport javax.persistence.NamedNativeQuery;\nimport javax.persistence.NamedQueries;\nimport javax.persistence.NamedQuery;\nimport javax.persistence.Table;\nimport javax.xml.bind.annotation.XmlRootElement;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Entity class for Book\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"BOOK\")\n@NamedQueries(value = { @NamedQuery(name = \"findByAuthor\", query = \"Select b from Book b where b.author = :author\"),\n        @NamedQuery(name = \"findByPublication\", query = \"Select b from Book b where b.publication = ?1\"),\n        @NamedQuery(name = \"findAllBooks\", query = \"Select b from Book b\") })\n@NamedNativeQueries(value = { @NamedNativeQuery(name = \"findAllBooksNative\", query = \"select * from \" + \"\\\"BOOK\\\"\") })\n@IndexCollection(columns = {@Index(name = \"publication\"), @Index(name = \"author\")})\n@XmlRootElement\npublic class Book\n{\n    @Id\n    @Column(name = \"ISBN\")\n    String isbn;\n\n    @Column(name = \"AUTHOR\")\n    String author;\n\n    @Column(name = \"PUBLICATION\")\n    String publication;\n\n    /**\n     * @return the isbn\n     */\n    public String getIsbn()\n    {\n        return isbn;\n    }\n\n    /**\n     * @param isbn\n     *            the isbn to set\n     */\n    public void setIsbn(String isbn)\n    {\n        this.isbn = isbn;\n    }\n\n    /**\n     * @return the author\n     */\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    /**\n     * @param author\n     *            the author to set\n     */\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    /**\n     * @return the publication\n     */\n    public String getPublication()\n    {\n        return publication;\n    }\n\n    /**\n     * @param publication\n     *            the publication to set\n     */\n    public void setPublication(String publication)\n    {\n        this.publication = publication;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/EntityUtilsTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.rest.common;\n\nimport javax.ws.rs.HttpMethod;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\n/**\n * <Prove description of functionality provided by this Type>\n * \n * @author amresh.singh\n */\npublic class EntityUtilsTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.rest.common.EntityUtils#isValidQuery(java.lang.String, java.lang.String)}\n     * .\n     */\n    @Test\n    public void testIsValidQuery()\n    {\n        /** Positive scenario */\n        String insertQuery = \"Insert into Book values (1, Amresh)\";\n        Assert.assertTrue(EntityUtils.isValidQuery(insertQuery, HttpMethod.POST));\n\n        String selectQuery = \"Select b from Book b\";\n        Assert.assertTrue(EntityUtils.isValidQuery(selectQuery, HttpMethod.GET));\n\n        String updateQuery = \"update Book set author=Amresh\";\n        Assert.assertTrue(EntityUtils.isValidQuery(updateQuery, HttpMethod.PUT));\n\n        String deleteQuery = \"delete from Book\";\n        Assert.assertTrue(EntityUtils.isValidQuery(deleteQuery, HttpMethod.DELETE));\n\n        /** Negative scenario - Unmatched Http Method */\n        String insertQuery2 = \"Insert into Book values (1, Amresh)\";\n        Assert.assertFalse(EntityUtils.isValidQuery(insertQuery2, HttpMethod.GET));\n\n        String selectQuery2 = \"Select b from Book b\";\n        Assert.assertFalse(EntityUtils.isValidQuery(selectQuery2, HttpMethod.POST));\n\n        String updateQuery2 = \"update Book set author=Amresh\";\n        Assert.assertFalse(EntityUtils.isValidQuery(updateQuery2, HttpMethod.DELETE));\n\n        String deleteQuery2 = \"delete from Book\";\n        Assert.assertFalse(EntityUtils.isValidQuery(deleteQuery2, HttpMethod.PUT));\n\n        /** Negative scenario - Junk Values */\n        String junkQuery = \"Blah Blah Blah\";\n        Assert.assertFalse(EntityUtils.isValidQuery(junkQuery, HttpMethod.GET));\n        Assert.assertFalse(EntityUtils.isValidQuery(junkQuery, HttpMethod.POST));\n        Assert.assertFalse(EntityUtils.isValidQuery(junkQuery, HttpMethod.DELETE));\n        Assert.assertFalse(EntityUtils.isValidQuery(junkQuery, HttpMethod.PUT));\n    }\n    \n   \n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/ExternalLink.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.rest.common;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * Entity class for user's External link details\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"EXTERNAL_LINK\")\n@XmlRootElement\npublic class ExternalLink\n{\n\n    @Id\n    @Column(name = \"EXT_LINK_ID\")\n    private String extLinkId;\n\n    @Column(name = \"LINK_TYPE\")\n    private String linkType;\n\n    @Column(name = \"LINK_ADDRESS\")\n    private String linkAddress;\n\n    public ExternalLink()\n    {\n    }\n\n    public ExternalLink(String extLinkId, String type, String address)\n    {\n        this.extLinkId = extLinkId;\n        this.linkType = type;\n        this.linkAddress = address;\n    }\n\n    /**\n     * @return the extLinkId\n     */\n    public String getExtLinkId()\n    {\n        return extLinkId;\n    }\n\n    /**\n     * @param extLinkId\n     *            the extLinkId to set\n     */\n    public void setExtLinkId(String extLinkId)\n    {\n        this.extLinkId = extLinkId;\n    }\n\n    /**\n     * @return the linkType\n     */\n    public String getLinkType()\n    {\n        return linkType;\n    }\n\n    /**\n     * @param linkType\n     *            the linkType to set\n     */\n    public void setLinkType(String linkType)\n    {\n        this.linkType = linkType;\n    }\n\n    /**\n     * @return the linkAddress\n     */\n    public String getLinkAddress()\n    {\n        return linkAddress;\n    }\n\n    /**\n     * @param linkAddress\n     *            the linkAddress to set\n     */\n    public void setLinkAddress(String linkAddress)\n    {\n        this.linkAddress = linkAddress;\n    }\n}\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/HabitatUni1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.rest.common;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.xml.bind.annotation.XmlRootElement;\n\n@Entity\n@Table(name = \"ADDRESS\")\n@XmlRootElement\npublic class HabitatUni1ToM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/JAXBUtilsTest.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.common;\r\n\r\nimport java.util.Date;\r\nimport java.util.UUID;\r\n\r\nimport javax.ws.rs.core.MediaType;\r\n\r\nimport junit.framework.Assert;\r\nimport junit.framework.TestCase;\r\n\r\n/**\r\n * Test case for {@link JAXBUtils}\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class JAXBUtilsTest extends TestCase\r\n{\r\n\r\n    protected void setUp() throws Exception\r\n    {\r\n        super.setUp();\r\n    }\r\n\r\n    protected void tearDown() throws Exception\r\n    {\r\n        super.tearDown();\r\n    }\r\n\r\n    /**\r\n     * Test method for\r\n     * {@link com.impetus.kundera.rest.common.JAXBUtils#toObject(java.lang.String, java.lang.Class)}\r\n     * .\r\n     */\r\n    public void testXMLToObject()\r\n    {\r\n        String xml = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><book><isbn>34523423423423</isbn><author>Amresh</author><publication>Willey</publication></book>\";\r\n        try\r\n        {\r\n\r\n            Book book = (Book) JAXBUtils\r\n                    .toObject(StreamUtils.toInputStream(xml), Book.class, MediaType.APPLICATION_XML);\r\n            assertNotNull(book);\r\n            assertEquals(\"34523423423423\", book.getIsbn());\r\n            assertEquals(\"Amresh\", book.getAuthor());\r\n            assertEquals(\"Willey\", book.getPublication());\r\n        }\r\n        catch (Exception e)\r\n        {\r\n            fail(e.getMessage());\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Test method for\r\n     * {@link com.impetus.kundera.rest.common.JAXBUtils#toObject(java.lang.String, java.lang.Class)}\r\n     * .\r\n     */\r\n    public void testJSONToObject()\r\n    {\r\n\r\n        String json = \"{\\\"isbn\\\":\\\"2222\\\",\\\"author\\\":\\\"Kuldeep\\\", \\\"publication\\\":\\\"McGraw\\\"}\";\r\n        try\r\n        {\r\n\r\n            Book book = (Book) JAXBUtils.toObject(json, Book.class,\r\n                    MediaType.APPLICATION_JSON);\r\n            assertNotNull(book);\r\n            assertEquals(\"2222\", book.getIsbn());\r\n            assertEquals(\"Kuldeep\", book.getAuthor());\r\n            assertEquals(\"McGraw\", book.getPublication());\r\n        }\r\n        catch (Exception e)\r\n        {\r\n            fail(e.getMessage());\r\n        }\r\n    }\r\n\r\n    public void testObjectToXML()\r\n    {\r\n        Book b = new Book();\r\n        b.setIsbn(\"11111111111\");\r\n        b.setAuthor(\"Xamry\");\r\n        b.setPublication(\"McGraw\");\r\n\r\n        String s = JAXBUtils.toString(b, MediaType.APPLICATION_JSON);\r\n        Assert.assertNotNull(s);\r\n        \r\n      \r\n    }\r\n    \r\n    public void testObject()\r\n    {\r\n        UUID timeLineId = UUID.randomUUID();\r\n        Date currentDate = new Date();\r\n        MongoCompoundKey key = new MongoCompoundKey(\"mevivs\", 1, timeLineId);\r\n        key.setTimeLineId(timeLineId);\r\n        key.setTweetId(1);\r\n        key.setUserId(\"mevivs\");\r\n        MongoPrimeUser timeLine = new MongoPrimeUser(key);\r\n        timeLine.setKey(key);\r\n        timeLine.setTweetBody(\"my first tweet\");\r\n        timeLine.setTweetDate(currentDate);\r\n\r\n        String s = JAXBUtils.toString(timeLine, MediaType.APPLICATION_JSON);\r\n        Assert.assertNotNull(s);\r\n        \r\n            \r\n    }\r\n\r\n\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/MongoCompoundKey.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.rest.common;\n\nimport java.util.UUID;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * @author vivek.mishra\n */\n@Embeddable\n@XmlRootElement\npublic class MongoCompoundKey\n{\n    @Column\n    private String userId;\n\n    public void setUserId(String userId) {\n        this.userId = userId;\n    }\n\n    @Column\n    private int tweetId;\n\n    public void setTweetId(int tweetId) {\n        this.tweetId = tweetId;\n    }\n\n    @Column\n    private UUID timeLineId;\n\n    public void setTimeLineId(UUID timeLineId) {\n        this.timeLineId = timeLineId;\n    }\n\n    /**\n     * \n     */\n    public MongoCompoundKey()\n    {\n    }\n\n    /**\n     * @param userId\n     * @param tweetId\n     * @param timeLineId\n     */\n    public MongoCompoundKey(String userId, int tweetId, UUID timeLineId)\n    {\n        this.userId = userId;\n        this.tweetId = tweetId;\n        this.timeLineId = timeLineId;\n    }\n\n    /**\n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * @return the tweetId\n     */\n    public int getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * @return the timeLineId\n     */\n    public UUID getTimeLineId()\n    {\n        return timeLineId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/MongoPrimeUser.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.rest.common;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.EmbeddedId;\nimport javax.persistence.Entity;\nimport javax.persistence.Table;\nimport javax.xml.bind.annotation.XmlRootElement;\n\n/**\n * @author vivek.mishra\n * \n */\n\n@Entity\n@Table(name = \"MongoUser\")\n@XmlRootElement\npublic class MongoPrimeUser\n{\n\n    @EmbeddedId\n    private MongoCompoundKey key;\n\n    public MongoCompoundKey getKey() {\n        return key;\n    }\n\n    public void setKey(MongoCompoundKey key) {\n        this.key = key;\n    }\n\n    @Column\n    private String tweetBody;\n\n    @Column\n    private Date tweetDate;\n\n    public MongoPrimeUser()\n    {\n    }\n\n    public MongoPrimeUser(MongoCompoundKey key)\n    {\n        this.key = key;\n    }\n\n    \n\n    /**\n     * @return the tweetBody\n     */\n    public String getTweetBody()\n    {\n        return tweetBody;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetBody\n     *            the tweetBody to set\n     */\n    public void setTweetBody(String tweetBody)\n    {\n        this.tweetBody = tweetBody;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n}\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/PersonalDetailCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2014 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.rest.common;\r\n\r\nimport java.util.UUID;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\nimport com.impetus.kundera.index.Index;\r\nimport com.impetus.kundera.index.IndexCollection;\r\n\r\n/**\r\n * Entity class for user's personal details\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\n@IndexCollection(columns = { @Index(name = \"name\"), @Index(name = \"relationshipStatus\") })\r\npublic class PersonalDetailCassandra\r\n{\r\n    @Column(name = \"personal_detail_id\")\r\n    private String personalDetailId;\r\n\r\n    @Column(name = \"person_name\")\r\n    private String name;\r\n\r\n    @Column(name = \"person_password\")\r\n    private String password;\r\n\r\n    @Column(name = \"rel_status\")\r\n    private String relationshipStatus;\r\n\r\n    public PersonalDetailCassandra()\r\n    {\r\n\r\n    }\r\n\r\n    public PersonalDetailCassandra(String name, String password, String relationshipStatus)\r\n    {\r\n        setPersonalDetailId(UUID.randomUUID().toString());\r\n        setName(name);\r\n        setPassword(password);\r\n        setRelationshipStatus(relationshipStatus);\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetailId\r\n     */\r\n    public String getPersonalDetailId()\r\n    {\r\n        return personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetailId\r\n     *            the personalDetailId to set\r\n     */\r\n    public void setPersonalDetailId(String personalDetailId)\r\n    {\r\n        this.personalDetailId = personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @return the name\r\n     */\r\n    public String getName()\r\n    {\r\n        return name;\r\n    }\r\n\r\n    /**\r\n     * @param name\r\n     *            the name to set\r\n     */\r\n    public void setName(String name)\r\n    {\r\n        this.name = name;\r\n    }\r\n\r\n    /**\r\n     * @return the password\r\n     */\r\n    public String getPassword()\r\n    {\r\n        return password;\r\n    }\r\n\r\n    /**\r\n     * @param password\r\n     *            the password to set\r\n     */\r\n    public void setPassword(String password)\r\n    {\r\n        this.password = password;\r\n    }\r\n\r\n    /**\r\n     * @return the relationshipStatus\r\n     */\r\n    public String getRelationshipStatus()\r\n    {\r\n        return relationshipStatus;\r\n    }\r\n\r\n    /**\r\n     * @param relationshipStatus\r\n     *            the relationshipStatus to set\r\n     */\r\n    public void setRelationshipStatus(String relationshipStatus)\r\n    {\r\n        this.relationshipStatus = relationshipStatus;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/PersonnelUni1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.rest.common;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\nimport javax.xml.bind.annotation.XmlRootElement;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\n\n@Entity\n@Table(name = \"PERSONNEL\")\n@XmlRootElement\npublic class PersonnelUni1ToM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String PERSON_ID;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<HabitatUni1ToM> HabitatUni1ToM;\n\n    @JsonProperty(\"PERSON_ID\")\n    public String getPersonId()\n    {\n        return PERSON_ID;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n    @JsonProperty(\"PERSON_ID\")\n    public void setPersonId(String personId)\n    {\n        this.PERSON_ID = personId;\n    }\n    @JsonProperty(\"HabitatUni1ToM\")\n    public Set<HabitatUni1ToM> getAddresses()\n    {\n        return HabitatUni1ToM;\n    }\n    @JsonProperty(\"HabitatUni1ToM\")\n    public void setAddresses(Set<HabitatUni1ToM> addresses)\n    {\n        this.HabitatUni1ToM = addresses;\n    }\n}\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/PreferenceCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2014 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.rest.common;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\nimport javax.xml.bind.annotation.XmlRootElement;\r\n\r\n/**\r\n * Entity class for User Preferences\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"PREFERENCE\")\r\n@XmlRootElement\r\npublic class PreferenceCassandra\r\n{\r\n    @Id\r\n    @Column(name = \"PREFERENCE_ID\")\r\n    String preferenceId;\r\n\r\n    @Column(name = \"WEBSITE_THEME\")\r\n    String websiteTheme;\r\n\r\n    @Column(name = \"PRIVACY_LEVEL\")\r\n    String privacyLevel; // 1, 2, 3\r\n\r\n    public PreferenceCassandra()\r\n    {\r\n\r\n    }\r\n\r\n    public PreferenceCassandra(String preferenceId, String theme, String privacyLevel)\r\n    {\r\n        this.preferenceId = preferenceId;\r\n        this.websiteTheme = theme;\r\n        this.privacyLevel = privacyLevel;\r\n    }\r\n\r\n    /**\r\n     * @return the preferenceId\r\n     */\r\n    public String getPreferenceId()\r\n    {\r\n        return preferenceId;\r\n    }\r\n\r\n    /**\r\n     * @param preferenceId\r\n     *            the preferenceId to set\r\n     */\r\n    public void setPreferenceId(String preferenceId)\r\n    {\r\n        this.preferenceId = preferenceId;\r\n    }\r\n\r\n    /**\r\n     * @return the websiteTheme\r\n     */\r\n    public String getWebsiteTheme()\r\n    {\r\n        return websiteTheme;\r\n    }\r\n\r\n    /**\r\n     * @param websiteTheme\r\n     *            the websiteTheme to set\r\n     */\r\n    public void setWebsiteTheme(String websiteTheme)\r\n    {\r\n        this.websiteTheme = websiteTheme;\r\n    }\r\n\r\n    /**\r\n     * @return the privacyLevel\r\n     */\r\n    public String getPrivacyLevel()\r\n    {\r\n        return privacyLevel;\r\n    }\r\n\r\n    /**\r\n     * @param privacyLevel\r\n     *            the privacyLevel to set\r\n     */\r\n    public void setPrivacyLevel(String privacyLevel)\r\n    {\r\n        this.privacyLevel = privacyLevel;\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/Professional.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.rest.common;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.NamedQueries;\nimport javax.persistence.NamedQuery;\nimport javax.persistence.Table;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\nimport javax.xml.bind.annotation.XmlRootElement;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PROFESSIONAL\")\n@IndexCollection(columns = { @Index(name = \"departmentId\"), @Index(name = \"isExceptional\"), @Index(name = \"age\"),\n        @Index(name = \"grade\"), @Index(name = \"digitalSignature\"), @Index(name = \"rating\"),\n        @Index(name = \"compliance\"), @Index(name = \"height\"), @Index(name = \"enrolmentDate\"),\n        @Index(name = \"enrolmentTime\"), @Index(name = \"joiningDateAndTime\"), @Index(name = \"yearsSpent\"),\n        @Index(name = \"uniqueId\"), @Index(name = \"monthlySalary\"), @Index(name = \"birthday\"),\n        @Index(name = \"birthtime\"), @Index(name = \"anniversary\"), @Index(name = \"jobAttempts\"),\n        @Index(name = \"accumulatedWealth\"), @Index(name = \"graduationDay\") })\n@NamedQueries(value = {\n        @NamedQuery(name = \"findByDepartment\", query = \"Select p from Professional p where p.departmentId = :departmentId\"),\n        @NamedQuery(name = \"findByEnrolmentDate\", query = \"Select p from Professional p where p.enrolmentDate = ?1\") })\n@XmlRootElement\npublic class Professional\n{\n    // Primitive Types\n    @Id\n    @Column(name = \"PROFESSION_ID\")\n    private String professionId;\n\n    @Column(name = \"DEPARTMENT_ID\")\n    private long departmentId;\n\n    @Column(name = \"IS_EXCEPTIONAL\")\n    private boolean isExceptional;\n\n    @Column(name = \"AGE\")\n    private int age;\n\n    @Column(name = \"GRADE\")\n    private char grade; // A,B,C,D,E,F for i to vi\n\n    @Column(name = \"DIGITAL_SIGNATURE\")\n    private byte digitalSignature;\n\n    @Column(name = \"RATING\")\n    private short rating; // 1-10\n\n    @Column(name = \"COMPLIANCE\")\n    private float compliance;\n\n    @Column(name = \"HEIGHT\")\n    private double height;\n\n    // Date-time types\n    @Column(name = \"ENROLMENT_DATE\")\n    @Temporal(TemporalType.DATE)\n    private java.util.Date enrolmentDate;\n\n    @Column(name = \"ENROLMENT_TIME\")\n    @Temporal(TemporalType.TIME)\n    private java.util.Date enrolmentTime;\n\n    @Column(name = \"JOINING_DATE_TIME\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private java.util.Date joiningDateAndTime;\n\n    // Wrapper types\n    @Column(name = \"YEARS_SPENT\")\n    private Integer yearsSpent;\n\n    @Column(name = \"UNIQUE_ID\")\n    private Long uniqueId;\n\n    @Column(name = \"MONTHLY_SALARY\")\n    private Double monthlySalary;\n\n    /*\n     * @Column(name = \"BIRTH_DAY\") private java.sql.Date birthday;\n     * \n     * @Column(name = \"BIRTH_TIME\") private java.sql.Time birthtime;\n     * \n     * @Column(name = \"ANNIVERSARY\") private java.sql.Timestamp anniversary;\n     */\n\n    @Column(name = \"JOB_ATTEMPTS\")\n    private BigInteger jobAttempts;\n\n    @Column(name = \"ACCUMULATED_WEALTH\")\n    private BigDecimal accumulatedWealth;\n\n    @Column(name = \"GRADUATION_DAY\")\n    private Calendar graduationDay;\n\n    public Professional()\n    {\n\n    }\n\n    public Professional(String professionId, long departmentId, boolean isExceptional, int age, char grade,\n            byte digitalSignature, short rating, float compliance, double height, Date enrolmentDate,\n            Date enrolmentTime, Date joiningDateAndTime, Integer yearsSpent, Long uniqueId, Double monthlySalary,\n            /* java.sql.Date birthday, Time birthtime, Timestamp anniversary, */BigInteger jobAttempts,\n            BigDecimal accumulatedWealth, Calendar graduationDay)\n    {\n        super();\n        this.professionId = professionId;\n        this.departmentId = departmentId;\n        this.isExceptional = isExceptional;\n        this.age = age;\n        this.grade = grade;\n        this.digitalSignature = digitalSignature;\n        this.rating = rating;\n        this.compliance = compliance;\n        this.height = height;\n        this.enrolmentDate = enrolmentDate;\n        this.enrolmentTime = enrolmentTime;\n        this.joiningDateAndTime = joiningDateAndTime;\n        this.yearsSpent = yearsSpent;\n        this.uniqueId = uniqueId;\n        this.monthlySalary = monthlySalary;\n        /*\n         * this.birthday = birthday; this.birthtime = birthtime;\n         * this.anniversary = anniversary;\n         */\n        this.jobAttempts = jobAttempts;\n        this.accumulatedWealth = accumulatedWealth;\n        this.graduationDay = graduationDay;\n    }\n\n    /**\n     * @return the professionId\n     */\n    public String getProfessionId()\n    {\n        return professionId;\n    }\n\n    /**\n     * @param professionId\n     *            the professionId to set\n     */\n    public void setProfessionId(String professionId)\n    {\n        this.professionId = professionId;\n    }\n\n    /**\n     * @return the departmentId\n     */\n    public long getDepartmentId()\n    {\n        return departmentId;\n    }\n\n    /**\n     * @param departmentId\n     *            the departmentId to set\n     */\n    public void setDepartmentId(long departmentId)\n    {\n        this.departmentId = departmentId;\n    }\n\n    /**\n     * @return the isExceptional\n     */\n    public boolean isExceptional()\n    {\n        return isExceptional;\n    }\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    public void setExceptional(boolean isExceptional)\n    {\n        this.isExceptional = isExceptional;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the grade\n     */\n    public char getGrade()\n    {\n        return grade;\n    }\n\n    /**\n     * @param grade\n     *            the grade to set\n     */\n    public void setGrade(char grade)\n    {\n        this.grade = grade;\n    }\n\n    /**\n     * @return the digitalSignature\n     */\n    public byte getDigitalSignature()\n    {\n        return digitalSignature;\n    }\n\n    /**\n     * @param digitalSignature\n     *            the digitalSignature to set\n     */\n    public void setDigitalSignature(byte digitalSignature)\n    {\n        this.digitalSignature = digitalSignature;\n    }\n\n    /**\n     * @return the rating\n     */\n    public short getRating()\n    {\n        return rating;\n    }\n\n    /**\n     * @param rating\n     *            the rating to set\n     */\n    public void setRating(short rating)\n    {\n        this.rating = rating;\n    }\n\n    /**\n     * @return the compliance\n     */\n    public float getCompliance()\n    {\n        return compliance;\n    }\n\n    /**\n     * @param compliance\n     *            the compliance to set\n     */\n    public void setCompliance(float compliance)\n    {\n        this.compliance = compliance;\n    }\n\n    /**\n     * @return the height\n     */\n    public double getHeight()\n    {\n        return height;\n    }\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    public void setHeight(double height)\n    {\n        this.height = height;\n    }\n\n    /**\n     * @return the enrolmentDate\n     */\n    public java.util.Date getEnrolmentDate()\n    {\n        return enrolmentDate;\n    }\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    public void setEnrolmentDate(java.util.Date enrolmentDate)\n    {\n        this.enrolmentDate = enrolmentDate;\n    }\n\n    /**\n     * @return the enrolmentTime\n     */\n    public java.util.Date getEnrolmentTime()\n    {\n        return enrolmentTime;\n    }\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    public void setEnrolmentTime(java.util.Date enrolmentTime)\n    {\n        this.enrolmentTime = enrolmentTime;\n    }\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    public java.util.Date getJoiningDateAndTime()\n    {\n        return joiningDateAndTime;\n    }\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    public void setJoiningDateAndTime(java.util.Date joiningDateAndTime)\n    {\n        this.joiningDateAndTime = joiningDateAndTime;\n    }\n\n    /**\n     * @return the yearsSpent\n     */\n    public Integer getYearsSpent()\n    {\n        return yearsSpent;\n    }\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    public void setYearsSpent(Integer yearsSpent)\n    {\n        this.yearsSpent = yearsSpent;\n    }\n\n    /**\n     * @return the uniqueId\n     */\n    public Long getUniqueId()\n    {\n        return uniqueId;\n    }\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    public void setUniqueId(Long uniqueId)\n    {\n        this.uniqueId = uniqueId;\n    }\n\n    /**\n     * @return the monthlySalary\n     */\n    public Double getMonthlySalary()\n    {\n        return monthlySalary;\n    }\n\n    /**\n     * @param monthlySalary\n     *            the monthlySalary to set\n     */\n    public void setMonthlySalary(Double monthlySalary)\n    {\n        this.monthlySalary = monthlySalary;\n    }\n\n    /**\n     * @return the jobAttempts\n     */\n    public BigInteger getJobAttempts()\n    {\n        return jobAttempts;\n    }\n\n    /**\n     * @param jobAttempts\n     *            the jobAttempts to set\n     */\n    public void setJobAttempts(BigInteger jobAttempts)\n    {\n        this.jobAttempts = jobAttempts;\n    }\n\n    /**\n     * @return the accumulatedWealth\n     */\n    public BigDecimal getAccumulatedWealth()\n    {\n        return accumulatedWealth;\n    }\n\n    /**\n     * @param accumulatedWealth\n     *            the accumulatedWealth to set\n     */\n    public void setAccumulatedWealth(BigDecimal accumulatedWealth)\n    {\n        this.accumulatedWealth = accumulatedWealth;\n    }\n\n    /**\n     * @return the graduationDay\n     */\n    public Calendar getGraduationDay()\n    {\n        return graduationDay;\n    }\n\n    /**\n     * @param graduationDay\n     *            the graduationDay to set\n     */\n    public void setGraduationDay(Calendar graduationDay)\n    {\n        this.graduationDay = graduationDay;\n    }\n\n}"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/ProfessionalDetailCassandra.java",
    "content": "/**\n * Copyright 2014 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.rest.common;\n\nimport java.math.BigDecimal;\nimport java.math.BigInteger;\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Embeddable;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Holds professional details of any user\n * \n * @author amresh.singh\n */\n\n@Embeddable\n@IndexCollection(columns = { @Index(name = \"professionId\"), @Index(name = \"departmentName\"),\n        @Index(name = \"isExceptional\"), @Index(name = \"age\"), @Index(name = \"grade\"),\n        @Index(name = \"digitalSignature\"), @Index(name = \"rating\"), @Index(name = \"compliance\"),\n        @Index(name = \"height\"), @Index(name = \"enrolmentDate\"), @Index(name = \"enrolmentTime\"),\n        @Index(name = \"joiningDateAndTime\"), @Index(name = \"yearsSpent\"), @Index(name = \"uniqueId\"),\n        @Index(name = \"monthlySalary\"), @Index(name = \"birthday\"), @Index(name = \"birthtime\"),\n        @Index(name = \"anniversary\"), @Index(name = \"jobAttempts\"), @Index(name = \"accumulatedWealth\"),\n        @Index(name = \"graduationDay\") })\npublic class ProfessionalDetailCassandra\n{\n\n    @Column(name = \"DEPARTMENT_ID\")\n    private long departmentId;\n\n    @Column(name = \"IS_EXCEPTIONAL\")\n    private boolean isExceptional;\n\n    @Column(name = \"AGE\")\n    private int age;\n\n    @Column(name = \"GRADE\")\n    private char grade; // A,B,C,D,E,F for i to vi\n\n//    @Column(name = \"DIGITAL_SIGNATURE\")\n//    private byte digitalSignature;\n\n    @Column(name = \"RATING\")\n    private short rating; // 1-10\n\n    @Column(name = \"COMPLIANCE\")\n    private float compliance;\n\n    @Column(name = \"HEIGHT\")\n    private double height;\n\n    // Date-time types\n    @Column(name = \"ENROLMENT_DATE\")\n    @Temporal(TemporalType.DATE)\n    private java.util.Date enrolmentDate;\n\n    @Column(name = \"ENROLMENT_TIME\")\n    @Temporal(TemporalType.TIME)\n    private java.util.Date enrolmentTime;\n\n    @Column(name = \"JOINING_DATE_TIME\")\n    @Temporal(TemporalType.TIMESTAMP)\n    private java.util.Date joiningDateAndTime;\n\n    // Wrapper types\n    @Column(name = \"YEARS_SPENT\")\n    private Integer yearsSpent;\n\n    @Column(name = \"UNIQUE_ID\")\n    private Long uniqueId;\n\n    @Column(name = \"MONTHLY_SALARY\")\n    private Double monthlySalary;\n\n    /*\n     * @Column(name = \"BIRTH_DAY\") private java.sql.Date birthday;\n     * \n     * @Column(name = \"BIRTH_TIME\") private java.sql.Time birthtime;\n     * \n     * @Column(name = \"ANNIVERSARY\") private java.sql.Timestamp anniversary;\n     */\n\n    @Column(name = \"JOB_ATTEMPTS\")\n    private BigInteger jobAttempts;\n\n    @Column(name = \"ACCUMULATED_WEALTH\")\n    private BigDecimal accumulatedWealth;\n\n    @Column(name = \"GRADUATION_DAY\")\n    private Calendar graduationDay;\n\n\n    public ProfessionalDetailCassandra()\n    {\n\n    }\n\n    public ProfessionalDetailCassandra(long departmentId, boolean isExceptional, int age, char grade,\n            byte digitalSignature, short rating, float compliance, double height, Date enrolmentDate,\n            Date enrolmentTime, Date joiningDateAndTime, Integer yearsSpent, Long uniqueId, Double monthlySalary,\n            /* java.sql.Date birthday, Time birthtime, Timestamp anniversary, */BigInteger jobAttempts,\n            BigDecimal accumulatedWealth, Calendar graduationDay)\n    {\n        super();\n       \n        this.departmentId = departmentId;\n        this.isExceptional = isExceptional;\n        this.age = age;\n        this.grade = grade;\n    //    this.digitalSignature = digitalSignature;\n        this.rating = rating;\n        this.compliance = compliance;\n        this.height = height;\n        this.enrolmentDate = enrolmentDate;\n        this.enrolmentTime = enrolmentTime;\n        this.joiningDateAndTime = joiningDateAndTime;\n        this.yearsSpent = yearsSpent;\n        this.uniqueId = uniqueId;\n        this.monthlySalary = monthlySalary;\n        /*\n         * this.birthday = birthday; this.birthtime = birthtime;\n         * this.anniversary = anniversary;\n         */\n        this.jobAttempts = jobAttempts;\n        this.accumulatedWealth = accumulatedWealth;\n        this.graduationDay = graduationDay;\n    }\n\n   \n\n    /**\n     * @return the departmentId\n     */\n    public long getDepartmentId()\n    {\n        return departmentId;\n    }\n\n    /**\n     * @param departmentId\n     *            the departmentId to set\n     */\n    public void setDepartmentId(long departmentId)\n    {\n        this.departmentId = departmentId;\n    }\n\n    /**\n     * @return the isExceptional\n     */\n    public boolean isExceptional()\n    {\n        return isExceptional;\n    }\n\n    /**\n     * @param isExceptional\n     *            the isExceptional to set\n     */\n    public void setExceptional(boolean isExceptional)\n    {\n        this.isExceptional = isExceptional;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the grade\n     */\n    public char getGrade()\n    {\n        return grade;\n    }\n\n    /**\n     * @param grade\n     *            the grade to set\n     */\n    public void setGrade(char grade)\n    {\n        this.grade = grade;\n    }\n\n//    /**\n//     * @return the digitalSignature\n//     */\n//    public byte getDigitalSignature()\n//    {\n//        return digitalSignature;\n//    }\n//\n//    /**\n//     * @param digitalSignature\n//     *            the digitalSignature to set\n//     */\n//    public void setDigitalSignature(byte digitalSignature)\n//    {\n//        this.digitalSignature = digitalSignature;\n//    }\n\n    /**\n     * @return the rating\n     */\n    public short getRating()\n    {\n        return rating;\n    }\n\n    /**\n     * @param rating\n     *            the rating to set\n     */\n    public void setRating(short rating)\n    {\n        this.rating = rating;\n    }\n\n    /**\n     * @return the compliance\n     */\n    public float getCompliance()\n    {\n        return compliance;\n    }\n\n    /**\n     * @param compliance\n     *            the compliance to set\n     */\n    public void setCompliance(float compliance)\n    {\n        this.compliance = compliance;\n    }\n\n    /**\n     * @return the height\n     */\n    public double getHeight()\n    {\n        return height;\n    }\n\n    /**\n     * @param height\n     *            the height to set\n     */\n    public void setHeight(double height)\n    {\n        this.height = height;\n    }\n\n    /**\n     * @return the enrolmentDate\n     */\n    public java.util.Date getEnrolmentDate()\n    {\n        return enrolmentDate;\n    }\n\n    /**\n     * @param enrolmentDate\n     *            the enrolmentDate to set\n     */\n    public void setEnrolmentDate(java.util.Date enrolmentDate)\n    {\n        this.enrolmentDate = enrolmentDate;\n    }\n\n    /**\n     * @return the enrolmentTime\n     */\n    public java.util.Date getEnrolmentTime()\n    {\n        return enrolmentTime;\n    }\n\n    /**\n     * @param enrolmentTime\n     *            the enrolmentTime to set\n     */\n    public void setEnrolmentTime(java.util.Date enrolmentTime)\n    {\n        this.enrolmentTime = enrolmentTime;\n    }\n\n    /**\n     * @return the joiningDateAndTime\n     */\n    public java.util.Date getJoiningDateAndTime()\n    {\n        return joiningDateAndTime;\n    }\n\n    /**\n     * @param joiningDateAndTime\n     *            the joiningDateAndTime to set\n     */\n    public void setJoiningDateAndTime(java.util.Date joiningDateAndTime)\n    {\n        this.joiningDateAndTime = joiningDateAndTime;\n    }\n\n    /**\n     * @return the yearsSpent\n     */\n    public Integer getYearsSpent()\n    {\n        return yearsSpent;\n    }\n\n    /**\n     * @param yearsSpent\n     *            the yearsSpent to set\n     */\n    public void setYearsSpent(Integer yearsSpent)\n    {\n        this.yearsSpent = yearsSpent;\n    }\n\n    /**\n     * @return the uniqueId\n     */\n    public Long getUniqueId()\n    {\n        return uniqueId;\n    }\n\n    /**\n     * @param uniqueId\n     *            the uniqueId to set\n     */\n    public void setUniqueId(Long uniqueId)\n    {\n        this.uniqueId = uniqueId;\n    }\n\n    /**\n     * @return the monthlySalary\n     */\n    public Double getMonthlySalary()\n    {\n        return monthlySalary;\n    }\n\n    /**\n     * @param monthlySalary\n     *            the monthlySalary to set\n     */\n    public void setMonthlySalary(Double monthlySalary)\n    {\n        this.monthlySalary = monthlySalary;\n    }\n\n    /**\n     * @return the jobAttempts\n     */\n    public BigInteger getJobAttempts()\n    {\n        return jobAttempts;\n    }\n\n    /**\n     * @param jobAttempts\n     *            the jobAttempts to set\n     */\n    public void setJobAttempts(BigInteger jobAttempts)\n    {\n        this.jobAttempts = jobAttempts;\n    }\n\n    /**\n     * @return the accumulatedWealth\n     */\n    public BigDecimal getAccumulatedWealth()\n    {\n        return accumulatedWealth;\n    }\n\n    /**\n     * @param accumulatedWealth\n     *            the accumulatedWealth to set\n     */\n    public void setAccumulatedWealth(BigDecimal accumulatedWealth)\n    {\n        this.accumulatedWealth = accumulatedWealth;\n    }\n\n    /**\n     * @return the graduationDay\n     */\n    public Calendar getGraduationDay()\n    {\n        return graduationDay;\n    }\n\n    /**\n     * @param graduationDay\n     *            the graduationDay to set\n     */\n    public void setGraduationDay(Calendar graduationDay)\n    {\n        this.graduationDay = graduationDay;\n    }\n\n\n   \n\n\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/StreamUtilsTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.rest.common;\n\nimport java.io.InputStream;\n\nimport junit.framework.TestCase;\n\n/**\n * Test case for {@link StreamUtils}\n * \n * @author amresh.singh\n */\npublic class StreamUtilsTest extends TestCase\n{\n\n    protected void setUp() throws Exception\n    {\n        super.setUp();\n    }\n\n    protected void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.rest.common.StreamUtils#toString(java.io.InputStream)}\n     * .\n     */\n    public void testToStringInputStream()\n    {\n\n        String str = \"<book><isbn>34523423423423</isbn><author>Amresh</author><publication>Willey</publication></book>\";\n        InputStream is = StreamUtils.toInputStream(str);\n        String str2 = StreamUtils.toString(is);\n        assertNotNull(str2);\n        assertEquals(str2, str);\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.rest.common.StreamUtils#toInputStream(java.lang.String)}\n     * .\n     */\n    public void testToInputStream()\n    {\n        String str = \"<book><isbn>34523423423423</isbn><author>Amresh</author><publication>Willey</publication></book>\";\n        InputStream is = StreamUtils.toInputStream(str);\n        assertNotNull(is);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/TokenUtilsTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.rest.common;\n\nimport junit.framework.TestCase;\n\n/**\n * Test case for {@link TokenUtils}\n * \n * @author amresh.singh\n */\npublic class TokenUtilsTest extends TestCase\n{\n\n    protected void setUp() throws Exception\n    {\n        super.setUp();\n\n    }\n\n    protected void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.rest.common.TokenUtils#generateApplicationToken()}\n     * .\n     */\n    public void testGenerateApplicationToken()\n    {\n        String applicationToken = TokenUtils.generateApplicationToken();\n        assertNotNull(applicationToken);\n        assertTrue(applicationToken.startsWith(Constants.APPLICATION_TOKEN_PREFIX + \"_\"));\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.rest.common.TokenUtils#generateSessionToken()}\n     * .\n     */\n    public void testGenerateSessionToken()\n    {\n        String sessionToken = TokenUtils.generateSessionToken();\n        assertNotNull(sessionToken);\n        assertTrue(sessionToken.startsWith(Constants.SESSION_TOKEN_PREFIX + \"_\"));\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/TweetCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2014 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.rest.common;\r\n\r\nimport java.util.UUID;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\nimport com.impetus.kundera.index.Index;\r\nimport com.impetus.kundera.index.IndexCollection;\r\n\r\n/**\r\n * Class for Tweets\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\n@IndexCollection(columns = { @Index(name = \"body\"), @Index(name = \"device\") })\r\npublic class TweetCassandra\r\n{\r\n\r\n    @Column(name = \"tweet_id\")\r\n    private String tweetId;\r\n\r\n    @Column(name = \"tweet_body\")\r\n    private String body;\r\n\r\n    @Column(name = \"tweeted_from\")\r\n    private String device;\r\n\r\n    // private long timestamp;\r\n\r\n    public TweetCassandra(String body, String device)\r\n    {\r\n        this.tweetId = UUID.randomUUID().toString();\r\n        this.body = body;\r\n        this.device = device;\r\n        // this.timestamp = ExampleUtils.getCurrentTimestamp();\r\n    }\r\n\r\n    public TweetCassandra()\r\n    {\r\n\r\n    }\r\n\r\n    /**\r\n     * @return the tweetId\r\n     */\r\n    public String getTweetId()\r\n    {\r\n        return tweetId;\r\n    }\r\n\r\n    /**\r\n     * @param tweetId\r\n     *            the tweetId to set\r\n     */\r\n    public void setTweetId(String tweetId)\r\n    {\r\n        this.tweetId = tweetId;\r\n    }\r\n\r\n    /**\r\n     * @return the body\r\n     */\r\n    public String getBody()\r\n    {\r\n        return body;\r\n    }\r\n\r\n    /**\r\n     * @param body\r\n     *            the body to set\r\n     */\r\n    public void setBody(String body)\r\n    {\r\n        this.body = body;\r\n    }\r\n\r\n    /**\r\n     * @return the device\r\n     */\r\n    public String getDevice()\r\n    {\r\n        return device;\r\n    }\r\n\r\n    /**\r\n     * @param device\r\n     *            the device to set\r\n     */\r\n    public void setDevice(String device)\r\n    {\r\n        this.device = device;\r\n    }\r\n\r\n    /*    *//**\r\n     * @return the timestamp\r\n     */\r\n    /*\r\n     * public long getTimestamp() { return timestamp; }\r\n     *//**\r\n     * @param timestamp\r\n     *            the timestamp to set\r\n     */\r\n    /*\r\n     * public void setTimestamp(long timestamp) { this.timestamp = timestamp; }\r\n     */\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/common/UserCassandra.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2014 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.rest.common;\r\n\r\n\r\nimport java.util.List;\r\nimport java.util.Set;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.CollectionTable;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.ElementCollection;\r\nimport javax.persistence.Embedded;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.OneToOne;\r\nimport javax.persistence.Table;\r\nimport javax.xml.bind.annotation.XmlRootElement;\r\n\r\nimport com.impetus.kundera.index.Index;\r\nimport com.impetus.kundera.index.IndexCollection;\r\n\r\n/**\r\n * @author impetus\r\n * \r\n */\r\n@Entity\r\n@Table(name = \"USER\")\r\n@XmlRootElement\r\n@IndexCollection(columns = { @Index(name = \"preference\") })\r\npublic class UserCassandra\r\n{\r\n\r\n    @Id\r\n    @Column(name = \"USER_ID\")\r\n    private String userId;\r\n\r\n    // Embedded object, will persist co-located\r\n    @Embedded\r\n    private PersonalDetailCassandra personalDetail;\r\n\r\n    // Embedded object, will persist co-located\r\n    @Embedded\r\n    private ProfessionalDetailCassandra professionalDetail;\r\n\r\n    // Element collection, will persist co-located\r\n    @ElementCollection\r\n    @CollectionTable(name = \"tweeted\")\r\n    private List<TweetCassandra> tweets;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"FRIEND_ID\")\r\n    private List<UserCassandra> friends; // List of users whom I follow\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"FOLLOWER_ID\")\r\n    private List<UserCassandra> followers; // List of users who are following me\r\n\r\n    // One-to-one, will be persisted separately\r\n    @OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"PREFERENCE_ID\")\r\n    //@XmlTransient\r\n    private PreferenceCassandra preference;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)\r\n    @JoinColumn(name = \"USER_ID\")\r\n    private Set<ExternalLink> externalLinks;\r\n    \r\n    @Column(name = \"USER_IMAGE\")\r\n    private byte[] userImage;\r\n\r\n   \r\n\r\n\tpublic UserCassandra()\r\n    {\r\n\r\n    }\r\n\r\n    public UserCassandra(String userId, String name, String password, String relationshipStatus)\r\n    {\r\n        PersonalDetailCassandra pd = new PersonalDetailCassandra(name, password, relationshipStatus);\r\n        setUserId(userId);\r\n        setPersonalDetail(pd);\r\n    }\r\n\r\n    /**\r\n     * @return the userId\r\n     */\r\n    public String getUserId()\r\n    {\r\n        return userId;\r\n    }\r\n\r\n    /**\r\n     * @param userId\r\n     *            the userId to set\r\n     */\r\n    public void setUserId(String userId)\r\n    {\r\n        this.userId = userId;\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetail\r\n     */\r\n    public PersonalDetailCassandra getPersonalDetail()\r\n    {\r\n        return personalDetail;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetail\r\n     *            the personalDetail to set\r\n     */\r\n    public void setPersonalDetail(PersonalDetailCassandra personalDetail)\r\n    {\r\n        this.personalDetail = personalDetail;\r\n    }\r\n\r\n    /**\r\n     * @return the professionalDetail\r\n     */\r\n    public ProfessionalDetailCassandra getProfessionalDetail()\r\n    {\r\n        return professionalDetail;\r\n    }\r\n\r\n    /**\r\n     * @param professionalDetail\r\n     *            the professionalDetail to set\r\n     */\r\n    public void setProfessionalDetail(ProfessionalDetailCassandra professionalDetail)\r\n    {\r\n        this.professionalDetail = professionalDetail;\r\n    }\r\n\r\n    /**\r\n     * @return the tweets\r\n     */\r\n    public List<TweetCassandra> getTweets()\r\n    {\r\n        return tweets;\r\n    }\r\n\r\n    /**\r\n     * @param tweets\r\n     *            the tweets to set\r\n     */\r\n    public void setTweets(List<TweetCassandra> tweets)\r\n    {\r\n        this.tweets = tweets;\r\n    }\r\n\r\n    /**\r\n     * @return the preference\r\n     */\r\n    public PreferenceCassandra getPreference()\r\n    {\r\n        return preference;\r\n    }\r\n\r\n    /**\r\n     * @param preference\r\n     *            the preference to set\r\n     */\r\n    public void setPreference(PreferenceCassandra preference)\r\n    {\r\n        this.preference = preference;\r\n    }\r\n\r\n    /**\r\n     * @return the externalLinks\r\n     */\r\n    public Set<ExternalLink> getExternalLinks()\r\n    {\r\n        return externalLinks;\r\n    }\r\n\r\n    /**\r\n     * @param imDetails\r\n     *            the imDetails to set\r\n     */\r\n    public void setExternalLinks(Set<ExternalLink> externalLinks)\r\n    {\r\n        this.externalLinks = externalLinks;\r\n    }\r\n\r\n   /**\r\n     * @return the friends\r\n     */\r\n    public List<UserCassandra> getFriends()\r\n    {\r\n        return friends;\r\n    }\r\n\r\n    /**\r\n     * @param friends\r\n     *            the friends to set\r\n     */\r\n    public void setFriends(List<UserCassandra> friends)\r\n    {\r\n        this.friends = friends;\r\n    }\r\n\r\n    /**\r\n     * @return the followers\r\n     */\r\n    public List<UserCassandra> getFollowers()\r\n    {\r\n        return followers;\r\n    }\r\n\r\n    /**\r\n     * @param followers\r\n     *            the followers to set\r\n     */\r\n    public void setFollowers(List<UserCassandra> followers)\r\n    {\r\n        this.followers = followers ;\r\n    }\r\n    \r\n    /**\r\n   \t * @return the userImage\r\n   \t */\r\n   \tpublic byte[] getUserImage() {\r\n   \t\treturn userImage;\r\n   \t}\r\n\r\n   \t/**\r\n   \t * @param userImage the userImage to set\r\n   \t */\r\n   \tpublic void setUserImage(byte[] userImage) {\r\n   \t\tthis.userImage = userImage;\r\n   \t}\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/converters/CollectionConverterTest.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.rest.converters;\r\n\r\nimport java.math.BigDecimal;\r\nimport java.math.BigInteger;\r\nimport java.util.ArrayList;\r\nimport java.util.Calendar;\r\nimport java.util.Collection;\r\nimport java.util.Date;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Set;\r\n\r\nimport javax.ws.rs.core.MediaType;\r\n\r\nimport junit.framework.Assert;\r\n\r\nimport org.junit.After;\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\n\r\nimport com.impetus.kundera.rest.common.Book;\r\nimport com.impetus.kundera.rest.common.ExternalLink;\r\nimport com.impetus.kundera.rest.common.JAXBUtils;\r\nimport com.impetus.kundera.rest.common.PreferenceCassandra;\r\nimport com.impetus.kundera.rest.common.ProfessionalDetailCassandra;\r\nimport com.impetus.kundera.rest.common.StreamUtils;\r\nimport com.impetus.kundera.rest.common.TweetCassandra;\r\nimport com.impetus.kundera.rest.common.UserCassandra;\r\n\r\n/**\r\n * @author amresh\r\n * \r\n */\r\npublic class CollectionConverterTest {\r\n\r\n\t/**\r\n\t * @throws java.lang.Exception\r\n\t */\r\n\t@Before\r\n\tpublic void setUp() throws Exception {\r\n\t}\r\n\r\n\t/**\r\n\t * @throws java.lang.Exception\r\n\t */\r\n\t@After\r\n\tpublic void tearDown() throws Exception {\r\n\t}\r\n\r\n\t/**\r\n\t * Test method for\r\n\t * {@link com.impetus.kundera.rest.converters.CollectionConverter#toString(java.util.Collection, java.lang.Class, java.lang.String)}\r\n\t * .\r\n\t */\r\n\t@Test\r\n\tpublic void testToStringCollectionOfQClassOfQString() {\r\n\t\tList books = new ArrayList();\r\n\r\n\t\tBook book1 = new Book();\r\n\t\tbook1.setIsbn(\"11111111111\");\r\n\t\tbook1.setAuthor(\"Amresh\");\r\n\t\tbook1.setPublication(\"AAA\");\r\n\r\n\t\tBook book2 = new Book();\r\n\t\tbook2.setIsbn(\"22222222222\");\r\n\t\tbook2.setAuthor(\"Vivek\");\r\n\t\tbook2.setPublication(\"BBB\");\r\n\r\n\t\tbooks.add(book1);\r\n\t\tbooks.add(book2);\r\n\r\n\t\tString s = CollectionConverter.toString(books, Book.class,\r\n\t\t\t\tMediaType.APPLICATION_JSON);\r\n\r\n\t\tAssert.assertNotNull(s);\r\n\t}\r\n\r\n\t@Test\r\n\tpublic void testToCollection() {\r\n\r\n\t\tString s = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" standalone=\\\"yes\\\"?><books><book><author>Saurabh</author><isbn>1111111111111</isbn><publication>Willey</publication></book><book><author>Vivek</author><isbn>2222222222222</isbn><publication>OReilly</publication></book><books>\";\r\n\t\tCollection c = CollectionConverter.toCollection(s, ArrayList.class,\r\n\t\t\t\tBook.class, MediaType.APPLICATION_XML);\r\n\t\tAssert.assertNotNull(c);\r\n\t\tAssert.assertFalse(c.isEmpty());\r\n\t\tAssert.assertEquals(2, c.size());\r\n\t\t\r\n\t\ts = \"[{\\\"isbn\\\":\\\"1111111111111\\\",\\\"author\\\":\\\"Amresh\\\", \\\"publication\\\":\\\"Willey\\\"},{\\\"isbn\\\":\\\"2222222222222\\\",\\\"author\\\":\\\"Vivek\\\", \\\"publication\\\":\\\"Oreilly\\\"}]\";\r\n\t\t\r\n\t\tc = CollectionConverter.toCollection(s, ArrayList.class,\r\n            Book.class, MediaType.APPLICATION_JSON);\r\n        Assert.assertNotNull(c);\r\n        Assert.assertFalse(c.isEmpty());\r\n        Assert.assertEquals(2, c.size());\r\n\r\n\t}\r\n\r\n\t@Test\r\n    public void testComplexCollection(){\r\n\t\t\r\n\t\tList users = new ArrayList();\r\n\t\t\r\n    \tList<UserCassandra> friendList = new ArrayList<UserCassandra>();\r\n    \t\r\n    \tList<UserCassandra> followers = new ArrayList<UserCassandra>();\r\n    \t\r\n    \t UserCassandra user1 = new UserCassandra(\"001\", \"Amresh\", \"password1\", \"married\");\r\n    \t \r\n         UserCassandra user2 = new UserCassandra(\"002\", \"Vivek\", \"password1\", \"married\");\r\n         \r\n         UserCassandra user3 = new UserCassandra(\"0003\", \"Kuldeep\", \"password1\", \"single\");\r\n\r\n         friendList.add(user2);\r\n         Calendar cal = Calendar.getInstance();\r\n         cal.setTime(new Date(1344079067777l));\r\n\r\n         \r\n         user1.setProfessionalDetail(new ProfessionalDetailCassandra(1234567, true, 31, 'C', (byte) 8, (short) 5, (float) 10.0, 163.12, new Date(\r\n                 Long.parseLong(\"1351667541111\")), new Date(Long.parseLong(\"1351667542222\")), new Date(\r\n                 Long.parseLong(\"1351667543333\")), 2, new Long(3634521523423L), new Double(7.23452342343),\r\n     \r\n         new BigInteger(\"123456789\"), new BigDecimal(123456789), cal));\r\n         \r\n         user2.setProfessionalDetail(new ProfessionalDetailCassandra(1234568, true, 21, 'C', (byte) 8, (short) 5, (float) 10.0, 163.12, new Date(\r\n                 Long.parseLong(\"1351667541111\")), new Date(Long.parseLong(\"1351667542222\")), new Date(\r\n                 Long.parseLong(\"1351667543333\")), 2, new Long(3634521523423L), new Double(7.23452342343),\r\n     \r\n         new BigInteger(\"123456789\"), new BigDecimal(123456789), cal));\r\n\r\n         user1.setPreference(new PreferenceCassandra(\"P1\", \"Motif\", \"2\"));\r\n         \r\n         followers.add(user3);\r\n         \r\n         friendList.add(user2);\r\n         \r\n         user1.setFriends(friendList);\r\n         \r\n         user1.setFollowers(followers);\r\n         \r\n         Set<ExternalLink> externalLinks = new HashSet<ExternalLink>();\r\n         List<TweetCassandra> tweetList = new ArrayList<TweetCassandra>();\r\n         \r\n         externalLinks.add(new ExternalLink(\"L1\", \"Facebook\", \"http://facebook.com/coolnerd\"));\r\n         externalLinks.add(new ExternalLink(\"L2\", \"LinkedIn\", \"http://linkedin.com/in/devilmate\"));\r\n         user1.setExternalLinks(externalLinks);\r\n         \r\n         \r\n         tweetList.add(new TweetCassandra(\"Here is my first tweet\", \"Web\"));\r\n         tweetList.add(new TweetCassandra(\"Second Tweet from me\", \"Mobile\"));\r\n         user1.setTweets(tweetList);\r\n         \r\n        \r\n         String userString1 = JAXBUtils.toString(user1, MediaType.APPLICATION_JSON);\r\n         String userString2= JAXBUtils.toString(user2, MediaType.APPLICATION_JSON);\r\n         String userString3 = JAXBUtils.toString(user3, MediaType.APPLICATION_JSON);\r\n         \r\n         \r\n         \r\n         users.add(user1);\r\n         users.add(user2);\r\n         users.add(user3);\r\n         \r\n         String userList = CollectionConverter.toString(users, UserCassandra.class, MediaType.APPLICATION_JSON);\r\n         Assert.assertNotNull( userList);\r\n         \r\n         \r\n         user1 = (UserCassandra) JAXBUtils.toObject(StreamUtils.toInputStream(userString1), UserCassandra.class, MediaType.APPLICATION_JSON);\r\n         Assert.assertNotNull(user1);\r\n         \r\n         \r\n         user2 = (UserCassandra) JAXBUtils.toObject(StreamUtils.toInputStream(userString2), UserCassandra.class, MediaType.APPLICATION_JSON);\r\n         Assert.assertNotNull(user2);\r\n         \r\n         \r\n         user3 = (UserCassandra) JAXBUtils.toObject(StreamUtils.toInputStream(userString3), UserCassandra.class, MediaType.APPLICATION_JSON);\r\n         Assert.assertNotNull(user3);\r\n         \r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/dao/RESTClient.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.dao;\r\n\r\nimport java.util.Map;\r\n\r\nimport com.sun.jersey.api.client.WebResource;\r\n\r\n/**\r\n * REST Client interface\r\n * \r\n * @author amresh.singh\r\n */\r\npublic interface RESTClient\r\n{\r\n\r\n    /** Handshake and metadata methods */\r\n    void initialize(WebResource wr, String mediaType);\r\n\r\n    String getApplicationToken(String persistenceUnit, String externalProperties);\r\n\r\n    String closeApplication(String applicationToken);\r\n\r\n    String getSessionToken(String applicationToken);\r\n\r\n    String closeSession(String sessionToken);\r\n\r\n    String getSchemaList(String sessionToken,String persistenceUnit);\r\n    \r\n    String getEntityModel(String sessionToken,String entityClassName);\r\n\r\n    /** Operations on Book entity */\r\n    String insertEntity(String sessionToken, String entityStr, String entityClassName);\r\n\r\n    String findEntity(String sessionToken, String pk, String entityClassName);\r\n\r\n    String updateEntity(String sessionToken, String newEntityStr, String entityClassName);\r\n\r\n    void deleteEntity(String sessionToken, String updatedBook, String pk, String entityClassName);\r\n\r\n    String getAllEntities(String sessionToken, String entityClassName);\r\n\r\n    String runJPAQuery(String sessionToken, String jpaQuery, Map<String, Object> params);\r\n\r\n    String runNamedJPAQuery(String sessionToken, String entityClassName, String namedQuery, Map<String, Object> params);\r\n\r\n    String runNativeQuery(String sessionToken, String entityClassName, String nativeQuery, Map<String, Object> params);\r\n    \r\n    String runNativeScript(String sessionToken, String nativeQuery, String persistenceUnit);\r\n\r\n    String runNamedNativeQuery(String sessionToken, String entityClassName, String namedNativeQuery,\r\n            Map<String, Object> params);\r\n\r\n    /** Operations on Person entity */\r\n\r\n    String insertPerson(String sessionToken, String person);\r\n\r\n    String findPerson(String sessionToken, String isbn);\r\n\r\n    String updatePerson(String sessionToken, String oldPerson);\r\n\r\n    String getAllPersons(String sessionToken);\r\n\r\n    void deletePerson(String sessionToken, String updatedPerson, String isbn);\r\n\r\n\tString runObjectJPAQuery(String sessionToken, String jpaQuery,\r\n\t\t\tMap<String, Object> params);\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/dao/RESTClientImpl.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.dao;\r\n\r\nimport java.io.IOException;\r\nimport java.io.InputStream;\r\nimport java.util.Map;\r\n\r\nimport javax.ws.rs.core.MediaType;\r\n\r\nimport org.codehaus.jackson.JsonGenerationException;\r\nimport org.codehaus.jackson.map.JsonMappingException;\r\nimport org.codehaus.jackson.map.ObjectMapper;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.rest.common.Constants;\r\nimport com.impetus.kundera.rest.common.StreamUtils;\r\nimport com.sun.jersey.api.client.ClientHandlerException;\r\nimport com.sun.jersey.api.client.ClientResponse;\r\nimport com.sun.jersey.api.client.UniformInterfaceException;\r\nimport com.sun.jersey.api.client.WebResource;\r\n\r\n/**\r\n * REST Client implementation for test cases\r\n * \r\n * @see RESTClient\r\n * @author amresh.singh\r\n */\r\npublic class RESTClientImpl implements RESTClient {\r\n    private static Logger log = LoggerFactory.getLogger(RESTClientImpl.class);\r\n\r\n    private WebResource webResource = null;\r\n\r\n    private String mediaType;\r\n\r\n    @Override\r\n    public void initialize(WebResource wr, String mediaType) {\r\n        this.webResource = wr;\r\n        this.mediaType = mediaType;\r\n    }\r\n\r\n    @Override\r\n    public String getApplicationToken(String persistenceUnit, String externalProperties) {\r\n        String applicationToken;\r\n        try {\r\n            log.debug(\"\\n\\nGetting Application Token...\");\r\n            WebResource.Builder atBuilder =\r\n                webResource.path(Constants.KUNDERA_API_PATH + \"/application/\" + persistenceUnit).accept(mediaType)\r\n                    .type(mediaType);\r\n            StringBuffer sb = new StringBuffer().append(externalProperties);\r\n            ClientResponse insertResponse = (ClientResponse) atBuilder.post(ClientResponse.class, sb.toString());\r\n\r\n            InputStream is = insertResponse.getEntityInputStream();\r\n            applicationToken = StreamUtils.toString(is);\r\n\r\n            log.debug(\"Application Token:\" + applicationToken);\r\n        } catch (UniformInterfaceException e) {\r\n            log.error(\"Error during getApplicationToken, Caused by:\" + e.getMessage() + \", returning null\");\r\n            return null;\r\n        } catch (ClientHandlerException e) {\r\n            log.error(\"Error during getApplicationToken, Caused by:\" + e.getMessage() + \", returning null\");\r\n            return null;\r\n        }\r\n        return applicationToken;\r\n    }\r\n\r\n    @Override\r\n    public String closeApplication(String applicationToken) {\r\n        log.debug(\"\\n\\nClosing Application for Token:\" + applicationToken);\r\n        WebResource.Builder atBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + \"/application\").type(mediaType).accept(mediaType)\r\n                .header(Constants.APPLICATION_TOKEN_HEADER_NAME, applicationToken);\r\n        String response = atBuilder.delete(String.class);\r\n        log.debug(\"Application Closure Response: \" + response);\r\n        return response;\r\n    }\r\n\r\n    @Override\r\n    public String getSessionToken(String applicationToken) {\r\n        log.debug(\"\\n\\nGetting Session Token...\");\r\n        WebResource.Builder stBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + \"/session\").type(mediaType).accept(mediaType)\r\n                .header(Constants.APPLICATION_TOKEN_HEADER_NAME, applicationToken);\r\n\r\n        String sessionToken = stBuilder.get(String.class);\r\n\r\n        log.debug(\"Session Token:\" + sessionToken);\r\n        return sessionToken;\r\n    }\r\n\r\n    @Override\r\n    public String closeSession(String sessionToken) {\r\n\r\n        log.debug(\"\\n\\nClosing Session for Token:\" + sessionToken);\r\n        WebResource.Builder stBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + \"/session\").type(mediaType).accept(mediaType)\r\n                .header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        String response = stBuilder.delete(String.class);\r\n        log.debug(\"Session Deletion Response: \" + response);\r\n        return response;\r\n    }\r\n\r\n    @Override\r\n    public String insertEntity(String sessionToken, String entityStr, String entityClassName) {\r\n        log.debug(\"\\n\\nInserting Entity...\");\r\n\r\n        WebResource.Builder insertBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + \"/crud/\" + entityClassName).type(mediaType).accept(mediaType)\r\n                .header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        StringBuffer sb = new StringBuffer().append(entityStr);\r\n        ClientResponse insertResponse = (ClientResponse) insertBuilder.post(ClientResponse.class, sb.toString());\r\n        log.debug(\"Response From Insert Entity: \" + insertResponse);\r\n        return insertResponse.toString();\r\n    }\r\n\r\n    @Override\r\n    public String findEntity(String sessionToken, String pk, String entityClassName) {\r\n        log.debug(\"\\n\\nFinding Entity...\");\r\n        WebResource.Builder findBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + \"/crud/\" + entityClassName + \"/\" + pk).accept(mediaType)\r\n                .type(mediaType).header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n\r\n        ClientResponse findResponse = (ClientResponse) findBuilder.get(ClientResponse.class);\r\n\r\n        InputStream is = findResponse.getEntityInputStream();\r\n        String entityStr = StreamUtils.toString(is);\r\n\r\n        log.debug(\"Found Entity:\" + entityStr);\r\n        return entityStr;\r\n    }\r\n\r\n    @Override\r\n    public String updateEntity(String sessionToken, String newEntityStr, String entityClassName) {\r\n        log.debug(\"\\n\\nUpdating Entity... \" + newEntityStr);\r\n        WebResource.Builder updateBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + \"/crud/\" + entityClassName).type(mediaType).accept(mediaType)\r\n                .header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        ClientResponse updateResponse = updateBuilder.put(ClientResponse.class, newEntityStr);\r\n        InputStream is = updateResponse.getEntityInputStream();\r\n        String updatedEntityStr = StreamUtils.toString(is);\r\n        log.debug(\"Updated Entity: \" + updatedEntityStr);\r\n        return updatedEntityStr;\r\n    }\r\n\r\n    @Override\r\n    public void deleteEntity(String sessionToken, String entityStr, String pk, String entityClassName) {\r\n        log.debug(\"\\n\\nDeleting Entity... \" + entityStr);\r\n        WebResource.Builder deleteBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + \"/crud/\" + entityClassName + \"/delete/\" + pk)\r\n                .accept(MediaType.TEXT_PLAIN).header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        ClientResponse deleteResponse = (ClientResponse) deleteBuilder.delete(ClientResponse.class);\r\n        log.debug(\"Delete Response:\" + deleteResponse.getStatus());\r\n    }\r\n\r\n    @Override\r\n    public String runJPAQuery(String sessionToken, String jpaQuery, Map<String, Object> params) {\r\n        log.debug(\"\\n\\nRunning JPA Query... \");\r\n\r\n        String paramsStr = buildParamString(params);\r\n        WebResource.Builder queryBuilder =\r\n            webResource\r\n                .path(Constants.KUNDERA_API_PATH + Constants.JPA_QUERY_RESOURCE_PATH + \"/\" + jpaQuery + paramsStr)\r\n                .type(mediaType).accept(mediaType).header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        ClientResponse queryResponse = (ClientResponse) queryBuilder.post(ClientResponse.class);\r\n        log.debug(\"Query Response:\" + queryResponse.getStatus());\r\n\r\n        InputStream is = queryResponse.getEntityInputStream();\r\n\r\n        String allStr = StreamUtils.toString(is);\r\n\r\n        log.debug(\"Found Entities:\" + allStr);\r\n        return allStr;\r\n    }\r\n\r\n    @Override\r\n    public String runObjectJPAQuery(String sessionToken, String jpaQuery, Map<String, Object> params) {\r\n        log.debug(\"\\n\\nRunning JPA Query... \");\r\n\r\n        String paramsStr = buildObjectParamString(params);\r\n\r\n        WebResource.Builder queryBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + Constants.JPA_QUERY_RESOURCE_PATH + \"/\" + jpaQuery)\r\n                .type(mediaType).accept(mediaType).header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        ClientResponse queryResponse = (ClientResponse) queryBuilder.post(ClientResponse.class, paramsStr);\r\n\r\n        log.debug(\"Query Response:\" + queryResponse.getStatus());\r\n\r\n        InputStream is = queryResponse.getEntityInputStream();\r\n\r\n        String allStr = StreamUtils.toString(is);\r\n\r\n        log.debug(\"Found Entities:\" + allStr);\r\n        return allStr;\r\n    }\r\n\r\n    private String buildObjectParamString(Map<String, Object> params) {\r\n\r\n        ObjectMapper mapper = new ObjectMapper();\r\n\r\n        String parameterString = null;\r\n        // convert map to JSON string\r\n        try {\r\n            parameterString = mapper.writeValueAsString(params);\r\n        } catch (JsonGenerationException e) {\r\n            log.error(e.getMessage());\r\n        } catch (JsonMappingException e) {\r\n            log.error(e.getMessage());\r\n        } catch (IOException e) {\r\n            log.error(e.getMessage());\r\n        }\r\n        return parameterString;\r\n    }\r\n\r\n    @Override\r\n    public String runNamedJPAQuery(String sessionToken, String entityClassName, String namedQuery,\r\n        Map<String, Object> params) {\r\n        log.debug(\"\\n\\nRunning Named JPA Query \" + namedQuery + \"... \");\r\n\r\n        String paramsStr = buildParamString(params);\r\n\r\n        WebResource wr =\r\n            webResource.path(Constants.KUNDERA_API_PATH + Constants.JPA_QUERY_RESOURCE_PATH + \"/\" + entityClassName\r\n                + \"/\" + namedQuery + paramsStr);\r\n\r\n        WebResource.Builder queryBuilder =\r\n            wr.accept(mediaType).header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken).type(mediaType);\r\n\r\n        ClientResponse queryResponse = (ClientResponse) queryBuilder.get(ClientResponse.class);\r\n        log.debug(\"Query Response:\" + queryResponse.getStatus());\r\n\r\n        InputStream is = queryResponse.getEntityInputStream();\r\n        String allBookStr = StreamUtils.toString(is);\r\n\r\n        log.debug(\"Found Entities for query \" + namedQuery + \":\" + allBookStr);\r\n        return allBookStr;\r\n    }\r\n\r\n    @Override\r\n    public String runNativeQuery(String sessionToken, String entityClassName, String nativeQuery,\r\n        Map<String, Object> params) {\r\n        log.debug(\"\\n\\nRunning Native Query... \");\r\n\r\n        String paramsStr = buildParamString(params);\r\n        WebResource.Builder queryBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + Constants.NATIVE_QUERY_RESOURCE_PATH + entityClassName)\r\n                .accept(mediaType).type(mediaType).header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n\r\n        ClientResponse queryResponse = (ClientResponse) queryBuilder.post(ClientResponse.class, nativeQuery);\r\n        log.debug(\"Query Response:\" + queryResponse.getStatus());\r\n\r\n        InputStream is = queryResponse.getEntityInputStream();\r\n\r\n        String allStr = StreamUtils.toString(is);\r\n\r\n        log.debug(\"Found Entities:\" + allStr);\r\n        return allStr;\r\n    }\r\n\r\n    @Override\r\n    public String runNamedNativeQuery(String sessionToken, String entityClassName, String namedNativeQuery,\r\n        Map<String, Object> params) {\r\n        log.debug(\"\\n\\nRunning Named Native JPA Query \" + namedNativeQuery + \"... \");\r\n\r\n        String paramsStr = buildParamString(params);\r\n\r\n        WebResource wr =\r\n            webResource.path(Constants.KUNDERA_API_PATH + Constants.NATIVE_QUERY_RESOURCE_PATH + entityClassName + \"/\"\r\n                + namedNativeQuery + paramsStr);\r\n\r\n        WebResource.Builder queryBuilder =\r\n            wr.accept(mediaType).type(mediaType).header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n\r\n        ClientResponse queryResponse = (ClientResponse) queryBuilder.get(ClientResponse.class);\r\n        log.debug(\"Query Response:\" + queryResponse.getStatus());\r\n\r\n        InputStream is = queryResponse.getEntityInputStream();\r\n        String allBookStr = StreamUtils.toString(is);\r\n\r\n        log.debug(\"Found Entities for query \" + namedNativeQuery + \":\" + allBookStr);\r\n        return allBookStr;\r\n    }\r\n\r\n    @Override\r\n    public String getAllEntities(String sessionToken, String entityClassName) {\r\n        log.debug(\"\\n\\nFinding all Entities... \");\r\n        WebResource.Builder queryBuilder =\r\n            webResource\r\n                .path(Constants.KUNDERA_API_PATH + Constants.JPA_QUERY_RESOURCE_PATH + \"/\" + entityClassName + \"/all\")\r\n                .accept(mediaType).type(mediaType).header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        ClientResponse queryResponse = (ClientResponse) queryBuilder.get(ClientResponse.class);\r\n        log.debug(\"Find All Response:\" + queryResponse.getStatus());\r\n\r\n        InputStream is = queryResponse.getEntityInputStream();\r\n        // List books = (List) JAXBUtils.toObject(is, ArrayList.class,\r\n        // MediaType.APPLICATION_XML);\r\n\r\n        String allEntitiesStr = StreamUtils.toString(is);\r\n\r\n        log.debug(\"Found All Entities:\" + allEntitiesStr);\r\n        return allEntitiesStr;\r\n    }\r\n\r\n    @Override\r\n    public String getSchemaList(String sessionToken, String persistenceUnit) {\r\n        log.debug(\"\\n\\nGetting Schema List for PU :\" + persistenceUnit);\r\n        WebResource.Builder slBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + \"/metadata/schemaList/\" + persistenceUnit).accept(mediaType)\r\n                .header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        ClientResponse schemaResponse = (ClientResponse) slBuilder.get(ClientResponse.class);\r\n\r\n        InputStream is = schemaResponse.getEntityInputStream();\r\n        String schemaList = StreamUtils.toString(is);\r\n\r\n        log.debug(\"Schema List:\" + schemaList);\r\n        return schemaList;\r\n    }\r\n\r\n    @Override\r\n    public String insertPerson(String sessionToken, String personStr) {\r\n\r\n        log.debug(\"\\n\\nInserting Entity...\");\r\n        WebResource.Builder insertBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + \"/crud/PersonnelUni1ToM\").type(mediaType).accept(mediaType)\r\n                .header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        StringBuffer sb = new StringBuffer().append(personStr);\r\n        ClientResponse insertResponse = (ClientResponse) insertBuilder.post(ClientResponse.class, sb.toString());\r\n        log.debug(\"Response From Insert person: \" + insertResponse);\r\n        return insertResponse.toString();\r\n\r\n    }\r\n\r\n    @Override\r\n    public String findPerson(String sessionToken, String isbn) {\r\n\r\n        log.debug(\"\\n\\nFinding Entity...\");\r\n        WebResource.Builder findBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + \"/crud/PersonnelUni1ToM/\" + isbn).accept(mediaType)\r\n                .type(mediaType).header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        ;\r\n\r\n        ClientResponse findResponse = (ClientResponse) findBuilder.get(ClientResponse.class);\r\n\r\n        InputStream is = findResponse.getEntityInputStream();\r\n        String personkStr = StreamUtils.toString(is);\r\n\r\n        log.debug(\"Found Entity:\" + personkStr);\r\n        return personkStr;\r\n    }\r\n\r\n    @Override\r\n    public String updatePerson(String sessionToken, String oldPersonStr) {\r\n\r\n        log.debug(\"\\n\\nUpdating Entity... \" + oldPersonStr);\r\n        oldPersonStr = oldPersonStr.replaceAll(\"XXXXXXXXX\", \"YYYYYYYYY\");\r\n        WebResource.Builder updateBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + \"/crud/PersonnelUni1ToM\").type(mediaType).accept(mediaType)\r\n                .header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        ClientResponse updateResponse = updateBuilder.put(ClientResponse.class, oldPersonStr);\r\n        InputStream is = updateResponse.getEntityInputStream();\r\n        String updatedPersonStr = StreamUtils.toString(is);\r\n        log.debug(\"Updated Person: \" + updatedPersonStr);\r\n        return updatedPersonStr;\r\n\r\n    }\r\n\r\n    @Override\r\n    public String getAllPersons(String sessionToken) {\r\n        log.debug(\"\\n\\nFinding all Entities... \");\r\n        WebResource.Builder queryBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + Constants.JPA_QUERY_RESOURCE_PATH + \"/PersonnelUni1ToM/all\")\r\n                .type(mediaType).accept(mediaType).header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        ClientResponse queryResponse = (ClientResponse) queryBuilder.get(ClientResponse.class);\r\n        log.debug(\"Find All Response:\" + queryResponse.getStatus());\r\n\r\n        InputStream is = queryResponse.getEntityInputStream();\r\n     \r\n        String allPersonStr = StreamUtils.toString(is);\r\n\r\n        log.debug(\"Found All Entities:\" + allPersonStr);\r\n        return allPersonStr;\r\n    }\r\n\r\n    @Override\r\n    public void deletePerson(String sessionToken, String updatedPerson, String isbn) {\r\n        log.debug(\"\\n\\nDeleting Entity... \" + updatedPerson);\r\n        WebResource.Builder deleteBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + \"/crud/PersonnelUni1ToM/delete/\" + isbn).accept(mediaType)\r\n                .type(mediaType).header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        ClientResponse deleteResponse = (ClientResponse) deleteBuilder.delete(ClientResponse.class);\r\n        log.debug(\"Delete Response:\" + deleteResponse.getStatus());\r\n    }\r\n\r\n    /**\r\n     * @param params\r\n     * @return\r\n     */\r\n    private String buildParamString(Map<String, Object> params) {\r\n        String paramsStr = \"\";\r\n        if (params != null && !params.isEmpty()) {\r\n            paramsStr += \"?\";\r\n\r\n            for (String paramName : params.keySet()) {\r\n                if (paramsStr.length() == 1) {\r\n                    paramsStr += (paramName + \"=\" + params.get(paramName));\r\n                } else {\r\n                    paramsStr += (\"&\" + paramName + \"=\" + params.get(paramName));\r\n                }\r\n            }\r\n        }\r\n        return paramsStr;\r\n    }\r\n\r\n    @Override\r\n    public String getEntityModel(String sessionToken, String entityClassName) {\r\n        log.debug(\"\\n\\nGetting model for class :\" + entityClassName);\r\n        WebResource.Builder insertBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + \"/metadata/\" + entityClassName).accept(mediaType)\r\n                .header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        StringBuffer sb = new StringBuffer();\r\n        ClientResponse insertResponse = (ClientResponse) insertBuilder.post(ClientResponse.class, sb.toString());\r\n\r\n        InputStream is = insertResponse.getEntityInputStream();\r\n        String model = StreamUtils.toString(is);\r\n\r\n        log.debug(\"Entity Model:\" + model);\r\n        return model;\r\n    }\r\n\r\n    @Override\r\n    public String runNativeScript(String sessionToken, String nativeScript, String persistenceUnit) {\r\n\r\n        log.debug(\"\\n\\nUpdating Entity... \" + nativeScript);\r\n        WebResource.Builder updateBuilder =\r\n            webResource.path(Constants.KUNDERA_API_PATH + Constants.NATIVE_QUERY_RESOURCE_PATH + persistenceUnit)\r\n                .type(mediaType).accept(mediaType).header(Constants.SESSION_TOKEN_HEADER_NAME, sessionToken);\r\n        ClientResponse updateResponse = updateBuilder.put(ClientResponse.class, nativeScript);\r\n        InputStream is = updateResponse.getEntityInputStream();\r\n        String updatedEntityStr = StreamUtils.toString(is);\r\n        log.debug(\"Updated Entity: \" + updatedEntityStr);\r\n        return updatedEntityStr;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/resources/CRUDResourceTest.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.rest.resources;\r\n\r\nimport java.io.IOException;\r\nimport java.nio.ByteBuffer;\r\nimport java.util.ArrayList;\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\n\r\nimport javax.ws.rs.core.MediaType;\r\n\r\nimport junit.framework.Assert;\r\n\r\nimport org.apache.cassandra.thrift.CfDef;\r\nimport org.apache.cassandra.thrift.ColumnDef;\r\nimport org.apache.cassandra.thrift.IndexType;\r\nimport org.apache.cassandra.thrift.InvalidRequestException;\r\nimport org.apache.cassandra.thrift.KsDef;\r\nimport org.apache.cassandra.thrift.NotFoundException;\r\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\r\nimport org.apache.cassandra.thrift.TimedOutException;\r\nimport org.apache.cassandra.thrift.UnavailableException;\r\nimport org.apache.thrift.TException;\r\nimport org.codehaus.jackson.JsonGenerationException;\r\nimport org.codehaus.jackson.map.JsonMappingException;\r\nimport org.databene.contiperf.PerfTest;\r\nimport org.databene.contiperf.junit.ContiPerfRule;\r\nimport org.databene.contiperf.report.CSVSummaryReportModule;\r\nimport org.databene.contiperf.report.HtmlReportModule;\r\nimport org.databene.contiperf.report.ReportModule;\r\nimport org.junit.After;\r\nimport org.junit.AfterClass;\r\nimport org.junit.Before;\r\nimport org.junit.BeforeClass;\r\nimport org.junit.Rule;\r\nimport org.junit.Test;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\r\nimport com.impetus.kundera.rest.common.Book;\r\nimport com.impetus.kundera.rest.common.Constants;\r\nimport com.impetus.kundera.rest.common.HabitatUni1ToM;\r\nimport com.impetus.kundera.rest.common.JAXBUtils;\r\nimport com.impetus.kundera.rest.common.PersonnelUni1ToM;\r\nimport com.impetus.kundera.rest.dao.RESTClient;\r\nimport com.impetus.kundera.rest.dao.RESTClientImpl;\r\nimport com.sun.jersey.api.client.WebResource;\r\nimport com.sun.jersey.test.framework.JerseyTest;\r\n\r\n/**\r\n * Test case for {@link CRUDResource} Cassandra-CLI Commands to run for\r\n * non-embedded mode: create keyspace KunderaExamples; use KunderaExamples; drop\r\n * column family BOOK; drop column family PERSONNEL; drop column family ADDRESS;\r\n * create column family BOOK with comparator=UTF8Type and\r\n * default_validation_class=UTF8Type and key_validation_class=UTF8Type and\r\n * column_metadata=[{column_name: AUTHOR, validation_class:UTF8Type, index_type:\r\n * KEYS},{column_name: PUBLICATION, validation_class:UTF8Type, index_type:\r\n * KEYS}]; create column family PERSONNEL with comparator=UTF8Type and\r\n * default_validation_class=UTF8Type and key_validation_class=UTF8Type and\r\n * column_metadata=[{column_name: PERSON_NAME, validation_class:UTF8Type,\r\n * index_type: KEYS},{column_name: ADDRESS_ID, validation_class:UTF8Type,\r\n * index_type: KEYS}]; create column family ADDRESS with comparator=UTF8Type and\r\n * default_validation_class=UTF8Type and key_validation_class=UTF8Type and\r\n * column_metadata=[{column_name: STREET, validation_class:UTF8Type, index_type:\r\n * KEYS},{column_name: PERSON_ID, validation_class:UTF8Type, index_type: KEYS}];\r\n * describe KunderaExamples;\r\n * \r\n * @author amresh\r\n * \r\n */\r\npublic class CRUDResourceTest extends JerseyTest\r\n{\r\n\r\n    private static final String _KEYSPACE = \"KunderaExamples\";\r\n\r\n    private static Logger log = LoggerFactory.getLogger(CRUDResourceTest.class);\r\n\r\n    static String mediaType = MediaType.APPLICATION_XML;\r\n\r\n    static RESTClient restClient;\r\n\r\n    String applicationToken = null;\r\n\r\n    String sessionToken = null;\r\n\r\n    String bookStr1;\r\n\r\n    String bookStr2;\r\n\r\n    String pk1;\r\n\r\n    String pk2;\r\n    \r\n    private Map<String, Object> puProperties = new HashMap<String, Object>();\r\n\r\n    @Rule\r\n    public ContiPerfRule i = new ContiPerfRule(new ReportModule[] { new CSVSummaryReportModule(),\r\n            new HtmlReportModule() });\r\n\r\n    private final static boolean USE_EMBEDDED_SERVER = true;\r\n\r\n    private final static boolean AUTO_MANAGE_SCHEMA = true;\r\n\r\n    WebResource webResource = resource();\r\n\r\n    public CRUDResourceTest() throws Exception\r\n    {\r\n        super(Constants.KUNDERA_REST_RESOURCES_PACKAGE);\r\n    }\r\n\r\n    @BeforeClass\r\n    public static void setUpBeforeClass() throws Exception\r\n    {\r\n        if (USE_EMBEDDED_SERVER)\r\n        {\r\n            CassandraCli.cassandraSetUp();\r\n        }\r\n\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            loadData();\r\n        }\r\n\r\n        // Initialize REST Client\r\n        restClient = new RESTClientImpl();\r\n\r\n    }\r\n\r\n    @Before\r\n    public void setup() throws Exception\r\n    {\r\n\r\n        restClient.initialize(webResource, mediaType);\r\n    }\r\n\r\n    @After\r\n    public void tearDown() throws Exception\r\n    {\r\n        super.tearDown();\r\n    }\r\n\r\n    @AfterClass\r\n    public static void tearDownAfterClass() throws Exception\r\n    {\r\n\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            CassandraCli.dropKeySpace(_KEYSPACE);\r\n        }\r\n\r\n        if (USE_EMBEDDED_SERVER)\r\n        {\r\n\r\n        }\r\n\r\n    }\r\n\r\n    @Test\r\n    @PerfTest(invocations = 10)\r\n    public void testCRUD() throws JsonGenerationException, JsonMappingException, IOException\r\n    {\r\n\r\n        if (MediaType.APPLICATION_XML.equals(mediaType))\r\n        {\r\n            bookStr1 = \"<book><isbn>1111111111111</isbn><author>Amresh</author><publication>Willey</publication></book>\";\r\n            bookStr2 = \"<book><isbn>2222222222222</isbn><author>Vivek</author><publication>OReilly</publication></book>\";\r\n            pk1 = \"1111111111111\";\r\n            pk2 = \"2222222222222\";\r\n        }\r\n        else if (MediaType.APPLICATION_JSON.equals(mediaType))\r\n        {\r\n            bookStr1 = \"{\\\"isbn\\\":\\\"1111111111111\\\",\\\"author\\\":\\\"Amresh\\\", \\\"publication\\\":\\\"Willey\\\"}\";\r\n            bookStr2 = \"{\\\"isbn\\\":\\\"2222222222222\\\",\\\"author\\\":\\\"Vivek\\\", \\\"publication\\\":\\\"Oreilly\\\"}\";\r\n            pk1 = \"1111111111111\";\r\n            pk2 = \"2222222222222\";\r\n        }\r\n        else\r\n        {\r\n            Assert.fail(\"Incorrect Media Type:\" + mediaType);\r\n            return;\r\n        }\r\n\r\n        // Get Application Token\r\n    \r\n        applicationToken = restClient.getApplicationToken(\"cassTest\", null);\r\n        Assert.assertNotNull(applicationToken);\r\n        \r\n        Assert.assertTrue(applicationToken.startsWith(\"\\\"AT_\"));\r\n        applicationToken = applicationToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n\r\n        // Get Session Token\r\n        sessionToken = restClient.getSessionToken(applicationToken);\r\n        Assert.assertNotNull(sessionToken);\r\n        Assert.assertTrue(sessionToken.startsWith(\"\\\"ST_\"));\r\n        \r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        \r\n   \r\n\r\n        // Insert Record\r\n        String insertResponse1 = restClient.insertEntity(sessionToken, bookStr1, \"Book\");\r\n        String insertResponse2 = restClient.insertEntity(sessionToken, bookStr2, \"Book\");\r\n\r\n        Assert.assertNotNull(insertResponse1);\r\n        Assert.assertNotNull(insertResponse2);\r\n        \r\n        Assert.assertTrue(insertResponse1.indexOf(\"200\") > 0);\r\n        Assert.assertTrue(insertResponse2.indexOf(\"200\") > 0);\r\n\r\n        // Find Record\r\n        String foundBook = restClient.findEntity(sessionToken, pk1, \"Book\");\r\n        Assert.assertNotNull(foundBook);\r\n        foundBook = foundBook.replaceAll(\"^\\'|\\'$\", \"\");\r\n    \r\n        Assert.assertTrue(foundBook.indexOf(\"Amresh\") > 0);\r\n\r\n        // Update Record\r\n        foundBook = foundBook.replaceAll(\"Amresh\", \"Saurabh\");\r\n        String updatedBook = restClient.updateEntity(sessionToken, foundBook, \"Book\");\r\n        Assert.assertNotNull(updatedBook);\r\n        \r\n        Assert.assertTrue(updatedBook.indexOf(\"Saurabh\") > 0);\r\n\r\n        /** JPA Query - Select */\r\n        // Get All books\r\n        String jpaQuery = \"select b from Book b\";\r\n        String queryResult = restClient.runJPAQuery(sessionToken, jpaQuery, new HashMap<String, Object>());\r\n\r\n        log.debug(\"Query Result:\" + queryResult);\r\n        \r\n        /** JPA Query - Select All */\r\n        // Get All Books\r\n        String allBooks = restClient.getAllEntities(sessionToken, \"Book\");\r\n        \r\n        \r\n        Assert.assertNotNull(allBooks);\r\n        Assert.assertTrue(allBooks.indexOf(\"books\") > 0);\r\n        Assert.assertTrue(allBooks.indexOf(\"Saurabh\") > 0);\r\n        Assert.assertTrue(allBooks.indexOf(\"Vivek\") > 0);\r\n        log.debug(allBooks);\r\n\r\n        /** Named JPA Query - Select */\r\n        // Get books for a specific author\r\n        Map<String, Object> params = new HashMap<String, Object>();\r\n        params.put(\"author\", \"Saurabh\");\r\n        String booksByAuthor = restClient.runNamedJPAQuery(sessionToken, Book.class.getSimpleName(), \"findByAuthor\",\r\n                params);\r\n        Assert.assertNotNull(booksByAuthor);\r\n        Assert.assertTrue(booksByAuthor.indexOf(\"books\") > 0);\r\n        Assert.assertTrue(booksByAuthor.indexOf(\"Saurabh\") > 0);\r\n        Assert.assertFalse(booksByAuthor.indexOf(\"Vivek\") > 0);\r\n        log.debug(booksByAuthor);\r\n\r\n        /** Named JPA Query - Select */\r\n        // Get books for a specific publication\r\n        Map<String, Object> paramsPublication = new HashMap<String, Object>();\r\n        paramsPublication.put(\"1\", \"Willey\");\r\n        String booksByPublication = restClient.runNamedJPAQuery(sessionToken, Book.class.getSimpleName(),\r\n                \"findByPublication\", paramsPublication);\r\n        Assert.assertNotNull(booksByPublication);\r\n        Assert.assertTrue(booksByAuthor.indexOf(\"books\") > 0);\r\n        Assert.assertTrue(booksByAuthor.indexOf(\"Saurabh\") > 0);\r\n        Assert.assertFalse(booksByAuthor.indexOf(\"Vivek\") > 0);\r\n        Assert.assertTrue(booksByAuthor.indexOf(\"Willey\") > 0);\r\n        log.debug(booksByAuthor);\r\n\r\n        /** Native Query - Select */\r\n        // Get All books\r\n        String nativeQuery = \"Select * from \" + \"\\\"BOOK\\\"\";\r\n        String nativeQueryResult = restClient.runNativeQuery(sessionToken, \"Book\", nativeQuery,\r\n                new HashMap<String, Object>());\r\n        log.debug(\"Native Query Select Result:\" + nativeQueryResult);\r\n        Assert.assertNotNull(nativeQueryResult);\r\n        Assert.assertTrue(nativeQueryResult.indexOf(\"books\") > 0);\r\n        Assert.assertTrue(nativeQueryResult.indexOf(\"Saurabh\") > 0);\r\n        Assert.assertTrue(nativeQueryResult.indexOf(\"Vivek\") > 0);\r\n\r\n        /** Named Native Query - Select */\r\n        String namedNativeQuerySelectResult = restClient.runNamedNativeQuery(sessionToken, \"Book\",\r\n                \"findAllBooksNative\", new HashMap<String, Object>());\r\n        log.debug(\"Named Native Query Select Result:\" + namedNativeQuerySelectResult);\r\n        Assert.assertNotNull(namedNativeQuerySelectResult);\r\n        Assert.assertTrue(namedNativeQuerySelectResult.indexOf(\"books\") > 0);\r\n        Assert.assertTrue(namedNativeQuerySelectResult.indexOf(\"Saurabh\") > 0);\r\n        Assert.assertTrue(namedNativeQuerySelectResult.indexOf(\"Vivek\") > 0);\r\n\r\n        // Delete Records\r\n        restClient.deleteEntity(sessionToken, updatedBook, pk1, \"Book\");\r\n        restClient.deleteEntity(sessionToken, updatedBook, pk2, \"Book\");\r\n\r\n        // Close Session\r\n        restClient.closeSession(sessionToken);\r\n\r\n        // Close Application\r\n        restClient.closeApplication(applicationToken);\r\n\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            truncateColumnFamily();\r\n        }\r\n    }\r\n\r\n    @Test\r\n    @PerfTest(invocations = 10)\r\n    public void testCRUDOnAssociation()\r\n    {\r\n        String personStr;\r\n\r\n        String personStr1;\r\n        String personPk = \"1234567\";\r\n\r\n        String person1Pk = \"1234568\";\r\n        String addressPk = \"201001\";\r\n\r\n        Set<HabitatUni1ToM> addresses = new HashSet<HabitatUni1ToM>();\r\n\r\n        HabitatUni1ToM add1 = new HabitatUni1ToM();\r\n        add1.setAddressId(addressPk);\r\n        add1.setStreet(\"XXXXXXXXX\");\r\n\r\n        HabitatUni1ToM add = new HabitatUni1ToM();\r\n        add.setAddressId(addressPk);\r\n        add.setStreet(\"XXXXXXXXX\");\r\n\r\n        addresses.add(add1);\r\n        addresses.add(add);\r\n\r\n        PersonnelUni1ToM p = new PersonnelUni1ToM();\r\n        p.setPersonId(personPk);\r\n        p.setPersonName(\"kuldeep\");\r\n        p.setAddresses(addresses);\r\n\r\n        PersonnelUni1ToM p1 = new PersonnelUni1ToM();\r\n        p1.setPersonId(person1Pk);\r\n        p1.setPersonName(\"kuldeep\");\r\n        p1.setAddresses(addresses);\r\n\r\n        personStr = JAXBUtils.toString(p, mediaType);\r\n        personStr1 = JAXBUtils.toString(p1, mediaType);\r\n\r\n        // Get Application Token\r\n        applicationToken = restClient.getApplicationToken(\"cassTest\", null);\r\n        Assert.assertNotNull(applicationToken);\r\n        Assert.assertTrue(applicationToken.startsWith(\"\\\"AT_\"));\r\n        applicationToken = applicationToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n\r\n        // Get Session Token\r\n        sessionToken = restClient.getSessionToken(applicationToken);\r\n        Assert.assertNotNull(sessionToken);\r\n        Assert.assertNotNull(sessionToken);\r\n        Assert.assertTrue(sessionToken.startsWith(\"\\\"ST_\"));\r\n        \r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n\r\n        // Insert person.\r\n        String insertResponse = restClient.insertPerson(sessionToken, personStr);\r\n        String insertResponse1 = restClient.insertPerson(sessionToken, personStr1);\r\n\r\n        Assert.assertNotNull(insertResponse);\r\n        Assert.assertTrue(insertResponse.indexOf(\"200\") > 0);\r\n        Assert.assertNotNull(insertResponse1);\r\n        Assert.assertTrue(insertResponse1.indexOf(\"200\") > 0);\r\n\r\n        // Find person.\r\n        String foundPerson = restClient.findPerson(sessionToken, personPk);\r\n        Assert.assertNotNull(foundPerson);\r\n        \r\n        if (MediaType.APPLICATION_JSON.equals(mediaType))\r\n        {\r\n            foundPerson = \"{personnelUni1ToM:\" + foundPerson + \"}\";\r\n        }\r\n        Assert.assertTrue(foundPerson.indexOf(addressPk) > 0);\r\n        Assert.assertTrue(foundPerson.indexOf(\"XXXXXXXXX\") > 0);\r\n        Assert.assertTrue(foundPerson.indexOf(\"kuldeep\") > 0);\r\n\r\n        // Update Record\r\n        String updatedPerson = restClient.updatePerson(sessionToken, foundPerson);\r\n        Assert.assertNotNull(updatedPerson);\r\n        Assert.assertTrue(updatedPerson.indexOf(\"YYYYYYYYY\") > 0);\r\n\r\n        // Find all persons.\r\n        String allPersons = restClient.getAllPersons(sessionToken);\r\n        Assert.assertNotNull(allPersons);\r\n        Assert.assertTrue(allPersons.indexOf(\"personneluni1toms\") > 0);\r\n        log.debug(allPersons);\r\n\r\n        // Run Query.\r\n        String jpaQuery = \"select p from PersonnelUni1ToM p where p.PERSON_ID >= \" + person1Pk;\r\n        String queryResult = restClient.runJPAQuery(sessionToken, jpaQuery, new HashMap<String, Object>());\r\n        log.debug(\"Query Result:\" + queryResult);\r\n        Assert.assertNotNull(queryResult);\r\n\r\n        // Delete person.\r\n        restClient.deletePerson(sessionToken, updatedPerson, personPk);\r\n        foundPerson = restClient.findPerson(sessionToken, personPk);\r\n        Assert.assertEquals(\"\", foundPerson);\r\n\r\n        // Close Session\r\n        restClient.closeSession(sessionToken);\r\n\r\n        // Close Application\r\n        restClient.closeApplication(applicationToken);\r\n\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            truncateColumnFamily();\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Load cassandra specific data.\r\n     * \r\n     * @throws TException\r\n     *             the t exception\r\n     * @throws InvalidRequestException\r\n     *             the invalid request exception\r\n     * @throws UnavailableException\r\n     *             the unavailable exception\r\n     * @throws TimedOutException\r\n     *             the timed out exception\r\n     * @throws SchemaDisagreementException\r\n     *             the schema disagreement exception\r\n     */\r\n    private static void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\r\n            SchemaDisagreementException\r\n    {\r\n        KsDef ksDef = null;\r\n        CfDef user_Def = new CfDef();\r\n        user_Def.name = \"BOOK\";\r\n        user_Def.keyspace = _KEYSPACE;\r\n        user_Def.setComparator_type(\"UTF8Type\");\r\n        user_Def.setKey_validation_class(\"UTF8Type\");\r\n\r\n        ColumnDef authorDef = new ColumnDef(ByteBuffer.wrap(\"AUTHOR\".getBytes()), \"UTF8Type\");\r\n        authorDef.index_type = IndexType.KEYS;\r\n        ColumnDef publicationDef = new ColumnDef(ByteBuffer.wrap(\"PUBLICATION\".getBytes()), \"UTF8Type\");\r\n        publicationDef.index_type = IndexType.KEYS;\r\n        user_Def.addToColumn_metadata(authorDef);\r\n        user_Def.addToColumn_metadata(publicationDef);\r\n\r\n        CfDef person_Def = new CfDef();\r\n        person_Def.name = \"PERSONNEL\";\r\n        person_Def.keyspace = _KEYSPACE;\r\n        person_Def.setComparator_type(\"UTF8Type\");\r\n        person_Def.setKey_validation_class(\"UTF8Type\");\r\n        person_Def.setComparator_type(\"UTF8Type\");\r\n        person_Def.setDefault_validation_class(\"UTF8Type\");\r\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"PERSON_NAME\".getBytes()), \"UTF8Type\");\r\n        person_Def.addToColumn_metadata(columnDef);\r\n\r\n        CfDef address_Def = new CfDef();\r\n        address_Def.name = \"ADDRESS\";\r\n        address_Def.keyspace = _KEYSPACE;\r\n        address_Def.setKey_validation_class(\"UTF8Type\");\r\n        address_Def.setComparator_type(\"UTF8Type\");\r\n        ColumnDef street = new ColumnDef(ByteBuffer.wrap(\"STREET\".getBytes()), \"UTF8Type\");\r\n        street.index_type = IndexType.KEYS;\r\n        address_Def.addToColumn_metadata(street);\r\n\r\n        ColumnDef personId = new ColumnDef(ByteBuffer.wrap(\"PERSON_ID\".getBytes()), \"UTF8Type\");\r\n        personId.index_type = IndexType.KEYS;\r\n        address_Def.addToColumn_metadata(personId);\r\n\r\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\r\n        cfDefs.add(user_Def);\r\n        cfDefs.add(person_Def);\r\n        cfDefs.add(address_Def);\r\n\r\n        try\r\n        {\r\n            ksDef = CassandraCli.client.describe_keyspace(_KEYSPACE);\r\n            CassandraCli.client.set_keyspace(_KEYSPACE);\r\n\r\n            List<CfDef> cfDefn = ksDef.getCf_defs();\r\n\r\n            for (CfDef cfDef1 : cfDefn)\r\n            {\r\n                if (cfDef1.getName().equalsIgnoreCase(\"BOOK\"))\r\n                {\r\n                    CassandraCli.client.system_drop_column_family(\"BOOK\");\r\n                }\r\n                if (cfDef1.getName().equalsIgnoreCase(\"PERSONNEL\"))\r\n                {\r\n\r\n                    CassandraCli.client.system_drop_column_family(\"PERSONNEL\");\r\n\r\n                }\r\n                if (cfDef1.getName().equalsIgnoreCase(\"ADDRESS\"))\r\n                {\r\n\r\n                    CassandraCli.client.system_drop_column_family(\"ADDRESS\");\r\n\r\n                }\r\n            }\r\n            CassandraCli.client.system_add_column_family(user_Def);\r\n            CassandraCli.client.system_add_column_family(person_Def);\r\n            CassandraCli.client.system_add_column_family(address_Def);\r\n\r\n        }\r\n        catch (NotFoundException e)\r\n        {\r\n\r\n            ksDef = new KsDef(_KEYSPACE, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\r\n            Map<String, String> strategy_options = new HashMap<String, String>();\r\n            strategy_options.put(\"replication_factor\", \"1\");\r\n            ksDef.setStrategy_options(strategy_options);\r\n            CassandraCli.client.system_add_keyspace(ksDef);\r\n        }\r\n\r\n        CassandraCli.client.set_keyspace(_KEYSPACE);\r\n    }\r\n\r\n    private void truncateColumnFamily()\r\n    {\r\n        String[] columnFamily = new String[] { \"BOOK\", \"PERSONNEL\", \"ADDRESS\" };\r\n        CassandraCli.truncateColumnFamily(_KEYSPACE, columnFamily);\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/resources/DataTypeTest.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.resources;\r\n\r\nimport java.math.BigDecimal;\r\nimport java.math.BigInteger;\r\nimport java.nio.ByteBuffer;\r\nimport java.util.ArrayList;\r\nimport java.util.Calendar;\r\nimport java.util.Date;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\n\r\nimport javax.ws.rs.core.MediaType;\r\n\r\nimport junit.framework.Assert;\r\n\r\nimport org.apache.cassandra.thrift.CfDef;\r\nimport org.apache.cassandra.thrift.ColumnDef;\r\nimport org.apache.cassandra.thrift.IndexType;\r\nimport org.apache.cassandra.thrift.InvalidRequestException;\r\nimport org.apache.cassandra.thrift.KsDef;\r\nimport org.apache.cassandra.thrift.NotFoundException;\r\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\r\nimport org.apache.cassandra.thrift.TimedOutException;\r\nimport org.apache.cassandra.thrift.UnavailableException;\r\nimport org.apache.commons.lang.StringUtils;\r\nimport org.apache.thrift.TException;\r\nimport org.junit.After;\r\nimport org.junit.AfterClass;\r\nimport org.junit.Before;\r\nimport org.junit.BeforeClass;\r\nimport org.junit.Test;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\r\nimport com.impetus.kundera.rest.common.Constants;\r\nimport com.impetus.kundera.rest.common.JAXBUtils;\r\nimport com.impetus.kundera.rest.common.Professional;\r\nimport com.impetus.kundera.rest.dao.RESTClient;\r\nimport com.impetus.kundera.rest.dao.RESTClientImpl;\r\nimport com.sun.jersey.api.client.WebResource;\r\nimport com.sun.jersey.test.framework.JerseyTest;\r\n\r\n/**\r\n * Test for all data types using {@link Professional} entity Cassandra-CLI\r\n * Commands to run for non-embedded mode: create keyspace KunderaExamples; use\r\n * KunderaExamples; drop column family PROFESSIONAL; create column family\r\n * PROFESSIONAL with comparator=UTF8Type and key_validation_class=UTF8Type and\r\n * column_metadata=[ {column_name: DEPARTMENT_ID, validation_class:LongType,\r\n * index_type: KEYS}, {column_name: IS_EXCEPTIONAL,\r\n * validation_class:BooleanType, index_type: KEYS}, {column_name: AGE,\r\n * validation_class:IntegerType, index_type: KEYS}, {column_name: GRADE,\r\n * validation_class:UTF8Type, index_type: KEYS}, {column_name:\r\n * DIGITAL_SIGNATURE, validation_class:BytesType, index_type: KEYS},\r\n * {column_name: RATING, validation_class:IntegerType, index_type: KEYS},\r\n * {column_name: COMPLIANCE, validation_class:FloatType, index_type: KEYS},\r\n * {column_name: HEIGHT, validation_class:DoubleType, index_type: KEYS},\r\n * {column_name: ENROLMENT_DATE, validation_class:DateType, index_type: KEYS},\r\n * {column_name: ENROLMENT_TIME, validation_class:DateType, index_type: KEYS},\r\n * {column_name: JOINING_DATE_TIME, validation_class:DateType, index_type:\r\n * KEYS}, {column_name: YEARS_SPENT, validation_class:IntegerType, index_type:\r\n * KEYS}, {column_name: UNIQUE_ID, validation_class:LongType, index_type: KEYS},\r\n * {column_name: MONTHLY_SALARY, validation_class:DoubleType, index_type: KEYS},\r\n * {column_name: JOB_ATTEMPTS, validation_class:IntegerType, index_type: KEYS},\r\n * {column_name: ACCUMULATED_WEALTH, validation_class:DecimalType, index_type:\r\n * KEYS}, {column_name: GRADUATION_DAY, validation_class:DateType, index_type:\r\n * KEYS} ]; describe KunderaExamples;\r\n * \r\n * @author amresh.singh\r\n */\r\npublic class DataTypeTest extends JerseyTest\r\n{\r\n    private static final String _KEYSPACE = \"KunderaExamples\";\r\n\r\n    private static final String COLUMN_FAMILY_PROFESSIONAL = \"PROFESSIONAL\";\r\n\r\n    private static final String PROFESSIONAL_CLASS_NAME = \"Professional\";\r\n\r\n    private static Logger log = LoggerFactory.getLogger(DataTypeTest.class);\r\n\r\n    static String mediaType = MediaType.APPLICATION_XML;\r\n\r\n    static RESTClient restClient;\r\n\r\n    String applicationToken = null;\r\n\r\n    String sessionToken = null;\r\n\r\n    String professionalStr1;\r\n\r\n    String professionalStr2;\r\n    \r\n    String userString;\r\n\r\n    String pk1;\r\n\r\n    String pk2;\r\n    \r\n    String userId1;\r\n    \r\n    String userId2;\r\n\r\n    Professional prof1;\r\n\r\n    Professional prof2;\r\n\r\n    private final static boolean USE_EMBEDDED_SERVER = true;\r\n\r\n    private final static boolean AUTO_MANAGE_SCHEMA = true;\r\n\r\n    public DataTypeTest() throws Exception\r\n    {\r\n        super(Constants.KUNDERA_REST_RESOURCES_PACKAGE);\r\n    }\r\n\r\n    @BeforeClass\r\n    public static void setUpBeforeClass() throws Exception\r\n    {\r\n        if (USE_EMBEDDED_SERVER)\r\n        {\r\n            CassandraCli.cassandraSetUp();\r\n        }\r\n\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            CassandraCli.dropKeySpace(_KEYSPACE.toLowerCase());\r\n            loadData();\r\n        }\r\n    }\r\n\r\n    @Before\r\n    public void setup() throws Exception\r\n    {\r\n\r\n    }\r\n\r\n    @After\r\n    public void tearDown() throws Exception\r\n    {\r\n        super.tearDown();\r\n    }\r\n\r\n    @AfterClass\r\n    public static void tearDownAfterClass() throws Exception\r\n    {\r\n\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            CassandraCli.dropKeySpace(_KEYSPACE);\r\n        }\r\n    }\r\n\r\n    @Test\r\n    public void testCRUD()\r\n    {\r\n        WebResource webResource = resource();\r\n        restClient = new RESTClientImpl();\r\n        restClient.initialize(webResource, mediaType);\r\n\r\n\r\n        buildProfessional1Str();\r\n        buildProfessional2Str();\r\n\r\n\r\n\r\n        // Get Application Token\r\n        applicationToken = restClient.getApplicationToken(\"cassTest\", null);\r\n        Assert.assertNotNull(applicationToken);\r\n        Assert.assertTrue(applicationToken.startsWith(\"\\\"AT_\"));\r\n        applicationToken = applicationToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n\r\n        // Get Session Token\r\n        sessionToken = restClient.getSessionToken(applicationToken);\r\n        Assert.assertNotNull(sessionToken);\r\n        Assert.assertTrue(sessionToken.startsWith(\"\\\"ST_\"));\r\n        \r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n\r\n        // Insert Record\r\n        String insertResponse1 = restClient.insertEntity(sessionToken, professionalStr1, PROFESSIONAL_CLASS_NAME);\r\n        String insertResponse2 = restClient.insertEntity(sessionToken, professionalStr2, PROFESSIONAL_CLASS_NAME);\r\n\r\n        Assert.assertNotNull(insertResponse1);\r\n        Assert.assertNotNull(insertResponse2);\r\n        Assert.assertTrue(insertResponse1.indexOf(\"200\") > 0);\r\n        Assert.assertTrue(insertResponse2.indexOf(\"200\") > 0);\r\n\r\n        // Find Record\r\n        String foundProfessional = restClient.findEntity(sessionToken, pk1, PROFESSIONAL_CLASS_NAME);\r\n        Assert.assertNotNull(foundProfessional);\r\n        Assert.assertTrue(foundProfessional.indexOf(pk1) > 0);\r\n\r\n        // Update Record\r\n        foundProfessional = foundProfessional.replaceAll(\"163.12\", \"165.21\");\r\n        \r\n        String updatedProfessional = restClient.updateEntity(sessionToken, foundProfessional, PROFESSIONAL_CLASS_NAME);\r\n        Assert.assertNotNull(updatedProfessional);\r\n        Assert.assertTrue(updatedProfessional.indexOf(\"165.21\") > 0);\r\n\r\n        /** JPA Query - Select */\r\n        // Get All Professionals\r\n        String jpaQuery = \"select p from \" + PROFESSIONAL_CLASS_NAME + \" p\";\r\n        String queryResult = restClient.runJPAQuery(sessionToken, jpaQuery, new HashMap<String, Object>());\r\n        log.debug(\"Query Result:\" + queryResult);\r\n        assertAllProfessionalsString(queryResult);\r\n\r\n        /** JPA Query - Select All */\r\n        // Get All Professionals\r\n        String allProfessionals = restClient.getAllEntities(sessionToken, PROFESSIONAL_CLASS_NAME);\r\n        log.debug(allProfessionals);\r\n        assertAllProfessionalsString(allProfessionals);\r\n\r\n        /** Named JPA Query - Select */\r\n        // Get Professionals for a specific department\r\n        Map<String, Object> params = new HashMap<String, Object>();\r\n        params.put(\"departmentId\", 23456789);\r\n        String profByDepartment = restClient.runNamedJPAQuery(sessionToken, PROFESSIONAL_CLASS_NAME,\r\n                \"findByDepartment\", params);\r\n        Assert.assertTrue(profByDepartment.indexOf(pk1) > 0);\r\n        log.debug(profByDepartment);\r\n\r\n        // Get Professionals for a specific Enrolment date\r\n        Map<String, Object> params2 = new HashMap<String, Object>();\r\n        params2.put(\"1\", prof1.getEnrolmentDate().getTime());\r\n        String profByEnrolmentDate = restClient.runNamedJPAQuery(sessionToken, PROFESSIONAL_CLASS_NAME,\r\n                \"findByEnrolmentDate\", params2);\r\n        Assert.assertTrue(profByEnrolmentDate.indexOf(pk1) > 0);\r\n        log.debug(profByEnrolmentDate);\r\n  \r\n        // Delete Records\r\n        restClient.deleteEntity(sessionToken, updatedProfessional, pk1, PROFESSIONAL_CLASS_NAME);\r\n        restClient.deleteEntity(sessionToken, updatedProfessional, pk2, PROFESSIONAL_CLASS_NAME);\r\n\r\n        // Close Session\r\n        restClient.closeSession(sessionToken);\r\n\r\n        // Close Application\r\n        restClient.closeApplication(applicationToken);\r\n    }\r\n    \r\n   \r\n\r\n    private void assertAllProfessionalsString(String queryResult)\r\n    {\r\n        Assert.assertFalse(StringUtils.isEmpty(queryResult));\r\n        Assert.assertTrue(queryResult.indexOf(\"professional\") > 0);\r\n        Assert.assertTrue(queryResult.indexOf(pk1) > 0);\r\n        Assert.assertTrue(queryResult.indexOf(pk2) > 0);\r\n    }\r\n\r\n    private void buildProfessional1Str()\r\n    {\r\n        pk1 = \"1111111111111\";\r\n\r\n        Calendar cal = Calendar.getInstance();\r\n        cal.setTime(new Date(1351667547777l));\r\n        prof1 = new Professional(pk1, 23456789, true, 31, 'C', (byte) 8, (short) 5, (float) 10.0, 163.12, new Date(\r\n                Long.parseLong(\"1351667541111\")), new Date(Long.parseLong(\"1351667542222\")), new Date(\r\n                Long.parseLong(\"1351667543333\")), 2, new Long(3634521523423L), new Double(7.23452342343),\r\n        /*\r\n         * new java.sql.Date(new\r\n         * Date(Long.parseLong(\"1344079061111\")).getTime()), new\r\n         * java.sql.Time(new Date(Long.parseLong(\"1344079062222\")).getTime()),\r\n         * new java.sql.Timestamp(new\r\n         * Date(Long.parseLong(\"13440790653333\")).getTime()),\r\n         */\r\n        new BigInteger(\"123456789\"), new BigDecimal(123456789), cal);\r\n\r\n        professionalStr1 = JAXBUtils.toString(prof1, mediaType);\r\n       \r\n\r\n    }\r\n\r\n    private void buildProfessional2Str()\r\n    {\r\n        pk2 = \"2222222222222\";\r\n\r\n        Calendar cal = Calendar.getInstance();\r\n        cal.setTime(new Date(1351667557777l));\r\n        prof2 = new Professional(pk2, 23456790, true, 33, 'A', (byte) 9, (short) 3, (float) 9.0, 167.75, new Date(\r\n                Long.parseLong(\"1351667551111\")), new Date(Long.parseLong(\"1351667552222\")), new Date(\r\n                Long.parseLong(\"1351667553333\")), 2, new Long(3634521523423L), new Double(7.23452342343),\r\n        /*\r\n         * new java.sql.Date(new\r\n         * Date(Long.parseLong(\"1344079061111\")).getTime()), new\r\n         * java.sql.Time(new Date(Long.parseLong(\"1344079062222\")).getTime()),\r\n         * new java.sql.Timestamp(new\r\n         * Date(Long.parseLong(\"13440790653333\")).getTime()),\r\n         */\r\n        new BigInteger(\"123456790\"), new BigDecimal(123456790), cal);\r\n\r\n        professionalStr2 = JAXBUtils.toString(prof2, mediaType);\r\n\r\n    }\r\n\r\n    private static void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\r\n            SchemaDisagreementException\r\n    {\r\n        KsDef ksDef = null;\r\n        CfDef professionalCfDef = new CfDef();\r\n        professionalCfDef.name = COLUMN_FAMILY_PROFESSIONAL;\r\n        professionalCfDef.keyspace = _KEYSPACE;\r\n        professionalCfDef.setComparator_type(\"UTF8Type\");\r\n        professionalCfDef.setKey_validation_class(\"UTF8Type\");\r\n\r\n        ColumnDef departmentDef = new ColumnDef(ByteBuffer.wrap(\"DEPARTMENT_ID\".getBytes()), \"LongType\");\r\n        departmentDef.index_type = IndexType.KEYS;\r\n        ColumnDef exceptionalDef = new ColumnDef(ByteBuffer.wrap(\"IS_EXCEPTIONAL\".getBytes()), \"BooleanType\");\r\n        exceptionalDef.index_type = IndexType.KEYS;\r\n        ColumnDef enrolmentDateDef = new ColumnDef(ByteBuffer.wrap(\"ENROLMENT_DATE\".getBytes()), \"DateType\");\r\n        enrolmentDateDef.index_type = IndexType.KEYS;\r\n\r\n        professionalCfDef.addToColumn_metadata(departmentDef);\r\n        professionalCfDef.addToColumn_metadata(exceptionalDef);\r\n        professionalCfDef.addToColumn_metadata(enrolmentDateDef);\r\n\r\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\r\n        cfDefs.add(professionalCfDef);\r\n\r\n        try\r\n        {\r\n            ksDef = CassandraCli.client.describe_keyspace(_KEYSPACE);\r\n            CassandraCli.client.set_keyspace(_KEYSPACE);\r\n\r\n            List<CfDef> cfDefn = ksDef.getCf_defs();\r\n\r\n            for (CfDef cfDef1 : cfDefn)\r\n            {\r\n                if (cfDef1.getName().equalsIgnoreCase(COLUMN_FAMILY_PROFESSIONAL))\r\n                {\r\n                    CassandraCli.client.system_drop_column_family(COLUMN_FAMILY_PROFESSIONAL);\r\n                }\r\n            }\r\n            CassandraCli.client.system_add_column_family(professionalCfDef);\r\n        }\r\n        catch (NotFoundException e)\r\n        {\r\n\r\n            ksDef = new KsDef(_KEYSPACE, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\r\n            Map<String, String> strategy_options = new HashMap<String, String>();\r\n            strategy_options.put(\"replication_factor\", \"1\");\r\n            ksDef.setStrategy_options(strategy_options);\r\n            CassandraCli.client.system_add_keyspace(ksDef);\r\n        }\r\n\r\n        CassandraCli.client.set_keyspace(_KEYSPACE);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/resources/MongoQueryTest.java",
    "content": "/**\r\n * Copyright 2014 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.resources;\r\n\r\nimport java.io.IOException;\r\nimport java.io.UnsupportedEncodingException;\r\nimport java.util.Date;\r\nimport java.util.HashMap;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.UUID;\r\n\r\nimport javax.ws.rs.core.MediaType;\r\n\r\nimport junit.framework.Assert;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\nimport org.codehaus.jackson.JsonParseException;\r\nimport org.codehaus.jackson.map.JsonMappingException;\r\nimport org.codehaus.jackson.map.ObjectMapper;\r\nimport org.junit.After;\r\nimport org.junit.AfterClass;\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\r\nimport com.impetus.kundera.rest.common.Constants;\r\nimport com.impetus.kundera.rest.common.JAXBUtils;\r\nimport com.impetus.kundera.rest.common.MongoCompoundKey;\r\nimport com.impetus.kundera.rest.common.MongoPrimeUser;\r\nimport com.impetus.kundera.rest.common.Professional;\r\nimport com.impetus.kundera.rest.dao.RESTClient;\r\nimport com.impetus.kundera.rest.dao.RESTClientImpl;\r\nimport com.sun.jersey.api.client.WebResource;\r\nimport com.sun.jersey.test.framework.JerseyTest;\r\n\r\n/**\r\n * Test for all data types using {@link Professional} entity Cassandra-CLI Commands to run for non-embedded mode: create\r\n * keyspace KunderaExamples; use KunderaExamples; drop column family PROFESSIONAL; create column family PROFESSIONAL\r\n * with comparator=UTF8Type and key_validation_class=UTF8Type and column_metadata=[ {column_name: DEPARTMENT_ID,\r\n * validation_class:LongType, index_type: KEYS}, {column_name: IS_EXCEPTIONAL, validation_class:BooleanType, index_type:\r\n * KEYS}, {column_name: AGE, validation_class:IntegerType, index_type: KEYS}, {column_name: GRADE,\r\n * validation_class:UTF8Type, index_type: KEYS}, {column_name: DIGITAL_SIGNATURE, validation_class:BytesType,\r\n * index_type: KEYS}, {column_name: RATING, validation_class:IntegerType, index_type: KEYS}, {column_name: COMPLIANCE,\r\n * validation_class:FloatType, index_type: KEYS}, {column_name: HEIGHT, validation_class:DoubleType, index_type: KEYS},\r\n * {column_name: ENROLMENT_DATE, validation_class:DateType, index_type: KEYS}, {column_name: ENROLMENT_TIME,\r\n * validation_class:DateType, index_type: KEYS}, {column_name: JOINING_DATE_TIME, validation_class:DateType, index_type:\r\n * KEYS}, {column_name: YEARS_SPENT, validation_class:IntegerType, index_type: KEYS}, {column_name: UNIQUE_ID,\r\n * validation_class:LongType, index_type: KEYS}, {column_name: MONTHLY_SALARY, validation_class:DoubleType, index_type:\r\n * KEYS}, {column_name: JOB_ATTEMPTS, validation_class:IntegerType, index_type: KEYS}, {column_name: ACCUMULATED_WEALTH,\r\n * validation_class:DecimalType, index_type: KEYS}, {column_name: GRADUATION_DAY, validation_class:DateType, index_type:\r\n * KEYS} ]; describe KunderaExamples;\r\n * \r\n * @author chhavi.gangwal\r\n */\r\npublic class MongoQueryTest extends JerseyTest {\r\n    private static final String _KEYSPACE = \"KunderaExamples\";\r\n\r\n    private static final String _PU = \"mongoPu\";\r\n\r\n    private static Logger log = LoggerFactory.getLogger(MongoQueryTest.class);\r\n\r\n    static String mediaType = MediaType.APPLICATION_JSON;\r\n\r\n    static RESTClient restClient;\r\n\r\n    String applicationToken = null;\r\n\r\n    String sessionToken = null;\r\n\r\n    String userString;\r\n\r\n    String pk1;\r\n\r\n    String pk2;\r\n\r\n    String userId1;\r\n\r\n    String userId2;\r\n\r\n    private final static boolean AUTO_MANAGE_SCHEMA = true;\r\n\r\n    public MongoQueryTest() throws Exception {\r\n        super(Constants.KUNDERA_REST_RESOURCES_PACKAGE);\r\n    }\r\n\r\n    @Before\r\n    public void setup() throws Exception {\r\n\r\n    }\r\n\r\n    @After\r\n    public void tearDown() throws Exception {\r\n        super.tearDown();\r\n    }\r\n\r\n    @AfterClass\r\n    public static void tearDownAfterClass() throws Exception {\r\n\r\n        if (AUTO_MANAGE_SCHEMA) {\r\n            CassandraCli.dropKeySpace(_KEYSPACE);\r\n        }\r\n    }\r\n\r\n    @Test\r\n    public void testCompositeUserCRUD() throws JsonParseException, JsonMappingException, IOException {\r\n        WebResource webResource = resource();\r\n        restClient = new RESTClientImpl();\r\n        restClient.initialize(webResource, mediaType);\r\n\r\n        // Get Application Token\r\n        applicationToken = restClient.getApplicationToken(_PU, null);\r\n        Assert.assertNotNull(applicationToken);\r\n        applicationToken = applicationToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        Assert.assertTrue(applicationToken.startsWith(\"AT_\"));\r\n\r\n        // Get Session Token\r\n        sessionToken = restClient.getSessionToken(applicationToken);\r\n        Assert.assertNotNull(sessionToken);\r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        Assert.assertTrue(sessionToken.startsWith(\"ST_\"));\r\n\r\n        UUID timeLineId = UUID.randomUUID();\r\n        Date currentDate = new Date();\r\n        MongoCompoundKey key = new MongoCompoundKey(\"mevivs\", 1, timeLineId);\r\n\r\n        MongoPrimeUser timeLine = new MongoPrimeUser(key);\r\n        timeLine.setKey(key);\r\n        timeLine.setTweetBody(\"my first tweet\");\r\n        timeLine.setTweetDate(currentDate);\r\n\r\n        MongoCompoundKey key1 = new MongoCompoundKey(\"john\", 2, timeLineId);\r\n\r\n        MongoPrimeUser timeLine2 = new MongoPrimeUser(key1);\r\n        timeLine2.setKey(key1);\r\n        timeLine2.setTweetBody(\"my second tweet\");\r\n        timeLine2.setTweetDate(currentDate);\r\n\r\n        String mongoUser = JAXBUtils.toString(timeLine, MediaType.APPLICATION_JSON);\r\n        Assert.assertNotNull(mongoUser);\r\n\r\n        String mongoUser1 = JAXBUtils.toString(timeLine2, MediaType.APPLICATION_JSON);\r\n        Assert.assertNotNull(mongoUser1);\r\n\r\n        // Insert Record\r\n        String insertResponse1 = restClient.insertEntity(sessionToken, mongoUser, \"MongoPrimeUser\");\r\n        String insertResponse2 = restClient.insertEntity(sessionToken, mongoUser1, \"MongoPrimeUser\");\r\n\r\n        Assert.assertNotNull(insertResponse1);\r\n        Assert.assertNotNull(insertResponse2);\r\n\r\n        Assert.assertTrue(insertResponse1.indexOf(\"200\") > 0);\r\n        Assert.assertTrue(insertResponse2.indexOf(\"200\") > 0);\r\n        String encodepk1 = null;\r\n        pk1 = JAXBUtils.toString(key, MediaType.APPLICATION_JSON);\r\n        pk2 = JAXBUtils.toString(key1, MediaType.APPLICATION_JSON);\r\n        try {\r\n            encodepk1 = java.net.URLEncoder.encode(pk1, \"UTF-8\");\r\n        } catch (UnsupportedEncodingException e) {\r\n            log.error(e.getMessage());\r\n        }\r\n        // Find Record\r\n        String foundUser = restClient.findEntity(sessionToken, encodepk1, \"MongoPrimeUser\");\r\n        Assert.assertNotNull(foundUser);\r\n\r\n        Assert.assertNotNull(foundUser);\r\n        Assert.assertTrue(foundUser.indexOf(\"mevivs\") > 0);\r\n\r\n        foundUser = foundUser.substring(1, foundUser.length() - 1);\r\n        Map<String, Object> userDetails = new HashMap<String, Object>();\r\n        ObjectMapper mapper = new ObjectMapper();\r\n        userDetails = mapper.readValue(foundUser, userDetails.getClass());\r\n        foundUser = mapper.writeValueAsString(userDetails.get(\"mongoprimeuser\"));\r\n\r\n        // Update Record\r\n        foundUser = foundUser.replaceAll(\"first\", \"hundreth\");\r\n\r\n        String updatedUser = restClient.updateEntity(sessionToken, foundUser, MongoPrimeUser.class.getSimpleName());\r\n\r\n        Assert.assertNotNull(updatedUser);\r\n        Assert.assertTrue(updatedUser.indexOf(\"hundreth\") > 0);\r\n\r\n        /** JPA Query - Select */\r\n        // Get All users\r\n        String jpaQuery = \"select p from \" + MongoPrimeUser.class.getSimpleName() + \" p\";\r\n        String queryResult = restClient.runJPAQuery(sessionToken, jpaQuery, new HashMap<String, Object>());\r\n        log.debug(\"Query Result:\" + queryResult);\r\n\r\n        Assert.assertNotNull(queryResult);\r\n        Assert.assertFalse(StringUtils.isEmpty(queryResult));\r\n\r\n        Assert.assertTrue(queryResult.indexOf(\"mongoprimeuser\") > 0);\r\n        Assert.assertTrue(queryResult.indexOf(pk1) > 0);\r\n        Assert.assertTrue(queryResult.indexOf(pk2) > 0);\r\n\r\n        Assert.assertTrue(queryResult.indexOf(\"Motif\") < 0);\r\n\r\n        jpaQuery = \"select p from \" + MongoPrimeUser.class.getSimpleName() + \" p WHERE p.key = :key\";\r\n        Map<String, Object> params = new HashMap<String, Object>();\r\n\r\n        params.put(\"key\", pk1);\r\n\r\n        queryResult = restClient.runObjectJPAQuery(sessionToken, jpaQuery, params);\r\n        log.debug(\"Query Result:\" + queryResult);\r\n\r\n        Assert.assertNotNull(queryResult);\r\n        Assert.assertFalse(StringUtils.isEmpty(queryResult));\r\n        Assert.assertTrue(queryResult.indexOf(\"mongoprimeuser\") > 0);\r\n        Assert.assertTrue(queryResult.indexOf(timeLineId.toString()) > 0);\r\n        Assert.assertTrue(queryResult.indexOf(pk2) < 0);\r\n\r\n        Assert.assertTrue(queryResult.indexOf(\"Motif\") < 0);\r\n\r\n        jpaQuery = \"select p from \" + MongoPrimeUser.class.getSimpleName() + \" p\";\r\n        params = new HashMap<String, Object>();\r\n        params.put(\"firstResult\", 0);\r\n        params.put(\"maxResult\", 1);\r\n\r\n        queryResult = restClient.runObjectJPAQuery(sessionToken, jpaQuery, params);\r\n\r\n        log.debug(\"Query Result:\" + queryResult);\r\n\r\n        String userList = queryResult.substring(1, queryResult.length() - 1);\r\n\r\n        mapper = new ObjectMapper();\r\n        userDetails = new HashMap<String, Object>();\r\n        userDetails = mapper.readValue(userList, userDetails.getClass());\r\n        userList = mapper.writeValueAsString(userDetails.get(\"mongoprimeuser\"));\r\n\r\n        List<MongoPrimeUser> navigation =\r\n            mapper.readValue(userList, mapper.getTypeFactory()\r\n                .constructCollectionType(List.class, MongoPrimeUser.class));\r\n\r\n        Assert.assertNotNull(queryResult);\r\n        Assert.assertFalse(StringUtils.isEmpty(queryResult));\r\n        Assert.assertTrue(queryResult.indexOf(\"mongoprimeuser\") > 0);\r\n        Assert.assertTrue(queryResult.indexOf(timeLineId.toString()) > 0);\r\n        Assert.assertEquals(1, navigation.size());\r\n\r\n        /** JPA Query - Select All */\r\n        // Get All Users\r\n        String allUsers = restClient.getAllEntities(sessionToken, MongoPrimeUser.class.getSimpleName());\r\n        log.debug(allUsers);\r\n        Assert.assertNotNull(allUsers);\r\n\r\n        // Close Session\r\n        restClient.closeSession(sessionToken);\r\n\r\n        // Close Application\r\n        restClient.closeApplication(applicationToken);\r\n    }\r\n\r\n    @Test\r\n    public void testMongoNativeQuery() throws JsonParseException, JsonMappingException, IOException {\r\n        WebResource webResource = resource();\r\n        restClient = new RESTClientImpl();\r\n        restClient.initialize(webResource, mediaType);\r\n\r\n        // Get Application Token\r\n        applicationToken = restClient.getApplicationToken(_PU, null);\r\n        Assert.assertNotNull(applicationToken);\r\n        applicationToken = applicationToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        Assert.assertTrue(applicationToken.startsWith(\"AT_\"));\r\n\r\n        // Get Session Token\r\n        sessionToken = restClient.getSessionToken(applicationToken);\r\n        Assert.assertNotNull(sessionToken);\r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        Assert.assertTrue(sessionToken.startsWith(\"ST_\"));\r\n\r\n        String dbResp = restClient.runNativeScript(sessionToken, \"db.adminCommand('listDatabases').databases\", _PU);\r\n        Assert.assertNotNull(dbResp);\r\n        Assert.assertTrue(dbResp.indexOf(\"local\") > 0);\r\n\r\n        // Close Session\r\n        restClient.closeSession(sessionToken);\r\n\r\n        // Close Application\r\n        restClient.closeApplication(applicationToken);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/test/java/com/impetus/kundera/rest/resources/PolyglotQueryTest.java",
    "content": "/**\r\n * Copyright 2014 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.rest.resources;\r\n\r\nimport java.io.IOException;\r\nimport java.math.BigDecimal;\r\nimport java.math.BigInteger;\r\nimport java.util.ArrayList;\r\nimport java.util.Calendar;\r\nimport java.util.Date;\r\nimport java.util.HashMap;\r\nimport java.util.HashSet;\r\nimport java.util.List;\r\nimport java.util.Map;\r\nimport java.util.Set;\r\n\r\nimport javax.ws.rs.core.MediaType;\r\n\r\nimport junit.framework.Assert;\r\n\r\nimport org.apache.commons.lang.StringUtils;\r\nimport org.codehaus.jackson.JsonParseException;\r\nimport org.codehaus.jackson.map.JsonMappingException;\r\nimport org.codehaus.jackson.map.ObjectMapper;\r\nimport org.junit.After;\r\nimport org.junit.AfterClass;\r\nimport org.junit.Before;\r\nimport org.junit.Test;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\r\nimport com.impetus.kundera.rest.common.Constants;\r\nimport com.impetus.kundera.rest.common.ExternalLink;\r\nimport com.impetus.kundera.rest.common.JAXBUtils;\r\nimport com.impetus.kundera.rest.common.PreferenceCassandra;\r\nimport com.impetus.kundera.rest.common.Professional;\r\nimport com.impetus.kundera.rest.common.ProfessionalDetailCassandra;\r\nimport com.impetus.kundera.rest.common.TweetCassandra;\r\nimport com.impetus.kundera.rest.common.UserCassandra;\r\nimport com.impetus.kundera.rest.dao.RESTClient;\r\nimport com.impetus.kundera.rest.dao.RESTClientImpl;\r\nimport com.sun.jersey.api.client.WebResource;\r\nimport com.sun.jersey.test.framework.JerseyTest;\r\n\r\n/**\r\n * Test for all data types using {@link Professional} entity Cassandra-CLI\r\n * Commands to run for non-embedded mode: create keyspace KunderaExamples; use\r\n * KunderaExamples; drop column family PROFESSIONAL; create column family\r\n * PROFESSIONAL with comparator=UTF8Type and key_validation_class=UTF8Type and\r\n * column_metadata=[ {column_name: DEPARTMENT_ID, validation_class:LongType,\r\n * index_type: KEYS}, {column_name: IS_EXCEPTIONAL,\r\n * validation_class:BooleanType, index_type: KEYS}, {column_name: AGE,\r\n * validation_class:IntegerType, index_type: KEYS}, {column_name: GRADE,\r\n * validation_class:UTF8Type, index_type: KEYS}, {column_name:\r\n * DIGITAL_SIGNATURE, validation_class:BytesType, index_type: KEYS},\r\n * {column_name: RATING, validation_class:IntegerType, index_type: KEYS},\r\n * {column_name: COMPLIANCE, validation_class:FloatType, index_type: KEYS},\r\n * {column_name: HEIGHT, validation_class:DoubleType, index_type: KEYS},\r\n * {column_name: ENROLMENT_DATE, validation_class:DateType, index_type: KEYS},\r\n * {column_name: ENROLMENT_TIME, validation_class:DateType, index_type: KEYS},\r\n * {column_name: JOINING_DATE_TIME, validation_class:DateType, index_type:\r\n * KEYS}, {column_name: YEARS_SPENT, validation_class:IntegerType, index_type:\r\n * KEYS}, {column_name: UNIQUE_ID, validation_class:LongType, index_type: KEYS},\r\n * {column_name: MONTHLY_SALARY, validation_class:DoubleType, index_type: KEYS},\r\n * {column_name: JOB_ATTEMPTS, validation_class:IntegerType, index_type: KEYS},\r\n * {column_name: ACCUMULATED_WEALTH, validation_class:DecimalType, index_type:\r\n * KEYS}, {column_name: GRADUATION_DAY, validation_class:DateType, index_type:\r\n * KEYS} ]; describe KunderaExamples;\r\n * \r\n * @author chhavi.gangwal\r\n */\r\npublic class PolyglotQueryTest extends JerseyTest\r\n{\r\n    private static final String _KEYSPACE = \"KunderaExamples\";\r\n    \r\n    private static final String _PU = \"twiCassandra,twiMongo\";\r\n\r\n    private static Logger log = LoggerFactory.getLogger(DataTypeTest.class);\r\n\r\n    static String mediaType = MediaType.APPLICATION_JSON;\r\n\r\n    static RESTClient restClient;\r\n\r\n    String applicationToken = null;\r\n\r\n    String sessionToken = null;\r\n\r\n    String userString;\r\n\r\n    String pk1;\r\n\r\n    String pk2;\r\n    \r\n    String userId1;\r\n    \r\n    String userId2;\r\n\r\n    \r\n\r\n    \r\n\r\n    private final static boolean AUTO_MANAGE_SCHEMA = true;\r\n\r\n    public PolyglotQueryTest() throws Exception\r\n    {\r\n        super(Constants.KUNDERA_REST_RESOURCES_PACKAGE);\r\n    }\r\n\r\n    \r\n\r\n    @Before\r\n    public void setup() throws Exception\r\n    {\r\n\r\n    }\r\n\r\n    @After\r\n    public void tearDown() throws Exception\r\n    {\r\n        super.tearDown();\r\n    }\r\n\r\n    @AfterClass\r\n    public static void tearDownAfterClass() throws Exception\r\n    {\r\n\r\n        if (AUTO_MANAGE_SCHEMA)\r\n        {\r\n            CassandraCli.dropKeySpace(_KEYSPACE);\r\n        }\r\n    }\r\n\r\n   \r\n    \r\n    @Test\r\n    public void testUserCRUD() throws JsonParseException, JsonMappingException, IOException\r\n    {\r\n        WebResource webResource = resource();\r\n        restClient = new RESTClientImpl();\r\n        restClient.initialize(webResource, mediaType);\r\n\r\n        buildUser1Str();\r\n        // Get Application Token\r\n        applicationToken = restClient.getApplicationToken(_PU, null);\r\n        Assert.assertNotNull(applicationToken);\r\n        applicationToken = applicationToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        Assert.assertTrue(applicationToken.startsWith(\"AT_\"));\r\n\r\n        // Get Session Token\r\n        sessionToken = restClient.getSessionToken(applicationToken);\r\n        Assert.assertNotNull(sessionToken);\r\n        sessionToken = sessionToken.replaceAll(\"^\\\"|\\\"$\", \"\");\r\n        Assert.assertTrue(sessionToken.startsWith(\"ST_\"));\r\n\r\n        // Insert Record\r\n        String insertResponse1 = restClient.insertEntity(sessionToken, userString, UserCassandra.class.getSimpleName());\r\n       \r\n\r\n        Assert.assertNotNull(insertResponse1);\r\n        Assert.assertTrue(insertResponse1.indexOf(\"200\") > 0);\r\n       \r\n\r\n        // Find Record\r\n        String foundUser = restClient.findEntity(sessionToken, \"0001\", UserCassandra.class.getSimpleName());\r\n        Assert.assertNotNull(foundUser);\r\n        Assert.assertTrue(foundUser.indexOf(\"0001\") > 0);\r\n        \r\n        foundUser = foundUser.substring(1,foundUser.length()-1);\r\n        Map<String, Object> userDetails = new HashMap<String, Object>();\r\n        ObjectMapper mapper = new ObjectMapper();\r\n        userDetails = mapper.readValue(foundUser, userDetails.getClass());\r\n        foundUser = mapper.writeValueAsString(userDetails.get(\"usercassandra\"));\r\n     \r\n        // Update Record\r\n        foundUser = foundUser.replaceAll(\"163.12\", \"165.21\");\r\n        \r\n        String updatedUser = restClient.updateEntity(sessionToken, foundUser, UserCassandra.class.getSimpleName());\r\n        \r\n        Assert.assertNotNull(updatedUser);\r\n        Assert.assertTrue(updatedUser.indexOf(\"165.21\") > 0);\r\n\r\n        /** JPA Query - Select */\r\n        // Get All Professionals\r\n        String jpaQuery = \"select p from \" + UserCassandra.class.getSimpleName() + \" p\";\r\n        String queryResult = restClient.runJPAQuery(sessionToken, jpaQuery, new HashMap<String, Object>());\r\n        log.debug(\"Query Result:\" + queryResult);\r\n        \r\n        Assert.assertNotNull(queryResult);\r\n        Assert.assertFalse(StringUtils.isEmpty(queryResult));\r\n        Assert.assertTrue(queryResult.indexOf(\"usercassandra\") > 0);\r\n        Assert.assertTrue(queryResult.indexOf(\"0001\") > 0);\r\n        Assert.assertTrue(queryResult.indexOf(\"0002\") > 0);\r\n        Assert.assertTrue(queryResult.indexOf(\"0003\") > 0);\r\n        \r\n        Assert.assertTrue(queryResult.indexOf(\"Motif\") < 0);\r\n       \r\n        jpaQuery = \"select p from \" + UserCassandra.class.getSimpleName() + \" p WHERE p.userId = :userId\";\r\n        Map<String, Object> params = new HashMap<String, Object>();\r\n        \r\n        params.put(\"userId\", \"0001\");\r\n        \r\n        \r\n        queryResult = restClient.runObjectJPAQuery(sessionToken, jpaQuery, params);\r\n        log.debug(\"Query Result:\" + queryResult);\r\n        \r\n        Assert.assertNotNull(queryResult);\r\n        Assert.assertFalse(StringUtils.isEmpty(queryResult));\r\n        Assert.assertTrue(queryResult.indexOf(\"usercassandra\") > 0);\r\n        Assert.assertTrue(queryResult.indexOf(\"0001\") > 0);\r\n\r\n        \r\n        Assert.assertTrue(queryResult.indexOf(\"Motif\") < 0);\r\n\r\n\r\n        /** JPA Query - Select All */\r\n        // Get All Professionals\r\n        String allUsers = restClient.getAllEntities(sessionToken, UserCassandra.class.getSimpleName());\r\n        log.debug(allUsers);\r\n        Assert.assertNotNull(allUsers);\r\n       \r\n\r\n        // Close Session\r\n        restClient.closeSession(sessionToken);\r\n\r\n        // Close Application\r\n        restClient.closeApplication(applicationToken);\r\n    }\r\n    \r\n    private void buildUser1Str()\r\n    {\r\n    \t \r\n    \tuserId1 = \"0001\";\r\n    \tuserId2 = \"0002\";\r\n    \t\r\n    \tList<UserCassandra> friendList = new ArrayList<UserCassandra>();\r\n    \t\r\n    \tList<UserCassandra> followers = new ArrayList<UserCassandra>();\r\n    \t\r\n    \t UserCassandra user1 = new UserCassandra(userId1, \"Amresh\", \"password1\", \"married\");\r\n    \t \r\n         UserCassandra user2 = new UserCassandra(userId2, \"Vivek\", \"password1\", \"married\");\r\n         \r\n         UserCassandra user3 = new UserCassandra(\"0003\", \"Kuldeep\", \"password1\", \"single\");\r\n\r\n         friendList.add(user2);\r\n         Calendar cal = Calendar.getInstance();\r\n         cal.setTime(new Date(1344079067777l));\r\n\r\n         \r\n         user1.setProfessionalDetail(new ProfessionalDetailCassandra(1234567, true, 31, 'C', (byte) 8, (short) 5, (float) 10.0, 163.12, new Date(\r\n                 Long.parseLong(\"1351667541111\")), new Date(Long.parseLong(\"1351667542222\")), new Date(\r\n                 Long.parseLong(\"1351667543333\")), 2, new Long(3634521523423L), new Double(7.23452342343),\r\n     \r\n         new BigInteger(\"123456789\"), new BigDecimal(123456789), cal));\r\n         \r\n         user2.setProfessionalDetail(new ProfessionalDetailCassandra(1234568, true, 21, 'C', (byte) 8, (short) 5, (float) 10.0, 163.12, new Date(\r\n                 Long.parseLong(\"1351667541111\")), new Date(Long.parseLong(\"1351667542222\")), new Date(\r\n                 Long.parseLong(\"1351667543333\")), 2, new Long(3634521523423L), new Double(7.23452342343),\r\n     \r\n         new BigInteger(\"123456789\"), new BigDecimal(123456789), cal));\r\n\r\n         user1.setPreference(new PreferenceCassandra(\"P1\", \"Motif\", \"2\"));\r\n         \r\n         followers.add(user3);\r\n         \r\n         friendList.add(user2);\r\n         \r\n         user1.setFriends(friendList);\r\n         \r\n         user1.setFollowers(followers);\r\n         \r\n         Set<ExternalLink> externalLinks = new HashSet<ExternalLink>();\r\n         List<TweetCassandra> tweetList = new ArrayList<TweetCassandra>();\r\n         \r\n         externalLinks.add(new ExternalLink(\"L1\", \"Facebook\", \"http://facebook.com/coolnerd\"));\r\n         externalLinks.add(new ExternalLink(\"L2\", \"LinkedIn\", \"http://linkedin.com/in/devilmate\"));\r\n         user1.setExternalLinks(externalLinks);\r\n         \r\n         \r\n         tweetList.add(new TweetCassandra(\"Here is my first tweet\", \"Web\"));\r\n         tweetList.add(new TweetCassandra(\"Second Tweet from me\", \"Mobile\"));\r\n         user1.setTweets(tweetList);\r\n         \r\n        \r\n         userString = JAXBUtils.toString(user1, mediaType);\r\n         \r\n         \r\n\r\n    }\r\n\r\n\r\n   \r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-rest/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"twiCassandra\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.rest.common.PreferenceCassandra</class>\r\n\t\t<class>com.impetus.kundera.rest.common.UserCassandra</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create-drop\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\t<persistence-unit name=\"twiMongo\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.rest.common.ExternalLink</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create-drop\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\r\n\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\t\t<persistence-unit name=\"cassTest\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n<!-- \t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" /> -->\r\n\t\t\t<!-- <property name=\"kundera.client.lookup.class\" -->\r\n\t\t\t<!-- value=\"com.impetus.client.cassandra.pelops.PelopsClientFactory\" /> -->\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\t<persistence-unit name=\"mongoPu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaExamples\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create-drop\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\r\n\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n</persistence>"
  },
  {
    "path": "src/kundera-rest/src/test/resources/WEB-INF/web.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n\tid=\"WebApp_ID\" version=\"2.5\">\n\t<display-name>kundera-web</display-name>\n\n\t<servlet>\n\t\t<description>JAX-RS Tools Generated - Do not modify</description>\n\t\t<servlet-name>JAX-RS Servlet</servlet-name>\n\t\t<!-- <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> -->\n\t\t<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>\n\t\t<init-param>\n\t\t\t<param-name>com.sun.jersey.config.property.packages</param-name>\n\t\t\t<param-value>com.impetus.kundera.rest.resources</param-value>\n\t\t</init-param>\n\t\t<init-param>\n\t\t\t<param-name>com.sun.jersey.config.feature.Redirect</param-name>\n\t\t\t<param-value>true</param-value>\n\t\t</init-param>\n\t\t<load-on-startup>1</load-on-startup>\n\t</servlet>\n\t<servlet-mapping>\n\t\t<servlet-name>JAX-RS Servlet</servlet-name>\n\t\t<url-pattern>/rest/*</url-pattern>\n\t</servlet-mapping>\n\n\n\t<welcome-file-list>\n\t\t<welcome-file>index.html</welcome-file>\n\t\t<welcome-file>index.htm</welcome-file>\n\t\t<welcome-file>index.jsp</welcome-file>\n\t\t<welcome-file>default.html</welcome-file>\n\t\t<welcome-file>default.htm</welcome-file>\n\t\t<welcome-file>default.jsp</welcome-file>\n\t</welcome-file-list>\n</web-app>"
  },
  {
    "path": "src/kundera-rest/src/test/resources/cassandra.yaml",
    "content": "# Cassandra storage config YAML \n\n# NOTE:\n#   See http://wiki.apache.org/cassandra/StorageConfiguration for\n#   full explanations of configuration directives\n# /NOTE\n\n# The name of the cluster. This is mainly used to prevent machines in\n# one logical cluster from joining another.\ncluster_name: 'Test Cluster'\n\n# This defines the number of tokens randomly assigned to this node on the ring\n# The more tokens, relative to other nodes, the larger the proportion of data\n# that this node will store. You probably want all nodes to have the same number\n# of tokens assuming they have equal hardware capability.\n#\n# If you leave this unspecified, Cassandra will use the default of 1 token for legacy compatibility,\n# and will use the initial_token as described below.\n#\n# Specifying initial_token will override this setting on the node's initial start,\n# on subsequent starts, this setting will apply even if initial token is set.\n#\n# If you already have a cluster with 1 token per node, and wish to migrate to \n# multiple tokens per node, see http://wiki.apache.org/cassandra/Operations\nnum_tokens: 256\n\n# initial_token allows you to specify tokens manually.  While you can use # it with\n# vnodes (num_tokens > 1, above) -- in which case you should provide a \n# comma-separated list -- it's primarily used when adding nodes # to legacy clusters \n# that do not have vnodes enabled.\n# initial_token:\n\n# See http://wiki.apache.org/cassandra/HintedHandoff\n# May either be \"true\" or \"false\" to enable globally, or contain a list\n# of data centers to enable per-datacenter.\n# hinted_handoff_enabled: DC1,DC2\nhinted_handoff_enabled: true\n# this defines the maximum amount of time a dead host will have hints\n# generated.  After it has been dead this long, new hints for it will not be\n# created until it has been seen alive and gone down again.\nmax_hint_window_in_ms: 10800000 # 3 hours\n# Maximum throttle in KBs per second, per delivery thread.  This will be\n# reduced proportionally to the number of nodes in the cluster.  (If there\n# are two nodes in the cluster, each delivery thread will use the maximum\n# rate; if there are three, each will throttle to half of the maximum,\n# since we expect two nodes to be delivering hints simultaneously.)\nhinted_handoff_throttle_in_kb: 1024\n# Number of threads with which to deliver hints;\n# Consider increasing this number when you have multi-dc deployments, since\n# cross-dc handoff tends to be slower\nmax_hints_delivery_threads: 2\n\n# Maximum throttle in KBs per second, total. This will be\n# reduced proportionally to the number of nodes in the cluster.\nbatchlog_replay_throttle_in_kb: 1024\n\n# Authentication backend, implementing IAuthenticator; used to identify users\n# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthenticator,\n# PasswordAuthenticator}.\n#\n# - AllowAllAuthenticator performs no checks - set it to disable authentication.\n# - PasswordAuthenticator relies on username/password pairs to authenticate\n#   users. It keeps usernames and hashed passwords in system_auth.credentials table.\n#   Please increase system_auth keyspace replication factor if you use this authenticator.\nauthenticator: AllowAllAuthenticator\n\n# Authorization backend, implementing IAuthorizer; used to limit access/provide permissions\n# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthorizer,\n# CassandraAuthorizer}.\n#\n# - AllowAllAuthorizer allows any action to any user - set it to disable authorization.\n# - CassandraAuthorizer stores permissions in system_auth.permissions table. Please\n#   increase system_auth keyspace replication factor if you use this authorizer.\nauthorizer: AllowAllAuthorizer\n\n# Validity period for permissions cache (fetching permissions can be an\n# expensive operation depending on the authorizer, CassandraAuthorizer is\n# one example). Defaults to 2000, set to 0 to disable.\n# Will be disabled automatically for AllowAllAuthorizer.\npermissions_validity_in_ms: 2000\n\n# The partitioner is responsible for distributing groups of rows (by\n# partition key) across nodes in the cluster.  You should leave this\n# alone for new clusters.  The partitioner can NOT be changed without\n# reloading all data, so when upgrading you should set this to the\n# same partitioner you were already using.\n#\n# Besides Murmur3Partitioner, partitioners included for backwards\n# compatibility include RandomPartitioner, ByteOrderedPartitioner, and\n# OrderPreservingPartitioner.\n#\npartitioner: org.apache.cassandra.dht.ByteOrderedPartitioner\n\n# Directories where Cassandra should store data on disk.  Cassandra\n# will spread data evenly across them, subject to the granularity of\n# the configured compaction strategy.\n# If not set, the default directory is $CASSANDRA_HOME/data/data.\n# data_file_directories:\n#     - /var/lib/cassandra/data\n\n# commit log.  when running on magnetic HDD, this should be a\n# separate spindle than the data directories.\n# If not set, the default directory is $CASSANDRA_HOME/data/commitlog.\n# commitlog_directory: /var/lib/cassandra/commitlog\n\n# policy for data disk failures:\n# die: shut down gossip and Thrift and kill the JVM for any fs errors or\n#      single-sstable errors, so the node can be replaced.\n# stop_paranoid: shut down gossip and Thrift even for single-sstable errors.\n# stop: shut down gossip and Thrift, leaving the node effectively dead, but\n#       can still be inspected via JMX.\n# best_effort: stop using the failed disk and respond to requests based on\n#              remaining available sstables.  This means you WILL see obsolete\n#              data at CL.ONE!\n# ignore: ignore fatal errors and let requests fail, as in pre-1.2 Cassandra\ndisk_failure_policy: stop\n\n# policy for commit disk failures:\n# die: shut down gossip and Thrift and kill the JVM, so the node can be replaced.\n# stop: shut down gossip and Thrift, leaving the node effectively dead, but\n#       can still be inspected via JMX.\n# stop_commit: shutdown the commit log, letting writes collect but\n#              continuing to service reads, as in pre-2.0.5 Cassandra\n# ignore: ignore fatal errors and let the batches fail\ncommit_failure_policy: stop\n\n# Maximum size of the key cache in memory.\n#\n# Each key cache hit saves 1 seek and each row cache hit saves 2 seeks at the\n# minimum, sometimes more. The key cache is fairly tiny for the amount of\n# time it saves, so it's worthwhile to use it at large numbers.\n# The row cache saves even more time, but must contain the entire row,\n# so it is extremely space-intensive. It's best to only use the\n# row cache if you have hot rows or static rows.\n#\n# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.\n#\n# Default value is empty to make it \"auto\" (min(5% of Heap (in MB), 100MB)). Set to 0 to disable key cache.\nkey_cache_size_in_mb:\n\n# Duration in seconds after which Cassandra should\n# save the key cache. Caches are saved to saved_caches_directory as\n# specified in this configuration file.\n#\n# Saved caches greatly improve cold-start speeds, and is relatively cheap in\n# terms of I/O for the key cache. Row cache saving is much more expensive and\n# has limited use.\n#\n# Default is 14400 or 4 hours.\nkey_cache_save_period: 14400\n\n# Number of keys from the key cache to save\n# Disabled by default, meaning all keys are going to be saved\n# key_cache_keys_to_save: 100\n\n# Maximum size of the row cache in memory.\n# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.\n#\n# Default value is 0, to disable row caching.\nrow_cache_size_in_mb: 0\n\n# Duration in seconds after which Cassandra should\n# save the row cache. Caches are saved to saved_caches_directory as specified\n# in this configuration file.\n#\n# Saved caches greatly improve cold-start speeds, and is relatively cheap in\n# terms of I/O for the key cache. Row cache saving is much more expensive and\n# has limited use.\n#\n# Default is 0 to disable saving the row cache.\nrow_cache_save_period: 0\n\n# Number of keys from the row cache to save\n# Disabled by default, meaning all keys are going to be saved\n# row_cache_keys_to_save: 100\n\n# Maximum size of the counter cache in memory.\n#\n# Counter cache helps to reduce counter locks' contention for hot counter cells.\n# In case of RF = 1 a counter cache hit will cause Cassandra to skip the read before\n# write entirely. With RF > 1 a counter cache hit will still help to reduce the duration\n# of the lock hold, helping with hot counter cell updates, but will not allow skipping\n# the read entirely. Only the local (clock, count) tuple of a counter cell is kept\n# in memory, not the whole counter, so it's relatively cheap.\n#\n# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.\n#\n# Default value is empty to make it \"auto\" (min(2.5% of Heap (in MB), 50MB)). Set to 0 to disable counter cache.\n# NOTE: if you perform counter deletes and rely on low gcgs, you should disable the counter cache.\ncounter_cache_size_in_mb:\n\n# Duration in seconds after which Cassandra should\n# save the counter cache (keys only). Caches are saved to saved_caches_directory as\n# specified in this configuration file.\n#\n# Default is 7200 or 2 hours.\ncounter_cache_save_period: 7200\n\n# Number of keys from the counter cache to save\n# Disabled by default, meaning all keys are going to be saved\n# counter_cache_keys_to_save: 100\n\n# The off-heap memory allocator.  Affects storage engine metadata as\n# well as caches.  Experiments show that JEMAlloc saves some memory\n# than the native GCC allocator (i.e., JEMalloc is more\n# fragmentation-resistant).\n# \n# Supported values are: NativeAllocator, JEMallocAllocator\n#\n# If you intend to use JEMallocAllocator you have to install JEMalloc as library and\n# modify cassandra-env.sh as directed in the file.\n#\n# Defaults to NativeAllocator\n# memory_allocator: NativeAllocator\n\n# saved caches\n# If not set, the default directory is $CASSANDRA_HOME/data/saved_caches.\n# saved_caches_directory: /var/lib/cassandra/saved_caches\n\n# commitlog_sync may be either \"periodic\" or \"batch.\" \n# When in batch mode, Cassandra won't ack writes until the commit log\n# has been fsynced to disk.  It will wait up to\n# commitlog_sync_batch_window_in_ms milliseconds for other writes, before\n# performing the sync.\n#\n# commitlog_sync: batch\n# commitlog_sync_batch_window_in_ms: 50\n#\n# the other option is \"periodic\" where writes may be acked immediately\n# and the CommitLog is simply synced every commitlog_sync_period_in_ms\n# milliseconds.  commitlog_periodic_queue_size allows 1024*(CPU cores) pending\n# entries on the commitlog queue by default.  If you are writing very large\n# blobs, you should reduce that; 16*cores works reasonably well for 1MB blobs.\n# It should be at least as large as the concurrent_writes setting.\ncommitlog_sync: periodic\ncommitlog_sync_period_in_ms: 10000\n# commitlog_periodic_queue_size:\n\n# The size of the individual commitlog file segments.  A commitlog\n# segment may be archived, deleted, or recycled once all the data\n# in it (potentially from each columnfamily in the system) has been\n# flushed to sstables.  \n#\n# The default size is 32, which is almost always fine, but if you are\n# archiving commitlog segments (see commitlog_archiving.properties),\n# then you probably want a finer granularity of archiving; 8 or 16 MB\n# is reasonable.\ncommitlog_segment_size_in_mb: 32\n\n# any class that implements the SeedProvider interface and has a\n# constructor that takes a Map<String, String> of parameters will do.\nseed_provider:\n    # Addresses of hosts that are deemed contact points. \n    # Cassandra nodes use this list of hosts to find each other and learn\n    # the topology of the ring.  You must change this if you are running\n    # multiple nodes!\n    - class_name: org.apache.cassandra.locator.SimpleSeedProvider\n      parameters:\n          # seeds is actually a comma-delimited list of addresses.\n          # Ex: \"<ip1>,<ip2>,<ip3>\"\n          - seeds: \"127.0.0.1\"\n\n# For workloads with more data than can fit in memory, Cassandra's\n# bottleneck will be reads that need to fetch data from\n# disk. \"concurrent_reads\" should be set to (16 * number_of_drives) in\n# order to allow the operations to enqueue low enough in the stack\n# that the OS and drives can reorder them. Same applies to\n# \"concurrent_counter_writes\", since counter writes read the current\n# values before incrementing and writing them back.\n#\n# On the other hand, since writes are almost never IO bound, the ideal\n# number of \"concurrent_writes\" is dependent on the number of cores in\n# your system; (8 * number_of_cores) is a good rule of thumb.\nconcurrent_reads: 32\nconcurrent_writes: 32\nconcurrent_counter_writes: 32\n\n# Total memory to use for sstable-reading buffers.  Defaults to\n# the smaller of 1/4 of heap or 512MB.\n# file_cache_size_in_mb: 512\n\n# Total permitted memory to use for memtables. Cassandra will stop \n# accepting writes when the limit is exceeded until a flush completes,\n# and will trigger a flush based on memtable_cleanup_threshold\n# If omitted, Cassandra will set both to 1/4 the size of the heap.\n# memtable_heap_space_in_mb: 2048\n# memtable_offheap_space_in_mb: 2048\n\n# Ratio of occupied non-flushing memtable size to total permitted size\n# that will trigger a flush of the largest memtable.  Lager mct will\n# mean larger flushes and hence less compaction, but also less concurrent\n# flush activity which can make it difficult to keep your disks fed\n# under heavy write load.\n#\n# memtable_cleanup_threshold defaults to 1 / (memtable_flush_writers + 1)\n# memtable_cleanup_threshold: 0.11\n\n# Specify the way Cassandra allocates and manages memtable memory.\n# Options are:\n#   heap_buffers:    on heap nio buffers\n#   offheap_buffers: off heap (direct) nio buffers\n#   offheap_objects: native memory, eliminating nio buffer heap overhead\nmemtable_allocation_type: heap_buffers\n\n# Total space to use for commitlogs.  Since commitlog segments are\n# mmapped, and hence use up address space, the default size is 32\n# on 32-bit JVMs, and 8192 on 64-bit JVMs.\n#\n# If space gets above this value (it will round up to the next nearest\n# segment multiple), Cassandra will flush every dirty CF in the oldest\n# segment and remove it.  So a small total commitlog space will tend\n# to cause more flush activity on less-active columnfamilies.\n# commitlog_total_space_in_mb: 8192\n\n# This sets the amount of memtable flush writer threads.  These will\n# be blocked by disk io, and each one will hold a memtable in memory\n# while blocked. \n#\n# memtable_flush_writers defaults to the smaller of (number of disks,\n# number of cores), with a minimum of 2 and a maximum of 8.\n# \n# If your data directories are backed by SSD, you should increase this\n# to the number of cores.\n#memtable_flush_writers: 8\n\n# A fixed memory pool size in MB for for SSTable index summaries. If left\n# empty, this will default to 5% of the heap size. If the memory usage of\n# all index summaries exceeds this limit, SSTables with low read rates will\n# shrink their index summaries in order to meet this limit.  However, this\n# is a best-effort process. In extreme conditions Cassandra may need to use\n# more than this amount of memory.\nindex_summary_capacity_in_mb:\n\n# How frequently index summaries should be resampled.  This is done\n# periodically to redistribute memory from the fixed-size pool to sstables\n# proportional their recent read rates.  Setting to -1 will disable this\n# process, leaving existing index summaries at their current sampling level.\nindex_summary_resize_interval_in_minutes: 60\n\n# Whether to, when doing sequential writing, fsync() at intervals in\n# order to force the operating system to flush the dirty\n# buffers. Enable this to avoid sudden dirty buffer flushing from\n# impacting read latencies. Almost always a good idea on SSDs; not\n# necessarily on platters.\ntrickle_fsync: false\ntrickle_fsync_interval_in_kb: 10240\n\n# TCP port, for commands and data\nstorage_port: 7000\n\n# SSL port, for encrypted communication.  Unused unless enabled in\n# encryption_options\nssl_storage_port: 7001\n\n# Address or interface to bind to and tell other Cassandra nodes to connect to.\n# You _must_ change this if you want multiple nodes to be able to communicate!\n#\n# Set listen_address OR listen_interface, not both. Interfaces must correspond\n# to a single address, IP aliasing is not supported.\n#\n# Leaving it blank leaves it up to InetAddress.getLocalHost(). This\n# will always do the Right Thing _if_ the node is properly configured\n# (hostname, name resolution, etc), and the Right Thing is to use the\n# address associated with the hostname (it might not be).\n#\n# Setting listen_address to 0.0.0.0 is always wrong.\nlisten_address: localhost\n# listen_interface: eth0\n\n# Address to broadcast to other Cassandra nodes\n# Leaving this blank will set it to the same value as listen_address\n# broadcast_address: 1.2.3.4\n\n# Internode authentication backend, implementing IInternodeAuthenticator;\n# used to allow/disallow connections from peer nodes.\n# internode_authenticator: org.apache.cassandra.auth.AllowAllInternodeAuthenticator\n\n# Whether to start the native transport server.\n# Please note that the address on which the native transport is bound is the\n# same as the rpc_address. The port however is different and specified below.\nstart_native_transport: true\n# port for the CQL native transport to listen for clients on\nnative_transport_port: 9042\n# The maximum threads for handling requests when the native transport is used.\n# This is similar to rpc_max_threads though the default differs slightly (and\n# there is no native_transport_min_threads, idle threads will always be stopped\n# after 30 seconds).\n# native_transport_max_threads: 128\n#\n# The maximum size of allowed frame. Frame (requests) larger than this will\n# be rejected as invalid. The default is 256MB.\n# native_transport_max_frame_size_in_mb: 256\n\n# Whether to start the thrift rpc server.\nstart_rpc: true\n\n# The address or interface to bind the Thrift RPC service and native transport\n# server to.\n#\n# Set rpc_address OR rpc_interface, not both. Interfaces must correspond\n# to a single address, IP aliasing is not supported.\n#\n# Leaving rpc_address blank has the same effect as on listen_address\n# (i.e. it will be based on the configured hostname of the node).\n#\n# Note that unlike listen_address, you can specify 0.0.0.0, but you must also\n# set broadcast_rpc_address to a value other than 0.0.0.0.\nrpc_address: localhost\n# rpc_interface: eth1\n\n# port for Thrift to listen for clients on\nrpc_port: 9160\n\n# RPC address to broadcast to drivers and other Cassandra nodes. This cannot\n# be set to 0.0.0.0. If left blank, this will be set to the value of\n# rpc_address. If rpc_address is set to 0.0.0.0, broadcast_rpc_address must\n# be set.\n# broadcast_rpc_address: 1.2.3.4\n\n# enable or disable keepalive on rpc/native connections\nrpc_keepalive: true\n\n# Cassandra provides two out-of-the-box options for the RPC Server:\n#\n# sync  -> One thread per thrift connection. For a very large number of clients, memory\n#          will be your limiting factor. On a 64 bit JVM, 180KB is the minimum stack size\n#          per thread, and that will correspond to your use of virtual memory (but physical memory\n#          may be limited depending on use of stack space).\n#\n# hsha  -> Stands for \"half synchronous, half asynchronous.\" All thrift clients are handled\n#          asynchronously using a small number of threads that does not vary with the amount\n#          of thrift clients (and thus scales well to many clients). The rpc requests are still\n#          synchronous (one thread per active request). If hsha is selected then it is essential\n#          that rpc_max_threads is changed from the default value of unlimited.\n#\n# The default is sync because on Windows hsha is about 30% slower.  On Linux,\n# sync/hsha performance is about the same, with hsha of course using less memory.\n#\n# Alternatively,  can provide your own RPC server by providing the fully-qualified class name\n# of an o.a.c.t.TServerFactory that can create an instance of it.\nrpc_server_type: sync\n\n# Uncomment rpc_min|max_thread to set request pool size limits.\n#\n# Regardless of your choice of RPC server (see above), the number of maximum requests in the\n# RPC thread pool dictates how many concurrent requests are possible (but if you are using the sync\n# RPC server, it also dictates the number of clients that can be connected at all).\n#\n# The default is unlimited and thus provides no protection against clients overwhelming the server. You are\n# encouraged to set a maximum that makes sense for you in production, but do keep in mind that\n# rpc_max_threads represents the maximum number of client requests this server may execute concurrently.\n#\n# rpc_min_threads: 16\n# rpc_max_threads: 2048\n\n# uncomment to set socket buffer sizes on rpc connections\n# rpc_send_buff_size_in_bytes:\n# rpc_recv_buff_size_in_bytes:\n\n# Uncomment to set socket buffer size for internode communication\n# Note that when setting this, the buffer size is limited by net.core.wmem_max\n# and when not setting it it is defined by net.ipv4.tcp_wmem\n# See:\n# /proc/sys/net/core/wmem_max\n# /proc/sys/net/core/rmem_max\n# /proc/sys/net/ipv4/tcp_wmem\n# /proc/sys/net/ipv4/tcp_wmem\n# and: man tcp\n# internode_send_buff_size_in_bytes:\n# internode_recv_buff_size_in_bytes:\n\n# Frame size for thrift (maximum message length).\nthrift_framed_transport_size_in_mb: 15\n\n# Set to true to have Cassandra create a hard link to each sstable\n# flushed or streamed locally in a backups/ subdirectory of the\n# keyspace data.  Removing these links is the operator's\n# responsibility.\nincremental_backups: false\n\n# Whether or not to take a snapshot before each compaction.  Be\n# careful using this option, since Cassandra won't clean up the\n# snapshots for you.  Mostly useful if you're paranoid when there\n# is a data format change.\nsnapshot_before_compaction: false\n\n# Whether or not a snapshot is taken of the data before keyspace truncation\n# or dropping of column families. The STRONGLY advised default of true \n# should be used to provide data safety. If you set this flag to false, you will\n# lose data on truncation or drop.\nauto_snapshot: true\n\n# When executing a scan, within or across a partition, we need to keep the\n# tombstones seen in memory so we can return them to the coordinator, which\n# will use them to make sure other replicas also know about the deleted rows.\n# With workloads that generate a lot of tombstones, this can cause performance\n# problems and even exaust the server heap.\n# (http://www.datastax.com/dev/blog/cassandra-anti-patterns-queues-and-queue-like-datasets)\n# Adjust the thresholds here if you understand the dangers and want to\n# scan more tombstones anyway.  These thresholds may also be adjusted at runtime\n# using the StorageService mbean.\ntombstone_warn_threshold: 1000\ntombstone_failure_threshold: 100000\n\n# Granularity of the collation index of rows within a partition.\n# Increase if your rows are large, or if you have a very large\n# number of rows per partition.  The competing goals are these:\n#   1) a smaller granularity means more index entries are generated\n#      and looking up rows withing the partition by collation column\n#      is faster\n#   2) but, Cassandra will keep the collation index in memory for hot\n#      rows (as part of the key cache), so a larger granularity means\n#      you can cache more hot rows\ncolumn_index_size_in_kb: 64\n\n\n# Log WARN on any batch size exceeding this value. 5kb per batch by default.\n# Caution should be taken on increasing the size of this threshold as it can lead to node instability.\nbatch_size_warn_threshold_in_kb: 5\n\n# Number of simultaneous compactions to allow, NOT including\n# validation \"compactions\" for anti-entropy repair.  Simultaneous\n# compactions can help preserve read performance in a mixed read/write\n# workload, by mitigating the tendency of small sstables to accumulate\n# during a single long running compactions. The default is usually\n# fine and if you experience problems with compaction running too\n# slowly or too fast, you should look at\n# compaction_throughput_mb_per_sec first.\n#\n# concurrent_compactors defaults to the smaller of (number of disks,\n# number of cores), with a minimum of 2 and a maximum of 8.\n# \n# If your data directories are backed by SSD, you should increase this\n# to the number of cores.\n#concurrent_compactors: 1\n\n# Throttles compaction to the given total throughput across the entire\n# system. The faster you insert data, the faster you need to compact in\n# order to keep the sstable count down, but in general, setting this to\n# 16 to 32 times the rate you are inserting data is more than sufficient.\n# Setting this to 0 disables throttling. Note that this account for all types\n# of compaction, including validation compaction.\ncompaction_throughput_mb_per_sec: 16\n\n# When compacting, the replacement sstable(s) can be opened before they\n# are completely written, and used in place of the prior sstables for\n# any range that has been written. This helps to smoothly transfer reads \n# between the sstables, reducing page cache churn and keeping hot rows hot\nsstable_preemptive_open_interval_in_mb: 50\n\n# Throttles all outbound streaming file transfers on this node to the\n# given total throughput in Mbps. This is necessary because Cassandra does\n# mostly sequential IO when streaming data during bootstrap or repair, which\n# can lead to saturating the network connection and degrading rpc performance.\n# When unset, the default is 200 Mbps or 25 MB/s.\n# stream_throughput_outbound_megabits_per_sec: 200\n\n# Throttles all streaming file transfer between the datacenters,\n# this setting allows users to throttle inter dc stream throughput in addition\n# to throttling all network stream traffic as configured with\n# stream_throughput_outbound_megabits_per_sec\n# inter_dc_stream_throughput_outbound_megabits_per_sec:\n\n# How long the coordinator should wait for read operations to complete\nread_request_timeout_in_ms: 5000\n# How long the coordinator should wait for seq or index scans to complete\nrange_request_timeout_in_ms: 10000\n# How long the coordinator should wait for writes to complete\nwrite_request_timeout_in_ms: 2000\n# How long the coordinator should wait for counter writes to complete\ncounter_write_request_timeout_in_ms: 5000\n# How long a coordinator should continue to retry a CAS operation\n# that contends with other proposals for the same row\ncas_contention_timeout_in_ms: 1000\n# How long the coordinator should wait for truncates to complete\n# (This can be much longer, because unless auto_snapshot is disabled\n# we need to flush first so we can snapshot before removing the data.)\ntruncate_request_timeout_in_ms: 60000\n# The default timeout for other, miscellaneous operations\nrequest_timeout_in_ms: 10000\n\n# Enable operation timeout information exchange between nodes to accurately\n# measure request timeouts.  If disabled, replicas will assume that requests\n# were forwarded to them instantly by the coordinator, which means that\n# under overload conditions we will waste that much extra time processing \n# already-timed-out requests.\n#\n# Warning: before enabling this property make sure to ntp is installed\n# and the times are synchronized between the nodes.\ncross_node_timeout: false\n\n# Enable socket timeout for streaming operation.\n# When a timeout occurs during streaming, streaming is retried from the start\n# of the current file. This _can_ involve re-streaming an important amount of\n# data, so you should avoid setting the value too low.\n# Default value is 0, which never timeout streams.\n# streaming_socket_timeout_in_ms: 0\n\n# phi value that must be reached for a host to be marked down.\n# most users should never need to adjust this.\n# phi_convict_threshold: 8\n\n# endpoint_snitch -- Set this to a class that implements\n# IEndpointSnitch.  The snitch has two functions:\n# - it teaches Cassandra enough about your network topology to route\n#   requests efficiently\n# - it allows Cassandra to spread replicas around your cluster to avoid\n#   correlated failures. It does this by grouping machines into\n#   \"datacenters\" and \"racks.\"  Cassandra will do its best not to have\n#   more than one replica on the same \"rack\" (which may not actually\n#   be a physical location)\n#\n# IF YOU CHANGE THE SNITCH AFTER DATA IS INSERTED INTO THE CLUSTER,\n# YOU MUST RUN A FULL REPAIR, SINCE THE SNITCH AFFECTS WHERE REPLICAS\n# ARE PLACED.\n#\n# Out of the box, Cassandra provides\n#  - SimpleSnitch:\n#    Treats Strategy order as proximity. This can improve cache\n#    locality when disabling read repair.  Only appropriate for\n#    single-datacenter deployments.\n#  - GossipingPropertyFileSnitch\n#    This should be your go-to snitch for production use.  The rack\n#    and datacenter for the local node are defined in\n#    cassandra-rackdc.properties and propagated to other nodes via\n#    gossip.  If cassandra-topology.properties exists, it is used as a\n#    fallback, allowing migration from the PropertyFileSnitch.\n#  - PropertyFileSnitch:\n#    Proximity is determined by rack and data center, which are\n#    explicitly configured in cassandra-topology.properties.\n#  - Ec2Snitch:\n#    Appropriate for EC2 deployments in a single Region. Loads Region\n#    and Availability Zone information from the EC2 API. The Region is\n#    treated as the datacenter, and the Availability Zone as the rack.\n#    Only private IPs are used, so this will not work across multiple\n#    Regions.\n#  - Ec2MultiRegionSnitch:\n#    Uses public IPs as broadcast_address to allow cross-region\n#    connectivity.  (Thus, you should set seed addresses to the public\n#    IP as well.) You will need to open the storage_port or\n#    ssl_storage_port on the public IP firewall.  (For intra-Region\n#    traffic, Cassandra will switch to the private IP after\n#    establishing a connection.)\n#  - RackInferringSnitch:\n#    Proximity is determined by rack and data center, which are\n#    assumed to correspond to the 3rd and 2nd octet of each node's IP\n#    address, respectively.  Unless this happens to match your\n#    deployment conventions, this is best used as an example of\n#    writing a custom Snitch class and is provided in that spirit.\n#\n# You can use a custom Snitch by setting this to the full class name\n# of the snitch, which will be assumed to be on your classpath.\nendpoint_snitch: SimpleSnitch\n\n# controls how often to perform the more expensive part of host score\n# calculation\ndynamic_snitch_update_interval_in_ms: 100 \n# controls how often to reset all host scores, allowing a bad host to\n# possibly recover\ndynamic_snitch_reset_interval_in_ms: 600000\n# if set greater than zero and read_repair_chance is < 1.0, this will allow\n# 'pinning' of replicas to hosts in order to increase cache capacity.\n# The badness threshold will control how much worse the pinned host has to be\n# before the dynamic snitch will prefer other replicas over it.  This is\n# expressed as a double which represents a percentage.  Thus, a value of\n# 0.2 means Cassandra would continue to prefer the static snitch values\n# until the pinned host was 20% worse than the fastest.\ndynamic_snitch_badness_threshold: 0.1\n\n# request_scheduler -- Set this to a class that implements\n# RequestScheduler, which will schedule incoming client requests\n# according to the specific policy. This is useful for multi-tenancy\n# with a single Cassandra cluster.\n# NOTE: This is specifically for requests from the client and does\n# not affect inter node communication.\n# org.apache.cassandra.scheduler.NoScheduler - No scheduling takes place\n# org.apache.cassandra.scheduler.RoundRobinScheduler - Round robin of\n# client requests to a node with a separate queue for each\n# request_scheduler_id. The scheduler is further customized by\n# request_scheduler_options as described below.\nrequest_scheduler: org.apache.cassandra.scheduler.NoScheduler\n\n# Scheduler Options vary based on the type of scheduler\n# NoScheduler - Has no options\n# RoundRobin\n#  - throttle_limit -- The throttle_limit is the number of in-flight\n#                      requests per client.  Requests beyond \n#                      that limit are queued up until\n#                      running requests can complete.\n#                      The value of 80 here is twice the number of\n#                      concurrent_reads + concurrent_writes.\n#  - default_weight -- default_weight is optional and allows for\n#                      overriding the default which is 1.\n#  - weights -- Weights are optional and will default to 1 or the\n#               overridden default_weight. The weight translates into how\n#               many requests are handled during each turn of the\n#               RoundRobin, based on the scheduler id.\n#\n# request_scheduler_options:\n#    throttle_limit: 80\n#    default_weight: 5\n#    weights:\n#      Keyspace1: 1\n#      Keyspace2: 5\n\n# request_scheduler_id -- An identifier based on which to perform\n# the request scheduling. Currently the only valid option is keyspace.\n# request_scheduler_id: keyspace\n\n# Enable or disable inter-node encryption\n# Default settings are TLS v1, RSA 1024-bit keys (it is imperative that\n# users generate their own keys) TLS_RSA_WITH_AES_128_CBC_SHA as the cipher\n# suite for authentication, key exchange and encryption of the actual data transfers.\n# Use the DHE/ECDHE ciphers if running in FIPS 140 compliant mode.\n# NOTE: No custom encryption options are enabled at the moment\n# The available internode options are : all, none, dc, rack\n#\n# If set to dc cassandra will encrypt the traffic between the DCs\n# If set to rack cassandra will encrypt the traffic between the racks\n#\n# The passwords used in these options must match the passwords used when generating\n# the keystore and truststore.  For instructions on generating these files, see:\n# http://download.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore\n#\nserver_encryption_options:\n    internode_encryption: none\n    keystore: conf/.keystore\n    keystore_password: cassandra\n    truststore: conf/.truststore\n    truststore_password: cassandra\n    # More advanced defaults below:\n    # protocol: TLS\n    # algorithm: SunX509\n    # store_type: JKS\n    # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]\n    # require_client_auth: false\n\n# enable or disable client/server encryption.\nclient_encryption_options:\n    enabled: false\n    keystore: conf/.keystore\n    keystore_password: cassandra\n    # require_client_auth: false\n    # Set trustore and truststore_password if require_client_auth is true\n    # truststore: conf/.truststore\n    # truststore_password: cassandra\n    # More advanced defaults below:\n    # protocol: TLS\n    # algorithm: SunX509\n    # store_type: JKS\n    # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]\n\n# internode_compression controls whether traffic between nodes is\n# compressed.\n# can be:  all  - all traffic is compressed\n#          dc   - traffic between different datacenters is compressed\n#          none - nothing is compressed.\ninternode_compression: all\n\n# Enable or disable tcp_nodelay for inter-dc communication.\n# Disabling it will result in larger (but fewer) network packets being sent,\n# reducing overhead from the TCP protocol itself, at the cost of increasing\n# latency if you block for cross-datacenter responses.\ninter_dc_tcp_nodelay: false\n"
  },
  {
    "path": "src/kundera-rethinkdb/pom.xml",
    "content": "<?xml version=\"1.0\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<artifactId>kundera</artifactId>\n\t\t<groupId>com.impetus</groupId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-rethinkdb</artifactId>\n\t<name>kundera-rethinkdb</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<rethinkdb.version>2.3.3</rethinkdb.version>\n\t</properties>\n\n\t<dependencies>\n\t\t<!-- Kundera dependencies -->\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>commons-beanutils</groupId>\n\t\t\t<artifactId>commons-beanutils-core</artifactId>\n\t\t\t<version>1.8.3</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<!-- rethinkdb dependencies -->\n\n\t\t<dependency>\n\t\t\t<groupId>com.rethinkdb</groupId>\n\t\t\t<artifactId>rethinkdb-driver</artifactId>\n\t\t\t<version>${rethinkdb.version}</version>\n\t\t</dependency>\n\n\t</dependencies>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n"
  },
  {
    "path": "src/kundera-rethinkdb/src/main/java/com/impetus/client/rethink/RethinkDBClient.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rethink;\n\nimport java.lang.reflect.Field;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.Id;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\n\nimport com.impetus.client.rethink.query.RethinkDBQuery;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.index.IndexManager;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.ClientMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.rethinkdb.RethinkDB;\nimport com.rethinkdb.model.MapObject;\nimport com.rethinkdb.net.Connection;\n\n/**\n * The Class RethinkDBClient.\n * \n * @author karthikp.manchala\n */\npublic class RethinkDBClient extends ClientBase implements Client<RethinkDBQuery>, ClientPropertiesSetter\n{\n\n    /** The Constant ID. */\n    private static final String ID = \"id\";\n\n    /** The connection. */\n    private Connection connection;\n\n    /** The Constant r. */\n    private static final RethinkDB r = RethinkDB.r;\n\n    /**\n     * Gets the connection.\n     * \n     * @return the connection\n     */\n    public Connection getConnection()\n    {\n        return connection;\n    }\n\n    /**\n     * Gets the r.\n     * \n     * @return the r\n     */\n    public static RethinkDB getR()\n    {\n        return r;\n    }\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /**\n     * Instantiates a new rethink db client.\n     * \n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param indexManager\n     *            the index manager\n     * @param reader\n     *            the reader\n     * @param properties\n     *            the properties\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param connection\n     *            the connection\n     * @param clientMetadata\n     *            the client metadata\n     */\n    protected RethinkDBClient(KunderaMetadata kunderaMetadata, IndexManager indexManager, EntityReader reader,\n            Map<String, Object> properties, String persistenceUnit, Connection connection,\n            ClientMetadata clientMetadata)\n    {\n        super(kunderaMetadata, properties, persistenceUnit);\n        this.reader = reader;\n        this.connection = connection;\n        this.indexManager = indexManager;\n        this.clientMetadata = clientMetadata;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientPropertiesSetter#\n     * populateClientProperties(com.impetus.kundera.client.Client,\n     * java.util.Map)\n     */\n    @Override\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.Object)\n     */\n    @Override\n    public Object find(Class entityClass, Object key)\n    {\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n\n        Object e = r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName()).get(key).run(connection,\n                entityClass);\n\n        PropertyAccessorHelper.setId(e, entityMetadata, key);\n\n        return e;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.String[], java.lang.Object[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    @Override\n    public void close()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera.\n     * persistence.context.jointable.JoinTableData )\n     */\n    @Override\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,\n            Object pKeyColumnValue, Class columnJavaType)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    @Override\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    @Override\n    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    @Override\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    @Override\n    public Class<RethinkDBQuery> getQueryImplementor()\n    {\n        // TODO Auto-generated method stub\n        return RethinkDBQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    @Override\n    public Generator getIdGenerator()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.\n     * metadata.model.EntityMetadata, java.lang.Object, java.lang.Object,\n     * java.util.List)\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n        if (!isUpdate)\n        {\n            r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName())\n                    .insert(populateRmap(entityMetadata, entity)).run(connection);\n        }\n        else\n        {\n            r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName())\n                    .update(populateRmap(entityMetadata, entity)).run(connection);\n        }\n    }\n\n    /**\n     * Populate rmap.\n     * \n     * @param entityMetadata\n     *            the entity metadata\n     * @param entity\n     *            the entity\n     * @return the map object\n     */\n    private MapObject populateRmap(EntityMetadata entityMetadata, Object entity)\n    {\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(entityMetadata.getPersistenceUnit());\n        Class entityClazz = entityMetadata.getEntityClazz();\n        EntityType entityType = metaModel.entity(entityClazz);\n        Set<Attribute> attributes = entityType.getAttributes();\n        Iterator<Attribute> iterator = attributes.iterator();\n        return iterateAndPopulateRmap(entity, metaModel, iterator);\n    }\n\n    /**\n     * Iterate and populate rmap.\n     * \n     * @param entity\n     *            the entity\n     * @param metaModel\n     *            the meta model\n     * @param iterator\n     *            the iterator\n     * @return the map object\n     */\n    private MapObject iterateAndPopulateRmap(Object entity, MetamodelImpl metaModel, Iterator<Attribute> iterator)\n    {\n        MapObject map = r.hashMap();\n        while (iterator.hasNext())\n        {\n            Attribute attribute = iterator.next();\n            Field field = (Field) attribute.getJavaMember();\n            Object value = PropertyAccessorHelper.getObject(entity, field);\n            if (field.isAnnotationPresent(Id.class))\n            {\n                map.with(ID, value);\n            }\n            else\n            {\n                map.with(((AbstractAttribute) attribute).getJPAColumnName(), value);\n            }\n        }\n        return map;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientBase#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    protected void delete(Object entity, Object pKey)\n    {\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass());\n        r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName()).get(pKey).delete().run(connection);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rethinkdb/src/main/java/com/impetus/client/rethink/RethinkDBClientFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rethink;\n\nimport java.util.Map;\nimport java.util.Properties;\n\nimport com.impetus.client.rethink.query.RethinkDBEntityReader;\nimport com.impetus.client.rethink.schemamanager.RethinkDBSchemaManager;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.rethinkdb.RethinkDB;\nimport com.rethinkdb.net.Connection;\n\n/**\n * A factory for creating RethinkDBClient objects.\n * \n * @author karthikp.manchala\n */\npublic class RethinkDBClientFactory extends GenericClientFactory\n{\n\n    /** The Constant r. */\n    private static final RethinkDB r = RethinkDB.r;\n\n    /** The connection. */\n    private Connection connection;\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.ClientFactory#getSchemaManager(java.util.Map)\n     */\n    @Override\n    public SchemaManager getSchemaManager(Map<String, Object> puProperties)\n    {\n        if (schemaManager == null)\n        {\n            initializePropertyReader();\n            setExternalProperties(puProperties);\n            schemaManager = new RethinkDBSchemaManager(RethinkDBClientFactory.class.getName(), puProperties,\n                    kunderaMetadata);\n        }\n        return schemaManager;\n    }\n\n    /**\n     * Initialize property reader.\n     */\n    private void initializePropertyReader()\n    {\n        if (propertyReader == null)\n        {\n            propertyReader = new RethinkDBPropertyReader(externalProperties,\n                    kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(getPersistenceUnit()));\n            propertyReader.read(getPersistenceUnit());\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.ClientLifeCycleManager#destroy()\n     */\n    @Override\n    public void destroy()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initialize(java.util.Map)\n     */\n    @Override\n    public void initialize(Map<String, Object> puProperties)\n    {\n        reader = new RethinkDBEntityReader(kunderaMetadata);\n        setExternalProperties(puProperties);\n        initializePropertyReader();\n        PersistenceUnitMetadata pum = kunderaMetadata.getApplicationMetadata()\n                .getPersistenceUnitMetadata(getPersistenceUnit());\n\n        Properties pumProps = pum.getProperties();\n\n        if (puProperties != null)\n        {\n            pumProps.putAll(puProperties);\n        }\n\n        String host = pumProps.getProperty(\"kundera.nodes\");\n        String port = pumProps.getProperty(\"kundera.port\");\n\n        if (host == null || port == null)\n        {\n            throw new KunderaException(\"Hostname/IP or Port is null.\");\n        }\n\n        connection = r.connection().hostname(host).port(Integer.parseInt(port)).connect();\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#createPoolOrConnection()\n     */\n    @Override\n    protected Object createPoolOrConnection()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#instantiateClient(java.\n     * lang.String)\n     */\n    @Override\n    protected Client instantiateClient(String persistenceUnit)\n    {\n        return new RethinkDBClient(kunderaMetadata, indexManager, reader, externalProperties, persistenceUnit,\n                this.connection, this.clientMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.GenericClientFactory#isThreadSafe()\n     */\n    @Override\n    public boolean isThreadSafe()\n    {\n        // TODO Auto-generated method stub\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initializeLoadBalancer(\n     * java.lang.String)\n     */\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rethinkdb/src/main/java/com/impetus/client/rethink/RethinkDBPropertyReader.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rethink;\n\nimport java.util.Map;\n\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * The Class RethinkDBPropertyReader.\n * \n * @author karthikp.manchala\n */\npublic class RethinkDBPropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n\n    /** The resmd. */\n    public static RethinkDBSchemaMetadata resmd;\n\n    /**\n     * Instantiates a new rethink db property reader.\n     * \n     * @param externalProperties\n     *            the external properties\n     * @param puMetadata\n     *            the pu metadata\n     */\n    public RethinkDBPropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        resmd = new RethinkDBSchemaMetadata();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.AbstractPropertyReader#onXml(com.impetus.\n     * kundera.configure.ClientProperties)\n     */\n    @Override\n    public void onXml(ClientProperties cp)\n    {\n        if (cp != null)\n        {\n            resmd.setClientProperties(cp);\n        }\n    }\n\n    /**\n     * The Class RethinkDBSchemaMetadata.\n     */\n    public class RethinkDBSchemaMetadata\n    {\n\n        /** The client properties. */\n        private ClientProperties clientProperties;\n\n        /**\n         * Instantiates a new rethink db schema metadata.\n         */\n        public RethinkDBSchemaMetadata()\n        {\n\n        }\n\n        /**\n         * Gets the client properties.\n         * \n         * @return the client properties\n         */\n        public ClientProperties getClientProperties()\n        {\n            return clientProperties;\n        }\n\n        /**\n         * Sets the client properties.\n         * \n         * @param clientProperties\n         *            the new client properties\n         */\n        private void setClientProperties(ClientProperties clientProperties)\n        {\n            this.clientProperties = clientProperties;\n        }\n\n        /**\n         * Gets the data store.\n         * \n         * @param datastore\n         *            the datastore\n         * @return the data store\n         */\n        public DataStore getDataStore(String datastore)\n        {\n            if (getClientProperties() != null && getClientProperties().getDatastores() != null)\n            {\n                for (DataStore dataStore : getClientProperties().getDatastores())\n                {\n                    if (dataStore.getName() != null && dataStore.getName().trim().equalsIgnoreCase(datastore))\n                    {\n                        return dataStore;\n                    }\n                }\n            }\n            return null;\n        }\n\n    }\n}"
  },
  {
    "path": "src/kundera-rethinkdb/src/main/java/com/impetus/client/rethink/query/RethinkDBEntityReader.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rethink.query;\n\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\n\n/**\n * The Class RethinkDBEntityReader.\n * \n * @author karthikp.manchala\n */\npublic class RethinkDBEntityReader extends AbstractEntityReader implements EntityReader\n{\n\n    /**\n     * Instantiates a new rethink db entity reader.\n     * \n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public RethinkDBEntityReader(KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.AbstractEntityReader#findById(java.lang.\n     * Object, com.impetus.kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        return super.findById(primaryKey, m, client);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#populateRelation(com.impetus\n     * .kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client, int)\n     */\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rethinkdb/src/main/java/com/impetus/client/rethink/query/RethinkDBQuery.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rethink.query;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport javax.persistence.Id;\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\n\nimport org.apache.commons.beanutils.ConvertUtils;\nimport org.eclipse.persistence.jpa.jpql.parser.ComparisonExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.JPQLExpression;\nimport org.eclipse.persistence.jpa.jpql.parser.WhereClause;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.rethink.RethinkDBClient;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.attributes.AbstractAttribute;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.KunderaQueryUtils;\nimport com.impetus.kundera.query.Query;\nimport com.impetus.kundera.query.QueryImpl;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\nimport com.rethinkdb.RethinkDB;\nimport com.rethinkdb.gen.ast.Filter;\nimport com.rethinkdb.gen.ast.Pluck;\nimport com.rethinkdb.gen.ast.ReqlExpr;\nimport com.rethinkdb.gen.ast.ReqlFunction1;\nimport com.rethinkdb.gen.ast.Table;\nimport com.rethinkdb.net.Connection;\nimport com.rethinkdb.net.Cursor;\n\n/**\n * The Class RethinkDBQuery.\n * \n * @author karthikp.manchala\n */\npublic class RethinkDBQuery extends QueryImpl implements Query\n{\n\n    /** The Constant ID. */\n    private static final String ID = \"id\";\n\n    /** The Constant DOT_REGEX. */\n    private static final String DOT_REGEX = \"[.]\";\n\n    /** The Constant PARAMETERIZED_PREFIX. */\n    private static final String PARAMETERIZED_PREFIX = \":\";\n\n    /** The Constant POSITIONAL_PREFIX. */\n    private static final String POSITIONAL_PREFIX = \"?\";\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(RethinkDBQuery.class);\n\n    /**\n     * Instantiates a new rethink db query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param persistenceDelegator\n     *            the persistence delegator\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public RethinkDBQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n        // TODO Auto-generated constructor stub\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera.\n     * metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List populateEntities(EntityMetadata m, Client client)\n    {\n        RethinkDB r = ((RethinkDBClient) client).getR();\n        Connection conn = ((RethinkDBClient) client).getConnection();\n\n        Filter filter = null;\n        Pluck pluck;\n        Table table = r.db(m.getSchema()).table(m.getTableName());\n\n        Cursor cursor = null;\n        List results = new ArrayList();\n\n        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()\n                .getMetamodel(m.getPersistenceUnit());\n        EntityType entityType = metaModel.entity(m.getEntityClazz());\n\n        JPQLExpression jpqlExp = kunderaQuery.getJpqlExpression();\n        List<String> selectColumns = KunderaQueryUtils.getSelectColumns(jpqlExp);\n\n        if (KunderaQueryUtils.hasWhereClause(jpqlExp))\n        {\n            // add filters\n            WhereClause whereClause = KunderaQueryUtils.getWhereClause(jpqlExp);\n            Expression whereExp = whereClause.getConditionalExpression();\n            filter = table.filter(parseAndBuildFilters(entityType, whereExp));\n        }\n\n        if (!selectColumns.isEmpty())\n        {\n            // select by specific columns, consider last for plucking\n            pluck = filter == null ? table.pluck(selectColumns) : filter.pluck(selectColumns);\n            cursor = pluck.run(conn);\n        }\n\n        if (cursor == null)\n        {\n            cursor = (Cursor) (filter == null ? table.run(conn) : filter.run(conn));\n        }\n\n        for (Object obj : cursor)\n        {\n            Object entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());\n            buildEntityFromCursor(entity, (HashMap) obj, entityType);\n            results.add(entity);\n        }\n\n        return results;\n    }\n\n    /**\n     * Builds the entity from cursor.\n     * \n     * @param entity\n     *            the entity\n     * @param obj\n     *            the obj\n     * @param entityType\n     *            the entity type\n     * @return the object\n     */\n    private void buildEntityFromCursor(Object entity, HashMap obj, EntityType entityType)\n    {\n        Iterator<Attribute> iter = entityType.getAttributes().iterator();\n        while (iter.hasNext())\n        {\n            Attribute attribute = iter.next();\n            Field field = (Field) attribute.getJavaMember();\n            if (field.isAnnotationPresent(Id.class))\n            {\n                PropertyAccessorHelper.set(entity, field, obj.get(ID));\n            }\n            else\n            {\n                PropertyAccessorHelper.set(entity, field, obj.get(((AbstractAttribute) attribute).getJPAColumnName()));\n            }\n\n        }\n    }\n\n    /**\n     * Parses the and build filters.\n     * \n     * @param entityType\n     *            the entity type\n     * @param whereExp\n     *            the where exp\n     * @return the reql function1\n     */\n    private ReqlFunction1 parseAndBuildFilters(EntityType entityType, Expression whereExp)\n    {\n        if (whereExp instanceof ComparisonExpression)\n        {\n            String left = ((ComparisonExpression) whereExp).getLeftExpression().toActualText();\n\n            String right = ((ComparisonExpression) whereExp).getRightExpression().toActualText();\n            right = right.replaceAll(\"['\\\"]\", \"\");\n            if (right.startsWith(POSITIONAL_PREFIX) || right.startsWith(PARAMETERIZED_PREFIX))\n            {\n                right = kunderaQuery.getParametersMap().get(right) + \"\";\n            }\n            Attribute attribute = entityType.getAttribute(left.split(DOT_REGEX)[1]);\n            boolean isId = ((Field) attribute.getJavaMember()).isAnnotationPresent(Id.class);\n          \n            return buildFunction(isId ? ID : ((AbstractAttribute) attribute).getJPAColumnName(),\n                    ConvertUtils.convert(right, attribute.getJavaType()),\n                    ((ComparisonExpression) whereExp).getActualIdentifier());\n        }\n        else\n        {\n            logger.error(\"Operation not supported\");\n            throw new KunderaException(\"Operation not supported\");\n        }\n    }\n\n    /**\n     * Builds the function.\n     * \n     * @param colName\n     *            the col name\n     * @param obj\n     *            the obj\n     * @param identifier\n     *            the identifier\n     * @return the reql function1\n     */\n    public static ReqlFunction1 buildFunction(final String colName, final Object obj, final String identifier)\n    {\n        return new ReqlFunction1()\n        {\n\n            @Override\n            public Object apply(ReqlExpr row)\n            {\n\n                switch (identifier)\n                {\n\n                case \"<\":\n                    return row.g(colName).lt(obj);\n\n                case \"<=\":\n                    return row.g(colName).le(obj);\n\n                case \">\":\n                    return row.g(colName).gt(obj);\n                case \">=\":\n                    return row.g(colName).ge(obj);\n\n                case \"=\":\n                    return row.g(colName).eq(obj);\n\n                default:\n                    logger.error(\"Operation not supported\");\n                    throw new KunderaException(\"Operation not supported\");\n\n                }\n            }\n        };\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#findUsingLucene(com.impetus.kundera.\n     * metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#recursivelyPopulateEntities(com.\n     * impetus.kundera.metadata.model.EntityMetadata ,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#getReader()\n     */\n    @Override\n    protected EntityReader getReader()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()\n     */\n    @Override\n    protected int onExecuteUpdate()\n    {\n        // TODO Auto-generated method stub\n        return 0;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#close()\n     */\n    @Override\n    public void close()\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#iterate()\n     */\n    @Override\n    public Iterator iterate()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rethinkdb/src/main/java/com/impetus/client/rethink/schemamanager/RethinkDBSchemaManager.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rethink.schemamanager;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.configure.schema.SchemaGenerationException;\nimport com.impetus.kundera.configure.schema.TableInfo;\nimport com.impetus.kundera.configure.schema.api.AbstractSchemaManager;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.rethinkdb.RethinkDB;\nimport com.rethinkdb.net.Connection;\n\n/**\n * The Class RethinkDBSchemaManager.\n * \n * @author karthikp.manchala\n */\npublic class RethinkDBSchemaManager extends AbstractSchemaManager implements SchemaManager\n{\n\n    /** The Constant logger. */\n    private static final Logger logger = LoggerFactory.getLogger(RethinkDBSchemaManager.class);\n\n    /** The connection. */\n    private Connection connection;\n\n    /** The Constant r. */\n    private static final RethinkDB r = RethinkDB.r;\n\n    /**\n     * Instantiates a new rethink db schema manager.\n     * \n     * @param clientFactory\n     *            the client factory\n     * @param externalProperties\n     *            the external properties\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public RethinkDBSchemaManager(String clientFactory, Map<String, Object> externalProperties,\n            KunderaMetadata kunderaMetadata)\n    {\n        super(clientFactory, externalProperties, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.SchemaManager#dropSchema()\n     */\n    @Override\n    public void dropSchema()\n    {\n        try\n        {\n            if (operation != null && (\"create-drop\").equalsIgnoreCase(operation))\n            {\n                r.dbDrop(databaseName);\n            }\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Error while dropping schema\", e);\n            throw new SchemaGenerationException(e, \"RethinkDB\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.SchemaManager#validateEntity\n     * (java.lang.Class)\n     */\n    @Override\n    public boolean validateEntity(Class clazz)\n    {\n        // TODO Auto-generated method stub\n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#initiateClient\n     * ()\n     */\n    @Override\n    protected boolean initiateClient()\n    {\n        for (String host : hosts)\n        {\n            if (host == null || !StringUtils.isNumeric(port) || port.isEmpty())\n            {\n                logger.error(\"Host or port should not be null / port should be numeric\");\n                throw new IllegalArgumentException(\"Host or port should not be null / port should be numeric\");\n            }\n            try\n            {\n                connection = r.connection().hostname(host).port(Integer.parseInt(port)).connect();\n            }\n            catch (Exception e)\n            {\n                logger.error(\"Database host/port cannot be resolved, Caused by: \" + e.getMessage());\n                throw new SchemaGenerationException(\"Database host/port cannot be resolved, Caused by: \" + e.getMessage());\n            }\n        }\n        return true;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#validate\n     * (java.util.List)\n     */\n    @Override\n    protected void validate(List<TableInfo> tableInfos)\n    {\n        List listTables = r.db(databaseName).tableList().run(connection);\n\n        for (TableInfo tableInfo : tableInfos)\n        {\n            try\n            {\n                if (!listTables.contains(tableInfo.getTableName()))\n                {\n                    throw new SchemaGenerationException(\"Table: \" + tableInfo.getTableName() + \" does not exist \");\n                }\n            }\n            catch (Exception e)\n            {\n                logger.error(\"Error while validating tables, Caused by: \" + e.getMessage());\n                throw new KunderaException(\"Error while validating tables, Caused by: \" + e.getMessage());\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#update\n     * (java.util.List)\n     */\n    @Override\n    protected void update(List<TableInfo> tableInfos)\n    {\n        List listTables = r.db(databaseName).tableList().run(connection);\n\n        for (TableInfo tableInfo : tableInfos)\n        {\n            try\n            {\n                if (!listTables.contains(tableInfo.getTableName()))\n                {\n                    r.db(databaseName).tableCreate(tableInfo.getTableName()).run(connection);\n                }\n            }\n            catch (Exception e)\n            {\n                logger.error(\"Error while updating tables, Caused by: \" + e.getMessage());\n                throw new KunderaException(\"Error while updating tables, Caused by: \" + e.getMessage());\n            }\n\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#create\n     * (java.util.List)\n     */\n    @Override\n    protected void create(List<TableInfo> tableInfos)\n    {\n        List dbList = r.dbList().run(connection);\n        \n        if(!dbList.contains(databaseName)){\n            r.dbCreate(databaseName).run(connection);\n        }\n        \n        List listTables = r.db(databaseName).tableList().run(connection);\n\n        for (TableInfo tableInfo : tableInfos)\n        {\n            try\n            {\n                if (listTables.contains(tableInfo.getTableName()))\n                {\n                    r.db(databaseName).tableDrop(tableInfo.getTableName()).run(connection);\n                }\n            }\n            catch (Exception e)\n            {\n                logger.error(\"Cannot check table existence for table \" + tableInfo.getTableName() + \". Caused By: \" + e);\n                throw new KunderaException(\"Cannot check table existence for table \" + tableInfo.getTableName()\n                        + \". Caused By: \" + e);\n            }\n            r.db(databaseName).tableCreate(tableInfo.getTableName()).run(connection);\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.schema.api.AbstractSchemaManager#create_drop\n     * (java.util.List)\n     */\n    @Override\n    protected void create_drop(List<TableInfo> tableInfos)\n    {\n        create(tableInfos);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.configure.schema.api.AbstractSchemaManager#\n     * exportSchema(java.lang.String, java.util.List)\n     */\n    public void exportSchema(final String persistenceUnit, List<TableInfo> schemas)\n    {\n        super.exportSchema(persistenceUnit, schemas);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rethinkdb/src/test/java/com/impetus/client/rethink/crud/RethinkCRUDTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rethink.crud;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.rethink.entities.Person;\n\n/**\n * The Class RethinkCRUDTest.\n * \n * @author: karthikp.manchala\n */\npublic class RethinkCRUDTest\n{\n\n    /** The Constant RETHINK_PU. */\n    private static final String RETHINK_PU = \"rethink_pu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(RETHINK_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test CRUD.\n     */\n    @Test\n    public void testCRUD()\n    {\n        testInsert();\n        testMerge();\n        testDelete();\n    }\n\n    /**\n     * Test insert.\n     */\n    private void testInsert()\n    {\n        Person person = new Person(\"101\", \"dev\", 22, 30000.5);\n        em.persist(person);\n        em.clear();\n        Person p = em.find(Person.class, \"101\");\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"101\", p.getPersonId());\n        Assert.assertEquals(\"dev\", p.getPersonName());\n        Assert.assertEquals(new Long(22), p.getAge());\n        Assert.assertEquals(30000.5, p.getSalary());\n    }\n\n    /**\n     * Test merge.\n     */\n    private void testMerge()\n    {\n        Person p = em.find(Person.class, \"101\");\n        p.setPersonName(\"karthik\");\n        em.merge(p);\n        em.clear();\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertNotNull(p1);\n        Assert.assertEquals(\"karthik\", p1.getPersonName());\n    }\n\n    /**\n     * Test delete.\n     */\n    private void testDelete()\n    {\n        Person p = em.find(Person.class, \"101\");\n        em.remove(p);\n        em.clear();\n        Person p1 = em.find(Person.class, \"101\");\n        Assert.assertNull(p1);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rethinkdb/src/test/java/com/impetus/client/rethink/entities/Person.java",
    "content": "/*******************************************************************************\n *  * Copyright 2017 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rethink.entities;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Person.\n * \n * @author: karthikp.manchala\n */\n@Entity\n@Table(name = \"PERSON_RETHINK\", schema = \"rethink@rethink_pu\")\npublic class Person\n{\n\n    /** The person id. */\n    @Id\n    private String personId;\n\n    /** The person name. */\n    private String personName;\n\n    /** The age. */\n    private Long age;\n\n    /** The salary. */\n    private Double salary;\n\n    /**\n     * Instantiates a new person.\n     */\n    public Person()\n    {\n    }\n\n    /**\n     * Instantiates a new person.\n     * \n     * @param personId\n     *            the person id\n     * @param personName\n     *            the person name\n     * @param age\n     *            the age\n     * @param salary\n     *            the salary\n     */\n    public Person(String personId, String personName, long age, Double salary)\n    {\n        super();\n        this.personId = personId;\n        this.personName = personName;\n        this.age = age;\n        this.salary = salary;\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public Long getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the new age\n     */\n    public void setAge(Long age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the salary.\n     * \n     * @return the salary\n     */\n    public Double getSalary()\n    {\n        return salary;\n    }\n\n    /**\n     * Sets the salary.\n     * \n     * @param salary\n     *            the new salary\n     */\n    public void setSalary(Double salary)\n    {\n        this.salary = salary;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rethinkdb/src/test/java/com/impetus/client/rethink/query/RethinkQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2016 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.rethink.query;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.rethink.entities.Person;\n\nimport junit.framework.Assert;\n\n/**\n * The Class KuduQueryTest.\n * \n * @author devender.yadav\n * \n */\npublic class RethinkQueryTest\n{\n    /** The Constant KUDU_PU. */\n    private static final String RETHINK_PU = \"rethink_pu\";\n\n    /** The Constant T. */\n    private static final boolean T = true;\n\n    /** The Constant F. */\n    private static final boolean F = false;\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private static EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(RETHINK_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n        createPersons();\n    }\n\n    /**\n     * Test select.\n     */\n    @Test\n    public void testSelect()\n    {\n        Query query = em.createQuery(\"Select p from Person p\");\n        List<Person> results = query.getResultList();\n        Assert.assertEquals(5, results.size());\n        assertResults(results, T, T, T, T, T);\n        \n        query = em.createQuery(\"Select p.personName from Person p where p.age = 20\");\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Person person = results.get(0);\n        Assert.assertNotNull(person);\n        Assert.assertEquals(\"karthik\", person.getPersonName());\n        Assert.assertNull(person.getPersonId());\n        Assert.assertNull(person.getSalary());\n        Assert.assertNull(person.getAge());\n\n        query = em.createQuery(\"Select p.personName,p.age from Person p where p.personId = '103'\");\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        Person p = results.get(0);\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"pg\", p.getPersonName());\n        Assert.assertEquals(new Long(30), p.getAge());\n        Assert.assertNull(p.getPersonId());\n        Assert.assertNull(p.getSalary());\n\n        query = em.createQuery(\"Select p from Person p where p.personId = '103'\");\n        results = query.getResultList();\n        Assert.assertEquals(1, results.size());\n        assertResults(results, F, F, T, F, F);\n\n        query = em.createQuery(\"Select p from Person p where p.age > 20\");\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        assertResults(results, F, F, T, T, T);\n\n        query = em.createQuery(\"Select p from Person p where p.age >= 20\");\n        results = query.getResultList();\n        Assert.assertEquals(4, results.size());\n        assertResults(results, F, T, T, T, T);\n\n        query = em.createQuery(\"Select p from Person p where p.age < 40\");\n        results = query.getResultList();\n        Assert.assertEquals(3, results.size());\n        assertResults(results, T, T, T, F, F);\n\n        query = em.createQuery(\"Select p from Person p where p.age <= 40\");\n        results = query.getResultList();\n        Assert.assertEquals(4, results.size());\n        assertResults(results, T, T, T, T, F);\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        deletePersons();\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n    /**\n     * Creates the persons.\n     */\n    private static void createPersons()\n    {\n        Person person1 = new Person(\"101\", \"dev\", 10, 10000.1);\n        em.persist(person1);\n        Person person2 = new Person(\"102\", \"karthik\", 20, 20000.2);\n        em.persist(person2);\n        Person person3 = new Person(\"103\", \"pg\", 30, 30000.3);\n        em.persist(person3);\n        Person person4 = new Person(\"104\", \"amit\", 40, 40000.4);\n        em.persist(person4);\n        Person person5 = new Person(\"105\", \"vivek\", 50, 50000.5);\n        em.persist(person5);\n    }\n\n    /**\n     * Delete persons.\n     */\n    private static void deletePersons()\n    {\n        Query query = em.createQuery(\"Select p from Person p\");\n        List<Person> results = query.getResultList();\n        for (Person p : results)\n        {\n            em.remove(p);\n        }\n    }\n\n    /**\n     * Validate person1.\n     *\n     * @param p\n     *            the person\n     */\n    protected void validatePerson1(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"101\", p.getPersonId());\n        Assert.assertEquals(\"dev\", p.getPersonName());\n        Assert.assertEquals(new Long(10), p.getAge());\n        Assert.assertEquals(10000.1, p.getSalary());\n    }\n\n    /**\n     * Validate person2.\n     *\n     * @param p\n     *            the person\n     */\n    protected void validatePerson2(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"102\", p.getPersonId());\n        Assert.assertEquals(\"karthik\", p.getPersonName());\n        Assert.assertEquals(new Long(20), p.getAge());\n        Assert.assertEquals(20000.2, p.getSalary());\n    }\n\n    /**\n     * Validate person3.\n     *\n     * @param p\n     *            the person\n     */\n    protected void validatePerson3(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"103\", p.getPersonId());\n        Assert.assertEquals(\"pg\", p.getPersonName());\n        Assert.assertEquals(new Long(30), p.getAge());\n        Assert.assertEquals(30000.3, p.getSalary());\n    }\n\n    /**\n     * Validate person4.\n     *\n     * @param p\n     *            the person\n     */\n    protected void validatePerson4(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"104\", p.getPersonId());\n        Assert.assertEquals(\"amit\", p.getPersonName());\n        Assert.assertEquals(new Long(40), p.getAge());\n        Assert.assertEquals(40000.4, p.getSalary());\n    }\n\n    /**\n     * Validate person5.\n     *\n     * @param p\n     *            the person\n     */\n    protected void validatePerson5(Person p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"105\", p.getPersonId());\n        Assert.assertEquals(\"vivek\", p.getPersonName());\n        Assert.assertEquals(new Long(50), p.getAge());\n        Assert.assertEquals(50000.5, p.getSalary());\n    }\n\n    /**\n     * Assert results.\n     *\n     * @param results\n     *            the results\n     * @param foundPerson1\n     *            the found person1\n     * @param foundPerson2\n     *            the found person2\n     * @param foundPerson3\n     *            the found person3\n     * @param foundPerson4\n     *            the found person4\n     * @param foundPerson5\n     *            the found person5\n     */\n    protected void assertResults(List<Person> results, boolean foundPerson1, boolean foundPerson2, boolean foundPerson3,\n            boolean foundPerson4, boolean foundPerson5)\n    {\n        for (Person person : results)\n        {\n            switch (person.getPersonId())\n            {\n            case \"101\":\n                if (foundPerson1)\n                    validatePerson1(person);\n                else\n                    Assert.fail();\n                break;\n            case \"102\":\n                if (foundPerson2)\n                    validatePerson2(person);\n                else\n                    Assert.fail();\n                break;\n            case \"103\":\n                if (foundPerson3)\n                    validatePerson3(person);\n                else\n                    Assert.fail();\n                break;\n            case \"104\":\n                if (foundPerson4)\n                    validatePerson4(person);\n                else\n                    Assert.fail();\n                break;\n            case \"105\":\n                if (foundPerson5)\n                    validatePerson5(person);\n                else\n                    Assert.fail();\n                break;\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-rethinkdb/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"rethink_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.client.rethink.entities.Person</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"28015\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"rethink\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"rethink\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.rethink.RethinkDBClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n</persistence>\r\n"
  },
  {
    "path": "src/kundera-spark/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t<groupId>com.impetus</groupId>\n\t\t<artifactId>kundera</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-spark-parent</artifactId>\n\t<packaging>pom</packaging>\n\t<name>kundera-spark-parent</name>\n\t<url>http://maven.apache.org</url>\n\n\t<!-- Dependencies -->\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<!-- spark dependencies -->\n\t\t<dependency>\n\t\t\t<groupId>org.apache.spark</groupId>\n\t\t\t<artifactId>spark-core_2.10</artifactId>\n\t\t\t<version>1.4.0</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.apache.spark</groupId>\n\t\t\t<artifactId>spark-sql_2.10</artifactId>\n\t\t\t<version>1.4.0</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.apache.spark</groupId>\n\t\t\t<artifactId>spark-hive_2.10</artifactId>\n\t\t\t<version>1.4.0</version>\n\t\t\t<scope>provided</scope>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>javax.servlet</groupId>\n\t\t\t\t\t<artifactId>servlet-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>javax.servlet</groupId>\n\t\t\t\t\t<artifactId>jsp-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t</dependencies>\n\n\t<profiles>\n\n\t\t<profile>\n\t\t\t<id>all</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>true</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>spark-core</module>\n\t\t\t\t<module>spark-cassandra</module>\n\t\t\t\t<module>spark-mongodb</module>\n\t\t\t\t<module>spark-hive</module>\n\t\t\t\t<module>spark-teradata</module>\n\t\t\t\t<!-- <module>spark-fs</module> -->\n\t\t\t</modules>\n\t\t</profile>\n\n\t\t<profile>\n\t\t\t<id>core</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>spark-core</module>\n\t\t\t</modules>\n\t\t</profile>\n\n\t\t<profile>\n\t\t\t<id>cassandra</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>spark-core</module>\n\t\t\t\t<module>spark-cassandra</module>\n\t\t\t</modules>\n\t\t</profile>\n\n\n\t\t<profile> \n\t\t   \t<id>mongodb</id>\n\t\t \t<activation> \n\t\t\t\t <activeByDefault>false</activeByDefault> \n\t\t\t</activation> \n\t\t\t<modules> \n\t\t\t\t<module>spark-core</module> \n\t\t\t\t <module>spark-mongodb</module> \n\t\t\t</modules> \n\t\t</profile> \n\t\t\n\t\t<profile> \n\t\t   \t<id>hive</id>\n\t\t \t<activation> \n\t\t\t\t <activeByDefault>false</activeByDefault> \n\t\t\t</activation> \n\t\t\t<modules> \n\t\t\t\t<module>spark-core</module> \n\t\t\t\t<module>spark-hive</module> \n\t\t\t</modules> \n\t\t</profile>\n\n\t\t<profile> \n\t\t   \t<id>teradata</id>\n\t\t \t<activation> \n\t\t\t\t <activeByDefault>false</activeByDefault> \n\t\t\t</activation> \n\t\t\t<modules> \n\t\t\t\t<module>spark-core</module> \n\t\t\t\t<module>spark-teradata</module> \n\t\t\t</modules> \n\t\t</profile>\n\n\t\t<!-- <profile> -->\n\t\t<!-- <id>fs</id> -->\n\t\t<!-- <activation> -->\n\t\t<!-- <activeByDefault>false</activeByDefault> -->\n\t\t<!-- </activation> -->\n\t\t<!-- <modules> -->\n\t\t<!-- <module>spark-core</module> -->\n\t\t<!-- <module>spark-fs</module> -->\n\t\t<!-- </modules> -->\n\t\t<!-- </profile> -->\n\n\t</profiles>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n"
  },
  {
    "path": "src/kundera-spark/spark-cassandra/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t<artifactId>kundera-spark-parent</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\n\t<artifactId>kundera-spark-cassandra</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-spark-cassandra</name>\n\t<url>http://maven.apache.org</url>\n\n\t<dependencies>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-spark</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-spark</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.datastax.spark</groupId>\n\t\t\t<artifactId>spark-cassandra-connector-java_2.10</artifactId>\n\t\t\t<version>1.3.0-M1</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.apache.cassandra</groupId>\n\t\t\t<artifactId>cassandra-all</artifactId>\n\t\t\t<version>2.1.3</version>\n\t\t</dependency>\n\n\n\t</dependencies>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-surefire-plugin</artifactId>\n\t\t\t\t<version>2.12</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<forkMode>never</forkMode>\n\t\t\t\t\t<argLine>-Xmx1024m</argLine>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n"
  },
  {
    "path": "src/kundera-spark/spark-cassandra/src/main/java/com/impetus/spark/client/CassSparkClient.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.spark.api.java.JavaRDD;\nimport org.apache.spark.sql.DataFrame;\nimport org.apache.spark.sql.SaveMode;\n\nimport scala.collection.immutable.Seq;\nimport scala.reflect.ClassTag;\n\nimport com.datastax.spark.connector.japi.CassandraJavaUtil;\nimport com.datastax.spark.connector.japi.SparkContextJavaFunctions;\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.spark.constants.SparkPropertiesConstants;\n\n/**\n * The Class CassSparkClient.\n * \n * @author: karthikp.manchala\n */\npublic class CassSparkClient implements SparkDataClient\n{\n\n    /** The Constant KEYSPACE. */\n    private static final String KEYSPACE = \"keyspace\";\n\n    /** The Constant TABLE. */\n    private static final String TABLE = \"table\";\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.spark.client.DataClient#registerTable(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.spark.client.SparkClient)\n     */\n    @Override\n    public void registerTable(EntityMetadata m, SparkClient sparkClient)\n    {\n        SparkContextJavaFunctions functions = CassandraJavaUtil.javaFunctions(sparkClient.sparkContext);\n        Class clazz = m.getEntityClazz();\n        JavaRDD cassandraRowsRDD = functions.cassandraTable(m.getSchema(), m.getTableName(),\n                CassandraJavaUtil.mapRowTo(clazz));\n        sparkClient.sqlContext.createDataFrame(cassandraRowsRDD, clazz).registerTempTable(m.getTableName());\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.spark.client.DataClient#saveDataFrame(org.apache.spark.sql\n     * .DataFrame, java.lang.Class, java.util.Map)\n     */\n    @Override\n    public void saveDataFrame(DataFrame dataFrame, Class<?> entityClazz, Map<String, Object> properties)\n    {\n        Map<String, String> options = new HashMap();\n        options.put(\"c_table\", (String) properties.get(TABLE));\n        options.put(KEYSPACE, (String) properties.get(KEYSPACE));\n\n        // TODO update order\n        dataFrame.save(SparkPropertiesConstants.SOURCE_CASSANDRA,\n                SaveMode.Append, options);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.spark.client.DataClient#persist(java.util.List,\n     * com.impetus.kundera.metadata.model.EntityMetadata,\n     * com.impetus.spark.client.SparkClient)\n     */\n    @Override\n    public boolean persist(List listEntity, EntityMetadata m, SparkClient sparkClient)\n    {\n        try\n        {\n            Seq s = scala.collection.JavaConversions.asScalaBuffer(listEntity).toList();\n            ClassTag tag = scala.reflect.ClassTag$.MODULE$.apply(m.getEntityClazz());\n            JavaRDD personRDD = sparkClient.sparkContext.parallelize(s, 1, tag).toJavaRDD();\n\n            CassandraJavaUtil.javaFunctions(personRDD)\n                    .writerBuilder(m.getSchema(), m.getTableName(), CassandraJavaUtil.mapToRow(m.getEntityClazz()))\n                    .saveToCassandra();\n            return true;\n        }\n        catch (Exception e)\n        {\n            throw new KunderaException(\"Cannot persist object(s)\", e);\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-cassandra/src/test/java/com/impetus/client/spark/Book.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.spark;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Book.\n * \n * @author devender.yadav\n */\n@Entity\n@Table(name = \"spark_book\")\npublic class Book implements Serializable\n{\n\n    /** The Constant serialVersionUID. */\n    private static final long serialVersionUID = 1L;\n\n    /** The id. */\n    @Id\n    private String id;\n\n    /** The title. */\n    @Column\n    private String title;\n\n    /** The author. */\n    @Column\n    private String author;\n\n    /** The category. */\n    @Column\n    private String category;\n\n    /** The num pages. */\n    @Column\n    private int numPages;\n\n    /**\n     * Instantiates a new book.\n     */\n    public Book()\n    {\n\n    }\n\n    /**\n     * Instantiates a new book.\n     * \n     * @param id\n     *            the id\n     * @param title\n     *            the title\n     * @param author\n     *            the author\n     * @param category\n     *            the category\n     * @param numPages\n     *            the num pages\n     */\n    public Book(String id, String title, String author, String category, int numPages)\n    {\n        this.id = id;\n        this.title = title;\n        this.author = author;\n        this.category = category;\n        this.numPages = numPages;\n    }\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the new id\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the title.\n     * \n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * Sets the title.\n     * \n     * @param title\n     *            the new title\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * Gets the author.\n     * \n     * @return the author\n     */\n    public String getAuthor()\n    {\n        return author;\n    }\n\n    /**\n     * Sets the author.\n     * \n     * @param author\n     *            the new author\n     */\n    public void setAuthor(String author)\n    {\n        this.author = author;\n    }\n\n    /**\n     * Gets the category.\n     * \n     * @return the category\n     */\n    public String getCategory()\n    {\n        return category;\n    }\n\n    /**\n     * Sets the category.\n     * \n     * @param category\n     *            the new category\n     */\n    public void setCategory(String category)\n    {\n        this.category = category;\n    }\n\n    /**\n     * Gets the num pages.\n     * \n     * @return the num pages\n     */\n    public int getNumPages()\n    {\n        return numPages;\n    }\n\n    /**\n     * Sets the num pages.\n     * \n     * @param number\n     *            the new num pages\n     */\n    public void setNumPages(int number)\n    {\n        this.numPages = number;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-cassandra/src/test/java/com/impetus/client/spark/SparkCassClientTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.spark;\n\nimport java.nio.ByteBuffer;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.spark.cassandra.utils.CassandraCli;\nimport com.impetus.client.spark.utils.SparkTestingUtils;\n\n/**\n * The Class SparkCassClientTest.\n * \n * @author: devender.yadav\n */\npublic class SparkCassClientTest\n{\n\n    /** The Constant PU. */\n    private static final String PU = \"spark_cass_pu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The em. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n        CassandraCli.cassandraSetUp(\"192.168.145.21\", 9161);\n        createKeyspace();\n        createColumnFamily();\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Spark cass test.\n     */\n    @Test\n    public void sparkCassTest()\n    {\n        persistBooks();\n        testPersist();\n        testQuery();\n        testSaveIntermediateResult();\n        intermediatePersistSyntaxTest();\n    }\n\n    /**\n     * Persist books.\n     */\n    private void persistBooks()\n    {\n        Book book1 = new Book(\"1\", \"A Tale of Two Cities\", \"Charles Dickens\", \"History\", 441);\n        Book book2 = new Book(\"2\", \"The Lord of the Rings\", \"J. R. R. Tolkien\", \"Adventure\", 1216);\n        Book book3 = new Book(\"3\", \"The Da Vinci Code\", \"Dan Brown\", \"Thriller\", 454);\n        em.persist(book1);\n        em.persist(book2);\n        em.persist(book3);\n    }\n\n    /**\n     * Test persist.\n     */\n    private void testPersist()\n    {\n        Book book = em.find(Book.class, \"1\");\n        validateBook1(book);\n        book = em.find(Book.class, \"2\");\n        validateBook2(book);\n        book = em.find(Book.class, \"3\");\n        validateBook3(book);\n    }\n\n    /**\n     * Query test.\n     */\n    private void testQuery()\n    {\n        List<Book> results = em.createNativeQuery(\"select * from spark_book\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        assertResults(results, true, true, true);\n\n        results = em.createNativeQuery(\"select * from spark_book where numPages > 450\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, false, true, true);\n\n        results = em.createNativeQuery(\"select * from spark_book where title like 'The%'\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, false, true, true);\n\n        List aggregateResults = em.createNativeQuery(\"select sum(numPages) from spark_book\").getResultList();\n        Assert.assertNotNull(aggregateResults);\n        Assert.assertEquals(1, aggregateResults.size());\n\n        aggregateResults = em.createNativeQuery(\"select count(numPages) from spark_book group by numPages\")\n                .getResultList();\n        Assert.assertNotNull(aggregateResults);\n    }\n\n    /**\n     * Intermediate persist syntax test.\n     */\n    private void intermediatePersistSyntaxTest()\n    {\n        String sqlString = \"INSERT INTO insert into cassandra.sparktest.table FROM (select * from spark_book)\";\n        Query query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n\n        sqlString = \"INSERT INTO into cassandra.sparktest.table FROM (select * from spark_book)\";\n        query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n\n        sqlString = \"INSERT asdf INTO cassandra.sparktest.table FROM (select * from spark_book)\";\n        query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n\n        sqlString = \"INSERT INTO dsfs cassandra.sparktest.table FROM (select * from spark_book)\";\n        query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n\n        sqlString = \" INTO cassandra.sparktest.table FROM (select * from spark_book)\";\n        query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n\n        sqlString = \"INSERT INTO cassandra.table FROM (select * from spark_book)\";\n        query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n\n        sqlString = \"INSERT INTO .sparktest.table FROM (select * from spark_book)\";\n        query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n\n        sqlString = \"INSERT INTO cassandra.sparktest.table.output FROM (select * from spark_book)\";\n        query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n\n        sqlString = \"INSERT INTO cassandra.sparktest.table (select * from spark_book)\";\n        query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n\n        sqlString = \"INSERT INTO cassandra.sparktest.table FROMM (select * from spark_book)\";\n        query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n\n        sqlString = \"INSERT INTO cassandra.sparktest.table FROM sadsd (select * from spark_book)\";\n        query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n\n        sqlString = \"INSERT INTO cassandra.sparktest.table FROM ()\";\n        query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n\n        sqlString = \"cassandra.sparktest.table FROM (select * from spark_book)\";\n        query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n\n        sqlString = \"INSERT INTO cassandra.sparktest.table (select * from spark_book)\";\n        query = em.createNativeQuery(sqlString, Book.class);\n        exceptionTest(query);\n    }\n\n    /**\n     * Save intermediate result.\n     */\n    private void testSaveIntermediateResult()\n    {\n        CassandraCli\n                .executeCqlQuery(\n                        \"CREATE TABLE IF NOT EXISTS spark_book_copy (id text PRIMARY KEY, title text, author text, category text, \\\"numPages\\\" int)\",\n                        \"sparktest\");\n\n        String sqlString = \"INSERT INTO cassandra.sparktest.spark_book_copy FROM (select * from spark_book)\";\n        Query q = em.createNativeQuery(sqlString, Book.class);\n        q.executeUpdate();\n\n        sqlString = \"INSERT INTO fs.[src/test/resources/testspark_csv] AS CSV FROM (select * from spark_book)\";\n        q = em.createNativeQuery(sqlString, Book.class);\n        q.executeUpdate();\n\n        sqlString = \"INSERT INTO fs.[src/test/resources/testspark_json] AS JSON FROM (select * from spark_book)\";\n        q = em.createNativeQuery(sqlString, Book.class);\n        q.executeUpdate();\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        SparkTestingUtils.recursivelyCleanDir(\"src/test/resources/testspark_csv\");\n        SparkTestingUtils.recursivelyCleanDir(\"src/test/resources/testspark_json\");\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        CassandraCli.executeCqlQuery(\"TRUNCATE spark_book\", \"sparktest\");\n        CassandraCli.executeCqlQuery(\"DROP TABLE spark_book\", \"sparktest\");\n        CassandraCli.executeCqlQuery(\"DROP KEYSPACE \\\"sparktest\\\"\", \"sparktest\");\n        emf.close();\n        emf = null;\n    }\n\n    /**\n     * Exception test.\n     * \n     * @param query\n     *            the query\n     * @return true, if successful\n     */\n    private boolean exceptionTest(Query query)\n    {\n        try\n        {\n            query.executeUpdate();\n        }\n        catch (Exception e)\n        {\n            return true;\n        }\n\n        Assert.fail();\n        return false;\n    }\n\n    /**\n     * Validate book1.\n     * \n     * @param book\n     *            the book\n     */\n    protected void validateBook1(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(\"A Tale of Two Cities\", book.getTitle());\n        Assert.assertEquals(\"Charles Dickens\", book.getAuthor());\n        Assert.assertEquals(\"History\", book.getCategory());\n        Assert.assertEquals(441, book.getNumPages());\n    }\n\n    /**\n     * Validate book2.\n     * \n     * @param book\n     *            the book\n     */\n    protected void validateBook2(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(\"The Lord of the Rings\", book.getTitle());\n        Assert.assertEquals(\"J. R. R. Tolkien\", book.getAuthor());\n        Assert.assertEquals(\"Adventure\", book.getCategory());\n        Assert.assertEquals(1216, book.getNumPages());\n    }\n\n    /**\n     * Validate book3.\n     * \n     * @param book\n     *            the book\n     */\n    protected void validateBook3(Book book)\n    {\n        Assert.assertNotNull(book);\n        Assert.assertEquals(\"The Da Vinci Code\", book.getTitle());\n        Assert.assertEquals(\"Dan Brown\", book.getAuthor());\n        Assert.assertEquals(\"Thriller\", book.getCategory());\n        Assert.assertEquals(454, book.getNumPages());\n    }\n\n    /**\n     * Assert results.\n     * \n     * @param results\n     *            the results\n     * @param foundBook1\n     *            the found book1\n     * @param foundBook2\n     *            the found book2\n     * @param foundBook3\n     *            the found book3\n     */\n    protected void assertResults(List<Book> results, boolean foundBook1, boolean foundBook2, boolean foundBook3)\n    {\n        for (Book book : results)\n        {\n            switch (book.getId())\n            {\n            case \"1\":\n                if (foundBook1)\n                    validateBook1(book);\n                else\n                    Assert.fail();\n                break;\n            case \"2\":\n                if (foundBook2)\n                    validateBook2(book);\n                else\n                    Assert.fail();\n                break;\n            case \"3\":\n                if (foundBook3)\n                    validateBook3(book);\n                else\n                    Assert.fail();\n                break;\n            }\n        }\n    }\n\n    /**\n     * Creates the column family.\n     */\n    private static void createColumnFamily()\n    {\n        try\n        {\n            CassandraCli.executeCqlQuery(\"USE \\\"sparktest\\\"\", \"sparktest\");\n            CassandraCli\n                    .executeCqlQuery(\n                            \"CREATE TABLE IF NOT EXISTS spark_book (id text PRIMARY KEY, title text, author text, category text, \\\"numPages\\\" int)\",\n                            \"sparktest\");\n        }\n        catch (Exception e)\n        {\n        }\n    }\n\n    /**\n     * Creates the keyspace.\n     */\n    private static void createKeyspace()\n    {\n        try\n        {\n            CassandraCli\n                    .getClient()\n                    .execute_cql3_query(\n                            ByteBuffer.wrap(\"CREATE KEYSPACE \\\"sparktest\\\" WITH replication = {'class':'SimpleStrategy','replication_factor':3}\"\n                                    .getBytes(\"UTF-8\")), Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception e)\n        {\n\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-cassandra/src/test/java/com/impetus/client/spark/cassandra/utils/CassandraCli.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2015 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.client.spark.cassandra.utils;\r\n\r\nimport java.io.File;\r\nimport java.io.IOException;\r\nimport java.io.UnsupportedEncodingException;\r\nimport java.net.Socket;\r\nimport java.net.UnknownHostException;\r\nimport java.nio.ByteBuffer;\r\nimport java.util.ArrayList;\r\nimport java.util.LinkedHashMap;\r\nimport java.util.List;\r\n\r\nimport org.apache.cassandra.locator.SimpleStrategy;\r\nimport org.apache.cassandra.service.EmbeddedCassandraService;\r\nimport org.apache.cassandra.thrift.Cassandra;\r\nimport org.apache.cassandra.thrift.CfDef;\r\nimport org.apache.cassandra.thrift.Compression;\r\nimport org.apache.cassandra.thrift.ConsistencyLevel;\r\nimport org.apache.cassandra.thrift.InvalidRequestException;\r\nimport org.apache.cassandra.thrift.KsDef;\r\nimport org.apache.cassandra.thrift.NotFoundException;\r\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\r\nimport org.apache.cassandra.thrift.TimedOutException;\r\nimport org.apache.cassandra.thrift.UnavailableException;\r\nimport org.apache.thrift.TException;\r\nimport org.apache.thrift.protocol.TBinaryProtocol;\r\nimport org.apache.thrift.protocol.TProtocol;\r\nimport org.apache.thrift.transport.TFramedTransport;\r\nimport org.apache.thrift.transport.TSocket;\r\nimport org.apache.thrift.transport.TTransport;\r\nimport org.apache.thrift.transport.TTransportException;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\n\r\nimport com.impetus.kundera.KunderaException;\r\n\r\n/**\r\n * The Class CassandraCli.\r\n * \r\n * @author vivek.mishra\r\n */\r\npublic final class CassandraCli\r\n{\r\n\r\n    /** The cassandra. */\r\n    private static EmbeddedCassandraService cassandra;\r\n\r\n    /** The client. */\r\n    public static Cassandra.Client client;\r\n\r\n    /** the log used by this class. */\r\n    private static Logger log = LoggerFactory.getLogger(CassandraCli.class);\r\n\r\n    private static List<String> puWithSchemaGeneration = new ArrayList<String>();\r\n\r\n    /**\r\n     * Cassandra set up.\r\n     * \r\n     * @throws IOException\r\n     *             Signals that an I/O exception has occurred.\r\n     * @throws TException\r\n     *             the t exception\r\n     * @throws InvalidRequestException\r\n     *             the invalid request exception\r\n     * @throws UnavailableException\r\n     *             the unavailable exception\r\n     * @throws TimedOutException\r\n     *             the timed out exception\r\n     * @throws SchemaDisagreementException\r\n     *             the schema disagreement exception\r\n     */\r\n    public static void cassandraSetUp(String ip, int port) throws IOException, TException, InvalidRequestException,\r\n            UnavailableException, TimedOutException, SchemaDisagreementException\r\n    {\r\n        if (!checkIfServerRunning(ip, port))\r\n        {\r\n            cassandra = new EmbeddedCassandraService();\r\n            cassandra.start();\r\n        }\r\n        initClient(ip, port);\r\n    }\r\n\r\n    public static void archivePu(final String peristenceunit)\r\n    {\r\n        puWithSchemaGeneration.add(peristenceunit);\r\n    }\r\n\r\n    public static boolean isArchived(final String persistenceUnit)\r\n    {\r\n        return puWithSchemaGeneration.contains(persistenceUnit);\r\n    }\r\n\r\n    /**\r\n     * Create keyspace.\r\n     * \r\n     * @param keyspaceName\r\n     *            keyspace name.\r\n     */\r\n    public static void createKeySpace(String keyspaceName)\r\n    {\r\n        try\r\n        {\r\n            client.describe_keyspace(keyspaceName);\r\n        }\r\n        catch (NotFoundException e)\r\n        {\r\n            List<CfDef> cfDefs = new ArrayList<CfDef>();\r\n            KsDef ks_Def = new KsDef(keyspaceName, SimpleStrategy.class.getName(), cfDefs);\r\n\r\n            // Set replication factor\r\n            if (ks_Def.strategy_options == null)\r\n            {\r\n                ks_Def.strategy_options = new LinkedHashMap<String, String>();\r\n            }\r\n            // Set replication factor, the value MUST be an integer\r\n            ks_Def.strategy_options.put(\"replication_factor\", \"1\");\r\n\r\n            try\r\n            {\r\n                client.system_add_keyspace(ks_Def);\r\n            }\r\n            catch (TException e1)\r\n            {\r\n                log.error(\"Error while adding keyspace, Caused by: .\", e1);\r\n            }\r\n\r\n        }\r\n\r\n        catch (InvalidRequestException e)\r\n        {\r\n            log.error(\"Error while adding keyspace, Caused by: .\", e);\r\n        }\r\n        catch (TException e)\r\n        {\r\n            log.error(\"Error while adding keyspace, Caused by: .\", e);\r\n        }\r\n\r\n    }\r\n\r\n    public static void truncateColumnFamily(String keyspace, String... columns)\r\n    {\r\n        try\r\n        {\r\n            if (client != null)\r\n            {\r\n                client.set_keyspace(keyspace);\r\n                for (String column : columns)\r\n                {\r\n                    if (columnFamilyExist(column, keyspace))\r\n                    {\r\n                        client.truncate(column);\r\n                    }\r\n                }\r\n            }\r\n        }\r\n        catch (IllegalArgumentException iex)\r\n        {\r\n            // do nothing.\r\n        }\r\n        catch (InvalidRequestException e)\r\n        {\r\n            // do nothing.\r\n        }\r\n        catch (UnavailableException e)\r\n        {\r\n            // do nothing.\r\n        }\r\n        catch (TimedOutException e)\r\n        {\r\n            // do nothing.\r\n        }\r\n        catch (TException e)\r\n        {\r\n            // do nothing.\r\n        }\r\n    }\r\n\r\n    /**\r\n     * Drop out key space.\r\n     * \r\n     * @param keyspaceName\r\n     *            keyspace name\r\n     */\r\n    public static void dropKeySpace(String keyspaceName)\r\n    {\r\n        try\r\n        {\r\n            if (client != null)\r\n            {\r\n                client.system_drop_keyspace(keyspaceName);\r\n            }\r\n        }\r\n        catch (InvalidRequestException e)\r\n        {\r\n            return;\r\n        }\r\n        catch (SchemaDisagreementException e)\r\n        {\r\n            log.error(\"Error while dropping keyspace, Caused by: .\", e);\r\n        }\r\n        catch (TException e)\r\n        {\r\n            log.error(\"Error while dropping keyspace, Caused by: .\", e);\r\n        }\r\n    }\r\n\r\n    private static void deleteCassandraFolders(String dir)\r\n    {\r\n        File directory = new File(dir);\r\n        // Get all files in directory\r\n        File[] files = directory.listFiles();\r\n        for (File file : files)\r\n        {\r\n            // Delete each file\r\n            if (!file.delete())\r\n            {\r\n                // Failed to delete file\r\n            }\r\n        }\r\n    }\r\n\r\n    public static boolean keyspaceExist(String keySpaceName)\r\n    {\r\n        try\r\n        {\r\n            return client.describe_keyspace(keySpaceName) != null;\r\n        }\r\n        catch (NotFoundException e)\r\n        {\r\n            return false;\r\n        }\r\n        catch (InvalidRequestException e)\r\n        {\r\n            log.error(\"Error while keyspace check, Caused by: .\", e);\r\n        }\r\n        catch (TException e)\r\n        {\r\n            log.error(\"Error while keyspace check, Caused by: .\", e);\r\n        }\r\n        return false;\r\n    }\r\n\r\n    public static boolean columnFamilyExist(String columnfamilyName, String keyspaceName)\r\n    {\r\n        try\r\n        {\r\n            client.set_keyspace(keyspaceName);\r\n            client.system_add_column_family(new CfDef(keyspaceName, columnfamilyName));\r\n        }\r\n        catch (InvalidRequestException irex)\r\n        {\r\n\r\n            StringBuilder builder = new StringBuilder(\"Cannot add already existing column family \");\r\n\r\n            if (irex.getWhy() != null && irex.getWhy().contains(builder.toString()))\r\n            {\r\n                return true;\r\n            }\r\n            return false;\r\n        }\r\n        catch (SchemaDisagreementException e)\r\n        {\r\n            return false;\r\n        }\r\n        catch (TException e)\r\n        {\r\n            return false;\r\n        }\r\n        return true;\r\n    }\r\n\r\n    /**\r\n     * Check if server running.\r\n     * \r\n     * @param port\r\n     * @param ip\r\n     * \r\n     * @return true, if successful\r\n     */\r\n    private static boolean checkIfServerRunning(String ip, int port)\r\n    {\r\n        try\r\n        {\r\n            Socket socket = new Socket(ip, port);\r\n            return socket.getInetAddress() != null;\r\n        }\r\n        catch (UnknownHostException e)\r\n        {\r\n            return false;\r\n        }\r\n        catch (IOException e)\r\n        {\r\n            return false;\r\n        }\r\n\r\n    }\r\n\r\n    /**\r\n     * Inits the client.\r\n     * \r\n     * @param port\r\n     * @param ip\r\n     * \r\n     * @throws TTransportException\r\n     *             the t transport exception\r\n     */\r\n    public static void initClient(String ip, int port) throws TTransportException\r\n    {\r\n        TSocket socket = new TSocket(ip, port);\r\n        TTransport transport = new TFramedTransport(socket);\r\n        TProtocol protocol = new TBinaryProtocol(transport, true, true);\r\n        client = new Cassandra.Client(protocol);\r\n        socket.open();\r\n    }\r\n\r\n    /**\r\n     * @return the client\r\n     */\r\n    public static Cassandra.Client getClient()\r\n    {\r\n        return client;\r\n    }\r\n\r\n    public static void executeCqlQuery(String cqlQuery, String keyspaceName)\r\n    {\r\n        try\r\n        {\r\n            getClient().set_cql_version(\"3.0.0\");\r\n            getClient().set_keyspace(keyspaceName);\r\n            getClient().execute_cql3_query(ByteBuffer.wrap(cqlQuery.getBytes(\"UTF-8\")), Compression.NONE,\r\n                    ConsistencyLevel.ONE);\r\n        }\r\n        catch (InvalidRequestException e)\r\n        {\r\n            log.error(\"Error while executing cql query {}, Caused by: .\", cqlQuery, e);\r\n            throw new KunderaException(e);\r\n        }\r\n        catch (UnavailableException e)\r\n        {\r\n            log.error(\"Error while executing cql query {}, Caused by: .\", cqlQuery, e);\r\n            throw new KunderaException(e);\r\n        }\r\n        catch (TimedOutException e)\r\n        {\r\n            log.error(\"Error while executing cql query {}, Caused by: .\", cqlQuery, e);\r\n            throw new KunderaException(e);\r\n        }\r\n        catch (SchemaDisagreementException e)\r\n        {\r\n            log.error(\"Error while executing cql query {}, Caused by: .\", cqlQuery, e);\r\n            throw new KunderaException(e);\r\n        }\r\n        catch (TException e)\r\n        {\r\n            log.error(\"Error while executing cql query {}, Caused by: .\", cqlQuery, e);\r\n            throw new KunderaException(e);\r\n        }\r\n        catch (UnsupportedEncodingException e)\r\n        {\r\n            log.error(\"Error while executing cql query {}, Caused by: .\", cqlQuery, e);\r\n            throw new KunderaException(e);\r\n        }\r\n    }\r\n\r\n    public static boolean dropColumnFamily(String columnFamilyName, String keyspaceName)\r\n    {\r\n        try\r\n        {\r\n            if (columnFamilyExist(columnFamilyName, keyspaceName))\r\n            {\r\n                client.system_drop_column_family(columnFamilyName);\r\n            }\r\n        }\r\n        catch (InvalidRequestException e)\r\n        {\r\n            return true;\r\n        }\r\n        catch (SchemaDisagreementException e)\r\n        {\r\n            return false;\r\n        }\r\n        catch (TException e)\r\n        {\r\n            return false;\r\n        }\r\n        return false;\r\n\r\n    }\r\n}\r\n"
  },
  {
    "path": "src/kundera-spark/spark-cassandra/src/test/resources/KunderaSparkCassProperties.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>cassandra</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"spark.executor.memory\" value=\"1g\"></property>\n\t\t\t\t\t<property name=\"spark.cassandra.connection.host\" value=\"192.168.145.21\"></property>\n\t\t\t\t\t<property name=\"spark.cassandra.connection.native.port\"\n\t\t\t\t\t\tvalue=\"9043\"></property>\n\t\t\t\t\t<property name=\"spark.cassandra.connection.rpc.port\"\n\t\t\t\t\t\tvalue=\"9161\"></property>\n\t\t\t\t\t<property name=\"spark.master\" value=\"local\"></property>\n\t\t\t\t\t<property name=\"spark.app.name\" value=\"testspark\"></property>\n\t\t\t\t\t<property name=\"spark.driver.allowMultipleContexts\" value=\"true\"></property>\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>\n"
  },
  {
    "path": "src/kundera-spark/spark-cassandra/src/test/resources/META-INF/persistence.xml",
    "content": "\r\n<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"spark_cass_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.client.spark.Book</class>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"7077\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"sparktest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"spark\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.spark.client.SparkClientFactory\" />\r\n\t\t\t<property name=\"kundera.client.property\" value=\"KunderaSparkCassProperties.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n</persistence>\r\n"
  },
  {
    "path": "src/kundera-spark/spark-core/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t<artifactId>kundera-spark-parent</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-spark</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-spark</name>\n\t<url>http://maven.apache.org</url>\n\n\t<!-- Dependencies -->\n\t<dependencies>\n\n\t\t<dependency>\n\t\t\t<groupId>com.databricks</groupId>\n\t\t\t<artifactId>spark-csv_2.10</artifactId>\n\t\t\t<version>1.1.0</version>\n\t\t</dependency>\n\n\t\t<!-- mysql connector -->\n\t\t<dependency>\n\t\t\t<groupId>mysql</groupId>\n\t\t\t<artifactId>mysql-connector-java</artifactId>\n\t\t\t<version>5.1.36</version>\n\t\t</dependency>\n\n\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hadoop</groupId>\n\t\t\t<artifactId>hadoop-client</artifactId>\n\t\t\t<version>2.7.0</version>\n\t\t\t<scope>provided</scope>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>javax.servlet</groupId>\n\t\t\t\t\t<artifactId>servlet-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>javax.servlet</groupId>\n\t\t\t\t\t<artifactId>jsp-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>commons-io</groupId>\n\t\t\t<artifactId>commons-io</artifactId>\n\t\t\t<version>2.4</version>\n\t\t</dependency>\n\n\t</dependencies>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-surefire-plugin</artifactId>\n\t\t\t\t<version>2.12</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<forkMode>never</forkMode>\n\t\t\t\t\t<argLine>-Xmx1024m</argLine>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n</project>"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/client/FSClient.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.spark.api.java.JavaRDD;\nimport org.apache.spark.sql.DataFrame;\nimport org.apache.spark.sql.SaveMode;\nimport org.apache.spark.sql.hive.HiveContext;\n\nimport scala.collection.immutable.Seq;\nimport scala.reflect.ClassTag;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.spark.client.FileFormatConstants.FileType;\nimport com.impetus.spark.constants.SparkPropertiesConstants;\n\n/**\n * The Class FSClient.\n * \n * @author: Devender Yadav\n */\npublic class FSClient extends FilePathBuilder implements SparkDataClient\n{\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.spark.client.DataClient#registerTable(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.spark.client.SparkClient)\n     */\n    @Override\n    public void registerTable(EntityMetadata m, SparkClient sparkClient)\n    {\n        String dataSourcePath = getInputFilePath(sparkClient.properties);\n        String ext = ((String) sparkClient.properties.get(\"format\")).toLowerCase();\n        FileType fileType = FileFormatConstants.extension.get(ext);\n        switch (fileType)\n        {\n        case CSV:\n            registerTableForCsv(m.getTableName(), dataSourcePath, sparkClient.sqlContext);\n            break;\n        case JSON:\n            registerTableForJson(m.getTableName(), dataSourcePath, sparkClient.sqlContext);\n            break;\n        default:\n            throw new UnsupportedOperationException(\"Files of type \" + ext + \" are not yet supported.\");\n        }\n    }\n\n    /**\n     * Register table for json.\n     * \n     * @param tableName\n     *            the table name\n     * @param dataSourcePath\n     *            the data source path\n     * @param sqlContext\n     *            the sql context\n     */\n    private void registerTableForJson(String tableName, String dataSourcePath, HiveContext sqlContext)\n    {\n        sqlContext.jsonFile(dataSourcePath).registerTempTable(tableName);\n    }\n\n    /**\n     * Register table for csv.\n     * \n     * @param tableName\n     *            the table name\n     * @param dataSourcePath\n     *            the data source path\n     * @param sqlContext\n     *            the sql context\n     */\n    private void registerTableForCsv(String tableName, String dataSourcePath, HiveContext sqlContext)\n    {\n        HashMap<String, String> options = new HashMap<String, String>();\n        options.put(\"header\", \"true\");\n        options.put(\"path\", dataSourcePath);\n        sqlContext.load(SparkPropertiesConstants.SOURCE_CSV, options).registerTempTable(tableName);\n    }\n\n    /**\n     * Gets the input file path.\n     * \n     * @param properties\n     *            the properties\n     * @return the input file path\n     */\n    @Override\n    public String getInputFilePath(Map<String, Object> properties)\n    {\n        String path = (String) properties.get(SparkPropertiesConstants.FS_INPUT_FILE_PATH);\n        if (path == null || path.isEmpty())\n        {\n            throw new KunderaException(\n                    \"Please set the path of inputfile while creating EntityManager using the property\" + \"\\\"\"\n                            + SparkPropertiesConstants.FS_INPUT_FILE_PATH + \"\\\".\");\n        }\n        return path;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.spark.client.DataClient#persist(java.util.List,\n     * com.impetus.kundera.metadata.model.EntityMetadata,\n     * com.impetus.spark.client.SparkClient)\n     */\n    @Override\n    public boolean persist(List listEntity, EntityMetadata m, SparkClient sparkClient)\n    {\n        Seq s = scala.collection.JavaConversions.asScalaBuffer(listEntity).toList();\n        ClassTag tag = scala.reflect.ClassTag$.MODULE$.apply(m.getEntityClazz());\n        JavaRDD personRDD = sparkClient.sparkContext.parallelize(s, 1, tag).toJavaRDD();\n        DataFrame df = sparkClient.sqlContext.createDataFrame(personRDD, m.getEntityClazz());\n\n        String outputFilePath = getOutputFilePath(sparkClient.properties);\n        String ext = (String) sparkClient.properties.get(\"format\");\n        FileType fileType = FileFormatConstants.extension.get(ext);\n        switch (fileType)\n        {\n        case CSV:\n            return writeDataInCsvFile(df, outputFilePath);\n        case JSON:\n            return writeDataInJsonFile(df, outputFilePath);\n        default:\n            throw new UnsupportedOperationException(\"Files of type \" + ext + \" are not yet supported.\");\n        }\n    }\n\n    /**\n     * Write data in csv file.\n     * \n     * @param df\n     *            the df\n     * @param outputFilePath\n     *            the output file path\n     * @return true, if successful\n     */\n    private boolean writeDataInCsvFile(DataFrame df, String outputFilePath)\n    {\n        // TODO change savemode to APPEND or ErrorIfExists as supported by\n        // latest version\n        df.save(outputFilePath, SparkPropertiesConstants.SOURCE_CSV, SaveMode.Overwrite);\n        return true;\n    }\n\n    /**\n     * Write data in json file.\n     * \n     * @param df\n     *            the df\n     * @param m\n     *            the m\n     * @param outputFilePath\n     *            the output file path\n     * @param sqlContext\n     *            the sql context\n     * @return true, if successful\n     */\n    private boolean writeDataInJsonFile(DataFrame df, String outputFilePath)\n    {\n        // TODO change savemode to APPEND or ErrorIfExists as supported by\n        // latest version\n        df.save(outputFilePath, \"json\", SaveMode.Overwrite);\n        return true;\n    }\n\n    /**\n     * Gets the output file path.\n     * \n     * @param properties\n     *            the properties\n     * @return the output file path\n     */\n    @Override\n    public String getOutputFilePath(Map<String, Object> properties)\n    {\n        String path = (String) properties.get(SparkPropertiesConstants.FS_OUTPUT_FILE_PATH);\n        if (path == null || path.isEmpty())\n        {\n            throw new KunderaException(\n                    \"Please set the path of outputfile while creating EntityManager using the property\" + \"\\\"\"\n                            + SparkPropertiesConstants.FS_OUTPUT_FILE_PATH + \"\\\".\");\n        }\n        return path;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.spark.client.DataClient#saveDataFrame(org.apache.spark.sql\n     * .DataFrame, java.lang.Class, java.util.Map)\n     */\n    @Override\n    public void saveDataFrame(DataFrame dataFrame, Class<?> entityClazz, Map<String, Object> properties)\n    {\n\n        FileType fileType = FileFormatConstants.extension.get(((String) properties.get(\"format\")).toLowerCase());\n        switch (fileType)\n        {\n        case CSV:\n            writeDataInCsvFile(dataFrame, getOutputFilePath(properties));\n            break;\n        case JSON:\n            writeDataInJsonFile(dataFrame, getOutputFilePath(properties));\n            break;\n        default:\n            throw new UnsupportedOperationException(\"Files of type \" + properties.get(\"format\")\n                    + \" are not yet supported.\");\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/client/FileFormatConstants.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * The Class FileFormatConstants.\n * \n * @author devender.yadav\n */\npublic class FileFormatConstants\n{\n\n    /** The Constant extension. */\n    public static final Map<String, FileType> extension = new HashMap<String, FileType>();\n\n    /**\n     * The Enum FileType.\n     */\n    public static enum FileType\n    {\n\n        /** The csv. */\n        CSV,\n        /** The json. */\n        JSON;\n    }\n\n    static\n    {\n        extension.put(\"csv\", FileType.CSV);\n        extension.put(\"json\", FileType.JSON);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/client/FilePathBuilder.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.util.Map;\n\n/**\n * The Class FilePathBuilder.\n * \n * @author devender.yadav\n */\npublic abstract class FilePathBuilder\n{\n\n    /**\n     * Gets the input file path.\n     * \n     * @param properties\n     *            the properties\n     * @return the input file path\n     */\n    abstract String getInputFilePath(Map<String, Object> properties);\n\n    /**\n     * Gets the output file path.\n     * \n     * @param properties\n     *            the properties\n     * @return the output file path\n     */\n    abstract String getOutputFilePath(Map<String, Object> properties);\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/client/HDFSClient.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.util.Map;\n\nimport org.apache.spark.sql.DataFrame;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.spark.constants.SparkPropertiesConstants;\n\n/**\n * The Class HDFSClient.\n * \n * @author: karthikp.manchala\n */\npublic class HDFSClient extends FSClient\n{\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.spark.client.FSClient#getInputFilePath(java.util.Map)\n     */\n    @Override\n    public String getInputFilePath(Map<String, Object> properties)\n    {\n        String path = (String) properties.get(SparkPropertiesConstants.HDFS_INPUT_FILE_PATH);\n        if (path == null || path.isEmpty())\n        {\n            throw new KunderaException(\n                    \"Please set the path of inputfile while creating EntityManager using the property\" + \"\\\"\"\n                            + SparkPropertiesConstants.HDFS_INPUT_FILE_PATH + \"\\\".\");\n        }\n\n        return path;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.spark.client.FSClient#getOutputFilePath(java.util.Map)\n     */\n    @Override\n    public String getOutputFilePath(Map<String, Object> properties)\n    {\n        String path = (String) properties.get(SparkPropertiesConstants.HDFS_OUTPUT_FILE_PATH);\n        if (path == null || path.isEmpty())\n        {\n            throw new KunderaException(\n                    \"Please set the path of outputfile while creating EntityManager using the property\" + \"\\\"\"\n                            + SparkPropertiesConstants.HDFS_OUTPUT_FILE_PATH + \"\\\".\");\n        }\n        return path;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.spark.client.FSClient#saveDataFrame(org.apache.spark.sql.\n     * DataFrame, java.lang.Class, java.util.Map)\n     */\n    @Override\n    public void saveDataFrame(DataFrame dataFrame, Class<?> entityClazz, Map<String, Object> properties)\n    {\n        dataFrame.save(getOutputFilePath(properties), \"json\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/client/SparkClient.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.apache.spark.SparkContext;\nimport org.apache.spark.sql.DataFrame;\nimport org.apache.spark.sql.hive.HiveContext;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.ClientBase;\nimport com.impetus.kundera.client.ClientPropertiesSetter;\nimport com.impetus.kundera.db.RelationHolder;\nimport com.impetus.kundera.generator.Generator;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.context.jointable.JoinTableData;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.spark.constants.SparkQueryConstants;\nimport com.impetus.spark.datahandler.SparkDataHandler;\nimport com.impetus.spark.query.SparkQuery;\n\n/**\n * The Class SparkClient.\n * \n * @author: karthikp.manchala\n */\npublic class SparkClient extends ClientBase implements Client<SparkQuery>, ClientPropertiesSetter\n{\n\n    /** The Constant DATA_CLIENT. */\n    private static final String DATA_CLIENT = \"kundera.client\";\n\n    /** The spark context. */\n    final SparkContext sparkContext;\n\n    /** The sql context. */\n    final HiveContext sqlContext;\n\n    /** The properties. */\n    Map<String, Object> properties = new HashMap<String, Object>();\n\n    /** The reader. */\n    private EntityReader reader;\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(SparkClient.class);\n\n    /** The registered tables. */\n    private static Map<String, Boolean> registeredTables = new HashMap<String, Boolean>();\n\n    /** The data handler. */\n    private SparkDataHandler dataHandler = new SparkDataHandler(kunderaMetadata);\n\n    /**\n     * Instantiates a new spark client.\n     * \n     * @param kunderaMetadata\n     *            the kundera metadata\n     * @param reader\n     *            the reader\n     * @param properties\n     *            the properties\n     * @param persistenceUnit\n     *            the persistence unit\n     * @param sparkContext\n     *            the spark context\n     * @param sqlContext\n     *            the sql context\n     */\n    protected SparkClient(KunderaMetadata kunderaMetadata, EntityReader reader, Map<String, Object> properties,\n            String persistenceUnit, SparkContext sparkContext, HiveContext sqlContext)\n    {\n        super(kunderaMetadata, properties, persistenceUnit);\n        this.reader = reader;\n        this.sparkContext = sparkContext;\n        this.sqlContext = sqlContext;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.lang.Object)\n     */\n    public Object find(Class entityClass, Object key)\n    {\n\n        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);\n\n        String tableName = entityMetadata.getTableName();\n        Class fieldClass = entityMetadata.getIdAttribute().getJavaType();\n        String select_Query = SparkQueryConstants.SELECTALL_QUERY;\n        select_Query = StringUtils.replace(select_Query, SparkQueryConstants.TABLE, tableName);\n        StringBuilder builder = new StringBuilder(select_Query);\n        builder.append(SparkQueryConstants.ADD_WHERE_CLAUSE);\n        builder.append(dataHandler.getColumnName(entityMetadata.getIdAttribute()));\n        builder.append(SparkQueryConstants.EQUALS);\n\n        appendValue(builder, fieldClass, key);\n        List result = this.executeQuery(builder.toString(), entityMetadata, null);\n        return result.isEmpty() ? null : result.get(0);\n    }\n\n    /**\n     * Append value.\n     * \n     * @param builder\n     *            the builder\n     * @param fieldClazz\n     *            the field clazz\n     * @param value\n     *            the value\n     */\n    private void appendValue(StringBuilder builder, Class fieldClazz, Object value)\n    {\n\n        if (fieldClazz != null\n                && value != null\n                && (fieldClazz.isAssignableFrom(String.class) || fieldClazz.isAssignableFrom(char.class)\n                        || fieldClazz.isAssignableFrom(Character.class) || value instanceof Enum))\n        {\n\n            if (fieldClazz.isAssignableFrom(String.class))\n            {\n                // To allow escape character\n                value = ((String) value).replaceAll(\"'\", \"''\");\n            }\n            builder.append(\"'\");\n\n            if (value instanceof Enum)\n            {\n                builder.append(((Enum) value).name());\n            }\n\n            else\n            {\n                builder.append(value);\n            }\n            builder.append(\"'\");\n        }\n        else\n        {\n            builder.append(value);\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#close()\n     */\n    public void close()\n    {\n        registeredTables.clear();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera\n     * .persistence.context.jointable.JoinTableData)\n     */\n    public void persistJoinTable(JoinTableData joinTableData)\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findIdsByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,\n            Object columnValue, Class entityClazz)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#deleteByColumn(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.Object)\n     */\n    public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findByRelation(java.lang.String,\n     * java.lang.Object, java.lang.Class)\n     */\n    public List findByRelation(String colName, Object colValue, Class entityClazz)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getReader()\n     */\n    public EntityReader getReader()\n    {\n        return reader;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getQueryImplementor()\n     */\n    public Class getQueryImplementor()\n    {\n        // TODO Auto-generated method stub\n        return SparkQuery.class;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getIdGenerator()\n     */\n    public Generator getIdGenerator()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.metadata\n     * .model.EntityMetadata, java.lang.Object, java.lang.Object,\n     * java.util.List)\n     */\n    @Override\n    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)\n    {\n        // TODO Auto-generated method stub\n        // handle persist object\n        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(\n                persistenceUnit);\n        String clientName = puMetadata.getProperty(DATA_CLIENT).toLowerCase();\n\n        List listEntity = new ArrayList<>();\n        listEntity.add(entity);\n\n        SparkDataClient dataClient = SparkDataClientFactory.getDataClient(clientName);\n\n        dataClient.persist(listEntity, entityMetadata, this);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.ClientBase#delete(java.lang.Object,\n     * java.lang.Object)\n     */\n    @Override\n    protected void delete(Object entity, Object pKey)\n    {\n        // TODO Auto-generated method stub\n\n    }\n\n    /**\n     * Execute query.\n     * \n     * @param query\n     *            the query\n     * @param m\n     *            the m\n     * @param kunderaQuery\n     *            the kundera query\n     * @return the list\n     */\n    public List executeQuery(String query, EntityMetadata m, KunderaQuery kunderaQuery)\n    {\n        DataFrame dataFrame = getDataFrame(query, m, kunderaQuery);\n\n        // dataFrame.show();\n        return dataHandler.loadDataAndPopulateResults(dataFrame, m, kunderaQuery);\n    }\n\n    /**\n     * Gets the data frame.\n     * \n     * @param query\n     *            the query\n     * @param m\n     *            the m\n     * @param kunderaQuery\n     *            the kundera query\n     * @return the data frame\n     */\n    public DataFrame getDataFrame(String query, EntityMetadata m, KunderaQuery kunderaQuery)\n    {\n        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(\n                persistenceUnit);\n        String clientName = puMetadata.getProperty(DATA_CLIENT).toLowerCase();\n\n        SparkDataClient dataClient = SparkDataClientFactory.getDataClient(clientName);\n        if (registeredTables.get(m.getTableName()) == null || !registeredTables.get(m.getTableName()))\n        {\n            dataClient.registerTable(m, this);\n            registeredTables.put(m.getTableName(), true);\n        }\n        // at this level temp table or table should be ready\n        DataFrame dataFrame = sqlContext.sql(query);\n\n        return dataFrame;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.client.ClientPropertiesSetter#populateClientProperties\n     * (com.impetus.kundera.client.Client, java.util.Map)\n     */\n    @Override\n    public void populateClientProperties(Client client, Map<String, Object> properties)\n    {\n        this.properties.putAll(properties);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#findAll(java.lang.Class,\n     * java.lang.String[], java.lang.Object[])\n     */\n    @Override\n    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#find(java.lang.Class,\n     * java.util.Map)\n     */\n    @Override\n    public <E> List<E> find(Class<E> entityClass, Map<String, String> embeddedColumnMap)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.client.Client#getColumnsById(java.lang.String,\n     * java.lang.String, java.lang.String, java.lang.String, java.lang.Object,\n     * java.lang.Class)\n     */\n    @Override\n    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName, String columnName,\n            Object pKeyColumnValue, Class columnJavaType)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/client/SparkClientFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.util.Enumeration;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.apache.spark.SparkConf;\nimport org.apache.spark.SparkContext;\nimport org.apache.spark.sql.hive.HiveContext;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection;\nimport com.impetus.kundera.configure.ClientProperties.DataStore.Connection.Server;\nimport com.impetus.kundera.configure.schema.api.SchemaManager;\nimport com.impetus.kundera.loader.GenericClientFactory;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.spark.client.SparkPropertyReader.SparkSchemaMetadata;\nimport com.impetus.spark.query.SparkEntityReader;\n\n/**\n * A factory for creating SparkClient objects.\n * \n * @author: karthikp.manchala\n */\npublic class SparkClientFactory extends GenericClientFactory\n{\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(SparkClientFactory.class);\n\n    /** The sparkconf. */\n    private SparkConf sparkconf;\n\n    /** The spark context. */\n    private SparkContext sparkContext;\n\n    /** The sql context. */\n    private HiveContext sqlContext;\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.ClientFactory#getSchemaManager(java.util.Map)\n     */\n    public SchemaManager getSchemaManager(Map<String, Object> puProperties)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n   \n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initialize(java.util.Map)\n     */\n    @Override\n    public void initialize(Map<String, Object> puProperties)\n    {\n        reader = new SparkEntityReader(kunderaMetadata);\n        setExternalProperties(puProperties);\n        initializePropertyReader();\n        PersistenceUnitMetadata pum = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(\n                getPersistenceUnit());\n        sparkconf = new SparkConf(true);\n        configureClientProperties(pum);\n        sparkContext = new SparkContext(sparkconf);\n        sqlContext = new HiveContext(sparkContext);\n    }\n\n    /**\n     * Configure client properties.\n     * \n     * @param puMetadata\n     *            the pu metadata\n     */\n    private void configureClientProperties(PersistenceUnitMetadata puMetadata)\n    {\n        SparkSchemaMetadata metadata = SparkPropertyReader.ssmd;\n        ClientProperties cp = metadata != null ? metadata.getClientProperties() : null;\n        if (cp != null)\n        {\n            DataStore dataStore = metadata != null ? metadata.getDataStore(puMetadata.getProperty(\"kundera.client\"))\n                    : null;\n            List<Server> servers = dataStore != null && dataStore.getConnection() != null ? dataStore.getConnection()\n                    .getServers() : null;\n\n            if (servers!=null && !servers.isEmpty())\n            {\n                Server server = servers.get(0);\n                sparkconf.set(\"hostname\", server.getHost());\n                sparkconf.set(\"portname\", server.getPort());\n            }\n\n            Connection conn = dataStore.getConnection();\n\n            Properties props = conn.getProperties();\n\n            Enumeration e = props.propertyNames();\n\n            while (e.hasMoreElements())\n            {\n                String key = (String) e.nextElement();\n                sparkconf.set(key, props.getProperty(key));\n            }\n        }\n    }\n\n    /**\n     * Initialize property reader.\n     */\n    private void initializePropertyReader()\n    {\n        if (propertyReader == null)\n        {\n            propertyReader = new SparkPropertyReader(externalProperties, kunderaMetadata.getApplicationMetadata()\n                    .getPersistenceUnitMetadata(getPersistenceUnit()));\n            propertyReader.read(getPersistenceUnit());\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#createPoolOrConnection()\n     */\n    @Override\n    protected Object createPoolOrConnection()\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#instantiateClient(java\n     * .lang.String)\n     */\n    @Override\n    protected Client instantiateClient(String persistenceUnit)\n    {\n        \n        return new SparkClient(kunderaMetadata, reader, externalProperties, persistenceUnit, sparkContext, sqlContext);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.GenericClientFactory#isThreadSafe()\n     */\n    @Override\n    public boolean isThreadSafe()\n    {\n        \n        return false;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.loader.GenericClientFactory#initializeLoadBalancer\n     * (java.lang.String)\n     */\n    @Override\n    protected void initializeLoadBalancer(String loadBalancingPolicyName)\n    {\n        // TODO Auto-generated method stub\n\n    }\n    \n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.loader.ClientLifeCycleManager#destroy()\n     */\n    @Override\n    public void destroy()\n    {\n        indexManager.close();\n        if (schemaManager != null)\n        {\n            schemaManager.dropSchema();\n        }\n        if (sparkContext != null)\n        {\n            logger.info(\"Closing connection to spark.\");\n            sparkContext.stop();\n            logger.info(\"Closed connection to spark.\");\n        }\n        else\n        {\n            logger.warn(\"Can't close connection to Spark, it was already disconnected\");\n        }\n        externalProperties = null;\n        schemaManager = null;\n    }\n\n\n}"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/client/SparkDataClient.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.spark.sql.DataFrame;\n\nimport com.impetus.kundera.metadata.model.EntityMetadata;\n\n/**\n * The Interface DataClient.\n * \n * @author: karthikp.manchala\n */\npublic interface SparkDataClient\n{\n\n    /**\n     * Register table.\n     * \n     * @param m\n     *            the m\n     * @param sparkClient\n     *            the spark client\n     */\n    void registerTable(EntityMetadata m, SparkClient sparkClient);\n\n    /**\n     * Persist.\n     * \n     * @param listEntity\n     *            the list entity\n     * @param m\n     *            the m\n     * @param sparkClient\n     *            the spark client\n     * @return true, if successful\n     */\n    boolean persist(List listEntity, EntityMetadata m, SparkClient sparkClient);\n\n    /**\n     * Save data frame.\n     * \n     * @param dataFrame\n     *            the data frame\n     * @param entityClazz\n     *            the entity clazz\n     * @param properties\n     *            the properties\n     */\n    void saveDataFrame(DataFrame dataFrame, Class<?> entityClazz, Map<String, Object> properties);\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/client/SparkDataClientFactory.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * A factory for creating DataClient objects.\n * \n * @author: karthikp.manchala\n */\npublic class SparkDataClientFactory\n{\n\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(SparkDataClientFactory.class);\n\n    /** The client pool. */\n    private static Map<String, SparkDataClient> clientPool = new HashMap<String, SparkDataClient>();\n\n    /** The client name to class. */\n    private static Map<String, String> clientNameToClass = new HashMap<String, String>();\n    static\n    {\n        clientNameToClass.put(\"teradata\", \"com.impetus.spark.client.TeradataSparkClient\");\n        clientNameToClass.put(\"cassandra\", \"com.impetus.spark.client.CassSparkClient\");\n        clientNameToClass.put(\"mongodb\", \"com.impetus.spark.client.MongoSparkClient\");\n        clientNameToClass.put(\"hdfs\", \"com.impetus.spark.client.HDFSClient\");\n        clientNameToClass.put(\"fs\", \"com.impetus.spark.client.FSClient\");\n        clientNameToClass.put(\"hive\", \"com.impetus.spark.client.HiveSparkClient\");\n    }\n\n    /**\n     * Gets the data client.\n     * \n     * @param clientName\n     *            the client name\n     * @return the data client\n     */\n    public static SparkDataClient getDataClient(String clientName)\n    {\n\n        if (clientPool.get(clientName) != null)\n        {\n            return clientPool.get(clientName);\n        }\n        try\n        {\n            SparkDataClient dataClient = (SparkDataClient) KunderaCoreUtils.createNewInstance(Class\n                    .forName(clientNameToClass.get(clientName)));\n            clientPool.put(clientName, dataClient);\n            return dataClient;\n        }\n        catch (Exception e)\n        {\n            logger.error(clientName\n                    + \" client is invalid/not supported. Please check kundera.client in persistence properties.\");\n            throw new KunderaException(clientName\n                    + \" client is invalid/not supported. Please check kundera.client in persistence properties.\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/client/SparkPropertyReader.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.util.Map;\n\nimport com.impetus.kundera.configure.AbstractPropertyReader;\nimport com.impetus.kundera.configure.ClientProperties;\nimport com.impetus.kundera.configure.ClientProperties.DataStore;\nimport com.impetus.kundera.configure.PropertyReader;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * The Class SparkPropertyReader.\n * \n * @author devender.yadav\n */\npublic class SparkPropertyReader extends AbstractPropertyReader implements PropertyReader\n{\n\n    /** The ssmd. */\n    public static SparkSchemaMetadata ssmd;\n\n    /**\n     * Instantiates a new spark property reader.\n     * \n     * @param externalProperties\n     *            the external properties\n     * @param puMetadata\n     *            the pu metadata\n     */\n    public SparkPropertyReader(Map externalProperties, final PersistenceUnitMetadata puMetadata)\n    {\n        super(externalProperties, puMetadata);\n        ssmd = new SparkSchemaMetadata();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.configure.AbstractPropertyReader#onXml(com.impetus\n     * .kundera.configure.ClientProperties)\n     */\n    public void onXml(ClientProperties cp)\n    {\n        if (cp != null)\n        {\n            ssmd.setClientProperties(cp);\n        }\n    }\n\n    /**\n     * The Class SparkSchemaMetadata.\n     */\n    public class SparkSchemaMetadata\n    {\n\n        /** The client properties. */\n        private ClientProperties clientProperties;\n\n        /**\n         * Instantiates a new spark schema metadata.\n         */\n        public SparkSchemaMetadata()\n        {\n\n        }\n\n        /**\n         * Gets the client properties.\n         * \n         * @return the clientProperties\n         */\n        public ClientProperties getClientProperties()\n        {\n            return clientProperties;\n        }\n\n        /**\n         * Sets the client properties.\n         * \n         * @param clientProperties\n         *            the clientProperties to set\n         */\n        private void setClientProperties(ClientProperties clientProperties)\n        {\n            this.clientProperties = clientProperties;\n        }\n\n        /**\n         * Gets the data store.\n         * \n         * @param datastore\n         *            the datastore\n         * @return the data store\n         */\n        public DataStore getDataStore(String datastore)\n        {\n            if (getClientProperties() != null && getClientProperties().getDatastores() != null)\n            {\n                for (DataStore dataStore : getClientProperties().getDatastores())\n                {\n                    if (dataStore.getName() != null && dataStore.getName().trim().equalsIgnoreCase(datastore))\n                    {\n                        return dataStore;\n                    }\n                }\n            }\n            return null;\n        }\n\n    }\n}"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/constants/SparkPropertiesConstants.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.constants;\n\n/**\n * The Class PropertiesConstants.\n * \n * @author: karthikp.manchala\n */\npublic final class SparkPropertiesConstants\n{\n    /** The Constant FS_OUTPUT_FILE_PATH. */\n    public static final String FS_OUTPUT_FILE_PATH = \"kundera.fs.outputfile.path\";\n\n    /** The Constant FS_INPUT_FILE_PATH. */\n    public static final String FS_INPUT_FILE_PATH = \"kundera.fs.inputfile.path\";\n\n    /** The Constant HDFS_OUTPUT_FILE_PATH. */\n    public static final String HDFS_OUTPUT_FILE_PATH = \"kundera.hdfs.outputfile.path\";\n\n    /** The Constant HDFS_INPUT_FILE_PATH. */\n    public static final String HDFS_INPUT_FILE_PATH = \"kundera.hdfs.inputfile.path\";\n\n    /** The Constant HDFS_CONNECTION_PORT. */\n    public static final String HDFS_CONNECTION_PORT = \"kundera.hdfs.connection.port\";\n\n    /** The Constant HDFS_CONNECTION_HOST. */\n    public static final String HDFS_CONNECTION_HOST = \"kundera.hdfs.connection.host\";\n\n    /** The Constant SOURCE_CSV. */\n    public static final String SOURCE_CSV = \"com.databricks.spark.csv\";\n\n    /** The Constant SOURCE_CASSANDRA. */\n    public static final String SOURCE_CASSANDRA = \"org.apache.spark.sql.cassandra\";\n\n    /** The Constant CLIENT_CASSANDRA. */\n    public static final String CLIENT_CASSANDRA = \"cassandra\";\n\n    /** The Constant CLIENT_FS. */\n    public static final String CLIENT_FS = \"fs\";\n\n    /** The Constant CLIENT_HDFS. */\n    public static final String CLIENT_HDFS = \"hdfs\";\n\n    /** The Constant CLIENT_MONGODB. */\n    public static final String CLIENT_MONGODB = \"mongodb\";\n\n    /** The Constant CLIENT_HIVE. */\n    public static final String CLIENT_HIVE = \"hive\";\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/constants/SparkQueryConstants.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.constants;\n\n\n/**\n * The Class QueryConstants.\n * \n * @author: karthikp.manchala\n */\npublic final class SparkQueryConstants\n{\n\n    /** The Constant SELECTALL_QUERY. */\n    public static final String SELECTALL_QUERY = \"SELECT * FROM $TABLE\";\n\n    /** The Constant ADD_WHERE_CLAUSE. */\n    public static final String ADD_WHERE_CLAUSE = \" WHERE \";\n\n    /** The Constant TABLE. */\n    public static final String TABLE = \"$TABLE\";\n\n    /** The Constant EQUALS. */\n    public static final String EQUALS = \" = \";\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/datahandler/SparkDataHandler.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.datahandler;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.metamodel.Attribute;\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.SingularAttribute;\n\nimport org.apache.spark.sql.DataFrame;\nimport org.apache.spark.sql.Row;\n\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.type.AbstractManagedType;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.property.PropertyAccessException;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.utils.KunderaCoreUtils;\n\n/**\n * The Class SparkDataHandler.\n * \n * @author: pragalbh.garg\n */\npublic class SparkDataHandler\n{\n\n    /** The kundera metadata. */\n    private KunderaMetadata kunderaMetadata;\n\n    /**\n     * Instantiates a new spark data handler.\n     * \n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public SparkDataHandler(KunderaMetadata kunderaMetadata)\n    {\n        this.kunderaMetadata = kunderaMetadata;\n    }\n\n    /**\n     * Load data and populate results.\n     * \n     * @param dataFrame\n     *            the data frame\n     * @param m\n     *            the m\n     * @param kunderaQuery\n     *            the kundera query\n     * @return the list\n     */\n    public List<?> loadDataAndPopulateResults(DataFrame dataFrame, EntityMetadata m, KunderaQuery kunderaQuery)\n    {\n        if (kunderaQuery != null && kunderaQuery.isAggregated())\n        {\n            return dataFrame.collectAsList();\n        }\n        // TODO: handle the case of specific field selection\n        else\n        {\n            return populateEntityObjectsList(dataFrame, m);\n        }\n    }\n\n    /**\n     * Populate entity objects list.\n     * \n     * @param dataFrame\n     *            the data frame\n     * @param m\n     *            the m\n     * @return the list\n     */\n    private List<?> populateEntityObjectsList(DataFrame dataFrame, EntityMetadata m)\n    {\n        List results = new ArrayList();\n        String[] columns = dataFrame.columns();\n        Map<String, Integer> map = createMapOfColumnIndex(columns);\n        for (Row row : dataFrame.collectAsList())\n        {\n            Object entity = populateEntityFromDataFrame(m, map, row);\n            results.add(entity);\n        }\n        return results;\n    }\n\n    /**\n     * Populate entity from data frame.\n     * \n     * @param m\n     *            the m\n     * @param columnIndexMap\n     *            the column index map\n     * @param row\n     *            the row\n     * @return the object\n     */\n    private Object populateEntityFromDataFrame(EntityMetadata m, Map<String, Integer> columnIndexMap, Row row)\n    {\n        try\n        {\n            // create entity instance\n            Object entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());\n            // handle relations\n            Map<String, Object> relations = new HashMap<String, Object>();\n            if (entity.getClass().isAssignableFrom(EnhanceEntity.class))\n            {\n                relations = ((EnhanceEntity) entity).getRelations();\n                entity = ((EnhanceEntity) entity).getEntity();\n            }\n            // get a Set of attributes\n            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(\n                    m.getPersistenceUnit());\n            EntityType entityType = metaModel.entity(m.getEntityClazz());\n            Set<Attribute> attributes = ((AbstractManagedType) entityType).getAttributes();\n            // iterate over attributes and find its value\n            for (Attribute attribute : attributes)\n            {\n                String columnName = getColumnName(attribute);\n                Object columnValue = row.get(columnIndexMap.get(columnName));\n                if (columnValue != null)\n                {\n                    Object value = PropertyAccessorHelper.fromSourceToTargetClass(attribute.getJavaType(),\n                            columnValue.getClass(), columnValue);\n\n                    PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), value);\n                }\n            }\n            // find the value of @Id field for EnhanceEntity\n            SingularAttribute attrib = m.getIdAttribute();\n            Object rowKey = PropertyAccessorHelper.getObject(entity, (Field) attrib.getJavaMember());\n            if (!relations.isEmpty())\n            {\n                return new EnhanceEntity(entity, rowKey, relations);\n            }\n            return entity;\n        }\n        catch (PropertyAccessException e1)\n        {\n            throw new RuntimeException(e1);\n        }\n    }\n\n    /**\n     * Gets the column name.\n     * \n     * @param attribute\n     *            the attribute\n     * @return the column name\n     */\n    public String getColumnName(Attribute attribute)\n    {\n        return attribute.getName();\n    }\n\n    /**\n     * Creates the map of column index.\n     * \n     * @param columns\n     *            the columns\n     * @return the map\n     */\n    private Map<String, Integer> createMapOfColumnIndex(String[] columns)\n    {\n        int i = 0;\n        Map<String, Integer> map = new HashMap<String, Integer>();\n        for (String column : columns)\n        {\n            map.put(column, i++);\n        }\n        return map;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/query/SparkEntityReader.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.query;\n\nimport java.util.List;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.EnhanceEntity;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.AbstractEntityReader;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\n\n/**\n * The Class SparkEntityReader.\n * \n * @author: karthikp.manchala\n */\npublic class SparkEntityReader extends AbstractEntityReader implements EntityReader\n{\n\n    /**\n     * Instantiates a new spark entity reader.\n     * \n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public SparkEntityReader(KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.AbstractEntityReader#findById(java.lang\n     * .Object, com.impetus.kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)\n    {\n        return super.findById(primaryKey, m, client);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.persistence.EntityReader#populateRelation(com.impetus\n     * .kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client, int)\n     */\n    @Override\n    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)\n    {\n        // TODO Auto-generated method stub\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/main/java/com/impetus/spark/query/SparkQuery.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.query;\n\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.apache.spark.sql.DataFrame;\nimport org.eclipse.persistence.jpa.jpql.parser.AggregateFunction;\nimport org.eclipse.persistence.jpa.jpql.parser.Expression;\nimport org.eclipse.persistence.jpa.jpql.parser.SelectClause;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.metadata.model.ApplicationMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.persistence.EntityReader;\nimport com.impetus.kundera.persistence.PersistenceDelegator;\nimport com.impetus.kundera.query.KunderaQuery;\nimport com.impetus.kundera.query.Query;\nimport com.impetus.kundera.query.QueryHandlerException;\nimport com.impetus.kundera.query.QueryImpl;\nimport com.impetus.spark.client.SparkClient;\nimport com.impetus.spark.client.SparkDataClient;\nimport com.impetus.spark.client.SparkDataClientFactory;\nimport com.impetus.spark.constants.SparkPropertiesConstants;\n\n/**\n * The Class SparkQuery.\n * \n * @author: karthikp.manchala\n */\npublic class SparkQuery extends QueryImpl implements Query\n{\n\n    /** the log used by this class. */\n    private static Logger logger = LoggerFactory.getLogger(SparkQuery.class);\n\n    /**\n     * Instantiates a new spark query.\n     * \n     * @param kunderaQuery\n     *            the kundera query\n     * @param persistenceDelegator\n     *            the persistence delegator\n     * @param kunderaMetadata\n     *            the kundera metadata\n     */\n    public SparkQuery(KunderaQuery kunderaQuery, PersistenceDelegator persistenceDelegator,\n            final KunderaMetadata kunderaMetadata)\n    {\n        super(kunderaQuery, persistenceDelegator, kunderaMetadata);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List populateEntities(EntityMetadata m, Client client)\n    {\n        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();\n        try\n        {\n            String query = appMetadata.getQuery(getJPAQuery());\n            if (kunderaQuery.isNative())\n            {\n                // Native Query Support is enabled\n                kunderaQuery.setAggregated(isAggregatedQuery());\n                return ((SparkClient) client).executeQuery(query == null ? getJPAQuery() : query, m, kunderaQuery);\n            }\n        }\n        catch (Exception e)\n        {\n\n            logger.error(\"Error during executing query, Caused by:\", e);\n            throw new QueryHandlerException(e);\n        }\n        return null;\n    }\n\n    /**\n     * Parses the insert into query.\n     * \n     * @param query\n     *            the query\n     * @return the map\n     */\n    private Map<String, Object> parseInsertIntoQuery(String query)\n    {\n        Map<String, Object> persistDetails = new HashMap<String, Object>();\n        String insertReg = \"(?i)^insert\\\\s+into\\\\s+(\\\\S+)\\\\s+(?:as\\\\s+(\\\\S+)\\\\s+)?FROM\\\\s+\\\\((.*)\\\\)$\";\n        Pattern r = Pattern.compile(insertReg);\n\n        Matcher m = r.matcher(query);\n        if (m.find())\n        {\n            try\n            {\n                parsePersistClause(m.group(1), persistDetails);\n                persistDetails.put(\"format\", m.group(2));\n                persistDetails.put(\"fetchQuery\", m.group(3));\n            }\n            catch (Exception e)\n            {\n                throw new KunderaException(\"Invalid Query\");\n            }\n        }\n        else\n        {\n            throw new KunderaException(\"Invalid Query\");\n        }\n\n        return persistDetails;\n    }\n\n    /**\n     * Parses the persist clause.\n     * \n     * @param persistClause\n     *            the persist clause\n     * @param persistDetails\n     *            the persist details\n     * @return the map\n     * @throws KunderaException\n     *             the kundera exception\n     */\n    private Map<String, Object> parsePersistClause(String persistClause, Map<String, Object> persistDetails)\n            throws KunderaException\n    {\n        Pattern pattern = Pattern.compile(\"^([^.]+)\\\\.(?:([^.]+)\\\\.([^.]+)|\\\\[([^\\\\]]+)\\\\])$\");\n        Matcher matcher = pattern.matcher(persistClause);\n\n        if (matcher.find())\n        {\n\n            persistDetails.put(\"client\", matcher.group(1));\n\n            switch (matcher.group(1).toLowerCase())\n            {\n\n            case SparkPropertiesConstants.CLIENT_CASSANDRA:\n                persistDetails.put(\"keyspace\", matcher.group(2));\n                persistDetails.put(\"table\", matcher.group(3));\n                break;\n\n            case SparkPropertiesConstants.CLIENT_FS:\n                persistDetails.put(SparkPropertiesConstants.FS_OUTPUT_FILE_PATH, matcher.group(4));\n                break;\n\n            case SparkPropertiesConstants.CLIENT_HDFS:\n                persistDetails.put(SparkPropertiesConstants.HDFS_OUTPUT_FILE_PATH, matcher.group(4));\n                break;\n            case SparkPropertiesConstants.CLIENT_HIVE:\n                persistDetails.put(\"keyspace\", matcher.group(2));\n                persistDetails.put(\"table\", matcher.group(3));\n                break;\n\n            default:\n                throw new UnsupportedOperationException(\"Not Supported for this client\");\n            }\n        }\n        else\n        {\n            throw new KunderaException(\"Invalid Query\");\n        }\n\n        return persistDetails;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#findUsingLucene(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List findUsingLucene(EntityMetadata m, Client client)\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.query.QueryImpl#recursivelyPopulateEntities(com.impetus\n     * .kundera.metadata.model.EntityMetadata,\n     * com.impetus.kundera.client.Client)\n     */\n    @Override\n    protected List recursivelyPopulateEntities(EntityMetadata m, Client client)\n    {\n        throw new KunderaException(\"Query on entities having relations is currently not supported in kundera-spark.\");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#getReader()\n     */\n    @Override\n    protected EntityReader getReader()\n    {\n        return null;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()\n     */\n    @Override\n    protected int onExecuteUpdate()\n    {\n        Map<String, Object> persistDetails = new HashMap<String, Object>();\n        DataFrame dataFrame;\n        try\n        {\n            String query = getJPAQuery();// .toLowerCase();\n\n            persistDetails = parseInsertIntoQuery(query);\n\n            dataFrame = getDataFrameToPersist(query, (String) persistDetails.get(\"fetchQuery\"));\n\n            String clientName = (String) persistDetails.get(\"client\");\n\n            SparkDataClient dataClient = SparkDataClientFactory.getDataClient(clientName);\n            dataClient.saveDataFrame(dataFrame, getEntityMetadata().getEntityClazz(), persistDetails);\n        }\n        catch (Exception e)\n        {\n            logger.error(\"Error during executing query, Caused by:\", e);\n            throw new QueryHandlerException(e);\n        }\n\n        return getDataFrameSize(dataFrame);\n    }\n\n    /**\n     * Gets the data frame size.\n     * \n     * @param dataFrame\n     *            the data frame\n     * @return the data frame size\n     */\n    public int getDataFrameSize(DataFrame dataFrame)\n    {\n        long l = dataFrame != null ? dataFrame.count() : 0;\n        if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE)\n        {\n            logger.error(l + \" cannot be cast to int without changing its value.\");\n            return 0;\n        }\n        return (int) l;\n    }\n\n    /**\n     * Gets the data frame to persist.\n     * \n     * @param query\n     *            the query\n     * @param subQuery\n     *            the sub query\n     * @return the data frame to persist\n     */\n    private DataFrame getDataFrameToPersist(String query, String subQuery)\n    {\n        EntityMetadata entityMetadata = getEntityMetadata();\n\n        Client client = entityMetadata != null ? persistenceDelegeator.getClient(entityMetadata)\n                : persistenceDelegeator.getClient(kunderaQuery.getPersistenceUnit());\n\n        return ((SparkClient) client).getDataFrame(subQuery, entityMetadata, getKunderaQuery());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#close()\n     */\n    @Override\n    public void close()\n    {\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.query.QueryImpl#iterate()\n     */\n    @Override\n    public Iterator iterate()\n    {\n        return null;\n    }\n\n    /**\n     * Checks if is aggregated query.\n     * \n     * @return true, if is aggregated query\n     */\n    boolean isAggregatedQuery()\n    {\n        if (kunderaQuery.getSelectStatement() != null)\n        {\n            Expression exp = ((SelectClause) kunderaQuery.getSelectStatement().getSelectClause()).getSelectExpression();\n            return AggregateFunction.class.isAssignableFrom(exp.getClass());\n        }\n        else\n        {\n            return false;\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/test/java/com/impetus/client/spark/entities/Person.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.spark.entities;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class Person.\n * \n * @author: karthikp.manchala\n */\n@Entity\n@Table(name = \"spark_person\")\n@IndexCollection(columns = { @Index(name = \"personName\"), @Index(name = \"age\"), @Index(name = \"salary\") })\npublic class Person implements Serializable\n{\n\n    /** The Constant serialVersionUID. */\n    private static final long serialVersionUID = 1L;\n\n    /** The person id. */\n    @Id\n    private String personId;\n\n    /** The person name. */\n    private String personName;\n\n    /** The age. */\n    private long age;\n\n    /** The salary. */\n    private Double salary;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Gets the age.\n     * \n     * @return the age\n     */\n    public long getAge()\n    {\n        return age;\n    }\n\n    /**\n     * Sets the age.\n     * \n     * @param age\n     *            the new age\n     */\n    public void setAge(long age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * Gets the salary.\n     * \n     * @return the salary\n     */\n    public Double getSalary()\n    {\n        return salary;\n    }\n\n    /**\n     * Sets the salary.\n     * \n     * @param salary\n     *            the new salary\n     */\n    public void setSalary(Double salary)\n    {\n        this.salary = salary;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/test/java/com/impetus/client/spark/tests/SparkBaseTest.java",
    "content": "package com.impetus.client.spark.tests;\n\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport com.impetus.client.spark.entities.Person;\n\n\n/**\n * The Class SparkBaseTest.\n */\npublic abstract class SparkBaseTest\n{\n\n \n    /**\n     * Gets the person.\n     *\n     * @param id the id\n     * @param name the name\n     * @param age the age\n     * @param salary the salary\n     * @return the person\n     */\n    public Person getPerson(String id, String name, Integer age, Double salary)\n    {\n        Person person = new Person();\n        person.setAge(age);\n        person.setPersonId(id);\n        person.setPersonName(name);\n        person.setSalary(salary);\n        return person;\n    }\n    \n    /**\n     * Validate person1.\n     *\n     * @param person the person\n     */\n    public void validatePerson1(Person person)\n    {\n        Assert.assertNotNull(person);\n        Assert.assertEquals(\"dev\", person.getPersonName());\n        Assert.assertEquals(22, person.getAge());\n        Assert.assertEquals(30000.5, person.getSalary());\n    }\n\n    /**\n     * Validate person2.\n     *\n     * @param person the person\n     */\n    public void validatePerson2(Person person)\n    {\n        Assert.assertNotNull(person);\n        Assert.assertEquals(\"pg\", person.getPersonName());\n        Assert.assertEquals(23, person.getAge());\n        Assert.assertEquals(40000.6, person.getSalary());\n    }\n\n    /**\n     * Validate person3.\n     *\n     * @param person the person\n     */\n    public void validatePerson3(Person person)\n    {\n        Assert.assertNotNull(person);\n        Assert.assertEquals(\"kpm\", person.getPersonName());\n        Assert.assertEquals(24, person.getAge());\n        Assert.assertEquals(50000.7, person.getSalary());\n    }\n\n    /**\n     * Assert results.\n     *\n     * @param results the results\n     * @param foundPerson1 the found person1\n     * @param foundPerson2 the found person2\n     * @param foundPerson3 the found person3\n     */\n    public void assertResults(List<Person> results, boolean foundPerson1, boolean foundPerson2,\n            boolean foundPerson3)\n    {\n        for (Person person : results)\n        {\n            switch (person.getPersonId())\n            {\n            case \"1\":\n                if (foundPerson1)\n                    validatePerson1(person);\n                else\n                    Assert.fail();\n                break;\n            case \"2\":\n                if (foundPerson2)\n                    validatePerson2(person);\n                else\n                    Assert.fail();\n                break;\n            case \"3\":\n                if (foundPerson3)\n                    validatePerson3(person);\n                else\n                    Assert.fail();\n                break;\n            }\n        }\n    }\n\n    \n    \n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/test/java/com/impetus/client/spark/tests/SparkCsvInsertionTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.spark.tests;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.spark.entities.Person;\nimport com.impetus.client.spark.utils.SparkTestingUtils;\n\n/**\n * The Class SparkCsvCrudTest.\n */\npublic class SparkCsvInsertionTest extends SparkBaseTest\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The entity manager. */\n    private EntityManager em;\n\n    /** The Constant PU. */\n    private static final String PU = \"spark_fs_pu\";\n\n    /** The Constant OUTPUT_FILE_DIR. */\n    private static final String OUTPUT_FILE_DIR = \"src/test/resources/csv_output/\";\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n        em.setProperty(\"kundera.fs.outputfile.path\", OUTPUT_FILE_DIR);\n        em.setProperty(\"format\", \"csv\");\n    }\n\n    /**\n     * Crud test.\n     */\n    @Test\n    public void testInsert()\n    {\n        Person person1 = getPerson(\"1\", \"dev\", 22, 30000.5);\n        em.persist(person1);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        SparkTestingUtils.recursivelyCleanDir(OUTPUT_FILE_DIR);\n        emf.close();\n        SparkTestingUtils.recursivelyCleanDir(System.getProperty(\"user.dir\")+\"/metastore_db\");\n        emf = null;\n    }\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/test/java/com/impetus/client/spark/tests/SparkCsvQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.spark.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.spark.entities.Person;\nimport com.impetus.client.spark.utils.SparkTestingUtils;\n\n/**\n * The Class SparkCsvQueryTest.\n */\npublic class SparkCsvQueryTest extends SparkBaseTest\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The entity manager. */\n    private EntityManager em;\n\n    /** The pu. */\n    private static final String PU = \"spark_fs_pu\";\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n        em.setProperty(\"kundera.fs.inputfile.path\", \"src/test/resources/test.csv\");\n        em.setProperty(\"format\", \"csv\");\n    }\n\n    /**\n     * Query test.\n     */\n    @Test\n    public void queryTest()\n    {\n        List<Person> results = em.createNativeQuery(\"select * from spark_person\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        assertResults(results, true, true, true);\n\n        results = em.createNativeQuery(\"select * from spark_person where salary > 35000\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, false, true, true);\n\n        results = em.createNativeQuery(\"select * from spark_person where salary > 35000 and age = 23\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        assertResults(results, false, true, false);\n\n        results = em.createNativeQuery(\"select * from spark_person where personName like 'kp%'\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        assertResults(results, false, false, true);\n\n        List aggregateResults = em.createNativeQuery(\"select sum(salary) from spark_person\").getResultList();\n        Assert.assertNotNull(aggregateResults);\n\n        aggregateResults = em.createNativeQuery(\"select count(*) from spark_person where salary > 30000\")\n                .getResultList();\n        Assert.assertNotNull(aggregateResults.size());\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        SparkTestingUtils.recursivelyCleanDir(System.getProperty(\"user.dir\")+\"/metastore_db\");\n        emf = null;\n        \n    }\n    \n   \n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/test/java/com/impetus/client/spark/tests/SparkHDFSClientTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.spark.tests;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.spark.entities.Person;\nimport com.impetus.client.spark.utils.SparkTestingUtils;\n\n/**\n * The Class SparkHDFSClientTest.\n * \n * @author amitkumar\n */\npublic class SparkHDFSClientTest extends SparkBaseTest\n{\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The entity manager. */\n    private EntityManager em;\n\n    /** The pu. */\n    private static final String PU = \"spark_hdfs_pu\";\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n        em.setProperty(\"kundera.hdfs.outputfile.path\", \"hdfs://localhost:9000/sparkInputTest/input\");\n        em.setProperty(\"kundera.hdfs.inputfile.path\", \"hdfs://localhost:9000/sparkInputTest/input\");\n        em.setProperty(\"format\", \"json\");\n    }\n\n    /**\n     * Spark hdfs test.\n     */\n    @Test\n    public void sparkHdfsTest()\n    {\n        testPersist();\n        testQuery();\n        testSaveIntermediateResult();\n    }\n\n    public void testPersist()\n    {\n        Person person1 = getPerson(\"1\", \"dev\", 22, 30000.5);\n\n        em.persist(person1);\n        em.clear();\n        Person p = em.find(Person.class, \"1\");\n        validatePerson1(p);\n    }\n\n    /**\n     * Test query.\n     */\n    public void testQuery()\n    {\n        List<Person> results = em.createNativeQuery(\"select * from spark_person\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        validatePerson1(results.get(0));\n    }\n\n    /**\n     * Test save intermediate result.\n     */\n    public void testSaveIntermediateResult()\n    {\n        String sqlString = \"INSERT INTO fs.[src/test/resources/testspark_csv] AS CSV FROM (select * from spark_person)\";\n        Query q = em.createNativeQuery(sqlString, Person.class);\n        q.executeUpdate();\n\n        sqlString = \"INSERT INTO fs.[src/test/resources/testspark_json] AS JSON FROM (select * from spark_person)\";\n        q = em.createNativeQuery(sqlString, Person.class);\n        q.executeUpdate();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        SparkTestingUtils.recursivelyCleanDir(\"src/test/resources/testspark_json\");\n        SparkTestingUtils.recursivelyCleanDir(\"src/test/resources/testspark_csv\");\n        emf.close();\n        SparkTestingUtils.recursivelyCleanDir(System.getProperty(\"user.dir\")+\"/metastore_db\");\n        emf = null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/test/java/com/impetus/client/spark/utils/SparkTestingUtils.java",
    "content": "/**\n * Copyright 2015 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.client.spark.utils;\n\nimport java.io.File;\n\n/**\n * Provides utility methods for test cases.\n * \n * @author Pragalbh Garg\n */\npublic class SparkTestingUtils\n{\n\n    /**\n     * Recursively clean dir.\n     * \n     * @param targetDirPath\n     *            the target dir path\n     */\n    public static void recursivelyCleanDir(final String targetDirPath)\n    {\n        if (targetDirPath != null && targetDirPath.length() > 0)\n        {\n            File targetDir = new File(targetDirPath);\n            // Get all files in directory\n            File[] files = targetDir.listFiles();\n            if (files != null)\n            {\n                for (File file : files)\n                {\n                    if (file.isDirectory() && !(file.list().length == 0))\n                    {\n\n                        recursivelyCleanDir(file.getPath());\n                        file.delete();\n                    }\n                    else\n                    {\n                        file.delete();\n                    }\n\n                }\n            }\n            targetDir.delete();\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/test/resources/KunderaSparkTest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\n\t<datastores>\n\n\t\t<dataStore>\n\t\t\t<name>hdfs</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"spark.master\" value=\"local\"></property>\n\t\t\t\t\t<property name=\"spark.app.name\" value=\"sparkhdfs\"></property>\n\t\t\t\t\t<property name=\"spark.executor.memory\" value=\"1g\"></property>\n<!-- \t\t\t\t\t<property name=\"spark.driver.allowMultipleContexts\" value=\"true\"></property> -->\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\n\t\t<dataStore>\n\t\t\t<name>fs</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"spark.master\" value=\"local\"></property>\n\t\t\t\t\t<property name=\"spark.app.name\" value=\"sparkfs\"></property>\n\t\t\t\t\t<property name=\"spark.executor.memory\" value=\"1g\"></property>\n<!-- \t\t\t\t\t<property name=\"spark.driver.allowMultipleContexts\" value=\"true\"></property> -->\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\n\t</datastores>\n\n</clientProperties>\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/test/resources/META-INF/persistence.xml",
    "content": "\r\n<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"spark_hdfs_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"7077\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"sparktest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"spark\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"hdfs\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.spark.client.SparkClientFactory\" />\r\n\t\t\t<property name=\"kundera.client.property\" value=\"KunderaSparkTest.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\t\r\n\t\t<persistence-unit name=\"spark_fs_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"60000\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"sparktest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"spark\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"fs\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.spark.client.SparkClientFactory\" />\r\n\t\t\t<property name=\"kundera.client.property\" value=\"KunderaSparkTest.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\t\r\n\r\n</persistence>\r\n"
  },
  {
    "path": "src/kundera-spark/spark-core/src/test/resources/test.csv",
    "content": "personId,personName,age,salary\n\"1\",\"dev\",22,30000.5\n\"2\",\"pg\",23,40000.6\n\"3\",\"kpm\",24,50000.7\n"
  },
  {
    "path": "src/kundera-spark/spark-hive/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t<artifactId>kundera-spark-parent</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\n\t<artifactId>kundera-spark-hive</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-spark-hive</name>\n\t<url>http://maven.apache.org</url>\n\n\t<dependencies>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-spark</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-spark</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t</dependencies>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-surefire-plugin</artifactId>\n\t\t\t\t<version>2.12</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<forkMode>never</forkMode>\n\t\t\t\t\t<argLine>-Xmx1024m</argLine>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "src/kundera-spark/spark-hive/src/main/java/com/impetus/spark/client/HiveSparkClient.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.spark.api.java.JavaRDD;\nimport org.apache.spark.sql.DataFrame;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport scala.collection.immutable.Seq;\nimport scala.reflect.ClassTag;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\n\n/**\n * The Class HiveSparkClient.\n * \n * @author amitkumar\n */\npublic class HiveSparkClient implements SparkDataClient\n{\n    /** The logger. */\n    private static Logger logger = LoggerFactory.getLogger(HiveSparkClient.class);\n\n    /** The Constant KEYSPACE. */\n    private static final String KEYSPACE = \"keyspace\";\n\n    /** The Constant TABLE. */\n    private static final String TABLE = \"table\";\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.spark.client.SparkDataClient#registerTable(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.spark.client.SparkClient)\n     */\n    @Override\n    public void registerTable(EntityMetadata m, SparkClient sparkClient)\n    {\n        sparkClient.sqlContext.sql(\"use \" + m.getSchema());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.spark.client.SparkDataClient#persist(java.util.List,\n     * com.impetus.kundera.metadata.model.EntityMetadata,\n     * com.impetus.spark.client.SparkClient)\n     */\n    @Override\n    public boolean persist(List listEntity, EntityMetadata m, SparkClient sparkClient)\n    {\n        try\n        {\n            Seq s = scala.collection.JavaConversions.asScalaBuffer(listEntity).toList();\n            ClassTag tag = scala.reflect.ClassTag$.MODULE$.apply(m.getEntityClazz());\n            JavaRDD personRDD = sparkClient.sparkContext.parallelize(s, 1, tag).toJavaRDD();\n\n            DataFrame df = sparkClient.sqlContext.createDataFrame(personRDD, m.getEntityClazz());\n            sparkClient.sqlContext.sql(\"use \" + m.getSchema());\n            if (logger.isDebugEnabled())\n            {\n                logger.info(\"Below are the registered table with hive context: \");\n                sparkClient.sqlContext.sql(\"show tables\").show();\n            }\n            df.write().insertInto(m.getTableName());\n\n            return true;\n        }\n        catch (Exception e)\n        {\n            throw new KunderaException(\"Cannot persist object(s)\", e);\n        }\n\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.spark.client.SparkDataClient#saveDataFrame(org.apache.spark\n     * .sql.DataFrame, java.lang.Class, java.util.Map)\n     */\n    @Override\n    public void saveDataFrame(DataFrame dataFrame, Class<?> entityClazz, Map<String, Object> properties)\n    {\n        dataFrame.sqlContext().sql(\"use \" + (String) properties.get(KEYSPACE));\n        dataFrame.write().insertInto((String) properties.get(TABLE));\n    }\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-hive/src/test/java/com/impetus/client/spark/PersonHive.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.spark;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * The Class PersonHive.\n * \n * @author amitkumar\n */\n@Entity\n@Table(name = \"person\")\n@IndexCollection(columns = { @Index(name = \"personname\"), @Index(name = \"age\"), @Index(name = \"salary\") })\npublic class PersonHive implements Serializable\n{\n    /** The Constant serialVersionUID. */\n    private static final long serialVersionUID = 1L;\n\n    /** The person id. */\n    @Id\n    private String personid;\n\n    /** The person name. */\n    private String personname;\n\n    /** The salary. */\n    private Double salary;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personid;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personid = personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personname;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personname = personName;\n    }\n\n    /**\n     * Gets the salary.\n     * \n     * @return the salary\n     */\n    public Double getSalary()\n    {\n        return salary;\n    }\n\n    /**\n     * Sets the salary.\n     * \n     * @param salary\n     *            the new salary\n     */\n    public void setSalary(Double salary)\n    {\n        this.salary = salary;\n    }\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-hive/src/test/java/com/impetus/client/spark/SparkHiveClientTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.spark;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.spark.tests.SparkBaseTest;\n\n/**\n * The Class SparkHiveQueryTest.\n * \n * @author amitkumar\n */\npublic class SparkHiveClientTest extends SparkBaseTest\n{\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The entity manager. */\n    private EntityManager em;\n\n    /** The pu. */\n    private static final String PU = \"spark_hive_PU\";\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test hive with spark.\n     */\n    @Test\n    public void testHiveWithSpark()\n    {\n        testPersist();\n        persistData();\n        testQuery();\n        testSaveIntermediateResult();\n    }\n\n    /**\n     * Test query.\n     */\n    private void testQuery()\n    {\n        List<PersonHive> results = em.createNativeQuery(\"select * from sparktest.person\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        matchResults(results, 4);\n\n        results = em.createNativeQuery(\"select * from sparktest.person where salary > 80\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        matchResults(results, 2);\n\n        // results =\n        // em.createNativeQuery(\"select * from sparktest.person where salary > 50 and age = 60\").getResultList();\n        // Assert.assertNotNull(results);\n        // Assert.assertEquals(1, results.size());\n        // matchPerson(results.get(0), 2);\n\n        results = em.createNativeQuery(\"select * from sparktest.person where personName like 'Am%'\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        matchResults(results, 1);\n\n        List aggregateResults = em.createNativeQuery(\"select sum(salary) from sparktest.person\").getResultList();\n        Assert.assertNotNull(aggregateResults);\n\n        aggregateResults = em.createNativeQuery(\"select count(*) from sparktest.person where salary > 10.0\")\n                .getResultList();\n        Assert.assertNotNull(aggregateResults.size());\n\n        results = em.createNativeQuery(\"select * from person\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        matchResults(results, 4);\n\n        results = em.createNativeQuery(\"select * from person where salary > 80\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        matchResults(results, 2);\n\n        results = em.createNativeQuery(\"select * from person where salary between 20.0 and 90\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        matchPerson(results.get(0), 3);\n\n    }\n\n    /**\n     * Persist data.\n     */\n    private void persistData()\n    {\n        em.persist(createPerson(\"2\", \"John\", 200.00));\n        em.persist(createPerson(\"3\", \"Marty\", 50.00));\n        em.persist(createPerson(\"4\", \"Marty Cole\", 10.00));\n    }\n\n    /**\n     * Test persist.\n     */\n    private void testPersist()\n    {\n        PersonHive person = createPerson(\"1\", \"Amit\", 100.00);\n        em.persist(person);\n\n        List<PersonHive> results = em.createNativeQuery(\"select * from sparktest.person\").getResultList();\n        PersonHive personHive = results.get(0);\n\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"1\", personHive.getPersonId());\n        Assert.assertEquals(\"Amit\", personHive.getPersonName());\n        Assert.assertEquals(100.00, personHive.getSalary());\n    }\n\n    /**\n     * Creates the person.\n     * \n     * @param id\n     *            the id\n     * @param name\n     *            the name\n     * @param salary\n     *            the salary\n     * @return the person hive\n     */\n    private PersonHive createPerson(String id, String name, Double salary)\n    {\n        PersonHive person = new PersonHive();\n\n        person.setPersonId(id);\n        person.setPersonName(name);\n        person.setSalary(salary);\n\n        return person;\n    }\n\n    /**\n     * Test save intermediate result.\n     */\n    private void testSaveIntermediateResult()\n    {\n        String sqlString = \"INSERT INTO hive.sparktest.IntermediatePerson FROM (select * from person)\";\n        Query q = em.createNativeQuery(sqlString, PersonHive.class);\n        q.executeUpdate();\n\n        List<PersonHive> results = em.createNativeQuery(\"select * from sparktest.IntermediatePerson\").getResultList();\n        matchResults(results, 4);\n\n        sqlString = \"INSERT INTO fs.[src/test/resources/testspark_csv] AS CSV FROM (select * from person)\";\n        q = em.createNativeQuery(sqlString, PersonHive.class);\n        q.executeUpdate();\n\n        sqlString = \"INSERT INTO fs.[src/test/resources/testspark_json] AS JSON FROM (select * from person)\";\n        q = em.createNativeQuery(sqlString, PersonHive.class);\n        q.executeUpdate();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.createNativeQuery(\"TRUNCATE TABLE person\").getResultList();\n        em.createNativeQuery(\"TRUNCATE TABLE intermediatePerson\").getResultList();\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n    }\n\n    /**\n     * Match results.\n     * \n     * @param results\n     *            the results\n     * @param count\n     *            the count\n     */\n    private void matchResults(List<PersonHive> results, int count)\n    {\n        int flag = 1;\n        Assert.assertEquals(count, results.size());\n        for (PersonHive person : results)\n        {\n            matchPerson(person, flag++);\n        }\n    }\n\n    /**\n     * Match person.\n     * \n     * @param person\n     *            the person\n     * @param personId\n     *            the person id\n     */\n    private void matchPerson(PersonHive person, int personId)\n    {\n        switch (personId)\n        {\n        case 1:\n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"Amit\", person.getPersonName());\n            Assert.assertEquals(100.0, person.getSalary());\n            break;\n\n        case 2:\n            Assert.assertEquals(\"2\", person.getPersonId());\n            Assert.assertEquals(\"John\", person.getPersonName());\n            Assert.assertEquals(200.0, person.getSalary());\n            break;\n        case 3:\n            Assert.assertEquals(\"3\", person.getPersonId());\n            Assert.assertEquals(\"Marty\", person.getPersonName());\n            Assert.assertEquals(50.0, person.getSalary());\n            break;\n        case 4:\n            Assert.assertEquals(\"4\", person.getPersonId());\n            Assert.assertEquals(\"Marty Cole\", person.getPersonName());\n            Assert.assertEquals(10.0, person.getSalary());\n            break;\n        default:\n            Assert.assertTrue(false);\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-hive/src/test/java/com/impetus/client/spark/SparkHiveQueryTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.spark;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.spark.tests.SparkBaseTest;\n\n/**\n * The Class SparkHiveQueryTest.\n * \n * @author amitkumar\n */\npublic class SparkHiveQueryTest extends SparkBaseTest\n{\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The entity manager. */\n    private EntityManager em;\n\n    /** The pu. */\n    private static final String PU = \"spark_hive_PU\";\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Test hive with spark.\n     */\n    @Test\n    public void testHiveWithSpark()\n    {\n        testPersist();\n        persistData();\n        testQuery();\n        testSaveIntermediateResult();\n    }\n\n    /**\n     * Test query.\n     */\n    private void testQuery()\n    {\n        List<PersonHive> results = em.createNativeQuery(\"select * from sparktest.person\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        matchResults(results, 4);\n\n        results = em.createNativeQuery(\"select * from sparktest.person where salary > 80\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        matchResults(results, 2);\n\n        // results =\n        // em.createNativeQuery(\"select * from sparktest.person where salary > 50 and age = 60\").getResultList();\n        // Assert.assertNotNull(results);\n        // Assert.assertEquals(1, results.size());\n        // matchPerson(results.get(0), 2);\n\n        results = em.createNativeQuery(\"select * from sparktest.person where personName like 'Am%'\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        matchResults(results, 1);\n\n        List aggregateResults = em.createNativeQuery(\"select sum(salary) from sparktest.person\").getResultList();\n        Assert.assertNotNull(aggregateResults);\n\n        aggregateResults = em.createNativeQuery(\"select count(*) from sparktest.person where salary > 10.0\")\n                .getResultList();\n        Assert.assertNotNull(aggregateResults.size());\n\n        results = em.createNativeQuery(\"select * from person\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(4, results.size());\n        matchResults(results, 4);\n\n        results = em.createNativeQuery(\"select * from person where salary > 80\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        matchResults(results, 2);\n\n        results = em.createNativeQuery(\"select * from person where salary between 20.0 and 90\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        matchPerson(results.get(0), 3);\n\n    }\n\n    /**\n     * Persist data.\n     */\n    private void persistData()\n    {\n        em.persist(createPerson(\"2\", \"John\", 200.00));\n        em.persist(createPerson(\"3\", \"Marty\", 50.00));\n        em.persist(createPerson(\"4\", \"Marty Cole\", 10.00));\n    }\n\n    /**\n     * Test persist.\n     */\n    private void testPersist()\n    {\n        PersonHive person = createPerson(\"1\", \"Amit\", 100.00);\n        em.persist(person);\n\n        List<PersonHive> results = em.createNativeQuery(\"select * from sparktest.person\").getResultList();\n        PersonHive personHive = results.get(0);\n\n        Assert.assertEquals(1, results.size());\n        Assert.assertEquals(\"1\", personHive.getPersonId());\n        Assert.assertEquals(\"Amit\", personHive.getPersonName());\n        Assert.assertEquals(100.00, personHive.getSalary());\n    }\n\n    /**\n     * Creates the person.\n     * \n     * @param id\n     *            the id\n     * @param name\n     *            the name\n     * @param salary\n     *            the salary\n     * @return the person hive\n     */\n    private PersonHive createPerson(String id, String name, Double salary)\n    {\n        PersonHive person = new PersonHive();\n\n        person.setPersonId(id);\n        person.setPersonName(name);\n        person.setSalary(salary);\n\n        return person;\n    }\n\n    /**\n     * Test save intermediate result.\n     */\n    private void testSaveIntermediateResult()\n    {\n        String sqlString = \"INSERT INTO hive.sparktest.IntermediatePerson FROM (select * from person)\";\n        Query q = em.createNativeQuery(sqlString, PersonHive.class);\n        q.executeUpdate();\n\n        List<PersonHive> results = em.createNativeQuery(\"select * from sparktest.IntermediatePerson\").getResultList();\n        matchResults(results, 4);\n\n        sqlString = \"INSERT INTO fs.[src/test/resources/testspark_csv] AS CSV FROM (select * from person)\";\n        q = em.createNativeQuery(sqlString, PersonHive.class);\n        q.executeUpdate();\n\n        sqlString = \"INSERT INTO fs.[src/test/resources/testspark_json] AS JSON FROM (select * from person)\";\n        q = em.createNativeQuery(sqlString, PersonHive.class);\n        q.executeUpdate();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.createNativeQuery(\"TRUNCATE TABLE person\").getResultList();\n        em.createNativeQuery(\"TRUNCATE TABLE intermediatePerson\").getResultList();\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        emf.close();\n        emf = null;\n    }\n\n    /**\n     * Match results.\n     * \n     * @param results\n     *            the results\n     * @param count\n     *            the count\n     */\n    private void matchResults(List<PersonHive> results, int count)\n    {\n        int flag = 1;\n        Assert.assertEquals(count, results.size());\n        for (PersonHive person : results)\n        {\n            matchPerson(person, flag++);\n        }\n    }\n\n    /**\n     * Match person.\n     * \n     * @param person\n     *            the person\n     * @param personId\n     *            the person id\n     */\n    private void matchPerson(PersonHive person, int personId)\n    {\n        switch (personId)\n        {\n        case 1:\n            Assert.assertEquals(\"1\", person.getPersonId());\n            Assert.assertEquals(\"Amit\", person.getPersonName());\n            Assert.assertEquals(100.0, person.getSalary());\n            break;\n\n        case 2:\n            Assert.assertEquals(\"2\", person.getPersonId());\n            Assert.assertEquals(\"John\", person.getPersonName());\n            Assert.assertEquals(200.0, person.getSalary());\n            break;\n        case 3:\n            Assert.assertEquals(\"3\", person.getPersonId());\n            Assert.assertEquals(\"Marty\", person.getPersonName());\n            Assert.assertEquals(50.0, person.getSalary());\n            break;\n        case 4:\n            Assert.assertEquals(\"4\", person.getPersonId());\n            Assert.assertEquals(\"Marty Cole\", person.getPersonName());\n            Assert.assertEquals(10.0, person.getSalary());\n            break;\n        default:\n            Assert.assertTrue(false);\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-hive/src/test/resources/KunderaSparkHiveProperties.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>hive</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"spark.master\" value=\"local\"></property>\n\t\t\t\t\t<property name=\"spark.app.name\" value=\"sparkhive\"></property>\n\t\t\t\t\t<property name=\"spark.driver.allowMultipleContexts\" value=\"true\"></property>\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>\n"
  },
  {
    "path": "src/kundera-spark/spark-hive/src/test/resources/META-INF/persistence.xml",
    "content": "\r\n<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"spark_hive_PU\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.client.spark.PersonHive</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"7077\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"sparktest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"spark\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"hive\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.spark.client.SparkClientFactory\" />\r\n\t\t\t<property name=\"kundera.client.property\" value=\"KunderaSparkHiveProperties.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n</persistence>\r\n"
  },
  {
    "path": "src/kundera-spark/spark-hive/src/test/resources/hive-site.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>\n<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor \n\tlicense agreements. See the NOTICE file distributed with this work for additional \n\tinformation regarding copyright ownership. The ASF licenses this file to \n\tYou under the Apache License, Version 2.0 (the \"License\"); you may not use \n\tthis file except in compliance with the License. You may obtain a copy of \n\tthe License at http://www.apache.org/licenses/LICENSE-2.0 Unless required \n\tby applicable law or agreed to in writing, software distributed under the \n\tLicense is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS \n\tOF ANY KIND, either express or implied. See the License for the specific \n\tlanguage governing permissions and limitations under the License. -->\n<configuration>\n\t<property>\n\t\t<name>javax.jdo.option.ConnectionURL</name>\n\t\t<value>jdbc:mysql://localhost:3306/metastore</value>\n\t\t<description>the URL of the MySQL database</description>\n\t</property>\n\n\t<property>\n\t\t<name>javax.jdo.option.ConnectionDriverName</name>\n\t\t<value>com.mysql.jdbc.Driver</value>\n\t</property>\n\n\t<property>\n\t\t<name>javax.jdo.option.ConnectionUserName</name>\n\t\t<value>root</value>\n\t</property>\n\n\t<property>\n\t\t<name>javax.jdo.option.ConnectionPassword</name>\n\t\t<value>impetus</value>\n\t</property>\n\n\t<property>\n\t\t<name>fs.default.name</name>\n\t\t<value>hdfs://localhost:9000</value>\n\t</property>\n\n\t<property>\n\t\t<name>hive.metastore.warehouse.dir</name>\n\t\t<value>/user/hive/warehouse</value>\n\t\t<description>location of default database for the warehouse\n\t\t</description>\n\t</property>\n\n</configuration>"
  },
  {
    "path": "src/kundera-spark/spark-hive/src/test/resources/hive_script",
    "content": "create database sparktest;\ncreate table person(personId varchar(4), personName varchar(255), salary double) row format delimited fields terminated by ',';\ncreate table intermediatePerson(personId varchar(4), personName varchar(255), salary double) row format delimited fields terminated by ',';"
  },
  {
    "path": "src/kundera-spark/spark-mongodb/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t<artifactId>kundera-spark-parent</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.client</groupId>\n\t<artifactId>kundera-spark-mongodb</artifactId>\n\t<packaging>jar</packaging>\n\n\t<name>kundera-spark-mongodb</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t</properties>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-spark</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-spark</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.mongodb</groupId>\n\t\t\t<artifactId>mongo-java-driver</artifactId>\n\t\t\t<version>2.13.0</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.mongodb</groupId>\n\t\t\t<artifactId>mongo-hadoop-core</artifactId>\n\t\t\t<version>1.3.0</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.hadoop</groupId>\n\t\t\t<artifactId>hadoop-common</artifactId>\n\t\t\t<version>2.3.0</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.codehaus.jackson</groupId>\n\t\t\t<artifactId>jackson-mapper-asl</artifactId>\n\t\t\t<version>1.9.13</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.codehaus.jackson</groupId>\n\t\t\t<artifactId>jackson-core-asl</artifactId>\n\t\t\t<version>1.9.13</version>\n\t\t</dependency>\n\n\n\t</dependencies>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n\t<build>\n\t<plugins>\n\t\t<plugin>\n\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t<artifactId>maven-surefire-plugin</artifactId>\n\t\t\t<version>2.12</version>\n\t\t\t<configuration>\n\t\t\t\t<forkMode>never</forkMode>\n\t\t\t\t<argLine>-Xmx1024m</argLine>\n\t\t\t</configuration>\n\t\t</plugin>\n\t</plugins>\n\t</build>\n</project>\n"
  },
  {
    "path": "src/kundera-spark/spark-mongodb/src/main/java/com/impetus/spark/client/MongoSparkClient.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.io.IOException;\nimport java.io.Serializable;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.spark.SparkContext;\nimport org.apache.spark.api.java.JavaPairRDD;\nimport org.apache.spark.api.java.JavaRDD;\nimport org.apache.spark.api.java.function.FlatMapFunction;\nimport org.apache.spark.api.java.function.PairFunction;\nimport org.apache.spark.sql.DataFrame;\nimport org.bson.BSONObject;\nimport org.bson.BasicBSONObject;\nimport org.codehaus.jackson.JsonFactory;\nimport org.codehaus.jackson.JsonGenerationException;\nimport org.codehaus.jackson.JsonParseException;\nimport org.codehaus.jackson.JsonParser;\nimport org.codehaus.jackson.map.DeserializationConfig;\nimport org.codehaus.jackson.map.JsonMappingException;\nimport org.codehaus.jackson.map.ObjectMapper;\nimport org.codehaus.jackson.map.ObjectWriter;\n\nimport scala.Tuple2;\nimport scala.collection.immutable.Seq;\nimport scala.reflect.ClassTag;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.property.PropertyAccessorHelper;\nimport com.mongodb.hadoop.MongoInputFormat;\nimport com.mongodb.hadoop.MongoOutputFormat;\nimport com.mongodb.util.JSON;\n\n/**\n * The Class MongoSparkClient.\n */\npublic class MongoSparkClient implements SparkDataClient, Serializable\n{\n\n    /** The Constant serialVersionUID. */\n    private static final long serialVersionUID = 1L;\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.spark.client.DataClient#registerTable(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.spark.client.SparkClient)\n     */\n    public void registerTable(EntityMetadata m, SparkClient sparkClient)\n    {\n\n        final Class clazz = m.getEntityClazz();\n        SparkContext sc = sparkClient.sparkContext;\n        Configuration config = new Configuration();\n        config.set(\n                \"mongo.input.uri\",\n                buildMongoURIPath(sc.getConf().get(\"hostname\"), sc.getConf().get(\"portname\"), m.getSchema(),\n                        m.getTableName()));\n\n        JavaRDD<Tuple2<Object, BSONObject>> mongoJavaRDD = sc.newAPIHadoopRDD(config, MongoInputFormat.class,\n                Object.class, BSONObject.class).toJavaRDD();\n\n        JavaRDD<Object> mongoRDD = mongoJavaRDD.flatMap(new FlatMapFunction<Tuple2<Object, BSONObject>, Object>()\n        {\n            @Override\n            public Iterable<Object> call(Tuple2<Object, BSONObject> arg)\n            {\n                BSONObject obj = arg._2();\n                Object javaObject = generateJavaObjectFromBSON(obj, clazz);\n                return Arrays.asList(javaObject);\n            }\n        });\n\n        sparkClient.sqlContext.createDataFrame(mongoRDD, m.getEntityClazz()).registerTempTable(m.getTableName());\n    }\n\n    /**\n     * Builds the mongo uri path.\n     * \n     * @param host\n     *            the host\n     * @param port\n     *            the port\n     * @param db\n     *            the db\n     * @param table\n     *            the table\n     * @return the string\n     */\n    protected String buildMongoURIPath(String host, String port, String db, String table)\n    {\n        StringBuilder pathBuilder = new StringBuilder();\n        pathBuilder.append(\"mongodb://\");\n        pathBuilder.append(host);\n        pathBuilder.append(\":\");\n        pathBuilder.append(port);\n        pathBuilder.append(\"/\");\n        pathBuilder.append(db);\n        pathBuilder.append(\".\");\n        pathBuilder.append(table);\n        return pathBuilder.toString();\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.spark.client.DataClient#persist(java.util.List,\n     * com.impetus.kundera.metadata.model.EntityMetadata,\n     * com.impetus.spark.client.SparkClient)\n     */\n    public boolean persist(List listEntity, final EntityMetadata m, final SparkClient sparkClient)\n    {\n        try\n        {\n            Seq s = scala.collection.JavaConversions.asScalaBuffer(listEntity).toList();\n            ClassTag tag = scala.reflect.ClassTag$.MODULE$.apply(m.getEntityClazz());\n            JavaRDD javaRDD = sparkClient.sparkContext.parallelize(s, 1, tag).toJavaRDD();\n\n            final Object key = PropertyAccessorHelper.getId(listEntity.get(0), m);\n\n            JavaPairRDD<Object, BSONObject> javaRDDPair = javaRDD\n                    .mapToPair(new PairFunction<Object, Object, BSONObject>()\n                    {\n                        @Override\n                        public Tuple2<Object, BSONObject> call(Object p)\n                        {\n                            BSONObject bson = new BasicBSONObject();\n                            bson = generateBSONFromJavaObject(p);\n                            return new Tuple2<Object, BSONObject>(key, bson);\n                        }\n                    });\n            SparkContext sc = sparkClient.sparkContext;\n            Configuration outputConfig = new Configuration();\n            outputConfig.set(\"mongo.output.format\", \"com.mongodb.hadoop.MongoOutputFormat\");\n            outputConfig.set(\n                    \"mongo.output.uri\",\n                    buildMongoURIPath(sc.getConf().get(\"hostname\"), sc.getConf().get(\"portname\"), m.getSchema(),\n                            m.getTableName()));\n\n            javaRDDPair.saveAsNewAPIHadoopFile(\"file://dummy\", Object.class, BSONObject.class, MongoOutputFormat.class,\n                    outputConfig);\n            return true;\n        }\n        catch (Exception e)\n        {\n            throw new KunderaException(\"can't persist object(s)\", e);\n        }\n\n    }\n\n    /**\n     * Generate bson from java object.\n     * \n     * @param obj\n     *            the obj\n     * @return the BSON object\n     */\n    protected BSONObject generateBSONFromJavaObject(Object obj)\n    {\n        ObjectWriter ow = new ObjectMapper().writer();\n        String json = null;\n        try\n        {\n            json = ow.writeValueAsString(obj);\n            return (BSONObject) JSON.parse(json);\n        }\n        catch (JsonGenerationException | JsonMappingException e)\n        {\n            throw new KunderaException(\n                    \"Error in converting BSON Object from Java Object due to error in JSON generation/mapping. Caused BY:\",\n                    e);\n        }\n\n        catch (IOException e)\n        {\n            throw new KunderaException(\"Error in converting BSON Object from Java Object. Caused BY:\", e);\n        }\n\n    }\n\n    /**\n     * Generate java object from bson.\n     * \n     * @param bsonObj\n     *            the bsonObj\n     * @param clazz\n     *            the clazz\n     * @return the object\n     */\n    protected Object generateJavaObjectFromBSON(BSONObject bsonObj, Class clazz)\n    {\n        ObjectMapper mapper = new ObjectMapper();\n        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n        JsonParser jsonParser;\n        try\n        {\n            jsonParser = new JsonFactory().createJsonParser(bsonObj.toString());\n            return mapper.readValue(jsonParser, clazz);\n        }\n        catch (JsonParseException e)\n        {\n            throw new KunderaException(\n                    \"Error in converting Java Object from BSON Object due to error in JSON parsing. Caused BY:\", e);\n        }\n        catch (IOException e)\n        {\n            throw new KunderaException(\"Error in converting Java Object from BSON Object. Caused BY:\", e);\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.spark.client.DataClient#saveDataFrame(org.apache.spark.sql\n     * .DataFrame, java.lang.Class, java.util.Map)\n     */\n    @Override\n    public void saveDataFrame(DataFrame dataFrame, Class<?> entityClazz, Map<String, Object> properties)\n    {\n        throw new KunderaException(\"Saving data of DataFrame back to MongoDB is currently not supported. \");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-mongodb/src/test/java/com/impetus/spark/client/SparkMongoClientTest.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.net.UnknownHostException;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.client.spark.entities.Person;\nimport com.impetus.client.spark.tests.SparkBaseTest;\nimport com.impetus.client.spark.utils.SparkTestingUtils;\nimport com.mongodb.DB;\nimport com.mongodb.MongoClient;\nimport com.mongodb.ServerAddress;\n\n/**\n * The Class MongoClientTest.\n * \n * @author devender.yadav\n */\npublic class SparkMongoClientTest extends SparkBaseTest\n{\n\n    /** The Constant MONGO_PU. */\n    private static final String MONGO_PU = \"spark_mongo_pu\";\n\n    /** The emf. */\n    private static EntityManagerFactory emf;\n\n    /** The entity manager. */\n    private EntityManager em;\n\n    /**\n     * Sets the up before class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @BeforeClass\n    public static void SetUpBeforeClass() throws Exception\n    {\n        emf = Persistence.createEntityManagerFactory(MONGO_PU);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * Spark mongo test.\n     */\n    @Test\n    public void sparkMongoTest()\n    {\n        testPersist();\n        testQuery();\n        testSaveIntermediateResult();\n    }\n\n    /**\n     * Test persist.\n     */\n    public void testPersist()\n    {\n\n        Person person1 = getPerson(\"1\", \"dev\", 22, 30000.5);\n        Person person2 = getPerson(\"2\", \"pg\", 23, 40000.6);\n        Person person3 = getPerson(\"3\", \"kpm\", 24, 50000.7);\n\n        em.clear();\n        em.persist(person1);\n        em.persist(person2);\n        em.persist(person3);\n\n        Person p = em.find(Person.class, \"1\");\n        validatePerson1(p);\n\n        p = em.find(Person.class, \"2\");\n        validatePerson2(p);\n\n        p = em.find(Person.class, \"3\");\n        validatePerson3(p);\n    }\n\n    /**\n     * Test query.\n     */\n    public void testQuery()\n    {\n        List<Person> results = em.createNativeQuery(\"select * from spark_person\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(3, results.size());\n        assertResults(results, true, true, true);\n\n        results = em.createNativeQuery(\"select * from spark_person where salary > 35000\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(2, results.size());\n        assertResults(results, false, true, true);\n\n        results = em.createNativeQuery(\"select * from spark_person where salary > 35000 and age = 23\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        assertResults(results, false, true, false);\n\n        results = em.createNativeQuery(\"select * from spark_person where personName like 'kp%'\").getResultList();\n        Assert.assertNotNull(results);\n        Assert.assertEquals(1, results.size());\n        assertResults(results, false, false, true);\n\n        List aggregateResults = em.createNativeQuery(\"select sum(salary) from spark_person\").getResultList();\n        Assert.assertNotNull(aggregateResults);\n\n        aggregateResults = em.createNativeQuery(\"select count(*) from spark_person where salary > 30000\")\n                .getResultList();\n        Assert.assertNotNull(aggregateResults.size());\n\n    }\n\n    /**\n     * Test save intermediate result.\n     */\n    public void testSaveIntermediateResult()\n    {\n        String sqlString = \"INSERT INTO fs.[src/test/resources/testspark_csv] AS CSV FROM (select * from spark_person)\";\n        Query q = em.createNativeQuery(sqlString, Person.class);\n        q.executeUpdate();\n\n        sqlString = \"INSERT INTO fs.[src/test/resources/testspark_json] AS JSON FROM (select * from spark_person)\";\n        q = em.createNativeQuery(sqlString, Person.class);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n    }\n\n    /**\n     * Tear down after class.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        SparkTestingUtils.recursivelyCleanDir(\"src/test/resources/testspark_csv\");\n        SparkTestingUtils.recursivelyCleanDir(\"src/test/resources/testspark_json\");\n        dropDB();\n        emf.close();\n        emf = null;\n    }\n\n    private static void dropDB() throws UnknownHostException\n    {\n        MongoClient mongoClient = new MongoClient(new ServerAddress(\"localhost\", 27017));\n        DB db = mongoClient.getDB(\"sparktest\");\n        db.dropDatabase();\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-mongodb/src/test/resources/KunderaSparkMongoProperties.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>mongodb</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"spark.master\" value=\"local\"></property>\n\t\t\t\t\t<property name=\"spark.app.name\" value=\"sparkMongo\"></property>\n\t\t\t\t\t<property name=\"spark.driver.allowMultipleContexts\" value=\"true\"></property>\n\t\t\t\t</properties>\n\t\t\t\t<servers>\n\t\t\t\t\t<server>\n\t\t\t\t\t\t<host>localhost\n\t\t\t\t\t\t</host>\n\t\t\t\t\t\t<port>27017</port>\n\t\t\t\t\t</server>\n\t\t\t\t</servers>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>\n"
  },
  {
    "path": "src/kundera-spark/spark-mongodb/src/test/resources/META-INF/persistence.xml",
    "content": "\r\n<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"spark_mongo_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.client.spark.entities.Person</class>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"7077\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"sparktest\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"spark\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"mongodb\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.spark.client.SparkClientFactory\" />\r\n\t\t\t<property name=\"kundera.client.property\" value=\"KunderaSparkMongoProperties.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n</persistence>\r\n"
  },
  {
    "path": "src/kundera-spark/spark-teradata/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t<artifactId>kundera-spark-parent</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\n\t<artifactId>kundera-spark-teradata</artifactId>\n\t<packaging>jar</packaging>\n\t<name>kundera-spark-teradata</name>\n\t<url>http://maven.apache.org</url>\n\n\t<dependencies>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-spark</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-spark</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t</dependencies>\n\n\t<!-- Assembly build -->\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<!-- NOTE: We don't need a groupId specification because the group is \n\t\t\t\t\torg.apache.maven.plugins ...which is assumed by default. -->\n\t\t\t\t<artifactId>maven-assembly-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<descriptorRefs>\n\t\t\t\t\t\t<descriptorRef>jar-with-dependencies</descriptorRef>\n\t\t\t\t\t</descriptorRefs>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>test-jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-surefire-plugin</artifactId>\n\t\t\t\t<version>2.12</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<forkMode>never</forkMode>\n\t\t\t\t\t<argLine>-Xmx1024m</argLine>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "src/kundera-spark/spark-teradata/src/main/java/com/impetus/spark/client/TeradataSparkClient.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.spark.client;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.apache.spark.sql.DataFrame;\n\nimport com.impetus.kundera.KunderaException;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\n\n/**\n * The Class TeradataSparkClient.\n * \n * @author amitkumar\n */\npublic class TeradataSparkClient implements SparkDataClient\n{\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.spark.client.SparkDataClient#registerTable(com.impetus.kundera\n     * .metadata.model.EntityMetadata, com.impetus.spark.client.SparkClient)\n     */\n    @Override\n    public void registerTable(EntityMetadata m, SparkClient sparkClient)\n    {\n        String conn = getConnectionString(m);\n\n        Map<String, String> options = new HashMap<String, String>();\n        options.put(\"url\", conn);\n        options.put(\"dbtable\", m.getTableName());\n\n        sparkClient.sqlContext.load(\"jdbc\", options).registerTempTable(m.getTableName());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.spark.client.SparkDataClient#persist(java.util.List,\n     * com.impetus.kundera.metadata.model.EntityMetadata,\n     * com.impetus.spark.client.SparkClient)\n     */\n    @Override\n    public boolean persist(List listEntity, EntityMetadata m, SparkClient sparkClient)\n    {\n        throw new KunderaException(\"Entity persistence in teradata is currently not supported. \");\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.spark.client.SparkDataClient#saveDataFrame(org.apache.spark\n     * .sql.DataFrame, java.lang.Class, java.util.Map)\n     */\n    @Override\n    public void saveDataFrame(DataFrame dataFrame, Class<?> entityClazz, Map<String, Object> properties)\n    {\n        throw new KunderaException(\"Dataframe persistence in teradata is currently not supported. \");\n    }\n\n    /**\n     * Gets the connection string.\n     * \n     * @param m\n     *            the m\n     * @return the connection string\n     */\n    public String getConnectionString(EntityMetadata m)\n    {\n        Properties properties = new Properties();\n\n        String fileName = \"teradata.properties\";\n        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName);\n\n        if (inputStream != null)\n        {\n            try\n            {\n                properties.load(inputStream);\n            }\n            catch (IOException e)\n            {\n                throw new RuntimeException(\"Property file: \" + fileName + \"not found in the classpath\", e);\n            }\n        }\n        else\n        {\n            throw new RuntimeException(\"Property file: \" + fileName + \"not found in the classpath\");\n        }\n\n        String connectionString = \"jdbc:teradata://\" + properties.getProperty(\"teradata.host\") + \"/database=\"\n                + m.getSchema() + \",tmode=ANSI,charset=UTF8,user=\" + properties.getProperty(\"teradata.user\")\n                + \",password=\" + properties.getProperty(\"teradata.password\") + \"\";\n        return connectionString;\n    }\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-teradata/src/test/java/com/impetus/client/spark/Person.java",
    "content": "/*******************************************************************************\n *  * Copyright 2015 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.client.spark;\n\nimport java.io.Serializable;\n\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class Personnel.\n * \n * @author amitkumar\n */\n@Entity\n@Table(name = \"person\")\npublic class Person implements Serializable\n{\n    /** The Constant serialVersionUID. */\n    private static final long serialVersionUID = 1L;\n\n    /** The id. */\n    @Id\n    private int id;\n\n    /** The first name. */\n    private String firstName;\n\n    /** The state number. */\n    private int salary;\n\n    /**\n     * Instantiates a new personnel.\n     */\n    public Person()\n    {\n\n    }\n\n    /**\n     * Gets the id.\n     * \n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * Sets the id.\n     * \n     * @param id\n     *            the new id\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * Gets the first name.\n     * \n     * @return the first name\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * Sets the first name.\n     * \n     * @param firstName\n     *            the new first name\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * Gets the salary.\n     * \n     * @return the salary\n     */\n    public int getSalary()\n    {\n        return salary;\n    }\n\n    /**\n     * Sets the salary.\n     * \n     * @param salary\n     *            the new salary\n     */\n    public void setSalary(int salary)\n    {\n        this.salary = salary;\n    }\n\n    /**\n     * Gets the serialversionuid.\n     * \n     * @return the serialversionuid\n     */\n    public static long getSerialversionuid()\n    {\n        return serialVersionUID;\n    }\n}\n"
  },
  {
    "path": "src/kundera-spark/spark-teradata/src/test/resources/KunderaSparkTeradataProperties.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>teradata</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"spark.master\" value=\"local\"></property>\n\t\t\t\t\t<property name=\"spark.app.name\" value=\"sparkTeradata\"></property>\n\t\t\t\t\t<property name=\"spark.driver.allowMultipleContexts\" value=\"true\"></property>\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>\n"
  },
  {
    "path": "src/kundera-spark/spark-teradata/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"teradata_spark_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.client.spark.Person</class>\r\n\t\t<!-- <class>com.impetus.client.spark.PersonTeradata</class> -->\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"192.168.145.80\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"7077\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"etloffload\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"spark\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"teradata\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.spark.client.SparkClientFactory\" />\r\n\t\t\t<property name=\"kundera.client.property\" value=\"KunderaSparkTeradataProperties.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n</persistence>\r\n"
  },
  {
    "path": "src/kundera-spark/spark-teradata/src/test/resources/teradata.properties",
    "content": "# Teradata Properties\nteradata.host=192.168.145.80\nteradata.user=dbc\nteradata.password=dbc"
  },
  {
    "path": "src/kundera-tests/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<parent>\n\t\t<groupId>com.impetus</groupId>\n\t\t<artifactId>kundera</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\t<groupId>com.impetus.kundera</groupId>\n\t<artifactId>kundera-tests</artifactId>\n\t<version>3.14-SNAPSHOT</version>\n\t<packaging>jar</packaging>\n\n\t<name>kundera-tests</name>\n\t<url>http://maven.apache.org</url>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t</properties>\n\n\t<!-- <scm> <connection>scm:svn:http://kundera.googlecode.com/svn/trunk</connection> \n\t\t<developerConnection>scm:svn:https://kundera.googlecode.com/svn/trunk</developerConnection> \n\t\t<url>http://kundera.googlecode.com/svn/trunk</url> <tag>HEAD</tag> </scm> \n\t\t<issueManagement> <system>Google Code</system> <url>http://code.google.com/p/kundera/issues/list</url> \n\t\t</issueManagement> <repositories> <repository> <id>kundera-missing</id> <name>Kundera \n\t\tPublic Missing Resources Repository</name> <url>http://kundera.googlecode.com/svn/maven2/maven-missing-resources</url> \n\t\t<releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> \n\t\t</snapshots> </repository> <repository> <id>riptano</id> <name>riptano</name> \n\t\t<url>http://mvn.riptano.com/content/repositories/public</url> </repository> \n\t\t<repository> <id>spring-milestone</id> <name>Spring Maven MILESTONE Repository</name> \n\t\t<url>http://maven.springframework.org/milestone</url> </repository> <repository> \n\t\t<id>morphia.googlecode.com</id> <name>Morphia Repo at Google Code</name> \n\t\t<url>http://morphia.googlecode.com/svn/mavenrepo</url> </repository> <repository> \n\t\t<id>sonatype-nexus</id> <name>Kundera Public Repository</name> <url>https://oss.sonatype.org/content/repositories/releases</url> \n\t\t<releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> \n\t\t</snapshots> </repository> </repositories> -->\n\n\t<reporting>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-checkstyle-plugin</artifactId>\n\t\t\t\t<version>2.3.2</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<configLocation>impetus_java5_checks.xml</configLocation>\n\t\t\t\t\t<suppressionsLocation>checkstyle-suppressions.xml</suppressionsLocation>\n\t\t\t\t\t<suppressionsFileExpression>checkstyle.suppressions.file</suppressionsFileExpression>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-site-plugin</artifactId>\n\t\t\t\t<version>2.0-beta-7</version>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-pmd-plugin</artifactId>\n\t\t\t\t<version>2.3</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<targetJdk>${compileSource}</targetJdk>\n\t\t\t\t\t<rulesets>\n\t\t\t\t\t\t<ruleset>impetus_pmd_ruleset.xml</ruleset>\n\t\t\t\t\t</rulesets>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-changes-plugin</artifactId>\n\t\t\t\t<version>2.3.2</version>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.codehaus.mojo</groupId>\n\t\t\t\t<artifactId>cobertura-maven-plugin</artifactId>\n\t\t\t\t<version>2.0</version>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t<version>2.9</version>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-jxr-plugin</artifactId>\n\t\t\t\t<version>2.3.2</version>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-surefire-report-plugin</artifactId>\n\t\t\t\t<version>2.5</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<forkMode>always</forkMode>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.codehaus.mojo</groupId>\n\t\t\t\t<artifactId>jdepend-maven-plugin</artifactId>\n\t\t\t\t<version>1.3</version>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.codehaus.mojo</groupId>\n\t\t\t\t<artifactId>javancss-maven-plugin</artifactId>\n\t\t\t\t<version>1.3</version>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.codehaus.mojo</groupId>\n\t\t\t\t<artifactId>dashboard-maven-plugin</artifactId>\n\t\t\t\t<version>1.3</version>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</reporting>\n\n\t<dependencies>\n\n\t\t<dependency>\n\t\t\t<groupId>org.hsqldb</groupId>\n\t\t\t<artifactId>hsqldb</artifactId>\n\t\t\t<version>2.2.9</version>\n\t\t\t<scope>test</scope>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>javassist</groupId>\n\t\t\t\t\t<artifactId>javassist</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>commons-collections</groupId>\n\t\t\t<artifactId>commons-collections</artifactId>\n\t\t\t<version>3.2.2</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>commons-lang</groupId>\n\t\t\t<artifactId>commons-lang</artifactId>\n\t\t\t<version>2.4</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>commons-logging</groupId>\n\t\t\t<artifactId>commons-logging</artifactId>\n\t\t\t<version>1.1.1</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>log4j</groupId>\n\t\t\t<artifactId>log4j</artifactId>\n\t\t\t<version>1.2.16</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.slf4j</groupId>\n\t\t\t<artifactId>slf4j-api</artifactId>\n\t\t\t<version>1.7.2</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>commons-codec</groupId>\n\t\t\t<artifactId>commons-codec</artifactId>\n\t\t\t<version>1.2</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>cglib</groupId>\n\t\t\t<artifactId>cglib</artifactId>\n\t\t\t<version>2.2</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.github.stephenc</groupId>\n\t\t\t<artifactId>jamm</artifactId>\n\t\t\t<version>0.2.2</version>\n\t\t</dependency>\n\t\t<!-- <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> \n\t\t\t<version>2.0</version> </dependency> -->\n\n\t\t<!-- <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> \n\t\t\t<version>2.2.0</version> </dependency> -->\n\n\t\t<!-- <dependency> <groupId>org.xerial</groupId> <artifactId>snappy</artifactId> \n\t\t\t<version>1.0.1-rc4</version> </dependency> -->\n\n\t\t<!-- Non public dependencies- being picked from kundera svn repository -->\n\t\t<!-- <dependency> <groupId>org.safehaus.jug</groupId> <artifactId>jug-asl</artifactId> \n\t\t\t<version>2.0.0</version> <scope>test</scope> </dependency> -->\n\n\t\t<dependency>\n\t\t\t<groupId>org.databene</groupId>\n\t\t\t<artifactId>contiperf</artifactId>\n\t\t\t<version>2.2.0</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>net.sourceforge.jexcelapi</groupId>\n\t\t\t<artifactId>jxl</artifactId>\n\t\t\t<version>2.6</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.apache.lucene</groupId>\n\t\t\t<artifactId>lucene-core</artifactId>\n\t\t\t<version>3.5.0</version>\n\t\t</dependency>\n\n\t\t<!-- kundera dependencies -->\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>fallback-impl</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>3.14-SNAPSHOT</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<artifactId>httpclient</artifactId>\n\t\t\t\t\t<groupId>org.apache.httpcomponents</groupId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-mongo</artifactId>\n\t\t\t<version>3.14-SNAPSHOT</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-hbase</artifactId>\n\t\t\t<version>3.14-SNAPSHOT</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.apache.thrift</groupId>\n\t\t\t\t\t<artifactId>libthrift</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>commons-httpclient</groupId>\n\t\t\t\t\t<artifactId>commons-httpclient</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-rdbms</artifactId>\n\t\t\t<version>3.14-SNAPSHOT</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-rest</artifactId>\n\t\t\t<version>3.14-SNAPSHOT</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-oracle-nosql</artifactId>\n\t\t\t<version>3.14-SNAPSHOT</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-redis</artifactId>\n\t\t\t<version>3.14-SNAPSHOT</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-neo4j</artifactId>\n\t\t\t<version>3.14-SNAPSHOT</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-couchdb</artifactId>\n\t\t\t<version>3.14-SNAPSHOT</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-elastic-search</artifactId>\n\t\t\t<version>3.14-SNAPSHOT</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.apache.lucene</groupId>\n\t\t\t\t\t<artifactId>lucene-core</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t\t<!-- kundera tests dependencies -->\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.core</groupId>\n\t\t\t<artifactId>kundera-core</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<artifactId>httpclient</artifactId>\n\t\t\t\t\t<groupId>org.apache.httpcomponents</groupId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-mongo</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-hbase</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.apache.thrift</groupId>\n\t\t\t\t\t<artifactId>libthrift</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>commons-httpclient</groupId>\n\t\t\t\t\t<artifactId>commons-httpclient</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-rdbms</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-rest</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-couchdb</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>directory-naming</groupId>\n\t\t\t\t\t<artifactId>naming-java</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-redis</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-neo4j</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-elastic-search</artifactId>\n\t\t\t<version>${project.version}</version>\n\t\t\t<type>test-jar</type>\n\t\t\t<scope>test</scope>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.apache.lucene</groupId>\n\t\t\t\t\t<artifactId>lucene-core</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t\t<!-- <dependency> <groupId>com.impetus.kundera.client</groupId> <artifactId>kundera-oracle-nosql</artifactId> \n\t\t\t<version>2.5-SNAPSHOT</version> <type>test-jar</type> <scope>test</scope> \n\t\t\t</dependency> -->\n\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.8.2</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\n\t\t<!-- Unit Testing libraries -->\n\t\t<dependency>\n\t\t\t<groupId>com.sun.jersey.jersey-test-framework</groupId>\n\t\t\t<artifactId>jersey-test-framework-grizzly</artifactId>\n\t\t\t<version>1.12</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.sun.grizzly</groupId>\n\t\t\t<artifactId>grizzly-servlet-webserver</artifactId>\n\t\t\t<version>1.9.8</version>\n\t\t</dependency>\n\n\t\t<!-- <dependency> <groupId>org.apache.openejb</groupId> <artifactId>openejb-core</artifactId> \n\t\t\t<version>3.1</version> <scope>test</scope> </dependency> -->\n\t\t<dependency>\n\t\t\t<groupId>directory-naming</groupId>\n\t\t\t<artifactId>naming-java</artifactId>\n\t\t\t<version>0.8</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<version>2.3.2</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t\t<addClasspath>true</addClasspath>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-surefire-plugin</artifactId>\n\t\t\t\t<version>2.5</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<forkMode>once</forkMode>\n\t\t\t\t\t<argLine>-Xms256m -Xmx512m</argLine>\n\t\t\t\t</configuration>\n\t\t\t\t<dependencies>\n\t\t\t\t\t<dependency>\n\t\t\t\t\t\t<groupId>org.apache.maven.surefire</groupId>\n\t\t\t\t\t\t<artifactId>surefire-junit47</artifactId>\n\t\t\t\t\t\t<version>2.12</version>\n\t\t\t\t\t</dependency>\n\t\t\t\t</dependencies>\n\t\t\t</plugin>\n\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.3.2</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<archive>\n\t\t\t\t\t\t<manifest>\n\t\t\t\t\t\t\t<addClasspath>true</addClasspath>\n\t\t\t\t\t\t\t<classpathPrefix>/lib</classpathPrefix>\n\t\t\t\t\t\t</manifest>\n\t\t\t\t\t</archive>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-checkstyle-plugin</artifactId>\n\t\t\t\t<version>2.3.2</version>\n\t\t\t\t<dependencies>\n\t\t\t\t\t<dependency>\n\t\t\t\t\t\t<groupId>com.impetus.ilabs.build</groupId>\n\t\t\t\t\t\t<artifactId>checkstyle-config</artifactId>\n\t\t\t\t\t\t<version>1</version>\n\t\t\t\t\t</dependency>\n\t\t\t\t</dependencies>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-pmd-plugin</artifactId>\n\t\t\t\t<version>2.3</version>\n\t\t\t\t<dependencies>\n\t\t\t\t\t<dependency>\n\t\t\t\t\t\t<groupId>com.impetus.ilabs.build</groupId>\n\t\t\t\t\t\t<artifactId>pmd-config</artifactId>\n\t\t\t\t\t\t<version>1</version>\n\t\t\t\t\t</dependency>\n\t\t\t\t</dependencies>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-clean-plugin</artifactId>\n\t\t\t\t<version>2.5</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<filesets>\n\t\t\t\t\t\t<fileset>\n\t\t\t\t\t\t\t<directory>${basedir}</directory>\n\t\t\t\t\t\t\t<includes>\n\t\t\t\t\t\t\t\t<include>cobertura.ser</include>\n\t\t\t\t\t\t\t</includes>\n\t\t\t\t\t\t</fileset>\n\t\t\t\t\t</filesets>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> \n\t\t\t\t<configuration> <systemProperties> <property> <name>fileName</name> <value>${fileName}</value> \n\t\t\t\t</property> </systemProperties> </configuration> </plugin> --> \t\t\t<!-- <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> \n\t\t\t\t<configuration> The destination file for the code coverage report has to \n\t\t\t\tbe set to the same value in the parent pom and in each module pom. Then JaCoCo \n\t\t\t\twill add up information in the same report, so that, it will give the cross-module \n\t\t\t\tcode coverage. <destFile>${project.basedir}/../target/jacoco-it.exec</destFile> \n\t\t\t\t</configuration> <executions> <execution> <id>post-test</id> <configuration> \n\t\t\t\t<skip>true</skip> </configuration> </execution> </executions> </plugin> -->\n\t\t</plugins>\n\t</build>\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>doclint-java8-disable</id>\n\t\t\t<activation>\n\t\t\t\t<jdk>[1.8,)</jdk>\n\t\t\t</activation>\n\n\t\t\t<build>\n\t\t\t\t<plugins>\n\t\t\t\t\t<plugin>\n\t\t\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<additionalparam>-Xdoclint:none</additionalparam>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</plugin>\n\t\t\t\t</plugins>\n\t\t\t</build>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "src/kundera-tests/src/main/java/com/impetus/kundera/benchmark/ReadCSVFile.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.benchmark;\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.StringTokenizer;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Read CSV File class reads the csv file.\n * \n * @author Kuldeep Mishra\n * \n */\npublic class ReadCSVFile\n{\n    public static String[] cvsSheetColumnName = new String[] { \"serviceId\", \"duration\", \"invocations\", \"average\", \"\" };\n\n    public static Map<String, Integer> columnFieldIndexMap = new HashMap<String, Integer>();\n\n    private static final Logger log = LoggerFactory.getLogger(ReadCSVFile.class);\n\n    /**\n     * Return csv file content as a map.\n     * \n     * @param csvFile\n     * @return\n     */\n    public static Map<String, TestResult> getCSVFileInfo(String csvFile)\n    {\n        Map<String, TestResult> testCaseDataMap = new HashMap<String, TestResult>();\n        Map<String, String> summatyFieldToValueMap = new HashMap<String, String>();\n        String serviceId = null;\n        String duration = null;\n        String invocations = null;\n        String average = null;\n\n        if (csvFile != null)\n        {\n            FileReader fileReader = null;\n            try\n            {\n                fileReader = new FileReader(csvFile);\n            }\n            catch (Exception e)\n            {\n                log.error(\"File not found : \" + e);\n            }\n            try\n            {\n                if (fileReader != null)\n                {\n\n                    BufferedReader br = new BufferedReader(fileReader);\n                    log.info(\"Reading file : \" + csvFile);\n                    String line = \"\";\n                    StringTokenizer st = null;\n\n                    int lineNumber = 0;\n                    int tokenNumber = 0;\n\n                    // read comma separated file line by line\n                    while ((line = br.readLine()) != null)\n                    {\n\n                        lineNumber++;\n                        int i = 0;\n                        // use comma as token separator\n                        st = new StringTokenizer(line, \",\");\n\n                        while (st.hasMoreTokens())\n                        {\n                            tokenNumber++;\n                            // display csv values\n                            String token = st.nextToken();\n\n                            if (lineNumber == 1)\n                            {\n                                if (token.equals(cvsSheetColumnName[i]))\n                                {\n                                    columnFieldIndexMap.put(cvsSheetColumnName[i], tokenNumber);\n                                    i++;\n                                }\n                            }\n                            else\n                            {\n                                if (i < 4 && tokenNumber == columnFieldIndexMap.get(cvsSheetColumnName[i]))\n                                {\n                                    summatyFieldToValueMap.put(cvsSheetColumnName[i], token);\n                                    i++;\n                                }\n                            }\n                        }\n                        serviceId = summatyFieldToValueMap.get(cvsSheetColumnName[0]);\n                        duration = summatyFieldToValueMap.get(cvsSheetColumnName[1]);\n                        invocations = summatyFieldToValueMap.get(cvsSheetColumnName[2]);\n                        average = summatyFieldToValueMap.get(cvsSheetColumnName[3]);\n                        if (serviceId != null)\n                        {\n                            testCaseDataMap.put(serviceId,\n                                    new TestResult(duration != null ? Double.parseDouble(duration) : Double.NaN,\n                                            invocations != null ? Integer.parseInt(invocations) : 0,\n                                            average != null ? Double.parseDouble(average) : Double.NaN));\n                        }\n                        // reset token number\n                        tokenNumber = 0;\n                    }\n                }\n            }\n            catch (IOException e)\n            {\n                log.error(\"CSV file cannot be read : \" + e);\n            }\n            return testCaseDataMap;\n        }\n        return testCaseDataMap;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/main/java/com/impetus/kundera/benchmark/TestResult.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.benchmark;\n\n/**\n * Keeps the metadata of test result.\n * \n * @author Kuldeep Mishra\n * \n */\npublic class TestResult\n{\n    private Double totalTimeTaken;\n\n    private Integer noOfInvocation;\n\n    private Double avgTime;\n\n    private Double delta;\n\n    /**\n     * \n     */\n    public TestResult()\n    {\n\n    }\n\n    /**\n     * \n     */\n    public TestResult(Double totalTimeTaken, Integer noOfInvocation, Double avgTime)\n    {\n        this.totalTimeTaken = totalTimeTaken;\n        this.noOfInvocation = noOfInvocation;\n        this.avgTime = avgTime;\n    }\n\n    /**\n     * @return the totalTimeTaken\n     */\n    public Double getTotalTimeTaken()\n    {\n        return totalTimeTaken;\n    }\n\n    /**\n     * @param totalTimeTaken\n     *            the totalTimeTaken to set\n     */\n    public void setTotalTimeTaken(Double totalTimeTaken)\n    {\n        this.totalTimeTaken = totalTimeTaken;\n    }\n\n    /**\n     * @return the noOfInvocation\n     */\n    public Integer getNoOfInvocation()\n    {\n        return noOfInvocation;\n    }\n\n    /**\n     * @param noOfInvocation\n     *            the noOfInvocation to set\n     */\n    public void setNoOfInvocation(Integer noOfInvocation)\n    {\n        this.noOfInvocation = noOfInvocation;\n    }\n\n    /**\n     * @return the avgTime\n     */\n    public Double getAvgTime()\n    {\n        return avgTime;\n    }\n\n    /**\n     * @param avgTime\n     *            the avgTime to set\n     */\n    public void setAvgTime(Double avgTime)\n    {\n        this.avgTime = avgTime;\n    }\n\n    /**\n     * @return the delta\n     */\n    public Double getDelta()\n    {\n        return delta;\n    }\n\n    /**\n     * @param delta\n     *            the delta to set\n     */\n    public void setDelta(Double delta)\n    {\n        this.delta = delta;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/main/java/com/impetus/kundera/benchmark/WriteToExcelFile.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.benchmark;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Locale;\nimport java.util.Map;\n\nimport jxl.CellView;\nimport jxl.Workbook;\nimport jxl.WorkbookSettings;\nimport jxl.format.UnderlineStyle;\nimport jxl.write.Label;\nimport jxl.write.Number;\nimport jxl.write.WritableCellFormat;\nimport jxl.write.WritableFont;\nimport jxl.write.WritableSheet;\nimport jxl.write.WritableWorkbook;\nimport jxl.write.WriteException;\nimport jxl.write.biff.RowsExceededException;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * WriteToExcelFile class responsible create a excel file and write content into\n * it.\n * \n * @author Kuldeep Mishra\n * \n */\npublic class WriteToExcelFile\n{\n    private WritableCellFormat timesBoldUnderline;\n\n    private WritableCellFormat times;\n\n    private String inputFile;\n\n    private static final Logger log = LoggerFactory.getLogger(WriteToExcelFile.class);\n\n    public void setOutputFile(String inputFile)\n    {\n        this.inputFile = inputFile;\n    }\n\n    /**\n     * write into excel file.\n     * \n     * @param map\n     * @param testSummatyField\n     * @throws IOException\n     * @throws WriteException\n     */\n    public void write(Map<String, TestResult> map, String[] testSummatyField) throws IOException, WriteException\n    {\n        log.info(\"Writing file : \" + inputFile);\n        File file = new File(inputFile);\n        WorkbookSettings wbSettings = new WorkbookSettings();\n\n        wbSettings.setLocale(new Locale(\"en\", \"EN\"));\n\n        WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);\n        workbook.createSheet(\"PerformanceBenchmark\", 0);\n        WritableSheet excelSheet = workbook.getSheet(0);\n        createLabel(excelSheet, testSummatyField);\n        createContent(excelSheet, map);\n\n        workbook.write();\n        workbook.close();\n    }\n\n    /**\n     * create column\n     * \n     * @param sheet\n     * @param testSummatyField\n     * @throws WriteException\n     */\n    private void createLabel(WritableSheet sheet, String[] testSummatyField) throws WriteException\n    {\n        // Lets create a times font\n        WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);\n        // Define the cell format\n        times = new WritableCellFormat(times10pt);\n        // Lets automatically wrap the cells\n        times.setWrap(true);\n\n        // Create create a bold font with unterlines\n        WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false,\n                UnderlineStyle.SINGLE);\n        timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);\n        // Lets automatically wrap the cells\n        timesBoldUnderline.setWrap(true);\n\n        CellView cv = new CellView();\n        cv.setFormat(times);\n        cv.setFormat(timesBoldUnderline);\n        // cv.setSize(111);\n\n        // Write a few headers\n        addCaption(sheet, 0, 0, testSummatyField[0]);\n        addCaption(sheet, 1, 0, testSummatyField[1]);\n        addCaption(sheet, 2, 0, testSummatyField[2]);\n        addCaption(sheet, 3, 0, testSummatyField[3]);\n        addCaption(sheet, 4, 0, testSummatyField[4]);\n\n    }\n\n    /**\n     * put content\n     * \n     * @param sheet\n     * @param map\n     * @throws WriteException\n     * @throws RowsExceededException\n     */\n    private void createContent(WritableSheet sheet, Map<String, TestResult> map) throws WriteException,\n            RowsExceededException\n    {\n        int i = 0;\n        int j = 1;\n        for (String s : map.keySet())\n        {\n            addLabel(sheet, i++, j, s);\n            TestResult data = map.get(s);\n            if (data != null)\n            {\n                addNumber(sheet, i++, j, data.getTotalTimeTaken());\n                addNumber(sheet, i++, j, data.getNoOfInvocation());\n                addNumber(sheet, i++, j, data.getAvgTime());\n\n                addNumber(sheet, i++, j, data.getDelta() != null ? data.getDelta() : 0);\n            }\n            i = 0;\n            j++;\n        }\n    }\n\n    private void addCaption(WritableSheet sheet, int column, int row, String s) throws RowsExceededException,\n            WriteException\n    {\n        Label label;\n        label = new Label(column, row, s, timesBoldUnderline);\n        sheet.addCell(label);\n    }\n\n    private void addNumber(WritableSheet sheet, int column, int row, Integer integer) throws WriteException,\n            RowsExceededException\n    {\n        Number number;\n        number = new Number(column, row, integer, times);\n        sheet.addCell(number);\n    }\n\n    private void addNumber(WritableSheet sheet, int column, int row, Double doubleNumber) throws WriteException,\n            RowsExceededException\n    {\n        Number number;\n        number = new Number(column, row, doubleNumber, times);\n        sheet.addCell(number);\n    }\n\n    private void addLabel(WritableSheet sheet, int column, int row, Object s) throws WriteException,\n            RowsExceededException\n    {\n        Label label;\n        label = new Label(column, row, s.toString(), times);\n        sheet.addCell(label);\n    }\n\n    /**\n     * Create a excel file and write into it.\n     * \n     * @param map\n     * @param fileName\n     * @param testSummatyField\n     * @throws WriteException\n     * @throws IOException\n     */\n    public static void writeInXlsFile(Map<String, TestResult> map, String fileName, String[] testSummatyField)\n            throws WriteException, IOException\n    {\n        WriteToExcelFile excelFile = new WriteToExcelFile();\n        excelFile.setOutputFile(fileName);\n\n        excelFile.write(map, testSummatyField);\n        log.info(\"Please check the result file under \" + testSummatyField);\n    }\n}"
  },
  {
    "path": "src/kundera-tests/src/main/java/com/impetus/kundera/tests/crossdatastore/pickr/dao/Pickr.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.tests.crossdatastore.pickr.dao;\r\n\r\nimport java.util.List;\r\n\r\n/**\r\n * Interface for Pickr application\r\n * \r\n * @author amresh.singh\r\n */\r\npublic interface Pickr\r\n{\r\n    void addPhotographer(Object p);\r\n\r\n    Object getPhotographer(Class<?> entityClass, Integer photographerId);\r\n\r\n    public List<Object> getAllPhotographers(String className);\r\n\r\n    public void deletePhotographer(Object p);\r\n\r\n    public void mergePhotographer(Object p);\r\n\r\n    public void close();\r\n}\r\n"
  },
  {
    "path": "src/kundera-tests/src/main/java/com/impetus/kundera/tests/crossdatastore/pickr/dao/PickrImpl.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.tests.crossdatastore.pickr.dao;\r\n\r\nimport java.util.List;\r\n\r\nimport javax.persistence.EntityManager;\r\nimport javax.persistence.EntityManagerFactory;\r\nimport javax.persistence.Persistence;\r\nimport javax.persistence.Query;\r\n\r\n/**\r\n * Implementation class for Pickr functionality\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\npublic class PickrImpl implements Pickr\r\n{\r\n\r\n    EntityManagerFactory emf;\r\n\r\n    EntityManager em;\r\n\r\n    public PickrImpl(String persistenceUnitName)\r\n    {\r\n        if (emf == null)\r\n        {\r\n            emf = Persistence.createEntityManagerFactory(persistenceUnitName);\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void addPhotographer(Object p)\r\n    {\r\n        closeEntityManager();\r\n        EntityManager em = getEntityManager();\r\n        em.persist(p);\r\n        closeEntityManager();\r\n    }\r\n\r\n    @Override\r\n    public Object getPhotographer(Class<?> entityClass, Integer photographerId)\r\n    {\r\n        EntityManager em = getEntityManager();\r\n        Object p = em.find(entityClass, photographerId);\r\n        return p;\r\n    }\r\n\r\n    @Override\r\n    public List<Object> getAllPhotographers(String className)\r\n    {\r\n        EntityManager em = getEntityManager();\r\n        Query q = em.createQuery(\"select p from \" + className + \" p\");\r\n        List<Object> photographers = q.getResultList();\r\n        //closeEntityManager();\r\n        return photographers;\r\n    }\r\n\r\n    @Override\r\n    public void deletePhotographer(Object p)\r\n    {\r\n        EntityManager em = getEntityManager();\r\n        em.remove(p);\r\n        closeEntityManager();\r\n    }\r\n\r\n    @Override\r\n    public void mergePhotographer(Object p)\r\n    {\r\n        EntityManager em = getEntityManager();\r\n        em.merge(p);\r\n        closeEntityManager();\r\n    }\r\n\r\n    EntityManager getEntityManager()\r\n    {\r\n        if (em == null)\r\n        {\r\n            em = emf.createEntityManager();\r\n        }\r\n        return em;\r\n    }\r\n\r\n    void closeEntityManager()\r\n    {\r\n        if (em != null)\r\n        {\r\n            em.close();\r\n            em = null;\r\n        }\r\n    }\r\n\r\n    @Override\r\n    public void close()\r\n    {\r\n        closeEntityManager();\r\n        emf.close();\r\n    }\r\n\r\n}"
  },
  {
    "path": "src/kundera-tests/src/main/java/com/impetus/kundera/tests/crossdatastore/useraddress/dao/BaseDao.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.dao;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport com.impetus.client.cassandra.common.CassandraConstants;\nimport com.impetus.kundera.PersistenceProperties;\n\npublic class BaseDao\n{\n\n    EntityManagerFactory emf;\n\n    EntityManager em;\n\n    public EntityManager getEntityManager(String pu, Map propertyMap)\n    {\n        if (emf == null)\n        {\n            if (propertyMap.isEmpty())\n            {\n                propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_3_0);\n                propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"\");\n            }\n            Map mapOfExternalProperties = new HashMap<String, Map>();\n            mapOfExternalProperties.put(\"addCassandra\", propertyMap);\n            mapOfExternalProperties.put(\"piccandra\", propertyMap);\n            mapOfExternalProperties.put(\"secIdxAddCassandra\", propertyMap);\n            emf = Persistence.createEntityManagerFactory(pu, mapOfExternalProperties);\n            em = emf.createEntityManager();\n        }\n\n        if (em == null)\n        {\n            em = emf.createEntityManager();\n        }\n\n        return em;\n    }\n\n    public EntityManager getEntityManager(String pu)\n    {\n        if (emf == null)\n        {\n            emf = Persistence.createEntityManagerFactory(pu, new HashMap());\n            em = emf.createEntityManager();\n        }\n\n        if (em == null)\n        {\n            em = emf.createEntityManager();\n        }\n\n        return em;\n    }\n\n    public void closeEntityManager()\n    {\n        if (em != null)\n        {\n            em.close();\n            em = null;\n        }\n    }\n\n    public void closeEntityManagerFactory()\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n        emf = null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/main/java/com/impetus/kundera/tests/crossdatastore/useraddress/dao/UserAddressDaoImpl.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.dao;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\npublic class UserAddressDaoImpl extends BaseDao\n{\n    private String persistenceUnit;\n\n    public UserAddressDaoImpl(String pu)\n    {\n        this.persistenceUnit = pu;\n    }\n\n    public Query createQuery(String query)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n        Query q = em.createQuery(query);\n        return q;\n    }\n\n    public void insert(Object person)\n    {\n        em = getEntityManager(persistenceUnit);\n        em.persist(person);\n        closeEntityManager();\n    }\n\n    public void update(Object obj)\n    {\n        em.merge(obj);\n        closeEntityManager();\n    }\n\n    public Object findPerson(Class entityClass, Object personId)\n    {\n        if (em != null)\n            em.clear();\n        em = getEntityManager(persistenceUnit);\n        Object personnel = em.find(entityClass, personId);\n        return personnel;\n    }\n\n    public void savePersons(Set<?> personnels)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n\n        for (Object personnel : personnels)\n        {\n            em.persist(personnel);\n        }\n\n        closeEntityManager();\n    }\n\n    public void remove(Object pKey, Class clazz)\n    {\n        em = getEntityManager(persistenceUnit);\n        Object obj = em.find(clazz, pKey);\n        em.remove(obj);\n        closeEntityManager();\n    }\n\n    public void merge(Object modifiedObj)\n    {\n        em = getEntityManager(persistenceUnit);\n        em.merge(modifiedObj);\n        closeEntityManager();\n\n    }\n\n    public List<?> getAllPersons(String className)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n        Query q = em.createQuery(\"select p from \" + className + \" p\");\n        List<?> persons = q.getResultList();\n        closeEntityManager();\n        return persons;\n    }\n\n    public Object findPersonByIdColumn(Class entityClass, Object personId)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n        String query = \"Select p from \" + entityClass.getSimpleName() + \" p where p.personId = '\" + personId + \"'\";\n        Query q = em.createQuery(query);\n        List persons = q.getResultList();\n        // closeEntityManager();\n        assert persons != null;\n        assert !persons.isEmpty();\n        assert persons.size() == 1;\n\n        return persons.get(0);\n    }\n\n    public List findPersonByName(Class entityClass, String personName)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n        String query = \"Select p from \" + entityClass.getSimpleName() + \" p where p.personName = '\" + personName + \"'\";\n        Query q = em.createQuery(query);\n        List persons = q.getResultList();\n        // closeEntityManager();\n\n        return persons;\n    }\n\n    public Object findAddressByIdColumn(Class entityClass, Object addressId)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n        String query = \"Select a from \" + entityClass.getSimpleName() + \" a where a.addressId = '\" + addressId + \"'\";\n        Query q = em.createQuery(query);\n        List addresses = q.getResultList();\n        closeEntityManager();\n        assert addresses != null;\n        assert !addresses.isEmpty();\n        assert addresses.size() == 1;\n\n        return addresses.get(0);\n    }\n\n    public List findAddressByStreet(Class entityClass, String street)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n        String query = \"Select a from \" + entityClass.getSimpleName() + \" a where a.street = '\" + street + \"'\";\n        Query q = em.createQuery(query);\n        List addresses = q.getResultList();\n        closeEntityManager();\n\n        return addresses;\n    }\n\n}"
  },
  {
    "path": "src/kundera-tests/src/main/resources/applicationContext.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<beans xmlns=\"http://www.springframework.org/schema/beans\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:aop=\"http://www.springframework.org/schema/aop\"\n\txsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n\t\n\t<bean id=\"springExampleDao\" class=\"com.impetus.kundera.examples.spring.SpringExampleDao\">\n\t\t<property name=\"entityManagerFactory\" ref=\"entityManagerFactory\" />\n\t</bean>\t\n\t\n\t<bean id=\"entityManagerFactory\"\n\t\tclass=\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\">\n\t\t<property name=\"persistenceUnitName\" value=\"twissandra\" />\n\t</bean>\t\n</beans>"
  },
  {
    "path": "src/kundera-tests/src/main/resources/kundera-cassandra.properties",
    "content": "replication_facotr = 1\nplacement_strategy = org.apache.cassandra.locator.SimpleStrategy"
  },
  {
    "path": "src/kundera-tests/src/main/resources/log4j-server.properties",
    "content": "# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nlog4j.rootLogger=WARN, DRFA, CONSOLE\n\n# rolling log file (\"system.log\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\nlog4j.appender.DRFA.DatePattern='.'yyyy-MM-dd-HH\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\nlog4j.appender.DRFA.File=/var/log/kundera.log\n\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n"
  },
  {
    "path": "src/kundera-tests/src/main/resources/log4j.properties",
    "content": "log4j.rootLogger=ERROR, DRFA, CONSOLE\r\n\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/benchmark/PerformanceTestsSuite.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.benchmark;\n\nimport java.io.IOException;\nimport java.util.Map;\n\nimport jxl.write.WriteException;\n\nimport org.databene.contiperf.PerfTest;\nimport org.databene.contiperf.junit.ContiPerfRule;\nimport org.databene.contiperf.junit.ContiPerfSuiteRunner;\nimport org.databene.contiperf.report.CSVSummaryReportModule;\nimport org.databene.contiperf.report.HtmlReportModule;\nimport org.databene.contiperf.report.ReportModule;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Rule;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Suite.SuiteClasses;\n\nimport com.impetus.client.RedisClientTest;\nimport com.impetus.client.gis.MongoGISTest;\n\n/**\n * A test suite for performance benchmarking , add test classes in\n * {@code @SuiteClasses} to benchmark.\n * \n * @author Kuldeep Mishra\n * \n */\n@SuiteClasses({ MongoGISTest.class, RedisClientTest.class })\n@PerfTest(threads = 1, invocations = 2)\n@RunWith(ContiPerfSuiteRunner.class)\npublic class PerformanceTestsSuite\n{\n    private static String[] excelSheetColumnName = new String[] { \"serviceId\", \"duration\", \"invocations\", \"average\",\n            \"averagedelta\" };\n\n    private static String csvFile = \"./target/contiperf-report/summary.csv\";\n\n    private static String xlsFile = null;\n\n    private static Map<String, TestResult> testCaseDataMapBefore;\n\n    private static Map<String, TestResult> testCaseDataMapAfter;\n\n    @Rule\n    public ContiPerfRule i = new ContiPerfRule(new ReportModule[] { new CSVSummaryReportModule(),\n            new HtmlReportModule() });\n\n    @BeforeClass\n    public static void beforeClass() throws IOException\n    {\n        testCaseDataMapBefore = ReadCSVFile.getCSVFileInfo(csvFile);\n        xlsFile = System.getProperty(\"fileName\");\n    }\n\n    @AfterClass\n    public static void afterClass() throws IOException, WriteException\n    {\n        testCaseDataMapAfter = ReadCSVFile.getCSVFileInfo(csvFile);\n        generateDelta(testCaseDataMapBefore, testCaseDataMapAfter);\n        if (xlsFile != null)\n        {\n            WriteToExcelFile.writeInXlsFile(testCaseDataMapAfter, xlsFile, excelSheetColumnName);\n        }\n    }\n\n    /**\n     * @param testCaseDataMapBefore2\n     * @param testCaseDataMapAfter2\n     */\n    private static void generateDelta(Map<String, TestResult> testCaseDataMapBefore,\n            Map<String, TestResult> testCaseDataMapAfter)\n    {\n        if (testCaseDataMapBefore != null && !testCaseDataMapBefore.isEmpty() && testCaseDataMapAfter != null\n                && !testCaseDataMapAfter.isEmpty())\n        {\n            for (String s : testCaseDataMapBefore.keySet())\n            {\n                TestResult afterTestResult = testCaseDataMapAfter.get(s);\n                if (afterTestResult != null)\n                {\n                    Double avgDelta = (((double) (testCaseDataMapBefore.get(s).getAvgTime() - afterTestResult\n                            .getAvgTime())) / (testCaseDataMapBefore.get(s).getAvgTime())) / 100;\n                    afterTestResult.setDelta(avgDelta);\n                }\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/cli/CleanupUtilities.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.cli;\n\nimport java.io.File;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\n\n/**\n * Provides utility methods for all Kundera Examples test cases\n * \n * @author amresh.singh\n */\npublic class CleanupUtilities\n{\n    /** The log. */\n    private static Logger log = LoggerFactory.getLogger(CleanupUtilities.class);\n\n    public static void cleanLuceneDirectory(PersistenceUnitMetadata puMetadata)\n    {\n        if (puMetadata != null)\n        {\n            String luceneDir = puMetadata.getProperty(PersistenceProperties.KUNDERA_INDEX_HOME_DIR);\n            if (luceneDir != null && luceneDir.length() > 0)\n            {\n                log.debug(\"Cleaning up lucene folder \" + luceneDir);\n                File directory = new File(luceneDir);\n                // Get all files in directory\n                File[] files = directory.listFiles();\n                for (File file : files)\n                {\n                    // Delete each file\n                    if (!file.delete())\n                    {\n                        // Failed to delete file\n                        log.info(\"Failed to delete \" + file);\n                    }\n                }\n            }\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/EntityInTwoDatabaseTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2014 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.tests.entities.CommonUser;\n\n/**\n * Test a single entity associated with two persistence unit, inside same JVM.\n * \n * @author Kuldeep Mishra\n * \n */\npublic class EntityInTwoDatabaseTest\n{\n    // For mongodb.\n    private EntityManagerFactory emfMongo;\n\n    // For couchdb.\n    private EntityManagerFactory emfCouchdb;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        emfMongo = Persistence.createEntityManagerFactory(\"commonMongo\");\n\n        emfCouchdb = Persistence.createEntityManagerFactory(\"commonCouchdb\");\n    }\n\n    @Test\n    public void test()\n    {\n\n        CommonUser user1 = new CommonUser();\n        user1.setFirstName(\"Kuldeep\");\n        user1.setUserId(\"1\");\n        user1.setLastName(\"Mishra\");\n\n        CommonUser user2 = new CommonUser();\n        user2.setFirstName(\"Vivek\");\n        user2.setUserId(\"2\");\n        user2.setLastName(\"Mishra\");\n\n        EntityManager emMongo = emfMongo.createEntityManager();\n\n        EntityManager emCouchdb = emfCouchdb.createEntityManager();\n\n        emMongo.persist(user1);\n        emCouchdb.persist(user2);\n\n        emMongo.clear();\n        emCouchdb.clear();\n\n        CommonUser foundUserMongo = emMongo.find(CommonUser.class, \"1\");\n\n        CommonUser foundUserCouchdb = emCouchdb.find(CommonUser.class, \"2\");\n\n        Assert.assertNotNull(foundUserCouchdb);\n        Assert.assertEquals(\"2\", foundUserCouchdb.getUserId());\n        Assert.assertEquals(\"Mishra\", foundUserCouchdb.getLastName());\n        Assert.assertEquals(\"Vivek\", foundUserCouchdb.getFirstName());\n        Assert.assertNotNull(foundUserMongo);\n        Assert.assertEquals(\"1\", foundUserMongo.getUserId());\n        Assert.assertEquals(\"Mishra\", foundUserMongo.getLastName());\n        Assert.assertEquals(\"Kuldeep\", foundUserMongo.getFirstName());\n\n        foundUserCouchdb.setFirstName(\"KK\");\n\n        foundUserMongo.setFirstName(\"vivs\");\n\n        emCouchdb.merge(foundUserCouchdb);\n        emMongo.merge(foundUserMongo);\n\n        emMongo.clear();\n        emCouchdb.clear();\n\n        CommonUser updatedUserMongo = emMongo.find(CommonUser.class, \"1\");\n\n        CommonUser updatedUserCouchdb = emCouchdb.find(CommonUser.class, \"2\");\n\n        Assert.assertNotNull(updatedUserCouchdb);\n        Assert.assertEquals(\"2\", updatedUserCouchdb.getUserId());\n        Assert.assertEquals(\"Mishra\", updatedUserCouchdb.getLastName());\n        Assert.assertEquals(\"KK\", updatedUserCouchdb.getFirstName());\n        Assert.assertNotNull(updatedUserMongo);\n        Assert.assertEquals(\"1\", updatedUserMongo.getUserId());\n        Assert.assertEquals(\"Mishra\", updatedUserMongo.getLastName());\n        Assert.assertEquals(\"vivs\", updatedUserMongo.getFirstName());\n\n        emMongo.remove(updatedUserMongo);\n        emCouchdb.remove(updatedUserCouchdb);\n\n        CommonUser deletedUserMongo = emMongo.find(CommonUser.class, \"1\");\n\n        CommonUser deletedUserCouchdb = emCouchdb.find(CommonUser.class, \"2\");\n\n        Assert.assertNull(deletedUserMongo);\n        Assert.assertNull(deletedUserCouchdb);\n\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        emfMongo.close();\n        emfCouchdb.close();\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/generatedId/AddressMongoGeneratedId.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.generatedId;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"AddressMongoGeneratedId\", schema=\"KunderaTests@addMongo\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressMongoGeneratedId\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    @GeneratedValue()\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/generatedId/CrossdatastoreGeneratedIdTest.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.tests.crossdatastore.generatedId;\n\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.crud.RDBMSCli;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author impadmin\n * \n */\npublic class CrossdatastoreGeneratedIdTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private RDBMSCli cli;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        emf = Persistence.createEntityManagerFactory(\"secIdxAddCassandra,addMongo\");\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        CassandraCli.dropKeySpace(\"KunderaTests\");\n    }\n\n    @Test\n    public void test()\n    {\n        AddressMongoGeneratedId address = new AddressMongoGeneratedId();\n        address.setStreet(\"sector 20, G Block\");\n\n        UserCassandraGeneratedId user = new UserCassandraGeneratedId();\n        user.setAddress(address);\n        user.setPersonName(\"Kuldeep\");\n\n        em.persist(user);\n\n        em.clear();\n\n        List<UserCassandraGeneratedId> result = em.createQuery(\"Select u from UserCassandraGeneratedId u\")\n                .getResultList();\n        Assert.assertNotNull(result);\n        Assert.assertEquals(1, result.size());\n        Assert.assertNotNull(result.get(0).getAddress());\n        Assert.assertEquals(\"sector 20, G Block\", result.get(0).getAddress().getStreet());\n        Assert.assertEquals(\"Kuldeep\", result.get(0).getPersonName());\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/generatedId/UserCassandraGeneratedId.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.generatedId;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"UserCassandraGeneratedId\", schema=\"KunderaTests@secIdxAddCassandra\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class UserCassandraGeneratedId\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    @GeneratedValue(strategy = GenerationType.TABLE)\n    private int personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressMongoGeneratedId address;\n\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public AddressMongoGeneratedId getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressMongoGeneratedId address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/imdb/AssociationBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.imdb;\n\nimport java.io.IOException;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.metamodel.Metamodel;\n\nimport org.apache.cassandra.locator.SimpleStrategy;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport redis.clients.jedis.Jedis;\n\nimport com.impetus.client.crud.RDBMSCli;\nimport com.impetus.client.redis.RedisPropertyReader;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.CoreMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.proxy.cglib.CglibLazyInitializerFactory;\nimport com.impetus.kundera.tests.cli.CleanupUtilities;\nimport com.impetus.kundera.tests.crossdatastore.imdb.dao.IMDBDaoImpl;\n\n/**\n * The Class AssociationBase.\n * \n * @author vivek.mishra\n */\npublic abstract class AssociationBase\n{\n    protected static final String KEYSPACE = \"imdb\";\n\n    protected static final String MOVIE = \"MOVIE\";\n\n    protected static final String ACTOR = \"ACTOR\";\n\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\n\n    protected EntityManager em;\n\n    protected IMDBDaoImpl dao;\n\n    protected KunderaMetadata kunderaMetadata;\n\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(AssociationBase.class);\n\n    /** The col families. */\n    private String[] colFamilies;\n\n    protected RDBMSCli cli;\n\n    protected List<Object> col = new ArrayList<Object>();\n\n    public static final String CASSANDRA_PU = \"imdbCassandra\";\n\n    public static final String HBASE_PU = \"imdbHbase\";\n\n    public static final String MONGO_PU = \"addMongo\";\n\n    public static final String RDBMS_PU = \"imdbRDBMS\";\n\n    public static final String REDIS_PU = \"redis\";\n\n    public static final String NEO4J_PU = \"imdbNeo4J\";\n\n    public static String persistenceUnits = \"piccandra,picongo,secIdxAddCassandra,\";\n\n    public static final String[] ALL_PUs_UNDER_TEST = new String[] { NEO4J_PU, CASSANDRA_PU, MONGO_PU, REDIS_PU,/*\n                                                                                                                 * HBASE_PU\n                                                                                                                 * ,\n                                                                                                                 */\n    RDBMS_PU };\n\n    // public static final String[] ALL_PUs_UNDER_TEST = new String[] {\n    // NEO4J_PU, HBASE_PU};\n\n    public static void buildPersistenceUnitsList()\n    {\n        for (String pu : ALL_PUs_UNDER_TEST)\n        {\n            persistenceUnits = persistenceUnits + pu + \",\";\n        }\n        persistenceUnits = persistenceUnits.substring(0, persistenceUnits.length() - 1);\n    }\n\n    /**\n     * Sets the up internal.\n     * \n     * @param colFamilies\n     *            the new up internal\n     */\n    protected void setUpInternal(String... colFamilies)\n    {\n        // if (persistenceUnits.indexOf(HBASE_PU) > 0 && AUTO_MANAGE_SCHEMA)\n        //\n        // {\n        // if (!HBaseCli.isStarted())\n        // {\n        // HBaseCli.startCluster();\n        // }\n        // HBaseCli.createTable(\"MOVIE\");\n        // HBaseCli.addColumnFamily(\"MOVIE\", \"TITLE\");\n        // HBaseCli.addColumnFamily(\"MOVIE\", \"YEAR\");\n        // }\n\n        dao = new IMDBDaoImpl(persistenceUnits);\n\n        dao.closeEntityManager();\n        dao.closeEntityManagerFactory();\n\n        em = dao.getEntityManager(persistenceUnits);\n        kunderaMetadata = ((EntityManagerFactoryImpl) em.getEntityManagerFactory()).getKunderaMetadataInstance();\n        this.colFamilies = colFamilies;\n\n    }\n\n    /**\n     * Switch over persistence units.\n     * \n     * @param entityPuCol\n     *            the entity pu col\n     * @throws SchemaDisagreementException\n     * @throws TimedOutException\n     * @throws UnavailableException\n     * @throws InvalidRequestException\n     * @throws TException\n     * @throws IOException\n     */\n    protected void switchPersistenceUnits(Map<Class, String> entityPuCol) throws IOException, TException,\n            InvalidRequestException, UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        if (entityPuCol != null)\n        {\n            Iterator<Class> iter = entityPuCol.keySet().iterator();\n            log.warn(\"\\n\\nInvocation for:\\n--------------------------------\");\n            while (iter.hasNext())\n            {\n                Class clazz = iter.next();\n                String pu = entityPuCol.get(clazz);\n                Map<String, Metamodel> metaModels = kunderaMetadata.getApplicationMetadata().getMetamodelMap();\n\n                EntityMetadata mAdd = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n                for (Metamodel m : metaModels.values())\n                {\n                    mAdd = ((MetamodelImpl) m).getEntityMetadataMap().get(clazz.getName());\n                    if (mAdd != null)\n                    {\n                        break;\n                    }\n                }\n                mAdd.setPersistenceUnit(pu);\n                Map<String, List<String>> clazzToPu = new HashMap<String, List<String>>(1);\n                List<String> pus = new ArrayList<String>(1);\n                pus.add(pu);\n                clazzToPu.put(clazz.getName(), pus);\n                kunderaMetadata.getApplicationMetadata().setClazzToPuMap(clazzToPu);\n\n                Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(pu);\n                ((MetamodelImpl) metaModel).addEntityMetadata(clazz, mAdd);\n                kunderaMetadata.getApplicationMetadata().getMetamodelMap().put(pu, metaModel);\n                // kunderaMetadata.getApplicationMetadata().addEntityMetadata(pu,\n                // clazz, mAdd);\n                PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata()\n                        .getPersistenceUnitMetadata(pu);\n\n                CoreMetadata coreMetadata = new CoreMetadata();\n                coreMetadata.setLazyInitializerFactory(new CglibLazyInitializerFactory());\n                kunderaMetadata.setCoreMetadata(coreMetadata);\n\n                String client = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_CLIENT_FACTORY);\n                if (client.equalsIgnoreCase(\"com.impetus.client.cassandra.pelops.PelopsClientFactory\")\n                        || client.equalsIgnoreCase(\"com.impetus.client.cassandra.thrift.ThriftClientFactory\"))\n                {\n                    if (RUN_IN_EMBEDDED_MODE)\n                    {\n                        CassandraCli.cassandraSetUp();\n                        CassandraCli.initClient();\n                    }\n\n                    if (AUTO_MANAGE_SCHEMA)\n                    {\n                        if (mAdd.getTableName().equalsIgnoreCase(MOVIE))\n                        {\n                            loadDataForMovie();\n                        }\n                        else if (mAdd.getTableName().equalsIgnoreCase(ACTOR))\n                        {\n                            loadDataForActor();\n                        }\n                    }\n                }\n\n                if (client.equalsIgnoreCase(\"com.impetus.client.rdbms.RDBMSClientFactory\"))\n                {\n                    createRDBMSSchema();\n\n                }\n                String schema = puMetadata.getProperty(PersistenceProperties.KUNDERA_KEYSPACE);\n                mAdd.setSchema(schema != null ? schema : KEYSPACE);\n                log.warn(clazz.getSimpleName() + \" in \" + pu);\n            }\n        }\n\n        dao.closeEntityManager();\n        em = dao.getEntityManager(persistenceUnits);\n    }\n\n    /**\n     * Tear down internal.\n     * \n     * @param ALL_PUs_UNDER_TEST\n     * \n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    protected void tearDownInternal(String[] ALL_PUs_UNDER_TEST) throws InvalidRequestException,\n            SchemaDisagreementException\n    {\n        if (!em.isOpen())\n        {\n            em = dao.getEntityManager(persistenceUnits);\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            if (persistenceUnits.indexOf(CASSANDRA_PU) > 0)\n                // truncateCassandra();\n\n                if (persistenceUnits.indexOf(RDBMS_PU) > 0)\n                {\n\n                    truncateRdbms();\n                    // shutDownRdbmsServer();\n                }\n            if (persistenceUnits.indexOf(REDIS_PU) > 0)\n                truncateRedis();\n        }\n\n        for (String pu : ALL_PUs_UNDER_TEST)\n        {\n            CleanupUtilities.cleanLuceneDirectory(kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(\n                    pu));\n        }\n    }\n\n    /**\n     * \n     */\n    private void truncateCassandra()\n    {\n        String[] columnFamily = new String[] { ACTOR, MOVIE };\n        CassandraCli.truncateColumnFamily(KEYSPACE, columnFamily);\n    }\n\n    protected void addKeyspace(KsDef ksDef, List<CfDef> cfDefs) throws InvalidRequestException,\n            SchemaDisagreementException, TException\n    {\n        ksDef = new KsDef(KEYSPACE, SimpleStrategy.class.getSimpleName(), cfDefs);\n        // Set replication factor\n        if (ksDef.strategy_options == null)\n        {\n            ksDef.strategy_options = new LinkedHashMap<String, String>();\n        }\n        // Set replication factor, the value MUST be an integer\n        ksDef.strategy_options.put(\"replication_factor\", \"1\");\n        CassandraCli.client.system_add_keyspace(ksDef);\n    }\n\n    /**\n     * Truncates schema.\n     * \n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    protected void truncateSchema() throws InvalidRequestException, SchemaDisagreementException\n    {\n        log.warn(\"Truncating....\");\n        // CassandraCli.dropColumnFamily(\"ACTOR\", KEYSPACE);\n        // CassandraCli.dropColumnFamily(\"MOVIE\", KEYSPACE);\n        // CassandraCli.dropKeySpace(KEYSPACE);\n\n        CassandraCli.truncateColumnFamily(KEYSPACE, \"ACTOR\");\n        CassandraCli.truncateColumnFamily(KEYSPACE, \"MOVIE\");\n        // CassandraCli.dropColumnFamily(KEYSPACE, \"MOVIE\");\n\n    }\n\n    protected abstract void loadDataForActor() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException;\n\n    protected abstract void loadDataForMovie() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException;\n\n    protected void shutDownRdbmsServer()\n    {\n        if (cli != null)\n        {\n            try\n            {\n                if (AUTO_MANAGE_SCHEMA)\n                {\n                    cli.dropSchema(KEYSPACE);\n                }\n            }\n            catch (Exception e)\n            {\n                try\n                {\n                    cli.closeConnection();\n                }\n                catch (SQLException e1)\n                {\n                }\n            }\n            finally\n            {\n                try\n                {\n                    cli.closeConnection();\n                }\n                catch (SQLException e)\n                {\n                }\n            }\n\n        }\n    }\n\n    private void truncateRdbms()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM IMDB.MOVIE\");\n            // cli.update(\"DROP TABLE IMDB.MOVIE\");\n\n        }\n        catch (Exception e)\n        {\n\n        }\n    }\n\n    /**\n     * \n     */\n    protected void createRDBMSSchema()\n    {\n        try\n        {\n            if (AUTO_MANAGE_SCHEMA)\n            {\n                cli = new RDBMSCli(KEYSPACE);\n                cli.createSchema(KEYSPACE);\n\n                try\n                {\n                    cli.update(\"CREATE TABLE IMDB.MOVIE (MOVIE_ID VARCHAR(256) PRIMARY KEY, TITLE VARCHAR(256), YEAR VARCHAR(256))\");\n                }\n                catch (Exception e)\n                {\n                    cli.update(\"DELETE FROM IMDB.MOVIE\");\n                    // cli.update(\"DROP TABLE IMDB.MOVIE\");\n                    // cli.update(\"CREATE TABLE IMDB.MOVIE (MOVIE_ID VARCHAR(256) PRIMARY KEY, TITLE VARCHAR(256), YEAR VARCHAR(256))\");\n                }\n\n            }\n\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error in RDBMS cli \", e);\n        }\n    }\n\n    private void truncateRedis()\n\n    {\n        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(\n                \"redis\");\n        Properties props = puMetadata.getProperties();\n        String contactNode = RedisPropertyReader.rsmd.getHost() != null ? RedisPropertyReader.rsmd.getHost()\n                : (String) props.get(PersistenceProperties.KUNDERA_NODES);\n        String defaultPort = RedisPropertyReader.rsmd.getPort() != null ? RedisPropertyReader.rsmd.getPort()\n                : (String) props.get(PersistenceProperties.KUNDERA_PORT);\n        String password = RedisPropertyReader.rsmd.getPassword() != null ? RedisPropertyReader.rsmd.getPassword()\n                : (String) props.get(PersistenceProperties.KUNDERA_PASSWORD);\n        Jedis connection = new Jedis(contactNode, Integer.valueOf(defaultPort));\n        connection.auth(password);\n        connection.connect();\n        connection.flushDB();\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/imdb/IMDBPolyglotTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.imdb;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.imdb.entities.Actor;\nimport com.impetus.kundera.tests.crossdatastore.imdb.entities.Movie;\nimport com.impetus.kundera.tests.crossdatastore.imdb.entities.Role;\n\npublic class IMDBPolyglotTest extends TwinAssociation\n\n{\n    Set<Actor> actors = new HashSet<Actor>();\n\n    @BeforeClass\n    public static void init() throws Exception\n    {\n        buildPersistenceUnitsList();\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(Actor.class);\n        clazzz.add(Movie.class);\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"Pickr\"); \n        CassandraCli.createKeySpace(\"imdb\");\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal();\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        tryOperation(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void insert()\n    {\n        populateActors();\n        dao.insertActors(actors);\n    }\n\n    @Override\n    protected void find()\n    {\n\n        Actor actor1 = (Actor) dao.find(Actor.class, 1);\n        Actor actor2 = (Actor) dao.find(Actor.class, 2);\n\n        assertActors(actor1, actor2);\n    }\n\n    @Override\n    protected void update()\n    {\n        Actor actor1 = (Actor) dao.find(Actor.class, 1);\n        Actor actor2 = (Actor) dao.find(Actor.class, 2);\n        actor1.setName(\"Amresh\");\n        actor2.setName(\"Amir\");\n        dao.merge(actor1);\n        dao.merge(actor2);\n        Actor actor1Modified = (Actor) dao.find(Actor.class, 1);\n        Actor actor2Modified = (Actor) dao.find(Actor.class, 2);\n        assertUpdatedActors(actor1Modified, actor2Modified);\n    }\n\n    @Override\n    protected void remove()\n    {\n        Actor actor1 = (Actor) dao.find(Actor.class, 1);\n        Actor actor2 = (Actor) dao.find(Actor.class, 2);\n\n        dao.remove(actor1);\n        dao.remove(actor2);\n\n        Actor actor1Deleted = (Actor) dao.find(Actor.class, 1);\n        Actor actor2Deleted = (Actor) dao.find(Actor.class, 2);\n\n        Assert.assertNull(actor1Deleted);\n        Assert.assertNull(actor2Deleted);\n    }\n\n    @Override\n    public void findAllActors()\n    {\n\n        List<Actor> actors = dao.findAllActors();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(2, actors.size());\n    }\n\n    @Override\n    public void findActorByID()\n    {\n        List<Actor> actors = dao.findActorByID();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(1, actors.size());\n        assertActor2(actors.get(0));\n        dao.closeEntityManager();\n    }\n\n    @Override\n    public void findActorByName()\n    {\n        List<Actor> actors = dao.findActorByName();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(1, actors.size());\n        assertActor1(actors.get(0));\n        dao.closeEntityManager();\n    }\n\n    @Override\n    public void findActorByIDAndNamePositive()\n    {\n        List<Actor> actors = dao.findActorByIDAndNamePositive();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(1, actors.size());\n        assertActor1(actors.get(0));\n        dao.closeEntityManager();\n    }\n\n    @Override\n    public void findActorByIDAndNameNegative()\n    {\n        List<Actor> actors = dao.findActorByIDAndNameNegative();\n        Assert.assertTrue(actors == null || actors.isEmpty());\n        dao.closeEntityManager();\n    }\n\n    @Override\n    public void findActorWithMatchingName()\n    {\n        List<Actor> actors = dao.findActorWithMatchingName();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(1, actors.size());\n        assertActor2(actors.get(0));\n        dao.closeEntityManager();\n    }\n\n    @Override\n    public void findActorWithinGivenIdRange()\n    {\n        List<Actor> actors = dao.findActorWithinGivenIdRange();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(2, actors.size());\n        // assertActor2(actors.get(0));\n        dao.closeEntityManager();\n    }\n\n    @Override\n    public void findSelectedFields()\n    {\n        List<Actor> actors = dao.findSelectedFields();\n        Assert.assertNotNull(actors);\n        Assert.assertFalse(actors.isEmpty());\n        Assert.assertEquals(2, actors.size());\n\n        for (Actor actor : actors)\n        {\n            Assert.assertNotNull(actor);\n            Assert.assertNotNull(actor.getId());\n            Assert.assertNotNull(actor.getName());\n        }\n        dao.closeEntityManager();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n    }\n\n    @Override\n    protected void loadDataForActor() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n\n        KsDef ksDef = null;\n\n        CfDef cfDef = new CfDef();\n        cfDef.name = ACTOR;\n        cfDef.keyspace = KEYSPACE;\n        // cfDef.column_type = \"Super\";\n\n        cfDef.setComparator_type(\"UTF8Type\");\n        cfDef.setKey_validation_class(\"Int32Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ACTOR_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef);\n\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"ADDRESS_ID\".getBytes()), \"Int32Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef1);\n\n        // ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PERSON_ID\"\n        // .getBytes()), \"IntegerType\");\n        // cfDef.addToColumn_metadata(columnDef2);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(cfDef);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(KEYSPACE);\n            CassandraCli.client.set_keyspace(KEYSPACE);\n\n        //    List<CfDef> cfDefn = ksDef.getCf_defs();\n            \n            if (!CassandraCli.columnFamilyExist(ACTOR,KEYSPACE )) {\n                CassandraCli.client.system_add_column_family(cfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(KEYSPACE,ACTOR);\n            }\n\n\n            \n\n        }\n        catch (NotFoundException e)\n        {\n\n            addKeyspace(ksDef, cfDefs);\n        }\n\n        CassandraCli.client.set_keyspace(KEYSPACE);\n    }\n\n    @Override\n    protected void loadDataForMovie() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        KsDef ksDef = null;\n        CfDef cfDef2 = new CfDef();\n\n        cfDef2.name = MOVIE;\n        cfDef2.keyspace = KEYSPACE;\n        cfDef2.setComparator_type(\"UTF8Type\");\n        cfDef2.setKey_validation_class(\"UTF8Type\");\n\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"TITLE\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        cfDef2.addToColumn_metadata(columnDef);\n\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"YEAR\".getBytes()), \"Int32Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        cfDef2.addToColumn_metadata(columnDef1);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(cfDef2);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(KEYSPACE);\n            CassandraCli.client.set_keyspace(KEYSPACE);\n        //    List<CfDef> cfDefss = ksDef.getCf_defs();\n            if (!CassandraCli.columnFamilyExist(MOVIE,KEYSPACE)) {\n                CassandraCli.client.system_add_column_family(cfDef2);\n            } else {\n                CassandraCli.truncateColumnFamily(KEYSPACE, MOVIE);\n            }\n\n\n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        CassandraCli.client.set_keyspace(KEYSPACE);\n\n    }\n\n    private void populateActors()\n    {\n        // Actors\n        Actor actor1 = new Actor(1, \"Tom Cruise\");\n        Actor actor2 = new Actor(2, \"Emmanuelle Béart\");\n\n        // Movies\n        Movie movie1 = new Movie(\"m1\", \"War of the Worlds\", 2005);\n        Movie movie2 = new Movie(\"m2\", \"Mission Impossible\", 1996);\n        Movie movie3 = new Movie(\"m3\", \"Hell\", 2005);\n\n        // Roles\n        Role role1 = new Role(\"Ray Ferrier\", \"Lead Actor\");\n        role1.setActor(actor1);\n        role1.setMovie(movie1);\n        Role role2 = new Role(\"Ethan Hunt\", \"Lead Actor\");\n        role2.setActor(actor1);\n        role2.setMovie(movie2);\n        Role role3 = new Role(\"Claire Phelps\", \"Lead Actress\");\n        role3.setActor(actor2);\n        role1.setMovie(movie2);\n        Role role4 = new Role(\"Sophie\", \"Supporting Actress\");\n        role4.setActor(actor2);\n        role1.setMovie(movie3);\n\n        // Relationships\n        actor1.addMovie(role1, movie1);\n        actor1.addMovie(role2, movie2);\n        actor2.addMovie(role3, movie2);\n        actor2.addMovie(role4, movie3);\n\n        movie1.addActor(role1, actor1);\n        movie2.addActor(role2, actor1);\n        movie2.addActor(role3, actor2);\n        movie3.addActor(role4, actor2);\n\n        actors.add(actor1);\n        actors.add(actor2);\n    }\n\n    private void assertActors(Actor actor1, Actor actor2)\n    {\n        Assert.assertNotNull(actor1);\n        Assert.assertEquals(1, actor1.getId());\n        Assert.assertEquals(\"Tom Cruise\", actor1.getName());\n        Map<Role, Movie> movies1 = actor1.getMovies();\n        Assert.assertFalse(movies1 == null || movies1.isEmpty());\n        Assert.assertEquals(2, movies1.size());\n\n        Assert.assertNotNull(actor2);\n        Assert.assertEquals(2, actor2.getId());\n        Assert.assertEquals(\"Emmanuelle Béart\", actor2.getName());\n        Map<Role, Movie> movies2 = actor2.getMovies();\n        Assert.assertFalse(movies2 == null || movies2.isEmpty());\n        Assert.assertEquals(2, movies2.size());\n    }\n\n    /**\n     * @param actor1\n     * @param actor2\n     */\n    private void assertUpdatedActors(Actor actor1, Actor actor2)\n    {\n        Assert.assertNotNull(actor1);\n        Assert.assertEquals(1, actor1.getId());\n        Assert.assertEquals(\"Amresh\", actor1.getName());\n        Map<Role, Movie> movies1 = actor1.getMovies();\n        Assert.assertFalse(movies1 == null || movies1.isEmpty());\n        Assert.assertEquals(2, movies1.size());\n\n        Assert.assertNotNull(actor2);\n        Assert.assertEquals(2, actor2.getId());\n        Assert.assertEquals(\"Amir\", actor2.getName());\n        Map<Role, Movie> movies2 = actor2.getMovies();\n        Assert.assertFalse(movies2 == null || movies2.isEmpty());\n        Assert.assertEquals(2, movies2.size());\n    }\n\n    /**\n     * @param actor2\n     */\n    protected void assertActor2(Actor actor2)\n    {\n        Assert.assertNotNull(actor2);\n        Assert.assertEquals(2, actor2.getId());\n        Assert.assertEquals(\"Emmanuelle Béart\", actor2.getName());\n        Map<Role, Movie> movies2 = actor2.getMovies();\n        Assert.assertFalse(movies2 == null || movies2.isEmpty());\n        Assert.assertEquals(2, movies2.size());\n\n    }\n\n    /**\n     * @param actor1\n     */\n    protected void assertActor1(Actor actor1)\n    {\n        Assert.assertNotNull(actor1);\n        Assert.assertEquals(1, actor1.getId());\n        Assert.assertEquals(\"Tom Cruise\", actor1.getName());\n        Map<Role, Movie> movies1 = actor1.getMovies();\n        Assert.assertFalse(movies1 == null || movies1.isEmpty());\n        Assert.assertEquals(2, movies1.size());\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/imdb/TwinAssociation.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.imdb;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.Metamodel;\n\nimport org.junit.Assert;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.tests.crossdatastore.imdb.entities.Actor;\nimport com.impetus.kundera.tests.crossdatastore.imdb.entities.Movie;\n\n/**\n * The Class TwinAssociation.\n * \n * @author vivek.mishra\n */\npublic abstract class TwinAssociation extends AssociationBase\n{\n\n    /** The combinations. */\n    protected static List<Map<Class, String>> combinations = new ArrayList<Map<Class, String>>();\n\n    protected static List<String> traversedPus = new ArrayList<String>();\n\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(TwinAssociation.class);\n\n    /**\n     * Inits the.\n     * \n     * @param classes\n     *            the classes\n     * @param persistenceUnits\n     *            the persistence units\n     */\n    public static void init(List<Class> classes, String... persistenceUnits) throws Exception\n    {\n        \n        combinations = null;\n        combinations = new ArrayList<Map<Class, String>>();\n\n        // list of PUS with class.\n        Map<Class, String> puClazzMapper = null;\n\n        for (String pu : persistenceUnits)\n        {\n            for (String p : persistenceUnits)\n            {\n                puClazzMapper = new HashMap<Class, String>();\n                puClazzMapper.put(classes.get(0), pu);\n\n                for (Class c : classes.subList(1, classes.size()))\n                {\n                    puClazzMapper.put(c, p);\n                }\n                combinations.add(puClazzMapper);\n            }\n        }\n    }\n\n    /**\n     * Try operation.\n     * \n     * @param ALL_PUs_UNDER_TEST\n     */\n    protected void tryOperation(String[] ALL_PUs_UNDER_TEST)\n    {\n        try\n        {\n            Metamodel metaModel = null;\n            for (int i = 0; i < ALL_PUs_UNDER_TEST.length; i++)\n            {\n                metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(ALL_PUs_UNDER_TEST[i]);\n\n//                if (traversedPus.isEmpty() || !traversedPus.contains(ALL_PUs_UNDER_TEST[i]))\n//                {\n                  for (int i1 = 0; i1 < ALL_PUs_UNDER_TEST.length; i1++)\n                    {\n                        if (i != i1)\n                        {\n                            traversedPus.add(ALL_PUs_UNDER_TEST[i1]);\n                            Map<Class<?>, EntityType<?>> original = getManagedTypes((MetamodelImpl) metaModel);\n\n                            Metamodel m = kunderaMetadata.getApplicationMetadata().getMetamodel(\n                                    ALL_PUs_UNDER_TEST[i1]);\n                            Map<Class<?>, EntityType<?>> copy = getManagedTypes((MetamodelImpl) m);\n                            if (original != null && copy != null)\n                            {\n                                original.putAll(copy);\n                            }\n                        }\n                    }\n               // }\n            }\n\n            for (Map<Class, String> c : combinations)\n            {\n                Set<String> allPus = new HashSet<String>(c.values());\n                if (allPus.size() == 1)\n                {\n                    continue;\n                }\n                else\n                {\n                    String puForActor = c.get(Actor.class);\n                    String puForMovie = c.get(Movie.class);\n\n                    if (!puForActor.equals(\"imdbNeo4J\") || puForMovie.equals(\"imdbNeo4J\"))\n                    {\n                        continue;\n                    }\n\n                }\n\n                switchPersistenceUnits(c);\n\n                // CRUD\n                insert();\n                find();\n\n                // Queries\n                findAllActors();\n                findActorByID();\n                findActorByName();\n                findActorByIDAndNamePositive();\n                findActorByIDAndNameNegative();\n                findActorWithMatchingName();\n                findActorWithinGivenIdRange();\n                findSelectedFields();\n\n                update();\n                remove();\n\n                tearDownInternal(ALL_PUs_UNDER_TEST);\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error while switching persistence units\", e);\n            throw new RuntimeException(e);\n        }\n    }\n\n    /** Insert person with address */\n    protected abstract void insert();\n\n    /** Find person by ID */\n    protected abstract void find();\n\n    /** Update Person */\n    protected abstract void update();\n\n    /** Remove Person */\n    protected abstract void remove();\n\n    protected abstract void findAllActors();\n\n    protected abstract void findActorByID();\n\n    protected abstract void findActorByName();\n\n    protected abstract void findActorByIDAndNamePositive();\n\n    protected abstract void findActorByIDAndNameNegative();\n\n    protected abstract void findActorWithMatchingName();\n\n    protected abstract void findActorWithinGivenIdRange();\n\n    protected abstract void findSelectedFields();\n\n    private Map<Class<?>, EntityType<?>> getManagedTypes(MetamodelImpl metaModel)\n    {\n        try\n        {\n            Field managedTypesFields = null;\n            if (metaModel != null)\n                managedTypesFields = metaModel.getClass().getDeclaredField(\"entityTypes\");\n            if (managedTypesFields != null && !managedTypesFields.isAccessible())\n            {\n                managedTypesFields.setAccessible(true);\n\n                return ((Map<Class<?>, EntityType<?>>) managedTypesFields.get(metaModel));\n            }\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/imdb/dao/BaseDao.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.imdb.dao;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport com.impetus.kundera.PersistenceProperties;\n\npublic class BaseDao\n{\n\n    EntityManagerFactory emf;\n\n    EntityManager em;\n\n    public EntityManager getEntityManager(String pu)\n    {\n        if (emf == null)\n        {\n            Map<String, String> propertyMap = new HashMap<String, String>();\n\n            if (propertyMap.isEmpty())\n            {\n                propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"\");\n            }\n            Map mapOfExternalProperties = new HashMap<String, Map>();\n            mapOfExternalProperties.put(\"imdbCassandra\", propertyMap);\n            mapOfExternalProperties.put(\"piccandra\", propertyMap);\n            mapOfExternalProperties.put(\"secIdxAddCassandra\", propertyMap);\n            \n            emf = Persistence.createEntityManagerFactory(pu, mapOfExternalProperties);\n            em = emf.createEntityManager();\n        }\n\n        if (em == null)\n        {\n            em = emf.createEntityManager();\n        }\n\n        return em;\n    }\n\n    public void closeEntityManager()\n    {\n        if (em != null)\n        {\n            em.close();\n            em = null;\n        }\n    }\n\n    public void closeEntityManagerFactory()\n    {\n        if (emf != null)\n        {\n            emf.close();\n        }\n        emf = null;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/imdb/dao/IMDBDaoImpl.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.imdb.dao;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.Query;\n\nimport com.impetus.kundera.tests.crossdatastore.imdb.entities.Actor;\nimport com.impetus.kundera.tests.crossdatastore.imdb.entities.Movie;\n\n/**\n * Implementation of {@link IMDBDao}\n * \n * @author amresh.singh\n */\npublic class IMDBDaoImpl extends BaseDao\n{\n\n    private String persistenceUnit;\n\n    /**\n     * @param persistenceUnit\n     */\n    public IMDBDaoImpl(String persistenceUnit)\n    {\n        this.persistenceUnit = persistenceUnit;\n    }\n\n    public void insert(Object actor)\n    {\n        em = getEntityManager(persistenceUnit);\n        em.getTransaction().begin();\n        em.persist(actor);\n        em.getTransaction().commit();\n        closeEntityManager();\n    }\n\n    public Object find(Class entityClass, Object key)\n    {\n        em = getEntityManager(persistenceUnit);\n        em.clear();\n        Object actor = em.find(entityClass, key);\n        return actor;\n    }\n\n    public void insertActors(Set<?> actors)\n    {\n        EntityManager em = getEntityManager(persistenceUnit);\n        em.getTransaction().begin();\n        for (Object actor : actors)\n        {\n            em.persist(actor);\n        }\n        em.getTransaction().commit();\n        closeEntityManager();\n    }\n\n    public void remove(Object entity)\n    {\n        em = getEntityManager(persistenceUnit);\n        em.getTransaction().begin();\n        em.remove(entity);\n        em.getTransaction().commit();\n        closeEntityManager();\n    }\n\n    public void merge(Object modifiedObj)\n    {\n        em = getEntityManager(persistenceUnit);\n        em.getTransaction().begin();\n        em.merge(modifiedObj);\n        em.getTransaction().commit();\n        closeEntityManager();\n    }\n\n    public List<Actor> findAllActors()\n    {\n        em = getEntityManager(persistenceUnit);\n        Query query = em.createQuery(\"select a from Actor a\");\n        List<Actor> actors = query.getResultList();\n        closeEntityManager();\n        return actors;\n    }\n\n    public List<Actor> findActorByID()\n    {\n        em = getEntityManager(persistenceUnit);\n        Query query = em.createQuery(\"select a from Actor a where a.id = :id\");\n        query.setParameter(\"id\", 2);\n        List<Actor> actors = query.getResultList();\n        return actors;\n    }\n\n    public List<Actor> findActorByName()\n    {\n        em = getEntityManager(persistenceUnit);\n        Query query = em.createQuery(\"select a from Actor a where a.name=:name\");\n        query.setParameter(\"name\", \"Tom Cruise\");\n        List<Actor> actors = query.getResultList();\n        return actors;\n    }\n\n    public List<Actor> findActorByIDAndNamePositive()\n    {\n        em = getEntityManager(persistenceUnit);\n        // Positive scenario\n        Query query = em.createQuery(\"select a from Actor a where a.id=:id AND a.name=:name\");\n        query.setParameter(\"id\", 1);\n        query.setParameter(\"name\", \"Tom Cruise\");\n        List<Actor> actors = query.getResultList();\n        return actors;\n    }\n\n    public List<Actor> findActorByIDAndNameNegative()\n    {\n        em = getEntityManager(persistenceUnit); // Negative scenario\n        Query query = em.createQuery(\"select a from Actor a where a.id=:id AND a.name=:name\");\n        query.setParameter(\"id\", 2);\n        query.setParameter(\"name\", \"Tom Cruise\");\n        List<Actor> actors = query.getResultList();\n        //closeEntityManager();\n        return actors;\n    }\n\n    public List<Actor> findActorWithMatchingName()\n    {\n        em = getEntityManager(persistenceUnit);\n        Query query = em.createQuery(\"select a from Actor a where a.name like :name\");\n        query.setParameter(\"name\", \"Emma\");\n        List<Actor> actors = query.getResultList();\n        return actors;\n    }\n\n    public List<Actor> findActorWithinGivenIdRange()\n    {\n        em = getEntityManager(persistenceUnit);\n\n        Query query = em.createQuery(\"select a from Actor a where a.id between :min AND :max\");\n        query.setParameter(\"min\", 1);\n        query.setParameter(\"max\", 2);\n        List<Actor> actors = query.getResultList();\n        return actors;\n    }\n\n    public List<Movie> findMoviesBetweenAPeriod()\n    {\n        em = getEntityManager(persistenceUnit);\n        // Between\n        Query query = em.createQuery(\"select m from Movie m where m.year between :start AND :end\");\n        query.setParameter(\"start\", 1990);\n        query.setParameter(\"end\", 2006);\n        List<Movie> movies = query.getResultList();\n        return movies;\n\n    }\n\n    public List<Movie> findMoviesGreaterThanLessThanYear()\n    {\n        em = getEntityManager(persistenceUnit);\n        // Greater-than/ Less Than\n        Query query = em.createQuery(\"select m from Movie m where m.year >= :start AND m.year <= :end\");\n        query.setParameter(\"start\", 2005);\n        query.setParameter(\"end\", 2010);\n        List<Movie> movies = query.getResultList();\n        return movies;\n    }\n\n    public List<Actor> findSelectedFields()\n    {\n        em = getEntityManager(persistenceUnit);\n        Query query = em.createQuery(\"select a.name from Actor a\");\n        List<Actor> actors = query.getResultList();\n        return actors;\n    }\n\n    public List<Movie> findMoviesUsingIdOrTitle()\n    {\n        em = getEntityManager(persistenceUnit);\n        Query query = em.createQuery(\"select m from Movie m where m.id = :movieId OR m.title like :title\");\n        query.setParameter(\"movieId\", \"m1\");\n        query.setParameter(\"title\", \"Miss\");\n        List<Movie> movies = query.getResultList();\n        return movies;\n    }\n\n    public List<Movie> findMoviesUsingIdOrTitleOrYear()\n    {\n        em = getEntityManager(persistenceUnit);\n        Query query = em\n                .createQuery(\"select m from Movie m where m.id = :movieId OR m.title like :title OR m.year = :year\");\n        query.setParameter(\"movieId\", \"m1\");\n        query.setParameter(\"title\", \"Miss\");\n        query.setParameter(\"year\", 2009);\n        List<Movie> movies = query.getResultList();\n        return movies;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/imdb/entities/Actor.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.imdb.entities;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.MapKeyJoinColumn;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Actor Node Entity class\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ACTOR\", schema = \"imdb\")\n\n// Ignored for Neo4J\n@IndexCollection(columns = { @Index(name = \"name\", type = \"KEYS\") })\npublic class Actor\n{\n    @Id\n    @Column(name = \"ACTOR_ID\")\n    private int id;\n\n    @Column(name = \"ACTOR_NAME\")\n    private String name;\n\n    public Actor()\n    {\n    }\n\n    public Actor(int actorId, String actorName)\n    {\n        this.id = actorId;\n        this.name = actorName;\n    }\n\n    @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)\n    @MapKeyJoinColumn(name = \"ACTS_IN\")\n    private Map<Role, Movie> movies;\n\n    public void addMovie(Role role, Movie movie)\n    {\n        if (movies == null)\n            movies = new HashMap<Role, Movie>();\n        movies.put(role, movie);\n    }\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the movies\n     */\n    public Map<Role, Movie> getMovies()\n    {\n        return movies;\n    }\n\n    /**\n     * @param movies\n     *            the movies to set\n     */\n    public void setMovies(Map<Role, Movie> movies)\n    {\n        this.movies = movies;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/imdb/entities/Movie.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.imdb.entities;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Movie Node entity class\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"MOVIE\", schema = \"imdb\")\n@IndexCollection(columns = { @Index(name = \"title\", type = \"KEYS\"), @Index(name = \"year\", type = \"KEYS\") })\npublic class Movie\n{\n    @Id\n    @Column(name = \"MOVIE_ID\")\n    private String id;\n\n    @Column(name = \"TITLE\")\n    private String title;\n\n    @Column(name = \"YEAR\")\n    private int year;\n\n    @ManyToMany(fetch = FetchType.LAZY, mappedBy = \"movies\")\n    private Map<Role, Actor> actors;\n\n    public Movie()\n    {\n    }\n\n    public Movie(String id, String title, int year)\n    {\n        this.id = id;\n        this.title = title;\n        this.year = year;\n    }\n\n    public void addActor(Role role, Actor actor)\n    {\n        if (actors == null)\n            actors = new HashMap<Role, Actor>();\n        actors.put(role, actor);\n    }\n\n    /**\n     * @return the id\n     */\n    public String getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(String id)\n    {\n        this.id = id;\n    }\n\n    /**\n     * @return the title\n     */\n    public String getTitle()\n    {\n        return title;\n    }\n\n    /**\n     * @param title\n     *            the title to set\n     */\n    public void setTitle(String title)\n    {\n        this.title = title;\n    }\n\n    /**\n     * @return the year\n     */\n    public int getYear()\n    {\n        return year;\n    }\n\n    /**\n     * @param year\n     *            the year to set\n     */\n    public void setYear(int year)\n    {\n        this.year = year;\n    }\n\n    /**\n     * @return the actors\n     */\n    public Map<Role, Actor> getActors()\n    {\n        return actors;\n    }\n\n    /**\n     * @param actors\n     *            the actors to set\n     */\n    public void setActors(Map<Role, Actor> actors)\n    {\n        this.actors = actors;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/imdb/entities/Role.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.imdb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n/**\n * Role Relationship entity class\n * \n * @author amresh.singh\n */\n@Entity\n@Table(name = \"ROLE\", schema = \"imdb\")\n@IndexCollection(columns = { @Index(name = \"roleType\", type = \"KEYS\") })\npublic class Role\n{\n    @Id\n    @Column(name = \"ROLE_NAME\")\n    private String roleName;\n\n    @Column(name = \"ROLE_TYPE\")\n    private String roleType;\n\n    @OneToOne\n    private Actor actor;\n\n    @OneToOne\n    private Movie movie;\n\n    public Role()\n    {\n    }\n\n    public Role(String roleName, String roleType)\n    {\n        this.roleName = roleName;\n        this.roleType = roleType;\n    }\n\n    /**\n     * @return the roleName\n     */\n    public String getRoleName()\n    {\n        return roleName;\n    }\n\n    /**\n     * @param roleName\n     *            the roleName to set\n     */\n    public void setRoleName(String roleName)\n    {\n        this.roleName = roleName;\n    }\n\n    /**\n     * @return the roleType\n     */\n    public String getRoleType()\n    {\n        return roleType;\n    }\n\n    /**\n     * @param roleType\n     *            the roleType to set\n     */\n    public void setRoleType(String roleType)\n    {\n        this.roleType = roleType;\n    }\n\n    /**\n     * @return the actor\n     */\n    public Actor getActor()\n    {\n        return actor;\n    }\n\n    /**\n     * @param actor\n     *            the actor to set\n     */\n    public void setActor(Actor actor)\n    {\n        this.actor = actor;\n    }\n\n    /**\n     * @return the movie\n     */\n    public Movie getMovie()\n    {\n        return movie;\n    }\n\n    /**\n     * @param movie\n     *            the movie to set\n     */\n    public void setMovie(Movie movie)\n    {\n        this.movie = movie;\n    }\n\n    public boolean equals(Object o)\n    {\n        if (!(o instanceof Role))\n        {\n            return false;\n        }\n\n        Role that = (Role) o;\n\n        return (this.roleName == that.roleName || this.roleName.equals(that.roleName))\n                && (this.roleType == that.roleType || this.roleType.equals(that.roleType));\n\n    }\n\n    public int hashCode()\n    {\n        int h1 = (roleName == null) ? 0 : roleName.hashCode();\n        int h2 = (roleType == null) ? 0 : roleType.hashCode();\n        return h1 + 31 * h2;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrBaseTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.net.UnknownHostException;\nimport java.sql.SQLException;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport org.apache.cassandra.locator.SimpleStrategy;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.crud.RDBMSCli;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.dao.Pickr;\nimport com.impetus.kundera.tests.crossdatastore.pickr.dao.PickrImpl;\nimport com.mongodb.Mongo;\nimport com.mongodb.MongoException;\n\n/**\n * @author amresh.singh\n */\npublic abstract class PickrBaseTest\n{\n    protected static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    protected static final boolean AUTO_MANAGE_SCHEMA = true;\n\n    protected Pickr pickr;\n\n    protected int photographerId;\n\n    protected static final String SCHEMA = \"Pickr\";\n\n    protected String pu = \"piccandra,picmysql,picongo,secIdxAddCassandra,addMongo\";\n\n    protected RDBMSCli cli;\n\n    private static Logger log = LoggerFactory.getLogger(PickrBaseTest.class);\n\n    protected void setUp() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            CassandraCli.cassandraSetUp();\n            try\n            {\n\n                cli = new RDBMSCli(SCHEMA);\n\n                cli.createSchema(SCHEMA);\n            }\n            catch (Exception e)\n            {\n                log.error(\"Error in RDBMS cli \", e);\n            }\n            // HBaseCli.startCluster();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            createCassandraSchema();\n            createRDBMSTables();\n        }\n\n        photographerId = 1;\n        pickr = new PickrImpl(pu);\n    }\n\n    private void createRDBMSTables() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE PICKR.PHOTOGRAPHER (PHOTOGRAPHER_ID INT PRIMARY KEY, PHOTOGRAPHER_NAME VARCHAR(256),ALBUM_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM PICKR.PHOTOGRAPHER\");\n//            cli.update(\"DROP TABLE PICKR.PHOTOGRAPHER\");\n//            cli.update(\"CREATE TABLE PICKR.PHOTOGRAPHER (PHOTOGRAPHER_ID INT PRIMARY KEY, PHOTOGRAPHER_NAME VARCHAR(256),ALBUM_ID VARCHAR(150))\");\n        }\n        try\n        {\n            cli.update(\"CREATE TABLE PICKR.PHOTOGRAPHER_ALBUM (PHOTOGRAPHER_ID INT , ALBUM_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM PICKR.PHOTOGRAPHER_ALBUM\");\n//            cli.update(\"DROP TABLE PICKR.PHOTOGRAPHER_ALBUM\");\n//            cli.update(\"CREATE TABLE PICKR.PHOTOGRAPHER_ALBUM (PHOTOGRAPHER_ID INT , ALBUM_ID VARCHAR(150))\");\n        }\n\n    }\n\n    public void executeTests()\n    {\n        addPhotographer();\n        getPhotographer();\n        updatePhotographer();\n        getAllPhotographers();\n        deletePhotographer();\n    }\n\n    protected void tearDown() throws Exception\n    {\n        // pickr.close();\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            truncateSchema();\n           // CassandraCli.dropKeySpace(\"Pickr\");\n            truncateMongo();\n\n            deleteRDBMSSchemaAndTables();\n\n        }\n\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            if (cli != null)\n            {\n                cli.closeConnection();\n            }\n        }\n\n    }\n\n    protected void addKeyspace(KsDef ksDef, List<CfDef> cfDefs) throws InvalidRequestException,\n            SchemaDisagreementException, TException\n    {\n        ksDef = new KsDef(\"Pickr\", SimpleStrategy.class.getSimpleName(), cfDefs);\n        // Set replication factor\n        if (ksDef.strategy_options == null)\n        {\n            ksDef.strategy_options = new LinkedHashMap<String, String>();\n        }\n        // Set replication factor, the value MUST be an integer\n        ksDef.strategy_options.put(\"replication_factor\", \"1\");\n        CassandraCli.client.system_add_keyspace(ksDef);\n    }\n\n    /**\n     * \n     */\n    private void truncateMongo()\n    {\n        String host = \"localhost\";\n        String port = \"27017\";\n        try\n        {\n            Mongo m = null;\n            if (host != null && port != null)\n            {\n                m = new Mongo(host, Integer.parseInt(port));\n                m.getDB(\"Pickr\").dropDatabase();\n            }\n        }\n        catch (NumberFormatException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (MongoException e)\n        {\n            log.error(e.getMessage());\n        }\n    }\n    \n    private void truncateSchema() throws InvalidRequestException, SchemaDisagreementException\n    {\n        log.warn(\"Truncating....\");\n\n        \n        CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\",\"ALBUM\", \"PHOTO\", \"ALBUM_PHOTO\");\n    //    CassandraCli.dropColumnFamily(\"Pickr\", \"MOVIE\");\n       \n    }\n\n    private void deleteRDBMSSchemaAndTables()\n    {\n\n        try\n        {\n            cli.update(\"DELETE FROM PICKR.PHOTOGRAPHER\");\n         //   cli.update(\"DROP TABLE PICKR.PHOTOGRAPHER\");\n            cli.update(\"DELETE FROM PICKR.PHOTOGRAPHER_ALBUM\");\n        //    cli.update(\"DROP TABLE PICKR.PHOTOGRAPHER_ALBUM\");\n          //  cli.dropSchema(SCHEMA);\n            \n            \n        }\n        catch (SQLException e)\n        {\n            if (cli != null && RUN_IN_EMBEDDED_MODE)\n            {\n                try\n                {\n                    cli.closeConnection();\n                }\n                catch (SQLException e1)\n                {\n                \tlog.warn(e1.getMessage());\n                }\n            }\n        }\n\n    }\n\n    protected abstract void addPhotographer();\n\n    protected abstract void updatePhotographer();\n\n    protected abstract void getPhotographer();\n\n    protected abstract void getAllPhotographers();\n\n    protected abstract void deletePhotographer();\n\n    protected abstract void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException;\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestBi_1_1_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_1_1_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_1_1_1_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_1_1_1_1;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestBi_1_1_1_1 extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PickrTestBi_1_1_1_1.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        executeTests();\n\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        PhotographerBi_1_1_1_1 p = populatePhotographer();\n        pickr.addPhotographer(p);\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerBi_1_1_1_1 p = (PhotographerBi_1_1_1_1) pickr.getPhotographer(PhotographerBi_1_1_1_1.class,\n                photographerId);\n        assertPhotographer(p);\n\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerBi_1_1_1_1 p = (PhotographerBi_1_1_1_1) pickr.getPhotographer(PhotographerBi_1_1_1_1.class,\n                photographerId);\n        assertPhotographer(p);\n        p.setPhotographerName(\"Vivek\");\n\n        pickr.mergePhotographer(p);\n\n        PhotographerBi_1_1_1_1 p2 = (PhotographerBi_1_1_1_1) pickr.getPhotographer(PhotographerBi_1_1_1_1.class,\n                photographerId);\n        assertModifiedPhotographer(p2);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerBi_1_1_1_1.class.getSimpleName());\n        PhotographerBi_1_1_1_1 p = (PhotographerBi_1_1_1_1) ps.get(0);\n\n        assertModifiedPhotographer(p);\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerBi_1_1_1_1 p = (PhotographerBi_1_1_1_1) pickr.getPhotographer(PhotographerBi_1_1_1_1.class,\n                photographerId);\n        assertModifiedPhotographer(p);\n        pickr.deletePhotographer(p);\n        PhotographerBi_1_1_1_1 p2 = (PhotographerBi_1_1_1_1) pickr.getPhotographer(PhotographerBi_1_1_1_1.class,\n                photographerId);\n        Assert.assertNull(p2);\n\n    }\n\n    private void assertPhotographer(PhotographerBi_1_1_1_1 p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbum());\n        AlbumBi_1_1_1_1 album = p.getAlbum();\n        Assert.assertNotNull(album);\n        Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n        Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n        Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n        PhotographerBi_1_1_1_1 pRev = album.getPhotographer();\n        Assert.assertNotNull(pRev);\n\n        PhotoBi_1_1_1_1 photo = album.getPhoto();\n        Assert.assertNotNull(photo);\n        Assert.assertEquals(\"photo_1\", photo.getPhotoId());\n        Assert.assertEquals(\"One beach\", photo.getPhotoCaption());\n\n        AlbumBi_1_1_1_1 albumRev = photo.getAlbum();\n        Assert.assertNotNull(albumRev);\n    }\n\n    private void assertModifiedPhotographer(PhotographerBi_1_1_1_1 p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbum());\n        AlbumBi_1_1_1_1 album = p.getAlbum();\n        Assert.assertNotNull(album);\n        Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n        Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n        Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n        PhotographerBi_1_1_1_1 pRev = album.getPhotographer();\n        Assert.assertNotNull(pRev);\n\n        PhotoBi_1_1_1_1 photo = album.getPhoto();\n        Assert.assertNotNull(photo);\n        Assert.assertEquals(\"photo_1\", photo.getPhotoId());\n        Assert.assertEquals(\"One beach\", photo.getPhotoCaption());\n\n        AlbumBi_1_1_1_1 albumRev = photo.getAlbum();\n        Assert.assertNotNull(albumRev);\n    }\n\n    private PhotographerBi_1_1_1_1 populatePhotographer()\n    {\n        PhotographerBi_1_1_1_1 p = new PhotographerBi_1_1_1_1();\n        p.setPhotographerId(photographerId);\n        p.setPhotographerName(\"Amresh\");\n\n        AlbumBi_1_1_1_1 album = new AlbumBi_1_1_1_1(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n\n        PhotoBi_1_1_1_1 photo = new PhotoBi_1_1_1_1(\"photo_1\", \"One beach\", \"On beach with friends\");\n\n        album.setPhoto(photo);\n\n        p.setAlbum(album);\n        return p;\n    }\n\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef1 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        pColumnDef1.index_type = IndexType.KEYS;\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef1);\n        pCfDef.addToColumn_metadata(pColumnDef2);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_ID\".getBytes()), \"UTF8Type\");\n        columnDef4.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef3);\n        aCfDef.addToColumn_metadata(columnDef4);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n            \n            \n            \n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestBi_1_1_1_1_PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_1_1_1_PK;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_1_1_1_1_PK;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_1_1_1_1_PK;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestBi_1_1_1_1_PK extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PickrTestBi_1_1_1_1_PK.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n         executeTests();\n\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        PhotographerBi_1_1_1_1_PK p = populatePhotographer();\n        pickr.addPhotographer(p);\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerBi_1_1_1_1_PK p = (PhotographerBi_1_1_1_1_PK) pickr.getPhotographer(\n                PhotographerBi_1_1_1_1_PK.class, photographerId);\n        assertPhotographer(p);\n\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerBi_1_1_1_1_PK p = (PhotographerBi_1_1_1_1_PK) pickr.getPhotographer(\n                PhotographerBi_1_1_1_1_PK.class, photographerId);\n        assertPhotographer(p);\n        p.setPhotographerName(\"Vivek\");\n\n        pickr.mergePhotographer(p);\n\n        PhotographerBi_1_1_1_1_PK p2 = (PhotographerBi_1_1_1_1_PK) pickr.getPhotographer(\n                PhotographerBi_1_1_1_1_PK.class, photographerId);\n        assertModifiedPhotographer(p2);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerBi_1_1_1_1_PK.class.getSimpleName());\n        PhotographerBi_1_1_1_1_PK p = (PhotographerBi_1_1_1_1_PK) ps.get(0);\n\n        assertModifiedPhotographer(p);\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerBi_1_1_1_1_PK p = (PhotographerBi_1_1_1_1_PK) pickr.getPhotographer(\n                PhotographerBi_1_1_1_1_PK.class, photographerId);\n        assertModifiedPhotographer(p);\n        pickr.deletePhotographer(p);\n        PhotographerBi_1_1_1_1_PK p2 = (PhotographerBi_1_1_1_1_PK) pickr.getPhotographer(\n                PhotographerBi_1_1_1_1_PK.class, photographerId);\n        Assert.assertNull(p2);\n\n    }\n\n    private void assertPhotographer(PhotographerBi_1_1_1_1_PK p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbum());\n        AlbumBi_1_1_1_1_PK album = p.getAlbum();\n        Assert.assertNotNull(album);\n        Assert.assertTrue(album.getPhotographerId() == 1);\n        Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n        Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n        Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n        PhotographerBi_1_1_1_1_PK pRev = album.getPhotographer();\n        Assert.assertNotNull(pRev);\n\n        PhotoBi_1_1_1_1_PK photo = album.getPhoto();\n        Assert.assertNotNull(photo);\n        Assert.assertEquals(1, photo.getPhotographerId());\n        Assert.assertEquals(\"photo_1\", photo.getPhotoId());\n        Assert.assertEquals(\"One beach\", photo.getPhotoCaption());\n\n        AlbumBi_1_1_1_1_PK albumRev = photo.getAlbum();\n        Assert.assertNotNull(albumRev);\n    }\n\n    private void assertModifiedPhotographer(PhotographerBi_1_1_1_1_PK p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbum());\n        AlbumBi_1_1_1_1_PK album = p.getAlbum();\n        Assert.assertNotNull(album);\n        Assert.assertTrue(album.getPhotographerId() == 1);\n        Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n        Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n        Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n        PhotographerBi_1_1_1_1_PK pRev = album.getPhotographer();\n        Assert.assertNotNull(pRev);\n\n        PhotoBi_1_1_1_1_PK photo = album.getPhoto();\n        Assert.assertNotNull(photo);\n        Assert.assertEquals(1, photo.getPhotographerId());\n        Assert.assertEquals(\"photo_1\", photo.getPhotoId());\n        Assert.assertEquals(\"One beach\", photo.getPhotoCaption());\n\n        AlbumBi_1_1_1_1_PK albumRev = photo.getAlbum();\n        Assert.assertNotNull(albumRev);\n    }\n\n    private PhotographerBi_1_1_1_1_PK populatePhotographer()\n    {\n        PhotographerBi_1_1_1_1_PK p = new PhotographerBi_1_1_1_1_PK();\n        p.setPhotographerId(photographerId);\n        p.setPhotographerName(\"Amresh\");\n\n        AlbumBi_1_1_1_1_PK album = new AlbumBi_1_1_1_1_PK(photographerId, \"album_1\", \"My Phuket Vacation\",\n                \"Went Phuket with friends\");\n\n        PhotoBi_1_1_1_1_PK photo = new PhotoBi_1_1_1_1_PK(photographerId, \"photo_1\", \"One beach\",\n                \"On beach with friends\");\n\n        album.setPhoto(photo);\n\n        p.setAlbum(album);\n        return p;\n    }\n\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef1 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        pColumnDef1.index_type = IndexType.KEYS;\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef1);\n        pCfDef.addToColumn_metadata(pColumnDef2);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_ID\".getBytes()), \"UTF8Type\");\n        columnDef4.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef3);\n        aCfDef.addToColumn_metadata(columnDef4);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestBi_1_1_1_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_1_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_1_1_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_1_1_1_M;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestBi_1_1_1_M extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PickrTestBi_1_1_1_M.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        executeTests();\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        PhotographerBi_1_1_1_M p = populatePhotographer();\n        pickr.addPhotographer(p);\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerBi_1_1_1_M p = (PhotographerBi_1_1_1_M) pickr.getPhotographer(PhotographerBi_1_1_1_M.class,\n                photographerId);\n        assertPhotographer(p);\n\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerBi_1_1_1_M p = (PhotographerBi_1_1_1_M) pickr.getPhotographer(PhotographerBi_1_1_1_M.class,\n                photographerId);\n        assertPhotographer(p);\n        p.setPhotographerName(\"Vivek\");\n\n        pickr.mergePhotographer(p);\n\n        PhotographerBi_1_1_1_M p2 = (PhotographerBi_1_1_1_M) pickr.getPhotographer(PhotographerBi_1_1_1_M.class,\n                photographerId);\n        assertModifiedPhotographer(p2);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerBi_1_1_1_M.class.getSimpleName());\n        PhotographerBi_1_1_1_M p = (PhotographerBi_1_1_1_M) ps.get(0);\n\n        assertModifiedPhotographer(p);\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerBi_1_1_1_M p = (PhotographerBi_1_1_1_M) pickr.getPhotographer(PhotographerBi_1_1_1_M.class,\n                photographerId);\n        assertModifiedPhotographer(p);\n        pickr.deletePhotographer(p);\n        PhotographerBi_1_1_1_M p2 = (PhotographerBi_1_1_1_M) pickr.getPhotographer(PhotographerBi_1_1_1_M.class,\n                photographerId);\n        Assert.assertNull(p2);\n\n    }\n\n    private PhotographerBi_1_1_1_M populatePhotographer()\n    {\n        PhotographerBi_1_1_1_M p = new PhotographerBi_1_1_1_M();\n        p.setPhotographerId(photographerId);\n        p.setPhotographerName(\"Amresh\");\n\n        AlbumBi_1_1_1_M album1 = new AlbumBi_1_1_1_M(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n        album1.addPhoto(new PhotoBi_1_1_1_M(\"photo_1\", \"One beach\", \"On beach with friends\"));\n        album1.addPhoto(new PhotoBi_1_1_1_M(\"photo_2\", \"In Hotel\", \"Chilling out in room\"));\n        album1.addPhoto(new PhotoBi_1_1_1_M(\"photo_3\", \"At Airport\", \"So tired\"));\n\n        p.setAlbum(album1);\n\n        return p;\n\n    }\n\n    private void assertPhotographer(PhotographerBi_1_1_1_M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n        AlbumBi_1_1_1_M album = p.getAlbum();\n        Assert.assertNotNull(album);\n        Assert.assertEquals(\"album_1\", album.getAlbumId());\n        Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n        Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n        List<PhotoBi_1_1_1_M> photos = album.getPhotos();\n        Assert.assertNotNull(photos);\n        Assert.assertFalse(photos.isEmpty());\n        Assert.assertEquals(3, photos.size());\n\n        PhotoBi_1_1_1_M photo1 = photos.get(0);\n        Assert.assertNotNull(photo1);\n        Assert.assertEquals(7, photo1.getPhotoId().length());\n\n        AlbumBi_1_1_1_M albumRev = photo1.getAlbum();\n        Assert.assertNotNull(albumRev);\n    }\n\n    private void assertModifiedPhotographer(PhotographerBi_1_1_1_M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n        AlbumBi_1_1_1_M album = p.getAlbum();\n        Assert.assertNotNull(album);\n        Assert.assertEquals(\"album_1\", album.getAlbumId());\n        Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n        Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n        List<PhotoBi_1_1_1_M> photos = album.getPhotos();\n        Assert.assertNotNull(photos);\n        Assert.assertFalse(photos.isEmpty());\n        Assert.assertEquals(3, photos.size());\n\n        PhotoBi_1_1_1_M photo1 = photos.get(0);\n        Assert.assertNotNull(photo1);\n        Assert.assertEquals(7, photo1.getPhotoId().length());\n\n        AlbumBi_1_1_1_M albumRev = photo1.getAlbum();\n        Assert.assertNotNull(albumRev);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.pickr.PickrBaseTest#startServer\n     * ()\n     */\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef1 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        pColumnDef1.index_type = IndexType.KEYS;\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef1);\n        pCfDef.addToColumn_metadata(pColumnDef2);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef3);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef4.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n        photoLinkCfDef.addToColumn_metadata(columnDef4);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n\n        /**\n         * schema generation for cassandra.\n         * */\n\n        // HBaseCli.createTable(\"PHOTOGRAPHER\");\n        // HBaseCli.addColumnFamily(\"PHOTOGRAPHER\", \"ALBUM_ID\");\n        // HBaseCli.addColumnFamily(\"PHOTOGRAPHER\", \"PHOTOGRAPHER_NAME\");\n        //\n        // HBaseCli.createTable(\"PHOTO\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_CAPTION\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_DESC\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"ALBUM_ID\");\n        //\n        // HBaseCli.createTable(\"ALBUM\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_NAME\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_DESC\");\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestBi_1_M_1_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_M_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_1_M_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_1_M_1_M;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestBi_1_M_1_M extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PickrTestBi_1_M_1_M.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        executeTests();\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        PhotographerBi_1_M_1_M p = populatePhotographer();\n        pickr.addPhotographer(p);\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerBi_1_M_1_M p = (PhotographerBi_1_M_1_M) pickr.getPhotographer(PhotographerBi_1_M_1_M.class,\n                photographerId);\n        assertPhotographer(p);\n\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerBi_1_M_1_M p = (PhotographerBi_1_M_1_M) pickr.getPhotographer(PhotographerBi_1_M_1_M.class,\n                photographerId);\n        assertPhotographer(p);\n        p.setPhotographerName(\"Vivek\");\n\n        pickr.mergePhotographer(p);\n\n        PhotographerBi_1_M_1_M p2 = (PhotographerBi_1_M_1_M) pickr.getPhotographer(PhotographerBi_1_M_1_M.class,\n                photographerId);\n        assertModifiedPhotographer(p2);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerBi_1_M_1_M.class.getSimpleName());\n        PhotographerBi_1_M_1_M p = (PhotographerBi_1_M_1_M) ps.get(0);\n\n        assertModifiedPhotographer(p);\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerBi_1_M_1_M p = (PhotographerBi_1_M_1_M) pickr.getPhotographer(PhotographerBi_1_M_1_M.class,\n                photographerId);\n        assertModifiedPhotographer(p);\n        pickr.deletePhotographer(p);\n        PhotographerBi_1_M_1_M p2 = (PhotographerBi_1_M_1_M) pickr.getPhotographer(PhotographerBi_1_M_1_M.class,\n                photographerId);\n        Assert.assertNull(p2);\n\n    }\n\n    private PhotographerBi_1_M_1_M populatePhotographer()\n    {\n        PhotographerBi_1_M_1_M p = new PhotographerBi_1_M_1_M();\n        p.setPhotographerId(photographerId);\n        p.setPhotographerName(\"Amresh\");\n\n        AlbumBi_1_M_1_M album1 = new AlbumBi_1_M_1_M(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n        album1.addPhoto(new PhotoBi_1_M_1_M(\"photo_1\", \"One beach\", \"On beach with friends\"));\n        album1.addPhoto(new PhotoBi_1_M_1_M(\"photo_2\", \"In Hotel\", \"Chilling out in room\"));\n        album1.addPhoto(new PhotoBi_1_M_1_M(\"photo_3\", \"At Airport\", \"So tired\"));\n\n        AlbumBi_1_M_1_M album2 = new AlbumBi_1_M_1_M(\"album_2\", \"Office Pics\", \"Annual office party photos\");\n        album2.addPhoto(new PhotoBi_1_M_1_M(\"photo_4\", \"Office Team event\", \"Shot at Fun park\"));\n        album2.addPhoto(new PhotoBi_1_M_1_M(\"photo_5\", \"My Team\", \"My team is the best\"));\n\n        p.addAlbum(album1);\n        p.addAlbum(album2);\n        return p;\n\n    }\n\n    private void assertPhotographer(PhotographerBi_1_M_1_M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbums());\n        Assert.assertFalse(p.getAlbums().isEmpty());\n        Assert.assertEquals(2, p.getAlbums().size());\n\n        AlbumBi_1_M_1_M album1 = p.getAlbums().get(0);\n        Assert.assertNotNull(album1);\n        Assert.assertTrue(album1.getAlbumId().equals(\"album_1\") || album1.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album1.getAlbumName().length() == 0);\n        Assert.assertFalse(album1.getAlbumDescription().length() == 0);\n\n        List<PhotoBi_1_M_1_M> album1Photos = album1.getPhotos();\n        Assert.assertNotNull(album1Photos);\n        Assert.assertFalse(album1Photos.isEmpty());\n        Assert.assertFalse(album1Photos.size() < 2);\n\n        PhotoBi_1_M_1_M album1Photo1 = album1Photos.get(0);\n        Assert.assertNotNull(album1Photo1);\n        Assert.assertEquals(7, album1Photo1.getPhotoId().length());\n\n        AlbumBi_1_M_1_M album2 = p.getAlbums().get(1);\n        Assert.assertNotNull(album2);\n        Assert.assertTrue(album2.getAlbumId().equals(\"album_1\") || album2.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album2.getAlbumName().length() == 0);\n        Assert.assertFalse(album2.getAlbumDescription().length() == 0);\n\n        List<PhotoBi_1_M_1_M> album2Photos = album2.getPhotos();\n        Assert.assertNotNull(album2Photos);\n        Assert.assertFalse(album2Photos.isEmpty());\n        Assert.assertFalse(album2Photos.size() < 2);\n\n        PhotoBi_1_M_1_M album2Photo1 = album2Photos.get(0);\n        Assert.assertNotNull(album2Photo1);\n        Assert.assertEquals(7, album2Photo1.getPhotoId().length());\n    }\n\n    private void assertModifiedPhotographer(PhotographerBi_1_M_1_M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbums());\n        Assert.assertFalse(p.getAlbums().isEmpty());\n        Assert.assertEquals(2, p.getAlbums().size());\n\n        AlbumBi_1_M_1_M album1 = p.getAlbums().get(0);\n        Assert.assertNotNull(album1);\n        Assert.assertTrue(album1.getAlbumId().equals(\"album_1\") || album1.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album1.getAlbumName().length() == 0);\n        Assert.assertFalse(album1.getAlbumDescription().length() == 0);\n\n        List<PhotoBi_1_M_1_M> album1Photos = album1.getPhotos();\n        Assert.assertNotNull(album1Photos);\n        Assert.assertFalse(album1Photos.isEmpty());\n        Assert.assertFalse(album1Photos.size() < 2);\n\n        PhotoBi_1_M_1_M album1Photo1 = album1Photos.get(0);\n        Assert.assertNotNull(album1Photo1);\n        Assert.assertEquals(7, album1Photo1.getPhotoId().length());\n\n        AlbumBi_1_M_1_M album2 = p.getAlbums().get(1);\n        Assert.assertNotNull(album2);\n        Assert.assertTrue(album2.getAlbumId().equals(\"album_1\") || album2.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album2.getAlbumName().length() == 0);\n        Assert.assertFalse(album2.getAlbumDescription().length() == 0);\n\n        List<PhotoBi_1_M_1_M> album2Photos = album2.getPhotos();\n        Assert.assertNotNull(album2Photos);\n        Assert.assertFalse(album2Photos.isEmpty());\n        Assert.assertFalse(album2Photos.size() < 2);\n\n        PhotoBi_1_M_1_M album2Photo1 = album2Photos.get(0);\n        Assert.assertNotNull(album2Photo1);\n        Assert.assertEquals(7, album2Photo1.getPhotoId().length());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.pickr.PickrBaseTest#startServer\n     * ()\n     */\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef2);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        ColumnDef columnDef5 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_ID\".getBytes()), \"UTF8Type\");\n        columnDef5.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef5);\n        aCfDef.addToColumn_metadata(columnDef3);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef4.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n        photoLinkCfDef.addToColumn_metadata(columnDef4);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n\n        /**\n         * schema generation for cassandra.\n         * */\n\n        // HBaseCli.createTable(\"PHOTOGRAPHER\");\n        // HBaseCli.addColumnFamily(\"PHOTOGRAPHER\", \"PHOTOGRAPHER_NAME\");\n        //\n        // HBaseCli.createTable(\"PHOTO\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_CAPTION\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_DESC\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"ALBUM_ID\");\n        //\n        // HBaseCli.createTable(\"ALBUM\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_NAME\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_DESC\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"PHOTOGRAPHER_ID\");\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestBi_1_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_M_M_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_1_M_M_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_1_M_M_M;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestBi_1_M_M_M extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PickrTestBi_1_M_M_M.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void test()\n    {\n        executeTests();\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        PhotographerBi_1_M_M_M p = populatePhotographer();\n        pickr.addPhotographer(p);\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerBi_1_M_M_M p = (PhotographerBi_1_M_M_M) pickr.getPhotographer(PhotographerBi_1_M_M_M.class,\n                photographerId);\n        assertPhotographer(p);\n\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerBi_1_M_M_M p = (PhotographerBi_1_M_M_M) pickr.getPhotographer(PhotographerBi_1_M_M_M.class,\n                photographerId);\n        assertPhotographer(p);\n        p.setPhotographerName(\"Vivek\");\n\n        pickr.mergePhotographer(p);\n\n        PhotographerBi_1_M_M_M p2 = (PhotographerBi_1_M_M_M) pickr.getPhotographer(PhotographerBi_1_M_M_M.class,\n                photographerId);\n        assertModifiedPhotographer(p2);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerBi_1_M_M_M.class.getSimpleName());\n        PhotographerBi_1_M_M_M p = (PhotographerBi_1_M_M_M) ps.get(0);\n\n        assertModifiedPhotographer(p);\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerBi_1_M_M_M p = (PhotographerBi_1_M_M_M) pickr.getPhotographer(PhotographerBi_1_M_M_M.class,\n                photographerId);\n        assertModifiedPhotographer(p);\n        pickr.deletePhotographer(p);\n        PhotographerBi_1_M_M_M p2 = (PhotographerBi_1_M_M_M) pickr.getPhotographer(PhotographerBi_1_M_M_M.class,\n                photographerId);\n        Assert.assertNull(p2);\n\n    }\n\n    private PhotographerBi_1_M_M_M populatePhotographer()\n    {\n        PhotographerBi_1_M_M_M p = new PhotographerBi_1_M_M_M();\n        p.setPhotographerId(photographerId);\n        p.setPhotographerName(\"Amresh\");\n\n        AlbumBi_1_M_M_M album1 = new AlbumBi_1_M_M_M(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n        AlbumBi_1_M_M_M album2 = new AlbumBi_1_M_M_M(\"album_2\", \"Office Pics\", \"Annual office party photos\");\n\n        PhotoBi_1_M_M_M photo1 = new PhotoBi_1_M_M_M(\"photo_1\", \"One beach\", \"On beach with friends\");\n        PhotoBi_1_M_M_M photo2 = new PhotoBi_1_M_M_M(\"photo_2\", \"In Hotel\", \"Chilling out in room\");\n        PhotoBi_1_M_M_M photo3 = new PhotoBi_1_M_M_M(\"photo_3\", \"At Airport\", \"So tired\");\n        PhotoBi_1_M_M_M photo4 = new PhotoBi_1_M_M_M(\"photo_4\", \"Office Team event\", \"Shot at Fun park\");\n        PhotoBi_1_M_M_M photo5 = new PhotoBi_1_M_M_M(\"photo_5\", \"My Team\", \"My team is the best\");\n\n        album1.addPhoto(photo1);\n        album1.addPhoto(photo2);\n        album1.addPhoto(photo3);\n        album1.addPhoto(photo4);\n\n        album2.addPhoto(photo2);\n        album2.addPhoto(photo3);\n        album2.addPhoto(photo4);\n        album2.addPhoto(photo5);\n\n        photo1.addAlbum(album1);\n        photo2.addAlbum(album1);\n        photo2.addAlbum(album2);\n        photo3.addAlbum(album1);\n        photo3.addAlbum(album2);\n        photo4.addAlbum(album1);\n        photo4.addAlbum(album2);\n        photo5.addAlbum(album2);\n\n        album1.setPhotographer(p);\n        album2.setPhotographer(p);\n\n        p.addAlbum(album1);\n        p.addAlbum(album2);\n\n        return p;\n\n    }\n\n    private void assertPhotographer(PhotographerBi_1_M_M_M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbums());\n        Assert.assertFalse(p.getAlbums().isEmpty());\n        Assert.assertEquals(2, p.getAlbums().size());\n\n        // Album 1\n        AlbumBi_1_M_M_M album1 = p.getAlbums().get(0);\n        Assert.assertNotNull(album1);\n        Assert.assertTrue(album1.getAlbumId().equals(\"album_1\") || album1.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album1.getAlbumName().length() == 0);\n        Assert.assertFalse(album1.getAlbumDescription().length() == 0);\n\n        PhotographerBi_1_M_M_M revP = album1.getPhotographer();\n        Assert.assertNotNull(revP);\n        Assert.assertEquals(photographerId, revP.getPhotographerId());\n\n        List<PhotoBi_1_M_M_M> album1Photos = album1.getPhotos();\n        Assert.assertNotNull(album1Photos);\n        Assert.assertFalse(album1Photos.isEmpty());\n        Assert.assertFalse(album1Photos.size() < 2);\n\n        PhotoBi_1_M_M_M album1Photo1 = album1Photos.get(0);\n        Assert.assertNotNull(album1Photo1);\n        Assert.assertEquals(7, album1Photo1.getPhotoId().length());\n\n        Set<AlbumBi_1_M_M_M> revAlbums1 = album1Photo1.getAlbums();\n        Assert.assertNotNull(revAlbums1);\n        Assert.assertFalse(revAlbums1.isEmpty());\n        Assert.assertFalse(revAlbums1.size() < 1);\n\n        // Album 2\n        AlbumBi_1_M_M_M album2 = p.getAlbums().get(1);\n        Assert.assertNotNull(album2);\n        Assert.assertTrue(album2.getAlbumId().equals(\"album_1\") || album2.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album2.getAlbumName().length() == 0);\n        Assert.assertFalse(album2.getAlbumDescription().length() == 0);\n\n        PhotographerBi_1_M_M_M revP2 = album1.getPhotographer();\n        Assert.assertNotNull(revP2);\n        Assert.assertEquals(photographerId, revP2.getPhotographerId());\n\n        List<PhotoBi_1_M_M_M> album2Photos = album2.getPhotos();\n        Assert.assertNotNull(album2Photos);\n    }\n\n    private void assertModifiedPhotographer(PhotographerBi_1_M_M_M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbums());\n        Assert.assertFalse(p.getAlbums().isEmpty());\n        Assert.assertEquals(2, p.getAlbums().size());\n\n        // Album 1\n        AlbumBi_1_M_M_M album1 = p.getAlbums().get(0);\n        Assert.assertNotNull(album1);\n        Assert.assertTrue(album1.getAlbumId().equals(\"album_1\") || album1.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album1.getAlbumName().length() == 0);\n        Assert.assertFalse(album1.getAlbumDescription().length() == 0);\n\n        PhotographerBi_1_M_M_M revP = album1.getPhotographer();\n        Assert.assertNotNull(revP);\n        Assert.assertEquals(photographerId, revP.getPhotographerId());\n\n        List<PhotoBi_1_M_M_M> album1Photos = album1.getPhotos();\n        Assert.assertNotNull(album1Photos);\n        Assert.assertFalse(album1Photos.isEmpty());\n        Assert.assertFalse(album1Photos.size() < 2);\n\n        PhotoBi_1_M_M_M album1Photo1 = album1Photos.get(0);\n        Assert.assertNotNull(album1Photo1);\n        Assert.assertEquals(7, album1Photo1.getPhotoId().length());\n\n        Set<AlbumBi_1_M_M_M> revAlbums1 = album1Photo1.getAlbums();\n        Assert.assertNotNull(revAlbums1);\n        Assert.assertFalse(revAlbums1.isEmpty());\n        Assert.assertFalse(revAlbums1.size() < 1);\n\n        // Album 2\n        AlbumBi_1_M_M_M album2 = p.getAlbums().get(1);\n        Assert.assertNotNull(album2);\n        Assert.assertTrue(album2.getAlbumId().equals(\"album_1\") || album2.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album2.getAlbumName().length() == 0);\n        Assert.assertFalse(album2.getAlbumDescription().length() == 0);\n\n        PhotographerBi_1_M_M_M revP2 = album1.getPhotographer();\n        Assert.assertNotNull(revP2);\n        Assert.assertEquals(photographerId, revP2.getPhotographerId());\n\n        List<PhotoBi_1_M_M_M> album2Photos = album2.getPhotos();\n        Assert.assertNotNull(album2Photos);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.pickr.PickrBaseTest#startServer\n     * ()\n     */\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef2);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        ColumnDef columnDef5 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_ID\".getBytes()), \"UTF8Type\");\n        columnDef5.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef5);\n        aCfDef.addToColumn_metadata(columnDef3);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n\n        CfDef cfDef = new CfDef();\n        cfDef.name = \"ALBUM_PHOTO\";\n        cfDef.keyspace = \"Pickr\";\n        cfDef.setComparator_type(\"UTF8Type\");\n        cfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_ID\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef6 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef4);\n        cfDef.addToColumn_metadata(columnDef6);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(cfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM_PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(cfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM_PHOTO\");\n            }\n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n\n        /**\n         * schema generation for cassandra.\n         * */\n\n        // HBaseCli.createTable(\"PHOTOGRAPHER\");\n        // HBaseCli.addColumnFamily(\"PHOTOGRAPHER\", \"PHOTOGRAPHER_NAME\");\n        //\n        // HBaseCli.createTable(\"PHOTO\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_CAPTION\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_DESC\");\n        //\n        // HBaseCli.createTable(\"ALBUM\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_NAME\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_DESC\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"PHOTOGRAPHER_ID\");\n        //\n        // HBaseCli.createTable(\"ALBUM_PHOTO\");\n        // HBaseCli.addColumnFamily(\"ALBUM_PHOTO\", \"PHOTO_ID\");\n        // HBaseCli.addColumnFamily(\"ALBUM_PHOTO\", \"ALBUM_ID\");\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestBi_M_1_1_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_M_1_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_M_1_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_M_1_1_M;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestBi_M_1_1_M extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PickrTestBi_M_1_1_M.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        executeTests();\n\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        List<PhotographerBi_M_1_1_M> ps = populatePhotographers();\n\n        for (PhotographerBi_M_1_1_M p : ps)\n        {\n            pickr.addPhotographer(p);\n        }\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerBi_M_1_1_M p1 = (PhotographerBi_M_1_1_M) pickr.getPhotographer(PhotographerBi_M_1_1_M.class, 1);\n        assertPhotographer(p1, 1);\n\n        PhotographerBi_M_1_1_M p2 = (PhotographerBi_M_1_1_M) pickr.getPhotographer(PhotographerBi_M_1_1_M.class, 2);\n        assertPhotographer(p2, 2);\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerBi_M_1_1_M p1 = (PhotographerBi_M_1_1_M) pickr.getPhotographer(PhotographerBi_M_1_1_M.class, 1);\n        assertPhotographer(p1, 1);\n        p1.setPhotographerName(\"Amresh2\");\n\n        pickr.mergePhotographer(p1);\n\n        PhotographerBi_M_1_1_M p1Modified = (PhotographerBi_M_1_1_M) pickr.getPhotographer(\n                PhotographerBi_M_1_1_M.class, 1);\n        assertModifiedPhotographer(p1Modified, 1);\n\n        PhotographerBi_M_1_1_M p2 = (PhotographerBi_M_1_1_M) pickr.getPhotographer(PhotographerBi_M_1_1_M.class, 2);\n        assertPhotographer(p2, 2);\n        p2.setPhotographerName(\"Vivek2\");\n\n        pickr.mergePhotographer(p2);\n\n        PhotographerBi_M_1_1_M p2Modified = (PhotographerBi_M_1_1_M) pickr.getPhotographer(\n                PhotographerBi_M_1_1_M.class, 2);\n        assertModifiedPhotographer(p2Modified, 2);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerBi_M_1_1_M.class.getSimpleName());\n\n        for (Object p : ps)\n        {\n            PhotographerBi_M_1_1_M pp = (PhotographerBi_M_1_1_M) p;\n            Assert.assertNotNull(pp);\n            assertModifiedPhotographer(pp, pp.getPhotographerId());\n        }\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerBi_M_1_1_M p1 = (PhotographerBi_M_1_1_M) pickr.getPhotographer(PhotographerBi_M_1_1_M.class, 1);\n        assertModifiedPhotographer(p1, 1);\n        pickr.deletePhotographer(p1);\n\n        PhotographerBi_M_1_1_M p1AfterDeletion = (PhotographerBi_M_1_1_M) pickr.getPhotographer(\n                PhotographerBi_M_1_1_M.class, 1);\n        Assert.assertNull(p1AfterDeletion);\n\n        PhotographerBi_M_1_1_M p2 = (PhotographerBi_M_1_1_M) pickr.getPhotographer(PhotographerBi_M_1_1_M.class, 2);\n        Assert.assertNotNull(p2);\n        pickr.deletePhotographer(p2);\n\n        PhotographerBi_M_1_1_M p2AfterDeletion = (PhotographerBi_M_1_1_M) pickr.getPhotographer(\n                PhotographerBi_M_1_1_M.class, 2);\n        Assert.assertNull(p2AfterDeletion);\n\n    }\n\n    private void assertPhotographer(PhotographerBi_M_1_1_M p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumBi_M_1_1_M album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            List<PhotographerBi_M_1_1_M> ps = album.getPhotographers();\n            Assert.assertNotNull(ps);\n            Assert.assertFalse(ps.isEmpty());\n            Assert.assertEquals(2, ps.size());\n\n            List<PhotoBi_M_1_1_M> albumPhotos = album.getPhotos();\n            Assert.assertNotNull(albumPhotos);\n            Assert.assertFalse(albumPhotos.isEmpty());\n            Assert.assertEquals(3, albumPhotos.size());\n\n            PhotoBi_M_1_1_M photo1 = albumPhotos.get(0);\n            PhotoBi_M_1_1_M photo2 = albumPhotos.get(1);\n            PhotoBi_M_1_1_M photo3 = albumPhotos.get(2);\n\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo3);\n            Assert.assertTrue(photo3.getPhotoId().startsWith(\"photo_\"));\n\n            Assert.assertNotNull(photo1.getAlbum());\n            Assert.assertNotNull(photo2.getAlbum());\n            Assert.assertNotNull(photo3.getAlbum());\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumBi_M_1_1_M album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            List<PhotographerBi_M_1_1_M> ps = album.getPhotographers();\n            Assert.assertNotNull(ps);\n            Assert.assertFalse(ps.isEmpty());\n            Assert.assertEquals(2, ps.size());\n\n            List<PhotoBi_M_1_1_M> albumPhotos = album.getPhotos();\n            Assert.assertNotNull(albumPhotos);\n            Assert.assertFalse(albumPhotos.isEmpty());\n            Assert.assertEquals(3, albumPhotos.size());\n\n            PhotoBi_M_1_1_M photo1 = albumPhotos.get(0);\n            PhotoBi_M_1_1_M photo2 = albumPhotos.get(1);\n            PhotoBi_M_1_1_M photo3 = albumPhotos.get(2);\n\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo3);\n            Assert.assertTrue(photo3.getPhotoId().startsWith(\"photo_\"));\n\n            Assert.assertNotNull(photo1.getAlbum());\n            Assert.assertNotNull(photo2.getAlbum());\n            Assert.assertNotNull(photo3.getAlbum());\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private void assertModifiedPhotographer(PhotographerBi_M_1_1_M p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumBi_M_1_1_M album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            List<PhotographerBi_M_1_1_M> ps = album.getPhotographers();\n            Assert.assertNotNull(ps);\n            Assert.assertFalse(ps.isEmpty());\n            Assert.assertEquals(2, ps.size());\n\n            List<PhotoBi_M_1_1_M> albumPhotos = album.getPhotos();\n            Assert.assertNotNull(albumPhotos);\n            Assert.assertFalse(albumPhotos.isEmpty());\n            Assert.assertEquals(3, albumPhotos.size());\n\n            PhotoBi_M_1_1_M photo1 = albumPhotos.get(0);\n            PhotoBi_M_1_1_M photo2 = albumPhotos.get(1);\n            PhotoBi_M_1_1_M photo3 = albumPhotos.get(2);\n\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo3);\n            Assert.assertTrue(photo3.getPhotoId().startsWith(\"photo_\"));\n\n            Assert.assertNotNull(photo1.getAlbum());\n            Assert.assertNotNull(photo2.getAlbum());\n            Assert.assertNotNull(photo3.getAlbum());\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumBi_M_1_1_M album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            List<PhotographerBi_M_1_1_M> ps = album.getPhotographers();\n            Assert.assertNotNull(ps);\n            Assert.assertFalse(ps.isEmpty());\n            Assert.assertEquals(2, ps.size());\n\n            List<PhotoBi_M_1_1_M> albumPhotos = album.getPhotos();\n            Assert.assertNotNull(albumPhotos);\n            Assert.assertFalse(albumPhotos.isEmpty());\n            Assert.assertEquals(3, albumPhotos.size());\n\n            PhotoBi_M_1_1_M photo1 = albumPhotos.get(0);\n            PhotoBi_M_1_1_M photo2 = albumPhotos.get(1);\n            PhotoBi_M_1_1_M photo3 = albumPhotos.get(2);\n\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo3);\n            Assert.assertTrue(photo3.getPhotoId().startsWith(\"photo_\"));\n\n            Assert.assertNotNull(photo1.getAlbum());\n            Assert.assertNotNull(photo2.getAlbum());\n            Assert.assertNotNull(photo3.getAlbum());\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private List<PhotographerBi_M_1_1_M> populatePhotographers()\n    {\n        List<PhotographerBi_M_1_1_M> photographers = new ArrayList<PhotographerBi_M_1_1_M>();\n\n        // Photographer 1\n        PhotographerBi_M_1_1_M p1 = new PhotographerBi_M_1_1_M();\n        p1.setPhotographerId(1);\n        p1.setPhotographerName(\"Amresh\");\n\n        AlbumBi_M_1_1_M album = new AlbumBi_M_1_1_M(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n\n        album.addPhoto(new PhotoBi_M_1_1_M(\"photo_1\", \"One beach\", \"On beach with friends\"));\n        album.addPhoto(new PhotoBi_M_1_1_M(\"photo_2\", \"In Hotel\", \"Chilling out in room\"));\n        album.addPhoto(new PhotoBi_M_1_1_M(\"photo_3\", \"At Airport\", \"So tired\"));\n\n        p1.setAlbum(album);\n\n        // Photographer 2\n        PhotographerBi_M_1_1_M p2 = new PhotographerBi_M_1_1_M();\n        p2.setPhotographerId(2);\n        p2.setPhotographerName(\"Vivek\");\n\n        p2.setAlbum(album);\n\n        photographers.add(p1);\n        photographers.add(p2);\n\n        return photographers;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.pickr.PickrBaseTest#startServer\n     * ()\n     */\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        ColumnDef pColumnDef5 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        pColumnDef5.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef2);\n        pCfDef.addToColumn_metadata(pColumnDef5);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef3);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        ColumnDef columnDef5 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef5.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n        photoLinkCfDef.addToColumn_metadata(columnDef5);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n            \n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestBi_M_1_M_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_M_1_M_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_M_1_M_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_M_1_M_1;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestBi_M_1_M_1 extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PickrTestBi_M_1_M_1.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        executeTests();\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        List<PhotographerBi_M_1_M_1> ps = populatePhotographers();\n\n        for (PhotographerBi_M_1_M_1 p : ps)\n        {\n            pickr.addPhotographer(p);\n        }\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerBi_M_1_M_1 p1 = (PhotographerBi_M_1_M_1) pickr.getPhotographer(PhotographerBi_M_1_M_1.class, 1);\n        assertPhotographer(p1, 1);\n\n        PhotographerBi_M_1_M_1 p2 = (PhotographerBi_M_1_M_1) pickr.getPhotographer(PhotographerBi_M_1_M_1.class, 2);\n        assertPhotographer(p2, 2);\n\n        PhotographerBi_M_1_M_1 p3 = (PhotographerBi_M_1_M_1) pickr.getPhotographer(PhotographerBi_M_1_M_1.class, 3);\n        assertPhotographer(p3, 3);\n\n        PhotographerBi_M_1_M_1 p4 = (PhotographerBi_M_1_M_1) pickr.getPhotographer(PhotographerBi_M_1_M_1.class, 4);\n        assertPhotographer(p4, 4);\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerBi_M_1_M_1 p1 = (PhotographerBi_M_1_M_1) pickr.getPhotographer(PhotographerBi_M_1_M_1.class, 1);\n        assertPhotographer(p1, 1);\n        p1.setPhotographerName(\"Amresh2\");\n\n        pickr.mergePhotographer(p1);\n\n        PhotographerBi_M_1_M_1 p1Modified = (PhotographerBi_M_1_M_1) pickr.getPhotographer(\n                PhotographerBi_M_1_M_1.class, 1);\n        assertModifiedPhotographer(p1Modified, 1);\n\n        PhotographerBi_M_1_M_1 p2 = (PhotographerBi_M_1_M_1) pickr.getPhotographer(PhotographerBi_M_1_M_1.class, 2);\n        assertPhotographer(p2, 2);\n\n        p2.setPhotographerName(\"Vivek2\");\n        pickr.mergePhotographer(p2);\n\n        PhotographerBi_M_1_M_1 p2Modified = (PhotographerBi_M_1_M_1) pickr.getPhotographer(\n                PhotographerBi_M_1_M_1.class, 2);\n        assertModifiedPhotographer(p2Modified, 2);\n\n        PhotographerBi_M_1_M_1 p3 = (PhotographerBi_M_1_M_1) pickr.getPhotographer(PhotographerBi_M_1_M_1.class, 3);\n        assertPhotographer(p3, 3);\n        p3.setPhotographerName(\"Kuldeep2\");\n\n        pickr.mergePhotographer(p3);\n\n        PhotographerBi_M_1_M_1 p3Modified = (PhotographerBi_M_1_M_1) pickr.getPhotographer(\n                PhotographerBi_M_1_M_1.class, 3);\n        assertModifiedPhotographer(p3Modified, 3);\n\n        PhotographerBi_M_1_M_1 p4 = (PhotographerBi_M_1_M_1) pickr.getPhotographer(PhotographerBi_M_1_M_1.class, 4);\n        assertPhotographer(p4, 4);\n\n        p4.setPhotographerName(\"VivekS2\");\n        pickr.mergePhotographer(p4);\n\n        PhotographerBi_M_1_M_1 p4Modified = (PhotographerBi_M_1_M_1) pickr.getPhotographer(\n                PhotographerBi_M_1_M_1.class, 4);\n        assertModifiedPhotographer(p4Modified, 4);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerBi_M_1_M_1.class.getSimpleName());\n\n        for (Object p : ps)\n        {\n            PhotographerBi_M_1_M_1 pp = (PhotographerBi_M_1_M_1) p;\n            Assert.assertNotNull(pp);\n            assertModifiedPhotographer(pp, pp.getPhotographerId());\n        }\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerBi_M_1_M_1 p1 = (PhotographerBi_M_1_M_1) pickr.getPhotographer(PhotographerBi_M_1_M_1.class, 1);\n        assertModifiedPhotographer(p1, 1);\n\n        pickr.deletePhotographer(p1);\n\n        PhotographerBi_M_1_M_1 p1AfterDeletion = (PhotographerBi_M_1_M_1) pickr.getPhotographer(\n                PhotographerBi_M_1_M_1.class, 1);\n        Assert.assertNull(p1AfterDeletion);\n\n        PhotographerBi_M_1_M_1 p2 = (PhotographerBi_M_1_M_1) pickr.getPhotographer(PhotographerBi_M_1_M_1.class, 2);\n        Assert.assertNotNull(p2);\n\n        pickr.deletePhotographer(p2);\n\n        PhotographerBi_M_1_M_1 p2AfterDeletion = (PhotographerBi_M_1_M_1) pickr.getPhotographer(\n                PhotographerBi_M_1_M_1.class, 2);\n        Assert.assertNull(p2AfterDeletion);\n\n        PhotographerBi_M_1_M_1 p3 = (PhotographerBi_M_1_M_1) pickr.getPhotographer(PhotographerBi_M_1_M_1.class, 3);\n        Assert.assertNotNull(p3);\n\n        pickr.deletePhotographer(p3);\n\n        PhotographerBi_M_1_M_1 p3AfterDeletion = (PhotographerBi_M_1_M_1) pickr.getPhotographer(\n                PhotographerBi_M_1_M_1.class, 3);\n        Assert.assertNull(p3AfterDeletion);\n\n        PhotographerBi_M_1_M_1 p4 = (PhotographerBi_M_1_M_1) pickr.getPhotographer(PhotographerBi_M_1_M_1.class, 4);\n        Assert.assertNotNull(p4);\n\n        pickr.deletePhotographer(p4);\n\n        PhotographerBi_M_1_M_1 p4AfterDeletion = (PhotographerBi_M_1_M_1) pickr.getPhotographer(\n                PhotographerBi_M_1_M_1.class, 4);\n        Assert.assertNull(p4AfterDeletion);\n\n    }\n\n    private void assertPhotographer(PhotographerBi_M_1_M_1 p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumBi_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            Assert.assertNotNull(album.getPhotographers());\n            Assert.assertEquals(2, album.getPhotographers().size());\n            Assert.assertNotNull(album.getPhotographers().get(0));\n            Assert.assertNotNull(album.getPhotographers().get(1));\n\n            PhotoBi_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n\n            Assert.assertNotNull(albumPhoto.getAlbums());\n            Assert.assertEquals(2, albumPhoto.getAlbums().size());\n            Assert.assertNotNull(albumPhoto.getAlbums().get(0));\n            Assert.assertNotNull(albumPhoto.getAlbums().get(1));\n\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumBi_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            Assert.assertNotNull(album.getPhotographers());\n            Assert.assertEquals(2, album.getPhotographers().size());\n            Assert.assertNotNull(album.getPhotographers().get(0));\n            Assert.assertNotNull(album.getPhotographers().get(1));\n\n            PhotoBi_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n\n            Assert.assertNotNull(albumPhoto.getAlbums());\n            Assert.assertEquals(2, albumPhoto.getAlbums().size());\n            Assert.assertNotNull(albumPhoto.getAlbums().get(0));\n            Assert.assertNotNull(albumPhoto.getAlbums().get(1));\n        }\n        else if (photographerId == 3)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(3, p.getPhotographerId());\n            Assert.assertEquals(\"Kuldeep\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumBi_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_2\"));\n            Assert.assertEquals(\"My Shimla Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Shimla with friends\", album.getAlbumDescription());\n\n            Assert.assertNotNull(album.getPhotographers());\n            Assert.assertEquals(2, album.getPhotographers().size());\n            Assert.assertNotNull(album.getPhotographers().get(0));\n            Assert.assertNotNull(album.getPhotographers().get(1));\n\n            PhotoBi_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n\n            Assert.assertNotNull(albumPhoto.getAlbums());\n            Assert.assertEquals(2, albumPhoto.getAlbums().size());\n            Assert.assertNotNull(albumPhoto.getAlbums().get(0));\n            Assert.assertNotNull(albumPhoto.getAlbums().get(1));\n        }\n        else if (photographerId == 4)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(4, p.getPhotographerId());\n            Assert.assertEquals(\"VivekS\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumBi_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_2\"));\n            Assert.assertEquals(\"My Shimla Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Shimla with friends\", album.getAlbumDescription());\n\n            Assert.assertNotNull(album.getPhotographers());\n            Assert.assertEquals(2, album.getPhotographers().size());\n            Assert.assertNotNull(album.getPhotographers().get(0));\n            Assert.assertNotNull(album.getPhotographers().get(1));\n\n            PhotoBi_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n\n            Assert.assertNotNull(albumPhoto.getAlbums());\n            Assert.assertEquals(2, albumPhoto.getAlbums().size());\n            Assert.assertNotNull(albumPhoto.getAlbums().get(0));\n            Assert.assertNotNull(albumPhoto.getAlbums().get(1));\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private void assertModifiedPhotographer(PhotographerBi_M_1_M_1 p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumBi_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            Assert.assertNotNull(album.getPhotographers());\n            Assert.assertEquals(2, album.getPhotographers().size());\n            Assert.assertNotNull(album.getPhotographers().get(0));\n            Assert.assertNotNull(album.getPhotographers().get(1));\n\n            PhotoBi_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n\n            Assert.assertNotNull(albumPhoto.getAlbums());\n            Assert.assertEquals(2, albumPhoto.getAlbums().size());\n            Assert.assertNotNull(albumPhoto.getAlbums().get(0));\n            Assert.assertNotNull(albumPhoto.getAlbums().get(1));\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumBi_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            Assert.assertNotNull(album.getPhotographers());\n            Assert.assertEquals(2, album.getPhotographers().size());\n            Assert.assertNotNull(album.getPhotographers().get(0));\n            Assert.assertNotNull(album.getPhotographers().get(1));\n\n            PhotoBi_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n\n            Assert.assertNotNull(albumPhoto.getAlbums());\n            Assert.assertEquals(2, albumPhoto.getAlbums().size());\n            Assert.assertNotNull(albumPhoto.getAlbums().get(0));\n            Assert.assertNotNull(albumPhoto.getAlbums().get(1));\n        }\n        else if (photographerId == 3)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(3, p.getPhotographerId());\n            Assert.assertEquals(\"Kuldeep2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumBi_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_2\"));\n            Assert.assertEquals(\"My Shimla Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Shimla with friends\", album.getAlbumDescription());\n\n            Assert.assertNotNull(album.getPhotographers());\n            Assert.assertEquals(2, album.getPhotographers().size());\n            Assert.assertNotNull(album.getPhotographers().get(0));\n            Assert.assertNotNull(album.getPhotographers().get(1));\n\n            PhotoBi_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n\n            Assert.assertNotNull(albumPhoto.getAlbums());\n            Assert.assertEquals(2, albumPhoto.getAlbums().size());\n            Assert.assertNotNull(albumPhoto.getAlbums().get(0));\n            Assert.assertNotNull(albumPhoto.getAlbums().get(1));\n        }\n        else if (photographerId == 4)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(4, p.getPhotographerId());\n            Assert.assertEquals(\"VivekS2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumBi_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_2\"));\n            Assert.assertEquals(\"My Shimla Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Shimla with friends\", album.getAlbumDescription());\n\n            Assert.assertNotNull(album.getPhotographers());\n            Assert.assertEquals(2, album.getPhotographers().size());\n            Assert.assertNotNull(album.getPhotographers().get(0));\n            Assert.assertNotNull(album.getPhotographers().get(1));\n\n            PhotoBi_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n\n            Assert.assertNotNull(albumPhoto.getAlbums());\n            Assert.assertEquals(2, albumPhoto.getAlbums().size());\n            Assert.assertNotNull(albumPhoto.getAlbums().get(0));\n            Assert.assertNotNull(albumPhoto.getAlbums().get(1));\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private List<PhotographerBi_M_1_M_1> populatePhotographers()\n    {\n        List<PhotographerBi_M_1_M_1> photographers = new ArrayList<PhotographerBi_M_1_M_1>();\n\n        // Photographer 1\n        PhotographerBi_M_1_M_1 p1 = new PhotographerBi_M_1_M_1();\n        p1.setPhotographerId(1);\n        p1.setPhotographerName(\"Amresh\");\n\n        AlbumBi_M_1_M_1 album1 = new AlbumBi_M_1_M_1(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n\n        AlbumBi_M_1_M_1 album2 = new AlbumBi_M_1_M_1(\"album_2\", \"My Shimla Vacation\", \"Went Shimla with friends\");\n\n        PhotoBi_M_1_M_1 photo = new PhotoBi_M_1_M_1(\"photo_1\", \"One beach\", \"On beach with friends\");\n        album1.setPhoto(photo);\n        album2.setPhoto(photo);\n\n        p1.setAlbum(album1);\n\n        // Photographer 2\n        PhotographerBi_M_1_M_1 p2 = new PhotographerBi_M_1_M_1();\n        p2.setPhotographerId(2);\n        p2.setPhotographerName(\"Vivek\");\n\n        p2.setAlbum(album1);\n\n        // Photographer 3\n        PhotographerBi_M_1_M_1 p3 = new PhotographerBi_M_1_M_1();\n        p3.setPhotographerId(3);\n        p3.setPhotographerName(\"Kuldeep\");\n\n        p3.setAlbum(album2);\n\n        // Photographer 4\n        PhotographerBi_M_1_M_1 p4 = new PhotographerBi_M_1_M_1();\n        p4.setPhotographerId(4);\n        p4.setPhotographerName(\"VivekS\");\n\n        p4.setAlbum(album2);\n\n        photographers.add(p1);\n        photographers.add(p2);\n        photographers.add(p3);\n        photographers.add(p4);\n\n        return photographers;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.pickr.PickrBaseTest#startServer\n     * ()\n     */\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        ColumnDef pColumnDef5 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        pColumnDef5.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef2);\n        pCfDef.addToColumn_metadata(pColumnDef5);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        ColumnDef columnDef5 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_ID\".getBytes()), \"UTF8Type\");\n        columnDef5.index_type = IndexType.KEYS;\n\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef3);\n        aCfDef.addToColumn_metadata(columnDef5);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n         \n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestBi_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_M_M_1_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_M_M_1_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_M_M_1_1;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestBi_M_M_1_1 extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PickrTestBi_M_M_1_1.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void test()\n    {\n        executeTests();\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        List<PhotographerBi_M_M_1_1> ps = populatePhotographers();\n\n        for (PhotographerBi_M_M_1_1 p : ps)\n        {\n            pickr.addPhotographer(p);\n        }\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerBi_M_M_1_1 p1 = (PhotographerBi_M_M_1_1) pickr.getPhotographer(PhotographerBi_M_M_1_1.class, 1);\n        assertPhotographer(p1, 1);\n\n        PhotographerBi_M_M_1_1 p2 = (PhotographerBi_M_M_1_1) pickr.getPhotographer(PhotographerBi_M_M_1_1.class, 2);\n        assertPhotographer(p2, 2);\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerBi_M_M_1_1 p1 = (PhotographerBi_M_M_1_1) pickr.getPhotographer(PhotographerBi_M_M_1_1.class, 1);\n        assertPhotographer(p1, 1);\n        p1.setPhotographerName(\"Amresh2\");\n\n        pickr.mergePhotographer(p1);\n\n        PhotographerBi_M_M_1_1 p1Modified = (PhotographerBi_M_M_1_1) pickr.getPhotographer(\n                PhotographerBi_M_M_1_1.class, 1);\n        assertModifiedPhotographer(p1Modified, 1);\n\n        PhotographerBi_M_M_1_1 p2 = (PhotographerBi_M_M_1_1) pickr.getPhotographer(PhotographerBi_M_M_1_1.class, 2);\n        assertPhotographer(p2, 2);\n        p2.setPhotographerName(\"Vivek2\");\n\n        pickr.mergePhotographer(p2);\n\n        PhotographerBi_M_M_1_1 p2Modified = (PhotographerBi_M_M_1_1) pickr.getPhotographer(\n                PhotographerBi_M_M_1_1.class, 2);\n        assertModifiedPhotographer(p2Modified, 2);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerBi_M_M_1_1.class.getSimpleName());\n\n        for (Object p : ps)\n        {\n            PhotographerBi_M_M_1_1 pp = (PhotographerBi_M_M_1_1) p;\n            Assert.assertNotNull(pp);\n            assertModifiedPhotographer(pp, pp.getPhotographerId());\n        }\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerBi_M_M_1_1 p1 = (PhotographerBi_M_M_1_1) pickr.getPhotographer(PhotographerBi_M_M_1_1.class, 1);\n        assertModifiedPhotographer(p1, 1);\n        pickr.deletePhotographer(p1);\n\n        PhotographerBi_M_M_1_1 p1AfterDeletion = (PhotographerBi_M_M_1_1) pickr.getPhotographer(\n                PhotographerBi_M_M_1_1.class, 1);\n        Assert.assertNull(p1AfterDeletion);\n    }\n\n    private void assertPhotographer(PhotographerBi_M_M_1_1 p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumBi_M_M_1_1 album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n            PhotoBi_M_M_1_1 photo1 = album1.getPhoto();\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n\n            AlbumBi_M_M_1_1 album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n            PhotoBi_M_M_1_1 photo2 = album2.getPhoto();\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumBi_M_M_1_1 album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n            PhotoBi_M_M_1_1 photo1 = album1.getPhoto();\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n\n            AlbumBi_M_M_1_1 album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n            PhotoBi_M_M_1_1 photo2 = album2.getPhoto();\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private void assertModifiedPhotographer(PhotographerBi_M_M_1_1 p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumBi_M_M_1_1 album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n            PhotoBi_M_M_1_1 photo1 = album1.getPhoto();\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n\n            AlbumBi_M_M_1_1 album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n            PhotoBi_M_M_1_1 photo2 = album2.getPhoto();\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumBi_M_M_1_1 album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n            PhotoBi_M_M_1_1 photo1 = album1.getPhoto();\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n\n            AlbumBi_M_M_1_1 album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n            PhotoBi_M_M_1_1 photo2 = album2.getPhoto();\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private List<PhotographerBi_M_M_1_1> populatePhotographers()\n    {\n        List<PhotographerBi_M_M_1_1> photographers = new ArrayList<PhotographerBi_M_M_1_1>();\n\n        // Photographer 1\n        PhotographerBi_M_M_1_1 p1 = new PhotographerBi_M_M_1_1();\n        p1.setPhotographerId(1);\n        p1.setPhotographerName(\"Amresh\");\n\n        // Photographer 2\n        PhotographerBi_M_M_1_1 p2 = new PhotographerBi_M_M_1_1();\n        p2.setPhotographerId(2);\n        p2.setPhotographerName(\"Vivek\");\n\n        AlbumBi_M_M_1_1 album1 = new AlbumBi_M_M_1_1(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n        AlbumBi_M_M_1_1 album2 = new AlbumBi_M_M_1_1(\"album_2\", \"My Shimla Vacation\", \"Went Shimla with friends\");\n        AlbumBi_M_M_1_1 album3 = new AlbumBi_M_M_1_1(\"album_3\", \"My Zurik Vacation\", \"Went Zurik with friends\");\n\n        album1.setPhoto(new PhotoBi_M_M_1_1(\"photo_1\", \"One beach\", \"On beach with friends\"));\n        album2.setPhoto(new PhotoBi_M_M_1_1(\"photo_2\", \"In Hotel\", \"Chilling out in room\"));\n        album3.setPhoto(new PhotoBi_M_M_1_1(\"photo_3\", \"At Airport\", \"So tired\"));\n\n        p1.addAlbum(album1);\n        p1.addAlbum(album2);\n\n        p2.addAlbum(album2);\n        p2.addAlbum(album3);\n\n        photographers.add(p1);\n        photographers.add(p2);\n\n        return photographers;\n    }\n\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef2);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        ColumnDef columnDef5 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_ID\".getBytes()), \"UTF8Type\");\n        columnDef5.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef5);\n        aCfDef.addToColumn_metadata(columnDef3);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n\n        CfDef cfDef = new CfDef();\n        cfDef.name = \"PHOTOGRAPHER_ALBUM\";\n        cfDef.keyspace = \"Pickr\";\n        cfDef.setComparator_type(\"UTF8Type\");\n        cfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_ID\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef6 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef4);\n        cfDef.addToColumn_metadata(columnDef6);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(cfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM_PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(cfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM_PHOTO\");\n            }\n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestBi_M_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_M_M_M_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_M_M_M_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_M_M_M_M;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestBi_M_M_M_M extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PickrTestBi_M_M_M_M.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void test()\n    {\n        executeTests();\n\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        List<PhotographerBi_M_M_M_M> ps = populatePhotographers();\n\n        for (PhotographerBi_M_M_M_M p : ps)\n        {\n            pickr.addPhotographer(p);\n        }\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerBi_M_M_M_M p1 = (PhotographerBi_M_M_M_M) pickr.getPhotographer(PhotographerBi_M_M_M_M.class, 1);\n        assertPhotographer(p1, 1);\n\n        PhotographerBi_M_M_M_M p2 = (PhotographerBi_M_M_M_M) pickr.getPhotographer(PhotographerBi_M_M_M_M.class, 2);\n        assertPhotographer(p2, 2);\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerBi_M_M_M_M p1 = (PhotographerBi_M_M_M_M) pickr.getPhotographer(PhotographerBi_M_M_M_M.class, 1);\n        assertPhotographer(p1, 1);\n        p1.setPhotographerName(\"Amresh2\");\n\n        pickr.mergePhotographer(p1);\n\n        PhotographerBi_M_M_M_M p1Modified = (PhotographerBi_M_M_M_M) pickr.getPhotographer(\n                PhotographerBi_M_M_M_M.class, 1);\n        Assert.assertNotNull(p1Modified);\n        assertModifiedPhotographer(p1Modified, 1);\n\n        PhotographerBi_M_M_M_M p2 = (PhotographerBi_M_M_M_M) pickr.getPhotographer(PhotographerBi_M_M_M_M.class, 2);\n        assertPhotographer(p2, 2);\n        p2.setPhotographerName(\"Vivek2\");\n\n        pickr.mergePhotographer(p2);\n\n        PhotographerBi_M_M_M_M p2Modified = (PhotographerBi_M_M_M_M) pickr.getPhotographer(\n                PhotographerBi_M_M_M_M.class, 2);\n        Assert.assertNotNull(p2Modified);\n        assertModifiedPhotographer(p2Modified, 2);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerBi_M_M_M_M.class.getSimpleName());\n\n        for (Object p : ps)\n        {\n            PhotographerBi_M_M_M_M pp = (PhotographerBi_M_M_M_M) p;\n            Assert.assertNotNull(pp);\n            assertModifiedPhotographer(pp, pp.getPhotographerId());\n        }\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerBi_M_M_M_M p1 = (PhotographerBi_M_M_M_M) pickr.getPhotographer(PhotographerBi_M_M_M_M.class, 1);\n        Assert.assertNotNull(p1);\n        pickr.deletePhotographer(p1);\n\n        PhotographerBi_M_M_M_M p1AfterDeletion = (PhotographerBi_M_M_M_M) pickr.getPhotographer(\n                PhotographerBi_M_M_M_M.class, 1);\n        Assert.assertNull(p1AfterDeletion);\n\n    }\n\n    private void assertPhotographer(PhotographerBi_M_M_M_M p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumBi_M_M_M_M album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n\n            Assert.assertNotNull(album1.getPhotographers());\n            Assert.assertFalse(album1.getPhotographers().isEmpty());\n            Assert.assertTrue(album1.getAlbumId().equals(\"album_1\") ? album1.getPhotographers().size() == 1 : album1\n                    .getPhotographers().size() == 2);\n\n            Assert.assertNotNull(album1.getPhotos());\n            Assert.assertFalse(album1.getPhotos().isEmpty());\n            Assert.assertEquals(2, album1.getPhotos().size());\n\n            PhotoBi_M_M_M_M album1Photo1 = album1.getPhotos().get(0);\n            Assert.assertNotNull(album1Photo1.getAlbums());\n            Assert.assertFalse(album1Photo1.getAlbums().isEmpty());\n\n            AlbumBi_M_M_M_M album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n\n            Assert.assertNotNull(album2.getPhotos());\n            Assert.assertFalse(album2.getPhotos().isEmpty());\n            Assert.assertEquals(2, album2.getPhotos().size());\n\n            PhotoBi_M_M_M_M album2Photo1 = album2.getPhotos().get(0);\n            Assert.assertNotNull(album2Photo1.getAlbums());\n            Assert.assertFalse(album2Photo1.getAlbums().isEmpty());\n\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumBi_M_M_M_M album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n\n            Assert.assertNotNull(album1.getPhotographers());\n            Assert.assertFalse(album1.getPhotographers().isEmpty());\n            Assert.assertTrue(album1.getAlbumId().equals(\"album_3\") ? album1.getPhotographers().size() == 1 : album1\n                    .getPhotographers().size() == 2);\n\n            Assert.assertNotNull(album1.getPhotos());\n            Assert.assertFalse(album1.getPhotos().isEmpty());\n            Assert.assertEquals(2, album1.getPhotos().size());\n\n            PhotoBi_M_M_M_M album1Photo1 = album1.getPhotos().get(0);\n            Assert.assertNotNull(album1Photo1.getAlbums());\n            Assert.assertFalse(album1Photo1.getAlbums().isEmpty());\n\n            AlbumBi_M_M_M_M album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private void assertModifiedPhotographer(PhotographerBi_M_M_M_M p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumBi_M_M_M_M album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n\n            Assert.assertNotNull(album1.getPhotographers());\n            Assert.assertFalse(album1.getPhotographers().isEmpty());\n            Assert.assertTrue(album1.getAlbumId().equals(\"album_1\") ? album1.getPhotographers().size() == 1 : album1\n                    .getPhotographers().size() == 2);\n\n            Assert.assertNotNull(album1.getPhotos());\n            Assert.assertFalse(album1.getPhotos().isEmpty());\n            Assert.assertEquals(2, album1.getPhotos().size());\n\n            PhotoBi_M_M_M_M album1Photo1 = album1.getPhotos().get(0);\n            Assert.assertNotNull(album1Photo1.getAlbums());\n            Assert.assertFalse(album1Photo1.getAlbums().isEmpty());\n\n            AlbumBi_M_M_M_M album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumBi_M_M_M_M album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n\n            Assert.assertNotNull(album1.getPhotographers());\n            Assert.assertFalse(album1.getPhotographers().isEmpty());\n            Assert.assertTrue(album1.getAlbumId().equals(\"album_3\") ? album1.getPhotographers().size() == 1 : album1\n                    .getPhotographers().size() == 2);\n\n            Assert.assertNotNull(album1.getPhotos());\n            Assert.assertFalse(album1.getPhotos().isEmpty());\n            Assert.assertEquals(2, album1.getPhotos().size());\n\n            PhotoBi_M_M_M_M album1Photo1 = album1.getPhotos().get(0);\n            Assert.assertNotNull(album1Photo1.getAlbums());\n            Assert.assertFalse(album1Photo1.getAlbums().isEmpty());\n\n            AlbumBi_M_M_M_M album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private List<PhotographerBi_M_M_M_M> populatePhotographers()\n    {\n        List<PhotographerBi_M_M_M_M> photographers = new ArrayList<PhotographerBi_M_M_M_M>();\n\n        // Photographer 1\n        PhotographerBi_M_M_M_M p1 = new PhotographerBi_M_M_M_M();\n        p1.setPhotographerId(1);\n        p1.setPhotographerName(\"Amresh\");\n\n        // Photographer 2\n        PhotographerBi_M_M_M_M p2 = new PhotographerBi_M_M_M_M();\n        p2.setPhotographerId(2);\n        p2.setPhotographerName(\"Vivek\");\n\n        AlbumBi_M_M_M_M album1 = new AlbumBi_M_M_M_M(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n        AlbumBi_M_M_M_M album2 = new AlbumBi_M_M_M_M(\"album_2\", \"My Shimla Vacation\", \"Went Shimla with friends\");\n        AlbumBi_M_M_M_M album3 = new AlbumBi_M_M_M_M(\"album_3\", \"My Zurik Vacation\", \"Went Zurik with friends\");\n\n        PhotoBi_M_M_M_M photo1 = new PhotoBi_M_M_M_M(\"photo_1\", \"One beach\", \"On beach with friends\");\n        PhotoBi_M_M_M_M photo2 = new PhotoBi_M_M_M_M(\"photo_2\", \"In Hotel\", \"Chilling out in room\");\n        PhotoBi_M_M_M_M photo3 = new PhotoBi_M_M_M_M(\"photo_3\", \"At Airport\", \"So tired\");\n        PhotoBi_M_M_M_M photo4 = new PhotoBi_M_M_M_M(\"photo_4\", \"In Space\", \"I am flying\");\n\n        album1.addPhoto(photo1);\n        album1.addPhoto(photo2);\n        album2.addPhoto(photo2);\n        album2.addPhoto(photo3);\n        album3.addPhoto(photo3);\n        album3.addPhoto(photo4);\n\n        p1.addAlbum(album1);\n        p1.addAlbum(album2);\n\n        p2.addAlbum(album2);\n        p2.addAlbum(album3);\n\n        photographers.add(p1);\n        photographers.add(p2);\n\n        return photographers;\n    }\n\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        /**\n         * schema generation for cassandra.\n         */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef2);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef3);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n\n        CfDef cfDef = new CfDef();\n        cfDef.name = \"PHOTOGRAPHER_ALBUM\";\n        cfDef.keyspace = \"Pickr\";\n        cfDef.setComparator_type(\"UTF8Type\");\n        cfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_ID\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef6 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef4);\n        cfDef.addToColumn_metadata(columnDef6);\n\n        CfDef album_photo = new CfDef();\n        album_photo.name = \"ALBUM_PHOTO\";\n        album_photo.keyspace = \"Pickr\";\n        album_photo.setComparator_type(\"UTF8Type\");\n        album_photo.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef photo_id = new ColumnDef(ByteBuffer.wrap(\"PHOTO_ID\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef album_id = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        album_photo.addToColumn_metadata(photo_id);\n        album_photo.addToColumn_metadata(album_id);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(cfDef);\n        cfDefs.add(photoLinkCfDef);\n        cfDefs.add(album_photo);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM_PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(cfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM_PHOTO\");\n            }\n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestUni_1_1_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_1_1_1_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_1_1_1_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerUni_1_1_1_1;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestUni_1_1_1_1 extends PickrBaseTest\n{\n    private static final Logger log = LoggerFactory.getLogger(PickrTestUni_1_1_1_1.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        executeTests();\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        PhotographerUni_1_1_1_1 p = populatePhotographer();\n        pickr.addPhotographer(p);\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerUni_1_1_1_1 p = (PhotographerUni_1_1_1_1) pickr.getPhotographer(PhotographerUni_1_1_1_1.class,\n                photographerId);\n        assertPhotographer(p);\n        p.setPhotographerName(\"Vivek\");\n\n        pickr.mergePhotographer(p);\n\n        PhotographerUni_1_1_1_1 p2 = (PhotographerUni_1_1_1_1) pickr.getPhotographer(PhotographerUni_1_1_1_1.class,\n                photographerId);\n        assertModifiedPhotographer(p2);\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerUni_1_1_1_1 p = (PhotographerUni_1_1_1_1) pickr.getPhotographer(PhotographerUni_1_1_1_1.class,\n                photographerId);\n        assertPhotographer(p);\n\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerUni_1_1_1_1.class.getSimpleName());\n        PhotographerUni_1_1_1_1 p = (PhotographerUni_1_1_1_1) ps.get(0);\n\n        assertModifiedPhotographer(p);\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerUni_1_1_1_1 p = (PhotographerUni_1_1_1_1) pickr.getPhotographer(PhotographerUni_1_1_1_1.class,\n                photographerId);\n        assertModifiedPhotographer(p);\n        pickr.deletePhotographer(p);\n        PhotographerUni_1_1_1_1 p2 = (PhotographerUni_1_1_1_1) pickr.getPhotographer(PhotographerUni_1_1_1_1.class,\n                photographerId);\n        Assert.assertNull(p2);\n\n    }\n\n    private void assertPhotographer(PhotographerUni_1_1_1_1 p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbum());\n        AlbumUni_1_1_1_1 album = p.getAlbum();\n        Assert.assertNotNull(album);\n        Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n        Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n        Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n        PhotoUni_1_1_1_1 photo = album.getPhoto();\n        Assert.assertNotNull(photo);\n        Assert.assertEquals(\"photo_1\", photo.getPhotoId());\n        Assert.assertEquals(\"One beach\", photo.getPhotoCaption());\n    }\n\n    private void assertModifiedPhotographer(PhotographerUni_1_1_1_1 p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbum());\n        AlbumUni_1_1_1_1 album = p.getAlbum();\n        Assert.assertNotNull(album);\n        Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n        Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n        Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n        PhotoUni_1_1_1_1 photo = album.getPhoto();\n        Assert.assertNotNull(photo);\n        Assert.assertEquals(\"photo_1\", photo.getPhotoId());\n        Assert.assertEquals(\"One beach\", photo.getPhotoCaption());\n    }\n\n    private PhotographerUni_1_1_1_1 populatePhotographer()\n    {\n        PhotographerUni_1_1_1_1 p = new PhotographerUni_1_1_1_1();\n        p.setPhotographerId(photographerId);\n        p.setPhotographerName(\"Amresh\");\n\n        AlbumUni_1_1_1_1 album = new AlbumUni_1_1_1_1(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n\n        PhotoUni_1_1_1_1 photo = new PhotoUni_1_1_1_1(\"photo_1\", \"One beach\", \"On beach with friends\");\n\n        album.setPhoto(photo);\n\n        p.setAlbum(album);\n        return p;\n    }\n\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef1 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        pColumnDef1.index_type = IndexType.KEYS;\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef1);\n        pCfDef.addToColumn_metadata(pColumnDef2);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_ID\".getBytes()), \"UTF8Type\");\n        columnDef4.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef3);\n        aCfDef.addToColumn_metadata(columnDef4);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n          \n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n\n        /**\n         * schema generation for cassandra.\n         * */\n        //\n        // HBaseCli.createTable(\"PHOTOGRAPHER\");\n        // HBaseCli.addColumnFamily(\"PHOTOGRAPHER\", \"ALBUM_ID\");\n        // HBaseCli.addColumnFamily(\"PHOTOGRAPHER\", \"PHOTOGRAPHER_NAME\");\n        //\n        // HBaseCli.createTable(\"PHOTO\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_CAPTION\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_DESC\");\n        //\n        // HBaseCli.createTable(\"ALBUM\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_NAME\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_DESC\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"PHOTO_ID\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestUni_1_1_1_1_PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_1_1_1_1_PK;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_1_1_1_1_PK;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerUni_1_1_1_1_PK;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestUni_1_1_1_1_PK extends PickrBaseTest\n{\n    private static final Logger log = LoggerFactory.getLogger(PickrTestUni_1_1_1_1_PK.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        executeTests();\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        PhotographerUni_1_1_1_1_PK p = populatePhotographer();\n        pickr.addPhotographer(p);\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerUni_1_1_1_1_PK p = (PhotographerUni_1_1_1_1_PK) pickr.getPhotographer(\n                PhotographerUni_1_1_1_1_PK.class, photographerId);\n        assertPhotographer(p);\n        p.setPhotographerName(\"Vivek\");\n\n        pickr.mergePhotographer(p);\n\n        PhotographerUni_1_1_1_1_PK p2 = (PhotographerUni_1_1_1_1_PK) pickr.getPhotographer(\n                PhotographerUni_1_1_1_1_PK.class, photographerId);\n        assertModifiedPhotographer(p2);\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerUni_1_1_1_1_PK p = (PhotographerUni_1_1_1_1_PK) pickr.getPhotographer(\n                PhotographerUni_1_1_1_1_PK.class, photographerId);\n        assertPhotographer(p);\n\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerUni_1_1_1_1_PK.class.getSimpleName());\n        PhotographerUni_1_1_1_1_PK p = (PhotographerUni_1_1_1_1_PK) ps.get(0);\n\n        assertModifiedPhotographer(p);\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerUni_1_1_1_1_PK p = (PhotographerUni_1_1_1_1_PK) pickr.getPhotographer(\n                PhotographerUni_1_1_1_1_PK.class, photographerId);\n        assertModifiedPhotographer(p);\n        pickr.deletePhotographer(p);\n        PhotographerUni_1_1_1_1_PK p2 = (PhotographerUni_1_1_1_1_PK) pickr.getPhotographer(\n                PhotographerUni_1_1_1_1_PK.class, photographerId);\n        Assert.assertNull(p2);\n\n    }\n\n    private void assertPhotographer(PhotographerUni_1_1_1_1_PK p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbum());\n        AlbumUni_1_1_1_1_PK album = p.getAlbum();\n        Assert.assertNotNull(album);\n        Assert.assertTrue(album.getPhotographerId() == 1);\n        Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n        Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n        Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n        PhotoUni_1_1_1_1_PK photo = album.getPhoto();\n        Assert.assertNotNull(photo);\n        Assert.assertEquals(1, photo.getPhotographerId());\n        Assert.assertEquals(\"photo_1\", photo.getPhotoId());\n        Assert.assertEquals(\"One beach\", photo.getPhotoCaption());\n    }\n\n    private void assertModifiedPhotographer(PhotographerUni_1_1_1_1_PK p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbum());\n        AlbumUni_1_1_1_1_PK album = p.getAlbum();\n        Assert.assertNotNull(album);\n        Assert.assertTrue(album.getPhotographerId() == 1);\n        Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n        Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n        Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n        PhotoUni_1_1_1_1_PK photo = album.getPhoto();\n        Assert.assertNotNull(photo);\n        Assert.assertEquals(1, photo.getPhotographerId());\n        Assert.assertEquals(\"photo_1\", photo.getPhotoId());\n        Assert.assertEquals(\"One beach\", photo.getPhotoCaption());\n    }\n\n    private PhotographerUni_1_1_1_1_PK populatePhotographer()\n    {\n        PhotographerUni_1_1_1_1_PK p = new PhotographerUni_1_1_1_1_PK();\n        p.setPhotographerId(photographerId);\n        p.setPhotographerName(\"Amresh\");\n\n        AlbumUni_1_1_1_1_PK album = new AlbumUni_1_1_1_1_PK(photographerId, \"album_1\", \"My Phuket Vacation\",\n                \"Went Phuket with friends\");\n\n        PhotoUni_1_1_1_1_PK photo = new PhotoUni_1_1_1_1_PK(photographerId, \"photo_1\", \"One beach\",\n                \"On beach with friends\");\n\n        album.setPhoto(photo);\n\n        p.setAlbum(album);\n        return p;\n    }\n\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef1 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        pColumnDef1.index_type = IndexType.KEYS;\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef1);\n        pCfDef.addToColumn_metadata(pColumnDef2);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_ID\".getBytes()), \"UTF8Type\");\n        columnDef4.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef3);\n        aCfDef.addToColumn_metadata(columnDef4);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n          \n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n\n        /**\n         * schema generation for cassandra.\n         * */\n        //\n        // HBaseCli.createTable(\"PHOTOGRAPHER\");\n        // HBaseCli.addColumnFamily(\"PHOTOGRAPHER\", \"ALBUM_ID\");\n        // HBaseCli.addColumnFamily(\"PHOTOGRAPHER\", \"PHOTOGRAPHER_NAME\");\n        //\n        // HBaseCli.createTable(\"PHOTO\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_CAPTION\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_DESC\");\n        //\n        // HBaseCli.createTable(\"ALBUM\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_NAME\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_DESC\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"PHOTO_ID\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestUni_1_1_1_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_1_1_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_1_1_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerUni_1_1_1_M;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestUni_1_1_1_M extends PickrBaseTest\n{\n    private static final Logger log = LoggerFactory.getLogger(PickrTestUni_1_1_1_M.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        executeTests();\n\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        PhotographerUni_1_1_1_M p = populatePhotographer();\n        pickr.addPhotographer(p);\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerUni_1_1_1_M p = (PhotographerUni_1_1_1_M) pickr.getPhotographer(PhotographerUni_1_1_1_M.class,\n                photographerId);\n        assertPhotographer(p);\n\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerUni_1_1_1_M p = (PhotographerUni_1_1_1_M) pickr.getPhotographer(PhotographerUni_1_1_1_M.class,\n                photographerId);\n        assertPhotographer(p);\n        p.setPhotographerName(\"Vivek\");\n\n        pickr.mergePhotographer(p);\n\n        PhotographerUni_1_1_1_M p2 = (PhotographerUni_1_1_1_M) pickr.getPhotographer(PhotographerUni_1_1_1_M.class,\n                photographerId);\n        assertModifiedPhotographer(p2);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerUni_1_1_1_M.class.getSimpleName());\n        PhotographerUni_1_1_1_M p = (PhotographerUni_1_1_1_M) ps.get(0);\n\n        assertModifiedPhotographer(p);\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerUni_1_1_1_M p = (PhotographerUni_1_1_1_M) pickr.getPhotographer(PhotographerUni_1_1_1_M.class,\n                photographerId);\n        assertModifiedPhotographer(p);\n        pickr.deletePhotographer(p);\n        PhotographerUni_1_1_1_M p2 = (PhotographerUni_1_1_1_M) pickr.getPhotographer(PhotographerUni_1_1_1_M.class,\n                photographerId);\n        Assert.assertNull(p2);\n\n    }\n\n    private void assertPhotographer(PhotographerUni_1_1_1_M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbum());\n        AlbumUni_1_1_1_M album = p.getAlbum();\n        Assert.assertNotNull(album);\n        Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n        Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n        Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n        List<PhotoUni_1_1_1_M> albumPhotos = album.getPhotos();\n        Assert.assertNotNull(albumPhotos);\n        Assert.assertFalse(albumPhotos.isEmpty());\n        Assert.assertEquals(3, albumPhotos.size());\n\n        PhotoUni_1_1_1_M photo1 = albumPhotos.get(0);\n        PhotoUni_1_1_1_M photo2 = albumPhotos.get(0);\n        PhotoUni_1_1_1_M photo3 = albumPhotos.get(0);\n\n        Assert.assertNotNull(photo1);\n        Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n        Assert.assertNotNull(photo2);\n        Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n        Assert.assertNotNull(photo3);\n        Assert.assertTrue(photo3.getPhotoId().startsWith(\"photo_\"));\n\n    }\n\n    private void assertModifiedPhotographer(PhotographerUni_1_1_1_M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbum());\n        AlbumUni_1_1_1_M album = p.getAlbum();\n        Assert.assertNotNull(album);\n        Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n        Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n        Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n        List<PhotoUni_1_1_1_M> albumPhotos = album.getPhotos();\n        Assert.assertNotNull(albumPhotos);\n        Assert.assertFalse(albumPhotos.isEmpty());\n        Assert.assertEquals(3, albumPhotos.size());\n\n        PhotoUni_1_1_1_M photo1 = albumPhotos.get(0);\n        PhotoUni_1_1_1_M photo2 = albumPhotos.get(0);\n        PhotoUni_1_1_1_M photo3 = albumPhotos.get(0);\n\n        Assert.assertNotNull(photo1);\n        Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n        Assert.assertNotNull(photo2);\n        Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n        Assert.assertNotNull(photo3);\n        Assert.assertTrue(photo3.getPhotoId().startsWith(\"photo_\"));\n\n    }\n\n    private PhotographerUni_1_1_1_M populatePhotographer()\n    {\n        PhotographerUni_1_1_1_M p = new PhotographerUni_1_1_1_M();\n        p.setPhotographerId(photographerId);\n        p.setPhotographerName(\"Amresh\");\n\n        AlbumUni_1_1_1_M album = new AlbumUni_1_1_1_M(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n\n        album.addPhoto(new PhotoUni_1_1_1_M(\"photo_1\", \"One beach\", \"On beach with friends\"));\n        album.addPhoto(new PhotoUni_1_1_1_M(\"photo_2\", \"In Hotel\", \"Chilling out in room\"));\n        album.addPhoto(new PhotoUni_1_1_1_M(\"photo_3\", \"At Airport\", \"So tired\"));\n\n        p.setAlbum(album);\n\n        return p;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.pickr.PickrBaseTest#startServer\n     * ()\n     */\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef1 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        pColumnDef1.index_type = IndexType.KEYS;\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef1);\n        pCfDef.addToColumn_metadata(pColumnDef2);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef3);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef4.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n        photoLinkCfDef.addToColumn_metadata(columnDef4);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n\n        /**\n         * schema generation for cassandra.\n         * */\n\n        // HBaseCli.createTable(\"PHOTOGRAPHER\");\n        // HBaseCli.addColumnFamily(\"PHOTOGRAPHER\", \"ALBUM_ID\");\n        // HBaseCli.addColumnFamily(\"PHOTOGRAPHER\", \"PHOTOGRAPHER_NAME\");\n        //\n        // HBaseCli.createTable(\"PHOTO\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_CAPTION\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_DESC\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"ALBUM_ID\");\n        //\n        // HBaseCli.createTable(\"ALBUM\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_NAME\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_DESC\");\n    }\n\n}"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestUni_1_M_1_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_1_M_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_1_M_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerUni_1_M_1_M;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestUni_1_M_1_M extends PickrBaseTest\n{\n    private static final Logger log = LoggerFactory.getLogger(PickrTestUni_1_M_1_M.class);;\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        executeTests();\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        PhotographerUni_1_M_1_M p = preparePhotographer();\n\n        pickr.addPhotographer(p);\n    }\n\n    @Override\n    public void updatePhotographer()\n    {\n        PhotographerUni_1_M_1_M p = (PhotographerUni_1_M_1_M) pickr.getPhotographer(PhotographerUni_1_M_1_M.class,\n                photographerId);\n        assertPhotographer(p);\n\n        p.setPhotographerName(\"Vivek\");\n\n        pickr.mergePhotographer(p);\n\n        PhotographerUni_1_M_1_M p2 = (PhotographerUni_1_M_1_M) pickr.getPhotographer(PhotographerUni_1_M_1_M.class,\n                photographerId);\n\n        assertModifiedPhotographer(p2);\n    }\n\n    @Override\n    public void getPhotographer()\n    {\n        PhotographerUni_1_M_1_M p = (PhotographerUni_1_M_1_M) pickr.getPhotographer(PhotographerUni_1_M_1_M.class,\n                photographerId);\n        assertPhotographer(p);\n    }\n\n    @Override\n    public void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerUni_1_M_1_M.class.getSimpleName());\n        PhotographerUni_1_M_1_M p = (PhotographerUni_1_M_1_M) ps.get(0);\n\n        assertModifiedPhotographer(p);\n\n    }\n\n    @Override\n    public void deletePhotographer()\n    {\n        PhotographerUni_1_M_1_M p = (PhotographerUni_1_M_1_M) pickr.getPhotographer(PhotographerUni_1_M_1_M.class,\n                photographerId);\n        assertModifiedPhotographer(p);\n        pickr.deletePhotographer(p);\n        PhotographerUni_1_M_1_M p2 = (PhotographerUni_1_M_1_M) pickr.getPhotographer(PhotographerUni_1_M_1_M.class,\n                photographerId);\n        Assert.assertNull(p2);\n\n    }\n\n    private PhotographerUni_1_M_1_M preparePhotographer()\n    {\n        PhotographerUni_1_M_1_M p = new PhotographerUni_1_M_1_M();\n        p.setPhotographerId(photographerId);\n        p.setPhotographerName(\"Amresh\");\n\n        AlbumUni_1_M_1_M album1 = new AlbumUni_1_M_1_M(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n        album1.addPhoto(new PhotoUni_1_M_1_M(\"photo_1\", \"One beach\", \"On beach with friends\"));\n        album1.addPhoto(new PhotoUni_1_M_1_M(\"photo_2\", \"In Hotel\", \"Chilling out in room\"));\n        album1.addPhoto(new PhotoUni_1_M_1_M(\"photo_3\", \"At Airport\", \"So tired\"));\n\n        AlbumUni_1_M_1_M album2 = new AlbumUni_1_M_1_M(\"album_2\", \"Office Pics\", \"Annual office party photos\");\n        album2.addPhoto(new PhotoUni_1_M_1_M(\"photo_4\", \"Office Team event\", \"Shot at Fun park\"));\n        album2.addPhoto(new PhotoUni_1_M_1_M(\"photo_5\", \"My Team\", \"My team is the best\"));\n\n        p.addAlbum(album1);\n        p.addAlbum(album2);\n        return p;\n\n    }\n\n    private void assertPhotographer(PhotographerUni_1_M_1_M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbums());\n        Assert.assertFalse(p.getAlbums().isEmpty());\n        Assert.assertEquals(2, p.getAlbums().size());\n\n        AlbumUni_1_M_1_M album1 = p.getAlbums().get(0);\n        Assert.assertNotNull(album1);\n        Assert.assertTrue(album1.getAlbumId().equals(\"album_1\") || album1.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album1.getAlbumName().length() == 0);\n        Assert.assertFalse(album1.getAlbumDescription().length() == 0);\n\n        List<PhotoUni_1_M_1_M> album1Photos = album1.getPhotos();\n        Assert.assertNotNull(album1Photos);\n        Assert.assertFalse(album1Photos.isEmpty());\n        Assert.assertFalse(album1Photos.size() < 2);\n\n        PhotoUni_1_M_1_M album1Photo1 = album1Photos.get(0);\n        Assert.assertNotNull(album1Photo1);\n        Assert.assertEquals(7, album1Photo1.getPhotoId().length());\n\n        AlbumUni_1_M_1_M album2 = p.getAlbums().get(1);\n        Assert.assertNotNull(album2);\n        Assert.assertTrue(album2.getAlbumId().equals(\"album_1\") || album2.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album2.getAlbumName().length() == 0);\n        Assert.assertFalse(album2.getAlbumDescription().length() == 0);\n\n        List<PhotoUni_1_M_1_M> album2Photos = album2.getPhotos();\n        Assert.assertNotNull(album2Photos);\n        Assert.assertFalse(album2Photos.isEmpty());\n        Assert.assertFalse(album2Photos.size() < 2);\n\n        PhotoUni_1_M_1_M album2Photo1 = album2Photos.get(0);\n        Assert.assertNotNull(album2Photo1);\n        Assert.assertEquals(7, album2Photo1.getPhotoId().length());\n    }\n\n    private void assertModifiedPhotographer(PhotographerUni_1_M_1_M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbums());\n        Assert.assertFalse(p.getAlbums().isEmpty());\n        Assert.assertEquals(2, p.getAlbums().size());\n\n        AlbumUni_1_M_1_M album1 = p.getAlbums().get(0);\n        Assert.assertNotNull(album1);\n        Assert.assertTrue(album1.getAlbumId().equals(\"album_1\") || album1.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album1.getAlbumName().length() == 0);\n        Assert.assertFalse(album1.getAlbumDescription().length() == 0);\n\n        List<PhotoUni_1_M_1_M> album1Photos = album1.getPhotos();\n        Assert.assertNotNull(album1Photos);\n        Assert.assertFalse(album1Photos.isEmpty());\n        Assert.assertFalse(album1Photos.size() < 2);\n\n        PhotoUni_1_M_1_M album1Photo1 = album1Photos.get(0);\n        Assert.assertNotNull(album1Photo1);\n        Assert.assertEquals(7, album1Photo1.getPhotoId().length());\n\n        AlbumUni_1_M_1_M album2 = p.getAlbums().get(1);\n        Assert.assertNotNull(album2);\n        Assert.assertTrue(album2.getAlbumId().equals(\"album_1\") || album2.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album2.getAlbumName().length() == 0);\n        Assert.assertFalse(album2.getAlbumDescription().length() == 0);\n\n        List<PhotoUni_1_M_1_M> album2Photos = album2.getPhotos();\n        Assert.assertNotNull(album2Photos);\n        Assert.assertFalse(album2Photos.isEmpty());\n        Assert.assertFalse(album2Photos.size() < 2);\n\n        PhotoUni_1_M_1_M album2Photo1 = album2Photos.get(0);\n        Assert.assertNotNull(album2Photo1);\n        Assert.assertEquals(7, album2Photo1.getPhotoId().length());\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.pickr.PickrBaseTest#startServer\n     * ()\n     */\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef2);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        ColumnDef columnDef5 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_ID\".getBytes()), \"UTF8Type\");\n        columnDef5.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef5);\n        aCfDef.addToColumn_metadata(columnDef3);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef4.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n        photoLinkCfDef.addToColumn_metadata(columnDef4);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n         \n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n\n        /**\n         * schema generation for cassandra.\n         * */\n\n        // HBaseCli.createTable(\"PHOTOGRAPHER\");\n        // HBaseCli.addColumnFamily(\"PHOTOGRAPHER\", \"PHOTOGRAPHER_NAME\");\n        //\n        // HBaseCli.createTable(\"PHOTO\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_CAPTION\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"PHOTO_DESC\");\n        // HBaseCli.addColumnFamily(\"PHOTO\", \"ALBUM_ID\");\n        //\n        // HBaseCli.createTable(\"ALBUM\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_NAME\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"ALBUM_DESC\");\n        // HBaseCli.addColumnFamily(\"ALBUM\", \"PHOTOGRAPHER_ID\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestUni_1_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_1_M_M_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_1_M_M_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerUni_1_M_M_M;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestUni_1_M_M_M extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PhotographerUni_1_M_M_M.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        executeTests();\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        PhotographerUni_1_M_M_M p = preparePhotographer();\n        pickr.addPhotographer(p);\n    }\n\n    @Override\n    public void getPhotographer()\n    {\n        PhotographerUni_1_M_M_M p = (PhotographerUni_1_M_M_M) pickr.getPhotographer(PhotographerUni_1_M_M_M.class,\n                photographerId);\n        assertPhotographer(p);\n    }\n\n    @Override\n    public void updatePhotographer()\n    {\n        PhotographerUni_1_M_M_M p = (PhotographerUni_1_M_M_M) pickr.getPhotographer(PhotographerUni_1_M_M_M.class,\n                photographerId);\n        assertPhotographer(p);\n\n        p.setPhotographerName(\"Vivek\");\n\n        pickr.mergePhotographer(p);\n\n        PhotographerUni_1_M_M_M p2 = (PhotographerUni_1_M_M_M) pickr.getPhotographer(PhotographerUni_1_M_M_M.class,\n                photographerId);\n        assertModifiedPhotographer(p2);\n    }\n\n    @Override\n    public void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerUni_1_M_M_M.class.getSimpleName());\n        PhotographerUni_1_M_M_M p = (PhotographerUni_1_M_M_M) ps.get(0);\n\n        assertModifiedPhotographer(p);\n\n    }\n\n    @Override\n    public void deletePhotographer()\n    {\n        PhotographerUni_1_M_M_M p = (PhotographerUni_1_M_M_M) pickr.getPhotographer(PhotographerUni_1_M_M_M.class,\n                photographerId);\n        assertModifiedPhotographer(p);\n        pickr.deletePhotographer(p);\n        PhotographerUni_1_M_M_M p2 = (PhotographerUni_1_M_M_M) pickr.getPhotographer(PhotographerUni_1_M_M_M.class,\n                photographerId);\n        Assert.assertNull(p2);\n\n    }\n\n    private PhotographerUni_1_M_M_M preparePhotographer()\n    {\n        PhotographerUni_1_M_M_M p = new PhotographerUni_1_M_M_M();\n        p.setPhotographerId(photographerId);\n        p.setPhotographerName(\"Amresh\");\n\n        AlbumUni_1_M_M_M album1 = new AlbumUni_1_M_M_M(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n        AlbumUni_1_M_M_M album2 = new AlbumUni_1_M_M_M(\"album_2\", \"Office Pics\", \"Annual office party photos\");\n\n        PhotoUni_1_M_M_M photo1 = new PhotoUni_1_M_M_M(\"photo_1\", \"One beach\", \"On beach with friends\");\n        PhotoUni_1_M_M_M photo2 = new PhotoUni_1_M_M_M(\"photo_2\", \"In Hotel\", \"Chilling out in room\");\n        PhotoUni_1_M_M_M photo3 = new PhotoUni_1_M_M_M(\"photo_3\", \"At Airport\", \"So tired\");\n        PhotoUni_1_M_M_M photo4 = new PhotoUni_1_M_M_M(\"photo_4\", \"Office Team event\", \"Shot at Fun park\");\n        PhotoUni_1_M_M_M photo5 = new PhotoUni_1_M_M_M(\"photo_5\", \"My Team\", \"My team is the best\");\n\n        album1.addPhoto(photo1);\n        album1.addPhoto(photo2);\n        album1.addPhoto(photo3);\n        album1.addPhoto(photo4);\n\n        album2.addPhoto(photo2);\n        album2.addPhoto(photo3);\n        album2.addPhoto(photo4);\n        album2.addPhoto(photo5);\n\n        p.addAlbum(album1);\n        p.addAlbum(album2);\n\n        return p;\n\n    }\n\n    private void assertPhotographer(PhotographerUni_1_M_M_M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbums());\n        Assert.assertFalse(p.getAlbums().isEmpty());\n        Assert.assertEquals(2, p.getAlbums().size());\n\n        AlbumUni_1_M_M_M album1 = p.getAlbums().get(0);\n        Assert.assertNotNull(album1);\n        Assert.assertTrue(album1.getAlbumId().equals(\"album_1\") || album1.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album1.getAlbumName().length() == 0);\n        Assert.assertFalse(album1.getAlbumDescription().length() == 0);\n\n        List<PhotoUni_1_M_M_M> album1Photos = album1.getPhotos();\n        Assert.assertNotNull(album1Photos);\n        Assert.assertFalse(album1Photos.isEmpty());\n        Assert.assertTrue(album1Photos.size() == 4);\n\n        PhotoUni_1_M_M_M album1Photo1 = album1Photos.get(0);\n        Assert.assertNotNull(album1Photo1);\n        Assert.assertEquals(7, album1Photo1.getPhotoId().length());\n\n        AlbumUni_1_M_M_M album2 = p.getAlbums().get(1);\n        Assert.assertNotNull(album2);\n        Assert.assertTrue(album2.getAlbumId().equals(\"album_1\") || album2.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album2.getAlbumName().length() == 0);\n        Assert.assertFalse(album2.getAlbumDescription().length() == 0);\n\n        List<PhotoUni_1_M_M_M> album2Photos = album2.getPhotos();\n        Assert.assertNotNull(album2Photos);\n        Assert.assertFalse(album2Photos.isEmpty());\n        Assert.assertTrue(album2Photos.size() == 4);\n\n        PhotoUni_1_M_M_M album2Photo1 = album2Photos.get(0);\n        Assert.assertNotNull(album2Photo1);\n        Assert.assertEquals(7, album2Photo1.getPhotoId().length());\n    }\n\n    private void assertModifiedPhotographer(PhotographerUni_1_M_M_M p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1, p.getPhotographerId());\n        Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n        Assert.assertNotNull(p.getAlbums());\n        Assert.assertFalse(p.getAlbums().isEmpty());\n        Assert.assertEquals(2, p.getAlbums().size());\n\n        AlbumUni_1_M_M_M album1 = p.getAlbums().get(0);\n        Assert.assertNotNull(album1);\n        Assert.assertTrue(album1.getAlbumId().equals(\"album_1\") || album1.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album1.getAlbumName().length() == 0);\n        Assert.assertFalse(album1.getAlbumDescription().length() == 0);\n\n        List<PhotoUni_1_M_M_M> album1Photos = album1.getPhotos();\n        Assert.assertNotNull(album1Photos);\n        Assert.assertFalse(album1Photos.isEmpty());\n        Assert.assertTrue(album1Photos.size() == 4);\n\n        PhotoUni_1_M_M_M album1Photo1 = album1Photos.get(0);\n        Assert.assertNotNull(album1Photo1);\n        Assert.assertEquals(7, album1Photo1.getPhotoId().length());\n\n        AlbumUni_1_M_M_M album2 = p.getAlbums().get(1);\n        Assert.assertNotNull(album2);\n        Assert.assertTrue(album2.getAlbumId().equals(\"album_1\") || album2.getAlbumId().equals(\"album_2\"));\n\n        Assert.assertFalse(album2.getAlbumName().length() == 0);\n        Assert.assertFalse(album2.getAlbumDescription().length() == 0);\n\n        List<PhotoUni_1_M_M_M> album2Photos = album2.getPhotos();\n        Assert.assertNotNull(album2Photos);\n        Assert.assertFalse(album2Photos.isEmpty());\n        Assert.assertTrue(album2Photos.size() == 4);\n\n        PhotoUni_1_M_M_M album2Photo1 = album2Photos.get(0);\n        Assert.assertNotNull(album2Photo1);\n        Assert.assertEquals(7, album2Photo1.getPhotoId().length());\n    }\n\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef2);\n        pCfDef.setKey_validation_class(\"UTF8Type\");\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        ColumnDef columnDef5 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_ID\".getBytes()), \"UTF8Type\");\n        columnDef5.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef5);\n        aCfDef.addToColumn_metadata(columnDef3);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n\n        CfDef cfDef = new CfDef();\n        cfDef.name = \"ALBUM_PHOTO\";\n        cfDef.keyspace = \"Pickr\";\n        cfDef.setComparator_type(\"UTF8Type\");\n        cfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_ID\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef6 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef4);\n        cfDef.addToColumn_metadata(columnDef6);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(cfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM_PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(cfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM_PHOTO\");\n            }\n\n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestUni_M_1_1_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_M_1_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_M_1_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerUni_M_1_1_M;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestUni_M_1_1_M extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PickrTestUni_M_1_1_M.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        executeTests();\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        List<PhotographerUni_M_1_1_M> ps = populatePhotographers();\n\n        for (PhotographerUni_M_1_1_M p : ps)\n        {\n            pickr.addPhotographer(p);\n        }\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerUni_M_1_1_M p1 = (PhotographerUni_M_1_1_M) pickr.getPhotographer(PhotographerUni_M_1_1_M.class, 1);\n        assertPhotographer(p1, 1);\n\n        PhotographerUni_M_1_1_M p2 = (PhotographerUni_M_1_1_M) pickr.getPhotographer(PhotographerUni_M_1_1_M.class, 2);\n        assertPhotographer(p2, 2);\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerUni_M_1_1_M p1 = (PhotographerUni_M_1_1_M) pickr.getPhotographer(PhotographerUni_M_1_1_M.class, 1);\n        assertPhotographer(p1, 1);\n        p1.setPhotographerName(\"Amresh2\");\n\n        pickr.mergePhotographer(p1);\n\n        PhotographerUni_M_1_1_M p1Modified = (PhotographerUni_M_1_1_M) pickr.getPhotographer(\n                PhotographerUni_M_1_1_M.class, 1);\n        assertModifiedPhotographer(p1Modified, 1);\n\n        PhotographerUni_M_1_1_M p2 = (PhotographerUni_M_1_1_M) pickr.getPhotographer(PhotographerUni_M_1_1_M.class, 2);\n        assertPhotographer(p2, 2);\n\n        p2.setPhotographerName(\"Vivek2\");\n        pickr.mergePhotographer(p2);\n\n        PhotographerUni_M_1_1_M p2Modified = (PhotographerUni_M_1_1_M) pickr.getPhotographer(\n                PhotographerUni_M_1_1_M.class, 2);\n        assertModifiedPhotographer(p2Modified, 2);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerUni_M_1_1_M.class.getSimpleName());\n\n        for (Object p : ps)\n        {\n            PhotographerUni_M_1_1_M pp = (PhotographerUni_M_1_1_M) p;\n            Assert.assertNotNull(pp);\n            assertModifiedPhotographer(pp, pp.getPhotographerId());\n        }\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerUni_M_1_1_M p1 = (PhotographerUni_M_1_1_M) pickr.getPhotographer(PhotographerUni_M_1_1_M.class, 1);\n        assertModifiedPhotographer(p1, 1);\n\n        pickr.deletePhotographer(p1);\n\n        PhotographerUni_M_1_1_M p1AfterDeletion = (PhotographerUni_M_1_1_M) pickr.getPhotographer(\n                PhotographerUni_M_1_1_M.class, 1);\n        Assert.assertNull(p1AfterDeletion);\n\n        PhotographerUni_M_1_1_M p2 = (PhotographerUni_M_1_1_M) pickr.getPhotographer(PhotographerUni_M_1_1_M.class, 2);\n        Assert.assertNotNull(p2);\n\n        pickr.deletePhotographer(p2);\n\n        PhotographerUni_M_1_1_M p2AfterDeletion = (PhotographerUni_M_1_1_M) pickr.getPhotographer(\n                PhotographerUni_M_1_1_M.class, 2);\n        Assert.assertNull(p2AfterDeletion);\n\n    }\n\n    private void assertPhotographer(PhotographerUni_M_1_1_M p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumUni_M_1_1_M album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            List<PhotoUni_M_1_1_M> albumPhotos = album.getPhotos();\n            Assert.assertNotNull(albumPhotos);\n            Assert.assertFalse(albumPhotos.isEmpty());\n            Assert.assertEquals(3, albumPhotos.size());\n\n            PhotoUni_M_1_1_M photo1 = albumPhotos.get(0);\n            PhotoUni_M_1_1_M photo2 = albumPhotos.get(1);\n            PhotoUni_M_1_1_M photo3 = albumPhotos.get(2);\n\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo3);\n            Assert.assertTrue(photo3.getPhotoId().startsWith(\"photo_\"));\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumUni_M_1_1_M album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            List<PhotoUni_M_1_1_M> albumPhotos = album.getPhotos();\n            Assert.assertNotNull(albumPhotos);\n            Assert.assertFalse(albumPhotos.isEmpty());\n            Assert.assertEquals(3, albumPhotos.size());\n\n            PhotoUni_M_1_1_M photo1 = albumPhotos.get(0);\n            PhotoUni_M_1_1_M photo2 = albumPhotos.get(1);\n            PhotoUni_M_1_1_M photo3 = albumPhotos.get(2);\n\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo3);\n            Assert.assertTrue(photo3.getPhotoId().startsWith(\"photo_\"));\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private void assertModifiedPhotographer(PhotographerUni_M_1_1_M p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumUni_M_1_1_M album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            List<PhotoUni_M_1_1_M> albumPhotos = album.getPhotos();\n            Assert.assertNotNull(albumPhotos);\n            Assert.assertFalse(albumPhotos.isEmpty());\n            Assert.assertEquals(3, albumPhotos.size());\n\n            PhotoUni_M_1_1_M photo1 = albumPhotos.get(0);\n            PhotoUni_M_1_1_M photo2 = albumPhotos.get(1);\n            PhotoUni_M_1_1_M photo3 = albumPhotos.get(2);\n\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo3);\n            Assert.assertTrue(photo3.getPhotoId().startsWith(\"photo_\"));\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumUni_M_1_1_M album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            List<PhotoUni_M_1_1_M> albumPhotos = album.getPhotos();\n            Assert.assertNotNull(albumPhotos);\n            Assert.assertFalse(albumPhotos.isEmpty());\n            Assert.assertEquals(3, albumPhotos.size());\n\n            PhotoUni_M_1_1_M photo1 = albumPhotos.get(0);\n            PhotoUni_M_1_1_M photo2 = albumPhotos.get(1);\n            PhotoUni_M_1_1_M photo3 = albumPhotos.get(2);\n\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n            Assert.assertNotNull(photo3);\n            Assert.assertTrue(photo3.getPhotoId().startsWith(\"photo_\"));\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private List<PhotographerUni_M_1_1_M> populatePhotographers()\n    {\n        List<PhotographerUni_M_1_1_M> photographers = new ArrayList<PhotographerUni_M_1_1_M>();\n\n        // Photographer 1\n        PhotographerUni_M_1_1_M p1 = new PhotographerUni_M_1_1_M();\n        p1.setPhotographerId(1);\n        p1.setPhotographerName(\"Amresh\");\n\n        AlbumUni_M_1_1_M album = new AlbumUni_M_1_1_M(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n\n        album.addPhoto(new PhotoUni_M_1_1_M(\"photo_1\", \"One beach\", \"On beach with friends\"));\n        album.addPhoto(new PhotoUni_M_1_1_M(\"photo_2\", \"In Hotel\", \"Chilling out in room\"));\n        album.addPhoto(new PhotoUni_M_1_1_M(\"photo_3\", \"At Airport\", \"So tired\"));\n\n        p1.setAlbum(album);\n\n        // Photographer 2\n        PhotographerUni_M_1_1_M p2 = new PhotographerUni_M_1_1_M();\n        p2.setPhotographerId(2);\n        p2.setPhotographerName(\"Vivek\");\n\n        p2.setAlbum(album);\n\n        photographers.add(p1);\n        photographers.add(p2);\n\n        return photographers;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.pickr.PickrBaseTest#startServer\n     * ()\n     */\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        ColumnDef pColumnDef5 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        pColumnDef5.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef2);\n        pCfDef.addToColumn_metadata(pColumnDef5);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef3);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        ColumnDef columnDef5 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef5.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n        photoLinkCfDef.addToColumn_metadata(columnDef5);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n       \n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestUni_M_1_M_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_M_1_M_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_M_1_M_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerUni_M_1_M_1;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestUni_M_1_M_1 extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PickrTestUni_M_1_M_1.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        executeTests();\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        List<PhotographerUni_M_1_M_1> ps = populatePhotographers();\n\n        for (PhotographerUni_M_1_M_1 p : ps)\n        {\n            pickr.addPhotographer(p);\n        }\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerUni_M_1_M_1 p1 = (PhotographerUni_M_1_M_1) pickr.getPhotographer(PhotographerUni_M_1_M_1.class, 1);\n        assertPhotographer(p1, 1);\n\n        PhotographerUni_M_1_M_1 p2 = (PhotographerUni_M_1_M_1) pickr.getPhotographer(PhotographerUni_M_1_M_1.class, 2);\n        assertPhotographer(p2, 2);\n\n        PhotographerUni_M_1_M_1 p3 = (PhotographerUni_M_1_M_1) pickr.getPhotographer(PhotographerUni_M_1_M_1.class, 3);\n        assertPhotographer(p3, 3);\n\n        PhotographerUni_M_1_M_1 p4 = (PhotographerUni_M_1_M_1) pickr.getPhotographer(PhotographerUni_M_1_M_1.class, 4);\n        assertPhotographer(p4, 4);\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerUni_M_1_M_1 p1 = (PhotographerUni_M_1_M_1) pickr.getPhotographer(PhotographerUni_M_1_M_1.class, 1);\n        assertPhotographer(p1, 1);\n        p1.setPhotographerName(\"Amresh2\");\n\n        pickr.mergePhotographer(p1);\n\n        PhotographerUni_M_1_M_1 p1Modified = (PhotographerUni_M_1_M_1) pickr.getPhotographer(\n                PhotographerUni_M_1_M_1.class, 1);\n        assertModifiedPhotographer(p1Modified, 1);\n\n        PhotographerUni_M_1_M_1 p2 = (PhotographerUni_M_1_M_1) pickr.getPhotographer(PhotographerUni_M_1_M_1.class, 2);\n        assertPhotographer(p2, 2);\n\n        p2.setPhotographerName(\"Vivek2\");\n        pickr.mergePhotographer(p2);\n\n        PhotographerUni_M_1_M_1 p2Modified = (PhotographerUni_M_1_M_1) pickr.getPhotographer(\n                PhotographerUni_M_1_M_1.class, 2);\n        assertModifiedPhotographer(p2Modified, 2);\n\n        PhotographerUni_M_1_M_1 p3 = (PhotographerUni_M_1_M_1) pickr.getPhotographer(PhotographerUni_M_1_M_1.class, 3);\n        assertPhotographer(p3, 3);\n        p3.setPhotographerName(\"Kuldeep2\");\n\n        pickr.mergePhotographer(p3);\n\n        PhotographerUni_M_1_M_1 p3Modified = (PhotographerUni_M_1_M_1) pickr.getPhotographer(\n                PhotographerUni_M_1_M_1.class, 3);\n        assertModifiedPhotographer(p3Modified, 3);\n\n        PhotographerUni_M_1_M_1 p4 = (PhotographerUni_M_1_M_1) pickr.getPhotographer(PhotographerUni_M_1_M_1.class, 4);\n        assertPhotographer(p4, 4);\n\n        p4.setPhotographerName(\"VivekS2\");\n        pickr.mergePhotographer(p4);\n\n        PhotographerUni_M_1_M_1 p4Modified = (PhotographerUni_M_1_M_1) pickr.getPhotographer(\n                PhotographerUni_M_1_M_1.class, 4);\n        assertModifiedPhotographer(p4Modified, 4);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerUni_M_1_M_1.class.getSimpleName());\n\n        for (Object p : ps)\n        {\n            PhotographerUni_M_1_M_1 pp = (PhotographerUni_M_1_M_1) p;\n            Assert.assertNotNull(pp);\n            assertModifiedPhotographer(pp, pp.getPhotographerId());\n        }\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerUni_M_1_M_1 p1 = (PhotographerUni_M_1_M_1) pickr.getPhotographer(PhotographerUni_M_1_M_1.class, 1);\n        assertModifiedPhotographer(p1, 1);\n\n        pickr.deletePhotographer(p1);\n\n        PhotographerUni_M_1_M_1 p1AfterDeletion = (PhotographerUni_M_1_M_1) pickr.getPhotographer(\n                PhotographerUni_M_1_M_1.class, 1);\n        Assert.assertNull(p1AfterDeletion);\n\n        PhotographerUni_M_1_M_1 p2 = (PhotographerUni_M_1_M_1) pickr.getPhotographer(PhotographerUni_M_1_M_1.class, 2);\n        Assert.assertNotNull(p2);\n\n        pickr.deletePhotographer(p2);\n\n        PhotographerUni_M_1_M_1 p2AfterDeletion = (PhotographerUni_M_1_M_1) pickr.getPhotographer(\n                PhotographerUni_M_1_M_1.class, 2);\n        Assert.assertNull(p2AfterDeletion);\n\n        PhotographerUni_M_1_M_1 p3 = (PhotographerUni_M_1_M_1) pickr.getPhotographer(PhotographerUni_M_1_M_1.class, 3);\n        Assert.assertNotNull(p3);\n\n        pickr.deletePhotographer(p3);\n\n        PhotographerUni_M_1_M_1 p3AfterDeletion = (PhotographerUni_M_1_M_1) pickr.getPhotographer(\n                PhotographerUni_M_1_M_1.class, 3);\n        Assert.assertNull(p3AfterDeletion);\n\n        PhotographerUni_M_1_M_1 p4 = (PhotographerUni_M_1_M_1) pickr.getPhotographer(PhotographerUni_M_1_M_1.class, 4);\n        Assert.assertNotNull(p4);\n\n        pickr.deletePhotographer(p4);\n\n        PhotographerUni_M_1_M_1 p4AfterDeletion = (PhotographerUni_M_1_M_1) pickr.getPhotographer(\n                PhotographerUni_M_1_M_1.class, 4);\n        Assert.assertNull(p4AfterDeletion);\n\n    }\n\n    private void assertPhotographer(PhotographerUni_M_1_M_1 p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumUni_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            PhotoUni_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumUni_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            PhotoUni_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n        }\n        else if (photographerId == 3)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(3, p.getPhotographerId());\n            Assert.assertEquals(\"Kuldeep\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumUni_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_2\"));\n            Assert.assertEquals(\"My Shimla Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Shimla with friends\", album.getAlbumDescription());\n\n            PhotoUni_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n        }\n        else if (photographerId == 4)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(4, p.getPhotographerId());\n            Assert.assertEquals(\"VivekS\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumUni_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_2\"));\n            Assert.assertEquals(\"My Shimla Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Shimla with friends\", album.getAlbumDescription());\n\n            PhotoUni_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private void assertModifiedPhotographer(PhotographerUni_M_1_M_1 p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumUni_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            PhotoUni_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumUni_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_1\"));\n            Assert.assertEquals(\"My Phuket Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Phuket with friends\", album.getAlbumDescription());\n\n            PhotoUni_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n        }\n        else if (photographerId == 3)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(3, p.getPhotographerId());\n            Assert.assertEquals(\"Kuldeep2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumUni_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_2\"));\n            Assert.assertEquals(\"My Shimla Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Shimla with friends\", album.getAlbumDescription());\n\n            PhotoUni_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n        }\n        else if (photographerId == 4)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(4, p.getPhotographerId());\n            Assert.assertEquals(\"VivekS2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbum());\n            AlbumUni_M_1_M_1 album = p.getAlbum();\n            Assert.assertNotNull(album);\n            Assert.assertTrue(album.getAlbumId().equals(\"album_2\"));\n            Assert.assertEquals(\"My Shimla Vacation\", album.getAlbumName());\n            Assert.assertEquals(\"Went Shimla with friends\", album.getAlbumDescription());\n\n            PhotoUni_M_1_M_1 albumPhoto = album.getPhoto();\n            Assert.assertNotNull(albumPhoto);\n\n            Assert.assertNotNull(albumPhoto);\n            Assert.assertTrue(albumPhoto.getPhotoId().equals(\"photo_1\"));\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private List<PhotographerUni_M_1_M_1> populatePhotographers()\n    {\n        List<PhotographerUni_M_1_M_1> photographers = new ArrayList<PhotographerUni_M_1_M_1>();\n\n        // Photographer 1\n        PhotographerUni_M_1_M_1 p1 = new PhotographerUni_M_1_M_1();\n        p1.setPhotographerId(1);\n        p1.setPhotographerName(\"Amresh\");\n\n        AlbumUni_M_1_M_1 album1 = new AlbumUni_M_1_M_1(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n\n        AlbumUni_M_1_M_1 album2 = new AlbumUni_M_1_M_1(\"album_2\", \"My Shimla Vacation\", \"Went Shimla with friends\");\n\n        PhotoUni_M_1_M_1 photo = new PhotoUni_M_1_M_1(\"photo_1\", \"One beach\", \"On beach with friends\");\n        album1.setPhoto(photo);\n        album2.setPhoto(photo);\n\n        p1.setAlbum(album1);\n\n        // Photographer 2\n        PhotographerUni_M_1_M_1 p2 = new PhotographerUni_M_1_M_1();\n        p2.setPhotographerId(2);\n        p2.setPhotographerName(\"Vivek\");\n\n        p2.setAlbum(album1);\n\n        // Photographer 3\n        PhotographerUni_M_1_M_1 p3 = new PhotographerUni_M_1_M_1();\n        p3.setPhotographerId(3);\n        p3.setPhotographerName(\"Kuldeep\");\n\n        p3.setAlbum(album2);\n\n        // Photographer 4\n        PhotographerUni_M_1_M_1 p4 = new PhotographerUni_M_1_M_1();\n        p4.setPhotographerId(4);\n        p4.setPhotographerName(\"VivekS\");\n\n        p4.setAlbum(album2);\n\n        photographers.add(p1);\n        photographers.add(p2);\n        photographers.add(p3);\n        photographers.add(p4);\n\n        return photographers;\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.pickr.PickrBaseTest#startServer\n     * ()\n     */\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        ColumnDef pColumnDef5 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        pColumnDef5.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef2);\n        pCfDef.addToColumn_metadata(pColumnDef5);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        ColumnDef columnDef5 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_ID\".getBytes()), \"UTF8Type\");\n        columnDef5.index_type = IndexType.KEYS;\n\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef3);\n        aCfDef.addToColumn_metadata(columnDef5);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n       \n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestUni_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_M_M_1_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_M_M_1_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerUni_M_M_1_1;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestUni_M_M_1_1 extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PickrTestUni_M_M_1_1.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    /**\n     * Test.\n     */\n    @Test\n    public void test()\n    {\n        executeTests();\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        List<PhotographerUni_M_M_1_1> ps = populatePhotographers();\n\n        for (PhotographerUni_M_M_1_1 p : ps)\n        {\n            pickr.addPhotographer(p);\n        }\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerUni_M_M_1_1 p1 = (PhotographerUni_M_M_1_1) pickr.getPhotographer(PhotographerUni_M_M_1_1.class, 1);\n        assertPhotographer(p1, 1);\n\n        PhotographerUni_M_M_1_1 p2 = (PhotographerUni_M_M_1_1) pickr.getPhotographer(PhotographerUni_M_M_1_1.class, 2);\n        assertPhotographer(p2, 2);\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerUni_M_M_1_1 p1 = (PhotographerUni_M_M_1_1) pickr.getPhotographer(PhotographerUni_M_M_1_1.class, 1);\n        assertPhotographer(p1, 1);\n        p1.setPhotographerName(\"Amresh2\");\n\n        pickr.mergePhotographer(p1);\n\n        PhotographerUni_M_M_1_1 p1Modified = (PhotographerUni_M_M_1_1) pickr.getPhotographer(\n                PhotographerUni_M_M_1_1.class, 1);\n        assertModifiedPhotographer(p1Modified, 1);\n\n        PhotographerUni_M_M_1_1 p2 = (PhotographerUni_M_M_1_1) pickr.getPhotographer(PhotographerUni_M_M_1_1.class, 2);\n        assertPhotographer(p2, 2);\n        p2.setPhotographerName(\"Vivek2\");\n\n        pickr.mergePhotographer(p2);\n\n        PhotographerUni_M_M_1_1 p2Modified = (PhotographerUni_M_M_1_1) pickr.getPhotographer(\n                PhotographerUni_M_M_1_1.class, 2);\n        assertModifiedPhotographer(p2Modified, 2);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerUni_M_M_1_1.class.getSimpleName());\n\n        for (Object p : ps)\n        {\n            PhotographerUni_M_M_1_1 pp = (PhotographerUni_M_M_1_1) p;\n            assertModifiedPhotographer(pp, pp.getPhotographerId());\n        }\n\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerUni_M_M_1_1 p1 = (PhotographerUni_M_M_1_1) pickr.getPhotographer(PhotographerUni_M_M_1_1.class, 1);\n        assertModifiedPhotographer(p1, 1);\n        pickr.deletePhotographer(p1);\n\n        PhotographerUni_M_M_1_1 p1AfterDeletion = (PhotographerUni_M_M_1_1) pickr.getPhotographer(\n                PhotographerUni_M_M_1_1.class, 1);\n        Assert.assertNull(p1AfterDeletion);\n\n        PhotographerUni_M_M_1_1 p2 = (PhotographerUni_M_M_1_1) pickr.getPhotographer(PhotographerUni_M_M_1_1.class, 2);\n        Assert.assertNotNull(p2);\n        pickr.deletePhotographer(p2);\n\n        PhotographerUni_M_M_1_1 p2AfterDeletion = (PhotographerUni_M_M_1_1) pickr.getPhotographer(\n                PhotographerUni_M_M_1_1.class, 2);\n        Assert.assertNull(p2AfterDeletion);\n\n    }\n\n    private void assertPhotographer(PhotographerUni_M_M_1_1 p, int photographerId)\n    {\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumUni_M_M_1_1 album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n            PhotoUni_M_M_1_1 photo1 = album1.getPhoto();\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n\n            AlbumUni_M_M_1_1 album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n            PhotoUni_M_M_1_1 photo2 = album2.getPhoto();\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumUni_M_M_1_1 album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n            PhotoUni_M_M_1_1 photo1 = album1.getPhoto();\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n\n            AlbumUni_M_M_1_1 album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n            PhotoUni_M_M_1_1 photo2 = album2.getPhoto();\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private void assertModifiedPhotographer(PhotographerUni_M_M_1_1 p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumUni_M_M_1_1 album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n            PhotoUni_M_M_1_1 photo1 = album1.getPhoto();\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n\n            AlbumUni_M_M_1_1 album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n            PhotoUni_M_M_1_1 photo2 = album2.getPhoto();\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumUni_M_M_1_1 album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n            PhotoUni_M_M_1_1 photo1 = album1.getPhoto();\n            Assert.assertNotNull(photo1);\n            Assert.assertTrue(photo1.getPhotoId().startsWith(\"photo_\"));\n\n            AlbumUni_M_M_1_1 album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n            PhotoUni_M_M_1_1 photo2 = album2.getPhoto();\n            Assert.assertNotNull(photo2);\n            Assert.assertTrue(photo2.getPhotoId().startsWith(\"photo_\"));\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private List<PhotographerUni_M_M_1_1> populatePhotographers()\n    {\n        List<PhotographerUni_M_M_1_1> photographers = new ArrayList<PhotographerUni_M_M_1_1>();\n\n        // Photographer 1\n        PhotographerUni_M_M_1_1 p1 = new PhotographerUni_M_M_1_1();\n        p1.setPhotographerId(1);\n        p1.setPhotographerName(\"Amresh\");\n\n        // Photographer 2\n        PhotographerUni_M_M_1_1 p2 = new PhotographerUni_M_M_1_1();\n        p2.setPhotographerId(2);\n        p2.setPhotographerName(\"Vivek\");\n\n        AlbumUni_M_M_1_1 album1 = new AlbumUni_M_M_1_1(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n        AlbumUni_M_M_1_1 album2 = new AlbumUni_M_M_1_1(\"album_2\", \"My Shimla Vacation\", \"Went Shimla with friends\");\n        AlbumUni_M_M_1_1 album3 = new AlbumUni_M_M_1_1(\"album_3\", \"My Zurik Vacation\", \"Went Zurik with friends\");\n\n        album1.setPhoto(new PhotoUni_M_M_1_1(\"photo_1\", \"One beach\", \"On beach with friends\"));\n        album2.setPhoto(new PhotoUni_M_M_1_1(\"photo_2\", \"In Hotel\", \"Chilling out in room\"));\n        album3.setPhoto(new PhotoUni_M_M_1_1(\"photo_3\", \"At Airport\", \"So tired\"));\n\n        p1.addAlbum(album1);\n        p1.addAlbum(album2);\n\n        p2.addAlbum(album2);\n        p2.addAlbum(album3);\n\n        photographers.add(p1);\n        photographers.add(p2);\n\n        return photographers;\n    }\n\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef2);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        ColumnDef columnDef5 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_ID\".getBytes()), \"UTF8Type\");\n        columnDef5.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef5);\n        aCfDef.addToColumn_metadata(columnDef3);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n\n        CfDef cfDef = new CfDef();\n        cfDef.name = \"PHOTOGRAPHER_ALBUM\";\n        cfDef.keyspace = \"Pickr\";\n        cfDef.setComparator_type(\"UTF8Type\");\n        cfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_ID\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef6 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef4);\n        cfDef.addToColumn_metadata(columnDef6);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(cfDef);\n        cfDefs.add(photoLinkCfDef);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM_PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(cfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM_PHOTO\");\n            }\n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/PickrTestUni_M_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_M_M_M_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_M_M_M_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerUni_M_M_M_M;\n\n/**\n * @author amresh.singh\n * \n */\npublic class PickrTestUni_M_M_M_M extends PickrBaseTest\n{\n    private static Logger log = LoggerFactory.getLogger(PickrTestUni_M_M_M_M.class);\n\n    @Before\n    public void setUp() throws Exception\n    {\n        log.info(\"Executing PICKR Test: \" + this.getClass().getSimpleName() + \"\\n======\"\n                + \"==========================================================\");\n        super.setUp();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        super.tearDown();\n    }\n\n    @Test\n    public void test()\n    {\n        executeTests();\n    }\n\n    @Override\n    public void addPhotographer()\n    {\n        List<PhotographerUni_M_M_M_M> ps = populatePhotographers();\n\n        for (PhotographerUni_M_M_M_M p : ps)\n        {\n            pickr.addPhotographer(p);\n        }\n    }\n\n    @Override\n    protected void getPhotographer()\n    {\n        PhotographerUni_M_M_M_M p1 = (PhotographerUni_M_M_M_M) pickr.getPhotographer(PhotographerUni_M_M_M_M.class, 1);\n        assertPhotographer(p1, 1);\n\n        PhotographerUni_M_M_M_M p2 = (PhotographerUni_M_M_M_M) pickr.getPhotographer(PhotographerUni_M_M_M_M.class, 2);\n        assertPhotographer(p2, 2);\n    }\n\n    @Override\n    protected void updatePhotographer()\n    {\n        PhotographerUni_M_M_M_M p1 = (PhotographerUni_M_M_M_M) pickr.getPhotographer(PhotographerUni_M_M_M_M.class, 1);\n        assertPhotographer(p1, 1);\n        p1.setPhotographerName(\"Amresh2\");\n\n        pickr.mergePhotographer(p1);\n\n        PhotographerUni_M_M_M_M p1Modified = (PhotographerUni_M_M_M_M) pickr.getPhotographer(\n                PhotographerUni_M_M_M_M.class, 1);\n\n        assertModifiedPhotographer(p1Modified, 1);\n\n        PhotographerUni_M_M_M_M p2 = (PhotographerUni_M_M_M_M) pickr.getPhotographer(PhotographerUni_M_M_M_M.class, 2);\n        assertPhotographer(p2, 2);\n        p2.setPhotographerName(\"Vivek2\");\n\n        pickr.mergePhotographer(p2);\n\n        PhotographerUni_M_M_M_M p2Modified = (PhotographerUni_M_M_M_M) pickr.getPhotographer(\n                PhotographerUni_M_M_M_M.class, 2);\n        assertModifiedPhotographer(p2Modified, 2);\n    }\n\n    @Override\n    protected void getAllPhotographers()\n    {\n        List<Object> ps = pickr.getAllPhotographers(PhotographerUni_M_M_M_M.class.getSimpleName());\n\n        for (Object p : ps)\n        {\n            PhotographerUni_M_M_M_M pp = (PhotographerUni_M_M_M_M) p;\n            Assert.assertNotNull(pp);\n            assertModifiedPhotographer(pp, pp.getPhotographerId());\n        }\n    }\n\n    @Override\n    protected void deletePhotographer()\n    {\n        PhotographerUni_M_M_M_M p1 = (PhotographerUni_M_M_M_M) pickr.getPhotographer(PhotographerUni_M_M_M_M.class, 1);\n        assertModifiedPhotographer(p1, 1);\n        pickr.deletePhotographer(p1);\n\n        PhotographerUni_M_M_M_M p1AfterDeletion = (PhotographerUni_M_M_M_M) pickr.getPhotographer(\n                PhotographerUni_M_M_M_M.class, 1);\n        Assert.assertNull(p1AfterDeletion);\n\n        PhotographerUni_M_M_M_M p2 = (PhotographerUni_M_M_M_M) pickr.getPhotographer(PhotographerUni_M_M_M_M.class, 2);\n        Assert.assertNotNull(p2);\n        pickr.deletePhotographer(p2);\n\n        PhotographerUni_M_M_M_M p2AfterDeletion = (PhotographerUni_M_M_M_M) pickr.getPhotographer(\n                PhotographerUni_M_M_M_M.class, 2);\n        Assert.assertNull(p2AfterDeletion);\n\n    }\n\n    private void assertPhotographer(PhotographerUni_M_M_M_M p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumUni_M_M_M_M album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n\n            Assert.assertNotNull(album1.getPhotos());\n            Assert.assertFalse(album1.getPhotos().isEmpty());\n            Assert.assertEquals(2, album1.getPhotos().size());\n\n            AlbumUni_M_M_M_M album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n            Assert.assertNotNull(album2.getPhotos());\n            Assert.assertFalse(album2.getPhotos().isEmpty());\n            Assert.assertEquals(2, album2.getPhotos().size());\n\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumUni_M_M_M_M album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n\n            Assert.assertNotNull(album1.getPhotos());\n            Assert.assertFalse(album1.getPhotos().isEmpty());\n            Assert.assertEquals(2, album1.getPhotos().size());\n\n            AlbumUni_M_M_M_M album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n            Assert.assertNotNull(album2.getPhotos());\n            Assert.assertFalse(album2.getPhotos().isEmpty());\n            Assert.assertEquals(2, album2.getPhotos().size());\n\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private void assertModifiedPhotographer(PhotographerUni_M_M_M_M p, int photographerId)\n    {\n\n        if (photographerId == 1)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(1, p.getPhotographerId());\n            Assert.assertEquals(\"Amresh2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumUni_M_M_M_M album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n\n            Assert.assertNotNull(album1.getPhotos());\n            Assert.assertFalse(album1.getPhotos().isEmpty());\n            Assert.assertEquals(2, album1.getPhotos().size());\n\n            AlbumUni_M_M_M_M album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n            Assert.assertNotNull(album2.getPhotos());\n            Assert.assertFalse(album2.getPhotos().isEmpty());\n            Assert.assertEquals(2, album2.getPhotos().size());\n\n        }\n        else if (photographerId == 2)\n        {\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getPhotographerId());\n            Assert.assertEquals(\"Vivek2\", p.getPhotographerName());\n\n            Assert.assertNotNull(p.getAlbums());\n            Assert.assertFalse(p.getAlbums().isEmpty());\n            Assert.assertEquals(2, p.getAlbums().size());\n\n            AlbumUni_M_M_M_M album1 = p.getAlbums().get(0);\n            Assert.assertNotNull(album1);\n            Assert.assertTrue(album1.getAlbumId().startsWith(\"album_\"));\n\n            Assert.assertNotNull(album1.getPhotos());\n            Assert.assertFalse(album1.getPhotos().isEmpty());\n            Assert.assertEquals(2, album1.getPhotos().size());\n\n            AlbumUni_M_M_M_M album2 = p.getAlbums().get(1);\n            Assert.assertNotNull(album2);\n            Assert.assertTrue(album2.getAlbumId().startsWith(\"album_\"));\n            Assert.assertNotNull(album2.getPhotos());\n            Assert.assertFalse(album2.getPhotos().isEmpty());\n            Assert.assertEquals(2, album2.getPhotos().size());\n\n        }\n        else\n        {\n            Assert.fail(\"Invalid Photographer ID: \" + photographerId);\n        }\n\n    }\n\n    private List<PhotographerUni_M_M_M_M> populatePhotographers()\n    {\n        List<PhotographerUni_M_M_M_M> photographers = new ArrayList<PhotographerUni_M_M_M_M>();\n\n        // Photographer 1\n        PhotographerUni_M_M_M_M p1 = new PhotographerUni_M_M_M_M();\n        p1.setPhotographerId(1);\n        p1.setPhotographerName(\"Amresh\");\n\n        // Photographer 2\n        PhotographerUni_M_M_M_M p2 = new PhotographerUni_M_M_M_M();\n        p2.setPhotographerId(2);\n        p2.setPhotographerName(\"Vivek\");\n\n        AlbumUni_M_M_M_M album1 = new AlbumUni_M_M_M_M(\"album_1\", \"My Phuket Vacation\", \"Went Phuket with friends\");\n        AlbumUni_M_M_M_M album2 = new AlbumUni_M_M_M_M(\"album_2\", \"My Shimla Vacation\", \"Went Shimla with friends\");\n        AlbumUni_M_M_M_M album3 = new AlbumUni_M_M_M_M(\"album_3\", \"My Zurik Vacation\", \"Went Zurik with friends\");\n\n        PhotoUni_M_M_M_M photo1 = new PhotoUni_M_M_M_M(\"photo_1\", \"One beach\", \"On beach with friends\");\n        PhotoUni_M_M_M_M photo2 = new PhotoUni_M_M_M_M(\"photo_2\", \"In Hotel\", \"Chilling out in room\");\n        PhotoUni_M_M_M_M photo3 = new PhotoUni_M_M_M_M(\"photo_3\", \"At Airport\", \"So tired\");\n        PhotoUni_M_M_M_M photo4 = new PhotoUni_M_M_M_M(\"photo_4\", \"In Space\", \"I am flying\");\n\n        album1.addPhoto(photo1);\n        album1.addPhoto(photo2);\n        album2.addPhoto(photo2);\n        album2.addPhoto(photo3);\n        album3.addPhoto(photo3);\n        album3.addPhoto(photo4);\n\n        p1.addAlbum(album1);\n        p1.addAlbum(album2);\n\n        p2.addAlbum(album2);\n        p2.addAlbum(album3);\n\n        photographers.add(p1);\n        photographers.add(p2);\n\n        return photographers;\n    }\n\n    @Override\n    protected void createCassandraSchema() throws IOException, TException, InvalidRequestException,\n            UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        /**\n         * schema generation for cassandra.\n         * */\n\n        KsDef ksDef = null;\n\n        CfDef pCfDef = new CfDef();\n        pCfDef.name = \"PHOTOGRAPHER\";\n        pCfDef.keyspace = \"Pickr\";\n        pCfDef.setComparator_type(\"UTF8Type\");\n        pCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef pColumnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n        pColumnDef2.index_type = IndexType.KEYS;\n        pCfDef.addToColumn_metadata(pColumnDef2);\n\n        CfDef aCfDef = new CfDef();\n        aCfDef.name = \"ALBUM\";\n        aCfDef.keyspace = \"Pickr\";\n        aCfDef.setComparator_type(\"UTF8Type\");\n        aCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n        columnDef3.index_type = IndexType.KEYS;\n        aCfDef.addToColumn_metadata(columnDef);\n        aCfDef.addToColumn_metadata(columnDef3);\n\n        CfDef photoLinkCfDef = new CfDef();\n        photoLinkCfDef.name = \"PHOTO\";\n        photoLinkCfDef.keyspace = \"Pickr\";\n        photoLinkCfDef.setComparator_type(\"UTF8Type\");\n        photoLinkCfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_CAPTION\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTO_DESC\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        photoLinkCfDef.addToColumn_metadata(columnDef1);\n        photoLinkCfDef.addToColumn_metadata(columnDef2);\n\n        CfDef cfDef = new CfDef();\n        cfDef.name = \"PHOTOGRAPHER_ALBUM\";\n        cfDef.keyspace = \"Pickr\";\n        cfDef.setComparator_type(\"UTF8Type\");\n        cfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_ID\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef columnDef6 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        cfDef.addToColumn_metadata(columnDef4);\n        cfDef.addToColumn_metadata(columnDef6);\n\n        CfDef album_photo = new CfDef();\n        album_photo.name = \"ALBUM_PHOTO\";\n        album_photo.keyspace = \"Pickr\";\n        album_photo.setComparator_type(\"UTF8Type\");\n        album_photo.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef photo_id = new ColumnDef(ByteBuffer.wrap(\"PHOTO_ID\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        ColumnDef album_id = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        album_photo.addToColumn_metadata(photo_id);\n        album_photo.addToColumn_metadata(album_id);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(pCfDef);\n        cfDefs.add(aCfDef);\n        cfDefs.add(cfDef);\n        cfDefs.add(photoLinkCfDef);\n        cfDefs.add(album_photo);\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"Pickr\");\n            CassandraCli.client.set_keyspace(\"Pickr\");\n            if (!CassandraCli.columnFamilyExist(\"PHOTOGRAPHER\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(pCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTOGRAPHER\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(photoLinkCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(aCfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"PHOTO\");\n            }\n            if (!CassandraCli.columnFamilyExist(\"ALBUM_PHOTO\", \"Pickr\")) {\n                CassandraCli.client.system_add_column_family(cfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"Pickr\", \"ALBUM_PHOTO\");\n            }\n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        catch (InvalidRequestException e)\n        {\n            log.error(e.getMessage());\n        }\n        catch (TException e)\n        {\n            log.error(e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumBi_1_1_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_1_1_1_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_1_1_1_1;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumBi_1_1_1_1\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTO_ID\")\n    private PhotoBi_1_1_1_1 photo;\n\n    @OneToOne(mappedBy = \"album\")\n    private PhotographerBi_1_1_1_1 photographer;\n\n    public AlbumBi_1_1_1_1()\n    {\n\n    }\n\n    public AlbumBi_1_1_1_1(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    /**\n     * @return the albumId\n     */\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    /**\n     * @param albumId\n     *            the albumId to set\n     */\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photo\n     */\n    public PhotoBi_1_1_1_1 getPhoto()\n    {\n        return photo;\n    }\n\n    /**\n     * @param photo\n     *            the photo to set\n     */\n    public void setPhoto(PhotoBi_1_1_1_1 photo)\n    {\n        this.photo = photo;\n    }\n\n    /**\n     * @return the photographer\n     */\n    public PhotographerBi_1_1_1_1 getPhotographer()\n    {\n        return photographer;\n    }\n\n    /**\n     * @param photographer\n     *            the photographer to set\n     */\n    public void setPhotographer(PhotographerBi_1_1_1_1 photographer)\n    {\n        this.photographer = photographer;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumBi_1_1_1_1_PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_1_1_1_1_PK;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_1_1_1_1_PK;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumBi_1_1_1_1_PK\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @PrimaryKeyJoinColumn\n    private PhotoBi_1_1_1_1_PK photo;\n\n    @OneToOne(mappedBy = \"album\")\n    private PhotographerBi_1_1_1_1_PK photographer;\n\n    public AlbumBi_1_1_1_1_PK()\n    {\n\n    }\n\n    public AlbumBi_1_1_1_1_PK(int photographerId, String albumId, String name, String description)\n    {\n        this.photographerId = photographerId;\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    /**\n     * @return the albumId\n     */\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    /**\n     * @param albumId\n     *            the albumId to set\n     */\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photo\n     */\n    public PhotoBi_1_1_1_1_PK getPhoto()\n    {\n        return photo;\n    }\n\n    /**\n     * @param photo\n     *            the photo to set\n     */\n    public void setPhoto(PhotoBi_1_1_1_1_PK photo)\n    {\n        this.photo = photo;\n    }\n\n    /**\n     * @return the photographer\n     */\n    public PhotographerBi_1_1_1_1_PK getPhotographer()\n    {\n        return photographer;\n    }\n\n    /**\n     * @param photographer\n     *            the photographer to set\n     */\n    public void setPhotographer(PhotographerBi_1_1_1_1_PK photographer)\n    {\n        this.photographer = photographer;\n    }\n\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumBi_1_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_1_1_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_1_1_1_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumBi_1_1_1_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"album\")\n    private List<PhotoBi_1_1_1_M> photos;\n\n    @OneToOne(mappedBy = \"album\")\n    private PhotographerBi_1_1_1_M photographer;\n\n    public AlbumBi_1_1_1_M()\n    {\n\n    }\n\n    public AlbumBi_1_1_1_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoBi_1_1_1_M> getPhotos()\n    {\n        if (photos == null)\n        {\n            photos = new ArrayList<PhotoBi_1_1_1_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoBi_1_1_1_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoBi_1_1_1_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n    /**\n     * @return the photographer\n     */\n    public PhotographerBi_1_1_1_M getPhotographer()\n    {\n        return photographer;\n    }\n\n    /**\n     * @param photographer\n     *            the photographer to set\n     */\n    public void setPhotographer(PhotographerBi_1_1_1_M photographer)\n    {\n        this.photographer = photographer;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumBi_1_M_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_1_M_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_1_M_1_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumBi_1_M_1_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"album\")\n    private List<PhotoBi_1_M_1_M> photos;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTOGRAPHER_ID\")\n    private PhotographerBi_1_M_1_M photographer;\n\n    public AlbumBi_1_M_1_M()\n    {\n\n    }\n\n    public AlbumBi_1_M_1_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoBi_1_M_1_M> getPhotos()\n    {\n        if (photos == null)\n        {\n            photos = new ArrayList<PhotoBi_1_M_1_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoBi_1_M_1_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoBi_1_M_1_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n    /**\n     * @return the photographer\n     */\n    public PhotographerBi_1_M_1_M getPhotographer()\n    {\n        return photographer;\n    }\n\n    /**\n     * @param photographer\n     *            the photographer to set\n     */\n    public void setPhotographer(PhotographerBi_1_M_1_M photographer)\n    {\n        this.photographer = photographer;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumBi_1_M_M_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_1_M_M_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_1_M_M_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumBi_1_M_M_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"ALBUM_PHOTO\", joinColumns = { @JoinColumn(name = \"ALBUM_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"PHOTO_ID\") })\n    private List<PhotoBi_1_M_M_M> photos;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTOGRAPHER_ID\")\n    private PhotographerBi_1_M_M_M photographer;\n\n    public AlbumBi_1_M_M_M()\n    {\n\n    }\n\n    public AlbumBi_1_M_M_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoBi_1_M_M_M> getPhotos()\n    {\n        if (this.photos == null || this.photos.isEmpty())\n        {\n            this.photos = new ArrayList<PhotoBi_1_M_M_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoBi_1_M_M_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoBi_1_M_M_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n    /**\n     * @return the photographer\n     */\n    public PhotographerBi_1_M_M_M getPhotographer()\n    {\n        return photographer;\n    }\n\n    /**\n     * @param photographer\n     *            the photographer to set\n     */\n    public void setPhotographer(PhotographerBi_1_M_M_M photographer)\n    {\n        this.photographer = photographer;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumBi_M_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_M_1_1_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_M_1_1_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumBi_M_1_1_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"album\")\n    private List<PhotoBi_M_1_1_M> photos;\n\n    @OneToMany(mappedBy = \"album\", fetch = FetchType.LAZY)\n    private List<PhotographerBi_M_1_1_M> photographers;\n\n    public AlbumBi_M_1_1_M()\n    {\n\n    }\n\n    public AlbumBi_M_1_1_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoBi_M_1_1_M> getPhotos()\n    {\n        if (photos == null)\n        {\n            photos = new ArrayList<PhotoBi_M_1_1_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoBi_M_1_1_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoBi_M_1_1_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n    /**\n     * @return the photographers\n     */\n    public List<PhotographerBi_M_1_1_M> getPhotographers()\n    {\n        return photographers;\n    }\n\n    /**\n     * @param photographers\n     *            the photographers to set\n     */\n    public void setPhotographers(List<PhotographerBi_M_1_1_M> photographers)\n    {\n        this.photographers = photographers;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumBi_M_1_M_1.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_M_1_M_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_M_1_M_1;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumBi_M_1_M_1\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTO_ID\")\n    private PhotoBi_M_1_M_1 photo;\n\n    @OneToMany(mappedBy = \"album\", fetch = FetchType.LAZY)\n    private List<PhotographerBi_M_1_M_1> photographers;\n\n    public AlbumBi_M_1_M_1()\n    {\n\n    }\n\n    public AlbumBi_M_1_M_1(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public PhotoBi_M_1_M_1 getPhoto()\n    {\n        return photo;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhoto(PhotoBi_M_1_M_1 photo)\n    {\n        this.photo = photo;\n    }\n\n    public List<PhotographerBi_M_1_M_1> getPhotographers()\n    {\n        return photographers;\n    }\n\n    public void setPhotographers(List<PhotographerBi_M_1_M_1> photographers)\n    {\n        this.photographers = photographers;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumBi_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_M_M_1_1;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_M_M_1_1;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumBi_M_M_1_1\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTO_ID\")\n    private PhotoBi_M_M_1_1 photo;\n\n    @ManyToMany(mappedBy = \"albums\", fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    private List<PhotographerBi_M_M_1_1> photographers;\n\n    public AlbumBi_M_M_1_1()\n    {\n\n    }\n\n    public AlbumBi_M_M_1_1(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    /**\n     * @return the albumId\n     */\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    /**\n     * @param albumId\n     *            the albumId to set\n     */\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photo\n     */\n    public PhotoBi_M_M_1_1 getPhoto()\n    {\n        return photo;\n    }\n\n    /**\n     * @param photo\n     *            the photo to set\n     */\n    public void setPhoto(PhotoBi_M_M_1_1 photo)\n    {\n        this.photo = photo;\n    }\n\n    /**\n     * @return the photographers\n     */\n    public List<PhotographerBi_M_M_1_1> getPhotographers()\n    {\n        return photographers;\n    }\n\n    /**\n     * @param photographers\n     *            the photographers to set\n     */\n    public void setPhotographers(List<PhotographerBi_M_M_1_1> photographers)\n    {\n        this.photographers = photographers;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumBi_M_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoBi_M_M_M_M;\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer.PhotographerBi_M_M_M_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumBi_M_M_M_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    @JoinTable(name = \"ALBUM_PHOTO\", joinColumns = { @JoinColumn(name = \"ALBUM_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"PHOTO_ID\") })\n    private List<PhotoBi_M_M_M_M> photos;\n\n    @ManyToMany(mappedBy = \"albums\", fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    private List<PhotographerBi_M_M_M_M> photographers;\n\n    public AlbumBi_M_M_M_M()\n    {\n\n    }\n\n    public AlbumBi_M_M_M_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoBi_M_M_M_M> getPhotos()\n    {\n        if (this.photos == null || this.photos.isEmpty())\n        {\n            this.photos = new ArrayList<PhotoBi_M_M_M_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoBi_M_M_M_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoBi_M_M_M_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n    /**\n     * @return the photographers\n     */\n    public List<PhotographerBi_M_M_M_M> getPhotographers()\n    {\n        return photographers;\n    }\n\n    /**\n     * @param photographers\n     *            the photographers to set\n     */\n    public void setPhotographers(List<PhotographerBi_M_M_M_M> photographers)\n    {\n        this.photographers = photographers;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumUni_1_1_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_1_1_1_1;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumUni_1_1_1_1\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTO_ID\")\n    private PhotoUni_1_1_1_1 photo;\n\n    public AlbumUni_1_1_1_1()\n    {\n\n    }\n\n    public AlbumUni_1_1_1_1(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    /**\n     * @return the albumId\n     */\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    /**\n     * @param albumId\n     *            the albumId to set\n     */\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photo\n     */\n    public PhotoUni_1_1_1_1 getPhoto()\n    {\n        return photo;\n    }\n\n    /**\n     * @param photo\n     *            the photo to set\n     */\n    public void setPhoto(PhotoUni_1_1_1_1 photo)\n    {\n        this.photo = photo;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumUni_1_1_1_1_PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_1_1_1_1_PK;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumUni_1_1_1_1_PK\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @PrimaryKeyJoinColumn\n    private PhotoUni_1_1_1_1_PK photo;\n\n    public AlbumUni_1_1_1_1_PK()\n    {\n\n    }\n\n    public AlbumUni_1_1_1_1_PK(int photographerId, String albumId, String name, String description)\n    {\n        this.photographerId = photographerId;\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    /**\n     * @return the albumId\n     */\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    /**\n     * @param albumId\n     *            the albumId to set\n     */\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photo\n     */\n    public PhotoUni_1_1_1_1_PK getPhoto()\n    {\n        return photo;\n    }\n\n    /**\n     * @param photo\n     *            the photo to set\n     */\n    public void setPhoto(PhotoUni_1_1_1_1_PK photo)\n    {\n        this.photo = photo;\n    }\n\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumUni_1_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_1_1_1_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumUni_1_1_1_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private List<PhotoUni_1_1_1_M> photos;\n\n    public AlbumUni_1_1_1_M()\n    {\n\n    }\n\n    public AlbumUni_1_1_1_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoUni_1_1_1_M> getPhotos()\n    {\n        if (photos == null)\n        {\n            photos = new ArrayList<PhotoUni_1_1_1_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoUni_1_1_1_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoUni_1_1_1_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumUni_1_M_1_M.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.Table;\r\n\r\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_1_M_1_M;\r\n\r\n/**\r\n * Entity Class for album\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\r\npublic class AlbumUni_1_M_1_M\r\n{\r\n    @Id\r\n    @Column(name = \"ALBUM_ID\")\r\n    private String albumId;\r\n\r\n    @Column(name = \"ALBUM_NAME\")\r\n    private String albumName;\r\n\r\n    @Column(name = \"ALBUM_DESC\")\r\n    private String albumDescription;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\r\n    @JoinColumn(name = \"ALBUM_ID\")\r\n    private List<PhotoUni_1_M_1_M> photos;\r\n\r\n    public AlbumUni_1_M_1_M()\r\n    {\r\n\r\n    }\r\n\r\n    public AlbumUni_1_M_1_M(String albumId, String name, String description)\r\n    {\r\n        this.albumId = albumId;\r\n        this.albumName = name;\r\n        this.albumDescription = description;\r\n    }\r\n\r\n    public String getAlbumId()\r\n    {\r\n        return albumId;\r\n    }\r\n\r\n    public void setAlbumId(String albumId)\r\n    {\r\n        this.albumId = albumId;\r\n    }\r\n\r\n    /**\r\n     * @return the albumName\r\n     */\r\n    public String getAlbumName()\r\n    {\r\n        return albumName;\r\n    }\r\n\r\n    /**\r\n     * @param albumName\r\n     *            the albumName to set\r\n     */\r\n    public void setAlbumName(String albumName)\r\n    {\r\n        this.albumName = albumName;\r\n    }\r\n\r\n    /**\r\n     * @return the albumDescription\r\n     */\r\n    public String getAlbumDescription()\r\n    {\r\n        return albumDescription;\r\n    }\r\n\r\n    /**\r\n     * @param albumDescription\r\n     *            the albumDescription to set\r\n     */\r\n    public void setAlbumDescription(String albumDescription)\r\n    {\r\n        this.albumDescription = albumDescription;\r\n    }\r\n\r\n    /**\r\n     * @return the photos\r\n     */\r\n    public List<PhotoUni_1_M_1_M> getPhotos()\r\n    {\r\n        if (photos == null)\r\n        {\r\n            photos = new ArrayList<PhotoUni_1_M_1_M>();\r\n        }\r\n        return photos;\r\n    }\r\n\r\n    /**\r\n     * @param photos\r\n     *            the photos to set\r\n     */\r\n    public void setPhotos(List<PhotoUni_1_M_1_M> photos)\r\n    {\r\n        this.photos = photos;\r\n    }\r\n\r\n    public void addPhoto(PhotoUni_1_M_1_M photo)\r\n    {\r\n        getPhotos().add(photo);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumUni_1_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_1_M_M_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumUni_1_M_M_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"ALBUM_PHOTO\", joinColumns = { @JoinColumn(name = \"ALBUM_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"PHOTO_ID\") })\n    private List<PhotoUni_1_M_M_M> photos;\n\n    public AlbumUni_1_M_M_M()\n    {\n\n    }\n\n    public AlbumUni_1_M_M_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoUni_1_M_M_M> getPhotos()\n    {\n        if (this.photos == null || this.photos.isEmpty())\n        {\n            this.photos = new ArrayList<PhotoUni_1_M_M_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoUni_1_M_M_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoUni_1_M_M_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumUni_M_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_M_1_1_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumUni_M_1_1_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private List<PhotoUni_M_1_1_M> photos;\n\n    public AlbumUni_M_1_1_M()\n    {\n\n    }\n\n    public AlbumUni_M_1_1_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoUni_M_1_1_M> getPhotos()\n    {\n        if (photos == null)\n        {\n            photos = new ArrayList<PhotoUni_M_1_1_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoUni_M_1_1_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoUni_M_1_1_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumUni_M_1_M_1.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_M_1_M_1;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumUni_M_1_M_1\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTO_ID\")\n    private PhotoUni_M_1_M_1 photo;\n\n    public AlbumUni_M_1_M_1()\n    {\n\n    }\n\n    public AlbumUni_M_1_M_1(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public PhotoUni_M_1_M_1 getPhoto()\n    {\n        return photo;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhoto(PhotoUni_M_1_M_1 photo)\n    {\n        this.photo = photo;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumUni_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_M_M_1_1;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumUni_M_M_1_1\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTO_ID\")\n    private PhotoUni_M_M_1_1 photo;\n\n    public AlbumUni_M_M_1_1()\n    {\n\n    }\n\n    public AlbumUni_M_M_1_1(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    /**\n     * @return the albumId\n     */\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    /**\n     * @param albumId\n     *            the albumId to set\n     */\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photo\n     */\n    public PhotoUni_M_M_1_1 getPhoto()\n    {\n        return photo;\n    }\n\n    /**\n     * @param photo\n     *            the photo to set\n     */\n    public void setPhoto(PhotoUni_M_M_1_1 photo)\n    {\n        this.photo = photo;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/album/AlbumUni_M_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.album;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.photo.PhotoUni_M_M_M_M;\n\n/**\n * Entity Class for album\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"ALBUM\", schema = \"Pickr@piccandra\")\npublic class AlbumUni_M_M_M_M\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    @JoinTable(name = \"ALBUM_PHOTO\", joinColumns = { @JoinColumn(name = \"ALBUM_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"PHOTO_ID\") })\n    private List<PhotoUni_M_M_M_M> photos;\n\n    public AlbumUni_M_M_M_M()\n    {\n\n    }\n\n    public AlbumUni_M_M_M_M(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n    /**\n     * @return the photos\n     */\n    public List<PhotoUni_M_M_M_M> getPhotos()\n    {\n        if (this.photos == null || this.photos.isEmpty())\n        {\n            this.photos = new ArrayList<PhotoUni_M_M_M_M>();\n        }\n        return photos;\n    }\n\n    /**\n     * @param photos\n     *            the photos to set\n     */\n    public void setPhotos(List<PhotoUni_M_M_M_M> photos)\n    {\n        this.photos = photos;\n    }\n\n    public void addPhoto(PhotoUni_M_M_M_M photo)\n    {\n        getPhotos().add(photo);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoBi_1_1_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_1_1_1;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoBi_1_1_1_1\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @OneToOne(mappedBy = \"photo\")\n    private AlbumBi_1_1_1_1 album;\n\n    public PhotoBi_1_1_1_1()\n    {\n\n    }\n\n    public PhotoBi_1_1_1_1(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_1_1_1_1 getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_1_1_1_1 album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoBi_1_1_1_1_PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_1_1_1_PK;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoBi_1_1_1_1_PK\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @OneToOne(mappedBy = \"photo\")\n    private AlbumBi_1_1_1_1_PK album;\n\n    public PhotoBi_1_1_1_1_PK()\n    {\n\n    }\n\n    public PhotoBi_1_1_1_1_PK(int photographerId, String photoId, String caption, String description)\n    {\n        this.photographerId = photographerId;\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_1_1_1_1_PK getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_1_1_1_1_PK album)\n    {\n        this.album = album;\n    }\n\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoBi_1_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_1_1_M;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoBi_1_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumBi_1_1_1_M album;\n\n    public PhotoBi_1_1_1_M()\n    {\n\n    }\n\n    public PhotoBi_1_1_1_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_1_1_1_M getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_1_1_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoBi_1_M_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_M_1_M;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoBi_1_M_1_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumBi_1_M_1_M album;\n\n    public PhotoBi_1_M_1_M()\n    {\n\n    }\n\n    public PhotoBi_1_M_1_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_1_M_1_M getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_1_M_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoBi_1_M_M_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_M_M_M;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoBi_1_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @ManyToMany(mappedBy = \"photos\", fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    private Set<AlbumBi_1_M_M_M> albums;\n\n    public PhotoBi_1_M_M_M()\n    {\n\n    }\n\n    public PhotoBi_1_M_M_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the albums\n     */\n    public Set<AlbumBi_1_M_M_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void setAlbums(Set<AlbumBi_1_M_M_M> albums)\n    {\n        this.albums = albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumBi_1_M_M_M album)\n    {\n        if (albums == null)\n        {\n            albums = new HashSet<AlbumBi_1_M_M_M>();\n        }\n        albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoBi_M_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_M_1_1_M;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoBi_M_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumBi_M_1_1_M album;\n\n    public PhotoBi_M_1_1_M()\n    {\n\n    }\n\n    public PhotoBi_M_1_1_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_M_1_1_M getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_M_1_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoBi_M_1_M_1.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport java.util.List;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_M_1_M_1;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoBi_M_1_M_1\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @OneToMany(mappedBy = \"photo\", fetch = FetchType.LAZY)\n    private List<AlbumBi_M_1_M_1> albums;\n\n    public PhotoBi_M_1_M_1()\n    {\n\n    }\n\n    public PhotoBi_M_1_M_1(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    public List<AlbumBi_M_1_M_1> getAlbums()\n    {\n        return albums;\n    }\n\n    public void setAlbums(List<AlbumBi_M_1_M_1> albums)\n    {\n        this.albums = albums;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoBi_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_M_M_1_1;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoBi_M_M_1_1\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @OneToOne(mappedBy = \"photo\", fetch = FetchType.LAZY)\n    private AlbumBi_M_M_1_1 album;\n\n    public PhotoBi_M_M_1_1()\n    {\n\n    }\n\n    public PhotoBi_M_M_1_1(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_M_M_1_1 getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_M_M_1_1 album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoBi_M_M_M_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_M_M_M_M;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoBi_M_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    @ManyToMany(mappedBy = \"photos\", fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    private Set<AlbumBi_M_M_M_M> albums;\n\n    public PhotoBi_M_M_M_M()\n    {\n\n    }\n\n    public PhotoBi_M_M_M_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    /**\n     * @return the albums\n     */\n    public Set<AlbumBi_M_M_M_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void setAlbums(Set<AlbumBi_M_M_M_M> albums)\n    {\n        this.albums = albums;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoUni_1_1_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoUni_1_1_1_1\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_1_1_1_1()\n    {\n\n    }\n\n    public PhotoUni_1_1_1_1(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoUni_1_1_1_1_PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoUni_1_1_1_1_PK\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_1_1_1_1_PK()\n    {\n\n    }\n\n    public PhotoUni_1_1_1_1_PK(int albumId, String photoId, String caption, String description)\n    {\n        this.photographerId = albumId;\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoUni_1_1_1_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoUni_1_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_1_1_1_M()\n    {\n\n    }\n\n    public PhotoUni_1_1_1_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoUni_1_M_1_M.java",
    "content": "/**\r\n * Copyright 2012 Impetus Infotech.\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.Table;\r\n\r\n/**\r\n * Entity class for photo\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\r\npublic class PhotoUni_1_M_1_M\r\n{\r\n    @Id\r\n    @Column(name = \"PHOTO_ID\")\r\n    private String photoId;\r\n\r\n    @Column(name = \"PHOTO_CAPTION\")\r\n    private String photoCaption;\r\n\r\n    @Column(name = \"PHOTO_DESC\")\r\n    private String photoDescription;\r\n\r\n    public PhotoUni_1_M_1_M()\r\n    {\r\n\r\n    }\r\n\r\n    public PhotoUni_1_M_1_M(String photoId, String caption, String description)\r\n    {\r\n        this.photoId = photoId;\r\n        this.photoCaption = caption;\r\n        this.photoDescription = description;\r\n    }\r\n\r\n    /**\r\n     * @return the photoId\r\n     */\r\n    public String getPhotoId()\r\n    {\r\n        return photoId;\r\n    }\r\n\r\n    /**\r\n     * @param photoId\r\n     *            the photoId to set\r\n     */\r\n    public void setPhotoId(String photoId)\r\n    {\r\n        this.photoId = photoId;\r\n    }\r\n\r\n    /**\r\n     * @return the photoCaption\r\n     */\r\n    public String getPhotoCaption()\r\n    {\r\n        return photoCaption;\r\n    }\r\n\r\n    /**\r\n     * @param photoCaption\r\n     *            the photoCaption to set\r\n     */\r\n    public void setPhotoCaption(String photoCaption)\r\n    {\r\n        this.photoCaption = photoCaption;\r\n    }\r\n\r\n    /**\r\n     * @return the photoDescription\r\n     */\r\n    public String getPhotoDescription()\r\n    {\r\n        return photoDescription;\r\n    }\r\n\r\n    /**\r\n     * @param photoDescription\r\n     *            the photoDescription to set\r\n     */\r\n    public void setPhotoDescription(String photoDescription)\r\n    {\r\n        this.photoDescription = photoDescription;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoUni_1_M_M_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoUni_1_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_1_M_M_M()\n    {\n\n    }\n\n    public PhotoUni_1_M_M_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoUni_M_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoUni_M_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_M_1_1_M()\n    {\n\n    }\n\n    public PhotoUni_M_1_1_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoUni_M_1_M_1.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoUni_M_1_M_1\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_M_1_M_1()\n    {\n\n    }\n\n    public PhotoUni_M_1_M_1(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoUni_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoUni_M_M_1_1\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_M_M_1_1()\n    {\n\n    }\n\n    public PhotoUni_M_M_1_1(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photo/PhotoUni_M_M_M_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photo;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity class for photo\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTO\", schema = \"Pickr@picongo\")\npublic class PhotoUni_M_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTO_ID\")\n    private String photoId;\n\n    @Column(name = \"PHOTO_CAPTION\")\n    private String photoCaption;\n\n    @Column(name = \"PHOTO_DESC\")\n    private String photoDescription;\n\n    public PhotoUni_M_M_M_M()\n    {\n\n    }\n\n    public PhotoUni_M_M_M_M(String photoId, String caption, String description)\n    {\n        this.photoId = photoId;\n        this.photoCaption = caption;\n        this.photoDescription = description;\n    }\n\n    /**\n     * @return the photoId\n     */\n    public String getPhotoId()\n    {\n        return photoId;\n    }\n\n    /**\n     * @param photoId\n     *            the photoId to set\n     */\n    public void setPhotoId(String photoId)\n    {\n        this.photoId = photoId;\n    }\n\n    /**\n     * @return the photoCaption\n     */\n    public String getPhotoCaption()\n    {\n        return photoCaption;\n    }\n\n    /**\n     * @param photoCaption\n     *            the photoCaption to set\n     */\n    public void setPhotoCaption(String photoCaption)\n    {\n        this.photoCaption = photoCaption;\n    }\n\n    /**\n     * @return the photoDescription\n     */\n    public String getPhotoDescription()\n    {\n        return photoDescription;\n    }\n\n    /**\n     * @param photoDescription\n     *            the photoDescription to set\n     */\n    public void setPhotoDescription(String photoDescription)\n    {\n        this.photoDescription = photoDescription;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerBi_1_1_1_1.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_1_1_1;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerBi_1_1_1_1\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumBi_1_1_1_1 album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_1_1_1_1 getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_1_1_1_1 album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerBi_1_1_1_1_PK.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_1_1_1_PK;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerBi_1_1_1_1_PK\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)\n    @PrimaryKeyJoinColumn\n    private AlbumBi_1_1_1_1_PK album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_1_1_1_1_PK getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_1_1_1_1_PK album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerBi_1_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_1_1_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerBi_1_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumBi_1_1_1_M album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_1_1_1_M getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_1_1_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerBi_1_M_1_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_M_1_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerBi_1_M_1_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"photographer\")\n    private List<AlbumBi_1_M_1_M> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumBi_1_M_1_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumBi_1_M_1_M album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumBi_1_M_1_M>();\n        }\n        this.albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerBi_1_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_1_M_M_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerBi_1_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"photographer\")\n    private List<AlbumBi_1_M_M_M> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumBi_1_M_M_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void setAlbums(List<AlbumBi_1_M_M_M> albums)\n    {\n        this.albums = albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumBi_1_M_M_M album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumBi_1_M_M_M>();\n        }\n        this.albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerBi_M_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_M_1_1_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerBi_M_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumBi_M_1_1_M album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_M_1_1_M getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_M_1_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerBi_M_1_M_1.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_M_1_M_1;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerBi_M_1_M_1\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumBi_M_1_M_1 album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumBi_M_1_M_1 getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumBi_M_1_M_1 album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerBi_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_M_M_1_1;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerBi_M_M_1_1\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    @JoinTable(/* schema = \"Pickr\", */name = \"PHOTOGRAPHER_ALBUM\", joinColumns = { @JoinColumn(name = \"PHOTOGRAPHER_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ALBUM_ID\") })\n    private List<AlbumBi_M_M_1_1> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumBi_M_M_1_1> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumBi_M_M_1_1 album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumBi_M_M_1_1>();\n        }\n        this.albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerBi_M_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumBi_M_M_M_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerBi_M_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    @JoinTable(/* schema = \"Pickr\", */name = \"PHOTOGRAPHER_ALBUM\", joinColumns = { @JoinColumn(name = \"PHOTOGRAPHER_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ALBUM_ID\") })\n    private List<AlbumBi_M_M_M_M> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumBi_M_M_M_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumBi_M_M_M_M album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumBi_M_M_M_M>();\n        }\n        this.albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerUni_1_1_1_1.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_1_1_1_1;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerUni_1_1_1_1\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to one, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumUni_1_1_1_1 album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumUni_1_1_1_1 getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumUni_1_1_1_1 album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerUni_1_1_1_1_PK.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_1_1_1_1_PK;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerUni_1_1_1_1_PK\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to one, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)\n    @PrimaryKeyJoinColumn\n    private AlbumUni_1_1_1_1_PK album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumUni_1_1_1_1_PK getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumUni_1_1_1_1_PK album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerUni_1_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_1_1_1_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerUni_1_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumUni_1_1_1_M album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    public AlbumUni_1_1_1_M getAlbum()\n    {\n        return album;\n    }\n\n    public void setAlbum(AlbumUni_1_1_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerUni_1_M_1_M.java",
    "content": "/*******************************************************************************\r\n * * Copyright 2012 Impetus Infotech.\r\n *  *\r\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n *  * you may not use this file except in compliance with the License.\r\n *  * You may obtain a copy of the License at\r\n *  *\r\n *  *      http://www.apache.org/licenses/LICENSE-2.0\r\n *  *\r\n *  * Unless required by applicable law or agreed to in writing, software\r\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n *  * See the License for the specific language governing permissions and\r\n *  * limitations under the License.\r\n ******************************************************************************/\r\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.List;\r\n\r\nimport javax.persistence.CascadeType;\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Entity;\r\nimport javax.persistence.FetchType;\r\nimport javax.persistence.Id;\r\nimport javax.persistence.JoinColumn;\r\nimport javax.persistence.OneToMany;\r\nimport javax.persistence.Table;\r\n\r\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_1_M_1_M;\r\n\r\n/**\r\n * Entity class representing a photographer\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Entity\r\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\r\npublic class PhotographerUni_1_M_1_M\r\n{\r\n    @Id\r\n    @Column(name = \"PHOTOGRAPHER_ID\")\r\n    private int photographerId;\r\n\r\n    @Column(name = \"PHOTOGRAPHER_NAME\")\r\n    private String photographerName;\r\n\r\n    // One to many, will be persisted separately\r\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\r\n    @JoinColumn(name = \"PHOTOGRAPHER_ID\")\r\n    private List<AlbumUni_1_M_1_M> albums;\r\n\r\n    /**\r\n     * @return the photographerId\r\n     */\r\n    public int getPhotographerId()\r\n    {\r\n        return photographerId;\r\n    }\r\n\r\n    /**\r\n     * @param photographerId\r\n     *            the photographerId to set\r\n     */\r\n    public void setPhotographerId(int photographerId)\r\n    {\r\n        this.photographerId = photographerId;\r\n    }\r\n\r\n    /**\r\n     * @return the photographerName\r\n     */\r\n    public String getPhotographerName()\r\n    {\r\n        return photographerName;\r\n    }\r\n\r\n    /**\r\n     * @param photographerName\r\n     *            the photographerName to set\r\n     */\r\n    public void setPhotographerName(String photographerName)\r\n    {\r\n        this.photographerName = photographerName;\r\n    }\r\n\r\n    /**\r\n     * @return the albums\r\n     */\r\n    public List<AlbumUni_1_M_1_M> getAlbums()\r\n    {\r\n        return albums;\r\n    }\r\n\r\n    /**\r\n     * @param albums\r\n     *            the albums to set\r\n     */\r\n    public void addAlbum(AlbumUni_1_M_1_M album)\r\n    {\r\n        if (this.albums == null || this.albums.isEmpty())\r\n        {\r\n            this.albums = new ArrayList<AlbumUni_1_M_1_M>();\r\n        }\r\n        this.albums.add(album);\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerUni_1_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_1_M_M_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerUni_1_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PHOTOGRAPHER_ID\")\n    private List<AlbumUni_1_M_M_M> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumUni_1_M_M_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void setAlbums(List<AlbumUni_1_M_M_M> albums)\n    {\n        this.albums = albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumUni_1_M_M_M album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumUni_1_M_M_M>();\n        }\n        this.albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerUni_M_1_1_M.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_M_1_1_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerUni_M_1_1_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumUni_M_1_1_M album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumUni_M_1_1_M getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumUni_M_1_1_M album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerUni_M_1_M_1.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_M_1_M_1;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerUni_M_1_M_1\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private AlbumUni_M_1_M_1 album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public AlbumUni_M_1_M_1 getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(AlbumUni_M_1_M_1 album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerUni_M_M_1_1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_M_M_1_1;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerUni_M_M_1_1\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    @JoinTable(/* schema = \"Pickr\", */name = \"PHOTOGRAPHER_ALBUM\", joinColumns = { @JoinColumn(name = \"PHOTOGRAPHER_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ALBUM_ID\") })\n    private List<AlbumUni_M_M_1_1> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumUni_M_M_1_1> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumUni_M_M_1_1 album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumUni_M_M_1_1>();\n        }\n        this.albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/pickr/entities/photographer/PhotographerUni_M_M_M_M.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.pickr.entities.photographer;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.tests.crossdatastore.pickr.entities.album.AlbumUni_M_M_M_M;\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER\", schema = \"Pickr\")\npublic class PhotographerUni_M_M_M_M\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)\n    @JoinTable(/* schema = \"Pickr\", */name = \"PHOTOGRAPHER_ALBUM\", joinColumns = { @JoinColumn(name = \"PHOTOGRAPHER_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ALBUM_ID\") })\n    private List<AlbumUni_M_M_M_M> albums;\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the albums\n     */\n    public List<AlbumUni_M_M_M_M> getAlbums()\n    {\n        return albums;\n    }\n\n    /**\n     * @param albums\n     *            the albums to set\n     */\n    public void addAlbum(AlbumUni_M_M_M_M album)\n    {\n        if (this.albums == null || this.albums.isEmpty())\n        {\n            this.albums = new ArrayList<AlbumUni_M_M_M_M>();\n        }\n        this.albums.add(album);\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/transaction/CrossDataStoreTransactionTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.transaction;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.locator.SimpleStrategy;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.HabitatOToOFKEntity;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.PersonnelOToOFKEntity;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class CrossDataStoreTransactionTest\n{\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        CassandraCli.cassandraSetUp();\n        CassandraCli.createKeySpace(\"KunderaTests\");\n        loadData();\n        loadDataForHABITAT();\n\n        emf = Persistence.createEntityManagerFactory(\"secIdxAddCassandra,addMongo\");\n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testRollback()\n    {\n        PersonnelOToOFKEntity person = new PersonnelOToOFKEntity();\n        person.setPersonId(\"1_p\");\n        person.setPersonName(\"crossdata-store\");\n        HabitatOToOFKEntity address = new HabitatOToOFKEntity();\n        address.setAddressId(\"1_a\");\n        address.setStreet(\"my street\");\n        person.setAddress(address);\n        try\n        {\n            em.persist(person);\n        }\n        catch (Exception ex)\n        {\n            HabitatOToOFKEntity found = em.find(HabitatOToOFKEntity.class, \"1_a\");\n            Assert.assertNull(found);\n        }\n    }\n\n    /**\n     * @throws TException\n     * @throws InvalidRequestException\n     * @throws SchemaDisagreementException\n     * \n     */\n    private void loadData() throws InvalidRequestException, TException, SchemaDisagreementException\n    {\n\n        KsDef ksDef = null;\n\n        CfDef cfDef = new CfDef();\n        cfDef.name = \"PERSONNEL\";\n        cfDef.keyspace = \"KunderaTests\";\n        // cfDef.column_type = \"Super\";\n        cfDef.setComparator_type(\"UTF8Type\");\n        cfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDefPersonName = new ColumnDef(ByteBuffer.wrap(\"PERSON_NAME\".getBytes()), \"UTF8Type\");\n        columnDefPersonName.index_type = IndexType.KEYS;\n\n        ColumnDef columnDefAddressId = new ColumnDef(ByteBuffer.wrap(\"ADDRESS_ID\".getBytes()), \"UTF8Type\");\n        columnDefAddressId.index_type = IndexType.KEYS;\n\n        cfDef.addToColumn_metadata(columnDefPersonName);\n        cfDef.addToColumn_metadata(columnDefAddressId);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(cfDef);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaTests\");\n            CassandraCli.client.set_keyspace(\"KunderaTests\");\n            if (!CassandraCli.columnFamilyExist(\"PERSONNEL\", \"KunderaTests\")) {\n                CassandraCli.client.system_add_column_family(cfDef);\n            } else {\n                CassandraCli.truncateColumnFamily(\"KunderaTests\", \"PERSONNEL\");\n            }\n\n//            List<CfDef> cfDefn = ksDef.getCf_defs();\n//\n//            // CassandraCli.client.set_keyspace(\"KunderaTests\");\n//            for (CfDef cfDef1 : cfDefn)\n//            {\n//\n//                if (cfDef1.getName().equalsIgnoreCase(\"PERSONNEL\"))\n//                {\n//\n//                    CassandraCli.truncateColumnFamily(\"KunderaTests\", \"PERSONNEL\");\n//\n//                } else{\n//                    CassandraCli.client.system_add_column_family(cfDef);\n//                }\n//            }\n//            \n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n\n        CassandraCli.client.set_keyspace(\"KunderaTests\");\n\n    }\n\n    private void addKeyspace(KsDef ksDef, List<CfDef> cfDefs) throws InvalidRequestException,\n            SchemaDisagreementException, TException\n    {\n        ksDef = new KsDef(\"KunderaTests\", SimpleStrategy.class.getSimpleName(), cfDefs);\n        // Set replication factor\n        if (ksDef.strategy_options == null)\n        {\n            ksDef.strategy_options = new LinkedHashMap<String, String>();\n        }\n        // Set replication factor, the value MUST be an integer\n        ksDef.strategy_options.put(\"replication_factor\", \"1\");\n        CassandraCli.client.system_add_keyspace(ksDef);\n    }\n\n    private void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n\n        KsDef ksDef = null;\n        CfDef cfDef2 = new CfDef();\n        cfDef2.name = \"ADDRESS\";\n        cfDef2.keyspace = \"KunderaTests\";\n\n        ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"STREET\".getBytes()), \"UTF8Type\");\n        columnDef2.index_type = IndexType.KEYS;\n        cfDef2.addToColumn_metadata(columnDef2);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(cfDef2);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaTests\");\n            CassandraCli.client.set_keyspace(\"KunderaTests\");\n            if (!CassandraCli.columnFamilyExist(\"ADDRESS\", \"KunderaTests\")) {\n                CassandraCli.client.system_add_column_family(cfDef2);\n            } else {\n                CassandraCli.truncateColumnFamily(\"KunderaTests\", \"ADDRESS\");\n            }\n//            List<CfDef> cfDefss = ksDef.getCf_defs();\n//            for (CfDef cfDef : cfDefss)\n//            {\n//\n//                if (cfDef.getName().equalsIgnoreCase(\"ADDRESS\"))\n//                {\n//                    CassandraCli.truncateColumnFamily(\"KunderaTests\", \"ADDRESS\");\n//\n//                } else{\n//                    CassandraCli.client.system_add_column_family(cfDef2);\n//                }\n//            }\n            \n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n        CassandraCli.client.set_keyspace(\"KunderaTests\");\n\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        //CassandraCli.dropKeySpace(\"KunderaTests\");\n        CassandraCli.truncateColumnFamily(\"KunderaTests\", \"ADDRESS\", \"PERSONNEL\");\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/AssociationBase.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress;\n\nimport java.io.IOException;\nimport java.lang.reflect.Field;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.metamodel.Metamodel;\n\nimport org.apache.cassandra.locator.SimpleStrategy;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.http.HttpHost;\nimport org.apache.http.client.HttpClient;\nimport org.apache.thrift.TException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport redis.clients.jedis.Jedis;\n\nimport com.impetus.client.couchdb.utils.CouchDBTestUtils;\nimport com.impetus.client.crud.RDBMSCli;\nimport com.impetus.client.mongodb.MongoDBClient;\nimport com.impetus.client.redis.RedisPropertyReader;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.metadata.KunderaMetadataManager;\nimport com.impetus.kundera.metadata.model.CoreMetadata;\nimport com.impetus.kundera.metadata.model.EntityMetadata;\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\nimport com.impetus.kundera.metadata.model.PersistenceUnitMetadata;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl;\nimport com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;\nimport com.impetus.kundera.proxy.cglib.CglibLazyInitializerFactory;\nimport com.impetus.kundera.tests.cli.CleanupUtilities;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.dao.UserAddressDaoImpl;\nimport com.mongodb.DB;\n\n/**\n * The Class AssociationBase.\n * \n * @author vivek.mishra\n */\npublic abstract class AssociationBase\n{\n    private static final String KEYSPACE = \"KunderaTests\";\n\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\n\n    protected Map propertyMap = new HashMap();\n\n    // public static final String[] ALL_PUs_UNDER_TEST = new String[] {\n    // \"addCassandra\"};\n\n    // public static final String[] ALL_PUs_UNDER_TEST = new\n    // String[]{/*\"rdbms\",*/ \"twissandra\", \"twihbase\",\"twingo\"};\n    /** The em. */\n    protected EntityManager em;\n\n    /** The dao. */\n    protected UserAddressDaoImpl dao;\n\n    protected KunderaMetadata kunderaMetadata;\n\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(AssociationBase.class);\n\n    /** The col families. */\n    private String[] colFamilies;\n\n    protected List<Object> col = new ArrayList<Object>();\n\n    // private String persistenceUnits =\n    // \"redis,rdbms,addMongo,oracle_kvstore,piccandra,secIdxAddCassandra,picongo,addCassandra\";\n    // protected static final String[] ALL_PUs_UNDER_TEST = new String[] {\n    // \"addMongo\", \"rdbms\", \"redis\", \"addCassandra\",\n    // \"oracle_kvstore\" , \"addHbase\"};\n\n    private String persistenceUnits = \"rdbms,addMongo,oracle_kvstore,addCassandra,piccandra,secIdxAddCassandra,picongo,redis,addCouchdb\";\n\n    protected static final String[] ALL_PUs_UNDER_TEST = new String[] { \"addMongo\" ,\"rdbms\", \"redis\", \"addCassandra\",\n            \"oracle_kvstore\", \"addCouchdb\" /* , \"addHbase\" */};\n\n    protected RDBMSCli cli;\n\n    private HttpClient httpClient;\n\n    private HttpHost httpHost;\n\n    /**\n     * Sets the up internal.\n     * \n     * @param colFamilies\n     *            the new up internal\n     */\n    protected void setUpInternal(String... colFamilies)\n    {\n        try\n        {\n            cli = new RDBMSCli(KEYSPACE);\n            cli.createSchema(KEYSPACE);\n            CassandraCli.cassandraSetUp();\n            CassandraCli.createKeySpace(\"Pickr\");\n            CassandraCli.createKeySpace(KEYSPACE);\n\n            dao = new UserAddressDaoImpl(persistenceUnits);\n\n            dao.closeEntityManager();\n            dao.closeEntityManagerFactory();\n\n            em = dao.getEntityManager(persistenceUnits, propertyMap);\n            kunderaMetadata = ((EntityManagerFactoryImpl) em.getEntityManagerFactory()).getKunderaMetadataInstance();\n            this.colFamilies = colFamilies;\n\n            httpClient = CouchDBTestUtils.initiateHttpClient(kunderaMetadata, \"addCouchdb\");\n            httpHost = new HttpHost(\"localhost\", 5984);\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error caused by \", e);\n        }\n    }\n\n    /*    *//**\n     * Switch over persistence units.\n     * \n     * @param entityPuCol\n     *            the entity pu col\n     */\n    /*\n     * protected void switchPersistenceUnits(Map<Class, String> entityPuCol) {\n     * if (entityPuCol != null) { Iterator<Class> iter =\n     * entityPuCol.keySet().iterator(); log.warn(\"Invocation for:\"); while\n     * (iter.hasNext()) { Class clazz = iter.next(); String pu =\n     * entityPuCol.get(clazz); Map<String, Metamodel> metaModels =\n     * kunderaMetadata.getApplicationMetadata().getMetamodelMap();\n     * EntityMetadata mAdd = null; for (Metamodel m : metaModels.values()) {\n     * mAdd = ((MetamodelImpl) m).getEntityMetadataMap().get(clazz); if (mAdd !=\n     * null) { break; } } // EntityMetadata mAdd = //\n     * KunderaMetadataManager.getMetamodel\n     * (pu).getEntityMetadataMap().get(clazz); mAdd.setPersistenceUnit(pu);\n     * KunderaMetadataManager.getMetamodel(pu).getEntityMetadataMap().put(clazz,\n     * mAdd); log.warn(\"persistence unit:\" + pu + \"class::\" +\n     * clazz.getCanonicalName()); } } }\n     */\n\n    /**\n     * Switch over persistence units.\n     * \n     * @param entityPuCol\n     *            the entity pu col\n     * @throws SchemaDisagreementException\n     * @throws TimedOutException\n     * @throws UnavailableException\n     * @throws InvalidRequestException\n     * @throws TException\n     * @throws IOException\n     */\n    protected void switchPersistenceUnits(Map<Class, String> entityPuCol) throws IOException, TException,\n            InvalidRequestException, UnavailableException, TimedOutException, SchemaDisagreementException\n    {\n        if (entityPuCol != null)\n        {\n            Iterator<Class> iter = entityPuCol.keySet().iterator();\n            log.warn(\"Invocation for:\");\n            while (iter.hasNext())\n            {\n                Class clazz = iter.next();\n                String pu = entityPuCol.get(clazz);\n                // EntityMetadata mAdd = KunderaMetadataManager\n                // .getEntityMetadata(clazz);\n\n                Map<String, Metamodel> metaModels = kunderaMetadata.getApplicationMetadata().getMetamodelMap();\n\n                EntityMetadata mAdd = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);\n                for (Metamodel m : metaModels.values())\n                {\n                    mAdd = ((MetamodelImpl) m).getEntityMetadataMap().get(clazz.getName());\n                    if (mAdd != null)\n                    {\n                        break;\n                    }\n                }\n\n                // for a particular persistence unit, change keyspace.\n\n                mAdd.setPersistenceUnit(pu);\n                Map<String, List<String>> clazzToPu = new HashMap<String, List<String>>(1);\n                List<String> pus = new ArrayList<String>(1);\n                pus.add(pu);\n                clazzToPu.put(clazz.getName(), pus);\n                kunderaMetadata.getApplicationMetadata().setClazzToPuMap(clazzToPu);\n\n                Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(pu);\n                ((MetamodelImpl) metaModel).addEntityMetadata(clazz, mAdd);\n                kunderaMetadata.getApplicationMetadata().getMetamodelMap().put(pu, metaModel);\n                // kunderaMetadata.getApplicationMetadata().addEntityMetadata(pu,\n                // clazz, mAdd);\n                PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata()\n                        .getPersistenceUnitMetadata(pu);\n\n                CoreMetadata coreMetadata = new CoreMetadata();\n                coreMetadata.setLazyInitializerFactory(new CglibLazyInitializerFactory());\n                kunderaMetadata.setCoreMetadata(coreMetadata);\n\n                String client = puMetadata.getProperties().getProperty(PersistenceProperties.KUNDERA_CLIENT_FACTORY);\n                if (client.equalsIgnoreCase(\"com.impetus.client.cassandra.pelops.PelopsClientFactory\")\n                        || client.equalsIgnoreCase(\"com.impetus.client.cassandra.thrift.ThriftClientFactory\"))\n                {\n                    if (RUN_IN_EMBEDDED_MODE)\n                    {\n                        CassandraCli.cassandraSetUp();\n                        CassandraCli.initClient();\n                    }\n\n                    if (AUTO_MANAGE_SCHEMA)\n                    {\n                        if (mAdd.getTableName().equalsIgnoreCase(colFamilies[0]))\n                        {\n                            loadDataForHABITAT();\n                        }\n                        else if (mAdd.getTableName().equalsIgnoreCase(colFamilies[1]))\n                        {\n                            loadDataForPERSONNEL();\n                        }\n                    }\n\n                }\n                if (client.equalsIgnoreCase(\"com.impetus.client.hbase.HBaseClientFactory\") && RUN_IN_EMBEDDED_MODE)\n                {\n                    // HBaseCli.startCluster();\n                    // HBaseCli.createTable(\"PERSONNEL\");\n                    // HBaseCli.addColumnFamily(\"PERSONNEL\", \"PERSON_NAME\");\n                    // HBaseCli.addColumnFamily(\"PERSONNEL\", \"ADDRESS_ID\");\n                    //\n                    // HBaseCli.createTable(\"ADDRESS\");\n                    // HBaseCli.addColumnFamily(\"ADDRESS\", \"STREET\");\n                    // HBaseCli.addColumnFamily(\"ADDRESS\", \"PERSON_ID\");\n                    //\n                    // HBaseCli.createTable(\"PERSONNEL_ADDRESS\");\n                    // HBaseCli.addColumnFamily(\"PERSONNEL_ADDRESS\",\n                    // \"ADDRESS_ID\");\n                    // HBaseCli.addColumnFamily(\"PERSONNEL_ADDRESS\",\n                    // \"PERSON_ID\");\n                    // HBaseCli.addColumnFamily(\"PERSONNEL_ADDRESS\",\n                    // \"JoinColumns\");\n\n                }\n                if (client.equalsIgnoreCase(\"com.impetus.client.rdbms.RDBMSClientFactory\"))\n                {\n                    try\n                    {\n                        createSchemaForPERSONNEL();\n                        createSchemaForHABITAT();\n                    }\n                    catch (Exception e)\n                    {\n                        log.error(\"error during creating table in HSQLDB\", e);\n                    }\n\n                }\n\n                if (client.equalsIgnoreCase(\"com.impetus.client.couchdb.CouchDBClientFactory\"))\n                {\n                    try\n                    {\n                        CouchDBTestUtils.createDatabase(\"KunderaTests\".toLowerCase(), httpClient, httpHost);\n                        // CouchDBTestUtils.createViews(new String[] { \"STREET\",\n                        // \"ADDRESS_ID\", \"PERSON_ID\" }, \"ADDRESS\",\n                        // httpHost, \"KunderaTests\".toLowerCase(), httpClient);\n                        // CouchDBTestUtils.createViews(new String[] {\n                        // \"PERSON_NAME\", \"PERSON_ID\", \"ADDRESS_ID\" },\n                        // \"PERSONNEL\", httpHost, \"KunderaTests\".toLowerCase(),\n                        // httpClient);\n                        // CouchDBTestUtils.createViews(new String[] {\n                        // \"PERSON_ID\", \"ADDRESS_ID\" }, \"PERSONNEL_ADDRESS\",\n                        // httpHost, \"KunderaTests\".toLowerCase(), httpClient);\n\n                        CouchDBTestUtils.createViews(new String[] { \"STREET\", \"ADDRESS_ID\", \"PERSON_ID\" },\n                                colFamilies[0], httpHost, \"KunderaTests\".toLowerCase(), httpClient);\n                        CouchDBTestUtils.createViews(new String[] { \"PERSON_NAME\", \"PERSON_ID\", \"ADDRESS_ID\" },\n                                colFamilies[1], httpHost, \"KunderaTests\".toLowerCase(), httpClient);\n\n                        if (colFamilies.length == 3)\n                        {\n                            CouchDBTestUtils.createViews(new String[] { \"PERSON_ID\", \"ADDRESS_ID\" }, colFamilies[2],\n                                    httpHost, \"KunderaTests\".toLowerCase(), httpClient);\n                        }\n                    }\n                    catch (Exception e)\n                    {\n                        log.error(\"error during creating design document in couchDB\", e);\n                    }\n                }\n\n                String schema = puMetadata.getProperty(PersistenceProperties.KUNDERA_KEYSPACE);\n                mAdd.setSchema(schema != null ? schema : KEYSPACE);\n                // mAdd.setSchema(schema)\n\n                log.warn(\"persistence unit:\" + pu + \" and class:\" + clazz.getCanonicalName());\n            }\n        }\n\n        dao.closeEntityManager();\n        em = dao.getEntityManager(persistenceUnits, propertyMap);\n    }\n\n    /**\n     * Tear down internal.\n     * \n     * @param ALL_PUs_UNDER_TEST\n     * \n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    protected void tearDownInternal(String[] ALL_PUs_UNDER_TEST) throws InvalidRequestException,\n            SchemaDisagreementException\n    {\n        if (!em.isOpen())\n        {\n            em = dao.getEntityManager(persistenceUnits, propertyMap);\n        }\n\n        // if (/*AUTO_MANAGE_SCHEMA*/true)\n        // {\n        truncateColumnFamily();\n        truncateRdbms();\n\n        truncateMongo();\n\n        truncateRedis();\n        // }\n\n        for (String pu : ALL_PUs_UNDER_TEST)\n        {\n            CleanupUtilities.cleanLuceneDirectory(kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(\n                    pu));\n        }\n\n        CouchDBTestUtils.dropDatabase(\"KunderaTests\".toLowerCase(), httpClient, httpHost);\n        // HBaseCli.stopCluster();\n        // dao.closeEntityManagerFactory();\n\n    }\n\n    /**\n     * \n     */\n    private void truncateColumnFamily()\n    {\n        String[] columnFamily = new String[] { colFamilies[0], colFamilies[1],\n                colFamilies.length == 3 ? colFamilies[2] : null };\n        CassandraCli.truncateColumnFamily(KEYSPACE, columnFamily);\n    }\n\n    /**\n     * \n     */\n    private void truncateMongo()\n    {\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        MongoDBClient client = (MongoDBClient) clients.get(\"addMongo\");\n        if (client != null)\n        {\n            try\n            {\n                Field db = client.getClass().getDeclaredField(\"mongoDb\");\n                if (!db.isAccessible())\n                {\n                    db.setAccessible(true);\n                }\n                DB mongoDB = (DB) db.get(client);\n                if (mongoDB.collectionExists(colFamilies[0]))\n                {\n                    mongoDB.getCollection(colFamilies[0]).drop();\n                }\n                if (mongoDB.collectionExists(colFamilies[1]))\n                {\n                    mongoDB.getCollection(colFamilies[1]).drop();\n                }\n                if (colFamilies.length == 3 && mongoDB.collectionExists(colFamilies[2]))\n                {\n                    mongoDB.getCollection(colFamilies[2]).drop();\n                }\n            }\n            catch (SecurityException e)\n            {\n                log.error(\"Error while truncating db\", e);\n            }\n            catch (NoSuchFieldException e)\n            {\n                log.error(\"Error while truncating db\", e);\n            }\n            catch (IllegalArgumentException e)\n            {\n                log.error(\"Error while truncating db\", e);\n            }\n            catch (IllegalAccessException e)\n            {\n                log.error(\"Error while truncating db\", e);\n            }\n        }\n\n    }\n\n    private void truncateRedis()\n\n    {\n        if (RedisPropertyReader.rsmd != null)\n        {\n            PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(\n                    \"redis\");\n            Properties props = puMetadata.getProperties();\n            String contactNode = RedisPropertyReader.rsmd.getHost() != null ? RedisPropertyReader.rsmd.getHost()\n                    : (String) props.get(PersistenceProperties.KUNDERA_NODES);\n            String defaultPort = RedisPropertyReader.rsmd.getPort() != null ? RedisPropertyReader.rsmd.getPort()\n                    : (String) props.get(PersistenceProperties.KUNDERA_PORT);\n            String password = RedisPropertyReader.rsmd.getPassword() != null ? RedisPropertyReader.rsmd.getPassword()\n                    : (String) props.get(PersistenceProperties.KUNDERA_PASSWORD);\n            Jedis connection = new Jedis(contactNode, Integer.valueOf(defaultPort));\n            connection.auth(password);\n            connection.connect();\n            connection.flushDB();\n        }\n    }\n\n    /**\n     * \n     */\n    private void truncateRdbms()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.\" + colFamilies[0]);\n            // cli.update(\"DROP TABLE KUNDERATESTS.PERSONNEL\");\n            cli.update(\"DELETE FROM KUNDERATESTS.\" + colFamilies[1]);\n            // cli.update(\"DROP TABLE KUNDERATESTS.ADDRESS\");\n            if (colFamilies.length == 3)\n            {\n                cli.update(\"DELETE FROM KUNDERATESTS.\" + colFamilies[2]);\n            }\n            // cli.update(\"DROP TABLE KUNDERATESTS.PERSONNEL_ADDRESS\");\n\n        }\n        catch (Exception e)\n        {\n            // do nothing..weird!!\n        }\n\n    }\n\n    protected void addKeyspace(KsDef ksDef, List<CfDef> cfDefs) throws InvalidRequestException,\n            SchemaDisagreementException, TException\n    {\n        ksDef = new KsDef(KEYSPACE, SimpleStrategy.class.getSimpleName(), cfDefs);\n        // Set replication factor\n        if (ksDef.strategy_options == null)\n        {\n            ksDef.strategy_options = new LinkedHashMap<String, String>();\n        }\n        // Set replication factor, the value MUST be an integer\n        ksDef.strategy_options.put(\"replication_factor\", \"1\");\n        CassandraCli.client.system_add_keyspace(ksDef);\n    }\n\n    /**\n     * Truncates schema.\n     * \n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    protected void truncateSchema() throws InvalidRequestException, SchemaDisagreementException\n    {\n        log.warn(\"Truncating....\");\n\n        CassandraCli.dropColumnFamily(colFamilies[0], KEYSPACE);\n        CassandraCli.dropColumnFamily(colFamilies[1], KEYSPACE);\n        if (colFamilies.length == 3)\n        {\n            CassandraCli.dropColumnFamily(colFamilies[2], KEYSPACE);\n        }\n        CassandraCli.dropKeySpace(KEYSPACE);\n    }\n\n    protected abstract void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException;\n\n    protected abstract void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException;\n\n    protected abstract void createSchemaForPERSONNEL() throws SQLException;\n\n    protected abstract void createSchemaForHABITAT() throws SQLException;\n\n    protected void shutDownRdbmsServer() throws SQLException\n    {\n        if (cli != null)\n        {\n            try\n            {\n                cli.dropSchema(KEYSPACE);\n                cli.shutdown();\n            }\n            catch (Exception e)\n            {\n                cli.closeConnection();\n            }\n            finally\n            {\n                cli.closeConnection();\n            }\n\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/MTMBiAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.HabitatBiMToM;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.PersonnelBiMToM;\n\npublic class MTMBiAssociationTest extends TwinAssociation\n{\n\n    /**\n     * Inits the.\n     */\n    @BeforeClass\n    public static void init() throws Exception\n    {\n\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelBiMToM.class);\n        clazzz.add(HabitatBiMToM.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal(\"HabitatBiMToM\", \"PersonnelBiMToM\", \"PERSONNEL_ADDRESS\");\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        tryOperation(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonnelBiMToM person1 = new PersonnelBiMToM();\n        person1.setPersonId(\"bimanytomany_1\");\n        person1.setPersonName(\"Amresh\");\n\n        PersonnelBiMToM person2 = new PersonnelBiMToM();\n        person2.setPersonId(\"bimanytomany_2\");\n        person2.setPersonName(\"Vivek\");\n\n        HabitatBiMToM address1 = new HabitatBiMToM();\n        address1.setAddressId(\"bimanytomany_a\");\n        address1.setStreet(\"AAAAAAAAAAAAA\");\n\n        HabitatBiMToM address2 = new HabitatBiMToM();\n        address2.setAddressId(\"bimanytomany_b\");\n        address2.setStreet(\"BBBBBBBBBBBBBBB\");\n\n        HabitatBiMToM address3 = new HabitatBiMToM();\n        address3.setAddressId(\"bimanytomany_c\");\n        address3.setStreet(\"CCCCCCCCCCC\");\n\n        Set<HabitatBiMToM> person1Addresses = new HashSet<HabitatBiMToM>();\n        Set<HabitatBiMToM> person2Addresses = new HashSet<HabitatBiMToM>();\n\n        person1Addresses.add(address1);\n        person1Addresses.add(address2);\n\n        person2Addresses.add(address2);\n        person2Addresses.add(address3);\n\n        person1.setAddresses(person1Addresses);\n        person2.setAddresses(person2Addresses);\n\n        Set<PersonnelBiMToM> persons = new HashSet<PersonnelBiMToM>();\n        persons.add(person1);\n        persons.add(person2);\n\n        dao.savePersons(persons);\n\n        col.add(person1);\n        col.add(person2);\n        col.add(address1);\n        col.add(address2);\n        col.add(address3);\n\n    }\n\n    @Override\n    protected void find()\n    {\n        PersonnelBiMToM person1 = (PersonnelBiMToM) dao.findPerson(PersonnelBiMToM.class, \"bimanytomany_1\");\n        assertPerson1(person1);\n\n        PersonnelBiMToM person2 = (PersonnelBiMToM) dao.findPerson(PersonnelBiMToM.class, \"bimanytomany_2\");\n        assertPerson2(person2);\n\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        // Find Person 1\n        PersonnelBiMToM p1 = (PersonnelBiMToM) dao.findPersonByIdColumn(PersonnelBiMToM.class, \"bimanytomany_1\");\n        assertPerson1(p1);\n\n        // Find Person 2\n        PersonnelBiMToM p2 = (PersonnelBiMToM) dao.findPersonByIdColumn(PersonnelBiMToM.class, \"bimanytomany_2\");\n        assertPerson2(p2);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelBiMToM> persons = dao.findPersonByName(PersonnelBiMToM.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        assertPerson1(persons.get(0));\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n    }\n\n    @Override\n    protected void update()\n    {\n    }\n\n    @Override\n    protected void remove()\n    {\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        // shutDownRdbmsServer();\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * @param person2\n     */\n    private void assertPerson2(PersonnelBiMToM person2)\n    {\n        Assert.assertNotNull(person2);\n\n        Assert.assertEquals(\"bimanytomany_2\", person2.getPersonId());\n        Assert.assertEquals(\"Vivek\", person2.getPersonName());\n\n        Set<HabitatBiMToM> addresses2 = person2.getAddresses();\n        Assert.assertNotNull(addresses2);\n        Assert.assertFalse(addresses2.isEmpty());\n        Assert.assertEquals(2, addresses2.size());\n        HabitatBiMToM address21 = (HabitatBiMToM) addresses2.toArray()[0];\n        Assert.assertNotNull(address21);\n        HabitatBiMToM address22 = (HabitatBiMToM) addresses2.toArray()[1];\n        Assert.assertNotNull(address22);\n    }\n\n    /**\n     * @param person1\n     */\n    private void assertPerson1(PersonnelBiMToM person1)\n    {\n        Assert.assertNotNull(person1);\n        Assert.assertEquals(\"bimanytomany_1\", person1.getPersonId());\n        Assert.assertEquals(\"Amresh\", person1.getPersonName());\n\n        Set<HabitatBiMToM> addresses1 = person1.getAddresses();\n        Assert.assertNotNull(addresses1);\n        Assert.assertFalse(addresses1.isEmpty());\n        Assert.assertEquals(2, addresses1.size());\n        HabitatBiMToM address11 = (HabitatBiMToM) addresses1.toArray()[0];\n        Assert.assertNotNull(address11);\n        Assert.assertNotNull(address11.getPeople());\n        Assert.assertFalse(address11.getPeople().isEmpty());\n        HabitatBiMToM address12 = (HabitatBiMToM) addresses1.toArray()[1];\n        Assert.assertNotNull(address12.getPeople());\n        Assert.assertFalse(address12.getPeople().isEmpty());\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"PersonnelBiMToM\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelBiMToM\\\" ( \\\"PERSON_ID\\\" text PRIMARY KEY,  \\\"PERSON_NAME\\\" text, \\\"ADDRESS_ID\\\" text)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBiMToM\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PERSONNEL_ADDRESS\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PERSONNEL_ADDRESS\\\" ( \\\"PERSON_ID\\\" text,  \\\"key\\\" text PRIMARY KEY, \\\"ADDRESS_ID\\\" text)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PERSONNEL_ADDRESS\\\" ( \\\"PERSON_ID\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PERSONNEL_ADDRESS\\\" ( \\\"ADDRESS_ID\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, TimedOutException,\n            SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatBiMToM\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"HabitatBiMToM\\\" ( \\\"ADDRESS_ID\\\" text PRIMARY KEY,  \\\"STREET\\\" text)\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatBiMToM\\\" ( \\\"STREET\\\")\", keyspaceName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForPERSONNEL()\n     */\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        try\n        {\n            // cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBiMToM (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n            // cli.update(\"GRANT ALL PRIVILEGES ON KUNDERATESTS.PersonnelBiMToM TO PUBLIC\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBiMToM (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(150), ADDRESS_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelBiMToM\");\n            // cli.update(\"DELETE FROM KUNDERATESTS.PersonnelBiMToM\");\n            // cli.update(\"DROP TABLE KUNDERATESTS.PersonnelBiMToM\");\n            // cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBiMToM (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n            // cli.update(\"GRANT ALL PRIVILEGES ON KUNDERATESTS.PersonnelBiMToM TO PUBLIC\");\n        }\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PERSONNEL_ADDRESS (PERSON_ID VARCHAR(150) , ADDRESS_ID VARCHAR(150))\");\n            // cli.update(\"GRANT ALL PRIVILEGES ON KUNDERATESTS.PERSONNEL_ADDRESS TO PUBLIC\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PERSONNEL_ADDRESS\");\n            // cli.update(\"DROP TABLE KUNDERATESTS.PERSONNEL_ADDRESS\");\n            // cli.update(\"CREATE TABLE KUNDERATESTS.PERSONNEL_ADDRESS (PERSON_ID VARCHAR(150) , ADDRESS_ID VARCHAR(150))\");\n            // cli.update(\"GRANT ALL PRIVILEGES ON KUNDERATESTS.PERSONNEL_ADDRESS TO PUBLIC\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForHABITAT()\n     */\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n            // cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBiMToM (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256))\");\n            // cli.update(\"GRANT ALL PRIVILEGES ON KUNDERATESTS.HabitatBiMToM TO PUBLIC\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBiMToM (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256),PERSON_ID VARCHAR(150))\");\n\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatBiMToM\");\n            // cli.update(\"DROP TABLE KUNDERATESTS.HabitatBiMToM\");\n            // cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBiMToM (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256))\");\n            // cli.update(\"GRANT ALL PRIVILEGES ON KUNDERATESTS.HabitatBiMToM TO PUBLIC\");\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/MTMUniAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.HabitatUniMToM;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.PersonnelUniMToM;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class MTMUniAssociationTest extends TwinAssociation\n{\n    /**\n     * Inits the.\n     */\n    @BeforeClass\n    public static void init() throws Exception\n    {\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelUniMToM.class);\n        clazzz.add(HabitatUniMToM.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal(\"HabitatUniMToM\", \"PersonnelUniMToM\", \"PERSONNEL_ADDRESS\");\n    }\n\n    /**\n     * Test insert.\n     */\n    @Test\n    public void testCRUD()\n    {\n        try\n        {\n            tryOperation(ALL_PUs_UNDER_TEST);\n        }\n        catch (Exception e)\n        {\n            Assert.fail(\"Failed, Caused by:\" + e.getMessage());\n        }\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonnelUniMToM person1 = new PersonnelUniMToM();\n        person1.setPersonId(\"unimanytomany_1\");\n        person1.setPersonName(\"Amresh\");\n\n        PersonnelUniMToM person2 = new PersonnelUniMToM();\n        person2.setPersonId(\"unimanytomany_2\");\n        person2.setPersonName(\"Vivek\");\n\n        HabitatUniMToM address1 = new HabitatUniMToM();\n        address1.setAddressId(\"unimanytomany_a\");\n        address1.setStreet(\"AAAAAAAAAAAAA\");\n\n        HabitatUniMToM address2 = new HabitatUniMToM();\n        address2.setAddressId(\"unimanytomany_b\");\n        address2.setStreet(\"BBBBBBBBBBBBBBB\");\n\n        HabitatUniMToM address3 = new HabitatUniMToM();\n        address3.setAddressId(\"unimanytomany_c\");\n        address3.setStreet(\"CCCCCCCCCCC\");\n\n        Set<HabitatUniMToM> person1Addresses = new HashSet<HabitatUniMToM>();\n        Set<HabitatUniMToM> person2Addresses = new HashSet<HabitatUniMToM>();\n\n        person1Addresses.add(address1);\n        person1Addresses.add(address2);\n\n        person2Addresses.add(address2);\n        person2Addresses.add(address3);\n\n        person1.setAddresses(person1Addresses);\n        person2.setAddresses(person2Addresses);\n\n        Set<PersonnelUniMToM> persons = new HashSet<PersonnelUniMToM>();\n        persons.add(person1);\n        persons.add(person2);\n\n        dao.savePersons(persons);\n\n        col.add(person1);\n        col.add(person2);\n        col.add(address1);\n        col.add(address2);\n        col.add(address3);\n    }\n\n    @Override\n    protected void find()\n    {\n\n        PersonnelUniMToM person1 = (PersonnelUniMToM) dao.findPerson(PersonnelUniMToM.class, \"unimanytomany_1\");\n        assertPerson1(person1);\n\n        PersonnelUniMToM person2 = (PersonnelUniMToM) dao.findPerson(PersonnelUniMToM.class, \"unimanytomany_2\");\n        assertPerson2(person2);\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        // Find Person 1\n        PersonnelUniMToM p1 = (PersonnelUniMToM) dao.findPersonByIdColumn(PersonnelUniMToM.class, \"unimanytomany_1\");\n        assertPerson1(p1);\n\n        // Find Person 2\n        PersonnelUniMToM p2 = (PersonnelUniMToM) dao.findPersonByIdColumn(PersonnelUniMToM.class, \"unimanytomany_2\");\n        assertPerson2(p2);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelUniMToM> persons = dao.findPersonByName(PersonnelUniMToM.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        assertPerson1(persons.get(0));\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        HabitatUniMToM a = (HabitatUniMToM) dao.findAddressByIdColumn(HabitatUniMToM.class, \"unimanytomany_a\");\n        assertAddressForPerson1(a);\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        List<HabitatUniMToM> adds = dao.findAddressByStreet(HabitatUniMToM.class, \"AAAAAAAAAAAAA\");\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertTrue(adds.size() == 1);\n\n        assertAddressForPerson1(adds.get(0));\n    }\n\n    @Override\n    protected void update()\n    {\n        PersonnelUniMToM p1 = (PersonnelUniMToM) dao.findPerson(PersonnelUniMToM.class, \"unimanytomany_1\");\n        Assert.assertNotNull(p1);\n        Assert.assertEquals(2, p1.getAddresses().size());\n        for (HabitatUniMToM address : p1.getAddresses())\n        {\n            address.setStreet(\"Brand New Street\");\n        }\n        p1.setPersonName(\"Saurabh\");\n        dao.merge(p1);\n        PersonnelUniMToM p1AfterMerge = (PersonnelUniMToM) dao.findPerson(PersonnelUniMToM.class, \"unimanytomany_1\");\n        Assert.assertNotNull(p1AfterMerge);\n        Assert.assertEquals(\"Saurabh\", p1AfterMerge.getPersonName());\n        Assert.assertEquals(2, p1AfterMerge.getAddresses().size());\n        for (HabitatUniMToM address : p1AfterMerge.getAddresses())\n        {\n            Assert.assertEquals(\"Brand New Street\", address.getStreet());\n        }\n\n        PersonnelUniMToM p2 = (PersonnelUniMToM) dao.findPerson(PersonnelUniMToM.class, \"unimanytomany_2\");\n        Assert.assertNotNull(p2);\n        Assert.assertEquals(2, p2.getAddresses().size());\n        p2.setPersonName(\"Vijay\");\n        for (HabitatUniMToM address : p2.getAddresses())\n        {\n            address.setStreet(\"Brand New Street\");\n        }\n        dao.merge(p2);\n        PersonnelUniMToM p2AfterMerge = (PersonnelUniMToM) dao.findPerson(PersonnelUniMToM.class, \"unimanytomany_2\");\n        Assert.assertNotNull(p2AfterMerge);\n        Assert.assertEquals(\"Vijay\", p2AfterMerge.getPersonName());\n        Assert.assertEquals(2, p2AfterMerge.getAddresses().size());\n        for (HabitatUniMToM address : p2AfterMerge.getAddresses())\n        {\n            Assert.assertEquals(\"Brand New Street\", address.getStreet());\n        }\n    }\n\n    @Override\n    protected void remove()\n    {\n        dao.remove(\"unimanytomany_1\", PersonnelUniMToM.class);\n        PersonnelUniMToM person1AfterRemoval = (PersonnelUniMToM) dao.findPerson(PersonnelUniMToM.class,\n                \"unimanytomany_1\");\n        Assert.assertNull(person1AfterRemoval);\n\n        dao.remove(\"unimanytomany_2\", PersonnelUniMToM.class);\n        PersonnelUniMToM person2AfterRemoval = (PersonnelUniMToM) dao.findPerson(PersonnelUniMToM.class,\n                \"unimanytomany_2\");\n        Assert.assertNull(person2AfterRemoval);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        // shutDownRdbmsServer();\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * @param person1\n     */\n    private void assertPerson1(PersonnelUniMToM person1)\n    {\n        Assert.assertNotNull(person1);\n        Assert.assertEquals(\"unimanytomany_1\", person1.getPersonId());\n        Assert.assertEquals(\"Amresh\", person1.getPersonName());\n\n        Set<HabitatUniMToM> addresses1 = person1.getAddresses();\n        Assert.assertNotNull(addresses1);\n        Assert.assertFalse(addresses1.isEmpty());\n        Assert.assertEquals(2, addresses1.size());\n        HabitatUniMToM address11 = (HabitatUniMToM) addresses1.toArray()[0];\n        assertAddressForPerson1(address11);\n        HabitatUniMToM address12 = (HabitatUniMToM) addresses1.toArray()[1];\n        assertAddressForPerson1(address12);\n    }\n\n    /**\n     * @param person2\n     */\n    private void assertPerson2(PersonnelUniMToM person2)\n    {\n        Assert.assertNotNull(person2);\n\n        Assert.assertEquals(\"unimanytomany_2\", person2.getPersonId());\n        Assert.assertEquals(\"Vivek\", person2.getPersonName());\n\n        Set<HabitatUniMToM> addresses2 = person2.getAddresses();\n        Assert.assertNotNull(addresses2);\n        Assert.assertFalse(addresses2.isEmpty());\n        Assert.assertEquals(2, addresses2.size());\n        HabitatUniMToM address21 = (HabitatUniMToM) addresses2.toArray()[0];\n        assertAddressForPerson2(address21);\n        HabitatUniMToM address22 = (HabitatUniMToM) addresses2.toArray()[1];\n        assertAddressForPerson2(address22);\n    }\n\n    /**\n     * @param address11\n     */\n    private void assertAddressForPerson1(HabitatUniMToM address)\n    {\n        Assert.assertNotNull(address);\n        Assert.assertTrue(\"unimanytomany_a\".equals(address.getAddressId())\n                || \"unimanytomany_b\".equals(address.getAddressId()));\n        Assert.assertTrue(\"AAAAAAAAAAAAA\".equals(address.getStreet()) || \"BBBBBBBBBBBBBBB\".equals(address.getStreet()));\n    }\n\n    /**\n     * @param address12\n     */\n    private void assertAddressForPerson2(HabitatUniMToM address)\n    {\n        Assert.assertNotNull(address);\n\n        Assert.assertTrue(\"unimanytomany_b\".equals(address.getAddressId())\n                || \"unimanytomany_b\".equals(address.getAddressId()) || \"unimanytomany_c\".equals(address.getAddressId()));\n        Assert.assertTrue(\"CCCCCCCCCCC\".equals(address.getStreet()) || \"BBBBBBBBBBBBBBB\".equals(address.getStreet()));\n\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelUniMToM\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelUniMToM\\\" ( \\\"PERSON_ID\\\" text PRIMARY KEY,  \\\"PERSON_NAME\\\" text, \\\"ADDRESS_ID\\\" text)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUniMToM\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PERSONNEL_ADDRESS\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PERSONNEL_ADDRESS\\\" ( \\\"PERSON_ID\\\" text,  \\\"key\\\" text PRIMARY KEY, \\\"ADDRESS_ID\\\" text)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PERSONNEL_ADDRESS\\\" ( \\\"PERSON_ID\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PERSONNEL_ADDRESS\\\" ( \\\"ADDRESS_ID\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatUniMToM\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"HabitatUniMToM\\\" ( \\\"ADDRESS_ID\\\" text PRIMARY KEY,  \\\"STREET\\\" text)\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatUniMToM\\\" ( \\\"STREET\\\")\", keyspaceName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForPERSONNEL()\n     */\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        try\n        {\n            // cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUniMToM (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUniMToM (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(150), ADDRESS_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelUniMToM\");\n            // cli.update(\"DROP TABLE KUNDERATESTS.PersonnelUniMToM\");\n            // cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUniMToM (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n        }\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PERSONNEL_ADDRESS (PERSON_ID VARCHAR(150) , ADDRESS_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PERSONNEL_ADDRESS\");\n            // cli.update(\"DROP TABLE KUNDERATESTS.PERSONNEL_ADDRESS\");\n            // cli.update(\"CREATE TABLE KUNDERATESTS.PERSONNEL_ADDRESS (PERSON_ID VARCHAR(150) , ADDRESS_ID VARCHAR(150))\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForHABITAT()\n     */\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n            // cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUniMToM (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256))\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUniMToM (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256),PERSON_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatUniMToM\");\n            // cli.update(\"DROP TABLE KUNDERATESTS.HabitatUniMToM\");\n            // cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUniMToM (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/MTOBiAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.HabitatBiMTo1;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.PersonnelBiMTo1;\n\npublic class MTOBiAssociationTest extends TwinAssociation\n{\n    /**\n     * Inits the.\n     */\n    @BeforeClass\n    public static void init() throws Exception\n    {\n\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelBiMTo1.class);\n        clazzz.add(HabitatBiMTo1.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal(\"HabitatBiMTo1\",\"PersonnelBiMTo1\");\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        tryOperation(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonnelBiMTo1 person1 = new PersonnelBiMTo1();\n        person1.setPersonId(\"bimanytoone_1\");\n        person1.setPersonName(\"Amresh\");\n\n        PersonnelBiMTo1 person2 = new PersonnelBiMTo1();\n        person2.setPersonId(\"bimanytoone_2\");\n        person2.setPersonName(\"Vivek\");\n\n        HabitatBiMTo1 address = new HabitatBiMTo1();\n        address.setAddressId(\"bimanytoone_b\");\n        address.setStreet(\"AAAAAAAAAAAAA\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        Set<PersonnelBiMTo1> persons = new HashSet<PersonnelBiMTo1>();\n        persons.add(person1);\n        persons.add(person2);\n\n        dao.savePersons(persons);\n        col.add(person1);\n        col.add(person2);\n        col.add(address);\n\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person 1\n        PersonnelBiMTo1 p1 = (PersonnelBiMTo1) dao.findPerson(PersonnelBiMTo1.class, \"bimanytoone_1\");\n        assertPerson1(p1);\n\n        // Find Person 2\n        PersonnelBiMTo1 p2 = (PersonnelBiMTo1) dao.findPerson(PersonnelBiMTo1.class, \"bimanytoone_2\");\n        assertPerson2(p2);\n\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonnelBiMTo1 p = (PersonnelBiMTo1) dao.findPersonByIdColumn(PersonnelBiMTo1.class, \"bimanytoone_1\");\n        assertPerson1(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelBiMTo1> persons = dao.findPersonByName(PersonnelBiMTo1.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonnelBiMTo1 person = persons.get(0);\n        assertPerson1(person);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n    }\n\n    @Override\n    protected void update()\n    {\n    }\n\n    @Override\n    protected void remove()\n    {\n    }\n\n    /**\n     * @param p2\n     */\n    private void assertPerson2(PersonnelBiMTo1 p2)\n    {\n        Assert.assertNotNull(p2);\n        Assert.assertEquals(\"bimanytoone_2\", p2.getPersonId());\n        Assert.assertEquals(\"Vivek\", p2.getPersonName());\n\n        HabitatBiMTo1 add2 = p2.getAddress();\n        Assert.assertNotNull(add2);\n\n        Assert.assertEquals(\"bimanytoone_b\", add2.getAddressId());\n        Set<PersonnelBiMTo1> people2 = add2.getPeople();\n        Assert.assertNotNull(people2);\n        Assert.assertFalse(people2.isEmpty());\n        Assert.assertEquals(2, people2.size());\n    }\n\n    /**\n     * @param p1\n     */\n    private void assertPerson1(PersonnelBiMTo1 p1)\n    {\n        Assert.assertNotNull(p1);\n        Assert.assertEquals(\"bimanytoone_1\", p1.getPersonId());\n        Assert.assertEquals(\"Amresh\", p1.getPersonName());\n\n        HabitatBiMTo1 add = p1.getAddress();\n        Assert.assertNotNull(add);\n\n        Assert.assertEquals(\"bimanytoone_b\", add.getAddressId());\n        Set<PersonnelBiMTo1> people = add.getPeople();\n        Assert.assertNotNull(people);\n        Assert.assertFalse(people.isEmpty());\n        Assert.assertEquals(2, people.size());\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n       // shutDownRdbmsServer();\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelBiMTo1\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelBiMTo1\\\" ( \\\"PERSON_ID\\\" text PRIMARY KEY,  \\\"PERSON_NAME\\\" text, \\\"ADDRESS_ID\\\" text)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBiMTo1\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBiMTo1\\\" ( \\\"ADDRESS_ID\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatBiMTo1\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"HabitatBiMTo1\\\" ( \\\"ADDRESS_ID\\\" text PRIMARY KEY,  \\\"STREET\\\" text)\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatBiMTo1\\\" ( \\\"STREET\\\")\", keyspaceName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForPERSONNEL()\n     */\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBiMTo1 (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(150), ADDRESS_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelBiMTo1\");\n//            cli.update(\"DROP TABLE KUNDERATESTS.PersonnelBiMTo1\");\n//            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBiMTo1 (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(150), ADDRESS_ID VARCHAR(150))\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForHABITAT()\n     */\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n           // cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBiMTo1 (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(150))\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBiMTo1 (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256),PERSON_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatBiMTo1\");\n//            cli.update(\"DROP TABLE KUNDERATESTS.HabitatBiMTo1\");\n//            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBiMTo1 (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(150))\");\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/MTOUniAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.HabitatUniMTo1;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.PersonnelUniMTo1;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class MTOUniAssociationTest extends TwinAssociation\n{\n    /**\n     * Inits the.\n     */\n    @BeforeClass\n    public static void init() throws Exception\n    {\n\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelUniMTo1.class);\n        clazzz.add(HabitatUniMTo1.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal(\"HabitatUniMTo1\", \"PersonnelUniMTo1\");\n    }\n\n    /**\n     * Test CRUD.\n     */\n    @Test\n    public void testCRUD()\n    {\n        tryOperation(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonnelUniMTo1 person1 = new PersonnelUniMTo1();\n        person1.setPersonId(\"unimanytoone_1\");\n        person1.setPersonName(\"Amresh\");\n\n        PersonnelUniMTo1 person2 = new PersonnelUniMTo1();\n        person2.setPersonId(\"unimanytoone_2\");\n        person2.setPersonName(\"Vivek\");\n\n        HabitatUniMTo1 address = new HabitatUniMTo1();\n        address.setAddressId(\"unimanytoone_a\");\n        address.setStreet(\"AAAAAAAAAAAAA\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        Set<PersonnelUniMTo1> persons = new HashSet<PersonnelUniMTo1>();\n        persons.add(person1);\n        persons.add(person2);\n\n        dao.savePersons(persons);\n\n        col.add(person1);\n        col.add(person2);\n        col.add(address);\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person 1\n        PersonnelUniMTo1 p1 = (PersonnelUniMTo1) dao.findPerson(PersonnelUniMTo1.class, \"unimanytoone_1\");\n        assertPerson1(p1);\n\n        // Find Person 2\n        PersonnelUniMTo1 p2 = (PersonnelUniMTo1) dao.findPerson(PersonnelUniMTo1.class, \"unimanytoone_2\");\n        assertPerson2(p2);\n\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonnelUniMTo1 p = (PersonnelUniMTo1) dao.findPersonByIdColumn(PersonnelUniMTo1.class, \"unimanytoone_1\");\n        assertPerson1(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelUniMTo1> persons = dao.findPersonByName(PersonnelUniMTo1.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonnelUniMTo1 person = persons.get(0);\n        assertPerson1(person);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        HabitatUniMTo1 a = (HabitatUniMTo1) dao.findAddressByIdColumn(HabitatUniMTo1.class, \"unimanytoone_a\");\n        assertAddress(a);\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        List<HabitatUniMTo1> adds = dao.findAddressByStreet(HabitatUniMTo1.class, \"AAAAAAAAAAAAA\");\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertTrue(adds.size() == 1);\n\n        assertAddress(adds.get(0));\n    }\n\n    @Override\n    protected void update()\n    {\n        // Find Person 1\n        PersonnelUniMTo1 p1 = (PersonnelUniMTo1) dao.findPerson(PersonnelUniMTo1.class, \"unimanytoone_1\");\n        Assert.assertNotNull(p1);\n        p1.setPersonName(\"Saurabh\");\n        p1.getAddress().setStreet(\"Brand New Street\");\n        dao.merge(p1);\n        PersonnelUniMTo1 p1AfterMerge = (PersonnelUniMTo1) dao.findPerson(PersonnelUniMTo1.class, \"unimanytoone_1\");\n        Assert.assertNotNull(p1AfterMerge);\n        Assert.assertEquals(\"Saurabh\", p1AfterMerge.getPersonName());\n        Assert.assertEquals(\"Brand New Street\", p1AfterMerge.getAddress().getStreet());\n\n        // Find Person 2\n        PersonnelUniMTo1 p2 = (PersonnelUniMTo1) dao.findPerson(PersonnelUniMTo1.class, \"unimanytoone_2\");\n        Assert.assertNotNull(p2);\n        Assert.assertNotNull(p2.getAddress());\n        Assert.assertNotNull(p2.getAddress().getAddressId());\n        p2.setPersonName(\"Prateek\");\n        dao.merge(p2);\n        PersonnelUniMTo1 p2AfterMerge = (PersonnelUniMTo1) dao.findPerson(PersonnelUniMTo1.class, \"unimanytoone_2\");\n        Assert.assertNotNull(p2AfterMerge);\n        Assert.assertEquals(\"Prateek\", p2AfterMerge.getPersonName());\n        Assert.assertEquals(\"Brand New Street\", p2AfterMerge.getAddress().getStreet());\n    }\n\n    @Override\n    protected void remove()\n    {\n        // Remove Person 1\n        dao.remove(\"unimanytoone_1\", PersonnelUniMTo1.class);\n        PersonnelUniMTo1 p1AfterRemoval = (PersonnelUniMTo1) dao.findPerson(PersonnelUniMTo1.class, \"unimanytoone_1\");\n        Assert.assertNull(p1AfterRemoval);\n\n        // Remove Person 2\n        dao.remove(\"unimanytoone_2\", PersonnelUniMTo1.class);\n        PersonnelUniMTo1 p2AfterRemoval = (PersonnelUniMTo1) dao.findPerson(PersonnelUniMTo1.class, \"unimanytoone_2\");\n        Assert.assertNull(p2AfterRemoval);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        // shutDownRdbmsServer();\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * @param p2\n     */\n    private void assertPerson2(PersonnelUniMTo1 p2)\n    {\n        Assert.assertNotNull(p2);\n        Assert.assertEquals(\"unimanytoone_2\", p2.getPersonId());\n        Assert.assertEquals(\"Vivek\", p2.getPersonName());\n\n        HabitatUniMTo1 add2 = p2.getAddress();\n        assertAddress(add2);\n    }\n\n    /**\n     * @param p1\n     */\n    private void assertPerson1(PersonnelUniMTo1 p1)\n    {\n        Assert.assertNotNull(p1);\n        Assert.assertEquals(\"unimanytoone_1\", p1.getPersonId());\n        Assert.assertEquals(\"Amresh\", p1.getPersonName());\n\n        HabitatUniMTo1 add = p1.getAddress();\n        assertAddress(add);\n    }\n\n    /**\n     * @param add2\n     */\n    private void assertAddress(HabitatUniMTo1 add2)\n    {\n        Assert.assertNotNull(add2);\n\n        Assert.assertEquals(\"unimanytoone_a\", add2.getAddressId());\n        Assert.assertEquals(\"AAAAAAAAAAAAA\", add2.getStreet());\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelUniMTo1\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelUniMTo1\\\" ( \\\"PERSON_ID\\\" text PRIMARY KEY,  \\\"PERSON_NAME\\\" text, \\\"ADDRESS_ID\\\" text)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUniMTo1\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUniMTo1\\\" ( \\\"ADDRESS_ID\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatUniMTo1\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"HabitatUniMTo1\\\" ( \\\"ADDRESS_ID\\\" text PRIMARY KEY,  \\\"STREET\\\" text)\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatUniMTo1\\\" ( \\\"STREET\\\")\", keyspaceName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForPERSONNEL()\n     */\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        try\n        {\n            // cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUniMTo1 (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(150))\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUniMTo1 (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(150), ADDRESS_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelUniMTo1\");\n            // cli.update(\"DROP TABLE KUNDERATESTS.PersonnelUniMTo1\");\n            // cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUniMTo1 (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(150))\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForHABITAT()\n     */\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n            // cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUniMTo1 (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256))\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUniMTo1 (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256),PERSON_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatUniMTo1\");\n            // cli.update(\"DROP TABLE KUNDERATESTS.HabitatUniMTo1\");\n            // cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUniMTo1 (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/OTMBiAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.HabitatBi1ToM;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.PersonnelBi1ToM;\n\npublic class OTMBiAssociationTest extends TwinAssociation\n{\n    /**\n     * Inits the.\n     */\n    @BeforeClass\n    public static void init() throws Exception\n    {\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelBi1ToM.class);\n        clazzz.add(HabitatBi1ToM.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal(\"HabitatBi1ToM\", \"PersonnelBi1ToM\");\n    }\n\n    /**\n     * Test insert.\n     */\n    @Test\n    public void testCRUD()\n    {\n        tryOperation(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonnelBi1ToM personnel = new PersonnelBi1ToM();\n        personnel.setPersonId(\"bionetomany_1\");\n        personnel.setPersonName(\"Amresh\");\n\n        Set<HabitatBi1ToM> addresses = new HashSet<HabitatBi1ToM>();\n        HabitatBi1ToM address1 = new HabitatBi1ToM();\n        address1.setAddressId(\"bionetomany_a\");\n        address1.setStreet(\"AAAAAAAAAAAAA\");\n\n        HabitatBi1ToM address2 = new HabitatBi1ToM();\n        address2.setAddressId(\"bionetomany_b\");\n        address2.setStreet(\"BBBBBBBBBBB\");\n\n        addresses.add(address1);\n        addresses.add(address2);\n        personnel.setAddresses(addresses);\n        dao.insert(personnel);\n        col.add(personnel);\n        col.add(address1);\n        col.add(address2);\n\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person\n        PersonnelBi1ToM p = (PersonnelBi1ToM) dao.findPerson(PersonnelBi1ToM.class, \"bionetomany_1\");\n        assertPerson(p);\n\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonnelBi1ToM p = (PersonnelBi1ToM) dao.findPersonByIdColumn(PersonnelBi1ToM.class, \"bionetomany_1\");\n        assertPerson(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelBi1ToM> persons = dao.findPersonByName(PersonnelBi1ToM.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonnelBi1ToM person = persons.get(0);\n        assertPerson(person);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n    }\n\n    @Override\n    protected void update()\n    {\n        // Find Person\n        PersonnelBi1ToM p = (PersonnelBi1ToM) dao.findPerson(PersonnelBi1ToM.class, \"bionetomany_1\");\n        assertPerson(p);\n\n        p.setPersonName(\"Saurabh\");\n        for (HabitatBi1ToM address : p.getAddresses())\n        {\n            address.setStreet(\"Brand New Street\");\n        }\n        dao.merge(p);\n        PersonnelBi1ToM pAfterMerge = (PersonnelBi1ToM) dao.findPerson(PersonnelBi1ToM.class, \"bionetomany_1\");\n\n        assertPersonAfterUpdate(pAfterMerge);\n    }\n\n    @Override\n    protected void remove()\n    {\n        // Find Person\n        PersonnelBi1ToM p = (PersonnelBi1ToM) dao.findPerson(PersonnelBi1ToM.class, \"bionetomany_1\");\n        assertPersonAfterUpdate(p);\n\n        dao.remove(\"bionetomany_1\", PersonnelBi1ToM.class);\n        PersonnelBi1ToM pAfterRemoval = (PersonnelBi1ToM) dao.findPerson(PersonnelBi1ToM.class, \"bionetomany_1\");\n        Assert.assertNull(pAfterRemoval);\n    }\n\n    private void assertPerson(PersonnelBi1ToM p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"bionetomany_1\", p.getPersonId());\n        Assert.assertEquals(\"Amresh\", p.getPersonName());\n\n        Set<HabitatBi1ToM> adds = p.getAddresses();\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertEquals(2, adds.size());\n\n        for (HabitatBi1ToM address : adds)\n        {\n            Assert.assertNotNull(address);\n            PersonnelBi1ToM person = address.getPerson();\n            Assert.assertNotNull(person);\n            Assert.assertEquals(p.getPersonId(), person.getPersonId());\n            Assert.assertEquals(p.getPersonName(), person.getPersonName());\n            Assert.assertNotNull(person.getAddresses());\n            Assert.assertFalse(person.getAddresses().isEmpty());\n            Assert.assertEquals(2, person.getAddresses().size());\n        }\n    }\n\n    private void assertPersonAfterUpdate(PersonnelBi1ToM p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"bionetomany_1\", p.getPersonId());\n        Assert.assertEquals(\"Saurabh\", p.getPersonName());\n\n        Set<HabitatBi1ToM> adds = p.getAddresses();\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertEquals(2, adds.size());\n\n        for (HabitatBi1ToM address : adds)\n        {\n            Assert.assertNotNull(address);\n            Assert.assertEquals(\"Brand New Street\", address.getStreet());\n            PersonnelBi1ToM person = address.getPerson();\n            Assert.assertNotNull(person);\n            Assert.assertEquals(p.getPersonId(), person.getPersonId());\n            Assert.assertEquals(p.getPersonName(), person.getPersonName());\n            Assert.assertNotNull(person.getAddresses());\n            Assert.assertFalse(person.getAddresses().isEmpty());\n            Assert.assertEquals(2, person.getAddresses().size());\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        // shutDownRdbmsServer();\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelBi1ToM\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"PersonnelBi1ToM\\\" ( \\\"PERSON_ID\\\" text PRIMARY KEY,  \\\"PERSON_NAME\\\" text)\",\n                keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBi1ToM\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatBi1ToM\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"HabitatBi1ToM\\\" ( \\\"ADDRESS_ID\\\" text PRIMARY KEY,  \\\"STREET\\\" text, \\\"PERSON_ID\\\" text )\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatBi1ToM\\\" ( \\\"STREET\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatBi1ToM\\\" ( \\\"PERSON_ID\\\")\", keyspaceName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForPERSONNEL()\n     */\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        try\n        {\n            // cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBi1ToM (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBi1ToM (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(150), ADDRESS_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelBi1ToM\");\n            // cli.update(\"DROP TABLE KUNDERATESTS.PersonnelBi1ToM\");\n            // cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBi1ToM (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForHABITAT()\n     */\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBi1ToM (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256),PERSON_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatBi1ToM\");\n            // cli.update(\"DROP TABLE KUNDERATESTS.HabitatBi1ToM\");\n            // cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBi1ToM (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256),PERSON_ID VARCHAR(150))\");\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/OTMUniAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.HabitatUni1ToM;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.PersonnelUni1ToM;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class OTMUniAssociationTest extends TwinAssociation\n{\n    /**\n     * Inits the.\n     */\n    @BeforeClass\n    public static void init() throws Exception\n    {\n\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelUni1ToM.class);\n        clazzz.add(HabitatUni1ToM.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal(\"HabitatUni1ToM\", \"PersonnelUni1ToM\");\n    }\n\n    /**\n     * Test insert.\n     */\n    @Test\n    public void testCRUD()\n    {\n        tryOperation(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void insert()\n    {\n        // Save Person\n        PersonnelUni1ToM personnel = new PersonnelUni1ToM();\n        personnel.setPersonId(\"unionetomany_1\");\n        personnel.setPersonName(\"Amresh\");\n\n        Set<HabitatUni1ToM> addresses = new HashSet<HabitatUni1ToM>();\n        HabitatUni1ToM address1 = new HabitatUni1ToM();\n        address1.setAddressId(\"unionetomany_a\");\n        address1.setStreet(\"AAAAAAAAAAAAA\");\n\n        HabitatUni1ToM address2 = new HabitatUni1ToM();\n        address2.setAddressId(\"unionetomany_b\");\n        address2.setStreet(\"BBBBBBBBBBB\");\n\n        addresses.add(address1);\n        addresses.add(address2);\n        personnel.setAddresses(addresses);\n        dao.insert(personnel);\n        col.add(personnel);\n        col.add(address1);\n        col.add(address2);\n\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person\n        PersonnelUni1ToM p = (PersonnelUni1ToM) dao.findPerson(PersonnelUni1ToM.class, \"unionetomany_1\");\n        assertPerson(p);\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonnelUni1ToM p = (PersonnelUni1ToM) dao.findPersonByIdColumn(PersonnelUni1ToM.class, \"unionetomany_1\");\n        assertPerson(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelUni1ToM> persons = dao.findPersonByName(PersonnelUni1ToM.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonnelUni1ToM person = persons.get(0);\n        assertPerson(person);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        HabitatUni1ToM a = (HabitatUni1ToM) dao.findAddressByIdColumn(HabitatUni1ToM.class, \"unionetomany_a\");\n        Assert.assertNotNull(a);\n        Assert.assertEquals(\"unionetomany_a\", a.getAddressId());\n        Assert.assertEquals(\"AAAAAAAAAAAAA\", a.getStreet());\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        List<HabitatUni1ToM> adds = dao.findAddressByStreet(HabitatUni1ToM.class, \"AAAAAAAAAAAAA\");\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertTrue(adds.size() == 1);\n\n        HabitatUni1ToM a = adds.get(0);\n        Assert.assertNotNull(a);\n        Assert.assertEquals(\"unionetomany_a\", a.getAddressId());\n        Assert.assertEquals(\"AAAAAAAAAAAAA\", a.getStreet());\n    }\n\n    @Override\n    protected void update()\n    {\n        try\n        {\n            PersonnelUni1ToM p = (PersonnelUni1ToM) dao.findPerson(PersonnelUni1ToM.class, \"unionetomany_1\");\n            Assert.assertNotNull(p);\n            Assert.assertEquals(2, p.getAddresses().size());\n            p.setPersonName(\"Saurabh\");\n\n            for (HabitatUni1ToM address : p.getAddresses())\n            {\n                address.setStreet(\"Brand New Street\");\n            }\n            dao.merge(p);\n            assertPersonAfterUpdate();\n        }\n        catch (Exception e)\n        {\n\n            Assert.fail();\n        }\n    }\n\n    @Override\n    protected void remove()\n    {\n        try\n        {\n            dao.remove(\"unionetomany_1\", PersonnelUni1ToM.class);\n            PersonnelUni1ToM pAfterRemoval = (PersonnelUni1ToM) dao\n                    .findPerson(PersonnelUni1ToM.class, \"unionetomany_1\");\n            Assert.assertNull(pAfterRemoval);\n\n        }\n        catch (Exception e)\n        {\n\n            Assert.fail();\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        shutDownRdbmsServer();\n        // shutDownRdbmsServer();\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * @param p\n     */\n    private void assertPerson(PersonnelUni1ToM p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"unionetomany_1\", p.getPersonId());\n        Assert.assertEquals(\"Amresh\", p.getPersonName());\n\n        Set<HabitatUni1ToM> adds = p.getAddresses();\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertEquals(2, adds.size());\n\n        for (HabitatUni1ToM address : adds)\n        {\n            Assert.assertNotNull(address.getStreet());\n        }\n    }\n\n    /**\n     * \n     */\n    private void assertPersonAfterUpdate()\n    {\n        PersonnelUni1ToM pAfterMerge = (PersonnelUni1ToM) dao.findPerson(PersonnelUni1ToM.class, \"unionetomany_1\");\n        Assert.assertNotNull(pAfterMerge);\n        Assert.assertEquals(\"Saurabh\", pAfterMerge.getPersonName());\n        Assert.assertEquals(2, pAfterMerge.getAddresses().size());\n\n        for (HabitatUni1ToM address : pAfterMerge.getAddresses())\n        {\n            Assert.assertEquals(\"Brand New Street\", address.getStreet());\n        }\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelUni1ToM\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"PersonnelUni1ToM\\\" ( \\\"PERSON_ID\\\" text PRIMARY KEY,  \\\"PERSON_NAME\\\" text)\",\n                keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUni1ToM\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatUni1ToM\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"HabitatUni1ToM\\\" ( \\\"ADDRESS_ID\\\" text PRIMARY KEY,  \\\"STREET\\\" text, \\\"PERSON_ID\\\" text )\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatUni1ToM\\\" ( \\\"STREET\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatUni1ToM\\\" ( \\\"PERSON_ID\\\")\", keyspaceName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForPERSONNEL()\n     */\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        try\n        {\n            // cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUni1ToM (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(250))\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUni1ToM (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(150), ADDRESS_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelUni1ToM\");\n            // cli.update(\"DROP TABLE KUNDERATESTS.PersonnelUni1ToM\");\n            // cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUni1ToM (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(250))\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForHABITAT()\n     */\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUni1ToM (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(250),PERSON_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatUni1ToM\");\n            // cli.update(\"DROP TABLE KUNDERATESTS.HabitatUni1ToM\");\n            // cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUni1ToM (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(250),PERSON_ID VARCHAR(150))\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/OTOBiAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.HabitatBi1To1FK;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.PersonnelBi1To1FK;\n\npublic class OTOBiAssociationTest extends TwinAssociation\n{\n    /**\n     * Inits the.\n     */\n    @BeforeClass\n    public static void init() throws Exception\n    {\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelBi1To1FK.class);\n        clazzz.add(HabitatBi1To1FK.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        setUpInternal(\"HabitatBi1To1FK\",\"PersonnelBi1To1FK\");\n    }\n\n    /**\n     * Test CRUD\n     */\n    @Test\n    public void testCRUD()\n    {\n        tryOperation(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonnelBi1To1FK person = new PersonnelBi1To1FK();\n        person.setPersonId(\"bionetoonefk_1\");\n        person.setPersonName(\"Amresh\");\n\n        HabitatBi1To1FK address = new HabitatBi1To1FK();\n        address.setAddressId(\"bionetoonefk_a\");\n        address.setStreet(\"123, New street\");\n        person.setAddress(address);\n        address.setPerson(person);\n\n        dao.insert(person);\n        col.add(person);\n        col.add(address);\n\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person\n        PersonnelBi1To1FK p = (PersonnelBi1To1FK) dao.findPerson(PersonnelBi1To1FK.class, \"bionetoonefk_1\");\n        assertPersonnel(p);       \n \n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonnelBi1To1FK p = (PersonnelBi1To1FK) dao.findPersonByIdColumn(PersonnelBi1To1FK.class, \"bionetoonefk_1\");\n        assertPersonnel(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelBi1To1FK> persons = dao.findPersonByName(PersonnelBi1To1FK.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        assertPersonnel(persons.get(0));\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        /*\n         * HabitatBi1To1FK a = (HabitatBi1To1FK)\n         * dao.findAddressByIdColumn(HabitatBi1To1FK.class, \"bionetoonefk_a\");\n         * assertAddress(a);\n         */\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        /*\n         * List<HabitatBi1To1FK> adds =\n         * dao.findAddressByStreet(HabitatBi1To1FK.class, \"123, New street\");\n         * Assert.assertNotNull(adds); Assert.assertFalse(adds.isEmpty());\n         * Assert.assertTrue(adds.size() == 1);\n         * \n         * assertAddress(adds.get(0));\n         */\n    }\n\n    @Override\n    protected void update()\n    {\n        try\n        {\n            PersonnelBi1To1FK p = (PersonnelBi1To1FK) dao.findPerson(PersonnelBi1To1FK.class, \"bionetoonefk_1\");\n            assertPersonnel(p);\n\n            dao.merge(p); // This merge operation should do nothing since\n                          // nothing has changed\n\n            p = (PersonnelBi1To1FK) dao.findPerson(PersonnelBi1To1FK.class, \"bionetoonefk_1\");\n            assertPersonnel(p);\n\n            p.setPersonName(\"Saurabh\");\n            p.getAddress().setStreet(\"Brand New Street\");\n            dao.merge(p);\n\n            PersonnelBi1To1FK pAfterMerge = (PersonnelBi1To1FK) dao.findPerson(PersonnelBi1To1FK.class,\n                    \"bionetoonefk_1\");\n            assertPersonnelAfterUpdate(pAfterMerge);\n\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail();\n        }\n    }\n\n    @Override\n    protected void remove()\n    {\n        PersonnelBi1To1FK p = (PersonnelBi1To1FK) dao.findPerson(PersonnelBi1To1FK.class, \"bionetoonefk_1\");\n        assertPersonnelAfterUpdate(p);\n\n        dao.remove(\"bionetoonefk_1\", PersonnelBi1To1FK.class);\n\n        PersonnelBi1To1FK pAfterRemoval = (PersonnelBi1To1FK) dao.findPerson(PersonnelBi1To1FK.class, \"bionetoonefk_1\");\n        Assert.assertNull(pAfterRemoval);\n    }\n\n    private void assertPersonnel(PersonnelBi1To1FK p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(\"bionetoonefk_1\", p.getPersonId());\n        Assert.assertEquals(\"Amresh\", p.getPersonName());\n\n        HabitatBi1To1FK address = p.getAddress();       \n        assertAddress(address);\n    }\n\n    /**\n     * @param address\n     */\n    private void assertAddress(HabitatBi1To1FK address)\n    {\n        Assert.assertNotNull(address);\n        Assert.assertEquals(\"bionetoonefk_a\", address.getAddressId());\n        Assert.assertEquals(\"123, New street\", address.getStreet());\n\n        PersonnelBi1To1FK pp = address.getPerson();\n        Assert.assertNotNull(pp);\n        Assert.assertEquals(\"bionetoonefk_1\", pp.getPersonId());\n        Assert.assertEquals(\"Amresh\", pp.getPersonName());\n    }\n\n    private void assertPersonnelAfterUpdate(PersonnelBi1To1FK pAfterMerge)\n    {\n        Assert.assertNotNull(pAfterMerge);\n        Assert.assertEquals(\"Saurabh\", pAfterMerge.getPersonName());\n        HabitatBi1To1FK addressAfterMerge = pAfterMerge.getAddress();\n        Assert.assertNotNull(addressAfterMerge);\n        Assert.assertEquals(\"Brand New Street\", addressAfterMerge.getStreet());\n\n        PersonnelBi1To1FK pp = addressAfterMerge.getPerson();\n        Assert.assertNotNull(pp);\n        Assert.assertEquals(\"bionetoonefk_1\", pp.getPersonId());\n        Assert.assertEquals(\"Saurabh\", pp.getPersonName());\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n       // tearDownInternal(ALL_PUs_UNDER_TEST);\n       // shutDownRdbmsServer();\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelBi1To1FK\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelBi1To1FK\\\" ( \\\"PERSON_ID\\\" text PRIMARY KEY,  \\\"PERSON_NAME\\\" text, \\\"ADDRESS_ID\\\" text)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBi1To1FK\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBi1To1FK\\\" ( \\\"ADDRESS_ID\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatBi1To1FK\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"HabitatBi1To1FK\\\" ( \\\"ADDRESS_ID\\\" text PRIMARY KEY,  \\\"STREET\\\" text)\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatBi1To1FK\\\" ( \\\"STREET\\\")\", keyspaceName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForPERSONNEL()\n     */\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBi1To1FK (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelBi1To1FK\");\n//            cli.update(\"DROP TABLE KUNDERATESTS.PersonnelBi1To1FK\");\n//            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBi1To1FK (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(150))\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForHABITAT()\n     */\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n          //  cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBi1To1FK (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256))\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBi1To1FK (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(250),PERSON_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatBi1To1FK\");\n//            cli.update(\"DROP TABLE KUNDERATESTS.ADDRESS\");\n//            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBi1To1FK (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/OTOUniAssociationTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.HabitatUni1To1FK;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.entities.PersonnelUni1To1FK;\n\n/**\n * One to one association test for {@see} cassandra, mongodb,HBase and RDBMS\n * combination.\n * \n * Script to create super column family\n * \n * Note: As PersonnelUni1To1FK is holding embedded collection so to test as a\n * super col family. create super column family as given below: create column\n * family PersonnelUni1To1FK with comparator=UTF8Type and\n * default_validation_class=UTF8Type and key_validation_class=UTF8Type and\n * column_type=Super;\n * \n * \n * Note: To create as column family PersonnelUni1To1FK use as given below: create column\n * family PersonnelUni1To1FK with comparator=UTF8Type and column_metadata=[{column_name:\n * PERSON_NAME, validation_class: UTF8Type, index_type: KEYS}, {column_name:\n * AGE, validation_class: IntegerType, index_type: KEYS}]; PersonnelUni1ToM\n * \n * @author vivek.mishra\n */\n\npublic class OTOUniAssociationTest extends TwinAssociation\n{\n    /**\n     * Inits the.\n     */\n    @BeforeClass\n    public static void init() throws Exception\n    {\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelUni1To1FK.class);\n        clazzz.add(HabitatUni1To1FK.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal(\"HabitatUni1To1FK\",\"PersonnelUni1To1FK\");\n    }\n\n    /**\n     * Test CRUD\n     */\n    @Test\n    public void testCRUD()\n    {\n        try\n        {\n            tryOperation(ALL_PUs_UNDER_TEST);\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n    }\n\n    protected void insert()\n    {\n        try\n        {\n            PersonnelUni1To1FK person = new PersonnelUni1To1FK();\n            HabitatUni1To1FK address = new HabitatUni1To1FK();\n            person.setPersonId(\"unionetoonefk_1\");\n            person.setPersonName(\"Amresh\");\n            address.setAddressId(\"unionetoonefk_a\");\n            address.setStreet(\"123, New street\");\n            person.setAddress(address);\n            dao.insert(person);\n            col.add(person);\n            col.add(address);\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n    }\n\n    protected void find()\n    {\n        // Find Person\n        try\n        {\n            PersonnelUni1To1FK p = (PersonnelUni1To1FK) dao.findPerson(PersonnelUni1To1FK.class, \"unionetoonefk_1\");\n            assertPersonBeforeUpdate(p);\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonnelUni1To1FK p = (PersonnelUni1To1FK) dao.findPersonByIdColumn(PersonnelUni1To1FK.class,\n                \"unionetoonefk_1\");\n        assertPersonBeforeUpdate(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelUni1To1FK> persons = dao.findPersonByName(PersonnelUni1To1FK.class, \"Amresh\");\n        assertPersons(persons);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        HabitatUni1To1FK a = (HabitatUni1To1FK) dao.findAddressByIdColumn(HabitatUni1To1FK.class, \"unionetoonefk_a\");\n        assertAddressBeforeUpdate(a);\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        List<HabitatUni1To1FK> adds = dao.findAddressByStreet(HabitatUni1To1FK.class, \"123, New street\");\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertTrue(adds.size() == 1);\n\n        assertAddressBeforeUpdate(adds.get(0));\n    }\n\n    protected void update()\n    {\n        try\n        {\n            PersonnelUni1To1FK p = (PersonnelUni1To1FK) dao.findPerson(PersonnelUni1To1FK.class, \"unionetoonefk_1\");\n            Assert.assertNotNull(p);\n\n            // dao.merge(p); //This merge operation should do nothing since\n            // nothing has changed\n\n            // p = (PersonnelUni1To1FK) dao.findPerson(PersonnelUni1To1FK.class,\n            // \"unionetoonefk_1\");\n            p.setPersonName(\"Saurabh\");\n            HabitatUni1To1FK address = p.getAddress();\n            address.setStreet(\"Brand New Street\");\n            p.setAddress(address);\n            dao.merge(p);\n\n            PersonnelUni1To1FK pAfterMerge = (PersonnelUni1To1FK) dao.findPerson(PersonnelUni1To1FK.class,\n                    \"unionetoonefk_1\");\n            assertPersonAfterUpdate(pAfterMerge);\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n    }\n\n    protected void remove()\n    {\n        try\n        {\n            PersonnelUni1To1FK p = (PersonnelUni1To1FK) dao.findPerson(PersonnelUni1To1FK.class, \"unionetoonefk_1\");\n            Assert.assertNotNull(p);\n            dao.remove(\"unionetoonefk_1\", PersonnelUni1To1FK.class);\n\n            PersonnelUni1To1FK pAfterRemoval = (PersonnelUni1To1FK) dao.findPerson(PersonnelUni1To1FK.class,\n                    \"unionetoonefk_1\");\n            Assert.assertNull(pAfterRemoval);\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n      //  shutDownRdbmsServer();\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n\n    }\n\n    @Override\n    public void loadDataForPERSONNEL() throws InvalidRequestException, TException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelUni1To1FK\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelUni1To1FK\\\" ( \\\"PERSON_ID\\\" text PRIMARY KEY,  \\\"PERSON_NAME\\\" text, \\\"ADDRESS_ID\\\" text)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUni1To1FK\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUni1To1FK\\\" ( \\\"ADDRESS_ID\\\")\", keyspaceName);\n    }\n\n    @Override\n    public void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatUni1To1FK\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"HabitatUni1To1FK\\\" ( \\\"ADDRESS_ID\\\" text PRIMARY KEY,  \\\"STREET\\\" text)\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatUni1To1FK\\\" ( \\\"STREET\\\")\", keyspaceName);\n    }\n\n    /**\n     * @param p\n     */\n    private void assertPersonBeforeUpdate(PersonnelUni1To1FK p)\n    {\n        Assert.assertNotNull(p);\n\n        Assert.assertEquals(\"unionetoonefk_1\", p.getPersonId());\n        Assert.assertEquals(\"Amresh\", p.getPersonName());\n\n        assertAddressBeforeUpdate(p.getAddress());\n    }\n\n    /**\n     * @param p\n     */\n    private void assertAddressBeforeUpdate(HabitatUni1To1FK add)\n    {\n        Assert.assertNotNull(add);\n\n        String addressId = add.getAddressId();\n        String street = add.getStreet();\n\n        Assert.assertNotNull(addressId);\n        Assert.assertEquals(\"unionetoonefk_a\", addressId);\n        Assert.assertEquals(\"123, New street\", street);\n    }\n\n    /**\n     * @param pAfterMerge\n     */\n    private void assertPersonAfterUpdate(PersonnelUni1To1FK pAfterMerge)\n    {\n        Assert.assertNotNull(pAfterMerge);\n        Assert.assertEquals(\"Saurabh\", pAfterMerge.getPersonName());\n        HabitatUni1To1FK addressAfterMerge = pAfterMerge.getAddress();\n        Assert.assertNotNull(addressAfterMerge);\n        Assert.assertEquals(\"Brand New Street\", addressAfterMerge.getStreet());\n    }\n\n    /**\n     * @param persons\n     */\n    private void assertPersons(List<PersonnelUni1To1FK> persons)\n    {\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonnelUni1To1FK person = persons.get(0);\n        assertPersonBeforeUpdate(person);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForPERSONNEL()\n     */\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        // cli.update(\"USE testdb\");\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUni1To1FK (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelUni1To1FK\");\n//            cli.update(\"DROP TABLE KUNDERATESTS.PersonnelUni1To1FK\");\n//            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUni1To1FK (PERSON_ID VARCHAR(150) PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(150))\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForHABITAT()\n     */\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n            //cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUni1To1FK (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256))\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUni1To1FK (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(250),PERSON_ID VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatUni1To1FK\");\n//            cli.update(\"DROP TABLE KUNDERATESTS.HabitatUni1To1FK\");\n//            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUni1To1FK (ADDRESS_ID VARCHAR(150) PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/TwinAssociation.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress;\n\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.metamodel.EntityType;\nimport javax.persistence.metamodel.Metamodel;\n\nimport org.junit.Assert;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.kundera.metadata.model.MetamodelImpl;\n\n/**\n * The Class TwinAssociation.\n * \n * @author vivek.mishra\n */\npublic abstract class TwinAssociation extends AssociationBase\n{\n\n    /** The combinations. */\n    protected static List<Map<Class, String>> combinations = new ArrayList<Map<Class, String>>();\n\n    protected static List<String> traversedPus = new ArrayList<String>();\n\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(TwinAssociation.class);\n\n    /**\n     * Inits the.\n     * \n     * @param classes\n     *            the classes\n     * @param persistenceUnits\n     *            the persistence units\n     */\n    public static void init(List<Class> classes, String... persistenceUnits) throws Exception\n    {\n        \n        combinations = null;\n        combinations = new ArrayList<Map<Class, String>>();\n\n        /*\n         * if (RUN_IN_EMBEDDED_MODE) { CassandraCli.cassandraSetUp();\n         * \n         * }\n         * \n         * if (AUTO_MANAGE_SCHEMA) { CassandraCli.initClient(); }\n         */\n\n        // list of PUS with class.\n        Map<Class, String> puClazzMapper = null;\n\n        for (String pu : persistenceUnits)\n        {\n            for (String p : persistenceUnits)\n            {\n                puClazzMapper = new HashMap<Class, String>();\n                puClazzMapper.put(classes.get(0), pu);\n\n                for (Class c : classes.subList(1, classes.size()))\n                {\n                    puClazzMapper.put(c, p);\n                }\n                combinations.add(puClazzMapper);\n            }\n        }\n    }\n\n    /**\n     * Try operation.\n     * \n     * @param ALL_PUs_UNDER_TEST\n     */\n    protected void tryOperation(String[] ALL_PUs_UNDER_TEST)\n    {\n        try\n        {\n            Metamodel metaModel = null;\n            for (int i = 0; i < ALL_PUs_UNDER_TEST.length; i++)\n            {\n                metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(ALL_PUs_UNDER_TEST[i]);\n\n\n                    \n                    for (int i1 = 0; i1 < ALL_PUs_UNDER_TEST.length; i1++)\n                    {\n                        if (i != i1)\n                        {\n                            traversedPus.add(ALL_PUs_UNDER_TEST[i1]);\n\n                            Map<Class<?>, EntityType<?>> original = getManagedTypes((MetamodelImpl) metaModel);\n\n                            Metamodel m = kunderaMetadata.getApplicationMetadata().getMetamodel(\n                                    ALL_PUs_UNDER_TEST[i1]);\n                            Map<Class<?>, EntityType<?>> copy = getManagedTypes((MetamodelImpl) m);\n                            if (original != null && copy != null)\n                            {\n                                original.putAll(copy);\n                            }\n                        }\n                    }\n            \n            }\n\n            for (Map<Class, String> c : combinations)\n            {\n\n                switchPersistenceUnits(c);\n                insert();\n                // em.clear();\n                find();\n                findPersonByIdColumn();\n                findPersonByName();\n                findAddressByIdColumn();\n                findAddressByStreet();\n                update();\n                remove();\n                tearDownInternal(ALL_PUs_UNDER_TEST);\n            }\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error during switching persistence unit\", e);\n            Assert.fail(\"Failure caused by:\" + e);\n        }\n    }\n\n    /** Insert person with address */\n    protected abstract void insert();\n\n    /** Find person by ID */\n    protected abstract void find();\n\n    /** Find person by ID using query */\n    protected abstract void findPersonByIdColumn();\n\n    /** Find person by name using query */\n    protected abstract void findPersonByName();\n\n    /** Find Address by ID using query */\n    protected abstract void findAddressByIdColumn();\n\n    /** Find Address by street using query */\n    protected abstract void findAddressByStreet();\n\n    /** Update Person */\n    protected abstract void update();\n\n    /** Remove Person */\n    protected abstract void remove();\n\n    private Map<Class<?>, EntityType<?>> getManagedTypes(MetamodelImpl metaModel)\n    {\n        try\n        {\n            Field managedTypesFields = null;\n            if (metaModel != null)\n                managedTypesFields = metaModel.getClass().getDeclaredField(\"entityTypes\");\n            if (managedTypesFields != null && !managedTypesFields.isAccessible())\n            {\n                managedTypesFields.setAccessible(true);\n\n                return ((Map<Class<?>, EntityType<?>>) managedTypesFields.get(metaModel));\n            }\n        }\n        catch (SecurityException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (NoSuchFieldException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalArgumentException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        catch (IllegalAccessException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n        return null;\n    }\n}"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/MTMBiAssociationIntTest.java",
    "content": "/*******************************************************************************\n* * Copyright 2012 Impetus Infotech.\n* *\n* * Licensed under the Apache License, Version 2.0 (the \"License\");\n* * you may not use this file except in compliance with the License.\n* * You may obtain a copy of the License at\n* *\n* * http://www.apache.org/licenses/LICENSE-2.0\n* *\n* * Unless required by applicable law or agreed to in writing, software\n* * distributed under the License is distributed on an \"AS IS\" BASIS,\n* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* * See the License for the specific language governing permissions and\n* * limitations under the License.\n******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.TwinAssociation;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.HabitatBiMToMShort;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.PersonnelBiMToMInt;\n\npublic class MTMBiAssociationIntTest extends TwinAssociation\n\n{\n    public static final String[] ALL_PUs_UNDER_TEST = new String[] { \"addCassandra\", \"addMongo\", \n            \"addCouchdb\" };\n\n    private short addressID1 = Short.MAX_VALUE;\n\n    private short addressID2 = Short.MIN_VALUE;\n\n    private short addressID3 = (short) 3;\n\n    /**\n* Inits the.\n*/\n    @BeforeClass\n    public static void init() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            CassandraCli.cassandraSetUp();\n\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            CassandraCli.initClient();\n        }\n\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelBiMToMInt.class);\n        clazzz.add(HabitatBiMToMShort.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n* Sets the up.\n*\n* @throws Exception\n* the exception\n*/\n    @Before\n    public void setUp() throws Exception\n    {\n        // propertyMap.put(CassandraConstants.CQL_VERSION,\n        // CassandraConstants.CQL_VERSION_2_0);\n        setUpInternal(\"HabitatBiMToMShort\", \"PersonnelBiMToMInt\", \"PersonnelBiMToMInt_HabitatBiMToMShort\");\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        tryOperation(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonnelBiMToMInt person1 = new PersonnelBiMToMInt();\n        person1.setPersonId(1234);\n        person1.setPersonName(\"Amresh\");\n\n        PersonnelBiMToMInt person2 = new PersonnelBiMToMInt();\n        person2.setPersonId(1235);\n        person2.setPersonName(\"Vivek\");\n\n        HabitatBiMToMShort address1 = new HabitatBiMToMShort();\n        address1.setAddressId(addressID1);\n        address1.setStreet(\"AAAAAAAAAAAAA\");\n\n        HabitatBiMToMShort address2 = new HabitatBiMToMShort();\n        address2.setAddressId(addressID2);\n        address2.setStreet(\"BBBBBBBBBBBBBBB\");\n\n        HabitatBiMToMShort address3 = new HabitatBiMToMShort();\n        address3.setAddressId(addressID3);\n        address3.setStreet(\"CCCCCCCCCCC\");\n\n        Set<HabitatBiMToMShort> person1Addresses = new HashSet<HabitatBiMToMShort>();\n        Set<HabitatBiMToMShort> person2Addresses = new HashSet<HabitatBiMToMShort>();\n\n        person1Addresses.add(address1);\n        person1Addresses.add(address2);\n\n        person2Addresses.add(address2);\n        person2Addresses.add(address3);\n\n        person1.setAddresses(person1Addresses);\n        person2.setAddresses(person2Addresses);\n\n        Set<PersonnelBiMToMInt> persons = new HashSet<PersonnelBiMToMInt>();\n        persons.add(person1);\n        persons.add(person2);\n\n        dao.savePersons(persons);\n\n        col.add(person1);\n        col.add(person2);\n        col.add(address1);\n        col.add(address2);\n        col.add(address3);\n\n    }\n\n    @Override\n    protected void find()\n    {\n        PersonnelBiMToMInt person1 = (PersonnelBiMToMInt) dao.findPerson(PersonnelBiMToMInt.class, 1234);\n        assertPerson1(person1);\n\n        PersonnelBiMToMInt person2 = (PersonnelBiMToMInt) dao.findPerson(PersonnelBiMToMInt.class, 1235);\n        assertPerson2(person2);\n\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        // Find Person 1\n        PersonnelBiMToMInt p1 = (PersonnelBiMToMInt) dao.findPersonByIdColumn(PersonnelBiMToMInt.class, 1234);\n        assertPerson1(p1);\n\n        // Find Person 2\n        PersonnelBiMToMInt p2 = (PersonnelBiMToMInt) dao.findPersonByIdColumn(PersonnelBiMToMInt.class, 1235);\n        assertPerson2(p2);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelBiMToMInt> persons = dao.findPersonByName(PersonnelBiMToMInt.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        assertPerson1(persons.get(0));\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n    }\n\n    @Override\n    protected void update()\n    {\n    }\n\n    @Override\n    protected void remove()\n    {\n    }\n\n    /**\n* Tear down.\n*\n* @throws Exception\n* the exception\n*/\n    @After\n    public void tearDown() throws Exception\n    {\n        // shutDownRdbmsServer();\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n* @param person2\n*/\n    private void assertPerson2(PersonnelBiMToMInt person2)\n    {\n        Assert.assertNotNull(person2);\n\n        Assert.assertEquals(1235, person2.getPersonId());\n        Assert.assertEquals(\"Vivek\", person2.getPersonName());\n\n        Set<HabitatBiMToMShort> addresses2 = person2.getAddresses();\n        Assert.assertNotNull(addresses2);\n        Assert.assertFalse(addresses2.isEmpty());\n        Assert.assertEquals(2, addresses2.size());\n        HabitatBiMToMShort address21 = (HabitatBiMToMShort) addresses2.toArray()[0];\n        Assert.assertNotNull(address21);\n        HabitatBiMToMShort address22 = (HabitatBiMToMShort) addresses2.toArray()[1];\n        Assert.assertNotNull(address22);\n    }\n\n    /**\n* @param person1\n*/\n    private void assertPerson1(PersonnelBiMToMInt person1)\n    {\n        Assert.assertNotNull(person1);\n        Assert.assertEquals(1234, person1.getPersonId());\n        Assert.assertEquals(\"Amresh\", person1.getPersonName());\n\n        Set<HabitatBiMToMShort> addresses1 = person1.getAddresses();\n        Assert.assertNotNull(addresses1);\n        Assert.assertFalse(addresses1.isEmpty());\n        Assert.assertEquals(2, addresses1.size());\n        HabitatBiMToMShort address11 = (HabitatBiMToMShort) addresses1.toArray()[0];\n        Assert.assertNotNull(address11);\n        HabitatBiMToMShort address12 = (HabitatBiMToMShort) addresses1.toArray()[1];\n        Assert.assertNotNull(address12);\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelBiMToMInt\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelBiMToMInt\\\" ( \\\"PERSON_ID\\\" int PRIMARY KEY,  \\\"PERSON_NAME\\\" text, \\\"ADDRESS_ID\\\" text)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBiMToMInt\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelBiMToMInt_HabitatBiMToMShort\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelBiMToMInt_HabitatBiMToMShort\\\" ( \\\"PERSON_ID\\\" int,  \\\"key\\\" text PRIMARY KEY, \\\"ADDRESS_ID\\\" int)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBiMToMInt_HabitatBiMToMShort\\\" ( \\\"PERSON_ID\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBiMToMInt_HabitatBiMToMShort\\\" ( \\\"ADDRESS_ID\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatBiMToMShort\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"HabitatBiMToMShort\\\" ( \\\"ADDRESS_ID\\\" int PRIMARY KEY,  \\\"STREET\\\" text)\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatBiMToMShort\\\" ( \\\"STREET\\\")\", keyspaceName);\n    }\n    \n\n    /*\n* (non-Javadoc)\n*\n* @see\n* com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n* createSchemaForPERSONNEL()\n*/\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBiMToMInt (PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelBiMToMInt\");\n            cli.update(\"DROP TABLE KUNDERATESTS.PersonnelBiMToMInt\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBiMToMInt (PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n        }\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBiMToMInt_HabitatBiMToMShort (PERSON_ID INTEGER , ADDRESS_ID SMALLINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelBiMToMInt_HabitatBiMToMShort\");\n            cli.update(\"DROP TABLE KUNDERATESTS.PersonnelBiMToMInt_HabitatBiMToMShort\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBiMToMInt_HabitatBiMToMShort (PERSON_ID INTEGER , ADDRESS_ID SMALLINT)\");\n        }\n\n    }\n\n    /*\n* (non-Javadoc)\n*\n* @see\n* com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n* createSchemaForHABITAT()\n*/\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBiMToMShort (ADDRESS_ID SMALLINT PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatBiMToMShort\");\n            cli.update(\"DROP TABLE KUNDERATESTS.HabitatBiMToMShort\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBiMToMShort (ADDRESS_ID SMALLINT PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n\n    }\n\n}"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/MTMUniAssociationIntTest.java",
    "content": "/*******************************************************************************\n* * Copyright 2012 Impetus Infotech.\n* *\n* * Licensed under the Apache License, Version 2.0 (the \"License\");\n* * you may not use this file except in compliance with the License.\n* * You may obtain a copy of the License at\n* *\n* * http://www.apache.org/licenses/LICENSE-2.0\n* *\n* * Unless required by applicable law or agreed to in writing, software\n* * distributed under the License is distributed on an \"AS IS\" BASIS,\n* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* * See the License for the specific language governing permissions and\n* * limitations under the License.\n******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype;\n\nimport java.math.BigInteger;\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.TwinAssociation;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.HabitatUniMToMBigInteger;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.PersonnelUniMToMInt;\n\n/**\n* @author vivek.mishra\n*\n*/\npublic class MTMUniAssociationIntTest extends TwinAssociation\n{\n    private BigInteger addressID1 = BigInteger.TEN;\n\n    private BigInteger addressID2 = BigInteger.ONE;\n\n    private BigInteger addressID3 = new BigInteger(\"1234567\");\n\n    public static final String[] ALL_PUs_UNDER_TEST = new String[] { \"addCassandra\", \"addMongo\", \n            \"addCouchdb\" };\n\n    /**\n* Inits the.\n*/\n    @BeforeClass\n    public static void init() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            CassandraCli.cassandraSetUp();\n\n        }\n        else\n        {\n            if (AUTO_MANAGE_SCHEMA)\n            {\n                CassandraCli.initClient();\n            }\n\n        }\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelUniMToMInt.class);\n        clazzz.add(HabitatUniMToMBigInteger.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n\n    }\n\n    /**\n* Sets the up.\n*\n* @throws Exception\n* the exception\n*/\n    @Before\n    public void setUp() throws Exception\n    {\n        // propertyMap.put(CassandraConstants.CQL_VERSION,\n        // CassandraConstants.CQL_VERSION_2_0);\n        setUpInternal(\"HabitatUniMToMBigInteger\", \"PersonnelUniMToMInt\", \"PersonnelUniMToMInt_HabitatUniMToMBigInteger\");\n    }\n\n    /**\n* Test insert.\n*/\n    @Test\n    public void testCRUD()\n    {\n        try\n        {\n            tryOperation(ALL_PUs_UNDER_TEST);\n        }\n        catch (Exception e)\n        {\n            Assert.fail(\"Failed, Caused by:\" + e.getMessage());\n        }\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonnelUniMToMInt person1 = new PersonnelUniMToMInt();\n        person1.setPersonId(12345);\n        person1.setPersonName(\"Amresh\");\n\n        PersonnelUniMToMInt person2 = new PersonnelUniMToMInt();\n        person2.setPersonId(12346);\n        person2.setPersonName(\"Vivek\");\n\n        HabitatUniMToMBigInteger address1 = new HabitatUniMToMBigInteger();\n        address1.setAddressId(addressID1);\n        address1.setStreet(\"AAAAAAAAAAAAA\");\n\n        HabitatUniMToMBigInteger address2 = new HabitatUniMToMBigInteger();\n        address2.setAddressId(addressID2);\n        address2.setStreet(\"BBBBBBBBBBBBBBB\");\n\n        HabitatUniMToMBigInteger address3 = new HabitatUniMToMBigInteger();\n        address3.setAddressId(addressID3);\n        address3.setStreet(\"CCCCCCCCCCC\");\n\n        Set<HabitatUniMToMBigInteger> person1Addresses = new HashSet<HabitatUniMToMBigInteger>();\n        Set<HabitatUniMToMBigInteger> person2Addresses = new HashSet<HabitatUniMToMBigInteger>();\n\n        person1Addresses.add(address1);\n        person1Addresses.add(address2);\n\n        person2Addresses.add(address2);\n        person2Addresses.add(address3);\n\n        person1.setAddresses(person1Addresses);\n        person2.setAddresses(person2Addresses);\n\n        Set<PersonnelUniMToMInt> persons = new HashSet<PersonnelUniMToMInt>();\n        persons.add(person1);\n        persons.add(person2);\n\n        dao.savePersons(persons);\n\n        col.add(person1);\n        col.add(person2);\n        col.add(address1);\n        col.add(address2);\n        col.add(address3);\n    }\n\n    @Override\n    protected void find()\n    {\n\n        PersonnelUniMToMInt person1 = (PersonnelUniMToMInt) dao.findPerson(PersonnelUniMToMInt.class, 12345);\n        assertPerson1(person1);\n\n        PersonnelUniMToMInt person2 = (PersonnelUniMToMInt) dao.findPerson(PersonnelUniMToMInt.class, 12346);\n        assertPerson2(person2);\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        // Find Person 1\n        PersonnelUniMToMInt p1 = (PersonnelUniMToMInt) dao.findPersonByIdColumn(PersonnelUniMToMInt.class, 12345);\n        assertPerson1(p1);\n\n        // Find Person 2\n        PersonnelUniMToMInt p2 = (PersonnelUniMToMInt) dao.findPersonByIdColumn(PersonnelUniMToMInt.class, 12346);\n        assertPerson2(p2);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelUniMToMInt> persons = dao.findPersonByName(PersonnelUniMToMInt.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        assertPerson1(persons.get(0));\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        HabitatUniMToMBigInteger a = (HabitatUniMToMBigInteger) dao.findAddressByIdColumn(\n                HabitatUniMToMBigInteger.class, addressID1);\n        assertAddressForPerson1(a);\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        List<HabitatUniMToMBigInteger> adds = dao.findAddressByStreet(HabitatUniMToMBigInteger.class, \"AAAAAAAAAAAAA\");\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertTrue(adds.size() == 1);\n\n        assertAddressForPerson1(adds.get(0));\n    }\n\n    @Override\n    protected void update()\n    {\n        PersonnelUniMToMInt p1 = (PersonnelUniMToMInt) dao.findPerson(PersonnelUniMToMInt.class, 12345);\n        Assert.assertNotNull(p1);\n        for (HabitatUniMToMBigInteger address : p1.getAddresses())\n        {\n            address.setStreet(\"Brand New Street\");\n        }\n        p1.setPersonName(\"Saurabh\");\n        dao.merge(p1);\n        PersonnelUniMToMInt p1AfterMerge = (PersonnelUniMToMInt) dao.findPerson(PersonnelUniMToMInt.class, 12345);\n        Assert.assertNotNull(p1AfterMerge);\n        Assert.assertEquals(\"Saurabh\", p1AfterMerge.getPersonName());\n        for (HabitatUniMToMBigInteger address : p1AfterMerge.getAddresses())\n        {\n            Assert.assertEquals(\"Brand New Street\", address.getStreet());\n        }\n\n        PersonnelUniMToMInt p2 = (PersonnelUniMToMInt) dao.findPerson(PersonnelUniMToMInt.class, 12346);\n        Assert.assertNotNull(p2);\n        for (HabitatUniMToMBigInteger address : p2.getAddresses())\n        {\n            address.setStreet(\"Brand New Street\");\n        }\n        p2.setPersonName(\"Vijay\");\n        dao.merge(p2);\n        PersonnelUniMToMInt p2AfterMerge = (PersonnelUniMToMInt) dao.findPerson(PersonnelUniMToMInt.class, 12346);\n        Assert.assertNotNull(p2AfterMerge);\n        Assert.assertEquals(\"Vijay\", p2AfterMerge.getPersonName());\n        for (HabitatUniMToMBigInteger address : p2AfterMerge.getAddresses())\n        {\n            Assert.assertEquals(\"Brand New Street\", address.getStreet());\n        }\n    }\n\n    @Override\n    protected void remove()\n    {\n        dao.remove(12345, PersonnelUniMToMInt.class);\n        PersonnelUniMToMInt person1AfterRemoval = (PersonnelUniMToMInt) dao\n                .findPerson(PersonnelUniMToMInt.class, 12345);\n        Assert.assertNull(person1AfterRemoval);\n\n        dao.remove(12346, PersonnelUniMToMInt.class);\n        PersonnelUniMToMInt person2AfterRemoval = (PersonnelUniMToMInt) dao\n                .findPerson(PersonnelUniMToMInt.class, 12346);\n        Assert.assertNull(person2AfterRemoval);\n    }\n\n    /**\n* Tear down.\n*\n* @throws Exception\n* the exception\n*/\n    @After\n    public void tearDown() throws Exception\n    {\n        // shutDownRdbmsServer();\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n* @param person1\n*/\n    private void assertPerson1(PersonnelUniMToMInt person1)\n    {\n        Assert.assertNotNull(person1);\n        Assert.assertEquals(12345, person1.getPersonId());\n        Assert.assertEquals(\"Amresh\", person1.getPersonName());\n\n        Set<HabitatUniMToMBigInteger> addresses1 = person1.getAddresses();\n        Assert.assertNotNull(addresses1);\n        Assert.assertFalse(addresses1.isEmpty());\n        Assert.assertEquals(2, addresses1.size());\n        HabitatUniMToMBigInteger address11 = (HabitatUniMToMBigInteger) addresses1.toArray()[0];\n        assertAddressForPerson1(address11);\n        HabitatUniMToMBigInteger address12 = (HabitatUniMToMBigInteger) addresses1.toArray()[1];\n        assertAddressForPerson1(address12);\n    }\n\n    /**\n* @param person2\n*/\n    private void assertPerson2(PersonnelUniMToMInt person2)\n    {\n        Assert.assertNotNull(person2);\n\n        Assert.assertEquals(12346, person2.getPersonId());\n        Assert.assertEquals(\"Vivek\", person2.getPersonName());\n\n        Set<HabitatUniMToMBigInteger> addresses2 = person2.getAddresses();\n        Assert.assertNotNull(addresses2);\n        Assert.assertFalse(addresses2.isEmpty());\n        Assert.assertEquals(2, addresses2.size());\n        HabitatUniMToMBigInteger address21 = (HabitatUniMToMBigInteger) addresses2.toArray()[0];\n        assertAddressForPerson2(address21);\n        HabitatUniMToMBigInteger address22 = (HabitatUniMToMBigInteger) addresses2.toArray()[1];\n        assertAddressForPerson2(address22);\n    }\n\n    /**\n* @param address11\n*/\n    private void assertAddressForPerson1(HabitatUniMToMBigInteger address)\n    {\n        Assert.assertNotNull(address);\n        Assert.assertTrue(addressID1.equals(address.getAddressId()) || addressID2.equals(address.getAddressId()));\n        Assert.assertTrue(\"AAAAAAAAAAAAA\".equals(address.getStreet()) || \"BBBBBBBBBBBBBBB\".equals(address.getStreet()));\n    }\n\n    /**\n* @param address12\n*/\n    private void assertAddressForPerson2(HabitatUniMToMBigInteger address)\n    {\n        Assert.assertNotNull(address);\n\n        Assert.assertTrue(addressID2.equals(address.getAddressId()) || addressID2.equals(address.getAddressId())\n                || addressID3.equals(address.getAddressId()));\n        Assert.assertTrue(\"CCCCCCCCCCC\".equals(address.getStreet()) || \"BBBBBBBBBBBBBBB\".equals(address.getStreet()));\n\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelUniMToMInt\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelUniMToMInt\\\" ( \\\"PERSON_ID\\\" int PRIMARY KEY,  \\\"PERSON_NAME\\\" text, \\\"ADDRESS_ID\\\" text)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUniMToMInt\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelUniMToMInt_HabitatUniMToMBigInteger\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelUniMToMInt_HabitatUniMToMBigInteger\\\" ( \\\"PERSON_ID\\\" int,  \\\"key\\\" text PRIMARY KEY, \\\"ADDRESS_ID\\\" varint)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUniMToMInt_HabitatUniMToMBigInteger\\\" ( \\\"PERSON_ID\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUniMToMInt_HabitatUniMToMBigInteger\\\" ( \\\"ADDRESS_ID\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatUniMToMBigInteger\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"HabitatUniMToMBigInteger\\\" ( \\\"ADDRESS_ID\\\" varint PRIMARY KEY,  \\\"STREET\\\" text)\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatUniMToMBigInteger\\\" ( \\\"STREET\\\")\", keyspaceName);\n    }\n\n    /*\n* (non-Javadoc)\n*\n* @see\n* com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n* createSchemaForPERSONNEL()\n*/\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUniMToMInt (PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelUniMToMInt\");\n            cli.update(\"DROP TABLE KUNDERATESTS.PersonnelUniMToMInt\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUniMToMInt (PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n        }\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUniMToMInt_HabitatUniMToMBigInteger (PERSON_ID INTEGER , ADDRESS_ID BIGINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelUniMToMInt_HabitatUniMToMBigInteger\");\n            cli.update(\"DROP TABLE KUNDERATESTS.PersonnelUniMToMInt_HabitatUniMToMBigInteger\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUniMToMInt_HabitatUniMToMBigInteger (PERSON_ID INTEGER , ADDRESS_ID BIGINT)\");\n        }\n    }\n\n    /*\n* (non-Javadoc)\n*\n* @see\n* com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n* createSchemaForHABITAT()\n*/\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUniMToMBigInteger (ADDRESS_ID BIGINT PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatUniMToMBigInteger\");\n            cli.update(\"DROP TABLE KUNDERATESTS.HabitatUniMToMBigInteger\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUniMToMBigInteger (ADDRESS_ID BIGINT PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n    }\n\n}"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/MTOBiAssociationIntTest.java",
    "content": "/*******************************************************************************\n* * Copyright 2012 Impetus Infotech.\n* *\n* * Licensed under the Apache License, Version 2.0 (the \"License\");\n* * you may not use this file except in compliance with the License.\n* * You may obtain a copy of the License at\n* *\n* * http://www.apache.org/licenses/LICENSE-2.0\n* *\n* * Unless required by applicable law or agreed to in writing, software\n* * distributed under the License is distributed on an \"AS IS\" BASIS,\n* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* * See the License for the specific language governing permissions and\n* * limitations under the License.\n******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.TwinAssociation;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.HabitatBiMTo1Char;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.PersonnelBiMTo1Int;\n\npublic class MTOBiAssociationIntTest extends TwinAssociation\n{\n    public static final String[] ALL_PUs_UNDER_TEST = new String[] { \"addCassandra\", \"addMongo\", \n            \"addCouchdb\" };\n\n    /**\n* Inits the.\n*/\n    @BeforeClass\n    public static void init() throws Exception\n    {\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelBiMTo1Int.class);\n        clazzz.add(HabitatBiMTo1Char.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n* Sets the up.\n*\n* @throws Exception\n* the exception\n*/\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal(\"HabitatBiMTo1Char\", \"PersonnelBiMTo1Int\");\n    }\n\n    @Test\n    public void testCRUD()\n    {\n        tryOperation(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonnelBiMTo1Int person1 = new PersonnelBiMTo1Int();\n        person1.setPersonId(12345);\n        person1.setPersonName(\"Amresh\");\n\n        PersonnelBiMTo1Int person2 = new PersonnelBiMTo1Int();\n        person2.setPersonId(12346);\n        person2.setPersonName(\"Vivek\");\n\n        HabitatBiMTo1Char address = new HabitatBiMTo1Char();\n        address.setAddressId('A');\n        address.setStreet(\"AAAAAAAAAAAAA\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        Set<PersonnelBiMTo1Int> persons = new HashSet<PersonnelBiMTo1Int>();\n        persons.add(person1);\n        persons.add(person2);\n\n        dao.savePersons(persons);\n        col.add(person1);\n        col.add(person2);\n        col.add(address);\n\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person 1\n        PersonnelBiMTo1Int p1 = (PersonnelBiMTo1Int) dao.findPerson(PersonnelBiMTo1Int.class, 12345);\n        assertPerson1(p1);\n\n        // Find Person 2\n        PersonnelBiMTo1Int p2 = (PersonnelBiMTo1Int) dao.findPerson(PersonnelBiMTo1Int.class, 12346);\n        assertPerson2(p2);\n\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonnelBiMTo1Int p = (PersonnelBiMTo1Int) dao.findPersonByIdColumn(PersonnelBiMTo1Int.class, 12345);\n        assertPerson1(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelBiMTo1Int> persons = dao.findPersonByName(PersonnelBiMTo1Int.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonnelBiMTo1Int person = persons.get(0);\n        assertPerson1(person);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n    }\n\n    @Override\n    protected void update()\n    {\n    }\n\n    @Override\n    protected void remove()\n    {\n    }\n\n    /**\n* @param p2\n*/\n    private void assertPerson2(PersonnelBiMTo1Int p2)\n    {\n        Assert.assertNotNull(p2);\n        Assert.assertEquals(12346, p2.getPersonId());\n        Assert.assertEquals(\"Vivek\", p2.getPersonName());\n\n        HabitatBiMTo1Char add2 = p2.getAddress();\n        Assert.assertNotNull(add2);\n\n        Assert.assertEquals('A', add2.getAddressId());\n        Set<PersonnelBiMTo1Int> people2 = add2.getPeople();\n        Assert.assertNotNull(people2);\n        Assert.assertFalse(people2.isEmpty());\n        Assert.assertEquals(2, people2.size());\n    }\n\n    /**\n* @param p1\n*/\n    private void assertPerson1(PersonnelBiMTo1Int p1)\n    {\n        Assert.assertNotNull(p1);\n        Assert.assertEquals(12345, p1.getPersonId());\n        Assert.assertEquals(\"Amresh\", p1.getPersonName());\n\n        HabitatBiMTo1Char add = p1.getAddress();\n        Assert.assertNotNull(add);\n\n        Assert.assertEquals('A', add.getAddressId());\n        Set<PersonnelBiMTo1Int> people = add.getPeople();\n        Assert.assertNotNull(people);\n        Assert.assertFalse(people.isEmpty());\n        Assert.assertEquals(2, people.size());\n    }\n\n    /**\n* Tear down.\n*\n* @throws Exception\n* the exception\n*/\n    @After\n    public void tearDown() throws Exception\n    {\n        // shutDownRdbmsServer();\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelBiMTo1Int\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelBiMTo1Int\\\" ( \\\"PERSON_ID\\\" int PRIMARY KEY,  \\\"PERSON_NAME\\\" text, \\\"ADDRESS_ID\\\" text)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBiMTo1Int\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBiMTo1Int\\\" ( \\\"ADDRESS_ID\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatBiMTo1Char\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"HabitatBiMTo1Char\\\" ( \\\"ADDRESS_ID\\\" text PRIMARY KEY,  \\\"STREET\\\" text)\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatBiMTo1Char\\\" ( \\\"STREET\\\")\", keyspaceName);\n    }\n\n    /*\n* (non-Javadoc)\n*\n* @see\n* com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n* createSchemaForPERSONNEL()\n*/\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBiMTo1Int (PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(6))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelBiMTo1Int\");\n            cli.update(\"DROP TABLE KUNDERATESTS.PersonnelBiMTo1Int\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBiMTo1Int (PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID VARCHAR(6))\");\n        }\n    }\n\n    /*\n* (non-Javadoc)\n*\n* @see\n* com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n* createSchemaForHABITAT()\n*/\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.ADDRESS (ADDRESS_ID VARCHAR(6) PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatBiMTo1Char\");\n            cli.update(\"DROP TABLE KUNDERATESTS.HabitatBiMTo1Char\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBiMTo1Char (ADDRESS_ID VARCHAR(6) PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n    }\n}"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/MTOUniAssociationIntTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.TwinAssociation;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.HabitatUniMTo1Long;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.PersonnelUniMTo1Int;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class MTOUniAssociationIntTest extends TwinAssociation\n{\n    private static final Long ADDRESS_ID = new Long(123456);\n\n    public static final String[] ALL_PUs_UNDER_TEST = new String[] { \"addCassandra\", \"addMongo\", \"oracle_kvstore\",\n            \"addCouchdb\" };\n\n    /**\n     * Inits the.\n     */\n    @BeforeClass\n    public static void init() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            CassandraCli.initClient();\n        }\n\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelUniMTo1Int.class);\n        clazzz.add(HabitatUniMTo1Long.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal(\"HabitatUniMTo1Long\", \"PersonnelUniMTo1Int\");\n    }\n\n    /**\n     * Test CRUD.\n     */\n    @Test\n    public void testCRUD()\n    {\n        tryOperation(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonnelUniMTo1Int person1 = new PersonnelUniMTo1Int();\n        person1.setPersonId(12345);\n        person1.setPersonName(\"Amresh\");\n\n        PersonnelUniMTo1Int person2 = new PersonnelUniMTo1Int();\n        person2.setPersonId(12346);\n        person2.setPersonName(\"Vivek\");\n\n        HabitatUniMTo1Long address = new HabitatUniMTo1Long();\n        address.setAddressId(ADDRESS_ID);\n        address.setStreet(\"AAAAAAAAAAAAA\");\n\n        person1.setAddress(address);\n        person2.setAddress(address);\n\n        Set<PersonnelUniMTo1Int> persons = new HashSet<PersonnelUniMTo1Int>();\n        persons.add(person1);\n        persons.add(person2);\n\n        dao.savePersons(persons);\n\n        col.add(person1);\n        col.add(person2);\n        col.add(address);\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person 1\n        PersonnelUniMTo1Int p1 = (PersonnelUniMTo1Int) dao.findPerson(PersonnelUniMTo1Int.class, 12345);\n        assertPerson1(p1);\n\n        // Find Person 2\n        PersonnelUniMTo1Int p2 = (PersonnelUniMTo1Int) dao.findPerson(PersonnelUniMTo1Int.class, 12346);\n        assertPerson2(p2);\n\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonnelUniMTo1Int p = (PersonnelUniMTo1Int) dao.findPersonByIdColumn(PersonnelUniMTo1Int.class, 12345);\n        assertPerson1(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelUniMTo1Int> persons = dao.findPersonByName(PersonnelUniMTo1Int.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonnelUniMTo1Int person = persons.get(0);\n        assertPerson1(person);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        HabitatUniMTo1Long a = (HabitatUniMTo1Long) dao.findAddressByIdColumn(HabitatUniMTo1Long.class, ADDRESS_ID);\n        assertAddress(a);\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        List<HabitatUniMTo1Long> adds = dao.findAddressByStreet(HabitatUniMTo1Long.class, \"AAAAAAAAAAAAA\");\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertTrue(adds.size() == 1);\n\n        assertAddress(adds.get(0));\n    }\n\n    @Override\n    protected void update()\n    {\n        // Find Person 1\n        PersonnelUniMTo1Int p1 = (PersonnelUniMTo1Int) dao.findPerson(PersonnelUniMTo1Int.class, 12345);\n        Assert.assertNotNull(p1);\n        p1.setPersonName(\"Saurabh\");\n        p1.getAddress().setStreet(\"Brand New Street\");\n        dao.merge(p1);\n        PersonnelUniMTo1Int p1AfterMerge = (PersonnelUniMTo1Int) dao.findPerson(PersonnelUniMTo1Int.class, 12345);\n        Assert.assertNotNull(p1AfterMerge);\n        Assert.assertEquals(\"Saurabh\", p1AfterMerge.getPersonName());\n        Assert.assertEquals(\"Brand New Street\", p1AfterMerge.getAddress().getStreet());\n\n        // Find Person 2\n        PersonnelUniMTo1Int p2 = (PersonnelUniMTo1Int) dao.findPerson(PersonnelUniMTo1Int.class, 12346);\n        Assert.assertNotNull(p2);\n        p2.setPersonName(\"Prateek\");\n        dao.merge(p2);\n        PersonnelUniMTo1Int p2AfterMerge = (PersonnelUniMTo1Int) dao.findPerson(PersonnelUniMTo1Int.class, 12346);\n        Assert.assertNotNull(p2AfterMerge);\n        Assert.assertEquals(\"Prateek\", p2AfterMerge.getPersonName());\n        Assert.assertEquals(\"Brand New Street\", p2AfterMerge.getAddress().getStreet());\n    }\n\n    @Override\n    protected void remove()\n    {\n        // Remove Person 1\n        dao.remove(12345, PersonnelUniMTo1Int.class);\n        PersonnelUniMTo1Int p1AfterRemoval = (PersonnelUniMTo1Int) dao.findPerson(PersonnelUniMTo1Int.class, 12345);\n        Assert.assertNull(p1AfterRemoval);\n\n        // Remove Person 2\n        dao.remove(12346, PersonnelUniMTo1Int.class);\n        PersonnelUniMTo1Int p2AfterRemoval = (PersonnelUniMTo1Int) dao.findPerson(PersonnelUniMTo1Int.class, 12346);\n        Assert.assertNull(p2AfterRemoval);\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n        // shutDownRdbmsServer();\n    }\n\n    /**\n     * @param p2\n     */\n    private void assertPerson2(PersonnelUniMTo1Int p2)\n    {\n        Assert.assertNotNull(p2);\n        Assert.assertEquals(12346, p2.getPersonId());\n        Assert.assertEquals(\"Vivek\", p2.getPersonName());\n\n        HabitatUniMTo1Long add2 = p2.getAddress();\n        assertAddress(add2);\n    }\n\n    /**\n     * @param p1\n     */\n    private void assertPerson1(PersonnelUniMTo1Int p1)\n    {\n        Assert.assertNotNull(p1);\n        Assert.assertEquals(12345, p1.getPersonId());\n        Assert.assertEquals(\"Amresh\", p1.getPersonName());\n\n        HabitatUniMTo1Long add = p1.getAddress();\n        assertAddress(add);\n    }\n\n    /**\n     * @param add2\n     */\n    private void assertAddress(HabitatUniMTo1Long add2)\n    {\n        Assert.assertNotNull(add2);\n\n        Assert.assertEquals(ADDRESS_ID, add2.getAddressId());\n        Assert.assertEquals(\"AAAAAAAAAAAAA\", add2.getStreet());\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelUniMTo1Int\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelUniMTo1Int\\\" ( \\\"PERSON_ID\\\" int PRIMARY KEY,  \\\"PERSON_NAME\\\" text, \\\"ADDRESS_ID\\\" bigint)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUniMTo1Int\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUniMTo1Int\\\" ( \\\"ADDRESS_ID\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatUniMTo1Long\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"HabitatUniMTo1Long\\\" ( \\\"ADDRESS_ID\\\" bigint PRIMARY KEY,  \\\"STREET\\\" text)\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatUniMTo1Long\\\" ( \\\"STREET\\\")\", keyspaceName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForPERSONNEL()\n     */\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUniMTo1Int (PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID BIGINT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelUniMTo1Int\");\n            cli.update(\"DROP TABLE KUNDERATESTS.PersonnelUniMTo1Int\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUniMTo1Int (PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID BIGINT)\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForHABITAT()\n     */\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUniMTo1Long (ADDRESS_ID BIGINT PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatUniMTo1Long\");\n            cli.update(\"DROP TABLE KUNDERATESTS.HabitatUniMTo1Long\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUniMTo1Long(ADDRESS_ID BIGINT PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/OTMBiAssociationIntTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.TwinAssociation;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.HabitatBi1ToMDouble;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.PersonnelBi1ToMInt;\n\npublic class OTMBiAssociationIntTest extends TwinAssociation\n{\n    public static final String[] ALL_PUs_UNDER_TEST = new String[] { \"rdbms\", \"addCassandra\", \"addMongo\",\n            \"oracle_kvstore\", \"addCouchdb\" };\n\n    /**\n     * Inits the.\n     */\n    @BeforeClass\n    public static void init() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        else\n        {\n            if (AUTO_MANAGE_SCHEMA)\n            {\n                CassandraCli.initClient();\n            }\n        }\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelBi1ToMInt.class);\n        clazzz.add(HabitatBi1ToMDouble.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal(\"HabitatBi1ToMDouble\", \"PersonnelBi1ToMInt\");\n    }\n\n    /**\n     * Test insert.\n     */\n    @Test\n    public void testCRUD()\n    {\n        tryOperation(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonnelBi1ToMInt personnel = new PersonnelBi1ToMInt();\n        personnel.setPersonId(12345);\n        personnel.setPersonName(\"Amresh\");\n\n        Set<HabitatBi1ToMDouble> addresses = new HashSet<HabitatBi1ToMDouble>();\n        HabitatBi1ToMDouble address1 = new HabitatBi1ToMDouble();\n        address1.setAddressId(12345.1234);\n        address1.setStreet(\"AAAAAAAAAAAAA\");\n\n        HabitatBi1ToMDouble address2 = new HabitatBi1ToMDouble();\n        address2.setAddressId(12346.1234);\n        address2.setStreet(\"BBBBBBBBBBB\");\n\n        addresses.add(address1);\n        addresses.add(address2);\n        personnel.setAddresses(addresses);\n        dao.insert(personnel);\n        col.add(personnel);\n        col.add(address1);\n        col.add(address2);\n\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person\n        PersonnelBi1ToMInt p = (PersonnelBi1ToMInt) dao.findPerson(PersonnelBi1ToMInt.class, 12345);\n        assertPerson(p);\n\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonnelBi1ToMInt p = (PersonnelBi1ToMInt) dao.findPersonByIdColumn(PersonnelBi1ToMInt.class, 12345);\n        assertPerson(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelBi1ToMInt> persons = dao.findPersonByName(PersonnelBi1ToMInt.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonnelBi1ToMInt person = persons.get(0);\n        assertPerson(person);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n    }\n\n    @Override\n    protected void update()\n    {\n        // Find Person\n        PersonnelBi1ToMInt p = (PersonnelBi1ToMInt) dao.findPerson(PersonnelBi1ToMInt.class, 12345);\n        assertPerson(p);\n\n        p.setPersonName(\"Saurabh\");\n        for (HabitatBi1ToMDouble address : p.getAddresses())\n        {\n            address.setStreet(\"Brand New Street\");\n        }\n        dao.merge(p);\n        PersonnelBi1ToMInt pAfterMerge = (PersonnelBi1ToMInt) dao.findPerson(PersonnelBi1ToMInt.class, 12345);\n\n        assertPersonAfterUpdate(pAfterMerge);\n    }\n\n    @Override\n    protected void remove()\n    {\n        // Find Person\n        PersonnelBi1ToMInt p = (PersonnelBi1ToMInt) dao.findPerson(PersonnelBi1ToMInt.class, 12345);\n        assertPersonAfterUpdate(p);\n\n        dao.remove(12345, PersonnelBi1ToMInt.class);\n        PersonnelBi1ToMInt pAfterRemoval = (PersonnelBi1ToMInt) dao.findPerson(PersonnelBi1ToMInt.class, 12345);\n        Assert.assertNull(pAfterRemoval);\n    }\n\n    private void assertPerson(PersonnelBi1ToMInt p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(12345, p.getPersonId());\n        Assert.assertEquals(\"Amresh\", p.getPersonName());\n\n        Set<HabitatBi1ToMDouble> adds = p.getAddresses();\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertEquals(2, adds.size());\n\n        for (HabitatBi1ToMDouble address : adds)\n        {\n            Assert.assertNotNull(address);\n            PersonnelBi1ToMInt person = address.getPerson();\n            Assert.assertNotNull(person);\n            Assert.assertEquals(p.getPersonId(), person.getPersonId());\n            Assert.assertEquals(p.getPersonName(), person.getPersonName());\n            Assert.assertNotNull(person.getAddresses());\n            Assert.assertFalse(person.getAddresses().isEmpty());\n            Assert.assertEquals(2, person.getAddresses().size());\n        }\n    }\n\n    private void assertPersonAfterUpdate(PersonnelBi1ToMInt p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(12345, p.getPersonId());\n        Assert.assertEquals(\"Saurabh\", p.getPersonName());\n\n        Set<HabitatBi1ToMDouble> adds = p.getAddresses();\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertEquals(2, adds.size());\n\n        for (HabitatBi1ToMDouble address : adds)\n        {\n            Assert.assertNotNull(address);\n            Assert.assertEquals(\"Brand New Street\", address.getStreet());\n            PersonnelBi1ToMInt person = address.getPerson();\n            Assert.assertNotNull(person);\n            Assert.assertEquals(p.getPersonId(), person.getPersonId());\n            Assert.assertEquals(p.getPersonName(), person.getPersonName());\n            Assert.assertNotNull(person.getAddresses());\n            Assert.assertFalse(person.getAddresses().isEmpty());\n            Assert.assertEquals(2, person.getAddresses().size());\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        // shutDownRdbmsServer();\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelBi1ToMInt\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"PersonnelBi1ToMInt\\\" ( \\\"PERSON_ID\\\" int PRIMARY KEY,  \\\"PERSON_NAME\\\" text)\",\n                keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBi1ToMInt\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatBi1ToMDouble\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"HabitatBi1ToMDouble\\\" ( \\\"ADDRESS_ID\\\" double PRIMARY KEY,  \\\"STREET\\\" text, \\\"PERSON_ID\\\" int )\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatBi1ToMDouble\\\" ( \\\"STREET\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatBi1ToMDouble\\\" ( \\\"PERSON_ID\\\")\", keyspaceName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForPERSONNEL()\n     */\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBi1ToMInt (PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelBi1ToMInt\");\n            cli.update(\"DROP TABLE KUNDERATESTS.PersonnelBi1ToMInt\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelBi1ToMInt(PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(256))\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForHABITAT()\n     */\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBi1ToMDouble (ADDRESS_ID DECIMAL(10,4) PRIMARY KEY, STREET VARCHAR(256),PERSON_ID INTEGER)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatBi1ToMDouble\");\n            cli.update(\"DROP TABLE KUNDERATESTS.HabitatBi1ToMDouble\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatBi1ToMDouble (ADDRESS_ID DECIMAL(10,4) PRIMARY KEY, STREET VARCHAR(256),PERSON_ID INTEGER)\");\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/OTMUniAssociationIntTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.TwinAssociation;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.HabitatUni1ToMFloat;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.PersonnelUni1ToMInt;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class OTMUniAssociationIntTest extends TwinAssociation\n{\n    private static final float _AID2 = 1235.143f;\n\n    private static final float _AID1 = 1234.143f;\n\n    private static final int _PID = 12345;\n\n   //CouchDB's current supported version has an issue with handling fixed precision numbers\n    public static final String[] ALL_PUs_UNDER_TEST = new String[] {\"addCassandra\", \"addMongo\",\n            \"oracle_kvstore\"/*,\"addCouchdb\"*/ };\n\n    /**\n     * Inits the.\n     */\n    @BeforeClass\n    public static void init() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            CassandraCli.cassandraSetUp();\n        }\n\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            CassandraCli.initClient();\n        }\n\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelUni1ToMInt.class);\n        clazzz.add(HabitatUni1ToMFloat.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal(\"HabitatUni1ToMFloat\", \"PersonnelUni1ToMInt\");\n    }\n\n    /**\n     * Test insert.\n     */\n    @Test\n    public void testCRUD()\n    {\n        tryOperation(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void insert()\n    {\n        // Save Person\n        PersonnelUni1ToMInt personnel = new PersonnelUni1ToMInt();\n        personnel.setPersonId(_PID);\n        personnel.setPersonName(\"Amresh\");\n\n        Set<HabitatUni1ToMFloat> addresses = new HashSet<HabitatUni1ToMFloat>();\n        HabitatUni1ToMFloat address1 = new HabitatUni1ToMFloat();\n        address1.setAddressId(_AID1);\n        address1.setStreet(\"AAAAAAAAAAAAA\");\n\n        HabitatUni1ToMFloat address2 = new HabitatUni1ToMFloat();\n        address2.setAddressId(_AID2);\n        address2.setStreet(\"BBBBBBBBBBB\");\n\n        addresses.add(address1);\n        addresses.add(address2);\n        personnel.setAddresses(addresses);\n        dao.insert(personnel);\n        col.add(personnel);\n        col.add(address1);\n        col.add(address2);\n\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person\n        PersonnelUni1ToMInt p = (PersonnelUni1ToMInt) dao.findPerson(PersonnelUni1ToMInt.class, _PID);\n        assertPerson(p);\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonnelUni1ToMInt p = (PersonnelUni1ToMInt) dao.findPersonByIdColumn(PersonnelUni1ToMInt.class, _PID);\n        assertPerson(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelUni1ToMInt> persons = dao.findPersonByName(PersonnelUni1ToMInt.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonnelUni1ToMInt person = persons.get(0);\n        assertPerson(person);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        HabitatUni1ToMFloat a = (HabitatUni1ToMFloat) dao.findAddressByIdColumn(HabitatUni1ToMFloat.class, _AID1);\n        Assert.assertNotNull(a);\n        Assert.assertEquals(_AID1, a.getAddressId());\n        Assert.assertEquals(\"AAAAAAAAAAAAA\", a.getStreet());\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        List<HabitatUni1ToMFloat> adds = dao.findAddressByStreet(HabitatUni1ToMFloat.class, \"AAAAAAAAAAAAA\");\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertTrue(adds.size() == 1);\n\n        HabitatUni1ToMFloat a = adds.get(0);\n        Assert.assertNotNull(a);\n        Assert.assertEquals(_AID1, a.getAddressId());\n        Assert.assertEquals(\"AAAAAAAAAAAAA\", a.getStreet());\n    }\n\n    @Override\n    protected void update()\n    {\n        try\n        {\n            PersonnelUni1ToMInt p = (PersonnelUni1ToMInt) dao.findPerson(PersonnelUni1ToMInt.class, _PID);\n            Assert.assertNotNull(p);\n            p.setPersonName(\"Saurabh\");\n\n            for (HabitatUni1ToMFloat address : p.getAddresses())\n            {\n                address.setStreet(\"Brand New Street\");\n            }\n            dao.merge(p);\n            assertPersonAfterUpdate();\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail();\n        }\n    }\n\n    @Override\n    protected void remove()\n    {\n        try\n        {\n            // PersonnelUni1ToMInt p = (PersonnelUni1ToMInt)\n            // dao.findPerson(PersonnelUni1ToMInt.class, );\n            dao.remove(_PID, PersonnelUni1ToMInt.class);\n            PersonnelUni1ToMInt pAfterRemoval = (PersonnelUni1ToMInt) dao.findPerson(PersonnelUni1ToMInt.class, _PID);\n            Assert.assertNull(pAfterRemoval);\n\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail();\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n       // shutDownRdbmsServer();\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n\n    }\n\n    /**\n     * @param p\n     */\n    private void assertPerson(PersonnelUni1ToMInt p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(_PID, p.getPersonId());\n        Assert.assertEquals(\"Amresh\", p.getPersonName());\n\n        Set<HabitatUni1ToMFloat> adds = p.getAddresses();\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertEquals(2, adds.size());\n\n        for (HabitatUni1ToMFloat address : adds)\n        {\n            Assert.assertNotNull(address.getStreet());\n        }\n    }\n\n    /**\n     * \n     */\n    private void assertPersonAfterUpdate()\n    {\n        PersonnelUni1ToMInt pAfterMerge = (PersonnelUni1ToMInt) dao.findPerson(PersonnelUni1ToMInt.class, _PID);\n        Assert.assertNotNull(pAfterMerge);\n        Assert.assertEquals(\"Saurabh\", pAfterMerge.getPersonName());\n\n        for (HabitatUni1ToMFloat address : pAfterMerge.getAddresses())\n        {\n            Assert.assertEquals(\"Brand New Street\", address.getStreet());\n        }\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelUni1ToMInt\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"PersonnelUni1ToMInt\\\" ( \\\"PERSON_ID\\\" int PRIMARY KEY,  \\\"PERSON_NAME\\\" text)\",\n                keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUni1ToMInt\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatUni1ToMFloat\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"HabitatUni1ToMFloat\\\" ( \\\"ADDRESS_ID\\\" float PRIMARY KEY,  \\\"STREET\\\" text, \\\"PERSON_ID\\\" int )\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatUni1ToMFloat\\\" ( \\\"STREET\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatUni1ToMFloat\\\" ( \\\"PERSON_ID\\\")\", keyspaceName);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForPERSONNEL()\n     */\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PERSONNEL (PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(150))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelUni1ToMInt\");\n            cli.update(\"DROP TABLE KUNDERATESTS.PersonnelUni1ToMInt\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUni1ToMInt(PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(150))\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForHABITAT()\n     */\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUni1ToMFloat (ADDRESS_ID DECIMAL(10,3) PRIMARY KEY, STREET VARCHAR(256),PERSON_ID INTEGER)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatUni1ToMFloat\");\n            cli.update(\"DROP TABLE KUNDERATESTS.HabitatUni1ToMFloat\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUni1ToMFloat (ADDRESS_ID DECIMAL(10,3) PRIMARY KEY, STREET VARCHAR(256),PERSON_ID INTEGER)\");\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/OTOBiAssociationIntTest.java",
    "content": "/*******************************************************************************\n* * Copyright 2012 Impetus Infotech.\n* *\n* * Licensed under the Apache License, Version 2.0 (the \"License\");\n* * you may not use this file except in compliance with the License.\n* * You may obtain a copy of the License at\n* *\n* * http://www.apache.org/licenses/LICENSE-2.0\n* *\n* * Unless required by applicable law or agreed to in writing, software\n* * distributed under the License is distributed on an \"AS IS\" BASIS,\n* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* * See the License for the specific language governing permissions and\n* * limitations under the License.\n******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype;\n\nimport java.math.BigDecimal;\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.TwinAssociation;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.HabitatBi1To1FKBigDecimal;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.PersonnelBi1To1FKInt;\n\npublic class OTOBiAssociationIntTest extends TwinAssociation\n{\n    public static final String[] ALL_PUs_UNDER_TEST = new String[] { \"addCassandra\", \"addMongo\",\"addCouchdb\" };\n\n    private static final BigDecimal ADDRESS_ID = new BigDecimal(\"123456\");\n\n    /**\n* Inits the.\n*/\n    @BeforeClass\n    public static void init() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            CassandraCli.cassandraSetUp();\n        }\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelBi1To1FKInt.class);\n        clazzz.add(HabitatBi1To1FKBigDecimal.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n* Sets the up.\n*\n* @throws Exception\n* the exception\n*/\n    @Before\n    public void setUp() throws Exception\n    {\n//        propertyMap.put(CassandraConstants.CQL_VERSION, CassandraConstants.CQL_VERSION_2_0);\n//        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"\");\n        setUpInternal(\"HabitatBi1To1FKBigDecimal\", \"PersonnelBi1To1FKInt\");\n    }\n\n    /**\n* Test CRUD\n*/\n    @Test\n    public void testCRUD()\n    {\n        tryOperation(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void insert()\n    {\n        PersonnelBi1To1FKInt person = new PersonnelBi1To1FKInt();\n        person.setPersonId(1234);\n        person.setPersonName(\"Amresh\");\n\n        HabitatBi1To1FKBigDecimal address = new HabitatBi1To1FKBigDecimal();\n        address.setAddressId(ADDRESS_ID);\n        address.setStreet(\"123, New street\");\n        person.setAddress(address);\n        address.setPerson(person);\n\n        dao.insert(person);\n        col.add(person);\n        col.add(address);\n\n    }\n\n    @Override\n    protected void find()\n    {\n        // Find Person\n        PersonnelBi1To1FKInt p = (PersonnelBi1To1FKInt) dao.findPerson(PersonnelBi1To1FKInt.class, 1234);\n        assertPersonnel(p);\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonnelBi1To1FKInt p = (PersonnelBi1To1FKInt) dao.findPersonByIdColumn(PersonnelBi1To1FKInt.class, 1234);\n        assertPersonnel(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelBi1To1FKInt> persons = dao.findPersonByName(PersonnelBi1To1FKInt.class, \"Amresh\");\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        assertPersonnel(persons.get(0));\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        /*\n* HabitatBi1To1FK a = (HabitatBi1To1FK)\n* dao.findAddressByIdColumn(HabitatBi1To1FK.class, ADDRESS_ID);\n* assertAddress(a);\n*/\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        /*\n* List<HabitatBi1To1FK> adds =\n* dao.findAddressByStreet(HabitatBi1To1FK.class, \"123, New street\");\n* Assert.assertNotNull(adds); Assert.assertFalse(adds.isEmpty());\n* Assert.assertTrue(adds.size() == 1);\n*\n* assertAddress(adds.get(0));\n*/\n    }\n\n    @Override\n    protected void update()\n    {\n        try\n        {\n            PersonnelBi1To1FKInt p = (PersonnelBi1To1FKInt) dao.findPerson(PersonnelBi1To1FKInt.class, 1234);\n            assertPersonnel(p);\n\n            dao.merge(p); // This merge operation should do nothing since\n                          // nothing has changed\n\n            p = (PersonnelBi1To1FKInt) dao.findPerson(PersonnelBi1To1FKInt.class, 1234);\n            assertPersonnel(p);\n\n            p.setPersonName(\"Saurabh\");\n            p.getAddress().setStreet(\"Brand New Street\");\n            dao.merge(p);\n\n            PersonnelBi1To1FKInt pAfterMerge = (PersonnelBi1To1FKInt) dao.findPerson(PersonnelBi1To1FKInt.class, 1234);\n            assertPersonnelAfterUpdate(pAfterMerge);\n\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail();\n        }\n    }\n\n    @Override\n    protected void remove()\n    {\n        PersonnelBi1To1FKInt p = (PersonnelBi1To1FKInt) dao.findPerson(PersonnelBi1To1FKInt.class, 1234);\n        assertPersonnelAfterUpdate(p);\n\n        dao.remove(1234, PersonnelBi1To1FKInt.class);\n\n        PersonnelBi1To1FKInt pAfterRemoval = (PersonnelBi1To1FKInt) dao.findPerson(PersonnelBi1To1FKInt.class, 1234);\n        Assert.assertNull(pAfterRemoval);\n    }\n\n    private void assertPersonnel(PersonnelBi1To1FKInt p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1234, p.getPersonId());\n        Assert.assertEquals(\"Amresh\", p.getPersonName());\n\n        HabitatBi1To1FKBigDecimal address = p.getAddress();\n        assertAddress(address);\n    }\n\n    /**\n* @param address\n*/\n    private void assertAddress(HabitatBi1To1FKBigDecimal address)\n    {\n        Assert.assertNotNull(address);\n        Assert.assertEquals(ADDRESS_ID, address.getAddressId());\n        Assert.assertEquals(\"123, New street\", address.getStreet());\n\n        PersonnelBi1To1FKInt pp = address.getPerson();\n        Assert.assertNotNull(pp);\n        Assert.assertEquals(1234, pp.getPersonId());\n        Assert.assertEquals(\"Amresh\", pp.getPersonName());\n    }\n\n    private void assertPersonnelAfterUpdate(PersonnelBi1To1FKInt pAfterMerge)\n    {\n        Assert.assertNotNull(pAfterMerge);\n        Assert.assertEquals(\"Saurabh\", pAfterMerge.getPersonName());\n        HabitatBi1To1FKBigDecimal addressAfterMerge = pAfterMerge.getAddress();\n        Assert.assertNotNull(addressAfterMerge);\n        Assert.assertEquals(\"Brand New Street\", addressAfterMerge.getStreet());\n\n        PersonnelBi1To1FKInt pp = addressAfterMerge.getPerson();\n        Assert.assertNotNull(pp);\n        Assert.assertEquals(1234, pp.getPersonId());\n        Assert.assertEquals(\"Saurabh\", pp.getPersonName());\n    }\n\n    /**\n* Tear down.\n*\n* @throws Exception\n* the exception\n*/\n    @After\n    public void tearDown() throws Exception\n    {\n       // shutDownRdbmsServer();\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n    }\n\n    @Override\n    protected void loadDataForPERSONNEL() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelBi1To1FKInt\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelBi1To1FKInt\\\" ( \\\"PERSON_ID\\\" int PRIMARY KEY,  \\\"PERSON_NAME\\\" text, \\\"ADDRESS_ID\\\" decimal)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBi1To1FKInt\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelBi1To1FKInt\\\" ( \\\"ADDRESS_ID\\\")\", keyspaceName);\n    }\n\n    @Override\n    protected void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatBi1To1FKBigDecimal\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"HabitatBi1To1FKBigDecimal\\\" ( \\\"ADDRESS_ID\\\" decimal PRIMARY KEY,  \\\"STREET\\\" text)\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatBi1To1FKBigDecimal\\\" ( \\\"STREET\\\")\", keyspaceName);\n    }\n\n    /*\n* (non-Javadoc)\n*\n* @see\n* com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n* createSchemaForPERSONNEL()\n*/\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        // cli.update(\"CREATE TABLE KUNDERATESTS.PERSONNEL (PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID DECIMAL)\");\n    }\n\n    /*\n* (non-Javadoc)\n*\n* @see\n* com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n* createSchemaForHABITAT()\n*/\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        // cli.update(\"CREATE TABLE KUNDERATESTS.ADDRESS (ADDRESS_ID DECIMAL PRIMARY KEY, STREET VARCHAR(256)\");\n\n    }\n}"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/OTOUniAssociationIntTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.Compression;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.TwinAssociation;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.HabitatUni1To1FKInteger;\nimport com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities.PersonnelUni1To1FKInt;\n\n/**\n * One to one association test for {@see} cassandra, mongodb,HBase and RDBMS\n * combination.\n * \n * Script to create super column family\n * \n * Note: As PersonnelUni1To1FK is holding embedded collection so to test as a\n * super col family. create super column family as given below: create column\n * family PERSONNEL with comparator=UTF8Type and\n * default_validation_class=UTF8Type and key_validation_class=UTF8Type and\n * column_type=Super;\n * \n * \n * Note: To create as column family PERSONNEL use as given below: create column\n * family PERSONNEL with comparator=UTF8Type and column_metadata=[{column_name:\n * PERSON_NAME, validation_class: UTF8Type, index_type: KEYS}, {column_name:\n * AGE, validation_class: IntegerType, index_type: KEYS}];\n * \n * @author vivek.mishra\n */\n\npublic class OTOUniAssociationIntTest extends TwinAssociation\n{\n    public static final String[] ALL_PUs_UNDER_TEST = new String[] { \"rdbms\", \"addMongo\", \"oracle_kvstore\",\n            \"addCassandra\",\"addCouchdb\" };\n\n    private static final Integer ADDRESS_ID = new Integer(1234567);\n\n    /**\n     * Inits the.\n     */\n    @BeforeClass\n    public static void init() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            // HBaseCli cli = new HBaseCli();\n            // cli.startCluster();\n        }\n        List<Class> clazzz = new ArrayList<Class>(2);\n        clazzz.add(PersonnelUni1To1FKInt.class);\n        clazzz.add(HabitatUni1To1FKInteger.class);\n        init(clazzz, ALL_PUs_UNDER_TEST);\n    }\n\n    /**\n     * Sets the up.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        setUpInternal(\"HabitatUni1To1FKInteger\", \"PersonnelUni1To1FKInt\");\n    }\n\n    /**\n     * Test CRUD\n     */\n    @Test\n    public void testCRUD()\n    {\n        try\n        {\n            tryOperation(ALL_PUs_UNDER_TEST);\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail(e.getMessage());\n\n        }\n\n    }\n\n    protected void insert()\n    {\n        try\n        {\n            PersonnelUni1To1FKInt person = new PersonnelUni1To1FKInt();\n            HabitatUni1To1FKInteger address = new HabitatUni1To1FKInteger();\n            person.setPersonId(1234);\n            person.setPersonName(\"Amresh\");\n            address.setAddressId(ADDRESS_ID);\n            address.setStreet(\"123, New street\");\n            person.setAddress(address);\n            dao.insert(person);\n            col.add(person);\n            col.add(address);\n        }\n        catch (Exception e)\n        {\n           e.printStackTrace(); \n            Assert.fail();\n        }\n    }\n\n    protected void find()\n    {\n        // Find Person\n        try\n        {\n            PersonnelUni1To1FKInt p = (PersonnelUni1To1FKInt) dao.findPerson(PersonnelUni1To1FKInt.class, 1234);\n            assertPersonBeforeUpdate(p);\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail();\n        }\n    }\n\n    @Override\n    protected void findPersonByIdColumn()\n    {\n        PersonnelUni1To1FKInt p = (PersonnelUni1To1FKInt) dao.findPersonByIdColumn(PersonnelUni1To1FKInt.class, 1234);\n        assertPersonBeforeUpdate(p);\n    }\n\n    @Override\n    protected void findPersonByName()\n    {\n        List<PersonnelUni1To1FKInt> persons = dao.findPersonByName(PersonnelUni1To1FKInt.class, \"Amresh\");\n        assertPersons(persons);\n    }\n\n    @Override\n    protected void findAddressByIdColumn()\n    {\n        HabitatUni1To1FKInteger a = (HabitatUni1To1FKInteger) dao.findAddressByIdColumn(HabitatUni1To1FKInteger.class,\n                ADDRESS_ID);\n        assertAddressBeforeUpdate(a);\n    }\n\n    @Override\n    protected void findAddressByStreet()\n    {\n        List<HabitatUni1To1FKInteger> adds = dao.findAddressByStreet(HabitatUni1To1FKInteger.class, \"123, New street\");\n        Assert.assertNotNull(adds);\n        Assert.assertFalse(adds.isEmpty());\n        Assert.assertTrue(adds.size() == 1);\n\n        assertAddressBeforeUpdate(adds.get(0));\n    }\n\n    protected void update()\n    {\n        try\n        {\n            PersonnelUni1To1FKInt p = (PersonnelUni1To1FKInt) dao.findPerson(PersonnelUni1To1FKInt.class, 1234);\n            Assert.assertNotNull(p);\n\n            // dao.merge(p); //This merge operation should do nothing since\n            // nothing has changed\n\n            // p = (PersonnelUni1To1FK) dao.findPerson(PersonnelUni1To1FK.class,\n            // 1234);\n            p.setPersonName(\"Saurabh\");\n            p.getAddress().setStreet(\"Brand New Street\");\n            dao.merge(p);\n\n            PersonnelUni1To1FKInt pAfterMerge = (PersonnelUni1To1FKInt) dao.findPerson(PersonnelUni1To1FKInt.class,\n                    1234);\n            assertPersonAfterUpdate(pAfterMerge);\n        }\n        catch (Exception e)\n        {\n            \n            Assert.fail();\n        }\n    }\n\n    protected void remove()\n    {\n        try\n        {\n            // PersonnelUni1To1FK p = (PersonnelUni1To1FK)\n            // dao.findPerson(PersonnelUni1To1FK.class, 1234);\n            dao.remove(1234, PersonnelUni1To1FKInt.class);\n\n            PersonnelUni1To1FKInt pAfterRemoval = (PersonnelUni1To1FKInt) dao.findPerson(PersonnelUni1To1FKInt.class,\n                    1234);\n            Assert.assertNull(pAfterRemoval);\n        }\n        catch (Exception e)\n        {\n            Assert.fail();\n        }\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n       // shutDownRdbmsServer();\n        // tearDownInternal(ALL_PUs_UNDER_TEST);\n\n    }\n\n    /**\n     * Tear down.\n     * \n     * @throws Exception\n     *             the exception\n     */\n    @AfterClass\n    public static void tearDownAfterClass() throws Exception\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            // HBaseCli.stopCluster();\n        }\n    }\n\n    @Override\n    public void loadDataForPERSONNEL() throws InvalidRequestException, TException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(\n                    ByteBuffer.wrap(\"drop table \\\"PersonnelUni1To1FKInt\\\"\".getBytes(\"UTF-8\")), Compression.NONE,\n                    ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli\n                .executeCqlQuery(\n                        \"create table \\\"PersonnelUni1To1FKInt\\\" ( \\\"PERSON_ID\\\" int PRIMARY KEY,  \\\"PERSON_NAME\\\" text, \\\"ADDRESS_ID\\\" int)\",\n                        keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUni1To1FKInt\\\" ( \\\"PERSON_NAME\\\")\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"PersonnelUni1To1FKInt\\\" ( \\\"ADDRESS_ID\\\")\", keyspaceName);\n    }\n\n    @Override\n    public void loadDataForHABITAT() throws TException, InvalidRequestException, UnavailableException,\n            TimedOutException, SchemaDisagreementException\n    {\n        String keyspaceName = \"KunderaTests\";\n        CassandraCli.createKeySpace(keyspaceName);\n\n        CassandraCli.client.set_keyspace(keyspaceName);\n        try\n        {\n            CassandraCli.client.execute_cql3_query(ByteBuffer.wrap(\"drop table \\\"HabitatUni1To1FKInteger\\\"\".getBytes(\"UTF-8\")),\n                    Compression.NONE, ConsistencyLevel.ONE);\n        }\n        catch (Exception ex)\n        {\n\n        }\n        CassandraCli.executeCqlQuery(\n                \"create table \\\"HabitatUni1To1FKInteger\\\" ( \\\"ADDRESS_ID\\\" int PRIMARY KEY,  \\\"STREET\\\" text)\", keyspaceName);\n        CassandraCli.executeCqlQuery(\"create index on \\\"HabitatUni1To1FKInteger\\\" ( \\\"STREET\\\")\", keyspaceName);\n    }\n\n    /**\n     * @param p\n     */\n    private void assertPersonBeforeUpdate(PersonnelUni1To1FKInt p)\n    {\n        Assert.assertNotNull(p);\n        Assert.assertEquals(1234, p.getPersonId());\n        Assert.assertEquals(\"Amresh\", p.getPersonName());\n\n        assertAddressBeforeUpdate(p.getAddress());\n    }\n\n    /**\n     * @param p\n     */\n    private void assertAddressBeforeUpdate(HabitatUni1To1FKInteger add)\n    {\n        Assert.assertNotNull(add);\n        Assert.assertNotNull(add.getAddressId());\n        Assert.assertEquals(ADDRESS_ID, add.getAddressId());\n        Assert.assertEquals(\"123, New street\", add.getStreet());\n    }\n\n    /**\n     * @param pAfterMerge\n     */\n    private void assertPersonAfterUpdate(PersonnelUni1To1FKInt pAfterMerge)\n    {\n        Assert.assertNotNull(pAfterMerge);\n        Assert.assertEquals(\"Saurabh\", pAfterMerge.getPersonName());\n        HabitatUni1To1FKInteger addressAfterMerge = pAfterMerge.getAddress();\n        Assert.assertNotNull(addressAfterMerge);\n        Assert.assertEquals(\"Brand New Street\", addressAfterMerge.getStreet());\n    }\n\n    /**\n     * @param persons\n     */\n    private void assertPersons(List<PersonnelUni1To1FKInt> persons)\n    {\n        Assert.assertNotNull(persons);\n        Assert.assertFalse(persons.isEmpty());\n        Assert.assertTrue(persons.size() == 1);\n        PersonnelUni1To1FKInt person = persons.get(0);\n        assertPersonBeforeUpdate(person);\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForPERSONNEL()\n     */\n    @Override\n    protected void createSchemaForPERSONNEL() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUni1To1FKInt (PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID INTEGER)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.PersonnelUni1To1FKInt\");\n            cli.update(\"DROP TABLE KUNDERATESTS.PersonnelUni1To1FKInt\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.PersonnelUni1To1FKInt (PERSON_ID INTEGER PRIMARY KEY, PERSON_NAME VARCHAR(256), ADDRESS_ID INTEGER)\");\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.tests.crossdatastore.useraddress.AssociationBase#\n     * createSchemaForHABITAT()\n     */\n    @Override\n    protected void createSchemaForHABITAT() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUni1To1FKInteger (ADDRESS_ID INTEGER PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.HabitatUni1To1FKInteger\");\n            cli.update(\"DROP TABLE KUNDERATESTS.HabitatUni1To1FKInteger\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.HabitatUni1To1FKInteger (ADDRESS_ID INTEGER PRIMARY KEY, STREET VARCHAR(256))\");\n        }\n    }\n\n}"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/HabitatBi1To1FKBigDecimal.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport java.math.BigDecimal;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatBi1To1FKBigDecimal\", schema = \"KunderaTests@addCassandra\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatBi1To1FKBigDecimal\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private BigDecimal addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @OneToOne(mappedBy = \"address\")\n    private PersonnelBi1To1FKInt person;\n\n    public BigDecimal getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(BigDecimal addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public PersonnelBi1To1FKInt getPerson()\n    {\n        return person;\n    }\n\n    public void setPerson(PersonnelBi1To1FKInt person)\n    {\n        this.person = person;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/HabitatBi1ToMDouble.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatBi1ToMDouble\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatBi1ToMDouble\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private Double addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private PersonnelBi1ToMInt person;\n\n    public Double getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(Double addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public PersonnelBi1ToMInt getPerson()\n    {\n        return person;\n    }\n\n    public void setPerson(PersonnelBi1ToMInt person)\n    {\n        this.person = person;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/HabitatBiMTo1Char.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@IndexCollection(columns = { @Index(name = \"street\") })\n@Table(name = \"HabitatBiMTo1Char\", schema = \"KunderaTests@addCassandra\")\npublic class HabitatBiMTo1Char\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private char addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @OneToMany(mappedBy = \"address\", fetch = FetchType.LAZY)\n    private Set<PersonnelBiMTo1Int> people;\n\n    public char getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(char addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public Set<PersonnelBiMTo1Int> getPeople()\n    {\n        return people;\n    }\n\n    public void setPeople(Set<PersonnelBiMTo1Int> people)\n    {\n        this.people = people;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/HabitatBiMToMShort.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatBiMToMShort\", schema = \"KunderaTests@addCassandra\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatBiMToMShort\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private short addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @ManyToMany(mappedBy = \"addresses\", fetch = FetchType.LAZY)\n    private Set<PersonnelBiMToMInt> people;\n\n    public short getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(short addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public Set<PersonnelBiMToMInt> getPeople()\n    {\n        return people;\n    }\n\n    public void setPeople(Set<PersonnelBiMToMInt> people)\n    {\n        this.people = people;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/HabitatOToOFKEntityInt.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatOToOFKEntityInt\", schema = \"KunderaTests@addMongo\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatOToOFKEntityInt\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private int addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * \n     */\n    public HabitatOToOFKEntityInt()\n    {\n    }\n\n    public int getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(int addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/HabitatUni1To1FKInteger.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatUni1To1FKInteger\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatUni1To1FKInteger\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private Integer addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public Integer getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(Integer addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/HabitatUni1ToMFloat.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatUni1ToMFloat\", schema = \"KunderaTests@addCassandra\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatUni1ToMFloat\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private float addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public float getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(float addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/HabitatUniMTo1Long.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatUniMTo1Long\", schema = \"KunderaTests@addCassandra\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatUniMTo1Long\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private Long addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public Long getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(Long addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/HabitatUniMToMBigInteger.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport java.math.BigInteger;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatUniMToMBigInteger\", schema = \"KunderaTests@addCassandra\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatUniMToMBigInteger\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private BigInteger addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public BigInteger getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(BigInteger addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/PersonnelBi1To1FKInt.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelBi1To1FKInt\", schema = \"KunderaTests@addCassandra\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelBi1To1FKInt\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private Integer personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HabitatBi1To1FKBigDecimal address;\n\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatBi1To1FKBigDecimal getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatBi1To1FKBigDecimal address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/PersonnelBi1ToMInt.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelBi1ToMInt\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelBi1ToMInt\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private int personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"person\")\n    private Set<HabitatBi1ToMDouble> addresses;\n\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<HabitatBi1ToMDouble> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<HabitatBi1ToMDouble> addresses)\n    {\n        this.addresses = addresses;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/PersonnelBiMTo1Int.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@IndexCollection(columns = { @Index(name = \"personName\") })\n@Table(name = \"PersonnelBiMTo1Int\", schema = \"KunderaTests@addCassandra\")\npublic class PersonnelBiMTo1Int\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private int personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HabitatBiMTo1Char address;\n\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatBiMTo1Char getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatBiMTo1Char address)\n    {\n        this.address = address;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/PersonnelBiMToMInt.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelBiMToMInt\", schema = \"KunderaTests@addCassandra\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelBiMToMInt\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private int personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"PersonnelBiMToMInt_HabitatBiMToMShort\", schema = \"KunderaTests\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Set<HabitatBiMToMShort> addresses;\n\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<HabitatBiMToMShort> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<HabitatBiMToMShort> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/PersonnelOToOFKEntityInt.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelOToOFKEntityInt\", schema = \"KunderaTests@secIdxAddCassandra\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelOToOFKEntityInt\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private int personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HabitatOToOFKEntityInt address;\n\n    /**\n     * \n     */\n    public PersonnelOToOFKEntityInt()\n    {\n    }\n\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatOToOFKEntityInt getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatOToOFKEntityInt address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/PersonnelUni1To1FKInt.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelUni1To1FKInt\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelUni1To1FKInt\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private Integer personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HabitatUni1To1FKInteger address;\n\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatUni1To1FKInteger getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatUni1To1FKInteger address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/PersonnelUni1ToMInt.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelUni1ToMInt\", schema = \"KunderaTests@addCassandra\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelUni1ToMInt\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private int personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<HabitatUni1ToMFloat> addresses;\n\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<HabitatUni1ToMFloat> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<HabitatUni1ToMFloat> addresses)\n    {\n        this.addresses = addresses;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/PersonnelUniMTo1Int.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelUniMTo1Int\", schema = \"KunderaTests@addCassandra\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelUniMTo1Int\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private int personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HabitatUniMTo1Long address;\n\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatUniMTo1Long getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatUniMTo1Long address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/datatype/entities/PersonnelUniMToMInt.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.datatype.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelUniMToMInt\", schema = \"KunderaTests@addCassandra\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelUniMToMInt\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private int personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"PersonnelUniMToMInt_HabitatUniMToMBigInteger\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\")}, schema = \"KunderaTests\")\n    private Set<HabitatUniMToMBigInteger> addresses;\n\n    public int getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<HabitatUniMToMBigInteger> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<HabitatUniMToMBigInteger> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/HabitatBi1To1FK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatBi1To1FK\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatBi1To1FK\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @OneToOne(mappedBy = \"address\", fetch = FetchType.LAZY)\n    private PersonnelBi1To1FK person;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public PersonnelBi1To1FK getPerson()\n    {\n        return person;\n    }\n\n    public void setPerson(PersonnelBi1To1FK person)\n    {\n        this.person = person;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/HabitatBi1To1PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatBi1To1PK\", schema = \"hibernatepoc\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatBi1To1PK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @OneToOne(mappedBy = \"address\", fetch = FetchType.LAZY)\n    private PersonnelBi1To1PK person;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public PersonnelBi1To1PK getPerson()\n    {\n        return person;\n    }\n\n    public void setPerson(PersonnelBi1To1PK person)\n    {\n        this.person = person;\n    }\n\n}"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/HabitatBi1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatBi1ToM\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatBi1ToM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @ManyToOne(fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private PersonnelBi1ToM person;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public PersonnelBi1ToM getPerson()\n    {\n        return person;\n    }\n\n    public void setPerson(PersonnelBi1ToM person)\n    {\n        this.person = person;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/HabitatBiMTo1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@IndexCollection(columns = { @Index(name = \"street\") })\n@Table(name = \"HabitatBiMTo1\", schema = \"KunderaTests\")\npublic class HabitatBiMTo1\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @OneToMany(mappedBy = \"address\", fetch = FetchType.LAZY)\n    private Set<PersonnelBiMTo1> people;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public Set<PersonnelBiMTo1> getPeople()\n    {\n        return people;\n    }\n\n    public void setPeople(Set<PersonnelBiMTo1> people)\n    {\n        this.people = people;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/HabitatBiMToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatBiMToM\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatBiMToM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    @ManyToMany(mappedBy = \"addresses\", fetch = FetchType.LAZY)\n    private Set<PersonnelBiMToM> people;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n    public Set<PersonnelBiMToM> getPeople()\n    {\n        return people;\n    }\n\n    public void setPeople(Set<PersonnelBiMToM> people)\n    {\n        this.people = people;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/HabitatOToOFKEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatOToOFKEntity\", schema = \"KunderaTests@addMongo\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatOToOFKEntity\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * \n     */\n    public HabitatOToOFKEntity()\n    {\n    }\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/HabitatUni1To1FK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatUni1To1FK\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatUni1To1FK\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/HabitatUni1To1PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatUni1To1PK\", schema = \"KunderaExamples\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatUni1To1PK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/HabitatUni1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatUni1ToM\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatUni1ToM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/HabitatUniMTo1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatUniMTo1\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatUniMTo1\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/HabitatUniMToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"HabitatUniMToM\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class HabitatUniMToM\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/Personnel.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"Personnel\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class Personnel\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/PersonnelBi1To1FK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelBi1To1FK\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelBi1To1FK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HabitatBi1To1FK address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatBi1To1FK getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatBi1To1FK address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/PersonnelBi1To1PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelBi1To1PK\", schema = \"hibernatepoc\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelBi1To1PK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)\n    @PrimaryKeyJoinColumn\n    private HabitatBi1To1PK address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatBi1To1PK getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatBi1To1PK address)\n    {\n        this.address = address;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/PersonnelBi1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelBi1ToM\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelBi1ToM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"person\")\n//    @JoinColumn(name=\"PERSON_ID\")\n    private Set<HabitatBi1ToM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<HabitatBi1ToM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<HabitatBi1ToM> addresses)\n    {\n        this.addresses = addresses;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/PersonnelBiMTo1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@IndexCollection(columns = { @Index(name = \"personName\") })\n@Table(name = \"PersonnelBiMTo1\", schema = \"KunderaTests\")\npublic class PersonnelBiMTo1\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HabitatBiMTo1 address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatBiMTo1 getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatBiMTo1 address)\n    {\n        this.address = address;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/PersonnelBiMToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelBiMToM\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelBiMToM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinTable(name = \"PERSONNEL_ADDRESS\", schema = \"KunderaTests\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n    private Set<HabitatBiMToM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<HabitatBiMToM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<HabitatBiMToM> addresses)\n    {\n        this.addresses = addresses;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/PersonnelOToOFKEntity.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelOToOFKEntity\", schema = \"KunderaTests@secIdxAddCassandra\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelOToOFKEntity\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HabitatOToOFKEntity address;\n\n    /**\n     * \n     */\n    public PersonnelOToOFKEntity()\n    {\n    }\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatOToOFKEntity getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatOToOFKEntity address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/PersonnelUni1To1FK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelUni1To1FK\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelUni1To1FK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HabitatUni1To1FK address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatUni1To1FK getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatUni1To1FK address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/PersonnelUni1To1PK.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.OneToOne;\nimport javax.persistence.PrimaryKeyJoinColumn;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelUni1To1PK\", schema = \"hibernatepoc\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelUni1To1PK\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)\n    @PrimaryKeyJoinColumn\n    private HabitatUni1To1PK address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatUni1To1PK getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatUni1To1PK address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/PersonnelUni1ToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelUni1ToM\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelUni1ToM\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<HabitatUni1ToM> addresses;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public Set<HabitatUni1ToM> getAddresses()\n    {\n        return addresses;\n    }\n\n    public void setAddresses(Set<HabitatUni1ToM> addresses)\n    {\n        this.addresses = addresses;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/PersonnelUniMTo1.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.ManyToOne;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelUniMTo1\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelUniMTo1\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HabitatUniMTo1 address;\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatUniMTo1 getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatUniMTo1 address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/crossdatastore/useraddress/entities/PersonnelUniMToM.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.crossdatastore.useraddress.entities;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.JoinTable;\nimport javax.persistence.ManyToMany;\nimport javax.persistence.Table;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@Table(name = \"PersonnelUniMToM\", schema = \"KunderaTests\")\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class PersonnelUniMToM {\n\t@Id\n\t@Column(name = \"PERSON_ID\")\n\tprivate String personId;\n\n\t@Column(name = \"PERSON_NAME\")\n\tprivate String personName;\n\n\t@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n\t@JoinTable(name = \"PERSONNEL_ADDRESS\", schema = \"KunderaTests\", joinColumns = { @JoinColumn(name = \"PERSON_ID\") }, inverseJoinColumns = { @JoinColumn(name = \"ADDRESS_ID\") })\n\tprivate Set<HabitatUniMToM> addresses;\n\n\tpublic String getPersonId() {\n\t\treturn personId;\n\t}\n\n\tpublic String getPersonName() {\n\t\treturn personName;\n\t}\n\n\tpublic void setPersonName(String personName) {\n\t\tthis.personName = personName;\n\t}\n\n\tpublic void setPersonId(String personId) {\n\t\tthis.personId = personId;\n\t}\n\n\tpublic Set<HabitatUniMToM> getAddresses() {\n\t\treturn addresses;\n\t}\n\n\tpublic void setAddresses(Set<HabitatUniMToM> addresses) {\n\t\tthis.addresses = addresses;\n\t}\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/embeddedRDBMS/EmbeddedRDBMSUserTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.embeddedRDBMS;\n\nimport java.nio.ByteBuffer;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport org.apache.cassandra.locator.SimpleStrategy;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.impetus.client.crud.RDBMSCli;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.property.accessor.DateAccessor;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class EmbeddedRDBMSUserTest\n{\n    private RDBMSCli cli;\n\n    private static final String KEYSPACE = \"KunderaTests\";\n\n    /** the log used by this class. */\n    private static Logger log = LoggerFactory.getLogger(EmbeddedRDBMSUserTest.class);\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        \n        try\n        {\n            CassandraCli.cassandraSetUp();\n            CassandraCli.initClient();\n            CassandraCli.createKeySpace(\"Pickr\");\n            loadData();\n            cli = new RDBMSCli(KEYSPACE);\n            cli.createSchema(KEYSPACE);\n            createTable();\n        }\n        catch (Exception e)\n        {\n            log.error(\"Error in RDBMS cli \", e);\n        }\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        truncateRdbms();\n        truncateColumnFamily();\n        // HBaseCli.stopCluster();\n    }\n\n    @Test\n    public void test()\n    {\n\n        EntityManagerFactory emf = Persistence\n                .createEntityManagerFactory(\"rdbms,secIdxAddCassandra,piccandra,addMongo,picongo\");\n        try\n        {\n            loadData();\n        }\n        catch (InvalidRequestException e)\n        {\n\n            \n        }\n        catch (TException e)\n        {\n\n            \n        }\n        \n        EntityManager em = emf.createEntityManager();\n        // em.getTransaction().begin();\n        // em.setFlushMode(FlushModeType.COMMIT);\n\n        // prepare user object.\n        User user = addUser();\n\n        // Add Personal Details\n        addPersonalDetails(user);\n\n        // Persist user with tweets.\n        persist(user, em);\n        em.clear();\n\n        // Find by Id\n        user = findByKey(em, user.getUserId());\n\n        // Add tweets.(e.g. Association mapping)\n        addTweets(user, \"big data sample 1 for demo\", DateAccessor.getDateByPattern(\"MAY/22/2012 8:12:30\"), \"tweet_1\");\n        addTweets(user, \"big data sample 2 for demo\", DateAccessor.getDateByPattern(\"22-MAY-2012\"), \"tweet_2\");\n\n        // Persist user with tweets.\n        persist(user, em);\n        em.clear();\n\n        // Execute query.\n        String query = \"Select u from User u\";\n        findByQuery(em, query);\n\n        // Query by parameter\n        query = \"Select u from User u where u.emailId =?1\";\n\n        // find by named parameter(e.g. email)\n        findByEmail(em, query, \"bigdata@impetus.com\");\n\n        // em.getTransaction().commit();\n\n    }\n\n    private static void addPersonalDetails(User user)\n    {\n        PersonalDetail personalDetail = new PersonalDetail();\n        personalDetail.setName(\"bigdata\");\n        personalDetail.setPassword(\"xxxxxx\");\n        personalDetail.setPersonalDetailId(\"1\");\n        personalDetail.setAge(null);\n        user.setPersonalDetail(personalDetail);\n    }\n\n    /**\n     * @param user\n     */\n    private static void addTweets(User user, String body, Date tweetDate, String tweetId)\n    {\n        Tweets tweet = new Tweets();\n        tweet.setTweetId(tweetId);\n        tweet.setBody(body);\n        tweet.setTweetDate(tweetDate);\n\n        user.getTweets().add(tweet);\n\n    }\n\n    /**\n     * @return\n     */\n    private static User addUser()\n    {\n        User user = new User();\n        user.setUserId(\"impetus_user\");\n        user.setEmailId(\"bigdata@impetus.com\");\n        user.setFirstName(\"bigdata\");\n        user.setLastName(\"impetus\");\n        user.setTweets(new HashSet<Tweets>());\n        return user;\n    }\n\n    /**\n     * @param user\n     */\n    private static void persist(User user, EntityManager em)\n    {\n        em.persist(user);\n    }\n\n    /**\n     * @param em\n     * @param userId\n     */\n    private static User findByKey(EntityManager em, String userId)\n    {\n        User user = em.find(User.class, userId);\n        System.out.println(\"[On Find by key]\");\n        System.out.println(\"#######################START##########################################\");\n        System.out.println(\"\\n\");\n        System.out.println(\"\\t\\t User's first name:\" + user.getFirstName());\n        System.out.println(\"\\t\\t User's emailId:\" + user.getEmailId());\n        System.out.println(\"\\t\\t User's total tweets:\" + user.getTweets());\n        System.out.println(\"\\n\");\n        System.out.println(\"#######################END############################################\");\n        System.out.println(\"\\n\");\n        return user;\n    }\n\n    /**\n     * @param em\n     * @param query\n     */\n    private static void findByQuery(EntityManager em, String query)\n    {\n        Query q = em.createNamedQuery(query);\n\n        System.out.println(\"[On Find All by Query]\");\n        List<User> users = q.getResultList();\n\n        if (users == null)\n        {\n            System.out.println(\"0 Users Returned\");\n            return;\n        }\n\n        System.out.println(\"#######################START##########################################\");\n        System.out.println(\"\\t\\t Total number of users:\" + users.size());\n        System.out.println(\"\\t\\t User's total tweets:\" + users.get(0).getTweets().size());\n        printTweets(users);\n        System.out.println(\"\\n\");\n        // System.out.println(\"First tweet:\" users.get(0).getTweets().);\n        System.out.println(\"#######################END############################################\");\n        System.out.println(\"\\n\");\n    }\n\n    private static void findByEmail(EntityManager em, String query, String parameter)\n    {\n        Query q = em.createNamedQuery(query);\n        System.out.println(\"[On Find by Email]\");\n        System.out.println(\"#######################START##########################################\");\n        q.setParameter(1, parameter);\n\n        List<User> users = q.getResultList();\n\n        if (users == null)\n        {\n            System.out.println(\"0 Users Returned\");\n            return;\n        }\n\n        printTweets(users);\n        System.out.println(\"\\n\");\n        System.out.println(\"#######################END############################################\");\n    }\n\n    private static void printTweets(List<User> users)\n    {\n        // No null check as already knew it will not be null.\n        Iterator<Tweets> tweets = users.get(0).getTweets().iterator();\n\n        int counter = 1;\n        while (tweets.hasNext())\n        {\n            System.out.println(\"\\n\");\n            System.out.println(\"\\t\\t Tweet No:#\" + counter++);\n            Tweets rec = tweets.next();\n            System.out.println(\"\\t\\t tweet is ->\" + rec.getBody());\n            System.out.println(\"\\t\\t Tweeted at ->\" + rec.getTweetDate());\n        }\n    }\n\n    private void createTable() throws SQLException\n    {\n        try\n        {\n            cli.update(\"CREATE TABLE KUNDERATESTS.user (emailId VARCHAR(150), first_name VARCHAR(150), last_name VARCHAR(150), name VARCHAR(150), password VARCHAR(150), personal_detail_id VARCHAR(150), rel_status VARCHAR(150), user_id VARCHAR(150),age INT)\");\n        }\n        catch (Exception e)\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.user\");\n            cli.update(\"DROP TABLE KUNDERATESTS.user\");\n            cli.update(\"CREATE TABLE KUNDERATESTS.user (emailId VARCHAR(150), first_name VARCHAR(150), last_name VARCHAR(150), name VARCHAR(150), password VARCHAR(150), personal_detail_id VARCHAR(150), rel_status VARCHAR(150), user_id VARCHAR(150),age INT)\");\n        }\n    }\n\n    private void truncateRdbms()\n    {\n        try\n        {\n            cli.update(\"DELETE FROM KUNDERATESTS.user\");\n            cli.update(\"DROP TABLE KUNDERATESTS.user\");\n            cli.shutdown();\n        }\n        catch (Exception e)\n        {\n            // do nothing..weird!!\n        }\n\n    }\n\n    private void truncateColumnFamily()\n    {\n        String[] columnFamily = new String[] { \"tweets\" };\n        CassandraCli.truncateColumnFamily(KEYSPACE, columnFamily);\n    }\n\n    private void loadData() throws InvalidRequestException, TException, SchemaDisagreementException\n    {\n        KsDef ksDef = null;\n\n        CfDef cfDef = new CfDef();\n        cfDef.name = \"tweets\";\n        cfDef.keyspace = KEYSPACE;\n        // cfDef.column_type = \"Super\";\n        cfDef.setComparator_type(\"UTF8Type\");\n        cfDef.setDefault_validation_class(\"UTF8Type\");\n        ColumnDef columnDefPersonName = new ColumnDef(ByteBuffer.wrap(\"body\".getBytes()), \"UTF8Type\");\n        columnDefPersonName.index_type = IndexType.KEYS;\n\n        ColumnDef columnDefAddressId = new ColumnDef(ByteBuffer.wrap(\"tweeted_at\".getBytes()), \"DateType\");\n        columnDefAddressId.index_type = IndexType.KEYS;\n\n        ColumnDef columnDefUserId = new ColumnDef(ByteBuffer.wrap(\"user_id\".getBytes()), \"UTF8Type\");\n        columnDefUserId.index_type = IndexType.KEYS;\n\n        cfDef.addToColumn_metadata(columnDefPersonName);\n        cfDef.addToColumn_metadata(columnDefAddressId);\n        cfDef.addToColumn_metadata(columnDefUserId);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(cfDef);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(KEYSPACE);\n            CassandraCli.client.set_keyspace(KEYSPACE);\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            // CassandraCli.client.set_keyspace(\"KunderaTests\");\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"tweets\"))\n                {\n\n                    CassandraCli.client.system_drop_column_family(\"tweets\");\n\n                }\n            }\n            CassandraCli.client.system_add_column_family(cfDef);\n\n        }\n        catch (NotFoundException e)\n        {\n            addKeyspace(ksDef, cfDefs);\n        }\n\n        CassandraCli.client.set_keyspace(KEYSPACE);\n\n    }\n\n    private void addKeyspace(KsDef ksDef, List<CfDef> cfDefs) throws InvalidRequestException,\n            SchemaDisagreementException, TException\n    {\n        ksDef = new KsDef(KEYSPACE, SimpleStrategy.class.getSimpleName(), cfDefs);\n        // Set replication factor\n        if (ksDef.strategy_options == null)\n        {\n            ksDef.strategy_options = new LinkedHashMap<String, String>();\n        }\n        // Set replication factor, the value MUST be an integer\n        ksDef.strategy_options.put(\"replication_factor\", \"1\");\n        CassandraCli.client.system_add_keyspace(ksDef);\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/embeddedRDBMS/PersonalDetail.java",
    "content": "/*\r\n * Copyright 2011 Impetus Infotech.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n *      http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\npackage com.impetus.kundera.tests.embeddedRDBMS;\r\n\r\nimport java.util.UUID;\r\n\r\nimport javax.persistence.Column;\r\nimport javax.persistence.Embeddable;\r\n\r\n/**\r\n * Entity class for user's personal details\r\n * \r\n * @author amresh.singh\r\n */\r\n\r\n@Embeddable\r\npublic class PersonalDetail\r\n{\r\n    @Column(name = \"personal_detail_id\")\r\n    private String personalDetailId;\r\n\r\n    @Column(name = \"name\")\r\n    private String name;\r\n\r\n    @Column(name = \"password\")\r\n    private String password;\r\n\r\n    @Column(name = \"rel_status\")\r\n    private String relationshipStatus;\r\n\r\n    @Column(name = \"age\")\r\n    private Short age;\r\n\r\n    public PersonalDetail()\r\n    {\r\n\r\n    }\r\n\r\n    public PersonalDetail(String name, String password, String relationshipStatus, Short age)\r\n    {\r\n        setPersonalDetailId(UUID.randomUUID().toString());\r\n        setName(name);\r\n        setPassword(password);\r\n        setRelationshipStatus(relationshipStatus);\r\n        setAge(age);\r\n    }\r\n\r\n    /**\r\n     * @return the personalDetailId\r\n     */\r\n    public String getPersonalDetailId()\r\n    {\r\n        return personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @param personalDetailId\r\n     *            the personalDetailId to set\r\n     */\r\n    public void setPersonalDetailId(String personalDetailId)\r\n    {\r\n        this.personalDetailId = personalDetailId;\r\n    }\r\n\r\n    /**\r\n     * @return the name\r\n     */\r\n    public String getName()\r\n    {\r\n        return name;\r\n    }\r\n\r\n    /**\r\n     * @param name\r\n     *            the name to set\r\n     */\r\n    public void setName(String name)\r\n    {\r\n        this.name = name;\r\n    }\r\n\r\n    /**\r\n     * @return the password\r\n     */\r\n    public String getPassword()\r\n    {\r\n        return password;\r\n    }\r\n\r\n    /**\r\n     * @param password\r\n     *            the password to set\r\n     */\r\n    public void setPassword(String password)\r\n    {\r\n        this.password = password;\r\n    }\r\n\r\n    /**\r\n     * @return the relationshipStatus\r\n     */\r\n    public String getRelationshipStatus()\r\n    {\r\n        return relationshipStatus;\r\n    }\r\n\r\n    /**\r\n     * @param relationshipStatus\r\n     *            the relationshipStatus to set\r\n     */\r\n    public void setRelationshipStatus(String relationshipStatus)\r\n    {\r\n        this.relationshipStatus = relationshipStatus;\r\n    }\r\n\r\n    public Short getAge()\r\n    {\r\n        return age;\r\n    }\r\n\r\n    public void setAge(Short age)\r\n    {\r\n        this.age = age;\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/embeddedRDBMS/Tweets.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.embeddedRDBMS;\n\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n\n\n/**\n * @author vivek.mishra\n * \n */\n/**\n * create column family tweets with comparator=UTF8Type and\n * column_metadata=[{column_name: body, validation_class: UTF8Type, index_type:\n * KEYS}, {column_name: tweeted_at, validation_class: DateType, index_type:\n * KEYS}, {column_name: user_id, validation_class: UTF8Type, index_type: KEYS}];\n */\n@Entity\n@Table(name = \"tweets\", schema = \"KunderaTests@secIdxAddCassandra\")\n@IndexCollection(columns = { @Index(name = \"body\"),  @Index(name = \"tweetDate\")})\npublic class Tweets\n{\n\n    @Id\n    @Column(name = \"tweet_id\")\n    private String tweetId;\n\n    @Column(name = \"body\")\n    private String body;\n\n    @Column(name = \"tweeted_at\")\n    @Temporal(TemporalType.DATE)\n    private Date tweetDate;\n\n    public Tweets()\n    {\n        // Default constructor.\n    }\n\n    /**\n     * @return the tweetId\n     */\n    public String getTweetId()\n    {\n        return tweetId;\n    }\n\n    /**\n     * @param tweetId\n     *            the tweetId to set\n     */\n    public void setTweetId(String tweetId)\n    {\n        this.tweetId = tweetId;\n    }\n\n    /**\n     * @return the body\n     */\n    public String getBody()\n    {\n        return body;\n    }\n\n    /**\n     * @param body\n     *            the body to set\n     */\n    public void setBody(String body)\n    {\n        this.body = body;\n    }\n\n    /**\n     * @return the tweetDate\n     */\n    public Date getTweetDate()\n    {\n        return tweetDate;\n    }\n\n    /**\n     * @param tweetDate\n     *            the tweetDate to set\n     */\n    public void setTweetDate(Date tweetDate)\n    {\n        this.tweetDate = tweetDate;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/embeddedRDBMS/User.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.embeddedRDBMS;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Embedded;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * @author vivek.mishra\n * \n */\n@Entity\n@Table(name = \"user\", schema = \"KunderaTests\")\npublic class User\n{\n\n    @Id\n    @Column(name = \"user_id\")\n    private String userId;\n\n    @Column(name = \"first_name\")\n    private String firstName;\n\n    @Column(name = \"last_name\")\n    private String lastName;\n\n    @Column(name = \"emailId\")\n    private String emailId;\n\n    @Embedded\n    private PersonalDetail personalDetail;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"user_id\")\n    private Set<Tweets> tweets;\n\n    public User()\n    {\n        // Default constructor.\n    }\n\n    /**\n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * @param userId\n     *            the userId to set\n     */\n    public void setUserId(String userId)\n    {\n        this.userId = userId;\n    }\n\n    /**\n     * @return the firstName\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * @param firstName\n     *            the firstName to set\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * @return the lastName\n     */\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    /**\n     * @param lastName\n     *            the lastName to set\n     */\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n    /**\n     * @return the emailId\n     */\n    public String getEmailId()\n    {\n        return emailId;\n    }\n\n    /**\n     * @param emailId\n     *            the emailId to set\n     */\n    public void setEmailId(String emailId)\n    {\n        this.emailId = emailId;\n    }\n\n    /**\n     * @return the tweets\n     */\n    public Set<Tweets> getTweets()\n    {\n        return tweets;\n    }\n\n    /**\n     * @param tweets\n     *            the tweets to set\n     */\n    public void setTweets(Set<Tweets> tweets)\n    {\n        this.tweets = tweets;\n    }\n\n    /**\n     * @return the personalDetail\n     */\n    public PersonalDetail getPersonalDetail()\n    {\n        return personalDetail;\n    }\n\n    /**\n     * @param personalDetail\n     *            the personalDetail to set\n     */\n    public void setPersonalDetail(PersonalDetail personalDetail)\n    {\n        this.personalDetail = personalDetail;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/entities/AddressCassandra.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n@Entity\npublic class AddressCassandra\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/entities/AddressMongoNoAnnotation.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@IndexCollection(columns = { @Index(name = \"street\") })\npublic class AddressMongoNoAnnotation\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n    \n    public void setAddressId(String id)\n    {\n        this.addressId = id;\n    }\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n}"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/entities/CommonUser.java",
    "content": "package com.impetus.kundera.tests.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"CommonUser\")\npublic class CommonUser\n{\n\n    /** The person id. */\n    @Id\n    private String userId;\n\n    /** The first name. */\n    @Column(name = \"first_name\")\n    private String firstName;\n\n    /** The last name. */\n    @Column(name = \"last_name\")\n    private String lastName;\n\n    /**\n     * Instantiates a new personnel dto.\n     * \n     * @param userId\n     *            the person id\n     * @param firstName\n     *            the first name\n     * @param lastName\n     *            the last name\n     */\n    public CommonUser(String userId, String firstName, String lastName)\n    {\n        this.userId = userId;\n        this.firstName = firstName;\n        this.lastName = lastName;\n    }\n\n    /**\n     * Instantiates a new personnel dto.\n     */\n    public CommonUser()\n    {\n\n    }\n\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    public void setUserId(String userId)\n    {\n        this.userId = userId;\n    }\n\n    /**\n     * Gets the first name.\n     * \n     * @return the firstName\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * Sets the first name.\n     * \n     * @param firstName\n     *            the firstName to set\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * Gets the last name.\n     * \n     * @return the lastName\n     */\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    /**\n     * Sets the last name.\n     * \n     * @param lastName\n     *            the lastName to set\n     */\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/entities/PersonDetailAnnotationPolyglotTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.entities;\n\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author Chhavi Gangwal\n * \n */\npublic class PersonDetailAnnotationPolyglotTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    /**\n     * sets up cassandra client\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n\n    }\n\n    /**\n     * drops the keyspace of cassandra\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n\n        CassandraCli.dropKeySpace(\"KunderaTests\");\n    }\n    \n    /**\n     * Test method for testing asscoiation between Mongodb and cassandra\n     */\n    @Test\n    public void test()\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"addMongoNoAnnotateTest,secIdxAddCassandraNoAnnotateTest\");\n        em = emf.createEntityManager();\n\n        AddressMongoNoAnnotation address = new AddressMongoNoAnnotation();\n        address.setAddressId(\"1\");\n        address.setStreet(\"sector 20, G Block\");\n\n        UserCassandraNoAnnotation user = new UserCassandraNoAnnotation();\n        user.setPersonId(1);\n        user.setAddress(address);\n        user.setPersonName(\"Kuldeep\");\n\n        em.persist(user);\n\n        em.clear();\n\n        List<UserCassandraNoAnnotation> result = em.createQuery(\"Select u from UserCassandraNoAnnotation u\")\n                .getResultList();\n        Assert.assertNotNull(result);\n        Assert.assertEquals(1, result.size());\n        Assert.assertNotNull(result.get(0).getAddress());\n        Assert.assertEquals(\"sector 20, G Block\", result.get(0).getAddress().getStreet());\n        Assert.assertEquals(\"Kuldeep\", result.get(0).getPersonName());\n\n        em.close();\n        emf.close();\n    }\n    \n    /**\n     * Test method for testing polyglot between Mongodb and cassandra\n     */\n    @Test\n    public void testAnnotateforCassToMongo()\n    {\n\n        Map propertyMap = new HashMap();\n\n        propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"create-drop\");\n        EntityManagerFactory emfCass = Persistence.createEntityManagerFactory(\"noAnnotationAddCassandra\", propertyMap);\n        EntityManager emCass = emfCass.createEntityManager();\n\n        PersonDetailClassMap p = new PersonDetailClassMap();\n        p.setPersonId(\"1\");\n        p.setFirstName(\"Chhavi\");\n        p.setLastName(\"Gangwal\");\n        emCass.persist(p);\n        emCass.clear();\n\n        PersonDetailClassMap found = emCass.find(PersonDetailClassMap.class, \"1\");\n        Assert.assertNotNull(found);\n        Assert.assertEquals(\"1\", found.getPersonId());\n        Assert.assertEquals(\"Chhavi\", found.getFirstName());\n        Assert.assertEquals(\"Gangwal\", found.getLastName());\n\n        emCass.close();\n        emfCass.close();\n\n        EntityManagerFactory emfMongo = Persistence.createEntityManagerFactory(\"noAnnotationAddMongo\", propertyMap);\n        EntityManager emMongo = emfMongo.createEntityManager();\n\n        emMongo.persist(found);\n\n        PersonDetailClassMap foundMongo = emMongo.find(PersonDetailClassMap.class, \"1\");\n        Assert.assertNotNull(foundMongo);\n        Assert.assertEquals(\"1\", foundMongo.getPersonId());\n        Assert.assertEquals(\"Chhavi\", foundMongo.getFirstName());\n        Assert.assertEquals(\"Gangwal\", foundMongo.getLastName());\n\n        emMongo.close();\n        emfMongo.close();\n    }\n    \n    /**\n     * Test method for testing polyglot between RDBMS and cassandra\n     */\n    @Test\n    public void testRDBMSPolyglot()\n    {\n\n        emf = Persistence.createEntityManagerFactory(\"cassandraAddressNoAnnotate,rdbmsNoAnnotateTest\");\n        em = emf.createEntityManager();\n\n        PersonRDBMSPolyglot person = new PersonRDBMSPolyglot();\n        person.setPersonId(\"p1\");\n\n        AddressCassandra address = new AddressCassandra();\n        address.setAddressId(\"addr_1\");\n        address.setStreet(\"Street\");\n\n        person.setAddress(address);\n\n        em.persist(person);\n        \n        PersonRDBMSPolyglot found = em.find(PersonRDBMSPolyglot.class, \"p1\");\n        Assert.assertNotNull(found);\n        Assert.assertEquals(\"p1\", found.getPersonId());\n      \n\n        em.close();\n        emf.close();\n\n    }\n    \n    /**\n     * Test method for testing entity with no id set\n     */\n    @Test\n    public void testInvalidEntityObject()\n    {\n        try\n        {\n\n            Map<String, Object> puProperties = new HashMap<String, Object>();\n            puProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n\n            emf = Persistence.createEntityManagerFactory(\"rdbms,secIdxAddCassandra,piccandra,addMongo,picongo\",\n                    puProperties);\n\n            em = emf.createEntityManager();\n\n            AddressCassandra address = new AddressCassandra();\n            address.setAddressId(\"addr_1\");\n            address.setStreet(\"Street\");\n\n            PersonRDBMSPolyglot person = new PersonRDBMSPolyglot();\n            person.setAddress(address);\n\n            em.persist(person);\n\n            em.close();\n            emf.close();\n        }\n        catch (Exception iex)\n        {\n            Assert.assertNotNull(iex.getMessage());\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/entities/PersonDetailClassMap.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n\n/**\n * The Class PersonnelDTO.\n * \n * @author Chhavi Gangwal\n */\n\n@Entity\npublic class PersonDetailClassMap\n{\n    /** The person id. */\n    @Id\n    private String personId;\n\n    /** The first name. */\n    @Column(name = \"first_name\")\n    private String firstName;\n\n    /** The last name. */\n    @Column(name = \"last_name\")\n    private String lastName;\n\n    /**\n     * Instantiates a new personnel dto.\n     * \n     * @param personId\n     *            the person id\n     * @param firstName\n     *            the first name\n     * @param lastName\n     *            the last name\n     */\n    public PersonDetailClassMap(String personId, String firstName, String lastName)\n    {\n        this.personId = personId;\n        this.firstName = firstName;\n        this.lastName = lastName;\n    }\n\n    /**\n     * Instantiates a new personnel dto.\n     */\n    public PersonDetailClassMap()\n    {\n\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the personId\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the personId to set\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the first name.\n     * \n     * @return the firstName\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * Sets the first name.\n     * \n     * @param firstName\n     *            the firstName to set\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * Gets the last name.\n     * \n     * @return the lastName\n     */\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    /**\n     * Sets the last name.\n     * \n     * @param lastName\n     *            the lastName to set\n     */\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/entities/PersonDetailNoSchema.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * The Class PersonnelDTO.\n * \n * @author Chhavi Gangwal\n */\n\n@Entity\n@Table(name = \"person\")\npublic class PersonDetailNoSchema\n{\n    \n    /** The person id. */\n    @Id\n    private String personId;\n\n    /** The first name. */\n    @Column(name = \"first_name\")\n    private String firstName;\n\n    /** The last name. */\n    @Column(name = \"last_name\")\n    private String lastName;\n\n    /**\n     * Instantiates a new personnel dto.\n     * \n     * @param personId\n     *            the person id\n     * @param firstName\n     *            the first name\n     * @param lastName\n     *            the last name\n     */\n    public PersonDetailNoSchema(String personId, String firstName, String lastName)\n    {\n        this.personId = personId;\n        this.firstName = firstName;\n        this.lastName = lastName;\n    }\n\n    /**\n     * Instantiates a new personnel dto.\n     */\n    public PersonDetailNoSchema()\n    {\n\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the personId\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the personId to set\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the first name.\n     * \n     * @return the firstName\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * Sets the first name.\n     * \n     * @param firstName\n     *            the firstName to set\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * Gets the last name.\n     * \n     * @return the lastName\n     */\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    /**\n     * Sets the last name.\n     * \n     * @param lastName\n     *            the lastName to set\n     */\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/entities/PersonDetailNoTable.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\n\n\n/**\n * The Class PersonnelDTO.\n * \n * @author Chhavi Gangwal\n */\n\n@Entity\npublic class PersonDetailNoTable\n{\n    \n    /** The person id. */\n    @Id\n    private String personId;\n\n    /** The first name. */\n    @Column(name = \"first_name\")\n    private String firstName;\n\n    /** The last name. */\n    @Column(name = \"last_name\")\n    private String lastName;\n\n    /**\n     * Instantiates a new personnel dto.\n     * \n     * @param personId\n     *            the person id\n     * @param firstName\n     *            the first name\n     * @param lastName\n     *            the last name\n     */\n    public PersonDetailNoTable(String personId, String firstName, String lastName)\n    {\n        this.personId = personId;\n        this.firstName = firstName;\n        this.lastName = lastName;\n    }\n\n    /**\n     * Instantiates a new personnel dto.\n     */\n    public PersonDetailNoTable()\n    {\n\n    }\n\n    /**\n     * Gets the person id.\n     * \n     * @return the personId\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the personId to set\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * Gets the first name.\n     * \n     * @return the firstName\n     */\n    public String getFirstName()\n    {\n        return firstName;\n    }\n\n    /**\n     * Sets the first name.\n     * \n     * @param firstName\n     *            the firstName to set\n     */\n    public void setFirstName(String firstName)\n    {\n        this.firstName = firstName;\n    }\n\n    /**\n     * Gets the last name.\n     * \n     * @return the lastName\n     */\n    public String getLastName()\n    {\n        return lastName;\n    }\n\n    /**\n     * Sets the last name.\n     * \n     * @param lastName\n     *            the lastName to set\n     */\n    public void setLastName(String lastName)\n    {\n        this.lastName = lastName;\n    }\n\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/entities/PersonDetailTestAnnotation.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.entities;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n\npublic class PersonDetailTestAnnotation\n{\n    /**\n     * \n     */\n    private static final String _PU = \"secIdxAddCassandra,addMongo,oracle_kvstore,redis,piccandra,picongo\";\n  \n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Map<String, Object> mongoProperties = new HashMap<String, Object>();\n\n    private Map<String, Object> cassandraProperties = new HashMap<String, Object>();\n    \n    private Map<String, Object> properties = new HashMap<String, Object>();\n\n    private Map<String, Map<String, Object>> puPropertiesMap = new HashMap<String, Map<String, Object>>();\n\n    private HBaseCli cli;\n\n    /**\n     * setup for cassandra, mongo, oracle-nosql, redis and hbase\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n      \n        \n\n        mongoProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n\n        cassandraProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n        \n        properties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n\n        puPropertiesMap.put(\"addMongo\", mongoProperties);\n        puPropertiesMap.put(\"secIdxAddCassandra\", cassandraProperties);\n        puPropertiesMap.put(\"piccandra\", properties);\n        puPropertiesMap.put(\"picongo\", properties);\n\n        emf = Persistence.createEntityManagerFactory(_PU, puPropertiesMap);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * closes em\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        mongoProperties = null;\n        cassandraProperties = null;\n        puPropertiesMap = null;\n    }\n    \n    /**\n     * Test method for testing entity class with no table name annotation\n     */\n    @Test\n    public void testNoTableAnnotation()\n    {\n        PersonDetailNoTable p = new PersonDetailNoTable();\n        p.setPersonId(\"1\");\n        p.setFirstName(\"Chhavi\");\n        p.setLastName(\"Gangwal\");\n        em.persist(p);\n        em.clear();\n\n        PersonDetailNoTable found = em.find(PersonDetailNoTable.class, \"1\");\n        Assert.assertNotNull(found);\n        Assert.assertEquals(\"1\", found.getPersonId());\n        Assert.assertEquals(\"Chhavi\", found.getFirstName());\n        Assert.assertEquals(\"Gangwal\", found.getLastName());\n    }\n    \n    /**\n     * Test method for testing entity classes with no schema definition \n    */\n    @Test\n    public void testTableNoSchemaAnnotation()\n    {\n        PersonDetailNoSchema p = new PersonDetailNoSchema();\n        p.setPersonId(\"1\");\n        p.setFirstName(\"Chhavi\");\n        p.setLastName(\"Gangwal\");\n        em.persist(p);\n        em.clear();\n\n        PersonDetailNoSchema found = em.find(PersonDetailNoSchema.class, \"1\");\n        Assert.assertNotNull(found);\n        Assert.assertEquals(\"1\", found.getPersonId());\n        Assert.assertEquals(\"Chhavi\", found.getFirstName());\n        Assert.assertEquals(\"Gangwal\", found.getLastName());\n    }\n    \n    \n\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/entities/PersonRDBMSPolyglot.java",
    "content": "/*******************************************************************************\n * * Copyright 2013 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\n\n\n\n\n// TODO: Auto-generated Javadoc\n/**\n * The Class Person.\n */\n@Entity\npublic class PersonRDBMSPolyglot\n{\n\n    /** The person id. */\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    /** The person name. */\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    /** The age. */\n    @Column(name = \"AGE\")\n    private Integer age;\n    \n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressCassandra address;\n\n    /**\n     * Gets the person id.\n     * \n     * @return the person id\n     */\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    /**\n     * Gets the person name.\n     * \n     * @return the person name\n     */\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    /**\n     * Sets the person name.\n     * \n     * @param personName\n     *            the new person name\n     */\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    /**\n     * Sets the person id.\n     * \n     * @param personId\n     *            the new person id\n     */\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    /**\n     * @return the age\n     */\n    public int getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(int age)\n    {\n        this.age = age;\n    }\n    \n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(AddressCassandra address)\n    {\n        this.address = address;\n    }\n    \n    /**\n     * @return the address\n     */\n    public AddressCassandra getAddress()\n    {\n        return address;\n    }\n\n    \n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/entities/UserCassandraNoAnnotation.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.entities;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\n\nimport com.impetus.kundera.index.Index;\nimport com.impetus.kundera.index.IndexCollection;\n\n@Entity\n@IndexCollection(columns = { @Index(name = \"personName\") })\npublic class UserCassandraNoAnnotation\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private int personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private AddressMongoNoAnnotation address;\n\n    public int getPersonId()\n    {\n        return personId;\n    }\n    \n    public void setPersonId(int personId)\n    {\n        this.personId = personId;\n    }\n\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public AddressMongoNoAnnotation getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(AddressMongoNoAnnotation address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/externalproeprties/AccountHolder.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.tests.externalproeprties;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"ACCOUNTHOLDER\", schema = \"KunderaTests@secIdxAddCassandra\")\n//@IndexCollection(columns = { @Index(name = \"PERSON_ID\") })\npublic class AccountHolder\n{\n\n    @Id\n    @Column(name = \"ACCOUNTHOLDER_ID\")\n    private String accountHolderId;\n\n    @Column(name = \"ACCOUNTHOLDER_NAME\")\n    private String accountHoldername;\n\n    @Column(name = \"TOTALBALANCE\")\n    private String totalBalance;\n\n    /**\n     * @return the accountHolderId\n     */\n    public String getAccountHolderId()\n    {\n        return accountHolderId;\n    }\n\n    /**\n     * @param accountHolderId\n     *            the accountHolderId to set\n     */\n    public void setAccountHolderId(String accountHolderId)\n    {\n        this.accountHolderId = accountHolderId;\n    }\n\n    /**\n     * @return the accountHoldername\n     */\n    public String getAccountHoldername()\n    {\n        return accountHoldername;\n    }\n\n    /**\n     * @param accountHoldername\n     *            the accountHoldername to set\n     */\n    public void setAccountHoldername(String accountHoldername)\n    {\n        this.accountHoldername = accountHoldername;\n    }\n\n    /**\n     * @return the totalBalance\n     */\n    public String getTotalBalance()\n    {\n        return totalBalance;\n    }\n\n    /**\n     * @param totalBalance\n     *            the totalBalance to set\n     */\n    public void setTotalBalance(String totalBalance)\n    {\n        this.totalBalance = totalBalance;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/externalproeprties/Bank.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.tests.externalproeprties;\n\nimport java.util.Set;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToMany;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"BANK\", schema = \"KunderaTests@addMongo\")\npublic class Bank\n{\n\n    @Id\n    @Column(name = \"BANK_ID\")\n    private String bankId;\n\n    @Column(name = \"BANK_NAME\")\n    private String bankName;\n\n    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"PERSON_ID\")\n    private Set<AccountHolder> accountHolders;\n\n    /**\n     * @return the bankId\n     */\n    public String getBankId()\n    {\n        return bankId;\n    }\n\n    /**\n     * @param bankId\n     *            the bankId to set\n     */\n    public void setBankId(String bankId)\n    {\n        this.bankId = bankId;\n    }\n\n    /**\n     * @return the bankName\n     */\n    public String getBankName()\n    {\n        return bankName;\n    }\n\n    /**\n     * @param bankName\n     *            the bankName to set\n     */\n    public void setBankName(String bankName)\n    {\n        this.bankName = bankName;\n    }\n\n    /**\n     * @return the accountHolders\n     */\n    public Set<AccountHolder> getAccountHolders()\n    {\n        return accountHolders;\n    }\n\n    /**\n     * @param accountHolders\n     *            the accountHolders to set\n     */\n    public void setAccountHolders(Set<AccountHolder> accountHolders)\n    {\n        this.accountHolders = accountHolders;\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/externalproeprties/BankTest.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.tests.externalproeprties;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.client.hbase.junits.HBaseCli;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class BankTest\n{\n    /**\n     * \n     */\n    private static final String _PU = \"rdbms,secIdxAddCassandra,addMongo,piccandra,picongo\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Map<String, Object> mongoProperties = new HashMap<String, Object>();\n\n    private Map<String, Object> cassandraProperties = new HashMap<String, Object>();\n    \n    private Map<String, Object> properties = new HashMap<String, Object>();\n\n    private Map<String, Map<String, Object>> puPropertiesMap = new HashMap<String, Map<String, Object>>();\n\n    private HBaseCli cli;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        CassandraCli.cassandraSetUp();\n        \n\n        mongoProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n\n        cassandraProperties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n        \n        properties.put(\"kundera.ddl.auto.prepare\", \"create-drop\");\n\n        puPropertiesMap.put(\"addMongo\", mongoProperties);\n        puPropertiesMap.put(\"secIdxAddCassandra\", cassandraProperties);\n        puPropertiesMap.put(\"piccandra\", properties);\n        puPropertiesMap.put(\"picongo\", properties);\n\n        emf = Persistence.createEntityManagerFactory(_PU, puPropertiesMap);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        em.close();\n        emf.close();\n        mongoProperties = null;\n        cassandraProperties = null;\n        puPropertiesMap = null;\n    }\n\n    @Test\n    public void test()\n    {\n        Bank b = new Bank();\n        b.setBankId(\"SBI_1\");\n        b.setBankName(\"SBI\");\n        Set<AccountHolder> accountHolders = new HashSet<AccountHolder>();\n\n        AccountHolder accountHolder1 = new AccountHolder();\n        AccountHolder accountHolder2 = new AccountHolder();\n        accountHolder1.setAccountHolderId(\"1\");\n        accountHolder1.setAccountHoldername(\"kuldeep\");\n        accountHolder1.setTotalBalance(\"10000\");\n        accountHolder2.setAccountHolderId(\"2\");\n        accountHolder2.setAccountHoldername(\"amresh\");\n        accountHolder2.setTotalBalance(\"100000\");\n        accountHolders.add(accountHolder1);\n        accountHolders.add(accountHolder2);\n\n        b.setAccountHolders(accountHolders);\n\n        em.persist(b);\n\n        em.clear();\n\n        Bank found = em.find(Bank.class, \"SBI_1\");\n        Assert.assertNotNull(found);\n        Assert.assertEquals(\"SBI\", found.getBankName());\n        Assert.assertNotNull(found.getAccountHolders());\n        Assert.assertEquals(2, found.getAccountHolders().size());\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/file/dao/ProfilePictureDao.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.file.dao;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport com.google.common.io.Files;\nimport com.impetus.kundera.tests.file.entities.ProfilePicture;\n\n/**\n * DAO for profile picture class\n * \n * @author amresh.singh\n */\npublic class ProfilePictureDao\n{\n\n    EntityManagerFactory emf;\n\n    EntityManager em;\n\n    public ProfilePictureDao(String persistenceUnitName)\n    {\n        if (emf == null)\n        {\n            emf = Persistence.createEntityManagerFactory(persistenceUnitName);\n        }\n    }\n\n    public void addProfilePicture(int id, File fullPicture)\n    {\n        EntityManager em = getEntityManager();\n\n        ProfilePicture pp = new ProfilePicture();\n        pp.setProfilePicId(id);\n\n        try\n        {\n            pp.setFullPicture(Files.toByteArray(fullPicture));\n        }\n        catch (IOException e)\n        {\n            \n        }\n\n        em.persist(pp);\n        closeEntityManager();\n    }\n\n    public ProfilePicture getProfilePicture(int id)\n    {\n        EntityManager em = getEntityManager();\n\n        ProfilePicture pp = em.find(ProfilePicture.class, 1);\n\n        closeEntityManager();\n        return pp;\n    }\n\n    EntityManager getEntityManager()\n    {\n        if (em == null)\n        {\n            em = emf.createEntityManager();\n        }\n        return em;\n    }\n\n    private void closeEntityManager()\n    {\n        if (em != null)\n        {\n            em.close();\n            em = null;\n        }\n    }\n\n    void closeEntityManagerfactory()\n    {\n        if (emf != null)\n        {\n            emf.close();\n            emf = null;\n        }\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/file/dao/ProfilePictureDaoTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.file.dao;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.google.common.io.Files;\nimport com.impetus.kundera.tests.file.entities.ProfilePicture;\n\n/**\n * Test case for {@link ProfilePictureDao}\n * \n * @author amresh.singh\n */\npublic class ProfilePictureDaoTest\n{\n    String inputFilePath;\n\n    ProfilePictureDao dao;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        inputFilePath = \"/home/impadmin/input.jpg\";\n//        dao = new ProfilePictureDao(\"rdbms,addMongo,addCassandra,piccandra,secIdxAddCassandra,picongo\");\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n//        dao.closeEntityManagerfactory();\n    }\n\n    @Test\n    public void dummyTest()\n    {\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.tests.file.dao.ProfilePictureDao#addProfilePicture(int, java.io.File)}\n     * .\n     */\n    // @Test\n    public void test()\n    {\n        // Insert picture\n        int id = 1;\n        File fullPictureFile = new File(inputFilePath);\n        dao.addProfilePicture(id, fullPictureFile);\n\n        // Find Picture\n        ProfilePicture pp = dao.getProfilePicture(1);\n        try\n        {\n            Files.write(pp.getFullPicture(), new File(\"/home/impadmin/output.jpg\"));\n        }\n        catch (IOException e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/file/entities/ProfilePicture.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.file.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * Entity Class for User's profile picture\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PROFILE_PICTURE\", schema = \"KunderaTests@secIdxAddCassandra\")\npublic class ProfilePicture\n{\n    @Id\n    private int profilePicId;\n\n    @Column(name = \"FULL_PICTURE\")\n    private byte[] fullPicture;\n\n    @Column(name = \"CROPPED_PICTURE\")\n    private byte[] croppedPicture;\n\n    @Column(name = \"SMALL_PICTURE\")\n    private byte[] smallPicture;\n\n    /**\n     * @return the profilePicId\n     */\n    public int getProfilePicId()\n    {\n        return profilePicId;\n    }\n\n    /**\n     * @param profilePicId\n     *            the profilePicId to set\n     */\n    public void setProfilePicId(int profilePicId)\n    {\n        this.profilePicId = profilePicId;\n    }\n\n    /**\n     * @return the fullPicture\n     */\n    public byte[] getFullPicture()\n    {\n        return fullPicture;\n    }\n\n    /**\n     * @param fullPicture\n     *            the fullPicture to set\n     */\n    public void setFullPicture(byte[] fullPicture)\n    {\n        this.fullPicture = fullPicture;\n    }\n\n    /**\n     * @return the croppedPicture\n     */\n    public byte[] getCroppedPicture()\n    {\n        return croppedPicture;\n    }\n\n    /**\n     * @param croppedPicture\n     *            the croppedPicture to set\n     */\n    public void setCroppedPicture(byte[] croppedPicture)\n    {\n        this.croppedPicture = croppedPicture;\n    }\n\n    /**\n     * @return the smallPicture\n     */\n    public byte[] getSmallPicture()\n    {\n        return smallPicture;\n    }\n\n    /**\n     * @param smallPicture\n     *            the smallPicture to set\n     */\n    public void setSmallPicture(byte[] smallPicture)\n    {\n        this.smallPicture = smallPicture;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/persistence/jta/EjbJTAContextTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.persistence.jta;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport javax.naming.Context;\nimport javax.naming.InitialContext;\nimport javax.naming.NamingException;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.FlushModeType;\nimport javax.persistence.Persistence;\nimport javax.transaction.HeuristicMixedException;\nimport javax.transaction.HeuristicRollbackException;\nimport javax.transaction.NotSupportedException;\nimport javax.transaction.RollbackException;\nimport javax.transaction.SystemException;\nimport javax.transaction.UserTransaction;\n\nimport junit.framework.Assert;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.cassandra.thrift.TimedOutException;\nimport org.apache.cassandra.thrift.UnavailableException;\nimport org.apache.thrift.TException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\nimport com.impetus.kundera.persistence.jta.KunderaJTAUserTransaction;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class EjbJTAContextTest\n{\n    private InitialContext initialContext;\n\n    private UserTransaction userTransaction;\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Integer i = 0;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.naming.java.javaURLContextFactory\");\n        System.setProperty(Context.URL_PKG_PREFIXES, \"org.apache.naming\");\n\n        initialContext = new InitialContext();\n        initialContext.createSubcontext(\"java:comp\");\n        // This is what we need to bind to get handle of JTA's\n        // UserTransaction.\n\n        initialContext.bind(\"java:comp/UserTransaction\", new KunderaJTAUserTransaction());\n\n        CassandraCli.cassandraSetUp();\n        CassandraCli.dropKeySpace(\"KunderaTests\");\n        CassandraCli.createKeySpace(\"KunderaTests\");\n        emf = Persistence.createEntityManagerFactory(\"secIdxAddCassandraJTA,addMongoJTA\");\n        em = emf.createEntityManager();\n        loadData();\n    }\n\n    @Test\n    public void testConcurrentPersist() throws NotSupportedException, SystemException, NamingException,\n            SecurityException, IllegalStateException, RollbackException, HeuristicMixedException,\n            HeuristicRollbackException\n    {\n\n        userTransaction = (UserTransaction) initialContext.lookup(\"java:comp/UserTransaction\");\n\n        userTransaction.begin();\n\n        for (i = 0; i < 100; i++)\n        {\n            Runnable r = onExecute();\n            r.run();\n        }\n\n        userTransaction.commit();\n\n        userTransaction.begin();\n        // As data is commited, hence it should return values with other\n        // session.\n        for (i = 0; i < 100; i++)\n        {\n            EntityManager em1 = emf.createEntityManager();\n            Assert.assertNotNull(em1.find(PersonnelOToOFKEntityJTA.class, \"1_p\" + i));\n        }\n    }\n\n    private Runnable onExecute()\n    {\n        Runnable r = new Runnable()\n        {\n\n            @Override\n            public void run()\n            {\n                PersonnelOToOFKEntityJTA person = new PersonnelOToOFKEntityJTA();\n                person.setPersonId(\"1_p\" + i);\n                person.setPersonName(\"crossdata-store\");\n                HabitatOToOFKEntityJTA address = new HabitatOToOFKEntityJTA();\n                address.setAddressId(\"1_a\" + i);\n                address.setStreet(\"my street\");\n                person.setAddress(address);\n                try\n                {\n                    em.persist(person);\n                }\n                catch (Exception ex)\n                {\n                    HabitatOToOFKEntityJTA found = em.find(HabitatOToOFKEntityJTA.class, \"1_a\" + i);\n                    Assert.assertNull(found);\n                }\n\n                // As data is not commited, hence it should return null with\n                // other session.\n                EntityManager em1 = emf.createEntityManager();\n                Assert.assertNull(em1.find(PersonnelOToOFKEntityJTA.class, \"1_p\" + i));\n            }\n        };\n        return r;\n    }\n\n    @Test\n    public void testPersist() throws NotSupportedException, SystemException, NamingException, SecurityException,\n            IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException\n    {\n        userTransaction = (UserTransaction) initialContext.lookup(\"java:comp/UserTransaction\");\n        em.setFlushMode(FlushModeType.COMMIT);\n\n        userTransaction.begin();\n        PersonnelOToOFKEntityJTA person = new PersonnelOToOFKEntityJTA();\n        person.setPersonId(\"1_p\");\n        person.setPersonName(\"crossdata-store\");\n        HabitatOToOFKEntityJTA address = new HabitatOToOFKEntityJTA();\n        address.setAddressId(\"1_a\");\n        address.setStreet(\"my street\");\n        person.setAddress(address);\n        try\n        {\n            em.persist(person);\n        }\n        catch (Exception ex)\n        {\n            HabitatOToOFKEntityJTA found = em.find(HabitatOToOFKEntityJTA.class, \"1_a\");\n            Assert.assertNull(found);\n        }\n        userTransaction.commit();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        initialContext.unbind(\"java:comp/UserTransaction\");\n        initialContext.destroySubcontext(\"java:comp\");\n\n        // CassandraCli.dropKeySpace(\"KunderaTests\");\n        CassandraCli.truncateColumnFamily(\"KunderaTests\", \"PERSONNEL\");\n    }\n\n    /**\n     * Load cassandra specific data.\n     * \n     * @throws TException\n     *             the t exception\n     * @throws InvalidRequestException\n     *             the invalid request exception\n     * @throws UnavailableException\n     *             the unavailable exception\n     * @throws TimedOutException\n     *             the timed out exception\n     * @throws SchemaDisagreementException\n     *             the schema disagreement exception\n     */\n    private void loadData() throws TException, InvalidRequestException, UnavailableException, TimedOutException,\n            SchemaDisagreementException\n    {\n\n        KsDef ksDef = null;\n        CfDef user_Def = new CfDef();\n        user_Def.name = \"PERSONNEL\";\n        user_Def.keyspace = \"KunderaTests\";\n        user_Def.setComparator_type(\"UTF8Type\");\n        user_Def.setKey_validation_class(\"UTF8Type\");\n        ColumnDef columnDef = new ColumnDef(ByteBuffer.wrap(\"PERSON_NAME\".getBytes()), \"UTF8Type\");\n        columnDef.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef);\n        ColumnDef columnDef1 = new ColumnDef(ByteBuffer.wrap(\"ADDRESS_ID\".getBytes()), \"UTF8Type\");\n        columnDef1.index_type = IndexType.KEYS;\n        user_Def.addToColumn_metadata(columnDef1);\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        cfDefs.add(user_Def);\n\n        try\n        {\n            ksDef = CassandraCli.client.describe_keyspace(\"KunderaTests\");\n            CassandraCli.client.set_keyspace(\"KunderaTests\");\n            // if (!CassandraCli.columnFamilyExist(\"PERSONNEL\", \"KunderaTests\"))\n            // {\n            // CassandraCli.client.system_add_column_family(user_Def);\n            // }\n            // else\n            // {\n            // CassandraCli.truncateColumnFamily(\"KunderaTests\", \"PERSONNEL\");\n            // }\n\n            List<CfDef> cfDefn = ksDef.getCf_defs();\n\n            for (CfDef cfDef1 : cfDefn)\n            {\n\n                if (cfDef1.getName().equalsIgnoreCase(\"PERSONNEL\"))\n                {\n\n                    CassandraCli.client.system_drop_column_family(\"PERSONNEL\");\n\n                }\n            }\n            CassandraCli.client.system_add_column_family(user_Def);\n\n        }\n        catch (NotFoundException e)\n        {\n\n            ksDef = new KsDef(\"KunderaTests\", \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n            // Set replication factor\n            if (ksDef.strategy_options == null)\n            {\n                ksDef.strategy_options = new LinkedHashMap<String, String>();\n            }\n            // Set replication factor, the value MUST be an integer\n            ksDef.strategy_options.put(\"replication_factor\", \"1\");\n            CassandraCli.client.system_add_keyspace(ksDef);\n        }\n\n        CassandraCli.client.set_keyspace(\"KunderaTests\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/persistence/jta/HabitatOToOFKEntityJTA.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.persistence.jta;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"HabitatOToOFKEntityJTA\", schema = \"KunderaJTATests@addMongoJTA\")\npublic class HabitatOToOFKEntityJTA\n{\n    @Id\n    @Column(name = \"ADDRESS_ID\")\n    private String addressId;\n\n    @Column(name = \"STREET\")\n    private String street;\n\n    /**\n     * \n     */\n    public HabitatOToOFKEntityJTA()\n    {\n    }\n\n    public String getAddressId()\n    {\n        return addressId;\n    }\n\n    public void setAddressId(String addressId)\n    {\n        this.addressId = addressId;\n    }\n\n    public String getStreet()\n    {\n        return street;\n    }\n\n    public void setStreet(String street)\n    {\n        this.street = street;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/persistence/jta/OraclePersonnelOTOFKEntityJTA.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.persistence.jta;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"OraclePersonnelOTOFKEntityJTA\", schema = \"OracleNoSqlTests@oracle_kvstore_JTA\")\npublic class OraclePersonnelOTOFKEntityJTA\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HabitatOToOFKEntityJTA address;\n\n    /**\n     * \n     */\n    public OraclePersonnelOTOFKEntityJTA()\n    {\n    }\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatOToOFKEntityJTA getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatOToOFKEntityJTA address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/persistence/jta/OracleToMongoJTATest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.persistence.jta;\n\nimport javax.naming.Context;\nimport javax.naming.InitialContext;\nimport javax.naming.NamingException;\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.FlushModeType;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport javax.transaction.HeuristicMixedException;\nimport javax.transaction.HeuristicRollbackException;\nimport javax.transaction.NotSupportedException;\nimport javax.transaction.RollbackException;\nimport javax.transaction.SystemException;\nimport javax.transaction.UserTransaction;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.persistence.jta.KunderaJTAUserTransaction;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class OracleToMongoJTATest\n{\n    private InitialContext initialContext;\n\n    private UserTransaction userTransaction;\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private Integer i = 0;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, \"org.apache.naming.java.javaURLContextFactory\");\n        System.setProperty(Context.URL_PKG_PREFIXES, \"org.apache.naming\");\n\n        initialContext = new InitialContext();\n        initialContext.createSubcontext(\"java:comp\");\n        // This is what we need to bind to get handle of JTA's\n        // UserTransaction.\n\n        initialContext.bind(\"java:comp/UserTransaction\", new KunderaJTAUserTransaction());\n\n        emf = Persistence.createEntityManagerFactory(\"oracle_kvstore_JTA,addMongoJTA\");\n        \n        em = emf.createEntityManager();\n    }\n\n    @Test\n    public void testConcurrentPersist() throws NotSupportedException, SystemException, NamingException,\n            SecurityException, IllegalStateException, RollbackException, HeuristicMixedException,\n            HeuristicRollbackException\n    {\n\n        userTransaction = (UserTransaction) initialContext.lookup(\"java:comp/UserTransaction\");\n\n        userTransaction.begin();\n\n        for (i = 0; i < 100; i++)\n        {\n            Runnable r = onExecute();\n            r.run();\n        }\n\n        userTransaction.commit();\n\n        userTransaction.begin();\n        // As data is commited, hence it should return values with other\n        // session.\n        for (i = 0; i < 100; i++)\n        {\n            EntityManager em1 = emf.createEntityManager();\n            Assert.assertNotNull(em1.find(OraclePersonnelOTOFKEntityJTA.class, \"1_p\" + i));\n        }\n    }\n\n    private Runnable onExecute()\n    {\n        Runnable r = new Runnable()\n        {\n            @Override\n            public void run()\n            {\n                OraclePersonnelOTOFKEntityJTA person = new OraclePersonnelOTOFKEntityJTA();\n                person.setPersonId(\"1_p\" + i);\n                person.setPersonName(\"crossdata-store\");\n                HabitatOToOFKEntityJTA address = new HabitatOToOFKEntityJTA();\n                address.setAddressId(\"1_a\" + i);\n                address.setStreet(\"my street\");\n                person.setAddress(address);\n                try\n                {\n                    em.persist(person);\n                }\n                catch (Exception ex)\n                {\n                    HabitatOToOFKEntityJTA found = em.find(HabitatOToOFKEntityJTA.class, \"1_a\" + i);\n                    Assert.assertNull(found);\n                }\n\n                // As data is not commited, hence it should return null with\n                // other session.\n                EntityManager em1 = emf.createEntityManager();\n                Assert.assertNull(em1.find(OraclePersonnelOTOFKEntityJTA.class, \"1_p\" + i));\n            }\n        };\n        return r;\n    }\n\n    @Test\n    public void testPersist() throws NotSupportedException, SystemException, NamingException, SecurityException,\n            IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException\n    {\n        userTransaction = (UserTransaction) initialContext.lookup(\"java:comp/UserTransaction\");\n        em.setFlushMode(FlushModeType.COMMIT);\n\n        userTransaction.begin();\n        OraclePersonnelOTOFKEntityJTA person = new OraclePersonnelOTOFKEntityJTA();\n        person.setPersonId(\"1_p\");\n        person.setPersonName(\"crossdata-store\");\n        HabitatOToOFKEntityJTA address = new HabitatOToOFKEntityJTA();\n        address.setAddressId(\"1_a\");\n        address.setStreet(\"my street\");\n        person.setAddress(address);\n        try\n        {\n            em.persist(person);\n        }\n        catch (Exception ex)\n        {\n            HabitatOToOFKEntityJTA found = em.find(HabitatOToOFKEntityJTA.class, \"1_a\");\n            Assert.assertNull(found);\n        }\n        userTransaction.commit();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        userTransaction.begin();\n\n        // Delete by query.\n        String deleteQuery = \"Delete from OraclePersonnelOTOFKEntityJTA p\";\n        Query query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n\n        deleteQuery = \"Delete from HabitatOToOFKEntityJTA p\";\n        query = em.createQuery(deleteQuery);\n        query.executeUpdate();\n\n        userTransaction.commit();\n\n        initialContext.unbind(\"java:comp/UserTransaction\");\n        initialContext.destroySubcontext(\"java:comp\");\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/persistence/jta/PersonnelOToOFKEntityJTA.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.persistence.jta;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n@Entity\n@Table(name = \"PERSONNEL\", schema = \"KunderaTests@secIdxAddCassandraJTA\")\npublic class PersonnelOToOFKEntityJTA\n{\n    @Id\n    @Column(name = \"PERSON_ID\")\n    private String personId;\n\n    @Column(name = \"PERSON_NAME\")\n    private String personName;\n\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ADDRESS_ID\")\n    private HabitatOToOFKEntityJTA address;\n\n    /**\n     * \n     */\n    public PersonnelOToOFKEntityJTA()\n    {\n    }\n\n    public String getPersonId()\n    {\n        return personId;\n    }\n\n    public String getPersonName()\n    {\n        return personName;\n    }\n\n    public void setPersonName(String personName)\n    {\n        this.personName = personName;\n    }\n\n    public void setPersonId(String personId)\n    {\n        this.personId = personId;\n    }\n\n    public HabitatOToOFKEntityJTA getAddress()\n    {\n        return address;\n    }\n\n    public void setAddress(HabitatOToOFKEntityJTA address)\n    {\n        this.address = address;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/persistence/lazy/Album.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.persistence.lazy;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author amresh.singh\n * \n */\n@Entity\n@Table(name = \"ALBUM_LAZY\", schema = \"Pickr@piccandra\")\npublic class Album\n{\n    @Id\n    @Column(name = \"ALBUM_ID\")\n    private String albumId;\n\n    @Column(name = \"ALBUM_NAME\")\n    private String albumName;\n\n    @Column(name = \"ALBUM_DESC\")\n    private String albumDescription;\n\n    public Album()\n    {\n\n    }\n\n    public Album(String albumId, String name, String description)\n    {\n        this.albumId = albumId;\n        this.albumName = name;\n        this.albumDescription = description;\n    }\n\n    /**\n     * @return the albumId\n     */\n    public String getAlbumId()\n    {\n        return albumId;\n    }\n\n    /**\n     * @param albumId\n     *            the albumId to set\n     */\n    public void setAlbumId(String albumId)\n    {\n        this.albumId = albumId;\n    }\n\n    /**\n     * @return the albumName\n     */\n    public String getAlbumName()\n    {\n        return albumName;\n    }\n\n    /**\n     * @param albumName\n     *            the albumName to set\n     */\n    public void setAlbumName(String albumName)\n    {\n        this.albumName = albumName;\n    }\n\n    /**\n     * @return the albumDescription\n     */\n    public String getAlbumDescription()\n    {\n        return albumDescription;\n    }\n\n    /**\n     * @param albumDescription\n     *            the albumDescription to set\n     */\n    public void setAlbumDescription(String albumDescription)\n    {\n        this.albumDescription = albumDescription;\n    }\n\n}"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/persistence/lazy/KunderaPersistenceProviderUtilTest.java",
    "content": "/*******************************************************************************\n * * Copyright 2012 Impetus Infotech.\n *  *\n *  * Licensed under the Apache License, Version 2.0 (the \"License\");\n *  * you may not use this file except in compliance with the License.\n *  * You may obtain a copy of the License at\n *  *\n *  *      http://www.apache.org/licenses/LICENSE-2.0\n *  *\n *  * Unless required by applicable law or agreed to in writing, software\n *  * distributed under the License is distributed on an \"AS IS\" BASIS,\n *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  * See the License for the specific language governing permissions and\n *  * limitations under the License.\n ******************************************************************************/\npackage com.impetus.kundera.tests.persistence.lazy;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.spi.LoadState;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.KunderaPersistence;\nimport com.impetus.kundera.KunderaPersistenceProviderUtil;\nimport com.impetus.kundera.PersistenceProperties;\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * @author amresh.singh Test case for {@link KunderaPersistenceProviderUtil}\n *         Script for running this test case drop keyspace Pickr; create\n *         keyspace Pickr; use Pickr; create column family PHOTOGRAPHER with\n *         comparator=UTF8Type and default_validation_class=UTF8Type and\n *         key_validation_class=UTF8Type and column_metadata=[{column_name:\n *         PHOTOGRAPHER_NAME, validation_class:UTF8Type, index_type:\n *         KEYS},{column_name: ALBUM_ID, validation_class:UTF8Type, index_type:\n *         KEYS}]; create column family ALBUM with comparator=UTF8Type and\n *         default_validation_class=UTF8Type and key_validation_class=UTF8Type\n *         and column_metadata=[{column_name: ALBUM_NAME,\n *         validation_class:UTF8Type, index_type: KEYS},{column_name:\n *         ALBUM_DESC, validation_class:UTF8Type, index_type: KEYS}]; describe\n *         Pickr; list PHOTOGRAPHER; list ALBUM;\n */\npublic class KunderaPersistenceProviderUtilTest\n{\n    private static final String KUNDERA_TESTS = \"KunderaTests\";\n\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private KunderaPersistence kp = new KunderaPersistence();\n\n    private KunderaPersistenceProviderUtil util = new KunderaPersistenceProviderUtil(kp);\n\n    private LazyTestSetup setup = new LazyTestSetup();\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n\n        setup.startServer();\n        setup.createSchema();\n        \n        if(!CassandraCli.keyspaceExist(KUNDERA_TESTS)){\n            CassandraCli.createKeySpace(KUNDERA_TESTS);\n        }\n\n        Map<String, String> propertyMap = new HashMap<String, String>();\n        if (propertyMap.isEmpty())\n        {\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"\");\n            propertyMap.put(PersistenceProperties.KUNDERA_NODES, \"localhost\");\n        }\n        Map mapOfExternalProperties = new HashMap<String, Map>();\n        mapOfExternalProperties.put(\"addCassandra\", propertyMap);\n        mapOfExternalProperties.put(\"piccandra\", propertyMap);\n        mapOfExternalProperties.put(\"secIdxAddCassandra\", propertyMap);\n        \n        emf = Persistence\n                .createEntityManagerFactory(\"rdbms,addMongo,addCassandra,piccandra,secIdxAddCassandra,picongo\", mapOfExternalProperties);\n        em = emf.createEntityManager();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        setup.deleteSchema();\n        setup.stopServer();\n\n        if (em != null)\n        {\n            em.close();\n        }\n        if (emf != null)\n        {\n            emf.close();\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.KunderaPersistenceProviderUtil#isLoadedWithReference(java.lang.Object, java.lang.String)}\n     * .\n     */\n    @Test\n    public void testIsLoadedWithReference()\n    {\n        try\n        {\n            // Persist entity\n            Photographer photographer = new Photographer();\n            photographer.setPhotographerId(1);\n            photographer.setPhotographerName(\"Amresh\");\n            Album album = new Album(\"album1\", \"My Vacation\", \"Vacation pics\");\n            photographer.setAlbum(album);\n            em.persist(photographer);\n            em.close();\n\n            // Find entity\n            em = emf.createEntityManager();\n            Photographer p = em.find(Photographer.class, 1);\n            Album album2 = p.getAlbum();\n            // Load state before field referred\n            LoadState loadStateWithReference = util.isLoadedWithReference(album2, \"albumName\");\n            // UNKNOWN because PROXY initialization currently not implemented in\n            // Kundera\n            Assert.assertEquals(LoadState.UNKNOWN, loadStateWithReference);\n\n            // Load state after field referred\n            album2.getAlbumName();\n            loadStateWithReference = util.isLoadedWithReference(album2, \"albumName\");\n            // UNKNOWN because PROXY initialization currently not implemented in\n            // Kundera\n            Assert.assertEquals(LoadState.UNKNOWN, loadStateWithReference);\n        }\n        catch (Exception e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.KunderaPersistenceProviderUtil#isLoadedWithoutReference(java.lang.Object, java.lang.String)}\n     * .\n     */\n    @Test\n    public void testIsLoadedWithoutReference()\n    {\n        try\n        {\n            // Persist entity\n            Photographer photographer = new Photographer();\n            photographer.setPhotographerId(1);\n            photographer.setPhotographerName(\"Amresh\");\n            Album album = new Album(\"album1\", \"My Vacation\", \"Vacation pics\");\n            photographer.setAlbum(album);\n            em.persist(photographer);\n            em.close();\n\n            // Find entity\n            em = emf.createEntityManager();\n            Photographer p = em.find(Photographer.class, 1);\n            Album album2 = p.getAlbum();\n\n            // Load state before field referred\n            // Loaded because LAZY initialization currently not implemented in\n            // Kundera\n            LoadState loadStateWithoutReference = util.isLoadedWithoutReference(album2, \"albumName\");\n            Assert.assertEquals(LoadState.NOT_LOADED, loadStateWithoutReference);\n\n            // Load state after field referred\n            album2.getAlbumName();\n            loadStateWithoutReference = util.isLoadedWithoutReference(p, \"album\");\n            Assert.assertEquals(LoadState.LOADED, loadStateWithoutReference);\n        }\n        catch (Exception e)\n        {\n            Assert.fail(e.getMessage());\n        }\n\n    }\n\n    /**\n     * Test method for\n     * {@link com.impetus.kundera.KunderaPersistenceProviderUtil#isLoaded(java.lang.Object)}\n     * .\n     */\n    @Test\n    public void testIsLoaded()\n    {\n        try\n        {\n            // Persist entity\n            Photographer photographer = new Photographer();\n            photographer.setPhotographerId(1);\n            photographer.setPhotographerName(\"Amresh\");\n            Album album = new Album(\"album1\", \"My Vacation\", \"Vacation pics\");\n            photographer.setAlbum(album);\n            em.persist(photographer);\n            em.close();\n\n            // Find entity\n            em = emf.createEntityManager();\n            Photographer p = em.find(Photographer.class, 1);\n            Album album2 = p.getAlbum();\n\n            // Load state before field referred\n            LoadState loadState = util.isLoaded(album2);\n            Assert.assertEquals(LoadState.NOT_LOADED, loadState);\n\n            // Load state after field referred\n            album2.getAlbumName();\n            loadState = util.isLoaded(album2);\n            Assert.assertEquals(LoadState.LOADED, loadState);\n        }\n        catch (Exception e)\n        {\n            Assert.fail(e.getMessage());\n        }\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/persistence/lazy/KunderaPersistenceUnitUtilTest.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.persistence.lazy;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.PersistenceUnitUtil;\n\nimport junit.framework.Assert;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.PersistenceProperties;\n\n/**\n * \n * @author Amresh.singh junit for {@link PersistenceUnitUtil}\n * \n */\npublic class KunderaPersistenceUnitUtilTest\n{\n    private EntityManagerFactory emf;\n\n    private EntityManager em;\n\n    private PersistenceUnitUtil util;\n\n    private LazyTestSetup setup = new LazyTestSetup();\n\n    @Before\n    public void setUp() throws Exception\n    {\n        setup.startServer();\n        setup.createSchema();\n\n        Map<String, String> propertyMap = new HashMap<String, String>();\n        if (propertyMap.isEmpty())\n        {\n            propertyMap.put(PersistenceProperties.KUNDERA_DDL_AUTO_PREPARE, \"update\");\n            \n        }\n        Map mapOfExternalProperties = new HashMap<String, Map>();\n        mapOfExternalProperties.put(\"addCassandra\", propertyMap);\n        mapOfExternalProperties.put(\"piccandra\", propertyMap);\n        mapOfExternalProperties.put(\"secIdxAddCassandra\", propertyMap);\n        emf = Persistence.createEntityManagerFactory(\n                \"addCassandra,rdbms,redis,addMongo,piccandra,secIdxAddCassandra,picongo\", mapOfExternalProperties);\n        em = emf.createEntityManager();\n        util = emf.getPersistenceUnitUtil();\n    }\n\n    @After\n    public void tearDown() throws Exception\n    {\n        setup.deleteSchema();\n        setup.stopServer();\n\n        em.close();\n        emf.close();\n    }\n\n    @Test\n    public void testIsLoadedObjectString()\n    {\n        // Persist entity\n        Photographer photographer = new Photographer();\n        photographer.setPhotographerId(1);\n        photographer.setPhotographerName(\"Amresh\");\n        Album album = new Album(\"album1\", \"My Vacation\", \"Vacation pics\");\n        photographer.setAlbum(album);\n        em.persist(photographer);\n        em.close();\n\n        // Find entity\n        em = emf.createEntityManager();\n        Photographer p = em.find(Photographer.class, 1);\n        Album album2 = p.getAlbum();\n        boolean isLoaded = util.isLoaded(album2, \"albumName\");\n        Assert.assertFalse(isLoaded);\n\n        album2.getAlbumName();\n        isLoaded = util.isLoaded(p, \"album\");\n        Assert.assertTrue(isLoaded);\n    }\n\n    @Test\n    public void testIsLoadedObject()\n    {\n        // Persist entity\n        Photographer photographer = new Photographer();\n        photographer.setPhotographerId(1);\n        photographer.setPhotographerName(\"Amresh\");\n        Album album = new Album(\"album1\", \"My Vacation\", \"Vacation pics\");\n        photographer.setAlbum(album);\n        em.persist(photographer);\n        em.close();\n\n        // Find entity\n        em = emf.createEntityManager();\n        Photographer p = em.find(Photographer.class, 1);\n        Album album2 = p.getAlbum();\n        boolean isLoaded = util.isLoaded(album2);\n        Assert.assertFalse(isLoaded);\n\n        album2.getAlbumName();\n        isLoaded = util.isLoaded(album2);\n        Assert.assertTrue(isLoaded);\n    }\n\n    @Test\n    public void testGetIdentifier()\n    {\n        // Persist entity\n        Photographer photographer = new Photographer();\n        photographer.setPhotographerId(1);\n        photographer.setPhotographerName(\"Amresh\");\n        Album album = new Album(\"album1\", \"My Vacation\", \"Vacation pics\");\n        photographer.setAlbum(album);\n        em.persist(photographer);\n        em.close();\n\n        // Find entity\n        em = emf.createEntityManager();\n        Photographer p = em.find(Photographer.class, 1);\n\n        Object pk = util.getIdentifier(p);\n        Assert.assertEquals(1, pk);\n\n    }\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/persistence/lazy/LazyTestSetup.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.persistence.lazy;\n\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\n\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.ColumnDef;\nimport org.apache.cassandra.thrift.IndexType;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.thrift.TException;\n\nimport com.impetus.kundera.client.cassandra.persistence.CassandraCli;\n\n/**\n * Utilities for Test setup\n * \n * @author amresh.singh\n */\npublic class LazyTestSetup\n{\n    private static final String COLUMN_FAMILY_PHOTOGRAPHER = \"PHOTOGRAPHER_LAZY\";\n\n    private static final String COLUMN_FAMILY_ALBUM = \"ALBUM_LAZY\";\n\n    private static final String KEYSPACE = \"Pickr\";\n\n    public static final boolean RUN_IN_EMBEDDED_MODE = true;\n\n    public static final boolean AUTO_MANAGE_SCHEMA = true;\n\n    void startServer()\n    {\n        if (RUN_IN_EMBEDDED_MODE)\n        {\n            try\n            {\n                CassandraCli.cassandraSetUp();\n            }\n            catch (IOException e)\n            {\n\n            }\n            catch (TException e)\n            {\n\n            }\n        }\n\n    }\n\n    void stopServer()\n    {\n    }\n\n    void createSchema()\n    {\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            try\n            {\n                KsDef ksDef = null;\n\n                CfDef cfDefPhotographer = new CfDef();\n                cfDefPhotographer.name = COLUMN_FAMILY_PHOTOGRAPHER;\n                cfDefPhotographer.keyspace = KEYSPACE;\n                cfDefPhotographer.setKey_validation_class(\"Int32Type\");\n                cfDefPhotographer.setComparator_type(\"UTF8Type\");\n\n                ColumnDef columnDef2 = new ColumnDef(ByteBuffer.wrap(\"PHOTOGRAPHER_NAME\".getBytes()), \"UTF8Type\");\n                columnDef2.index_type = IndexType.KEYS;\n                cfDefPhotographer.addToColumn_metadata(columnDef2);\n\n                ColumnDef columnDef3 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_ID\".getBytes()), \"UTF8Type\");\n                columnDef3.index_type = IndexType.KEYS;\n                cfDefPhotographer.addToColumn_metadata(columnDef3);\n\n                CfDef cfDefAlbum = new CfDef();\n                cfDefAlbum.name = COLUMN_FAMILY_ALBUM;\n                cfDefAlbum.keyspace = KEYSPACE;\n                cfDefAlbum.setKey_validation_class(\"UTF8Type\");\n                cfDefAlbum.setComparator_type(\"UTF8Type\");\n                ColumnDef columnDef4 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_NAME\".getBytes()), \"UTF8Type\");\n                columnDef4.index_type = IndexType.KEYS;\n                cfDefAlbum.addToColumn_metadata(columnDef4);\n\n                ColumnDef columnDef5 = new ColumnDef(ByteBuffer.wrap(\"ALBUM_DESC\".getBytes()), \"UTF8Type\");\n                columnDef5.index_type = IndexType.KEYS;\n                cfDefAlbum.addToColumn_metadata(columnDef5);\n\n                List<CfDef> cfDefs = new ArrayList<CfDef>();\n                cfDefs.add(cfDefPhotographer);\n                cfDefs.add(cfDefAlbum);\n\n                try\n                {\n                    CassandraCli.initClient();\n                    ksDef = CassandraCli.client.describe_keyspace(KEYSPACE);\n                    CassandraCli.client.set_keyspace(KEYSPACE);\n\n                    if (!CassandraCli.columnFamilyExist(COLUMN_FAMILY_PHOTOGRAPHER, KEYSPACE))\n                    {\n                        CassandraCli.client.system_add_column_family(cfDefPhotographer);\n                    }\n                    else\n                    {\n                        CassandraCli.truncateColumnFamily(KEYSPACE, COLUMN_FAMILY_PHOTOGRAPHER);\n                    }\n\n                    if (!CassandraCli.columnFamilyExist(COLUMN_FAMILY_ALBUM, KEYSPACE))\n                    {\n                        CassandraCli.client.system_add_column_family(cfDefAlbum);\n                    }\n                    else\n                    {\n                        CassandraCli.truncateColumnFamily(KEYSPACE, COLUMN_FAMILY_ALBUM);\n                    }\n\n                }\n                catch (NotFoundException e)\n                {\n\n                    ksDef = new KsDef(KEYSPACE, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n                    // Set replication factor\n                    if (ksDef.strategy_options == null)\n                    {\n                        ksDef.strategy_options = new LinkedHashMap<String, String>();\n                    }\n                    // Set replication factor, the value MUST be an integer\n                    ksDef.strategy_options.put(\"replication_factor\", \"1\");\n                    CassandraCli.client.system_add_keyspace(ksDef);\n                }\n\n                CassandraCli.client.set_keyspace(KEYSPACE);\n            }\n            catch (TException e)\n            {\n\n            }\n\n        }\n\n    }\n\n    void deleteSchema()\n    {\n        if (AUTO_MANAGE_SCHEMA)\n        {\n            // CassandraCli.dropKeySpace(KEYSPACE);\n            CassandraCli.truncateColumnFamily(KEYSPACE, COLUMN_FAMILY_PHOTOGRAPHER, COLUMN_FAMILY_ALBUM);\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/java/com/impetus/kundera/tests/persistence/lazy/Photographer.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.tests.persistence.lazy;\n\nimport javax.persistence.CascadeType;\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.FetchType;\nimport javax.persistence.Id;\nimport javax.persistence.JoinColumn;\nimport javax.persistence.OneToOne;\nimport javax.persistence.Table;\n\n\n/**\n * Entity class representing a photographer\n * \n * @author amresh.singh\n */\n\n@Entity\n@Table(name = \"PHOTOGRAPHER_LAZY\", schema = \"Pickr@piccandra\")\npublic class Photographer\n{\n    @Id\n    @Column(name = \"PHOTOGRAPHER_ID\")\n    private int photographerId;\n\n    @Column(name = \"PHOTOGRAPHER_NAME\")\n    private String photographerName;\n\n    // One to many, will be persisted separately\n    @OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n    @JoinColumn(name = \"ALBUM_ID\")\n    private Album album;\n\n    /**\n     * @return the photographerName\n     */\n    public String getPhotographerName()\n    {\n        return photographerName;\n    }\n\n    /**\n     * @param photographerName\n     *            the photographerName to set\n     */\n    public void setPhotographerName(String photographerName)\n    {\n        this.photographerName = photographerName;\n    }\n\n    /**\n     * @return the photographerId\n     */\n    public int getPhotographerId()\n    {\n        return photographerId;\n    }\n\n    /**\n     * @param photographerId\n     *            the photographerId to set\n     */\n    public void setPhotographerId(int photographerId)\n    {\n        this.photographerId = photographerId;\n    }\n\n    /**\n     * @return the album\n     */\n    public Album getAlbum()\n    {\n        return album;\n    }\n\n    /**\n     * @param album\n     *            the album to set\n     */\n    public void setAlbum(Album album)\n    {\n        this.album = album;\n    }\n\n}\n"
  },
  {
    "path": "src/kundera-tests/src/test/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\n\tversion=\"2.0\">\n\t<!-- Persistence Units for User-Address example (Cross-data store persistence) -->\n\n\t<persistence-unit name=\"addCassandra\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"./lucene\" /> -->\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"secIdxAddCassandraJTA\"\n\t\ttransaction-type=\"JTA\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.tests.persistence.jta.PersonnelOToOFKEntityJTA</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<!-- <property name=\"kundera.ddl.auto.prepare\" value=\"create\" /> -->\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"/home/impadmin/lucene\" /> -->\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"addMongoJTA\" transaction-type=\"JTA\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.tests.persistence.jta.HabitatOToOFKEntityJTA</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaJTATests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\n\t<persistence-unit name=\"secIdxAddCassandra\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"/home/impadmin/lucene\" /> -->\n\t\t</properties>\n\n\t</persistence-unit>\n\t<persistence-unit name=\"addHbase\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"0\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"/home/impadmin/lucene\" /> -->\n\t\t\t<!-- <property name=\"kundera.ddl.auto.prepare\" value=\"create\" /> -->\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"addMongo\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"rdbms\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.examples.crossdatastore.useraddress.entities.PersonnelUni1To1FK</class>\n\t\t<class>com.impetus.kundera.examples.crossdatastore.useraddress.entities.HabitatUni1To1FK</class>\n\t\t<properties>\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.rdbms.RDBMSClientFactory\" />\n\t\t\t<property name=\"current_session_context_class\" value=\"thread\" />\n\t\t\t<property name=\"hibernate.show_sql\" value=\"false\" />\n\t\t\t<property name=\"hibernate.format_sql\" value=\"true\" />\n\t\t\t<property name=\"hibernate.connection.driver_class\" value=\"org.hsqldb.jdbcDriver\" />\n\t\t\t<property name=\"hibernate.connection.url\" value=\"jdbc:hsqldb:mem:KunderaTests\" />\n\t\t\t<property name=\"hibernate.connection.username\" value=\"sa\" />\n\t\t\t<property name=\"hibernate.connection.password\" value=\"\" />\n\t\t\t<property name=\"hibernate.connection.pool_size\" value=\"10\" />\n\t\t\t<property name=\"hibernate.connection.autocommit\" value=\"true\" />\n\t\t\t<property name=\"hibernate.dialect\" value=\"org.hibernate.dialect.HSQLDialect\" />\n\t\t\t<property name=\"connection.provider_class\"\n\t\t\t\tvalue=\"org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<!-- Persistence Units for Pickr application -->\n\t<persistence-unit name=\"picmysql\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.rdbms.RDBMSClientFactory\" />\n\t\t\t<property name=\"current_session_context_class\" value=\"thread\" />\n\t\t\t<!-- <property name=\"hibernate.hbm2ddl.auto\" value=\"create\" /> -->\n\t\t\t<!-- <property name=\"hibernate.show_sql\" value=\"true\" /> -->\n\t\t\t<property name=\"hibernate.format_sql\" value=\"true\" />\n\t\t\t<property name=\"hibernate.connection.driver_class\" value=\"org.hsqldb.jdbcDriver\" />\n\t\t\t<property name=\"hibernate.connection.url\" value=\"jdbc:hsqldb:mem:Pickr\" />\n\t\t\t<property name=\"hibernate.connection.username\" value=\"sa\" />\n\t\t\t<property name=\"hibernate.connection.password\" value=\"\" />\n\t\t\t<property name=\"hibernate.connection.pool_size\" value=\"10\" />\n\t\t\t<property name=\"hibernate.connection.autocommit\" value=\"true\" />\n\t\t\t<property name=\"hibernate.dialect\" value=\"org.hibernate.dialect.HSQLDialect\" />\n\t\t\t<property name=\"connection.provider_class\"\n\t\t\t\tvalue=\"org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<!-- Persistence Units for Pickr application -->\n\t<!-- <persistence-unit name=\"picmysql\"> <provider>com.impetus.kundera.KunderaPersistence</provider> \n\t\t<properties> <property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.rdbms.RDBMSClientFactory\" \n\t\t/> <property name=\"hibernate.hbm2ddl.auto\" value=\"create\" /> <property name=\"hibernate.max_fetch_depth\" \n\t\tvalue=\"0\" /> <property name=\"hibernate.show_sql\" value=\"true\" /> <property \n\t\tname=\"hibernate.format_sql\" value=\"true\" /> <property name=\"hibernate.dialect\" \n\t\tvalue=\"org.hibernate.dialect.MySQL5Dialect\" /> <property name=\"hibernate.connection.driver_class\" \n\t\tvalue=\"com.mysql.jdbc.Driver\" /> <property name=\"hibernate.connection.url\" \n\t\tvalue=\"jdbc:mysql://localhost:3306/Pickr\" /> <property name=\"hibernate.connection.url\" \n\t\tvalue=\"jdbc:mysql://192.168.145.168:3306/Pickr\" /> <property name=\"hibernate.connection.username\" \n\t\tvalue=\"root\" /> <property name=\"hibernate.connection.password\" value=\"impetus\" \n\t\t/> <property name=\"hibernate.current_session_context_class\" value=\"org.hibernate.context.ThreadLocalSessionContext\" \n\t\t/> <property name=\"index.home.dir\" value=\"./lucene\" /> </properties> </persistence-unit> -->\n\n\t<persistence-unit name=\"piccandra\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"Pickr\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"picbase\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"Pickr\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<property name=\"index.home.dir\" value=\"./lucene\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"picongo\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"Pickr\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"redis\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"6379\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"RedisK\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"redis\" />\n\t\t\t<property name=\"kundera.client\" value=\"redis\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.redis.RedisClientFactory\" />\n\t\t\t<property name=\"kundera.password\" value=\"Kundera@123\" />\n\t\t\t<property name=\"kundera.transaction.timeout\" value=\"30\" />\n\t\t\t<property name=\"kundera.indexer.class\" value=\"com.impetus.client.redis.RedisIndexer\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<!-- Persistence Units for IMDB application -->\n\t<persistence-unit name=\"imdbCassandra\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"imdb\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<!-- <property name=\"kundera.ddl.auto.prepare\" value=\"create\" /> -->\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"imdbNeo4J\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"7474\" />\n\t\t\t<property name=\"kundera.datastore.file.path\" value=\"target/imdb.db\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"neo4j\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.neo4j.Neo4JClientFactory\" />\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaNeo4JTest.xml\" />\n\t\t\t<property name=\"kundera.transaction.resource.class\" value=\"com.impetus.client.neo4j.Neo4JTransaction\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"imdbRDBMS\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.rdbms.RDBMSClientFactory\" />\n\t\t\t<property name=\"current_session_context_class\" value=\"thread\" />\n\t\t\t<!-- <property name=\"hibernate.show_sql\" value=\"true\" /> -->\n\t\t\t<property name=\"hibernate.format_sql\" value=\"true\" />\n\t\t\t<property name=\"hibernate.connection.driver_class\" value=\"org.hsqldb.jdbcDriver\" />\n\t\t\t<property name=\"hibernate.connection.url\" value=\"jdbc:hsqldb:mem:imdb\" />\n\t\t\t<property name=\"hibernate.connection.username\" value=\"sa\" />\n\t\t\t<property name=\"hibernate.connection.password\" value=\"\" />\n\t\t\t<property name=\"hibernate.connection.pool_size\" value=\"10\" />\n\t\t\t<property name=\"hibernate.connection.autocommit\" value=\"true\" />\n\t\t\t<property name=\"hibernate.dialect\" value=\"org.hibernate.dialect.HSQLDialect\" />\n\t\t\t<property name=\"connection.provider_class\"\n\t\t\t\tvalue=\"org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"imdbHbase\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"2181\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"imdb\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\n\t\t\t<!-- <property name=\"kundera.ddl.auto.prepare\" value=\"create\" /> -->\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"oracle_kvstore\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"5000\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.OracleNoSQLClientFactory\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"OracleNoSqlTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.client\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.indexer.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.index.OracleNoSQLInvertedIndexer\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"oracle_kvstore_JTA\"\n\t\ttransaction-type=\"JTA\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"5000\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.OracleNoSQLClientFactory\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"OracleNoSqlTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.client\" value=\"kvstore\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.indexer.class\"\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.index.OracleNoSQLInvertedIndexer\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"noAnnotationAddCassandra\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.tests.entities.PersonDetailClassMap</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"/home/impadmin/lucene\" /> -->\n\t\t</properties>\n\n\t</persistence-unit>\n\t<persistence-unit name=\"noAnnotationAddMongo\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.tests.entities.PersonDetailClassMap</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"addMongoNoAnnotateTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.tests.entities.AddressMongoNoAnnotation</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\t<persistence-unit name=\"secIdxAddCassandraNoAnnotateTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.tests.entities.UserCassandraNoAnnotation</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"/home/impadmin/lucene\" /> -->\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"addCouchdb\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"5984\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"couchdb\" />\n\t\t\t<property name=\"kundera.client\" value=\"couchdb\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.couchdb.CouchDBClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"cassandraAddressNoAnnotate\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.tests.entities.AddressCassandra</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create-drop\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\n\t\t\t<!-- <property name=\"index.home.dir\" value=\"/home/impadmin/lucene\" /> -->\n\t\t</properties>\n\n\t</persistence-unit>\n\t<persistence-unit name=\"rdbmsNoAnnotateTest\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.tests.entities.PersonRDBMSPolyglot</class>\n\t\t<class>com.impetus.kundera.tests.entities.AddressCassandra</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.rdbms.RDBMSClientFactory\" />\n\t\t\t<property name=\"current_session_context_class\" value=\"thread\" />\n\t\t\t<!-- <property name=\"hibernate.show_sql\" value=\"true\" /> -->\n\t\t\t<property name=\"hibernate.format_sql\" value=\"true\" />\n\t\t\t<property name=\"hibernate.connection.driver_class\" value=\"org.hsqldb.jdbcDriver\" />\n\t\t\t<property name=\"hibernate.connection.url\" value=\"jdbc:hsqldb:mem:KunderaTests\" />\n\t\t\t<property name=\"hibernate.hbm2ddl.auto\" value=\"create-drop\" />\n\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"commonCouchdb\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.tests.entities.CommonUser</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"5984\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"couchdb\" />\n\t\t\t<property name=\"kundera.client\" value=\"couchdb\" />\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.couchdb.CouchDBClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n\t<persistence-unit name=\"commonMongo\">\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\n\t\t<class>com.impetus.kundera.tests.entities.CommonUser</class>\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\n\t\t<properties>\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\n\t\t\t<property name=\"kundera.keyspace\" value=\"KunderaTests\" />\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\n\t\t\t<property name=\"kundera.client.lookup.class\"\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\n\t\t</properties>\n\t</persistence-unit>\n\n</persistence>"
  },
  {
    "path": "src/kundera-tests/src/test/resources/META-INF/persistence_2_0.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<!-- persistence.xml schema -->\r\n<xsd:schema targetNamespace=\"http://java.sun.com/xml/ns/persistence\" \r\n  xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\r\n  xmlns:persistence=\"http://java.sun.com/xml/ns/persistence\"\r\n  elementFormDefault=\"qualified\" \r\n  attributeFormDefault=\"unqualified\" \r\n  version=\"2.0\">\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n      @(#)persistence_2_0.xsd  1.0  October 1 2009\r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:annotation>\r\n    <xsd:documentation>\r\n\r\n  Copyright (c) 2008, 2009 Sun Microsystems. All rights reserved. \r\n  \r\n  This program and the accompanying materials are made available under the \r\n  terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 \r\n  which accompanies this distribution. \r\n  The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html\r\n  and the Eclipse Distribution License is available at \r\n  http://www.eclipse.org/org/documents/edl-v10.php.\r\n  \r\n  Contributors:\r\n      Linda DeMichiel - Java Persistence 2.0, Version 2.0 (October 1, 2009)\r\n      Specification available from http://jcp.org/en/jsr/detail?id=317\r\n \r\n    </xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n   <xsd:annotation>\r\n     <xsd:documentation><![CDATA[\r\n\r\n     This is the XML Schema for the persistence configuration file.\r\n     The file must be named \"META-INF/persistence.xml\" in the \r\n     persistence archive.\r\n\r\n     Persistence configuration files must indicate\r\n     the persistence schema by using the persistence namespace:\r\n\r\n     http://java.sun.com/xml/ns/persistence\r\n\r\n     and indicate the version of the schema by\r\n     using the version element as shown below:\r\n\r\n      <persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n        xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n        xsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n          http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd\"\r\n        version=\"2.0\">\r\n          ...\r\n      </persistence>\r\n\r\n    ]]></xsd:documentation>\r\n  </xsd:annotation>\r\n\r\n  <xsd:simpleType name=\"versionType\">\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:pattern value=\"[0-9]+(\\.[0-9]+)*\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:element name=\"persistence\">\r\n    <xsd:complexType>\r\n      <xsd:sequence>\r\n\r\n        <!-- **************************************************** -->\r\n\r\n        <xsd:element name=\"persistence-unit\" \r\n                     minOccurs=\"1\" maxOccurs=\"unbounded\">\r\n          <xsd:complexType>\r\n            <xsd:annotation>\r\n              <xsd:documentation>\r\n\r\n                Configuration of a persistence unit.\r\n\r\n              </xsd:documentation>\r\n            </xsd:annotation>\r\n            <xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"description\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Description of this persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"provider\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Provider class that supplies EntityManagers for this \r\n                    persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of the JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"non-jta-data-source\" type=\"xsd:string\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The container-specific name of a non-JTA datasource to use.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"mapping-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    File containing mapping information. Loaded as a resource \r\n                    by the persistence provider.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"jar-file\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Jar file that is to be scanned for managed classes. \r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"class\" type=\"xsd:string\" \r\n                           minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Managed class to be included in the persistence unit and\r\n                    to scan for annotations.  It should be annotated \r\n                    with either @Entity, @Embeddable or @MappedSuperclass.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"exclude-unlisted-classes\" type=\"xsd:boolean\" \r\n                           default=\"true\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    When set to true then only listed classes and jars will \r\n                    be scanned for persistent classes, otherwise the \r\n                    enclosing jar or directory will also be scanned. \r\n                    Not applicable to Java SE persistence units.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"shared-cache-mode\" \r\n                           type=\"persistence:persistence-unit-caching-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    Defines whether caching is enabled for the \r\n                    persistence unit if caching is supported by the\r\n                    persistence provider. When set to ALL, all entities \r\n                    will be cached. When set to NONE, no entities will\r\n                    be cached. When set to ENABLE_SELECTIVE, only entities\r\n                    specified as cacheable will be cached. When set to\r\n                    DISABLE_SELECTIVE, entities specified as not cacheable\r\n                    will not be cached. When not specified or when set to\r\n                    UNSPECIFIED, provider defaults may apply.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"validation-mode\" \r\n                           type=\"persistence:persistence-unit-validation-mode-type\" \r\n                           minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    The validation mode to be used for the persistence unit.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n              </xsd:element>\r\n\r\n\r\n              <!-- **************************************************** -->\r\n\r\n              <xsd:element name=\"properties\" minOccurs=\"0\">\r\n                <xsd:annotation>\r\n                  <xsd:documentation>\r\n\r\n                    A list of standard and vendor-specific properties \r\n                    and hints.\r\n\r\n                  </xsd:documentation>\r\n                </xsd:annotation>\r\n                <xsd:complexType>\r\n                  <xsd:sequence>\r\n                    <xsd:element name=\"property\" \r\n                                 minOccurs=\"0\" maxOccurs=\"unbounded\">\r\n                      <xsd:annotation>\r\n                        <xsd:documentation>\r\n                          A name-value pair.\r\n                        </xsd:documentation>\r\n                      </xsd:annotation>\r\n                      <xsd:complexType>\r\n                        <xsd:attribute name=\"name\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                        <xsd:attribute name=\"value\" type=\"xsd:string\" \r\n                                       use=\"required\"/>\r\n                      </xsd:complexType>\r\n                    </xsd:element>\r\n                  </xsd:sequence>\r\n                </xsd:complexType>\r\n              </xsd:element>\r\n\r\n            </xsd:sequence>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"name\" type=\"xsd:string\" use=\"required\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Name used in code to reference this persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n            <!-- **************************************************** -->\r\n\r\n            <xsd:attribute name=\"transaction-type\" \r\n                           type=\"persistence:persistence-unit-transaction-type\">\r\n              <xsd:annotation>\r\n                <xsd:documentation>\r\n\r\n                  Type of transactions used by EntityManagers from this \r\n                  persistence unit.\r\n\r\n                </xsd:documentation>\r\n              </xsd:annotation>\r\n            </xsd:attribute>\r\n\r\n          </xsd:complexType>\r\n        </xsd:element>\r\n      </xsd:sequence>\r\n      <xsd:attribute name=\"version\" type=\"persistence:versionType\" \r\n                     fixed=\"2.0\" use=\"required\"/>\r\n    </xsd:complexType>\r\n  </xsd:element>\r\n\r\n  <!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-transaction-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum PersistenceUnitTransactionType {JTA, RESOURCE_LOCAL};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"JTA\"/>\r\n      <xsd:enumeration value=\"RESOURCE_LOCAL\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-caching-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum SharedCacheMode { ALL, NONE, ENABLE_SELECTIVE, DISABLE_SELECTIVE, UNSPECIFIED};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"ALL\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n      <xsd:enumeration value=\"ENABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"DISABLE_SELECTIVE\"/>\r\n      <xsd:enumeration value=\"UNSPECIFIED\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n<!-- **************************************************** -->\r\n\r\n  <xsd:simpleType name=\"persistence-unit-validation-mode-type\">\r\n    <xsd:annotation>\r\n      <xsd:documentation>\r\n\r\n        public enum ValidationMode { AUTO, CALLBACK, NONE};\r\n\r\n      </xsd:documentation>\r\n    </xsd:annotation>\r\n    <xsd:restriction base=\"xsd:token\">\r\n      <xsd:enumeration value=\"AUTO\"/>\r\n      <xsd:enumeration value=\"CALLBACK\"/>\r\n      <xsd:enumeration value=\"NONE\"/>\r\n    </xsd:restriction>\r\n  </xsd:simpleType>\r\n\r\n</xsd:schema>\r\n"
  },
  {
    "path": "src/kundera-tests/src/test/resources/cassandra.yaml",
    "content": "# Cassandra storage config YAML \n\n# NOTE:\n#   See http://wiki.apache.org/cassandra/StorageConfiguration for\n#   full explanations of configuration directives\n# /NOTE\n\n# The name of the cluster. This is mainly used to prevent machines in\n# one logical cluster from joining another.\ncluster_name: 'Test Cluster'\n\n# This defines the number of tokens randomly assigned to this node on the ring\n# The more tokens, relative to other nodes, the larger the proportion of data\n# that this node will store. You probably want all nodes to have the same number\n# of tokens assuming they have equal hardware capability.\n#\n# If you leave this unspecified, Cassandra will use the default of 1 token for legacy compatibility,\n# and will use the initial_token as described below.\n#\n# Specifying initial_token will override this setting on the node's initial start,\n# on subsequent starts, this setting will apply even if initial token is set.\n#\n# If you already have a cluster with 1 token per node, and wish to migrate to \n# multiple tokens per node, see http://wiki.apache.org/cassandra/Operations\nnum_tokens: 256\n\n# initial_token allows you to specify tokens manually.  While you can use # it with\n# vnodes (num_tokens > 1, above) -- in which case you should provide a \n# comma-separated list -- it's primarily used when adding nodes # to legacy clusters \n# that do not have vnodes enabled.\n# initial_token:\n\n# See http://wiki.apache.org/cassandra/HintedHandoff\n# May either be \"true\" or \"false\" to enable globally, or contain a list\n# of data centers to enable per-datacenter.\n# hinted_handoff_enabled: DC1,DC2\nhinted_handoff_enabled: true\n# this defines the maximum amount of time a dead host will have hints\n# generated.  After it has been dead this long, new hints for it will not be\n# created until it has been seen alive and gone down again.\nmax_hint_window_in_ms: 10800000 # 3 hours\n# Maximum throttle in KBs per second, per delivery thread.  This will be\n# reduced proportionally to the number of nodes in the cluster.  (If there\n# are two nodes in the cluster, each delivery thread will use the maximum\n# rate; if there are three, each will throttle to half of the maximum,\n# since we expect two nodes to be delivering hints simultaneously.)\nhinted_handoff_throttle_in_kb: 1024\n# Number of threads with which to deliver hints;\n# Consider increasing this number when you have multi-dc deployments, since\n# cross-dc handoff tends to be slower\nmax_hints_delivery_threads: 2\n\n# Maximum throttle in KBs per second, total. This will be\n# reduced proportionally to the number of nodes in the cluster.\nbatchlog_replay_throttle_in_kb: 1024\n\n# Authentication backend, implementing IAuthenticator; used to identify users\n# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthenticator,\n# PasswordAuthenticator}.\n#\n# - AllowAllAuthenticator performs no checks - set it to disable authentication.\n# - PasswordAuthenticator relies on username/password pairs to authenticate\n#   users. It keeps usernames and hashed passwords in system_auth.credentials table.\n#   Please increase system_auth keyspace replication factor if you use this authenticator.\nauthenticator: AllowAllAuthenticator\n\n# Authorization backend, implementing IAuthorizer; used to limit access/provide permissions\n# Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllAuthorizer,\n# CassandraAuthorizer}.\n#\n# - AllowAllAuthorizer allows any action to any user - set it to disable authorization.\n# - CassandraAuthorizer stores permissions in system_auth.permissions table. Please\n#   increase system_auth keyspace replication factor if you use this authorizer.\nauthorizer: AllowAllAuthorizer\n\n# Validity period for permissions cache (fetching permissions can be an\n# expensive operation depending on the authorizer, CassandraAuthorizer is\n# one example). Defaults to 2000, set to 0 to disable.\n# Will be disabled automatically for AllowAllAuthorizer.\npermissions_validity_in_ms: 2000\n\n# The partitioner is responsible for distributing groups of rows (by\n# partition key) across nodes in the cluster.  You should leave this\n# alone for new clusters.  The partitioner can NOT be changed without\n# reloading all data, so when upgrading you should set this to the\n# same partitioner you were already using.\n#\n# Besides Murmur3Partitioner, partitioners included for backwards\n# compatibility include RandomPartitioner, ByteOrderedPartitioner, and\n# OrderPreservingPartitioner.\n#\npartitioner: org.apache.cassandra.dht.ByteOrderedPartitioner\n\n# Directories where Cassandra should store data on disk.  Cassandra\n# will spread data evenly across them, subject to the granularity of\n# the configured compaction strategy.\n# If not set, the default directory is $CASSANDRA_HOME/data/data.\n# data_file_directories:\n#     - /var/lib/cassandra/data\n\n# commit log.  when running on magnetic HDD, this should be a\n# separate spindle than the data directories.\n# If not set, the default directory is $CASSANDRA_HOME/data/commitlog.\n# commitlog_directory: /var/lib/cassandra/commitlog\n\n# policy for data disk failures:\n# die: shut down gossip and Thrift and kill the JVM for any fs errors or\n#      single-sstable errors, so the node can be replaced.\n# stop_paranoid: shut down gossip and Thrift even for single-sstable errors.\n# stop: shut down gossip and Thrift, leaving the node effectively dead, but\n#       can still be inspected via JMX.\n# best_effort: stop using the failed disk and respond to requests based on\n#              remaining available sstables.  This means you WILL see obsolete\n#              data at CL.ONE!\n# ignore: ignore fatal errors and let requests fail, as in pre-1.2 Cassandra\ndisk_failure_policy: stop\n\n# policy for commit disk failures:\n# die: shut down gossip and Thrift and kill the JVM, so the node can be replaced.\n# stop: shut down gossip and Thrift, leaving the node effectively dead, but\n#       can still be inspected via JMX.\n# stop_commit: shutdown the commit log, letting writes collect but\n#              continuing to service reads, as in pre-2.0.5 Cassandra\n# ignore: ignore fatal errors and let the batches fail\ncommit_failure_policy: stop\n\n# Maximum size of the key cache in memory.\n#\n# Each key cache hit saves 1 seek and each row cache hit saves 2 seeks at the\n# minimum, sometimes more. The key cache is fairly tiny for the amount of\n# time it saves, so it's worthwhile to use it at large numbers.\n# The row cache saves even more time, but must contain the entire row,\n# so it is extremely space-intensive. It's best to only use the\n# row cache if you have hot rows or static rows.\n#\n# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.\n#\n# Default value is empty to make it \"auto\" (min(5% of Heap (in MB), 100MB)). Set to 0 to disable key cache.\nkey_cache_size_in_mb:\n\n# Duration in seconds after which Cassandra should\n# save the key cache. Caches are saved to saved_caches_directory as\n# specified in this configuration file.\n#\n# Saved caches greatly improve cold-start speeds, and is relatively cheap in\n# terms of I/O for the key cache. Row cache saving is much more expensive and\n# has limited use.\n#\n# Default is 14400 or 4 hours.\nkey_cache_save_period: 14400\n\n# Number of keys from the key cache to save\n# Disabled by default, meaning all keys are going to be saved\n# key_cache_keys_to_save: 100\n\n# Maximum size of the row cache in memory.\n# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.\n#\n# Default value is 0, to disable row caching.\nrow_cache_size_in_mb: 0\n\n# Duration in seconds after which Cassandra should\n# save the row cache. Caches are saved to saved_caches_directory as specified\n# in this configuration file.\n#\n# Saved caches greatly improve cold-start speeds, and is relatively cheap in\n# terms of I/O for the key cache. Row cache saving is much more expensive and\n# has limited use.\n#\n# Default is 0 to disable saving the row cache.\nrow_cache_save_period: 0\n\n# Number of keys from the row cache to save\n# Disabled by default, meaning all keys are going to be saved\n# row_cache_keys_to_save: 100\n\n# Maximum size of the counter cache in memory.\n#\n# Counter cache helps to reduce counter locks' contention for hot counter cells.\n# In case of RF = 1 a counter cache hit will cause Cassandra to skip the read before\n# write entirely. With RF > 1 a counter cache hit will still help to reduce the duration\n# of the lock hold, helping with hot counter cell updates, but will not allow skipping\n# the read entirely. Only the local (clock, count) tuple of a counter cell is kept\n# in memory, not the whole counter, so it's relatively cheap.\n#\n# NOTE: if you reduce the size, you may not get you hottest keys loaded on startup.\n#\n# Default value is empty to make it \"auto\" (min(2.5% of Heap (in MB), 50MB)). Set to 0 to disable counter cache.\n# NOTE: if you perform counter deletes and rely on low gcgs, you should disable the counter cache.\ncounter_cache_size_in_mb:\n\n# Duration in seconds after which Cassandra should\n# save the counter cache (keys only). Caches are saved to saved_caches_directory as\n# specified in this configuration file.\n#\n# Default is 7200 or 2 hours.\ncounter_cache_save_period: 7200\n\n# Number of keys from the counter cache to save\n# Disabled by default, meaning all keys are going to be saved\n# counter_cache_keys_to_save: 100\n\n# The off-heap memory allocator.  Affects storage engine metadata as\n# well as caches.  Experiments show that JEMAlloc saves some memory\n# than the native GCC allocator (i.e., JEMalloc is more\n# fragmentation-resistant).\n# \n# Supported values are: NativeAllocator, JEMallocAllocator\n#\n# If you intend to use JEMallocAllocator you have to install JEMalloc as library and\n# modify cassandra-env.sh as directed in the file.\n#\n# Defaults to NativeAllocator\n# memory_allocator: NativeAllocator\n\n# saved caches\n# If not set, the default directory is $CASSANDRA_HOME/data/saved_caches.\n# saved_caches_directory: /var/lib/cassandra/saved_caches\n\n# commitlog_sync may be either \"periodic\" or \"batch.\" \n# When in batch mode, Cassandra won't ack writes until the commit log\n# has been fsynced to disk.  It will wait up to\n# commitlog_sync_batch_window_in_ms milliseconds for other writes, before\n# performing the sync.\n#\n# commitlog_sync: batch\n# commitlog_sync_batch_window_in_ms: 50\n#\n# the other option is \"periodic\" where writes may be acked immediately\n# and the CommitLog is simply synced every commitlog_sync_period_in_ms\n# milliseconds.  commitlog_periodic_queue_size allows 1024*(CPU cores) pending\n# entries on the commitlog queue by default.  If you are writing very large\n# blobs, you should reduce that; 16*cores works reasonably well for 1MB blobs.\n# It should be at least as large as the concurrent_writes setting.\ncommitlog_sync: periodic\ncommitlog_sync_period_in_ms: 10000\n# commitlog_periodic_queue_size:\n\n# The size of the individual commitlog file segments.  A commitlog\n# segment may be archived, deleted, or recycled once all the data\n# in it (potentially from each columnfamily in the system) has been\n# flushed to sstables.  \n#\n# The default size is 32, which is almost always fine, but if you are\n# archiving commitlog segments (see commitlog_archiving.properties),\n# then you probably want a finer granularity of archiving; 8 or 16 MB\n# is reasonable.\ncommitlog_segment_size_in_mb: 32\n\n# any class that implements the SeedProvider interface and has a\n# constructor that takes a Map<String, String> of parameters will do.\nseed_provider:\n    # Addresses of hosts that are deemed contact points. \n    # Cassandra nodes use this list of hosts to find each other and learn\n    # the topology of the ring.  You must change this if you are running\n    # multiple nodes!\n    - class_name: org.apache.cassandra.locator.SimpleSeedProvider\n      parameters:\n          # seeds is actually a comma-delimited list of addresses.\n          # Ex: \"<ip1>,<ip2>,<ip3>\"\n          - seeds: \"127.0.0.1\"\n\n# For workloads with more data than can fit in memory, Cassandra's\n# bottleneck will be reads that need to fetch data from\n# disk. \"concurrent_reads\" should be set to (16 * number_of_drives) in\n# order to allow the operations to enqueue low enough in the stack\n# that the OS and drives can reorder them. Same applies to\n# \"concurrent_counter_writes\", since counter writes read the current\n# values before incrementing and writing them back.\n#\n# On the other hand, since writes are almost never IO bound, the ideal\n# number of \"concurrent_writes\" is dependent on the number of cores in\n# your system; (8 * number_of_cores) is a good rule of thumb.\nconcurrent_reads: 32\nconcurrent_writes: 32\nconcurrent_counter_writes: 32\n\n# Total memory to use for sstable-reading buffers.  Defaults to\n# the smaller of 1/4 of heap or 512MB.\n# file_cache_size_in_mb: 512\n\n# Total permitted memory to use for memtables. Cassandra will stop \n# accepting writes when the limit is exceeded until a flush completes,\n# and will trigger a flush based on memtable_cleanup_threshold\n# If omitted, Cassandra will set both to 1/4 the size of the heap.\n# memtable_heap_space_in_mb: 2048\n# memtable_offheap_space_in_mb: 2048\n\n# Ratio of occupied non-flushing memtable size to total permitted size\n# that will trigger a flush of the largest memtable.  Lager mct will\n# mean larger flushes and hence less compaction, but also less concurrent\n# flush activity which can make it difficult to keep your disks fed\n# under heavy write load.\n#\n# memtable_cleanup_threshold defaults to 1 / (memtable_flush_writers + 1)\n# memtable_cleanup_threshold: 0.11\n\n# Specify the way Cassandra allocates and manages memtable memory.\n# Options are:\n#   heap_buffers:    on heap nio buffers\n#   offheap_buffers: off heap (direct) nio buffers\n#   offheap_objects: native memory, eliminating nio buffer heap overhead\nmemtable_allocation_type: heap_buffers\n\n# Total space to use for commitlogs.  Since commitlog segments are\n# mmapped, and hence use up address space, the default size is 32\n# on 32-bit JVMs, and 8192 on 64-bit JVMs.\n#\n# If space gets above this value (it will round up to the next nearest\n# segment multiple), Cassandra will flush every dirty CF in the oldest\n# segment and remove it.  So a small total commitlog space will tend\n# to cause more flush activity on less-active columnfamilies.\n# commitlog_total_space_in_mb: 8192\n\n# This sets the amount of memtable flush writer threads.  These will\n# be blocked by disk io, and each one will hold a memtable in memory\n# while blocked. \n#\n# memtable_flush_writers defaults to the smaller of (number of disks,\n# number of cores), with a minimum of 2 and a maximum of 8.\n# \n# If your data directories are backed by SSD, you should increase this\n# to the number of cores.\n#memtable_flush_writers: 8\n\n# A fixed memory pool size in MB for for SSTable index summaries. If left\n# empty, this will default to 5% of the heap size. If the memory usage of\n# all index summaries exceeds this limit, SSTables with low read rates will\n# shrink their index summaries in order to meet this limit.  However, this\n# is a best-effort process. In extreme conditions Cassandra may need to use\n# more than this amount of memory.\nindex_summary_capacity_in_mb:\n\n# How frequently index summaries should be resampled.  This is done\n# periodically to redistribute memory from the fixed-size pool to sstables\n# proportional their recent read rates.  Setting to -1 will disable this\n# process, leaving existing index summaries at their current sampling level.\nindex_summary_resize_interval_in_minutes: 60\n\n# Whether to, when doing sequential writing, fsync() at intervals in\n# order to force the operating system to flush the dirty\n# buffers. Enable this to avoid sudden dirty buffer flushing from\n# impacting read latencies. Almost always a good idea on SSDs; not\n# necessarily on platters.\ntrickle_fsync: false\ntrickle_fsync_interval_in_kb: 10240\n\n# TCP port, for commands and data\nstorage_port: 7000\n\n# SSL port, for encrypted communication.  Unused unless enabled in\n# encryption_options\nssl_storage_port: 7001\n\n# Address or interface to bind to and tell other Cassandra nodes to connect to.\n# You _must_ change this if you want multiple nodes to be able to communicate!\n#\n# Set listen_address OR listen_interface, not both. Interfaces must correspond\n# to a single address, IP aliasing is not supported.\n#\n# Leaving it blank leaves it up to InetAddress.getLocalHost(). This\n# will always do the Right Thing _if_ the node is properly configured\n# (hostname, name resolution, etc), and the Right Thing is to use the\n# address associated with the hostname (it might not be).\n#\n# Setting listen_address to 0.0.0.0 is always wrong.\nlisten_address: localhost\n# listen_interface: eth0\n\n# Address to broadcast to other Cassandra nodes\n# Leaving this blank will set it to the same value as listen_address\n# broadcast_address: 1.2.3.4\n\n# Internode authentication backend, implementing IInternodeAuthenticator;\n# used to allow/disallow connections from peer nodes.\n# internode_authenticator: org.apache.cassandra.auth.AllowAllInternodeAuthenticator\n\n# Whether to start the native transport server.\n# Please note that the address on which the native transport is bound is the\n# same as the rpc_address. The port however is different and specified below.\nstart_native_transport: true\n# port for the CQL native transport to listen for clients on\nnative_transport_port: 9042\n# The maximum threads for handling requests when the native transport is used.\n# This is similar to rpc_max_threads though the default differs slightly (and\n# there is no native_transport_min_threads, idle threads will always be stopped\n# after 30 seconds).\n# native_transport_max_threads: 128\n#\n# The maximum size of allowed frame. Frame (requests) larger than this will\n# be rejected as invalid. The default is 256MB.\n# native_transport_max_frame_size_in_mb: 256\n\n# Whether to start the thrift rpc server.\nstart_rpc: true\n\n# The address or interface to bind the Thrift RPC service and native transport\n# server to.\n#\n# Set rpc_address OR rpc_interface, not both. Interfaces must correspond\n# to a single address, IP aliasing is not supported.\n#\n# Leaving rpc_address blank has the same effect as on listen_address\n# (i.e. it will be based on the configured hostname of the node).\n#\n# Note that unlike listen_address, you can specify 0.0.0.0, but you must also\n# set broadcast_rpc_address to a value other than 0.0.0.0.\nrpc_address: localhost\n# rpc_interface: eth1\n\n# port for Thrift to listen for clients on\nrpc_port: 9160\n\n# RPC address to broadcast to drivers and other Cassandra nodes. This cannot\n# be set to 0.0.0.0. If left blank, this will be set to the value of\n# rpc_address. If rpc_address is set to 0.0.0.0, broadcast_rpc_address must\n# be set.\n# broadcast_rpc_address: 1.2.3.4\n\n# enable or disable keepalive on rpc/native connections\nrpc_keepalive: true\n\n# Cassandra provides two out-of-the-box options for the RPC Server:\n#\n# sync  -> One thread per thrift connection. For a very large number of clients, memory\n#          will be your limiting factor. On a 64 bit JVM, 180KB is the minimum stack size\n#          per thread, and that will correspond to your use of virtual memory (but physical memory\n#          may be limited depending on use of stack space).\n#\n# hsha  -> Stands for \"half synchronous, half asynchronous.\" All thrift clients are handled\n#          asynchronously using a small number of threads that does not vary with the amount\n#          of thrift clients (and thus scales well to many clients). The rpc requests are still\n#          synchronous (one thread per active request). If hsha is selected then it is essential\n#          that rpc_max_threads is changed from the default value of unlimited.\n#\n# The default is sync because on Windows hsha is about 30% slower.  On Linux,\n# sync/hsha performance is about the same, with hsha of course using less memory.\n#\n# Alternatively,  can provide your own RPC server by providing the fully-qualified class name\n# of an o.a.c.t.TServerFactory that can create an instance of it.\nrpc_server_type: sync\n\n# Uncomment rpc_min|max_thread to set request pool size limits.\n#\n# Regardless of your choice of RPC server (see above), the number of maximum requests in the\n# RPC thread pool dictates how many concurrent requests are possible (but if you are using the sync\n# RPC server, it also dictates the number of clients that can be connected at all).\n#\n# The default is unlimited and thus provides no protection against clients overwhelming the server. You are\n# encouraged to set a maximum that makes sense for you in production, but do keep in mind that\n# rpc_max_threads represents the maximum number of client requests this server may execute concurrently.\n#\n# rpc_min_threads: 16\n# rpc_max_threads: 2048\n\n# uncomment to set socket buffer sizes on rpc connections\n# rpc_send_buff_size_in_bytes:\n# rpc_recv_buff_size_in_bytes:\n\n# Uncomment to set socket buffer size for internode communication\n# Note that when setting this, the buffer size is limited by net.core.wmem_max\n# and when not setting it it is defined by net.ipv4.tcp_wmem\n# See:\n# /proc/sys/net/core/wmem_max\n# /proc/sys/net/core/rmem_max\n# /proc/sys/net/ipv4/tcp_wmem\n# /proc/sys/net/ipv4/tcp_wmem\n# and: man tcp\n# internode_send_buff_size_in_bytes:\n# internode_recv_buff_size_in_bytes:\n\n# Frame size for thrift (maximum message length).\nthrift_framed_transport_size_in_mb: 15\n\n# Set to true to have Cassandra create a hard link to each sstable\n# flushed or streamed locally in a backups/ subdirectory of the\n# keyspace data.  Removing these links is the operator's\n# responsibility.\nincremental_backups: false\n\n# Whether or not to take a snapshot before each compaction.  Be\n# careful using this option, since Cassandra won't clean up the\n# snapshots for you.  Mostly useful if you're paranoid when there\n# is a data format change.\nsnapshot_before_compaction: false\n\n# Whether or not a snapshot is taken of the data before keyspace truncation\n# or dropping of column families. The STRONGLY advised default of true \n# should be used to provide data safety. If you set this flag to false, you will\n# lose data on truncation or drop.\nauto_snapshot: true\n\n# When executing a scan, within or across a partition, we need to keep the\n# tombstones seen in memory so we can return them to the coordinator, which\n# will use them to make sure other replicas also know about the deleted rows.\n# With workloads that generate a lot of tombstones, this can cause performance\n# problems and even exaust the server heap.\n# (http://www.datastax.com/dev/blog/cassandra-anti-patterns-queues-and-queue-like-datasets)\n# Adjust the thresholds here if you understand the dangers and want to\n# scan more tombstones anyway.  These thresholds may also be adjusted at runtime\n# using the StorageService mbean.\ntombstone_warn_threshold: 1000\ntombstone_failure_threshold: 100000\n\n# Granularity of the collation index of rows within a partition.\n# Increase if your rows are large, or if you have a very large\n# number of rows per partition.  The competing goals are these:\n#   1) a smaller granularity means more index entries are generated\n#      and looking up rows withing the partition by collation column\n#      is faster\n#   2) but, Cassandra will keep the collation index in memory for hot\n#      rows (as part of the key cache), so a larger granularity means\n#      you can cache more hot rows\ncolumn_index_size_in_kb: 64\n\n\n# Log WARN on any batch size exceeding this value. 5kb per batch by default.\n# Caution should be taken on increasing the size of this threshold as it can lead to node instability.\nbatch_size_warn_threshold_in_kb: 5\n\n# Number of simultaneous compactions to allow, NOT including\n# validation \"compactions\" for anti-entropy repair.  Simultaneous\n# compactions can help preserve read performance in a mixed read/write\n# workload, by mitigating the tendency of small sstables to accumulate\n# during a single long running compactions. The default is usually\n# fine and if you experience problems with compaction running too\n# slowly or too fast, you should look at\n# compaction_throughput_mb_per_sec first.\n#\n# concurrent_compactors defaults to the smaller of (number of disks,\n# number of cores), with a minimum of 2 and a maximum of 8.\n# \n# If your data directories are backed by SSD, you should increase this\n# to the number of cores.\n#concurrent_compactors: 1\n\n# Throttles compaction to the given total throughput across the entire\n# system. The faster you insert data, the faster you need to compact in\n# order to keep the sstable count down, but in general, setting this to\n# 16 to 32 times the rate you are inserting data is more than sufficient.\n# Setting this to 0 disables throttling. Note that this account for all types\n# of compaction, including validation compaction.\ncompaction_throughput_mb_per_sec: 16\n\n# When compacting, the replacement sstable(s) can be opened before they\n# are completely written, and used in place of the prior sstables for\n# any range that has been written. This helps to smoothly transfer reads \n# between the sstables, reducing page cache churn and keeping hot rows hot\nsstable_preemptive_open_interval_in_mb: 50\n\n# Throttles all outbound streaming file transfers on this node to the\n# given total throughput in Mbps. This is necessary because Cassandra does\n# mostly sequential IO when streaming data during bootstrap or repair, which\n# can lead to saturating the network connection and degrading rpc performance.\n# When unset, the default is 200 Mbps or 25 MB/s.\n# stream_throughput_outbound_megabits_per_sec: 200\n\n# Throttles all streaming file transfer between the datacenters,\n# this setting allows users to throttle inter dc stream throughput in addition\n# to throttling all network stream traffic as configured with\n# stream_throughput_outbound_megabits_per_sec\n# inter_dc_stream_throughput_outbound_megabits_per_sec:\n\n# How long the coordinator should wait for read operations to complete\nread_request_timeout_in_ms: 5000\n# How long the coordinator should wait for seq or index scans to complete\nrange_request_timeout_in_ms: 10000\n# How long the coordinator should wait for writes to complete\nwrite_request_timeout_in_ms: 2000\n# How long the coordinator should wait for counter writes to complete\ncounter_write_request_timeout_in_ms: 5000\n# How long a coordinator should continue to retry a CAS operation\n# that contends with other proposals for the same row\ncas_contention_timeout_in_ms: 1000\n# How long the coordinator should wait for truncates to complete\n# (This can be much longer, because unless auto_snapshot is disabled\n# we need to flush first so we can snapshot before removing the data.)\ntruncate_request_timeout_in_ms: 60000\n# The default timeout for other, miscellaneous operations\nrequest_timeout_in_ms: 10000\n\n# Enable operation timeout information exchange between nodes to accurately\n# measure request timeouts.  If disabled, replicas will assume that requests\n# were forwarded to them instantly by the coordinator, which means that\n# under overload conditions we will waste that much extra time processing \n# already-timed-out requests.\n#\n# Warning: before enabling this property make sure to ntp is installed\n# and the times are synchronized between the nodes.\ncross_node_timeout: false\n\n# Enable socket timeout for streaming operation.\n# When a timeout occurs during streaming, streaming is retried from the start\n# of the current file. This _can_ involve re-streaming an important amount of\n# data, so you should avoid setting the value too low.\n# Default value is 0, which never timeout streams.\n# streaming_socket_timeout_in_ms: 0\n\n# phi value that must be reached for a host to be marked down.\n# most users should never need to adjust this.\n# phi_convict_threshold: 8\n\n# endpoint_snitch -- Set this to a class that implements\n# IEndpointSnitch.  The snitch has two functions:\n# - it teaches Cassandra enough about your network topology to route\n#   requests efficiently\n# - it allows Cassandra to spread replicas around your cluster to avoid\n#   correlated failures. It does this by grouping machines into\n#   \"datacenters\" and \"racks.\"  Cassandra will do its best not to have\n#   more than one replica on the same \"rack\" (which may not actually\n#   be a physical location)\n#\n# IF YOU CHANGE THE SNITCH AFTER DATA IS INSERTED INTO THE CLUSTER,\n# YOU MUST RUN A FULL REPAIR, SINCE THE SNITCH AFFECTS WHERE REPLICAS\n# ARE PLACED.\n#\n# Out of the box, Cassandra provides\n#  - SimpleSnitch:\n#    Treats Strategy order as proximity. This can improve cache\n#    locality when disabling read repair.  Only appropriate for\n#    single-datacenter deployments.\n#  - GossipingPropertyFileSnitch\n#    This should be your go-to snitch for production use.  The rack\n#    and datacenter for the local node are defined in\n#    cassandra-rackdc.properties and propagated to other nodes via\n#    gossip.  If cassandra-topology.properties exists, it is used as a\n#    fallback, allowing migration from the PropertyFileSnitch.\n#  - PropertyFileSnitch:\n#    Proximity is determined by rack and data center, which are\n#    explicitly configured in cassandra-topology.properties.\n#  - Ec2Snitch:\n#    Appropriate for EC2 deployments in a single Region. Loads Region\n#    and Availability Zone information from the EC2 API. The Region is\n#    treated as the datacenter, and the Availability Zone as the rack.\n#    Only private IPs are used, so this will not work across multiple\n#    Regions.\n#  - Ec2MultiRegionSnitch:\n#    Uses public IPs as broadcast_address to allow cross-region\n#    connectivity.  (Thus, you should set seed addresses to the public\n#    IP as well.) You will need to open the storage_port or\n#    ssl_storage_port on the public IP firewall.  (For intra-Region\n#    traffic, Cassandra will switch to the private IP after\n#    establishing a connection.)\n#  - RackInferringSnitch:\n#    Proximity is determined by rack and data center, which are\n#    assumed to correspond to the 3rd and 2nd octet of each node's IP\n#    address, respectively.  Unless this happens to match your\n#    deployment conventions, this is best used as an example of\n#    writing a custom Snitch class and is provided in that spirit.\n#\n# You can use a custom Snitch by setting this to the full class name\n# of the snitch, which will be assumed to be on your classpath.\nendpoint_snitch: SimpleSnitch\n\n# controls how often to perform the more expensive part of host score\n# calculation\ndynamic_snitch_update_interval_in_ms: 100 \n# controls how often to reset all host scores, allowing a bad host to\n# possibly recover\ndynamic_snitch_reset_interval_in_ms: 600000\n# if set greater than zero and read_repair_chance is < 1.0, this will allow\n# 'pinning' of replicas to hosts in order to increase cache capacity.\n# The badness threshold will control how much worse the pinned host has to be\n# before the dynamic snitch will prefer other replicas over it.  This is\n# expressed as a double which represents a percentage.  Thus, a value of\n# 0.2 means Cassandra would continue to prefer the static snitch values\n# until the pinned host was 20% worse than the fastest.\ndynamic_snitch_badness_threshold: 0.1\n\n# request_scheduler -- Set this to a class that implements\n# RequestScheduler, which will schedule incoming client requests\n# according to the specific policy. This is useful for multi-tenancy\n# with a single Cassandra cluster.\n# NOTE: This is specifically for requests from the client and does\n# not affect inter node communication.\n# org.apache.cassandra.scheduler.NoScheduler - No scheduling takes place\n# org.apache.cassandra.scheduler.RoundRobinScheduler - Round robin of\n# client requests to a node with a separate queue for each\n# request_scheduler_id. The scheduler is further customized by\n# request_scheduler_options as described below.\nrequest_scheduler: org.apache.cassandra.scheduler.NoScheduler\n\n# Scheduler Options vary based on the type of scheduler\n# NoScheduler - Has no options\n# RoundRobin\n#  - throttle_limit -- The throttle_limit is the number of in-flight\n#                      requests per client.  Requests beyond \n#                      that limit are queued up until\n#                      running requests can complete.\n#                      The value of 80 here is twice the number of\n#                      concurrent_reads + concurrent_writes.\n#  - default_weight -- default_weight is optional and allows for\n#                      overriding the default which is 1.\n#  - weights -- Weights are optional and will default to 1 or the\n#               overridden default_weight. The weight translates into how\n#               many requests are handled during each turn of the\n#               RoundRobin, based on the scheduler id.\n#\n# request_scheduler_options:\n#    throttle_limit: 80\n#    default_weight: 5\n#    weights:\n#      Keyspace1: 1\n#      Keyspace2: 5\n\n# request_scheduler_id -- An identifier based on which to perform\n# the request scheduling. Currently the only valid option is keyspace.\n# request_scheduler_id: keyspace\n\n# Enable or disable inter-node encryption\n# Default settings are TLS v1, RSA 1024-bit keys (it is imperative that\n# users generate their own keys) TLS_RSA_WITH_AES_128_CBC_SHA as the cipher\n# suite for authentication, key exchange and encryption of the actual data transfers.\n# Use the DHE/ECDHE ciphers if running in FIPS 140 compliant mode.\n# NOTE: No custom encryption options are enabled at the moment\n# The available internode options are : all, none, dc, rack\n#\n# If set to dc cassandra will encrypt the traffic between the DCs\n# If set to rack cassandra will encrypt the traffic between the racks\n#\n# The passwords used in these options must match the passwords used when generating\n# the keystore and truststore.  For instructions on generating these files, see:\n# http://download.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore\n#\nserver_encryption_options:\n    internode_encryption: none\n    keystore: conf/.keystore\n    keystore_password: cassandra\n    truststore: conf/.truststore\n    truststore_password: cassandra\n    # More advanced defaults below:\n    # protocol: TLS\n    # algorithm: SunX509\n    # store_type: JKS\n    # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]\n    # require_client_auth: false\n\n# enable or disable client/server encryption.\nclient_encryption_options:\n    enabled: false\n    keystore: conf/.keystore\n    keystore_password: cassandra\n    # require_client_auth: false\n    # Set trustore and truststore_password if require_client_auth is true\n    # truststore: conf/.truststore\n    # truststore_password: cassandra\n    # More advanced defaults below:\n    # protocol: TLS\n    # algorithm: SunX509\n    # store_type: JKS\n    # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]\n\n# internode_compression controls whether traffic between nodes is\n# compressed.\n# can be:  all  - all traffic is compressed\n#          dc   - traffic between different datacenters is compressed\n#          none - nothing is compressed.\ninternode_compression: all\n\n# Enable or disable tcp_nodelay for inter-dc communication.\n# Disabling it will result in larger (but fewer) network packets being sent,\n# reducing overhead from the TCP protocol itself, at the cost of increasing\n# latency if you block for cross-datacenter responses.\ninter_dc_tcp_nodelay: false\n"
  },
  {
    "path": "src/kundera-tests/src/test/resources/log4j.properties",
    "content": "log4j.rootLogger=WARN, DRFA, CONSOLE\r\n\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %C{1} %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %C{1} %x - %m%n\r\n"
  },
  {
    "path": "src/kundera-tests/src/test/resources/oracle-kv-db.script",
    "content": "# Uni OTO\n\nplan remove-table -name PersonnelUni1To1FK -wait\nplan remove-table -name HabitatUni1To1FK -wait\n\ntable create -name PersonnelUni1To1FK\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nadd-field -type string -name ADDRESS_ID\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonnelUni1To1FK -wait\nplan add-index -name PERSON_NAME -table PersonnelUni1To1FK -field PERSON_NAME -wait\n\ntable create -name HabitatUni1To1FK\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatUni1To1FK -wait\nplan add-index -name STREET -table HabitatUni1To1FK -field STREET -wait\n\n# Bi OTO\n\nplan remove-table -name PersonnelBi1To1FK -wait\nplan remove-table -name HabitatBi1To1FK -wait\n\ntable create -name PersonnelBi1To1FK\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nadd-field -type string -name ADDRESS_ID\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonnelBi1To1FK -wait\nplan add-index -name PERSON_NAME -table PersonnelBi1To1FK -field PERSON_NAME -wait\n\ntable create -name HabitatBi1To1FK\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatBi1To1FK -wait\nplan add-index -name STREET -table HabitatBi1To1FK -field STREET -wait\n\n\n# Bi OTM\n\nplan remove-table -name PersonnelBi1ToM -wait\nplan remove-table -name HabitatBi1ToM -wait\n\ntable create -name PersonnelBi1ToM\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonnelBi1ToM -wait\n\nplan add-index -name PERSON_NAME -table PersonnelBi1ToM -field PERSON_NAME -wait\n\ntable create -name HabitatBi1ToM\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name PERSON_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatBi1ToM -wait\n\nplan add-index -name STREET -table HabitatBi1ToM -field STREET -wait\nplan add-index -name PERSON_ID -table HabitatBi1ToM -field PERSON_ID -wait\n\n# Uni OTM\n\nplan remove-table -name PersonnelUni1ToM -wait\nplan remove-table -name HabitatUni1ToM -wait\n\ntable create -name PersonnelUni1ToM\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonnelUni1ToM -wait\n\nplan add-index -name PERSON_NAME -table PersonnelUni1ToM -field PERSON_NAME -wait\n\ntable create -name HabitatUni1ToM\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name PERSON_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatUni1ToM -wait\n\nplan add-index -name STREET -table HabitatUni1ToM -field STREET -wait\nplan add-index -name PERSON_ID -table HabitatUni1ToM -field PERSON_ID -wait\n\n\n# Bi MTO\n\nplan remove-table -name PersonnelBiMTo1 -wait\nplan remove-table -name HabitatBiMTo1 -wait\n\ntable create -name PersonnelBiMTo1\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nadd-field -type string -name ADDRESS_ID\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonnelBiMTo1 -wait\n\nplan add-index -name PERSON_NAME -table PersonnelBiMTo1 -field PERSON_NAME -wait\nplan add-index -name ADDRESS_ID -table PersonnelBiMTo1 -field ADDRESS_ID -wait\n\ntable create -name HabitatBiMTo1\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatBiMTo1 -wait\n\nplan add-index -name STREET -table HabitatBiMTo1 -field STREET -wait\n\n# Uni MTO\n\nplan remove-table -name PersonnelUniMTo1 -wait\nplan remove-table -name HabitatUniMTo1 -wait\n\ntable create -name PersonnelUniMTo1\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nadd-field -type string -name ADDRESS_ID\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonnelUniMTo1 -wait\n\nplan add-index -name PERSON_NAME -table PersonnelUniMTo1 -field PERSON_NAME -wait\nplan add-index -name ADDRESS_ID -table PersonnelUniMTo1 -field ADDRESS_ID -wait\n\ntable create -name HabitatUniMTo1\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatUniMTo1 -wait\n\nplan add-index -name STREET -table HabitatUniMTo1 -field STREET -wait\n\n# Uni MTM\n\nplan remove-table -name PersonnelUniMToM -wait\nplan remove-table -name HabitatUniMToM -wait\nplan remove-table -name PERSONNEL_ADDRESS -wait\n\ntable create -name PersonnelUniMToM\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonnelUniMToM -wait\n\nplan add-index -name PERSON_NAME -table PersonnelUniMToM -field PERSON_NAME -wait\nplan add-index -name ADDRESS_ID -table PersonnelUniMToM -field ADDRESS_ID -wait\n\ntable create -name HabitatUniMToM\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatUniMToM -wait\n\nplan add-index -name STREET -table HabitatUniMToM -field STREET -wait\n\ntable create -name PERSONNEL_ADDRESS\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name PERSON_ID\nadd-field -type string -name key\nprimary-key -field key\nexit\nplan add-table -name PERSONNEL_ADDRESS -wait\n\nplan add-index -name ADDRESS_ID -table PERSONNEL_ADDRESS -field ADDRESS_ID -wait\nplan add-index -name PERSON_ID -table PERSONNEL_ADDRESS -field PERSON_ID -wait\n\n# Bi MTM\n\nplan remove-table -name PersonnelBiMToM -wait\nplan remove-table -name HabitatBiMToM -wait\n\ntable create -name PersonnelBiMToM\nadd-field -type string -name PERSON_ID\nadd-field -type string -name PERSON_NAME\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonnelBiMToM -wait\n\nplan add-index -name PERSON_NAME -table PersonnelBiMToM -field PERSON_NAME -wait\nplan add-index -name ADDRESS_ID -table PersonnelBiMToM -field ADDRESS_ID -wait\n\ntable create -name HabitatBiMToM\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatBiMToM -wait\n\nplan add-index -name STREET -table HabitatBiMToM -field STREET -wait\n\n\nplan remove-table -name HabitatBiMTo1Char -wait\nplan remove-table -name PersonnelBiMTo1Int -wait\n\ntable create -name HabitatBiMTo1Char\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatBiMTo1Char -wait\n\ntable create -name PersonnelBiMTo1Int\nadd-field -type string -name PERSON_NAME\nadd-field -type integer -name PERSON_ID\nadd-field -type string -name ADDRESS_ID\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonnelBiMTo1Int -wait\n\nplan add-index -name STREET -table HabitatBiMTo1Char -field STREET -wait\nplan add-index -name PERSON_NAME -table PersonnelBiMTo1Int -field PERSON_NAME -wait\nplan add-index -name ADDRESS_ID -table PersonnelBiMTo1Int -field ADDRESS_ID -wait\n\n\nplan remove-table -name HabitatUniMTo1Long -wait\nplan remove-table -name PersonnelUniMTo1Int -wait\n\ntable create -name HabitatUniMTo1Long\nadd-field -type long -name ADDRESS_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatUniMTo1Long -wait\n\n\ntable create -name PersonnelUniMTo1Int\nadd-field -type string -name PERSON_NAME\nadd-field -type integer -name PERSON_ID\nadd-field -type long -name ADDRESS_ID\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonnelUniMTo1Int -wait\n\nplan add-index -name STREET -table HabitatUniMTo1Long -field STREET -wait\nplan add-index -name PERSON_NAME -table PersonnelUniMTo1Int -field PERSON_NAME -wait\nplan add-index -name ADDRESS_ID -table PersonnelUniMTo1Int -field ADDRESS_ID -wait\n\n\nplan remove-table -name PersonnelBi1ToMInt -wait\nplan remove-table -name HabitatBi1ToMDouble -wait\n\ntable create -name HabitatBi1ToMDouble\nadd-field -type double -name ADDRESS_ID\nadd-field -type string -name STREET\nadd-field -type integer -name PERSON_ID\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatBi1ToMDouble -wait\n\ntable create -name PersonnelBi1ToMInt\nadd-field -type string -name PERSON_NAME\nadd-field -type integer -name PERSON_ID\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonnelBi1ToMInt -wait\n\n\nplan add-index -name STREET -table HabitatBi1ToMDouble -field STREET -wait\nplan add-index -name PERSON_NAME -table PersonnelBi1ToMInt -field PERSON_NAME -wait\nplan add-index -name PERSON_ID -table HabitatBi1ToMDouble -field PERSON_ID -wait\n\n\n\nplan remove-table -name PersonnelUni1ToMInt -wait\nplan remove-table -name HabitatUni1ToMFloat -wait\n\ntable create -name HabitatUni1ToMFloat\nadd-field -type float -name ADDRESS_ID\nadd-field -type string -name STREET\nadd-field -type integer -name PERSON_ID\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatUni1ToMFloat -wait\n\ntable create -name PersonnelUni1ToMInt\nadd-field -type string -name PERSON_NAME\nadd-field -type integer -name PERSON_ID\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonnelUni1ToMInt -wait\n\n\nplan add-index -name STREET -table HabitatUni1ToMFloat -field STREET -wait\nplan add-index -name PERSON_NAME -table PersonnelUni1ToMInt -field PERSON_NAME -wait\nplan add-index -name PERSON_ID -table HabitatUni1ToMFloat -field PERSON_ID -wait\n\n\nplan remove-table -name PersonnelUni1To1FKInt -wait\nplan remove-table -name HabitatUni1To1FKInteger -wait\n\n\ntable create -name PersonnelUni1To1FKInt\nadd-field -type string -name PERSON_NAME\nadd-field -type integer -name PERSON_ID\nadd-field -type integer -name ADDRESS_ID\nprimary-key -field PERSON_ID\nexit\nplan add-table -name PersonnelUni1To1FKInt -wait\n\ntable create -name HabitatUni1To1FKInteger\nadd-field -type integer -name ADDRESS_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatUni1To1FKInteger -wait\n\nplan add-index -name STREET -table HabitatUni1To1FKInteger -field STREET -wait\nplan add-index -name PERSON_NAME -table PersonnelUni1To1FKInt -field PERSON_NAME -wait\nplan add-index -name ADDRESS_ID -table PersonnelUni1To1FKInt -field ADDRESS_ID -wait\n\ntable create -name OraclePersonnelOTOFKEntityJTA\nadd-field -type string -name PERSON_NAME\nadd-field -type string -name PERSON_ID\nadd-field -type string -name ADDRESS_ID\nprimary-key -field PERSON_ID\nexit\nplan add-table -name OraclePersonnelOTOFKEntityJTA -wait\nplan add-index -name ADDRESS_ID -table OraclePersonnelOTOFKEntityJTA -field ADDRESS_ID -wait\n\n\n\ntable create -name HabitatOToOFKEntityJTA\nadd-field -type string -name ADDRESS_ID\nadd-field -type string -name STREET\nprimary-key -field ADDRESS_ID\nexit\nplan add-table -name HabitatOToOFKEntityJTA -wait\n"
  },
  {
    "path": "src/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus</groupId>\n\t\t<artifactId>kundera-parent</artifactId>\n\t\t<version>3.14-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus</groupId>\n\t<artifactId>kundera</artifactId>\n\t<version>3.14-SNAPSHOT</version>\n\t<packaging>pom</packaging>\n\t<name>kundera-trunk</name>\n\t<url>https://github.com/Impetus/Kundera</url>\n\n\t<licenses>\n\t\t<license>\n\t\t\t<name>The Apache Software License, Version 2.0</name>\n\t\t\t<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>\n\t\t\t<distribution>repo</distribution>\n\t\t</license>\n\t</licenses>\n\n\t<scm>\n\t\t<connection>scm:git:git@github.com:Impetus/Kundera.git</connection>\n\t\t<developerConnection>scm:git:git@github.com:Impetus/Kundera.git</developerConnection>\n\t\t<url>git@github.com:Impetus/Kundera.git</url>\n\t\t<tag>HEAD</tag>\n\t</scm>\n\n\t<developers>\n\t\t<developer>\n\t\t\t<id>vivek.mishra</id>\n\t\t\t<name>Vivek Mishra</name>\n\t\t\t<email>vivek.mishra@yahoo.com</email>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<id>devender-yadav</id>\n\t\t\t<name>Devender Yadav</name>\n\t\t\t<email>devender.yadav@impetus.co.in</email>\n\t\t</developer>\n\t\t<developer>\n\t\t\t<id>karthikprasad13</id>\n\t\t\t<name>Karthik Prasad Manchala</name>\n\t\t\t<email>karthikp.manchala@impetus.co.in</email>\n\t\t</developer>\n\t</developers>\n\n\t<!-- <issueManagement> <system>Google Code</system> <url>http://code.google.com/p/kundera/issues/list</url> \n\t\t</issueManagement> <distributionManagement> <site> <id>website</id> <url>http://kundera.googlecode.com/svn/trunk</url> \n\t\t</site> <repository> <id>googlecode.kundera.repo</id> <url>dav:https://kundera.googlecode.com/svn/maven2/maven-repo-release/</url> \n\t\t</repository> <snapshotRepository> <id>googlecode.kundera.snapshotrepo</id> \n\t\t<url>dav:https://kundera.googlecode.com/svn/maven2/maven-repo-snapshot/</url> \n\t\t<uniqueVersion>false</uniqueVersion> </snapshotRepository> </distributionManagement> -->\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t\t<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n\t\t<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>\n\t\t<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>\n\t\t<sonar.jacoco.itReportPath>${project.basedir}/../target/jacoco-it.exec</sonar.jacoco.itReportPath>\n\t\t<sonar.language>java</sonar.language>\n\t</properties>\n\n\t<!-- <repositories> <repository> <id>clover</id> <name>Clover maven repo</name> \n\t\t<url>http://mirrors.ibiblio.org/pub/mirrors/maven</url> <releases> <enabled>true</enabled> \n\t\t</releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> \n\t\t<repository> <id>kundera-missing</id> <name>Kundera Public Missing Resources \n\t\tRepository</name> <url>http://kundera.googlecode.com/svn/maven2/maven-missing-resources</url> \n\t\t<releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> \n\t\t</snapshots> </repository> <repository> <id>riptano</id> <name>riptano</name> \n\t\t<url>http://mvn.riptano.com/content/repositories/public</url> </repository> \n\t\t<repository> <id>maven.scale7.org</id> <name>Scale7 Maven Repo</name> <url>https://github.com/s7/mvnrepo/raw/master</url> \n\t\t<snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> -->\n\n\t<!-- Build profiles -->\n\t<profiles>\n\n\t\t<profile>\n\t\t\t<id>all</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>true</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-elastic-search</module>\n\t\t\t\t<module>kundera-cassandra</module>\n\t\t\t\t<module>kundera-spark</module>\n\t\t\t\t<module>kundera-kudu</module>\n\t\t\t\t<module>kundera-rethinkdb</module>\n\t\t\t\t<module>data-as-object</module>\n\t\t\t\t<module>kundera-hbase</module>\n\t\t\t\t<module>kundera-mongo</module>\n\t\t\t\t<module>kundera-rdbms</module>\n\t\t\t\t<module>kundera-neo4j</module>\n\t\t\t\t<module>kundera-rest</module>\n\t\t\t\t<module>kundera-redis</module>\n\t\t\t\t<module>kundera-oracle-nosql</module>\n\t\t\t\t<module>kundera-couchdb</module>\n\t\t\t\t<module>kundera-couchbase</module>\n\t\t\t\t<module>kundera-ethereum</module>\n\t\t\t\t<module>kundera-tests</module>\n\t\t\t</modules>\n\t\t</profile>\n\t\t<profile>\n\t\t\t<id>ethereum</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-ethereum</module>\n\t\t\t</modules>\n\t\t</profile>\n\t\t<profile>\n\t\t\t<id>elastic-search</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-elastic-search</module>\n\t\t\t</modules>\n\t\t</profile>\n\n\t\t<profile>\n\t\t\t<id>rdbms</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-rdbms</module>\n\t\t\t</modules>\n\t\t</profile>\n\n\n\t\t<profile>\n\t\t\t<id>redis</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-redis</module>\n\t\t\t</modules>\n\t\t</profile>\n\t\t<profile>\n\t\t\t<id>oracle-nosql</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-oracle-nosql</module>\n\t\t\t</modules>\n\t\t</profile>\n\t\t<profile>\n\t\t\t<id>couchdb</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-couchdb</module>\n\t\t\t</modules>\n\t\t</profile>\n\t\t<profile>\n\t\t\t<id>couchbase</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-couchbase</module>\n\t\t\t</modules>\n\t\t</profile>\n\t\t<profile>\n\t\t\t<id>hbase</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-hbase</module>\n\t\t\t</modules>\n\t\t</profile>\n\n\t\t<profile>\n\t\t\t<id>spark</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-spark</module>\n\t\t\t</modules>\n\t\t</profile>\n\n\t\t<profile>\n\t\t\t<id>kudu</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-kudu</module>\n\t\t\t</modules>\n\t\t</profile>\n\n\t\t<profile>\n\t\t\t<id>rethinkdb</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-rethinkdb</module>\n\t\t\t</modules>\n\t\t</profile>\n\n\t\t<profile>\n\t\t\t<id>data-as-object</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>data-as-object</module>\n\t\t\t</modules>\n\t\t</profile>\n\n\t\t<profile>\n\t\t\t<id>mongo</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-mongo</module>\n\t\t\t</modules>\n\t\t</profile>\n\t\t<profile>\n\t\t\t<id>neo4j</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-neo4j</module>\n\t\t\t</modules>\n\t\t</profile>\n\t\t<profile>\n\t\t\t<id>cassandra</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-elastic-search</module>\n\t\t\t\t<module>kundera-cassandra</module>\n\t\t\t</modules>\n\t\t</profile>\n\t\t<profile>\n\t\t\t<id>rest</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>false</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>jpa-engine</module>\n\t\t\t\t<module>kundera-rest</module>\n\t\t\t</modules>\n\t\t</profile>\n\t</profiles>\n\n\t<build>\n\t\t<extensions>\n\t\t\t<extension>\n\t\t\t\t<groupId>org.apache.maven.wagon</groupId>\n\t\t\t\t<artifactId>wagon-webdav</artifactId>\n\t\t\t\t<version>1.0-beta-2</version>\n\t\t\t</extension>\n\t\t</extensions>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<version>2.3.2</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t\t<!-- <fork>true</fork> -->\n\t\t\t\t\t<meminitial>512m</meminitial>\n\t\t\t\t\t<maxmem>256m</maxmem>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-checkstyle-plugin</artifactId>\n\t\t\t\t<version>2.3.2</version>\n\t\t\t\t<dependencies>\n\t\t\t\t\t<!-- <dependency> <groupId>com.impetus.ilabs.build</groupId> <artifactId>checkstyle-config</artifactId> \n\t\t\t\t\t\t<version>1</version> </dependency> -->\n\t\t\t\t</dependencies>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-pmd-plugin</artifactId>\n\t\t\t\t<version>2.3</version>\n\t\t\t\t<dependencies>\n\t\t\t\t\t<!-- <dependency> <groupId>com.impetus.ilabs.build</groupId> <artifactId>pmd-config</artifactId> \n\t\t\t\t\t\t<version>1</version> </dependency> -->\n\t\t\t\t</dependencies>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-source-plugin</artifactId>\n\t\t\t\t<version>2.4</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<id>attach-sources</id>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-javadoc-plugin</artifactId>\n\t\t\t\t<version>2.9</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<id>attach-javadocs</id>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> \n\t\t\t\t<executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> \n\t\t\t\t<goal>sign</goal> </goals> </execution> </executions> </plugin> -->\n\t\t\t<!-- <plugin> -->\n\t\t\t<!-- <groupId>org.jacoco</groupId> -->\n\t\t\t<!-- <artifactId>jacoco-maven-plugin</artifactId> -->\n\t\t\t<!-- <version>0.5.3.201107060350</version> -->\n\t\t\t<!-- </plugin> -->\n\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.jacoco</groupId>\n\t\t\t\t<artifactId>jacoco-maven-plugin</artifactId>\n\t\t\t\t<version>0.5.3.201107060350</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<includes>com.*</includes>\n\t\t\t\t</configuration>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<id>pre-test</id>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>prepare-agent</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<id>post-test</id>\n\t\t\t\t\t\t<phase>test</phase>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>report</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n\n"
  },
  {
    "path": "test/benchmark/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus.kundera</groupId>\n\t\t<artifactId>test</artifactId>\n\t\t<version>1.0.0-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera</groupId>\n\t<artifactId>kundera-benchmark</artifactId>\n\t<version>1.0.0-SNAPSHOT</version>\n\t<packaging>pom</packaging>\n\n\t<name>benchmark</name>\n\t<url>https://github.com/impetus-opensource/Kundera</url>\n\n\t<!-- Build profiles -->\n\t<profiles>\n\n\t\t<profile>\n\t\t\t<id>all</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>true</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>ycsb</module>\n\t\t\t</modules>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  },
  {
    "path": "test/benchmark/ycsb/README.md",
    "content": "kundera-benchmarks\n==================\n\nKundera performance benchmarking API. Current version provides YCSB based performance benchmarking for Kundera.\nProject includes benchmarking for Cassandra,MongoDB,Neo4j,Redis.\n\n{Performance Benchmarking}\n\nCassandra\n=========\n1. Kundera's thrift client vs. raw Thrift client.\n2. Kundera's pelops client vs. raw Pelops client.\n\nMongoDB\n=======\n1. Kundera's MongoDB client vs. MongoDB client.\n\nHBase\n=======\n1. Kundera's HBase client vs. Raw HBase client.\n\nRedis\n=====\n1. Kundera Redis client vs. Jedis\n\nNeo4j\n=====\n1. Kundera Neo4j vs. Native neo4j client.\n\n\nHow to run:\n========== \n <b>Step1: <b>\n \n  Modify properties file specific to nosql database. For example, in case of Cassandra it is db-cassandra.properties. \n You need to modify for \"ycsbjar.location\" and \"clientjar.location\" according to system configuration.\n \n <b>Step2: <b>\n \n Command to run a test is as follows:\n mvn -Dtest=RedisYCSBTest test -DfileName=src/main/resources/db-redis.properties\n Here \"RedisYCSBTest\" is junit name and -DfileName is for corresponding properties file.\n {Above command to execute Redis YCSB benchmark test}. \n Other test cases are CassandraYCSBTest,MongoDBYCSBTest,Neo4jYCSBTest.\n\n\nFor more details on usage of YCSB framework, please refer:\n\n1. https://github.com/brianfrankcooper/YCSB\n2. https://github.com/brianfrankcooper/YCSB/wiki/Getting-Started\n"
  },
  {
    "path": "test/benchmark/ycsb/pom.xml",
    "content": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n<parent>\n\t\t<groupId>com.impetus.kundera</groupId>\n\t\t<artifactId>kundera-benchmark</artifactId>\n\t\t<version>1.0.0-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera.ycsb</groupId>\n\t<artifactId>kundera-ycsb</artifactId>\n\t<packaging>jar</packaging>\n\t<version>1.0.0</version>\n\n\t<name>ycsb</name>\n\t<url>https://github.com/impetus-opensource/Kundera</url>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t\t<kundera.version>3.7</kundera.version>\n\t</properties>\n\n\t<dependencies>\n\n<!-- \t\t<dependency> -->\n<!-- \t\t<groupId>com.yahoo.ycsb</groupId> -->\n<!-- \t\t<artifactId>core</artifactId> -->\n<!-- \t\t<version>0.1.4</version> -->\n<!-- \t\t<exclusions> -->\n<!-- \t\t<exclusion> -->\n<!-- \t\t<groupId>com.google.collections</groupId> -->\n<!-- \t\t<artifactId>google-collections</artifactId> -->\n<!-- \t\t</exclusion> -->\n<!-- \t\t</exclusions> -->\n<!-- \t\t</dependency> -->\n\n\t\t<dependency>\n\t\t\t<groupId>com.yahoo.ycsb</groupId>\n\t\t\t<artifactId>core</artifactId>\n\t\t\t<version>0.1.4</version>\n\t\t\t<scope>system</scope>\n\t\t\t<systemPath>/home/IMPETUS/devender.yadav/core-0.1.4.jar</systemPath>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>com.google.collections</groupId>\n\t\t\t\t\t<artifactId>google-collections</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>org.apache.phoenix</groupId>\n\t\t\t<artifactId>phoenix-core</artifactId>\n\t\t\t<version>4.5.0-HBase-1.0</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.apache.httpcomponents</groupId>\n\t\t\t\t\t<artifactId>httpclient</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.apache.httpcomponents</groupId>\n\t\t\t\t\t<artifactId>httpcore</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>net.sourceforge.jexcelapi</groupId>\n\t\t\t<artifactId>jxl</artifactId>\n\t\t\t<version>2.6.3</version>\n\t\t</dependency>\n\n\t\t<!-- for mail -->\n\t\t<dependency>\n\t\t\t<groupId>org.springframework</groupId>\n\t\t\t<artifactId>spring-context-support</artifactId>\n\t\t\t<version>3.0.5.RELEASE</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>javax.mail</groupId>\n\t\t\t<artifactId>mail</artifactId>\n\t\t\t<version>1.4</version>\n\t\t</dependency>\n\n\t\t<!-- kundera dependencies -->\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-kudu</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-hbase-v2</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.apache.httpcomponents</groupId>\n\t\t\t\t\t<artifactId>httpclient</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.apache.httpcomponents</groupId>\n\t\t\t\t\t<artifactId>httpcore</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t\t\t<artifactId>kundera-elastic-search</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-rdbms</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-redis</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-neo4j</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-mongo</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-cassandra-pelops</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.google.guava</groupId>\n\t\t\t<artifactId>guava</artifactId>\n\t\t\t<version>16.0.1</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-oracle-nosql</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\n\t\t<dependency>\n\t\t\t<groupId>com.impetus.kundera.client</groupId>\n\t\t\t<artifactId>kundera-couchdb</artifactId>\n\t\t\t<version>${kundera.version}</version>\n\t\t</dependency>\n\n\t\t<!-- <dependency> -->\n\t\t<!-- <groupId>org.hibernate</groupId> -->\n\t\t<!-- <artifactId>hibernate-entitymanager</artifactId> -->\n\t\t<!-- <version>4.1.7.Final</version> -->\n\t\t<!-- </dependency> -->\n\n\n\t\t<dependency>\n\t\t\t<groupId>junit</groupId>\n\t\t\t<artifactId>junit</artifactId>\n\t\t\t<version>4.11</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\n\t\t<!-- apache commons -->\n\t\t<!-- <dependency> -->\n\t\t<!-- <groupId>commons-configuration</groupId> -->\n\t\t<!-- <artifactId>commons-configuration</artifactId> -->\n\t\t<!-- <version>1.9</version> -->\n\t\t<!-- </dependency> -->\n\n\n\n\t\t<!-- hector dependency -->\n\t\t<dependency>\n\t\t\t<groupId>me.prettyprint</groupId>\n\t\t\t<artifactId>hector-core</artifactId>\n\t\t\t<version>1.0-5</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.apache.cassandra</groupId>\n\t\t\t\t\t<artifactId>cassandra-thrift</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\n\t\t<!-- redis client -->\n\t\t<dependency>\n\t\t\t<groupId>redis.clients</groupId>\n\t\t\t<artifactId>jedis</artifactId>\n\t\t\t<version>2.6.0</version>\n\t\t\t<type>jar</type>\n\t\t\t<scope>compile</scope>\n\t\t</dependency>\n\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t\n\t\t\t\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-shade-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<filters>\n\t\t\t\t\t\t<filter>\n\t\t\t\t\t\t\t<artifact>*:*</artifact>\n\t\t\t\t\t\t\t<excludes>\n\t\t\t\t\t\t\t\t<exclude>META-INF/*.SF</exclude>\n\t\t\t\t\t\t\t\t<exclude>META-INF/*.DSA</exclude>\n\t\t\t\t\t\t\t\t<exclude>META-INF/*.RSA</exclude>\n\t\t\t\t\t\t\t</excludes>\n\t\t\t\t\t\t</filter>\n\t\t\t\t\t</filters>\n\t\t\t\t</configuration>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<id>job-driver-jar</id>\n\t\t\t\t\t\t<phase>package</phase>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>shade</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<!-- <shadedArtifactAttached>true</shadedArtifactAttached> -->\n\t\t\t\t\t\t\t<!-- <shadedClassifierName>driver</shadedClassifierName> -->\n\t\t\t\t\t\t\t<finalName>${project.artifactId}-${project.version}</finalName>\n\n\t\t\t\t\t\t\t<transformers>\n\t\t\t\t\t\t\t\t<transformer\n\t\t\t\t\t\t\t\t\timplementation=\"org.apache.maven.plugins.shade.resource.ServicesResourceTransformer\" />\n\t\t\t\t\t\t\t\t<!-- Some care is required: http://doc.akka.io/docs/akka/snapshot/general/configuration.html -->\n\t\t\t\t\t\t\t\t<transformer\n\t\t\t\t\t\t\t\t\timplementation=\"org.apache.maven.plugins.shade.resource.AppendingTransformer\">\n\t\t\t\t\t\t\t\t\t<resource>reference.conf</resource>\n\t\t\t\t\t\t\t\t</transformer>\n\t\t\t\t\t\t\t\t<transformer\n\t\t\t\t\t\t\t\t\timplementation=\"org.apache.maven.plugins.shade.resource.ManifestResourceTransformer\">\n\t\t\t\t\t\t\t\t\t<mainClass>foo.bar.SparkJobs</mainClass>\n\t\t\t\t\t\t\t\t</transformer>\n\t\t\t\t\t\t\t</transformers>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t\n\n\t\t\t<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> \n\t\t\t\t<version>2.9</version> <configuration> <argLine>-Xms512M -Xmx2048M -XX:+UseConcMarkSweepGC \n\t\t\t\t-XX:+UseParNewGC</argLine> </configuration> </plugin> -->\n\t\t</plugins>\n\t</build>\n\n</project>\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/CouchDBNativeClient.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.Reader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.HttpStatus;\nimport org.apache.http.client.ClientProtocolException;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.client.methods.HttpPut;\nimport org.apache.http.entity.StringEntity;\n\nimport redis.clients.jedis.Protocol;\n\nimport com.google.gson.Gson;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonObject;\nimport com.impetus.client.couchdb.CouchDBConstants;\nimport com.impetus.client.couchdb.CouchDBUtils;\nimport com.impetus.kundera.Constants;\nimport com.impetus.kundera.ycsb.utils.CouchDBOperationUtils;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\n\n/**\n * @author Vivek mishra\n * \n */\npublic class CouchDBNativeClient extends DB\n{\n    private HttpClient httpClient;\n\n    private HttpHost httpHost;\n\n    public static final String HOST_PROPERTY = \"hosts\";\n\n    public static final String PORT_PROPERTY = \"port\";\n\n    public static final String INDEX_KEY = \"_indices\";\n\n    private String database = \"schema\";\n\n    private Gson gson = new Gson();\n\n    private CouchDBOperationUtils utils = new CouchDBOperationUtils();;\n\n    public void init() throws DBException\n    {\n        Properties props = getProperties();\n        database = props.getProperty(\"schema\", \"kundera_native\");\n        if (httpClient == null || httpHost == null)\n        {\n            System.out.println(\"Initailizing ....\");\n            int port;\n\n            String portString = props.getProperty(PORT_PROPERTY);\n            if (portString != null)\n            {\n                port = Integer.parseInt(portString);\n            }\n            else\n            {\n                port = Protocol.DEFAULT_PORT;\n            }\n            String host = props.getProperty(HOST_PROPERTY);\n\n            httpClient = utils.initiateClient(host, port);\n            httpHost = new HttpHost(host, port);\n        }\n    }\n\n    public void cleanup() throws DBException\n    {\n        // httpClient.getConnectionManager().shutdown();\n        // httpHost = null;\n    }\n\n    /*\n     * Calculate a hash for a key to store it in an index. The actual return\n     * value of this function is not interesting -- it primarily needs to be\n     * fast and scattered along the whole space of doubles. In a real world\n     * scenario one would probably use the ASCII values of the keys.\n     */\n    private double hash(String key)\n    {\n        return key.hashCode();\n    }\n\n    // XXX jedis.select(int index) to switch to `table`\n\n    @Override\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        HttpResponse response = null;\n        try\n        {\n            System.out.println(\"Reading ....\");\n            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + database.toLowerCase() + CouchDBConstants.URL_SEPARATOR + table\n                            + key, null, null);\n            HttpGet get = new HttpGet(uri);\n            get.addHeader(\"Accept\", \"application/json\");\n            response = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));\n\n            InputStream content = response.getEntity().getContent();\n            Reader reader = new InputStreamReader(content);\n\n            JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);\n\n            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND)\n            {\n                return 1;\n            }\n            return 0;\n        }\n        catch (Exception e)\n        {\n            throw new RuntimeException(e);\n        }\n        finally\n        {\n            // CouchDBUtils.closeContent(response);\n        }\n    }\n\n    @Override\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        HttpResponse response = null;\n        try\n        {\n            System.out.println(\"Inserting ....\");\n            JsonObject object = new JsonObject();\n            for (Map.Entry<String, ByteIterator> entry : values.entrySet())\n            {\n                object.addProperty(entry.getKey(), entry.getValue().toString());\n            }\n            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + database.toLowerCase() + CouchDBConstants.URL_SEPARATOR + table\n                            + key, null, null);\n\n            HttpPut put = new HttpPut(uri);\n\n            StringEntity stringEntity = null;\n            object.addProperty(\"_id\", table + key);\n            stringEntity = new StringEntity(object.toString(), Constants.CHARSET_UTF8);\n            stringEntity.setContentType(\"application/json\");\n            put.setEntity(stringEntity);\n\n            response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));\n\n            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND)\n            {\n                return 1;\n            }\n            return 0;\n        }\n        catch (Exception e)\n        {\n            throw new RuntimeException(e);\n        }\n        finally\n        {\n            // CouchDBUtils.closeContent(response);\n        }\n    }\n\n    @Override\n    public int delete(String table, String key)\n    {\n\n        HttpResponse response = null;\n        URI uri = null;\n        try\n        {\n            System.out.println(\"Deleting ....\");\n            HttpGet get;\n            Reader reader;\n            uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                    CouchDBConstants.URL_SEPARATOR + database.toLowerCase() + CouchDBConstants.URL_SEPARATOR + table\n                            + key, null, null);\n            get = new HttpGet(uri);\n            get.addHeader(\"Accept\", \"application/json\");\n            response = httpClient.execute(get);\n\n            reader = new InputStreamReader(response.getEntity().getContent());\n            JsonObject json = gson.fromJson(reader, JsonObject.class);\n            // CouchDBUtils.closeContent(response);\n            if (!(response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND))\n            {\n                onDelete(database, table + key, response, json);\n                return 0;\n            }\n            return 1;\n        }\n        catch (Exception e)\n        {\n            throw new RuntimeException(e);\n        }\n        finally\n        {\n            // CouchDBUtils.closeContent(response);\n        }\n\n    }\n\n    @Override\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n\n        throw new RuntimeException(\"Operation not supported\");\n    }\n\n    @Override\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        throw new RuntimeException(\"Operation not supported\");\n    }\n\n    private void onDelete(String schemaName, Object pKey, HttpResponse response, JsonObject jsonObject)\n            throws URISyntaxException, IOException, ClientProtocolException\n    {\n        URI uri;\n        String q;\n        JsonElement rev = jsonObject.get(\"_rev\");\n\n        StringBuilder builder = new StringBuilder();\n        builder.append(\"rev=\");\n        builder.append(rev.getAsString());\n        q = builder.toString();\n\n        // uri = new URI(CouchDBConstants.PROTOCOL, null,\n        // httpHost.getHostName(), httpHost.getPort(),\n        // CouchDBConstants.URL_SAPRATOR + schemaName.toLowerCase() +\n        // CouchDBConstants.URL_SAPRATOR + pKey, q,\n        // null);\n\n        // HttpDelete delete = new HttpDelete(uri);\n\n        // response = httpClient.execute(delete);\n        // CouchDBUtils.closeContent(response);\n    }\n\n    public static void main(String[] args)\n    {\n\n        CouchDBNativeClient cli = new CouchDBNativeClient();\n\n        Properties props = new Properties();\n\n        props.setProperty(\"hosts\", \"localhost\");\n        props.setProperty(\"port\", \"5984\");\n        cli.setProperties(props);\n\n        try\n        {\n            cli.init();\n        }\n        catch (Exception e)\n        {\n            e.printStackTrace();\n            System.exit(0);\n        }\n\n        HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();\n        vals.put(\"age\", new StringByteIterator(\"57\"));\n        vals.put(\"middlename\", new StringByteIterator(\"bradley\"));\n        vals.put(\"favoritecolor\", new StringByteIterator(\"blue\"));\n        int res = cli.insert(\"usertable\", \"BrianFrankCooper\", vals);\n        System.out.println(\"Result of insert: \" + res);\n\n        HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();\n        HashSet<String> fields = new HashSet<String>();\n        fields.add(\"middlename\");\n        fields.add(\"age\");\n        fields.add(\"favoritecolor\");\n        res = cli.read(\"usertable\", \"BrianFrankCooper\", null, result);\n        System.out.println(\"Result of read: \" + res);\n        for (String s : result.keySet())\n        {\n            System.out.println(\"[\" + s + \"]=[\" + result.get(s) + \"]\");\n        }\n\n        res = cli.delete(\"usertable\", \"BrianFrankCooper\");\n        System.out.println(\"Result of delete: \" + res);\n\n    }\n}"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/HBaseClient.java",
    "content": "package com.impetus.kundera.ycsb.benchmark;\n\n/**\n * Copyright (c) 2010 Yahoo! Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You\n * may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License. See accompanying\n * LICENSE file.\n */\n\nimport java.io.IOException;\nimport java.util.ConcurrentModificationException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.hbase.HBaseConfiguration;\nimport org.apache.hadoop.hbase.KeyValue;\nimport org.apache.hadoop.hbase.client.Delete;\nimport org.apache.hadoop.hbase.client.Get;\nimport org.apache.hadoop.hbase.client.HTableInterface;\nimport org.apache.hadoop.hbase.client.HTablePool;\nimport org.apache.hadoop.hbase.client.Put;\nimport org.apache.hadoop.hbase.client.Result;\nimport org.apache.hadoop.hbase.client.ResultScanner;\nimport org.apache.hadoop.hbase.client.Scan;\nimport org.apache.hadoop.hbase.util.Bytes;\n\nimport com.yahoo.ycsb.ByteArrayByteIterator;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\n\n/**\n * YCSB HBase client for YCSB framework\n */\npublic class HBaseClient extends com.yahoo.ycsb.DB\n{\n    // BFC: Change to fix broken build (with HBase 0.20.6)\n    // private static final Configuration config = HBaseConfiguration.create();\n    private static final Configuration config = HBaseConfiguration.create(); // new\n                                                                             // HBaseConfiguration();\n\n    public boolean _debug = false;\n\n    public static String _table = \"usertable\";\n\n    public HTableInterface _hTable = null;\n\n    public static String _columnFamily = \"user\";\n\n    public static byte _columnFamilyBytes[]= Bytes.toBytes(_columnFamily);\n\n    public static final int Ok = 0;\n\n    public static final int ServerError = -1;\n\n    public static final int HttpError = -2;\n\n    public static final int NoMatchingRecord = -3;\n\n    public static final Object tableLock = new Object();\n\n    public static final int poolSize = 100;\n\n    private static HTablePool hTablePool = new HTablePool(config, poolSize);\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {/*\n        if ((getProperties().getProperty(\"debug\") != null)\n                && (getProperties().getProperty(\"debug\").compareTo(\"true\") == 0))\n        {\n            _debug = true;\n        }\n\n        _columnFamily = getProperties().getProperty(\"columnfamilyOrTable\");\n        _table = getProperties().getProperty(\"schema\");\n        // System.out.println(_table);\n\n        if (_columnFamily == null)\n        {\n            System.err.println(\"Error, must specify a columnfamily for HBase table\");\n            throw new DBException(\"No columnfamily specified\");\n        }\n        _columnFamilyBytes = Bytes.toBytes(_columnFamily);\n\n    */}\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n        // // Get the measurements instance as this is the only client that\n        // should\n        // // count clean up time like an update since autoflush is off.\n        // // Measurements _measurements = Measurements.getMeasurements();\n        // try\n        // {\n        // // long st = System.nanoTime();\n        // /* if (_hTable != null)\n        // {\n        // _hTable.flushCommits();\n        // }*/\n        // // long en = System.nanoTime();\n        // // _measurements.measure(\"UPDATE\", (int) ((en - st) / 1000));\n        // }\n        // catch (IOException e)\n        // {\n        // throw new DBException(e);\n        // }\n    }\n\n    public void getHTable(String table) throws IOException\n    {\n        // synchronized (tableLock)\n        // {\n\n        _hTable = hTablePool.getTable(table);\n        // _hTable = new HTable(config, table);\n        // 2 suggestions from\n        // http://ryantwopointoh.blogspot.com/2009/01/performance-of-hbase-importing.html\n        // _hTable.setAutoFlush(true);\n        // _hTable.setWriteBufferSize(1024*1024*12);\n        // return hTable;\n        // }\n\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        // if this is a \"new\" table, init HTable object. Else, use existing one\n        /*\n         * if (!_table.equals(table)) { _hTable = null; try { getHTable(table);\n         * _table = table; } catch (IOException e) {\n         * System.err.println(\"Error accessing HBase table: \"+e); return\n         * ServerError; } }\n         */\n\n        try\n        {\n            // if (_hTable == null)\n            // {\n\n            getHTable(_table);\n            // }\n        }\n        catch (IOException e)\n        {\n            System.err.println(\"Error accessing HBase table: \" + e);\n            return ServerError;\n        }\n\n        Result r = null;\n        try\n        {\n            // if (_debug)\n            // {\n            // System.out.println(\"Doing read from HBase columnfamily \" +\n            // _columnFamily);\n            // System.out.println(\"Doing read for key: \" + key);\n            // }\n            Get g = new Get(Bytes.toBytes(key));\n            if (fields == null)\n            {\n                g.addFamily(_columnFamilyBytes);\n            }\n            else\n            {\n                for (String field : fields)\n                {\n                    g.addColumn(_columnFamilyBytes, Bytes.toBytes(field));\n                }\n            }\n            r = _hTable.get(g);\n        }\n        catch (IOException e)\n        {\n            System.err.println(\"Error doing get: \" + e);\n            return ServerError;\n        }\n        catch (ConcurrentModificationException e)\n        {\n            // do nothing for now...need to understand HBase concurrency model\n            // better\n            return ServerError;\n        }\n        finally\n        {\n            try\n            {\n                hTablePool.putTable(_hTable);\n            }\n            catch (IOException e)\n            {\n            }\n        }\n\n        for (KeyValue kv : r.raw())\n        {\n            String column = Bytes.toString(kv.getQualifier());\n            Object value = new ByteArrayByteIterator(kv.getValue());/*\n                                                                     * PropertyAccessorHelper\n                                                                     * .\n                                                                     * getObject\n                                                                     * (\n                                                                     * Object.class\n                                                                     * ,\n                                                                     * kv.getValue\n                                                                     * ());\n                                                                     */\n            assert column != null;\n            assert value != null;\n            // result.put(Bytes.toString(kv.getQualifier()), new\n            // ByteArrayByteIterator(kv.getValue()));\n            // if (_debug)\n            // {\n            // System.out.println(\"Result for field: \" +\n            // Bytes.toString(kv.getQualifier()) + \" is: \"\n            // + Bytes.toString(kv.getValue()));\n            // }\n\n        }\n        return Ok;\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        // if this is a \"new\" table, init HTable object. Else, use existing one\n        if (!_table.equals(table))\n        {\n            _hTable = null;\n            try\n            {\n                getHTable(table);\n                _table = table;\n            }\n            catch (IOException e)\n            {\n                System.err.println(\"Error accessing HBase table: \" + e);\n                return ServerError;\n            }\n        }\n\n        Scan s = new Scan(Bytes.toBytes(startkey));\n        // HBase has no record limit. Here, assume recordcount is small enough\n        // to bring back in one call.\n        // We get back recordcount records\n        s.setCaching(recordcount);\n\n        // add specified fields or else all fields\n        if (fields == null)\n        {\n            s.addFamily(_columnFamilyBytes);\n        }\n        else\n        {\n            for (String field : fields)\n            {\n                s.addColumn(_columnFamilyBytes, Bytes.toBytes(field));\n            }\n        }\n\n        // get results\n        ResultScanner scanner = null;\n        try\n        {\n            scanner = _hTable.getScanner(s);\n            int numResults = 0;\n            for (Result rr = scanner.next(); rr != null; rr = scanner.next())\n            {\n                // get row key\n                String key = Bytes.toString(rr.getRow());\n                if (_debug)\n                {\n                    System.out.println(\"Got scan result for key: \" + key);\n                }\n\n                HashMap<String, ByteIterator> rowResult = new HashMap<String, ByteIterator>();\n\n                for (KeyValue kv : rr.raw())\n                {\n                    rowResult.put(Bytes.toString(kv.getQualifier()), new ByteArrayByteIterator(kv.getValue()));\n                }\n                // add rowResult to result vector\n                result.add(rowResult);\n                numResults++;\n                if (numResults >= recordcount) // if hit recordcount, bail out\n                {\n                    break;\n                }\n            } // done with row\n\n        }\n\n        catch (IOException e)\n        {\n            if (_debug)\n            {\n                System.out.println(\"Error in getting/parsing scan result: \" + e);\n            }\n            return ServerError;\n        }\n        finally\n        {\n            scanner.close();\n            try\n            {\n                hTablePool.putTable(_hTable);\n            }\n            catch (IOException e)\n            {\n            }\n        }\n\n        return Ok;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        // if this is a \"new\" table, init HTable object. Else, use existing one\n        try\n        {\n            if (_hTable == null)\n            {\n                getHTable(_table);\n            }\n        }\n        catch (IOException e)\n        {\n            System.err.println(\"Error accessing HBase table: \" + e);\n            return ServerError;\n        }\n\n        /*\n         * if (!_table.equals(table)) { _hTable = null; try { getHTable(table);\n         * _table = table; } catch (IOException e) {\n         * System.err.println(\"Error accessing HBase table: \"+e); return\n         * ServerError; } }\n         */\n\n        if (_debug)\n        {\n            System.out.println(\"Setting up put for key: \" + key);\n        }\n        Put p = new Put(Bytes.toBytes(key));\n        for (Map.Entry<String, ByteIterator> entry : values.entrySet())\n        {\n            if (_debug)\n            {\n                System.out.println(\"Adding field/value \" + entry.getKey() + \"/\" + entry.getValue() + \" to put request\");\n            }\n            p.add(_columnFamilyBytes, Bytes.toBytes(entry.getKey()), entry.getValue().toArray());\n        }\n\n        try\n        {\n            _hTable.put(p);\n        }\n        catch (IOException e)\n        {\n            if (_debug)\n            {\n                System.err.println(\"Error doing put: \" + e);\n            }\n            return ServerError;\n        }\n        catch (ConcurrentModificationException e)\n        {\n            // do nothing for now...hope this is rare\n            return ServerError;\n        }\n        finally\n        {\n            try\n            {\n                hTablePool.putTable(_hTable);\n            }\n            catch (IOException e)\n            {\n            }\n        }\n\n        return Ok;\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        // if this is a \"new\" table, init HTable object. Else, use existing one\n        try\n        {\n            // if (_hTable == null)\n            // {\n            getHTable(_table);\n            // }\n        }\n        catch (IOException e)\n        {\n            System.err.println(\"Error accessing HBase table: \" + e);\n            return ServerError;\n        }\n\n        /*\n         * if (!_table.equals(table)) { _hTable = null; try { getHTable(table);\n         * _table = table; } catch (IOException e) {\n         * System.err.println(\"Error accessing HBase table: \"+e); return\n         * ServerError; } }\n         */\n\n        if (_debug)\n        {\n            System.out.println(\"Setting up put for key: \" + key);\n        }\n        Put p = new Put(Bytes.toBytes(key));\n\n        // getString(key, \"24\"), getString(key, \"gzb\"), getString(key, \"mishra\")\n\n        for (Map.Entry<String, ByteIterator> entry : values.entrySet())\n        {\n            if (_debug)\n            {\n                System.out.println(\"Adding field/value \" + entry.getKey() + \"/\" + entry.getValue() + \" to put request\");\n            }\n            p.add(_columnFamilyBytes, Bytes.toBytes(entry.getKey()), entry.getValue().toArray());\n        }\n\n        try\n        {\n            _hTable.put(p);\n        }\n        catch (IOException e)\n        {\n            if (_debug)\n            {\n                System.err.println(\"Error doing put: \" + e);\n            }\n            return ServerError;\n        }\n        catch (ConcurrentModificationException e)\n        {\n            // do nothing for now...hope this is rare\n            return ServerError;\n        }\n        finally\n        {\n            try\n            {\n                hTablePool.putTable(_hTable);\n            }\n            catch (IOException e)\n            {\n            }\n        }\n\n        return Ok;\n\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        // if this is a \"new\" table, init HTable object. Else, use existing one\n        if (!_table.equals(table))\n        {\n            _hTable = null;\n            try\n            {\n                getHTable(table);\n                _table = table;\n            }\n            catch (IOException e)\n            {\n                System.err.println(\"Error accessing HBase table: \" + e);\n                return ServerError;\n            }\n        }\n\n        if (_debug)\n        {\n            System.out.println(\"Doing delete for key: \" + key);\n        }\n\n        Delete d = new Delete(Bytes.toBytes(key));\n        try\n        {\n            _hTable.delete(d);\n        }\n        catch (IOException e)\n        {\n            if (_debug)\n            {\n                System.err.println(\"Error doing delete: \" + e);\n            }\n            return ServerError;\n        }\n\n        return Ok;\n    }\n\n    public static void main(String[] args)\n    {\n        if (args.length != 3)\n        {\n            System.out.println(\"Please specify a threadcount, columnfamily and operation count\");\n            System.exit(0);\n        }\n\n        final int keyspace = 10000; // 120000000;\n\n        final int threadcount = Integer.parseInt(args[0]);\n\n        final String columnfamily = args[1];\n\n        final int opcount = 10;\n\n        Vector<Thread> allthreads = new Vector<Thread>();\n\n        for (int i = 0; i < threadcount; i++)\n        {\n            Thread t = new Thread()\n            {\n                public void run()\n                {\n                    try\n                    {\n                        Random random = new Random();\n\n                        HBaseClient cli = new HBaseClient();\n\n                        Properties props = new Properties();\n                        props.setProperty(\"columnfamilyOrTable\", columnfamily);\n                        props.setProperty(\"schema\", \"usertable\");\n                        // props.setProperty(\"debug\",\"true\");\n                        cli.setProperties(props);\n\n                        cli.init();\n\n                        // HashMap<String,String> result=new\n                        // HashMap<String,String>();\n\n                        long accum = 0;\n\n                        for (int i = 0; i < opcount; i++)\n                        {\n                            int keynum = random.nextInt(keyspace);\n                            String key = \"user\" + keynum;\n                            long st = System.currentTimeMillis();\n                            int rescode;\n                            HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();\n                            vals.put(\"age\", new StringByteIterator(\"57\"));\n                            vals.put(\"middlename\", new StringByteIterator(\"bradley\"));\n                            vals.put(\"favoritecolor\", new StringByteIterator(\"blue\"));\n                            cli.insert(\"usertable\", key, vals);\n                        }\n                        /*\n                         * HashMap hm = new HashMap();\n                         * hm.put(\"field1\",\"value1\"); hm.put(\"field2\",\"value2\");\n                         * hm.put(\"field3\",\"value3\");\n                         * rescode=cli.insert(\"table1\",key,hm); HashSet<String>\n                         * s = new HashSet(); s.add(\"field1\"); s.add(\"field2\");\n                         * \n                         * rescode=cli.read(\"table1\", key, s, result);\n                         * //rescode=cli.delete(\"table1\",key);\n                         * rescode=cli.read(\"table1\", key, s, result);\n                         */\n                        // HashSet<String> scanFields = new HashSet<String>();\n                        // scanFields.add(\"field1\");\n                        // scanFields.add(\"field3\");\n                        // Vector<HashMap<String,ByteIterator>> scanResults =\n                        // new Vector<HashMap<String,ByteIterator>>();\n                        /*\n                         * rescode =\n                         * cli.scan(\"usertable\",\"user2\",20,null,scanResults);\n                         * \n                         * long en=System.currentTimeMillis();\n                         * \n                         * accum+=(en-st);\n                         * \n                         * if (rescode!=Ok) {\n                         * System.out.println(\"Error \"+rescode+\" for \"+key); }\n                         *//*\n                            * if (i%1==0) {\n                            * System.out.println(i+\" operations, average latency: \"\n                            * +(((double)accum)/((double)i))); } }\n                            */\n                        // System.out.println(\"Average latency: \"+(((double)accum)/((double)opcount)));\n                        // System.out.println(\"Average get latency: \"+(((double)cli.TotalGetTime)/((double)cli.TotalGetOps)));\n                    }\n                    catch (Exception e)\n                    {\n                        e.printStackTrace();\n                    }\n                }\n            };\n            allthreads.add(t);\n        }\n\n        long st = System.currentTimeMillis();\n        for (Thread t : allthreads)\n        {\n            t.start();\n        }\n\n        for (Thread t : allthreads)\n        {\n            try\n            {\n                t.join();\n            }\n            catch (InterruptedException e)\n            {\n            }\n        }\n        long en = System.currentTimeMillis();\n\n        System.out.println(\"Throughput: \" + ((1000.0) * (((double) (opcount * threadcount)) / ((double) (en - st))))\n                + \" ops/sec\");\n\n    }\n}\n\n/*\n * For customized vim control set autoindent set si set shiftwidth=4\n */"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/HBaseV2Client.java",
    "content": "package com.impetus.kundera.ycsb.benchmark;\n\n/**\n * Copyright (c) 2010 Yahoo! Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You\n * may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License. See accompanying\n * LICENSE file.\n */\n\nimport java.io.IOException;\nimport java.util.ConcurrentModificationException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport org.apache.hadoop.conf.Configuration;\nimport org.apache.hadoop.hbase.Cell;\nimport org.apache.hadoop.hbase.CellUtil;\nimport org.apache.hadoop.hbase.HBaseConfiguration;\nimport org.apache.hadoop.hbase.TableName;\nimport org.apache.hadoop.hbase.client.Connection;\nimport org.apache.hadoop.hbase.client.ConnectionFactory;\nimport org.apache.hadoop.hbase.client.Delete;\nimport org.apache.hadoop.hbase.client.Get;\nimport org.apache.hadoop.hbase.client.Put;\nimport org.apache.hadoop.hbase.client.Result;\nimport org.apache.hadoop.hbase.client.ResultScanner;\nimport org.apache.hadoop.hbase.client.Scan;\nimport org.apache.hadoop.hbase.client.Table;\nimport org.apache.hadoop.hbase.util.Bytes;\n\nimport com.yahoo.ycsb.ByteArrayByteIterator;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\n\n/**\n * YCSB HBase client for YCSB framework\n */\npublic class HBaseV2Client extends com.yahoo.ycsb.DB\n{\n    // BFC: Change to fix broken build (with HBase 0.20.6)\n    // private static final Configuration config = HBaseConfiguration.create();\n    private static final Configuration config = HBaseConfiguration.create(); // new\n                                                                             // HBaseConfiguration();\n    public boolean _debug = false;\n\n    public static String _table = \"usertable:user\";\n\n    public Table _hTable = null;\n\n    public static String _columnFamily = \"user\";\n\n    public static byte _columnFamilyBytes[]= Bytes.toBytes(_columnFamily);\n\n    public static final int Ok = 0;\n\n    public static final int ServerError = -1;\n\n    public static final int HttpError = -2;\n\n    public static final int NoMatchingRecord = -3;\n\n    public static final Object tableLock = new Object();\n\n    private static Connection connection;\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {\n    \ttry {\n\t\t\tconnection = ConnectionFactory.createConnection(config);\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(\"Error accessing HBase table: \" + e);\n\t\t}\n    }\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n    }\n\n    public void getHTable(String table) throws IOException\n    {\n    \t_hTable = connection.getTable(TableName.valueOf(table));\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        try\n        {\n            getHTable(_table);\n        }\n        catch (IOException e)\n        {\n            System.err.println(\"Error accessing HBase table: \" + e);\n            return ServerError;\n        }\n        Result r = null;\n        try\n        {\n            Get g = new Get(Bytes.toBytes(key));\n            if (fields == null)\n            {\n                g.addFamily(_columnFamilyBytes);\n            }\n            else\n            {\n                for (String field : fields)\n                {\n                    g.addColumn(_columnFamilyBytes, Bytes.toBytes(field));\n                }\n            }\n            r = _hTable.get(g);\n        }\n        catch (IOException e)\n        {\n            System.err.println(\"Error doing get: \" + e);\n            return ServerError;\n        }\n        catch (ConcurrentModificationException e)\n        {\n            return ServerError;\n        }\n        finally\n        {\n            try\n            {\n                _hTable.close();\n            }\n            catch (IOException e)\n            {\n            }\n        }\n\n        for(Cell cell : r.listCells()){\n        \tString column = Bytes.toString(CellUtil.cloneQualifier(cell));\n            Object value = new ByteArrayByteIterator(CellUtil.cloneValue(cell));\n            assert column != null;\n            assert value != null;\n        }\n        return Ok;\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        // if this is a \"new\" table, init HTable object. Else, use existing one\n        if (!_table.equals(table))\n        {\n            _hTable = null;\n            try\n            {\n                getHTable(table);\n                _table = table;\n            }\n            catch (IOException e)\n            {\n                System.err.println(\"Error accessing HBase table: \" + e);\n                return ServerError;\n            }\n        }\n\n        Scan s = new Scan(Bytes.toBytes(startkey));\n        s.setCaching(recordcount);\n\n        // add specified fields or else all fields\n        if (fields == null)\n        {\n            s.addFamily(_columnFamilyBytes);\n        }\n        else\n        {\n            for (String field : fields)\n            {\n                s.addColumn(_columnFamilyBytes, Bytes.toBytes(field));\n            }\n        }\n\n        // get results\n        ResultScanner scanner = null;\n        try\n        {\n            scanner = _hTable.getScanner(s);\n            int numResults = 0;\n            for (Result rr = scanner.next(); rr != null; rr = scanner.next())\n            {\n                // get row key\n                String key = Bytes.toString(rr.getRow());\n                if (_debug)\n                {\n                    System.out.println(\"Got scan result for key: \" + key);\n                }\n\n                HashMap<String, ByteIterator> rowResult = new HashMap<String, ByteIterator>();\n\n                for (Cell cell : rr.listCells()){\n                \trowResult.put(Bytes.toString(CellUtil.cloneQualifier(cell)), new ByteArrayByteIterator(CellUtil.cloneValue(cell)));\n                }\n                // add rowResult to result vector\n                result.add(rowResult);\n                numResults++;\n                if (numResults >= recordcount) // if hit recordcount, bail out\n                {\n                    break;\n                }\n            } // done with row\n\n        }\n\n        catch (IOException e)\n        {\n            if (_debug)\n            {\n                System.out.println(\"Error in getting/parsing scan result: \" + e);\n            }\n            return ServerError;\n        }\n        finally\n        {\n            scanner.close();\n            try\n            {\n            \t_hTable.close();\n            }\n            catch (IOException e)\n            {\n            }\n        }\n\n        return Ok;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        // if this is a \"new\" table, init HTable object. Else, use existing one\n        try\n        {\n            if (_hTable == null)\n            {\n                getHTable(_table);\n            }\n        }\n        catch (IOException e)\n        {\n            System.err.println(\"Error accessing HBase table: \" + e);\n            return ServerError;\n        }\n        if (_debug)\n        {\n            System.out.println(\"Setting up put for key: \" + key);\n        }\n        Put p = new Put(Bytes.toBytes(key));\n        for (Map.Entry<String, ByteIterator> entry : values.entrySet())\n        {\n            if (_debug)\n            {\n                System.out.println(\"Adding field/value \" + entry.getKey() + \"/\" + entry.getValue() + \" to put request\");\n            }\n            p.addColumn(_columnFamilyBytes, Bytes.toBytes(entry.getKey()), entry.getValue().toArray());\n        }\n\n        try\n        {\n            _hTable.put(p);\n        }\n        catch (IOException e)\n        {\n            if (_debug)\n            {\n                System.err.println(\"Error doing put: \" + e);\n            }\n            return ServerError;\n        }\n        catch (ConcurrentModificationException e)\n        {\n            // do nothing for now...hope this is rare\n            return ServerError;\n        }\n        finally\n        {\n            try\n            {\n            \t_hTable.close();\n            }\n            catch (IOException e)\n            {\n            }\n        }\n\n        return Ok;\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        // if this is a \"new\" table, init HTable object. Else, use existing one\n        try\n        {\n            // if (_hTable == null)\n            // {\n            getHTable(_table);\n            // }\n        }\n        catch (IOException e)\n        {\n            System.err.println(\"Error accessing HBase table: \" + e);\n            return ServerError;\n        }\n\n        /*\n         * if (!_table.equals(table)) { _hTable = null; try { getHTable(table);\n         * _table = table; } catch (IOException e) {\n         * System.err.println(\"Error accessing HBase table: \"+e); return\n         * ServerError; } }\n         */\n\n        if (_debug)\n        {\n            System.out.println(\"Setting up put for key: \" + key);\n        }\n        Put p = new Put(Bytes.toBytes(key));\n\n        // getString(key, \"24\"), getString(key, \"gzb\"), getString(key, \"mishra\")\n\n        for (Map.Entry<String, ByteIterator> entry : values.entrySet())\n        {\n            if (_debug)\n            {\n                System.out.println(\"Adding field/value \" + entry.getKey() + \"/\" + entry.getValue() + \" to put request\");\n            }\n            p.addColumn(_columnFamilyBytes, Bytes.toBytes(entry.getKey()), entry.getValue().toArray());\n        }\n\n        try\n        {\n            _hTable.put(p);\n        }\n        catch (IOException e)\n        {\n            if (_debug)\n            {\n                System.err.println(\"Error doing put: \" + e);\n            }\n            return ServerError;\n        }\n        catch (ConcurrentModificationException e)\n        {\n            // do nothing for now...hope this is rare\n            return ServerError;\n        }\n        finally\n        {\n            try\n            {\n            \t_hTable.close();\n            }\n            catch (IOException e)\n            {\n            }\n        }\n\n        return Ok;\n\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        // if this is a \"new\" table, init HTable object. Else, use existing one\n        if (!_table.equals(table))\n        {\n            _hTable = null;\n            try\n            {\n                getHTable(table);\n                _table = table;\n            }\n            catch (IOException e)\n            {\n                System.err.println(\"Error accessing HBase table: \" + e);\n                return ServerError;\n            }\n        }\n\n        if (_debug)\n        {\n            System.out.println(\"Doing delete for key: \" + key);\n        }\n\n        Delete d = new Delete(Bytes.toBytes(key));\n        try\n        {\n            _hTable.delete(d);\n        }\n        catch (IOException e)\n        {\n            if (_debug)\n            {\n                System.err.println(\"Error doing delete: \" + e);\n            }\n            return ServerError;\n        }\n\n        return Ok;\n    }\n\n    public static void main(String[] args)\n    {\n        if (args.length != 3)\n        {\n            System.out.println(\"Please specify a threadcount, columnfamily and operation count\");\n            System.exit(0);\n        }\n\n        final int keyspace = 10000; // 120000000;\n\n        final int threadcount = Integer.parseInt(args[0]);\n\n        final String columnfamily = args[1];\n\n        final int opcount = 10;\n\n        Vector<Thread> allthreads = new Vector<Thread>();\n\n        for (int i = 0; i < threadcount; i++)\n        {\n            Thread t = new Thread()\n            {\n                public void run()\n                {\n                    try\n                    {\n                        Random random = new Random();\n\n                        HBaseV2Client cli = new HBaseV2Client();\n\n                        Properties props = new Properties();\n                        props.setProperty(\"columnfamilyOrTable\", columnfamily);\n                        props.setProperty(\"schema\", \"usertable\");\n                        // props.setProperty(\"debug\",\"true\");\n                        cli.setProperties(props);\n\n                        cli.init();\n\n                        // HashMap<String,String> result=new\n                        // HashMap<String,String>();\n\n//                        long accum = 0;\n\n                        for (int i = 0; i < opcount; i++)\n                        {\n                            int keynum = random.nextInt(keyspace);\n                            String key = \"user\" + keynum;\n//                            long st = System.currentTimeMillis();\n//                            int rescode;\n                            HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();\n                            vals.put(\"age\", new StringByteIterator(\"57\"));\n                            vals.put(\"middlename\", new StringByteIterator(\"bradley\"));\n                            vals.put(\"favoritecolor\", new StringByteIterator(\"blue\"));\n                            cli.insert(\"usertable\", key, vals);\n                        }\n                    }\n                    catch (Exception e)\n                    {\n                        e.printStackTrace();\n                    }\n                }\n            };\n            allthreads.add(t);\n        }\n\n        long st = System.currentTimeMillis();\n        for (Thread t : allthreads)\n        {\n            t.start();\n        }\n\n        for (Thread t : allthreads)\n        {\n            try\n            {\n                t.join();\n            }\n            catch (InterruptedException e)\n            {\n            }\n        }\n        long en = System.currentTimeMillis();\n\n        System.out.println(\"Throughput: \" + ((1000.0) * (((double) (opcount * threadcount)) / ((double) (en - st))))\n                + \" ops/sec\");\n\n    }\n}\n\n/*\n * For customized vim control set autoindent set si set shiftwidth=4\n */"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/HectorClient.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport me.prettyprint.cassandra.model.AllOneConsistencyLevelPolicy;\nimport me.prettyprint.cassandra.model.BasicColumnFamilyDefinition;\nimport me.prettyprint.cassandra.serializers.StringSerializer;\nimport me.prettyprint.cassandra.service.ThriftCfDef;\nimport me.prettyprint.hector.api.Cluster;\nimport me.prettyprint.hector.api.Keyspace;\nimport me.prettyprint.hector.api.beans.ColumnSlice;\nimport me.prettyprint.hector.api.ddl.ColumnFamilyDefinition;\nimport me.prettyprint.hector.api.ddl.KeyspaceDefinition;\nimport me.prettyprint.hector.api.factory.HFactory;\nimport me.prettyprint.hector.api.mutation.Mutator;\nimport me.prettyprint.hector.api.query.QueryResult;\nimport me.prettyprint.hector.api.query.SliceQuery;\n\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\nimport common.Logger;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class HectorClient extends DB\n{\n\n    private static Logger logger = Logger.getLogger(HectorClient.class);\n\n    private static Random random = new Random();\n\n    private static final int Ok = 0;\n\n    private static final int Error = -1;\n\n    private static String column_family;\n\n    private static final String COLUMN_FAMILY_PROPERTY = \"columnfamilyOrTable\";\n\n//    private static final String COLUMN_FAMILY_PROPERTY_DEFAULT = \"columnfamilyOrTable\";\n\n//    private static String _keyspace = \"kundera\";\n\n    private static Cluster cluster;\n\n    private static Keyspace keyspace;\n\n    private static String createKeyspace;\n\n    private static final String CLUSTER = \"hectorpoccluster\";\n\n//    private static final String PORT = \"9160\";\n\n    static\n    {\n        }\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public synchronized void init() throws DBException\n    {\n        if (cluster == null)\n        {\n            String hosts = getProperties().getProperty(\"hosts\");\n            if (hosts == null)\n            {\n                throw new DBException(\"Required property \\\"hosts\\\" missing for CassandraClient\");\n            }\n\n            column_family = getProperties().getProperty(COLUMN_FAMILY_PROPERTY);\n            \n            System.out.println(column_family);\n            String[] allhosts = hosts.split(\",\");\n            String myhost = allhosts[random.nextInt(allhosts.length)];\n            \n            System.out.println(myhost);\n            cluster = HFactory.getOrCreateCluster(CLUSTER, myhost + \":\" + getProperties().getProperty(\"port\"));\n            keyspace = HFactory.createKeyspace(getProperties().getProperty(\"schema\"), cluster, new AllOneConsistencyLevelPolicy());\n            if (createKeyspace == null)\n            {\n\n                // Define column family...\n                BasicColumnFamilyDefinition columnFamilyDefinition = new BasicColumnFamilyDefinition();\n                columnFamilyDefinition.setKeyspaceName(getProperties().getProperty(\"schema\"));\n                columnFamilyDefinition.setName(column_family);\n\n                ColumnFamilyDefinition cfDefStandard = new ThriftCfDef(columnFamilyDefinition);\n\n                KeyspaceDefinition keyspaceDefinition = HFactory.createKeyspaceDefinition(getProperties().getProperty(\"schema\"),\n                        \"org.apache.cassandra.locator.SimpleStrategy\", 1, Arrays.asList(cfDefStandard));\n\n                System.out.println(\"creating keyspace definition\");\n                try\n                {\n                    cluster.dropKeyspace(keyspace.getKeyspaceName());\n//                    createKeyspace = cluster.addKeyspace(keyspaceDefinition);\n//                    System.out.println(\"Added keyspace\" + keyspace.getKeyspaceName());\n//                    System.out.println(\"Added keyspace\" + column_family);\n                }\n                catch (Exception e)\n                {\n                    e.printStackTrace();\n                    logger.info(e);\n                    createKeyspace = cluster.addKeyspace(keyspaceDefinition);\n                }\n            }\n        }\n/*\n         * cluster = HFactory.getOrCreateCluster(CLUSTER, myhost + \":\" + PORT);\n         * keyspace = HFactory.createKeyspace(_keyspace, cluster, new\n         * AllOneConsistencyLevelPolicy()); if (createKeyspace == null) { //\n         * Define column family... BasicColumnFamilyDefinition\n         * columnFamilyDefinition = new BasicColumnFamilyDefinition();\n         * columnFamilyDefinition.setKeyspaceName(_keyspace);\n         * columnFamilyDefinition.setName(column_family);\n         * \n         * ColumnFamilyDefinition cfDefStandard = new ThriftCfDef(\n         * columnFamilyDefinition);\n         * \n         * KeyspaceDefinition keyspaceDefinition = HFactory\n         * .createKeyspaceDefinition(_keyspace,\n         * \"org.apache.cassandra.locator.SimpleStrategy\", 1,\n         * Arrays.asList(cfDefStandard)); try { createKeyspace =\n         * cluster.addKeyspace(keyspaceDefinition); } catch (Exception e) {\n         * createKeyspace = cluster.addKeyspace(keyspaceDefinition);\n         * logger.error(e); } }\n         */\n    }\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n//        HFactory.shutdownCluster(cluster);\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        try\n        {\n            QueryResult<ColumnSlice<String, String>> queryResult;\n            SliceQuery<String, String, String> sliceQuery = HFactory.createSliceQuery(keyspace, StringSerializer.get(),\n                    StringSerializer.get(), StringSerializer.get());\n\n            sliceQuery.setKey(key);\n            sliceQuery.setColumnFamily(column_family);\n            if (fields != null)\n            {\n                sliceQuery.setColumnNames(fields.toArray(new String[] {}));\n            }\n            else\n            {\n                sliceQuery.setRange(new String(new byte[0]), new String(new byte[0]), false, Integer.MAX_VALUE);\n            }\n            queryResult = sliceQuery.execute();\n            assert queryResult.get() != null;\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        return Error;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write.\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return Error;\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        try\n        {\n            Mutator<String> mutator = HFactory.createMutator(keyspace, StringSerializer.get());\n\n            for (Map.Entry<String, ByteIterator> entry : values.entrySet())\n            {\n                mutator.addInsertion(key, column_family,\n                        HFactory.createStringColumn(entry.getKey(), entry.getValue().toString()));\n            }\n            mutator.execute();\n\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            e.printStackTrace();\n            logger.error(e);\n            return Error;\n        } finally\n        {\n            values.clear();\n            values=null;\n            values = new HashMap<String, ByteIterator>();\n        }\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        Mutator<String> mutator = HFactory.createMutator(keyspace, StringSerializer.get());\n        mutator.addDeletion(key, column_family);\n        mutator.execute();\n        return Ok;\n    }\n\n    public static void main(String[] args)\n    {\n        HectorClient cli = new HectorClient();\n\n        Properties props = new Properties();\n\n        props.setProperty(\"hosts\", \"localhost\");\n        cli.setProperties(props);\n\n        try\n        {\n            cli.init();\n        }\n        catch (Exception e)\n        {\n            e.printStackTrace();\n            System.exit(0);\n        }\n\n        HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();\n        vals.put(\"age\", new StringByteIterator(\"57\"));\n        vals.put(\"middlename\", new StringByteIterator(\"bradley\"));\n        vals.put(\"favoritecolor\", new StringByteIterator(\"blue\"));\n        int res = cli.insert(\"usertable\", \"BrianFrankCooper\", vals);\n        System.out.println(\"Result of insert: \" + res);\n\n        HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();\n        HashSet<String> fields = new HashSet<String>();\n        fields.add(\"middlename\");\n        fields.add(\"age\");\n        fields.add(\"favoritecolor\");\n        res = cli.read(\"usertable\", \"BrianFrankCooper\", null, result);\n        System.out.println(\"Result of read: \" + res);\n        for (String s : result.keySet())\n        {\n            System.out.println(\"[\" + s + \"]=[\" + result.get(s) + \"]\");\n        }\n\n//        res = cli.delete(\"usertable\", \"BrianFrankCooper\");\n        System.out.println(\"Result of delete: \" + res);\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/KuduYCSBClient.java",
    "content": "package com.impetus.kundera.ycsb.benchmark;\n\nimport static com.yahoo.ycsb.workloads.CoreWorkload.TABLENAME_PROPERTY;\nimport static com.yahoo.ycsb.workloads.CoreWorkload.TABLENAME_PROPERTY_DEFAULT;\nimport static org.apache.kudu.Type.STRING;\nimport static org.apache.kudu.client.KuduPredicate.ComparisonOp.EQUAL;\nimport static org.apache.kudu.client.KuduPredicate.ComparisonOp.GREATER_EQUAL;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport org.apache.kudu.ColumnSchema;\nimport org.apache.kudu.Schema;\nimport org.apache.kudu.client.CreateTableOptions;\nimport org.apache.kudu.client.Delete;\nimport org.apache.kudu.client.Insert;\nimport org.apache.kudu.client.KuduClient;\nimport org.apache.kudu.client.KuduException;\nimport org.apache.kudu.client.KuduPredicate;\nimport org.apache.kudu.client.KuduScanner;\nimport org.apache.kudu.client.KuduSession;\nimport org.apache.kudu.client.KuduTable;\nimport org.apache.kudu.client.Operation;\nimport org.apache.kudu.client.OperationResponse;\nimport org.apache.kudu.client.PartialRow;\nimport org.apache.kudu.client.RowResult;\nimport org.apache.kudu.client.RowResultIterator;\nimport org.apache.kudu.client.Update;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.stumbleupon.async.TimeoutException;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\nimport com.yahoo.ycsb.workloads.CoreWorkload;\n\npublic class KuduYCSBClient extends com.yahoo.ycsb.DB\n{\n    private static final Logger LOG = LoggerFactory.getLogger(KuduYCSBClient.class);\n\n    private static final String KEY = \"key\";\n\n    private static final int MAX_TABLETS = 9000;\n\n    private static final long DEFAULT_SLEEP = 60000;\n\n    private static final String SYNC_OPS_OPT = \"kudu_sync_ops\";\n\n    private static final String PRE_SPLIT_NUM_TABLETS_OPT = \"kudu_pre_split_num_tablets\";\n\n    private static final String TABLE_NUM_REPLICAS = \"kudu_table_num_replicas\";\n\n    private static final String BLOCK_SIZE_OPT = \"kudu_block_size\";\n\n    private static final String MASTER_ADDRESSES_OPT = \"kudu_master_addresses\";\n\n    private static final int BLOCK_SIZE_DEFAULT = 4096;\n\n    private static final List<String> COLUMN_NAMES = new ArrayList<>();\n\n    private static KuduClient client;\n\n    private static Schema schema;\n\n    private KuduSession session;\n\n    private KuduTable kuduTable;\n\n    @Override\n    public void init() throws DBException\n    {\n        String tableName = getProperties().getProperty(TABLENAME_PROPERTY, TABLENAME_PROPERTY_DEFAULT);\n        initClient(tableName, getProperties());\n        this.session = client.newSession();\n        if (getProperties().getProperty(SYNC_OPS_OPT) != null\n                && getProperties().getProperty(SYNC_OPS_OPT).equals(\"false\"))\n        {\n            this.session.setFlushMode(KuduSession.FlushMode.AUTO_FLUSH_BACKGROUND);\n            this.session.setMutationBufferSpace(100);\n        }\n        else\n        {\n            this.session.setFlushMode(KuduSession.FlushMode.AUTO_FLUSH_SYNC);\n        }\n        try\n        {\n            this.kuduTable = client.openTable(tableName);\n        }\n        catch (Exception e)\n        {\n            throw new DBException(\"Could not open a table because of:\", e);\n        }\n    }\n\n    private static synchronized void initClient(String tableName, Properties prop) throws DBException\n    {\n        if (client != null)\n        {\n            return;\n        }\n        String masterAddresses = prop.getProperty(MASTER_ADDRESSES_OPT);\n        if (masterAddresses == null)\n        {\n            masterAddresses = \"quickstart.cloudera:7051\";\n        }\n        int numTablets = getIntFromProp(prop, PRE_SPLIT_NUM_TABLETS_OPT, 4);\n        if (numTablets > MAX_TABLETS)\n        {\n            throw new DBException(String.format(\"Specified number of tablets (%s) must be equal or below %s\",\n                    numTablets, MAX_TABLETS));\n        }\n        int numReplicas = getIntFromProp(prop, TABLE_NUM_REPLICAS, 3);\n        int blockSize = getIntFromProp(prop, BLOCK_SIZE_OPT, BLOCK_SIZE_DEFAULT);\n        client = new KuduClient.KuduClientBuilder(masterAddresses).defaultSocketReadTimeoutMs(DEFAULT_SLEEP)\n                .defaultOperationTimeoutMs(DEFAULT_SLEEP).defaultAdminOperationTimeoutMs(DEFAULT_SLEEP).build();\n        LOG.debug(\"Connecting to the masters at {}\", masterAddresses);\n        int fieldCount = getIntFromProp(prop, CoreWorkload.FIELD_COUNT_PROPERTY,\n                Integer.parseInt(CoreWorkload.FIELD_COUNT_PROPERTY_DEFAULT));\n        List<ColumnSchema> columns = new ArrayList<>(fieldCount + 1);\n        ColumnSchema keyColumn = new ColumnSchema.ColumnSchemaBuilder(KEY, STRING).key(true)\n                .desiredBlockSize(blockSize).build();\n        columns.add(keyColumn);\n        COLUMN_NAMES.add(KEY);\n        for (int i = 0; i < fieldCount; i++)\n        {\n            String name = \"field\" + i;\n            COLUMN_NAMES.add(name);\n            columns.add(new ColumnSchema.ColumnSchemaBuilder(name, STRING).desiredBlockSize(blockSize).build());\n        }\n        schema = new Schema(columns);\n        CreateTableOptions builder = new CreateTableOptions();\n        builder.setRangePartitionColumns(new ArrayList<String>());\n        List<String> hashPartitionColumns = new ArrayList<>();\n        hashPartitionColumns.add(KEY);\n        builder.addHashPartitions(hashPartitionColumns, numTablets);\n        builder.setNumReplicas(numReplicas);\n        try\n        {\n            client.createTable(tableName, schema, builder);\n        }\n        catch (Exception e)\n        {\n            if (!e.getMessage().contains(\"already exists\"))\n            {\n                throw new DBException(\"Couldn't create the table\", e);\n            }\n        }\n    }\n\n    private static int getIntFromProp(Properties prop, String propName, int defaultValue) throws DBException\n    {\n        String intStr = prop.getProperty(propName);\n        if (intStr == null)\n        {\n            return defaultValue;\n        }\n        else\n        {\n            try\n            {\n                return Integer.valueOf(intStr);\n            }\n            catch (NumberFormatException ex)\n            {\n                throw new DBException(\"Provided number for \" + propName + \" isn't a valid integer\");\n            }\n        }\n    }\n\n    @Override\n    public void cleanup() throws DBException\n    {\n        try\n        {\n            this.session.close();\n        }\n        catch (Exception e)\n        {\n            throw new DBException(\"Couldn't cleanup the session\", e);\n        }\n    }\n\n    @Override\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        Vector<HashMap<String, ByteIterator>> results = new Vector<>();\n        final int status = scan(table, key, 1, fields, results);\n        if (status != 1)\n        {\n            return status;\n        }\n        if (results.size() != 1)\n        {\n            return 0;\n        }\n        result.putAll(results.firstElement());\n        return 1;\n    }\n\n    @Override\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        try\n        {\n            KuduScanner.KuduScannerBuilder scannerBuilder = client.newScannerBuilder(kuduTable);\n            List<String> querySchema;\n            if (fields == null)\n            {\n                querySchema = COLUMN_NAMES;\n                // No need to set the projected columns with the whole schema.\n            }\n            else\n            {\n                querySchema = new ArrayList<>(fields);\n                scannerBuilder.setProjectedColumnNames(querySchema);\n            }\n            ColumnSchema column = schema.getColumnByIndex(0);\n            KuduPredicate.ComparisonOp predicateOp = recordcount == 1 ? EQUAL : GREATER_EQUAL;\n            KuduPredicate predicate = KuduPredicate.newComparisonPredicate(column, predicateOp, startkey);\n            scannerBuilder.addPredicate(predicate);\n            scannerBuilder.limit(recordcount); // currently noop\n            KuduScanner scanner = scannerBuilder.build();\n            while (scanner.hasMoreRows())\n            {\n                RowResultIterator data = scanner.nextRows();\n                addAllRowsToResult(data, recordcount, querySchema, result);\n                if (recordcount == result.size())\n                {\n                    break;\n                }\n            }\n            RowResultIterator closer = scanner.close();\n            addAllRowsToResult(closer, recordcount, querySchema, result);\n        }\n        catch (TimeoutException te)\n        {\n            LOG.info(\"Waited too long for a scan operation with start key={}\", startkey);\n            return -1;\n        }\n        catch (Exception e)\n        {\n            LOG.warn(\"Unexpected exception\", e);\n            return 0;\n        }\n        return 1;\n    }\n\n    private void addAllRowsToResult(RowResultIterator it, int recordcount, List<String> querySchema,\n            Vector<HashMap<String, ByteIterator>> result) throws Exception\n    {\n        RowResult row;\n        HashMap<String, ByteIterator> rowResult = new HashMap<>(querySchema.size());\n        if (it == null)\n        {\n            return;\n        }\n        while (it.hasNext())\n        {\n            if (result.size() == recordcount)\n            {\n                return;\n            }\n            row = it.next();\n            int colIdx = 0;\n            for (String col : querySchema)\n            {\n                rowResult.put(col, new StringByteIterator(row.getString(colIdx)));\n                colIdx++;\n            }\n            result.add(rowResult);\n        }\n    }\n\n    @Override\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        Update update = this.kuduTable.newUpdate();\n        PartialRow row = update.getRow();\n        row.addString(KEY, key);\n        for (int i = 1; i < schema.getColumnCount(); i++)\n        {\n            String columnName = schema.getColumnByIndex(i).getName();\n            if (values.containsKey(columnName))\n            {\n                String value = values.get(columnName).toString();\n                row.addString(columnName, value);\n            }\n        }\n        apply(update);\n        return 1;\n    }\n\n    @Override\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        Insert insert = this.kuduTable.newInsert();\n        PartialRow row = insert.getRow();\n        row.addString(KEY, key);\n        for (int i = 1; i < schema.getColumnCount(); i++)\n        {\n            row.addString(i, values.get(schema.getColumnByIndex(i).getName()).toString());\n        }\n        apply(insert);\n        return 1;\n    }\n\n    @Override\n    public int delete(String table, String key)\n    {\n        Delete delete = this.kuduTable.newDelete();\n        PartialRow row = delete.getRow();\n        row.addString(KEY, key);\n        apply(delete);\n        return 1;\n    }\n\n    private void apply(Operation op)\n    {\n        try\n        {\n            OperationResponse response = session.apply(op);\n            if (response != null && response.hasRowError())\n            {\n                LOG.info(\"Write operation failed: {}\", response.getRowError());\n            }\n        }\n        catch (KuduException ex)\n        {\n            LOG.warn(\"Write operation failed\", ex);\n        }\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/KunderaCouchDBClient.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Properties;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport com.impetus.kundera.ycsb.entities.CouchDBUser;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\nimport common.Logger;\n\n/**\n * @author Vivek mishra\n * \n */\npublic class KunderaCouchDBClient extends DB\n{\n    private static Logger logger = Logger.getLogger(KunderaCouchDBClient.class);\n\n    static Random random = new Random();\n\n    private static final int Ok = 0;\n\n    private static final int Error = -1;\n\n    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"kundera_couchdb_pu\");\n\n    private EntityManager em;\n\n    private int j;\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {\n        em = emf.createEntityManager();\n        j = 1;\n    }\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n//        em.close();\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        /*if (em == null || !em.isOpen())\n        {\n            em = emf.createEntityManager();\n        }*/\n        try\n        {\n            Object o = em.find(CouchDBUser.class, key);\n            assert o != null;\n            j++;\n//            if (j % 5000 == 0)\n//            {\n                em.clear();\n//            }\n//            em.clear();\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        return Ok;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write.\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return insert(table, key, values);\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        if (em == null || !em.isOpen())\n        {\n            em = emf.createEntityManager();\n        }\n\n        try\n        {\n            CouchDBUser u = new CouchDBUser(key, getString(key, \"24\"), getString(key, \"gzb\"), getString(key, \"mishra\"));\n            em.persist(u);\n           j++;\n            if (j % 5000 == 0)\n            {\n                em.clear();\n             }\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n\t    return Error;\n        }\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        try\n        {\n            em.remove(em.find(CouchDBUser.class, key));\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    private String getString(String key, String value)\n    {\n        StringBuilder builder = new StringBuilder(key);\n        builder.append(value);\n        return builder.toString();\n    }\n\n    public static void main(String[] args)\n    {\n        KunderaCouchDBClient cli = new KunderaCouchDBClient();\n\n        Properties props = new Properties();\n\n        props.setProperty(\"hosts\", \"localhost\");\n        cli.setProperties(props);\n\n        try\n        {\n            cli.init();\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            System.exit(0);\n        }\n\n        HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();\n        vals.put(\"age\", new StringByteIterator(\"57\"));\n        vals.put(\"middlename\", new StringByteIterator(\"bradley\"));\n        vals.put(\"favoritecolor\", new StringByteIterator(\"blue\"));\n        int res = cli.insert(\"usertable\", \"BrianFrankCooper\", vals);\n        System.out.println(\"Result of insert: \" + res);\n\n        HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();\n        HashSet<String> fields = new HashSet<String>();\n        fields.add(\"middlename\");\n        fields.add(\"age\");\n        fields.add(\"favoritecolor\");\n        res = cli.read(\"usertable\", \"BrianFrankCooper\", null, result);\n        System.out.println(\"Result of read: \" + res);\n        for (String s : result.keySet())\n        {\n            System.out.println(\"[\" + s + \"]=[\" + result.get(s) + \"]\");\n        }\n\n//        res = cli.delete(\"usertable\", \"BrianFrankCooper\");\n        System.out.println(\"Result of delete: \" + res);\n\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/KunderaHBaseClient.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Properties;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\n\nimport com.impetus.kundera.ycsb.entities.HBaseUser;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\n\nimport common.Logger;\n\n/**\n * @author Vivek mishra\n * \n */\npublic class KunderaHBaseClient extends DB\n{\n    private static Logger logger = Logger.getLogger(KunderaHBaseClient.class);\n\n    static Random random = new Random();\n\n    private static final int Ok = 0;\n\n    private static final int Error = -1;\n\n    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"kundera_hbase_pu\");\n\n    private EntityManager em;\n\n    private int j;\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {\n        em = emf.createEntityManager();\n        j = 1;\n    }\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n        em.clear();\n//        em.close();\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        /*if (em == null || !em.isOpen())\n        {\n            em = emf.createEntityManager();\n        }*/\n        try\n        {\n            Query qry = em.createQuery(\"select h from HBaseUser h where h.name = :key\");\n            qry.setParameter(\"key\", key);\n            Object o = em.find(HBaseUser.class, key);\n            assert o != null;\n            /*j++;\n            if (j % 5000 == 0)\n            {\n                em.clear();\n            }*/\n            em.clear();\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        return Ok;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write.\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return insert(table, key, values);\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n/*        if (em == null || !em.isOpen())\n        {\n            em = emf.createEntityManager();\n        }\n*/\n        try\n        {\n            HBaseUser u = new HBaseUser(key, getString(key, \"24\"), getString(key, \"gzb\"), getString(key, \"mishra\"));\n            em.persist(u);\n           j++;\n            if (j % 5000 == 0)\n            {\n                em.clear();\n             }\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n\t    return Error;\n        }\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        try\n        {\n            em.remove(em.find(HBaseUser.class, key));\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    private String getString(String key, String value)\n    {\n        StringBuilder builder = new StringBuilder(key);\n        builder.append(value);\n        return builder.toString();\n    }\n\n    public static void main(String[] args)\n    {\n        KunderaHBaseClient cli = new KunderaHBaseClient();\n\n        Properties props = new Properties();\n\n        props.setProperty(\"hosts\", \"localhost\");\n        cli.setProperties(props);\n\n        try\n        {\n            cli.init();\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            System.exit(0);\n        }\n\n        HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();\n        vals.put(\"age\", new StringByteIterator(\"57\"));\n        vals.put(\"middlename\", new StringByteIterator(\"bradley\"));\n        vals.put(\"favoritecolor\", new StringByteIterator(\"blue\"));\n        int res = cli.insert(\"usertable\", \"BrianFrankCooper\", vals);\n        System.out.println(\"Result of insert: \" + res);\n\n        HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();\n        HashSet<String> fields = new HashSet<String>();\n        fields.add(\"middlename\");\n        fields.add(\"age\");\n        fields.add(\"favoritecolor\");\n        res = cli.read(\"usertable\", \"BrianFrankCooper\", null, result);\n        System.out.println(\"Result of read: \" + res);\n        for (String s : result.keySet())\n        {\n            System.out.println(\"[\" + s + \"]=[\" + result.get(s) + \"]\");\n        }\n\n//        res = cli.delete(\"usertable\", \"BrianFrankCooper\");\n        System.out.println(\"Result of delete: \" + res);\n\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/KunderaKuduDBClient.java",
    "content": "/**\n * Copyright 2017 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.ycsb.entities.KuduUser;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport common.Logger;\n\npublic class KunderaKuduDBClient extends DB\n{\n\n    private static Logger logger = Logger.getLogger(KunderaKuduDBClient.class);\n\n    static Random random = new Random();\n\n    private static final int Ok = 0;\n\n    private static final int Error = -1;\n\n    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"kundera_kudu_pu\");\n\n    private EntityManager em;\n\n    private int j;\n\n    private Client client;\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {\n        // emf\n        em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n\n        client = clients.get(\"kundera_kudu_pu\");\n        j = 1;\n\n    }\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n        em.clear();\n        em.close();\n        // emf.close();\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        try\n        {\n            // em.clear();\n\n            final Object o = em.find(KuduUser.class, key);\n\n            assert o != null;\n            // em.clear();\n            j++;\n            if (j % 5000 == 0)\n            {\n                em.clear();\n            }\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        return Ok;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write.\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return insert(table, key, values);\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        try\n        {\n            final KuduUser u = new KuduUser(key, getString(key, \"24\"), getString(key, \"gzb\"), getString(key, \"mishra\"));\n            em.persist(u);\n            j++;\n            if (j % 5000 == 0)\n            {\n                em.clear();\n            }\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        try\n        {\n            em.remove(em.find(KuduUser.class, key));\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    private String getString(String key, String value)\n    {\n        StringBuilder builder = new StringBuilder(key);\n        builder.append(value);\n        return builder.toString();\n    }\n\n    public static void main(String[] args) throws DBException\n    {\n        KunderaKuduDBClient client = new KunderaKuduDBClient();\n        client.init();\n        client.insert(\"user\", \"1\", null);\n        client.read(\"user\", \"1\", null, null);\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/KunderaMongoClient.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.ycsb.entities.MongoUser;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport common.Logger;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class KunderaMongoClient extends DB\n{\n\n    private static Logger logger = Logger.getLogger(KunderaMongoClient.class);\n\n    static Random random = new Random();\n\n    private static final int Ok = 0;\n\n    private static final int Error = -1;\n\n    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"kundera_mongo_pu\");\n\n    private EntityManager em;\n\n    private int j;\n    \n    private Client client;\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {\n//        emf \n        em = emf.createEntityManager();\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        \n        client = clients.get(\"kundera_mongo_pu\");\n        j = 1;\n\n    }\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n        em.clear();\n        em.close();\n        // emf.close();\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        try\n        {\n         //   em.clear();\n            \n            final Object o = em.find(MongoUser.class, key);\n            \n            assert o != null;\n//            em.clear();\n            j++;\n            if (j % 5000 == 0)\n            {\n                em.clear();\n            }\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        return Ok;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write.\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return insert(table, key, values);\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        try\n        {\n            final MongoUser u = new MongoUser(key, getString(key, \"24\"), getString(key, \"gzb\"),\n                    getString(key, \"mishra\"));\n            em.persist(u);\n            j++;\n            if (j % 5000 == 0)\n            {\n                em.clear();\n            }\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        try\n        {\n            em.remove(em.find(MongoUser.class, key));\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    private String getString(String key, String value)\n    {\n        StringBuilder builder = new StringBuilder(key);\n        builder.append(value);\n        return builder.toString();\n    }\n\n\n    public static void main(String[] args) throws DBException\n    {\n        KunderaMongoClient client = new KunderaMongoClient();\n        client.init();\n        client.insert(\"user\", \"1\", null);\n        client.read(\"user\", \"1\", null, null);\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/KunderaNeo4JClient.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport com.impetus.kundera.ycsb.entities.Neo4JUser;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport common.Logger;\n\n/**\n * Kundera Neo4J Client for YCSB Framework\n * @author Amresh Singh\n * \n */\npublic class KunderaNeo4JClient extends DB\n{\n\n    private static Logger logger = Logger.getLogger(KunderaNeo4JClient.class);\n\n    static Random random = new Random();\n\n    private static final int Ok = 0;\n\n    private static final int Error = -1;\n\n    static Map<String, String> config = new HashMap<String, String>(); \n    \n    static\n    {\n        config.put(\"node_auto_indexing\", \"true\");\n        config.put(\"node_keys_indexable\", \"USER_ID\");\n    }           \n    \n    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"kundera_neo4j_pu\", config);\n    private EntityManager em = emf.createEntityManager();\n    \n\n    private int j;\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {       \n        em.getTransaction().begin();\n        j = 1;   \n        \n    }\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n        em.getTransaction().commit();\n        em.clear();\n        em.close();\n        //emf.close();\n    }\n    \n    \n    \n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        try\n        {\n            final Neo4JUser u = new Neo4JUser(key, getString(key, \"Amresh\"), getString(key, \"31\"),\n                    getString(key, \"New Street\"));\n            \n            em.persist(u);\n            \n            j++;\n            if (j % 1000 == 0)\n            {\n                em.getTransaction().commit();\n                em.clear();\n                em.getTransaction().begin();\n            }\n            return Ok;\n        }\n        catch (Exception e)\n        {\n\t\te.printStackTrace();\n//            logger.error(e);\n            //em.getTransaction().rollback();\n            return Error;\n        }\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        try\n        {\n//            em.clear();\n            final Object o = em.find(Neo4JUser.class, key);\n            assert o != null;\n            j++;\n            if (j % 5000 == 0)\n            {\n                em.clear();\n            }\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        return Ok;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write.\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return insert(table, key, values);\n    }\n\n    \n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        try\n        {\n            em.remove(em.find(Neo4JUser.class, key));\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    private String getString(String key, String value)\n    {\n        StringBuilder builder = new StringBuilder(key);\n        builder.append(value);\n        return builder.toString();\n    }\n    \n    \n    public static void main(String[] args)\n    {\n        try\n        {\n            new KunderaNeo4JClient().init();\n        }\n        catch (DBException e)\n        {\n            e.printStackTrace();\n        }\n        \n        new KunderaNeo4JClient().insert(\"USER\", \"1\", new HashMap());\n        \n        System.out.println(new KunderaNeo4JClient().read(\"USER\", \"1\", null, null));\n        \n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/KunderaOracleNosqlClient.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Properties;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport com.impetus.kundera.ycsb.entities.OracleNosqlUser;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\nimport common.Logger;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class KunderaOracleNosqlClient extends DB\n{\n    private static Logger logger = Logger.getLogger(KunderaOracleNosqlClient.class);\n\n    static Random random = new Random();\n\n    private static final int Ok = 0;\n\n    private static final int Error = -1;\n\n    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"kundera_oracle_pu\");\n\n    private EntityManager em;\n\n    private int j;\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {\n        em = emf.createEntityManager();\n        j = 1;\n    }\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n        em.clear();\n        em.close();\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        if (em == null || !em.isOpen())\n        {\n            em = emf.createEntityManager();\n        }\n        try\n        {\n            Object o = em.find(OracleNosqlUser.class, key);\n            assert o != null;\n            j++;\n            if (j % 5000 == 0)\n            {\n                em.clear();\n            }\n            // em.clear();\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        return Ok;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write.\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return insert(table, key, values);\n        // return Error;\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        if (em == null || !em.isOpen())\n        {\n            em = emf.createEntityManager();\n        }\n\n        try\n        {\n            OracleNosqlUser u = new OracleNosqlUser(key, getString(key, \"24\"), getString(key, \"gzb\"), getString(key,\n                    \"mishra\"));\n            em.persist(u);\n            j++;\n            if (j % 5000 == 0)\n            {\n                em.clear();\n            }\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        try\n        {\n            em.remove(em.find(OracleNosqlUser.class, key));\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    private String getString(String key, String value)\n    {\n        StringBuilder builder = new StringBuilder(key);\n        builder.append(value);\n        return builder.toString();\n    }\n\n    public static void main(String[] args)\n    {\n        KunderaOracleNosqlClient cli = new KunderaOracleNosqlClient();\n\n        Properties props = new Properties();\n\n        props.setProperty(\"helperHost\", \"localhost:5000\");\n        cli.setProperties(props);\n\n        try\n        {\n            cli.init();\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            System.exit(0);\n        }\n\n        HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();\n        vals.put(\"age\", new StringByteIterator(\"57\"));\n        vals.put(\"middlename\", new StringByteIterator(\"bradley\"));\n        vals.put(\"favoritecolor\", new StringByteIterator(\"blue\"));\n        int res = cli.insert(\"usertable\", \"BrianFrankCooper\", vals);\n        System.out.println(\"Result of insert: \" + res);\n\n        HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();\n        HashSet<String> fields = new HashSet<String>();\n        fields.add(\"middlename\");\n        fields.add(\"age\");\n        fields.add(\"favoritecolor\");\n        res = cli.read(\"usertable\", \"BrianFrankCooper\", null, result);\n        System.out.println(\"Result of read: \" + res);\n        for (String s : result.keySet())\n        {\n            System.out.println(\"[\" + s + \"]=[\" + result.get(s) + \"]\");\n        }\n\n        res = cli.delete(\"usertable\", \"BrianFrankCooper\");\n        System.out.println(\"Result of delete: \" + res);\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/KunderaPelopsClient.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.HashMap;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport com.impetus.kundera.ycsb.entities.PelopsUser;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport common.Logger;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class KunderaPelopsClient extends DB\n{\n\n    private static Logger logger = Logger.getLogger(KunderaPelopsClient.class);\n\n//    static Random random = new Random();\n\n    private static final int Ok = 0;\n\n    private static final int Error = -1;\n\n    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"kundera_pelops_pu\");\n\n    private EntityManager em;\n\n    private int j;\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {\n        em = emf.createEntityManager();\n        j = 1;\n    }\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n        em.clear();\n//        em.close();\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        try\n        {\n            Object o = em.find(PelopsUser.class, key);\n            assert o != null;\n            j++;\n            em.clear();\n//            if (j % 5000 == 0)\n//            {\n//                em.clear();\n//             }\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        return Ok;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write.\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return insert(table, key, values);\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        try\n        {\n            PelopsUser u = new PelopsUser(key, getString(key, \"24\"), getString(key, \"gzb\"), getString(key, \"mishra\"));\n            em.persist(u);\n//            j++;\n//            if (j % 5000 == 0)\n//            {\n                em.clear();\n//             }\n            \n                return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        try\n        {\n            em.remove(em.find(PelopsUser.class, key));\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    private String getString(String key, String value)\n    {\n        StringBuilder builder = new StringBuilder(key);\n        builder.append(value);\n        return builder.toString();\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/KunderaRedisClient.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport com.impetus.kundera.client.Client;\nimport com.impetus.kundera.ycsb.entities.RedisUser;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\nimport common.Logger;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class KunderaRedisClient extends DB\n{\n\n    private static Logger logger = Logger.getLogger(KunderaRedisClient.class);\n\n    static Random random = new Random();\n\n    private static final int Ok = 0;\n\n    private static final int Error = -1;\n\n    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"kundera_redis_pu\");\n\n    private EntityManager em;\n\n    private int j;\n\n    private Client client;\n\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {\n        //emf \n \n        em = emf.createEntityManager();\n\n        Map<String, Client> clients = (Map<String, Client>) em.getDelegate();\n        \n        client = clients.get(\"kundera_redis_pu\");\n        j = 1;\n     //    System.out.println(\"initialized\");\n\n    }\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n//        System.out.println(em);\n        em.clear(); \n        em.close();\n       // emf.close();\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        try\n        {\n           // em.clear();\n            \n//            Object o = client.find(RedisUser.class, key);\n            \n            Object o = em.find(RedisUser.class, key);\n//            System.out.println(o);\n            assert o != null;\n            j++;\n            if (j % 5000 == 0)\n            {\n                em.clear();\n            }\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n//        return Ok;\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        return Ok;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write.\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return insert(table, key, values);\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        try\n        {\n            final RedisUser u = new RedisUser(key, getString(key, \"24\"), getString(key, \"gzb\"),\n                    getString(key, \"mishra\"));\n          // System.out.println(\"persist\" + key );\n            em.persist(u);\n//            em.clear();\n\t//\t System.out.println( j );\n\n            j++;\n            if (j % 5000 == 0)\n            {\n//\t\tem.flush();\n                em.clear();\n                j = 0;\n            } \n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        try\n        {\n            em.remove(em.find(RedisUser.class, key));\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    private String getString(String key, String value)\n    {\n        StringBuilder builder = new StringBuilder(key);\n        builder.append(value);\n        return builder.toString();\n    }\n\n    public static void main(String[] args)\n    {\n\n        Runnable t = new Runnable()\n        {\n\n            @Override\n            public void run()\n            {\n\n                KunderaRedisClient cli = new KunderaRedisClient();\n\n                Properties props = new Properties();\n\n                props.setProperty(\"hosts\", \"localhost\");\n                cli.setProperties(props);\n\n                try\n                {\n                    cli.init();\n                }\n                catch (Exception e)\n                {\n                    logger.error(e);\n                    System.exit(0);\n                }\n\n                HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();\n                vals.put(\"age\", new StringByteIterator(\"57\"));\n                vals.put(\"middlename\", new StringByteIterator(\"bradley\"));\n                vals.put(\"favoritecolor\", new StringByteIterator(\"blue\"));\n                int res = cli.insert(\"usertable\", \"BrianFrankCooper\", vals);\n                \n                cli.read(\"usertable\", \"BrianFrankCooper\", null, null);\n                System.out.println(\"Result of insert: \" + res);\n                try\n                {\n                    cli.cleanup();\n                }\n                catch (DBException e)\n                {\n                    // TODO Auto-generated catch block\n                    e.printStackTrace();\n                }\n\n            }\n\n        };\n        for (int i = 0; i < 100; i++)\n        {\n            t.run();\n        }\n\n        /*\n         * HashMap<String, ByteIterator> result = new HashMap<String,\n         * ByteIterator>(); HashSet<String> fields = new HashSet<String>();\n         * fields.add(\"middlename\"); fields.add(\"age\");\n         * fields.add(\"favoritecolor\"); res = cli.read(\"usertable\",\n         * \"BrianFrankCooper\", null, result);\n         * System.out.println(\"Result of read: \" + res); for (String s :\n         * result.keySet()) { System.out.println(\"[\" + s + \"]=[\" + result.get(s)\n         * + \"]\"); }\n         * \n         * res = cli.delete(\"usertable\", \"BrianFrankCooper\");\n         * System.out.println(\"Result of delete: \" + res);\n         */}\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/KunderaThriftClient.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Properties;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\nimport com.impetus.kundera.ycsb.entities.ThriftUser;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\nimport common.Logger;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class KunderaThriftClient extends DB\n{\n    private static Logger logger = Logger.getLogger(KunderaThriftClient.class);\n\n    static Random random = new Random();\n\n    private static final int Ok = 0;\n\n    private static final int Error = -1;\n\n    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory(\"kundera_thrift_pu\");\n\n    private EntityManager em;\n\n    private int j;\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {\n        em = emf.createEntityManager();\n        j = 1;\n    }\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n        em.clear();\n//        em.close();.\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        if (em == null || !em.isOpen())\n        {\n            em = emf.createEntityManager();\n        }\n        try\n        {\n            Object o = em.find(ThriftUser.class, key);\n            assert o != null;\n           /* j++;\n            if (j % 5000 == 0)\n            {*/\n                em.clear();\n//             }\n//            em.clear();\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        return Ok;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write.\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return insert(table, key, values);\n//        return Error;\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        if (em == null || !em.isOpen())\n        {\n            em = emf.createEntityManager();\n        }\n\n        try\n        {\n            ThriftUser u = new ThriftUser(key, getString(key, \"24\"), getString(key, \"gzb\"), getString(key, \"mishra\"));\n            em.persist(u);\n           /*j++;\n            if (j % 5000 == 0)\n            {*/\n                em.clear();\n//             }\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n\t    return Error;\n        }\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        try\n        {\n            em.remove(em.find(ThriftUser.class, key));\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    private String getString(String key, String value)\n    {\n        StringBuilder builder = new StringBuilder(key);\n        builder.append(value);\n        return builder.toString();\n    }\n\n    public static void main(String[] args)\n    {\n        KunderaThriftClient cli = new KunderaThriftClient();\n\n        Properties props = new Properties();\n\n        props.setProperty(\"hosts\", \"localhost\");\n        cli.setProperties(props);\n\n        try\n        {\n            cli.init();\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            System.exit(0);\n        }\n\n        HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();\n        vals.put(\"age\", new StringByteIterator(\"57\"));\n        vals.put(\"middlename\", new StringByteIterator(\"bradley\"));\n        vals.put(\"favoritecolor\", new StringByteIterator(\"blue\"));\n        int res = cli.insert(\"usertable\", \"BrianFrankCooper\", vals);\n        System.out.println(\"Result of insert: \" + res);\n\n        HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();\n        HashSet<String> fields = new HashSet<String>();\n        fields.add(\"middlename\");\n        fields.add(\"age\");\n        fields.add(\"favoritecolor\");\n        res = cli.read(\"usertable\", \"BrianFrankCooper\", null, result);\n        System.out.println(\"Result of read: \" + res);\n        for (String s : result.keySet())\n        {\n            System.out.println(\"[\" + s + \"]=[\" + result.get(s) + \"]\");\n        }\n\n        res = cli.delete(\"usertable\", \"BrianFrankCooper\");\n        System.out.println(\"Result of delete: \" + res);\n\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/MongoDbClient.java",
    "content": "/**\n * MongoDB client binding for YCSB.\n *\n * Submitted by Yen Pai on 5/11/2010.\n *\n * https://gist.github.com/000a66b8db2caf42467b#file_mongo_db.java\n *\n */\n\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport com.mongodb.BasicDBObject;\nimport com.mongodb.DBAddress;\nimport com.mongodb.DBCollection;\nimport com.mongodb.DBCursor;\nimport com.mongodb.DBObject;\nimport com.mongodb.Mongo;\nimport com.mongodb.WriteConcern;\nimport com.mongodb.WriteResult;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\n\n/**\n * MongoDB client for YCSB framework.\n * \n * Properties to set:\n * \n * mongodb.url=mongodb://localhost:27017 mongodb.database=ycsb\n * mongodb.writeConcern=normal\n * \n * @author ypai\n * \n */\npublic class MongoDbClient extends DB\n{\n\n    private  Mongo mongo;\n\n    private WriteConcern writeConcern;\n\n    private String database;\n\n    private com.mongodb.DB db = null;\n\n//    private DBCollection collection;\n\n    @Override\n    /**\n     * Initialize any state for this DB.\n     * Called once per DB instance; there is one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {\n            // initialize MongoDb driver\n            Properties props = getProperties();\n            String host=props.getProperty(\"hosts\");;\n            String port=props.getProperty(\"port\");\n            String url = \"mongodb://\"+host+\":\"+port;\n//            String url = props.getProperty(\"mongodb.url\", \"mongodb://192.168.145.168:27017\");\n            database = props.getProperty(\"schema\", \"kundera\");\n            String writeConcernType = props.getProperty(\"mongodb.writeConcern\", \"safe\").toLowerCase();\n\n            if (\"none\".equals(writeConcernType))\n            {\n                writeConcern = WriteConcern.NONE;\n            }\n            else if (\"safe\".equals(writeConcernType))\n            {\n                writeConcern = WriteConcern.SAFE;\n            }\n            else if (\"normal\".equals(writeConcernType))\n            {\n                writeConcern = WriteConcern.NORMAL;\n            }\n            else if (\"fsync_safe\".equals(writeConcernType))\n            {\n                writeConcern = WriteConcern.FSYNC_SAFE;\n            }\n            else if (\"replicas_safe\".equals(writeConcernType))\n            {\n                writeConcern = WriteConcern.REPLICAS_SAFE;\n            }\n            else\n            {\n                System.err.println(\"ERROR: Invalid writeConcern: '\" + writeConcernType + \"'. \"\n                        + \"Must be [ none | safe | normal | fsync_safe | replicas_safe ]\");\n                System.exit(1);\n            }\n\n            try\n            {\n                // strip out prefix since Java driver doesn't currently support\n                // standard connection format URL yet\n                // http://www.mongodb.org/display/DOCS/Connections\n                if (url.startsWith(\"mongodb://\"))\n                {\n                    url = url.substring(10);\n                }\n\n                // need to append db to url.\n                url += \"/\" + database;\n                // System.out.println(\"new database url = \" + url);\n                mongo = new Mongo(new DBAddress(url));\n                mongo.getMongoOptions().setConnectionsPerHost(100);\n                // System.out.println(\"mongo connection created with \" + url);\n            }\n            catch (Exception e1)\n            {\n                System.err.println(\"Could not initialize MongoDB connection pool for Loader: \" + e1.toString());\n                e1.printStackTrace();\n                return;\n            }\n            db = mongo.getDB(database);\n            \n    }\n\n    @Override\n    /**\n     * Cleanup any state for this DB.\n     * Called once per DB instance; there is one DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n        try\n        {\n            mongo.close();\n        }\n        catch (Exception e1)\n        {\n            System.err.println(\"Could not close MongoDB connection pool: \" + e1.toString());\n            e1.printStackTrace();\n            return;\n        }\n    }\n\n    @Override\n    /**\n     * Delete a record from the database.\n     *\n     * @param table The name of the table\n     * @param key The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.\n     */\n    public int delete(String table, String key)\n    {\n        com.mongodb.DB db = null;\n        try\n        {\n            db = mongo.getDB(database);\n            db.requestStart();\n            DBCollection collection = db.getCollection(table);\n            DBObject q = new BasicDBObject().append(\"_id\", key);\n            WriteResult res = collection.remove(q, writeConcern);\n            return res.getN() == 1 ? 0 : 1;\n        }\n        catch (Exception e)\n        {\n            System.err.println(e.toString());\n            return 1;\n        }\n        finally\n        {\n            if (db != null)\n            {\n                db.requestDone();\n            }\n        }\n    }\n\n    @Override\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified values HashMap will be written into the record with the specified\n     * record key.\n     *\n     * @param table The name of the table\n     * @param key The record key of the record to insert.\n     * @param values A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        try\n        {\n            // db.requestStart();\n            \n            DBCollection collection = db.getCollection(\"kundera\");\n            DBObject r = new BasicDBObject();\n            r.put(\"_id\", key);\n            for (String k : values.keySet())\n            {\n                r.put(k, getString(key, \"kk\"));\n            }\n            // WriteResult res = collection.insert(r, writeConcern);\n            // return res.getError() == null ? 0 : 1;\n            collection.insert(r);\n            return 0;\n        }\n        catch (Exception e)\n        {\n            e.printStackTrace();\n            return 1;\n        }\n    }\n\n    @Override\n    @SuppressWarnings(\"unchecked\")\n    /**\n     * Read a record from the database. Each field/value pair from the result will be stored in a HashMap.\n     *\n     * @param table The name of the table\n     * @param key The record key of the record to read.\n     * @param fields The list of fields to read, or null for all of them\n     * @param result A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error or \"not found\".\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        // com.mongodb.DB db = null;\n        try\n        {\n            // db = mongo.getDB(database);\n            //\n            // db.requestStart();\n            //\n            // DBCollection collection = db.getCollection(table);\n            DBObject q = new BasicDBObject().append(\"_id\", key);\n            DBObject fieldsToReturn = new BasicDBObject();\n            boolean returnAllFields = fields == null;\n\n            DBObject queryResult = null;\n            DBCollection collection = db.getCollection(\"kundera\");\n            if (!returnAllFields)\n            {\n                Iterator<String> iter = fields.iterator();\n                while (iter.hasNext())\n                {\n                    fieldsToReturn.put(iter.next(), 1);\n                }\n                queryResult = collection.findOne(q, fieldsToReturn);\n            }\n            else\n            { \n                queryResult = collection.findOne(q);\n            }\n            \n           \n            if (queryResult != null)\n            {\n                result.putAll(queryResult.toMap());\n            }\n            return queryResult != null ? 0 : 1;\n        }\n        catch (Exception e)\n        {\n            System.err.println(e.toString());\n            return 1;\n        }\n        /*\n         * finally { if (db != null) { db.requestDone(); } }\n         */\n    }\n\n    @Override\n    /**\n     * Update a record in the database. Any field/value pairs in the specified values HashMap will be written into the record with the specified\n     * record key, overwriting any existing values with the same field name.\n     *\n     * @param table The name of the table\n     * @param key The record key of the record to write.\n     * @param values A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        com.mongodb.DB db = null;\n        try\n        {\n            db = mongo.getDB(database);\n\n            db.requestStart();\n\n            DBCollection collection = db.getCollection(table);\n            DBObject q = new BasicDBObject().append(\"_id\", key);\n            DBObject u = new BasicDBObject();\n            DBObject fieldsToSet = new BasicDBObject();\n            Iterator<String> keys = values.keySet().iterator();\n            while (keys.hasNext())\n            {\n                String tmpKey = keys.next();\n                fieldsToSet.put(tmpKey, values.get(tmpKey).toArray());\n\n            }\n            u.put(\"$set\", fieldsToSet);\n            WriteResult res = collection.update(q, u, false, false, writeConcern);\n            return res.getN() == 1 ? 0 : 1;\n        }\n        catch (Exception e)\n        {\n            System.err.println(e.toString());\n            return 1;\n        }\n        finally\n        {\n            if (db != null)\n            {\n                db.requestDone();\n            }\n        }\n    }\n\n    @Override\n    @SuppressWarnings(\"unchecked\")\n    /**\n     * Perform a range scan for a set of records in the database. Each field/value pair from the result will be stored in a HashMap.\n     *\n     * @param table The name of the table\n     * @param startkey The record key of the first record to read.\n     * @param recordcount The number of records to read\n     * @param fields The list of fields to read, or null for all of them\n     * @param result A Vector of HashMaps, where each HashMap is a set field/value pairs for one record\n     * @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        com.mongodb.DB db = null;\n        try\n        {\n            db = mongo.getDB(database);\n            db.requestStart();\n            DBCollection collection = db.getCollection(table);\n            // { \"_id\":{\"$gte\":startKey, \"$lte\":{\"appId\":key+\"\\uFFFF\"}} }\n            DBObject scanRange = new BasicDBObject().append(\"$gte\", startkey);\n            DBObject q = new BasicDBObject().append(\"_id\", scanRange);\n            DBCursor cursor = collection.find(q).limit(recordcount);\n            while (cursor.hasNext())\n            {\n                // toMap() returns a Map, but result.add() expects a\n                // Map<String,String>. Hence, the suppress warnings.\n                result.add(StringByteIterator.getByteIteratorMap((Map<String, String>) cursor.next().toMap()));\n            }\n\n            return 0;\n        }\n        catch (Exception e)\n        {\n            System.err.println(e.toString());\n            return 1;\n        }\n        finally\n        {\n            if (db != null)\n            {\n                db.requestDone();\n            }\n        }\n\n    }\n\n    private String getString(String key, String value)\n    {\n        StringBuilder builder = new StringBuilder(key);\n        builder.append(value);\n        return builder.toString();\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/Neo4JNativeClient.java",
    "content": "/**\n * MongoDB client binding for YCSB.\n *\n * Submitted by Yen Pai on 5/11/2010.\n *\n * https://gist.github.com/000a66b8db2caf42467b#file_mongo_db.java\n *\n */\n\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport org.neo4j.graphdb.GraphDatabaseService;\nimport org.neo4j.graphdb.Node;\nimport org.neo4j.graphdb.Transaction;\nimport org.neo4j.graphdb.factory.GraphDatabaseBuilder;\nimport org.neo4j.graphdb.factory.GraphDatabaseFactory;\nimport org.neo4j.graphdb.index.IndexHits;\nimport org.neo4j.graphdb.index.ReadableIndex;\nimport org.neo4j.graphdb.index.UniqueFactory;\n\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\n\n/**\n * Neo4J Native client for YCSB framework.\n * \n * Properties to set:\n * \n * mongodb.url=mongodb://localhost:27017 mongodb.database=ycsb\n * mongodb.writeConcern=normal\n * \n * @author Amresh Singh\n * \n */\npublic class Neo4JNativeClient extends DB\n{\n    private static GraphDatabaseService graphDb;\n//    private GraphDatabaseService graphDb;\n    Transaction tx = null;\n    private int j;\n    static {\n        Map<String, String> config = new HashMap<String, String>(); \n        config.put(\"node_auto_indexing\", \"true\");\n        config.put(\"node_keys_indexable\", \"USER_ID\");        \n        \n        \n        String datastoreFilePath = \"target/neo4jPerfNative.db\";\n        GraphDatabaseBuilder builder = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(datastoreFilePath);\n        builder.setConfig(config);                \n        \n        graphDb = builder.newGraphDatabase();           \n        \n        System.out.println(\"Neo4J connection created with file path: \" + datastoreFilePath);\n        \n        \n    }\n\n    /**\n     * Initialize any state for this DB.\n     * Called once per DB instance; there is one DB instance per client thread.\n     */\n    @Override    \n    public void init() throws DBException\n    {    \n/*        Map<String, String> config = new HashMap<String, String>(); \n        config.put(\"node_auto_indexing\", \"true\");\n        config.put(\"node_keys_indexable\", \"USER_ID\");        \n        \n        \n        String datastoreFilePath = \"target/neo4jPerfNative.db\";\n        GraphDatabaseBuilder builder = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(datastoreFilePath);\n        builder.setConfig(config);                \n        \n        graphDb = builder.newGraphDatabase();           \n        \n*///        System.out.println(\"Neo4J connection created with file path: \" + datastoreFilePath);\n        tx = graphDb.beginTx();\n        j = 1;\n    }    \n    \n\n    /**\n     * Cleanup any state for this DB.\n     * Called once per DB instance; there is one DB instance per client thread.\n     */\n    @Override    \n    public void cleanup() throws DBException\n    {\n        tx.success();\n        tx.finish();\n        /*try\n        {\n            //graphDb.shutdown();\n        }\n        catch (Exception e1)\n        {\n            System.err.println(\"Could not close Neo4J connection: \" + e1.toString());\n            e1.printStackTrace();\n            return;\n        }*/\n    }\n    \n    /**\n     * Insert a record in the database. Any field/value pairs in the specified values HashMap will be written into the record with the specified\n     * record key.\n     *\n     * @param table The name of the table\n     * @param key The record key of the record to insert.\n     * @param values A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.\n     */\n    @Override\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        try\n        {            \n            \n            /*Node node = graphDb.createNode();\n            node.setProperty(\"USER_ID\", key);\n            node.setProperty(\"NAME\", key + \"Keenu Reeves\");\n            node.setProperty(\"AGE\", key + \"39\");\n            node.setProperty(\"ADDRESS\", key + \"New Street\"); */\n            \n            \n            UniqueFactory<Node> factory = new UniqueFactory.UniqueNodeFactory(graphDb, \"users\")\n            {\n                @Override\n                protected void initialize(Node created, Map<String, Object> properties)\n                {\n                    created.setProperty(\"USER_ID\", properties.get(\"USER_ID\"));\n                }\n            };           \n           Node node = factory.getOrCreate(\"USER_ID\", key);\n           node.setProperty(\"NAME\", key + \"Keenu Reeves\");\n           node.setProperty(\"AGE\", key + \"39\");\n           node.setProperty(\"ADDRESS\", key + \"New Street\");            \n            \n            j++;\n            if (j % 1000 == 0)\n            {\n                tx.success();\n                tx.finish();                \n                tx = graphDb.beginTx();\n            }\n            \n            \n            return 0;           \n        }\n        catch (Exception e)\n        {\n            e.printStackTrace();\n            return 1;\n        }\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result will be stored in a HashMap.\n     *\n     * @param table The name of the table\n     * @param key The record key of the record to read.\n     * @param fields The list of fields to read, or null for all of them\n     * @param result A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error or \"not found\".\n     */\n    @Override\n    @SuppressWarnings(\"unchecked\")\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n    \tboolean present=false;\n        try\n        {            \n            ReadableIndex<Node> autoNodeIndex = graphDb.index().getNodeAutoIndexer().getAutoIndex();\n            IndexHits<Node> nodesFound = autoNodeIndex.get(\"USER_ID\", key);\n            Node node = null;\n            \n            assert nodesFound.size() == 1;\n            \n            if(nodesFound.hasNext())\n            {\n                node = nodesFound.next();\n            }\n            \n            Iterable<String> fieldNames = node.getPropertyKeys();\n            \n            Iterator<String> iter = fieldNames.iterator();\n            \n            while(iter.hasNext())\n            {\n            \tpresent=true;\n            \tString field = iter.next();\n            \tObject value = node.getProperty(field);\n            \tassert value != null;\n            \tassert field != null;\n            }\n        }\n        catch (Exception e)\n        {\n            System.err.println(e.toString());\n            return 1;\n        }\n        return present? 0:1;\n    }\n    \n \n    \n    \n    /**\n     * Update a record in the database. Any field/value pairs in the specified values HashMap will be written into the record with the specified\n     * record key, overwriting any existing values with the same field name.\n     *\n     * @param table The name of the table\n     * @param key The record key of the record to write.\n     * @param values A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.\n     */\n    @Override\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return insert(table, key, values);\n        /*com.mongodb.DB db = null;\n        try\n        {\n            db = mongo.getDB(database);\n\n            db.requestStart();\n\n            DBCollection collection = db.getCollection(table);\n            DBObject q = new BasicDBObject().append(\"_id\", key);\n            DBObject u = new BasicDBObject();\n            DBObject fieldsToSet = new BasicDBObject();\n            Iterator<String> keys = values.keySet().iterator();\n            while (keys.hasNext())\n            {\n                String tmpKey = keys.next();\n                fieldsToSet.put(tmpKey, values.get(tmpKey).toArray());\n\n            }\n            u.put(\"$set\", fieldsToSet);\n            WriteResult res = collection.update(q, u, false, false, writeConcern);\n            return res.getN() == 1 ? 0 : 1;\n        }\n        catch (Exception e)\n        {\n            System.err.println(e.toString());\n            return 1;\n        }\n        finally\n        {\n            if (db != null)\n            {\n                db.requestDone();\n            }\n        }*/\n//        return 0;\n    }\n    \n    \n    /**\n     * Delete a record from the database.\n     *\n     * @param table The name of the table\n     * @param key The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.\n     */\n    @Override\n    public int delete(String table, String key)\n    {  \n        Transaction tx = null;\n        try\n        {\n            tx = graphDb.beginTx();\n            \n            Node node = graphDb.getNodeById(Long.parseLong(key));\n            node.delete();\n            \n            tx.success();\n            tx.finish();\n            \n            /*db = mongo.getDB(database);\n            db.requestStart();\n            DBCollection collection = db.getCollection(table);\n            DBObject q = new BasicDBObject().append(\"_id\", key);\n            WriteResult res = collection.remove(q, writeConcern);\n            return res.getN() == 1 ? 0 : 1;*/\n            \n            return 0;\n        }\n        catch (Exception e)\n        {\n            System.err.println(e.toString());\n            tx.failure();\n            return 1;\n        }        \n    } \n   \n    \n    /**\n     * Perform a range scan for a set of records in the database. Each field/value pair from the result will be stored in a HashMap.\n     *\n     * @param table The name of the table\n     * @param startkey The record key of the first record to read.\n     * @param recordcount The number of records to read\n     * @param fields The list of fields to read, or null for all of them\n     * @param result A Vector of HashMaps, where each HashMap is a set field/value pairs for one record\n     * @return Zero on success, a non-zero error code on error. See this class's description for a discussion of error codes.\n     */\n    @Override\n    @SuppressWarnings(\"unchecked\")\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        /*com.mongodb.DB db = null;\n        try\n        {\n            db = mongo.getDB(database);\n            db.requestStart();\n            DBCollection collection = db.getCollection(table);\n            // { \"_id\":{\"$gte\":startKey, \"$lte\":{\"appId\":key+\"\\uFFFF\"}} }\n            DBObject scanRange = new BasicDBObject().append(\"$gte\", startkey);\n            DBObject q = new BasicDBObject().append(\"_id\", scanRange);\n            DBCursor cursor = collection.find(q).limit(recordcount);\n            while (cursor.hasNext())\n            {\n                // toMap() returns a Map, but result.add() expects a\n                // Map<String,String>. Hence, the suppress warnings.\n                result.add(StringByteIterator.getByteIteratorMap((Map<String, String>) cursor.next().toMap()));\n            }\n\n            return 0;\n        }\n        catch (Exception e)\n        {\n            System.err.println(e.toString());\n            return 1;\n        }\n        finally\n        {\n            if (db != null)\n            {\n                db.requestDone();\n            }\n        }*/\n        return 0;\n\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/OracleNosqlClient.java",
    "content": "package com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport oracle.kv.Direction;\nimport oracle.kv.DurabilityException;\nimport oracle.kv.FaultException;\nimport oracle.kv.KVStore;\nimport oracle.kv.KVStoreConfig;\nimport oracle.kv.KVStoreFactory;\nimport oracle.kv.Key;\nimport oracle.kv.KeyValueVersion;\nimport oracle.kv.Operation;\nimport oracle.kv.OperationExecutionException;\nimport oracle.kv.Value;\n\nimport com.yahoo.ycsb.ByteArrayByteIterator;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.RandomByteIterator;\nimport com.yahoo.ycsb.generator.IntegerGenerator;\nimport com.yahoo.ycsb.generator.ZipfianGenerator;\n\n/**\n * A database interface layer for Oracle NoSQL Database.\n */\npublic class OracleNosqlClient extends DB\n{\n\n    public static final int OK = 0;\n\n    public static final int ERROR = -1;\n\n    private static KVStoreConfig config = new KVStoreConfig(\"OracleNoSqlTests\", \"localhost:5000\");\n\n    private static KVStore store = KVStoreFactory.getStore(config);\n\n    private int getPropertyInt(Properties properties, String key, int defaultValue) throws DBException\n    {\n        String p = properties.getProperty(key);\n        int i = defaultValue;\n        if (p != null)\n        {\n            try\n            {\n                i = Integer.parseInt(p);\n            }\n            catch (NumberFormatException e)\n            {\n                throw new DBException(\"Illegal number format in \" + key + \" property\");\n            }\n        }\n        return i;\n    }\n\n    @Override\n    public void init() throws DBException\n    {/*\n      * if (store == null) { Properties properties = getProperties();\n      * \n      * Mandatory properties String storeName =\n      * properties.getProperty(\"storeName\", \"kvstore\"); String[] helperHosts =\n      * properties.getProperty(\"helperHost\", \"localhost:5000\").split(\",\");\n      * \n      * KVStoreConfig config = new KVStoreConfig(storeName, helperHosts);\n      * \n      * Optional properties String p;\n      * \n      * p = properties.getProperty(\"consistency\"); if (p != null) { if\n      * (p.equalsIgnoreCase(\"ABSOLUTE\")) {\n      * config.setConsistency(Consistency.ABSOLUTE); } else if\n      * (p.equalsIgnoreCase(\"NONE_REQUIRED\")) {\n      * config.setConsistency(Consistency.NONE_REQUIRED); } else { throw new\n      * DBException(\"Illegal value in consistency property\"); } }\n      * \n      * p = properties.getProperty(\"durability\"); if (p != null) { if\n      * (p.equalsIgnoreCase(\"COMMIT_NO_SYNC\")) {\n      * config.setDurability(Durability.COMMIT_NO_SYNC); } else if\n      * (p.equalsIgnoreCase(\"COMMIT_SYNC\")) {\n      * config.setDurability(Durability.COMMIT_SYNC); } else if\n      * (p.equalsIgnoreCase(\"COMMIT_WRITE_NO_SYNC\")) {\n      * config.setDurability(Durability.COMMIT_WRITE_NO_SYNC); } else { throw\n      * new DBException(\"Illegal value in durability property\"); } }\n      * \n      * int maxActiveRequests = getPropertyInt(properties,\n      * \"requestLimit.maxActiveRequests\",\n      * RequestLimitConfig.DEFAULT_MAX_ACTIVE_REQUESTS); int\n      * requestThresholdPercent = getPropertyInt(properties,\n      * \"requestLimit.requestThresholdPercent\",\n      * RequestLimitConfig.DEFAULT_REQUEST_THRESHOLD_PERCENT); int\n      * nodeLimitPercent = getPropertyInt(properties,\n      * \"requestLimit.nodeLimitPercent\",\n      * RequestLimitConfig.DEFAULT_NODE_LIMIT_PERCENT); RequestLimitConfig\n      * requestLimitConfig;\n      * \n      * It is said that the constructor could throw NodeRequestLimitException in\n      * Javadoc, the exception is not provided\n      * \n      * // try { requestLimitConfig = new RequestLimitConfig(maxActiveRequests,\n      * requestThresholdPercent, nodeLimitPercent); // } catch\n      * (NodeRequestLimitException e) { // throw new DBException(e); // }\n      * config.setRequestLimit(requestLimitConfig);\n      * \n      * p = properties.getProperty(\"requestTimeout\"); if (p != null) { long\n      * timeout = 1; try { timeout = Long.parseLong(p); } catch\n      * (NumberFormatException e) { throw new\n      * DBException(\"Illegal number format in requestTimeout property\"); } try {\n      * // TODO Support other TimeUnit config.setRequestTimeout(timeout,\n      * TimeUnit.SECONDS); } catch (IllegalArgumentException e) { throw new\n      * DBException(e); } } try { store = KVStoreFactory.getStore(config); }\n      * catch (FaultException e) { throw new DBException(e); } }\n      */\n    }\n\n    @Override\n    public void cleanup() throws DBException\n    {\n        // store.close();\n    }\n\n    /**\n     * Create a key object. We map \"table\" and (YCSB's) \"key\" to a major\n     * component of the oracle.kv.Key, and \"field\" to a minor component.\n     * \n     * @return An oracle.kv.Key object.\n     */\n    private static Key createKey(String table, String key, String field)\n    {\n        List<String> majorPath = new ArrayList<String>();\n        majorPath.add(table);\n        majorPath.add(key);\n        if (field == null)\n        {\n            return Key.createKey(majorPath);\n        }\n\n        return Key.createKey(majorPath, field);\n    }\n\n    private static Key createKey(String table, String key)\n    {\n        return createKey(table, key, null);\n    }\n\n    private static String getFieldFromKey(Key key)\n    {\n        return key.getMinorPath().get(0);\n    }\n\n    @Override\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        List<String> majorComponents = new ArrayList<String>();\n        majorComponents.add(table);\n        majorComponents.add(key);\n        Key kvKey = Key.createKey(majorComponents);\n        Iterator<KeyValueVersion> iterator;\n        try\n        {\n            iterator = store.multiGetIterator(Direction.FORWARD, 0, kvKey, null, null);\n        }\n        catch (FaultException e)\n        {\n            System.err.println(e);\n            return ERROR;\n        }\n\n        while (iterator != null && iterator.hasNext())\n        {\n            /* If fields is null, read all fields */\n            KeyValueVersion next = iterator.next();\n            String field = getFieldFromKey(next.getKey());\n            if (fields != null && !fields.contains(field))\n            {\n                continue;\n            }\n            result.put(field, new ByteArrayByteIterator(next.getValue().getValue()));\n        }\n\n        return OK;\n    }\n\n    @Override\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        System.err.println(\"Oracle NoSQL Database does not support Scan semantics\");\n        return ERROR;\n    }\n\n    @Override\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        List<Operation> persistOperations = new ArrayList<Operation>();\n        List<String> majorKeyComponent = new ArrayList<String>();\n        majorKeyComponent.add(table);\n        majorKeyComponent.add(key); // Major\n\n        for (Map.Entry<String, ByteIterator> entry : values.entrySet())\n        {\n            Key kvKey = Key.createKey(majorKeyComponent, entry.getKey());\n            Value kvValue = Value.createValue(entry.getValue().toArray());\n            try\n            {\n                Operation op = store.getOperationFactory().createPut(kvKey, kvValue);\n                persistOperations.add(op);\n            }\n            catch (FaultException e)\n            {\n                System.err.println(e);\n                return ERROR;\n            }\n        }\n        try\n        {\n            store.execute(persistOperations);\n        }\n        catch (DurabilityException e)\n        {\n            System.err.println(e);\n            return ERROR;\n        }\n        catch (OperationExecutionException e)\n        {\n            System.err.println(e);\n            return ERROR;\n        }\n        catch (FaultException e)\n        {\n            System.err.println(e);\n            return ERROR;\n        }\n        return OK;\n    }\n\n    @Override\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return update(table, key, values);\n    }\n\n    @Override\n    public int delete(String table, String key)\n    {\n        Key kvKey = createKey(table, key);\n        try\n        {\n            store.multiDelete(kvKey, null, null);\n        }\n        catch (FaultException e)\n        {\n            System.err.println(e);\n            return ERROR;\n        }\n\n        return OK;\n    }\n\n    public static void main(String[] args)\n    {\n\n        OracleNosqlClient client = new OracleNosqlClient();\n        HashMap<String, ByteIterator> values = new HashMap<String, ByteIterator>();\n        values = client.buildValues();\n\n        client.insert(\"User\", \"1\", values);\n        System.out.println(\"persisted\");\n    }\n\n    private HashMap<String, ByteIterator> buildValues()\n    {\n        IntegerGenerator fieldlengthgenerator = new ZipfianGenerator(1, 4);\n        HashMap<String, ByteIterator> values = new HashMap<String, ByteIterator>();\n\n        for (int i = 0; i < 4; i++)\n        {\n            String fieldkey = \"field\" + i;\n            ByteIterator data = new RandomByteIterator(fieldlengthgenerator.nextInt());\n            values.put(fieldkey, data);\n        }\n        return values;\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/PelopsClient.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.ColumnOrSuperColumn;\nimport org.apache.cassandra.thrift.ColumnParent;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.utils.ByteBufferUtil;\nimport org.scale7.cassandra.pelops.Bytes;\nimport org.scale7.cassandra.pelops.Cluster;\nimport org.scale7.cassandra.pelops.IConnection;\nimport org.scale7.cassandra.pelops.Mutator;\nimport org.scale7.cassandra.pelops.Pelops;\nimport org.scale7.cassandra.pelops.Selector;\nimport org.scale7.cassandra.pelops.pool.IThriftPool;\n\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\nimport common.Logger;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class PelopsClient extends DB\n{\n\n    private static Logger logger = Logger.getLogger(PelopsClient.class);\n\n    static Random random = new Random();\n\n    private static final int Ok = 0;\n\n    private static final int Error = -1;\n\n    private String column_family;\n\n    private static final String COLUMN_FAMILY_PROPERTY = \"columnfamilyOrTable\";\n\n    private static final String COLUMN_FAMILY_PROPERTY_DEFAULT = \"data\";\n\n    private static final String READ_CONSISTENCY_LEVEL_PROPERTY = \"cassandra.readconsistencylevel\";\n\n    private static final String READ_CONSISTENCY_LEVEL_PROPERTY_DEFAULT = \"ONE\";\n\n    private static final String WRITE_CONSISTENCY_LEVEL_PROPERTY = \"cassandra.writeconsistencylevel\";\n\n    private static final String WRITE_CONSISTENCY_LEVEL_PROPERTY_DEFAULT = \"ONE\";\n\n    private static String _keyspace = \"kundera\";\n\n    private static String _host = \"localhost\";\n\n    private static int _port = 9160;\n\n    private static String poolName = _host + \":\" + _port + \":\" + _keyspace;\n\n    private ConsistencyLevel writeConsistencyLevel = ConsistencyLevel.ONE;\n\n    private ConsistencyLevel readConsistencyLevel = ConsistencyLevel.ONE;\n\n    private static IThriftPool pool;\n\n    static\n    {\n\n        String[] contactNodes = new String[] { _host };\n        Cluster cluster = new Cluster(contactNodes, new IConnection.Config(_port, true, -1), false);\n        Pelops.addPool(getPoolName(), cluster, _keyspace);\n        pool = Pelops.getDbConnPool(getPoolName());\n        \n    }\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {\n        String hosts = getProperties().getProperty(\"hosts\");\n        if (hosts == null)\n        {\n            throw new DBException(\"Required property \\\"hosts\\\" missing for CassandraClient\");\n        }\n\n        column_family = \"pelopsuser\";\n        // column_family = getProperties().getProperty(COLUMN_FAMILY_PROPERTY,\n        // COLUMN_FAMILY_PROPERTY_DEFAULT);\n        //\n        // readConsistencyLevel =\n        // ConsistencyLevel.valueOf(getProperties().getProperty(READ_CONSISTENCY_LEVEL_PROPERTY,\n        // READ_CONSISTENCY_LEVEL_PROPERTY_DEFAULT));\n        //\n        // writeConsistencyLevel =\n        // ConsistencyLevel.valueOf(getProperties().getProperty(WRITE_CONSISTENCY_LEVEL_PROPERTY,\n        // WRITE_CONSISTENCY_LEVEL_PROPERTY_DEFAULT));\n        //\n        // String[] allhosts = hosts.split(\",\");\n        // _host = allhosts[random.nextInt(allhosts.length)];\n\n        /*\n         * if (Pelops.getDbConnPool(getPoolName()) == null) {\n         * System.out.println(\"calling\");\n         * \n         * }\n         */\n    }\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n        // Pelops.shutdown();\n        // Pelops.removePool(getPoolName());\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        try\n        {\n            List<ByteBuffer> keys = new ArrayList<ByteBuffer>();\n            keys.add(ByteBufferUtil.bytes(key));\n            \n            Selector selector = pool.createSelector();/*Pelops.createSelector(getPoolName());*/\n            Map<ByteBuffer, List<ColumnOrSuperColumn>> columns = selector.getColumnOrSuperColumnsFromRows(new ColumnParent(column_family), keys,\n                    Selector.newColumnsPredicateAll(false, 10000), readConsistencyLevel);\n\n            assert columns != null;\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        return Ok;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write.\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return insert(table, key, values);\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        Mutator mutator = \n                Pelops.createMutator(_host + \":\" + _port + \":\" + _keyspace);\n        try\n        {\n            List<Column> columns = new ArrayList<Column>();\n            for (Map.Entry<String, ByteIterator> entry : values.entrySet())\n            {\n                Column col = new Column();\n                col.setName(ByteBuffer.wrap(entry.getKey().getBytes(\"UTF-8\")));\n                col.setValue(ByteBuffer.wrap(entry.getValue().toArray()));\n                col.setTimestamp(System.currentTimeMillis());\n\n                columns.add(col);\n            }\n\n            mutator.writeColumns(column_family, Bytes.fromUTF8(key), columns);\n            mutator.execute(writeConsistencyLevel);\n\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        return Error;\n    }\n\n    public static void main(String[] args)\n    {\n        PelopsClient cli = new PelopsClient();\n\n        Properties props = new Properties();\n\n        props.setProperty(\"hosts\", \"localhost\");\n        cli.setProperties(props);\n\n        try\n        {\n            cli.init();\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            System.exit(0);\n        }\n\n        HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();\n        vals.put(\"age\", new StringByteIterator(\"57\"));\n        vals.put(\"middlename\", new StringByteIterator(\"bradley\"));\n        vals.put(\"favoritecolor\", new StringByteIterator(\"blue\"));\n        int res = cli.insert(\"usertable\", \"BrianFrankCooper\", vals);\n        System.out.println(\"Result of insert: \" + res);\n\n        HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();\n        HashSet<String> fields = new HashSet<String>();\n        fields.add(\"middlename\");\n        fields.add(\"age\");\n        fields.add(\"favoritecolor\");\n        res = cli.read(\"usertable\", \"BrianFrankCooper\", null, result);\n        System.out.println(\"Result of read: \" + res);\n        for (String s : result.keySet())\n        {\n            System.out.println(\"[\" + s + \"]=[\" + result.get(s) + \"]\");\n        }\n\n        res = cli.delete(\"usertable\", \"BrianFrankCooper\");\n        System.out.println(\"Result of delete: \" + res);\n    }\n\n    protected static String getPoolName()\n    {\n        return poolName;\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/PhoenixClient.java",
    "content": "package com.impetus.kundera.ycsb.benchmark;\n\n/**\n * Copyright (c) 2010 Yahoo! Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You\n * may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License. See accompanying\n * LICENSE file.\n */\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\nimport java.util.HashMap;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport com.impetus.kundera.KunderaException;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\n\n/**\n * YCSB HBase client for YCSB framework\n */\npublic class PhoenixClient extends DB\n{\n    public boolean _debug = false;\n\n    public static String _table = \"phoenix_table\";\n\n    public static final int Ok = 0;\n\n    public static final int ServerError = -1;\n\n    public static final int HttpError = -2;\n\n    public static final int NoMatchingRecord = -3;\n\n    public static final Object tableLock = new Object();\n\n    public Connection connection/*; //*/ = initConenction();\n    \n    public Statement stmt;\n    \n    public PreparedStatement prepstmnt;\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {\n        try\n        {\n//            connection = connection!=null?connection:DriverManager.getConnection(\"jdbc:phoenix\");\n            stmt = connection.createStatement();\n            stmt.executeUpdate(\"create table if not exists \" + _table\n                    + \"(name varchar not null primary key, age varchar, address varchar, lname varchar)\");\n        }\n        catch (SQLException e)\n        {\n            System.err.println(\"Error accessing HBase table: \" + e);\n        }\n    }\n\n    private Connection initConenction()\n    {\n        try\n        {\n            return DriverManager.getConnection(\"jdbc:phoenix\");\n        }\n        catch (SQLException e)\n        {\n            throw new KunderaException(e);\n        }\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n\n        try\n        {\n            prepstmnt = connection.prepareStatement(\"select * from phoenix_table where name = ?\");\n            prepstmnt.setString(1, key);\n            ResultSet rset = prepstmnt.executeQuery();\n/*            StringBuilder sb = new StringBuilder(\"select * from \");\n            sb.append(_table);\n            sb.append(\" where name = \");\n            sb.append(\"'\"+key+\"'\");\n            PreparedStatement statement = connection.prepareStatement(sb.toString());\n            ResultSet rset = statement.executeQuery();*/\n            rset.next();\n            assert rset != null;\n        }\n        catch (SQLException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        return Ok;\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        return Ok;\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        insert(table, key, values);\n        return Ok;\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n       \n        try{\n/*        prepstmnt = connection.prepareStatement(\"upsert into phoenix_table values (?,?,?,?)\");\n        prepstmnt.setString(1, key);\n        prepstmnt.setString(2, key+\"24\");\n        prepstmnt.setString(3, key+\"gzb\");\n        prepstmnt.setString(4, key+\"mishra\");*/\n        StringBuilder sb = new StringBuilder(\"upsert into \");\n        sb.append(_table);\n        sb.append(\" values (\");\n        sb.append(\"'\" + key + \"'\");\n        sb.append(\",\");\n        sb.append(\"'\" + key + \"24\" + \"'\");\n        sb.append(\",\");\n        sb.append(\"'\" + key + \"gzb\" + \"'\");\n        sb.append(\",\");\n        sb.append(\"'\" + key + \"mishra\" + \"'\");\n        sb.append(\")\");\n       /* try\n        {*/\n//            Statement stmt = connection.createStatement();\n            stmt.executeUpdate(sb.toString());\n//        assert prepstmnt.executeUpdate()!=0;\n            connection.commit();\n        }\n        catch (SQLException e)\n        {\n            e.printStackTrace();\n        }\n        return Ok;\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        StringBuilder sb = new StringBuilder(\"delete from \");\n        sb.append(_table);\n        sb.append(\" where  name = \");\n        sb.append(\"'\"+key+\"'\");\n        try\n        {\n//            Statement stmt = connection.createStatement();\n            stmt.executeUpdate(sb.toString());\n            connection.commit();\n        }\n        catch (SQLException e)\n        {\n            e.printStackTrace();\n        }\n        return Ok;\n    }\n\n    public static void main(String[] args)\n    {\n        PhoenixClient cli = new PhoenixClient();\n        try\n        {\n            cli.init();\n        }\n        catch (Exception e)\n        {\n            System.exit(0);\n        }\n        long num =200000;\n        long i = num;\n//        cli.read(_table, \"user2679876345976412335\", null, null);\n        long t1 = System.currentTimeMillis();\n        long temp = t1;\n        while (i-- != 0)\n        {\n            cli.insert(_table, \"\"+i, null);\n//            cli.read(null, \"\"+num, null,null);\n            if(i%10000 == 0){\n                System.out.println(num-i + \" records inserted!\");\n                System.out.println(\"time taken = \" + (System.currentTimeMillis() - temp));\n                temp = System.currentTimeMillis();\n            }\n            \n        }\n        System.out.println(\"time taken = \" + (System.currentTimeMillis()-t1));\n    }\n}\n\n/*\n * For customized vim control set autoindent set si set shiftwidth=4\n */"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/RedisClient.java",
    "content": "/**\n * Redis client binding for YCSB.\n *\n * All YCSB records are mapped to a Redis *hash field*.  For scanning\n * operations, all keys are saved (by an arbitrary hash) in a sorted set.\n */\n\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport redis.clients.jedis.Jedis;\nimport redis.clients.jedis.Protocol;\n\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\n\n/**\n * @author Kuldeep mishra\n *\n */\npublic class RedisClient extends DB\n{\n    private Jedis jedis;\n\n    public static final String HOST_PROPERTY = \"hosts\";\n\n    public static final String PORT_PROPERTY = \"port\";\n\n    public static final String PASSWORD_PROPERTY = \"password\";\n\n    public static final String INDEX_KEY = \"_indices\";\n\n    public void init() throws DBException\n    {\n        Properties props = getProperties();\n        int port;\n\n        String portString = props.getProperty(PORT_PROPERTY);\n        if (portString != null)\n        {\n            port = Integer.parseInt(portString);\n        }\n        else\n        {\n            port = Protocol.DEFAULT_PORT;\n        }\n        String host = props.getProperty(HOST_PROPERTY);\n\n        jedis = new Jedis(host, port);\n        jedis.connect();\n\n        String password = props.getProperty(PASSWORD_PROPERTY);\n        if (password != null)\n        {\n            jedis.auth(password);\n        }\n    }\n\n    public void cleanup() throws DBException\n    {\n        jedis.disconnect();\n    }\n\n    /*\n     * Calculate a hash for a key to store it in an index. The actual return\n     * value of this function is not interesting -- it primarily needs to be\n     * fast and scattered along the whole space of doubles. In a real world\n     * scenario one would probably use the ASCII values of the keys.\n     */\n    private double hash(String key)\n    {\n        return key.hashCode();\n    }\n\n    // XXX jedis.select(int index) to switch to `table`\n\n    @Override\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        if (fields == null)\n        {\n            StringByteIterator.putAllAsByteIterators(result, jedis.hgetAll(key));\n        }\n        else\n        {\n            String[] fieldArray = (String[]) fields.toArray(new String[fields.size()]);\n            List<String> values = jedis.hmget(key, fieldArray);\n\n            Iterator<String> fieldIterator = fields.iterator();\n            Iterator<String> valueIterator = values.iterator();\n\n            while (fieldIterator.hasNext() && valueIterator.hasNext())\n            {\n                result.put(fieldIterator.next(), new StringByteIterator(valueIterator.next()));\n            }\n            assert !fieldIterator.hasNext() && !valueIterator.hasNext();\n        }\n        return result.isEmpty() ? 1 : 0;\n    }\n\n    @Override\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        if (jedis.hmset(key, StringByteIterator.getStringMap(values)).equals(\"OK\"))\n        {\n         //  jedis.zadd(INDEX_KEY, hash(key), key);\n            return 0;\n        }\n        return 1;\n    }\n\n    @Override\n    public int delete(String table, String key)\n    {\n        return jedis.del(key) == 0 && jedis.zrem(INDEX_KEY, key) == 0 ? 1 : 0;\n    }\n\n    @Override\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return jedis.hmset(key, StringByteIterator.getStringMap(values)).equals(\"OK\") ? 0 : 1;\n    }\n\n    @Override\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        Set<String> keys = jedis.zrangeByScore(INDEX_KEY, hash(startkey), Double.POSITIVE_INFINITY, 0, recordcount);\n\n        HashMap<String, ByteIterator> values;\n        for (String key : keys)\n        {\n            values = new HashMap<String, ByteIterator>();\n            read(table, key, fields, values);\n            result.add(values);\n        }\n\n        return 0;\n    }\n\n    public static void main(String[] args)\n    {\n\n        RedisClient cli = new RedisClient();\n\n        Properties props = new Properties();\n\n        props.setProperty(\"hosts\", \"localhost\");\n        props.setProperty(\"password\",\"Kundera@123\");\n        cli.setProperties(props);\n\n        try\n        {\n            cli.init();\n        }\n        catch (Exception e)\n        {\n            e.printStackTrace();\n            System.exit(0);\n        }\n\n        HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();\n        vals.put(\"age\", new StringByteIterator(\"57\"));\n        vals.put(\"middlename\", new StringByteIterator(\"bradley\"));\n        vals.put(\"favoritecolor\", new StringByteIterator(\"blue\"));\n        int res = cli.insert(\"usertable\", \"BrianFrankCooper\", vals);\n        System.out.println(\"Result of insert: \" + res);\n\n        HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();\n        HashSet<String> fields = new HashSet<String>();\n        fields.add(\"middlename\");\n        fields.add(\"age\");\n        fields.add(\"favoritecolor\");\n        res = cli.read(\"usertable\", \"BrianFrankCooper\", null, result);\n        System.out.println(\"Result of read: \" + res);\n        for (String s : result.keySet())\n        {\n            System.out.println(\"[\" + s + \"]=[\" + result.get(s) + \"]\");\n        }\n\n        res = cli.delete(\"usertable\", \"BrianFrankCooper\");\n        System.out.println(\"Result of delete: \" + res);\n\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/benchmark/ThriftClient.java",
    "content": "/**\n * Copyright (c) 2010 Yahoo! Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You\n * may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License. See accompanying\n * LICENSE file.\n */\n\npackage com.impetus.kundera.ycsb.benchmark;\n\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Vector;\n\nimport org.apache.cassandra.thrift.AuthenticationRequest;\nimport org.apache.cassandra.thrift.Cassandra;\nimport org.apache.cassandra.thrift.Column;\nimport org.apache.cassandra.thrift.ColumnOrSuperColumn;\nimport org.apache.cassandra.thrift.ColumnParent;\nimport org.apache.cassandra.thrift.ColumnPath;\nimport org.apache.cassandra.thrift.ConsistencyLevel;\nimport org.apache.cassandra.thrift.KeyRange;\nimport org.apache.cassandra.thrift.KeySlice;\nimport org.apache.cassandra.thrift.Mutation;\nimport org.apache.cassandra.thrift.SlicePredicate;\nimport org.apache.cassandra.thrift.SliceRange;\nimport org.apache.thrift.protocol.TBinaryProtocol;\nimport org.apache.thrift.protocol.TProtocol;\nimport org.apache.thrift.transport.TFramedTransport;\nimport org.apache.thrift.transport.TSocket;\nimport org.apache.thrift.transport.TTransport;\nimport org.scale7.cassandra.pelops.Bytes;\n\nimport com.yahoo.ycsb.ByteArrayByteIterator;\nimport com.yahoo.ycsb.ByteIterator;\nimport com.yahoo.ycsb.DB;\nimport com.yahoo.ycsb.DBException;\nimport com.yahoo.ycsb.StringByteIterator;\nimport common.Logger;\n\n//XXXX if we do replication, fix the consistency levels\n/**\n * Cassandra 1.0.6 client for YCSB framework\n */\npublic class ThriftClient extends DB\n{\n    private static Logger logger = Logger.getLogger(ThriftClient.class);\n\n    static Random random = new Random();\n\n    public static final int Ok = 0;\n\n    public static final int Error = -1;\n\n    public static final ByteBuffer emptyByteBuffer = ByteBuffer.wrap(new byte[0]);\n\n    public int ConnectionRetries;\n\n    public String column_family;\n\n    public static final String CONNECTION_RETRY_PROPERTY = \"cassandra.connectionretries\";\n\n    public static final String CONNECTION_RETRY_PROPERTY_DEFAULT = \"300\";\n\n    public static final String USERNAME_PROPERTY = \"cassandra.username\";\n\n    public static final String PASSWORD_PROPERTY = \"cassandra.password\";\n\n    public static final String COLUMN_FAMILY_PROPERTY = \"columnfamilyOrTable\";\n\n    // public static final String COLUMN_FAMILY_PROPERTY_DEFAULT = \"data\";\n\n    public static final String READ_CONSISTENCY_LEVEL_PROPERTY = \"cassandra.readconsistencylevel\";\n\n    public static final String READ_CONSISTENCY_LEVEL_PROPERTY_DEFAULT = \"ONE\";\n\n    public static final String WRITE_CONSISTENCY_LEVEL_PROPERTY = \"cassandra.writeconsistencylevel\";\n\n    public static final String WRITE_CONSISTENCY_LEVEL_PROPERTY_DEFAULT = \"ONE\";\n\n    public static final String SCAN_CONSISTENCY_LEVEL_PROPERTY = \"cassandra.scanconsistencylevel\";\n\n    public static final String SCAN_CONSISTENCY_LEVEL_PROPERTY_DEFAULT = \"ONE\";\n\n    public static final String DELETE_CONSISTENCY_LEVEL_PROPERTY = \"cassandra.deleteconsistencylevel\";\n\n    public static final String DELETE_CONSISTENCY_LEVEL_PROPERTY_DEFAULT = \"ONE\";\n\n    TTransport tr;\n\n    Cassandra.Client client;\n\n    boolean _debug = false;\n\n    String _table = \"\";\n\n    Exception errorexception = null;\n\n    List<Mutation> mutations = new ArrayList<Mutation>();\n\n    Map<String, List<Mutation>> mutationMap = new HashMap<String, List<Mutation>>();\n\n    Map<ByteBuffer, Map<String, List<Mutation>>> record = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();\n\n    ColumnParent parent;\n\n    ConsistencyLevel readConsistencyLevel = ConsistencyLevel.ONE;\n\n    ConsistencyLevel writeConsistencyLevel = ConsistencyLevel.ONE;\n\n    ConsistencyLevel scanConsistencyLevel = ConsistencyLevel.ONE;\n\n    ConsistencyLevel deleteConsistencyLevel = ConsistencyLevel.ONE;\n\n    /**\n     * Initialize any state for this DB. Called once per DB instance; there is\n     * one DB instance per client thread.\n     */\n    public void init() throws DBException\n    {\n//        System.out.println(\"**************************\" + column_family);\n        try\n        {\n            String hosts = getProperties().getProperty(\"hosts\");\n            if (hosts == null)\n            {\n                throw new DBException(\"Required property \\\"hosts\\\" missing for CassandraClient\");\n            }\n\n            column_family = getProperties().getProperty(COLUMN_FAMILY_PROPERTY);\n            parent = new ColumnParent(column_family);\n\n            _table = getProperties().getProperty(\"schema\");\n            ConnectionRetries = Integer.parseInt(getProperties().getProperty(CONNECTION_RETRY_PROPERTY,\n                    CONNECTION_RETRY_PROPERTY_DEFAULT));\n\n            String username = getProperties().getProperty(USERNAME_PROPERTY);\n            String password = getProperties().getProperty(PASSWORD_PROPERTY);\n\n            readConsistencyLevel = ConsistencyLevel.valueOf(getProperties().getProperty(\n                    READ_CONSISTENCY_LEVEL_PROPERTY, READ_CONSISTENCY_LEVEL_PROPERTY_DEFAULT));\n            writeConsistencyLevel = ConsistencyLevel.valueOf(getProperties().getProperty(\n                    WRITE_CONSISTENCY_LEVEL_PROPERTY, WRITE_CONSISTENCY_LEVEL_PROPERTY_DEFAULT));\n            scanConsistencyLevel = ConsistencyLevel.valueOf(getProperties().getProperty(\n                    SCAN_CONSISTENCY_LEVEL_PROPERTY, SCAN_CONSISTENCY_LEVEL_PROPERTY_DEFAULT));\n            deleteConsistencyLevel = ConsistencyLevel.valueOf(getProperties().getProperty(\n                    DELETE_CONSISTENCY_LEVEL_PROPERTY, DELETE_CONSISTENCY_LEVEL_PROPERTY_DEFAULT));\n\n            _debug = Boolean.parseBoolean(getProperties().getProperty(\"debug\", \"false\"));\n\n            String[] allhosts = hosts.split(\",\");\n            String myhost = allhosts[random.nextInt(allhosts.length)];\n\n            Exception connectexception = null;\n\n//            System.out.println(\"Initiating connection\");\n            if (tr == null || client == null)\n            {\n\n                for (int retry = 0; retry < ConnectionRetries; retry++)\n                {\n                    tr = new TFramedTransport(new TSocket(myhost, 9160));\n                    TProtocol proto = new TBinaryProtocol(tr);\n//                    System.out.println(\"creating connection::\");\n                    client = new Cassandra.Client(proto);\n                    try\n                    {\n                        tr.open();\n                        connectexception = null;\n                        break;\n                    }\n                    catch (Exception e)\n                    {\n                        connectexception = e;\n                        logger.error(e);\n                    }\n                    try\n                    {\n                        Thread.sleep(1000);\n                    }\n                    catch (InterruptedException e)\n                    {\n                        logger.error(e);\n                    }\n\n                }\n            }\n\n            if (connectexception != null)\n            {\n                logger.info(\"Unable to connect to \" + myhost + \" after \" + ConnectionRetries + \" tries\");\n                throw new DBException(connectexception);\n            }\n\n            if (username != null && password != null)\n            {\n                Map<String, String> cred = new HashMap<String, String>();\n                cred.put(\"username\", username);\n                cred.put(\"password\", password);\n                AuthenticationRequest req = new AuthenticationRequest(cred);\n                try\n                {\n                    client.login(req);\n                }\n                catch (Exception e)\n                {\n                    e.printStackTrace();\n                    logger.info(e);\n                    throw new DBException(e);\n                }\n            }\n            client.set_keyspace(_table);\n        }\n        catch (Exception e)\n        {\n            logger.info(e);\n\n        }\n    }\n\n    /**\n     * Cleanup any state for this DB. Called once per DB instance; there is one\n     * DB instance per client thread.\n     */\n    public void cleanup() throws DBException\n    {\n        // tr.close();\n    }\n\n    /**\n     * Read a record from the database. Each field/value pair from the result\n     * will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to read.\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A HashMap of field/value pairs for the result\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result)\n    {\n        // System.out.println(key);\n//        System.out.println(\"key:\" + key);\n//        System.out.println(\"_table\" + _table);\n//        System.out.println(\"table\" + table);\n\n        /*\n         * if (!_table.equals(table)) {\n         */\n        try\n        {\n            /*\n             * _table = table;\n             */}\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n        // }\n\n        try\n        {\n            SlicePredicate predicate = new SlicePredicate();\n            if (fields == null)\n            {\n//                SlicePredicate predicate = new SlicePredicate();\n                predicate = new SlicePredicate();\n                predicate.setSlice_range(new SliceRange(Bytes.EMPTY.getBytes(), Bytes.EMPTY.getBytes(), true, 10000));\n\n//                predicate = new SlicePredicate().setSlice_range(new SliceRange(emptyByteBuffer, emptyByteBuffer, false,\n//                        1000000));\n\n            }\n            else\n            {\n                ArrayList<ByteBuffer> fieldlist = new ArrayList<ByteBuffer>(fields.size());\n                for (String s : fields)\n                {\n                    fieldlist.add(ByteBuffer.wrap(s.getBytes(\"UTF-8\")));\n                }\n\n                predicate = new SlicePredicate().setColumn_names(fieldlist);\n            }\n\n            List<ColumnOrSuperColumn> results = client.get_slice(ByteBuffer.wrap(key.getBytes(\"UTF-8\")), parent,\n                    predicate, readConsistencyLevel);\n\n            if (_debug)\n            {\n                System.out.print(\"Reading key: \" + key);\n            }\n\n            Column column;\n            String name;\n            ByteIterator value;\n            \n            assert results != null && !results.isEmpty();\n/*            for (ColumnOrSuperColumn oneresult : results)\n            {\n\n                column = oneresult.column;\n                name = new String(column.name.array(), column.name.position() + column.name.arrayOffset(),\n                        column.name.remaining());\n                value = new ByteArrayByteIterator(column.value.array(), column.value.position()\n                        + column.value.arrayOffset(), column.value.remaining());\n\n                result.put(name, value);\n\n                if (_debug)\n                {\n                    logger.info(\"(\" + name + \"=\" + value + \")\");\n                }\n            }\n*/\n            if (_debug)\n            {\n                logger.info(\"ConsistencyLevel=\" + readConsistencyLevel.toString());\n            }\n\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n\n        }\n    }\n\n    /**\n     * Perform a range scan for a set of records in the database. Each\n     * field/value pair from the result will be stored in a HashMap.\n     * \n     * @param table\n     *            The name of the table\n     * @param startkey\n     *            The record key of the first record to read.\n     * @param recordcount\n     *            The number of records to read\n     * @param fields\n     *            The list of fields to read, or null for all of them\n     * @param result\n     *            A Vector of HashMaps, where each HashMap is a set field/value\n     *            pairs for one record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int scan(String table, String startkey, int recordcount, Set<String> fields,\n            Vector<HashMap<String, ByteIterator>> result)\n    {\n        if (!_table.equals(table))\n        {\n            try\n            {\n                client.set_keyspace(table);\n                _table = table;\n            }\n            catch (Exception e)\n            {\n                logger.error(e);\n                return Error;\n            }\n        }\n        try\n        {\n            SlicePredicate predicate;\n            if (fields == null)\n            {\n                predicate = new SlicePredicate().setSlice_range(new SliceRange(emptyByteBuffer, emptyByteBuffer, false,\n                        1000000));\n\n            }\n            else\n            {\n                ArrayList<ByteBuffer> fieldlist = new ArrayList<ByteBuffer>(fields.size());\n                for (String s : fields)\n                {\n                    fieldlist.add(ByteBuffer.wrap(s.getBytes(\"UTF-8\")));\n                }\n\n                predicate = new SlicePredicate().setColumn_names(fieldlist);\n            }\n\n            KeyRange kr = new KeyRange().setStart_key(startkey.getBytes(\"UTF-8\")).setEnd_key(new byte[] {})\n                    .setCount(recordcount);\n\n            List<KeySlice> results = client.get_range_slices(parent, predicate, kr, scanConsistencyLevel);\n\n            if (_debug)\n            {\n                logger.info(\"Scanning startkey: \" + startkey);\n            }\n\n            HashMap<String, ByteIterator> tuple;\n            for (KeySlice oneresult : results)\n            {\n                tuple = new HashMap<String, ByteIterator>();\n\n                Column column;\n                String name;\n                ByteIterator value;\n                for (ColumnOrSuperColumn onecol : oneresult.columns)\n                {\n                    column = onecol.column;\n                    name = new String(column.name.array(), column.name.position() + column.name.arrayOffset(),\n                            column.name.remaining());\n                    value = new ByteArrayByteIterator(column.value.array(), column.value.position()\n                            + column.value.arrayOffset(), column.value.remaining());\n\n                    tuple.put(name, value);\n\n                    if (_debug)\n                    {\n                        logger.info(\"(\" + name + \"=\" + value + \")\");\n                    }\n                }\n\n                result.add(tuple);\n                if (_debug)\n                {\n                    logger.info(\"ConsistencyLevel=\" + scanConsistencyLevel.toString());\n                }\n            }\n\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n\n    }\n\n    /**\n     * Update a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key, overwriting any existing values with the same field name.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to write.\n     * @param values\n     *            A HashMap of field/value pairs to update in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int update(String table, String key, HashMap<String, ByteIterator> values)\n    {\n        return insert(table, key, values);\n//        return Error;\n    }\n\n    /**\n     * Insert a record in the database. Any field/value pairs in the specified\n     * values HashMap will be written into the record with the specified record\n     * key.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to insert.\n     * @param values\n     *            A HashMap of field/value pairs to insert in the record\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int insert(String table, String key, HashMap<String, ByteIterator> values)\n    {\n\n        /*\n         * if (!_table.equals(table)) {\n         */try\n        {\n            client.set_keyspace(_table);\n            // _table = table;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n        /*\n         * }\n         */if (_debug)\n        {\n//            System.out.println(\"Inserting key: \" + key);\n        }\n\n        try\n        {\n            ByteBuffer wrappedKey = ByteBuffer.wrap(key.getBytes(\"UTF-8\"));\n\n            Column col;\n            ColumnOrSuperColumn column;\n            for (Map.Entry<String, ByteIterator> entry : values.entrySet())\n            {\n                col = new Column();\n                col.setName(ByteBuffer.wrap(entry.getKey().getBytes(\"UTF-8\")));\n                col.setValue(ByteBuffer.wrap(entry.getValue().toArray()));\n                col.setTimestamp(System.currentTimeMillis());\n\n                column = new ColumnOrSuperColumn();\n                column.setColumn(col);\n\n                mutations.add(new Mutation().setColumn_or_supercolumn(column));\n            }\n\n            mutationMap.put(column_family, mutations);\n            record.put(wrappedKey, mutationMap);\n\n            client.batch_mutate(record, writeConsistencyLevel);\n\n            mutations.clear();\n            mutationMap.clear();\n            record.clear();\n\n            if (_debug)\n            {\n                logger.info(\"ConsistencyLevel=\" + writeConsistencyLevel.toString());\n            }\n\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    /**\n     * Delete a record from the database.\n     * \n     * @param table\n     *            The name of the table\n     * @param key\n     *            The record key of the record to delete.\n     * @return Zero on success, a non-zero error code on error\n     */\n    public int delete(String table, String key)\n    {\n        if (!_table.equals(table))\n        {\n            try\n            {\n                client.set_keyspace(table);\n                _table = table;\n            }\n            catch (Exception e)\n            {\n                logger.error(e);\n                return Error;\n            }\n        }\n        try\n        {\n            client.remove(ByteBuffer.wrap(key.getBytes(\"UTF-8\")), new ColumnPath(column_family),\n                    System.currentTimeMillis(), deleteConsistencyLevel);\n\n            if (_debug)\n            {\n                logger.info(\"Delete key: \" + key);\n                logger.info(\"ConsistencyLevel=\" + deleteConsistencyLevel.toString());\n            }\n\n            return Ok;\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            return Error;\n        }\n    }\n\n    public static void main(String[] args)\n    {\n        ThriftClient cli = new ThriftClient();\n\n        Properties props = new Properties();\n\n        props.setProperty(\"hosts\", \"localhost\");\n        cli.setProperties(props);\n\n        try\n        {\n            cli.init();\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            System.exit(0);\n        }\n\n        HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();\n        vals.put(\"age\", new StringByteIterator(\"57\"));\n        vals.put(\"middlename\", new StringByteIterator(\"bradley\"));\n        vals.put(\"favoritecolor\", new StringByteIterator(\"blue\"));\n        int res = cli.insert(\"usertable\", \"BrianFrankCooper\", vals);\n        logger.info(\"Result of insert: \" + res);\n\n        HashMap<String, ByteIterator> result = new HashMap<String, ByteIterator>();\n        HashSet<String> fields = new HashSet<String>();\n        fields.add(\"middlename\");\n        fields.add(\"age\");\n        fields.add(\"favoritecolor\");\n        res = cli.read(\"usertable\", \"BrianFrankCooper\", null, result);\n        logger.info(\"Result of read: \" + res);\n        for (String s : result.keySet())\n        {\n            logger.info(\"[\" + s + \"]=[\" + result.get(s) + \"]\");\n        }\n\n        res = cli.delete(\"usertable\", \"BrianFrankCooper\");\n        logger.info(\"Result of delete: \" + res);\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/entities/CouchDBUser.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Vivek Mishra\n * \n */\n@Entity\n@Table(name = \"kunderauser\", schema = \"kundera@kundera_couchdb_pu\")\npublic class CouchDBUser\n{\n\n    @Id\n    private String name;\n\n    @Column\n    private String age;\n\n    @Column\n    private String address;\n\n    @Column\n    private String lname;\n\n    public CouchDBUser()\n    {\n\n    }\n\n    public CouchDBUser(String name, String age, String add, String lname)\n    {\n        this.lname = lname;\n        this.address = add;\n        this.name = name;\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public String getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(String age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    /**\n     * @return the lname\n     */\n    public String getLname()\n    {\n        return lname;\n    }\n\n    /**\n     * @param lname\n     *            the lname to set\n     */\n    public void setLname(String lname)\n    {\n        this.lname = lname;\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/entities/HBaseUser.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Vivek Mishra\n * \n */\n@Entity\n@Table(name = \"kunderauser\", schema = \"kundera@kundera_hbase_pu\")\npublic class HBaseUser\n{\n\n    @Id\n    private String name;\n\n    @Column\n    private String age;\n\n    @Column\n    private String address;\n\n    @Column\n    private String lname;\n\n    public HBaseUser()\n    {\n\n    }\n\n    public HBaseUser(String name, String age, String add, String lname)\n    {\n        this.lname = lname;\n        this.address = add;\n        this.name = name;\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public String getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(String age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    /**\n     * @return the lname\n     */\n    public String getLname()\n    {\n        return lname;\n    }\n\n    /**\n     * @param lname\n     *            the lname to set\n     */\n    public void setLname(String lname)\n    {\n        this.lname = lname;\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/entities/KuduUser.java",
    "content": "/**\n * Copyright 2017 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author karthikp.manchala\n * \n */\n@Entity\n@Table(name = \"kuduuser\", schema = \"kundera@kundera_kudu_pu\")\npublic class KuduUser\n{\n\n    @Id\n    private String name;\n\n    @Column\n    private String age;\n\n    @Column\n    private String address;\n\n    @Column\n    private String lname;\n\n    public KuduUser()\n    {\n\n    }\n\n    public KuduUser(String name, String age, String add, String lname)\n    {\n        this.lname = lname;\n        this.address = add;\n        this.name = name;\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public String getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(String age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    /**\n     * @return the last name\n     */\n    public String getLname()\n    {\n        return lname;\n    }\n\n    /**\n     * @param lname\n     *            the last name to set\n     */\n    public void setLname(String lname)\n    {\n        this.lname = lname;\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/entities/MongoUser.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n *\n */\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"user\", schema = \"kundera@kundera_mongo_pu\")\npublic class MongoUser\n{\n\n    @Id\n    private String name;\n\n    @Column\n    private String age;\n\n    @Column\n    private String address;\n\n    @Column\n    private String lname;\n\n    public MongoUser()\n    {\n\n    }\n\n    public MongoUser(String name, String age, String add, String lname)\n    {\n        this.lname = lname;\n        this.address = add;\n        this.name = name;\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public String getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(String age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    /**\n     * @return the lname\n     */\n    public String getLname()\n    {\n        return lname;\n    }\n\n    /**\n     * @param lname\n     *            the lname to set\n     */\n    public void setLname(String lname)\n    {\n        this.lname = lname;\n    }\n\n}"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/entities/Neo4JUser.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Amresh Singh\n * \n */\n@Entity\n@Table(name = \"user\")\npublic class Neo4JUser\n{\n\n    @Id\n    @Column(name=\"USER_ID\")\n    private String userId;\n\n    @Column(name=\"NAME\")\n    private String name;\n    \n    @Column(name=\"AGE\")\n    private String age;\n\n    @Column(name=\"ADDRESS\")\n    private String address;  \n\n    public Neo4JUser()\n    {\n\n    }\n\n    public Neo4JUser(String userId, String name, String age, String address)\n    {\n        super();\n        this.userId = userId;\n        this.name = name;\n        this.age = age;\n        this.address = address;\n    }   \n\n    /**\n     * @return the userId\n     */\n    public String getUserId()\n    {\n        return userId;\n    }\n\n    /**\n     * @param userId the userId to set\n     */\n    public void setUserId(String userId)\n    {\n        this.userId = userId;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public String getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age the age to set\n     */\n    public void setAge(String age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }  \n\n}"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/entities/OracleNosqlUser.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"kunderauser\", schema = \"OracleNoSqlTests@kundera_oracle_pu\")\npublic class OracleNosqlUser {\n\n\t@Id\n\tprivate String name;\n\n\t@Column\n\tprivate String age;\n\n\t@Column\n\tprivate String address;\n\n\t@Column\n\tprivate String lname;\n\n\tpublic OracleNosqlUser() {\n\n\t}\n\n\tpublic OracleNosqlUser(String name, String age, String add, String lname) {\n\t\tthis.lname = lname;\n\t\tthis.address = add;\n\t\tthis.name = name;\n\t\tthis.age = age;\n\t}\n\n\t/**\n\t * @return the name\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * @param name\n\t *            the name to set\n\t */\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * @return the age\n\t */\n\tpublic String getAge() {\n\t\treturn age;\n\t}\n\n\t/**\n\t * @param age\n\t *            the age to set\n\t */\n\tpublic void setAge(String age) {\n\t\tthis.age = age;\n\t}\n\n\t/**\n\t * @return the address\n\t */\n\tpublic String getAddress() {\n\t\treturn address;\n\t}\n\n\t/**\n\t * @param address\n\t *            the address to set\n\t */\n\tpublic void setAddress(String address) {\n\t\tthis.address = address;\n\t}\n\n\t/**\n\t * @return the lname\n\t */\n\tpublic String getLname() {\n\t\treturn lname;\n\t}\n\n\t/**\n\t * @param lname\n\t *            the lname to set\n\t */\n\tpublic void setLname(String lname) {\n\t\tthis.lname = lname;\n\t}\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/entities/PelopsUser.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"kpelopsuser\", schema = \"kundera@kundera_pelops_pu\")\npublic class PelopsUser\n{\n\n    @Id\n    private String name;\n\n    @Column\n    private String age;\n\n    @Column\n    private String address;\n\n    @Column\n    private String lname;\n\n    public PelopsUser()\n    {\n\n    }\n\n    public PelopsUser(String name, String age, String add, String lname)\n    {\n        this.lname = lname;\n        this.address = add;\n        this.name = name;\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public String getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(String age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    /**\n     * @return the lname\n     */\n    public String getLname()\n    {\n        return lname;\n    }\n\n    /**\n     * @param lname\n     *            the lname to set\n     */\n    public void setLname(String lname)\n    {\n        this.lname = lname;\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/entities/PerformanceNoInfo.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.entities;\n\nimport java.math.BigDecimal;\nimport java.util.Date;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\nimport javax.persistence.Temporal;\nimport javax.persistence.TemporalType;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"PerformanceNo\")\npublic class PerformanceNoInfo\n{\n    @Id\n    @GeneratedValue(strategy = GenerationType.AUTO)\n    @Column(name = \"id\")\n    private int id;\n\n    @Column\n    @Temporal(TemporalType.DATE)\n    private Date date;\n\n    @Column\n    private String clientType;\n\n    @Column\n    private double releaseNo;\n\n    @Column\n    private String testType;\n\n    @Column\n    private int noOfThreads;\n\n    @Column\n    private long noOfOperations;\n\n    @Column\n    private double totalTimeTaken;\n\n    @Column\n    private int runSequence;\n\n    @Column\n    private BigDecimal avgLatency;\n    \n    @Column BigDecimal throughput;\n    \n    \n    /**\n     * @return the date\n     */\n    public Date getDate()\n    {\n        return date;\n    }\n\n    /**\n     * @param date\n     *            the date to set\n     */\n    public void setDate(Date date)\n    {\n        this.date = date;\n    }\n\n    /**\n     * @return the clientType\n     */\n    public String getClientType()\n    {\n        return clientType;\n    }\n\n    /**\n     * @param clientType\n     *            the clientType to set\n     */\n    public void setClientType(String clientType)\n    {\n        this.clientType = clientType;\n    }\n\n    /**\n     * \n     */\n    public PerformanceNoInfo()\n    {\n\n    }\n\n    /**\n     * \n     */\n    public PerformanceNoInfo(Date date, double releaseNo, String clientType, String testType, int noOfThreads,\n            long noOfOperations, double totalTimeTaken, int runSequence)\n    {\n        this.date = date;\n        this.clientType = clientType;\n        this.runSequence = runSequence;\n        this.releaseNo = releaseNo;\n        this.testType = testType;\n        this.noOfThreads = noOfThreads;\n        this.noOfOperations = noOfOperations;\n        this.totalTimeTaken = totalTimeTaken;\n    }\n\n    /**\n     * @return the releaseNo\n     */\n    public double getReleaseNo()\n    {\n        return releaseNo;\n    }\n\n    /**\n     * @param releaseNo\n     *            the releaseNo to set\n     */\n    public void setReleaseNo(double releaseNo)\n    {\n        this.releaseNo = releaseNo;\n    }\n\n    /**\n     * @return the testType\n     */\n    public String getTestType()\n    {\n        return testType;\n    }\n\n    /**\n     * @param testType\n     *            the testType to set\n     */\n    public void setTestType(String testType)\n    {\n        this.testType = testType;\n    }\n\n    /**\n     * @return the noOfThreads\n     */\n    public int getNoOfThreads()\n    {\n        return noOfThreads;\n    }\n\n    /**\n     * @param noOfThreads\n     *            the noOfThreads to set\n     */\n    public void setNoOfThreads(int noOfThreads)\n    {\n        this.noOfThreads = noOfThreads;\n    }\n\n    /**\n     * @return the noOfOperations\n     */\n    public long getNoOfOperations()\n    {\n        return noOfOperations;\n    }\n\n    /**\n     * @param noOfOperations\n     *            the noOfOperations to set\n     */\n    public void setNoOfOperations(long noOfOperations)\n    {\n        this.noOfOperations = noOfOperations;\n    }\n\n    /**\n     * @return the totalTimeTaken\n     */\n    public double getTotalTimeTaken()\n    {\n        return totalTimeTaken;\n    }\n\n    /**\n     * @param totalTimeTaken\n     *            the totalTimeTaken to set\n     */\n    public void setTotalTimeTaken(double totalTimeTaken)\n    {\n        this.totalTimeTaken = totalTimeTaken;\n    }\n\n    /**\n     * @return the runSequence\n     */\n    public int getRunSequence()\n    {\n        return runSequence;\n    }\n\n    /**\n     * @param runSequence\n     *            the runSequence to set\n     */\n    public void setRunSequence(int runSequence)\n    {\n        this.runSequence = runSequence;\n    }\n\n    /**\n     * @return the id\n     */\n    public int getId()\n    {\n        return id;\n    }\n\n    /**\n     * @param id\n     *            the id to set\n     */\n    public void setId(int id)\n    {\n        this.id = id;\n    }\n\n    public BigDecimal getAvgLatency()\n    {\n        return avgLatency;\n    }\n\n    public void setAvgLatency(BigDecimal avgLatency)\n    {\n        this.avgLatency = avgLatency;\n    }\n\n    public BigDecimal getThroughput()\n    {\n        return throughput;\n    }\n\n    public void setThroughput(BigDecimal throughput)\n    {\n        this.throughput = throughput;\n    }\n\n    \n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/entities/RedisUser.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.ycsb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"user\", schema = \"0@kundera_redis_pu\")\npublic class RedisUser\n{\n\n    @Id\n    private String name;\n\n    @Column\n    private String age;\n\n    @Column\n    private String address;\n\n    @Column\n    private String lname;\n\n    public RedisUser()\n    {\n\n    }\n\n    public RedisUser(String name, String age, String add, String lname)\n    {\n        this.lname = lname;\n        this.address = add;\n        this.name = name;\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public String getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(String age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    /**\n     * @return the lname\n     */\n    public String getLname()\n    {\n        return lname;\n    }\n\n    /**\n     * @param lname\n     *            the lname to set\n     */\n    public void setLname(String lname)\n    {\n        this.lname = lname;\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/entities/ThriftUser.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.entities;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.Id;\nimport javax.persistence.Table;\n\n/**\n * @author Kuldeep Mishra\n * \n */\n@Entity\n@Table(name = \"kthriftuser\", schema = \"kundera@kundera_thrift_pu\")\npublic class ThriftUser\n{\n\n    @Id\n    private String name;\n\n    @Column\n    private String age;\n\n    @Column\n    private String address;\n\n    @Column\n    private String lname;\n\n    public ThriftUser()\n    {\n\n    }\n\n    public ThriftUser(String name, String age, String add, String lname)\n    {\n        this.lname = lname;\n        this.address = add;\n        this.name = name;\n        this.age = age;\n    }\n\n    /**\n     * @return the name\n     */\n    public String getName()\n    {\n        return name;\n    }\n\n    /**\n     * @param name\n     *            the name to set\n     */\n    public void setName(String name)\n    {\n        this.name = name;\n    }\n\n    /**\n     * @return the age\n     */\n    public String getAge()\n    {\n        return age;\n    }\n\n    /**\n     * @param age\n     *            the age to set\n     */\n    public void setAge(String age)\n    {\n        this.age = age;\n    }\n\n    /**\n     * @return the address\n     */\n    public String getAddress()\n    {\n        return address;\n    }\n\n    /**\n     * @param address\n     *            the address to set\n     */\n    public void setAddress(String address)\n    {\n        this.address = address;\n    }\n\n    /**\n     * @return the lname\n     */\n    public String getLname()\n    {\n        return lname;\n    }\n\n    /**\n     * @param lname\n     *            the lname to set\n     */\n    public void setLname(String lname)\n    {\n        this.lname = lname;\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/runner/CassandraRunner.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.runner;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.commons.configuration.Configuration;\n\nimport com.impetus.kundera.ycsb.utils.CassandraOperationUtils;\nimport com.impetus.kundera.ycsb.utils.MailUtils;\nimport common.Logger;\n\n/**\n * @author Vivek Mishra\n * \n */\npublic class CassandraRunner extends YCSBRunner\n{\n    private CassandraOperationUtils operationUtils;\n\n    private String cassandraServerLocation;\n\n    private static Logger logger = Logger.getLogger(CassandraRunner.class);\n\n    public CassandraRunner(final String propertyFile, final Configuration config)\n    {\n        super(propertyFile,config);\n        this.cassandraServerLocation = config.getString(\"server.location\");\n        operationUtils = new CassandraOperationUtils();\n    }\n\n    @Override\n    public void startServer(boolean performDelete, Runtime runTime)\n    {\n        try\n        {\n            operationUtils.startCassandraServer(performDelete, runTime, cassandraServerLocation);\n            \n            // When running with t. no need to load up these.\n            \n            if(performDelete)\n            {\n            \toperationUtils.dropKeyspace(schema,host,port);\n            }\n         \n            /*if (!currentClient.equalsIgnoreCase(\"com.impetus.kundera.ycsb.benchmark.HectorClient\"))\n            {*/\n            \t// When running with \"t\" option . no need to load up these.\n                operationUtils.createKeysapce(schema, performDelete, host, columnFamilyOrTable,port);\n//            }\n        }\n        catch (IOException e)\n        {\n            logger.error(e);\n            throw new RuntimeException(e);\n        }\n        catch (InterruptedException e)\n        {\n            logger.error(e);\n            throw new RuntimeException(e);\n        }\n\n    }\n\n    @Override\n    public void stopServer(Runtime runTime)\n    {\n    \t// No need to run with \"t\" option.\n    \t\n        try\n        {\n            operationUtils.stopCassandraServer(false, runTime);\n        }\n        catch (IOException e)\n        {\n            logger.error(e);\n            throw new RuntimeException(e);\n        }\n        catch (InterruptedException e)\n        {\n            logger.error(e);\n            throw new RuntimeException(e);\n        }\n\n    }\n\n    protected void sendMail()\n    {\n        Map<String, Double> delta = new HashMap<String, Double>();\n        double kunderaPelopsToPelopsDelta = 0.0;\n        double kunderaThriftToThriftDelta = 0.0;\n        if (timeTakenByClient.get(clients[1]) != null && timeTakenByClient.get(clients[0]) != null)\n        {\n\n            kunderaPelopsToPelopsDelta = ((timeTakenByClient.get(clients[1]).doubleValue() - timeTakenByClient.get(\n                    clients[0]).doubleValue())\n                    / timeTakenByClient.get(clients[1]).doubleValue() * 100);\n        }\n\n        if (clients.length ==4 && timeTakenByClient.get(clients[2]) != null && timeTakenByClient.get(clients[3]) != null)\n        {\n            kunderaThriftToThriftDelta = ((timeTakenByClient.get(clients[3]).doubleValue() - timeTakenByClient.get(\n                    clients[2]).doubleValue())\n                    / timeTakenByClient.get(clients[3]).doubleValue() * 100);\n        }\n        // double kunderaPelopsToHectorDelta =\n        // ((timeTakenByClient.get(clients[1]) -\n        // timeTakenByClient.get(clients[4]))\n        // / timeTakenByClient.get(clients[1]) * 100);\n        delta.put(\"kunderaPelopsToPelopsDelta\", kunderaPelopsToPelopsDelta);\n        delta.put(\"kunderaThriftToThriftDelta\", kunderaThriftToThriftDelta);\n        // delta.put(\"kunderaPelopsToHectorDelta\", kunderaPelopsToHectorDelta);\n\n        if ( /*(kunderaPelopsToHectorDelta > 10.00) || */(kunderaPelopsToPelopsDelta > 8.00)\n                || (kunderaThriftToThriftDelta > 8.00))\n        {\n            MailUtils.sendMail(delta, isUpdate ? \"update\" : runType, \"cassandra\");\n        } else\n        {\n            MailUtils.sendPositiveEmail(delta, isUpdate ? \"update\" : runType, \"cassandra\");\n            \n        }\n\n    }\n    \n    \n    public static void main(String g[])\n    {\n        String s = \"abc\";\n        String s2=s;\n        s2=\"cdb\";\n        s=s2;\n        System.out.println(s);\n        System.out.println(s2);\n        \n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/runner/CouchDBRunner.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.runner;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.commons.configuration.Configuration;\n\nimport com.impetus.kundera.ycsb.utils.CouchDBOperationUtils;\nimport com.impetus.kundera.ycsb.utils.MailUtils;\nimport common.Logger;\n\n/**\n * @author Vivek Mishra\n * \n */\npublic class CouchDBRunner extends YCSBRunner\n{\n    private CouchDBOperationUtils operationUtils;\n\n    private static Logger logger = Logger.getLogger(CouchDBRunner.class);\n\n    public CouchDBRunner(final String propertyFile, final Configuration config)\n    {\n        super(propertyFile,config);\n        operationUtils = new CouchDBOperationUtils();\n    }\n\n    @Override\n    public void startServer(boolean performDelete, Runtime runTime)\n    {\n        try\n        {\n            operationUtils.createdatabase(schema, host, port);\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            throw new RuntimeException(e);\n        }\n    }\n\n    @Override\n    public void stopServer(Runtime runTime)\n    {\n    \t// No need to run with \"t\" option.\n    \t\n        try\n        {\n//            operationUtils.dropDatabase(schema, host, port);\n        }\n        catch (Exception e)\n        {\n            logger.error(e);\n            throw new RuntimeException(e);\n        }\n    }\n\n    protected void sendMail()\n    {\n        Map<String, Double> delta = new HashMap<String, Double>();\n        double kunderaPelopsToPelopsDelta = 0.0;\n        double kunderaThriftToThriftDelta = 0.0;\n        if (timeTakenByClient.get(clients[1]) != null && timeTakenByClient.get(clients[0]) != null)\n        {\n\n            kunderaPelopsToPelopsDelta = ((timeTakenByClient.get(clients[1]).doubleValue() - timeTakenByClient.get(\n                    clients[0]).doubleValue())\n                    / timeTakenByClient.get(clients[1]).doubleValue() * 100);\n        }\n\n        if (clients.length ==3 && timeTakenByClient.get(clients[2]) != null && timeTakenByClient.get(clients[3]) != null)\n        {\n            kunderaThriftToThriftDelta = ((timeTakenByClient.get(clients[3]).doubleValue() - timeTakenByClient.get(\n                    clients[2]).doubleValue())\n                    / timeTakenByClient.get(clients[3]).doubleValue() * 100);\n        }\n        // double kunderaPelopsToHectorDelta =\n        // ((timeTakenByClient.get(clients[1]) -\n        // timeTakenByClient.get(clients[4]))\n        // / timeTakenByClient.get(clients[1]) * 100);\n        delta.put(\"kunderaPelopsToPelopsDelta\", kunderaPelopsToPelopsDelta);\n        delta.put(\"kunderaThriftToThriftDelta\", kunderaThriftToThriftDelta);\n        // delta.put(\"kunderaPelopsToHectorDelta\", kunderaPelopsToHectorDelta);\n\n        if ( /*(kunderaPelopsToHectorDelta > 10.00) || */(kunderaPelopsToPelopsDelta > 8.00)\n                || (kunderaThriftToThriftDelta > 8.00))\n        {\n            MailUtils.sendMail(delta, isUpdate ? \"update\" : runType, \"cassandra\");\n        } else\n        {\n            MailUtils.sendPositiveEmail(delta, isUpdate ? \"update\" : runType, \"cassandra\");\n            \n        }\n\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/runner/HBaseRunner.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.ycsb.runner;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.commons.configuration.Configuration;\n\nimport com.impetus.kundera.ycsb.utils.HBaseOperationUtils;\nimport com.impetus.kundera.ycsb.utils.MailUtils;\n\n/**\n * @author vivek.mishra\n * \n */\npublic class HBaseRunner extends YCSBRunner\n{\n    private String startHBaseServerCommand;\n\n    private String stopHBaseServerCommand;\n\n    public HBaseRunner(String propertyFile, Configuration config)\n    {\n        super(propertyFile, config);\n        String server = config.getString(\"server.location\");\n        this.startHBaseServerCommand = server+\"start-hbase.sh\";\n        this.stopHBaseServerCommand = \"/root/software/stopServers.sh\";\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.ycsb.runner.YCSBRunner#startServer(boolean,\n     * java.lang.Runtime)\n     */\n    @Override\n    public void startServer(boolean performDelete, Runtime runTime)\n    {\n        if (performDelete)\n        {\n            try\n            {\n                HBaseOperationUtils.startHBaseServer(runTime, startHBaseServerCommand);\n                HBaseOperationUtils utils = new HBaseOperationUtils();\n//                utils.createTable(schema, columnFamilyOrTable);\n                utils.deleteAllTables();\n            }\n            catch (IOException e)\n            {\n                e.printStackTrace();\n            }\n            catch (InterruptedException e)\n            {\n                e.printStackTrace();\n            }\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see\n     * com.impetus.kundera.ycsb.runner.YCSBRunner#stopServer(java.lang.Runtime)\n     */\n    @Override\n    public void stopServer(Runtime runTime)\n    {\n        try\n        {\n            HBaseOperationUtils.stopHBaseServer(stopHBaseServerCommand, runTime);\n        }\n        catch (IOException e)\n        {\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            e.printStackTrace();\n        }\n    }\n\n    /*\n     * (non-Javadoc)\n     * \n     * @see com.impetus.kundera.ycsb.runner.YCSBRunner#sendMail()\n     */\n    @Override\n    protected void sendMail()\n    {\n        Map<String, Double> delta = new HashMap<String, Double>();\n\n        delta.put(\"throughput of \" + clients[0] + \" = \", timeTakenByClient.get(clients[0]).doubleValue());\n        delta.put(\"throughput of \" + clients[1] + \" = \", timeTakenByClient.get(clients[1]).doubleValue());\n        double kunderaHBaseToPhoenixDelta = ((timeTakenByClient.get(clients[1]).doubleValue() - timeTakenByClient.get(\n                clients[0]).doubleValue())\n                / timeTakenByClient.get(clients[1]).doubleValue() * 100);\n        delta.put(\"kunderaHBaseToPhoenixDelta ==> \", kunderaHBaseToPhoenixDelta);\n\n        if (kunderaHBaseToPhoenixDelta > 8.00)\n        {\n            MailUtils.sendMail(delta, isUpdate ? \"update\" : runType, \"hbase\");\n        } else\n        {\n            MailUtils.sendPositiveEmail(delta, isUpdate ? \"update\" : runType, \"hbase\");\n            \n        }\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/runner/KuduRunner.java",
    "content": "/**\n * Copyright 2017 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.runner;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.commons.configuration.Configuration;\n\nimport com.impetus.kundera.ycsb.utils.MailUtils;\nimport common.Logger;\n\n/**\n * @author karthikp.manchala\n * \n */\npublic class KuduRunner extends YCSBRunner\n{\n    private String url;\n\n    private static Logger logger = Logger.getLogger(KuduRunner.class);\n\n    public KuduRunner(final String propertyFile, final Configuration config)\n    {\n        super(propertyFile, config);\n        // this.startMongoServerCommand = config.getString(\"server.location\");\n        // operationUtils = new MongoDBOperationUtils();\n        url = \"mongodb://\" + host + \":\" + port;\n    }\n\n    @Override\n    public void startServer(boolean performCleanUp, Runtime runTime)\n    {\n    }\n\n    @Override\n    public void stopServer(Runtime runTime)\n    {\n    }\n\n    protected void sendMail()\n    {\n        Map<String, Double> delta = new HashMap<String, Double>();\n\n        double kunderaMongoToNativeDelta = ((timeTakenByClient.get(clients[1]).doubleValue() - timeTakenByClient.get(\n                clients[0]).doubleValue())\n                / timeTakenByClient.get(clients[1]).doubleValue() * 100);\n        delta.put(\"kunderaMongoToNativeDelta\", kunderaMongoToNativeDelta);\n\n        if (kunderaMongoToNativeDelta > 8.0)\n        {\n            MailUtils.sendMail(delta, isUpdate ? \"update\" : runType, \"mongoDb\");\n        }\n        else\n        {\n            MailUtils.sendPositiveEmail(delta, isUpdate ? \"update\" : runType, \"mongoDb\");\n\n        }\n\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/runner/MongoRunner.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.runner;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.commons.configuration.Configuration;\n\nimport com.impetus.kundera.ycsb.utils.MailUtils;\nimport com.impetus.kundera.ycsb.utils.MongoDBOperationUtils;\nimport common.Logger;\n\n/**\n * @author vivek mishra\n * \n */\npublic class MongoRunner extends YCSBRunner\n{\n    private static MongoDBOperationUtils operationUtils;\n\n    private String url;\n\n    private String startMongoServerCommand;\n\n    private static Logger logger = Logger.getLogger(CassandraRunner.class);\n\n    public MongoRunner(final String propertyFile, final Configuration config)\n    {\n        super(propertyFile, config);\n        this.startMongoServerCommand = config.getString(\"server.location\");\n        operationUtils = new MongoDBOperationUtils();\n        url = \"mongodb://\" + host + \":\" + port;\n    }\n\n    @Override\n    public void startServer(boolean performCleanUp, Runtime runTime)\n    {\n        try\n        {\n            operationUtils.startMongoServer(runTime, startMongoServerCommand);\n        }\n        catch (IOException e1)\n        {\n            // TODO Auto-generated catch block\n            e1.printStackTrace();\n        }\n        catch (InterruptedException e1)\n        {\n            // TODO Auto-generated catch block\n            e1.printStackTrace();\n        }\n        if (performCleanUp)\n        {\n            try\n            {\n                operationUtils.cleanDatabase(url, schema);\n            }\n            catch (IOException e)\n            {\n                logger.error(e);\n                throw new RuntimeException(e);\n            }\n            catch (InterruptedException e)\n            {\n                logger.error(e);\n                throw new RuntimeException(e);\n            }\n        }\n    }\n\n    @Override\n    public void stopServer(Runtime runTime)\n    {\n        try\n        {\n            operationUtils.stopMongoServer(runTime);\n        }\n        catch (IOException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n    }\n\n    protected void sendMail()\n    {\n        Map<String, Double> delta = new HashMap<String, Double>();\n\n        double kunderaMongoToNativeDelta = ((timeTakenByClient.get(clients[1]).doubleValue() - timeTakenByClient.get(\n                clients[0]).doubleValue())\n                / timeTakenByClient.get(clients[1]).doubleValue() * 100);\n        delta.put(\"kunderaMongoToNativeDelta\", kunderaMongoToNativeDelta);\n\n        if (kunderaMongoToNativeDelta > 8.0)\n        {\n            MailUtils.sendMail(delta, isUpdate ? \"update\" : runType, \"mongoDb\");\n        } else\n        {\n            MailUtils.sendPositiveEmail(delta, isUpdate ? \"update\" : runType, \"mongoDb\");\n            \n        }\n\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/runner/Neo4jRunner.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.runner;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.commons.configuration.Configuration;\n\nimport com.impetus.kundera.ycsb.utils.MailUtils;\nimport common.Logger;\n\n/**\n * @author vivek mishra\n * \n */\npublic class Neo4jRunner extends YCSBRunner\n{\n   \n    private static Logger logger = Logger.getLogger(RedisRunner.class);\n\n    public Neo4jRunner(final String propertyFile, final Configuration config)\n    {\n        super(propertyFile,config);\n    }\n\n    @Override\n    public void startServer(boolean performCleanup,Runtime runTime)\n    {\n        // do nothing.\n    }\n\n    @Override\n    public void stopServer(Runtime runTime)\n    {\n        // Do nothing.\n    }\n\n    @Override\n    protected void sendMail()\n    {\n        Map<String, Double> delta = new HashMap<String, Double>();\n\n        double kunderaNativeToNativeDelta = ((timeTakenByClient.get(clients[1]).doubleValue() - timeTakenByClient.get(clients[0]).doubleValue())\n                / timeTakenByClient.get(clients[1]).doubleValue() * 100);\n        delta.put(\"KunderaNeo4JToNativeDelta\", kunderaNativeToNativeDelta);\n\n        if (kunderaNativeToNativeDelta > 8.00)\n        {\n            MailUtils.sendMail(delta, isUpdate ? \"update\" : runType, \"neo4j\");\n        } else\n        {\n            MailUtils.sendPositiveEmail(delta, isUpdate ? \"update\" : runType, \"neo4j\");\n        }\n\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/runner/OracleNosqlRunner.java",
    "content": "/**\n * Copyright 2013 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.runner;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.commons.configuration.Configuration;\n\nimport com.impetus.kundera.ycsb.utils.MailUtils;\nimport com.impetus.kundera.ycsb.utils.OracleNosqlOperationUtils;\n\n/**\n * @author Kuldeep mishra\n * \n */\npublic class OracleNosqlRunner extends YCSBRunner\n{\n    private static OracleNosqlOperationUtils operationUtils;\n\n    public OracleNosqlRunner(final String propertyFile, final Configuration config)\n    {\n        super(propertyFile, config);\n        operationUtils = new OracleNosqlOperationUtils();\n    }\n\n    @Override\n    public void startServer(boolean performCleanup, Runtime runTime)\n    {\n        try\n        {\n            operationUtils.cleanAndStartOracleServer(runTime);\n        }\n        catch (IOException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n    }\n\n    @Override\n    public void stopServer(Runtime runTime)\n    {\n        try\n        {\n            operationUtils.stopOracleServer(runTime);\n        }\n        catch (IOException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n    }\n\n    @Override\n    protected void sendMail()\n    {\n        Map<String, Double> delta = new HashMap<String, Double>();\n\n        double kunderaOracleToNativeDelta = ((timeTakenByClient.get(clients[1]).doubleValue() - timeTakenByClient.get(\n                clients[0]).doubleValue())\n                / timeTakenByClient.get(clients[1]).doubleValue() * 100);\n        delta.put(\"kunderaOracleToNativeDelta\", kunderaOracleToNativeDelta);\n\n        if (kunderaOracleToNativeDelta > 10.00)\n        {\n            MailUtils.sendMail(delta, isUpdate ? \"update\" : runType, \"oracle\");\n        }\n        else\n        {\n            MailUtils.sendPositiveEmail(delta, isUpdate ? \"update\" : runType, \"oracle\");\n        }\n\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/runner/RedisRunner.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.runner;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.commons.configuration.Configuration;\n\nimport com.impetus.kundera.ycsb.utils.MailUtils;\nimport com.impetus.kundera.ycsb.utils.RedisOperationUtils;\nimport common.Logger;\n\n/**\n * @author vivek mishra\n * \n */\npublic class RedisRunner extends YCSBRunner\n{\n    private static RedisOperationUtils operationUtils;\n\n    private String redisServerLocation;\n\n    private static Logger logger = Logger.getLogger(RedisRunner.class);\n\n    public RedisRunner(final String propertyFile, final Configuration config)\n    {\n        super(propertyFile, config);\n        this.redisServerLocation = config.getString(\"server.location\");\n        operationUtils = new RedisOperationUtils();\n    }\n\n    @Override\n    public void startServer(boolean performCleanup, Runtime runTime)\n    {\n        try\n        {\n            operationUtils.startRedisServer(runTime, redisServerLocation);\n        }\n        catch (IOException e)\n        {\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            e.printStackTrace();\n        }\n    }\n\n    @Override\n    public void stopServer(Runtime runTime)\n    {\n        try\n        {\n            operationUtils.stopRedisServer(runTime);\n        }\n        catch (IOException e)\n        {\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            e.printStackTrace();\n        }\n    }\n\n    @Override\n    protected void sendMail()\n    {\n        Map<String, Double> delta = new HashMap<String, Double>();\n\n        double kunderaRedisToJedisDelta = ((timeTakenByClient.get(clients[1]).doubleValue() - timeTakenByClient.get(\n                clients[0]).doubleValue())\n                / timeTakenByClient.get(clients[1]).doubleValue() * 100);\n        delta.put(\"kunderaRedisToJedisDelta\", kunderaRedisToJedisDelta);\n\n        if (kunderaRedisToJedisDelta > 10.00)\n        {\n            MailUtils.sendMail(delta, isUpdate ? \"update\" : runType, \"redis\");\n        }\n        else\n        {\n            MailUtils.sendPositiveEmail(delta, isUpdate ? \"update\" : runType, \"redis\");\n        }\n\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/runner/YCSBRunner.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.runner;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.math.BigDecimal;\nimport java.math.MathContext;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.apache.commons.configuration.Configuration;\n\nimport com.impetus.kundera.ycsb.entities.PerformanceNoInfo;\nimport com.impetus.kundera.ycsb.utils.HibernateCRUDUtils;\nimport common.Logger;\n\n/**\n * @author vivek.mishra\n * \n */\npublic abstract class YCSBRunner\n{\n\n    private HibernateCRUDUtils crudUtils;\n\n    protected String schema;\n\n    protected String columnFamilyOrTable;\n\n    private String clientjarlocation;\n\n    private String ycsbJarLocation;\n\n    private String propertyFile;\n\n    protected int noOfThreads;\n\n    protected String runType;\n\n    protected double releaseNo;\n\n    protected String host;\n\n    protected int port;\n\n    protected String[] clients;\n\n    protected String workLoad;\n\n    protected String currentClient;\n\n    protected String password;\n\n    protected boolean isUpdate;\n\n    protected Map<String, BigDecimal> timeTakenByClient = new HashMap<String, BigDecimal>();\n\n    private static Logger logger = Logger.getLogger(YCSBRunner.class);\n\n    public YCSBRunner(final String propertyFile, final Configuration config)\n    {\n        this.propertyFile = propertyFile;\n        ycsbJarLocation = config.getString(\"ycsbjar.location\");\n        clientjarlocation = config.getString(\"clientjar.location\");\n        host = config.getString(\"hosts\");\n        schema = config.getString(\"schema\");\n        columnFamilyOrTable = config.getString(\"columnfamilyOrTable\");\n        releaseNo = config.getDouble(\"release.no\");\n        runType = config.getString(\"run.type\", \"load\");\n        port = config.getInt(\"port\");\n        password = config.getString(\"password\");\n        clients = config.getStringArray(\"clients\");\n        isUpdate = config.containsKey(\"update\");\n        crudUtils = new HibernateCRUDUtils();\n    }\n\n    public void run(final String workLoad, final int threadCount) throws IOException\n    {\n        int runCounter = crudUtils.getMaxRunSequence(new Date(), runType);\n        runCounter = runCounter + 1;\n        noOfThreads = threadCount;\n        // id column of performanceNoInfo table\n        Date id = new Date();\n\n        int counter = 1;\n        for (String client : clients)\n        {\n            currentClient = client;\n            if (clientjarlocation != null && ycsbJarLocation != null && client != null && runType != null\n                    && host != null && schema != null && columnFamilyOrTable != null)\n            {\n                Runtime runtime = Runtime.getRuntime();\n                counter++;\n                String runCommand = getCommandString(client, workLoad);\n\n                logger.info(runCommand);\n                double totalTime = 0.0;\n                long noOfOperations = 0;\n\n                Process process = runtime.exec(runCommand);\n\n                InputStream er = process.getErrorStream();\n                InputStreamReader esr = new InputStreamReader(er);\n                BufferedReader ebr = new BufferedReader(esr);\n                String line;\n                while ((line = ebr.readLine()) != null)\n                {\n                    logger.debug(line);\n                }\n\n                InputStream is = process.getInputStream();\n                InputStreamReader isr = new InputStreamReader(is);\n                BufferedReader br = new BufferedReader(isr);\n                BigDecimal avgLatency = null;\n                BigDecimal throughput = null;\n\n                boolean processed = false;\n                while ((line = br.readLine()) != null)\n                {\n                    logger.debug(line);\n\n                    processed = true;\n                    if (line.contains(\"RunTime\"))\n                    {\n                        totalTime = Double.parseDouble(line.substring(line.lastIndexOf(\", \") + 2));\n                        logger.info(\"Total time taken \" + totalTime);\n                    }\n                    if (line.contains(\"Operations\") && noOfOperations == 0)\n                    {\n                        noOfOperations = Long.parseLong(line.substring(line.lastIndexOf(\", \") + 2));\n                        logger.info(\"Total no of oprations \" + noOfOperations);\n                    }\n                    if (line.contains(\"Throughput\"))\n                    {\n\n                        throughput = new BigDecimal(line.substring(line.lastIndexOf(\", \") + 2));\n                        logger.info(\"Throughput(ops/sec) \" + line);\n                    }\n                    if (line.contains(\"AverageLatency\"))\n                    {\n                        if (avgLatency == null)\n                        {\n                            avgLatency = new BigDecimal(line.substring(line.lastIndexOf(\", \") + 2));\n                            logger.info(\"AverageLatency \" + line);\n                        }\n                    }\n                    /*\n                     * if(line.contains(\"MinLatency\")) {\n                     * logger.info(\"MinLatency \" + line); }\n                     * if(line.contains(\"MaxLatency\")) {\n                     * logger.info(\"MaxLatency \" + line); }\n                     */\n                    // if(!(line.contains(\"CLEANUP\") || line.contains(\"UPDATE\")\n                    // || line.contains(\"INSERT\") )){\n                    // logger.info(line);\n                    // }\n                }\n\n                if (!processed)\n                {\n                    is = process.getErrorStream();\n                    isr = new InputStreamReader(is);\n                    br = new BufferedReader(isr);\n                    line = null;\n                    while ((line = br.readLine()) != null)\n                    {\n                        logger.info(line);\n\n                    }\n                    throw new RuntimeException(\"Error while processing\");\n                }\n\n                PerformanceNoInfo info = new PerformanceNoInfo(id, releaseNo,\n                        client.substring(client.lastIndexOf(\".\") + 1), runType, noOfThreads, noOfOperations, totalTime,\n                        runCounter);\n\n                if (avgLatency != null)\n                {\n                    info.setAvgLatency(avgLatency.round(MathContext.DECIMAL32));\n                }\n\n                if (throughput != null)\n                {\n                    info.setThroughput(throughput.round(MathContext.DECIMAL32));\n                }\n                crudUtils.persistInfo(info);\n                timeTakenByClient.put(client, throughput);\n            }\n        }\n\n        sendMail();\n    }\n\n    protected String getCommandString(String clazz, String workLoad)\n    {\n        StringBuilder command = new StringBuilder(\"java -Xms512M -Xmx2048M -cp \");\n        command.append(clientjarlocation);\n        command.append(\":\");\n        command.append(ycsbJarLocation);\n        command.append(\" com.yahoo.ycsb.Client -db \");\n        command.append(clazz);\n        command.append(\" -s -P \");\n        command.append(workLoad);\n        command.append(\" -P \");\n        command.append(propertyFile);\n        if (noOfThreads > 1)\n        {\n            command.append(\" -threads \");\n            command.append(noOfThreads);\n        }\n        command.append(\" -\");\n        command.append(runType);\n\n        return command.toString();\n    }\n\n    public abstract void startServer(boolean performDelete, Runtime runTime);\n\n    public abstract void stopServer(Runtime runTime);\n\n    protected abstract void sendMail();\n\n    /**\n     * If multiple clients are running, clear data for first time but only in\n     * case of load.\n     * \n     * @param counter\n     *            client counter\n     * @return true, if delete needs to be performed, else false.s\n     */\n    private boolean performDelete(int counter)\n    {\n        if (runType.equals(\"load\"))\n        {\n            return counter == 1;\n        }\n\n        return false;\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/utils/CassandraOperationUtils.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.utils;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\nimport org.apache.cassandra.thrift.Cassandra;\nimport org.apache.cassandra.thrift.CfDef;\nimport org.apache.cassandra.thrift.InvalidRequestException;\nimport org.apache.cassandra.thrift.KsDef;\nimport org.apache.cassandra.thrift.NotFoundException;\nimport org.apache.cassandra.thrift.SchemaDisagreementException;\nimport org.apache.thrift.TException;\nimport org.apache.thrift.protocol.TBinaryProtocol;\nimport org.apache.thrift.protocol.TProtocol;\nimport org.apache.thrift.transport.TFramedTransport;\nimport org.apache.thrift.transport.TSocket;\nimport org.apache.thrift.transport.TTransport;\nimport org.apache.thrift.transport.TTransportException;\n\nimport common.Logger;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class CassandraOperationUtils\n{\n\n    private Cassandra.Client cassandra_client;\n\n    private static Logger logger = Logger.getLogger(CassandraOperationUtils.class);\n\n    private static Runtime runTime;\n\n    /**\n     * Start mongo server.\n     * \n     * @param args\n     * \n     * @param runtime\n     *            the runtime\n     * @return the process\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws InterruptedException\n     */\n    public void startCassandraServer(Boolean performDeleteData, Runtime runtime, String startCassandraServerCommand)\n            throws IOException, InterruptedException\n    {\n        logger.info(\"Starting casssandra server ...........\");\n        this.runTime = runtime;\n        while (checkOnProcess(runtime))\n        {\n            stopCassandraServer(performDeleteData, runtime);\n            TimeUnit.SECONDS.sleep(2);\n        }\n\n        if (performDeleteData)\n        {\n            runtime.exec(\"rm -rf /var/lib/cassandra/*\").waitFor();\n            runtime.exec(\"mkdir /var/lib/cassandra/\").waitFor();\n            runtime.exec(\"chmod 777 -R /var/lib/cassandra/\").waitFor();\n        }\n        runtime.exec(startCassandraServerCommand).waitFor();\n        TimeUnit.SECONDS.sleep(5);\n        while (!checkOnProcess(runtime))\n        {\n            TimeUnit.SECONDS.sleep(2);\n        }\n        logger.info(\"started..............\");\n    }\n\n    /**\n     * Stop mongo server.\n     * \n     * @param runtime\n     *            the runtime\n     * @param br\n     *            the br\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws InterruptedException\n     */\n    public void stopCassandraServer(Boolean performDeleteData, Runtime runtime) throws IOException,\n            InterruptedException\n    {\n        logger.info(\"Stoping casssandra server..\");\n        this.runTime = runtime;\n        Process process = runtime.exec(\"jps\");\n        InputStream is = process.getInputStream();\n        InputStreamReader isr = new InputStreamReader(is);\n        BufferedReader br = new BufferedReader(isr);\n\n        String line = null;\n        while ((line = br.readLine()) != null)\n        {\n            if (line.contains(\"CassandraDaemon\"))\n            {\n                int idx;\n                idx = line.indexOf(\"CassandraDaemon\");\n\n                runtime.exec(\"kill -9 \" + line.substring(0, idx - 1));\n                // logger.info(\"Killed process \" + line.substring(0, idx\n                // - 1));\n                TimeUnit.SECONDS.sleep(5);\n                if (performDeleteData)\n                {\n                    deleteCassandraFolders(\"/var/lib/cassandra/data/\");\n                    deleteCassandraFolders(\"/var/lib/cassandra/data/system/\");\n                    deleteCassandraFolders(\"/var/lib/cassandra/commitlog/\");\n                    deleteCassandraFolders(\"/var/lib/cassandra/saved_caches/\");\n                    deleteCassandraFolders(\"/var/log/cassandra/\");\n                }\n            }\n        }\n\n        logger.info(\"stopped..............\");\n    }\n\n    public void createKeysapce(String keyspace, boolean performCleanup, String host, String columnFamily, int port)\n            throws InterruptedException, IOException\n    {\n        logger.info(\"creating keyspace \" + keyspace + \" and column family \" + columnFamily);\n        cassandra_client = null;\n        if (cassandra_client == null)\n        {\n            initiateClient(host, this.runTime, port);\n        }\n        KsDef ksDef = null;\n\n        try\n        {\n            ksDef = cassandra_client.describe_keyspace(keyspace);\n            if (performCleanup)\n            {\n                dropKeyspace(keyspace, host, port);\n                createKeyspaceAndColumnFamily(keyspace, columnFamily, ksDef);\n            }\n        }\n        catch (NotFoundException e)\n        {\n            createKeyspaceAndColumnFamily(keyspace, columnFamily, ksDef);\n        }\n\n        catch (InvalidRequestException e)\n        {\n            logger.error(e);\n        }\n        catch (TException e)\n        {\n            logger.error(e);\n        }\n\n        logger.info(\"created keyspace \" + keyspace + \" and column family \" + columnFamily);\n        TimeUnit.SECONDS.sleep(3);\n\n    }\n\n    /**\n     * @param keyspace\n     * @param columnFamily\n     */\n    private void createKeyspaceAndColumnFamily(String keyspace, String columnFamily, KsDef ksDef)\n    {\n\n        List<CfDef> cfDefs = new ArrayList<CfDef>();\n        CfDef cfDef = new CfDef(keyspace, columnFamily); // thrift client.\n        cfDef.setDefault_validation_class(\"UTF8Type\");\n        cfDef.setKey_validation_class(\"UTF8Type\");\n        cfDef.setComparator_type(\"UTF8Type\");\n\n        CfDef cfDef1 = new CfDef(keyspace, \"kthrift\" + columnFamily); // kundera\n                                                                      // thrift\n                                                                      // client.\n        cfDef1.setDefault_validation_class(\"UTF8Type\");\n        cfDef1.setKey_validation_class(\"UTF8Type\");\n        cfDef1.setComparator_type(\"UTF8Type\");\n\n        CfDef cfDef2 = new CfDef(keyspace, \"kpelops\" + columnFamily); // kundera\n                                                                      // pelops\n                                                                      // client.\n        cfDef2.setDefault_validation_class(\"UTF8Type\");\n        cfDef2.setKey_validation_class(\"UTF8Type\");\n        cfDef2.setComparator_type(\"UTF8Type\");\n\n        CfDef cfDef3 = new CfDef(keyspace, \"pelops\" + columnFamily); // pelops\n                                                                     // client.\n        cfDef3.setDefault_validation_class(\"UTF8Type\");\n        cfDef3.setKey_validation_class(\"UTF8Type\");\n        cfDef3.setComparator_type(\"UTF8Type\");\n\n        cfDefs.add(cfDef);\n        cfDefs.add(cfDef1);\n        cfDefs.add(cfDef2);\n        cfDefs.add(cfDef3);\n        ksDef = new KsDef(keyspace, \"org.apache.cassandra.locator.SimpleStrategy\", cfDefs);\n        Map<String, String> strategy_options = new HashMap<String, String>();\n        strategy_options.put(\"replication_factor\", \"1\");\n        ksDef.setStrategy_options(strategy_options);\n\n        try\n        {\n            cassandra_client.system_add_keyspace(ksDef);\n        }\n        catch (InvalidRequestException e1)\n        {\n            logger.error(e1);\n        }\n        catch (SchemaDisagreementException e1)\n        {\n            logger.error(e1);\n        }\n        catch (TException e1)\n        {\n            logger.error(e1);\n        }\n    }\n\n    public void dropKeyspace(String keyspace, String host, int port) throws InterruptedException, IOException\n    {\n        cassandra_client = null;\n        if (cassandra_client == null)\n        {\n            initiateClient(host, this.runTime, port);\n        }\n        try\n        {\n            cassandra_client.system_drop_keyspace(keyspace);\n        }\n        catch (InvalidRequestException e)\n        {\n            // logger.error(e);\n        }\n        catch (SchemaDisagreementException e)\n        {\n            logger.error(e);\n        }\n        catch (TException e)\n        {\n            logger.error(e);\n        }\n        TimeUnit.SECONDS.sleep(3);\n\n    }\n\n    private void deleteCassandraFolders(String dir)\n    {\n        // logger.info(\"Cleaning up folder \" + dir);\n        File directory = new File(dir);\n        // Get all files in directory\n        File[] files = directory.listFiles();\n        for (File file : files)\n        {\n            // Delete each file\n            if (!file.delete())\n            {\n                // Failed to delete file\n                // logger.info(\"Failed to delete \" + file);\n            }\n        }\n    }\n\n    /**\n     * @throws IOException\n     */\n    private boolean checkOnProcess(Runtime runtime) throws IOException\n    {\n        Process process = runtime.exec(\"jps\");\n        InputStream is = process.getInputStream();\n        InputStreamReader isr = new InputStreamReader(is);\n        BufferedReader br = new BufferedReader(isr);\n\n        String line = null;\n        boolean found = false;\n        while ((line = br.readLine()) != null)\n        {\n            if (line.contains(\"CassandraDaemon\"))\n            {\n                found = true;\n                break;\n            }\n        }\n\n        return found;\n    }\n\n    private void initiateClient(String host, Runtime runtime, int port) throws InterruptedException, IOException\n    {\n        while (checkOnProcess(runtime))\n        {\n            TSocket socket = new TSocket(host, port);\n            TTransport transport = new TFramedTransport(socket);\n            TProtocol protocol = new TBinaryProtocol(transport, true, true);\n            cassandra_client = new Cassandra.Client(protocol);\n            try\n            {\n                if (!socket.isOpen())\n                {\n                    socket.open();\n                }\n            }\n            catch (TTransportException e)\n            {\n                logger.error(e);\n            }\n            catch (NumberFormatException e)\n            {\n                logger.error(e);\n            }\n            TimeUnit.SECONDS.sleep(3);\n            return;\n        }\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/utils/CouchDBOperationUtils.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.utils;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\nimport org.apache.http.HttpHost;\nimport org.apache.http.HttpRequest;\nimport org.apache.http.HttpRequestInterceptor;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.HttpResponseInterceptor;\nimport org.apache.http.client.ClientProtocolException;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpDelete;\nimport org.apache.http.client.methods.HttpPut;\nimport org.apache.http.conn.scheme.PlainSocketFactory;\nimport org.apache.http.conn.scheme.Scheme;\nimport org.apache.http.conn.scheme.SchemeRegistry;\nimport org.apache.http.conn.scheme.SchemeSocketFactory;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport org.apache.http.impl.conn.PoolingClientConnectionManager;\nimport org.apache.http.params.CoreProtocolPNames;\nimport org.apache.http.protocol.HttpContext;\n\nimport com.impetus.client.couchdb.CouchDBConstants;\nimport com.impetus.client.couchdb.CouchDBUtils;\nimport common.Logger;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class CouchDBOperationUtils\n{\n    private static Logger logger = Logger.getLogger(CouchDBOperationUtils.class);\n\n    private HttpClient httpClient;\n\n    private HttpHost httpHost;\n\n    public void createdatabase(String keyspace, String host, int port) throws URISyntaxException, IOException\n\n    {\n        initiateClient(host, port);\n        URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                CouchDBConstants.URL_SEPARATOR + keyspace.toLowerCase(), null, null);\n\n        HttpPut put = new HttpPut(uri);\n        HttpResponse putRes = null;\n        try\n        {\n            // creating database.\n            logger.info(\"Creating database \" + keyspace);\n            putRes = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));\n        }\n        finally\n        {\n            CouchDBUtils.closeContent(putRes);\n        }\n    }\n\n    public void dropDatabase(String keyspace, String host, int port) throws URISyntaxException,\n            ClientProtocolException, IOException\n    {\n        initiateClient(host, port);\n        URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),\n                CouchDBConstants.URL_SEPARATOR + keyspace.toLowerCase(), null, null);\n\n        HttpDelete delete = new HttpDelete(uri);\n        HttpResponse delReq = null;\n        try\n        {\n            // creating database.\n            logger.info(\"Droping database \" + keyspace);\n            delReq = httpClient.execute(httpHost, delete, CouchDBUtils.getContext(httpHost));\n        }\n        finally\n        {\n            CouchDBUtils.closeContent(delReq);\n        }\n    }\n\n    public HttpClient initiateClient(String host, int port)\n    {\n        if (httpClient == null || httpHost == null)\n        {\n            SchemeSocketFactory ssf = null;\n            ssf = PlainSocketFactory.getSocketFactory();\n            SchemeRegistry schemeRegistry = new SchemeRegistry();\n\n            schemeRegistry.register(new Scheme(\"http\", port, ssf));\n            PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);\n            \n            ccm.setMaxTotal(100);\n//            ccm.setDefaultMaxPerRoute(50);\n            \n            httpClient = new DefaultHttpClient(ccm);\n            httpHost = new HttpHost(host, port);\n\n            try\n            {\n                // Http params\n                httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, \"UTF-8\");\n\n                // request interceptor\n                ((DefaultHttpClient) httpClient).addRequestInterceptor(new HttpRequestInterceptor()\n                {\n                    public void process(final HttpRequest request, final HttpContext context) throws IOException\n                    {\n\n                    }\n                });\n                // response interceptor\n                ((DefaultHttpClient) httpClient).addResponseInterceptor(new HttpResponseInterceptor()\n                {\n                    public void process(final HttpResponse response, final HttpContext context) throws IOException\n                    {\n\n                    }\n                });\n            }\n            catch (Exception e)\n            {\n                throw new IllegalStateException(e);\n            }\n        }\n        return httpClient;\n    }\n}"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/utils/HBaseOperationUtils.java",
    "content": "package com.impetus.kundera.ycsb.utils;\n\nimport java.io.IOException;\n\nimport javax.persistence.PersistenceException;\n\nimport org.apache.hadoop.hbase.HColumnDescriptor;\nimport org.apache.hadoop.hbase.HTableDescriptor;\nimport org.apache.hadoop.hbase.NamespaceDescriptor;\nimport org.apache.hadoop.hbase.TableName;\nimport org.apache.hadoop.hbase.client.Admin;\nimport org.apache.hadoop.hbase.client.Connection;\nimport org.apache.hadoop.hbase.client.ConnectionFactory;\n\nimport common.Logger;\n\npublic final class HBaseOperationUtils\n{\n\n    private Admin admin;\n\n    private static Logger logger = Logger.getLogger(HBaseOperationUtils.class);\n\n    public HBaseOperationUtils()\n    {\n        try\n        {\n            Connection conn  = ConnectionFactory.createConnection();\n            admin = conn.getAdmin();\n        }\n        catch (Exception e)\n        {\n            throw new PersistenceException(e);\n        }\n    }\n\n    public void deleteTable(String name) throws IOException\n    {\n        admin.disableTable(TableName.valueOf(name));\n        admin.deleteTable(TableName.valueOf(name));\n        \n    }\n\n\n    public void createTable(String name, String familyName) throws IOException\n    {\n    \tString tableName = name + \":\" + familyName;\n        if(admin.tableExists(TableName.valueOf(tableName)))\n        {\n            deleteTable(tableName);\n            admin.deleteNamespace(name);\n        }\n        NamespaceDescriptor descriptor = NamespaceDescriptor.create(name).build();\n        admin.createNamespace(descriptor);\n        HTableDescriptor table = new HTableDescriptor(TableName.valueOf(tableName));\n        HColumnDescriptor columnFamily = new HColumnDescriptor(familyName);\n        table.addFamily(columnFamily);\n        admin.createTable(table);\n    }\n\n\n    public void deleteAllTables()\n    {\n        try\n        {\n            admin.disableTables(\".*\");\n            admin.deleteTables(\".*\");\n        }\n        catch (IOException e)\n        {\n            e.printStackTrace();\n        }\n\n    }\n    /**\n     * Start HBase server.\n     * \n     * @param runtime\n     *            the runtime\n     * @return the process\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws InterruptedException\n     */\n    public static void startHBaseServer(Runtime runtime, String startHBaseServerCommand) throws IOException,\n            InterruptedException\n    {\n        logger.info(\"Starting hbase server ...........\");\n        runtime.exec(startHBaseServerCommand);\n        Thread.sleep(40000);\n        logger.info(\"started..............\");\n    }\n\n    /**\n     * Stop HBase server.\n     * \n     * @param runtime\n     *            the runtime\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws InterruptedException\n     */\n    public static void stopHBaseServer(String stopHBaseServerCommand, Runtime runtime) throws IOException,\n            InterruptedException\n    {\n        logger.info(\"Stoping hbase server..\");\n        runtime.exec(stopHBaseServerCommand);\n        Thread.sleep(60000);\n        logger.info(\"stopped..............\");\n    }\n\n    public static void main(String[] args)\n    {\n//        HBaseOperationUtils utils = new HBaseOperationUtils();\n        Runtime runtime = Runtime.getRuntime();\n        String startHBaseServercommand = \"/home/impadmin/software/hbase-0.94.3/bin/start-hbase.sh\";\n        String stopHBaseServercommand = \"/home/impadmin/software/hbase-0.94.3/bin/stop-hbase.sh\";\n        try\n        {\n            HBaseOperationUtils.startHBaseServer(runtime, startHBaseServercommand);\n        }\n        catch (IOException e)\n        {\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            e.printStackTrace();\n        }\n        try\n        {\n            HBaseOperationUtils.stopHBaseServer(stopHBaseServercommand, runtime);\n        }\n        catch (IOException e)\n        {\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            e.printStackTrace();\n        }\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/utils/HibernateCRUDUtils.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.utils;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport javax.persistence.EntityManager;\nimport javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\nimport javax.persistence.Query;\nimport javax.persistence.TemporalType;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class HibernateCRUDUtils\n{\n    private EntityManagerFactory emf;\n\n    public void persistInfo(com.impetus.kundera.ycsb.entities.PerformanceNoInfo info)\n    {\n        // create emf and em.\n        EntityManager em = getEntityManager();\n\n        em.getTransaction().begin();\n\n        em.persist(info);\n\n        em.getTransaction().commit();\n        closeEntityManager(em);\n    }\n\n    /**\n     * @return\n     * \n     */\n    private EntityManager getEntityManager()\n    {\n        if (emf == null || !emf.isOpen())\n        {\n            emf = Persistence.createEntityManagerFactory(\"kundera_rdbms_pu\");\n        }\n        return emf.createEntityManager();\n    }\n\n    private void closeEntityManager(EntityManager em)\n    {\n        em.close();\n    }\n\n    /**\n     * @param testType\n     * \n     */\n    public int getMaxRunSequence(Date date, String testType)\n    {\n        EntityManager em = getEntityManager();\n\n        em.getTransaction().begin();\n\n        Query q = em.createQuery(\"select max(p.runSequence) from PerformanceNoInfo p where p.date = '\"+date+\"'\");\n     //   q.setParameter(\"date\", date, TemporalType.DATE);\n        List results = q.getResultList();\n\n        em.getTransaction().commit();\n\n        closeEntityManager(em);\n\n        return results.get(0) != null ? (Integer) results.get(0) : 0;\n    }\n\n    \n    public static void main(String[] args)\n    {\n        HibernateCRUDUtils utils = new HibernateCRUDUtils();\n        \n        EntityManager em  = utils.getEntityManager();\n        \n        System.out.println(em.getProperties());\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/utils/MailUtils.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb.utils;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.springframework.mail.SimpleMailMessage;\nimport org.springframework.mail.javamail.JavaMailSenderImpl;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class MailUtils\n{\n\n    public static void sendMail(Map<String, Double> delta, String operationType, String dataStore)\n    {\n        onSendEmail(delta, operationType, dataStore, new String[] { \"kundera@impetus.co.in\" });\n    }\n\n    public static void sendPositiveEmail(Map<String, Double> delta, String operationType, String dataStore)\n    {\n        onSendEmail(delta, operationType, dataStore, new String[] { \"kundera@impetus.co.in\" });\n    }\n\n    private static void onSendEmail(Map<String, Double> delta, String operationType, String dataStore,\n            String[] reciepents)\n    {\n        String host = \"192.168.150.5\";\n        JavaMailSenderImpl emailSender = new JavaMailSenderImpl();\n        emailSender.setHost(host);\n        // emailSender.setPort(port);\n        emailSender.setUsername(\"noreply-kundera@build.co.in\");\n        SimpleMailMessage mail = new SimpleMailMessage();\n        mail.setTo(reciepents);\n        mail.setFrom(\"noreply-kundera@build.co.in\");\n\n        if (operationType.equalsIgnoreCase(\"load\"))\n        {\n            operationType = \"write\";\n        }\n        else if (operationType.equalsIgnoreCase(\"t\"))\n        {\n            operationType = \"read\";\n        }\n        mail.setSubject(operationType + \" kundera-\" + dataStore + \"-performance Delta\");\n\n        String mailBody = null;\n        for (String key : delta.keySet())\n        {\n            if (mailBody == null)\n            {\n                mailBody = key + delta.get(key) + \" \\n\";\n            }\n            else\n            {\n                mailBody = mailBody + key + delta.get(key) + \" \\n\";\n            }\n        }\n        mail.setText(mailBody);\n        emailSender.send(mail);\n    }\n\n    public static void main(String[] args)\n    {\n        MailUtils mailUtils = new MailUtils();\n        mailUtils.sendMail(new HashMap<String, Double>(), \"load\", \"Cassandra\");\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/utils/MongoDBOperationUtils.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.ycsb.utils;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.StringTokenizer;\n\nimport com.mongodb.DB;\nimport com.mongodb.DBAddress;\nimport com.mongodb.Mongo;\nimport common.Logger;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class MongoDBOperationUtils\n{\n    private static Logger logger = Logger.getLogger(MongoDBOperationUtils.class);\n\n    /**\n     * Stop mongo server.\n     * \n     * @param port\n     *            the runtime\n     * @param br\n     *            the br\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws InterruptedException\n     */\n    public void cleanDatabase(String url, String dbname) throws IOException, InterruptedException\n    {\n        logger.info(\"flushing db ..........\");\n\n        if (url.startsWith(\"mongodb://\"))\n        {\n            url = url.substring(10);\n        }\n\n        // need to append db to url.\n        url += \"/\" + dbname;\n\n        Mongo mongo = new Mongo(new DBAddress(url));\n\n        DB db = mongo.getDB(dbname);\n        db.dropDatabase();\n        mongo.close();\n    }\n\n    /**\n     * Start Mongo server.\n     * \n     * @param runtime\n     *            the runtime\n     * @return the process\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws InterruptedException\n     */\n    public void startMongoServer(Runtime runtime, String startMongoServerCommand) throws IOException, InterruptedException\n    {\n        logger.info(\"Starting mongo server at ...........\"  + startMongoServerCommand);\n        runtime.exec(startMongoServerCommand);\n        logger.info(\"started..............\");\n\tThread.sleep(90000);\n    }\n\n    /**\n     * Stop Mongo server.\n     * \n     * @param runtime\n     *            the runtime\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws InterruptedException\n     */\n    public void stopMongoServer(Runtime runtime) throws IOException, InterruptedException\n    {\n        logger.info(\"Stoping mongo server..\");\n        String line;\n        Process ps = runtime.exec(\"ps -ux\");\n        InputStream is = ps.getInputStream();\n        InputStreamReader isr = new InputStreamReader(is);\n        BufferedReader br = new BufferedReader(isr);\n        while ((line = br.readLine()) != null)\n        {\n            StringTokenizer tokenizer = new StringTokenizer(line, \" \");\n            if (line.contains(\"mongod\"))\n            {\n                System.out.println(line);\n                tokenizer.nextElement();\n                String nextElement = (String) tokenizer.nextElement();\n                System.out.println(nextElement);\n                runtime.exec(\"kill -9 \" + nextElement);\n                logger.info(\"stopped..............\");\n                break;\n            }\n        }\n    }\n\n    public static void main(String[] args)\n    {\n        MongoDBOperationUtils utils = new MongoDBOperationUtils();\n        Runtime runtime = Runtime.getRuntime();\n        String mongoServerLocation = \"/home/impadmin/software/mongodb-linux-x86_64-2.0.8/bin\";\n        try\n        {\n            utils.startMongoServer(runtime, mongoServerLocation);\n        }\n        catch (IOException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        try\n        {\n            utils.stopMongoServer(runtime);\n        }\n        catch (IOException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/utils/OracleNosqlOperationUtils.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.ycsb.utils;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.concurrent.TimeUnit;\n\nimport common.Logger;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class OracleNosqlOperationUtils\n{\n    private static Logger logger = Logger.getLogger(OracleNosqlOperationUtils.class);\n\n    /**\n     * Start Redis server.\n     * \n     * @param runtime\n     *            the runtime\n     * @return the process\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws InterruptedException\n     */\n    public void cleanAndStartOracleServer(Runtime runtime) throws IOException, InterruptedException\n    {\n        logger.info(\"Starting oracle server ...........\");\n        runtime.exec(\"src/main/resources/startOracleServer.sh\");\n        Thread.sleep(35000);\n        logger.info(\"started..............\");\n    }\n\n    /**\n     * Stop Redis server.\n     * \n     * @param runtime\n     *            the runtime\n     * @param performDeleteData\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws InterruptedException\n     */\n    public void stopOracleServer(Runtime runtime) throws IOException, InterruptedException\n    {\n        logger.info(\"Stoping oracle server..\");\n        Process process = runtime.exec(\"jps\");\n        InputStream is = process.getInputStream();\n        InputStreamReader isr = new InputStreamReader(is);\n        BufferedReader br = new BufferedReader(isr);\n\n        String line = null;\n        while ((line = br.readLine()) != null)\n        {\n            if (line.contains(\"kvstore.jar\"))\n            {\n                int idx;\n                idx = line.indexOf(\"kvstore.jar\");\n                runtime.exec(\"kill -9 \" + line.substring(0, idx - 1));\n                TimeUnit.SECONDS.sleep(5);\n            }\n        }\n\n        logger.info(\"stopped..............\");\n    }\n\n    public static void main(String[] args)\n    {\n        OracleNosqlOperationUtils utils = new OracleNosqlOperationUtils();\n        Runtime runtime = Runtime.getRuntime();\n        try\n        {\n            utils.cleanAndStartOracleServer(runtime);\n        }\n        catch (IOException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        try\n        {\n            utils.stopOracleServer(runtime);\n        }\n        catch (IOException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/java/com/impetus/kundera/ycsb/utils/RedisOperationUtils.java",
    "content": "/**\n * \n */\npackage com.impetus.kundera.ycsb.utils;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.StringTokenizer;\n\nimport redis.clients.jedis.Jedis;\n\nimport common.Logger;\n\n/**\n * @author Kuldeep Mishra\n * \n */\npublic class RedisOperationUtils\n{\n    private static Logger logger = Logger.getLogger(RedisOperationUtils.class);\n\n    /**\n     * Stop mongo server.\n     * \n     * @param port\n     *            the runtime\n     * @param br\n     *            the br\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws InterruptedException\n     */\n    public void cleanRedisDatabase(String host, int port, String password) throws IOException, InterruptedException\n    {\n        logger.info(\"flushing db ..........\");\n        Jedis jedis = new Jedis(host, port);\n        jedis.connect();\n        if (password != null)\n        {\n            jedis.auth(password);\n        }\n        jedis.flushDB();\n        jedis.disconnect();\n    }\n\n    /**\n     * Start Redis server.\n     * \n     * @param runtime\n     *            the runtime\n     * @return the process\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws InterruptedException\n     */\n    public void startRedisServer(Runtime runtime, String startRedisServerCommand) throws IOException,\n            InterruptedException\n    {\n        logger.info(\"Starting redis server at \" + startRedisServerCommand + \"...........\");\n        runtime.exec(startRedisServerCommand);\n        Thread.sleep(35000);\n        logger.info(\"started..............\");\n    }\n\n    /**\n     * Stop Redis server.\n     * \n     * @param runtime\n     *            the runtime\n     * @throws IOException\n     *             Signals that an I/O exception has occurred.\n     * @throws InterruptedException\n     */\n    public void stopRedisServer(Runtime runtime) throws IOException, InterruptedException\n    {\n        logger.info(\"Stoping redis server..\");\n        String line;\n        Process ps = runtime.exec(\"ps -ux\");\n        InputStream is = ps.getInputStream();\n        InputStreamReader isr = new InputStreamReader(is);\n        BufferedReader br = new BufferedReader(isr);\n        while ((line = br.readLine()) != null)\n        {\n            StringTokenizer tokenizer = new StringTokenizer(line, \" \");\n            if (line.contains(\"redis-server\"))\n            {\n                System.out.println(line);\n                tokenizer.nextElement();\n                String nextElement = (String) tokenizer.nextElement();\n                System.out.println(nextElement);\n                runtime.exec(\"kill -9 \" + nextElement);\n                logger.info(\"stopped..............\");\n                break;\n            }\n        }\n    }\n\n    public static void main(String[] args)\n    {\n        RedisOperationUtils utils = new RedisOperationUtils();\n        Runtime runtime = Runtime.getRuntime();\n        String redisServerLocation = \"/home/impadmin/software/redis-2.6.6/src/redis-server /home/impadmin/software/redis-2.6.6/redis.conf\";\n        try\n        {\n            utils.startRedisServer(runtime, redisServerLocation);\n        }\n        catch (IOException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        try\n        {\n            utils.stopRedisServer(runtime);\n        }\n        catch (IOException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        catch (InterruptedException e)\n        {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/META-INF/persistence.xml",
    "content": "<persistence xmlns=\"http://java.sun.com/xml/ns/persistence\"\r\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence\r\n\thttps://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd\"\r\n\tversion=\"2.0\">\r\n\r\n\t<persistence-unit name=\"kundera_kudu_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.ycsb.entities.KuduUser</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"quickstart.cloudera\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"7051\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"kundera\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"kudu\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.kudu.KuduDBClientFactory\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\r\n\t<persistence-unit name=\"kundera_pelops_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"kundera\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.cassandra.pelops.PelopsClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t\t<property name=\"kundera.pool.size.max.active\" value=\"50\" />\r\n\t\t\t<property name=\"kundera.pool.size.max.total\" value=\"50\" />\r\n\t\t\t<!-- <property name=\"kundera.client.property\" value=\"kunderacassandraloadbalancer.xml\" \r\n\t\t\t\t/> -->\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"kundera_thrift_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"9160\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"kundera\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"cassandra\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.cassandra.thrift.ThriftClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t\t<property name=\"kundera.pool.size.max.active\" value=\"50\" />\r\n\t\t\t<property name=\"kundera.pool.size.max.total\" value=\"50\" />\r\n\t\t\t<!-- <property name=\"kundera.client.property\" value=\"kunderacassandraloadbalancer.xml\" \r\n\t\t\t\t/> -->\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"kundera_rdbms_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<class>com.impetus.kundera.ycsb.entities.PerformanceNoInfo</class>\r\n\t\t<exclude-unlisted-classes>true</exclude-unlisted-classes>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.rdbms.RDBMSClientFactory\" />\r\n\t\t\t<property name=\"hibernate.show_sql\" value=\"false\" />\r\n\t\t\t<property name=\"hibernate.format_sql\" value=\"false\" />\r\n\t\t\t<property name=\"dialect\"\r\n\t\t\t\tvalue=\"org.openmeetings.app.hibernate.utils.MySQL5MyISAMDialect\" />\r\n\t\t\t<property name=\"hibernate.dialect\" value=\"org.hibernate.dialect.MySQL5Dialect\" />\r\n\t\t\t<property name=\"hibernate.connection.driver_class\" value=\"com.mysql.jdbc.Driver\" />\r\n\t\t\t<property name=\"hibernate.connection.url\" value=\"jdbc:mysql://192.168.145.151:3306/testPerformance\" />\r\n\t\t\t<property name=\"hibernate.connection.username\" value=\"root\" />\r\n\t\t\t<property name=\"hibernate.connection.password\" value=\"root\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"kundera_mongo_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<!-- <property name=\"kundera.nodes\" value=\"192.168.145.168\" /> -->\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"27017\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"kundera\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"mongodb\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.mongodb.MongoDBClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t\t<property name=\"kundera.pool.size.max.active\" value=\"50\" />\r\n\t\t\t<property name=\"kundera.pool.size.max.total\" value=\"50\" />\r\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaMongoTest.xml\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"kundera_redis_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"6379\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"0\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"redis\" />\r\n\t\t\t<property name=\"kundera.password\" value=\"Kundera@123\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.redis.RedisClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> -->\t\t\t<!-- <property name=\"kundera.pool.size.max.active\" value=\"50\" /> -->\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\r\n\t<persistence-unit name=\"kundera_neo4j_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"7474\" />\r\n\t\t\t<property name=\"kundera.datastore.file.path\" value=\"target/neo4jPerfKundera.db\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"neo4j\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.neo4j.Neo4JClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t\t<property name=\"kundera.client.property\" value=\"kunderaNeo4JTest.xml\" />\r\n\t\t\t<property name=\"kundera.transaction.resource.class\" value=\"com.impetus.client.neo4j.Neo4JTransaction\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\r\n\t<persistence-unit name=\"kundera_hbase_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"2181\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"kundera\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"hbase\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\" value=\"com.impetus.client.hbase.HBaseClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"update\" />\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"kundera_oracle_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"5000\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.oraclenosql.OracleNoSQLClientFactory\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"OracleNoSqlTests\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"kvstore\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"kvstore\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n\t<persistence-unit name=\"kundera_couchdb_pu\">\r\n\t\t<provider>com.impetus.kundera.KunderaPersistence</provider>\r\n\t\t<properties>\r\n\t\t\t<property name=\"kundera.nodes\" value=\"localhost\" />\r\n\t\t\t<property name=\"kundera.port\" value=\"5984\" />\r\n\t\t\t<property name=\"kundera.keyspace\" value=\"kundera\" />\r\n\t\t\t<property name=\"kundera.dialect\" value=\"couchdb\" />\r\n\t\t\t<property name=\"kundera.client\" value=\"couchdb\" />\r\n\t\t\t<property name=\"kundera.ddl.auto.prepare\" value=\"create\" />\r\n\t\t\t<property name=\"kundera.client.lookup.class\"\r\n\t\t\t\tvalue=\"com.impetus.client.couchdb.CouchDBClientFactory\" />\r\n\t\t\t<!-- <property name=\"kundera.cache.provider.class\" value=\"com.impetus.kundera.cache.ehcache.EhCacheProvider\" \r\n\t\t\t\t/> <property name=\"kundera.cache.config.resource\" value=\"/ehcache-test.xml\" \r\n\t\t\t\t/> -->\r\n\t\t</properties>\r\n\t</persistence-unit>\r\n\r\n</persistence>\r\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/db-cassandra.properties",
    "content": "hosts=localhost\nport=9160\nfieldcount=4\nschema=kundera\ncolumnfamilyOrTable=user\nworkload.dir=src\\/main\\/resources\\/workloads\n#bulk.workload.type=workloadinsert1000000\nworkload.file=workloadinsert1000000\nrun.type=t\nthreads=9\n# Change jar location as per settings.\nycsbjar.location=\\/root\\/.m2\\/repository\\/com\\/yahoo\\/ycsb\\/core\\/0.1.4\\/core-0.1.4.jar\n#ycsbjar.location=\\/home\\/impadmin\\/.m2\\/repository\\/com\\/yahoo\\/ycsb\\/core\\/0.1.4\\/core-0.1.4.jar\nclientjar.location=/root/.jenkins/jobs/Kundera-benchmark/workspace/test/benchmark/ycsb/target\\/*\nrelease.no=2.5\n# Change server.location as per settings.\nserver.location=\\/root\\/software\\/apache-cassandra-2.1.2\\/bin\\/cassandra\n#server.location=\\/home\\/impadmin\\/software\\/apache-cassandra-1.2.4\\/bin\\/cassandra\nclients=com.impetus.kundera.ycsb.benchmark.KunderaPelopsClient,com.impetus.kundera.ycsb.benchmark.PelopsClient,com.impetus.kundera.ycsb.benchmark.KunderaThriftClient,com.impetus.kundera.ycsb.benchmark.ThriftClient\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/db-couch.properties",
    "content": "hosts=localhost\nport=5984\nfieldcount=4\nschema=kundera\ncolumnfamilyOrTable=user\nworkload.dir=src\\/main\\/resources\\/workloads\n#bulk.workload.type=workloadinsert1000000\nworkload.file=workloadinsert1000\nrun.type=load\nthreads=30\n# Change jar location as per settings.\nycsbjar.location=\\/usr\\/local\\/mvn_repo\\/com\\/yahoo\\/ycsb\\/core\\/0.1.4\\/core-0.1.4.jar\n#ycsbjar.location=\\/home\\/impadmin\\/.m2\\/repository\\/com\\/yahoo\\/ycsb\\/core\\/0.1.4\\/core-0.1.4.jar\nclientjar.location=/root/.jenkins/jobs/Kundera-benchmark/workspace/test/benchmark/ycsb\\/target\\/*\nrelease.no=2.8\n#server.location=\\/home\\/impadmin\\/software\\/apache-cassandra-1.2.4\\/bin\\/cassandra\nclients=com.impetus.kundera.ycsb.benchmark.CouchDBNativeClient,com.impetus.kundera.ycsb.benchmark.KunderaCouchDBClient\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/db-hbase.properties",
    "content": "hosts=localhost\nport=2181\nfieldcount=4\nschema=usertable\ncolumnfamilyOrTable=user\nworkload.dir=src/main/resources/workloads\n#bulk.workload.type=workloadinsert1000000\nworkload.file=workloadinsert1100000\nrun.type=load\nthreads=1\n# Change jar location as per settings.\nycsbjar.location=/root/.m2/repository/com/yahoo/ycsb/core/0.1.4/core-0.1.4.jar\n#ycsbjar.location=\\/home\\/impadmin\\/.m2\\/repository\\/com\\/yahoo\\/ycsb\\/core\\/0.1.4\\/core-0.1.4.jar\nclientjar.location=/root/.jenkins/jobs/Kundera-benchmark/workspace/test/benchmark/ycsb/target/*\n#clientjar.location=target\\/*\nrelease.no=2.5\n# Change server.location as per settings.\n#server.location= \\/root\\/software\\/hbase-0.94.3\\/bin\\/\nserver.location= /root/software/hbase-1.0.0/bin/\n#clients=com.impetus.kundera.ycsb.benchmark.KunderaHBaseClient,com.impetus.kundera.ycsb.benchmark.HBaseClient\nclients=com.impetus.kundera.ycsb.benchmark.KunderaHBaseClient,com.impetus.kundera.ycsb.benchmark.PhoenixClient\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/db-kudu.properties",
    "content": "hosts = quickstart.cloudera\nport = 7051\nkudu_table_num_replicas = 1\nfieldcount = 4\nschema = kundera\ncolumnfamilyOrTable = user\nworkload.dir = src\\/main\\/resources\\/workloads\n#bulk.workload.type=workloadinsert1000000\nworkload.file = workloadinsert10000\nrun.type = load\nthreads = 9\n# Change jar location as per settings.\nycsbjar.location = \\/home\\/IMPETUS\\/devender.yadav\\/core-0.1.4.jar\n#ycsbjar.location=\\/home\\/impadmin\\/.m2\\/repository\\/com\\/yahoo\\/ycsb\\/core\\/0.1.4\\/core-0.1.4.jar\nclientjar.location = \\/home\\/IMPETUS\\/devender.yadav\\/Kundera\\/test\\/benchmark\\/ycsb\\/target\\/*\nrelease.no = 3.9\n# Change server.location as per settings.\n#server.location=\\/root\\/software\\/apache-cassandra-2.1.2\\/bin\\/cassandra\n#server.location=\\/home\\/impadmin\\/software\\/apache-cassandra-1.2.4\\/bin\\/cassandra\nclients = com.impetus.kundera.ycsb.benchmark.KuduYCSBClient,com.impetus.kundera.ycsb.benchmark.KunderaKuduDBClient\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/db-mongo.properties",
    "content": "hosts=localhost\nport=27017\nfieldcount=4\nschema=kundera\ncolumnfamilyOrTable=user\nworkload.dir=src\\/main\\/resources\\/workloads\nbulk.workload.type=workloadinsert1000\nworkload.file=workloadinsert1000000\nrun.type=t\nthreads=2\n# Change jar location as per settings.\n#ycsbjar.location=\\/home\\/impadmin\\/.m2\\/repository\\/com\\/yahoo\\/ycsb\\/core\\/0.1.4\\/core-0.1.4.jar\nycsbjar.location=\\/root\\/.m2\\/repository\\/com\\/yahoo\\/ycsb\\/core\\/0.1.4\\/core-0.1.4.jar\n# Change server.location as per settings.\nserver.location=/root/software/start-mongo.sh\n#server.location=\\/home\\/impadmin\\/software\\/mongodb-linux-x86_64-2.0.8\\/bin\\/mongod&\nclientjar.location=/root/.jenkins/jobs/Kundera-benchmark/workspace/test/benchmark/ycsb/target/*\nrelease.no=2.5\nclients=com.impetus.kundera.ycsb.benchmark.KunderaMongoClient,com.impetus.kundera.ycsb.benchmark.MongoDbClient\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/db-neo4j.properties",
    "content": "hosts=localhost\nport=6379\nfieldcount=4\nschema=kundera\ncolumnfamilyOrTable=user\nworkload.dir=src/main/resources/workloads\nbulk.workload.type=workloadinsert100000\nworkload.file=workloadinsert100000\nrun.type=t\nthreads=5\n# Change jar location as per settings.\n#ycsbjar.location=/home/impadmin/.m2/repository/com/yahoo/ycsb/core/0.1.4/core-0.1.4.jar\nycsbjar.location=/root/.m2/repository/com/yahoo/ycsb/core/0.1.4/core-0.1.4.jar\n# Change server.location as per settings.\n#clientjar.location=target/*\nclientjar.location=/root/.jenkins/jobs/Kundera-benchmark/workspace/test/benchmark/ycsb/target/*\nrelease.no=2.5\nclients=com.impetus.kundera.ycsb.benchmark.KunderaNeo4JClient,com.impetus.kundera.ycsb.benchmark.Neo4JNativeClient\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/db-oracle-nosql.properties",
    "content": "hosts=localhost\nhelperHost=localhost:5000\nport=5000\nfieldcount=4\nstoreName=KunderaTests\nschema=KunderaTests\ncolumnfamilyOrTable=kunderauser\nworkload.dir=src/main/resources/workloads\nworkload.file=workloadinsert100000\nrun.type=load\nthreads=5\n# Change jar location as per settings.\n#ycsbjar.location=/home/impadmin/.m2/repository/com/yahoo/ycsb/core/0.1.4/core-0.1.4.jar\nycsbjar.location=\\/root\\/.m2\\/repository\\/com\\/yahoo\\/ycsb\\/core\\/0.1.4\\/core-0.1.4.jar\n#clientjar.location=target/*\nclientjar.location=/root/.jenkins/jobs/Kundera-benchmark/workspace/test/benchmark/ycsb/target/*\nrelease.no=2.8\n# Change server.location as per settings.\nclients=com.impetus.kundera.ycsb.benchmark.KunderaOracleNosqlClient,com.impetus.kundera.ycsb.benchmark.OracleNosqlClient\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/db-redis.properties",
    "content": "hosts=localhost\nport=6379\npassword=Kundera@123\nfieldcount=4\nschema=kundera\ncolumnfamilyOrTable=user\nworkload.dir=src/main/resources/workloads\nbulk.workload.type=workloadinsert100000\nworkload.file=workloadinsert100000\nrun.type=t\nthreads=5\n# Change jar location as per settings.\n#ycsbjar.location=/home/impadmin/.m2/repository/com/yahoo/ycsb/core/0.1.4/core-0.1.4.jar\nycsbjar.location=\\/root\\/.m2\\/repository\\/com\\/yahoo\\/ycsb\\/core\\/0.1.4\\/core-0.1.4.jar\n# Change server.location as per settings.\nserver.location= \\/root\\/software\\/start-redis.sh\n#server.location= /home/impadmin/software/start-redis.sh\n#clientjar.location=target/*\nclientjar.location=/root/.jenkins/jobs/Kundera-benchmark/workspace/test/benchmark/ycsb/target/*\nrelease.no=2.5\nclients=com.impetus.kundera.ycsb.benchmark.KunderaRedisClient,com.impetus.kundera.ycsb.benchmark.RedisClient\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/kunderaMongoTest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>mongo</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\n\t\t\t\t\t<property name=\"read.preference\" value=\"primary\"></property>\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t</dataStore>\n\t</datastores>\n</clientProperties>\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/kunderaNeo4JTest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<clientProperties>\n\t<datastores>\n\t\t<dataStore>\n\t\t\t<name>neo4j</name>\n\t\t\t<connection>\n\t\t\t\t<properties>\t\t\t\t\t\n\t\t\t\t\t<property name=\"node_auto_indexing\" value=\"true\"></property>\t\t\t\t\t\n\t\t\t\t\t<property name=\"node_keys_indexable\" value=\"USER_ID\"></property>\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t</properties>\n\t\t\t</connection>\n\t\t\t</dataStore>\n\t</datastores>\n</clientProperties>"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/log4j.properties",
    "content": "log4j.rootLogger=WARN, DRFA, CONSOLE\r\n\r\n### direct log messages to stdout ###\r\nlog4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender\r\nlog4j.appender.DRFA.File=${user.home}/kundera-benchmark.log\r\n# Rollover at midnight\r\nlog4j.appender.DRFA.DatePattern=.yyyy-MM-dd\r\nlog4j.appender.DRFA.layout=org.apache.log4j.PatternLayout\r\n# Pattern format: Date LogLevel LoggerName LogMessage\r\nlog4j.appender.DRFA.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n\r\n\r\nlog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender\r\nlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout\r\nlog4j.appender.CONSOLE.layout.ConversionPattern=%d [%-5p] [%t] %c %x - %m%n\r\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/startOracleServer.sh",
    "content": "    #!/bin/bash\n    echo \"Starting oracle server.....\"\n    java -jar lib/kvstore.jar kvlite -store KunderaTests&\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloada",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=10\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=zipfian\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadb",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n# Yahoo! Cloud System Benchmark\n# Workload B: Read mostly workload\n#   Application example: photo tagging; add a tag is an update, but most operations are to read tags\n#                        \n#   Read/update ratio: 95/5\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=1000000\noperationcount=1000000\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\nreadallfields=true\n\nreadproportion=1.0\nupdateproportion=0\nscanproportion=0\ninsertproportion=0\n\nrequestdistribution=zipfian\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadc",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n# Yahoo! Cloud System Benchmark\n# Workload C: Read only\n#   Application example: user profile cache, where profiles are constructed elsewhere (e.g., Hadoop)\n#                        \n#   Read/update ratio: 100/0\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=1000\noperationcount=1000\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\nreadallfields=true\n\nreadproportion=1\nupdateproportion=0\nscanproportion=0\ninsertproportion=0\n\nrequestdistribution=zipfian\n\n\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadd",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \r\n#                                                                                                                                                                                 \r\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \r\n# may not use this file except in compliance with the License. You                                                                                                                \r\n# may obtain a copy of the License at                                                                                                                                             \r\n#                                                                                                                                                                                 \r\n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \r\n#                                                                                                                                                                                 \r\n# Unless required by applicable law or agreed to in writing, software                                                                                                             \r\n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \r\n# implied. See the License for the specific language governing                                                                                                                    \r\n# permissions and limitations under the License. See accompanying                                                                                                                 \r\n# LICENSE file.                                                                                                                                                                   \r\n\r\n# Yahoo! Cloud System Benchmark\r\n# Workload D: Read latest workload\r\n#   Application example: user status updates; people want to read the latest\r\n#                        \r\n#   Read/update/insert ratio: 95/0/5\r\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\r\n#   Request distribution: latest\r\n\r\n# The insert order for this is hashed, not ordered. The \"latest\" items may be \r\n# scattered around the keyspace if they are keyed by userid.timestamp. A workload\r\n# which orders items purely by time, and demands the latest, is very different than \r\n# workload here (which we believe is more typical of how people build systems.)\r\n\r\nrecordcount=1000\r\noperationcount=1000\r\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\r\n\r\nreadallfields=true\r\n\r\nreadproportion=0.95\r\nupdateproportion=0\r\nscanproportion=0\r\ninsertproportion=0.05\r\n\r\nrequestdistribution=latest\r\n\r\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloade",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n# Yahoo! Cloud System Benchmark\n# Workload E: Short ranges\n#   Application example: threaded conversations, where each scan is for the posts in a given thread (assumed to be clustered by thread id)\n#                        \n#   Scan/insert ratio: 95/5\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\n# The insert order is hashed, not ordered. Although the scans are ordered, it does not necessarily\n# follow that the data is inserted in order. For example, posts for thread 342 may not be inserted contiguously, but\n# instead interspersed with posts from lots of other threads. The way the YCSB client works is that it will pick a start\n# key, and then request a number of records; this works fine even for hashed insertion.\n\nrecordcount=1000\noperationcount=1000\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0.95\ninsertproportion=0.05\n\nrequestdistribution=zipfian\n\nmaxscanlength=100\n\nscanlengthdistribution=uniform\n\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadf",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \r\n#                                                                                                                                                                                 \r\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \r\n# may not use this file except in compliance with the License. You                                                                                                                \r\n# may obtain a copy of the License at                                                                                                                                             \r\n#                                                                                                                                                                                 \r\n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \r\n#                                                                                                                                                                                 \r\n# Unless required by applicable law or agreed to in writing, software                                                                                                             \r\n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \r\n# implied. See the License for the specific language governing                                                                                                                    \r\n# permissions and limitations under the License. See accompanying                                                                                                                 \r\n# LICENSE file.                                                                                                                                                                   \r\n\r\n# Yahoo! Cloud System Benchmark\r\n# Workload F: Read-modify-write workload\r\n#   Application example: user database, where user records are read and modified by the user or to record user activity.\r\n#                        \r\n#   Read/read-modify-write ratio: 50/50\r\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\r\n#   Request distribution: zipfian\r\n\r\nrecordcount=1000\r\noperationcount=1000\r\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\r\n\r\nreadallfields=true\r\n\r\nreadproportion=0.5\r\nupdateproportion=0\r\nscanproportion=0\r\ninsertproportion=0\r\nreadmodifywriteproportion=0.5\r\n\r\nrequestdistribution=zipfian\r\n\r\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert10",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=10\noperationcount=10\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=1\nupdateproportion=0\nscanproportion=0\ninsertproportion=0\n\nrequestdistribution=zipfian\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert100",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=100\noperationcount=100\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=1\nupdateproportion=0\nscanproportion=0\ninsertproportion=0\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert1000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=1000\noperationcount=1000\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=1\nupdateproportion=0\nscanproportion=0\ninsertproportion=0\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert10000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=10000\noperationcount=10000\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=1\nupdateproportion=0\nscanproportion=0\ninsertproportion=0\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert100000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=1200000\noperationcount=1200000\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=1\nupdateproportion=0\nscanproportion=0\ninsertproportion=0\n\nrequestdistribution=zipfian\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert1000000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=1000000\noperationcount=1000000\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=1\nupdateproportion=0\nscanproportion=0\ninsertproportion=0\n\nrequestdistribution=zipfian\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert10000~",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=10000\noperationcount=1000\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=1\nupdateproportion=0\nscanproportion=0\ninsertproportion=0\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert1100000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \nd#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=1100000\noperationcount=1100000\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=zipfian\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert150000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=150000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert150000~",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=5000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert200000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=200000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert2000000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=2000000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=zipfian\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert2000000~",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=1000000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=zipfian\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert200000~",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=150000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert250000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=250000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert250000~",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=200000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert300000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=300000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert3000000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=3000000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=zipfian\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert3000000~",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=4000000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=zipfian\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert300000~",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=250000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert4000000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=4000000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=zipfian\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert4000000~",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=3000000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=zipfian\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert4500000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=4500000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=zipfian\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert4500000~",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=4500000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=zipfian\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert5000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=5000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert5000000",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=4500000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=zipfian\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert5000000~",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=5000000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=zipfian\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/main/resources/workloads/workloadinsert5000~",
    "content": "# Copyright (c) 2010 Yahoo! Inc. All rights reserved.                                                                                                                             \n#                                                                                                                                                                                 \n# Licensed under the Apache License, Version 2.0 (the \"License\"); you                                                                                                             \n# may not use this file except in compliance with the License. You                                                                                                                \n# may obtain a copy of the License at                                                                                                                                             \n#                                                                                                                                                                                 \n# http://www.apache.org/licenses/LICENSE-2.0                                                                                                                                      \n#                                                                                                                                                                                 \n# Unless required by applicable law or agreed to in writing, software                                                                                                             \n# distributed under the License is distributed on an \"AS IS\" BASIS,                                                                                                               \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or                                                                                                                 \n# implied. See the License for the specific language governing                                                                                                                    \n# permissions and limitations under the License. See accompanying                                                                                                                 \n# LICENSE file.                                                                                                                                                                   \n\n\n# Yahoo! Cloud System Benchmark\n# Workload A: Update heavy workload\n#   Application example: Session store recording recent actions\n#                        \n#   Read/update ratio: 50/50\n#   Default data size: 1 KB records (10 fields, 100 bytes each, plus key)\n#   Request distribution: zipfian\n\nrecordcount=1000\noperationcount=1\nworkload=com.yahoo.ycsb.workloads.CoreWorkload\n\n\nreadallfields=true\n\nreadproportion=0\nupdateproportion=0\nscanproportion=0\ninsertproportion=1\n\nrequestdistribution=uniform\n\n"
  },
  {
    "path": "test/benchmark/ycsb/src/test/java/com/impetus/kundera/ycsb/CassandraYCSBTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb;\n\nimport java.io.IOException;\n\nimport org.apache.commons.configuration.ConfigurationException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.FixMethodOrder;\nimport org.junit.Test;\nimport org.junit.runners.MethodSorters;\n\nimport com.impetus.kundera.ycsb.runner.CassandraRunner;\n\n/**\n * Cassandra Kundera YCSB benchmarking.\n * \n * @author vivek.mishra\n * \n */\n@FixMethodOrder(MethodSorters.NAME_ASCENDING)\npublic class CassandraYCSBTest extends YCSBBaseTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        System.setProperty(\"fileName\", \"src/main/resources/db-cassandra.properties\");\n        // in case property file name is not set as system property.\n        super.setUp();\n    }\n\n    @Test\n    public void onTest() throws Exception\n    {\n       testConcurrentWorkload();\n        testRead();\n//        testUpdate();\n\n    }\n\n    void testConcurrentWorkload() throws IOException, ConfigurationException\n    {\n        onChangeRunType(\"load\");\n        Runtime runtime = Runtime.getRuntime();\n        runner.startServer(true, runtime);\n\n        process();\n    }\n\n    void testRead() throws Exception\n    {\n        onChangeRunType(\"t\");\n        onRead();\n    }\n\n    void testUpdate() throws Exception\n    {\n        onChangeRunType(true);\n        onUpdate();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        onDestroy();\n    }\n\n    /**\n     * @param runType\n     * @throws ConfigurationException\n     */\n    protected void onChangeRunType(final String runType) throws ConfigurationException\n    {\n        config.setProperty(\"run.type\", runType);\n        config.setProperty(\"ycsbjar.location\", ycsbJarLocation);\n        config.save();\n        runner = new CassandraRunner(propsFileName, config);\n//        Runtime runtime = Runtime.getRuntime();\n//        runner.startServer(runType.equals(\"load\"), runtime);\n\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/test/java/com/impetus/kundera/ycsb/CouchDBYCSBTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb;\n\nimport java.io.IOException;\n\nimport org.apache.commons.configuration.ConfigurationException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.FixMethodOrder;\nimport org.junit.Test;\nimport org.junit.runners.MethodSorters;\n\nimport com.impetus.kundera.ycsb.runner.CouchDBRunner;\n\n/**\n * Cassandra Kundera YCSB benchmarking.\n * \n * @author vivek.mishra\n * \n */\n@FixMethodOrder(MethodSorters.NAME_ASCENDING)\npublic class CouchDBYCSBTest extends YCSBBaseTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        System.setProperty(\"fileName\", \"src/main/resources/db-couch.properties\");\n        // in case property file name is not set as system property.\n        super.setUp();\n    }\n\n    @Test\n    public void onTest() throws Exception\n    {\n       testConcurrentWorkload();\n        testRead();\n//        testUpdate();\n\n    }\n\n    void testConcurrentWorkload() throws IOException, ConfigurationException\n    {\n        onChangeRunType(\"load\");\n        Runtime runtime = Runtime.getRuntime();\n        runner.startServer(true, runtime);\n\n        process();\n    }\n\n    void testRead() throws Exception\n    {\n        onChangeRunType(\"t\");\n        onRead();\n    }\n\n    void testUpdate() throws Exception\n    {\n        onChangeRunType(true);\n        onUpdate();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        onDestroy();\n    }\n\n    /**\n     * @param runType\n     * @throws ConfigurationException\n     */\n    protected void onChangeRunType(final String runType) throws ConfigurationException\n    {\n        config.setProperty(\"run.type\", runType);\n        config.setProperty(\"ycsbjar.location\", ycsbJarLocation);\n        config.save();\n        runner = new CouchDBRunner(propsFileName, config);\n//        Runtime runtime = Runtime.getRuntime();\n//        runner.startServer(runType.equals(\"load\"), runtime);\n\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/test/java/com/impetus/kundera/ycsb/HBaseYCSBTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb;\n\nimport java.io.IOException;\n\nimport org.apache.commons.configuration.ConfigurationException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.ycsb.runner.HBaseRunner;\n\n/**\n * Cassandra Kundera YCSB benchmarking.\n * \n * @author vivek.mishra\n * \n */\npublic class HBaseYCSBTest extends YCSBBaseTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        System.setProperty(\"fileName\", \"src/main/resources/db-hbase.properties\");\n        super.setUp();\n    }\n\n    @Test\n    public void onTest() throws Exception\n    {\n        testConcurrentWorkload();\n        testRead();\n//        testUpdate();\n    }\n\n    private void testConcurrentWorkload() throws IOException, ConfigurationException\n    {\n        onChangeRunType(\"load\");\n        Runtime runtime = Runtime.getRuntime();\n        runner.startServer(true, runtime);\n\n        process();\n    }\n\n    private void testRead() throws Exception\n    {\n        onChangeRunType(\"t\");\n        onRead();\n    }\n\n    private void testUpdate() throws Exception\n    {\n        onChangeRunType(true);\n        onUpdate();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        onDestroy();\n    }\n\n    /**\n     * @param runType\n     * @throws ConfigurationException\n     */\n    protected void onChangeRunType(final String runType) throws ConfigurationException\n    {\n        config.setProperty(\"run.type\", runType);\n        config.setProperty(\"ycsbjar.location\", ycsbJarLocation);\n        config.save();\n        runner = new HBaseRunner(propsFileName, config);\n//        Runtime runtime = Runtime.getRuntime();\n//        runner.startServer(runType.equals(\"load\"), runtime);\n\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/test/java/com/impetus/kundera/ycsb/KuduDBYCSBTest.java",
    "content": "/**\n * Copyright 2017 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb;\n\nimport java.io.IOException;\n\nimport org.apache.commons.configuration.ConfigurationException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.ycsb.runner.KuduRunner;\n\n/**\n * KuduDB YCSB Kundera benchmarking.\n * \n * @author karthikp.manchala\n * \n */\npublic class KuduDBYCSBTest extends YCSBBaseTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        // in case property file name is not set as system property.\n        System.setProperty(\"fileName\", \"src/main/resources/db-kudu.properties\");\n        super.setUp();\n    }\n\n    @Test\n    public void onTest() throws Exception\n    {\n        testConcurrentWorkload();\n        testRead();\n        testUpdate();\n    }\n\n    private void testConcurrentWorkload() throws IOException, ConfigurationException\n    {\n        onChangeRunType(\"load\");\n        Runtime runtime = Runtime.getRuntime();\n        runner.startServer(true, runtime);\n        process();\n    }\n\n    private void testRead() throws Exception\n    {\n        onChangeRunType(\"t\");\n        onRead();\n    }\n\n    private void testUpdate() throws Exception\n    {\n        onChangeRunType(true);\n        onUpdate();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        onDestroy();\n    }\n\n    /**\n     * @param runType\n     * @throws ConfigurationException\n     */\n    protected void onChangeRunType(final String runType) throws ConfigurationException\n    {\n        config.setProperty(\"run.type\", runType);\n        config.setProperty(\"ycsbjar.location\", ycsbJarLocation);\n        config.save();\n        runner = new KuduRunner(propsFileName, config);\n        // Runtime runtime = Runtime.getRuntime();\n        // runner.startServer(runType.equals(\"load\"), runtime);\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/test/java/com/impetus/kundera/ycsb/MongoDBYCSBTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb;\n\nimport java.io.IOException;\n\nimport org.apache.commons.configuration.ConfigurationException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.ycsb.runner.MongoRunner;\n\n/**\n * MongoDB YCSB Kundera benchmarking.\n * \n * @author vivek.mishra\n * \n */\npublic class MongoDBYCSBTest extends YCSBBaseTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        // in case property file name is not set as system property.\n        System.setProperty(\"fileName\", \"src/main/resources/db-mongo.properties\");\n        super.setUp();\n    }\n\n    @Test\n    public void onTest() throws Exception\n    {\n        testConcurrentWorkload();\n        testRead();\n//        testUpdate();\n    }\n\n    private void testConcurrentWorkload() throws IOException, ConfigurationException\n    {\n        onChangeRunType(\"load\");\n        Runtime runtime = Runtime.getRuntime();\n        runner.startServer(true, runtime);\n        process();\n    }\n\n    private void testRead() throws Exception\n    {\n        onChangeRunType(\"t\");\n        onRead();\n    }\n\n    private void testUpdate() throws Exception\n    {\n        onChangeRunType(true);\n        onUpdate();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        onDestroy();\n    }\n\n    /**\n     * @param runType\n     * @throws ConfigurationException\n     */\n    protected void onChangeRunType(final String runType) throws ConfigurationException\n    {\n        config.setProperty(\"run.type\", runType);\n        config.setProperty(\"ycsbjar.location\", ycsbJarLocation);\n        config.save();\n        runner = new MongoRunner(propsFileName, config);\n//        Runtime runtime = Runtime.getRuntime();\n//        runner.startServer(runType.equals(\"load\"), runtime);\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/test/java/com/impetus/kundera/ycsb/Neo4JYCSBTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb;\n\nimport java.io.IOException;\n\nimport org.apache.commons.configuration.ConfigurationException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.ycsb.runner.Neo4jRunner;\n\n/**\n * Neo4J YCSB Kundera benchmarking.\n * \n * @author vivek.mishra\n * \n */\npublic class Neo4JYCSBTest extends YCSBBaseTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        // in case property file name is not set as system property.\n        System.setProperty(\"fileName\", \"src/main/resources/db-neo4j.properties\");\n        super.setUp();\n    }\n\n    @Test\n    public void onTest() throws Exception\n    {\n        testConcurrentWorkload();\n        testRead();\n//        testUpdate();\n    }\n\n    private void testConcurrentWorkload() throws IOException, ConfigurationException\n    {\n        onChangeRunType(\"load\");\n        process();\n    }\n\n    private void testRead() throws Exception\n    {\n        onChangeRunType(\"t\");\n        onRead();\n    }\n\n    private void testUpdate() throws Exception\n    {\n        onChangeRunType(true);\n        onUpdate();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        onDestroy();\n    }\n\n    /**\n     * @param runType\n     * @throws ConfigurationException\n     */\n    protected void onChangeRunType(final String runType) throws ConfigurationException\n    {\n        config.setProperty(\"run.type\", runType);\n        config.setProperty(\"ycsbjar.location\", ycsbJarLocation);\n        config.save();\n        runner = new Neo4jRunner(propsFileName, config);\n//        Runtime runtime = Runtime.getRuntime();\n//        runner.startServer(runType.equals(\"load\"), runtime);\n\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/test/java/com/impetus/kundera/ycsb/OracleNosqlYCSBTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb;\n\nimport java.io.IOException;\n\nimport org.apache.commons.configuration.ConfigurationException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.FixMethodOrder;\nimport org.junit.Test;\nimport org.junit.runners.MethodSorters;\n\nimport com.impetus.kundera.ycsb.runner.OracleNosqlRunner;\n\n/**\n * Cassandra Kundera YCSB benchmarking.\n * \n * @author vivek.mishra\n * \n */\n@FixMethodOrder(MethodSorters.NAME_ASCENDING)\npublic class OracleNosqlYCSBTest extends YCSBBaseTest\n{\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        System.setProperty(\"fileName\", \"src/main/resources/db-oracle-nosql.properties\");\n        // in case property file name is not set as system property.\n        super.setUp();\n    }\n\n    @Test\n    public void onTest() throws Exception\n    {\n      //  testConcurrentWorkload();\n        testRead();\n        // testUpdate();\n\n    }\n\n    void testConcurrentWorkload() throws IOException, ConfigurationException\n    {\n        onChangeRunType(\"load\");\n        Runtime runtime = Runtime.getRuntime();\n        runner.startServer(true, runtime);\n\n        process();\n    }\n\n    void testRead() throws Exception\n    {\n        onChangeRunType(\"t\");\n        onRead();\n    }\n\n    void testUpdate() throws Exception\n    {\n        onChangeRunType(true);\n        onUpdate();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        onDestroy();\n    }\n\n    /**\n     * @param runType\n     * @throws ConfigurationException\n     */\n    protected void onChangeRunType(final String runType) throws ConfigurationException\n    {\n        config.setProperty(\"run.type\", runType);\n        config.setProperty(\"ycsbjar.location\", ycsbJarLocation);\n        config.save();\n        runner = new OracleNosqlRunner(propsFileName, config);\n        // Runtime runtime = Runtime.getRuntime();\n        // runner.startServer(runType.equals(\"load\"), runtime);\n\n    }\n\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/test/java/com/impetus/kundera/ycsb/RedisYCSBTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb;\n\nimport java.io.IOException;\n\nimport org.apache.commons.configuration.ConfigurationException;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\n\nimport com.impetus.kundera.ycsb.runner.RedisRunner;\n\n/**\n * Redis Cloud YCSB benchmark.\n * \n * @author vivek.mishra\n * \n */\npublic class RedisYCSBTest extends YCSBBaseTest\n{\n    /**\n     * @throws java.lang.Exception\n     */\n    @Before\n    public void setUp() throws Exception\n    {\n        // in case property file name is not set as system property.\n        System.setProperty(\"fileName\", \"src/main/resources/db-redis.properties\");\n        super.setUp();\n    }\n\n    @Test\n    public void onTest() throws Exception\n    {\n        testConcurrentWorkload();\n        testRead();\n//        testUpdate();\n    }\n\n    private void testConcurrentWorkload() throws IOException, ConfigurationException\n    {\n        onChangeRunType(\"load\");\n        Runtime runtime = Runtime.getRuntime();\n        runner.startServer(true, runtime);\n        process();\n    }\n\n    private void testRead() throws Exception\n    {\n        //stop and start server\n        onDestroy();\n        onChangeRunType(\"t\");\n        Thread.sleep(30000);\n        Runtime runtime = Runtime.getRuntime();\n        runner.startServer(true, runtime);\n        onRead();\n    }\n\n    private void testUpdate() throws Exception\n    {\n        onChangeRunType(true);\n        onUpdate();\n    }\n\n    /**\n     * @throws java.lang.Exception\n     */\n    @After\n    public void tearDown() throws Exception\n    {\n        onDestroy();\n    }\n\n    /**\n     * @param runType\n     * @throws ConfigurationException\n     */\n    protected void onChangeRunType(final String runType) throws ConfigurationException\n    {\n        config.setProperty(\"run.type\", runType);\n        config.setProperty(\"ycsbjar.location\", ycsbJarLocation);\n        config.save();\n        runner = new RedisRunner(propsFileName, config);\n//        runner.startServer(runType.equals(\"load\"), runtime);\n\n    }\n}\n"
  },
  {
    "path": "test/benchmark/ycsb/src/test/java/com/impetus/kundera/ycsb/YCSBBaseTest.java",
    "content": "/**\n * Copyright 2012 Impetus Infotech.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.impetus.kundera.ycsb;\n\nimport java.io.IOException;\n\nimport org.apache.commons.configuration.ConfigurationException;\nimport org.apache.commons.configuration.PropertiesConfiguration;\n\nimport com.impetus.kundera.ycsb.runner.YCSBRunner;\n\n/**\n * @author vivek.mishra\n * \n */\npublic abstract class YCSBBaseTest\n{\n    protected PropertiesConfiguration config;\n\n    protected String workLoadPackage;\n\n    protected YCSBRunner runner;\n\n    protected String propsFileName;\n\n    protected String ycsbJarLocation;\n\n    /**\n     * @throws java.lang.Exception\n     */\n    protected void setUp() throws Exception\n    {\n        propsFileName = System.getProperty(\"fileName\");\n        // System.out.println(propsFileName);\n        config = new PropertiesConfiguration(propsFileName);\n        ycsbJarLocation = config.getString(\"ycsbjar.location\");\n        workLoadPackage = config.getString(\"workload.dir\", \"src/main/resources/workloads\");\n    }\n\n    /**\n     * @throws IOException\n     */\n    protected void onBulkLoad() throws IOException\n    {\n        int noOfThreads = 1;\n        String[] workLoadList = config.getStringArray(\"bulk.workload.type\");\n\n        for (String workLoad : workLoadList)\n        {\n            runner.run(workLoadPackage + \"/\" + workLoad, noOfThreads);\n        }\n\n    }\n\n    /**\n     * @throws NumberFormatException\n     * @throws IOException\n     */\n    protected void process() throws NumberFormatException, IOException\n    {\n        // comma seperated list.\n        String[] noOfThreads = config.getStringArray(\"threads\");\n\n        String[] workLoadList = config.getStringArray(\"workload.file\");\n\n        for (int i = 0; i < noOfThreads.length; i++)\n        {\n            runner.run(workLoadPackage + \"/\" + workLoadList[0], Integer.parseInt(noOfThreads[i]));\n        }\n\n    }\n\n    /**\n     * @throws ConfigurationException\n     * @throws IOException\n     * @throws NumberFormatException\n     */\n    protected void onRead() throws ConfigurationException, NumberFormatException, IOException\n    {\n        String[] workLoadList = config.getStringArray(\"workload.file\");\n        PropertiesConfiguration workLoadConfig = new PropertiesConfiguration(workLoadPackage + \"/\"\n                + workLoadList[0]);\n        workLoadConfig.setProperty(\"readproportion\", \"1\");\n        workLoadConfig.setProperty(\"updateproportion\", \"0\");\n        workLoadConfig.setProperty(\"scanproportion\", \"0\");\n        workLoadConfig.setProperty(\"insertproportion\", \"0\");\n        workLoadConfig.save();\n\n        config.setProperty(\"workload.file\", workLoadList[0]);\n        config.save();\n        process();\n\n    }\n\n    /**\n     * @throws ConfigurationException\n     * @throws IOException\n     * @throws NumberFormatException\n     */\n    protected void onUpdate() throws ConfigurationException, NumberFormatException, IOException\n    {\n        String[] workLoadList = config.getStringArray(\"workload.file\");\n        for (String workLoad : workLoadList)\n        {\n            PropertiesConfiguration workLoadConfig = new PropertiesConfiguration(workLoadPackage + \"/\" + workLoad);\n            workLoadConfig.setProperty(\"readproportion\", \"0\");\n            workLoadConfig.setProperty(\"updateproportion\", \"1\");\n            workLoadConfig.setProperty(\"scanproportion\", \"0\");\n            workLoadConfig.setProperty(\"insertproportion\", \"0\");\n            workLoadConfig.save();\n            process();\n        }\n\n    }\n\n    protected abstract void onChangeRunType(final String runType) throws ConfigurationException;\n\n    protected void onDestroy() throws ConfigurationException\n    {\n        config.clearProperty(\"update\");\n        config.save();\n        Runtime runtime = Runtime.getRuntime();\n        runner.stopServer(runtime);\n    }\n\n    /**\n     * @param runType\n     * @throws ConfigurationException\n     */\n    protected void onChangeRunType(boolean onUpdate) throws ConfigurationException\n    {\n        config.setProperty(\"update\", \"true\");\n        onChangeRunType(\"t\");\n    }\n\n}\n"
  },
  {
    "path": "test/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\n\t<parent>\n\t\t<groupId>com.impetus</groupId>\n\t\t<artifactId>kundera-parent</artifactId>\n\t\t<version>3.9-SNAPSHOT</version>\n\t</parent>\n\n\t<groupId>com.impetus.kundera</groupId>\n\t<artifactId>test</artifactId>\n\t<version>1.0.0-SNAPSHOT</version>\n\t<packaging>pom</packaging>\n\n\t<name>test</name>\n\t<url>https://github.com/impetus-opensource/Kundera</url>\n\n\t<!-- Build profiles -->\n\t<profiles>\n\t\t<profile>\n\t\t\t<id>all</id>\n\t\t\t<activation>\n\t\t\t\t<activeByDefault>true</activeByDefault>\n\t\t\t</activation>\n\t\t\t<modules>\n\t\t\t\t<module>benchmark</module>\n\t\t\t</modules>\n\t\t</profile>\n\t</profiles>\n</project>\n"
  }
]